@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,1242 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { canonicalEvaluationScope, EvaluationStoreError } from './store.js';
3
+ /**
4
+ * WP22 slice 2: bounded, tighten-only attention tuning with exact-version
5
+ * cohort rollback. A cohort is one notification `(lane, sourceId)` inside one
6
+ * Evaluation scope. Versions are immutable and bound to their exact parent.
7
+ *
8
+ * WP22 slice 3 (explicit opt-in): a loosening request is sealed against a
9
+ * hash-partitioned holdout the proposer never reads, replayed independently
10
+ * on a later tick, and adopted only inside an owner one-time grant; outside
11
+ * it a structured owner question is recorded instead. Without the opt-in,
12
+ * loosening is rejected exactly as in slice 2.
13
+ */
14
+ export const ATTENTION_TUNING_PROTOCOL = 'assistant-evaluation/attention-tuning/v1';
15
+ /** Fixed code constants; neither configuration nor a request can widen them. */
16
+ export const attentionTuningBounds = Object.freeze({
17
+ interruptionCostDelta: Object.freeze({ min: 0, max: 100, step: 10 }),
18
+ minimumUtilityDelta: Object.freeze({ min: 0, max: 100, step: 10 }),
19
+ quietExtensionMinutes: Object.freeze({ min: 0, max: 120, step: 30 }),
20
+ });
21
+ /** Fixed single-step order: cheapest reversible lever first, mute last. */
22
+ export const attentionTuningOrder = Object.freeze(['interruptionCostDelta', 'minimumUtilityDelta', 'quietExtensionMinutes', 'muted']);
23
+ export const defaultAttentionTuningParameters = Object.freeze({
24
+ interruptionCostDelta: 0, minimumUtilityDelta: 0, quietExtensionMinutes: 0, muted: false,
25
+ });
26
+ function invalid(message) {
27
+ throw new EvaluationStoreError('invalid-input', `attention tuning: ${message}`);
28
+ }
29
+ function stable(value) {
30
+ if (value === null || typeof value !== 'object')
31
+ return JSON.stringify(value);
32
+ if (Array.isArray(value))
33
+ return `[${value.map(stable).join(',')}]`;
34
+ const record = value;
35
+ return `{${Object.keys(record).filter(key => record[key] !== undefined).sort()
36
+ .map(key => `${JSON.stringify(key)}:${stable(record[key])}`).join(',')}}`;
37
+ }
38
+ function sha256(value) {
39
+ return createHash('sha256').update(stable(value)).digest('hex');
40
+ }
41
+ function deepFreeze(value) {
42
+ if (value !== null && typeof value === 'object') {
43
+ for (const entry of Object.values(value))
44
+ deepFreeze(entry);
45
+ Object.freeze(value);
46
+ }
47
+ return value;
48
+ }
49
+ function identifier(value, label, max) {
50
+ if (typeof value !== 'string' || value.length < 1 || value.length > max || value.trim() !== value || /\p{Cc}/u.test(value)) {
51
+ invalid(`${label} must be a bounded identifier`);
52
+ }
53
+ return value;
54
+ }
55
+ export function normalizeAttentionCohort(input) {
56
+ if (input === null || typeof input !== 'object' || Array.isArray(input))
57
+ invalid('cohort must be an object');
58
+ const record = input;
59
+ if (Object.keys(record).some(key => key !== 'lane' && key !== 'sourceId'))
60
+ invalid('cohort has unknown fields');
61
+ return Object.freeze({ lane: identifier(record.lane, 'cohort.lane', 64), sourceId: identifier(record.sourceId, 'cohort.sourceId', 256) });
62
+ }
63
+ const INTAKE_RULE_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u;
64
+ const MAX_INTAKE_RULE_UPDATES = 32;
65
+ const OPTIONAL_TUNING_FIELDS = new Set(['workItemsMode', 'intakeRuleUpdates']);
66
+ export function normalizeIntakeRuleUpdates(input) {
67
+ if (!Array.isArray(input) || input.length > MAX_INTAKE_RULE_UPDATES) {
68
+ invalid(`intakeRuleUpdates must be an array of at most ${MAX_INTAKE_RULE_UPDATES} rules`);
69
+ }
70
+ const seen = new Set();
71
+ const normalized = [];
72
+ for (const entry of input) {
73
+ if (entry === null || typeof entry !== 'object' || Array.isArray(entry)) {
74
+ invalid('intakeRuleUpdates entries must be objects');
75
+ }
76
+ const record = entry;
77
+ for (const key of Object.keys(record)) {
78
+ if (!['ruleId', 'enabled', 'mode', 'confidenceThresholdPpm', 'minUtility'].includes(key)) {
79
+ invalid(`intakeRuleUpdates entry has unknown field ${key}`);
80
+ }
81
+ }
82
+ const ruleId = record['ruleId'];
83
+ if (typeof ruleId !== 'string' || !INTAKE_RULE_ID_PATTERN.test(ruleId)) {
84
+ invalid('intakeRuleUpdates.ruleId is invalid');
85
+ }
86
+ if (seen.has(ruleId))
87
+ invalid(`intakeRuleUpdates contains duplicate ruleId ${ruleId}`);
88
+ seen.add(ruleId);
89
+ const enabled = record['enabled'];
90
+ if (enabled !== undefined && typeof enabled !== 'boolean') {
91
+ invalid('intakeRuleUpdates.enabled must be a boolean');
92
+ }
93
+ const mode = record['mode'];
94
+ if (mode !== undefined && mode !== 'observe' && mode !== 'auto') {
95
+ invalid("intakeRuleUpdates.mode must be 'observe' or 'auto'");
96
+ }
97
+ const confidenceThresholdPpm = record['confidenceThresholdPpm'];
98
+ if (confidenceThresholdPpm !== undefined && (typeof confidenceThresholdPpm !== 'number'
99
+ || !Number.isSafeInteger(confidenceThresholdPpm) || confidenceThresholdPpm < 0 || confidenceThresholdPpm > 1_000_000)) {
100
+ invalid('intakeRuleUpdates.confidenceThresholdPpm must be an integer in [0, 1000000]');
101
+ }
102
+ const minUtility = record['minUtility'];
103
+ if (minUtility !== undefined && (typeof minUtility !== 'number' || !Number.isFinite(minUtility))) {
104
+ invalid('intakeRuleUpdates.minUtility must be a finite number');
105
+ }
106
+ normalized.push(Object.freeze({
107
+ ruleId,
108
+ ...(enabled === undefined ? {} : { enabled }),
109
+ ...(mode === undefined ? {} : { mode }),
110
+ ...(confidenceThresholdPpm === undefined ? {} : { confidenceThresholdPpm }),
111
+ ...(minUtility === undefined ? {} : { minUtility }),
112
+ }));
113
+ }
114
+ normalized.sort((a, b) => (a.ruleId < b.ruleId ? -1 : a.ruleId > b.ruleId ? 1 : 0));
115
+ return Object.freeze(normalized);
116
+ }
117
+ /** Strict shape check only; bounds and step alignment are judged separately so a request can be recorded. */
118
+ export function normalizeAttentionTuningParameters(input) {
119
+ if (input === null || typeof input !== 'object' || Array.isArray(input))
120
+ invalid('parameters must be an object');
121
+ const record = input;
122
+ const keys = Object.keys(record);
123
+ for (const key of keys) {
124
+ if (!attentionTuningOrder.includes(key) && !OPTIONAL_TUNING_FIELDS.has(key)) {
125
+ invalid('parameters must name exactly the tunable fields');
126
+ }
127
+ }
128
+ for (const baseKey of attentionTuningOrder) {
129
+ if (!(baseKey in record))
130
+ invalid('parameters must name exactly the tunable fields');
131
+ }
132
+ for (const key of ['interruptionCostDelta', 'minimumUtilityDelta', 'quietExtensionMinutes']) {
133
+ if (!Number.isSafeInteger(record[key]))
134
+ invalid(`${key} must be an integer`);
135
+ }
136
+ if (typeof record.muted !== 'boolean')
137
+ invalid('muted must be a boolean');
138
+ let workItemsMode;
139
+ if (record.workItemsMode !== undefined) {
140
+ if (record.workItemsMode !== 'observe' && record.workItemsMode !== 'auto') {
141
+ invalid("workItemsMode must be 'observe' or 'auto'");
142
+ }
143
+ workItemsMode = record.workItemsMode;
144
+ }
145
+ const intakeRuleUpdates = record.intakeRuleUpdates === undefined
146
+ ? undefined
147
+ : normalizeIntakeRuleUpdates(record.intakeRuleUpdates);
148
+ return deepFreeze({
149
+ interruptionCostDelta: record.interruptionCostDelta,
150
+ minimumUtilityDelta: record.minimumUtilityDelta,
151
+ quietExtensionMinutes: record.quietExtensionMinutes,
152
+ muted: record.muted,
153
+ ...(workItemsMode === undefined ? {} : { workItemsMode }),
154
+ ...(intakeRuleUpdates === undefined ? {} : { intakeRuleUpdates }),
155
+ });
156
+ }
157
+ /** Clamp every numeric field into its fixed bound (snapped down to the step grid). */
158
+ export function clampAttentionTuning(input) {
159
+ const clamp = (key) => {
160
+ const { min, max, step } = attentionTuningBounds[key];
161
+ const value = Math.min(max, Math.max(min, Math.trunc(input[key])));
162
+ return min + Math.floor((value - min) / step) * step;
163
+ };
164
+ const workItemsMode = input.workItemsMode === 'observe' || input.workItemsMode === 'auto'
165
+ ? input.workItemsMode
166
+ : undefined;
167
+ const intakeRuleUpdates = input.intakeRuleUpdates === undefined
168
+ ? undefined
169
+ : normalizeIntakeRuleUpdates(input.intakeRuleUpdates);
170
+ return deepFreeze({
171
+ interruptionCostDelta: clamp('interruptionCostDelta'),
172
+ minimumUtilityDelta: clamp('minimumUtilityDelta'),
173
+ quietExtensionMinutes: clamp('quietExtensionMinutes'),
174
+ muted: input.muted === true,
175
+ ...(workItemsMode === undefined ? {} : { workItemsMode }),
176
+ ...(intakeRuleUpdates === undefined ? {} : { intakeRuleUpdates }),
177
+ });
178
+ }
179
+ export function withinAttentionTuningBounds(input) {
180
+ return stable(clampAttentionTuning(input)) === stable(input);
181
+ }
182
+ function rulesTighterOrEqual(aRules, bRules) {
183
+ const aMap = new Map((aRules ?? []).map(r => [r.ruleId, r]));
184
+ const bMap = new Map((bRules ?? []).map(r => [r.ruleId, r]));
185
+ const ids = new Set([...aMap.keys(), ...bMap.keys()]);
186
+ for (const id of ids) {
187
+ const a = aMap.get(id);
188
+ const b = bMap.get(id);
189
+ const aEnabled = a?.enabled ?? true;
190
+ const bEnabled = b?.enabled ?? true;
191
+ if (aEnabled && !bEnabled)
192
+ return false;
193
+ const aMode = a?.mode ?? 'observe';
194
+ const bMode = b?.mode ?? 'observe';
195
+ if (aMode === 'auto' && bMode === 'observe')
196
+ return false;
197
+ const aConf = a?.confidenceThresholdPpm ?? 0;
198
+ const bConf = b?.confidenceThresholdPpm ?? 0;
199
+ if (aConf < bConf)
200
+ return false;
201
+ const aUtil = a?.minUtility ?? Number.NEGATIVE_INFINITY;
202
+ const bUtil = b?.minUtility ?? Number.NEGATIVE_INFINITY;
203
+ if (aUtil < bUtil)
204
+ return false;
205
+ }
206
+ return true;
207
+ }
208
+ /** True when any field would make notifications more frequent than `current`. */
209
+ export function isAttentionLoosening(current, next) {
210
+ return next.interruptionCostDelta < current.interruptionCostDelta
211
+ || next.minimumUtilityDelta < current.minimumUtilityDelta
212
+ || next.quietExtensionMinutes < current.quietExtensionMinutes
213
+ || (current.muted && !next.muted)
214
+ || ((current.workItemsMode ?? 'observe') === 'observe' && next.workItemsMode === 'auto')
215
+ || !rulesTighterOrEqual(next.intakeRuleUpdates, current.intakeRuleUpdates);
216
+ }
217
+ function atLeastRate(numerator, denominator, ratePpm) {
218
+ return BigInt(numerator) * 1000000n >= BigInt(ratePpm) * BigInt(denominator);
219
+ }
220
+ /**
221
+ * Pure tighten-only tuner. With at least `minSample` decided notifications and
222
+ * a negative (rejected + expired-unhandled) rate at or above the threshold, it
223
+ * proposes exactly one step on the first non-maxed parameter in fixed order;
224
+ * mute additionally requires `muteRatePpm`. Never proposes loosening.
225
+ */
226
+ export function proposeAttentionTuning(currentInput, stats, policy) {
227
+ const current = clampAttentionTuning(currentInput);
228
+ if (stats.decided < policy.minSample || stats.decided === 0)
229
+ return deepFreeze({ kind: 'no-op', reason: 'insufficient-sample' });
230
+ if (!atLeastRate(stats.negative, stats.decided, policy.negativeRatePpm))
231
+ return deepFreeze({ kind: 'no-op', reason: 'below-threshold' });
232
+ for (const parameter of attentionTuningOrder) {
233
+ if (parameter === 'muted') {
234
+ if (current.muted || !atLeastRate(stats.negative, stats.decided, policy.muteRatePpm))
235
+ continue;
236
+ return deepFreeze({ kind: 'tighten', change: { parameter, from: false, to: true }, parameters: { ...current, muted: true } });
237
+ }
238
+ const { max, step } = attentionTuningBounds[parameter];
239
+ if (current[parameter] >= max)
240
+ continue;
241
+ const to = Math.min(max, current[parameter] + step);
242
+ return deepFreeze({ kind: 'tighten', change: { parameter, from: current[parameter], to }, parameters: { ...current, [parameter]: to } });
243
+ }
244
+ return deepFreeze({ kind: 'no-op', reason: 'at-bound' });
245
+ }
246
+ /**
247
+ * Regression test for an observing version: the post-adoption negative rate
248
+ * must exceed the basis (parent-era) rate by more than the margin. Cross
249
+ * multiplication keeps it exact; acceptances only lower the rate, so positive
250
+ * evidence can never satisfy it.
251
+ */
252
+ export function attentionRegressed(basis, post, policy) {
253
+ if (post.decided < policy.minSample || post.decided === 0 || basis.decided === 0)
254
+ return false;
255
+ const left = BigInt(post.negative) * BigInt(basis.decided) * 1000000n;
256
+ const right = BigInt(basis.negative) * BigInt(post.decided) * 1000000n + BigInt(policy.regressionMarginPpm) * BigInt(basis.decided) * BigInt(post.decided);
257
+ return left > right;
258
+ }
259
+ /**
260
+ * WP22 slice 3: sealed holdout partition. Membership is a pure function of the
261
+ * notification id under a fixed protocol salt and modulus, so it is
262
+ * reproducible by any auditor and never chosen by the proposer.
263
+ */
264
+ export const ATTENTION_HOLDOUT_PROTOCOL = 'assistant-evaluation/attention-holdout/v1';
265
+ export const attentionHoldoutModulus = 4;
266
+ export const ATTENTION_LOOSENING_PROTOCOL = 'assistant-evaluation/attention-loosening/v1';
267
+ export const ATTENTION_LOOSENING_GRANT_PROTOCOL = 'assistant-evaluation/attention-loosening-grant/v1';
268
+ export const ATTENTION_OWNER_QUESTION_PROTOCOL = 'assistant-evaluation/attention-owner-question/v1';
269
+ export function attentionHoldoutMember(notificationId) {
270
+ const hex = createHash('sha256').update(`${ATTENTION_HOLDOUT_PROTOCOL}\n${notificationId}`).digest('hex');
271
+ return Number.parseInt(hex.slice(0, 8), 16) % attentionHoldoutModulus === 0;
272
+ }
273
+ /** True when `a` suppresses at least everything `b` suppresses (every field at least as tight). */
274
+ export function attentionTighterOrEqual(a, b) {
275
+ return a.interruptionCostDelta >= b.interruptionCostDelta
276
+ && a.minimumUtilityDelta >= b.minimumUtilityDelta
277
+ && a.quietExtensionMinutes >= b.quietExtensionMinutes
278
+ && (a.muted || !b.muted)
279
+ && ((a.workItemsMode ?? 'observe') === 'observe' || b.workItemsMode === 'auto')
280
+ && rulesTighterOrEqual(a.intakeRuleUpdates, b.intakeRuleUpdates);
281
+ }
282
+ /** One parameter moved toward the default by whole grid steps, or an unmute; anything else is undefined. */
283
+ export function attentionLooseningChange(current, next) {
284
+ const changed = attentionTuningOrder.filter(key => current[key] !== next[key]);
285
+ if ((current.workItemsMode ?? 'observe') !== (next.workItemsMode ?? 'observe'))
286
+ changed.push('workItemsMode');
287
+ if (stable(current.intakeRuleUpdates ?? []) !== stable(next.intakeRuleUpdates ?? []))
288
+ changed.push('intakeRuleUpdates');
289
+ if (changed.length !== 1)
290
+ return undefined;
291
+ const parameter = changed[0];
292
+ if (parameter === 'muted')
293
+ return current.muted && !next.muted ? Object.freeze({ parameter, from: true, to: false, steps: 1 }) : undefined;
294
+ if (parameter === 'workItemsMode') {
295
+ const from = current.workItemsMode ?? 'observe';
296
+ const to = next.workItemsMode ?? 'observe';
297
+ return from === 'observe' && to === 'auto' ? Object.freeze({ parameter, from, to, steps: 1 }) : undefined;
298
+ }
299
+ if (parameter === 'intakeRuleUpdates') {
300
+ const from = current.intakeRuleUpdates ?? Object.freeze([]);
301
+ const to = next.intakeRuleUpdates ?? Object.freeze([]);
302
+ return !rulesTighterOrEqual(to, from) && rulesTighterOrEqual(from, to)
303
+ ? deepFreeze({ parameter, from, to, steps: 1 })
304
+ : undefined;
305
+ }
306
+ const delta = current[parameter] - next[parameter];
307
+ const { step } = attentionTuningBounds[parameter];
308
+ if (delta <= 0 || delta % step !== 0)
309
+ return undefined;
310
+ return Object.freeze({ parameter, from: current[parameter], to: next[parameter], steps: delta / step });
311
+ }
312
+ const positiveOutcomes = ['accepted', 'reacted'];
313
+ /**
314
+ * Deterministic counterfactual replay of a loosening on holdout records.
315
+ * Notifications carry no per-message utility, so each is attributed by the
316
+ * era it was sent under: an era at least as tight as a configuration proves
317
+ * that configuration would also have sent it. Passing requires enough
318
+ * discriminating evidence, an extra-interruption rate below the tuning
319
+ * threshold minus the regression margin, a candidate-wide negative rate below
320
+ * the tightening threshold (so it would not be immediately re-tightened), and
321
+ * more owner-valued notifications recovered than extra interruptions added.
322
+ */
323
+ export function replayAttentionLoosening(records, parent, candidate, policy) {
324
+ const tally = () => ({ decided: 0, positive: 0, negative: 0 });
325
+ const shared = tally();
326
+ const discriminating = tally();
327
+ const unattributable = tally();
328
+ for (const record of records) {
329
+ const positive = positiveOutcomes.includes(record.outcome);
330
+ const negative = negativeOutcomes.includes(record.outcome);
331
+ if (!positive && !negative)
332
+ continue;
333
+ const bucket = attentionTighterOrEqual(record.era, parent) ? shared
334
+ : attentionTighterOrEqual(record.era, candidate) ? discriminating : unattributable;
335
+ bucket.decided += 1;
336
+ if (positive)
337
+ bucket.positive += 1;
338
+ else
339
+ bucket.negative += 1;
340
+ }
341
+ const maxDiscriminatingNegativeRatePpm = Math.max(0, policy.negativeRatePpm - policy.regressionMarginPpm);
342
+ const candidateDecided = shared.decided + discriminating.decided;
343
+ const candidateNegative = shared.negative + discriminating.negative;
344
+ const reason = discriminating.decided < policy.minSample || discriminating.decided === 0 ? 'insufficient-holdout'
345
+ : BigInt(discriminating.negative) * 1000000n > BigInt(maxDiscriminatingNegativeRatePpm) * BigInt(discriminating.decided) ? 'extra-interruptions'
346
+ : atLeastRate(candidateNegative, candidateDecided, policy.negativeRatePpm) ? 'candidate-negative-rate'
347
+ : discriminating.positive <= discriminating.negative ? 'no-net-benefit'
348
+ : undefined;
349
+ return deepFreeze({
350
+ protocol: ATTENTION_LOOSENING_PROTOCOL, shared, discriminating, unattributable,
351
+ parent: { falsePositives: shared.negative, misses: discriminating.positive },
352
+ candidate: { falsePositives: candidateNegative, misses: 0 },
353
+ thresholds: { minSample: policy.minSample, maxDiscriminatingNegativeRatePpm, maxCandidateNegativeRatePpm: policy.negativeRatePpm },
354
+ verdict: reason === undefined ? 'pass' : 'fail',
355
+ ...(reason === undefined ? {} : { reason }),
356
+ });
357
+ }
358
+ export function normalizeAttentionLooseningGrant(input) {
359
+ if (input === null || typeof input !== 'object' || Array.isArray(input))
360
+ invalid('grant must be an object');
361
+ const record = input;
362
+ const fields = ['expiresAt', 'grantId', 'lowerBound', 'maxAdoptions', 'maxStepsPerAdoption', 'upperBound'];
363
+ if (stable(Object.keys(record).sort()) !== stable(fields))
364
+ invalid('grant must name exactly the grant fields');
365
+ const grantId = identifier(record.grantId, 'grant.grantId', 128);
366
+ const lowerBound = normalizeAttentionTuningParameters(record.lowerBound);
367
+ const upperBound = normalizeAttentionTuningParameters(record.upperBound);
368
+ if (!withinAttentionTuningBounds(lowerBound) || !withinAttentionTuningBounds(upperBound))
369
+ invalid('grant bounds must lie on the fixed tuning grid');
370
+ if (!attentionTighterOrEqual(upperBound, lowerBound))
371
+ invalid('grant upperBound must be at least as tight as lowerBound');
372
+ const integer = (key, min, max) => {
373
+ const value = record[key];
374
+ if (!Number.isSafeInteger(value) || value < min || value > max)
375
+ invalid(`grant.${key} must be an integer in [${min}, ${max}]`);
376
+ return value;
377
+ };
378
+ return deepFreeze({
379
+ grantId, lowerBound: { ...lowerBound }, upperBound: { ...upperBound },
380
+ // A sealed proposal moves one parameter by whole grid steps; the widest
381
+ // fixed grid (interruptionCostDelta 0..100 step 10) allows 10. Capping
382
+ // grants lower would make an exact one-time grant impossible to state.
383
+ maxStepsPerAdoption: integer('maxStepsPerAdoption', 1, 10),
384
+ maxAdoptions: integer('maxAdoptions', 1, 10),
385
+ expiresAt: integer('expiresAt', 0, Number.MAX_SAFE_INTEGER),
386
+ });
387
+ }
388
+ /** Every way a holdout-accepted loosening falls outside the active grant; empty means adoptable. */
389
+ export function attentionGrantExceeded(grant, used, parent, candidate, steps, now) {
390
+ if (grant === undefined)
391
+ return Object.freeze(['no-grant']);
392
+ const exceeded = [];
393
+ if (now >= grant.expiresAt)
394
+ exceeded.push('grant-expired');
395
+ if (used >= grant.maxAdoptions)
396
+ exceeded.push('grant-exhausted');
397
+ if (!attentionTighterOrEqual(grant.upperBound, parent) || !attentionTighterOrEqual(candidate, grant.lowerBound))
398
+ exceeded.push('outside-bounds');
399
+ if (steps > grant.maxStepsPerAdoption)
400
+ exceeded.push('step-too-large');
401
+ return Object.freeze(exceeded);
402
+ }
403
+ /** Single-step tightening check for an explicit request. */
404
+ function singleStep(current, next) {
405
+ const changed = attentionTuningOrder.filter(key => current[key] !== next[key]);
406
+ if ((current.workItemsMode ?? 'observe') !== (next.workItemsMode ?? 'observe'))
407
+ changed.push('workItemsMode');
408
+ if (stable(current.intakeRuleUpdates ?? []) !== stable(next.intakeRuleUpdates ?? []))
409
+ changed.push('intakeRuleUpdates');
410
+ if (changed.length !== 1)
411
+ return undefined;
412
+ const parameter = changed[0];
413
+ if (parameter === 'muted')
414
+ return { parameter, from: current.muted, to: next.muted };
415
+ if (parameter === 'workItemsMode') {
416
+ const from = current.workItemsMode ?? 'observe';
417
+ const to = next.workItemsMode ?? 'observe';
418
+ return from === 'auto' && to === 'observe' ? { parameter, from, to } : undefined;
419
+ }
420
+ if (parameter === 'intakeRuleUpdates') {
421
+ const from = current.intakeRuleUpdates ?? Object.freeze([]);
422
+ const to = next.intakeRuleUpdates ?? Object.freeze([]);
423
+ return rulesTighterOrEqual(to, from) && !rulesTighterOrEqual(from, to) ? { parameter, from, to } : undefined;
424
+ }
425
+ if (next[parameter] - current[parameter] !== attentionTuningBounds[parameter].step)
426
+ return undefined;
427
+ return { parameter, from: current[parameter], to: next[parameter] };
428
+ }
429
+ function versionDigest(input) {
430
+ return sha256({
431
+ protocol: input.protocol, scopeKey: input.scopeKey, cohort: input.cohort, version: input.version,
432
+ parentVersion: input.parentVersion, parentDigest: input.parentDigest, parameters: input.parameters,
433
+ basis: input.basis, change: input.change, origin: input.origin,
434
+ });
435
+ }
436
+ const negativeOutcomes = ['rejected', 'expired-unhandled'];
437
+ /**
438
+ * Cohort filter: a linked-alias fallback report reached the owner on another
439
+ * channel, so its outcome says nothing about the origin cohort's parameters.
440
+ * Stats, holdout seals/replays and cohort discovery all use this filter;
441
+ * route-free (pre-existing) records count as origin.
442
+ */
443
+ const originRoute = `coalesce(json_extract(r.record_json, '$.route.kind'), 'origin')='origin'`;
444
+ /**
445
+ * Durable ledger over the same Evaluation database as the notification canon.
446
+ * All decisions recompute inside BEGIN IMMEDIATE so concurrent ticks or a
447
+ * restart mid-observation converge on one head.
448
+ */
449
+ export class AttentionTuningLedger {
450
+ #database;
451
+ #now;
452
+ #questions;
453
+ constructor(database, now, questions) {
454
+ this.#database = database;
455
+ this.#now = now;
456
+ this.#questions = questions;
457
+ }
458
+ #transaction(fn) {
459
+ this.#database.exec('BEGIN IMMEDIATE');
460
+ try {
461
+ const value = fn();
462
+ this.#database.exec('COMMIT');
463
+ return value;
464
+ }
465
+ catch (error) {
466
+ this.#database.exec('ROLLBACK');
467
+ throw error;
468
+ }
469
+ }
470
+ /** Current-head (id, outcome, notifiedAt) rows for one cohort, notified in [from, to), in id order. */
471
+ #records(scopeKey, cohort, fromNotifiedAt, toNotifiedAt, includeIntake = false) {
472
+ if (cohort.lane === 'intake' && includeIntake) {
473
+ const rows = this.#database.prepare(`
474
+ SELECT eval_id, would_accept, outcome_kind, agreement_status, evaluated_at
475
+ FROM evaluation_intake_evaluation_heads
476
+ WHERE scope_key=? AND (source=? OR (source || ':' || rule_id)=?) AND evaluated_at>=? AND evaluated_at<?
477
+ ORDER BY eval_id
478
+ `).all(scopeKey, cohort.sourceId, cohort.sourceId, fromNotifiedAt, toNotifiedAt);
479
+ return rows.map(row => ({
480
+ notification_id: row.eval_id,
481
+ outcome: row.outcome_kind === 'pending'
482
+ ? 'delivered'
483
+ : row.agreement_status === 'true-positive' || row.agreement_status === 'false-negative'
484
+ ? 'accepted'
485
+ : 'rejected',
486
+ occurred_at: row.evaluated_at,
487
+ counterfactual: row.would_accept === 0,
488
+ }));
489
+ }
490
+ const rows = this.#database.prepare(`SELECT h.notification_id AS notification_id, h.outcome AS outcome, h.occurred_at AS occurred_at
491
+ FROM evaluation_notification_outcome_heads h
492
+ JOIN evaluation_notification_outcome_revisions r ON r.notification_id=h.notification_id AND r.version=h.version
493
+ WHERE h.scope_key=? AND h.occurred_at>=? AND h.occurred_at<?
494
+ AND json_extract(r.record_json, '$.lane')=? AND json_extract(r.record_json, '$.sourceId')=?
495
+ AND ${originRoute}
496
+ ORDER BY h.notification_id`).all(scopeKey, fromNotifiedAt, toNotifiedAt, cohort.lane, cohort.sourceId);
497
+ return rows.map(row => ({ ...row, counterfactual: false }));
498
+ }
499
+ /** Holdout membership for a window: ids only. Outcomes are deliberately not part of the seal. */
500
+ #holdout(scopeKey, cohort, fromNotifiedAt, toNotifiedAt, includeIntake = false) {
501
+ const ids = this.#records(scopeKey, cohort, fromNotifiedAt, toNotifiedAt, includeIntake)
502
+ .map(row => row.notification_id)
503
+ .filter(attentionHoldoutMember);
504
+ const digest = sha256({ protocol: ATTENTION_HOLDOUT_PROTOCOL, modulus: attentionHoldoutModulus, scopeKey, cohort: { lane: cohort.lane, sourceId: cohort.sourceId },
505
+ fromNotifiedAt, toNotifiedAt, ids });
506
+ return deepFreeze({ ids, seal: { protocol: ATTENTION_HOLDOUT_PROTOCOL, modulus: attentionHoldoutModulus, count: ids.length, digest } });
507
+ }
508
+ /**
509
+ * Current-head outcome counts for one cohort, notified in [from, to).
510
+ * `training` excludes the sealed holdout partition; every proposer uses it
511
+ * once the slice-3 opt-in is on, so no proposal is fitted to holdout data.
512
+ */
513
+ stats(scopeKey, cohort, fromNotifiedAt, toNotifiedAt, partition = 'all', options = {}) {
514
+ const includeIntake = options.includeIntake ?? false;
515
+ const includeCounterfactual = options.includeCounterfactual ?? false;
516
+ if (partition === 'training' || (cohort.lane === 'intake' && includeIntake)) {
517
+ const counts = new Map();
518
+ for (const row of this.#records(scopeKey, cohort, fromNotifiedAt, toNotifiedAt, includeIntake)) {
519
+ if (partition === 'training' && attentionHoldoutMember(row.notification_id))
520
+ continue;
521
+ if (row.counterfactual && !includeCounterfactual)
522
+ continue;
523
+ counts.set(row.outcome, (counts.get(row.outcome) ?? 0) + 1);
524
+ }
525
+ return this.#summarize(fromNotifiedAt, toNotifiedAt, [...counts].map(([outcome, count]) => ({ outcome, count })));
526
+ }
527
+ const rows = this.#database.prepare(`SELECT h.outcome AS outcome, COUNT(*) AS count
528
+ FROM evaluation_notification_outcome_heads h
529
+ JOIN evaluation_notification_outcome_revisions r ON r.notification_id=h.notification_id AND r.version=h.version
530
+ WHERE h.scope_key=? AND h.occurred_at>=? AND h.occurred_at<?
531
+ AND json_extract(r.record_json, '$.lane')=? AND json_extract(r.record_json, '$.sourceId')=?
532
+ AND ${originRoute}
533
+ GROUP BY h.outcome`).all(scopeKey, fromNotifiedAt, toNotifiedAt, cohort.lane, cohort.sourceId);
534
+ return this.#summarize(fromNotifiedAt, toNotifiedAt, rows);
535
+ }
536
+ #summarize(fromNotifiedAt, toNotifiedAt, rows) {
537
+ const count = (outcome) => rows.find(row => row.outcome === outcome)?.count ?? 0;
538
+ const accepted = count('accepted');
539
+ const reacted = count('reacted');
540
+ const rejected = count('rejected');
541
+ const expiredUnhandled = count('expired-unhandled');
542
+ return Object.freeze({
543
+ fromNotifiedAt, toNotifiedAt,
544
+ total: rows.reduce((sum, row) => sum + row.count, 0),
545
+ accepted, reacted, rejected, expiredUnhandled,
546
+ decided: accepted + reacted + rejected + expiredUnhandled,
547
+ negative: negativeOutcomes.reduce((sum, outcome) => sum + count(outcome), 0),
548
+ });
549
+ }
550
+ /** Scopes that have at least one notification (or synced intake evaluation) in the cohort, plus scopes with a tuning head. */
551
+ scopes(cohort, includeIntake = false) {
552
+ if (cohort.lane === 'intake' && includeIntake) {
553
+ const rows = this.#database.prepare(`SELECT DISTINCT workspace, preset
554
+ FROM evaluation_intake_evaluation_heads
555
+ WHERE scope_key IS NOT NULL AND workspace IS NOT NULL AND preset IS NOT NULL
556
+ AND (source=? OR (source || ':' || rule_id)=?)
557
+ UNION SELECT workspace, preset FROM evaluation_attention_tuning_heads WHERE lane=? AND source_id=?
558
+ ORDER BY workspace, preset`).all(cohort.sourceId, cohort.sourceId, cohort.lane, cohort.sourceId);
559
+ return Object.freeze(rows.map(row => Object.freeze({ workspace: row.workspace, preset: row.preset })));
560
+ }
561
+ const rows = this.#database.prepare(`SELECT DISTINCT json_extract(r.record_json, '$.scope.workspace') AS workspace,
562
+ json_extract(r.record_json, '$.scope.preset') AS preset
563
+ FROM evaluation_notification_outcome_heads h
564
+ JOIN evaluation_notification_outcome_revisions r ON r.notification_id=h.notification_id AND r.version=h.version
565
+ WHERE json_extract(r.record_json, '$.lane')=? AND json_extract(r.record_json, '$.sourceId')=? AND ${originRoute}
566
+ UNION SELECT workspace, preset FROM evaluation_attention_tuning_heads WHERE lane=? AND source_id=?
567
+ ORDER BY workspace, preset`).all(cohort.lane, cohort.sourceId, cohort.lane, cohort.sourceId);
568
+ return Object.freeze(rows.map(row => Object.freeze({ workspace: row.workspace, preset: row.preset })));
569
+ }
570
+ /** Known `intake` cohorts from synced WP20 evaluations or existing tuning/loosening state. */
571
+ intakeCohorts() {
572
+ const rows = this.#database.prepare(`
573
+ SELECT source AS source_id FROM evaluation_intake_evaluation_heads WHERE scope_key IS NOT NULL
574
+ UNION SELECT source_id FROM evaluation_attention_tuning_heads WHERE lane='intake'
575
+ UNION SELECT source_id FROM evaluation_attention_loosening_proposals WHERE lane='intake'
576
+ UNION SELECT source_id FROM evaluation_attention_loosening_grants WHERE lane='intake'
577
+ ORDER BY source_id
578
+ `).all();
579
+ return Object.freeze(rows.map(row => Object.freeze({ lane: 'intake', sourceId: row.source_id })));
580
+ }
581
+ #scopeWatermark(scopeKey) {
582
+ return this.#database.prepare('SELECT watermark FROM evaluation_notification_watermarks WHERE scope_key=?')
583
+ .get(scopeKey)?.watermark ?? 0;
584
+ }
585
+ #head(scopeKey, cohort) {
586
+ return this.#database.prepare('SELECT * FROM evaluation_attention_tuning_heads WHERE scope_key=? AND lane=? AND source_id=?')
587
+ .get(scopeKey, cohort.lane, cohort.sourceId);
588
+ }
589
+ #row(scopeKey, cohort, version) {
590
+ return this.#database.prepare('SELECT * FROM evaluation_attention_tuning_versions WHERE scope_key=? AND lane=? AND source_id=? AND version=?')
591
+ .get(scopeKey, cohort.lane, cohort.sourceId, version);
592
+ }
593
+ /** Parse and digest-verify one stored version; undefined when unreadable or tampered. */
594
+ #verified(scopeKey, cohort, version) {
595
+ const row = this.#row(scopeKey, cohort, version);
596
+ if (row === undefined)
597
+ return undefined;
598
+ try {
599
+ const parentDigest = row.parent_version === 0 ? null : this.#row(scopeKey, cohort, row.parent_version)?.digest ?? null;
600
+ if (row.parent_version !== 0 && parentDigest === null)
601
+ return undefined;
602
+ const parameters = normalizeAttentionTuningParameters(JSON.parse(row.parameters_json));
603
+ if (!withinAttentionTuningBounds(parameters))
604
+ return undefined;
605
+ const body = {
606
+ protocol: ATTENTION_TUNING_PROTOCOL, scopeKey, cohort: { lane: cohort.lane, sourceId: cohort.sourceId }, version: row.version,
607
+ parentVersion: row.parent_version, parentDigest, parameters,
608
+ basis: JSON.parse(row.basis_json),
609
+ change: JSON.parse(row.change_json), origin: row.origin,
610
+ };
611
+ if (versionDigest(body) !== row.digest)
612
+ return undefined;
613
+ return deepFreeze({ ...body, digest: row.digest, createdAt: row.created_at });
614
+ }
615
+ catch {
616
+ return undefined;
617
+ }
618
+ }
619
+ #versionNumbers(scopeKey, cohort) {
620
+ return this.#database.prepare('SELECT version FROM evaluation_attention_tuning_versions WHERE scope_key=? AND lane=? AND source_id=? ORDER BY version')
621
+ .all(scopeKey, cohort.lane, cohort.sourceId).map(row => row.version);
622
+ }
623
+ /**
624
+ * Active parameters for a consumer. A version that cannot be read or fails
625
+ * digest verification falls back along its recorded parent chain, then to
626
+ * the built-in default; a consumer never sees an unverified overlay.
627
+ */
628
+ current(scopeInput, cohortInput) {
629
+ const { scopeKey } = canonicalEvaluationScope(scopeInput);
630
+ const cohort = normalizeAttentionCohort(cohortInput);
631
+ return this.#current(scopeKey, cohort);
632
+ }
633
+ #current(scopeKey, cohort) {
634
+ const active = this.#head(scopeKey, cohort)?.active_version ?? 0;
635
+ let version = active;
636
+ let fallback = false;
637
+ const seen = new Set();
638
+ while (version > 0 && !seen.has(version)) {
639
+ seen.add(version);
640
+ const verified = this.#verified(scopeKey, cohort, version);
641
+ if (verified !== undefined) {
642
+ return deepFreeze({ scopeKey, cohort: { ...cohort }, version, digest: verified.digest, parameters: { ...verified.parameters }, source: fallback ? 'parent-fallback' : 'active' });
643
+ }
644
+ fallback = true;
645
+ const parent = this.#database.prepare('SELECT parent_version FROM evaluation_attention_tuning_versions WHERE scope_key=? AND lane=? AND source_id=? AND version=?')
646
+ .get(scopeKey, cohort.lane, cohort.sourceId, version)?.parent_version;
647
+ version = Number.isSafeInteger(parent) && parent >= 0 && parent < version ? parent : 0;
648
+ }
649
+ return deepFreeze({ scopeKey, cohort: { ...cohort }, version: 0, digest: null, parameters: { ...defaultAttentionTuningParameters }, source: active === 0 ? 'active' : 'default' });
650
+ }
651
+ status(scopeInput, cohortInput, eventLimit = 50) {
652
+ const { scopeKey } = canonicalEvaluationScope(scopeInput);
653
+ const cohort = normalizeAttentionCohort(cohortInput);
654
+ const head = this.#head(scopeKey, cohort);
655
+ const versions = this.#versionNumbers(scopeKey, cohort)
656
+ .map(version => this.#verified(scopeKey, cohort, version)).filter(value => value !== undefined);
657
+ const events = this.#database.prepare(`SELECT sequence, kind, from_version, to_version, reason, detail_json, occurred_at
658
+ FROM evaluation_attention_tuning_events WHERE scope_key=? AND lane=? AND source_id=? ORDER BY sequence DESC LIMIT ?`)
659
+ .all(scopeKey, cohort.lane, cohort.sourceId, eventLimit).reverse().map(row => ({
660
+ sequence: row.sequence, kind: row.kind, fromVersion: row.from_version, toVersion: row.to_version,
661
+ reason: row.reason, detail: JSON.parse(row.detail_json), occurredAt: row.occurred_at,
662
+ }));
663
+ return deepFreeze({
664
+ current: this.#current(scopeKey, cohort),
665
+ state: head?.state ?? 'idle',
666
+ ...(head?.observe_from == null ? {} : { observeFrom: head.observe_from }),
667
+ ...(head?.observe_until == null ? {} : { observeUntil: head.observe_until }),
668
+ versions, events,
669
+ });
670
+ }
671
+ #event(scopeKey, cohort, kind, fromVersion, toVersion, reason, detail, idempotencyKey, now) {
672
+ this.#database.prepare(`INSERT INTO evaluation_attention_tuning_events
673
+ (scope_key, lane, source_id, kind, from_version, to_version, reason, detail_json, idempotency_key, occurred_at) VALUES (?,?,?,?,?,?,?,?,?,?)
674
+ ON CONFLICT(idempotency_key) DO NOTHING`)
675
+ .run(scopeKey, cohort.lane, cohort.sourceId, kind, fromVersion, toVersion, reason, stable(detail), idempotencyKey, now);
676
+ }
677
+ #adopt(scope, scopeKey, cohort, head, current, proposal, stats, origin, observationMs, now, loosening) {
678
+ // Parent is the verified version the consumer is actually running.
679
+ const parentVersion = current.version;
680
+ const scopeWatermark = this.#scopeWatermark(scopeKey);
681
+ const idempotencyKey = `adopt:${sha256([scopeKey, cohort.lane, cohort.sourceId, parentVersion, current.digest, scopeWatermark, proposal.change, origin,
682
+ ...(loosening === undefined ? [] : [loosening.proposalId])])}`;
683
+ const existing = this.#database.prepare('SELECT version FROM evaluation_attention_tuning_versions WHERE idempotency_key=?')
684
+ .get(idempotencyKey);
685
+ if (existing !== undefined)
686
+ return existing.version;
687
+ const version = (head?.latest_version ?? 0) + 1;
688
+ const body = {
689
+ protocol: ATTENTION_TUNING_PROTOCOL, scopeKey, cohort: { lane: cohort.lane, sourceId: cohort.sourceId }, version,
690
+ parentVersion, parentDigest: current.digest, parameters: proposal.parameters,
691
+ basis: { stats, scopeWatermark }, change: proposal.change, origin,
692
+ };
693
+ const digest = versionDigest(body);
694
+ this.#database.prepare(`INSERT INTO evaluation_attention_tuning_versions
695
+ (scope_key, lane, source_id, version, parent_version, parameters_json, basis_json, change_json, origin, digest, idempotency_key, created_at)
696
+ VALUES (?,?,?,?,?,?,?,?,?,?,?,?)`).run(scopeKey, cohort.lane, cohort.sourceId, version, parentVersion, stable(body.parameters), stable(body.basis), stable(body.change), origin, digest, idempotencyKey, now);
697
+ const observeUntil = now + observationMs;
698
+ if (head === undefined) {
699
+ this.#database.prepare(`INSERT INTO evaluation_attention_tuning_heads
700
+ (scope_key, lane, source_id, workspace, preset, active_version, latest_version, state, observing_version, observe_from, observe_until, changed_at)
701
+ VALUES (?,?,?,?,?,?,?, 'observing', ?,?,?,?)`).run(scopeKey, cohort.lane, cohort.sourceId, scope.workspace, scope.preset, version, version, version, now, observeUntil, now);
702
+ }
703
+ else {
704
+ this.#database.prepare(`UPDATE evaluation_attention_tuning_heads SET active_version=?, latest_version=?, state='observing',
705
+ observing_version=?, observe_from=?, observe_until=?, changed_at=? WHERE scope_key=? AND lane=? AND source_id=?`)
706
+ .run(version, version, version, now, observeUntil, now, scopeKey, cohort.lane, cohort.sourceId);
707
+ }
708
+ this.#event(scopeKey, cohort, 'adopted', parentVersion, version, loosening !== undefined ? 'holdout-accepted' : origin === 'auto' ? 'negative-rate-threshold' : 'owner-request', { digest, change: proposal.change, stats, scopeWatermark, ...loosening }, idempotencyKey, now);
709
+ return version;
710
+ }
711
+ /**
712
+ * One deterministic step for one cohort: monitor an observing version
713
+ * (rollback to its exact parent on regression, settle at window end), or
714
+ * when idle propose and adopt a single bounded tightening step.
715
+ */
716
+ tick(scopeInput, cohortInput, policy, options) {
717
+ const { scope, scopeKey } = canonicalEvaluationScope(scopeInput);
718
+ const cohort = normalizeAttentionCohort(cohortInput);
719
+ const includeIntake = options.includeIntakeEvaluations ?? options.loosening?.includeIntakeEvaluations ?? false;
720
+ return this.#transaction(() => {
721
+ const now = this.#now();
722
+ const head = this.#head(scopeKey, cohort);
723
+ if (head?.state === 'observing') {
724
+ const observed = head.observing_version;
725
+ const version = this.#verified(scopeKey, cohort, observed);
726
+ const post = this.stats(scopeKey, cohort, head.observe_from, now + 1, 'all', { includeIntake });
727
+ // An unverifiable observing version is reverted exactly like a regression.
728
+ if (version === undefined || attentionRegressed(version.basis.stats, post, policy)) {
729
+ const parent = this.#database.prepare('SELECT parent_version FROM evaluation_attention_tuning_versions WHERE scope_key=? AND lane=? AND source_id=? AND version=?')
730
+ .get(scopeKey, cohort.lane, cohort.sourceId, observed)?.parent_version ?? 0;
731
+ this.#database.prepare(`UPDATE evaluation_attention_tuning_heads SET active_version=?, state='idle', observing_version=NULL,
732
+ observe_from=NULL, observe_until=NULL, changed_at=? WHERE scope_key=? AND lane=? AND source_id=?`)
733
+ .run(parent, now, scopeKey, cohort.lane, cohort.sourceId);
734
+ this.#event(scopeKey, cohort, 'rolled-back', observed, parent, version === undefined ? 'version-unverifiable' : 'negative-rate-regressed', { basis: version?.basis.stats ?? null, post }, `rollback:${sha256([scopeKey, cohort.lane, cohort.sourceId, observed, parent])}`, now);
735
+ return Object.freeze({ action: 'rolled-back', fromVersion: observed, toVersion: parent });
736
+ }
737
+ if (now >= head.observe_until) {
738
+ this.#database.prepare(`UPDATE evaluation_attention_tuning_heads SET state='idle', observing_version=NULL,
739
+ observe_from=NULL, observe_until=NULL, changed_at=? WHERE scope_key=? AND lane=? AND source_id=?`)
740
+ .run(now, scopeKey, cohort.lane, cohort.sourceId);
741
+ this.#event(scopeKey, cohort, 'settled', observed, observed, 'observation-complete', { post }, `settle:${sha256([scopeKey, cohort.lane, cohort.sourceId, observed, head.observe_from])}`, now);
742
+ return Object.freeze({ action: 'settled', version: observed });
743
+ }
744
+ return Object.freeze({ action: 'observing', version: observed });
745
+ }
746
+ if (options.loosening !== undefined) {
747
+ // A sealed loosening proposal is judged before any new tightening so
748
+ // its parent cannot move underneath it.
749
+ const pending = this.#pendingProposal(scopeKey, cohort);
750
+ if (pending !== undefined)
751
+ return this.#decideLoosening(scope, scopeKey, cohort, head, pending, policy, options.loosening, options.observationMs, now, includeIntake);
752
+ }
753
+ const current = this.#current(scopeKey, cohort);
754
+ // Evidence is only counted since the last change, so an adopted or
755
+ // rolled-back version is never re-judged on its predecessor's sample.
756
+ const from = Math.max(0, head?.changed_at ?? 0, now - options.evaluationWindowMs);
757
+ const stats = this.stats(scopeKey, cohort, from, now + 1, options.loosening === undefined ? 'all' : 'training', { includeIntake });
758
+ const proposal = proposeAttentionTuning(current.parameters, stats, policy);
759
+ if (proposal.kind === 'no-op')
760
+ return Object.freeze({ action: 'no-op', reason: proposal.reason });
761
+ const version = this.#adopt(scope, scopeKey, cohort, head, current, proposal, stats, 'auto', options.observationMs, now);
762
+ return Object.freeze({ action: 'adopted', version, change: proposal.change });
763
+ });
764
+ }
765
+ /**
766
+ * Explicit parameter request. Any loosening field is rejected with
767
+ * `loosening-requires-holdout` and recorded; so is every other rejection.
768
+ * A single in-bounds tightening step is adopted with an observation window.
769
+ */
770
+ request(scopeInput, cohortInput, parametersInput, options) {
771
+ const { scope, scopeKey } = canonicalEvaluationScope(scopeInput);
772
+ const cohort = normalizeAttentionCohort(cohortInput);
773
+ const requested = normalizeAttentionTuningParameters(parametersInput);
774
+ const includeIntake = options.includeIntakeEvaluations ?? options.loosening?.includeIntakeEvaluations ?? false;
775
+ return this.#transaction(() => {
776
+ const now = this.#now();
777
+ const head = this.#head(scopeKey, cohort);
778
+ const current = this.#current(scopeKey, cohort);
779
+ if (options.loosening !== undefined && isAttentionLoosening(current.parameters, requested)) {
780
+ return this.#proposeLoosening(scopeKey, cohort, head, current, requested, options.enabled, options.loosening, now, includeIntake);
781
+ }
782
+ const change = singleStep(current.parameters, requested);
783
+ const reason = isAttentionLoosening(current.parameters, requested) ? 'loosening-requires-holdout'
784
+ : !withinAttentionTuningBounds(requested) ? 'out-of-bounds'
785
+ : stable(requested) === stable(current.parameters) ? 'no-change'
786
+ : change === undefined ? 'not-single-step'
787
+ : !options.enabled ? 'auto-adoption-disabled'
788
+ : head?.state === 'observing' ? 'observation-in-progress'
789
+ : undefined;
790
+ if (reason !== undefined || change === undefined) {
791
+ const code = reason ?? 'not-single-step';
792
+ this.#event(scopeKey, cohort, 'request-rejected', current.version, current.version, code, { current: current.parameters, requested }, null, now);
793
+ return Object.freeze({ status: 'rejected', reason: code });
794
+ }
795
+ const stats = this.stats(scopeKey, cohort, Math.max(0, head?.changed_at ?? 0, now - options.evaluationWindowMs), now + 1, options.loosening === undefined ? 'all' : 'training', { includeIntake });
796
+ const version = this.#adopt(scope, scopeKey, cohort, head, current, { change, parameters: requested }, stats, 'request', options.observationMs, now);
797
+ return deepFreeze({ status: 'adopted', version, change });
798
+ });
799
+ }
800
+ /**
801
+ * Slice 3 loosening request: validate, then seal a proposal that names the
802
+ * holdout membership by digest only. Nothing is adopted here; a later tick
803
+ * replays the holdout independently and checks the owner grant.
804
+ */
805
+ #proposeLoosening(scopeKey, cohort, head, current, requested, enabled, loosening, now, includeIntake = false) {
806
+ const change = attentionLooseningChange(current.parameters, requested);
807
+ const reason = !withinAttentionTuningBounds(requested) ? 'out-of-bounds'
808
+ : change === undefined ? 'not-single-parameter'
809
+ : !enabled ? 'auto-adoption-disabled'
810
+ : head?.state === 'observing' ? 'observation-in-progress'
811
+ : this.#pendingProposal(scopeKey, cohort) !== undefined ? 'proposal-pending'
812
+ : this.#openQuestion(scopeKey, cohort) ? 'owner-question-pending'
813
+ : undefined;
814
+ if (reason !== undefined || change === undefined) {
815
+ const code = reason ?? 'not-single-parameter';
816
+ this.#event(scopeKey, cohort, 'request-rejected', current.version, current.version, code, { current: current.parameters, requested }, null, now);
817
+ return Object.freeze({ status: 'rejected', reason: code });
818
+ }
819
+ const window = { fromNotifiedAt: Math.max(0, now - loosening.replayWindowMs), toNotifiedAt: now + 1 };
820
+ const holdout = this.#holdout(scopeKey, cohort, window.fromNotifiedAt, window.toNotifiedAt, includeIntake);
821
+ const body = {
822
+ protocol: ATTENTION_LOOSENING_PROTOCOL, scopeKey, cohort: { lane: cohort.lane, sourceId: cohort.sourceId },
823
+ ordinal: this.#database.prepare(`SELECT COUNT(*) AS count FROM evaluation_attention_loosening_proposals
824
+ WHERE scope_key=? AND lane=? AND source_id=?`).get(scopeKey, cohort.lane, cohort.sourceId).count + 1,
825
+ parentVersion: current.version, parentDigest: current.digest, parent: { ...current.parameters }, candidate: { ...requested },
826
+ change: { parameter: change.parameter, from: change.from, to: change.to }, steps: change.steps, window,
827
+ holdout: holdout.seal,
828
+ basis: {
829
+ stats: this.stats(scopeKey, cohort, window.fromNotifiedAt, window.toNotifiedAt, 'training', {
830
+ includeIntake,
831
+ includeCounterfactual: cohort.lane === 'intake' && includeIntake,
832
+ }),
833
+ scopeWatermark: this.#scopeWatermark(scopeKey),
834
+ },
835
+ createdAt: now,
836
+ };
837
+ const proposalId = sha256(body);
838
+ this.#database.prepare(`INSERT INTO evaluation_attention_loosening_proposals
839
+ (proposal_id, scope_key, lane, source_id, parent_version, proposal_json, holdout_digest, created_at) VALUES (?,?,?,?,?,?,?,?)`)
840
+ .run(proposalId, scopeKey, cohort.lane, cohort.sourceId, current.version, stable(body), holdout.seal.digest, now);
841
+ return deepFreeze({ status: 'proposed', proposalId, holdout: { ...holdout.seal } });
842
+ }
843
+ #pendingProposal(scopeKey, cohort) {
844
+ return this.#database.prepare(`SELECT p.* FROM evaluation_attention_loosening_proposals p
845
+ LEFT JOIN evaluation_attention_loosening_decisions d ON d.proposal_id=p.proposal_id
846
+ WHERE p.scope_key=? AND p.lane=? AND p.source_id=? AND d.proposal_id IS NULL
847
+ ORDER BY p.created_at, p.rowid LIMIT 1`).get(scopeKey, cohort.lane, cohort.sourceId);
848
+ }
849
+ /**
850
+ * A recorded owner reply closes the question even though the grant row it
851
+ * was asked under is unchanged; only a different grant or a reply closes
852
+ * it, and the latest question stays open until then.
853
+ */
854
+ #openQuestion(scopeKey, cohort) {
855
+ const question = this.#database.prepare(`SELECT question_id, question_json FROM evaluation_attention_owner_questions
856
+ WHERE scope_key=? AND lane=? AND source_id=? ORDER BY created_at DESC, rowid DESC LIMIT 1`)
857
+ .get(scopeKey, cohort.lane, cohort.sourceId);
858
+ if (question === undefined)
859
+ return false;
860
+ let parsed;
861
+ try {
862
+ parsed = JSON.parse(question.question_json);
863
+ }
864
+ catch {
865
+ return true;
866
+ }
867
+ return parsed.grantId === this.#latestGrantId(scopeKey, cohort) && !this.#replied(question.question_id);
868
+ }
869
+ /** True once any reply (authorize or decline) is recorded for this exact question. */
870
+ #replied(questionId) {
871
+ return this.#database.prepare('SELECT 1 AS present FROM evaluation_attention_owner_question_replies WHERE question_id=?')
872
+ .get(questionId) !== undefined;
873
+ }
874
+ /**
875
+ * WP22 slice 4: the latest owner question of a cohort, verified against its
876
+ * content id, and whether it is still open (same rule as `#openQuestion`,
877
+ * including the slice-5 rule that any recorded reply closes it). Older
878
+ * questions are always closed. A row whose body no longer hashes to its id
879
+ * is reported as `unverifiable` and must never be delivered.
880
+ */
881
+ latestOwnerQuestion(scopeInput, cohortInput) {
882
+ const { scopeKey } = canonicalEvaluationScope(scopeInput);
883
+ const cohort = normalizeAttentionCohort(cohortInput);
884
+ const row = this.#database.prepare(`SELECT question_id, question_json FROM evaluation_attention_owner_questions
885
+ WHERE scope_key=? AND lane=? AND source_id=? ORDER BY created_at DESC, rowid DESC LIMIT 1`)
886
+ .get(scopeKey, cohort.lane, cohort.sourceId);
887
+ if (row === undefined)
888
+ return undefined;
889
+ let question;
890
+ try {
891
+ question = JSON.parse(row.question_json);
892
+ }
893
+ catch {
894
+ return 'unverifiable';
895
+ }
896
+ if (sha256(question) !== row.question_id || question.protocol !== ATTENTION_OWNER_QUESTION_PROTOCOL
897
+ || question.scopeKey !== scopeKey || question.cohort?.lane !== cohort.lane || question.cohort?.sourceId !== cohort.sourceId)
898
+ return 'unverifiable';
899
+ return deepFreeze({ questionId: row.question_id, question,
900
+ open: question.grantId === this.#latestGrantId(scopeKey, cohort) && !this.#replied(row.question_id) });
901
+ }
902
+ #latestGrantId(scopeKey, cohort) {
903
+ return this.#database.prepare(`SELECT grant_id FROM evaluation_attention_loosening_grants
904
+ WHERE scope_key=? AND lane=? AND source_id=? ORDER BY created_at DESC, rowid DESC LIMIT 1`)
905
+ .get(scopeKey, cohort.lane, cohort.sourceId)?.grant_id ?? null;
906
+ }
907
+ /**
908
+ * Slice 5 evidence-backed apply path for one exact owner reply. Inside one
909
+ * transaction it verifies the cohort's latest question against its content
910
+ * id, records the reply, and then:
911
+ * - `decline` writes the proposal's one terminal `owner-declined` decision;
912
+ * - `authorize-once` creates a bounded one-time grant whose bounds are
913
+ * exactly the questioned proposal's parent/candidate, charged once, and
914
+ * leaves adoption to the next tuning tick's independent holdout replay;
915
+ * - a proposal that already has a decision (a question recorded before the
916
+ * reply loop was enabled) returns `proposal-terminal` and changes nothing.
917
+ * Record-only callers keep using `AttentionOwnerQuestionLedger.recordReply`.
918
+ */
919
+ applyOwnerQuestionReply(scopeInput, cohortInput, questionIdInput, choiceInput, options) {
920
+ const { scope, scopeKey } = canonicalEvaluationScope(scopeInput);
921
+ const cohort = normalizeAttentionCohort(cohortInput);
922
+ if (typeof questionIdInput !== 'string' || !/^[a-f0-9]{64}$/u.test(questionIdInput))
923
+ invalid('question id is not recognised');
924
+ const choice = choiceInput === 'authorize-once' || choiceInput === 'decline'
925
+ ? choiceInput : undefined;
926
+ if (choice === undefined)
927
+ invalid('choice is not recognised');
928
+ if (!Number.isSafeInteger(options.noticeTtlMs) || options.noticeTtlMs < 1)
929
+ invalid('owner question notice TTL is invalid');
930
+ const questions = this.#questions;
931
+ if (questions === undefined)
932
+ invalid('owner question ledger is unavailable');
933
+ return this.#transaction(() => {
934
+ const now = this.#now();
935
+ const latest = this.latestOwnerQuestion(scope, cohort);
936
+ if (latest === undefined || latest === 'unverifiable' || latest.questionId !== questionIdInput) {
937
+ return Object.freeze({ status: 'rejected', reason: 'unknown-question' });
938
+ }
939
+ const question = latest.question;
940
+ const questionId = latest.questionId;
941
+ const expired = now >= question.createdAt + options.noticeTtlMs;
942
+ const reply = questions.recordReplyInTransaction(scope, cohort, questionId, choice, latest.open, expired);
943
+ if (reply.status === 'rejected')
944
+ return reply;
945
+ const decided = this.#database.prepare('SELECT 1 AS present FROM evaluation_attention_loosening_decisions WHERE proposal_id=?')
946
+ .get(question.proposalId) !== undefined;
947
+ if (decided) {
948
+ return Object.freeze({ status: 'applied', questionId: questionId, choice,
949
+ proposalId: question.proposalId, grantId: null, adoption: 'proposal-terminal' });
950
+ }
951
+ if (choice === 'decline') {
952
+ const version = this.#current(scopeKey, cohort).version;
953
+ this.#decision(scopeKey, cohort, question.proposalId, 'rejected', 'owner-declined', null, null, question.replay, now);
954
+ this.#event(scopeKey, cohort, 'request-rejected', version, version, 'owner-declined', { proposalId: question.proposalId, questionId: questionId, choice }, `owner-question:${questionId}`, now);
955
+ return Object.freeze({ status: 'applied', questionId: questionId, choice,
956
+ proposalId: question.proposalId, grantId: null, adoption: 'declined' });
957
+ }
958
+ // Exactly the questioned proposal: parent as the tightest start, its
959
+ // candidate as the loosest end, one adoption, the proposal's step size.
960
+ const grant = normalizeAttentionLooseningGrant({
961
+ grantId: `owner-question:${questionId}`,
962
+ lowerBound: { ...question.candidate }, upperBound: { ...question.parent },
963
+ maxStepsPerAdoption: question.steps, maxAdoptions: 1, expiresAt: now + options.noticeTtlMs,
964
+ });
965
+ const digest = this.#grantDigest(scopeKey, cohort, grant);
966
+ const existing = this.#database.prepare(`SELECT digest FROM evaluation_attention_loosening_grants
967
+ WHERE scope_key=? AND lane=? AND source_id=? AND grant_id=?`)
968
+ .get(scopeKey, cohort.lane, cohort.sourceId, grant.grantId);
969
+ if (existing === undefined) {
970
+ this.#database.prepare(`INSERT INTO evaluation_attention_loosening_grants
971
+ (scope_key, lane, source_id, grant_id, grant_json, digest, created_at) VALUES (?,?,?,?,?,?,?)`)
972
+ .run(scopeKey, cohort.lane, cohort.sourceId, grant.grantId, stable(grant), digest, now);
973
+ }
974
+ else if (existing.digest !== digest) {
975
+ // Rolls the recorded reply back with this transaction; never leaves an
976
+ // authorization pointing at a grant id it did not create.
977
+ invalid('owner question grant conflicts with an existing grant');
978
+ }
979
+ return Object.freeze({ status: 'applied', questionId: questionId, choice,
980
+ proposalId: question.proposalId, grantId: grant.grantId, adoption: 'deferred' });
981
+ });
982
+ }
983
+ #verifiedProposal(row, scopeKey, cohort) {
984
+ try {
985
+ const body = JSON.parse(row.proposal_json);
986
+ if (sha256(body) !== row.proposal_id || body.protocol !== ATTENTION_LOOSENING_PROTOCOL || body.scopeKey !== scopeKey
987
+ || body.cohort.lane !== cohort.lane || body.cohort.sourceId !== cohort.sourceId || body.parentVersion !== row.parent_version
988
+ || body.holdout.digest !== row.holdout_digest || body.holdout.protocol !== ATTENTION_HOLDOUT_PROTOCOL || body.holdout.modulus !== attentionHoldoutModulus)
989
+ return undefined;
990
+ const parent = normalizeAttentionTuningParameters(body.parent);
991
+ const candidate = normalizeAttentionTuningParameters(body.candidate);
992
+ const change = attentionLooseningChange(parent, candidate);
993
+ if (!withinAttentionTuningBounds(parent) || !withinAttentionTuningBounds(candidate) || change === undefined || change.steps !== body.steps)
994
+ return undefined;
995
+ return deepFreeze(body);
996
+ }
997
+ catch {
998
+ return undefined;
999
+ }
1000
+ }
1001
+ #grantDigest(scopeKey, cohort, grant) {
1002
+ return sha256({ protocol: ATTENTION_LOOSENING_GRANT_PROTOCOL, scopeKey, cohort: { lane: cohort.lane, sourceId: cohort.sourceId }, grant });
1003
+ }
1004
+ /** Latest grant for the cohort; `unverifiable` when its stored body fails the digest. */
1005
+ #activeGrant(scopeKey, cohort) {
1006
+ const row = this.#database.prepare(`SELECT grant_id, grant_json, digest, created_at FROM evaluation_attention_loosening_grants
1007
+ WHERE scope_key=? AND lane=? AND source_id=? ORDER BY created_at DESC, rowid DESC LIMIT 1`)
1008
+ .get(scopeKey, cohort.lane, cohort.sourceId);
1009
+ if (row === undefined)
1010
+ return undefined;
1011
+ try {
1012
+ const grant = normalizeAttentionLooseningGrant(JSON.parse(row.grant_json));
1013
+ if (grant.grantId !== row.grant_id || this.#grantDigest(scopeKey, cohort, grant) !== row.digest)
1014
+ return 'unverifiable';
1015
+ return Object.freeze({ grant, digest: row.digest, createdAt: row.created_at });
1016
+ }
1017
+ catch {
1018
+ return 'unverifiable';
1019
+ }
1020
+ }
1021
+ /** Adoptions charged to a grant. Decisions are immutable, so a rollback never refunds quota. */
1022
+ #grantUsed(scopeKey, cohort, grantId) {
1023
+ return this.#database.prepare(`SELECT COUNT(*) AS count FROM evaluation_attention_loosening_decisions
1024
+ WHERE scope_key=? AND lane=? AND source_id=? AND grant_id=? AND decision='adopted'`)
1025
+ .get(scopeKey, cohort.lane, cohort.sourceId, grantId).count;
1026
+ }
1027
+ /** Parameters in force at a notification time, from the append-only adopted/rolled-back events. */
1028
+ #eraResolver(scopeKey, cohort) {
1029
+ const changes = this.#database.prepare(`SELECT to_version, occurred_at FROM evaluation_attention_tuning_events
1030
+ WHERE scope_key=? AND lane=? AND source_id=? AND kind IN ('adopted','rolled-back') ORDER BY sequence`)
1031
+ .all(scopeKey, cohort.lane, cohort.sourceId);
1032
+ const cache = new Map();
1033
+ return notifiedAt => {
1034
+ let version = 0;
1035
+ for (const change of changes)
1036
+ if (change.occurred_at <= notifiedAt)
1037
+ version = change.to_version;
1038
+ if (version === 0)
1039
+ return defaultAttentionTuningParameters;
1040
+ if (!cache.has(version))
1041
+ cache.set(version, this.#verified(scopeKey, cohort, version)?.parameters);
1042
+ return cache.get(version);
1043
+ };
1044
+ }
1045
+ #decision(scopeKey, cohort, proposalId, decision, reason, grantId, version, replay, now) {
1046
+ this.#database.prepare(`INSERT INTO evaluation_attention_loosening_decisions
1047
+ (proposal_id, scope_key, lane, source_id, decision, reason, grant_id, version, replay_json, decided_at) VALUES (?,?,?,?,?,?,?,?,?,?)`)
1048
+ .run(proposalId, scopeKey, cohort.lane, cohort.sourceId, decision, reason, grantId, version, stable(replay), now);
1049
+ }
1050
+ /**
1051
+ * Independent acceptance of one sealed proposal: verify it, require the
1052
+ * exact parent still in force, recompute holdout membership against the
1053
+ * frozen digest, replay parent vs candidate on holdout outcomes only, then
1054
+ * adopt inside the owner grant or record an owner question. Every outcome
1055
+ * is one immutable decision row plus a schema-15 tuning event.
1056
+ */
1057
+ #decideLoosening(scope, scopeKey, cohort, head, row, policy, loosening, observationMs, now, includeIntake = false) {
1058
+ const proposalId = row.proposal_id;
1059
+ const current = this.#current(scopeKey, cohort);
1060
+ const reject = (reason, replay) => {
1061
+ this.#decision(scopeKey, cohort, proposalId, 'rejected', reason, null, null, replay, now);
1062
+ this.#event(scopeKey, cohort, 'request-rejected', current.version, current.version, reason, { proposalId, replay }, `loosening:${proposalId}`, now);
1063
+ return Object.freeze({ action: 'loosening-rejected', reason, proposalId });
1064
+ };
1065
+ const proposal = this.#verifiedProposal(row, scopeKey, cohort);
1066
+ if (proposal === undefined)
1067
+ return reject('proposal-unverifiable', null);
1068
+ if (current.version !== proposal.parentVersion || current.digest !== proposal.parentDigest
1069
+ || stable(current.parameters) !== stable(proposal.parent))
1070
+ return reject('stale-parent', null);
1071
+ if (proposal.basis.stats.decided < policy.minSample)
1072
+ return reject('insufficient-basis', null);
1073
+ const { fromNotifiedAt, toNotifiedAt } = proposal.window;
1074
+ const holdout = this.#holdout(scopeKey, cohort, fromNotifiedAt, toNotifiedAt, includeIntake);
1075
+ if (holdout.seal.digest !== proposal.holdout.digest)
1076
+ return reject('holdout-drifted', null);
1077
+ const members = new Set(holdout.ids);
1078
+ const era = this.#eraResolver(scopeKey, cohort);
1079
+ const records = [];
1080
+ for (const record of this.#records(scopeKey, cohort, fromNotifiedAt, toNotifiedAt, includeIntake)) {
1081
+ if (!members.has(record.notification_id))
1082
+ continue;
1083
+ const parameters = era(record.occurred_at);
1084
+ if (parameters === undefined)
1085
+ return reject('era-unverifiable', null);
1086
+ const effectiveParameters = record.counterfactual && attentionTighterOrEqual(parameters, proposal.parent)
1087
+ ? proposal.candidate
1088
+ : parameters;
1089
+ records.push({ era: effectiveParameters, outcome: record.outcome });
1090
+ }
1091
+ const replay = replayAttentionLoosening(records, proposal.parent, proposal.candidate, policy);
1092
+ if (replay.verdict === 'fail')
1093
+ return reject('holdout-failed', replay);
1094
+ const active = this.#activeGrant(scopeKey, cohort);
1095
+ const grant = active === 'unverifiable' ? undefined : active?.grant;
1096
+ const exceeded = active === 'unverifiable' ? ['grant-unverifiable']
1097
+ : attentionGrantExceeded(grant, grant === undefined ? 0 : this.#grantUsed(scopeKey, cohort, grant.grantId), proposal.parent, proposal.candidate, proposal.steps, now);
1098
+ if (exceeded.length > 0 || grant === undefined) {
1099
+ const replyLoop = loosening.ownerQuestionReplyLoop;
1100
+ if (replyLoop !== undefined) {
1101
+ const existing = this.#ownerQuestionForProposal(proposalId, scopeKey, cohort);
1102
+ if (existing === 'unverifiable')
1103
+ return reject('proposal-unverifiable', replay);
1104
+ if (existing !== undefined) {
1105
+ // Slice 5 deferred state: the proposal stays undecided while the
1106
+ // question is open, so the next tick can still adopt it. A terminal
1107
+ // decision is written only on decline, unusable authorization or
1108
+ // notice TTL expiry, never on first sight. Its event uses the
1109
+ // question-scoped key because the question-created event already
1110
+ // holds the proposal-scoped key.
1111
+ const terminate = (reason) => {
1112
+ this.#decision(scopeKey, cohort, proposalId, 'rejected', reason, null, null, replay, now);
1113
+ this.#event(scopeKey, cohort, 'request-rejected', current.version, current.version, reason, { proposalId, questionId: existing.questionId, replay }, `owner-question:${existing.questionId}`, now);
1114
+ return Object.freeze({ action: 'loosening-rejected', reason, proposalId });
1115
+ };
1116
+ const reply = this.#questions?.reply(existing.questionId);
1117
+ if (reply?.choice === 'decline')
1118
+ return terminate('owner-declined');
1119
+ if (reply?.choice === 'authorize-once')
1120
+ return terminate('owner-authorization-unusable');
1121
+ if (now >= existing.question.createdAt + replyLoop.noticeTtlMs)
1122
+ return terminate('owner-question-expired');
1123
+ return deepFreeze({ action: 'owner-question', questionId: existing.questionId, proposalId, exceeded: [...exceeded] });
1124
+ }
1125
+ const askedUnder = this.#latestGrantId(scopeKey, cohort);
1126
+ const body = {
1127
+ protocol: ATTENTION_OWNER_QUESTION_PROTOCOL, kind: 'attention-loosening-authorization', scopeKey,
1128
+ cohort: { lane: cohort.lane, sourceId: cohort.sourceId }, proposalId,
1129
+ parentVersion: proposal.parentVersion, parentDigest: proposal.parentDigest, parent: proposal.parent, candidate: proposal.candidate,
1130
+ change: proposal.change, steps: proposal.steps, replay, exceeded: [...exceeded], grantId: askedUnder,
1131
+ choices: ['authorize-once', 'decline'], delivery: 'not-sent', createdAt: now,
1132
+ };
1133
+ const questionId = sha256(body);
1134
+ this.#database.prepare(`INSERT INTO evaluation_attention_owner_questions
1135
+ (question_id, proposal_id, scope_key, lane, source_id, question_json, created_at) VALUES (?,?,?,?,?,?,?)`)
1136
+ .run(questionId, proposalId, scopeKey, cohort.lane, cohort.sourceId, stable(body), now);
1137
+ // No decision row: the deferred proposal remains pending until the
1138
+ // reply or TTL closes it, so a one-time grant can still adopt it.
1139
+ this.#event(scopeKey, cohort, 'request-rejected', current.version, current.version, 'loosening-requires-owner', { proposalId, questionId, exceeded }, `loosening:${proposalId}`, now);
1140
+ return deepFreeze({ action: 'owner-question', questionId, proposalId, exceeded: [...exceeded] });
1141
+ }
1142
+ const askedUnder = this.#latestGrantId(scopeKey, cohort);
1143
+ const body = {
1144
+ protocol: ATTENTION_OWNER_QUESTION_PROTOCOL, kind: 'attention-loosening-authorization', scopeKey,
1145
+ cohort: { lane: cohort.lane, sourceId: cohort.sourceId }, proposalId,
1146
+ parentVersion: proposal.parentVersion, parentDigest: proposal.parentDigest, parent: proposal.parent, candidate: proposal.candidate,
1147
+ change: proposal.change, steps: proposal.steps, replay, exceeded: [...exceeded], grantId: askedUnder,
1148
+ choices: ['authorize-once', 'decline'], delivery: 'not-sent', createdAt: now,
1149
+ };
1150
+ const questionId = sha256(body);
1151
+ this.#database.prepare(`INSERT INTO evaluation_attention_owner_questions
1152
+ (question_id, proposal_id, scope_key, lane, source_id, question_json, created_at) VALUES (?,?,?,?,?,?,?)`)
1153
+ .run(questionId, proposalId, scopeKey, cohort.lane, cohort.sourceId, stable(body), now);
1154
+ this.#decision(scopeKey, cohort, proposalId, 'owner-question', 'loosening-requires-owner', askedUnder, null, replay, now);
1155
+ this.#event(scopeKey, cohort, 'request-rejected', current.version, current.version, 'loosening-requires-owner', { proposalId, questionId, exceeded }, `loosening:${proposalId}`, now);
1156
+ return deepFreeze({ action: 'owner-question', questionId, proposalId, exceeded: [...exceeded] });
1157
+ }
1158
+ const version = this.#adopt(scope, scopeKey, cohort, head, current, { change: proposal.change, parameters: proposal.candidate }, proposal.basis.stats, 'request', observationMs, now, { proposalId, grantId: grant.grantId });
1159
+ this.#decision(scopeKey, cohort, proposalId, 'adopted', 'holdout-accepted', grant.grantId, version, replay, now);
1160
+ return deepFreeze({ action: 'loosening-adopted', version, change: { ...proposal.change }, proposalId, grantId: grant.grantId });
1161
+ }
1162
+ /** One immutable question row for a proposal, verified against its content id. */
1163
+ #ownerQuestionForProposal(proposalId, scopeKey, cohort) {
1164
+ const row = this.#database.prepare(`SELECT question_id, question_json FROM evaluation_attention_owner_questions
1165
+ WHERE proposal_id=? AND scope_key=? AND lane=? AND source_id=?`)
1166
+ .get(proposalId, scopeKey, cohort.lane, cohort.sourceId);
1167
+ if (row === undefined)
1168
+ return undefined;
1169
+ try {
1170
+ const question = JSON.parse(row.question_json);
1171
+ if (sha256(question) !== row.question_id || question.protocol !== ATTENTION_OWNER_QUESTION_PROTOCOL
1172
+ || question.proposalId !== proposalId || question.scopeKey !== scopeKey
1173
+ || question.cohort?.lane !== cohort.lane || question.cohort?.sourceId !== cohort.sourceId)
1174
+ return 'unverifiable';
1175
+ return deepFreeze({ questionId: row.question_id, question });
1176
+ }
1177
+ catch {
1178
+ return 'unverifiable';
1179
+ }
1180
+ }
1181
+ /**
1182
+ * Record an owner one-time pre-authorization. Grants are immutable; the
1183
+ * latest one is active and its quota is never refunded. Re-sending the same
1184
+ * grant is idempotent; reusing an id with different content is rejected.
1185
+ */
1186
+ grant(scopeInput, cohortInput, grantInput) {
1187
+ const { scopeKey } = canonicalEvaluationScope(scopeInput);
1188
+ const cohort = normalizeAttentionCohort(cohortInput);
1189
+ const grant = normalizeAttentionLooseningGrant(grantInput);
1190
+ return this.#transaction(() => {
1191
+ const now = this.#now();
1192
+ const digest = this.#grantDigest(scopeKey, cohort, grant);
1193
+ const existing = this.#database.prepare(`SELECT digest FROM evaluation_attention_loosening_grants
1194
+ WHERE scope_key=? AND lane=? AND source_id=? AND grant_id=?`).get(scopeKey, cohort.lane, cohort.sourceId, grant.grantId);
1195
+ if (existing !== undefined) {
1196
+ return existing.digest === digest ? Object.freeze({ status: 'granted', grantId: grant.grantId, digest })
1197
+ : Object.freeze({ status: 'rejected', reason: 'grant-conflict' });
1198
+ }
1199
+ if (now >= grant.expiresAt)
1200
+ return Object.freeze({ status: 'rejected', reason: 'grant-expired' });
1201
+ this.#database.prepare(`INSERT INTO evaluation_attention_loosening_grants
1202
+ (scope_key, lane, source_id, grant_id, grant_json, digest, created_at) VALUES (?,?,?,?,?,?,?)`)
1203
+ .run(scopeKey, cohort.lane, cohort.sourceId, grant.grantId, stable(grant), digest, now);
1204
+ return Object.freeze({ status: 'granted', grantId: grant.grantId, digest });
1205
+ });
1206
+ }
1207
+ looseningStatus(scopeInput, cohortInput, limit = 50) {
1208
+ const { scopeKey } = canonicalEvaluationScope(scopeInput);
1209
+ const cohort = normalizeAttentionCohort(cohortInput);
1210
+ const active = this.#activeGrant(scopeKey, cohort);
1211
+ const grant = active === undefined || active === 'unverifiable' ? null : (() => {
1212
+ const used = this.#grantUsed(scopeKey, cohort, active.grant.grantId);
1213
+ return { ...active, used, remaining: Math.max(0, active.grant.maxAdoptions - used) };
1214
+ })();
1215
+ const rows = this.#database.prepare(`SELECT * FROM evaluation_attention_loosening_proposals
1216
+ WHERE scope_key=? AND lane=? AND source_id=? ORDER BY created_at DESC, rowid DESC LIMIT ?`)
1217
+ .all(scopeKey, cohort.lane, cohort.sourceId, limit).reverse();
1218
+ const proposals = rows.flatMap(row => {
1219
+ const proposal = this.#verifiedProposal(row, scopeKey, cohort);
1220
+ if (proposal === undefined)
1221
+ return [];
1222
+ const decided = this.#database.prepare(`SELECT decision, reason, grant_id, version, replay_json, decided_at
1223
+ FROM evaluation_attention_loosening_decisions WHERE proposal_id=?`).get(row.proposal_id);
1224
+ const decision = decided === undefined ? null : {
1225
+ decision: decided.decision, reason: decided.reason, grantId: decided.grant_id, version: decided.version,
1226
+ replay: JSON.parse(decided.replay_json), decidedAt: decided.decided_at,
1227
+ };
1228
+ return [{ proposalId: row.proposal_id, proposal, decision }];
1229
+ });
1230
+ const questions = this.#database.prepare(`SELECT question_id, question_json FROM evaluation_attention_owner_questions
1231
+ WHERE scope_key=? AND lane=? AND source_id=? ORDER BY created_at DESC, rowid DESC LIMIT ?`)
1232
+ .all(scopeKey, cohort.lane, cohort.sourceId, limit).reverse()
1233
+ .map(row => ({ questionId: row.question_id, question: JSON.parse(row.question_json) }));
1234
+ return deepFreeze({ grant, proposals, questions });
1235
+ }
1236
+ counts() {
1237
+ const versions = this.#database.prepare('SELECT COUNT(*) AS count FROM evaluation_attention_tuning_versions').get();
1238
+ const events = this.#database.prepare('SELECT COUNT(*) AS count FROM evaluation_attention_tuning_events').get();
1239
+ return { versions: versions.count, events: events.count };
1240
+ }
1241
+ }
1242
+ //# sourceMappingURL=attention-tuning.js.map