@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/sqlite.js ADDED
@@ -0,0 +1,1247 @@
1
+ import { chmodSync, closeSync, constants, existsSync, lstatSync, mkdirSync, openSync, } from 'node:fs';
2
+ import { dirname, isAbsolute } from 'node:path';
3
+ import { DatabaseSync } from 'node:sqlite';
4
+ export const evaluationSchemaVersion = 19;
5
+ export class EvaluationDatabaseError extends Error {
6
+ code;
7
+ constructor(code, message) {
8
+ super(message);
9
+ this.code = code;
10
+ this.name = 'EvaluationDatabaseError';
11
+ }
12
+ }
13
+ function assertSafeFile(path) {
14
+ const stat = lstatSync(path);
15
+ if (!stat.isFile() || stat.isSymbolicLink() || stat.nlink !== 1) {
16
+ throw new EvaluationDatabaseError('unsafe-file', 'evaluation database must be one regular, unlinked file');
17
+ }
18
+ if ((stat.mode & 0o077) !== 0) {
19
+ throw new EvaluationDatabaseError('unsafe-file', 'evaluation database permissions must not allow group or other access');
20
+ }
21
+ const uid = process.getuid?.();
22
+ if (uid !== undefined && stat.uid !== uid) {
23
+ throw new EvaluationDatabaseError('unsafe-file', 'evaluation database must be owned by the current OS user');
24
+ }
25
+ }
26
+ function preparePrivateFile(path) {
27
+ mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
28
+ if (!existsSync(path)) {
29
+ const descriptor = openSync(path, constants.O_CREAT | constants.O_EXCL | constants.O_RDWR, 0o600);
30
+ closeSync(descriptor);
31
+ }
32
+ assertSafeFile(path);
33
+ }
34
+ function schemaVersion(database) {
35
+ return database.prepare('PRAGMA user_version').get().user_version;
36
+ }
37
+ const selfAssessmentSchema = `
38
+ CREATE TABLE evaluation_self_assessments (
39
+ id TEXT PRIMARY KEY,
40
+ outcome_id TEXT NOT NULL,
41
+ idempotency_key TEXT NOT NULL UNIQUE,
42
+ payload_hash TEXT NOT NULL,
43
+ scope_key TEXT NOT NULL,
44
+ objective_status TEXT NOT NULL
45
+ CHECK (objective_status IN ('achieved', 'partial', 'not-achieved', 'unknown')),
46
+ evidence_json TEXT NOT NULL,
47
+ occurred_at INTEGER NOT NULL,
48
+ recorded_at INTEGER NOT NULL,
49
+ evaluator_id TEXT NOT NULL,
50
+ evaluator_version TEXT NOT NULL,
51
+ FOREIGN KEY (outcome_id) REFERENCES evaluation_outcomes(id) ON DELETE RESTRICT
52
+ ) STRICT;
53
+ CREATE INDEX evaluation_self_assessments_scope_time
54
+ ON evaluation_self_assessments(scope_key, occurred_at DESC, id DESC);
55
+ CREATE INDEX evaluation_self_assessments_outcome_time
56
+ ON evaluation_self_assessments(outcome_id, occurred_at DESC, id DESC);
57
+ `;
58
+ const projectionOutboxSchema = `
59
+ CREATE TABLE evaluation_projection_outbox (
60
+ evaluation_id TEXT PRIMARY KEY,
61
+ status TEXT NOT NULL CHECK (status IN ('pending', 'recorded', 'not-required')),
62
+ attempt_count INTEGER NOT NULL CHECK (attempt_count >= 0),
63
+ next_attempt_at INTEGER NOT NULL,
64
+ last_failure_at INTEGER,
65
+ last_failure_code TEXT,
66
+ created_at INTEGER NOT NULL,
67
+ updated_at INTEGER NOT NULL,
68
+ FOREIGN KEY (evaluation_id) REFERENCES evaluation_outcomes(id) ON DELETE RESTRICT
69
+ ) STRICT;
70
+ CREATE INDEX evaluation_projection_outbox_due
71
+ ON evaluation_projection_outbox(status, next_attempt_at, created_at, evaluation_id);
72
+ `;
73
+ const scopeWatermarkSchema = `
74
+ CREATE TABLE evaluation_scope_watermarks (
75
+ scope_key TEXT PRIMARY KEY,
76
+ watermark INTEGER NOT NULL CHECK (watermark >= 0),
77
+ updated_at INTEGER NOT NULL
78
+ ) STRICT, WITHOUT ROWID;
79
+ `;
80
+ const taskProjectionFeedSchema = `
81
+ CREATE TABLE IF NOT EXISTS evaluation_task_projection_feed_heads (
82
+ subject_key TEXT PRIMARY KEY REFERENCES evaluation_task_projections(subject_key) ON DELETE RESTRICT,
83
+ scope_key TEXT NOT NULL,
84
+ watermark INTEGER NOT NULL CHECK (watermark >= 1)
85
+ ) STRICT, WITHOUT ROWID;
86
+ CREATE UNIQUE INDEX IF NOT EXISTS evaluation_task_projection_feed_scope_watermark
87
+ ON evaluation_task_projection_feed_heads(scope_key, watermark);
88
+ `;
89
+ const taskProjectionViewSchema = `
90
+ CREATE VIEW evaluation_task_projection_view AS
91
+ SELECT
92
+ projection.subject_key AS task_subject_key,
93
+ projection.subject_kind AS task_subject_kind,
94
+ projection.subject_ref AS task_subject_ref,
95
+ projection.objective_conflicted AS task_objective_conflicted,
96
+ projection.primary_outcome_id AS task_primary_outcome_id,
97
+ projection.execution_outcome_id AS task_execution_outcome_id,
98
+ projection.objective_outcome_id AS task_objective_outcome_id,
99
+ projection.delivery_outcome_id AS task_delivery_outcome_id,
100
+ projection.learning_version AS task_learning_version,
101
+ projection.learning_digest AS task_learning_digest,
102
+ projection.learning_disposition AS task_learning_disposition,
103
+ primary_outcome.id,
104
+ primary_outcome.idempotency_key,
105
+ primary_outcome.payload_hash,
106
+ primary_outcome.scope_key,
107
+ primary_outcome.workspace,
108
+ primary_outcome.preset,
109
+ primary_outcome.situation,
110
+ COALESCE(execution_outcome.execution_status, 'unknown') AS execution_status,
111
+ CASE
112
+ WHEN projection.objective_conflicted = 1 THEN 'unknown'
113
+ ELSE COALESCE(objective_outcome.objective_status, 'unknown')
114
+ END AS objective_status,
115
+ COALESCE(delivery_outcome.delivery_status, 'unknown') AS delivery_status,
116
+ primary_outcome.source_kind,
117
+ primary_outcome.source_id,
118
+ primary_outcome.trust,
119
+ primary_outcome.evidence_json,
120
+ COALESCE(execution_outcome.metrics_json, '{}') AS metrics_json,
121
+ execution_outcome.cost_usd_micros,
122
+ execution_outcome.latency_ms,
123
+ execution_outcome.input_tokens,
124
+ execution_outcome.output_tokens,
125
+ execution_outcome.tool_calls,
126
+ COALESCE(execution_outcome.occurred_at, primary_outcome.occurred_at) AS occurred_at,
127
+ projection.updated_at AS recorded_at,
128
+ primary_outcome.evaluator_id,
129
+ primary_outcome.evaluator_version
130
+ FROM evaluation_task_projections projection
131
+ JOIN evaluation_outcomes primary_outcome ON primary_outcome.id = projection.primary_outcome_id
132
+ LEFT JOIN evaluation_outcomes execution_outcome ON execution_outcome.id = projection.execution_outcome_id
133
+ LEFT JOIN evaluation_outcomes objective_outcome ON objective_outcome.id = projection.objective_outcome_id
134
+ LEFT JOIN evaluation_outcomes delivery_outcome ON delivery_outcome.id = projection.delivery_outcome_id;
135
+ `;
136
+ /**
137
+ * Schema emitted by the v3 -> v4 migration. Keep this definition separate
138
+ * from the current view: a database that is genuinely at v4 does not have the
139
+ * versioned learning columns yet. Reusing the current schema here caused the
140
+ * same migration transaction to create those columns and then try to add them
141
+ * again in the v4 -> v5 step.
142
+ */
143
+ const legacyTaskProjectionViewSchema = `
144
+ CREATE VIEW evaluation_task_projection_view AS
145
+ SELECT
146
+ projection.subject_key AS task_subject_key,
147
+ projection.subject_kind AS task_subject_kind,
148
+ projection.subject_ref AS task_subject_ref,
149
+ projection.objective_conflicted AS task_objective_conflicted,
150
+ projection.primary_outcome_id AS task_primary_outcome_id,
151
+ projection.execution_outcome_id AS task_execution_outcome_id,
152
+ projection.objective_outcome_id AS task_objective_outcome_id,
153
+ projection.delivery_outcome_id AS task_delivery_outcome_id,
154
+ primary_outcome.id,
155
+ primary_outcome.idempotency_key,
156
+ primary_outcome.payload_hash,
157
+ primary_outcome.scope_key,
158
+ primary_outcome.workspace,
159
+ primary_outcome.preset,
160
+ primary_outcome.situation,
161
+ COALESCE(execution_outcome.execution_status, 'unknown') AS execution_status,
162
+ CASE
163
+ WHEN projection.objective_conflicted = 1 THEN 'unknown'
164
+ ELSE COALESCE(objective_outcome.objective_status, 'unknown')
165
+ END AS objective_status,
166
+ COALESCE(delivery_outcome.delivery_status, 'unknown') AS delivery_status,
167
+ primary_outcome.source_kind,
168
+ primary_outcome.source_id,
169
+ primary_outcome.trust,
170
+ primary_outcome.evidence_json,
171
+ COALESCE(execution_outcome.metrics_json, '{}') AS metrics_json,
172
+ execution_outcome.cost_usd_micros,
173
+ execution_outcome.latency_ms,
174
+ execution_outcome.input_tokens,
175
+ execution_outcome.output_tokens,
176
+ execution_outcome.tool_calls,
177
+ COALESCE(execution_outcome.occurred_at, primary_outcome.occurred_at) AS occurred_at,
178
+ projection.updated_at AS recorded_at,
179
+ primary_outcome.evaluator_id,
180
+ primary_outcome.evaluator_version
181
+ FROM evaluation_task_projections projection
182
+ JOIN evaluation_outcomes primary_outcome ON primary_outcome.id = projection.primary_outcome_id
183
+ LEFT JOIN evaluation_outcomes execution_outcome ON execution_outcome.id = projection.execution_outcome_id
184
+ LEFT JOIN evaluation_outcomes objective_outcome ON objective_outcome.id = projection.objective_outcome_id
185
+ LEFT JOIN evaluation_outcomes delivery_outcome ON delivery_outcome.id = projection.delivery_outcome_id;
186
+ `;
187
+ const taskProjectionSchema = `
188
+ CREATE INDEX evaluation_outcomes_task_subject
189
+ ON evaluation_outcomes(task_subject_key, recorded_at, id);
190
+ CREATE TABLE evaluation_task_projections (
191
+ subject_key TEXT PRIMARY KEY,
192
+ scope_key TEXT NOT NULL,
193
+ subject_kind TEXT NOT NULL CHECK (subject_kind IN ('automation-run', 'foreground-turn', 'goal-step', 'goal-outcome', 'work-item', 'outcome')),
194
+ subject_ref TEXT NOT NULL,
195
+ primary_outcome_id TEXT,
196
+ execution_outcome_id TEXT,
197
+ objective_outcome_id TEXT,
198
+ delivery_outcome_id TEXT,
199
+ objective_conflicted INTEGER NOT NULL DEFAULT 0 CHECK (objective_conflicted IN (0, 1)),
200
+ learning_version INTEGER NOT NULL DEFAULT 0 CHECK (learning_version >= 0),
201
+ learning_digest TEXT CHECK (learning_digest IS NULL OR length(learning_digest) = 64),
202
+ learning_disposition TEXT CHECK (learning_disposition IN ('upsert', 'retract')),
203
+ updated_at INTEGER NOT NULL,
204
+ FOREIGN KEY (primary_outcome_id) REFERENCES evaluation_outcomes(id) ON DELETE RESTRICT,
205
+ FOREIGN KEY (execution_outcome_id) REFERENCES evaluation_outcomes(id) ON DELETE RESTRICT,
206
+ FOREIGN KEY (objective_outcome_id) REFERENCES evaluation_outcomes(id) ON DELETE RESTRICT,
207
+ FOREIGN KEY (delivery_outcome_id) REFERENCES evaluation_outcomes(id) ON DELETE RESTRICT
208
+ ) STRICT;
209
+ CREATE INDEX evaluation_task_projections_scope_time
210
+ ON evaluation_task_projections(scope_key, updated_at DESC, subject_key);
211
+
212
+ ${taskProjectionViewSchema}
213
+ `;
214
+ const legacyTaskProjectionSchema = `
215
+ CREATE INDEX evaluation_outcomes_task_subject
216
+ ON evaluation_outcomes(task_subject_key, recorded_at, id);
217
+ CREATE TABLE evaluation_task_projections (
218
+ subject_key TEXT PRIMARY KEY,
219
+ scope_key TEXT NOT NULL,
220
+ subject_kind TEXT NOT NULL CHECK (subject_kind IN ('automation-run', 'outcome')),
221
+ subject_ref TEXT NOT NULL,
222
+ primary_outcome_id TEXT,
223
+ execution_outcome_id TEXT,
224
+ objective_outcome_id TEXT,
225
+ delivery_outcome_id TEXT,
226
+ objective_conflicted INTEGER NOT NULL DEFAULT 0 CHECK (objective_conflicted IN (0, 1)),
227
+ updated_at INTEGER NOT NULL,
228
+ FOREIGN KEY (primary_outcome_id) REFERENCES evaluation_outcomes(id) ON DELETE RESTRICT,
229
+ FOREIGN KEY (execution_outcome_id) REFERENCES evaluation_outcomes(id) ON DELETE RESTRICT,
230
+ FOREIGN KEY (objective_outcome_id) REFERENCES evaluation_outcomes(id) ON DELETE RESTRICT,
231
+ FOREIGN KEY (delivery_outcome_id) REFERENCES evaluation_outcomes(id) ON DELETE RESTRICT
232
+ ) STRICT;
233
+ CREATE INDEX evaluation_task_projections_scope_time
234
+ ON evaluation_task_projections(scope_key, updated_at DESC, subject_key);
235
+
236
+ ${legacyTaskProjectionViewSchema}
237
+ `;
238
+ function legacyTaskSubject(scopeKey, id, evidenceJson) {
239
+ try {
240
+ const parsed = JSON.parse(evidenceJson);
241
+ if (Array.isArray(parsed)) {
242
+ const refs = new Set(parsed.flatMap(entry => {
243
+ if (typeof entry !== 'object' || entry === null || Array.isArray(entry))
244
+ return [];
245
+ const candidate = entry;
246
+ return candidate.kind === 'automation-run' && typeof candidate.ref === 'string'
247
+ && candidate.ref.trim() !== ''
248
+ ? [candidate.ref]
249
+ : [];
250
+ }));
251
+ if (refs.size === 1) {
252
+ const ref = [...refs][0];
253
+ return { key: JSON.stringify([scopeKey, 'automation-run', ref]), kind: 'automation-run', ref };
254
+ }
255
+ }
256
+ }
257
+ catch {
258
+ // A malformed legacy reference is deliberately not guessed into a shared task.
259
+ }
260
+ return { key: JSON.stringify([scopeKey, 'outcome', id]), kind: 'outcome', ref: id };
261
+ }
262
+ /**
263
+ * WP22 per-notification outcome canon. Revisions are immutable; the head names
264
+ * the current revision and carries a per-scope notification watermark used as a
265
+ * restart-safe read cursor. Separate from task-learning watermarks so this
266
+ * read-only feed never fences or advances Evolution evidence.
267
+ */
268
+ const notificationOutcomeSchema = `
269
+ CREATE TABLE evaluation_notification_outcome_revisions (
270
+ notification_id TEXT NOT NULL CHECK (length(notification_id) BETWEEN 1 AND 256),
271
+ version INTEGER NOT NULL CHECK (version >= 1),
272
+ scope_key TEXT NOT NULL,
273
+ outcome TEXT NOT NULL CHECK (outcome IN ('pending','delivered','reacted','accepted','rejected','expired-unhandled','failed')),
274
+ record_json TEXT NOT NULL CHECK (json_valid(record_json)),
275
+ digest TEXT NOT NULL CHECK (length(digest) = 64),
276
+ watermark INTEGER NOT NULL CHECK (watermark >= 1),
277
+ recorded_at INTEGER NOT NULL CHECK (recorded_at >= 0),
278
+ PRIMARY KEY (notification_id, version),
279
+ UNIQUE (scope_key, watermark)
280
+ ) STRICT;
281
+ CREATE TRIGGER evaluation_notification_outcome_revisions_immutable
282
+ BEFORE UPDATE ON evaluation_notification_outcome_revisions
283
+ BEGIN SELECT RAISE(ABORT, 'notification outcome revisions are immutable'); END;
284
+ CREATE TRIGGER evaluation_notification_outcome_revisions_no_delete
285
+ BEFORE DELETE ON evaluation_notification_outcome_revisions
286
+ BEGIN SELECT RAISE(ABORT, 'notification outcome revisions are durable'); END;
287
+ CREATE TABLE evaluation_notification_outcome_heads (
288
+ notification_id TEXT PRIMARY KEY,
289
+ scope_key TEXT NOT NULL,
290
+ version INTEGER NOT NULL CHECK (version >= 1),
291
+ digest TEXT NOT NULL CHECK (length(digest) = 64),
292
+ outcome TEXT NOT NULL,
293
+ occurred_at INTEGER NOT NULL CHECK (occurred_at >= 0),
294
+ watermark INTEGER NOT NULL CHECK (watermark >= 1),
295
+ last_checked_at INTEGER NOT NULL CHECK (last_checked_at >= 0),
296
+ UNIQUE (scope_key, watermark),
297
+ FOREIGN KEY (notification_id, version) REFERENCES evaluation_notification_outcome_revisions(notification_id, version)
298
+ ) STRICT;
299
+ -- Re-check scans range over occurred_at so heads older than the observation
300
+ -- horizon are never visited again; the scan is bounded by in-horizon heads.
301
+ CREATE INDEX evaluation_notification_outcome_heads_due
302
+ ON evaluation_notification_outcome_heads(occurred_at, last_checked_at);
303
+ CREATE INDEX evaluation_notification_outcome_heads_scope_time
304
+ ON evaluation_notification_outcome_heads(scope_key, occurred_at);
305
+ CREATE TRIGGER evaluation_notification_outcome_heads_insert_matches_revision
306
+ BEFORE INSERT ON evaluation_notification_outcome_heads
307
+ WHEN NOT EXISTS (SELECT 1 FROM evaluation_notification_outcome_revisions r
308
+ WHERE r.notification_id = NEW.notification_id AND r.version = NEW.version AND r.scope_key = NEW.scope_key
309
+ AND r.digest = NEW.digest AND r.outcome = NEW.outcome AND r.watermark = NEW.watermark
310
+ AND json_extract(r.record_json, '$.notifiedAt') = NEW.occurred_at)
311
+ BEGIN SELECT RAISE(ABORT, 'notification outcome head must match its revision'); END;
312
+ CREATE TRIGGER evaluation_notification_outcome_heads_update_matches_revision
313
+ BEFORE UPDATE ON evaluation_notification_outcome_heads
314
+ WHEN NOT EXISTS (SELECT 1 FROM evaluation_notification_outcome_revisions r
315
+ WHERE r.notification_id = NEW.notification_id AND r.version = NEW.version AND r.scope_key = NEW.scope_key
316
+ AND r.digest = NEW.digest AND r.outcome = NEW.outcome AND r.watermark = NEW.watermark
317
+ AND json_extract(r.record_json, '$.notifiedAt') = NEW.occurred_at)
318
+ BEGIN SELECT RAISE(ABORT, 'notification outcome head must match its revision'); END;
319
+ CREATE TRIGGER evaluation_notification_outcome_heads_identity_immutable
320
+ BEFORE UPDATE OF notification_id, scope_key, occurred_at ON evaluation_notification_outcome_heads
321
+ WHEN NEW.notification_id IS NOT OLD.notification_id OR NEW.scope_key IS NOT OLD.scope_key
322
+ OR NEW.occurred_at IS NOT OLD.occurred_at
323
+ BEGIN SELECT RAISE(ABORT, 'notification outcome head identity is immutable'); END;
324
+ CREATE TRIGGER evaluation_notification_outcome_heads_monotonic
325
+ BEFORE UPDATE OF version, watermark ON evaluation_notification_outcome_heads
326
+ WHEN NEW.version <= OLD.version OR NEW.watermark <= OLD.watermark
327
+ BEGIN SELECT RAISE(ABORT, 'notification outcome head must advance'); END;
328
+ CREATE TRIGGER evaluation_notification_outcome_heads_no_delete
329
+ BEFORE DELETE ON evaluation_notification_outcome_heads
330
+ BEGIN SELECT RAISE(ABORT, 'notification outcome heads are durable'); END;
331
+ CREATE TABLE evaluation_notification_watermarks (
332
+ scope_key TEXT PRIMARY KEY,
333
+ watermark INTEGER NOT NULL CHECK (watermark >= 1)
334
+ ) STRICT;
335
+ CREATE TRIGGER evaluation_notification_watermarks_monotonic
336
+ BEFORE UPDATE ON evaluation_notification_watermarks
337
+ WHEN NEW.scope_key IS NOT OLD.scope_key OR NEW.watermark <= OLD.watermark
338
+ BEGIN SELECT RAISE(ABORT, 'notification watermark must advance'); END;
339
+ CREATE TRIGGER evaluation_notification_watermarks_no_delete
340
+ BEFORE DELETE ON evaluation_notification_watermarks
341
+ BEGIN SELECT RAISE(ABORT, 'notification watermarks are durable'); END;
342
+ CREATE TABLE evaluation_notification_sync_cursor (
343
+ id INTEGER PRIMARY KEY CHECK (id = 1),
344
+ after_sequence INTEGER NOT NULL CHECK (after_sequence >= 0),
345
+ updated_at INTEGER NOT NULL CHECK (updated_at >= 0)
346
+ ) STRICT;
347
+ CREATE TRIGGER evaluation_notification_sync_cursor_monotonic
348
+ BEFORE UPDATE ON evaluation_notification_sync_cursor
349
+ WHEN NEW.after_sequence < OLD.after_sequence
350
+ BEGIN SELECT RAISE(ABORT, 'notification sync cursor must not regress'); END;
351
+ CREATE TRIGGER evaluation_notification_sync_cursor_no_delete
352
+ BEFORE DELETE ON evaluation_notification_sync_cursor
353
+ BEGIN SELECT RAISE(ABORT, 'notification sync cursor is durable'); END;
354
+ `;
355
+ /**
356
+ * WP22 slice 2 attention-tuning canon. Each version is immutable, names its
357
+ * exact parent (0 = built-in default) and carries the basis outcome summary
358
+ * plus scope notification watermark it was derived from. The head names the
359
+ * active version and a durable observation window; events are append-only.
360
+ */
361
+ const attentionTuningSchema = `
362
+ CREATE TABLE evaluation_attention_tuning_versions (
363
+ scope_key TEXT NOT NULL,
364
+ lane TEXT NOT NULL CHECK (length(lane) BETWEEN 1 AND 64),
365
+ source_id TEXT NOT NULL CHECK (length(source_id) BETWEEN 1 AND 256),
366
+ version INTEGER NOT NULL CHECK (version >= 1),
367
+ parent_version INTEGER NOT NULL CHECK (parent_version >= 0 AND parent_version < version),
368
+ parameters_json TEXT NOT NULL CHECK (json_valid(parameters_json)),
369
+ basis_json TEXT NOT NULL CHECK (json_valid(basis_json)),
370
+ change_json TEXT NOT NULL CHECK (json_valid(change_json)),
371
+ origin TEXT NOT NULL CHECK (origin IN ('auto','request')),
372
+ digest TEXT NOT NULL CHECK (length(digest) = 64),
373
+ idempotency_key TEXT NOT NULL UNIQUE,
374
+ created_at INTEGER NOT NULL CHECK (created_at >= 0),
375
+ PRIMARY KEY (scope_key, lane, source_id, version)
376
+ ) STRICT;
377
+ CREATE TRIGGER evaluation_attention_tuning_versions_immutable
378
+ BEFORE UPDATE ON evaluation_attention_tuning_versions
379
+ BEGIN SELECT RAISE(ABORT, 'attention tuning versions are immutable'); END;
380
+ CREATE TRIGGER evaluation_attention_tuning_versions_no_delete
381
+ BEFORE DELETE ON evaluation_attention_tuning_versions
382
+ BEGIN SELECT RAISE(ABORT, 'attention tuning versions are durable'); END;
383
+ CREATE TABLE evaluation_attention_tuning_heads (
384
+ scope_key TEXT NOT NULL,
385
+ lane TEXT NOT NULL,
386
+ source_id TEXT NOT NULL,
387
+ workspace TEXT NOT NULL,
388
+ preset TEXT NOT NULL,
389
+ active_version INTEGER NOT NULL CHECK (active_version >= 0),
390
+ latest_version INTEGER NOT NULL CHECK (latest_version >= active_version),
391
+ state TEXT NOT NULL CHECK (state IN ('idle','observing')),
392
+ observing_version INTEGER,
393
+ observe_from INTEGER,
394
+ observe_until INTEGER,
395
+ changed_at INTEGER NOT NULL CHECK (changed_at >= 0),
396
+ CHECK ((state = 'idle' AND observing_version IS NULL AND observe_from IS NULL AND observe_until IS NULL)
397
+ OR (state = 'observing' AND observing_version = active_version AND observe_from IS NOT NULL AND observe_until > observe_from)),
398
+ PRIMARY KEY (scope_key, lane, source_id)
399
+ ) STRICT;
400
+ CREATE TRIGGER evaluation_attention_tuning_heads_no_delete
401
+ BEFORE DELETE ON evaluation_attention_tuning_heads
402
+ BEGIN SELECT RAISE(ABORT, 'attention tuning heads are durable'); END;
403
+ CREATE TABLE evaluation_attention_tuning_events (
404
+ sequence INTEGER PRIMARY KEY AUTOINCREMENT,
405
+ scope_key TEXT NOT NULL,
406
+ lane TEXT NOT NULL,
407
+ source_id TEXT NOT NULL,
408
+ kind TEXT NOT NULL CHECK (kind IN ('adopted','rolled-back','settled','request-rejected')),
409
+ from_version INTEGER NOT NULL CHECK (from_version >= 0),
410
+ to_version INTEGER NOT NULL CHECK (to_version >= 0),
411
+ reason TEXT NOT NULL CHECK (length(reason) BETWEEN 1 AND 64),
412
+ detail_json TEXT NOT NULL CHECK (json_valid(detail_json)),
413
+ idempotency_key TEXT UNIQUE,
414
+ occurred_at INTEGER NOT NULL CHECK (occurred_at >= 0)
415
+ ) STRICT;
416
+ CREATE INDEX evaluation_attention_tuning_events_cohort
417
+ ON evaluation_attention_tuning_events(scope_key, lane, source_id, sequence);
418
+ CREATE TRIGGER evaluation_attention_tuning_events_immutable
419
+ BEFORE UPDATE ON evaluation_attention_tuning_events
420
+ BEGIN SELECT RAISE(ABORT, 'attention tuning events are immutable'); END;
421
+ CREATE TRIGGER evaluation_attention_tuning_events_no_delete
422
+ BEFORE DELETE ON evaluation_attention_tuning_events
423
+ BEGIN SELECT RAISE(ABORT, 'attention tuning events are durable'); END;
424
+ `;
425
+ /**
426
+ * WP22 slice 3 loosening canon, appended after schema 15. An owner grant is a
427
+ * one-time pre-authorization; a proposal seals only the holdout membership
428
+ * digest (never its outcomes); each proposal gets exactly one immutable
429
+ * decision; an out-of-grant pass records a structured owner question (not
430
+ * delivered in this slice). Grant usage is the count of adopted decisions
431
+ * naming the grant, so a later rollback never refunds quota.
432
+ */
433
+ const attentionLooseningSchema = `
434
+ CREATE TABLE evaluation_attention_loosening_grants (
435
+ scope_key TEXT NOT NULL,
436
+ lane TEXT NOT NULL CHECK (length(lane) BETWEEN 1 AND 64),
437
+ source_id TEXT NOT NULL CHECK (length(source_id) BETWEEN 1 AND 256),
438
+ grant_id TEXT NOT NULL CHECK (length(grant_id) BETWEEN 1 AND 128),
439
+ grant_json TEXT NOT NULL CHECK (json_valid(grant_json)),
440
+ digest TEXT NOT NULL CHECK (length(digest) = 64),
441
+ created_at INTEGER NOT NULL CHECK (created_at >= 0),
442
+ PRIMARY KEY (scope_key, lane, source_id, grant_id)
443
+ ) STRICT;
444
+ CREATE TRIGGER evaluation_attention_loosening_grants_immutable
445
+ BEFORE UPDATE ON evaluation_attention_loosening_grants
446
+ BEGIN SELECT RAISE(ABORT, 'attention loosening grants are immutable'); END;
447
+ CREATE TRIGGER evaluation_attention_loosening_grants_no_delete
448
+ BEFORE DELETE ON evaluation_attention_loosening_grants
449
+ BEGIN SELECT RAISE(ABORT, 'attention loosening grants are durable'); END;
450
+ CREATE TABLE evaluation_attention_loosening_proposals (
451
+ proposal_id TEXT PRIMARY KEY CHECK (length(proposal_id) = 64),
452
+ scope_key TEXT NOT NULL,
453
+ lane TEXT NOT NULL,
454
+ source_id TEXT NOT NULL,
455
+ parent_version INTEGER NOT NULL CHECK (parent_version >= 0),
456
+ proposal_json TEXT NOT NULL CHECK (json_valid(proposal_json)),
457
+ holdout_digest TEXT NOT NULL CHECK (length(holdout_digest) = 64),
458
+ created_at INTEGER NOT NULL CHECK (created_at >= 0)
459
+ ) STRICT;
460
+ CREATE INDEX evaluation_attention_loosening_proposals_cohort
461
+ ON evaluation_attention_loosening_proposals(scope_key, lane, source_id, created_at);
462
+ CREATE TRIGGER evaluation_attention_loosening_proposals_immutable
463
+ BEFORE UPDATE ON evaluation_attention_loosening_proposals
464
+ BEGIN SELECT RAISE(ABORT, 'attention loosening proposals are immutable'); END;
465
+ CREATE TRIGGER evaluation_attention_loosening_proposals_no_delete
466
+ BEFORE DELETE ON evaluation_attention_loosening_proposals
467
+ BEGIN SELECT RAISE(ABORT, 'attention loosening proposals are durable'); END;
468
+ CREATE TABLE evaluation_attention_loosening_decisions (
469
+ proposal_id TEXT PRIMARY KEY,
470
+ scope_key TEXT NOT NULL,
471
+ lane TEXT NOT NULL,
472
+ source_id TEXT NOT NULL,
473
+ decision TEXT NOT NULL CHECK (decision IN ('adopted','rejected','owner-question')),
474
+ reason TEXT NOT NULL CHECK (length(reason) BETWEEN 1 AND 64),
475
+ grant_id TEXT,
476
+ version INTEGER,
477
+ replay_json TEXT NOT NULL CHECK (json_valid(replay_json)),
478
+ decided_at INTEGER NOT NULL CHECK (decided_at >= 0),
479
+ CHECK ((decision = 'adopted' AND grant_id IS NOT NULL AND version >= 1) OR (decision <> 'adopted' AND version IS NULL)),
480
+ FOREIGN KEY (proposal_id) REFERENCES evaluation_attention_loosening_proposals(proposal_id) ON DELETE RESTRICT
481
+ ) STRICT;
482
+ CREATE INDEX evaluation_attention_loosening_decisions_grant
483
+ ON evaluation_attention_loosening_decisions(scope_key, lane, source_id, grant_id, decision);
484
+ CREATE TRIGGER evaluation_attention_loosening_decisions_immutable
485
+ BEFORE UPDATE ON evaluation_attention_loosening_decisions
486
+ BEGIN SELECT RAISE(ABORT, 'attention loosening decisions are immutable'); END;
487
+ CREATE TRIGGER evaluation_attention_loosening_decisions_no_delete
488
+ BEFORE DELETE ON evaluation_attention_loosening_decisions
489
+ BEGIN SELECT RAISE(ABORT, 'attention loosening decisions are durable'); END;
490
+ CREATE TABLE evaluation_attention_owner_questions (
491
+ question_id TEXT PRIMARY KEY CHECK (length(question_id) = 64),
492
+ proposal_id TEXT NOT NULL UNIQUE,
493
+ scope_key TEXT NOT NULL,
494
+ lane TEXT NOT NULL,
495
+ source_id TEXT NOT NULL,
496
+ question_json TEXT NOT NULL CHECK (json_valid(question_json)),
497
+ created_at INTEGER NOT NULL CHECK (created_at >= 0),
498
+ FOREIGN KEY (proposal_id) REFERENCES evaluation_attention_loosening_proposals(proposal_id) ON DELETE RESTRICT
499
+ ) STRICT;
500
+ CREATE INDEX evaluation_attention_owner_questions_cohort
501
+ ON evaluation_attention_owner_questions(scope_key, lane, source_id, created_at);
502
+ CREATE TRIGGER evaluation_attention_owner_questions_immutable
503
+ BEFORE UPDATE ON evaluation_attention_owner_questions
504
+ BEGIN SELECT RAISE(ABORT, 'attention owner questions are immutable'); END;
505
+ CREATE TRIGGER evaluation_attention_owner_questions_no_delete
506
+ BEFORE DELETE ON evaluation_attention_owner_questions
507
+ BEGIN SELECT RAISE(ABORT, 'attention owner questions are durable'); END;
508
+ `;
509
+ const attentionOwnerQuestionDeliverySchema = `
510
+ CREATE TABLE evaluation_attention_owner_question_deliveries (
511
+ question_id TEXT PRIMARY KEY CHECK (length(question_id) = 64),
512
+ scope_key TEXT NOT NULL,
513
+ lane TEXT NOT NULL,
514
+ source_id TEXT NOT NULL,
515
+ status TEXT NOT NULL CHECK (status IN ('queued','closed','expired')),
516
+ outbox_id TEXT CHECK (outbox_id IS NULL OR length(outbox_id) BETWEEN 1 AND 256),
517
+ idempotency_key TEXT NOT NULL CHECK (length(idempotency_key) BETWEEN 1 AND 256),
518
+ recorded_at INTEGER NOT NULL CHECK (recorded_at >= 0),
519
+ CHECK ((status = 'queued') = (outbox_id IS NOT NULL)),
520
+ FOREIGN KEY (question_id) REFERENCES evaluation_attention_owner_questions(question_id) ON DELETE RESTRICT
521
+ ) STRICT;
522
+ CREATE TRIGGER evaluation_attention_owner_question_deliveries_immutable
523
+ BEFORE UPDATE ON evaluation_attention_owner_question_deliveries
524
+ BEGIN SELECT RAISE(ABORT, 'attention owner question deliveries are immutable'); END;
525
+ CREATE TRIGGER evaluation_attention_owner_question_deliveries_no_delete
526
+ BEFORE DELETE ON evaluation_attention_owner_question_deliveries
527
+ BEGIN SELECT RAISE(ABORT, 'attention owner question deliveries are durable'); END;
528
+ CREATE TABLE evaluation_attention_owner_question_replies (
529
+ question_id TEXT PRIMARY KEY CHECK (length(question_id) = 64),
530
+ scope_key TEXT NOT NULL,
531
+ lane TEXT NOT NULL,
532
+ source_id TEXT NOT NULL,
533
+ choice TEXT NOT NULL CHECK (choice IN ('authorize-once','decline')),
534
+ replied_at INTEGER NOT NULL CHECK (replied_at >= 0),
535
+ FOREIGN KEY (question_id) REFERENCES evaluation_attention_owner_questions(question_id) ON DELETE RESTRICT
536
+ ) STRICT;
537
+ CREATE TRIGGER evaluation_attention_owner_question_replies_immutable
538
+ BEFORE UPDATE ON evaluation_attention_owner_question_replies
539
+ BEGIN SELECT RAISE(ABORT, 'attention owner question replies are immutable'); END;
540
+ CREATE TRIGGER evaluation_attention_owner_question_replies_no_delete
541
+ BEFORE DELETE ON evaluation_attention_owner_question_replies
542
+ BEGIN SELECT RAISE(ABORT, 'attention owner question replies are durable'); END;
543
+ `;
544
+ /**
545
+ * WP22 E1: durable, append-only intake/attention agreement snapshots.
546
+ *
547
+ * One row is one bucket/scope/digest observation. Replaying a tick inside the
548
+ * same bucket must not append a second row, so (scope, window, digest) is
549
+ * unique; a late outcome revision that changes counts forms a new digest and
550
+ * is appended for the same window. Rows are immutable and durable.
551
+ */
552
+ const intakeAttentionAgreementSchema = `
553
+ CREATE TABLE evaluation_intake_attention_agreement (
554
+ sequence INTEGER PRIMARY KEY AUTOINCREMENT,
555
+ scope_key TEXT NOT NULL,
556
+ workspace TEXT NOT NULL,
557
+ preset TEXT NOT NULL,
558
+ from_notified_at INTEGER NOT NULL CHECK (from_notified_at >= 0),
559
+ to_notified_at INTEGER NOT NULL CHECK (to_notified_at > from_notified_at),
560
+ computed_at INTEGER NOT NULL CHECK (computed_at >= 0),
561
+ window_ms INTEGER NOT NULL CHECK (window_ms >= 60000),
562
+ scan_limit INTEGER NOT NULL CHECK (scan_limit >= 1),
563
+ truncated INTEGER NOT NULL CHECK (truncated IN (0, 1)),
564
+ provenance_available INTEGER NOT NULL CHECK (provenance_available IN (0, 1)),
565
+ not_intake INTEGER NOT NULL CHECK (not_intake >= 0),
566
+ unresolved INTEGER NOT NULL CHECK (unresolved >= 0),
567
+ foreign_count INTEGER NOT NULL CHECK (foreign_count >= 0),
568
+ intake_json TEXT NOT NULL CHECK (json_valid(intake_json)),
569
+ by_level_json TEXT NOT NULL CHECK (json_valid(by_level_json)),
570
+ snapshot_json TEXT NOT NULL CHECK (json_valid(snapshot_json)),
571
+ digest TEXT NOT NULL CHECK (length(digest) = 64),
572
+ UNIQUE (scope_key, from_notified_at, to_notified_at, digest)
573
+ ) STRICT;
574
+ CREATE INDEX evaluation_intake_attention_agreement_scope_time
575
+ ON evaluation_intake_attention_agreement(scope_key, to_notified_at DESC, sequence DESC);
576
+ CREATE TRIGGER evaluation_intake_attention_agreement_immutable
577
+ BEFORE UPDATE ON evaluation_intake_attention_agreement
578
+ BEGIN SELECT RAISE(ABORT, 'intake attention agreement snapshots are immutable'); END;
579
+ CREATE TRIGGER evaluation_intake_attention_agreement_no_delete
580
+ BEFORE DELETE ON evaluation_intake_attention_agreement
581
+ BEGIN SELECT RAISE(ABORT, 'intake attention agreement snapshots are durable'); END;
582
+ `;
583
+ const attentionOwnerQuestionDeliveryTables = Object.freeze([
584
+ 'evaluation_attention_owner_question_deliveries',
585
+ 'evaluation_attention_owner_question_replies',
586
+ ]);
587
+ const intakeAttentionAgreementTables = Object.freeze(['evaluation_intake_attention_agreement']);
588
+ /**
589
+ * WP22 (schema 19): durable WP20 `would-accept` intake evaluation agreement
590
+ * heads, append-only revision history, and strictly monotonic incremental
591
+ * sync cursor for `assistantWorkItems.listIntakeEvaluationFeed`.
592
+ */
593
+ const intakeEvaluationAgreementSchema = `
594
+ CREATE TABLE evaluation_intake_evaluation_sync_cursor (
595
+ id INTEGER PRIMARY KEY CHECK (id = 1),
596
+ after_seq INTEGER NOT NULL CHECK (after_seq >= 0),
597
+ after_recorded_at INTEGER NOT NULL CHECK (after_recorded_at >= 0),
598
+ after_id TEXT NOT NULL CHECK (length(after_id) <= 256),
599
+ updated_at INTEGER NOT NULL CHECK (updated_at >= 0)
600
+ ) STRICT;
601
+ CREATE TRIGGER evaluation_intake_evaluation_sync_cursor_monotonic
602
+ BEFORE UPDATE ON evaluation_intake_evaluation_sync_cursor
603
+ WHEN NEW.id IS NOT OLD.id
604
+ OR NEW.after_recorded_at < OLD.after_recorded_at
605
+ OR (NEW.after_recorded_at = OLD.after_recorded_at AND NEW.after_id < OLD.after_id)
606
+ OR (NEW.after_recorded_at = OLD.after_recorded_at AND NEW.after_id = OLD.after_id AND NEW.after_seq <= OLD.after_seq)
607
+ BEGIN SELECT RAISE(ABORT, 'intake evaluation sync cursor must advance'); END;
608
+ CREATE TRIGGER evaluation_intake_evaluation_sync_cursor_no_delete
609
+ BEFORE DELETE ON evaluation_intake_evaluation_sync_cursor
610
+ BEGIN SELECT RAISE(ABORT, 'intake evaluation sync cursor is durable'); END;
611
+ CREATE TABLE evaluation_intake_evaluation_heads (
612
+ eval_id TEXT PRIMARY KEY CHECK (length(eval_id) = 64),
613
+ source TEXT NOT NULL CHECK (length(source) BETWEEN 1 AND 64),
614
+ source_event_id TEXT NOT NULL CHECK (length(source_event_id) BETWEEN 1 AND 256),
615
+ rule_id TEXT NOT NULL CHECK (length(rule_id) BETWEEN 1 AND 256),
616
+ policy_version TEXT NOT NULL CHECK (length(policy_version) BETWEEN 1 AND 256),
617
+ scope_key TEXT,
618
+ workspace TEXT,
619
+ preset TEXT,
620
+ item_id TEXT,
621
+ would_accept INTEGER NOT NULL CHECK (would_accept IN (0, 1)),
622
+ evaluation_level TEXT NOT NULL CHECK (evaluation_level IN ('ignore', 'digest', 'notify', 'accept')),
623
+ mode TEXT NOT NULL CHECK (mode IN ('observe', 'auto')),
624
+ outcome_kind TEXT NOT NULL CHECK (outcome_kind IN ('agreed', 'disagreed', 'pending')),
625
+ agreement_status TEXT NOT NULL CHECK (agreement_status IN (
626
+ 'true-positive', 'false-positive', 'false-negative', 'true-negative', 'pending'
627
+ )),
628
+ outcome_source TEXT NOT NULL CHECK (outcome_source IN (
629
+ 'none', 'work-item-outcome', 'work-item-verdict', 'notification-outcome', 'owner-feedback', 'owner-withdrawal'
630
+ )),
631
+ evaluated_at INTEGER NOT NULL CHECK (evaluated_at >= 0),
632
+ feed_recorded_at INTEGER NOT NULL CHECK (feed_recorded_at >= 0),
633
+ version INTEGER NOT NULL CHECK (version >= 1),
634
+ latest_digest TEXT NOT NULL CHECK (length(latest_digest) = 64),
635
+ updated_at INTEGER NOT NULL CHECK (updated_at >= 0),
636
+ UNIQUE (source, source_event_id, rule_id, policy_version)
637
+ ) STRICT;
638
+ CREATE INDEX evaluation_intake_evaluation_heads_scope_time
639
+ ON evaluation_intake_evaluation_heads(scope_key, evaluated_at, eval_id);
640
+ CREATE INDEX evaluation_intake_evaluation_heads_source_time
641
+ ON evaluation_intake_evaluation_heads(source, rule_id, evaluated_at, eval_id);
642
+ CREATE INDEX evaluation_intake_evaluation_heads_item_idx
643
+ ON evaluation_intake_evaluation_heads(item_id) WHERE item_id IS NOT NULL;
644
+ CREATE TRIGGER evaluation_intake_evaluation_heads_monotonic
645
+ BEFORE UPDATE ON evaluation_intake_evaluation_heads
646
+ WHEN NEW.eval_id IS NOT OLD.eval_id
647
+ OR NEW.source IS NOT OLD.source
648
+ OR NEW.source_event_id IS NOT OLD.source_event_id
649
+ OR NEW.rule_id IS NOT OLD.rule_id
650
+ OR NEW.policy_version IS NOT OLD.policy_version
651
+ OR NEW.would_accept IS NOT OLD.would_accept
652
+ OR NEW.evaluation_level IS NOT OLD.evaluation_level
653
+ OR NEW.evaluated_at IS NOT OLD.evaluated_at
654
+ OR NEW.version <= OLD.version
655
+ BEGIN SELECT RAISE(ABORT, 'intake evaluation head revision must advance'); END;
656
+ CREATE TRIGGER evaluation_intake_evaluation_heads_no_delete
657
+ BEFORE DELETE ON evaluation_intake_evaluation_heads
658
+ BEGIN SELECT RAISE(ABORT, 'intake evaluation heads are durable'); END;
659
+ CREATE TABLE evaluation_intake_evaluation_revisions (
660
+ eval_id TEXT NOT NULL REFERENCES evaluation_intake_evaluation_heads(eval_id) ON DELETE RESTRICT,
661
+ version INTEGER NOT NULL CHECK (version >= 1),
662
+ outcome_kind TEXT NOT NULL CHECK (outcome_kind IN ('agreed', 'disagreed', 'pending')),
663
+ agreement_status TEXT NOT NULL CHECK (agreement_status IN (
664
+ 'true-positive', 'false-positive', 'false-negative', 'true-negative', 'pending'
665
+ )),
666
+ outcome_source TEXT NOT NULL CHECK (outcome_source IN (
667
+ 'none', 'work-item-outcome', 'work-item-verdict', 'notification-outcome', 'owner-feedback', 'owner-withdrawal'
668
+ )),
669
+ record_digest TEXT NOT NULL CHECK (length(record_digest) = 64),
670
+ record_json TEXT NOT NULL CHECK (json_valid(record_json)),
671
+ recorded_at INTEGER NOT NULL CHECK (recorded_at >= 0),
672
+ PRIMARY KEY (eval_id, version)
673
+ ) STRICT;
674
+ CREATE TRIGGER evaluation_intake_evaluation_revisions_immutable
675
+ BEFORE UPDATE ON evaluation_intake_evaluation_revisions
676
+ BEGIN SELECT RAISE(ABORT, 'intake evaluation revisions are immutable'); END;
677
+ CREATE TRIGGER evaluation_intake_evaluation_revisions_no_delete
678
+ BEFORE DELETE ON evaluation_intake_evaluation_revisions
679
+ BEGIN SELECT RAISE(ABORT, 'intake evaluation revisions are durable'); END;
680
+ `;
681
+ const intakeEvaluationAgreementTables = Object.freeze([
682
+ 'evaluation_intake_evaluation_sync_cursor',
683
+ 'evaluation_intake_evaluation_heads',
684
+ 'evaluation_intake_evaluation_revisions',
685
+ ]);
686
+ function schemaObjectsFor(database, tables) {
687
+ const placeholders = tables.map(() => '?').join(',');
688
+ const rows = database.prepare(`SELECT type, name, tbl_name, sql FROM sqlite_schema
689
+ WHERE tbl_name IN (${placeholders}) OR name IN (${placeholders})`)
690
+ .all(...tables, ...tables);
691
+ return rows.map(row => JSON.stringify([row.type, row.name, row.tbl_name, row.sql?.replace(/\s+/g, ' ').trim() ?? null])).sort();
692
+ }
693
+ function expectedObjectsFor(tables, ddl) {
694
+ const reference = new DatabaseSync(':memory:');
695
+ try {
696
+ reference.exec(ddl);
697
+ return Object.freeze(schemaObjectsFor(reference, tables));
698
+ }
699
+ finally {
700
+ reference.close();
701
+ }
702
+ }
703
+ function assertExpectedSchemaObjects(database, tables, expected, message) {
704
+ const actual = schemaObjectsFor(database, tables);
705
+ if (actual.length !== expected.length || actual.some((entry, index) => entry !== expected[index])) {
706
+ throw new EvaluationDatabaseError('schema-drift', message);
707
+ }
708
+ }
709
+ function ownerQuestionSchemaObjects(database) {
710
+ return schemaObjectsFor(database, attentionOwnerQuestionDeliveryTables);
711
+ }
712
+ let expectedOwnerQuestionSchema;
713
+ /**
714
+ * Fail closed unless the schema-17 owner-question tables, their indexes and
715
+ * their immutability triggers are exactly the ones the migration creates.
716
+ */
717
+ function assertOwnerQuestionSchema(database) {
718
+ expectedOwnerQuestionSchema ??= expectedObjectsFor(attentionOwnerQuestionDeliveryTables, attentionOwnerQuestionDeliverySchema);
719
+ assertExpectedSchemaObjects(database, attentionOwnerQuestionDeliveryTables, expectedOwnerQuestionSchema, 'evaluation owner-question delivery schema does not match schema 17');
720
+ }
721
+ function intakeAttentionAgreementSchemaObjects(database) {
722
+ return schemaObjectsFor(database, intakeAttentionAgreementTables);
723
+ }
724
+ let expectedIntakeAttentionAgreementSchema;
725
+ /**
726
+ * Fail closed unless the schema-18 agreement table, its index and its
727
+ * immutability triggers are exactly the ones the migration creates.
728
+ */
729
+ function assertIntakeAttentionAgreementSchema(database) {
730
+ expectedIntakeAttentionAgreementSchema ??= expectedObjectsFor(intakeAttentionAgreementTables, intakeAttentionAgreementSchema);
731
+ assertExpectedSchemaObjects(database, intakeAttentionAgreementTables, expectedIntakeAttentionAgreementSchema, 'evaluation intake attention agreement schema does not match schema 18');
732
+ }
733
+ function intakeEvaluationAgreementSchemaObjects(database) {
734
+ return schemaObjectsFor(database, intakeEvaluationAgreementTables);
735
+ }
736
+ let expectedIntakeEvaluationAgreementSchema;
737
+ /**
738
+ * Fail closed unless the schema-19 intake evaluation agreement tables, indexes
739
+ * and immutability/monotonic triggers are exactly those created by migration.
740
+ */
741
+ function assertIntakeEvaluationAgreementSchema(database) {
742
+ expectedIntakeEvaluationAgreementSchema ??= expectedObjectsFor(intakeEvaluationAgreementTables, intakeEvaluationAgreementSchema);
743
+ assertExpectedSchemaObjects(database, intakeEvaluationAgreementTables, expectedIntakeEvaluationAgreementSchema, 'evaluation intake evaluation agreement schema does not match schema 19');
744
+ }
745
+ function migrate(database) {
746
+ migrateEvaluationDatabase(database);
747
+ }
748
+ /**
749
+ * Upgrade `database` to `target` (default: the current schema). Exported
750
+ * outside the package index so tests can build a genuine older schema with
751
+ * the same migration chain.
752
+ */
753
+ export function migrateEvaluationDatabase(database, target = evaluationSchemaVersion) {
754
+ if (!Number.isSafeInteger(target) || target < 1 || target > evaluationSchemaVersion) {
755
+ throw new Error('evaluation migration target is not a supported schema');
756
+ }
757
+ const initial = schemaVersion(database);
758
+ if (initial > evaluationSchemaVersion) {
759
+ throw new EvaluationDatabaseError('schema-too-new', `evaluation schema ${initial} is newer than supported schema ${evaluationSchemaVersion}`);
760
+ }
761
+ if (initial >= target) {
762
+ if (initial >= 17)
763
+ assertOwnerQuestionSchema(database);
764
+ if (initial >= 18)
765
+ assertIntakeAttentionAgreementSchema(database);
766
+ if (initial >= 19)
767
+ assertIntakeEvaluationAgreementSchema(database);
768
+ return;
769
+ }
770
+ database.exec('BEGIN IMMEDIATE');
771
+ try {
772
+ if (schemaVersion(database) === 0 && target > 0) {
773
+ database.exec(`
774
+ CREATE TABLE evaluation_schema_meta (
775
+ key TEXT PRIMARY KEY,
776
+ value TEXT NOT NULL
777
+ ) STRICT;
778
+
779
+ CREATE TABLE evaluation_outcomes (
780
+ id TEXT PRIMARY KEY,
781
+ idempotency_key TEXT NOT NULL UNIQUE,
782
+ payload_hash TEXT NOT NULL,
783
+ scope_key TEXT NOT NULL,
784
+ workspace TEXT NOT NULL,
785
+ preset TEXT NOT NULL,
786
+ situation TEXT NOT NULL,
787
+ execution_status TEXT NOT NULL
788
+ CHECK (execution_status IN ('succeeded', 'failed', 'timed-out', 'cancelled', 'unknown')),
789
+ objective_status TEXT NOT NULL
790
+ CHECK (objective_status IN ('achieved', 'partial', 'not-achieved', 'unknown')),
791
+ delivery_status TEXT NOT NULL
792
+ CHECK (delivery_status IN ('delivered', 'failed', 'not-required', 'unknown')),
793
+ source_kind TEXT NOT NULL
794
+ CHECK (source_kind IN ('automation', 'foreground', 'delivery', 'user-feedback', 'system', 'evaluator', 'import')),
795
+ source_id TEXT NOT NULL,
796
+ trust TEXT NOT NULL CHECK (trust IN ('trusted', 'self-reported', 'external')),
797
+ evidence_json TEXT NOT NULL,
798
+ metrics_json TEXT NOT NULL,
799
+ cost_usd_micros INTEGER,
800
+ latency_ms INTEGER,
801
+ input_tokens INTEGER,
802
+ output_tokens INTEGER,
803
+ tool_calls INTEGER,
804
+ occurred_at INTEGER NOT NULL,
805
+ recorded_at INTEGER NOT NULL,
806
+ evaluator_id TEXT NOT NULL,
807
+ evaluator_version TEXT NOT NULL,
808
+ task_subject_key TEXT,
809
+ task_subject_kind TEXT,
810
+ task_subject_ref TEXT
811
+ ) STRICT;
812
+
813
+ CREATE INDEX evaluation_outcomes_scope_time
814
+ ON evaluation_outcomes(scope_key, occurred_at DESC, id DESC);
815
+ CREATE INDEX evaluation_outcomes_scope_situation_time
816
+ ON evaluation_outcomes(scope_key, situation, occurred_at DESC, id DESC);
817
+ CREATE INDEX evaluation_outcomes_summary
818
+ ON evaluation_outcomes(scope_key, occurred_at, situation, trust);
819
+
820
+ ${selfAssessmentSchema}
821
+ ${projectionOutboxSchema}
822
+ ${taskProjectionSchema}
823
+ ${scopeWatermarkSchema}
824
+
825
+ INSERT INTO evaluation_schema_meta(key, value) VALUES ('schema-version', '7');
826
+ PRAGMA user_version = 7;
827
+ `);
828
+ }
829
+ if (schemaVersion(database) === 1 && target > 1) {
830
+ database.exec(`
831
+ ${selfAssessmentSchema}
832
+ UPDATE evaluation_schema_meta SET value = '2' WHERE key = 'schema-version';
833
+ PRAGMA user_version = 2;
834
+ `);
835
+ }
836
+ if (schemaVersion(database) === 2 && target > 2) {
837
+ database.exec(`
838
+ ${projectionOutboxSchema}
839
+ INSERT INTO evaluation_projection_outbox(
840
+ evaluation_id, status, attempt_count, next_attempt_at,
841
+ last_failure_at, last_failure_code, created_at, updated_at)
842
+ SELECT id, 'pending', 0, recorded_at, NULL, NULL, recorded_at, recorded_at
843
+ FROM evaluation_outcomes
844
+ WHERE trust = 'trusted' AND objective_status <> 'unknown';
845
+ UPDATE evaluation_schema_meta SET value = '3' WHERE key = 'schema-version';
846
+ PRAGMA user_version = 3;
847
+ `);
848
+ }
849
+ if (schemaVersion(database) === 3 && target > 3) {
850
+ database.exec(`
851
+ ALTER TABLE evaluation_outcomes ADD COLUMN task_subject_key TEXT;
852
+ ALTER TABLE evaluation_outcomes ADD COLUMN task_subject_kind TEXT;
853
+ ALTER TABLE evaluation_outcomes ADD COLUMN task_subject_ref TEXT;
854
+ ${legacyTaskProjectionSchema}
855
+ `);
856
+ const columns = new Set(database.prepare('PRAGMA table_info(evaluation_outcomes)').all().map(column => column.name));
857
+ if (columns.has('scope_key') && columns.has('evidence_json')) {
858
+ const rows = database.prepare(`
859
+ SELECT id, scope_key, evidence_json FROM evaluation_outcomes
860
+ ORDER BY recorded_at, id
861
+ `).all();
862
+ const update = database.prepare(`
863
+ UPDATE evaluation_outcomes
864
+ SET task_subject_key = ?, task_subject_kind = ?, task_subject_ref = ?
865
+ WHERE id = ?
866
+ `);
867
+ const insert = database.prepare(`
868
+ INSERT INTO evaluation_task_projections(
869
+ subject_key, scope_key, subject_kind, subject_ref, updated_at)
870
+ VALUES (?, ?, ?, ?, 0)
871
+ ON CONFLICT(subject_key) DO NOTHING
872
+ `);
873
+ for (const row of rows) {
874
+ const subject = legacyTaskSubject(row.scope_key, row.id, row.evidence_json);
875
+ update.run(subject.key, subject.kind, subject.ref, row.id);
876
+ insert.run(subject.key, row.scope_key, subject.kind, subject.ref);
877
+ }
878
+ }
879
+ database.exec(`
880
+ UPDATE evaluation_schema_meta SET value = '4' WHERE key = 'schema-version';
881
+ PRAGMA user_version = 4;
882
+ `);
883
+ }
884
+ if (schemaVersion(database) === 4 && target > 4) {
885
+ database.exec(`
886
+ DROP VIEW evaluation_task_projection_view;
887
+ ALTER TABLE evaluation_task_projections
888
+ ADD COLUMN learning_version INTEGER NOT NULL DEFAULT 0 CHECK (learning_version >= 0);
889
+ ALTER TABLE evaluation_task_projections
890
+ ADD COLUMN learning_digest TEXT CHECK (learning_digest IS NULL OR length(learning_digest) = 64);
891
+ ALTER TABLE evaluation_task_projections
892
+ ADD COLUMN learning_disposition TEXT CHECK (learning_disposition IN ('upsert', 'retract'));
893
+ ${taskProjectionViewSchema}
894
+
895
+ -- v4 delivered raw outcome state. Re-run each retained trigger once so
896
+ -- Evolution can replace it with the canonical versioned task state.
897
+ UPDATE evaluation_projection_outbox
898
+ SET status = 'pending', attempt_count = 0, next_attempt_at = updated_at,
899
+ last_failure_at = NULL, last_failure_code = NULL;
900
+ INSERT INTO evaluation_projection_outbox(
901
+ evaluation_id, status, attempt_count, next_attempt_at,
902
+ last_failure_at, last_failure_code, created_at, updated_at)
903
+ SELECT projection.primary_outcome_id, 'pending', 0, projection.updated_at,
904
+ NULL, NULL, projection.updated_at, projection.updated_at
905
+ FROM evaluation_task_projections projection
906
+ JOIN evaluation_outcomes outcome ON outcome.id = projection.primary_outcome_id
907
+ WHERE outcome.trust = 'trusted'
908
+ ON CONFLICT(evaluation_id) DO NOTHING;
909
+
910
+ UPDATE evaluation_schema_meta SET value = '5' WHERE key = 'schema-version';
911
+ PRAGMA user_version = 5;
912
+ `);
913
+ }
914
+ if (schemaVersion(database) === 5 && target > 5) {
915
+ database.exec(`
916
+ -- Protocol v2 uses a distinct task-revision sink capability. A v5
917
+ -- Evaluation may already have marked a trigger recorded after an older
918
+ -- Evolution accepted the raw-outcome protocol, which would otherwise
919
+ -- lose a later retract forever. Requeue every retained task once when
920
+ -- crossing this compatibility boundary.
921
+ UPDATE evaluation_projection_outbox
922
+ SET status = 'pending', attempt_count = 0, next_attempt_at = updated_at,
923
+ last_failure_at = NULL, last_failure_code = NULL;
924
+ INSERT INTO evaluation_projection_outbox(
925
+ evaluation_id, status, attempt_count, next_attempt_at,
926
+ last_failure_at, last_failure_code, created_at, updated_at)
927
+ SELECT projection.primary_outcome_id, 'pending', 0, projection.updated_at,
928
+ NULL, NULL, projection.updated_at, projection.updated_at
929
+ FROM evaluation_task_projections projection
930
+ JOIN evaluation_outcomes outcome ON outcome.id = projection.primary_outcome_id
931
+ WHERE outcome.trust = 'trusted'
932
+ ON CONFLICT(evaluation_id) DO UPDATE SET
933
+ status = 'pending', attempt_count = 0,
934
+ next_attempt_at = excluded.next_attempt_at,
935
+ last_failure_at = NULL, last_failure_code = NULL,
936
+ updated_at = excluded.updated_at;
937
+
938
+ UPDATE evaluation_schema_meta SET value = '6' WHERE key = 'schema-version';
939
+ PRAGMA user_version = 6;
940
+ `);
941
+ }
942
+ if (schemaVersion(database) === 6 && target > 6) {
943
+ database.exec(`
944
+ ${scopeWatermarkSchema}
945
+ -- The sum of each subject's monotonic learning revision is the exact
946
+ -- number of retained canonical changes represented by a v6 database.
947
+ -- New changes increment this scope value one at a time.
948
+ INSERT INTO evaluation_scope_watermarks(scope_key, watermark, updated_at)
949
+ SELECT scope_key, SUM(learning_version), MAX(updated_at)
950
+ FROM evaluation_task_projections
951
+ GROUP BY scope_key;
952
+
953
+ -- Protocol v3 carries the scope watermark and is mandatory for the
954
+ -- downstream writer fence. A v6 sink acknowledgement is insufficient.
955
+ UPDATE evaluation_projection_outbox
956
+ SET status = 'pending', attempt_count = 0, next_attempt_at = updated_at,
957
+ last_failure_at = NULL, last_failure_code = NULL;
958
+ INSERT INTO evaluation_projection_outbox(
959
+ evaluation_id, status, attempt_count, next_attempt_at,
960
+ last_failure_at, last_failure_code, created_at, updated_at)
961
+ SELECT projection.primary_outcome_id, 'pending', 0, projection.updated_at,
962
+ NULL, NULL, projection.updated_at, projection.updated_at
963
+ FROM evaluation_task_projections projection
964
+ JOIN evaluation_outcomes outcome ON outcome.id = projection.primary_outcome_id
965
+ WHERE outcome.trust = 'trusted'
966
+ ON CONFLICT(evaluation_id) DO UPDATE SET
967
+ status = 'pending', attempt_count = 0,
968
+ next_attempt_at = excluded.next_attempt_at,
969
+ last_failure_at = NULL, last_failure_code = NULL,
970
+ updated_at = excluded.updated_at;
971
+
972
+ UPDATE evaluation_schema_meta SET value = '7' WHERE key = 'schema-version';
973
+ PRAGMA user_version = 7;
974
+ `);
975
+ }
976
+ if (schemaVersion(database) === 7 && target > 7) {
977
+ database.exec(`
978
+ CREATE TABLE evaluation_owner_revisions (
979
+ outcome_id TEXT PRIMARY KEY REFERENCES evaluation_outcomes(id),
980
+ subject_key TEXT NOT NULL,
981
+ lineage TEXT NOT NULL,
982
+ version INTEGER NOT NULL,
983
+ previous_outcome_id TEXT,
984
+ action TEXT NOT NULL,
985
+ command_json TEXT NOT NULL,
986
+ UNIQUE(subject_key, lineage, version)
987
+ ) STRICT;
988
+ CREATE TABLE evaluation_owner_commands (
989
+ operation_id TEXT PRIMARY KEY,
990
+ payload_hash TEXT NOT NULL,
991
+ outcome_id TEXT REFERENCES evaluation_outcomes(id),
992
+ failure_code TEXT
993
+ ) STRICT;
994
+ UPDATE evaluation_schema_meta SET value = '8' WHERE key = 'schema-version';
995
+ PRAGMA user_version = 8;
996
+ `);
997
+ }
998
+ if (schemaVersion(database) === 8 && target > 8) {
999
+ // SQLite CHECK constraints cannot be widened in place. Preserve every
1000
+ // existing v8 projection while enabling the distinct foreground subject.
1001
+ database.exec(`
1002
+ DROP VIEW evaluation_task_projection_view;
1003
+ ALTER TABLE evaluation_task_projections RENAME TO evaluation_task_projections_v8;
1004
+ DROP INDEX evaluation_task_projections_scope_time;
1005
+ CREATE TABLE evaluation_task_projections (
1006
+ subject_key TEXT PRIMARY KEY,
1007
+ scope_key TEXT NOT NULL,
1008
+ subject_kind TEXT NOT NULL CHECK (subject_kind IN ('automation-run', 'foreground-turn', 'outcome')),
1009
+ subject_ref TEXT NOT NULL,
1010
+ primary_outcome_id TEXT,
1011
+ execution_outcome_id TEXT,
1012
+ objective_outcome_id TEXT,
1013
+ delivery_outcome_id TEXT,
1014
+ objective_conflicted INTEGER NOT NULL DEFAULT 0 CHECK (objective_conflicted IN (0, 1)),
1015
+ learning_version INTEGER NOT NULL DEFAULT 0 CHECK (learning_version >= 0),
1016
+ learning_digest TEXT CHECK (learning_digest IS NULL OR length(learning_digest) = 64),
1017
+ learning_disposition TEXT CHECK (learning_disposition IN ('upsert', 'retract')),
1018
+ updated_at INTEGER NOT NULL,
1019
+ FOREIGN KEY (primary_outcome_id) REFERENCES evaluation_outcomes(id) ON DELETE RESTRICT,
1020
+ FOREIGN KEY (execution_outcome_id) REFERENCES evaluation_outcomes(id) ON DELETE RESTRICT,
1021
+ FOREIGN KEY (objective_outcome_id) REFERENCES evaluation_outcomes(id) ON DELETE RESTRICT,
1022
+ FOREIGN KEY (delivery_outcome_id) REFERENCES evaluation_outcomes(id) ON DELETE RESTRICT
1023
+ ) STRICT;
1024
+ CREATE INDEX evaluation_task_projections_scope_time
1025
+ ON evaluation_task_projections(scope_key, updated_at DESC, subject_key);
1026
+ INSERT INTO evaluation_task_projections (
1027
+ subject_key, scope_key, subject_kind, subject_ref, primary_outcome_id,
1028
+ execution_outcome_id, objective_outcome_id, delivery_outcome_id,
1029
+ objective_conflicted, learning_version, learning_digest, learning_disposition, updated_at
1030
+ ) SELECT subject_key, scope_key, subject_kind, subject_ref, primary_outcome_id,
1031
+ execution_outcome_id, objective_outcome_id, delivery_outcome_id,
1032
+ objective_conflicted, learning_version, learning_digest, learning_disposition, updated_at
1033
+ FROM evaluation_task_projections_v8;
1034
+ DROP TABLE evaluation_task_projections_v8;
1035
+ ${taskProjectionViewSchema}
1036
+ UPDATE evaluation_schema_meta SET value = '9' WHERE key = 'schema-version';
1037
+ PRAGMA user_version = 9;
1038
+ `);
1039
+ }
1040
+ if (schemaVersion(database) === 9 && target > 9) {
1041
+ // Rebuild only the constrained projection table; its rows and all
1042
+ // outcome/foreign-key references remain intact across the v9 -> v10 step.
1043
+ database.exec(`
1044
+ DROP VIEW evaluation_task_projection_view;
1045
+ ALTER TABLE evaluation_task_projections RENAME TO evaluation_task_projections_v9;
1046
+ DROP INDEX evaluation_task_projections_scope_time;
1047
+ ${taskProjectionSchema.replace('CREATE INDEX evaluation_outcomes_task_subject\n ON evaluation_outcomes(task_subject_key, recorded_at, id);', '')}
1048
+ INSERT INTO evaluation_task_projections SELECT * FROM evaluation_task_projections_v9;
1049
+ DROP TABLE evaluation_task_projections_v9;
1050
+ UPDATE evaluation_schema_meta SET value = '10' WHERE key = 'schema-version';
1051
+ PRAGMA user_version = 10;
1052
+ `);
1053
+ }
1054
+ if (schemaVersion(database) === 10 && target > 10) {
1055
+ // Preserve all historical projections while widening only the durable
1056
+ // subject-kind constraint for whole-goal verifier assessments.
1057
+ database.exec(`
1058
+ DROP VIEW evaluation_task_projection_view;
1059
+ ALTER TABLE evaluation_task_projections RENAME TO evaluation_task_projections_v10;
1060
+ DROP INDEX evaluation_task_projections_scope_time;
1061
+ ${taskProjectionSchema.replace('CREATE INDEX evaluation_outcomes_task_subject\n ON evaluation_outcomes(task_subject_key, recorded_at, id);', '')}
1062
+ INSERT INTO evaluation_task_projections SELECT * FROM evaluation_task_projections_v10;
1063
+ DROP TABLE evaluation_task_projections_v10;
1064
+ UPDATE evaluation_schema_meta SET value = '11' WHERE key = 'schema-version';
1065
+ PRAGMA user_version = 11;
1066
+ `);
1067
+ }
1068
+ if (schemaVersion(database) === 11 && target > 11) {
1069
+ // Historical projections had a scope fence but no cursorable head. Give
1070
+ // every existing canonical subject a stable new watermark exactly once.
1071
+ const overflow = database.prepare(`
1072
+ SELECT 1 FROM evaluation_scope_watermarks watermark
1073
+ JOIN (
1074
+ SELECT scope_key, COUNT(*) AS count FROM evaluation_task_projections
1075
+ WHERE learning_version >= 1 AND learning_digest IS NOT NULL GROUP BY scope_key
1076
+ ) projection ON projection.scope_key = watermark.scope_key
1077
+ WHERE watermark.watermark > ${Number.MAX_SAFE_INTEGER} - projection.count LIMIT 1
1078
+ `).get();
1079
+ if (overflow !== undefined)
1080
+ throw new Error('evaluation projection feed watermark overflow');
1081
+ database.exec(`
1082
+ ${taskProjectionFeedSchema}
1083
+ INSERT INTO evaluation_scope_watermarks(scope_key, watermark, updated_at)
1084
+ SELECT scope_key, 0, MAX(updated_at) FROM evaluation_task_projections
1085
+ GROUP BY scope_key ON CONFLICT(scope_key) DO NOTHING;
1086
+ INSERT INTO evaluation_task_projection_feed_heads(subject_key, scope_key, watermark)
1087
+ SELECT projection.subject_key, projection.scope_key,
1088
+ existing.watermark + ROW_NUMBER() OVER (PARTITION BY projection.scope_key ORDER BY projection.subject_key)
1089
+ FROM evaluation_task_projections projection
1090
+ JOIN evaluation_outcomes primary_outcome ON primary_outcome.id = projection.primary_outcome_id
1091
+ JOIN evaluation_scope_watermarks existing ON existing.scope_key = projection.scope_key
1092
+ WHERE primary_outcome.trust = 'trusted'
1093
+ AND projection.learning_version >= 1 AND projection.learning_digest IS NOT NULL
1094
+ ON CONFLICT(subject_key) DO NOTHING;
1095
+ UPDATE evaluation_scope_watermarks
1096
+ SET watermark = watermark + (
1097
+ SELECT COUNT(*) FROM evaluation_task_projection_feed_heads head
1098
+ WHERE head.scope_key = evaluation_scope_watermarks.scope_key
1099
+ );
1100
+ UPDATE evaluation_schema_meta SET value = '12' WHERE key = 'schema-version';
1101
+ PRAGMA user_version = 12;
1102
+ `);
1103
+ }
1104
+ if (schemaVersion(database) === 12 && target > 12) {
1105
+ // Preserve feed heads and every semantic revision verbatim while widening
1106
+ // the projection identity. Historical settlement evidence is not re-keyed.
1107
+ database.exec(`
1108
+ CREATE TEMP TABLE evaluation_v12_feed AS SELECT * FROM evaluation_task_projection_feed_heads;
1109
+ DROP TABLE evaluation_task_projection_feed_heads;
1110
+ DROP VIEW evaluation_task_projection_view;
1111
+ ALTER TABLE evaluation_task_projections RENAME TO evaluation_task_projections_v12;
1112
+ DROP INDEX evaluation_task_projections_scope_time;
1113
+ ${taskProjectionSchema.replace('CREATE INDEX evaluation_outcomes_task_subject\n ON evaluation_outcomes(task_subject_key, recorded_at, id);', '')}
1114
+ INSERT INTO evaluation_task_projections SELECT * FROM evaluation_task_projections_v12;
1115
+ DROP TABLE evaluation_task_projections_v12;
1116
+ ${taskProjectionFeedSchema}
1117
+ INSERT INTO evaluation_task_projection_feed_heads SELECT * FROM evaluation_v12_feed;
1118
+ DROP TABLE evaluation_v12_feed;
1119
+ CREATE TEMP TABLE evaluation_v12_outbox AS SELECT * FROM evaluation_projection_outbox;
1120
+ DROP TABLE evaluation_projection_outbox;
1121
+ ${projectionOutboxSchema}
1122
+ INSERT INTO evaluation_projection_outbox SELECT * FROM evaluation_v12_outbox;
1123
+ DROP TABLE evaluation_v12_outbox;
1124
+ UPDATE evaluation_schema_meta SET value = '13' WHERE key = 'schema-version';
1125
+ PRAGMA user_version = 13;
1126
+ `);
1127
+ }
1128
+ if (schemaVersion(database) === 13 && target > 13) {
1129
+ database.exec(`
1130
+ ${notificationOutcomeSchema}
1131
+ UPDATE evaluation_schema_meta SET value = '14' WHERE key = 'schema-version';
1132
+ PRAGMA user_version = 14;
1133
+ `);
1134
+ }
1135
+ if (schemaVersion(database) === 14 && target > 14) {
1136
+ database.exec(`
1137
+ ${attentionTuningSchema}
1138
+ UPDATE evaluation_schema_meta SET value = '15' WHERE key = 'schema-version';
1139
+ PRAGMA user_version = 15;
1140
+ `);
1141
+ }
1142
+ if (schemaVersion(database) === 15 && target > 15) {
1143
+ database.exec(`
1144
+ ${attentionLooseningSchema}
1145
+ UPDATE evaluation_schema_meta SET value = '16' WHERE key = 'schema-version';
1146
+ PRAGMA user_version = 16;
1147
+ `);
1148
+ }
1149
+ if (schemaVersion(database) === 16 && target > 16) {
1150
+ if (ownerQuestionSchemaObjects(database).length > 0) {
1151
+ throw new EvaluationDatabaseError('schema-drift', 'evaluation schema 16 already holds owner-question delivery objects');
1152
+ }
1153
+ database.exec(`
1154
+ ${attentionOwnerQuestionDeliverySchema}
1155
+ UPDATE evaluation_schema_meta SET value = '17' WHERE key = 'schema-version';
1156
+ PRAGMA user_version = 17;
1157
+ `);
1158
+ }
1159
+ if (schemaVersion(database) === 17 && target > 17) {
1160
+ // A test/rollback fixture can leave the exact schema-18 objects behind
1161
+ // while rewinding only the version. Reuse them after an exact drift
1162
+ // check; anything else at schema 17 is genuine drift and fails closed.
1163
+ if (intakeAttentionAgreementSchemaObjects(database).length > 0) {
1164
+ assertIntakeAttentionAgreementSchema(database);
1165
+ }
1166
+ else {
1167
+ database.exec(intakeAttentionAgreementSchema);
1168
+ }
1169
+ database.exec(`
1170
+ UPDATE evaluation_schema_meta SET value = '18' WHERE key = 'schema-version';
1171
+ PRAGMA user_version = 18;
1172
+ `);
1173
+ }
1174
+ if (schemaVersion(database) === 18 && target > 18) {
1175
+ // A test/rollback fixture can leave the exact schema-19 objects behind
1176
+ // while rewinding only the version. Reuse them after an exact drift
1177
+ // check; anything else at schema 18 is genuine drift and fails closed.
1178
+ if (intakeEvaluationAgreementSchemaObjects(database).length > 0) {
1179
+ assertIntakeEvaluationAgreementSchema(database);
1180
+ }
1181
+ else {
1182
+ database.exec(intakeEvaluationAgreementSchema);
1183
+ }
1184
+ database.exec(`
1185
+ UPDATE evaluation_schema_meta SET value = '19' WHERE key = 'schema-version';
1186
+ PRAGMA user_version = 19;
1187
+ `);
1188
+ }
1189
+ if (schemaVersion(database) !== target) {
1190
+ throw new Error('evaluation migration did not reach the current schema');
1191
+ }
1192
+ if (target >= 17)
1193
+ assertOwnerQuestionSchema(database);
1194
+ if (target >= 18)
1195
+ assertIntakeAttentionAgreementSchema(database);
1196
+ if (target >= 19)
1197
+ assertIntakeEvaluationAgreementSchema(database);
1198
+ database.exec('COMMIT');
1199
+ }
1200
+ catch (error) {
1201
+ database.exec('ROLLBACK');
1202
+ throw error;
1203
+ }
1204
+ }
1205
+ const walRetryWait = new Int32Array(new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT));
1206
+ function enableWal(database) {
1207
+ const deadline = Date.now() + 5_000;
1208
+ while (true) {
1209
+ try {
1210
+ const row = database.prepare('PRAGMA journal_mode = WAL').get();
1211
+ if (row.journal_mode.toLowerCase() !== 'wal') {
1212
+ throw new Error(`evaluation database refused WAL mode: ${row.journal_mode}`);
1213
+ }
1214
+ return;
1215
+ }
1216
+ catch (error) {
1217
+ const retryable = error instanceof Error && /database is (?:busy|locked)/i.test(error.message);
1218
+ if (!retryable || Date.now() >= deadline)
1219
+ throw error;
1220
+ Atomics.wait(walRetryWait, 0, 0, 10);
1221
+ }
1222
+ }
1223
+ }
1224
+ export function openEvaluationDatabase(path) {
1225
+ if (path !== ':memory:' && !isAbsolute(path)) {
1226
+ throw new EvaluationDatabaseError('invalid-path', 'evaluation database path must be absolute');
1227
+ }
1228
+ if (path !== ':memory:')
1229
+ preparePrivateFile(path);
1230
+ const database = new DatabaseSync(path);
1231
+ try {
1232
+ database.exec('PRAGMA foreign_keys = ON');
1233
+ database.exec('PRAGMA busy_timeout = 5000');
1234
+ database.exec('PRAGMA synchronous = FULL');
1235
+ migrate(database);
1236
+ if (path !== ':memory:') {
1237
+ enableWal(database);
1238
+ chmodSync(path, 0o600);
1239
+ }
1240
+ return database;
1241
+ }
1242
+ catch (error) {
1243
+ database.close();
1244
+ throw error;
1245
+ }
1246
+ }
1247
+ //# sourceMappingURL=sqlite.js.map