@dzhechkov/harness-core 0.7.11 → 0.8.1

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 (137) hide show
  1. package/.dz-manifest.json +287 -87
  2. package/README.md +60 -1
  3. package/dist/amendment-trace.d.ts +12 -1
  4. package/dist/amendment-trace.d.ts.map +1 -1
  5. package/dist/amendment-trace.js +22 -4
  6. package/dist/amendment-trace.js.map +1 -1
  7. package/dist/book-kb.d.ts.map +1 -1
  8. package/dist/book-kb.js +17 -0
  9. package/dist/book-kb.js.map +1 -1
  10. package/dist/feature-adr-checkpoints.d.ts +61 -0
  11. package/dist/feature-adr-checkpoints.d.ts.map +1 -1
  12. package/dist/feature-adr-checkpoints.js +116 -2
  13. package/dist/feature-adr-checkpoints.js.map +1 -1
  14. package/dist/feature-adr-routing.d.ts +69 -12
  15. package/dist/feature-adr-routing.d.ts.map +1 -1
  16. package/dist/feature-adr-routing.js +117 -7
  17. package/dist/feature-adr-routing.js.map +1 -1
  18. package/dist/index.d.ts +23 -6
  19. package/dist/index.d.ts.map +1 -1
  20. package/dist/index.js +23 -4
  21. package/dist/index.js.map +1 -1
  22. package/dist/learning-backend.d.ts +39 -0
  23. package/dist/learning-backend.d.ts.map +1 -1
  24. package/dist/learning-backend.js +31 -11
  25. package/dist/learning-backend.js.map +1 -1
  26. package/dist/lesson-bandit.d.ts +116 -0
  27. package/dist/lesson-bandit.d.ts.map +1 -0
  28. package/dist/lesson-bandit.js +235 -0
  29. package/dist/lesson-bandit.js.map +1 -0
  30. package/dist/lesson-payoff.d.ts +260 -0
  31. package/dist/lesson-payoff.d.ts.map +1 -0
  32. package/dist/lesson-payoff.js +597 -0
  33. package/dist/lesson-payoff.js.map +1 -0
  34. package/dist/loop-blobs.generated.js +2 -2
  35. package/dist/loop-blobs.generated.js.map +1 -1
  36. package/dist/mutation-gate.d.ts +31 -8
  37. package/dist/mutation-gate.d.ts.map +1 -1
  38. package/dist/mutation-gate.js +57 -16
  39. package/dist/mutation-gate.js.map +1 -1
  40. package/dist/named-lock.d.ts.map +1 -1
  41. package/dist/named-lock.js +11 -9
  42. package/dist/named-lock.js.map +1 -1
  43. package/dist/native-dep-probe.d.ts +11 -0
  44. package/dist/native-dep-probe.d.ts.map +1 -0
  45. package/dist/native-dep-probe.js +100 -0
  46. package/dist/native-dep-probe.js.map +1 -0
  47. package/dist/operations.d.ts.map +1 -1
  48. package/dist/operations.js +82 -1
  49. package/dist/operations.js.map +1 -1
  50. package/dist/parser-safe-region.d.ts +47 -0
  51. package/dist/parser-safe-region.d.ts.map +1 -0
  52. package/dist/parser-safe-region.js +47 -0
  53. package/dist/parser-safe-region.js.map +1 -0
  54. package/dist/patterns.d.ts +21 -0
  55. package/dist/patterns.d.ts.map +1 -1
  56. package/dist/patterns.js +52 -4
  57. package/dist/patterns.js.map +1 -1
  58. package/dist/profile.d.ts +202 -0
  59. package/dist/profile.d.ts.map +1 -0
  60. package/dist/profile.js +536 -0
  61. package/dist/profile.js.map +1 -0
  62. package/dist/project-skills-root.d.ts +44 -0
  63. package/dist/project-skills-root.d.ts.map +1 -0
  64. package/dist/project-skills-root.js +62 -0
  65. package/dist/project-skills-root.js.map +1 -0
  66. package/dist/publish.d.ts +5 -3
  67. package/dist/publish.d.ts.map +1 -1
  68. package/dist/publish.js +46 -8
  69. package/dist/publish.js.map +1 -1
  70. package/dist/qe-rounds.d.ts +75 -0
  71. package/dist/qe-rounds.d.ts.map +1 -0
  72. package/dist/qe-rounds.js +174 -0
  73. package/dist/qe-rounds.js.map +1 -0
  74. package/dist/registry.d.ts.map +1 -1
  75. package/dist/registry.js +5 -1
  76. package/dist/registry.js.map +1 -1
  77. package/dist/run-records.d.ts.map +1 -1
  78. package/dist/run-records.js +8 -1
  79. package/dist/run-records.js.map +1 -1
  80. package/dist/setup.d.ts +35 -4
  81. package/dist/setup.d.ts.map +1 -1
  82. package/dist/setup.js +86 -23
  83. package/dist/setup.js.map +1 -1
  84. package/dist/sign.d.ts +29 -24
  85. package/dist/sign.d.ts.map +1 -1
  86. package/dist/sign.js +183 -61
  87. package/dist/sign.js.map +1 -1
  88. package/dist/store-location.d.ts +56 -0
  89. package/dist/store-location.d.ts.map +1 -0
  90. package/dist/store-location.js +56 -0
  91. package/dist/store-location.js.map +1 -0
  92. package/dist/store-lock.d.ts +1 -0
  93. package/dist/store-lock.d.ts.map +1 -1
  94. package/dist/store-lock.js +7 -1
  95. package/dist/store-lock.js.map +1 -1
  96. package/dist/store-merge.d.ts +55 -0
  97. package/dist/store-merge.d.ts.map +1 -0
  98. package/dist/store-merge.js +77 -0
  99. package/dist/store-merge.js.map +1 -0
  100. package/dist/teach-target.d.ts +61 -0
  101. package/dist/teach-target.d.ts.map +1 -0
  102. package/dist/teach-target.js +105 -0
  103. package/dist/teach-target.js.map +1 -0
  104. package/dist/vector-tier.d.ts +30 -0
  105. package/dist/vector-tier.d.ts.map +1 -1
  106. package/dist/vector-tier.js +178 -20
  107. package/dist/vector-tier.js.map +1 -1
  108. package/package.json +13 -13
  109. package/sbom.json +591 -87
  110. package/src/amendment-trace.ts +34 -4
  111. package/src/book-kb.ts +17 -0
  112. package/src/feature-adr-checkpoints.ts +111 -2
  113. package/src/feature-adr-routing.ts +146 -7
  114. package/src/index.ts +55 -3
  115. package/src/learning-backend.ts +62 -11
  116. package/src/lesson-bandit.ts +279 -0
  117. package/src/lesson-payoff.ts +728 -0
  118. package/src/loop-blobs.generated.ts +2 -2
  119. package/src/mutation-gate.ts +74 -17
  120. package/src/named-lock.ts +10 -8
  121. package/src/native-dep-probe.ts +118 -0
  122. package/src/operations.ts +77 -1
  123. package/src/parser-safe-region.ts +65 -0
  124. package/src/patterns.ts +76 -6
  125. package/src/profile.ts +593 -0
  126. package/src/project-skills-root.ts +63 -0
  127. package/src/publish.ts +43 -7
  128. package/src/qe-rounds.ts +226 -0
  129. package/src/registry.ts +5 -1
  130. package/src/run-records.ts +9 -1
  131. package/src/setup.ts +87 -23
  132. package/src/sign.ts +180 -60
  133. package/src/store-location.ts +76 -0
  134. package/src/store-lock.ts +8 -1
  135. package/src/store-merge.ts +91 -0
  136. package/src/teach-target.ts +126 -0
  137. package/src/vector-tier.ts +236 -21
