@dsh-ray/assistant-association 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 (120) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +132 -1
  3. package/cordis.patch.yml +26 -0
  4. package/lib/aho-corasick.d.ts +41 -0
  5. package/lib/aho-corasick.d.ts.map +1 -0
  6. package/lib/aho-corasick.js +352 -0
  7. package/lib/aho-corasick.js.map +1 -0
  8. package/lib/bm25.d.ts +17 -0
  9. package/lib/bm25.d.ts.map +1 -0
  10. package/lib/bm25.js +73 -0
  11. package/lib/bm25.js.map +1 -0
  12. package/lib/clustering.d.ts +161 -0
  13. package/lib/clustering.d.ts.map +1 -0
  14. package/lib/clustering.js +1043 -0
  15. package/lib/clustering.js.map +1 -0
  16. package/lib/config.d.ts +67 -0
  17. package/lib/config.d.ts.map +1 -0
  18. package/lib/config.js +834 -0
  19. package/lib/config.js.map +1 -0
  20. package/lib/cues.d.ts +134 -0
  21. package/lib/cues.d.ts.map +1 -0
  22. package/lib/cues.js +793 -0
  23. package/lib/cues.js.map +1 -0
  24. package/lib/dreaming.d.ts +211 -0
  25. package/lib/dreaming.d.ts.map +1 -0
  26. package/lib/dreaming.js +1418 -0
  27. package/lib/dreaming.js.map +1 -0
  28. package/lib/entities.d.ts +18 -0
  29. package/lib/entities.d.ts.map +1 -0
  30. package/lib/entities.js +111 -0
  31. package/lib/entities.js.map +1 -0
  32. package/lib/eval-pool.d.ts +111 -0
  33. package/lib/eval-pool.d.ts.map +1 -0
  34. package/lib/eval-pool.js +392 -0
  35. package/lib/eval-pool.js.map +1 -0
  36. package/lib/hebbian.d.ts +54 -0
  37. package/lib/hebbian.d.ts.map +1 -0
  38. package/lib/hebbian.js +226 -0
  39. package/lib/hebbian.js.map +1 -0
  40. package/lib/holdout.d.ts +18 -0
  41. package/lib/holdout.d.ts.map +1 -0
  42. package/lib/holdout.js +97 -0
  43. package/lib/holdout.js.map +1 -0
  44. package/lib/hot-path.d.ts +8 -0
  45. package/lib/hot-path.d.ts.map +1 -0
  46. package/lib/hot-path.js +503 -0
  47. package/lib/hot-path.js.map +1 -0
  48. package/lib/hysteresis.d.ts +39 -0
  49. package/lib/hysteresis.d.ts.map +1 -0
  50. package/lib/hysteresis.js +297 -0
  51. package/lib/hysteresis.js.map +1 -0
  52. package/lib/index-memory.d.ts +112 -0
  53. package/lib/index-memory.d.ts.map +1 -0
  54. package/lib/index-memory.js +391 -0
  55. package/lib/index-memory.js.map +1 -0
  56. package/lib/index.d.ts +37 -0
  57. package/lib/index.d.ts.map +1 -0
  58. package/lib/index.js +37 -0
  59. package/lib/index.js.map +1 -0
  60. package/lib/intake-signal.d.ts +158 -0
  61. package/lib/intake-signal.d.ts.map +1 -0
  62. package/lib/intake-signal.js +366 -0
  63. package/lib/intake-signal.js.map +1 -0
  64. package/lib/param-tuning.d.ts +302 -0
  65. package/lib/param-tuning.d.ts.map +1 -0
  66. package/lib/param-tuning.js +1743 -0
  67. package/lib/param-tuning.js.map +1 -0
  68. package/lib/service.d.ts +164 -0
  69. package/lib/service.d.ts.map +1 -0
  70. package/lib/service.js +2071 -0
  71. package/lib/service.js.map +1 -0
  72. package/lib/sources.d.ts +42 -0
  73. package/lib/sources.d.ts.map +1 -0
  74. package/lib/sources.js +2024 -0
  75. package/lib/sources.js.map +1 -0
  76. package/lib/sqlite.d.ts +88 -0
  77. package/lib/sqlite.d.ts.map +1 -0
  78. package/lib/sqlite.js +1815 -0
  79. package/lib/sqlite.js.map +1 -0
  80. package/lib/tokenize.d.ts +4 -0
  81. package/lib/tokenize.d.ts.map +1 -0
  82. package/lib/tokenize.js +35 -0
  83. package/lib/tokenize.js.map +1 -0
  84. package/lib/tools.d.ts +27 -0
  85. package/lib/tools.d.ts.map +1 -0
  86. package/lib/tools.js +126 -0
  87. package/lib/tools.js.map +1 -0
  88. package/lib/types.d.ts +551 -0
  89. package/lib/types.d.ts.map +1 -0
  90. package/lib/types.js +163 -0
  91. package/lib/types.js.map +1 -0
  92. package/lib/version.d.ts +2 -0
  93. package/lib/version.d.ts.map +1 -0
  94. package/lib/version.js +2 -0
  95. package/lib/version.js.map +1 -0
  96. package/lib/web-fetch.d.ts +95 -0
  97. package/lib/web-fetch.d.ts.map +1 -0
  98. package/lib/web-fetch.js +833 -0
  99. package/lib/web-fetch.js.map +1 -0
  100. package/lib/web-learning-interests.d.ts +42 -0
  101. package/lib/web-learning-interests.d.ts.map +1 -0
  102. package/lib/web-learning-interests.js +4344 -0
  103. package/lib/web-learning-interests.js.map +1 -0
  104. package/lib/web-learning-runner.d.ts +43 -0
  105. package/lib/web-learning-runner.d.ts.map +1 -0
  106. package/lib/web-learning-runner.js +322 -0
  107. package/lib/web-learning-runner.js.map +1 -0
  108. package/lib/web-learning-worker.d.ts +75 -0
  109. package/lib/web-learning-worker.d.ts.map +1 -0
  110. package/lib/web-learning-worker.js +367 -0
  111. package/lib/web-learning-worker.js.map +1 -0
  112. package/lib/web-learning.d.ts +161 -0
  113. package/lib/web-learning.d.ts.map +1 -0
  114. package/lib/web-learning.js +912 -0
  115. package/lib/web-learning.js.map +1 -0
  116. package/lib/write-queue.d.ts +42 -0
  117. package/lib/write-queue.d.ts.map +1 -0
  118. package/lib/write-queue.js +439 -0
  119. package/lib/write-queue.js.map +1 -0
  120. package/package.json +149 -4
