omnicell-router 0.2.0 → 0.3.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 (102) hide show
  1. package/backend/dist/budget/budget-manager.d.ts +25 -0
  2. package/backend/dist/budget/budget-manager.js +54 -0
  3. package/backend/dist/cli/clients/index.js +2 -0
  4. package/backend/dist/cli/clients/omp.d.ts +53 -0
  5. package/backend/dist/cli/clients/omp.js +664 -0
  6. package/backend/dist/cli/clients/pi.js +79 -32
  7. package/backend/dist/cli/index.js +2 -2
  8. package/backend/dist/cli/types.d.ts +1 -1
  9. package/backend/dist/config/governance-limits.d.ts +68 -0
  10. package/backend/dist/config/governance-limits.js +261 -0
  11. package/backend/dist/config/index.js +1 -1
  12. package/backend/dist/config/types.d.ts +15 -5
  13. package/backend/dist/flywheel/collector.d.ts +74 -0
  14. package/backend/dist/flywheel/collector.js +235 -0
  15. package/backend/dist/flywheel/dataset.d.ts +130 -0
  16. package/backend/dist/flywheel/dataset.js +638 -0
  17. package/backend/dist/flywheel/decision-capture.d.ts +68 -0
  18. package/backend/dist/flywheel/decision-capture.js +85 -0
  19. package/backend/dist/flywheel/prune.d.ts +133 -0
  20. package/backend/dist/flywheel/prune.js +495 -0
  21. package/backend/dist/flywheel/schema.d.ts +108 -0
  22. package/backend/dist/flywheel/schema.js +117 -0
  23. package/backend/dist/flywheel/trainer.d.ts +84 -0
  24. package/backend/dist/flywheel/trainer.js +198 -0
  25. package/backend/dist/harness/adapters/amp.js +1 -0
  26. package/backend/dist/harness/adapters/claude.js +1 -0
  27. package/backend/dist/harness/adapters/cline.js +3 -1
  28. package/backend/dist/harness/adapters/codex.js +3 -1
  29. package/backend/dist/harness/adapters/cursor.js +1 -0
  30. package/backend/dist/harness/adapters/declarative.d.ts +3 -1
  31. package/backend/dist/harness/adapters/declarative.js +15 -1
  32. package/backend/dist/harness/adapters/dsh.js +1 -1
  33. package/backend/dist/harness/adapters/gemini-cli.js +1 -0
  34. package/backend/dist/harness/adapters/github-copilot.js +1 -0
  35. package/backend/dist/harness/adapters/index.d.ts +11 -3
  36. package/backend/dist/harness/adapters/index.js +48 -1
  37. package/backend/dist/harness/adapters/omp.d.ts +11 -0
  38. package/backend/dist/harness/adapters/omp.js +22 -0
  39. package/backend/dist/harness/adapters/opencode.js +1 -0
  40. package/backend/dist/harness/adapters/pi.js +2 -1
  41. package/backend/dist/harness/adapters/types.d.ts +19 -4
  42. package/backend/dist/harness/adapters/windsurf.js +1 -0
  43. package/backend/dist/harness/adapters/zed.js +3 -1
  44. package/backend/dist/harness/hosts.js +1 -0
  45. package/backend/dist/harness/translation.js +12 -4
  46. package/backend/dist/harness/types.d.ts +2 -2
  47. package/backend/dist/harness/writers/skill.d.ts +1 -1
  48. package/backend/dist/opencode/agents.d.ts +7 -0
  49. package/backend/dist/opencode/agents.js +22 -3
  50. package/backend/dist/opencode/catalog/custom-store.d.ts +50 -0
  51. package/backend/dist/opencode/catalog/custom-store.js +144 -0
  52. package/backend/dist/opencode/credentials/push.d.ts +38 -0
  53. package/backend/dist/opencode/credentials/push.js +116 -0
  54. package/backend/dist/opencode/credentials/reconcile.d.ts +49 -0
  55. package/backend/dist/opencode/credentials/reconcile.js +216 -0
  56. package/backend/dist/opencode/sync.d.ts +29 -0
  57. package/backend/dist/opencode/sync.js +186 -0
  58. package/backend/dist/pipeline/account-selection.d.ts +101 -0
  59. package/backend/dist/pipeline/account-selection.js +112 -0
  60. package/backend/dist/pipeline/orchestrator.js +34 -3
  61. package/backend/dist/providers/systemone.d.ts +29 -0
  62. package/backend/dist/providers/systemone.js +170 -0
  63. package/backend/dist/ratelimit/duration.d.ts +24 -0
  64. package/backend/dist/ratelimit/duration.js +43 -0
  65. package/backend/dist/ratelimit/governance-runtime.d.ts +121 -0
  66. package/backend/dist/ratelimit/governance-runtime.js +183 -0
  67. package/backend/dist/ratelimit/index.d.ts +4 -0
  68. package/backend/dist/ratelimit/index.js +4 -0
  69. package/backend/dist/ratelimit/limiter.d.ts +157 -0
  70. package/backend/dist/ratelimit/limiter.js +244 -0
  71. package/backend/dist/ratelimit/sliding-window-counter.d.ts +63 -0
  72. package/backend/dist/ratelimit/sliding-window-counter.js +103 -0
  73. package/backend/dist/ratelimit/subject.d.ts +26 -0
  74. package/backend/dist/ratelimit/subject.js +28 -0
  75. package/backend/dist/resilience/account-state.d.ts +84 -0
  76. package/backend/dist/resilience/account-state.js +228 -0
  77. package/backend/dist/router/layer1-classifier.d.ts +111 -0
  78. package/backend/dist/router/layer1-classifier.js +467 -0
  79. package/backend/dist/router/layer2-judge.d.ts +111 -0
  80. package/backend/dist/router/layer2-judge.js +373 -0
  81. package/backend/dist/router/retry-escalation.d.ts +89 -0
  82. package/backend/dist/router/retry-escalation.js +99 -0
  83. package/backend/dist/routes/flywheel.d.ts +3 -0
  84. package/backend/dist/routes/flywheel.js +268 -0
  85. package/backend/dist/routes/harness.js +4 -1
  86. package/backend/dist/routes/systemone.d.ts +3 -0
  87. package/backend/dist/routes/systemone.js +90 -0
  88. package/backend/dist/server.d.ts +0 -15
  89. package/backend/dist/server.js +40 -43
  90. package/backend/dist/session/session-manager.d.ts +15 -0
  91. package/backend/dist/session/session-manager.js +17 -0
  92. package/backend/dist/session/session-row.d.ts +78 -0
  93. package/backend/dist/session/session-row.js +52 -0
  94. package/backend/dist/surfaces/governance-envelope.d.ts +34 -0
  95. package/backend/dist/surfaces/governance-envelope.js +47 -0
  96. package/backend/dist/utils/token-estimator.d.ts +7 -0
  97. package/backend/dist/utils/token-estimator.js +20 -0
  98. package/bin/ocr.js +2 -2
  99. package/frontend/dist/assets/{index-DvXKvNxl.js → index-B7GKsUyU.js} +264 -244
  100. package/frontend/dist/assets/{index-1o7qI-KJ.css → index-DLKLOkQJ.css} +1 -1
  101. package/frontend/dist/index.html +2 -2
  102. package/package.json +1 -1