@@ -0,0 +1,597 @@
1
+ /**
2
+ * Lesson Payoff — the anti-corruption layer around the vendored bandit engine
3
+ * (feature lesson-bandit-rerank; ADR-001 / ADR-002 / ADR-003, domain model §6).
4
+ *
5
+ * WHAT THIS OWNS. One question: *how often did THIS lesson, in THIS kind of situation, actually
6
+ * resolve a problem?* It knows a lesson only as an opaque `ArmKey` (its `dzId`). It never reads
7
+ * lesson text, never writes to the pattern store, never decides candidate membership, and never
8
+ * touches quarantine state (INV-9).
9
+ *
10
+ * WHY AN ACL WHEN WE OWN THE COPY. Vendoring gives us the FILE, not the LANGUAGE. The engine's
11
+ * only counter-advancing method (`recordReward`) also moves the Beta parameters, so there is no way
12
+ * to tell it "a pull happened, no evidence either way". Our domain MUST be able to say that: an
13
+ * EXPOSURE is not a REWARD (INV-2 — the defect cross-model QE already removed once from
14
+ * `patterns.ts`, where recall-hit telemetry was silently promoting every viewed lesson). So the
15
+ * exposure counter lives in OUR envelope, beside the engine payload, and INV-2 is true by DATA
16
+ * LAYOUT rather than by call-site discipline: there is no field in `bandit.contexts` an exposure is
17
+ * allowed to touch.
18
+ *
19
+ * DETERMINISM (ADR-001 D-2 / D-7, reaffirmed by ADR-003's P5). The default payoff term is the
20
+ * POSTERIOR MEAN `alpha/(alpha+beta)`, mapped to `[-1,+1]`, using ONLY `getArmStats` — never
21
+ * `selectArm`, never `rerank`. Both of those Thompson-SAMPLE (`Math.random()` on every zero-pull
22
+ * arm), which would make two identical recalls disagree, defeat the byte-identity proof, and hand
23
+ * quarantined lessons a random lift. `05_architecture.md` §3 and `04_domain_model.md` §6.2 sketch an
24
+ * order-projection over `rerank()` instead; that draft is refuted by ADR-003's P5 ("with
25
+ * `banditExploration` absent, no `Math.random()` is consumed on the recall path"), which `rerank`
26
+ * cannot satisfy. The ADRs are the decision record and they win; this file implements them, and the
27
+ * bound the order-projection was chosen for is preserved exactly — the term is in `[-1,+1]` by
28
+ * construction, so the caller's cap is an EXACT bound.
29
+ *
30
+ * FAILURE POSTURE (NFR-5 / INV-7). Every read here degrades to "no term applied, honest reason
31
+ * recorded"; every write degrades to "this reward was dropped, counted, and logged". Nothing in
32
+ * this module may throw into `hybridRecall` or `reinforcePattern`.
33
+ */
34
+ import { appendFileSync, copyFileSync, existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
35
+ import { randomBytes } from 'node:crypto';
36
+ import { join } from 'node:path';
37
+ import { LessonBandit } from './lesson-bandit.js';
38
+ import { withNamedLockSync } from './named-lock.js';
39
+ import { readMemoryLearningConfig } from './patterns.js';
40
+ // ── Paths and constants ─────────────────────────────────────────────────────────────────────────
41
+ /** OUR envelope version — distinct from the engine's own `version` field (architecture §7.2). */
42
+ export const BANDIT_STATE_SCHEMA = 1;
43
+ /**
44
+ * The named lock guarding the state file. It resolves to `<projectRoot>/.dz/locks/lesson-bandit.lock`,
45
+ * i.e. the lock sits in the SAME `.dz` that holds the store — two worktrees pointing at one brain
46
+ * therefore share one lock, which is the only placement that serializes the right writers.
47
+ */
48
+ export const BANDIT_LOCK_NAME = 'lesson-bandit';
49
+ export function banditStateDir(projectRoot) {
50
+ return join(projectRoot, '.dz', 'lesson-bandit');
51
+ }
52
+ /**
53
+ * `<projectRoot>/.dz/lesson-bandit/state.json` (plan §0 D0-1 — the ADRs' worked examples say
54
+ * `.dz/memory/bandit-state.json`; ADR-002's FR-2 already hedges "or equivalent path under `.dz/`",
55
+ * and requirements/domain-model/architecture all key on this one).
56
+ */
57
+ export function banditStatePath(projectRoot) {
58
+ return join(banditStateDir(projectRoot), 'state.json');
59
+ }
60
+ const warnedNoOpExploration = new Set();
61
+ export function resolveBanditConfig(projectRoot, cfg = readMemoryLearningConfig(projectRoot)) {
62
+ const enabled = cfg.banditRerank === true;
63
+ const explorationRequested = cfg.banditExploration === true;
64
+ if (explorationRequested && !enabled && !warnedNoOpExploration.has(projectRoot)) {
65
+ warnedNoOpExploration.add(projectRoot);
66
+ // ADR-003: this combination is a no-op, and a silently ignored flag is how an operator comes to
67
+ // believe a feature is on. Warn ONCE per project per process — never on the armed path.
68
+ try {
69
+ process.stderr.write('dz: memory.learning.banditExploration is true but memory.learning.banditRerank is false — ' +
70
+ 'exploration has no re-rank to perturb and is doing nothing.\n');
71
+ }
72
+ catch { /* a closed stderr must not break recall */ }
73
+ }
74
+ return { enabled, explorationRequested, exploration: enabled && explorationRequested };
75
+ }
76
+ // ── Value objects ───────────────────────────────────────────────────────────────────────────────
77
+ /**
78
+ * ContextKey (domain model §3.3) — the coarse situation bucket a recall happened in, derived from
79
+ * the resolved recall domain (the axis `dz recall --domain` already boosts on). COARSE on purpose:
80
+ * with a per-query key every arm would sit at `pulls === 0` forever and the term would be noise.
81
+ * Normalising constructor, so two spellings of one domain cannot fork a posterior.
82
+ */
83
+ export function contextKeyFor(domain) {
84
+ if (typeof domain !== 'string')
85
+ return 'general';
86
+ // UNICODE-AWARE. The first draft stripped `[^a-z0-9._-]`, which MEASURED 2026-08-26 collapsed every
87
+ // Cyrillic and CJK domain to the SAME bucket — `'медицина'` and `'健康'` both became `'general'`,
88
+ // `'мед-обзор'` became the bare `'-'`, and `'café'` was silently mangled to `'caf'`. Distinct
89
+ // international domains sharing one posterior is not a cosmetic defect: it CONTAMINATES the payoff
90
+ // axis, teaching one domain's confirmations to reorder another's. Cyrillic is the majority of this
91
+ // store's real query traffic, so the ASCII-only draft would have mis-scoped most of it.
92
+ // NFKC folds compatibility forms so two spellings of one domain still cannot fork a posterior;
93
+ // \p{L}\p{N} keeps letters and digits in ANY script; separators collapse to a single '-'.
94
+ const norm = domain
95
+ .normalize('NFKC')
96
+ .toLowerCase()
97
+ .replace(/[^\p{L}\p{N}._-]+/gu, '-')
98
+ .replace(/^[-.]+|[-.]+$/g, '');
99
+ return norm.length > 0 ? norm.slice(0, 64) : 'general';
100
+ }
101
+ const clamp01 = (v) => Math.max(0, Math.min(1, v));
102
+ /**
103
+ * Build a {@link RewardEvent}, clamping reward into `[0,1]` at the domain boundary (INV-8/AC-7).
104
+ *
105
+ * A NON-FINITE reward (`NaN`, `Infinity`) is REJECTED (`null`), not coerced: `clamp01(NaN)` is
106
+ * `NaN`, which would poison `alpha`; and coercing it to `0` would be worse still — `reward: 0` moves
107
+ * `beta`, i.e. it records evidence the lesson FAILED. Dropping is the only fail-safe direction.
108
+ */
109
+ export function makeRewardEvent(dzId, contextKey, reward, ts) {
110
+ if (typeof reward !== 'number' || !Number.isFinite(reward))
111
+ return null;
112
+ return { dzId, contextKey, reward: clamp01(reward), ts };
113
+ }
114
+ /**
115
+ * Translate one upstream learning sample into exactly one domain event (domain model §5).
116
+ *
117
+ * `kind:'merge'` and every UNRECOGNISED kind are DROPPED — a sample kind added upstream tomorrow
118
+ * defaults to *ignored*, never to *rewarded*. That asymmetry is the whole point of translating
119
+ * rather than subscribing.
120
+ */
121
+ export function classifySignal(sample, contextKey) {
122
+ if (sample.kind === 'recall-hit') {
123
+ return { type: 'exposure', event: { dzId: sample.dzId, contextKey, ts: sample.ts } };
124
+ }
125
+ if (sample.kind === 'reinforce') {
126
+ const ev = makeRewardEvent(sample.dzId, contextKey, sample.reward ?? 1, sample.ts);
127
+ return ev === null ? null : { type: 'reward', event: ev };
128
+ }
129
+ return null;
130
+ }
131
+ export function freshBanditEnvelope(now = new Date().toISOString()) {
132
+ return {
133
+ schemaVersion: BANDIT_STATE_SCHEMA,
134
+ bandit: new LessonBandit().serialize(),
135
+ exposures: {},
136
+ explorePulls: {},
137
+ updatedAt: now,
138
+ };
139
+ }
140
+ const isPlainObject = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
141
+ const warnedCorrupt = new Set();
142
+ function warnOnce(projectRoot, reason) {
143
+ const key = `${projectRoot}::${reason}`;
144
+ if (warnedCorrupt.has(key))
145
+ return;
146
+ warnedCorrupt.add(key);
147
+ try {
148
+ process.stderr.write(`dz: bandit state at ${banditStatePath(projectRoot)} is unusable (${reason}) — ranking continues with no payoff term.\n`);
149
+ }
150
+ catch { /* a closed stderr must not break recall */ }
151
+ }
152
+ /**
153
+ * Read the state envelope. **Never throws** (INV-7): every failure yields a FRESH empty envelope
154
+ * plus an honest `reason`, and recall proceeds with no payoff axis.
155
+ *
156
+ * This function is READ-ONLY — it does not delete, repair, or rename anything. `dz recall` is not
157
+ * the right process to destroy state, and the read path is lock-free (§7.4), so a rename here would
158
+ * race every concurrent recall. Quarantining a corrupt file happens once, inside the WRITE
159
+ * transaction, where a write is expected and the lock is held (see {@link mutateBanditState}).
160
+ */
161
+ export function loadBanditState(projectRoot) {
162
+ const path = banditStatePath(projectRoot);
163
+ let raw;
164
+ try {
165
+ if (!existsSync(path))
166
+ return { state: freshBanditEnvelope(), reason: 'absent' };
167
+ raw = readFileSync(path, 'utf-8');
168
+ }
169
+ catch (err) {
170
+ const reason = `corrupt: ${err instanceof Error ? err.message : String(err)}`;
171
+ warnOnce(projectRoot, reason);
172
+ return { state: freshBanditEnvelope(), reason };
173
+ }
174
+ let parsed;
175
+ try {
176
+ parsed = JSON.parse(raw);
177
+ }
178
+ catch (err) {
179
+ const reason = `corrupt: ${err instanceof Error ? err.message : String(err)}`;
180
+ warnOnce(projectRoot, reason);
181
+ return { state: freshBanditEnvelope(), reason };
182
+ }
183
+ if (!isPlainObject(parsed)) {
184
+ warnOnce(projectRoot, 'malformed');
185
+ return { state: freshBanditEnvelope(), reason: 'malformed' };
186
+ }
187
+ const schema = parsed['schemaVersion'];
188
+ if (typeof schema === 'number' && schema > BANDIT_STATE_SCHEMA) {
189
+ // A newer dz wrote this. Never downgrade it in place, never write over it.
190
+ warnOnce(projectRoot, 'future-schema');
191
+ return { state: freshBanditEnvelope(), reason: 'future-schema' };
192
+ }
193
+ const bandit = parsed['bandit'];
194
+ if (!isPlainObject(bandit) || !isPlainObject(bandit['contexts'])) {
195
+ warnOnce(projectRoot, 'malformed');
196
+ return { state: freshBanditEnvelope(), reason: 'malformed' };
197
+ }
198
+ const contexts = {};
199
+ for (const [ctxKey, arms] of Object.entries(bandit['contexts'])) {
200
+ if (!isPlainObject(arms))
201
+ continue;
202
+ const out = {};
203
+ for (const [armKey, stats] of Object.entries(arms)) {
204
+ if (!isPlainObject(stats))
205
+ continue;
206
+ // Coercing a junk field to 0 was WRONG in the one direction that matters: a Beta posterior with
207
+ // alpha=0 (or a negative alpha/beta) is not a conservative prior, it is an INVALID one, and it can
208
+ // yield a maximal payoff term — i.e. a corrupt file would not merely be tolerated, it would push a
209
+ // lesson to the top. The stated posture for malformed state is "apply no payoff axis at all", so an
210
+ // arm that violates the invariants is DROPPED rather than repaired into something rankable.
211
+ // Invariants: alpha >= 1 and beta >= 1 (Beta(1,1) is the uniform prior every arm starts from),
212
+ // pulls >= 0, totalReward >= 0, and every field finite.
213
+ const num = (k) => {
214
+ const v = stats[k];
215
+ return typeof v === 'number' && Number.isFinite(v) ? v : null;
216
+ };
217
+ const alpha = num('alpha');
218
+ const beta = num('beta');
219
+ const pulls = num('pulls');
220
+ const totalReward = num('totalReward');
221
+ const costEma = num('costEma');
222
+ if (alpha === null || beta === null || pulls === null || totalReward === null || costEma === null)
223
+ continue;
224
+ if (alpha < 1 || beta < 1 || pulls < 0 || totalReward < 0)
225
+ continue;
226
+ out[armKey] = { alpha, beta, pulls, totalReward, costEma };
227
+ }
228
+ contexts[ctxKey] = out;
229
+ }
230
+ const cfgRaw = isPlainObject(bandit['config']) ? bandit['config'] : {};
231
+ const num = (k, dflt) => {
232
+ const v = cfgRaw[k];
233
+ return typeof v === 'number' && Number.isFinite(v) ? v : dflt;
234
+ };
235
+ const counters = (v) => {
236
+ const out = {};
237
+ if (!isPlainObject(v))
238
+ return out;
239
+ for (const [ctxKey, arms] of Object.entries(v)) {
240
+ if (!isPlainObject(arms))
241
+ continue;
242
+ const inner = {};
243
+ for (const [armKey, count] of Object.entries(arms)) {
244
+ if (typeof count === 'number' && Number.isFinite(count) && count >= 0)
245
+ inner[armKey] = count;
246
+ }
247
+ out[ctxKey] = inner;
248
+ }
249
+ return out;
250
+ };
251
+ const updatedAt = typeof parsed['updatedAt'] === 'string' ? parsed['updatedAt'] : new Date().toISOString();
252
+ return {
253
+ state: {
254
+ schemaVersion: typeof schema === 'number' ? schema : BANDIT_STATE_SCHEMA,
255
+ bandit: {
256
+ version: typeof bandit['version'] === 'number' ? bandit['version'] : 1,
257
+ config: { costWeight: num('costWeight', 0.01), costDecay: num('costDecay', 0.1), explorationBonus: num('explorationBonus', 0.1) },
258
+ contexts,
259
+ },
260
+ exposures: counters(parsed['exposures']),
261
+ explorePulls: counters(parsed['explorePulls']),
262
+ updatedAt,
263
+ },
264
+ };
265
+ }
266
+ /** Session-log sink — the file that already carries `{event:'reinforce'}` (patterns.ts). Best-effort. */
267
+ function logBanditEvent(projectRoot, record) {
268
+ try {
269
+ appendFileSync(join(projectRoot, '.dz', 'sessions.jsonl'), `${JSON.stringify(record)}\n`);
270
+ }
271
+ catch { /* best-effort: observability must never fail an operation */ }
272
+ }
273
+ function writeEnvelopeAtomic(projectRoot, env) {
274
+ const dir = banditStateDir(projectRoot);
275
+ mkdirSync(dir, { recursive: true });
276
+ const target = banditStatePath(projectRoot);
277
+ // Backup INSIDE the critical section (ADR-002), matching the discipline every other modifying
278
+ // write in this repo uses.
279
+ if (existsSync(target)) {
280
+ try {
281
+ copyFileSync(target, `${target}.bak`);
282
+ }
283
+ catch { /* a missing .bak never blocks the write */ }
284
+ }
285
+ const tmp = `${target}.tmp-${process.pid}-${randomBytes(4).toString('hex')}`;
286
+ try {
287
+ writeFileSync(tmp, `${JSON.stringify(env, null, 2)}\n`, 'utf-8');
288
+ renameSync(tmp, target);
289
+ }
290
+ catch (err) {
291
+ try {
292
+ rmSync(tmp, { force: true });
293
+ }
294
+ catch { /* nothing to clean */ }
295
+ throw err;
296
+ }
297
+ }
298
+ /**
299
+ * The write transaction (INV-5, AC-6): ONE short synchronous read-plan-write under the named lock,
300
+ * ending in temp+rename.
301
+ *
302
+ * **Why the lock and not just the atomic rename.** MEASURED in this repo (2026-08-19, four
303
+ * barrier-synchronised writers on one JSON file, all exit 0): ONE of four updates survived without a
304
+ * lock; all four survived with `withNamedLockSync`. Temp+rename prevents a TORN read; it does
305
+ * nothing about a LOST update, and the loss is silent — both writers report success.
306
+ *
307
+ * No network call, no subprocess, no model turn inside the section — an advisory lock held past its
308
+ * stale threshold stops excluding anyone.
309
+ */
310
+ function mutateBanditState(projectRoot, op, mutate) {
311
+ try {
312
+ return withNamedLockSync(projectRoot, BANDIT_LOCK_NAME, () => {
313
+ const { state, reason } = loadBanditState(projectRoot);
314
+ if (reason === 'future-schema') {
315
+ // Refuse to clobber a state written by a newer dz. The reward is dropped, loudly.
316
+ logBanditEvent(projectRoot, { event: 'bandit-error', ts: new Date().toISOString(), op, reason: 'future-schema' });
317
+ return { ok: false, reason: 'future-schema' };
318
+ }
319
+ if (reason !== undefined && reason !== 'absent') {
320
+ // Preserve the evidence before overwriting it — never delete, never "repair". This is the
321
+ // ONE place a corrupt file is touched, and it is under the lock.
322
+ const target = banditStatePath(projectRoot);
323
+ try {
324
+ renameSync(target, `${target}.corrupt-${new Date().toISOString().replace(/[:.]/g, '-')}`);
325
+ }
326
+ catch { /* best-effort */ }
327
+ logBanditEvent(projectRoot, { event: 'bandit-error', ts: new Date().toISOString(), op, reason });
328
+ }
329
+ const bandit = LessonBandit.deserialize(state.bandit);
330
+ const exposures = { ...state.exposures };
331
+ const explorePulls = { ...state.explorePulls };
332
+ mutate(bandit, { exposures, explorePulls });
333
+ writeEnvelopeAtomic(projectRoot, {
334
+ schemaVersion: BANDIT_STATE_SCHEMA,
335
+ bandit: bandit.serialize(),
336
+ exposures,
337
+ explorePulls,
338
+ updatedAt: new Date().toISOString(),
339
+ });
340
+ return { ok: true };
341
+ });
342
+ }
343
+ catch (err) {
344
+ // A lock timeout, a compromised lock, a full disk: the reward is DROPPED, counted and logged.
345
+ // It never propagates into `reinforcePattern` or `hybridRecall` (NFR-5, §10).
346
+ const reason = err instanceof Error ? err.name : String(err);
347
+ logBanditEvent(projectRoot, { event: 'bandit-error', ts: new Date().toISOString(), op, reason });
348
+ return { ok: false, reason };
349
+ }
350
+ }
351
+ /**
352
+ * Record a genuine confirmation (ADR-001 D-5). This is the ONLY operation that moves reward mass.
353
+ * Called from `reinforcePattern`'s non-exposure branch, AFTER the store lock is released.
354
+ */
355
+ export function recordReward(projectRoot, event) {
356
+ let pulls = 0;
357
+ const out = mutateBanditState(projectRoot, 'reward', (bandit) => {
358
+ bandit.recordReward(event.contextKey, event.dzId, event.reward);
359
+ pulls = bandit.getArmStats(event.contextKey, event.dzId)?.pulls ?? 0;
360
+ });
361
+ if (out.ok) {
362
+ logBanditEvent(projectRoot, { event: 'bandit-reward', ts: event.ts, dzId: event.dzId, ctx: event.contextKey, reward: event.reward, pulls });
363
+ }
364
+ return out;
365
+ }
366
+ /**
367
+ * Record that lessons were merely SEEN (INV-2 / AC-2).
368
+ *
369
+ * ONE locked transaction per RECALL, not per hit (architecture §4) — `limit` transactions per recall
370
+ * would hold the lock far more often than the work justifies.
371
+ *
372
+ * **No engine call happens here, at any reward value, including `0`.** `recordReward(ctx, arm, 0)`
373
+ * adds `beta += 1`: it is evidence the lesson FAILED. Penalising a lesson for being read is the
374
+ * mirror image of the promote-by-view defect this invariant exists to prevent.
375
+ *
376
+ * `exploredDzIds` are the arms that received a trial lift on this recall (ADR-003 §4) — counted in
377
+ * their own projection, never in `alpha`/`beta`, and never touching `qStatus`.
378
+ */
379
+ export function recordExposures(projectRoot, events, exploredDzIds = [], meta = {}) {
380
+ if (events.length === 0 && exploredDzIds.length === 0)
381
+ return { ok: true };
382
+ const bump = (map, ctx, dzId) => {
383
+ const inner = map[ctx] ?? {};
384
+ inner[dzId] = (inner[dzId] ?? 0) + 1;
385
+ map[ctx] = inner;
386
+ };
387
+ const out = mutateBanditState(projectRoot, 'exposure', (_bandit, env) => {
388
+ for (const ev of events)
389
+ bump(env.exposures, ev.contextKey, ev.dzId);
390
+ const ctx = events[0]?.contextKey;
391
+ if (ctx !== undefined)
392
+ for (const dzId of exploredDzIds)
393
+ bump(env.explorePulls, ctx, dzId);
394
+ });
395
+ if (out.ok) {
396
+ logBanditEvent(projectRoot, {
397
+ // DIFFERENT event name from `bandit-reward` on purpose: INV-2 must be auditable from the log
398
+ // alone, by anyone, without reading the code (architecture §11, "the last row").
399
+ event: 'bandit-exposure',
400
+ ts: events[0]?.ts ?? new Date().toISOString(),
401
+ ctx: events[0]?.contextKey ?? 'general',
402
+ n: events.length,
403
+ ...(meta.moved !== undefined ? { moved: meta.moved } : {}),
404
+ ...(meta.arms !== undefined ? { arms: meta.arms } : {}),
405
+ ...(exploredDzIds.length > 0 ? { explored: exploredDzIds.length } : {}),
406
+ });
407
+ }
408
+ return out;
409
+ }
410
+ const EMPTY_TERMS = { terms: new Map(), reason: null, unknownArms: 0, explored: [], unknownDzIds: [] };
411
+ /**
412
+ * Project the posterior for each arm into a bounded term (ADR-001 D-2). **Lock-free** (§7.4): the
413
+ * writer's final step is a rename, so a reader sees the whole old document or the whole new one,
414
+ * never a partial; a reader that loses the race by microseconds ranks with a state one reward stale,
415
+ * which is a ranking hint, not a fact.
416
+ *
417
+ * ```
418
+ * term = (alpha/(alpha+beta) - 0.5) * 2 ∈ [-1,+1] when pulls > 0 ('posterior')
419
+ * term = 0 when pulls === 0 ('unknown-arm')
420
+ * ```
421
+ * `pulls === 0 ⇒ 0` is the cold start ADR-001 accepts on purpose: no evidence ⇒ no nudge, and
422
+ * crucially no RANDOM lift. `Math.random()` is reached only when `opts.exploration` is true, and
423
+ * then only for a NON-QUARANTINED zero-pull arm (ADR-003 P5/P6) — quarantined lessons are excluded
424
+ * here as a SET RELATION, in addition to the ranker's own arm-list filter upstream.
425
+ *
426
+ * Never throws (NFR-5): any failure yields an empty map plus a reason.
427
+ */
428
+ export function payoffTermsFor(projectRoot, contextKey, armKeys, opts = {}) {
429
+ if (armKeys.length === 0)
430
+ return EMPTY_TERMS;
431
+ try {
432
+ const { state, reason } = loadBanditState(projectRoot);
433
+ const bandit = LessonBandit.deserialize(state.bandit);
434
+ const terms = new Map();
435
+ const explored = [];
436
+ const unknownDzIds = [];
437
+ const quarantined = opts.quarantined ?? new Set();
438
+ const rng = opts.rng ?? Math.random;
439
+ let unknownArms = 0;
440
+ for (const dzId of armKeys) {
441
+ const s = bandit.getArmStats(contextKey, dzId);
442
+ if (s === null || s.pulls === 0) {
443
+ unknownArms += 1;
444
+ unknownDzIds.push(dzId); // ids, so a downstream cut can narrow this counter too
445
+ // The ONLY branch that can consume randomness, and it is unreachable while disarmed.
446
+ if (opts.exploration === true && !quarantined.has(dzId)) {
447
+ const u = rng();
448
+ const lift = typeof u === 'number' && Number.isFinite(u) ? Math.max(0, Math.min(1, u)) : 0;
449
+ explored.push(dzId);
450
+ terms.set(dzId, { dzId, term: lift, basis: 'explored' });
451
+ }
452
+ else {
453
+ terms.set(dzId, { dzId, term: 0, basis: 'unknown-arm' });
454
+ }
455
+ continue;
456
+ }
457
+ const denom = s.alpha + s.beta;
458
+ const mean = denom > 0 ? s.alpha / denom : 0.5;
459
+ const raw = (mean - 0.5) * 2;
460
+ const term = Number.isFinite(raw) ? Math.max(-1, Math.min(1, raw)) : 0;
461
+ terms.set(dzId, { dzId, term, basis: 'posterior' });
462
+ }
463
+ return { terms, reason: reason ?? null, unknownArms, explored, unknownDzIds };
464
+ }
465
+ catch {
466
+ // A ranking aid that can throw on the hook path is a net loss.
467
+ return EMPTY_TERMS;
468
+ }
469
+ }
470
+ /**
471
+ * Narrow a report to the hits a caller actually PRINTED. `dz recall` over-fetches under `--domain`
472
+ * and truncates again, so the un-narrowed count would describe a PRE-cut list the reader never saw —
473
+ * the exact dishonesty FR-8/AC-11 names.
474
+ */
475
+ export function narrowBanditReport(report, shownDzIds) {
476
+ const shown = new Set(shownDzIds);
477
+ // Defensive reads: a report serialised by an older build carries none of the id lists, and a
478
+ // ranking explanation must never be the thing that throws inside `dz recall` (NFR-5). A missing
479
+ // list narrows to empty rather than crashing — and the counter it feeds goes to 0, which is the
480
+ // honest reading of "this build cannot tell you", not a stale pre-cut number presented as post-cut.
481
+ const list = (v) => (Array.isArray(v) ? v : []);
482
+ const armDzIds = list(report.armDzIds).filter((id) => shown.has(id));
483
+ const unknownDzIds = list(report.unknownDzIds).filter((id) => shown.has(id));
484
+ const exploredDzIds = list(report.exploredDzIds).filter((id) => shown.has(id));
485
+ // `moved` is RECOMPUTED, never intersected. Dropping candidates can UNDO a displacement — if the
486
+ // only thing that pushed B past A was C, and C is cut, B and A may sit in their original order in
487
+ // the list the reader actually saw. Filtering the old movedDzIds would keep claiming a move that
488
+ // no longer exists in the shown ranking, which is the same dishonesty the narrowing exists to end.
489
+ const beforeOrder = list(report.beforeOrder).filter((id) => shown.has(id));
490
+ const afterOrder = list(report.afterOrder).filter((id) => shown.has(id));
491
+ // With no orders to recompute from, fall back to the intersection — weaker, and labelled as such
492
+ // in the type docs, but never a crash and never a pre-cut count worn as a post-cut one.
493
+ const movedDzIds = afterOrder.length > 0 || beforeOrder.length > 0
494
+ ? afterOrder.filter((id, i) => beforeOrder[i] !== id)
495
+ : list(report.movedDzIds).filter((id) => shown.has(id));
496
+ return {
497
+ ...report,
498
+ armsConsidered: armDzIds.length,
499
+ unknownArms: unknownDzIds.length,
500
+ explored: exploredDzIds.length,
501
+ moved: movedDzIds.length,
502
+ armDzIds, movedDzIds, unknownDzIds, exploredDzIds, beforeOrder, afterOrder,
503
+ };
504
+ }
505
+ /** Read-only health snapshot from the state file + `sessions.jsonl`. Never throws. */
506
+ export function banditStats(projectRoot) {
507
+ const present = existsSync(banditStatePath(projectRoot));
508
+ const { state, reason } = loadBanditState(projectRoot);
509
+ const bandit = LessonBandit.deserialize(state.bandit);
510
+ const agg = bandit.getStats();
511
+ let armsWithReward = 0;
512
+ for (const arms of Object.values(state.bandit.contexts)) {
513
+ // `alpha > 1` counted only POSITIVE evidence. An explicit confirmation carrying reward 0 moves
514
+ // `beta` and `pulls` while leaving `alpha` at its prior — real, measured, ranking-affecting
515
+ // evidence that the old predicate reported as "no payoff axis yet", so `dz compounding` could
516
+ // announce an empty axis while a negative posterior was actively demoting lessons. Evidence is
517
+ // EITHER posterior parameter having moved off its Beta(1,1) prior, or a recorded pull.
518
+ for (const st of Object.values(arms))
519
+ if (st.pulls > 0 || st.alpha > 1 || st.beta > 1)
520
+ armsWithReward += 1;
521
+ }
522
+ const sum = (m) => {
523
+ let t = 0;
524
+ for (const inner of Object.values(m))
525
+ for (const v of Object.values(inner))
526
+ t += v;
527
+ return t;
528
+ };
529
+ let rewardEvents = 0;
530
+ let exposureEvents = 0;
531
+ let banditWriteErrors = 0;
532
+ // The field is documented as "mean `moved / armsConsidered` over logged recalls". Summing the
533
+ // numerators and denominators separately computes a DIFFERENT statistic — a hit-count-weighted
534
+ // rate, in which one 50-hit recall outweighs ten 5-hit ones. Recall limits vary per call here, so
535
+ // the two answers genuinely diverge. Accumulate each event's own ratio and count the events.
536
+ let rateSum = 0;
537
+ let rateEvents = 0;
538
+ try {
539
+ const text = readFileSync(join(projectRoot, '.dz', 'sessions.jsonl'), 'utf-8');
540
+ for (const line of text.split('\n')) {
541
+ if (line.trim() === '')
542
+ continue;
543
+ try {
544
+ const o = JSON.parse(line);
545
+ if (o.event === 'bandit-reward')
546
+ rewardEvents += 1;
547
+ else if (o.event === 'bandit-exposure') {
548
+ exposureEvents += 1;
549
+ if (typeof o.moved === 'number' && typeof o.arms === 'number' && o.arms > 0) {
550
+ rateSum += o.moved / o.arms;
551
+ rateEvents += 1;
552
+ }
553
+ }
554
+ else if (o.event === 'bandit-error')
555
+ banditWriteErrors += 1;
556
+ }
557
+ catch { /* skip one bad line, never the file */ }
558
+ }
559
+ }
560
+ catch { /* no session log yet */ }
561
+ return {
562
+ present,
563
+ // The honest posture `dz compounding` already takes: no state, no verdict.
564
+ verdict: present && agg.totalPulls > 0 ? 'OK' : 'INSUFFICIENT_DATA',
565
+ reason: reason ?? null,
566
+ updatedAt: present ? state.updatedAt : null,
567
+ contexts: agg.contexts,
568
+ armsTotal: agg.totalArms,
569
+ armsWithReward,
570
+ totalPulls: agg.totalPulls,
571
+ totalReward: agg.totalReward,
572
+ exposureTotal: sum(state.exposures),
573
+ explorePullTotal: sum(state.explorePulls),
574
+ rewardEvents,
575
+ exposureEvents,
576
+ banditWriteErrors,
577
+ movedRate: rateEvents > 0 ? rateSum / rateEvents : null,
578
+ };
579
+ }
580
+ /** Text rendering of {@link banditStats} for `dz compounding`. Pure. */
581
+ export function renderBanditHealth(h) {
582
+ const lines = ['bandit payoff axis (memory.learning.banditRerank)'];
583
+ if (!h.present) {
584
+ lines.push(' INSUFFICIENT_DATA — no bandit state file; the payoff axis has never been written.');
585
+ return lines.join('\n');
586
+ }
587
+ lines.push(` verdict: ${h.verdict}${h.reason !== null ? ` (state ${h.reason})` : ''}`);
588
+ lines.push(` arms: ${h.armsTotal} in ${h.contexts} context(s); with measured payoff (alpha>1): ${h.armsWithReward}`);
589
+ lines.push(` pulls: ${h.totalPulls}, reward mass: ${h.totalReward.toFixed(3)}, exposures: ${h.exposureTotal}, trial impressions: ${h.explorePullTotal}`);
590
+ // The row that catches THIS project's recurring failure: a collect leg with no apply leg.
591
+ lines.push(` feed: ${h.rewardEvents} reward event(s) vs ${h.exposureEvents} exposure event(s)${h.rewardEvents === 0 && h.exposureEvents > 0 ? ' ← write-only: the view feed is alive and the reward feed is not' : ''}`);
592
+ lines.push(` write errors: ${h.banditWriteErrors}`);
593
+ lines.push(` movedRate: ${h.movedRate === null ? 'INSUFFICIENT_DATA' : h.movedRate.toFixed(3)}${h.movedRate === 0 ? ' ← armed, harmless, and useless' : ''}`);
594
+ lines.push(' NOTE: none of this measures whether the re-ranking is BETTER — `moved` counts change, not improvement.');
595
+ return lines.join('\n');
596
+ }
597
+ //# sourceMappingURL=lesson-payoff.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"les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