@dsh-ray/assistant-evaluation 0.0.0-stage → 0.2.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 (217) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +310 -2
  3. package/bin/dsh-benchmark.js +46 -0
  4. package/cordis.patch.yml +17 -0
  5. package/lib/attention-owner-questions.d.ts +104 -0
  6. package/lib/attention-owner-questions.d.ts.map +1 -0
  7. package/lib/attention-owner-questions.js +185 -0
  8. package/lib/attention-owner-questions.js.map +1 -0
  9. package/lib/attention-tuning.d.ts +513 -0
  10. package/lib/attention-tuning.d.ts.map +1 -0
  11. package/lib/attention-tuning.js +1242 -0
  12. package/lib/attention-tuning.js.map +1 -0
  13. package/lib/benchmark/cli.d.ts +6 -0
  14. package/lib/benchmark/cli.d.ts.map +1 -0
  15. package/lib/benchmark/cli.js +370 -0
  16. package/lib/benchmark/cli.js.map +1 -0
  17. package/lib/benchmark/corpus.d.ts +39 -0
  18. package/lib/benchmark/corpus.d.ts.map +1 -0
  19. package/lib/benchmark/corpus.js +183 -0
  20. package/lib/benchmark/corpus.js.map +1 -0
  21. package/lib/benchmark/deepseek.d.ts +15 -0
  22. package/lib/benchmark/deepseek.d.ts.map +1 -0
  23. package/lib/benchmark/deepseek.js +143 -0
  24. package/lib/benchmark/deepseek.js.map +1 -0
  25. package/lib/benchmark/families-corpus.d.ts +109 -0
  26. package/lib/benchmark/families-corpus.d.ts.map +1 -0
  27. package/lib/benchmark/families-corpus.js +587 -0
  28. package/lib/benchmark/families-corpus.js.map +1 -0
  29. package/lib/benchmark/families-runtime.d.ts +191 -0
  30. package/lib/benchmark/families-runtime.d.ts.map +1 -0
  31. package/lib/benchmark/families-runtime.js +1171 -0
  32. package/lib/benchmark/families-runtime.js.map +1 -0
  33. package/lib/benchmark/growth-runtime.d.ts +97 -0
  34. package/lib/benchmark/growth-runtime.d.ts.map +1 -0
  35. package/lib/benchmark/growth-runtime.js +437 -0
  36. package/lib/benchmark/growth-runtime.js.map +1 -0
  37. package/lib/benchmark/holdout-evidence.d.ts +126 -0
  38. package/lib/benchmark/holdout-evidence.d.ts.map +1 -0
  39. package/lib/benchmark/holdout-evidence.js +466 -0
  40. package/lib/benchmark/holdout-evidence.js.map +1 -0
  41. package/lib/benchmark/holdout-isolation.d.ts +27 -0
  42. package/lib/benchmark/holdout-isolation.d.ts.map +1 -0
  43. package/lib/benchmark/holdout-isolation.js +66 -0
  44. package/lib/benchmark/holdout-isolation.js.map +1 -0
  45. package/lib/benchmark/holdout-protocol.d.ts +68 -0
  46. package/lib/benchmark/holdout-protocol.d.ts.map +1 -0
  47. package/lib/benchmark/holdout-protocol.js +271 -0
  48. package/lib/benchmark/holdout-protocol.js.map +1 -0
  49. package/lib/benchmark/holdout-provider.d.ts +26 -0
  50. package/lib/benchmark/holdout-provider.d.ts.map +1 -0
  51. package/lib/benchmark/holdout-provider.js +382 -0
  52. package/lib/benchmark/holdout-provider.js.map +1 -0
  53. package/lib/benchmark/holdout.d.ts +83 -0
  54. package/lib/benchmark/holdout.d.ts.map +1 -0
  55. package/lib/benchmark/holdout.js +394 -0
  56. package/lib/benchmark/holdout.js.map +1 -0
  57. package/lib/benchmark/index.d.ts +12 -0
  58. package/lib/benchmark/index.d.ts.map +1 -0
  59. package/lib/benchmark/index.js +9 -0
  60. package/lib/benchmark/index.js.map +1 -0
  61. package/lib/benchmark/memory-corpus.d.ts +55 -0
  62. package/lib/benchmark/memory-corpus.d.ts.map +1 -0
  63. package/lib/benchmark/memory-corpus.js +153 -0
  64. package/lib/benchmark/memory-corpus.js.map +1 -0
  65. package/lib/benchmark/memory-runtime.d.ts +63 -0
  66. package/lib/benchmark/memory-runtime.d.ts.map +1 -0
  67. package/lib/benchmark/memory-runtime.js +75 -0
  68. package/lib/benchmark/memory-runtime.js.map +1 -0
  69. package/lib/benchmark/native-goal-services.d.ts +66 -0
  70. package/lib/benchmark/native-goal-services.d.ts.map +1 -0
  71. package/lib/benchmark/native-goal-services.js +52 -0
  72. package/lib/benchmark/native-goal-services.js.map +1 -0
  73. package/lib/benchmark/native-skills-runtime.d.ts +157 -0
  74. package/lib/benchmark/native-skills-runtime.d.ts.map +1 -0
  75. package/lib/benchmark/native-skills-runtime.js +337 -0
  76. package/lib/benchmark/native-skills-runtime.js.map +1 -0
  77. package/lib/benchmark/native-skills.d.ts +142 -0
  78. package/lib/benchmark/native-skills.d.ts.map +1 -0
  79. package/lib/benchmark/native-skills.js +259 -0
  80. package/lib/benchmark/native-skills.js.map +1 -0
  81. package/lib/benchmark/native.d.ts +77 -0
  82. package/lib/benchmark/native.d.ts.map +1 -0
  83. package/lib/benchmark/native.js +711 -0
  84. package/lib/benchmark/native.js.map +1 -0
  85. package/lib/benchmark/planning-runtime.d.ts +80 -0
  86. package/lib/benchmark/planning-runtime.d.ts.map +1 -0
  87. package/lib/benchmark/planning-runtime.js +313 -0
  88. package/lib/benchmark/planning-runtime.js.map +1 -0
  89. package/lib/benchmark/report.d.ts +4 -0
  90. package/lib/benchmark/report.d.ts.map +1 -0
  91. package/lib/benchmark/report.js +243 -0
  92. package/lib/benchmark/report.js.map +1 -0
  93. package/lib/benchmark/runner.d.ts +25 -0
  94. package/lib/benchmark/runner.d.ts.map +1 -0
  95. package/lib/benchmark/runner.js +124 -0
  96. package/lib/benchmark/runner.js.map +1 -0
  97. package/lib/benchmark/schema.d.ts +20 -0
  98. package/lib/benchmark/schema.d.ts.map +1 -0
  99. package/lib/benchmark/schema.js +183 -0
  100. package/lib/benchmark/schema.js.map +1 -0
  101. package/lib/benchmark/store.d.ts +18 -0
  102. package/lib/benchmark/store.d.ts.map +1 -0
  103. package/lib/benchmark/store.js +321 -0
  104. package/lib/benchmark/store.js.map +1 -0
  105. package/lib/benchmark/strategy-capabilities.d.ts +154 -0
  106. package/lib/benchmark/strategy-capabilities.d.ts.map +1 -0
  107. package/lib/benchmark/strategy-capabilities.js +304 -0
  108. package/lib/benchmark/strategy-capabilities.js.map +1 -0
  109. package/lib/benchmark/strategy-config.d.ts +29 -0
  110. package/lib/benchmark/strategy-config.d.ts.map +1 -0
  111. package/lib/benchmark/strategy-config.js +98 -0
  112. package/lib/benchmark/strategy-config.js.map +1 -0
  113. package/lib/benchmark/strategy-corpus-v2.d.ts +18 -0
  114. package/lib/benchmark/strategy-corpus-v2.d.ts.map +1 -0
  115. package/lib/benchmark/strategy-corpus-v2.js +143 -0
  116. package/lib/benchmark/strategy-corpus-v2.js.map +1 -0
  117. package/lib/benchmark/strategy-corpus.d.ts +30 -0
  118. package/lib/benchmark/strategy-corpus.d.ts.map +1 -0
  119. package/lib/benchmark/strategy-corpus.js +95 -0
  120. package/lib/benchmark/strategy-corpus.js.map +1 -0
  121. package/lib/benchmark/strategy-evidence.d.ts +161 -0
  122. package/lib/benchmark/strategy-evidence.d.ts.map +1 -0
  123. package/lib/benchmark/strategy-evidence.js +561 -0
  124. package/lib/benchmark/strategy-evidence.js.map +1 -0
  125. package/lib/benchmark/strategy-executor.d.ts +29 -0
  126. package/lib/benchmark/strategy-executor.d.ts.map +1 -0
  127. package/lib/benchmark/strategy-executor.js +180 -0
  128. package/lib/benchmark/strategy-executor.js.map +1 -0
  129. package/lib/benchmark/strategy-goal-runtime.d.ts +80 -0
  130. package/lib/benchmark/strategy-goal-runtime.d.ts.map +1 -0
  131. package/lib/benchmark/strategy-goal-runtime.js +283 -0
  132. package/lib/benchmark/strategy-goal-runtime.js.map +1 -0
  133. package/lib/benchmark/strategy-meter.d.ts +62 -0
  134. package/lib/benchmark/strategy-meter.d.ts.map +1 -0
  135. package/lib/benchmark/strategy-meter.js +330 -0
  136. package/lib/benchmark/strategy-meter.js.map +1 -0
  137. package/lib/benchmark/strategy-owner.d.ts +71 -0
  138. package/lib/benchmark/strategy-owner.d.ts.map +1 -0
  139. package/lib/benchmark/strategy-owner.js +282 -0
  140. package/lib/benchmark/strategy-owner.js.map +1 -0
  141. package/lib/benchmark/strategy-plan.d.ts +58 -0
  142. package/lib/benchmark/strategy-plan.d.ts.map +1 -0
  143. package/lib/benchmark/strategy-plan.js +81 -0
  144. package/lib/benchmark/strategy-plan.js.map +1 -0
  145. package/lib/benchmark/strategy-policy.d.ts +16 -0
  146. package/lib/benchmark/strategy-policy.d.ts.map +1 -0
  147. package/lib/benchmark/strategy-policy.js +77 -0
  148. package/lib/benchmark/strategy-policy.js.map +1 -0
  149. package/lib/benchmark/strategy-projection.d.ts +157 -0
  150. package/lib/benchmark/strategy-projection.d.ts.map +1 -0
  151. package/lib/benchmark/strategy-projection.js +171 -0
  152. package/lib/benchmark/strategy-projection.js.map +1 -0
  153. package/lib/benchmark/strategy.d.ts +17 -0
  154. package/lib/benchmark/strategy.d.ts.map +1 -0
  155. package/lib/benchmark/strategy.js +21 -0
  156. package/lib/benchmark/strategy.js.map +1 -0
  157. package/lib/benchmark/traex.d.ts +17 -0
  158. package/lib/benchmark/traex.d.ts.map +1 -0
  159. package/lib/benchmark/traex.js +139 -0
  160. package/lib/benchmark/traex.js.map +1 -0
  161. package/lib/benchmark/types.d.ts +190 -0
  162. package/lib/benchmark/types.d.ts.map +1 -0
  163. package/lib/benchmark/types.js +3 -0
  164. package/lib/benchmark/types.js.map +1 -0
  165. package/lib/benchmark/usage.d.ts +36 -0
  166. package/lib/benchmark/usage.d.ts.map +1 -0
  167. package/lib/benchmark/usage.js +84 -0
  168. package/lib/benchmark/usage.js.map +1 -0
  169. package/lib/index.d.ts +26 -0
  170. package/lib/index.d.ts.map +1 -0
  171. package/lib/index.js +19 -0
  172. package/lib/index.js.map +1 -0
  173. package/lib/intake-attention-agreement-store.d.ts +33 -0
  174. package/lib/intake-attention-agreement-store.d.ts.map +1 -0
  175. package/lib/intake-attention-agreement-store.js +162 -0
  176. package/lib/intake-attention-agreement-store.js.map +1 -0
  177. package/lib/intake-attention-agreement.d.ts +126 -0
  178. package/lib/intake-attention-agreement.d.ts.map +1 -0
  179. package/lib/intake-attention-agreement.js +209 -0
  180. package/lib/intake-attention-agreement.js.map +1 -0
  181. package/lib/intake-evaluation-agreement.d.ts +204 -0
  182. package/lib/intake-evaluation-agreement.d.ts.map +1 -0
  183. package/lib/intake-evaluation-agreement.js +740 -0
  184. package/lib/intake-evaluation-agreement.js.map +1 -0
  185. package/lib/notification-outcomes.d.ts +63 -0
  186. package/lib/notification-outcomes.d.ts.map +1 -0
  187. package/lib/notification-outcomes.js +399 -0
  188. package/lib/notification-outcomes.js.map +1 -0
  189. package/lib/service.d.ts +694 -0
  190. package/lib/service.d.ts.map +1 -0
  191. package/lib/service.js +2992 -0
  192. package/lib/service.js.map +1 -0
  193. package/lib/sqlite.d.ts +15 -0
  194. package/lib/sqlite.d.ts.map +1 -0
  195. package/lib/sqlite.js +1247 -0
  196. package/lib/sqlite.js.map +1 -0
  197. package/lib/store.d.ts +175 -0
  198. package/lib/store.d.ts.map +1 -0
  199. package/lib/store.js +1722 -0
  200. package/lib/store.js.map +1 -0
  201. package/lib/tools.d.ts +4 -0
  202. package/lib/tools.d.ts.map +1 -0
  203. package/lib/tools.js +212 -0
  204. package/lib/tools.js.map +1 -0
  205. package/lib/types.d.ts +787 -0
  206. package/lib/types.d.ts.map +1 -0
  207. package/lib/types.js +28 -0
  208. package/lib/types.js.map +1 -0
  209. package/lib/version.d.ts +2 -0
  210. package/lib/version.d.ts.map +1 -0
  211. package/lib/version.js +2 -0
  212. package/lib/version.js.map +1 -0
  213. package/lib/work-item-owner-proof.d.ts +4 -0
  214. package/lib/work-item-owner-proof.d.ts.map +1 -0
  215. package/lib/work-item-owner-proof.js +53 -0
  216. package/lib/work-item-owner-proof.js.map +1 -0
  217. package/package.json +242 -3