@@ -0,0 +1,638 @@
1
+ /**
2
+ * Read/query/relabel side of the flywheel dataset — built for MILLIONS of rows.
3
+ *
4
+ * Architecture (why not "parse the whole file into objects"):
5
+ * A million-row dataset is ~800 MB of JSON; materializing it as JS objects
6
+ * costs gigabytes and re-parsing it after every single gateway append is
7
+ * quadratic in practice. Instead the dataset keeps a COLUMNAR INDEX of just
8
+ * the fields that filtering, aggregation and training need (byte offset,
9
+ * timestamp, feature vector, tier, label source, flags), backed by typed
10
+ * arrays — roughly 200 MB of flat memory per million rows. Full records are
11
+ * read back lazily: a page of samples triggers ~limit random single-line
12
+ * reads, nothing more.
13
+ *
14
+ * The index advances incrementally: `ensureIndexed()` only parses bytes past
15
+ * the last complete line it saw, so steady-state cost per gateway append is
16
+ * one small tail read. A full rebuild (first visit to a pre-existing large
17
+ * file, or after a prune/truncate) is the only expensive path; `warmup()`
18
+ * walks that down in event-loop-friendly slices.
19
+ *
20
+ * The dataset file is append-only under NORMAL gateway operation. Lifecycle
21
+ * operations (prune / retention sweep / batch delete / reset, implemented in
22
+ * `flywheel/prune.ts`) discard whole records via atomic tmp+rename rewrites
23
+ * under the documented backup policy — they never mutate a record in place.
24
+ * Relabelling still writes a sidecar overlay keyed by record id: the read
25
+ * side here never edits recorded content, only discards it.
26
+ */
27
+ import fs from 'node:fs';
28
+ import path from 'node:path';
29
+ import { FLYWHEEL_TIERS, deriveDefaultLabel, isTier, migrateRecord, } from './schema.js';
30
+ import { DEFAULT_BASE_MODEL } from '../router/layer1-classifier.js';
31
+ // ---- index flag bits ------------------------------------------------------
32
+ const F_SYNTHETIC = 1 << 0;
33
+ const F_FALLBACK = 1 << 1;
34
+ const F_TRAINABLE = 1 << 2; // row carried a usable 8-dim feature vector
35
+ const TIER_NONE = 255;
36
+ const SRC_UNLABELED = 3; // index of 'unlabeled' in SOURCE_ORDER
37
+ const SOURCE_ORDER = ['human', 'runtime_fallback', 'observed_execution', 'unlabeled'];
38
+ const VECTOR_DIMS = DEFAULT_BASE_MODEL.featureDimensions; // index stores exactly this many dims
39
+ const READ_CHUNK = 4 * 1024 * 1024; // 4 MB tail-read chunks
40
+ const WARMUP_SLICE_BYTES = 8 * 1024 * 1024; // event-loop budget per warmup slice
41
+ export class FlywheelDataset {
42
+ datasetPath;
43
+ labelsPath;
44
+ // ---- columnar index (parallel arrays, length = this.n) ----
45
+ n = 0;
46
+ cap = 0;
47
+ ids = [];
48
+ idToIdx = new Map();
49
+ offsets = new Float64Array(0); // line start byte offset (Float64: files can exceed 2^32)
50
+ tsMs = new Float64Array(0); // record timestamp as epoch ms
51
+ vectors = new Float64Array(0); // n * VECTOR_DIMS, row-major
52
+ tierIdx = new Uint8Array(0); // FLYWHEEL_TIERS index, TIER_NONE = unlabelled
53
+ srcIdx = new Uint8Array(0); // SOURCE_ORDER index
54
+ flags = new Uint8Array(0);
55
+ modelPool = [];
56
+ modelIdx = new Int32Array(0); // index into modelPool
57
+ promptPrefix = []; // first 48 chars, lowercased, for search
58
+ indexedBytes = 0; // bytes of the dataset file already reflected in the index
59
+ indexedIno = null; // inode of the file the index was built from (D5 guard)
60
+ indexVersion = 0; // bumped on every index change (summary cache key)
61
+ overrides = {};
62
+ labelsLoaded = false;
63
+ summaryCache = null;
64
+ constructor(datasetPath) {
65
+ this.datasetPath = datasetPath;
66
+ this.labelsPath = `${datasetPath}.labels.json`;
67
+ }
68
+ getDatasetPath() {
69
+ return this.datasetPath;
70
+ }
71
+ getLabelsPath() {
72
+ return this.labelsPath;
73
+ }
74
+ /** Drop all in-memory state; the next access re-reads from scratch. */
75
+ invalidate() {
76
+ this.n = 0;
77
+ this.cap = 0;
78
+ this.ids = [];
79
+ this.idToIdx.clear();
80
+ this.offsets = new Float64Array(0);
81
+ this.tsMs = new Float64Array(0);
82
+ this.vectors = new Float64Array(0);
83
+ this.tierIdx = new Uint8Array(0);
84
+ this.srcIdx = new Uint8Array(0);
85
+ this.flags = new Uint8Array(0);
86
+ this.modelPool = [];
87
+ this.modelIdx = new Int32Array(0);
88
+ this.promptPrefix = [];
89
+ this.indexedBytes = 0;
90
+ this.indexedIno = null;
91
+ this.indexVersion++;
92
+ this.summaryCache = null;
93
+ this.labelsLoaded = false;
94
+ // No fd to release: dataset.ts opens per indexing pass / per row read and
95
+ // never holds a handle open between calls — a long-lived read handle
96
+ // makes an atomic tmp+rename rewrite fail with EPERM on Windows, and the
97
+ // four sanctioned rewriters (prune, retention sweep, batch delete,
98
+ // reset, plus the offline CLI) must never be blocked by a reader.
99
+ }
100
+ /**
101
+ * Index the dataset to completion, synchronously. Cheap when the index is
102
+ * current (only new bytes are parsed); expensive only on a cold start over a
103
+ * large pre-existing file. The HTTP layer should prefer `warmup()`.
104
+ */
105
+ ensureIndexed() {
106
+ this.loadOverrides();
107
+ // One statSync for both size and inode — the guard below needs both and
108
+ // the hot path (file unchanged) must not pay twice.
109
+ let st;
110
+ try {
111
+ st = fs.statSync(this.datasetPath);
112
+ }
113
+ catch {
114
+ st = null; // file absent/vanished — treated as empty below
115
+ }
116
+ const size = st ? st.size : 0;
117
+ // Inode guard (design doc D5): every sanctioned rewrite swaps the inode
118
+ // via tmp+rename, so an external rewrite (retention timer sweep, offline
119
+ // CLI) is detected even when the replacement file is equal-or-larger —
120
+ // a pure size comparison races a concurrent append restoring the byte
121
+ // count before the next pass and leaves stale byte offsets behind.
122
+ const inodeReplaced = st !== null && this.indexedIno !== null && st.ino !== this.indexedIno;
123
+ if (inodeReplaced || size < this.indexedBytes) {
124
+ // File rewritten / shrank (pruned / truncated / replaced) — start over.
125
+ const keepLabels = this.labelsLoaded;
126
+ this.invalidate();
127
+ this.labelsLoaded = keepLabels;
128
+ this.loadOverrides();
129
+ }
130
+ this.indexedIno = st ? st.ino : null;
131
+ if (size === this.indexedBytes)
132
+ return;
133
+ // Open per indexing pass and release on exit — never cache the handle.
134
+ // Windows refuses a tmp+rename over a file with an open read handle
135
+ // (EPERM), so a reader must not block the sanctioned rewriters (prune,
136
+ // retention sweep, batch delete, reset, offline CLI — see invalidate()).
137
+ let fd;
138
+ try {
139
+ fd = fs.openSync(this.datasetPath, 'r');
140
+ }
141
+ catch {
142
+ return; // file vanished between stat and open
143
+ }
144
+ try {
145
+ const buf = Buffer.allocUnsafe(Math.min(READ_CHUNK, size - this.indexedBytes));
146
+ // All splitting below works in BYTES, never in string offsets. Prompts are
147
+ // multibyte UTF-8, so string positions drift apart from real file offsets
148
+ // and every recorded line start after non-ASCII text would be wrong — rows
149
+ // then fail to re-read in readRow() and silently vanish from the browser
150
+ // while `total` still counts them.
151
+ let carry = Buffer.alloc(0); // undecoded tail bytes after the last newline
152
+ let readFrom = this.indexedBytes;
153
+ while (readFrom < size) {
154
+ const want = Math.min(buf.length, size - readFrom);
155
+ let got = 0;
156
+ try {
157
+ got = fs.readSync(fd, buf, 0, want, readFrom);
158
+ }
159
+ catch {
160
+ break;
161
+ }
162
+ if (got <= 0)
163
+ break;
164
+ readFrom += got;
165
+ // Copy even when `carry` is empty: a chunk that ends without a newline
166
+ // becomes the next carry and must survive the following readSync into the
167
+ // reused `buf` — a subarray would alias it and be overwritten.
168
+ const chunk = carry.length === 0 ? Buffer.from(buf.subarray(0, got)) : Buffer.concat([carry, buf.subarray(0, got)]);
169
+ // Only complete lines are consumed; the tail (if any) waits for more
170
+ // bytes. JSONL never embeds raw newline bytes, so scanning for 0x0A is
171
+ // an exact line terminator even inside multibyte characters, and the
172
+ // per-line decode in indexLines() can't corrupt a character split at a
173
+ // chunk boundary.
174
+ const lastNewline = chunk.lastIndexOf(0x0a);
175
+ if (lastNewline === -1) {
176
+ carry = chunk;
177
+ continue;
178
+ }
179
+ const complete = chunk.subarray(0, lastNewline + 1);
180
+ carry = chunk.subarray(lastNewline + 1);
181
+ // The block starts where the previous carry ended: file offset of the
182
+ // first line = current read position minus the whole chunk in bytes.
183
+ const blockFileStart = readFrom - chunk.length;
184
+ this.indexLines(complete, blockFileStart);
185
+ this.indexedBytes = readFrom - carry.length;
186
+ }
187
+ }
188
+ finally {
189
+ try {
190
+ fs.closeSync(fd);
191
+ }
192
+ catch {
193
+ /* already closed */
194
+ }
195
+ }
196
+ this.indexVersion++;
197
+ this.summaryCache = null;
198
+ }
199
+ /**
200
+ * Walk a cold start down in event-loop-friendly slices. Resolves once the
201
+ * index covers the whole file. Safe to call repeatedly / concurrently —
202
+ * concurrent callers just await the same walk.
203
+ */
204
+ warmupPromise = null;
205
+ warmup() {
206
+ if (this.warmupPromise)
207
+ return this.warmupPromise;
208
+ this.warmupPromise = (async () => {
209
+ for (;;) {
210
+ this.ensureIndexed();
211
+ if (this.fileSize() <= this.indexedBytes)
212
+ break;
213
+ // Parse at most one slice per macrotask so HTTP traffic interleaves.
214
+ const before = this.indexedBytes;
215
+ await new Promise((resolve) => setImmediate(resolve));
216
+ if (this.indexedBytes === before)
217
+ break; // no progress (read error) — bail out
218
+ }
219
+ })().finally(() => {
220
+ this.warmupPromise = null;
221
+ });
222
+ return this.warmupPromise;
223
+ }
224
+ fileSize() {
225
+ try {
226
+ return fs.statSync(this.datasetPath).size;
227
+ }
228
+ catch {
229
+ return 0;
230
+ }
231
+ }
232
+ /** Parse a block of complete newline-terminated lines into the index. */
233
+ indexLines(block, blockStartOffset) {
234
+ let lineStart = 0;
235
+ for (;;) {
236
+ const nl = block.indexOf(0x0a, lineStart);
237
+ if (nl === -1)
238
+ break;
239
+ // Decode per line: `lineStart`/`nl` are byte offsets, so each line is a
240
+ // complete UTF-8 sequence regardless of chunk boundaries.
241
+ const line = block.toString('utf8', lineStart, nl).trim();
242
+ this.indexOne(line, blockStartOffset + lineStart);
243
+ lineStart = nl + 1;
244
+ }
245
+ }
246
+ indexOne(line, byteOffset) {
247
+ // No size cap here: the collector truncates prompts far below readRow()'s
248
+ // 4 MiB range cap, so oversized lines are only reachable via out-of-band writes.
249
+ if (!line)
250
+ return;
251
+ let raw;
252
+ try {
253
+ raw = JSON.parse(line);
254
+ }
255
+ catch {
256
+ return; // torn/malformed line — skip, never break the console
257
+ }
258
+ const rec = migrateRecord(raw);
259
+ if (!rec)
260
+ return;
261
+ if (this.n === this.cap)
262
+ this.grow();
263
+ const i = this.n++;
264
+ this.ids.push(rec.id);
265
+ this.idToIdx.set(rec.id, { idx: i }); // last write wins: relabel targets the newest row
266
+ this.offsets[i] = byteOffset;
267
+ this.tsMs[i] = Date.parse(rec.timestamp) || 0;
268
+ const t = rec.label.tier;
269
+ this.tierIdx[i] = t ? FLYWHEEL_TIERS.indexOf(t) : TIER_NONE;
270
+ this.srcIdx[i] = Math.max(0, SOURCE_ORDER.indexOf(rec.label.source));
271
+ let f = 0;
272
+ if (rec.execution.isSynthetic)
273
+ f |= F_SYNTHETIC;
274
+ if (rec.execution.fallbackOccurred)
275
+ f |= F_FALLBACK;
276
+ if (rec.input.featureVector && rec.input.featureVector.length === VECTOR_DIMS) {
277
+ f |= F_TRAINABLE;
278
+ for (let d = 0; d < VECTOR_DIMS; d++)
279
+ this.vectors[i * VECTOR_DIMS + d] = rec.input.featureVector[d];
280
+ }
281
+ this.flags[i] = f;
282
+ const model = rec.execution.modelUsed;
283
+ let mi = this.modelPool.indexOf(model);
284
+ if (mi === -1) {
285
+ this.modelPool.push(model);
286
+ mi = this.modelPool.length - 1;
287
+ }
288
+ this.modelIdx[i] = mi;
289
+ this.promptPrefix.push(rec.input.userPrompt.slice(0, 48).toLowerCase());
290
+ }
291
+ grow() {
292
+ const newCap = this.cap === 0 ? 1024 : this.cap * 2;
293
+ const offsets = new Float64Array(newCap);
294
+ offsets.set(this.offsets.subarray(0, this.n));
295
+ const tsMs = new Float64Array(newCap);
296
+ tsMs.set(this.tsMs.subarray(0, this.n));
297
+ const vectors = new Float64Array(newCap * VECTOR_DIMS);
298
+ vectors.set(this.vectors.subarray(0, this.n * VECTOR_DIMS));
299
+ const tierIdx = new Uint8Array(newCap);
300
+ tierIdx.set(this.tierIdx.subarray(0, this.n));
301
+ const srcIdx = new Uint8Array(newCap);
302
+ srcIdx.set(this.srcIdx.subarray(0, this.n));
303
+ const flags = new Uint8Array(newCap);
304
+ flags.set(this.flags.subarray(0, this.n));
305
+ const modelIdx = new Int32Array(newCap);
306
+ modelIdx.set(this.modelIdx.subarray(0, this.n));
307
+ this.offsets = offsets;
308
+ this.tsMs = tsMs;
309
+ this.vectors = vectors;
310
+ this.tierIdx = tierIdx;
311
+ this.srcIdx = srcIdx;
312
+ this.flags = flags;
313
+ this.modelIdx = modelIdx;
314
+ this.cap = newCap;
315
+ }
316
+ // ---- overrides -----------------------------------------------------------
317
+ loadOverrides() {
318
+ if (this.labelsLoaded)
319
+ return;
320
+ try {
321
+ const parsed = JSON.parse(fs.readFileSync(this.labelsPath, 'utf8'));
322
+ const out = {};
323
+ for (const [id, value] of Object.entries(parsed || {})) {
324
+ const v = value;
325
+ if (v && isTier(v.tier))
326
+ out[id] = { tier: v.tier, updatedAt: String(v.updatedAt || '') };
327
+ }
328
+ this.overrides = out;
329
+ }
330
+ catch {
331
+ this.overrides = {};
332
+ }
333
+ this.labelsLoaded = true;
334
+ }
335
+ writeOverrides() {
336
+ const dir = path.dirname(this.labelsPath);
337
+ if (!fs.existsSync(dir)) {
338
+ try {
339
+ fs.mkdirSync(dir, { recursive: true });
340
+ }
341
+ catch { /* best effort */ }
342
+ }
343
+ // Atomic swap: a crash mid-write must not corrupt the label history.
344
+ const tmp = `${this.labelsPath}.tmp`;
345
+ fs.writeFileSync(tmp, JSON.stringify(this.overrides, null, 2), 'utf8');
346
+ fs.renameSync(tmp, this.labelsPath);
347
+ }
348
+ /** Effective label for row i: the overlay if present, else the observed derivation. */
349
+ effectiveLabel(i) {
350
+ const observed = deriveDefaultLabel({
351
+ targetTier: FLYWHEEL_TIERS[this.tierIdx[i]] ?? 'plus',
352
+ tierUsed: FLYWHEEL_TIERS[this.tierIdx[i]] ?? 'plus',
353
+ fallbackOccurred: (this.flags[i] & F_FALLBACK) !== 0,
354
+ });
355
+ const override = this.overrides[this.ids[i]];
356
+ if (!override)
357
+ return observed;
358
+ return {
359
+ ...observed,
360
+ tier: override.tier,
361
+ source: 'human',
362
+ confidence: 1,
363
+ updatedAt: override.updatedAt,
364
+ };
365
+ }
366
+ /**
367
+ * Set or clear an operator label. Returns the row's effective label after
368
+ * the change (human override or re-derived observation), or null when the
369
+ * id does not exist in the dataset. Targets the most recent row with that id.
370
+ */
371
+ setLabel(id, tier) {
372
+ this.ensureIndexed();
373
+ const entry = this.idToIdx.get(id);
374
+ if (!entry)
375
+ return null;
376
+ if (tier === null) {
377
+ delete this.overrides[id];
378
+ }
379
+ else {
380
+ if (!isTier(tier))
381
+ throw new Error(`Invalid tier: ${String(tier)}`);
382
+ this.overrides[id] = { tier, updatedAt: new Date().toISOString() };
383
+ }
384
+ this.writeOverrides();
385
+ return this.effectiveLabel(entry.idx);
386
+ }
387
+ /** Clear every operator label (does not touch the append-only dataset). */
388
+ clearOverrides() {
389
+ this.ensureIndexed();
390
+ const count = Object.keys(this.overrides).length;
391
+ this.overrides = {};
392
+ this.writeOverrides();
393
+ return count;
394
+ }
395
+ // ---- random row access ---------------------------------------------------
396
+ /** Read one full record back off disk by index position (lazy detail). */
397
+ readRow(i) {
398
+ this.ensureIndexed();
399
+ if (i < 0 || i >= this.n)
400
+ return null;
401
+ const start = this.offsets[i];
402
+ // The last indexed row ends where the last COMPLETE line ends
403
+ // (indexedBytes), not at fileSize(): a torn trailing line (crash
404
+ // mid-append) must not glue itself onto the last record and break its
405
+ // JSON.parse.
406
+ const end = i + 1 < this.n ? this.offsets[i + 1] : this.indexedBytes;
407
+ const len = Math.max(0, end - start);
408
+ if (len === 0 || len > 4 * 1024 * 1024)
409
+ return null;
410
+ // Open-per-read: same Windows rename-share rule as ensureIndexed().
411
+ let fd;
412
+ try {
413
+ fd = fs.openSync(this.datasetPath, 'r');
414
+ }
415
+ catch {
416
+ return null;
417
+ }
418
+ const buf = Buffer.allocUnsafe(len);
419
+ try {
420
+ const got = fs.readSync(fd, buf, 0, len, start);
421
+ // The range can contain more than one physical line when torn writes or
422
+ // malformed rows sit between indexed records. Record i starts exactly at
423
+ // `start`, so the first non-blank line IS record i — parse only that one
424
+ // and never fall through: a later line would serve a different record's
425
+ // content under row i's label.
426
+ for (const line of buf.toString('utf8', 0, got).split('\n')) {
427
+ const trimmed = line.trim();
428
+ if (!trimmed)
429
+ continue;
430
+ const rec = migrateRecord(JSON.parse(trimmed));
431
+ return rec ? { ...rec, label: this.effectiveLabel(i) } : null;
432
+ }
433
+ return null;
434
+ }
435
+ catch {
436
+ return null;
437
+ }
438
+ finally {
439
+ try {
440
+ fs.closeSync(fd);
441
+ }
442
+ catch {
443
+ /* already closed */
444
+ }
445
+ }
446
+ }
447
+ // ---- summary -------------------------------------------------------------
448
+ summary() {
449
+ this.ensureIndexed();
450
+ if (this.summaryCache && this.summaryCache.version === this.indexVersion) {
451
+ return this.summaryCache.value;
452
+ }
453
+ const trainableByTier = {};
454
+ const sourceDistribution = {};
455
+ let trainable = 0;
456
+ let synthetic = 0;
457
+ let humanLabeled = 0;
458
+ let unlabeled = 0;
459
+ let minTs = Infinity;
460
+ let maxTs = -Infinity;
461
+ for (let i = 0; i < this.n; i++) {
462
+ const f = this.flags[i];
463
+ if (f & F_SYNTHETIC)
464
+ synthetic++;
465
+ const label = this.effectiveLabel(i);
466
+ if (label.source === 'human')
467
+ humanLabeled++;
468
+ sourceDistribution[label.source] = (sourceDistribution[label.source] || 0) + 1;
469
+ if (label.tier) {
470
+ if ((f & F_TRAINABLE) && !(f & F_SYNTHETIC)) {
471
+ trainable++;
472
+ trainableByTier[label.tier] = (trainableByTier[label.tier] || 0) + 1;
473
+ }
474
+ }
475
+ else {
476
+ unlabeled++;
477
+ }
478
+ if (this.tsMs[i] < minTs)
479
+ minTs = this.tsMs[i];
480
+ if (this.tsMs[i] > maxTs)
481
+ maxTs = this.tsMs[i];
482
+ }
483
+ const value = {
484
+ total: this.n,
485
+ trainable,
486
+ synthetic,
487
+ humanLabeled,
488
+ unlabeled,
489
+ trainableByTier,
490
+ sourceDistribution,
491
+ datasetPath: this.datasetPath,
492
+ labelsPath: this.labelsPath,
493
+ fileBytes: this.fileSize(),
494
+ firstTimestamp: Number.isFinite(minTs) ? new Date(minTs).toISOString() : null,
495
+ lastTimestamp: Number.isFinite(maxTs) ? new Date(maxTs).toISOString() : null,
496
+ };
497
+ this.summaryCache = { version: this.indexVersion, value };
498
+ return value;
499
+ }
500
+ // ---- query ----------------------------------------------------------------
501
+ /** Effective tier for row i — the overlay if present, else the indexed value. */
502
+ effTier(i) {
503
+ const o = this.overrides[this.ids[i]];
504
+ if (o)
505
+ return o.tier;
506
+ return this.tierIdx[i] === TIER_NONE ? null : FLYWHEEL_TIERS[this.tierIdx[i]];
507
+ }
508
+ /** Effective label source for row i — 'human' when an overlay exists. */
509
+ effSource(i) {
510
+ return this.overrides[this.ids[i]] ? 'human' : SOURCE_ORDER[this.srcIdx[i]];
511
+ }
512
+ matchesIndex(i, q) {
513
+ const f = this.flags[i];
514
+ if (!q.includeSynthetic && f & F_SYNTHETIC)
515
+ return false;
516
+ if (q.trainableOnly && !(f & F_TRAINABLE && !(f & F_SYNTHETIC) && this.effTier(i) !== null))
517
+ return false;
518
+ // Tier/source filtering MUST consult the effective (overlay-aware) values:
519
+ // a human relabel changes both without touching the index columns. The
520
+ // lookup is skipped entirely while no overrides exist — the common case.
521
+ if (q.tier && q.tier !== 'any') {
522
+ const t = Object.keys(this.overrides).length > 0 ? this.effTier(i) : (this.tierIdx[i] === TIER_NONE ? null : FLYWHEEL_TIERS[this.tierIdx[i]]);
523
+ if (q.tier === 'none') {
524
+ if (t !== null)
525
+ return false;
526
+ }
527
+ else if (t !== q.tier)
528
+ return false;
529
+ }
530
+ if (q.source && q.source !== 'any') {
531
+ const s = Object.keys(this.overrides).length > 0 ? this.effSource(i) : SOURCE_ORDER[this.srcIdx[i]];
532
+ if (s !== q.source)
533
+ return false;
534
+ }
535
+ if (q.search) {
536
+ const needle = q.search.toLowerCase();
537
+ const model = this.modelPool[this.modelIdx[i]] || '';
538
+ if (!this.ids[i].toLowerCase().includes(needle) &&
539
+ !model.toLowerCase().includes(needle) &&
540
+ !this.promptPrefix[i].includes(needle)) {
541
+ return false;
542
+ }
543
+ }
544
+ return true;
545
+ }
546
+ /**
547
+ * Filter over the columnar index (fast, no file I/O), then materialize only
548
+ * the returned page by reading those lines back off disk. Rows come back in
549
+ * append order, newest last-position first — for gateway traffic the append
550
+ * order IS the chronological order.
551
+ */
552
+ query(query = {}) {
553
+ this.ensureIndexed();
554
+ const limit = Math.min(Math.max(query.limit ?? 50, 1), 500);
555
+ const offset = Math.max(query.offset ?? 0, 0);
556
+ // Walk newest-first (append order reversed). The full pass is required for
557
+ // an exact `total`; over the columnar index this is a few typed-array
558
+ // comparisons per row, not file I/O.
559
+ const pageIdx = [];
560
+ let total = 0;
561
+ for (let i = this.n - 1; i >= 0; i--) {
562
+ if (!this.matchesIndex(i, query))
563
+ continue;
564
+ if (total >= offset && pageIdx.length < limit)
565
+ pageIdx.push(i);
566
+ total++;
567
+ }
568
+ const rows = [];
569
+ for (const i of pageIdx) {
570
+ const rec = this.readRow(i);
571
+ if (!rec)
572
+ continue;
573
+ rows.push({
574
+ id: rec.id,
575
+ timestamp: rec.timestamp,
576
+ userPrompt: rec.input.userPrompt,
577
+ tokenCount: rec.input.tokenCount,
578
+ featureVector: rec.input.featureVector,
579
+ decision: rec.decision,
580
+ execution: rec.execution,
581
+ label: rec.label,
582
+ });
583
+ }
584
+ return { rows, total, offset, limit };
585
+ }
586
+ // ---- training pool ---------------------------------------------------------
587
+ /**
588
+ * Materialize trainable samples straight from the index — no file I/O at
589
+ * all, the feature vectors are columns. Synthetic rows, unlabelled rows and
590
+ * rows whose feature vector is missing are dropped here, so the console and
591
+ * the trainer always agree on the eligible pool.
592
+ */
593
+ trainingSamples(options = {}) {
594
+ this.ensureIndexed();
595
+ const skipped = {
596
+ synthetic: 0,
597
+ unlabelled: 0,
598
+ missingVector: 0,
599
+ weakSource: 0,
600
+ badDimension: 0,
601
+ };
602
+ const samples = [];
603
+ const sourceRank = {
604
+ human: 3,
605
+ runtime_fallback: 2,
606
+ observed_execution: 1,
607
+ unlabeled: 0,
608
+ };
609
+ const minRank = sourceRank[options.minSource ?? 'observed_execution'];
610
+ for (let i = 0; i < this.n; i++) {
611
+ const f = this.flags[i];
612
+ if (f & F_SYNTHETIC && !options.includeSynthetic) {
613
+ skipped.synthetic++;
614
+ continue;
615
+ }
616
+ const label = this.effectiveLabel(i);
617
+ if (!label.tier) {
618
+ skipped.unlabelled++;
619
+ continue;
620
+ }
621
+ if (sourceRank[label.source] < minRank) {
622
+ skipped.weakSource++;
623
+ continue;
624
+ }
625
+ if (!(f & F_TRAINABLE)) {
626
+ skipped.missingVector++;
627
+ continue;
628
+ }
629
+ const features = Array.from(this.vectors.subarray(i * VECTOR_DIMS, (i + 1) * VECTOR_DIMS));
630
+ if (features.length !== VECTOR_DIMS) {
631
+ skipped.badDimension++;
632
+ continue;
633
+ }
634
+ samples.push({ features, targetTier: label.tier });
635
+ }
636
+ return { samples, featureDimensions: VECTOR_DIMS, skipped };
637
+ }
638
+ }