@dsh-ray/assistant-evaluation 0.0.1-seed.0 → 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 +309 -1
  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 +235 -4
@@ -0,0 +1,740 @@
1
+ /**
2
+ * WP22: canonical ingestion and correlation of WP20 `would-accept` intake
3
+ * evaluations against admitted work-item outcomes, notification outcomes, and
4
+ * subsequent owner feedback or withdrawals.
5
+ *
6
+ * Reads only the text-free `listIntakeEvaluationFeed` surface structurally
7
+ * from WorkItems (no runtime dependency) and maintains a durable incremental
8
+ * cursor plus immutable revision history alongside notification outcomes.
9
+ */
10
+ import { createHash } from 'node:crypto';
11
+ import { canonicalEvaluationScope, EvaluationStoreError } from './store.js';
12
+ export const WORK_ITEM_INTAKE_EVALUATION_FEED_PROTOCOL = 'work-items/intake-evaluation-feed/v1';
13
+ export const INTAKE_EVALUATION_AGREEMENT_PROTOCOL = 'assistant-evaluation/intake-evaluation-agreement/v1';
14
+ export function isIntakeEvaluationFeedSource(value) {
15
+ return typeof value === 'object' && value !== null
16
+ && typeof value.listIntakeEvaluationFeed === 'function';
17
+ }
18
+ const LEVELS = ['ignore', 'digest', 'notify', 'accept'];
19
+ const POSITIVE_NOTIFICATIONS = new Set(['accepted', 'reacted']);
20
+ const NEGATIVE_NOTIFICATIONS = new Set(['rejected', 'expired-unhandled']);
21
+ const FORBIDDEN_BODY_FIELDS = ['text', 'body', 'title', 'brief', 'prompt', 'sourceText', 'objective', 'messages'];
22
+ const AUTHORITY_RANK = Object.freeze({
23
+ 'owner-feedback': 4,
24
+ 'owner-withdrawal': 3,
25
+ 'notification-outcome': 2,
26
+ 'work-item-verdict': 1,
27
+ 'work-item-outcome': 0,
28
+ });
29
+ function canonical(value) {
30
+ if (value === null || typeof value === 'boolean' || typeof value === 'number' || typeof value === 'string') {
31
+ return JSON.stringify(value);
32
+ }
33
+ if (Array.isArray(value))
34
+ return `[${value.map(item => canonical(item)).join(',')}]`;
35
+ const record = value;
36
+ return `{${Object.keys(record).filter(key => record[key] !== undefined).sort()
37
+ .map(key => `${JSON.stringify(key)}:${canonical(record[key])}`).join(',')}}`;
38
+ }
39
+ function sha256(value) {
40
+ return createHash('sha256').update(typeof value === 'string' ? value : canonical(value), 'utf8').digest('hex');
41
+ }
42
+ function invalid(message) {
43
+ throw new EvaluationStoreError('invalid-input', message);
44
+ }
45
+ function nonEmptyString(value, label, maxLength) {
46
+ if (typeof value !== 'string' || value.length === 0 || value.length > maxLength) {
47
+ invalid(`intake evaluation ${label} must be a non-empty string`);
48
+ }
49
+ return value;
50
+ }
51
+ function nonNegInt(value, label) {
52
+ if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 0) {
53
+ invalid(`intake evaluation ${label} must be a non-negative integer`);
54
+ }
55
+ return value;
56
+ }
57
+ function optionalPlainRecord(value, label) {
58
+ if (value === null || value === undefined)
59
+ return null;
60
+ if (typeof value !== 'object' || Array.isArray(value))
61
+ invalid(`intake evaluation ${label} must be an object`);
62
+ const record = value;
63
+ for (const forbidden of FORBIDDEN_BODY_FIELDS) {
64
+ if (Object.hasOwn(record, forbidden))
65
+ invalid(`intake evaluation ${label} must not contain raw text field ${forbidden}`);
66
+ }
67
+ return record;
68
+ }
69
+ export function intakeEvaluationCanonicalId(source, sourceEventId, ruleId, policyVersion) {
70
+ return sha256({
71
+ protocol: 'assistant-evaluation/intake-evaluation/v1',
72
+ source,
73
+ sourceEventId,
74
+ ruleId,
75
+ policyVersion,
76
+ });
77
+ }
78
+ function normalizeFeedItem(raw) {
79
+ const item = optionalPlainRecord(raw, 'feed item');
80
+ if (item === null)
81
+ invalid('intake evaluation feed item must be an object');
82
+ const seq = nonNegInt(item['seq'], 'seq');
83
+ if (seq < 1)
84
+ invalid('intake evaluation seq must be positive');
85
+ const feedId = nonEmptyString(item['id'], 'id', 256);
86
+ const recordedAt = nonNegInt(item['recordedAt'], 'recordedAt');
87
+ const evaluatedAt = nonNegInt(item['evaluatedAt'], 'evaluatedAt');
88
+ const source = nonEmptyString(item['source'], 'source', 64);
89
+ const sourceEventId = nonEmptyString(item['sourceEventId'], 'sourceEventId', 256);
90
+ const ruleId = nonEmptyString(item['ruleId'], 'ruleId', 256);
91
+ const policyVersion = nonEmptyString(item['policyVersion'], 'policyVersion', 256);
92
+ if (typeof item['wouldAccept'] !== 'boolean')
93
+ invalid('intake evaluation wouldAccept must be a boolean');
94
+ const mode = item['mode'];
95
+ if (mode !== 'observe' && mode !== 'auto')
96
+ invalid('intake evaluation mode is invalid');
97
+ const level = item['evaluationLevel'];
98
+ if (!LEVELS.includes(level))
99
+ invalid('intake evaluation level is invalid');
100
+ const metadataDigest = nonEmptyString(item['metadataDigest'], 'metadataDigest', 128);
101
+ const sourceDigest = nonEmptyString(item['sourceDigest'], 'sourceDigest', 128);
102
+ const contentDigest = item['contentDigest'] === null || item['contentDigest'] === undefined
103
+ ? null : nonEmptyString(item['contentDigest'], 'contentDigest', 128);
104
+ const itemId = item['itemId'] === null || item['itemId'] === undefined
105
+ ? null : nonEmptyString(item['itemId'], 'itemId', 256);
106
+ let scope = null;
107
+ let scopeKey = null;
108
+ if (item['scope'] !== null && item['scope'] !== undefined) {
109
+ const scopeObj = optionalPlainRecord(item['scope'], 'scope');
110
+ if (scopeObj === null)
111
+ invalid('intake evaluation scope must be an object');
112
+ const canonicalScope = canonicalEvaluationScope({
113
+ workspace: scopeObj['workspace'],
114
+ preset: scopeObj['preset'],
115
+ });
116
+ scope = canonicalScope.scope;
117
+ scopeKey = canonicalScope.scopeKey;
118
+ }
119
+ const rawOutcome = optionalPlainRecord(item['outcome'], 'outcome');
120
+ const outcome = rawOutcome === null ? null : Object.freeze({
121
+ revision: nonNegInt(rawOutcome['revision'], 'outcome.revision'),
122
+ settledBy: nonEmptyString(rawOutcome['settledBy'], 'outcome.settledBy', 64),
123
+ executionStatus: nonEmptyString(rawOutcome['executionStatus'], 'outcome.executionStatus', 64),
124
+ objectiveStatus: nonEmptyString(rawOutcome['objectiveStatus'], 'outcome.objectiveStatus', 64),
125
+ evidenceState: nonEmptyString(rawOutcome['evidenceState'], 'outcome.evidenceState', 64),
126
+ settledAt: nonNegInt(rawOutcome['settledAt'], 'outcome.settledAt'),
127
+ recordedAt: nonNegInt(rawOutcome['recordedAt'], 'outcome.recordedAt'),
128
+ ownerWithdrawn: rawOutcome['ownerWithdrawn'] === true || rawOutcome['settledBy'] === 'withdrawn',
129
+ });
130
+ const rawVerdict = optionalPlainRecord(item['acceptanceVerdict'], 'acceptanceVerdict');
131
+ let acceptanceVerdict = null;
132
+ if (rawVerdict !== null) {
133
+ const obj = rawVerdict['objectiveStatus'];
134
+ if (obj !== 'achieved' && obj !== 'not-achieved' && obj !== 'unknown') {
135
+ invalid('intake evaluation acceptanceVerdict.objectiveStatus is invalid');
136
+ }
137
+ acceptanceVerdict = Object.freeze({
138
+ objectiveStatus: obj,
139
+ receiptDigest: nonEmptyString(rawVerdict['receiptDigest'], 'acceptanceVerdict.receiptDigest', 128),
140
+ completedAt: nonNegInt(rawVerdict['completedAt'], 'acceptanceVerdict.completedAt'),
141
+ recordedAt: nonNegInt(rawVerdict['recordedAt'], 'acceptanceVerdict.recordedAt'),
142
+ });
143
+ }
144
+ const rawCorrection = optionalPlainRecord(item['ownerCorrection'], 'ownerCorrection');
145
+ let ownerCorrection = null;
146
+ if (rawCorrection !== null) {
147
+ if (rawCorrection['kind'] !== 'withdrawn')
148
+ invalid('intake evaluation ownerCorrection.kind is invalid');
149
+ ownerCorrection = Object.freeze({
150
+ kind: 'withdrawn',
151
+ stateReason: rawCorrection['stateReason'] === null || rawCorrection['stateReason'] === undefined
152
+ ? null : nonEmptyString(rawCorrection['stateReason'], 'ownerCorrection.stateReason', 256),
153
+ recordedAt: nonNegInt(rawCorrection['recordedAt'], 'ownerCorrection.recordedAt'),
154
+ });
155
+ }
156
+ return Object.freeze({
157
+ evalId: intakeEvaluationCanonicalId(source, sourceEventId, ruleId, policyVersion),
158
+ feedId,
159
+ seq,
160
+ recordedAt,
161
+ evaluatedAt,
162
+ source,
163
+ sourceEventId,
164
+ ruleId,
165
+ policyVersion,
166
+ mode,
167
+ evaluationLevel: level,
168
+ wouldAccept: item['wouldAccept'],
169
+ itemId,
170
+ scope,
171
+ scopeKey,
172
+ feedSignals: Object.freeze({
173
+ metadataDigest,
174
+ sourceDigest,
175
+ contentDigest,
176
+ outcome,
177
+ acceptanceVerdict,
178
+ ownerCorrection,
179
+ }),
180
+ });
181
+ }
182
+ export function normalizeFeedCursor(raw) {
183
+ if (raw === null || raw === undefined)
184
+ return null;
185
+ if (typeof raw !== 'object' || Array.isArray(raw))
186
+ invalid('intake evaluation cursor must be an object');
187
+ const record = raw;
188
+ return Object.freeze({
189
+ afterSeq: nonNegInt(record['afterSeq'], 'cursor.afterSeq'),
190
+ afterRecordedAt: nonNegInt(record['afterRecordedAt'], 'cursor.afterRecordedAt'),
191
+ afterId: nonEmptyString(record['afterId'], 'cursor.afterId', 256),
192
+ });
193
+ }
194
+ export function normalizeFeedPage(raw) {
195
+ if (typeof raw !== 'object' || raw === null || Array.isArray(raw))
196
+ invalid('intake evaluation feed page must be an object');
197
+ const record = raw;
198
+ if (record['protocol'] !== WORK_ITEM_INTAKE_EVALUATION_FEED_PROTOCOL) {
199
+ invalid('intake evaluation feed protocol is unsupported');
200
+ }
201
+ if (!Array.isArray(record['items']))
202
+ invalid('intake evaluation feed items must be an array');
203
+ if (typeof record['hasMore'] !== 'boolean')
204
+ invalid('intake evaluation feed hasMore must be a boolean');
205
+ return Object.freeze({
206
+ items: record['items'],
207
+ hasMore: record['hasMore'],
208
+ nextCursor: normalizeFeedCursor(record['nextCursor']),
209
+ });
210
+ }
211
+ function classifyAgreement(wouldAccept, winning) {
212
+ if (winning === undefined) {
213
+ return { outcomeKind: 'pending', agreementStatus: 'pending', outcomeSource: 'none' };
214
+ }
215
+ if (wouldAccept && winning.positive) {
216
+ return { outcomeKind: 'agreed', agreementStatus: 'true-positive', outcomeSource: winning.source };
217
+ }
218
+ if (wouldAccept && !winning.positive) {
219
+ return { outcomeKind: 'disagreed', agreementStatus: 'false-positive', outcomeSource: winning.source };
220
+ }
221
+ if (!wouldAccept && winning.positive) {
222
+ return { outcomeKind: 'disagreed', agreementStatus: 'false-negative', outcomeSource: winning.source };
223
+ }
224
+ return { outcomeKind: 'agreed', agreementStatus: 'true-negative', outcomeSource: winning.source };
225
+ }
226
+ function cursorAdvances(next, prev) {
227
+ if (next.afterRecordedAt > prev.afterRecordedAt)
228
+ return true;
229
+ if (next.afterRecordedAt < prev.afterRecordedAt)
230
+ return false;
231
+ if (next.afterId > prev.afterId)
232
+ return true;
233
+ if (next.afterId < prev.afterId)
234
+ return false;
235
+ return next.afterSeq > prev.afterSeq;
236
+ }
237
+ function toStoredHead(row) {
238
+ return Object.freeze({
239
+ evalId: row.eval_id,
240
+ source: row.source,
241
+ sourceEventId: row.source_event_id,
242
+ ruleId: row.rule_id,
243
+ policyVersion: row.policy_version,
244
+ scope: row.workspace !== null && row.preset !== null
245
+ ? Object.freeze({ workspace: row.workspace, preset: row.preset })
246
+ : null,
247
+ scopeKey: row.scope_key,
248
+ itemId: row.item_id,
249
+ wouldAccept: row.would_accept === 1,
250
+ evaluationLevel: row.evaluation_level,
251
+ mode: row.mode,
252
+ outcomeKind: row.outcome_kind,
253
+ agreementStatus: row.agreement_status,
254
+ outcomeSource: row.outcome_source,
255
+ evaluatedAt: row.evaluated_at,
256
+ feedRecordedAt: row.feed_recorded_at,
257
+ version: row.version,
258
+ digest: row.latest_digest,
259
+ updatedAt: row.updated_at,
260
+ });
261
+ }
262
+ /**
263
+ * Durable WP20 `would-accept` correlation ledger stored inside Evaluation SQLite
264
+ * (schema 19) alongside notification outcomes.
265
+ */
266
+ export class IntakeEvaluationAgreementLedger {
267
+ #database;
268
+ #now;
269
+ constructor(database, now) {
270
+ this.#database = database;
271
+ this.#now = now;
272
+ }
273
+ #transaction(fn) {
274
+ this.#database.exec('BEGIN IMMEDIATE');
275
+ try {
276
+ const value = fn();
277
+ this.#database.exec('COMMIT');
278
+ return value;
279
+ }
280
+ catch (error) {
281
+ this.#database.exec('ROLLBACK');
282
+ throw error;
283
+ }
284
+ }
285
+ /** Durable incremental feed cursor (`{ afterSeq: 0, afterRecordedAt: 0, afterId: '' }` initially). */
286
+ syncCursor() {
287
+ const row = this.#database.prepare('SELECT after_seq, after_recorded_at, after_id FROM evaluation_intake_evaluation_sync_cursor WHERE id = 1').get();
288
+ return row === undefined
289
+ ? Object.freeze({ afterSeq: 0, afterRecordedAt: 0, afterId: '' })
290
+ : Object.freeze({ afterSeq: row.after_seq, afterRecordedAt: row.after_recorded_at, afterId: row.after_id });
291
+ }
292
+ /** Advance the durable cursor monotonically; identical or regressive writes are ignored/rejected. */
293
+ advanceSyncCursor(next) {
294
+ const normalized = normalizeFeedCursor(next);
295
+ if (normalized === null)
296
+ return false;
297
+ return this.#transaction(() => {
298
+ const existing = this.#database.prepare('SELECT after_seq, after_recorded_at, after_id FROM evaluation_intake_evaluation_sync_cursor WHERE id = 1').get();
299
+ const now = this.#now();
300
+ if (existing === undefined) {
301
+ this.#database.prepare(`INSERT INTO evaluation_intake_evaluation_sync_cursor
302
+ (id, after_seq, after_recorded_at, after_id, updated_at) VALUES (1, ?, ?, ?, ?)`)
303
+ .run(normalized.afterSeq, normalized.afterRecordedAt, normalized.afterId, now);
304
+ return true;
305
+ }
306
+ const prev = {
307
+ afterSeq: existing.after_seq,
308
+ afterRecordedAt: existing.after_recorded_at,
309
+ afterId: existing.after_id,
310
+ };
311
+ if (!cursorAdvances(normalized, prev))
312
+ return false;
313
+ this.#database.prepare(`UPDATE evaluation_intake_evaluation_sync_cursor
314
+ SET after_seq = ?, after_recorded_at = ?, after_id = ?, updated_at = ? WHERE id = 1`)
315
+ .run(normalized.afterSeq, normalized.afterRecordedAt, normalized.afterId, now);
316
+ return true;
317
+ });
318
+ }
319
+ /** Look up local notification / owner feedback signals referencing `itemId`, plus inferred scope if needed. */
320
+ #localSignals(itemId, expectedScopeKey) {
321
+ const signals = [];
322
+ let inferredScope = null;
323
+ const notifRows = this.#database.prepare(`
324
+ SELECT h.notification_id, h.scope_key, h.outcome, h.occurred_at, r.record_json
325
+ FROM evaluation_notification_outcome_heads h
326
+ JOIN evaluation_notification_outcome_revisions r
327
+ ON r.notification_id = h.notification_id AND r.version = h.version
328
+ WHERE json_extract(r.record_json, '$.workItemId') = ?
329
+ AND (? IS NULL OR h.scope_key = ?)
330
+ ORDER BY h.occurred_at DESC, h.version DESC, h.notification_id DESC
331
+ `).all(itemId, expectedScopeKey, expectedScopeKey);
332
+ for (const row of notifRows) {
333
+ if (inferredScope === null) {
334
+ try {
335
+ const parsed = JSON.parse(row.record_json);
336
+ if (parsed?.scope?.workspace && parsed?.scope?.preset) {
337
+ inferredScope = canonicalEvaluationScope({
338
+ workspace: parsed.scope.workspace,
339
+ preset: parsed.scope.preset,
340
+ });
341
+ }
342
+ }
343
+ catch { /* ignore malformed historical record */ }
344
+ }
345
+ if (POSITIVE_NOTIFICATIONS.has(row.outcome) || NEGATIVE_NOTIFICATIONS.has(row.outcome)) {
346
+ signals.push({
347
+ positive: POSITIVE_NOTIFICATIONS.has(row.outcome),
348
+ source: 'notification-outcome',
349
+ at: row.occurred_at,
350
+ authorityRank: AUTHORITY_RANK['notification-outcome'],
351
+ detail: { notificationId: row.notification_id, outcome: row.outcome },
352
+ });
353
+ break;
354
+ }
355
+ }
356
+ const projection = this.#database.prepare(`
357
+ SELECT p.scope_key, p.learning_disposition, p.updated_at,
358
+ o.id AS outcome_id, o.objective_status, o.occurred_at, o.source_kind, o.workspace, o.preset
359
+ FROM evaluation_task_projections p
360
+ JOIN evaluation_outcomes o ON o.id = COALESCE(p.objective_outcome_id, p.primary_outcome_id)
361
+ WHERE p.subject_kind = 'work-item' AND p.subject_ref = ?
362
+ AND o.source_kind = 'user-feedback'
363
+ AND (? IS NULL OR p.scope_key = ?)
364
+ ORDER BY p.updated_at DESC LIMIT 1
365
+ `).get(itemId, expectedScopeKey, expectedScopeKey);
366
+ if (projection !== undefined) {
367
+ if (inferredScope === null) {
368
+ inferredScope = canonicalEvaluationScope({
369
+ workspace: projection.workspace,
370
+ preset: projection.preset,
371
+ });
372
+ }
373
+ if (projection.learning_disposition === 'retract') {
374
+ signals.push({
375
+ positive: false,
376
+ source: 'owner-feedback',
377
+ at: projection.occurred_at,
378
+ authorityRank: AUTHORITY_RANK['owner-feedback'],
379
+ detail: { outcomeId: projection.outcome_id, disposition: 'retract' },
380
+ });
381
+ }
382
+ else if (projection.objective_status === 'achieved' || projection.objective_status === 'not-achieved') {
383
+ signals.push({
384
+ positive: projection.objective_status === 'achieved',
385
+ source: 'owner-feedback',
386
+ at: projection.occurred_at,
387
+ authorityRank: AUTHORITY_RANK['owner-feedback'],
388
+ detail: { outcomeId: projection.outcome_id, objectiveStatus: projection.objective_status },
389
+ });
390
+ }
391
+ }
392
+ return { signals, inferredScope };
393
+ }
394
+ #resolveDecision(itemId, scope, scopeKey, wouldAccept, feedSignals) {
395
+ const candidates = [];
396
+ if (feedSignals.ownerCorrection?.kind === 'withdrawn' || feedSignals.outcome?.ownerWithdrawn) {
397
+ candidates.push({
398
+ positive: false,
399
+ source: 'owner-withdrawal',
400
+ at: feedSignals.ownerCorrection?.recordedAt ?? feedSignals.outcome?.settledAt ?? 0,
401
+ authorityRank: AUTHORITY_RANK['owner-withdrawal'],
402
+ detail: {
403
+ settledBy: 'withdrawn',
404
+ stateReason: feedSignals.ownerCorrection?.stateReason ?? null,
405
+ },
406
+ });
407
+ }
408
+ if (feedSignals.acceptanceVerdict !== null && feedSignals.acceptanceVerdict.objectiveStatus !== 'unknown') {
409
+ candidates.push({
410
+ positive: feedSignals.acceptanceVerdict.objectiveStatus === 'achieved',
411
+ source: 'work-item-verdict',
412
+ at: feedSignals.acceptanceVerdict.recordedAt,
413
+ authorityRank: AUTHORITY_RANK['work-item-verdict'],
414
+ detail: {
415
+ objectiveStatus: feedSignals.acceptanceVerdict.objectiveStatus,
416
+ receiptDigest: feedSignals.acceptanceVerdict.receiptDigest,
417
+ },
418
+ });
419
+ }
420
+ if (feedSignals.outcome !== null && !feedSignals.outcome.ownerWithdrawn) {
421
+ const o = feedSignals.outcome;
422
+ if (o.evidenceState === 'observed' && o.objectiveStatus === 'achieved') {
423
+ candidates.push({
424
+ positive: true,
425
+ source: 'work-item-outcome',
426
+ at: o.recordedAt,
427
+ authorityRank: AUTHORITY_RANK['work-item-outcome'],
428
+ detail: { revision: o.revision, settledBy: o.settledBy, objectiveStatus: o.objectiveStatus },
429
+ });
430
+ }
431
+ else if (o.objectiveStatus === 'not-achieved'
432
+ || o.settledBy === 'report-failed' || o.settledBy === 'retry-exhausted' || o.settledBy === 'report-blocked') {
433
+ candidates.push({
434
+ positive: false,
435
+ source: 'work-item-outcome',
436
+ at: o.recordedAt,
437
+ authorityRank: AUTHORITY_RANK['work-item-outcome'],
438
+ detail: { revision: o.revision, settledBy: o.settledBy, objectiveStatus: o.objectiveStatus },
439
+ });
440
+ }
441
+ }
442
+ let resolvedScope = scope;
443
+ let resolvedScopeKey = scopeKey;
444
+ if (itemId !== null) {
445
+ const local = this.#localSignals(itemId, resolvedScopeKey);
446
+ candidates.push(...local.signals);
447
+ if (resolvedScopeKey === null && local.inferredScope !== null) {
448
+ resolvedScope = local.inferredScope.scope;
449
+ resolvedScopeKey = local.inferredScope.scopeKey;
450
+ }
451
+ }
452
+ candidates.sort((a, b) => (a.at !== b.at ? b.at - a.at : b.authorityRank - a.authorityRank));
453
+ const winning = candidates[0];
454
+ const classified = classifyAgreement(wouldAccept, winning);
455
+ return Object.freeze({
456
+ ...classified,
457
+ winning: winning ?? null,
458
+ scope: resolvedScope,
459
+ scopeKey: resolvedScopeKey,
460
+ });
461
+ }
462
+ #upsertInTx(input) {
463
+ const decision = this.#resolveDecision(input.itemId, input.scope, input.scopeKey, input.wouldAccept, input.feedSignals);
464
+ const canonicalBody = {
465
+ protocol: INTAKE_EVALUATION_AGREEMENT_PROTOCOL,
466
+ evalId: input.evalId,
467
+ source: input.source,
468
+ sourceEventId: input.sourceEventId,
469
+ ruleId: input.ruleId,
470
+ policyVersion: input.policyVersion,
471
+ scopeKey: decision.scopeKey,
472
+ itemId: input.itemId,
473
+ wouldAccept: input.wouldAccept,
474
+ evaluationLevel: input.evaluationLevel,
475
+ mode: input.mode,
476
+ outcomeKind: decision.outcomeKind,
477
+ agreementStatus: decision.agreementStatus,
478
+ outcomeSource: decision.outcomeSource,
479
+ winningSignal: decision.winning,
480
+ feedSignals: input.feedSignals,
481
+ };
482
+ const digest = sha256(canonicalBody);
483
+ const recordJson = canonical(canonicalBody);
484
+ const existing = this.#database.prepare('SELECT * FROM evaluation_intake_evaluation_heads WHERE eval_id = ?')
485
+ .get(input.evalId);
486
+ if (existing === undefined) {
487
+ this.#database.prepare(`INSERT INTO evaluation_intake_evaluation_heads (
488
+ eval_id, source, source_event_id, rule_id, policy_version,
489
+ scope_key, workspace, preset, item_id,
490
+ would_accept, evaluation_level, mode,
491
+ outcome_kind, agreement_status, outcome_source,
492
+ evaluated_at, feed_recorded_at, version, latest_digest, updated_at
493
+ ) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,1,?,?)`).run(input.evalId, input.source, input.sourceEventId, input.ruleId, input.policyVersion, decision.scopeKey, decision.scope?.workspace ?? null, decision.scope?.preset ?? null, input.itemId, input.wouldAccept ? 1 : 0, input.evaluationLevel, input.mode, decision.outcomeKind, decision.agreementStatus, decision.outcomeSource, input.evaluatedAt, input.feedRecordedAt, digest, input.now);
494
+ this.#database.prepare(`INSERT INTO evaluation_intake_evaluation_revisions
495
+ (eval_id, version, outcome_kind, agreement_status, outcome_source, record_digest, record_json, recorded_at)
496
+ VALUES (?,1,?,?,?,?,?,?)`).run(input.evalId, decision.outcomeKind, decision.agreementStatus, decision.outcomeSource, digest, recordJson, input.now);
497
+ const head = this.#database.prepare('SELECT * FROM evaluation_intake_evaluation_heads WHERE eval_id = ?')
498
+ .get(input.evalId);
499
+ return Object.freeze({ head: toStoredHead(head), revised: true });
500
+ }
501
+ if (existing.source !== input.source || existing.source_event_id !== input.sourceEventId
502
+ || existing.rule_id !== input.ruleId || existing.policy_version !== input.policyVersion
503
+ || (existing.would_accept === 1) !== input.wouldAccept || existing.evaluation_level !== input.evaluationLevel
504
+ || existing.evaluated_at !== input.evaluatedAt) {
505
+ throw new EvaluationStoreError('version-conflict', 'immutable intake evaluation fields disagree with persisted head');
506
+ }
507
+ if (existing.latest_digest === digest && input.feedRecordedAt <= existing.feed_recorded_at) {
508
+ return Object.freeze({ head: toStoredHead(existing), revised: false });
509
+ }
510
+ if (existing.latest_digest === digest) {
511
+ return Object.freeze({ head: toStoredHead(existing), revised: false });
512
+ }
513
+ const nextVersion = existing.version + 1;
514
+ const nextFeedRecordedAt = Math.max(existing.feed_recorded_at, input.feedRecordedAt);
515
+ this.#database.prepare(`UPDATE evaluation_intake_evaluation_heads SET
516
+ scope_key = ?, workspace = ?, preset = ?, item_id = ?,
517
+ outcome_kind = ?, agreement_status = ?, outcome_source = ?,
518
+ feed_recorded_at = ?, version = ?, latest_digest = ?, updated_at = ?
519
+ WHERE eval_id = ?`).run(decision.scopeKey, decision.scope?.workspace ?? null, decision.scope?.preset ?? null, input.itemId, decision.outcomeKind, decision.agreementStatus, decision.outcomeSource, nextFeedRecordedAt, nextVersion, digest, input.now, input.evalId);
520
+ this.#database.prepare(`INSERT INTO evaluation_intake_evaluation_revisions
521
+ (eval_id, version, outcome_kind, agreement_status, outcome_source, record_digest, record_json, recorded_at)
522
+ VALUES (?,?,?,?,?,?,?,?)`).run(input.evalId, nextVersion, decision.outcomeKind, decision.agreementStatus, decision.outcomeSource, digest, recordJson, input.now);
523
+ const updated = this.#database.prepare('SELECT * FROM evaluation_intake_evaluation_heads WHERE eval_id = ?')
524
+ .get(input.evalId);
525
+ return Object.freeze({ head: toStoredHead(updated), revised: true });
526
+ }
527
+ /** Validate and apply one feed item against canonical state and local owner outcomes. */
528
+ applyFeedItem(rawItem) {
529
+ const normalized = normalizeFeedItem(rawItem);
530
+ return this.#transaction(() => this.#upsertInTx({
531
+ evalId: normalized.evalId,
532
+ source: normalized.source,
533
+ sourceEventId: normalized.sourceEventId,
534
+ ruleId: normalized.ruleId,
535
+ policyVersion: normalized.policyVersion,
536
+ mode: normalized.mode,
537
+ evaluationLevel: normalized.evaluationLevel,
538
+ wouldAccept: normalized.wouldAccept,
539
+ evaluatedAt: normalized.evaluatedAt,
540
+ feedRecordedAt: normalized.recordedAt,
541
+ itemId: normalized.itemId,
542
+ scope: normalized.scope,
543
+ scopeKey: normalized.scopeKey,
544
+ feedSignals: normalized.feedSignals,
545
+ now: this.#now(),
546
+ }));
547
+ }
548
+ /**
549
+ * Re-evaluate correlations for already-ingested heads that name a `workItemId`
550
+ * so late local notification reactions or owner feedback revisions produce a
551
+ * new immutable agreement revision even without a new WorkItems feed row.
552
+ */
553
+ reconcileLocalCorrelations(limit = 500) {
554
+ const safeLimit = Math.max(1, Math.min(Math.trunc(limit), 2000));
555
+ return this.#transaction(() => {
556
+ const now = this.#now();
557
+ const rows = this.#database.prepare(`
558
+ SELECT h.*, r.record_json
559
+ FROM evaluation_intake_evaluation_heads h
560
+ JOIN evaluation_intake_evaluation_revisions r
561
+ ON r.eval_id = h.eval_id AND r.version = h.version
562
+ WHERE h.item_id IS NOT NULL AND (
563
+ EXISTS (
564
+ SELECT 1 FROM evaluation_notification_outcome_heads nh
565
+ JOIN evaluation_notification_outcome_revisions nr
566
+ ON nr.notification_id = nh.notification_id AND nr.version = nh.version
567
+ WHERE json_extract(nr.record_json, '$.workItemId') = h.item_id
568
+ )
569
+ OR EXISTS (
570
+ SELECT 1 FROM evaluation_task_projections tp
571
+ WHERE tp.subject_kind = 'work-item' AND tp.subject_ref = h.item_id
572
+ )
573
+ )
574
+ ORDER BY h.updated_at ASC, h.eval_id ASC
575
+ LIMIT ?
576
+ `).all(safeLimit);
577
+ let revised = 0;
578
+ for (const row of rows) {
579
+ let feedSignals;
580
+ try {
581
+ const parsed = JSON.parse(row.record_json);
582
+ feedSignals = parsed.feedSignals ?? {
583
+ metadataDigest: '0'.repeat(64),
584
+ sourceDigest: '0'.repeat(64),
585
+ contentDigest: null,
586
+ outcome: null,
587
+ acceptanceVerdict: null,
588
+ ownerCorrection: null,
589
+ };
590
+ }
591
+ catch {
592
+ continue;
593
+ }
594
+ const scope = row.workspace !== null && row.preset !== null
595
+ ? Object.freeze({ workspace: row.workspace, preset: row.preset })
596
+ : null;
597
+ const result = this.#upsertInTx({
598
+ evalId: row.eval_id,
599
+ source: row.source,
600
+ sourceEventId: row.source_event_id,
601
+ ruleId: row.rule_id,
602
+ policyVersion: row.policy_version,
603
+ mode: row.mode,
604
+ evaluationLevel: row.evaluation_level,
605
+ wouldAccept: row.would_accept === 1,
606
+ evaluatedAt: row.evaluated_at,
607
+ feedRecordedAt: row.feed_recorded_at,
608
+ itemId: row.item_id,
609
+ scope,
610
+ scopeKey: row.scope_key,
611
+ feedSignals,
612
+ now,
613
+ });
614
+ if (result.revised)
615
+ revised += 1;
616
+ }
617
+ return Object.freeze({ checked: rows.length, revised });
618
+ });
619
+ }
620
+ /** Total distinct intake evaluation heads persisted. */
621
+ count() {
622
+ const row = this.#database.prepare('SELECT COUNT(*) AS count FROM evaluation_intake_evaluation_heads').get();
623
+ return row.count;
624
+ }
625
+ /** Full revision history for one intake evaluation key or evalId. */
626
+ history(input) {
627
+ const evalId = input.evalId !== undefined
628
+ ? input.evalId
629
+ : input.source && input.sourceEventId && input.ruleId && input.policyVersion
630
+ ? intakeEvaluationCanonicalId(input.source, input.sourceEventId, input.ruleId, input.policyVersion)
631
+ : invalid('history lookup requires evalId or (source, sourceEventId, ruleId, policyVersion)');
632
+ const headRow = this.#database.prepare('SELECT * FROM evaluation_intake_evaluation_heads WHERE eval_id = ?')
633
+ .get(evalId);
634
+ if (headRow === undefined)
635
+ return undefined;
636
+ const revRows = this.#database.prepare(`SELECT eval_id, version, outcome_kind, agreement_status, outcome_source, record_digest, record_json, recorded_at
637
+ FROM evaluation_intake_evaluation_revisions WHERE eval_id = ? ORDER BY version ASC`).all(evalId);
638
+ const revisions = Object.freeze(revRows.map(rev => {
639
+ let feedSignals = {};
640
+ try {
641
+ const parsed = JSON.parse(rev.record_json);
642
+ if (parsed.feedSignals)
643
+ feedSignals = parsed.feedSignals;
644
+ }
645
+ catch { /* ignore */ }
646
+ return Object.freeze({
647
+ evalId: rev.eval_id,
648
+ version: rev.version,
649
+ outcomeKind: rev.outcome_kind,
650
+ agreementStatus: rev.agreement_status,
651
+ outcomeSource: rev.outcome_source,
652
+ digest: rev.record_digest,
653
+ recordedAt: rev.recorded_at,
654
+ feedSignals: Object.freeze(feedSignals),
655
+ });
656
+ }));
657
+ return Object.freeze({ head: toStoredHead(headRow), revisions });
658
+ }
659
+ /** Paginated list of stored canonical intake evaluation agreement heads. */
660
+ list(options = {}) {
661
+ const scopeKey = options.scope === undefined ? null : canonicalEvaluationScope(options.scope).scopeKey;
662
+ const source = options.source === undefined ? null : nonEmptyString(options.source, 'source', 64);
663
+ const ruleId = options.ruleId === undefined ? null : nonEmptyString(options.ruleId, 'ruleId', 256);
664
+ const agreementStatus = options.agreementStatus ?? null;
665
+ const limit = options.limit === undefined ? 100 : Math.max(1, Math.min(Math.trunc(options.limit), 500));
666
+ const hasCursor = options.afterEvaluatedAt !== undefined || options.afterEvalId !== undefined;
667
+ if (hasCursor && (options.afterEvaluatedAt === undefined || options.afterEvalId === undefined)) {
668
+ invalid('afterEvaluatedAt and afterEvalId must be provided together');
669
+ }
670
+ const afterAt = options.afterEvaluatedAt ?? -1;
671
+ const afterId = options.afterEvalId ?? '';
672
+ const rows = this.#database.prepare(`
673
+ SELECT * FROM evaluation_intake_evaluation_heads
674
+ WHERE (? IS NULL OR scope_key = ?)
675
+ AND (? IS NULL OR source = ?)
676
+ AND (? IS NULL OR rule_id = ?)
677
+ AND (? IS NULL OR agreement_status = ?)
678
+ AND (? < 0 OR (evaluated_at, eval_id) > (?, ?))
679
+ ORDER BY evaluated_at ASC, eval_id ASC
680
+ LIMIT ?
681
+ `).all(scopeKey, scopeKey, source, source, ruleId, ruleId, agreementStatus, agreementStatus, afterAt, afterAt, afterId, limit + 1);
682
+ const hasMore = rows.length > limit;
683
+ const items = Object.freeze(rows.slice(0, limit).map(toStoredHead));
684
+ const last = items.at(-1);
685
+ const nextCursor = last === undefined ? null : Object.freeze({ afterEvaluatedAt: last.evaluatedAt, afterEvalId: last.evalId });
686
+ return Object.freeze({ items, hasMore, nextCursor });
687
+ }
688
+ /** Summary metrics over persisted intake evaluations in canonical state. */
689
+ summary(options = {}) {
690
+ const scopeInfo = options.scope === undefined ? null : canonicalEvaluationScope(options.scope);
691
+ const scopeKey = scopeInfo?.scopeKey ?? null;
692
+ const source = options.source === undefined ? null : nonEmptyString(options.source, 'source', 64);
693
+ const ruleId = options.ruleId === undefined ? null : nonEmptyString(options.ruleId, 'ruleId', 256);
694
+ const fromEvaluatedAt = options.fromEvaluatedAt === undefined ? 0 : nonNegInt(options.fromEvaluatedAt, 'fromEvaluatedAt');
695
+ const toEvaluatedAt = options.toEvaluatedAt === undefined ? this.#now() + 1 : nonNegInt(options.toEvaluatedAt, 'toEvaluatedAt');
696
+ if (toEvaluatedAt <= fromEvaluatedAt)
697
+ invalid('summary window is empty or reversed');
698
+ const rows = this.#database.prepare(`
699
+ SELECT agreement_status, COUNT(*) AS count
700
+ FROM evaluation_intake_evaluation_heads
701
+ WHERE (? IS NULL OR scope_key = ?)
702
+ AND (? IS NULL OR source = ?)
703
+ AND (? IS NULL OR rule_id = ?)
704
+ AND evaluated_at >= ? AND evaluated_at < ?
705
+ GROUP BY agreement_status
706
+ `).all(scopeKey, scopeKey, source, source, ruleId, ruleId, fromEvaluatedAt, toEvaluatedAt);
707
+ const countOf = (status) => rows.find(r => r.agreement_status === status)?.count ?? 0;
708
+ const truePositive = countOf('true-positive');
709
+ const falsePositive = countOf('false-positive');
710
+ const falseNegative = countOf('false-negative');
711
+ const trueNegative = countOf('true-negative');
712
+ const pending = countOf('pending');
713
+ const agreed = truePositive + trueNegative;
714
+ const disagreed = falsePositive + falseNegative;
715
+ const decided = agreed + disagreed;
716
+ const acceptedTotal = truePositive + falsePositive;
717
+ const rejectedTotal = trueNegative + falseNegative;
718
+ return Object.freeze({
719
+ protocol: INTAKE_EVALUATION_AGREEMENT_PROTOCOL,
720
+ scope: scopeInfo?.scope ?? null,
721
+ source,
722
+ ruleId,
723
+ fromEvaluatedAt,
724
+ toEvaluatedAt,
725
+ total: decided + pending,
726
+ truePositive,
727
+ falsePositive,
728
+ falseNegative,
729
+ trueNegative,
730
+ pending,
731
+ agreed,
732
+ disagreed,
733
+ decided,
734
+ agreementPpm: decided === 0 ? null : Math.floor((agreed * 1_000_000) / decided),
735
+ falsePositiveRatePpm: acceptedTotal === 0 ? null : Math.floor((falsePositive * 1_000_000) / acceptedTotal),
736
+ falseNegativeRatePpm: rejectedTotal === 0 ? null : Math.floor((falseNegative * 1_000_000) / rejectedTotal),
737
+ });
738
+ }
739
+ }
740
+ //# sourceMappingURL=intake-evaluation-agreement.js.map