@@ -0,0 +1,1743 @@
1
+ import { assertExactGrowthKeys, canonicalGrowthJson, growthObjectDigest, isGrowthRecord, } from '@dsh-ray/assistant-growth-contract';
2
+ import { runHotPathQuery } from './hot-path.js';
3
+ import { DEFAULT_SOURCE_WEIGHTS, NODE_KINDS, WEB_LEARNING_SOURCE_PLUGIN, } from './types.js';
4
+ export const ASSOC_PARAM_PROFILE_PROTOCOL = 'assistant-association/param-profile/v1';
5
+ export const ASSOC_PARAM_RELAX_PROTOCOL = 'assistant-association/param-relaxation/v1';
6
+ export const ASSOC_PARAM_HOLDOUT_PROTOCOL = 'assistant-association/param-holdout/v1';
7
+ export const DECAY_HALF_LIFE_LADDER = Object.freeze([
8
+ 86_400_000, // 1d (tightest)
9
+ 259_200_000, // 3d
10
+ 604_800_000, // 7d
11
+ 1_209_600_000, // 14d
12
+ 2_592_000_000, // 30d (loosest)
13
+ ]);
14
+ export const ASSOC_PARAM_BOUNDS = Object.freeze({
15
+ maxHops: Object.freeze({ min: 1, max: 2, step: 1 }),
16
+ maxItems: Object.freeze({ min: 5, max: 8, step: 1 }),
17
+ hysteresisDeltaMilli: Object.freeze({ min: 50, max: 500, step: 50 }),
18
+ sourceWeightPct: Object.freeze({ min: 20, max: 150, step: 10 }),
19
+ });
20
+ const PROFILE_KEYS = [
21
+ 'decayHalfLifeMs',
22
+ 'maxHops',
23
+ 'maxItems',
24
+ 'hysteresisDeltaMilli',
25
+ 'sourceWeightsPct',
26
+ ];
27
+ const SOURCE_PLUGIN_TO_KIND = Object.freeze({
28
+ 'personal-memory': 'memory',
29
+ 'assistant-goals': 'goal',
30
+ 'assistant-work-items': 'work-item',
31
+ 'assistant-automations': 'automation',
32
+ 'assistant-delivery': 'episode',
33
+ 'personal-wiki': 'wiki',
34
+ 'assistant-skills': 'skill',
35
+ 'event-triggers': 'event',
36
+ 'assistant-dreaming': 'dream',
37
+ [WEB_LEARNING_SOURCE_PLUGIN]: 'web',
38
+ });
39
+ export const DEFAULT_ASSOC_PARAM_TUNING_POLICY = Object.freeze({
40
+ minSample: 20,
41
+ minStepSample: 20,
42
+ minSourceSample: 10,
43
+ minHoldoutSamples: 20,
44
+ maxTimeoutRatePpm: 50_000,
45
+ lowUsageRatePpm: 100_000,
46
+ healthyUsageRatePpm: 250_000,
47
+ highCorrectionRatePpm: 250_000,
48
+ noisySourceRatePpm: 850_000,
49
+ regressionMarginPpm: 100_000,
50
+ timeoutMarginPpm: 25_000,
51
+ maxTimeoutMarginPpm: 25_000,
52
+ usageDropMarginPpm: 100_000,
53
+ observationMs: 7 * 86_400_000,
54
+ evaluationWindowMs: 7 * 86_400_000,
55
+ relaxReplayWindowMs: 30 * 86_400_000,
56
+ rollbackCooldownMs: 7 * 86_400_000,
57
+ hotPathBudgetMs: 4.5,
58
+ minItems: 5,
59
+ autoTightenEnabled: true,
60
+ relaxationReplayEnabled: true,
61
+ });
62
+ export class AssocParamTuningError extends Error {
63
+ code;
64
+ constructor(code, message) {
65
+ super(message);
66
+ this.code = code;
67
+ this.name = 'AssocParamTuningError';
68
+ }
69
+ }
70
+ function invalid(message) {
71
+ throw new AssocParamTuningError('invalid-input', `assoc param tuning: ${message}`);
72
+ }
73
+ function deepFreeze(value) {
74
+ if (value !== null && typeof value === 'object') {
75
+ for (const entry of Object.values(value)) {
76
+ deepFreeze(entry);
77
+ }
78
+ Object.freeze(value);
79
+ }
80
+ return value;
81
+ }
82
+ function validateScopeKey(scopeKey) {
83
+ if (typeof scopeKey !== 'string' ||
84
+ scopeKey.length < 1 ||
85
+ scopeKey.length > 128 ||
86
+ scopeKey.trim() !== scopeKey ||
87
+ /\p{Cc}/u.test(scopeKey)) {
88
+ invalid('scopeKey must be a non-empty bounded identifier');
89
+ }
90
+ return scopeKey;
91
+ }
92
+ function clampGridInt(value, min, max, step) {
93
+ const finite = Number.isFinite(value) ? value : min;
94
+ const clamped = Math.min(max, Math.max(min, finite));
95
+ const snapped = min + Math.round((clamped - min) / step) * step;
96
+ return Math.min(max, Math.max(min, snapped));
97
+ }
98
+ export function snapDecayHalfLifeMs(value) {
99
+ const minRung = DECAY_HALF_LIFE_LADDER[0];
100
+ const maxRung = DECAY_HALF_LIFE_LADDER[DECAY_HALF_LIFE_LADDER.length - 1];
101
+ const finite = Number.isFinite(value) ? value : 1_209_600_000;
102
+ const clamped = Math.min(maxRung, Math.max(minRung, finite));
103
+ let best = minRung;
104
+ let bestDist = Math.abs(clamped - minRung);
105
+ for (let i = 1; i < DECAY_HALF_LIFE_LADDER.length; i += 1) {
106
+ const rung = DECAY_HALF_LIFE_LADDER[i];
107
+ const dist = Math.abs(clamped - rung);
108
+ if (dist < bestDist) {
109
+ best = rung;
110
+ bestDist = dist;
111
+ }
112
+ }
113
+ return best;
114
+ }
115
+ export function clampAssocParamProfile(input, options) {
116
+ const minItems = Math.max(ASSOC_PARAM_BOUNDS.maxItems.min, Math.min(ASSOC_PARAM_BOUNDS.maxItems.max, Math.trunc(options?.minItems ?? 5)));
117
+ const weights = {};
118
+ for (const kind of NODE_KINDS) {
119
+ const raw = input.sourceWeightsPct[kind] ?? Math.round(DEFAULT_SOURCE_WEIGHTS[kind] * 100);
120
+ weights[kind] = clampGridInt(raw, ASSOC_PARAM_BOUNDS.sourceWeightPct.min, ASSOC_PARAM_BOUNDS.sourceWeightPct.max, ASSOC_PARAM_BOUNDS.sourceWeightPct.step);
121
+ }
122
+ return deepFreeze({
123
+ decayHalfLifeMs: snapDecayHalfLifeMs(input.decayHalfLifeMs),
124
+ maxHops: clampGridInt(input.maxHops, ASSOC_PARAM_BOUNDS.maxHops.min, ASSOC_PARAM_BOUNDS.maxHops.max, ASSOC_PARAM_BOUNDS.maxHops.step),
125
+ maxItems: clampGridInt(input.maxItems, minItems, ASSOC_PARAM_BOUNDS.maxItems.max, ASSOC_PARAM_BOUNDS.maxItems.step),
126
+ hysteresisDeltaMilli: clampGridInt(input.hysteresisDeltaMilli, ASSOC_PARAM_BOUNDS.hysteresisDeltaMilli.min, ASSOC_PARAM_BOUNDS.hysteresisDeltaMilli.max, ASSOC_PARAM_BOUNDS.hysteresisDeltaMilli.step),
127
+ sourceWeightsPct: weights,
128
+ });
129
+ }
130
+ export function normalizeAssocParamProfile(input) {
131
+ if (!isGrowthRecord(input))
132
+ invalid('profile must be an object');
133
+ assertExactGrowthKeys(input, PROFILE_KEYS, 'assocParamProfile');
134
+ for (const key of ['decayHalfLifeMs', 'maxHops', 'maxItems', 'hysteresisDeltaMilli']) {
135
+ if (!Number.isSafeInteger(input[key])) {
136
+ invalid(`${key} must be a safe integer`);
137
+ }
138
+ }
139
+ const rawWeights = input.sourceWeightsPct;
140
+ if (!isGrowthRecord(rawWeights))
141
+ invalid('sourceWeightsPct must be an object');
142
+ assertExactGrowthKeys(rawWeights, NODE_KINDS, 'assocParamProfile.sourceWeightsPct');
143
+ const weights = {};
144
+ for (const kind of NODE_KINDS) {
145
+ const val = rawWeights[kind];
146
+ if (!Number.isSafeInteger(val)) {
147
+ invalid(`sourceWeightsPct.${kind} must be a safe integer`);
148
+ }
149
+ weights[kind] = val;
150
+ }
151
+ return deepFreeze({
152
+ decayHalfLifeMs: input.decayHalfLifeMs,
153
+ maxHops: input.maxHops,
154
+ maxItems: input.maxItems,
155
+ hysteresisDeltaMilli: input.hysteresisDeltaMilli,
156
+ sourceWeightsPct: weights,
157
+ });
158
+ }
159
+ export function withinAssocParamBounds(profile, options) {
160
+ const minItems = Math.max(ASSOC_PARAM_BOUNDS.maxItems.min, Math.min(ASSOC_PARAM_BOUNDS.maxItems.max, Math.trunc(options?.minItems ?? 5)));
161
+ if (!DECAY_HALF_LIFE_LADDER.includes(profile.decayHalfLifeMs))
162
+ return false;
163
+ if (!Number.isSafeInteger(profile.maxHops) ||
164
+ profile.maxHops < ASSOC_PARAM_BOUNDS.maxHops.min ||
165
+ profile.maxHops > ASSOC_PARAM_BOUNDS.maxHops.max) {
166
+ return false;
167
+ }
168
+ if (!Number.isSafeInteger(profile.maxItems) ||
169
+ profile.maxItems < minItems ||
170
+ profile.maxItems > ASSOC_PARAM_BOUNDS.maxItems.max) {
171
+ return false;
172
+ }
173
+ if (!Number.isSafeInteger(profile.hysteresisDeltaMilli) ||
174
+ profile.hysteresisDeltaMilli < ASSOC_PARAM_BOUNDS.hysteresisDeltaMilli.min ||
175
+ profile.hysteresisDeltaMilli > ASSOC_PARAM_BOUNDS.hysteresisDeltaMilli.max ||
176
+ (profile.hysteresisDeltaMilli - ASSOC_PARAM_BOUNDS.hysteresisDeltaMilli.min) %
177
+ ASSOC_PARAM_BOUNDS.hysteresisDeltaMilli.step !==
178
+ 0) {
179
+ return false;
180
+ }
181
+ for (const kind of NODE_KINDS) {
182
+ const w = profile.sourceWeightsPct[kind];
183
+ if (!Number.isSafeInteger(w) ||
184
+ w < ASSOC_PARAM_BOUNDS.sourceWeightPct.min ||
185
+ w > ASSOC_PARAM_BOUNDS.sourceWeightPct.max ||
186
+ (w - ASSOC_PARAM_BOUNDS.sourceWeightPct.min) % ASSOC_PARAM_BOUNDS.sourceWeightPct.step !== 0) {
187
+ return false;
188
+ }
189
+ }
190
+ return true;
191
+ }
192
+ export function fromAssociationConfig(config) {
193
+ const weights = {};
194
+ for (const kind of NODE_KINDS) {
195
+ const raw = config.sourceWeights[kind] ?? DEFAULT_SOURCE_WEIGHTS[kind];
196
+ weights[kind] = clampGridInt(Math.round(raw * 100), ASSOC_PARAM_BOUNDS.sourceWeightPct.min, ASSOC_PARAM_BOUNDS.sourceWeightPct.max, ASSOC_PARAM_BOUNDS.sourceWeightPct.step);
197
+ }
198
+ return clampAssocParamProfile({
199
+ decayHalfLifeMs: snapDecayHalfLifeMs(config.decayHalfLifeMs),
200
+ maxHops: Math.round(config.maxHops),
201
+ maxItems: Math.round(config.maxItems),
202
+ hysteresisDeltaMilli: Math.round(config.hysteresisDelta * 1000),
203
+ sourceWeightsPct: weights,
204
+ }, { minItems: config.minItems });
205
+ }
206
+ export function toHotPathProfile(values, baseConfig) {
207
+ const sourceWeights = {};
208
+ for (const kind of NODE_KINDS) {
209
+ sourceWeights[kind] = values.sourceWeightsPct[kind] / 100;
210
+ }
211
+ return deepFreeze({
212
+ maxHops: values.maxHops,
213
+ hopTopN: baseConfig.hopTopN,
214
+ maxFanoutPerNode: baseConfig.maxFanoutPerNode,
215
+ maxItems: values.maxItems,
216
+ decayHalfLifeMs: values.decayHalfLifeMs,
217
+ budgetMs: baseConfig.hotPathBudgetMs,
218
+ sourceWeights: sourceWeights,
219
+ hysteresisDelta: values.hysteresisDeltaMilli / 1000,
220
+ });
221
+ }
222
+ export function isProfileTighterOrEqual(a, b) {
223
+ if (a.decayHalfLifeMs > b.decayHalfLifeMs)
224
+ return false;
225
+ if (a.maxHops > b.maxHops)
226
+ return false;
227
+ if (a.maxItems > b.maxItems)
228
+ return false;
229
+ if (a.hysteresisDeltaMilli < b.hysteresisDeltaMilli)
230
+ return false;
231
+ for (const kind of NODE_KINDS) {
232
+ if (a.sourceWeightsPct[kind] > b.sourceWeightsPct[kind])
233
+ return false;
234
+ }
235
+ return true;
236
+ }
237
+ export function classifyProfileChange(current, next) {
238
+ if (canonicalGrowthJson(current) === canonicalGrowthJson(next)) {
239
+ return 'identical';
240
+ }
241
+ if (isProfileTighterOrEqual(next, current)) {
242
+ return 'tighten';
243
+ }
244
+ return 'relax';
245
+ }
246
+ function collectParamDiffs(current, next) {
247
+ const diffs = [];
248
+ if (current.decayHalfLifeMs !== next.decayHalfLifeMs) {
249
+ diffs.push({ parameter: 'decayHalfLifeMs', from: current.decayHalfLifeMs, to: next.decayHalfLifeMs });
250
+ }
251
+ if (current.maxHops !== next.maxHops) {
252
+ diffs.push({ parameter: 'maxHops', from: current.maxHops, to: next.maxHops });
253
+ }
254
+ if (current.maxItems !== next.maxItems) {
255
+ diffs.push({ parameter: 'maxItems', from: current.maxItems, to: next.maxItems });
256
+ }
257
+ if (current.hysteresisDeltaMilli !== next.hysteresisDeltaMilli) {
258
+ diffs.push({
259
+ parameter: 'hysteresisDeltaMilli',
260
+ from: current.hysteresisDeltaMilli,
261
+ to: next.hysteresisDeltaMilli,
262
+ });
263
+ }
264
+ for (const kind of NODE_KINDS) {
265
+ if (current.sourceWeightsPct[kind] !== next.sourceWeightsPct[kind]) {
266
+ diffs.push({
267
+ parameter: `sourceWeightsPct.${kind}`,
268
+ from: current.sourceWeightsPct[kind],
269
+ to: next.sourceWeightsPct[kind],
270
+ });
271
+ }
272
+ }
273
+ return diffs;
274
+ }
275
+ export function describeSingleTighteningStep(current, next, options) {
276
+ if (!withinAssocParamBounds(next, options))
277
+ return undefined;
278
+ const diffs = collectParamDiffs(current, next);
279
+ if (diffs.length !== 1)
280
+ return undefined;
281
+ const diff = diffs[0];
282
+ if (diff.parameter === 'decayHalfLifeMs') {
283
+ const curIdx = DECAY_HALF_LIFE_LADDER.indexOf(diff.from);
284
+ const nextIdx = DECAY_HALF_LIFE_LADDER.indexOf(diff.to);
285
+ if (curIdx < 0 || nextIdx !== curIdx - 1)
286
+ return undefined;
287
+ return Object.freeze({ parameter: diff.parameter, from: diff.from, to: diff.to, steps: 1 });
288
+ }
289
+ if (diff.parameter === 'maxHops' || diff.parameter === 'maxItems') {
290
+ if (diff.from - diff.to !== 1)
291
+ return undefined;
292
+ return Object.freeze({ parameter: diff.parameter, from: diff.from, to: diff.to, steps: 1 });
293
+ }
294
+ if (diff.parameter === 'hysteresisDeltaMilli') {
295
+ if (diff.to - diff.from !== ASSOC_PARAM_BOUNDS.hysteresisDeltaMilli.step)
296
+ return undefined;
297
+ return Object.freeze({ parameter: diff.parameter, from: diff.from, to: diff.to, steps: 1 });
298
+ }
299
+ if (diff.from - diff.to !== ASSOC_PARAM_BOUNDS.sourceWeightPct.step)
300
+ return undefined;
301
+ return Object.freeze({ parameter: diff.parameter, from: diff.from, to: diff.to, steps: 1 });
302
+ }
303
+ export function describeRelaxationChange(current, next, options) {
304
+ if (!withinAssocParamBounds(next, options))
305
+ return undefined;
306
+ const diffs = collectParamDiffs(current, next);
307
+ if (diffs.length !== 1)
308
+ return undefined;
309
+ const diff = diffs[0];
310
+ if (diff.parameter === 'decayHalfLifeMs') {
311
+ const curIdx = DECAY_HALF_LIFE_LADDER.indexOf(diff.from);
312
+ const nextIdx = DECAY_HALF_LIFE_LADDER.indexOf(diff.to);
313
+ if (curIdx < 0 || nextIdx <= curIdx)
314
+ return undefined;
315
+ return Object.freeze({
316
+ parameter: diff.parameter,
317
+ from: diff.from,
318
+ to: diff.to,
319
+ steps: nextIdx - curIdx,
320
+ });
321
+ }
322
+ if (diff.parameter === 'maxHops' || diff.parameter === 'maxItems') {
323
+ const delta = diff.to - diff.from;
324
+ if (delta <= 0)
325
+ return undefined;
326
+ return Object.freeze({ parameter: diff.parameter, from: diff.from, to: diff.to, steps: delta });
327
+ }
328
+ if (diff.parameter === 'hysteresisDeltaMilli') {
329
+ const delta = diff.from - diff.to;
330
+ const { step } = ASSOC_PARAM_BOUNDS.hysteresisDeltaMilli;
331
+ if (delta <= 0 || delta % step !== 0)
332
+ return undefined;
333
+ return Object.freeze({
334
+ parameter: diff.parameter,
335
+ from: diff.from,
336
+ to: diff.to,
337
+ steps: delta / step,
338
+ });
339
+ }
340
+ const delta = diff.to - diff.from;
341
+ const { step } = ASSOC_PARAM_BOUNDS.sourceWeightPct;
342
+ if (delta <= 0 || delta % step !== 0)
343
+ return undefined;
344
+ return Object.freeze({
345
+ parameter: diff.parameter,
346
+ from: diff.from,
347
+ to: diff.to,
348
+ steps: delta / step,
349
+ });
350
+ }
351
+ function atLeastRate(numerator, denominator, ratePpm) {
352
+ if (denominator <= 0)
353
+ return false;
354
+ return BigInt(numerator) * 1000000n >= BigInt(ratePpm) * BigInt(denominator);
355
+ }
356
+ function atMostRate(numerator, denominator, ratePpm) {
357
+ if (denominator <= 0)
358
+ return false;
359
+ return BigInt(numerator) * 1000000n <= BigInt(ratePpm) * BigInt(denominator);
360
+ }
361
+ function buildTightenedCandidate(current, field, minItems) {
362
+ if (field === 'maxHops') {
363
+ if (current.maxHops <= ASSOC_PARAM_BOUNDS.maxHops.min)
364
+ return undefined;
365
+ const to = current.maxHops - 1;
366
+ return deepFreeze({
367
+ change: { parameter: 'maxHops', from: current.maxHops, to, steps: 1 },
368
+ parameters: { ...current, maxHops: to },
369
+ });
370
+ }
371
+ if (field === 'maxItems') {
372
+ if (current.maxItems <= minItems)
373
+ return undefined;
374
+ const to = current.maxItems - 1;
375
+ return deepFreeze({
376
+ change: { parameter: 'maxItems', from: current.maxItems, to, steps: 1 },
377
+ parameters: { ...current, maxItems: to },
378
+ });
379
+ }
380
+ if (field === 'hysteresisDeltaMilli') {
381
+ if (current.hysteresisDeltaMilli >= ASSOC_PARAM_BOUNDS.hysteresisDeltaMilli.max)
382
+ return undefined;
383
+ const to = current.hysteresisDeltaMilli + ASSOC_PARAM_BOUNDS.hysteresisDeltaMilli.step;
384
+ return deepFreeze({
385
+ change: {
386
+ parameter: 'hysteresisDeltaMilli',
387
+ from: current.hysteresisDeltaMilli,
388
+ to,
389
+ steps: 1,
390
+ },
391
+ parameters: { ...current, hysteresisDeltaMilli: to },
392
+ });
393
+ }
394
+ if (field === 'decayHalfLifeMs') {
395
+ const idx = DECAY_HALF_LIFE_LADDER.indexOf(current.decayHalfLifeMs);
396
+ if (idx <= 0)
397
+ return undefined;
398
+ const to = DECAY_HALF_LIFE_LADDER[idx - 1];
399
+ return deepFreeze({
400
+ change: { parameter: 'decayHalfLifeMs', from: current.decayHalfLifeMs, to, steps: 1 },
401
+ parameters: { ...current, decayHalfLifeMs: to },
402
+ });
403
+ }
404
+ const kind = field.slice('sourceWeightsPct.'.length);
405
+ const curW = current.sourceWeightsPct[kind];
406
+ if (curW <= ASSOC_PARAM_BOUNDS.sourceWeightPct.min)
407
+ return undefined;
408
+ const to = curW - ASSOC_PARAM_BOUNDS.sourceWeightPct.step;
409
+ return deepFreeze({
410
+ change: { parameter: field, from: curW, to, steps: 1 },
411
+ parameters: {
412
+ ...current,
413
+ sourceWeightsPct: { ...current.sourceWeightsPct, [kind]: to },
414
+ },
415
+ });
416
+ }
417
+ export function proposeAssocParamTightening(currentInput, stats, policy, isBlockedParamsDigest = () => false) {
418
+ const minItems = Math.max(ASSOC_PARAM_BOUNDS.maxItems.min, Math.min(ASSOC_PARAM_BOUNDS.maxItems.max, Math.trunc(policy.minItems)));
419
+ const current = clampAssocParamProfile(currentInput, { minItems });
420
+ const hasStepSample = stats.totalSteps >= policy.minStepSample;
421
+ const hasTaskSample = stats.decidedTasks >= policy.minSample;
422
+ if (!hasStepSample && !hasTaskSample) {
423
+ return deepFreeze({ kind: 'no-op', reason: 'insufficient-sample' });
424
+ }
425
+ const highTimeout = stats.totalSteps >= policy.minStepSample &&
426
+ atLeastRate(stats.timedOutSteps, stats.totalSteps, policy.maxTimeoutRatePpm);
427
+ const highCorrection = stats.injectedTasks >= policy.minSample &&
428
+ atLeastRate(stats.correctedTasks, stats.injectedTasks, policy.highCorrectionRatePpm);
429
+ const lowUsage = stats.totalSteps >= policy.minStepSample &&
430
+ stats.injectedTasks >= policy.minSample &&
431
+ atMostRate(stats.usedTasks, stats.injectedTasks, policy.lowUsageRatePpm) &&
432
+ !atLeastRate(stats.usedTasks, stats.injectedTasks, policy.healthyUsageRatePpm);
433
+ if (!highTimeout && !highCorrection && !lowUsage) {
434
+ if (stats.totalSteps < policy.minStepSample && stats.injectedTasks < policy.minSample) {
435
+ return deepFreeze({ kind: 'no-op', reason: 'insufficient-sample' });
436
+ }
437
+ return deepFreeze({ kind: 'no-op', reason: 'below-threshold' });
438
+ }
439
+ const candidateFields = [];
440
+ let triggerReason = 'low-usage-rate';
441
+ if (highTimeout) {
442
+ triggerReason = 'high-timeout-rate';
443
+ candidateFields.push('maxHops', 'maxItems', 'decayHalfLifeMs', 'hysteresisDeltaMilli');
444
+ }
445
+ else {
446
+ triggerReason = highCorrection ? 'high-correction-rate' : 'low-usage-rate';
447
+ const noisyKinds = [];
448
+ for (const kind of NODE_KINDS) {
449
+ const exp = stats.sourceExposures[kind];
450
+ if (exp.total >= policy.minSourceSample &&
451
+ atLeastRate(exp.unusedOrCorrected, exp.total, policy.noisySourceRatePpm)) {
452
+ noisyKinds.push({ kind, ratio: exp.unusedOrCorrected / exp.total });
453
+ }
454
+ }
455
+ noisyKinds.sort((a, b) => b.ratio - a.ratio);
456
+ for (const entry of noisyKinds) {
457
+ candidateFields.push(`sourceWeightsPct.${entry.kind}`);
458
+ }
459
+ candidateFields.push('maxItems', 'hysteresisDeltaMilli', 'decayHalfLifeMs', 'maxHops');
460
+ }
461
+ let sawUnblockedBound = false;
462
+ for (const field of candidateFields) {
463
+ const candidate = buildTightenedCandidate(current, field, minItems);
464
+ if (candidate === undefined)
465
+ continue;
466
+ sawUnblockedBound = true;
467
+ const paramsDigest = growthObjectDigest(candidate.parameters);
468
+ if (isBlockedParamsDigest(paramsDigest))
469
+ continue;
470
+ return deepFreeze({
471
+ kind: 'tighten',
472
+ change: candidate.change,
473
+ parameters: candidate.parameters,
474
+ triggerReason: field.startsWith('sourceWeightsPct.') && !highTimeout ? 'noisy-source-kind' : triggerReason,
475
+ });
476
+ }
477
+ return deepFreeze({
478
+ kind: 'no-op',
479
+ reason: sawUnblockedBound ? 'blocked-by-rollback' : 'at-bound',
480
+ });
481
+ }
482
+ export function hasAssocObservedRegression(basis, post, policy) {
483
+ if (post.decidedTasks < policy.minSample && post.totalSteps < policy.minStepSample) {
484
+ return Object.freeze({ regressed: false });
485
+ }
486
+ const effectiveTimeoutMarginPpm = Math.min(policy.timeoutMarginPpm, policy.maxTimeoutMarginPpm);
487
+ if (post.totalSteps >= policy.minStepSample) {
488
+ if (basis.totalSteps > 0) {
489
+ const left = BigInt(post.timedOutSteps) * BigInt(basis.totalSteps) * 1000000n;
490
+ const right = BigInt(basis.timedOutSteps) * BigInt(post.totalSteps) * 1000000n +
491
+ BigInt(effectiveTimeoutMarginPpm) * BigInt(basis.totalSteps) * BigInt(post.totalSteps);
492
+ if (left > right) {
493
+ return Object.freeze({ regressed: true, reason: 'timeout-rate-regressed' });
494
+ }
495
+ }
496
+ else if (atLeastRate(post.timedOutSteps, post.totalSteps, policy.maxTimeoutRatePpm)) {
497
+ return Object.freeze({ regressed: true, reason: 'timeout-rate-regressed' });
498
+ }
499
+ }
500
+ if (post.injectedTasks >= policy.minSample) {
501
+ if (basis.injectedTasks > 0) {
502
+ const left = BigInt(post.correctedTasks) * BigInt(basis.injectedTasks) * 1000000n;
503
+ const right = BigInt(basis.correctedTasks) * BigInt(post.injectedTasks) * 1000000n +
504
+ BigInt(policy.regressionMarginPpm) * BigInt(basis.injectedTasks) * BigInt(post.injectedTasks);
505
+ if (left > right) {
506
+ return Object.freeze({ regressed: true, reason: 'correction-rate-regressed' });
507
+ }
508
+ }
509
+ else if (atLeastRate(post.correctedTasks, post.injectedTasks, policy.highCorrectionRatePpm)) {
510
+ return Object.freeze({ regressed: true, reason: 'correction-rate-regressed' });
511
+ }
512
+ }
513
+ if (post.injectedTasks >= policy.minSample && basis.injectedTasks >= policy.minSample) {
514
+ const left = BigInt(post.usedTasks) * BigInt(basis.injectedTasks) * 1000000n +
515
+ BigInt(policy.usageDropMarginPpm) * BigInt(basis.injectedTasks) * BigInt(post.injectedTasks);
516
+ const right = BigInt(basis.usedTasks) * BigInt(post.injectedTasks) * 1000000n;
517
+ if (left < right) {
518
+ return Object.freeze({ regressed: true, reason: 'usage-rate-regressed' });
519
+ }
520
+ }
521
+ return Object.freeze({ regressed: false });
522
+ }
523
+ export function ensureParamTuningSchema(database) {
524
+ database.exec(`
525
+ CREATE TABLE IF NOT EXISTS assoc_replay_episodes (
526
+ task_id TEXT PRIMARY KEY CHECK (length(task_id) BETWEEN 1 AND 512),
527
+ owner_scope_key TEXT NOT NULL CHECK (length(owner_scope_key) = 64 AND owner_scope_key NOT GLOB '*[^0-9a-f]*'),
528
+ in_holdout INTEGER NOT NULL CHECK (in_holdout IN (0, 1)),
529
+ cues_json TEXT NOT NULL CHECK (json_valid(cues_json)),
530
+ used_node_ids_json TEXT NOT NULL DEFAULT '[]' CHECK (json_valid(used_node_ids_json)),
531
+ corrected_node_ids_json TEXT NOT NULL DEFAULT '[]' CHECK (json_valid(corrected_node_ids_json)),
532
+ profile_version INTEGER NOT NULL DEFAULT 0 CHECK (profile_version >= 0),
533
+ occurred_at INTEGER NOT NULL CHECK (occurred_at >= 0)
534
+ ) STRICT;
535
+
536
+ CREATE INDEX IF NOT EXISTS assoc_replay_episodes_scope_time
537
+ ON assoc_replay_episodes(owner_scope_key, occurred_at DESC);
538
+
539
+ CREATE TABLE IF NOT EXISTS assoc_param_profile_versions (
540
+ scope_key TEXT NOT NULL,
541
+ version INTEGER NOT NULL CHECK (version >= 0),
542
+ parent_version INTEGER CHECK (parent_version IS NULL OR (parent_version >= 0 AND parent_version < version)),
543
+ params_json TEXT NOT NULL CHECK (json_valid(params_json)),
544
+ params_digest TEXT NOT NULL,
545
+ basis_json TEXT NOT NULL CHECK (json_valid(basis_json)),
546
+ change_json TEXT NOT NULL CHECK (json_valid(change_json)),
547
+ origin TEXT NOT NULL CHECK (origin IN ('baseline', 'auto', 'replay', 'manual')),
548
+ digest TEXT NOT NULL,
549
+ idempotency_key TEXT NOT NULL UNIQUE,
550
+ created_at INTEGER NOT NULL CHECK (created_at >= 0),
551
+ PRIMARY KEY (scope_key, version)
552
+ ) STRICT;
553
+
554
+ CREATE TRIGGER IF NOT EXISTS assoc_param_profile_versions_immutable
555
+ BEFORE UPDATE ON assoc_param_profile_versions
556
+ BEGIN SELECT RAISE(ABORT, 'assoc_param_profile_versions are immutable'); END;
557
+
558
+ CREATE TRIGGER IF NOT EXISTS assoc_param_profile_versions_no_delete
559
+ BEFORE DELETE ON assoc_param_profile_versions
560
+ BEGIN SELECT RAISE(ABORT, 'assoc_param_profile_versions are durable'); END;
561
+
562
+ CREATE TABLE IF NOT EXISTS assoc_param_profile_heads (
563
+ scope_key TEXT PRIMARY KEY,
564
+ active_version INTEGER NOT NULL CHECK (active_version >= 0),
565
+ latest_version INTEGER NOT NULL CHECK (latest_version >= active_version),
566
+ active_digest TEXT NOT NULL,
567
+ state TEXT NOT NULL CHECK (state IN ('idle', 'observing')),
568
+ observing_version INTEGER,
569
+ observe_from INTEGER,
570
+ observe_until INTEGER,
571
+ changed_at INTEGER NOT NULL CHECK (changed_at >= 0),
572
+ CHECK (
573
+ (state = 'idle' AND observing_version IS NULL AND observe_from IS NULL AND observe_until IS NULL)
574
+ OR (state = 'observing' AND observing_version = active_version AND observe_from IS NOT NULL AND observe_until IS NOT NULL AND observe_until > observe_from)
575
+ )
576
+ ) STRICT;
577
+
578
+ CREATE TRIGGER IF NOT EXISTS assoc_param_profile_heads_no_delete
579
+ BEFORE DELETE ON assoc_param_profile_heads
580
+ BEGIN SELECT RAISE(ABORT, 'assoc_param_profile_heads are durable'); END;
581
+
582
+ CREATE TABLE IF NOT EXISTS assoc_param_profile_events (
583
+ seq INTEGER PRIMARY KEY AUTOINCREMENT,
584
+ scope_key TEXT NOT NULL,
585
+ kind TEXT NOT NULL CHECK (kind IN ('adopted', 'rolled-back', 'settled', 'request-rejected')),
586
+ from_version INTEGER,
587
+ to_version INTEGER,
588
+ from_digest TEXT,
589
+ to_digest TEXT,
590
+ reason TEXT NOT NULL,
591
+ detail_json TEXT NOT NULL CHECK (json_valid(detail_json)),
592
+ idempotency_key TEXT NOT NULL UNIQUE,
593
+ occurred_at INTEGER NOT NULL CHECK (occurred_at >= 0)
594
+ ) STRICT;
595
+
596
+ CREATE INDEX IF NOT EXISTS assoc_param_profile_events_scope
597
+ ON assoc_param_profile_events(scope_key, seq);
598
+
599
+ CREATE TRIGGER IF NOT EXISTS assoc_param_profile_events_immutable
600
+ BEFORE UPDATE ON assoc_param_profile_events
601
+ BEGIN SELECT RAISE(ABORT, 'assoc_param_profile_events are immutable'); END;
602
+
603
+ CREATE TRIGGER IF NOT EXISTS assoc_param_profile_events_no_delete
604
+ BEFORE DELETE ON assoc_param_profile_events
605
+ BEGIN SELECT RAISE(ABORT, 'assoc_param_profile_events are durable'); END;
606
+
607
+ CREATE TABLE IF NOT EXISTS assoc_param_relax_proposals (
608
+ proposal_id TEXT PRIMARY KEY,
609
+ scope_key TEXT NOT NULL,
610
+ parent_version INTEGER NOT NULL,
611
+ parent_digest TEXT NOT NULL,
612
+ candidate_json TEXT NOT NULL CHECK (json_valid(candidate_json)),
613
+ params_digest TEXT NOT NULL,
614
+ change_json TEXT NOT NULL CHECK (json_valid(change_json)),
615
+ holdout_seal TEXT NOT NULL,
616
+ window_from INTEGER NOT NULL,
617
+ window_to INTEGER NOT NULL,
618
+ basis_json TEXT NOT NULL CHECK (json_valid(basis_json)),
619
+ status TEXT NOT NULL CHECK (status IN ('pending', 'adopted', 'rejected')),
620
+ created_at INTEGER NOT NULL CHECK (created_at >= 0)
621
+ ) STRICT;
622
+
623
+ CREATE INDEX IF NOT EXISTS assoc_param_relax_proposals_scope
624
+ ON assoc_param_relax_proposals(scope_key, created_at);
625
+
626
+ CREATE TRIGGER IF NOT EXISTS assoc_param_relax_proposals_immutable
627
+ BEFORE UPDATE ON assoc_param_relax_proposals
628
+ BEGIN SELECT RAISE(ABORT, 'assoc_param_relax_proposals are immutable'); END;
629
+
630
+ CREATE TRIGGER IF NOT EXISTS assoc_param_relax_proposals_no_delete
631
+ BEFORE DELETE ON assoc_param_relax_proposals
632
+ BEGIN SELECT RAISE(ABORT, 'assoc_param_relax_proposals are durable'); END;
633
+
634
+ CREATE TABLE IF NOT EXISTS assoc_param_relax_decisions (
635
+ decision_id TEXT PRIMARY KEY,
636
+ proposal_id TEXT NOT NULL UNIQUE,
637
+ scope_key TEXT NOT NULL,
638
+ status TEXT NOT NULL CHECK (status IN ('adopted', 'rejected')),
639
+ reason TEXT NOT NULL,
640
+ replay_json TEXT NOT NULL CHECK (json_valid(replay_json)),
641
+ decided_at INTEGER NOT NULL CHECK (decided_at >= 0),
642
+ FOREIGN KEY (proposal_id) REFERENCES assoc_param_relax_proposals(proposal_id) ON DELETE RESTRICT
643
+ ) STRICT;
644
+
645
+ CREATE TRIGGER IF NOT EXISTS assoc_param_relax_decisions_immutable
646
+ BEFORE UPDATE ON assoc_param_relax_decisions
647
+ BEGIN SELECT RAISE(ABORT, 'assoc_param_relax_decisions are immutable'); END;
648
+
649
+ CREATE TRIGGER IF NOT EXISTS assoc_param_relax_decisions_no_delete
650
+ BEFORE DELETE ON assoc_param_relax_decisions
651
+ BEGIN SELECT RAISE(ABORT, 'assoc_param_relax_decisions are durable'); END;
652
+
653
+ CREATE TABLE IF NOT EXISTS assoc_param_rolled_back_digests (
654
+ scope_key TEXT NOT NULL,
655
+ params_digest TEXT NOT NULL,
656
+ rolled_back_at INTEGER NOT NULL CHECK (rolled_back_at >= 0),
657
+ from_version INTEGER NOT NULL,
658
+ reason TEXT NOT NULL,
659
+ PRIMARY KEY (scope_key, params_digest)
660
+ ) STRICT;
661
+ `);
662
+ }
663
+ function versionDigest(input) {
664
+ return growthObjectDigest(input);
665
+ }
666
+ function computeP99(values) {
667
+ if (values.length === 0)
668
+ return 0;
669
+ const sorted = [...values].sort((a, b) => a - b);
670
+ const idx = Math.min(sorted.length - 1, Math.max(0, Math.ceil(0.99 * sorted.length) - 1));
671
+ return sorted[idx];
672
+ }
673
+ function emptySourceExposures() {
674
+ const out = {};
675
+ for (const kind of NODE_KINDS) {
676
+ out[kind] = Object.freeze({ total: 0, unusedOrCorrected: 0 });
677
+ }
678
+ return out;
679
+ }
680
+ const DEFAULT_BASE_CONFIG = Object.freeze({
681
+ decayHalfLifeMs: 14 * 86_400_000,
682
+ maxHops: 2,
683
+ maxItems: 8,
684
+ minItems: 5,
685
+ hysteresisDelta: 0.15,
686
+ sourceWeights: DEFAULT_SOURCE_WEIGHTS,
687
+ hopTopN: 32,
688
+ maxFanoutPerNode: 128,
689
+ hotPathBudgetMs: 4.5,
690
+ });
691
+ export class AssociationParamTuningLedger {
692
+ #database;
693
+ #now;
694
+ #hotPathClock;
695
+ #baseConfig;
696
+ #baselineParams;
697
+ #policy;
698
+ constructor(database, options) {
699
+ this.#database = database;
700
+ this.#now = options?.now ?? (() => Date.now());
701
+ this.#hotPathClock = options?.hotPathClock;
702
+ this.#baseConfig = options?.baseConfig ?? DEFAULT_BASE_CONFIG;
703
+ this.#policy = Object.freeze({
704
+ ...DEFAULT_ASSOC_PARAM_TUNING_POLICY,
705
+ minItems: this.#baseConfig.minItems,
706
+ hotPathBudgetMs: this.#baseConfig.hotPathBudgetMs,
707
+ ...options?.policy,
708
+ });
709
+ this.#baselineParams = fromAssociationConfig(this.#baseConfig);
710
+ }
711
+ get policy() {
712
+ return this.#policy;
713
+ }
714
+ get baselineParameters() {
715
+ return this.#baselineParams;
716
+ }
717
+ #transaction(fn) {
718
+ this.#database.exec('BEGIN IMMEDIATE');
719
+ try {
720
+ const value = fn();
721
+ this.#database.exec('COMMIT');
722
+ return value;
723
+ }
724
+ catch (error) {
725
+ this.#database.exec('ROLLBACK');
726
+ throw error;
727
+ }
728
+ }
729
+ #baseline(scopeKey) {
730
+ const paramsDigest = growthObjectDigest(this.#baselineParams);
731
+ const digest = versionDigest({
732
+ protocol: ASSOC_PARAM_PROFILE_PROTOCOL,
733
+ scopeKey,
734
+ version: 0,
735
+ parentVersion: null,
736
+ parentDigest: null,
737
+ parameters: this.#baselineParams,
738
+ paramsDigest,
739
+ basis: { stats: this.#emptyStats(0, 0) },
740
+ change: null,
741
+ origin: 'baseline',
742
+ });
743
+ return deepFreeze({
744
+ scopeKey,
745
+ version: 0,
746
+ origin: 'baseline',
747
+ digest,
748
+ paramsDigest,
749
+ parameters: this.#baselineParams,
750
+ source: 'active',
751
+ });
752
+ }
753
+ #emptyStats(fromAt, toAt) {
754
+ return deepFreeze({
755
+ fromAt,
756
+ toAt,
757
+ totalSteps: 0,
758
+ timedOutSteps: 0,
759
+ p99LatencyUs: 0,
760
+ injectedTasks: 0,
761
+ decidedTasks: 0,
762
+ usedTasks: 0,
763
+ correctedTasks: 0,
764
+ sourceExposures: emptySourceExposures(),
765
+ });
766
+ }
767
+ #head(scopeKey) {
768
+ return this.#database
769
+ .prepare('SELECT * FROM assoc_param_profile_heads WHERE scope_key = ?')
770
+ .get(scopeKey);
771
+ }
772
+ #row(scopeKey, version) {
773
+ return this.#database
774
+ .prepare('SELECT * FROM assoc_param_profile_versions WHERE scope_key = ? AND version = ?')
775
+ .get(scopeKey, version);
776
+ }
777
+ #verified(scopeKey, version, visited = new Set()) {
778
+ if (!Number.isSafeInteger(version) || version < 0 || visited.has(version)) {
779
+ return undefined;
780
+ }
781
+ visited.add(version);
782
+ if (version === 0) {
783
+ const base = this.#baseline(scopeKey);
784
+ return deepFreeze({
785
+ protocol: ASSOC_PARAM_PROFILE_PROTOCOL,
786
+ scopeKey,
787
+ version: 0,
788
+ parentVersion: null,
789
+ parentDigest: null,
790
+ parameters: base.parameters,
791
+ paramsDigest: base.paramsDigest,
792
+ basis: { stats: this.#emptyStats(0, 0) },
793
+ change: null,
794
+ origin: 'baseline',
795
+ digest: base.digest,
796
+ createdAt: 0,
797
+ });
798
+ }
799
+ const row = this.#row(scopeKey, version);
800
+ if (row === undefined || row.version !== version)
801
+ return undefined;
802
+ try {
803
+ const base = this.#baseline(scopeKey);
804
+ const parentVersion = row.parent_version ?? 0;
805
+ if (!Number.isSafeInteger(parentVersion) || parentVersion < 0 || parentVersion >= row.version) {
806
+ return undefined;
807
+ }
808
+ const parentDigest = parentVersion === 0
809
+ ? base.digest
810
+ : this.#verified(scopeKey, parentVersion, visited)?.digest;
811
+ if (parentDigest === undefined)
812
+ return undefined;
813
+ const parameters = normalizeAssocParamProfile(JSON.parse(row.params_json));
814
+ if (!withinAssocParamBounds(parameters, { minItems: this.#policy.minItems }))
815
+ return undefined;
816
+ const paramsDigest = growthObjectDigest(parameters);
817
+ if (paramsDigest !== row.params_digest)
818
+ return undefined;
819
+ const basis = JSON.parse(row.basis_json);
820
+ const change = JSON.parse(row.change_json);
821
+ const expected = versionDigest({
822
+ protocol: ASSOC_PARAM_PROFILE_PROTOCOL,
823
+ scopeKey,
824
+ version: row.version,
825
+ parentVersion,
826
+ parentDigest,
827
+ parameters,
828
+ paramsDigest,
829
+ basis,
830
+ change,
831
+ origin: row.origin,
832
+ });
833
+ if (expected !== row.digest)
834
+ return undefined;
835
+ return deepFreeze({
836
+ protocol: ASSOC_PARAM_PROFILE_PROTOCOL,
837
+ scopeKey,
838
+ version: row.version,
839
+ parentVersion,
840
+ parentDigest,
841
+ parameters,
842
+ paramsDigest,
843
+ basis,
844
+ change,
845
+ origin: row.origin,
846
+ digest: row.digest,
847
+ createdAt: row.created_at,
848
+ });
849
+ }
850
+ catch {
851
+ return undefined;
852
+ }
853
+ }
854
+ current(scopeKeyInput) {
855
+ const scopeKey = validateScopeKey(scopeKeyInput);
856
+ return this.#current(scopeKey);
857
+ }
858
+ #current(scopeKey) {
859
+ const active = this.#head(scopeKey)?.active_version ?? 0;
860
+ let version = active;
861
+ let fallback = false;
862
+ const seen = new Set();
863
+ while (version > 0 && !seen.has(version)) {
864
+ seen.add(version);
865
+ const verified = this.#verified(scopeKey, version);
866
+ if (verified !== undefined) {
867
+ return deepFreeze({
868
+ scopeKey,
869
+ version: verified.version,
870
+ origin: verified.origin,
871
+ digest: verified.digest,
872
+ paramsDigest: verified.paramsDigest,
873
+ parameters: verified.parameters,
874
+ source: fallback ? 'parent-fallback' : 'active',
875
+ });
876
+ }
877
+ fallback = true;
878
+ const parent = this.#database
879
+ .prepare('SELECT parent_version FROM assoc_param_profile_versions WHERE scope_key = ? AND version = ?')
880
+ .get(scopeKey, version)?.parent_version;
881
+ version =
882
+ Number.isSafeInteger(parent) && parent >= 0 && parent < version
883
+ ? parent
884
+ : 0;
885
+ }
886
+ const base = this.#baseline(scopeKey);
887
+ return deepFreeze({
888
+ ...base,
889
+ source: active === 0 ? 'active' : 'default',
890
+ });
891
+ }
892
+ status(scopeKeyInput, eventLimit = 50) {
893
+ const scopeKey = validateScopeKey(scopeKeyInput);
894
+ const head = this.#head(scopeKey);
895
+ const versionNums = this.#database
896
+ .prepare('SELECT version FROM assoc_param_profile_versions WHERE scope_key = ? AND version >= 1 ORDER BY version ASC')
897
+ .all(scopeKey).map((r) => r.version);
898
+ const versions = versionNums
899
+ .map((v) => this.#verified(scopeKey, v))
900
+ .filter((v) => v !== undefined);
901
+ const events = this.#database
902
+ .prepare(`SELECT seq, kind, from_version, to_version, from_digest, to_digest, reason, detail_json, occurred_at
903
+ FROM assoc_param_profile_events WHERE scope_key = ? ORDER BY seq DESC LIMIT ?`)
904
+ .all(scopeKey, eventLimit)
905
+ .reverse()
906
+ .map((row) => ({
907
+ sequence: row.seq,
908
+ kind: row.kind,
909
+ fromVersion: row.from_version,
910
+ toVersion: row.to_version,
911
+ fromDigest: row.from_digest,
912
+ toDigest: row.to_digest,
913
+ reason: row.reason,
914
+ detail: JSON.parse(row.detail_json),
915
+ occurredAt: row.occurred_at,
916
+ }));
917
+ const proposalRows = this.#database
918
+ .prepare('SELECT * FROM assoc_param_relax_proposals WHERE scope_key = ? ORDER BY created_at ASC')
919
+ .all(scopeKey);
920
+ const proposals = proposalRows
921
+ .map((pRow) => {
922
+ const verified = this.#verifiedProposal(pRow, scopeKey);
923
+ if (verified === undefined)
924
+ return undefined;
925
+ const dRow = this.#database
926
+ .prepare('SELECT * FROM assoc_param_relax_decisions WHERE proposal_id = ?')
927
+ .get(pRow.proposal_id);
928
+ let decision = null;
929
+ if (dRow !== undefined) {
930
+ const adoptedEvent = dRow.status === 'adopted'
931
+ ? this.#database
932
+ .prepare('SELECT to_version FROM assoc_param_profile_events WHERE idempotency_key = ?')
933
+ .get(`relax-adopt:${pRow.proposal_id}`)
934
+ : undefined;
935
+ decision = {
936
+ decisionId: dRow.decision_id,
937
+ proposalId: dRow.proposal_id,
938
+ decision: dRow.status,
939
+ reason: dRow.reason,
940
+ version: adoptedEvent?.to_version ?? null,
941
+ replay: JSON.parse(dRow.replay_json),
942
+ decidedAt: dRow.decided_at,
943
+ };
944
+ }
945
+ return { proposalId: pRow.proposal_id, proposal: verified, decision };
946
+ })
947
+ .filter((item) => item !== undefined);
948
+ const blockedParamsDigests = this.#database
949
+ .prepare('SELECT params_digest FROM assoc_param_rolled_back_digests WHERE scope_key = ? ORDER BY rolled_back_at ASC')
950
+ .all(scopeKey).map((r) => r.params_digest);
951
+ return deepFreeze({
952
+ current: this.#current(scopeKey),
953
+ state: head?.state ?? 'idle',
954
+ ...(head?.observe_from == null ? {} : { observeFrom: head.observe_from }),
955
+ ...(head?.observe_until == null ? {} : { observeUntil: head.observe_until }),
956
+ versions,
957
+ events,
958
+ proposals,
959
+ blockedParamsDigests,
960
+ });
961
+ }
962
+ listScopeKeys() {
963
+ const rows = this.#database
964
+ .prepare(`SELECT scope_key FROM assoc_param_profile_heads
965
+ UNION SELECT DISTINCT owner_scope_key AS scope_key FROM assoc_step_metrics
966
+ UNION SELECT DISTINCT owner_scope_key AS scope_key FROM assoc_holdout_assignments
967
+ ORDER BY scope_key ASC`)
968
+ .all();
969
+ return Object.freeze(rows.map((r) => r.scope_key));
970
+ }
971
+ stats(scopeKeyInput, fromAt, toAt, partition = 'training') {
972
+ const scopeKey = validateScopeKey(scopeKeyInput);
973
+ const holdoutClause = partition === 'training' ? 'AND in_holdout = 0' : partition === 'holdout' ? 'AND in_holdout = 1' : '';
974
+ const metricRows = this.#database
975
+ .prepare(`SELECT task_id, in_holdout, latency_us, timed_out, injected_count
976
+ FROM assoc_step_metrics
977
+ WHERE owner_scope_key = ? AND occurred_at >= ? AND occurred_at < ? ${holdoutClause}`)
978
+ .all(scopeKey, fromAt, toAt);
979
+ const distinctMetricTasks = new Set();
980
+ const distinctInjectedTasks = new Set();
981
+ let nullTaskSteps = 0;
982
+ let nullTaskInjected = 0;
983
+ let timedOutSteps = 0;
984
+ const latencies = [];
985
+ for (const row of metricRows) {
986
+ if (row.timed_out === 1)
987
+ timedOutSteps += 1;
988
+ latencies.push(row.latency_us);
989
+ if (row.task_id !== null) {
990
+ distinctMetricTasks.add(row.task_id);
991
+ if (row.injected_count > 0)
992
+ distinctInjectedTasks.add(row.task_id);
993
+ }
994
+ else {
995
+ nullTaskSteps += 1;
996
+ if (row.injected_count > 0)
997
+ nullTaskInjected += 1;
998
+ }
999
+ }
1000
+ if (partition === 'holdout' || partition === 'all') {
1001
+ const holdoutRows = this.#database
1002
+ .prepare(`SELECT task_id FROM assoc_holdout_assignments
1003
+ WHERE owner_scope_key = ? AND in_holdout = 1 AND assigned_at >= ? AND assigned_at < ?`)
1004
+ .all(scopeKey, fromAt, toAt);
1005
+ for (const row of holdoutRows) {
1006
+ distinctMetricTasks.add(row.task_id);
1007
+ }
1008
+ }
1009
+ const exposureCols = new Set(this.#database.prepare('PRAGMA table_info(assoc_exposures)').all().map((col) => col.name));
1010
+ const hasWasExposed = exposureCols.has('was_exposed');
1011
+ const hasStrongUsed = exposureCols.has('strong_used');
1012
+ const hasWeakUsed = exposureCols.has('weak_used');
1013
+ const exposureRows = this.#database
1014
+ .prepare(`SELECT e.task_id, e.node_id, e.source_plugin, e.assoc_read_count, e.weak_use_count,
1015
+ ${hasStrongUsed ? 'e.strong_used' : 'NULL AS strong_used'},
1016
+ ${hasWeakUsed ? 'e.weak_used' : 'NULL AS weak_used'},
1017
+ e.corrected,
1018
+ n.kind AS node_kind,
1019
+ COALESCE(
1020
+ (SELECT h.in_holdout FROM assoc_holdout_assignments h WHERE h.task_id = e.task_id),
1021
+ (SELECT MAX(m.in_holdout) FROM assoc_step_metrics m WHERE m.task_id = e.task_id AND m.owner_scope_key = e.owner_scope_key),
1022
+ 0
1023
+ ) AS in_holdout
1024
+ FROM assoc_exposures e
1025
+ LEFT JOIN assoc_nodes n ON n.id = e.node_id
1026
+ WHERE e.owner_scope_key = ? AND e.exposed_at >= ? AND e.exposed_at < ?${hasWasExposed ? ' AND e.was_exposed = 1' : ''}`)
1027
+ .all(scopeKey, fromAt, toAt);
1028
+ const taskAgg = new Map();
1029
+ const sourceAgg = {
1030
+ memory: { total: 0, unusedOrCorrected: 0 },
1031
+ goal: { total: 0, unusedOrCorrected: 0 },
1032
+ 'work-item': { total: 0, unusedOrCorrected: 0 },
1033
+ automation: { total: 0, unusedOrCorrected: 0 },
1034
+ episode: { total: 0, unusedOrCorrected: 0 },
1035
+ wiki: { total: 0, unusedOrCorrected: 0 },
1036
+ skill: { total: 0, unusedOrCorrected: 0 },
1037
+ event: { total: 0, unusedOrCorrected: 0 },
1038
+ dream: { total: 0, unusedOrCorrected: 0 },
1039
+ abstraction: { total: 0, unusedOrCorrected: 0 },
1040
+ web: { total: 0, unusedOrCorrected: 0 },
1041
+ };
1042
+ for (const row of exposureRows) {
1043
+ if (partition === 'training' && row.in_holdout !== 0)
1044
+ continue;
1045
+ if (partition === 'holdout' && row.in_holdout !== 1)
1046
+ continue;
1047
+ distinctMetricTasks.add(row.task_id);
1048
+ distinctInjectedTasks.add(row.task_id);
1049
+ const cur = taskAgg.get(row.task_id) ?? { used: false, corrected: false };
1050
+ const isStrong = hasStrongUsed ? row.strong_used === 1 : row.assoc_read_count > 0;
1051
+ const isWeak = hasWeakUsed ? row.weak_used === 1 : row.weak_use_count > 0;
1052
+ const isUsed = isStrong || isWeak;
1053
+ const isCorrected = row.corrected === 1;
1054
+ if (isUsed)
1055
+ cur.used = true;
1056
+ if (isCorrected)
1057
+ cur.corrected = true;
1058
+ taskAgg.set(row.task_id, cur);
1059
+ const kind = row.node_kind ?? SOURCE_PLUGIN_TO_KIND[row.source_plugin];
1060
+ if (kind !== undefined) {
1061
+ sourceAgg[kind].total += 1;
1062
+ if (isCorrected || !isUsed) {
1063
+ sourceAgg[kind].unusedOrCorrected += 1;
1064
+ }
1065
+ }
1066
+ }
1067
+ let usedTasks = 0;
1068
+ let correctedTasks = 0;
1069
+ for (const agg of taskAgg.values()) {
1070
+ if (agg.used)
1071
+ usedTasks += 1;
1072
+ if (agg.corrected)
1073
+ correctedTasks += 1;
1074
+ }
1075
+ const sourceExposures = {};
1076
+ for (const kind of NODE_KINDS) {
1077
+ sourceExposures[kind] = Object.freeze({ ...sourceAgg[kind] });
1078
+ }
1079
+ return deepFreeze({
1080
+ fromAt,
1081
+ toAt,
1082
+ totalSteps: metricRows.length,
1083
+ timedOutSteps,
1084
+ p99LatencyUs: computeP99(latencies),
1085
+ injectedTasks: distinctInjectedTasks.size + nullTaskInjected,
1086
+ decidedTasks: distinctMetricTasks.size + nullTaskSteps,
1087
+ usedTasks,
1088
+ correctedTasks,
1089
+ sourceExposures: sourceExposures,
1090
+ });
1091
+ }
1092
+ #holdout(scopeKey, fromAt, toAt) {
1093
+ const rows = this.#database
1094
+ .prepare(`SELECT task_id FROM assoc_holdout_assignments
1095
+ WHERE owner_scope_key = ? AND in_holdout = 1 AND assigned_at >= ? AND assigned_at < ?
1096
+ UNION
1097
+ SELECT task_id FROM assoc_step_metrics
1098
+ WHERE owner_scope_key = ? AND in_holdout = 1 AND task_id IS NOT NULL AND occurred_at >= ? AND occurred_at < ?
1099
+ ORDER BY task_id ASC`)
1100
+ .all(scopeKey, fromAt, toAt, scopeKey, fromAt, toAt);
1101
+ const ids = rows.map((r) => r.task_id);
1102
+ const digest = growthObjectDigest({
1103
+ protocol: ASSOC_PARAM_HOLDOUT_PROTOCOL,
1104
+ scopeKey,
1105
+ fromAt,
1106
+ toAt,
1107
+ ids,
1108
+ });
1109
+ return deepFreeze({
1110
+ ids,
1111
+ seal: {
1112
+ protocol: ASSOC_PARAM_HOLDOUT_PROTOCOL,
1113
+ count: ids.length,
1114
+ digest,
1115
+ },
1116
+ });
1117
+ }
1118
+ #isParamsDigestBlocked(scopeKey, paramsDigest) {
1119
+ const row = this.#database
1120
+ .prepare('SELECT 1 AS ok FROM assoc_param_rolled_back_digests WHERE scope_key = ? AND params_digest = ?')
1121
+ .get(scopeKey, paramsDigest);
1122
+ return row !== undefined;
1123
+ }
1124
+ #inRollbackCooldown(scopeKey, now) {
1125
+ if (this.#policy.rollbackCooldownMs <= 0)
1126
+ return false;
1127
+ const row = this.#database
1128
+ .prepare('SELECT MAX(rolled_back_at) AS last_rolled_back_at FROM assoc_param_rolled_back_digests WHERE scope_key = ?')
1129
+ .get(scopeKey);
1130
+ if (row?.last_rolled_back_at == null)
1131
+ return false;
1132
+ return now - row.last_rolled_back_at < this.#policy.rollbackCooldownMs;
1133
+ }
1134
+ #nextEventIdempotencyKey(scopeKey, kind, now) {
1135
+ const row = this.#database
1136
+ .prepare('SELECT COALESCE(MAX(seq), 0) + 1 AS next_seq FROM assoc_param_profile_events')
1137
+ .get();
1138
+ return `evt:${growthObjectDigest([scopeKey, kind, now, row.next_seq])}`;
1139
+ }
1140
+ #event(scopeKey, kind, fromVersion, toVersion, fromDigest, toDigest, reason, detail, idempotencyKey, now) {
1141
+ const key = idempotencyKey ?? this.#nextEventIdempotencyKey(scopeKey, kind, now);
1142
+ this.#database
1143
+ .prepare(`INSERT INTO assoc_param_profile_events
1144
+ (scope_key, kind, from_version, to_version, from_digest, to_digest, reason, detail_json, idempotency_key, occurred_at)
1145
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
1146
+ ON CONFLICT(idempotency_key) DO NOTHING`)
1147
+ .run(scopeKey, kind, fromVersion, toVersion, fromDigest, toDigest, reason, canonicalGrowthJson(detail), key, now);
1148
+ }
1149
+ #adopt(scopeKey, head, current, proposal, stats, origin, reason, now, explicitIdempotencyKey, extraEventDetail) {
1150
+ const parentVersion = current.version;
1151
+ const idempotencyKey = explicitIdempotencyKey ??
1152
+ `adopt:${growthObjectDigest({
1153
+ scopeKey,
1154
+ parentVersion,
1155
+ parentDigest: current.digest,
1156
+ change: proposal.change,
1157
+ origin,
1158
+ changedAt: head?.changed_at ?? 0,
1159
+ })}`;
1160
+ const existing = this.#database
1161
+ .prepare('SELECT version FROM assoc_param_profile_versions WHERE idempotency_key = ?')
1162
+ .get(idempotencyKey);
1163
+ if (existing !== undefined)
1164
+ return existing.version;
1165
+ const version = (head?.latest_version ?? 0) + 1;
1166
+ const paramsDigest = growthObjectDigest(proposal.parameters);
1167
+ const basis = { stats };
1168
+ const digest = versionDigest({
1169
+ protocol: ASSOC_PARAM_PROFILE_PROTOCOL,
1170
+ scopeKey,
1171
+ version,
1172
+ parentVersion,
1173
+ parentDigest: current.digest,
1174
+ parameters: proposal.parameters,
1175
+ paramsDigest,
1176
+ basis,
1177
+ change: proposal.change,
1178
+ origin,
1179
+ });
1180
+ this.#database
1181
+ .prepare(`INSERT INTO assoc_param_profile_versions
1182
+ (scope_key, version, parent_version, params_json, params_digest, basis_json, change_json, origin, digest, idempotency_key, created_at)
1183
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`)
1184
+ .run(scopeKey, version, parentVersion, canonicalGrowthJson(proposal.parameters), paramsDigest, canonicalGrowthJson(basis), canonicalGrowthJson(proposal.change), origin, digest, idempotencyKey, now);
1185
+ const observeUntil = now + Math.max(1, this.#policy.observationMs);
1186
+ if (head === undefined) {
1187
+ this.#database
1188
+ .prepare(`INSERT INTO assoc_param_profile_heads
1189
+ (scope_key, active_version, latest_version, active_digest, state, observing_version, observe_from, observe_until, changed_at)
1190
+ VALUES (?, ?, ?, ?, 'observing', ?, ?, ?, ?)`)
1191
+ .run(scopeKey, version, version, digest, version, now, observeUntil, now);
1192
+ }
1193
+ else {
1194
+ this.#database
1195
+ .prepare(`UPDATE assoc_param_profile_heads
1196
+ SET active_version = ?, latest_version = ?, active_digest = ?, state = 'observing',
1197
+ observing_version = ?, observe_from = ?, observe_until = ?, changed_at = ?
1198
+ WHERE scope_key = ?`)
1199
+ .run(version, version, digest, version, now, observeUntil, now, scopeKey);
1200
+ }
1201
+ this.#event(scopeKey, 'adopted', parentVersion, version, current.digest, digest, reason, {
1202
+ digest,
1203
+ paramsDigest,
1204
+ change: proposal.change,
1205
+ origin,
1206
+ stats,
1207
+ ...extraEventDetail,
1208
+ }, idempotencyKey, now);
1209
+ return version;
1210
+ }
1211
+ #pendingProposal(scopeKey) {
1212
+ return this.#database
1213
+ .prepare(`SELECT p.* FROM assoc_param_relax_proposals p
1214
+ LEFT JOIN assoc_param_relax_decisions d ON d.proposal_id = p.proposal_id
1215
+ WHERE p.scope_key = ? AND d.proposal_id IS NULL
1216
+ ORDER BY p.created_at ASC, p.rowid ASC LIMIT 1`)
1217
+ .get(scopeKey);
1218
+ }
1219
+ #verifiedProposal(row, scopeKey) {
1220
+ try {
1221
+ const parentVersionInfo = this.#verified(scopeKey, row.parent_version);
1222
+ if (parentVersionInfo === undefined)
1223
+ return undefined;
1224
+ const candidate = normalizeAssocParamProfile(JSON.parse(row.candidate_json));
1225
+ const change = JSON.parse(row.change_json);
1226
+ const basisMeta = JSON.parse(row.basis_json);
1227
+ const body = {
1228
+ protocol: ASSOC_PARAM_RELAX_PROTOCOL,
1229
+ scopeKey,
1230
+ ordinal: basisMeta.ordinal,
1231
+ parentVersion: row.parent_version,
1232
+ parentDigest: row.parent_digest,
1233
+ parent: parentVersionInfo.parameters,
1234
+ candidate,
1235
+ change,
1236
+ reason: basisMeta.reason,
1237
+ window: { fromAt: row.window_from, toAt: row.window_to },
1238
+ holdout: {
1239
+ protocol: ASSOC_PARAM_HOLDOUT_PROTOCOL,
1240
+ count: basisMeta.holdoutCount,
1241
+ digest: row.holdout_seal,
1242
+ },
1243
+ basis: { stats: basisMeta.stats },
1244
+ createdAt: basisMeta.createdAt,
1245
+ };
1246
+ if (growthObjectDigest(body) !== row.proposal_id ||
1247
+ growthObjectDigest(candidate) !== row.params_digest ||
1248
+ basisMeta.createdAt !== row.created_at) {
1249
+ return undefined;
1250
+ }
1251
+ const checkedChange = describeRelaxationChange(parentVersionInfo.parameters, candidate, {
1252
+ minItems: this.#policy.minItems,
1253
+ });
1254
+ if (!withinAssocParamBounds(parentVersionInfo.parameters, { minItems: this.#policy.minItems }) ||
1255
+ !withinAssocParamBounds(candidate, { minItems: this.#policy.minItems }) ||
1256
+ checkedChange === undefined ||
1257
+ canonicalGrowthJson(checkedChange) !== canonicalGrowthJson(change)) {
1258
+ return undefined;
1259
+ }
1260
+ return deepFreeze(body);
1261
+ }
1262
+ catch {
1263
+ return undefined;
1264
+ }
1265
+ }
1266
+ requestChange(input) {
1267
+ const scopeKey = validateScopeKey(input.scopeKey);
1268
+ const requested = normalizeAssocParamProfile(input.candidate);
1269
+ const reason = input.reason.trim() || 'explicit-request';
1270
+ return this.#transaction(() => {
1271
+ const now = input.nowMs ?? this.#now();
1272
+ const head = this.#head(scopeKey);
1273
+ const current = this.#current(scopeKey);
1274
+ const direction = classifyProfileChange(current.parameters, requested);
1275
+ if (direction === 'identical') {
1276
+ this.#event(scopeKey, 'request-rejected', current.version, current.version, current.digest, current.digest, 'no-change', { current: current.parameters, requested }, null, now);
1277
+ return Object.freeze({ status: 'rejected', reason: 'no-change' });
1278
+ }
1279
+ if (direction === 'relax') {
1280
+ if (!this.#policy.relaxationReplayEnabled) {
1281
+ this.#event(scopeKey, 'request-rejected', current.version, current.version, current.digest, current.digest, 'loosening-requires-holdout', { current: current.parameters, requested }, null, now);
1282
+ return Object.freeze({
1283
+ status: 'rejected',
1284
+ reason: 'loosening-requires-holdout',
1285
+ });
1286
+ }
1287
+ const change = describeRelaxationChange(current.parameters, requested, {
1288
+ minItems: this.#policy.minItems,
1289
+ });
1290
+ const candDigest = growthObjectDigest(requested);
1291
+ const rejectReason = !withinAssocParamBounds(requested, { minItems: this.#policy.minItems })
1292
+ ? 'out-of-bounds'
1293
+ : change === undefined
1294
+ ? 'not-single-parameter'
1295
+ : head?.state === 'observing'
1296
+ ? 'observation-in-progress'
1297
+ : this.#pendingProposal(scopeKey) !== undefined
1298
+ ? 'proposal-pending'
1299
+ : this.#isParamsDigestBlocked(scopeKey, candDigest)
1300
+ ? 'digest-previously-rolled-back'
1301
+ : this.#inRollbackCooldown(scopeKey, now)
1302
+ ? 'rollback-cooldown'
1303
+ : undefined;
1304
+ if (rejectReason !== undefined || change === undefined) {
1305
+ const code = rejectReason ?? 'not-single-parameter';
1306
+ this.#event(scopeKey, 'request-rejected', current.version, current.version, current.digest, current.digest, code, { current: current.parameters, requested }, null, now);
1307
+ return Object.freeze({ status: 'rejected', reason: code });
1308
+ }
1309
+ const window = {
1310
+ fromAt: Math.max(0, now - this.#policy.relaxReplayWindowMs),
1311
+ toAt: now + 1,
1312
+ };
1313
+ const holdout = this.#holdout(scopeKey, window.fromAt, window.toAt);
1314
+ const ordinal = this.#database
1315
+ .prepare('SELECT COUNT(*) AS count FROM assoc_param_relax_proposals WHERE scope_key = ?')
1316
+ .get(scopeKey).count + 1;
1317
+ const basisStats = this.stats(scopeKey, window.fromAt, window.toAt, 'training');
1318
+ const body = {
1319
+ protocol: ASSOC_PARAM_RELAX_PROTOCOL,
1320
+ scopeKey,
1321
+ ordinal,
1322
+ parentVersion: current.version,
1323
+ parentDigest: current.digest,
1324
+ parent: current.parameters,
1325
+ candidate: requested,
1326
+ change,
1327
+ reason,
1328
+ window,
1329
+ holdout: holdout.seal,
1330
+ basis: { stats: basisStats },
1331
+ createdAt: now,
1332
+ };
1333
+ const proposalId = growthObjectDigest(body);
1334
+ const storedBasis = {
1335
+ stats: basisStats,
1336
+ ordinal,
1337
+ reason,
1338
+ holdoutCount: holdout.seal.count,
1339
+ createdAt: now,
1340
+ };
1341
+ this.#database
1342
+ .prepare(`INSERT INTO assoc_param_relax_proposals
1343
+ (proposal_id, scope_key, parent_version, parent_digest, candidate_json, params_digest, change_json, holdout_seal, window_from, window_to, basis_json, status, created_at)
1344
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'pending', ?)`)
1345
+ .run(proposalId, scopeKey, current.version, current.digest, canonicalGrowthJson(requested), candDigest, canonicalGrowthJson(change), holdout.seal.digest, window.fromAt, window.toAt, canonicalGrowthJson(storedBasis), now);
1346
+ return deepFreeze({
1347
+ status: 'proposed',
1348
+ proposalId,
1349
+ holdout: holdout.seal,
1350
+ });
1351
+ }
1352
+ if (input.idempotencyKey !== undefined) {
1353
+ const existing = this.#database
1354
+ .prepare('SELECT version, change_json FROM assoc_param_profile_versions WHERE idempotency_key = ?')
1355
+ .get(input.idempotencyKey);
1356
+ if (existing !== undefined) {
1357
+ return deepFreeze({
1358
+ status: 'adopted',
1359
+ version: existing.version,
1360
+ change: JSON.parse(existing.change_json),
1361
+ });
1362
+ }
1363
+ }
1364
+ const change = describeSingleTighteningStep(current.parameters, requested, {
1365
+ minItems: this.#policy.minItems,
1366
+ });
1367
+ const candDigest = growthObjectDigest(requested);
1368
+ const rejectReason = !withinAssocParamBounds(requested, { minItems: this.#policy.minItems })
1369
+ ? 'out-of-bounds'
1370
+ : change === undefined
1371
+ ? 'not-single-step'
1372
+ : !this.#policy.autoTightenEnabled
1373
+ ? 'auto-adoption-disabled'
1374
+ : head?.state === 'observing'
1375
+ ? 'observation-in-progress'
1376
+ : this.#isParamsDigestBlocked(scopeKey, candDigest)
1377
+ ? 'digest-previously-rolled-back'
1378
+ : this.#inRollbackCooldown(scopeKey, now)
1379
+ ? 'rollback-cooldown'
1380
+ : undefined;
1381
+ if (rejectReason !== undefined || change === undefined) {
1382
+ const code = rejectReason ?? 'not-single-step';
1383
+ this.#event(scopeKey, 'request-rejected', current.version, current.version, current.digest, current.digest, code, { current: current.parameters, requested }, null, now);
1384
+ return Object.freeze({ status: 'rejected', reason: code });
1385
+ }
1386
+ const fromAt = Math.max(0, head?.changed_at ?? 0, now - this.#policy.evaluationWindowMs);
1387
+ const stats = this.stats(scopeKey, fromAt, now + 1, 'training');
1388
+ const version = this.#adopt(scopeKey, head, current, { change, parameters: requested }, stats, 'manual', reason, now, input.idempotencyKey);
1389
+ return deepFreeze({ status: 'adopted', version, change });
1390
+ });
1391
+ }
1392
+ #resolveScopeFilter(scopeKey, index, filterTemplate) {
1393
+ const scopeRow = this.#database
1394
+ .prepare('SELECT workspace, agent_preset FROM assoc_owner_scopes WHERE owner_scope_key = ?')
1395
+ .get(scopeKey);
1396
+ let workspace = filterTemplate?.workspace ?? scopeRow?.workspace;
1397
+ let agentPreset = filterTemplate?.agentPreset ?? scopeRow?.agent_preset;
1398
+ if (workspace === undefined || agentPreset === undefined) {
1399
+ const ownerIdx = index.ownerKeys.get(scopeKey);
1400
+ if (ownerIdx !== undefined) {
1401
+ for (let slot = 0; slot < index.nodeCount; slot += 1) {
1402
+ if (index.nodeOwnerIdx[slot] !== ownerIdx)
1403
+ continue;
1404
+ if (workspace === undefined) {
1405
+ const wsIdx = index.nodeWorkspaceIdx[slot];
1406
+ for (const [k, v] of index.workspaces.entries()) {
1407
+ if (v === wsIdx) {
1408
+ workspace = k;
1409
+ break;
1410
+ }
1411
+ }
1412
+ }
1413
+ if (agentPreset === undefined) {
1414
+ const pIdx = index.nodePresetIdx[slot];
1415
+ for (const [k, v] of index.presets.entries()) {
1416
+ if (v === pIdx) {
1417
+ agentPreset = k;
1418
+ break;
1419
+ }
1420
+ }
1421
+ }
1422
+ if (workspace !== undefined && agentPreset !== undefined)
1423
+ break;
1424
+ }
1425
+ }
1426
+ }
1427
+ return {
1428
+ ownerScopeKey: scopeKey,
1429
+ workspace: workspace ?? '',
1430
+ agentPreset: agentPreset ?? '',
1431
+ allowLowTrust: filterTemplate?.allowLowTrust ?? true,
1432
+ allowSensitive: filterTemplate?.allowSensitive ?? false,
1433
+ };
1434
+ }
1435
+ #replayRelaxation(scopeKey, proposal, index, filterTemplate) {
1436
+ const { fromAt, toAt } = proposal.window;
1437
+ const holdoutStats = this.stats(scopeKey, fromAt, toAt, 'holdout');
1438
+ const trainingStats = this.stats(scopeKey, fromAt, toAt, 'training');
1439
+ const emptyTally = { timeouts: 0, p99Ms: 0, usedHits: 0, noiseExposed: 0 };
1440
+ const fail = (failureReason, episodeCount, parentTally, candidateTally) => deepFreeze({
1441
+ protocol: ASSOC_PARAM_RELAX_PROTOCOL,
1442
+ episodeCount,
1443
+ holdoutDecided: holdoutStats.decidedTasks,
1444
+ trainingDecided: trainingStats.decidedTasks,
1445
+ parent: parentTally,
1446
+ candidate: candidateTally,
1447
+ verdict: 'fail',
1448
+ failureReason,
1449
+ });
1450
+ if (holdoutStats.decidedTasks < this.#policy.minHoldoutSamples) {
1451
+ return fail('insufficient-holdout', 0, emptyTally, emptyTally);
1452
+ }
1453
+ if (trainingStats.injectedTasks > 0 &&
1454
+ atLeastRate(trainingStats.correctedTasks, trainingStats.injectedTasks, this.#policy.highCorrectionRatePpm)) {
1455
+ return fail('holdout-regression', 0, emptyTally, emptyTally);
1456
+ }
1457
+ if (holdoutStats.injectedTasks > 0 && trainingStats.injectedTasks > 0) {
1458
+ const left = BigInt(trainingStats.correctedTasks) * BigInt(holdoutStats.injectedTasks) * 1000000n;
1459
+ const right = BigInt(holdoutStats.correctedTasks) * BigInt(trainingStats.injectedTasks) * 1000000n +
1460
+ BigInt(this.#policy.regressionMarginPpm) *
1461
+ BigInt(holdoutStats.injectedTasks) *
1462
+ BigInt(trainingStats.injectedTasks);
1463
+ if (left > right) {
1464
+ return fail('holdout-regression', 0, emptyTally, emptyTally);
1465
+ }
1466
+ }
1467
+ if (holdoutStats.totalSteps > 0 && trainingStats.totalSteps > 0) {
1468
+ const effectiveTimeoutMarginPpm = Math.min(this.#policy.timeoutMarginPpm, this.#policy.maxTimeoutMarginPpm);
1469
+ const left = BigInt(trainingStats.timedOutSteps) * BigInt(holdoutStats.totalSteps) * 1000000n;
1470
+ const right = BigInt(holdoutStats.timedOutSteps) * BigInt(trainingStats.totalSteps) * 1000000n +
1471
+ BigInt(effectiveTimeoutMarginPpm) *
1472
+ BigInt(holdoutStats.totalSteps) *
1473
+ BigInt(trainingStats.totalSteps);
1474
+ if (left > right) {
1475
+ return fail('holdout-regression', 0, emptyTally, emptyTally);
1476
+ }
1477
+ }
1478
+ const episodes = this.#database
1479
+ .prepare(`SELECT task_id, cues_json, used_node_ids_json, corrected_node_ids_json, occurred_at
1480
+ FROM assoc_replay_episodes
1481
+ WHERE owner_scope_key = ? AND in_holdout = 0 AND occurred_at >= ? AND occurred_at < ?
1482
+ ORDER BY occurred_at ASC, task_id ASC`)
1483
+ .all(scopeKey, fromAt, toAt);
1484
+ if (index === undefined || episodes.length === 0) {
1485
+ return fail('insufficient-replay-episodes', episodes.length, emptyTally, emptyTally);
1486
+ }
1487
+ const baseFilter = this.#resolveScopeFilter(scopeKey, index, filterTemplate);
1488
+ const parentProfile = toHotPathProfile(proposal.parent, this.#baseConfig);
1489
+ const candidateProfile = toHotPathProfile(proposal.candidate, this.#baseConfig);
1490
+ const queryOpt = this.#hotPathClock === undefined ? undefined : { clock: this.#hotPathClock };
1491
+ let parentTimeouts = 0;
1492
+ let candidateTimeouts = 0;
1493
+ const parentLatencies = [];
1494
+ const candidateLatencies = [];
1495
+ let parentUsedHits = 0;
1496
+ let candidateUsedHits = 0;
1497
+ let parentNoise = 0;
1498
+ let candidateNoise = 0;
1499
+ for (const ep of episodes) {
1500
+ const cues = JSON.parse(ep.cues_json);
1501
+ const usedSet = new Set(JSON.parse(ep.used_node_ids_json));
1502
+ const correctedSet = new Set(JSON.parse(ep.corrected_node_ids_json));
1503
+ const filter = { ...baseFilter, nowMs: ep.occurred_at };
1504
+ const pRes = runHotPathQuery(index, cues, filter, parentProfile, queryOpt);
1505
+ const cRes = runHotPathQuery(index, cues, filter, candidateProfile, queryOpt);
1506
+ if (pRes.timedOut)
1507
+ parentTimeouts += 1;
1508
+ if (cRes.timedOut)
1509
+ candidateTimeouts += 1;
1510
+ parentLatencies.push(pRes.elapsedMs);
1511
+ candidateLatencies.push(cRes.elapsedMs);
1512
+ for (const item of pRes.items) {
1513
+ if (usedSet.has(item.id))
1514
+ parentUsedHits += 1;
1515
+ else if (correctedSet.has(item.id))
1516
+ parentNoise += 2;
1517
+ else
1518
+ parentNoise += 1;
1519
+ }
1520
+ for (const item of cRes.items) {
1521
+ if (usedSet.has(item.id))
1522
+ candidateUsedHits += 1;
1523
+ else if (correctedSet.has(item.id))
1524
+ candidateNoise += 2;
1525
+ else
1526
+ candidateNoise += 1;
1527
+ }
1528
+ }
1529
+ const parentTally = {
1530
+ timeouts: parentTimeouts,
1531
+ p99Ms: computeP99(parentLatencies),
1532
+ usedHits: parentUsedHits,
1533
+ noiseExposed: parentNoise,
1534
+ };
1535
+ const candidateTally = {
1536
+ timeouts: candidateTimeouts,
1537
+ p99Ms: computeP99(candidateLatencies),
1538
+ usedHits: candidateUsedHits,
1539
+ noiseExposed: candidateNoise,
1540
+ };
1541
+ if (candidateTally.timeouts > parentTally.timeouts) {
1542
+ return fail('replay-timeouts', episodes.length, parentTally, candidateTally);
1543
+ }
1544
+ if (candidateTally.p99Ms > this.#policy.hotPathBudgetMs) {
1545
+ return fail('latency-budget-exceeded', episodes.length, parentTally, candidateTally);
1546
+ }
1547
+ if (candidateTally.usedHits < parentTally.usedHits) {
1548
+ return fail('recall-regression', episodes.length, parentTally, candidateTally);
1549
+ }
1550
+ const usedGain = candidateTally.usedHits - parentTally.usedHits;
1551
+ const noiseGain = candidateTally.noiseExposed - parentTally.noiseExposed;
1552
+ if (usedGain <= noiseGain) {
1553
+ return fail('no-net-benefit', episodes.length, parentTally, candidateTally);
1554
+ }
1555
+ return deepFreeze({
1556
+ protocol: ASSOC_PARAM_RELAX_PROTOCOL,
1557
+ episodeCount: episodes.length,
1558
+ holdoutDecided: holdoutStats.decidedTasks,
1559
+ trainingDecided: trainingStats.decidedTasks,
1560
+ parent: parentTally,
1561
+ candidate: candidateTally,
1562
+ verdict: 'pass',
1563
+ });
1564
+ }
1565
+ #decideRelaxation(scopeKey, head, row, now, index, filterTemplate) {
1566
+ const proposalId = row.proposal_id;
1567
+ const current = this.#current(scopeKey);
1568
+ const reject = (reason, replay) => {
1569
+ const decisionId = growthObjectDigest({ proposalId, status: 'rejected', reason, now });
1570
+ this.#database
1571
+ .prepare(`INSERT INTO assoc_param_relax_decisions
1572
+ (decision_id, proposal_id, scope_key, status, reason, replay_json, decided_at)
1573
+ VALUES (?, ?, ?, 'rejected', ?, ?, ?)`)
1574
+ .run(decisionId, proposalId, scopeKey, reason, canonicalGrowthJson(replay), now);
1575
+ this.#event(scopeKey, 'request-rejected', current.version, current.version, current.digest, current.digest, reason, { proposalId, replay }, `relax:${proposalId}`, now);
1576
+ return deepFreeze({
1577
+ action: 'relax-rejected',
1578
+ reason,
1579
+ proposalId,
1580
+ ...(replay === null ? {} : { replay }),
1581
+ });
1582
+ };
1583
+ const proposal = this.#verifiedProposal(row, scopeKey);
1584
+ if (proposal === undefined) {
1585
+ return reject('proposal-unverifiable', null);
1586
+ }
1587
+ if (current.version !== proposal.parentVersion ||
1588
+ current.digest !== proposal.parentDigest ||
1589
+ canonicalGrowthJson(current.parameters) !== canonicalGrowthJson(proposal.parent)) {
1590
+ return reject('stale-parent', null);
1591
+ }
1592
+ const candDigest = growthObjectDigest(proposal.candidate);
1593
+ if (this.#isParamsDigestBlocked(scopeKey, candDigest)) {
1594
+ return reject('digest-previously-rolled-back', null);
1595
+ }
1596
+ if (this.#inRollbackCooldown(scopeKey, now)) {
1597
+ return reject('rollback-cooldown', null);
1598
+ }
1599
+ const holdout = this.#holdout(scopeKey, proposal.window.fromAt, proposal.window.toAt);
1600
+ if (holdout.seal.digest !== proposal.holdout.digest) {
1601
+ return reject('holdout-drifted', null);
1602
+ }
1603
+ const replay = this.#replayRelaxation(scopeKey, proposal, index, filterTemplate);
1604
+ if (replay.verdict === 'fail') {
1605
+ return reject('holdout-failed', replay);
1606
+ }
1607
+ const version = this.#adopt(scopeKey, head, current, { change: proposal.change, parameters: proposal.candidate }, proposal.basis.stats, 'replay', proposal.reason || 'holdout-replay-accepted', now, `relax-adopt:${proposalId}`, { proposalId, replay });
1608
+ const decisionId = growthObjectDigest({
1609
+ proposalId,
1610
+ status: 'adopted',
1611
+ reason: 'holdout-replay-accepted',
1612
+ version,
1613
+ now,
1614
+ });
1615
+ this.#database
1616
+ .prepare(`INSERT INTO assoc_param_relax_decisions
1617
+ (decision_id, proposal_id, scope_key, status, reason, replay_json, decided_at)
1618
+ VALUES (?, ?, ?, 'adopted', 'holdout-replay-accepted', ?, ?)`)
1619
+ .run(decisionId, proposalId, scopeKey, canonicalGrowthJson(replay), now);
1620
+ return deepFreeze({
1621
+ action: 'relax-adopted',
1622
+ version,
1623
+ change: proposal.change,
1624
+ proposalId,
1625
+ replay,
1626
+ });
1627
+ }
1628
+ tick(input) {
1629
+ const scopeKey = validateScopeKey(input.scopeKey);
1630
+ return this.#transaction(() => {
1631
+ const now = input.nowMs ?? this.#now();
1632
+ const head = this.#head(scopeKey);
1633
+ if (head?.state === 'observing') {
1634
+ const observed = head.observing_version;
1635
+ const version = this.#verified(scopeKey, observed);
1636
+ const post = this.stats(scopeKey, head.observe_from, now + 1, 'training');
1637
+ const regression = version === undefined
1638
+ ? { regressed: true, reason: 'version-unverifiable' }
1639
+ : hasAssocObservedRegression(version.basis.stats, post, this.#policy);
1640
+ if (version === undefined || regression.regressed) {
1641
+ const rowInfo = this.#database
1642
+ .prepare('SELECT parent_version, params_digest, digest FROM assoc_param_profile_versions WHERE scope_key = ? AND version = ?')
1643
+ .get(scopeKey, observed);
1644
+ const rawParent = rowInfo?.parent_version;
1645
+ let candidate = rawParent != null &&
1646
+ Number.isSafeInteger(rawParent) &&
1647
+ rawParent >= 0 &&
1648
+ rawParent < observed
1649
+ ? rawParent
1650
+ : 0;
1651
+ let parentInfo;
1652
+ const visited = new Set();
1653
+ while (candidate > 0 && !visited.has(candidate)) {
1654
+ visited.add(candidate);
1655
+ parentInfo = this.#verified(scopeKey, candidate);
1656
+ if (parentInfo !== undefined)
1657
+ break;
1658
+ const nextParent = this.#database
1659
+ .prepare('SELECT parent_version FROM assoc_param_profile_versions WHERE scope_key = ? AND version = ?')
1660
+ .get(scopeKey, candidate)?.parent_version;
1661
+ candidate =
1662
+ Number.isSafeInteger(nextParent) &&
1663
+ nextParent >= 0 &&
1664
+ nextParent < candidate
1665
+ ? nextParent
1666
+ : 0;
1667
+ }
1668
+ parentInfo ??= this.#verified(scopeKey, 0);
1669
+ const parentVersion = parentInfo.version;
1670
+ const parentDigest = parentInfo.digest;
1671
+ this.#database
1672
+ .prepare(`UPDATE assoc_param_profile_heads
1673
+ SET active_version = ?, active_digest = ?, state = 'idle', observing_version = NULL,
1674
+ observe_from = NULL, observe_until = NULL, changed_at = ?
1675
+ WHERE scope_key = ?`)
1676
+ .run(parentVersion, parentDigest, now, scopeKey);
1677
+ const reason = regression.reason ?? 'observed-regression';
1678
+ const rolledBackParamsDigest = version?.paramsDigest ?? rowInfo?.params_digest;
1679
+ if (rolledBackParamsDigest !== undefined) {
1680
+ this.#database
1681
+ .prepare(`INSERT INTO assoc_param_rolled_back_digests
1682
+ (scope_key, params_digest, rolled_back_at, from_version, reason)
1683
+ VALUES (?, ?, ?, ?, ?)
1684
+ ON CONFLICT(scope_key, params_digest) DO UPDATE SET
1685
+ rolled_back_at = excluded.rolled_back_at,
1686
+ from_version = excluded.from_version,
1687
+ reason = excluded.reason`)
1688
+ .run(scopeKey, rolledBackParamsDigest, now, observed, reason);
1689
+ }
1690
+ this.#event(scopeKey, 'rolled-back', observed, parentVersion, version?.digest ?? rowInfo?.digest ?? null, parentDigest, reason, {
1691
+ basis: version?.basis.stats ?? null,
1692
+ post,
1693
+ rolledBackParamsDigest: rolledBackParamsDigest ?? null,
1694
+ }, `rollback:${growthObjectDigest([scopeKey, observed, parentVersion, now])}`, now);
1695
+ return Object.freeze({
1696
+ action: 'rolled-back',
1697
+ fromVersion: observed,
1698
+ toVersion: parentVersion,
1699
+ reason,
1700
+ });
1701
+ }
1702
+ if (now >= head.observe_until) {
1703
+ this.#database
1704
+ .prepare(`UPDATE assoc_param_profile_heads
1705
+ SET state = 'idle', observing_version = NULL,
1706
+ observe_from = NULL, observe_until = NULL, changed_at = ?
1707
+ WHERE scope_key = ?`)
1708
+ .run(now, scopeKey);
1709
+ this.#event(scopeKey, 'settled', observed, observed, version.digest, version.digest, 'observation-complete', { post }, `settle:${growthObjectDigest([scopeKey, observed, head.observe_from])}`, now);
1710
+ return Object.freeze({ action: 'settled', version: observed });
1711
+ }
1712
+ return Object.freeze({ action: 'observing', version: observed });
1713
+ }
1714
+ if (this.#policy.relaxationReplayEnabled) {
1715
+ const pending = this.#pendingProposal(scopeKey);
1716
+ if (pending !== undefined) {
1717
+ return this.#decideRelaxation(scopeKey, head, pending, now, input.index, input.filterTemplate);
1718
+ }
1719
+ }
1720
+ if (!this.#policy.autoTightenEnabled) {
1721
+ return Object.freeze({ action: 'no-op', reason: 'disabled' });
1722
+ }
1723
+ if (this.#inRollbackCooldown(scopeKey, now)) {
1724
+ return Object.freeze({ action: 'no-op', reason: 'rollback-cooldown' });
1725
+ }
1726
+ const current = this.#current(scopeKey);
1727
+ const fromAt = Math.max(0, head?.changed_at ?? 0, now - this.#policy.evaluationWindowMs);
1728
+ const stats = this.stats(scopeKey, fromAt, now + 1, 'training');
1729
+ const proposal = proposeAssocParamTightening(current.parameters, stats, this.#policy, (paramsDigest) => this.#isParamsDigestBlocked(scopeKey, paramsDigest));
1730
+ if (proposal.kind === 'no-op') {
1731
+ return Object.freeze({ action: 'no-op', reason: proposal.reason });
1732
+ }
1733
+ const version = this.#adopt(scopeKey, head, current, { change: proposal.change, parameters: proposal.parameters }, stats, 'auto', proposal.triggerReason, now);
1734
+ return deepFreeze({
1735
+ action: 'adopted',
1736
+ version,
1737
+ change: proposal.change,
1738
+ triggerReason: proposal.triggerReason,
1739
+ });
1740
+ });
1741
+ }
1742
+ }
1743
+ //# sourceMappingURL=param-tuning.js.map