package/lib/store.js ADDED
@@ -0,0 +1,1722 @@
1
+ import { createHash, randomUUID } from 'node:crypto';
2
+ import { AttentionTuningLedger } from './attention-tuning.js';
3
+ import { AttentionOwnerQuestionLedger } from './attention-owner-questions.js';
4
+ import { IntakeAttentionAgreementLedger } from './intake-attention-agreement-store.js';
5
+ import { IntakeEvaluationAgreementLedger } from './intake-evaluation-agreement.js';
6
+ import { NotificationOutcomeLedger } from './notification-outcomes.js';
7
+ import { isAbsolute, resolve } from 'node:path';
8
+ import { evaluationSchemaVersion, openEvaluationDatabase } from './sqlite.js';
9
+ import { deliveryStatuses, executionStatuses, objectiveStatuses, outcomeSourceKinds, outcomeTrustLevels, } from './types.js';
10
+ export class EvaluationStoreError extends Error {
11
+ code;
12
+ constructor(code, message) {
13
+ super(message);
14
+ this.code = code;
15
+ this.name = 'EvaluationStoreError';
16
+ }
17
+ }
18
+ function projectionState(row) {
19
+ return Object.freeze({
20
+ evaluationId: row.evaluation_id,
21
+ scope: Object.freeze({ workspace: row.workspace, preset: row.preset }),
22
+ status: row.status,
23
+ attemptCount: row.attempt_count,
24
+ nextAttemptAt: row.next_attempt_at,
25
+ ...(row.last_failure_code === null ? {} : { lastFailureCode: row.last_failure_code }),
26
+ createdAt: row.created_at,
27
+ updatedAt: row.updated_at,
28
+ });
29
+ }
30
+ const standardIntegerMetrics = new Set([
31
+ 'costUsdMicros', 'latencyMs', 'inputTokens', 'outputTokens', 'toolCalls', 'retries',
32
+ ]);
33
+ function boundedText(value, label, maxBytes) {
34
+ if (typeof value !== 'string')
35
+ throw new EvaluationStoreError('invalid-input', `${label} must be a string`);
36
+ const normalized = value.normalize('NFC').trim();
37
+ if (normalized === '' || Buffer.byteLength(normalized) > maxBytes) {
38
+ throw new EvaluationStoreError('invalid-input', `${label} must contain 1-${maxBytes} UTF-8 bytes`);
39
+ }
40
+ return normalized;
41
+ }
42
+ function timestamp(value, label) {
43
+ if (!Number.isSafeInteger(value) || value < 0) {
44
+ throw new EvaluationStoreError('invalid-input', `${label} must be a non-negative safe integer`);
45
+ }
46
+ return value;
47
+ }
48
+ export function canonicalEvaluationScope(input) {
49
+ const workspace = boundedText(input.workspace, 'scope.workspace', 4_096);
50
+ if (!isAbsolute(workspace)) {
51
+ throw new EvaluationStoreError('invalid-input', 'scope.workspace must be absolute');
52
+ }
53
+ const scope = Object.freeze({ workspace: resolve(workspace), preset: boundedText(input.preset, 'scope.preset', 200) });
54
+ return { scope, scopeKey: JSON.stringify([scope.workspace, scope.preset]) };
55
+ }
56
+ function canonicalJson(value, label, state, depth = 0) {
57
+ state.nodes += 1;
58
+ if (state.nodes > 128 || depth > 4) {
59
+ throw new EvaluationStoreError('invalid-input', `${label} exceeds the JSON complexity limit`);
60
+ }
61
+ if (value === null || typeof value === 'boolean')
62
+ return value;
63
+ if (typeof value === 'number') {
64
+ if (!Number.isFinite(value) || Math.abs(value) > Number.MAX_SAFE_INTEGER) {
65
+ throw new EvaluationStoreError('invalid-input', `${label} contains an invalid number`);
66
+ }
67
+ return value;
68
+ }
69
+ if (typeof value === 'string') {
70
+ const normalized = value.normalize('NFC');
71
+ if (Buffer.byteLength(normalized) > 256) {
72
+ throw new EvaluationStoreError('invalid-input', `${label} contains an oversized string`);
73
+ }
74
+ return normalized;
75
+ }
76
+ if (Array.isArray(value)) {
77
+ if (value.length > 32)
78
+ throw new EvaluationStoreError('invalid-input', `${label} contains an oversized array`);
79
+ return value.map((entry, index) => canonicalJson(entry, `${label}[${index}]`, state, depth + 1));
80
+ }
81
+ if (typeof value !== 'object' || value === undefined) {
82
+ throw new EvaluationStoreError('invalid-input', `${label} must contain JSON values only`);
83
+ }
84
+ const prototype = Object.getPrototypeOf(value);
85
+ if (prototype !== Object.prototype && prototype !== null) {
86
+ throw new EvaluationStoreError('invalid-input', `${label} must contain plain JSON objects only`);
87
+ }
88
+ const entries = Object.entries(value);
89
+ if (entries.length > 32)
90
+ throw new EvaluationStoreError('invalid-input', `${label} contains too many keys`);
91
+ const output = {};
92
+ for (const [rawKey, entry] of entries.sort(([left], [right]) => left.localeCompare(right))) {
93
+ const key = boundedText(rawKey, `${label} key`, 64);
94
+ if (['__proto__', 'constructor', 'prototype'].includes(key) || key in output) {
95
+ throw new EvaluationStoreError('invalid-input', `${label} contains an unsafe or duplicate key`);
96
+ }
97
+ if (entry === undefined)
98
+ throw new EvaluationStoreError('invalid-input', `${label}.${key} must be JSON`);
99
+ output[key] = canonicalJson(entry, `${label}.${key}`, state, depth + 1);
100
+ }
101
+ return output;
102
+ }
103
+ function metrics(input, maxBytes) {
104
+ const normalized = canonicalJson(input, 'metrics', { nodes: 0 });
105
+ if (Array.isArray(normalized) || normalized === null || typeof normalized !== 'object') {
106
+ throw new EvaluationStoreError('invalid-input', 'metrics must be a JSON object');
107
+ }
108
+ const object = normalized;
109
+ for (const key of standardIntegerMetrics) {
110
+ const value = object[key];
111
+ if (value !== undefined && (!Number.isSafeInteger(value) || value < 0)) {
112
+ throw new EvaluationStoreError('invalid-input', `metrics.${key} must be a non-negative safe integer`);
113
+ }
114
+ }
115
+ if (Buffer.byteLength(JSON.stringify(normalized)) > maxBytes) {
116
+ throw new EvaluationStoreError('invalid-input', `metrics exceeds the ${maxBytes}-byte limit`);
117
+ }
118
+ return Object.freeze(object);
119
+ }
120
+ function evidence(input, maximum) {
121
+ if (!Array.isArray(input) || input.length > maximum) {
122
+ throw new EvaluationStoreError('invalid-input', `evidence exceeds the ${maximum}-reference limit`);
123
+ }
124
+ return Object.freeze(input.map((entry, index) => {
125
+ if (typeof entry !== 'object' || entry === null || Array.isArray(entry)) {
126
+ throw new EvaluationStoreError('invalid-input', `evidence[${index}] must be an object`);
127
+ }
128
+ const kind = boundedText(entry.kind, `evidence[${index}].kind`, 64);
129
+ const ref = boundedText(entry.ref, `evidence[${index}].ref`, 512);
130
+ const digest = entry.digest === undefined
131
+ ? undefined
132
+ : boundedText(entry.digest, `evidence[${index}].digest`, 128);
133
+ return Object.freeze({ kind, ref, ...(digest === undefined ? {} : { digest }) });
134
+ }));
135
+ }
136
+ function oneOf(value, values, label) {
137
+ if (typeof value !== 'string' || !values.includes(value)) {
138
+ throw new EvaluationStoreError('invalid-input', `${label} is invalid`);
139
+ }
140
+ return value;
141
+ }
142
+ function stored(row) {
143
+ return Object.freeze({
144
+ id: row.id,
145
+ idempotencyKey: row.idempotency_key,
146
+ scopeKey: row.scope_key,
147
+ scope: Object.freeze({ workspace: row.workspace, preset: row.preset }),
148
+ situation: row.situation,
149
+ executionStatus: row.execution_status,
150
+ objectiveStatus: row.objective_status,
151
+ deliveryStatus: row.delivery_status,
152
+ source: Object.freeze({ kind: row.source_kind, id: row.source_id }),
153
+ trust: row.trust,
154
+ evidence: Object.freeze(JSON.parse(row.evidence_json)),
155
+ metrics: Object.freeze(JSON.parse(row.metrics_json)),
156
+ occurredAt: row.occurred_at,
157
+ recordedAt: row.recorded_at,
158
+ evaluator: Object.freeze({ id: row.evaluator_id, version: row.evaluator_version }),
159
+ });
160
+ }
161
+ function trustedEvidence(row) {
162
+ return Object.freeze(JSON.parse(row.evidence_json)
163
+ .map(entry => Object.freeze({ ...entry })));
164
+ }
165
+ function executionComponent(row) {
166
+ if (row === undefined)
167
+ return undefined;
168
+ return Object.freeze({
169
+ outcomeId: row.id,
170
+ status: row.execution_status,
171
+ source: Object.freeze({ kind: row.source_kind, id: row.source_id }),
172
+ evidence: trustedEvidence(row),
173
+ occurredAt: row.occurred_at,
174
+ evaluator: Object.freeze({ id: row.evaluator_id, version: row.evaluator_version }),
175
+ });
176
+ }
177
+ function objectiveComponent(row) {
178
+ if (row === undefined)
179
+ return undefined;
180
+ return Object.freeze({
181
+ outcomeId: row.id,
182
+ status: row.objective_status,
183
+ source: Object.freeze({ kind: row.source_kind, id: row.source_id }),
184
+ evidence: trustedEvidence(row),
185
+ occurredAt: row.occurred_at,
186
+ evaluator: Object.freeze({ id: row.evaluator_id, version: row.evaluator_version }),
187
+ });
188
+ }
189
+ function projected(row) {
190
+ return Object.freeze({
191
+ ...stored(row),
192
+ projection: Object.freeze({
193
+ subjectKind: row.task_subject_kind,
194
+ subjectRef: row.task_subject_ref,
195
+ status: row.task_objective_conflicted === 1 ? 'objective-conflict' : 'ready',
196
+ primaryOutcomeId: row.task_primary_outcome_id,
197
+ ...(row.task_execution_outcome_id === null
198
+ ? {} : { executionOutcomeId: row.task_execution_outcome_id }),
199
+ ...(row.task_objective_outcome_id === null
200
+ ? {} : { objectiveOutcomeId: row.task_objective_outcome_id }),
201
+ ...(row.task_delivery_outcome_id === null
202
+ ? {} : { deliveryOutcomeId: row.task_delivery_outcome_id }),
203
+ learningVersion: row.task_learning_version,
204
+ learningDigest: row.task_learning_digest,
205
+ learningDisposition: row.task_learning_disposition,
206
+ }),
207
+ });
208
+ }
209
+ function selfAssessment(row) {
210
+ return Object.freeze({
211
+ id: row.id,
212
+ outcomeId: row.outcome_id,
213
+ idempotencyKey: row.idempotency_key,
214
+ scopeKey: row.scope_key,
215
+ scope: Object.freeze({ workspace: row.workspace, preset: row.preset }),
216
+ situation: row.situation,
217
+ executionStatus: row.execution_status,
218
+ objectiveStatus: row.objective_status,
219
+ deliveryStatus: row.delivery_status,
220
+ trust: 'self-reported',
221
+ evidence: Object.freeze(JSON.parse(row.evidence_json)),
222
+ occurredAt: row.occurred_at,
223
+ recordedAt: row.recorded_at,
224
+ evaluator: Object.freeze({ id: row.evaluator_id, version: row.evaluator_version }),
225
+ });
226
+ }
227
+ function digest(value) {
228
+ return createHash('sha256').update(JSON.stringify(value)).digest('hex');
229
+ }
230
+ /** Stable cross-package digest for one canonical task learning revision. */
231
+ export function evaluationLearningProjectionDigest(input) {
232
+ return digest([
233
+ 'evaluation-task-learning/v1',
234
+ input.scopeKey,
235
+ input.projection.subjectKind,
236
+ input.projection.subjectRef,
237
+ input.projection.disposition,
238
+ input.situation,
239
+ input.execution === undefined ? null : [
240
+ input.execution.outcomeId,
241
+ input.execution.status,
242
+ input.execution.source.kind,
243
+ input.execution.source.id,
244
+ input.execution.evidence.map(entry => [entry.kind, entry.ref, entry.digest ?? null]),
245
+ input.execution.occurredAt,
246
+ input.execution.evaluator.id,
247
+ input.execution.evaluator.version,
248
+ ],
249
+ input.objective === undefined ? null : [
250
+ input.objective.outcomeId,
251
+ input.objective.status,
252
+ input.objective.source.kind,
253
+ input.objective.source.id,
254
+ input.objective.evidence.map(entry => [entry.kind, entry.ref, entry.digest ?? null]),
255
+ input.objective.occurredAt,
256
+ input.objective.evaluator.id,
257
+ input.objective.evaluator.version,
258
+ ],
259
+ input.projection.evidenceOutcomeId ?? null,
260
+ ]);
261
+ }
262
+ function taskSubjectKey(scopeKey, kind, ref) {
263
+ return JSON.stringify([scopeKey, kind, ref]);
264
+ }
265
+ function taskSubject(scopeKey, outcomeId, references, authority) {
266
+ if (authority?.trust === 'trusted' && (authority.source.kind === 'system' && authority.source.id === 'assistant-work-items-owner-proof'
267
+ && authority.evaluator.id === 'assistant-work-items-owner-proof' && authority.evaluator.version === '1'
268
+ || authority.source.kind === 'user-feedback' && authority.source.id === 'assistant-delivery/typed-owner-feedback'
269
+ && authority.evaluator.id === 'assistant-delivery-owner-feedback' && authority.evaluator.version === '2')) {
270
+ const targets = references.filter(item => item.kind === 'work-item-owner-result');
271
+ if (targets.length === 1 && !references.some(item => ['automation-run', 'foreground-turn', 'goal-step', 'goal-outcome'].includes(item.kind))) {
272
+ const ref = targets[0].ref;
273
+ return Object.freeze({ key: taskSubjectKey(scopeKey, 'work-item', ref), kind: 'work-item', ref });
274
+ }
275
+ }
276
+ const typed = references.flatMap(reference => (reference.kind === 'automation-run' || reference.kind === 'foreground-turn' || reference.kind === 'goal-step' || reference.kind === 'goal-outcome'
277
+ ? [{ kind: reference.kind, ref: reference.ref }]
278
+ : []));
279
+ const identities = new Map(typed.map(reference => [`${reference.kind}\u0000${reference.ref}`, reference]));
280
+ // A row that names more than one task subject is intentionally quarantined
281
+ // to its own audit outcome. It must never bridge an Automation and a
282
+ // foreground turn (or two runs) into one learning subject.
283
+ if (identities.size === 1) {
284
+ const { kind, ref } = [...identities.values()][0];
285
+ return Object.freeze({
286
+ key: taskSubjectKey(scopeKey, kind, ref),
287
+ kind,
288
+ ref,
289
+ });
290
+ }
291
+ return Object.freeze({
292
+ key: taskSubjectKey(scopeKey, 'outcome', outcomeId),
293
+ kind: 'outcome',
294
+ ref: outcomeId,
295
+ });
296
+ }
297
+ function newer(left, right) {
298
+ if (left.recorded_at !== right.recorded_at)
299
+ return left.recorded_at - right.recorded_at;
300
+ // Two trusted facts can share one millisecond. Random UUIDs do not encode order,
301
+ // so the durable append sequence decides which fact is the current revision.
302
+ if (left.seq !== undefined && right.seq !== undefined && left.seq !== right.seq)
303
+ return left.seq - right.seq;
304
+ return left.id === right.id ? 0 : left.id > right.id ? 1 : -1;
305
+ }
306
+ function latest(rows) {
307
+ return rows.reduce((winner, row) => (winner === undefined || newer(row, winner) > 0 ? row : winner), undefined);
308
+ }
309
+ function containsEvidence(row, kind) {
310
+ try {
311
+ return JSON.parse(row.evidence_json).some(entry => (typeof entry === 'object' && entry !== null && !Array.isArray(entry)
312
+ && entry.kind === kind));
313
+ }
314
+ catch {
315
+ return false;
316
+ }
317
+ }
318
+ function isAuthoritativeAutomationTerminal(row) {
319
+ return row.trust === 'trusted'
320
+ && row.source_kind === 'automation'
321
+ && row.source_id === 'assistant-automations'
322
+ && row.evaluator_id === 'assistant-automations'
323
+ && /^(?:terminal|host-runbook)-v[1-9][0-9]*$/u.test(row.evaluator_version)
324
+ && containsEvidence(row, 'automation-run');
325
+ }
326
+ function isAuthenticatedOwnerFeedback(row) {
327
+ return row.trust === 'trusted'
328
+ && row.source_kind === 'user-feedback'
329
+ && row.source_id === 'assistant-delivery/typed-owner-feedback'
330
+ && row.evaluator_id === 'assistant-delivery-owner-feedback'
331
+ && row.evaluator_version === '2'
332
+ && (containsEvidence(row, 'automation-run') || containsEvidence(row, 'foreground-turn')
333
+ || containsEvidence(row, 'goal-outcome') || containsEvidence(row, 'work-item-owner-result'))
334
+ && containsEvidence(row, 'delivery-outbox');
335
+ }
336
+ function isTrustedVerifierReceipt(row) {
337
+ return row.trust === 'trusted'
338
+ && row.source_kind === 'evaluator'
339
+ && row.source_id === 'assistant-verifier'
340
+ && row.evaluator_id === 'assistant-verifier'
341
+ && row.evaluator_version === '1'
342
+ && containsEvidence(row, 'acceptance-contract')
343
+ && containsEvidence(row, 'verification-receipt');
344
+ }
345
+ function workItemProductionIdentity(evidence) {
346
+ const matches = evidence.filter(item => item.kind === 'work-item-production-proof');
347
+ return matches.length === 1 && matches[0].digest !== undefined
348
+ ? JSON.stringify([matches[0].ref, matches[0].digest]) : undefined;
349
+ }
350
+ function isAuthoritativeWorkItemTerminal(row) {
351
+ return row.trust === 'trusted' && row.source_kind === 'system'
352
+ && row.source_id === 'assistant-work-items-owner-proof'
353
+ && row.evaluator_id === 'assistant-work-items-owner-proof' && row.evaluator_version === '1'
354
+ && containsEvidence(row, 'work-item-owner-result') && containsEvidence(row, 'work-item-production-proof')
355
+ && row.execution_status !== 'unknown' && row.objective_status === 'unknown';
356
+ }
357
+ function latestWorkItemTerminal(rows) {
358
+ const revision = (row) => {
359
+ const reports = JSON.parse(row.evidence_json).filter(item => item.kind === 'work-item-report');
360
+ if (reports.length !== 1)
361
+ return 0;
362
+ const value = Number(reports[0].ref.slice(reports[0].ref.lastIndexOf('#') + 1));
363
+ return Number.isSafeInteger(value) && value > 0 ? value : 0;
364
+ };
365
+ const candidates = rows.filter(isAuthoritativeWorkItemTerminal).filter(row => revision(row) > 0)
366
+ .sort((left, right) => revision(left) - revision(right) || newer(left, right));
367
+ const latest = candidates.at(-1);
368
+ if (latest === undefined)
369
+ return undefined;
370
+ // Report order is ledger authority. Millisecond timestamps and random audit
371
+ // ids cannot make an older report win, and conflicting proof for one report
372
+ // cannot be silently resolved into a learning-eligible execution.
373
+ const identities = new Set(candidates.filter(row => revision(row) === revision(latest))
374
+ .map(row => workItemProductionIdentity(JSON.parse(row.evidence_json))));
375
+ return identities.size === 1 && !identities.has(undefined) ? latest : undefined;
376
+ }
377
+ function isAuthoritativeForegroundTerminal(row) {
378
+ return isTrustedVerifierReceipt(row)
379
+ && row.source_kind === 'evaluator'
380
+ && containsEvidence(row, 'foreground-turn');
381
+ }
382
+ export class EvaluationStore {
383
+ #database;
384
+ #now;
385
+ #maxQueryLimit;
386
+ #maxSituationBytes;
387
+ #maxMetricsBytes;
388
+ #maxEvidenceRefs;
389
+ #maxSummaryWindowMs;
390
+ #defaultSummaryWindowMs;
391
+ /** WP22 read-only per-notification outcome canon. */
392
+ notifications;
393
+ /** WP22 slice 2 tighten-only attention tuning versions over the notification canon. */
394
+ attention;
395
+ /** WP22 slice 4 at-most-once delivery and record-only reply ledger for owner questions. */
396
+ attentionQuestions;
397
+ /** WP22 E1 append-only intake/attention agreement snapshots (default off). */
398
+ intakeAttentionAgreement;
399
+ /** WP22 WP20 `would-accept` evaluation feed cursor and canonical correlation ledger. */
400
+ intakeEvaluations;
401
+ constructor(options) {
402
+ this.#database = openEvaluationDatabase(options.path);
403
+ this.#now = options.now ?? Date.now;
404
+ this.notifications = new NotificationOutcomeLedger(this.#database, this.#now);
405
+ this.attentionQuestions = new AttentionOwnerQuestionLedger(this.#database, this.#now);
406
+ this.intakeAttentionAgreement = new IntakeAttentionAgreementLedger(this.#database);
407
+ this.intakeEvaluations = new IntakeEvaluationAgreementLedger(this.#database, this.#now);
408
+ // The tuning ledger reads replies and records them atomically with a grant
409
+ // or a proposal decision (slice 5); all ledgers share one database handle.
410
+ this.attention = new AttentionTuningLedger(this.#database, this.#now, this.attentionQuestions);
411
+ this.#maxQueryLimit = options.maxQueryLimit ?? 100;
412
+ this.#maxSituationBytes = options.maxSituationBytes ?? 200;
413
+ this.#maxMetricsBytes = options.maxMetricsBytes ?? 4_096;
414
+ this.#maxEvidenceRefs = options.maxEvidenceRefs ?? 32;
415
+ this.#maxSummaryWindowMs = options.maxSummaryWindowMs ?? 31_536_000_000;
416
+ this.#defaultSummaryWindowMs = options.defaultSummaryWindowMs
417
+ ?? Math.min(2_592_000_000, this.#maxSummaryWindowMs);
418
+ for (const [label, value] of [
419
+ ['maxQueryLimit', this.#maxQueryLimit], ['maxSituationBytes', this.#maxSituationBytes],
420
+ ['maxMetricsBytes', this.#maxMetricsBytes], ['maxEvidenceRefs', this.#maxEvidenceRefs],
421
+ ['maxSummaryWindowMs', this.#maxSummaryWindowMs], ['defaultSummaryWindowMs', this.#defaultSummaryWindowMs],
422
+ ]) {
423
+ if (!Number.isSafeInteger(value) || value < 1) {
424
+ this.#database.close();
425
+ throw new EvaluationStoreError('invalid-input', `${label} must be a positive safe integer`);
426
+ }
427
+ }
428
+ if (this.#defaultSummaryWindowMs > this.#maxSummaryWindowMs) {
429
+ this.#database.close();
430
+ throw new EvaluationStoreError('invalid-input', 'default summary window exceeds the maximum window');
431
+ }
432
+ try {
433
+ this.#rebuildTaskProjections();
434
+ }
435
+ catch (error) {
436
+ this.#database.close();
437
+ throw error;
438
+ }
439
+ }
440
+ close() { this.#database.close(); }
441
+ getOutcome(scopeInput, outcomeIdInput) {
442
+ const { scopeKey } = canonicalEvaluationScope(scopeInput);
443
+ const outcomeId = boundedText(outcomeIdInput, 'outcomeId', 200);
444
+ const row = this.#database.prepare(`
445
+ SELECT * FROM evaluation_outcomes WHERE id = ? AND scope_key = ?
446
+ `).get(outcomeId, scopeKey);
447
+ return row === undefined ? undefined : stored(row);
448
+ }
449
+ /** Adopt a pre-revision owner row only through the exact Host delivery capability. */
450
+ adoptLegacyOwnerFeedback(claims) {
451
+ if (claims.ownerCommand === undefined || claims.initialIdempotencyKey === undefined)
452
+ return;
453
+ // Pre-revision rows only represented Automation runs. Foreground turns were
454
+ // introduced with the typed subject claims and cannot be guessed from them.
455
+ if ((claims.subjectKind ?? 'automation-run') !== 'automation-run')
456
+ return;
457
+ const scopeKey = canonicalEvaluationScope(claims.scope).scopeKey;
458
+ this.#database.exec('BEGIN IMMEDIATE');
459
+ try {
460
+ const row = this.#database.prepare(`SELECT * FROM evaluation_outcomes WHERE idempotency_key = ? AND scope_key = ?`)
461
+ .get(claims.initialIdempotencyKey, scopeKey);
462
+ if (row !== undefined && isAuthenticatedOwnerFeedback(row)) {
463
+ const evidence = JSON.parse(row.evidence_json);
464
+ if (!evidence.some(ref => ref.kind === 'automation-run' && ref.ref === claims.runId)
465
+ || !evidence.some(ref => ref.kind === 'delivery-outbox' && ref.ref === claims.outboxId)) {
466
+ throw new EvaluationStoreError('invalid-input', 'legacy feedback does not match exact delivered result');
467
+ }
468
+ this.#database.prepare(`INSERT INTO evaluation_owner_revisions
469
+ (outcome_id, subject_key, lineage, version, previous_outcome_id, action, command_json)
470
+ VALUES (?, ?, ?, 1, NULL, 'initial', ?) ON CONFLICT DO NOTHING`)
471
+ .run(row.id, row.task_subject_key, JSON.stringify([claims.ownerCommand.principalRecordId, claims.ownerCommand.principalVersion]), JSON.stringify({
472
+ ...claims.ownerCommand, action: 'legacy-adoption', outboxId: claims.outboxId,
473
+ runId: claims.runId, bindingId: claims.bindingId, principalId: claims.principalId,
474
+ }));
475
+ }
476
+ this.#database.exec('COMMIT');
477
+ }
478
+ catch (error) {
479
+ this.#database.exec('ROLLBACK');
480
+ throw error;
481
+ }
482
+ }
483
+ /**
484
+ * Adopt the exact current Verifier whole-goal judgement as revision one for
485
+ * an authenticated owner lineage. The immutable Verifier outcome remains the
486
+ * authority row; the Goals proof is checked by the service and is not stored.
487
+ */
488
+ adoptTrustedGoalOutcomeOwnerBaseline(claims, proof, verifierOutcome) {
489
+ if (claims.subjectKind !== 'goal-outcome' || claims.ownerCommand === undefined) {
490
+ throw new EvaluationStoreError('invalid-input', 'goal outcome owner baseline claims are invalid');
491
+ }
492
+ const { scopeKey } = canonicalEvaluationScope(claims.scope);
493
+ const subjectRef = boundedText(claims.subjectRef, 'goal outcome assessmentId', 1_000);
494
+ const subject = taskSubject(scopeKey, '', [{ kind: 'goal-outcome', ref: subjectRef }]);
495
+ const lineage = JSON.stringify([
496
+ claims.ownerCommand.principalRecordId,
497
+ claims.ownerCommand.principalVersion,
498
+ ]);
499
+ const normalized = this.#normalize(verifierOutcome);
500
+ const payloadHash = digest(normalized);
501
+ const recordedAt = timestamp(this.#now(), 'recordedAt');
502
+ const outcomeId = `outcome-${randomUUID()}`;
503
+ const verifierSubject = taskSubject(normalized.scopeKey, outcomeId, normalized.evidence, normalized);
504
+ const exactEvidence = (entries, kind, ref, digestValue) => entries.some(item => (item.kind === kind && item.ref === ref
505
+ && (digestValue === undefined || item.digest === digestValue)));
506
+ if (normalized.scopeKey !== scopeKey || normalized.situation !== claims.situation
507
+ || normalized.objectiveStatus !== proof.receipt.objectiveStatus
508
+ || normalized.deliveryStatus !== 'not-required' || normalized.trust !== 'trusted'
509
+ || normalized.source.kind !== 'evaluator' || normalized.source.id !== 'assistant-verifier'
510
+ || normalized.evaluator.id !== 'assistant-verifier' || normalized.evaluator.version !== '1'
511
+ || normalized.occurredAt !== proof.receipt.completedAt
512
+ || normalized.idempotencyKey !== `assistant-verifier:${proof.receipt.id}`
513
+ || verifierSubject.kind !== 'goal-outcome' || verifierSubject.ref !== subjectRef
514
+ || normalized.evidence.length !== 4
515
+ || !exactEvidence(normalized.evidence, 'goal-outcome', subjectRef)
516
+ || !exactEvidence(normalized.evidence, 'acceptance-contract', proof.contract.id, proof.contract.digest)
517
+ || !exactEvidence(normalized.evidence, 'verification-receipt', proof.receipt.id, proof.receipt.digest)
518
+ || normalized.evidence.filter(item => item.kind === 'execution' && item.ref === subjectRef).length !== 1) {
519
+ throw new EvaluationStoreError('invalid-input', 'trusted goal outcome baseline input is invalid');
520
+ }
521
+ let changed = false;
522
+ this.#database.exec('BEGIN IMMEDIATE');
523
+ try {
524
+ let row = this.#database.prepare(`
525
+ SELECT outcome.* FROM evaluation_outcomes outcome
526
+ WHERE outcome.task_subject_key = ? AND outcome.task_subject_kind = 'goal-outcome'
527
+ AND outcome.task_subject_ref = ? AND outcome.trust = 'trusted'
528
+ AND outcome.source_kind = 'evaluator' AND outcome.source_id = 'assistant-verifier'
529
+ AND outcome.evaluator_id = 'assistant-verifier' AND outcome.evaluator_version = '1'
530
+ ORDER BY outcome.recorded_at DESC, outcome.rowid DESC LIMIT 1
531
+ `).get(subject.key, subjectRef);
532
+ if (row === undefined) {
533
+ const metric = normalized.metrics;
534
+ this.#database.prepare(`
535
+ INSERT INTO evaluation_outcomes(
536
+ id, idempotency_key, payload_hash, scope_key, workspace, preset, situation,
537
+ execution_status, objective_status, delivery_status, source_kind, source_id,
538
+ trust, evidence_json, metrics_json, cost_usd_micros, latency_ms, input_tokens,
539
+ output_tokens, tool_calls, occurred_at, recorded_at, evaluator_id, evaluator_version,
540
+ task_subject_key, task_subject_kind, task_subject_ref)
541
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
542
+ ON CONFLICT(idempotency_key) DO NOTHING
543
+ `).run(outcomeId, normalized.idempotencyKey, payloadHash, normalized.scopeKey, normalized.scope.workspace, normalized.scope.preset, normalized.situation, normalized.executionStatus, normalized.objectiveStatus, normalized.deliveryStatus, normalized.source.kind, normalized.source.id, normalized.trust, JSON.stringify(normalized.evidence), JSON.stringify(normalized.metrics), metric.costUsdMicros ?? null, metric.latencyMs ?? null, metric.inputTokens ?? null, metric.outputTokens ?? null, metric.toolCalls ?? null, normalized.occurredAt, recordedAt, normalized.evaluator.id, normalized.evaluator.version, verifierSubject.key, verifierSubject.kind, verifierSubject.ref);
544
+ const winner = this.#database.prepare('SELECT * FROM evaluation_outcomes WHERE idempotency_key = ?')
545
+ .get(normalized.idempotencyKey);
546
+ if (winner.payload_hash !== payloadHash || winner.task_subject_key !== verifierSubject.key
547
+ || winner.task_subject_kind !== verifierSubject.kind || winner.task_subject_ref !== verifierSubject.ref) {
548
+ throw new EvaluationStoreError('idempotency-conflict', 'trusted verifier outcome identity was reused');
549
+ }
550
+ this.#database.prepare(`
551
+ INSERT INTO evaluation_task_projections(
552
+ subject_key, scope_key, subject_kind, subject_ref, updated_at)
553
+ VALUES (?, ?, ?, ?, ?) ON CONFLICT(subject_key) DO NOTHING
554
+ `).run(verifierSubject.key, winner.scope_key, verifierSubject.kind, verifierSubject.ref, winner.recorded_at);
555
+ const refreshed = this.#refreshTaskProjection(verifierSubject.key);
556
+ if (refreshed.learningVersionChanged) {
557
+ this.#database.prepare(`
558
+ INSERT INTO evaluation_projection_outbox(
559
+ evaluation_id, status, attempt_count, next_attempt_at,
560
+ last_failure_at, last_failure_code, created_at, updated_at)
561
+ VALUES (?, 'pending', 0, ?, NULL, NULL, ?, ?)
562
+ ON CONFLICT(evaluation_id) DO NOTHING
563
+ `).run(winner.id, winner.recorded_at, winner.recorded_at, winner.recorded_at);
564
+ this.#advanceScopeWatermark(winner.scope_key, winner.recorded_at, verifierSubject.key);
565
+ }
566
+ row = winner;
567
+ changed = true;
568
+ }
569
+ const storedEvidence = JSON.parse(row.evidence_json);
570
+ if (!isTrustedVerifierReceipt(row)
571
+ || row.idempotency_key !== normalized.idempotencyKey || row.payload_hash !== payloadHash
572
+ || (row.objective_status !== 'achieved' && row.objective_status !== 'not-achieved')
573
+ || row.objective_status !== proof.receipt.objectiveStatus
574
+ || row.situation !== claims.situation
575
+ || !exactEvidence(storedEvidence, 'goal-outcome', subjectRef)
576
+ || !exactEvidence(storedEvidence, 'acceptance-contract', proof.contract.id, proof.contract.digest)
577
+ || !exactEvidence(storedEvidence, 'verification-receipt', proof.receipt.id, proof.receipt.digest)) {
578
+ throw new EvaluationStoreError('invalid-input', 'trusted goal outcome baseline does not match the current verifier receipt');
579
+ }
580
+ const existing = this.#database.prepare(`
581
+ SELECT outcome_id FROM evaluation_owner_revisions
582
+ WHERE subject_key = ? AND lineage = ? ORDER BY version DESC LIMIT 1
583
+ `).get(subject.key, lineage);
584
+ if (existing !== undefined) {
585
+ this.#database.exec('COMMIT');
586
+ return changed;
587
+ }
588
+ const foreignLineage = this.#database.prepare(`
589
+ SELECT lineage FROM evaluation_owner_revisions WHERE subject_key = ? LIMIT 1
590
+ `).get(subject.key);
591
+ if (foreignLineage !== undefined) {
592
+ throw new EvaluationStoreError('invalid-input', 'goal outcome baseline belongs to another owner lineage');
593
+ }
594
+ this.#database.prepare(`INSERT INTO evaluation_owner_revisions
595
+ (outcome_id, subject_key, lineage, version, previous_outcome_id, action, command_json)
596
+ VALUES (?, ?, ?, 1, NULL, 'initial', ?)`)
597
+ .run(row.id, subject.key, lineage, JSON.stringify({
598
+ action: 'goal-outcome-baseline-adoption',
599
+ assessmentId: subjectRef,
600
+ }));
601
+ changed = true;
602
+ this.#database.exec('COMMIT');
603
+ return changed;
604
+ }
605
+ catch (error) {
606
+ this.#database.exec('ROLLBACK');
607
+ throw error;
608
+ }
609
+ }
610
+ ownerObjectiveState(scope, subjectKindOrRef, subjectRefOrPrincipal, principalRecordIdOrVersion, principalVersion) {
611
+ // Arity, not the opaque legacy run id, selects the generic overload.
612
+ const generic = principalVersion !== undefined;
613
+ const subjectKind = generic ? subjectKindOrRef : 'automation-run';
614
+ const subjectRef = generic ? subjectRefOrPrincipal : subjectKindOrRef;
615
+ const principalRecordId = generic ? principalRecordIdOrVersion : subjectRefOrPrincipal;
616
+ const version = generic ? principalVersion : principalRecordIdOrVersion;
617
+ const scopeKey = canonicalEvaluationScope(scope).scopeKey;
618
+ const subject = subjectKind === 'work-item'
619
+ ? { key: JSON.stringify([scopeKey, 'work-item', subjectRef]) }
620
+ : taskSubject(scopeKey, '', [{ kind: subjectKind, ref: subjectRef }]);
621
+ const row = this.#database.prepare(`
622
+ SELECT revision.version, outcome.objective_status
623
+ FROM evaluation_owner_revisions revision JOIN evaluation_outcomes outcome ON outcome.id = revision.outcome_id
624
+ WHERE revision.subject_key = ? AND revision.lineage = ? ORDER BY revision.version DESC LIMIT 1
625
+ `).get(subject.key, JSON.stringify([principalRecordId, version]));
626
+ return row === undefined ? undefined : { version: row.version, objectiveStatus: row.objective_status };
627
+ }
628
+ ownerCommandResult(outcome) {
629
+ const row = this.#database.prepare(`SELECT version FROM evaluation_owner_revisions WHERE outcome_id = ?`)
630
+ .get(outcome.id);
631
+ return row === undefined ? outcome : { ...outcome, ownerFeedbackState: { version: row.version, objectiveStatus: outcome.objectiveStatus } };
632
+ }
633
+ append(input, ownerCommand) {
634
+ const normalized = this.#normalize(input);
635
+ const payloadHash = digest(normalized);
636
+ const id = `outcome-${randomUUID()}`;
637
+ const subject = taskSubject(normalized.scopeKey, id, normalized.evidence, normalized);
638
+ const recordedAt = timestamp(this.#now(), 'recordedAt');
639
+ const metric = normalized.metrics;
640
+ let committed = false;
641
+ this.#database.exec('BEGIN IMMEDIATE');
642
+ try {
643
+ let previous;
644
+ const commandHash = digest({ input: normalized, ownerCommand: ownerCommand ?? null });
645
+ if (ownerCommand !== undefined) {
646
+ const replay = this.#database.prepare(`SELECT * FROM evaluation_owner_commands WHERE operation_id = ?`)
647
+ .get(ownerCommand.operationId);
648
+ if (replay !== undefined) {
649
+ if (replay.payload_hash !== commandHash)
650
+ throw new EvaluationStoreError('idempotency-conflict', 'owner command identity reused');
651
+ if (replay.failure_code !== null)
652
+ throw new EvaluationStoreError(replay.failure_code === 'idempotency-conflict' ? 'idempotency-conflict' : 'version-conflict', 'owner judgement changed; inspect current feedback and retry');
653
+ const result = this.getOutcome(input.scope, replay.outcome_id);
654
+ this.#database.exec('COMMIT');
655
+ return this.ownerCommandResult(result);
656
+ }
657
+ previous = this.#database.prepare(`
658
+ SELECT revision.outcome_id, revision.version, outcome.objective_status, outcome.evidence_json
659
+ FROM evaluation_owner_revisions revision JOIN evaluation_outcomes outcome ON outcome.id = revision.outcome_id
660
+ WHERE revision.subject_key = ? AND revision.lineage = ? ORDER BY revision.version DESC LIMIT 1
661
+ `).get(subject.key, JSON.stringify([ownerCommand.principalRecordId, ownerCommand.principalVersion]));
662
+ if (ownerCommand.action !== 'initial' && (previous === undefined
663
+ || previous.version !== ownerCommand.expectedVersion || previous.objective_status !== ownerCommand.previousStatus)) {
664
+ this.#database.prepare(`INSERT INTO evaluation_owner_commands VALUES (?, ?, NULL, 'version-conflict')`)
665
+ .run(ownerCommand.operationId, commandHash);
666
+ this.#database.exec('COMMIT');
667
+ committed = true;
668
+ throw new EvaluationStoreError('version-conflict', 'owner judgement changed; inspect current feedback and retry');
669
+ }
670
+ const sameWorkItemProof = subject.kind !== 'work-item' || previous === undefined
671
+ || workItemProductionIdentity(JSON.parse(previous.evidence_json))
672
+ === workItemProductionIdentity(normalized.evidence);
673
+ if (previous !== undefined && (ownerCommand.action === 'initial'
674
+ || previous.objective_status === normalized.objectiveStatus && sameWorkItemProof)) {
675
+ if (previous.objective_status !== normalized.objectiveStatus || !sameWorkItemProof) {
676
+ this.#database.prepare(`INSERT INTO evaluation_owner_commands VALUES (?, ?, NULL, 'idempotency-conflict')`)
677
+ .run(ownerCommand.operationId, commandHash);
678
+ this.#database.exec('COMMIT');
679
+ committed = true;
680
+ throw new EvaluationStoreError('idempotency-conflict', 'initial judgement already exists; use an explicit correction');
681
+ }
682
+ this.#database.prepare(`INSERT INTO evaluation_owner_commands VALUES (?, ?, ?, NULL)`)
683
+ .run(ownerCommand.operationId, commandHash, previous.outcome_id);
684
+ const result = this.getOutcome(input.scope, previous.outcome_id);
685
+ this.#database.exec('COMMIT');
686
+ return this.ownerCommandResult(result);
687
+ }
688
+ }
689
+ this.#database.prepare(`
690
+ INSERT INTO evaluation_outcomes(
691
+ id, idempotency_key, payload_hash, scope_key, workspace, preset, situation,
692
+ execution_status, objective_status, delivery_status, source_kind, source_id,
693
+ trust, evidence_json, metrics_json, cost_usd_micros, latency_ms, input_tokens,
694
+ output_tokens, tool_calls, occurred_at, recorded_at, evaluator_id, evaluator_version,
695
+ task_subject_key, task_subject_kind, task_subject_ref)
696
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
697
+ ON CONFLICT(idempotency_key) DO NOTHING
698
+ `).run(id, normalized.idempotencyKey, payloadHash, normalized.scopeKey, normalized.scope.workspace, normalized.scope.preset, normalized.situation, normalized.executionStatus, normalized.objectiveStatus, normalized.deliveryStatus, normalized.source.kind, normalized.source.id, normalized.trust, JSON.stringify(normalized.evidence), JSON.stringify(normalized.metrics), metric.costUsdMicros ?? null, metric.latencyMs ?? null, metric.inputTokens ?? null, metric.outputTokens ?? null, metric.toolCalls ?? null, normalized.occurredAt, recordedAt, normalized.evaluator.id, normalized.evaluator.version, subject.key, subject.kind, subject.ref);
699
+ const winner = this.#database.prepare('SELECT * FROM evaluation_outcomes WHERE idempotency_key = ?')
700
+ .get(normalized.idempotencyKey);
701
+ if (winner.payload_hash !== payloadHash) {
702
+ throw new EvaluationStoreError('idempotency-conflict', 'evaluation outcome idempotency key was reused with different content');
703
+ }
704
+ const winnerSubject = winner.task_subject_key === null
705
+ ? taskSubject(winner.scope_key, winner.id, JSON.parse(winner.evidence_json))
706
+ : {
707
+ key: winner.task_subject_key,
708
+ kind: winner.task_subject_kind,
709
+ ref: winner.task_subject_ref,
710
+ };
711
+ this.#database.prepare(`
712
+ INSERT INTO evaluation_task_projections(
713
+ subject_key, scope_key, subject_kind, subject_ref, updated_at)
714
+ VALUES (?, ?, ?, ?, ?)
715
+ ON CONFLICT(subject_key) DO NOTHING
716
+ `).run(winnerSubject.key, winner.scope_key, winnerSubject.kind, winnerSubject.ref, winner.recorded_at);
717
+ if (ownerCommand !== undefined) {
718
+ this.#database.prepare(`INSERT INTO evaluation_owner_revisions VALUES (?, ?, ?, ?, ?, ?, ?)`)
719
+ .run(winner.id, winnerSubject.key, JSON.stringify([ownerCommand.principalRecordId, ownerCommand.principalVersion]), (previous?.version ?? 0) + 1, previous?.outcome_id ?? null, ownerCommand.action, JSON.stringify(ownerCommand));
720
+ this.#database.prepare(`INSERT INTO evaluation_owner_commands VALUES (?, ?, ?, NULL)`)
721
+ .run(ownerCommand.operationId, commandHash, winner.id);
722
+ }
723
+ const refreshed = this.#refreshTaskProjection(winnerSubject.key);
724
+ if (winner.trust === 'trusted' && refreshed.learningVersionChanged) {
725
+ this.#database.prepare(`
726
+ INSERT INTO evaluation_projection_outbox(
727
+ evaluation_id, status, attempt_count, next_attempt_at,
728
+ last_failure_at, last_failure_code, created_at, updated_at)
729
+ VALUES (?, ?, 0, ?, NULL, NULL, ?, ?)
730
+ ON CONFLICT(evaluation_id) DO NOTHING
731
+ `).run(winner.id, winnerSubject.kind === 'work-item' ? 'not-required' : 'pending', winner.recorded_at, winner.recorded_at, winner.recorded_at);
732
+ this.#advanceScopeWatermark(winner.scope_key, winner.recorded_at, winnerSubject.key);
733
+ }
734
+ this.#database.exec('COMMIT');
735
+ return ownerCommand === undefined ? stored(winner) : this.ownerCommandResult(stored(winner));
736
+ }
737
+ catch (error) {
738
+ if (!committed)
739
+ this.#database.exec('ROLLBACK');
740
+ throw error;
741
+ }
742
+ }
743
+ listPendingProjections(limitInput = 100, nowInput = this.#now()) {
744
+ const limit = timestamp(limitInput, 'projection limit');
745
+ const now = timestamp(nowInput, 'projection now');
746
+ if (limit < 1 || limit > 1_000) {
747
+ throw new EvaluationStoreError('invalid-input', 'projection limit must be between 1 and 1000');
748
+ }
749
+ const rows = this.#database.prepare(`
750
+ SELECT projection.*, outcome.workspace, outcome.preset
751
+ FROM evaluation_projection_outbox projection
752
+ JOIN evaluation_outcomes outcome ON outcome.id = projection.evaluation_id
753
+ WHERE projection.status = 'pending' AND projection.next_attempt_at <= ?
754
+ ORDER BY projection.next_attempt_at, projection.created_at, projection.evaluation_id
755
+ LIMIT ?
756
+ `).all(now, limit);
757
+ return rows.map(row => projectionState(row));
758
+ }
759
+ peekPendingProjection(scopeInput, nowInput = this.#now()) {
760
+ const { scopeKey } = canonicalEvaluationScope(scopeInput);
761
+ const now = timestamp(nowInput, 'projection now');
762
+ const row = this.#database.prepare(`
763
+ SELECT projection.*, outcome.workspace, outcome.preset
764
+ FROM evaluation_projection_outbox projection
765
+ JOIN evaluation_outcomes outcome ON outcome.id = projection.evaluation_id
766
+ WHERE projection.status = 'pending' AND projection.next_attempt_at <= ?
767
+ AND outcome.scope_key = ? AND outcome.trust = 'trusted'
768
+ ORDER BY projection.next_attempt_at, projection.created_at, projection.evaluation_id
769
+ LIMIT 1
770
+ `).get(now, scopeKey);
771
+ return row === undefined ? undefined : projectionState(row);
772
+ }
773
+ getProjection(scopeInput, evaluationIdInput) {
774
+ const { scopeKey } = canonicalEvaluationScope(scopeInput);
775
+ const evaluationId = boundedText(evaluationIdInput, 'evaluationId', 200);
776
+ const row = this.#database.prepare(`
777
+ SELECT projection.*, outcome.workspace, outcome.preset
778
+ FROM evaluation_projection_outbox projection
779
+ JOIN evaluation_outcomes outcome ON outcome.id = projection.evaluation_id
780
+ WHERE projection.evaluation_id = ? AND outcome.scope_key = ?
781
+ AND outcome.trust = 'trusted'
782
+ `).get(evaluationId, scopeKey);
783
+ return row === undefined ? undefined : projectionState(row);
784
+ }
785
+ completeProjection(input) {
786
+ const evaluationId = boundedText(input.evaluationId, 'evaluationId', 200);
787
+ const now = timestamp(input.now, 'projection completion time');
788
+ return this.#database.prepare(`
789
+ UPDATE evaluation_projection_outbox
790
+ SET status = 'recorded', updated_at = ?, last_failure_code = NULL
791
+ WHERE evaluation_id = ? AND status = 'pending'
792
+ `).run(now, evaluationId).changes === 1;
793
+ }
794
+ deferProjection(input) {
795
+ const evaluationId = boundedText(input.evaluationId, 'evaluationId', 200);
796
+ const now = timestamp(input.now, 'projection failure time');
797
+ const retryAt = timestamp(input.retryAt, 'projection retry time');
798
+ if (retryAt <= now)
799
+ throw new EvaluationStoreError('invalid-input', 'projection retry must be in the future');
800
+ const failureCode = boundedText(input.failureCode, 'projection failureCode', 64);
801
+ if (!/^[A-Za-z0-9][A-Za-z0-9._:-]{0,63}$/u.test(failureCode)) {
802
+ throw new EvaluationStoreError('invalid-input', 'projection failureCode is invalid');
803
+ }
804
+ return this.#database.prepare(`
805
+ UPDATE evaluation_projection_outbox
806
+ SET attempt_count = attempt_count + 1, next_attempt_at = ?,
807
+ last_failure_at = ?, last_failure_code = ?, updated_at = ?
808
+ WHERE evaluation_id = ? AND status = 'pending'
809
+ `).run(retryAt, now, failureCode, now, evaluationId).changes === 1;
810
+ }
811
+ /**
812
+ * Append a self-reported objective judgement linked to an immutable Host
813
+ * outcome. Execution and delivery are inherited, metrics are not copied, and
814
+ * the assessment never participates in the trusted outcome count.
815
+ */
816
+ appendSelfAssessment(input) {
817
+ const { scope, scopeKey } = canonicalEvaluationScope(input.scope);
818
+ const outcomeId = boundedText(input.outcomeId, 'outcomeId', 200);
819
+ const target = this.#database.prepare('SELECT * FROM evaluation_outcomes WHERE id = ?')
820
+ .get(outcomeId);
821
+ if (target === undefined)
822
+ throw new EvaluationStoreError('not-found', 'self-assessment outcome was not found');
823
+ if (target.scope_key !== scopeKey) {
824
+ throw new EvaluationStoreError('invalid-input', 'self-assessment scope does not match the referenced outcome');
825
+ }
826
+ const normalized = Object.freeze({
827
+ outcomeId,
828
+ scope,
829
+ scopeKey,
830
+ objectiveStatus: oneOf(input.objectiveStatus, objectiveStatuses, 'objectiveStatus'),
831
+ evidence: evidence(input.evidence, this.#maxEvidenceRefs),
832
+ occurredAt: timestamp(input.occurredAt, 'occurredAt'),
833
+ idempotencyKey: boundedText(input.idempotencyKey, 'idempotencyKey', 200),
834
+ evaluator: Object.freeze({
835
+ id: boundedText(input.evaluator?.id, 'evaluator.id', 200),
836
+ version: boundedText(input.evaluator?.version, 'evaluator.version', 100),
837
+ }),
838
+ });
839
+ const payloadHash = digest(normalized);
840
+ const recordedAt = timestamp(this.#now(), 'recordedAt');
841
+ this.#database.prepare(`
842
+ INSERT INTO evaluation_self_assessments(
843
+ id, outcome_id, idempotency_key, payload_hash, scope_key,
844
+ objective_status, evidence_json, occurred_at, recorded_at, evaluator_id, evaluator_version)
845
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
846
+ ON CONFLICT(idempotency_key) DO NOTHING
847
+ `).run(`assessment-${randomUUID()}`, outcomeId, normalized.idempotencyKey, payloadHash, scopeKey, normalized.objectiveStatus, JSON.stringify(normalized.evidence), normalized.occurredAt, recordedAt, normalized.evaluator.id, normalized.evaluator.version);
848
+ const winner = this.#database.prepare(`
849
+ SELECT assessment.*, outcome.workspace, outcome.preset, outcome.situation,
850
+ outcome.execution_status, outcome.delivery_status
851
+ FROM evaluation_self_assessments assessment
852
+ JOIN evaluation_outcomes outcome ON outcome.id = assessment.outcome_id
853
+ WHERE assessment.idempotency_key = ?
854
+ `).get(normalized.idempotencyKey);
855
+ if (winner.payload_hash !== payloadHash) {
856
+ throw new EvaluationStoreError('idempotency-conflict', 'self-assessment idempotency key was reused with different content');
857
+ }
858
+ return selfAssessment(winner);
859
+ }
860
+ /** Latest self-report for each requested parent, preserving parent order. */
861
+ latestSelfAssessments(scopeInput, outcomeIdsInput) {
862
+ const { scopeKey } = canonicalEvaluationScope(scopeInput);
863
+ if (!Array.isArray(outcomeIdsInput) || outcomeIdsInput.length > this.#maxQueryLimit) {
864
+ throw new EvaluationStoreError('invalid-input', 'self-assessment parent query exceeds the limit');
865
+ }
866
+ const outcomeIds = outcomeIdsInput.map(id => boundedText(id, 'outcomeId', 200));
867
+ if (new Set(outcomeIds).size !== outcomeIds.length) {
868
+ throw new EvaluationStoreError('invalid-input', 'self-assessment parent query contains a duplicate');
869
+ }
870
+ if (outcomeIds.length === 0)
871
+ return [];
872
+ const placeholders = outcomeIds.map(() => '?').join(', ');
873
+ const rows = this.#database.prepare(`
874
+ SELECT assessment.*, outcome.workspace, outcome.preset, outcome.situation,
875
+ outcome.execution_status, outcome.delivery_status
876
+ FROM evaluation_self_assessments assessment
877
+ JOIN evaluation_outcomes outcome ON outcome.id = assessment.outcome_id
878
+ WHERE assessment.scope_key = ? AND assessment.outcome_id IN (${placeholders})
879
+ ORDER BY assessment.occurred_at DESC, assessment.rowid DESC
880
+ `).all(scopeKey, ...outcomeIds);
881
+ const latest = new Map();
882
+ for (const row of rows) {
883
+ if (!latest.has(row.outcome_id))
884
+ latest.set(row.outcome_id, selfAssessment(row));
885
+ }
886
+ return outcomeIds.flatMap(id => {
887
+ const assessment = latest.get(id);
888
+ return assessment === undefined ? [] : [assessment];
889
+ });
890
+ }
891
+ /** Resolve the task projection containing one immutable audit outcome. */
892
+ getTaskProjection(scopeInput, outcomeIdInput) {
893
+ const { scopeKey } = canonicalEvaluationScope(scopeInput);
894
+ const outcomeId = boundedText(outcomeIdInput, 'outcomeId', 200);
895
+ const row = this.#database.prepare(`
896
+ SELECT task.*
897
+ FROM evaluation_outcomes audit
898
+ JOIN evaluation_task_projection_view task
899
+ ON task.task_subject_key = audit.task_subject_key
900
+ WHERE audit.id = ? AND audit.scope_key = ?
901
+ `).get(outcomeId, scopeKey);
902
+ return row === undefined ? undefined : projected(row);
903
+ }
904
+ /** Exact run lookup without an audit query limit or a second success definition. */
905
+ getAutomationRunLearningProjection(scopeInput, runIdInput) {
906
+ const { scopeKey } = canonicalEvaluationScope(scopeInput);
907
+ const runId = boundedText(runIdInput, 'runId', 200);
908
+ const row = this.#database.prepare(`
909
+ SELECT task.* FROM evaluation_task_projection_view task
910
+ WHERE task.task_subject_key = ? AND task.scope_key = ? AND task.task_subject_kind = 'automation-run'
911
+ AND task.task_subject_ref = ?
912
+ `).get(taskSubjectKey(scopeKey, 'automation-run', runId), scopeKey, runId);
913
+ if (row === undefined)
914
+ return undefined;
915
+ const task = projected(row);
916
+ if (task.projection.status !== 'ready')
917
+ return undefined;
918
+ return this.getTaskLearningProjection(scopeInput, task.projection.primaryOutcomeId);
919
+ }
920
+ /** Host-only exact current foreground projection, including retractions. */
921
+ getForegroundLearningProjection(scopeInput, inboxIdInput) {
922
+ const { scopeKey } = canonicalEvaluationScope(scopeInput);
923
+ const inboxId = boundedText(inboxIdInput, 'inboxId', 1_000);
924
+ // A display-only primary update may have no projection outbox of its own.
925
+ // Resolve a real trusted trigger for the exact subject, as the durable feed
926
+ // does, then let the shared reader return the subject's current revision.
927
+ const row = this.#database.prepare(`SELECT outbox.evaluation_id
928
+ FROM evaluation_task_projection_view task
929
+ JOIN evaluation_outcomes audit ON audit.task_subject_key = task.task_subject_key
930
+ AND audit.scope_key = task.scope_key
931
+ JOIN evaluation_projection_outbox outbox ON outbox.evaluation_id = audit.id
932
+ WHERE task.task_subject_key = ? AND task.scope_key = ? AND task.task_subject_kind = 'foreground-turn'
933
+ AND task.task_subject_ref = ? AND audit.trust = 'trusted'
934
+ ORDER BY audit.recorded_at DESC, audit.rowid DESC LIMIT 1`)
935
+ .get(taskSubjectKey(scopeKey, 'foreground-turn', inboxId), scopeKey, inboxId);
936
+ if (row === undefined)
937
+ return undefined;
938
+ return this.getTaskLearningProjection(scopeInput, row.evaluation_id);
939
+ }
940
+ /** Exact work-item owner-result projection; historical system settlements stay audit-only. */
941
+ getWorkItemLearningProjection(scopeInput, itemIdInput) {
942
+ const { scopeKey } = canonicalEvaluationScope(scopeInput);
943
+ const itemId = boundedText(itemIdInput, 'itemId', 1_000);
944
+ const row = this.#database.prepare(`SELECT outbox.evaluation_id
945
+ FROM evaluation_task_projection_view task
946
+ JOIN evaluation_outcomes audit ON audit.task_subject_key = task.task_subject_key AND audit.scope_key = task.scope_key
947
+ JOIN evaluation_projection_outbox outbox ON outbox.evaluation_id = audit.id
948
+ WHERE task.task_subject_key = ? AND task.scope_key = ? AND task.task_subject_kind = 'work-item' AND task.task_subject_ref = ? AND audit.trust = 'trusted'
949
+ ORDER BY audit.recorded_at DESC, audit.rowid DESC LIMIT 1`)
950
+ .get(taskSubjectKey(scopeKey, 'work-item', itemId), scopeKey, itemId);
951
+ return row === undefined ? undefined : this.getTaskLearningProjection(scopeInput, row.evaluation_id);
952
+ }
953
+ /** Exact whole-goal lookup by the verifier assessment identity. */
954
+ getGoalOutcomeLearningProjection(scopeInput, assessmentIdInput) {
955
+ const { scopeKey } = canonicalEvaluationScope(scopeInput);
956
+ const assessmentId = boundedText(assessmentIdInput, 'assessmentId', 1_000);
957
+ const row = this.#database.prepare(`
958
+ SELECT task.* FROM evaluation_task_projection_view task
959
+ WHERE task.task_subject_key = ? AND task.scope_key = ? AND task.task_subject_kind = 'goal-outcome'
960
+ AND task.task_subject_ref = ?
961
+ `).get(taskSubjectKey(scopeKey, 'goal-outcome', assessmentId), scopeKey, assessmentId);
962
+ if (row === undefined)
963
+ return undefined;
964
+ const task = projected(row);
965
+ return this.getTaskLearningProjection(scopeInput, task.projection.primaryOutcomeId);
966
+ }
967
+ /**
968
+ * Resolve an append-only outbox trigger to the latest canonical state of its
969
+ * task. The trigger may be arbitrarily old; version/digest always describe
970
+ * the current task projection.
971
+ */
972
+ getTaskLearningProjection(scopeInput, outcomeIdInput) {
973
+ const { scopeKey } = canonicalEvaluationScope(scopeInput);
974
+ const outcomeId = boundedText(outcomeIdInput, 'outcomeId', 200);
975
+ const row = this.#database.prepare(`
976
+ SELECT task.*
977
+ FROM evaluation_projection_outbox outbox
978
+ JOIN evaluation_outcomes audit ON audit.id = outbox.evaluation_id
979
+ JOIN evaluation_task_projection_view task
980
+ ON task.task_subject_key = audit.task_subject_key
981
+ WHERE audit.id = ? AND audit.scope_key = ? AND audit.trust = 'trusted'
982
+ `).get(outcomeId, scopeKey);
983
+ if (row === undefined || row.trust !== 'trusted')
984
+ return undefined;
985
+ const watermarkRow = this.#database.prepare(`
986
+ SELECT watermark FROM evaluation_scope_watermarks WHERE scope_key = ?
987
+ `).get(scopeKey);
988
+ if (watermarkRow === undefined || !Number.isSafeInteger(watermarkRow.watermark)
989
+ || watermarkRow.watermark < 1) {
990
+ throw new EvaluationStoreError('invalid-input', 'canonical scope watermark is unavailable');
991
+ }
992
+ const task = projected(row);
993
+ const selected = (id) => id === undefined
994
+ ? undefined
995
+ : this.#database.prepare('SELECT * FROM evaluation_outcomes WHERE id = ? AND scope_key = ?')
996
+ .get(id, scopeKey);
997
+ const execution = executionComponent(selected(task.projection.executionOutcomeId));
998
+ const objective = task.projection.status === 'objective-conflict'
999
+ ? undefined
1000
+ : objectiveComponent(selected(task.projection.objectiveOutcomeId));
1001
+ const projection = Object.freeze({
1002
+ subjectKind: task.projection.subjectKind,
1003
+ subjectRef: task.projection.subjectRef,
1004
+ version: task.projection.learningVersion,
1005
+ digest: task.projection.learningDigest,
1006
+ disposition: task.projection.learningDisposition,
1007
+ ...(task.projection.objectiveOutcomeId === undefined
1008
+ ? {} : { evidenceOutcomeId: task.projection.objectiveOutcomeId }),
1009
+ });
1010
+ const receipt = Object.freeze({
1011
+ triggerOutcomeId: outcomeId,
1012
+ scope: Object.freeze({ ...task.scope }),
1013
+ scopeKey: task.scopeKey,
1014
+ scopeWatermark: watermarkRow.watermark,
1015
+ situation: task.situation,
1016
+ ...(execution === undefined ? {} : { execution }),
1017
+ ...(objective === undefined ? {} : { objective }),
1018
+ projection,
1019
+ });
1020
+ if (projection.version < 1 || !/^[a-f\d]{64}$/u.test(projection.digest)
1021
+ || evaluationLearningProjectionDigest(receipt) !== projection.digest) {
1022
+ throw new EvaluationStoreError('invalid-input', 'canonical task learning projection is corrupt');
1023
+ }
1024
+ return receipt;
1025
+ }
1026
+ listTaskLearningProjectionFeed(scopeInput, afterInput, limitInput = 100) {
1027
+ const { scope, scopeKey } = canonicalEvaluationScope(scopeInput);
1028
+ if (!Number.isSafeInteger(limitInput) || limitInput < 1 || limitInput > 100)
1029
+ throw new EvaluationStoreError('invalid-input', 'projection feed limit must be between 1 and 100');
1030
+ if (afterInput !== undefined && (!afterInput || typeof afterInput !== 'object' || Array.isArray(afterInput)
1031
+ || Object.getPrototypeOf(afterInput) !== Object.prototype || Object.getOwnPropertySymbols(afterInput).length !== 0
1032
+ || Object.keys(afterInput).length !== 2 || !Object.hasOwn(afterInput, 'scopeKey') || !Object.hasOwn(afterInput, 'watermark')
1033
+ || afterInput.scopeKey !== scopeKey || !Number.isSafeInteger(afterInput.watermark) || afterInput.watermark < 0)) {
1034
+ throw new EvaluationStoreError('invalid-input', 'projection feed cursor is invalid');
1035
+ }
1036
+ const after = afterInput === undefined ? 0 : afterInput.watermark;
1037
+ this.#database.exec('BEGIN');
1038
+ try {
1039
+ const watermarkRow = this.#database.prepare('SELECT watermark FROM evaluation_scope_watermarks WHERE scope_key = ?').get(scopeKey);
1040
+ const scopeWatermark = watermarkRow?.watermark ?? 0;
1041
+ if (!Number.isSafeInteger(scopeWatermark) || scopeWatermark < 0 || after > scopeWatermark)
1042
+ throw new EvaluationStoreError('invalid-input', 'projection feed cursor is ahead of scope');
1043
+ const rows = this.#database.prepare(`
1044
+ SELECT head.watermark, (
1045
+ SELECT outbox.evaluation_id FROM evaluation_projection_outbox outbox
1046
+ JOIN evaluation_outcomes audit ON audit.id = outbox.evaluation_id
1047
+ WHERE audit.task_subject_key = projection.subject_key AND audit.trust = 'trusted'
1048
+ ORDER BY audit.recorded_at DESC, audit.rowid DESC LIMIT 1
1049
+ ) AS trigger_outcome_id
1050
+ FROM evaluation_task_projection_feed_heads head
1051
+ JOIN evaluation_task_projections projection ON projection.subject_key = head.subject_key
1052
+ WHERE head.scope_key = ? AND head.watermark > ?
1053
+ ORDER BY head.watermark LIMIT ?
1054
+ `).all(scopeKey, after, limitInput + 1);
1055
+ const selected = rows.slice(0, limitInput).map(row => {
1056
+ const receipt = row.trigger_outcome_id === null ? undefined : this.getTaskLearningProjection(scope, row.trigger_outcome_id);
1057
+ if (receipt === undefined)
1058
+ throw new EvaluationStoreError('invalid-input', 'projection feed head is not trusted');
1059
+ return Object.freeze({ watermark: row.watermark, receipt });
1060
+ });
1061
+ const next = selected.at(-1)?.watermark ?? after;
1062
+ const page = Object.freeze({ items: Object.freeze(selected), nextCursor: Object.freeze({ scopeKey, watermark: next }), scopeWatermark, hasMore: rows.length > limitInput });
1063
+ this.#database.exec('COMMIT');
1064
+ return page;
1065
+ }
1066
+ catch (error) {
1067
+ this.#database.exec('ROLLBACK');
1068
+ throw error;
1069
+ }
1070
+ }
1071
+ /**
1072
+ * Host-only read of one trusted outcome's resource metrics. Deliberately a
1073
+ * separate projection rather than a receipt field: adding it to the receipt
1074
+ * would change every historical learning-projection digest.
1075
+ */
1076
+ inspectTrustedOutcomeMetrics(scopeInput, outcomeIdInput) {
1077
+ const { scopeKey } = canonicalEvaluationScope(scopeInput);
1078
+ const outcomeId = boundedText(outcomeIdInput, 'outcomeId', 200);
1079
+ const row = this.#database.prepare(`SELECT metrics_json FROM evaluation_outcomes
1080
+ WHERE id = ? AND scope_key = ? AND trust = 'trusted'`).get(outcomeId, scopeKey);
1081
+ if (row === undefined)
1082
+ return undefined;
1083
+ let parsed;
1084
+ try {
1085
+ parsed = JSON.parse(row.metrics_json);
1086
+ }
1087
+ catch {
1088
+ return undefined;
1089
+ }
1090
+ if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed))
1091
+ return undefined;
1092
+ const read = (key) => {
1093
+ const value = parsed[key];
1094
+ return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0 ? value : undefined;
1095
+ };
1096
+ const inputTokens = read('inputTokens'), outputTokens = read('outputTokens');
1097
+ const costUsdMicros = read('costUsdMicros'), latencyMs = read('latencyMs');
1098
+ const metrics = {
1099
+ ...(inputTokens === undefined ? {} : { inputTokens }),
1100
+ ...(outputTokens === undefined ? {} : { outputTokens }),
1101
+ ...(costUsdMicros === undefined ? {} : { costUsdMicros }),
1102
+ ...(latencyMs === undefined ? {} : { latencyMs }),
1103
+ };
1104
+ return Object.freeze(metrics);
1105
+ }
1106
+ inspectTaskOwnerRevision(scopeInput, outcomeIdInput, principalRecordIdInput, principalVersionInput) {
1107
+ const { scopeKey } = canonicalEvaluationScope(scopeInput);
1108
+ const outcomeId = boundedText(outcomeIdInput, 'outcomeId', 200);
1109
+ const principalRecordId = boundedText(principalRecordIdInput, 'principalRecordId', 4_096);
1110
+ if (!Number.isSafeInteger(principalVersionInput) || principalVersionInput < 1)
1111
+ throw new EvaluationStoreError('invalid-input', 'principalVersion must be a positive safe integer');
1112
+ const receipt = this.getTaskLearningProjection(scopeInput, outcomeId);
1113
+ if (!receipt || receipt.projection.evidenceOutcomeId === undefined)
1114
+ return undefined;
1115
+ const row = this.#database.prepare(`
1116
+ SELECT revision.outcome_id, revision.version, revision.action, outcome.objective_status,
1117
+ json_extract(revision.command_json, '$.operationId') AS operation_id
1118
+ FROM evaluation_owner_revisions revision
1119
+ JOIN evaluation_outcomes outcome ON outcome.id = revision.outcome_id
1120
+ JOIN evaluation_task_projections projection ON projection.subject_key = revision.subject_key
1121
+ WHERE revision.outcome_id = ? AND revision.lineage = ? AND projection.scope_key = ?
1122
+ AND projection.objective_outcome_id = revision.outcome_id
1123
+ AND NOT EXISTS (
1124
+ SELECT 1 FROM evaluation_owner_revisions newer
1125
+ WHERE newer.subject_key = revision.subject_key AND newer.lineage = revision.lineage
1126
+ AND newer.version > revision.version
1127
+ )
1128
+ ORDER BY revision.version DESC LIMIT 1
1129
+ `).get(receipt.projection.evidenceOutcomeId, JSON.stringify([principalRecordId, principalVersionInput]), scopeKey);
1130
+ return row === undefined ? undefined : Object.freeze({ outcomeId: row.outcome_id, version: row.version, action: row.action, objectiveStatus: row.objective_status,
1131
+ ...(typeof row.operation_id === 'string' ? { operationId: row.operation_id } : {}) });
1132
+ }
1133
+ /**
1134
+ * Hold Evaluation's scope writer fence while a synchronous downstream
1135
+ * callback acquires and commits its own writer transaction. The fixed lock
1136
+ * order is Evaluation first, downstream second; a Promise-returning callback
1137
+ * is rejected so the lock can never escape this stack frame.
1138
+ */
1139
+ withLearningWriterFence(scopeInput, fenceInput, callback, options = {}) {
1140
+ const { scopeKey } = canonicalEvaluationScope(scopeInput);
1141
+ const fence = this.#normalizeLearningWriterFence(fenceInput, false);
1142
+ if (options.requireProjectionDelivery !== false && fence.evidence.some(item => item.subjectKind === 'work-item')) {
1143
+ throw new EvaluationStoreError('invalid-input', 'work-item evidence is not supported by the Evolution writer fence');
1144
+ }
1145
+ return this.#withLearningWriterFence(scopeKey, fence, callback, options);
1146
+ }
1147
+ /**
1148
+ * Fence exact current canonical revisions, including retractions, without
1149
+ * waiting for optional Evolution projection delivery.
1150
+ */
1151
+ withCanonicalTaskWriterFence(scopeInput, fenceInput, callback) {
1152
+ const { scopeKey } = canonicalEvaluationScope(scopeInput);
1153
+ const fence = this.#normalizeLearningWriterFence(fenceInput, true);
1154
+ return this.#withLearningWriterFence(scopeKey, fence, callback, { requireProjectionDelivery: false });
1155
+ }
1156
+ /** Scope-only writer exclusion; zero means no canonical revision exists yet. */
1157
+ withCanonicalScopeWriterFence(scopeInput, fenceInput, callback) {
1158
+ const { scopeKey } = canonicalEvaluationScope(scopeInput);
1159
+ if (typeof fenceInput !== 'object' || fenceInput === null || Array.isArray(fenceInput)
1160
+ || !Number.isSafeInteger(fenceInput.scopeWatermark) || fenceInput.scopeWatermark < 0
1161
+ || typeof callback !== 'function') {
1162
+ throw new EvaluationStoreError('invalid-input', 'canonical scope writer fence is invalid');
1163
+ }
1164
+ return this.#withLearningWriterFence(scopeKey, { scopeWatermark: fenceInput.scopeWatermark, evidence: [] }, callback, { requireProjectionDelivery: false });
1165
+ }
1166
+ #withLearningWriterFence(scopeKey, fence, callback, options) {
1167
+ this.#database.exec('BEGIN IMMEDIATE');
1168
+ try {
1169
+ const watermark = this.#database.prepare(`
1170
+ SELECT watermark FROM evaluation_scope_watermarks WHERE scope_key = ?
1171
+ `).get(scopeKey);
1172
+ if ((watermark?.watermark ?? 0) !== fence.scopeWatermark) {
1173
+ this.#database.exec('COMMIT');
1174
+ return Object.freeze({ matched: false, reason: 'watermark-changed' });
1175
+ }
1176
+ const pending = options.requireProjectionDelivery === false ? undefined : this.#database.prepare(`
1177
+ SELECT 1 AS present
1178
+ FROM evaluation_projection_outbox outbox
1179
+ JOIN evaluation_outcomes outcome ON outcome.id = outbox.evaluation_id
1180
+ WHERE outcome.scope_key = ? AND outcome.trust = 'trusted'
1181
+ AND outbox.status = 'pending'
1182
+ LIMIT 1
1183
+ `).get(scopeKey);
1184
+ if (pending !== undefined) {
1185
+ this.#database.exec('COMMIT');
1186
+ return Object.freeze({ matched: false, reason: 'projection-pending' });
1187
+ }
1188
+ const statement = this.#database.prepare(`
1189
+ SELECT learning_version AS version, learning_digest AS digest,
1190
+ learning_disposition AS disposition
1191
+ FROM evaluation_task_projections
1192
+ WHERE subject_key = ? AND scope_key = ? AND subject_kind = ? AND subject_ref = ?
1193
+ `);
1194
+ for (const evidence of fence.evidence) {
1195
+ const current = statement.get(taskSubjectKey(scopeKey, evidence.subjectKind, evidence.subjectRef), scopeKey, evidence.subjectKind, evidence.subjectRef);
1196
+ if (current === undefined || current.version !== evidence.version
1197
+ || current.digest !== evidence.digest || current.disposition !== evidence.disposition) {
1198
+ this.#database.exec('COMMIT');
1199
+ return Object.freeze({ matched: false, reason: 'evidence-changed' });
1200
+ }
1201
+ }
1202
+ const value = callback();
1203
+ if ((typeof value === 'object' || typeof value === 'function') && value !== null && 'then' in value) {
1204
+ // Never evaluate an untrusted then getter. The native method only
1205
+ // consumes real Promise rejections; other thenables fail its brand
1206
+ // check without running their implementation.
1207
+ try {
1208
+ Promise.prototype.then.call(value, undefined, () => undefined);
1209
+ }
1210
+ catch { /* Not a native Promise. */ }
1211
+ throw new EvaluationStoreError('invalid-input', 'learning writer fence callback must be synchronous');
1212
+ }
1213
+ this.#database.exec('COMMIT');
1214
+ return Object.freeze({ matched: true, value });
1215
+ }
1216
+ catch (error) {
1217
+ this.#database.exec('ROLLBACK');
1218
+ throw error;
1219
+ }
1220
+ }
1221
+ /** Query one deterministic latest row per task; raw query() remains the audit API. */
1222
+ queryTasks(input) {
1223
+ const { scopeKey } = canonicalEvaluationScope(input.scope);
1224
+ const limit = input.limit ?? Math.min(50, this.#maxQueryLimit);
1225
+ if (!Number.isSafeInteger(limit) || limit < 1 || limit > this.#maxQueryLimit) {
1226
+ throw new EvaluationStoreError('invalid-input', `query limit must be between 1 and ${this.#maxQueryLimit}`);
1227
+ }
1228
+ const clauses = ['scope_key = ?'];
1229
+ const parameters = [scopeKey];
1230
+ const add = (column, value) => {
1231
+ if (value === undefined)
1232
+ return;
1233
+ clauses.push(`${column} = ?`);
1234
+ parameters.push(value);
1235
+ };
1236
+ add('situation', input.situation === undefined ? undefined : this.#situation(input.situation));
1237
+ add('execution_status', input.executionStatus === undefined
1238
+ ? undefined : oneOf(input.executionStatus, executionStatuses, 'executionStatus'));
1239
+ add('objective_status', input.objectiveStatus === undefined
1240
+ ? undefined : oneOf(input.objectiveStatus, objectiveStatuses, 'objectiveStatus'));
1241
+ add('delivery_status', input.deliveryStatus === undefined
1242
+ ? undefined : oneOf(input.deliveryStatus, deliveryStatuses, 'deliveryStatus'));
1243
+ add('source_kind', input.sourceKind === undefined
1244
+ ? undefined : oneOf(input.sourceKind, outcomeSourceKinds, 'sourceKind'));
1245
+ add('trust', input.trust === undefined ? undefined : oneOf(input.trust, outcomeTrustLevels, 'trust'));
1246
+ if (input.excludeSituationPrefix !== undefined) {
1247
+ const prefix = this.#situation(input.excludeSituationPrefix);
1248
+ clauses.push('substr(situation, 1, length(?)) <> ?');
1249
+ parameters.push(prefix, prefix);
1250
+ }
1251
+ const [from, to] = this.#optionalRange(input.fromOccurredAt, input.toOccurredAt);
1252
+ if (from !== undefined) {
1253
+ clauses.push('occurred_at >= ?');
1254
+ parameters.push(from);
1255
+ }
1256
+ if (to !== undefined) {
1257
+ clauses.push('occurred_at <= ?');
1258
+ parameters.push(to);
1259
+ }
1260
+ parameters.push(limit);
1261
+ const rows = this.#database.prepare(`
1262
+ SELECT * FROM evaluation_task_projection_view WHERE ${clauses.join(' AND ')}
1263
+ ORDER BY occurred_at DESC, task_subject_key DESC LIMIT ?
1264
+ `).all(...parameters);
1265
+ return rows.map(row => projected(row));
1266
+ }
1267
+ query(input) {
1268
+ const { scopeKey } = canonicalEvaluationScope(input.scope);
1269
+ const limit = input.limit ?? Math.min(50, this.#maxQueryLimit);
1270
+ if (!Number.isSafeInteger(limit) || limit < 1 || limit > this.#maxQueryLimit) {
1271
+ throw new EvaluationStoreError('invalid-input', `query limit must be between 1 and ${this.#maxQueryLimit}`);
1272
+ }
1273
+ const clauses = ['scope_key = ?'];
1274
+ const parameters = [scopeKey];
1275
+ const add = (column, value) => {
1276
+ if (value === undefined)
1277
+ return;
1278
+ clauses.push(`${column} = ?`);
1279
+ parameters.push(value);
1280
+ };
1281
+ add('situation', input.situation === undefined ? undefined : this.#situation(input.situation));
1282
+ add('execution_status', input.executionStatus === undefined
1283
+ ? undefined : oneOf(input.executionStatus, executionStatuses, 'executionStatus'));
1284
+ add('objective_status', input.objectiveStatus === undefined
1285
+ ? undefined : oneOf(input.objectiveStatus, objectiveStatuses, 'objectiveStatus'));
1286
+ add('delivery_status', input.deliveryStatus === undefined
1287
+ ? undefined : oneOf(input.deliveryStatus, deliveryStatuses, 'deliveryStatus'));
1288
+ add('source_kind', input.sourceKind === undefined
1289
+ ? undefined : oneOf(input.sourceKind, outcomeSourceKinds, 'sourceKind'));
1290
+ add('trust', input.trust === undefined ? undefined : oneOf(input.trust, outcomeTrustLevels, 'trust'));
1291
+ if (input.excludeSituationPrefix !== undefined) {
1292
+ const prefix = this.#situation(input.excludeSituationPrefix);
1293
+ clauses.push('substr(situation, 1, length(?)) <> ?');
1294
+ parameters.push(prefix, prefix);
1295
+ }
1296
+ const [from, to] = this.#optionalRange(input.fromOccurredAt, input.toOccurredAt);
1297
+ if (from !== undefined) {
1298
+ clauses.push('occurred_at >= ?');
1299
+ parameters.push(from);
1300
+ }
1301
+ if (to !== undefined) {
1302
+ clauses.push('occurred_at <= ?');
1303
+ parameters.push(to);
1304
+ }
1305
+ parameters.push(limit);
1306
+ const rows = this.#database.prepare(`
1307
+ SELECT * FROM evaluation_outcomes WHERE ${clauses.join(' AND ')}
1308
+ ORDER BY occurred_at DESC, id DESC LIMIT ?
1309
+ `).all(...parameters);
1310
+ return rows.map(row => stored(row));
1311
+ }
1312
+ summary(input) {
1313
+ const { scope, scopeKey } = canonicalEvaluationScope(input.scope);
1314
+ const [fromOccurredAt, toOccurredAt] = this.#summaryRange(input.fromOccurredAt, input.toOccurredAt);
1315
+ const situation = input.situation === undefined ? undefined : this.#situation(input.situation);
1316
+ const excludeSituationPrefix = input.excludeSituationPrefix === undefined
1317
+ ? undefined
1318
+ : this.#situation(input.excludeSituationPrefix);
1319
+ const row = this.#database.prepare(`
1320
+ SELECT
1321
+ COUNT(*) AS total,
1322
+ SUM(execution_status = 'succeeded') AS execution_succeeded,
1323
+ SUM(execution_status = 'failed') AS execution_failed,
1324
+ SUM(execution_status = 'timed-out') AS execution_timed_out,
1325
+ SUM(execution_status = 'cancelled') AS execution_cancelled,
1326
+ SUM(execution_status = 'unknown') AS execution_unknown,
1327
+ SUM(objective_status = 'achieved') AS objective_achieved,
1328
+ SUM(objective_status = 'partial') AS objective_partial,
1329
+ SUM(objective_status = 'not-achieved') AS objective_not_achieved,
1330
+ SUM(objective_status = 'unknown') AS objective_unknown,
1331
+ SUM(delivery_status = 'delivered') AS delivery_delivered,
1332
+ SUM(delivery_status = 'failed') AS delivery_failed,
1333
+ SUM(delivery_status = 'not-required') AS delivery_not_required,
1334
+ SUM(delivery_status = 'unknown') AS delivery_unknown,
1335
+ SUM(trust = 'trusted') AS trust_trusted,
1336
+ SUM(trust = 'self-reported') AS trust_self_reported,
1337
+ SUM(trust = 'external') AS trust_external,
1338
+ TOTAL(cost_usd_micros) AS cost_usd_micros,
1339
+ TOTAL(input_tokens) AS input_tokens,
1340
+ TOTAL(output_tokens) AS output_tokens,
1341
+ TOTAL(tool_calls) AS tool_calls,
1342
+ TOTAL(latency_ms) AS latency_total,
1343
+ COUNT(latency_ms) AS latency_count
1344
+ FROM evaluation_task_projection_view
1345
+ WHERE scope_key = ? AND occurred_at >= ? AND occurred_at <= ?
1346
+ AND (? IS NULL OR situation = ?)
1347
+ AND (? IS NULL OR substr(situation, 1, length(?)) <> ?)
1348
+ `).get(scopeKey, fromOccurredAt, toOccurredAt, situation ?? null, situation ?? null, excludeSituationPrefix ?? null, excludeSituationPrefix ?? null, excludeSituationPrefix ?? null);
1349
+ const count = (key) => row[key] ?? 0;
1350
+ const latencyCount = count('latency_count');
1351
+ return Object.freeze({
1352
+ scope,
1353
+ scopeKey,
1354
+ ...(situation === undefined ? {} : { situation }),
1355
+ fromOccurredAt,
1356
+ toOccurredAt,
1357
+ total: count('total'),
1358
+ execution: Object.freeze({
1359
+ succeeded: count('execution_succeeded'), failed: count('execution_failed'),
1360
+ timedOut: count('execution_timed_out'), cancelled: count('execution_cancelled'), unknown: count('execution_unknown'),
1361
+ }),
1362
+ objective: Object.freeze({
1363
+ achieved: count('objective_achieved'), partial: count('objective_partial'),
1364
+ notAchieved: count('objective_not_achieved'), unknown: count('objective_unknown'),
1365
+ }),
1366
+ delivery: Object.freeze({
1367
+ delivered: count('delivery_delivered'), failed: count('delivery_failed'),
1368
+ notRequired: count('delivery_not_required'), unknown: count('delivery_unknown'),
1369
+ }),
1370
+ trust: Object.freeze({
1371
+ trusted: count('trust_trusted'), selfReported: count('trust_self_reported'), external: count('trust_external'),
1372
+ }),
1373
+ metrics: Object.freeze({
1374
+ costUsdMicros: count('cost_usd_micros'), inputTokens: count('input_tokens'),
1375
+ outputTokens: count('output_tokens'), toolCalls: count('tool_calls'),
1376
+ ...(latencyCount === 0 ? {} : { averageLatencyMs: Math.round(count('latency_total') / latencyCount) }),
1377
+ }),
1378
+ });
1379
+ }
1380
+ health() {
1381
+ const row = this.#database.prepare(`
1382
+ SELECT COUNT(*) AS outcomes,
1383
+ SUM(trust = 'trusted') AS trusted,
1384
+ SUM(trust = 'self-reported') AS self_reported,
1385
+ SUM(trust = 'external') AS external,
1386
+ MAX(occurred_at) AS latest
1387
+ FROM evaluation_outcomes
1388
+ `).get();
1389
+ const assessmentRow = this.#database.prepare('SELECT COUNT(*) AS count FROM evaluation_self_assessments')
1390
+ .get();
1391
+ const taskRow = this.#database.prepare(`
1392
+ SELECT COUNT(*) AS count, SUM(objective_conflicted) AS conflicted
1393
+ FROM evaluation_task_projections WHERE primary_outcome_id IS NOT NULL
1394
+ `).get();
1395
+ const projectionRow = this.#database.prepare(`
1396
+ SELECT COUNT(*) AS pending,
1397
+ SUM(attempt_count > 0) AS retrying,
1398
+ TOTAL(attempt_count) AS attempts,
1399
+ MIN(created_at) AS oldest
1400
+ FROM evaluation_projection_outbox WHERE status = 'pending'
1401
+ `).get();
1402
+ const notifications = this.notifications.counts();
1403
+ return Object.freeze({
1404
+ ready: true,
1405
+ schemaVersion: evaluationSchemaVersion,
1406
+ outcomes: row.outcomes,
1407
+ trustedOutcomes: row.trusted ?? 0,
1408
+ selfReportedOutcomes: row.self_reported ?? 0,
1409
+ externalOutcomes: row.external ?? 0,
1410
+ selfAssessments: assessmentRow.count,
1411
+ taskProjections: taskRow.count,
1412
+ conflictedTaskProjections: taskRow.conflicted ?? 0,
1413
+ pendingProjections: projectionRow.pending,
1414
+ retryingProjections: projectionRow.retrying ?? 0,
1415
+ projectionAttempts: projectionRow.attempts,
1416
+ notificationOutcomes: notifications.notifications,
1417
+ notificationOutcomeRevisions: notifications.revisions,
1418
+ intakeEvaluations: this.intakeEvaluations.count(),
1419
+ ...(projectionRow.oldest === null ? {} : { oldestPendingProjectionAt: projectionRow.oldest }),
1420
+ ...(row.latest === null ? {} : { latestOccurredAt: row.latest }),
1421
+ });
1422
+ }
1423
+ #rebuildTaskProjections() {
1424
+ this.#database.exec('BEGIN IMMEDIATE');
1425
+ try {
1426
+ const rows = this.#database.prepare(`
1427
+ SELECT * FROM evaluation_outcomes ORDER BY recorded_at, id
1428
+ `).all();
1429
+ const updateOutcome = this.#database.prepare(`
1430
+ UPDATE evaluation_outcomes
1431
+ SET task_subject_key = ?, task_subject_kind = ?, task_subject_ref = ?
1432
+ WHERE id = ?
1433
+ `);
1434
+ const insertSubject = this.#database.prepare(`
1435
+ INSERT INTO evaluation_task_projections(
1436
+ subject_key, scope_key, subject_kind, subject_ref, updated_at)
1437
+ VALUES (?, ?, ?, ?, ?)
1438
+ ON CONFLICT(subject_key) DO UPDATE SET
1439
+ scope_key = excluded.scope_key,
1440
+ subject_kind = excluded.subject_kind,
1441
+ subject_ref = excluded.subject_ref
1442
+ `);
1443
+ const subjects = new Set();
1444
+ for (const row of rows) {
1445
+ const subject = row.task_subject_key === null
1446
+ || row.task_subject_kind === null
1447
+ || row.task_subject_ref === null
1448
+ ? taskSubject(row.scope_key, row.id, JSON.parse(row.evidence_json))
1449
+ : { key: row.task_subject_key, kind: row.task_subject_kind, ref: row.task_subject_ref };
1450
+ if (row.task_subject_key !== subject.key
1451
+ || row.task_subject_kind !== subject.kind
1452
+ || row.task_subject_ref !== subject.ref) {
1453
+ updateOutcome.run(subject.key, subject.kind, subject.ref, row.id);
1454
+ }
1455
+ insertSubject.run(subject.key, row.scope_key, subject.kind, subject.ref, row.recorded_at);
1456
+ subjects.add(subject.key);
1457
+ }
1458
+ for (const subjectKey of [...subjects].sort()) {
1459
+ const refreshed = this.#refreshTaskProjection(subjectKey);
1460
+ if (!refreshed.learningVersionChanged)
1461
+ continue;
1462
+ const current = this.#database.prepare(`
1463
+ SELECT projection.scope_key, projection.primary_outcome_id, projection.updated_at,
1464
+ projection.subject_kind, outcome.trust
1465
+ FROM evaluation_task_projections projection
1466
+ JOIN evaluation_outcomes outcome ON outcome.id = projection.primary_outcome_id
1467
+ WHERE projection.subject_key = ?
1468
+ `).get(subjectKey);
1469
+ if (current.trust !== 'trusted')
1470
+ continue;
1471
+ this.#database.prepare(`
1472
+ INSERT INTO evaluation_projection_outbox(
1473
+ evaluation_id, status, attempt_count, next_attempt_at,
1474
+ last_failure_at, last_failure_code, created_at, updated_at)
1475
+ VALUES (?, ?, 0, ?, NULL, NULL, ?, ?)
1476
+ ON CONFLICT(evaluation_id) DO UPDATE SET
1477
+ status = excluded.status, attempt_count = 0,
1478
+ next_attempt_at = excluded.next_attempt_at,
1479
+ last_failure_at = NULL, last_failure_code = NULL,
1480
+ updated_at = excluded.updated_at
1481
+ `).run(current.primary_outcome_id, current.subject_kind === 'work-item' ? 'not-required' : 'pending', current.updated_at, current.updated_at, current.updated_at);
1482
+ this.#advanceScopeWatermark(current.scope_key, current.updated_at, subjectKey);
1483
+ }
1484
+ // An unsupported optional consumer must never become retry work. This
1485
+ // also settles pending rows from an interrupted pre-release Host without
1486
+ // inventing an Evolution applied receipt or rewriting canonical evidence.
1487
+ this.#database.prepare(`UPDATE evaluation_projection_outbox SET status = 'not-required'
1488
+ WHERE status = 'pending' AND EXISTS (SELECT 1 FROM evaluation_outcomes outcome
1489
+ WHERE outcome.id = evaluation_projection_outbox.evaluation_id AND outcome.task_subject_kind = 'work-item')`).run();
1490
+ this.#database.exec('COMMIT');
1491
+ }
1492
+ catch (error) {
1493
+ this.#database.exec('ROLLBACK');
1494
+ throw error;
1495
+ }
1496
+ }
1497
+ #refreshTaskProjection(subjectKey) {
1498
+ const projection = this.#database.prepare(`
1499
+ SELECT subject_kind, subject_ref, learning_version, learning_digest, learning_disposition
1500
+ FROM evaluation_task_projections WHERE subject_key = ?
1501
+ `).get(subjectKey);
1502
+ if (projection === undefined) {
1503
+ throw new EvaluationStoreError('not-found', 'task projection subject was not found');
1504
+ }
1505
+ const rows = this.#database.prepare(`
1506
+ SELECT rowid AS seq, * FROM evaluation_outcomes WHERE task_subject_key = ?
1507
+ ORDER BY recorded_at, rowid
1508
+ `).all(subjectKey);
1509
+ if (rows.length === 0)
1510
+ return { learningVersionChanged: false };
1511
+ let primary;
1512
+ let execution;
1513
+ let objective;
1514
+ let delivery;
1515
+ let objectiveConflicted = false;
1516
+ if (projection.subject_kind === 'outcome') {
1517
+ primary = latest(rows);
1518
+ execution = primary;
1519
+ objective = primary;
1520
+ delivery = primary;
1521
+ }
1522
+ else {
1523
+ const terminals = rows.filter(row => isAuthoritativeAutomationTerminal(row));
1524
+ execution = projection.subject_kind === 'automation-run'
1525
+ ? latest(terminals)
1526
+ : projection.subject_kind === 'work-item'
1527
+ ? latestWorkItemTerminal(rows)
1528
+ : latest(rows.filter(row => isAuthoritativeForegroundTerminal(row)));
1529
+ const superseded = new Set(this.#database.prepare(`
1530
+ SELECT previous_outcome_id FROM evaluation_owner_revisions WHERE subject_key = ? AND previous_outcome_id IS NOT NULL
1531
+ `).all(subjectKey).map(row => row.previous_outcome_id));
1532
+ const owners = rows.filter(row => isAuthenticatedOwnerFeedback(row) && !superseded.has(row.id));
1533
+ const ownerStatuses = new Set(owners.map(row => row.objective_status));
1534
+ if (ownerStatuses.size > 1)
1535
+ objectiveConflicted = true;
1536
+ else if (owners.length > 0)
1537
+ objective = latest(owners);
1538
+ else {
1539
+ const trustedObjectives = rows.filter(row => row.trust === 'trusted'
1540
+ && row.source_kind !== 'user-feedback'
1541
+ // The newest verifier receipt is authoritative even when it is
1542
+ // unknown: it retracts a stale achieved proof after expiry/recheck.
1543
+ && (row.objective_status !== 'unknown' || isTrustedVerifierReceipt(row)));
1544
+ const ranked = trustedObjectives.map(row => ({
1545
+ row,
1546
+ // Independent trusted evaluators supersede the terminal producer's
1547
+ // initial objective, while an owner judgement has already won above.
1548
+ rank: isAuthoritativeAutomationTerminal(row) ? 1 : isTrustedVerifierReceipt(row) ? 3 : 2,
1549
+ })).sort((left, right) => left.rank - right.rank || newer(left.row, right.row));
1550
+ objective = ranked.at(-1)?.row;
1551
+ }
1552
+ const ownerDelivery = latest(rows.filter(row => isAuthenticatedOwnerFeedback(row)
1553
+ && row.delivery_status === 'delivered'));
1554
+ const trustedDelivery = latest(rows.filter(row => row.trust === 'trusted'
1555
+ && row.source_kind === 'delivery' && row.delivery_status !== 'unknown'));
1556
+ delivery = ownerDelivery ?? trustedDelivery ?? execution;
1557
+ const rankedPrimary = rows.map(row => ({
1558
+ row,
1559
+ rank: isAuthoritativeAutomationTerminal(row) || isAuthoritativeForegroundTerminal(row) || isAuthoritativeWorkItemTerminal(row)
1560
+ ? 4
1561
+ : isAuthenticatedOwnerFeedback(row)
1562
+ ? 3
1563
+ : row.trust === 'trusted'
1564
+ ? 2
1565
+ : row.trust === 'external' ? 1 : 0,
1566
+ })).sort((left, right) => left.rank - right.rank || newer(left.row, right.row));
1567
+ primary = rankedPrimary.at(-1).row;
1568
+ }
1569
+ const objectiveStatus = objectiveConflicted ? 'unknown' : objective?.objective_status ?? 'unknown';
1570
+ const objectiveSituationMismatch = objective !== undefined && objective.situation !== primary.situation;
1571
+ const hostRunbook = execution !== undefined && isAuthoritativeAutomationTerminal(execution)
1572
+ && /^host-runbook-v[1-9][0-9]*$/u.test(execution.evaluator_version);
1573
+ const workItemProofIdentity = execution === undefined ? undefined
1574
+ : workItemProductionIdentity(JSON.parse(execution.evidence_json));
1575
+ const workItemProofMatches = projection.subject_kind !== 'work-item' || objective !== undefined
1576
+ && workItemProofIdentity !== undefined
1577
+ && workItemProofIdentity === workItemProductionIdentity(JSON.parse(objective.evidence_json));
1578
+ const learningDisposition = !objectiveConflicted
1579
+ && workItemProofMatches
1580
+ && !objectiveSituationMismatch
1581
+ && objective?.trust === 'trusted'
1582
+ && (objectiveStatus === 'achieved' || objectiveStatus === 'not-achieved')
1583
+ && (!['automation-run', 'work-item'].includes(projection.subject_kind) || execution !== undefined)
1584
+ && !hostRunbook
1585
+ ? 'upsert'
1586
+ : 'retract';
1587
+ const evidenceOutcomeId = objectiveConflicted ? undefined : objective?.id;
1588
+ const learningExecution = executionComponent(execution);
1589
+ const learningObjective = objectiveConflicted ? undefined : objectiveComponent(objective);
1590
+ const learningDigest = evaluationLearningProjectionDigest({
1591
+ scopeKey: primary.scope_key,
1592
+ situation: primary.situation,
1593
+ ...(learningExecution === undefined ? {} : { execution: learningExecution }),
1594
+ ...(learningObjective === undefined ? {} : { objective: learningObjective }),
1595
+ projection: {
1596
+ subjectKind: projection.subject_kind,
1597
+ subjectRef: projection.subject_ref,
1598
+ disposition: learningDisposition,
1599
+ ...(evidenceOutcomeId === undefined ? {} : { evidenceOutcomeId }),
1600
+ },
1601
+ });
1602
+ const learningVersionChanged = projection.learning_digest !== learningDigest
1603
+ || projection.learning_disposition !== learningDisposition;
1604
+ const learningVersion = projection.learning_version === 0
1605
+ ? 1
1606
+ : learningVersionChanged
1607
+ ? projection.learning_version + 1
1608
+ : projection.learning_version;
1609
+ if (!Number.isSafeInteger(learningVersion)) {
1610
+ throw new EvaluationStoreError('invalid-input', 'task learning projection version overflow');
1611
+ }
1612
+ const updatedAt = Math.max(...rows.map(row => row.recorded_at));
1613
+ this.#database.prepare(`
1614
+ UPDATE evaluation_task_projections
1615
+ SET primary_outcome_id = ?, execution_outcome_id = ?, objective_outcome_id = ?,
1616
+ delivery_outcome_id = ?, objective_conflicted = ?, learning_version = ?,
1617
+ learning_digest = ?, learning_disposition = ?, updated_at = ?
1618
+ WHERE subject_key = ?
1619
+ `).run(primary.id, execution?.id ?? null, objectiveConflicted ? null : objective?.id ?? null, delivery?.id ?? null, objectiveConflicted ? 1 : 0, learningVersion, learningDigest, learningDisposition, updatedAt, subjectKey);
1620
+ return { learningVersionChanged: projection.learning_version === 0 || learningVersionChanged };
1621
+ }
1622
+ #advanceScopeWatermark(scopeKey, updatedAt, subjectKey) {
1623
+ this.#database.prepare(`
1624
+ INSERT INTO evaluation_scope_watermarks(scope_key, watermark, updated_at)
1625
+ VALUES (?, 1, ?)
1626
+ ON CONFLICT(scope_key) DO UPDATE SET
1627
+ watermark = evaluation_scope_watermarks.watermark + 1,
1628
+ updated_at = excluded.updated_at
1629
+ `).run(scopeKey, updatedAt);
1630
+ const row = this.#database.prepare(`
1631
+ SELECT watermark FROM evaluation_scope_watermarks WHERE scope_key = ?
1632
+ `).get(scopeKey);
1633
+ if (!Number.isSafeInteger(row.watermark) || row.watermark < 1) {
1634
+ throw new EvaluationStoreError('invalid-input', 'canonical scope watermark overflow');
1635
+ }
1636
+ this.#database.prepare(`
1637
+ INSERT INTO evaluation_task_projection_feed_heads(subject_key, scope_key, watermark)
1638
+ VALUES (?, ?, ?)
1639
+ ON CONFLICT(subject_key) DO UPDATE SET scope_key = excluded.scope_key, watermark = excluded.watermark
1640
+ `).run(subjectKey, scopeKey, row.watermark);
1641
+ return row.watermark;
1642
+ }
1643
+ #normalizeLearningWriterFence(input, allowRetract) {
1644
+ if (typeof input !== 'object' || input === null || Array.isArray(input)
1645
+ || !Number.isSafeInteger(input.scopeWatermark) || input.scopeWatermark < 1
1646
+ || !Array.isArray(input.evidence) || input.evidence.length < 1
1647
+ || input.evidence.length > 10_000) {
1648
+ throw new EvaluationStoreError('invalid-input', 'learning writer fence is invalid');
1649
+ }
1650
+ const seen = new Set();
1651
+ const entries = input.evidence.map((raw, index) => {
1652
+ if (typeof raw !== 'object' || raw === null || Array.isArray(raw)
1653
+ || (raw.disposition !== 'upsert' && (!allowRetract || raw.disposition !== 'retract'))
1654
+ || (raw.subjectKind !== 'automation-run' && raw.subjectKind !== 'foreground-turn' && raw.subjectKind !== 'goal-step' && raw.subjectKind !== 'goal-outcome' && raw.subjectKind !== 'work-item' && raw.subjectKind !== 'outcome')
1655
+ || !Number.isSafeInteger(raw.version) || raw.version < 1
1656
+ || raw.version > 1_000_000_000
1657
+ || typeof raw.digest !== 'string' || !/^[a-f\d]{64}$/u.test(raw.digest)) {
1658
+ throw new EvaluationStoreError('invalid-input', `learning writer fence evidence[${index}] is invalid`);
1659
+ }
1660
+ const subjectRef = boundedText(raw.subjectRef, `evidence[${index}].subjectRef`, 1_000);
1661
+ const identity = JSON.stringify([raw.subjectKind, subjectRef]);
1662
+ if (seen.has(identity)) {
1663
+ throw new EvaluationStoreError('invalid-input', 'learning writer fence contains duplicate evidence');
1664
+ }
1665
+ seen.add(identity);
1666
+ return Object.freeze({
1667
+ subjectKind: raw.subjectKind,
1668
+ subjectRef,
1669
+ version: raw.version,
1670
+ digest: raw.digest,
1671
+ disposition: raw.disposition,
1672
+ });
1673
+ });
1674
+ return Object.freeze({
1675
+ scopeWatermark: input.scopeWatermark,
1676
+ evidence: Object.freeze(entries),
1677
+ });
1678
+ }
1679
+ #normalize(input) {
1680
+ const { scope, scopeKey } = canonicalEvaluationScope(input.scope);
1681
+ const situation = this.#situation(input.situation);
1682
+ const sourceKind = oneOf(input.source?.kind, outcomeSourceKinds, 'source.kind');
1683
+ const sourceId = boundedText(input.source?.id, 'source.id', 200);
1684
+ const evaluatorId = boundedText(input.evaluator?.id, 'evaluator.id', 200);
1685
+ const evaluatorVersion = boundedText(input.evaluator?.version, 'evaluator.version', 100);
1686
+ return Object.freeze({
1687
+ scope,
1688
+ scopeKey,
1689
+ situation,
1690
+ executionStatus: oneOf(input.executionStatus, executionStatuses, 'executionStatus'),
1691
+ objectiveStatus: oneOf(input.objectiveStatus, objectiveStatuses, 'objectiveStatus'),
1692
+ deliveryStatus: oneOf(input.deliveryStatus, deliveryStatuses, 'deliveryStatus'),
1693
+ source: Object.freeze({ kind: sourceKind, id: sourceId }),
1694
+ trust: oneOf(input.trust, outcomeTrustLevels, 'trust'),
1695
+ evidence: evidence(input.evidence, this.#maxEvidenceRefs),
1696
+ metrics: metrics(input.metrics, this.#maxMetricsBytes),
1697
+ occurredAt: timestamp(input.occurredAt, 'occurredAt'),
1698
+ idempotencyKey: boundedText(input.idempotencyKey, 'idempotencyKey', 200),
1699
+ evaluator: Object.freeze({ id: evaluatorId, version: evaluatorVersion }),
1700
+ });
1701
+ }
1702
+ #situation(value) { return boundedText(value, 'situation', this.#maxSituationBytes); }
1703
+ #optionalRange(fromInput, toInput) {
1704
+ const from = fromInput === undefined ? undefined : timestamp(fromInput, 'fromOccurredAt');
1705
+ const to = toInput === undefined ? undefined : timestamp(toInput, 'toOccurredAt');
1706
+ if (from !== undefined && to !== undefined && from > to) {
1707
+ throw new EvaluationStoreError('invalid-input', 'query time range is reversed');
1708
+ }
1709
+ return [from, to];
1710
+ }
1711
+ #summaryRange(fromInput, toInput) {
1712
+ const to = toInput === undefined ? timestamp(this.#now(), 'toOccurredAt') : timestamp(toInput, 'toOccurredAt');
1713
+ const from = fromInput === undefined ? Math.max(0, to - this.#defaultSummaryWindowMs) : timestamp(fromInput, 'fromOccurredAt');
1714
+ if (from > to)
1715
+ throw new EvaluationStoreError('invalid-input', 'summary time range is reversed');
1716
+ if (to - from > this.#maxSummaryWindowMs) {
1717
+ throw new EvaluationStoreError('invalid-input', `summary window exceeds ${this.#maxSummaryWindowMs}ms`);
1718
+ }
1719
+ return [from, to];
1720
+ }
1721
+ }
1722
+ //# sourceMappingURL=store.js.map