omnicell-router 0.1.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 (212) hide show
  1. package/RELEASING.md +238 -238
  2. package/RELEASING.zh-CN.md +230 -230
  3. package/backend/dist/capture/recorder.js +2 -1
  4. package/backend/dist/cli/clients/base.js +8 -16
  5. package/backend/dist/cli/clients/dsh.js +8 -16
  6. package/backend/dist/cli/clients/pi.js +16 -9
  7. package/backend/dist/cli/types.d.ts +5 -0
  8. package/backend/dist/config/env.js +2 -1
  9. package/backend/dist/config/index.js +2 -0
  10. package/backend/dist/config/types.d.ts +23 -0
  11. package/backend/dist/harness/adapters/amp.d.ts +2 -0
  12. package/backend/dist/harness/adapters/amp.js +7 -0
  13. package/backend/dist/harness/adapters/claude.d.ts +2 -0
  14. package/backend/dist/harness/adapters/claude.js +7 -0
  15. package/backend/dist/harness/adapters/cline.d.ts +2 -0
  16. package/backend/dist/harness/adapters/cline.js +6 -0
  17. package/backend/dist/harness/adapters/codex.d.ts +2 -0
  18. package/backend/dist/harness/adapters/codex.js +6 -0
  19. package/backend/dist/harness/adapters/cursor.d.ts +5 -0
  20. package/backend/dist/harness/adapters/cursor.js +10 -0
  21. package/backend/dist/harness/adapters/declarative.d.ts +62 -0
  22. package/backend/dist/harness/adapters/declarative.js +202 -0
  23. package/backend/dist/harness/adapters/dsh.d.ts +5 -0
  24. package/backend/dist/harness/adapters/dsh.js +6 -0
  25. package/backend/dist/harness/adapters/gemini-cli.d.ts +2 -0
  26. package/backend/dist/harness/adapters/gemini-cli.js +7 -0
  27. package/backend/dist/harness/adapters/github-copilot.d.ts +5 -0
  28. package/backend/dist/harness/adapters/github-copilot.js +10 -0
  29. package/backend/dist/harness/adapters/index.d.ts +44 -0
  30. package/backend/dist/harness/adapters/index.js +99 -0
  31. package/backend/dist/harness/adapters/opencode.d.ts +2 -0
  32. package/backend/dist/harness/adapters/opencode.js +55 -0
  33. package/backend/dist/harness/adapters/pi.d.ts +1 -0
  34. package/backend/dist/harness/adapters/pi.js +22 -0
  35. package/backend/dist/harness/adapters/skills-paths.d.ts +15 -0
  36. package/backend/dist/harness/adapters/skills-paths.js +17 -0
  37. package/backend/dist/harness/adapters/types.d.ts +174 -0
  38. package/backend/dist/harness/adapters/types.js +12 -0
  39. package/backend/dist/harness/adapters/universal.d.ts +6 -0
  40. package/backend/dist/harness/adapters/universal.js +10 -0
  41. package/backend/dist/harness/adapters/windsurf.d.ts +2 -0
  42. package/backend/dist/harness/adapters/windsurf.js +10 -0
  43. package/backend/dist/harness/adapters/zed.d.ts +2 -0
  44. package/backend/dist/harness/adapters/zed.js +6 -0
  45. package/backend/dist/harness/awesome-opencode.d.ts +40 -0
  46. package/backend/dist/harness/awesome-opencode.js +75 -0
  47. package/backend/dist/harness/browse.d.ts +202 -0
  48. package/backend/dist/harness/browse.js +1214 -0
  49. package/backend/dist/harness/catalog-npm.d.ts +59 -0
  50. package/backend/dist/harness/catalog-npm.js +145 -0
  51. package/backend/dist/harness/clawhub.d.ts +212 -0
  52. package/backend/dist/harness/clawhub.js +426 -0
  53. package/backend/dist/harness/config-file.d.ts +29 -0
  54. package/backend/dist/harness/config-file.js +35 -0
  55. package/backend/dist/harness/detail.d.ts +74 -0
  56. package/backend/dist/harness/detail.js +330 -0
  57. package/backend/dist/harness/discover.d.ts +118 -0
  58. package/backend/dist/harness/discover.js +507 -0
  59. package/backend/dist/harness/drift.d.ts +21 -0
  60. package/backend/dist/harness/drift.js +25 -0
  61. package/backend/dist/harness/hash.d.ts +10 -0
  62. package/backend/dist/harness/hash.js +63 -0
  63. package/backend/dist/harness/hosts.d.ts +18 -0
  64. package/backend/dist/harness/hosts.js +15 -0
  65. package/backend/dist/harness/install.d.ts +88 -0
  66. package/backend/dist/harness/install.js +301 -0
  67. package/backend/dist/harness/inventory.d.ts +10 -0
  68. package/backend/dist/harness/inventory.js +198 -0
  69. package/backend/dist/harness/ledger.d.ts +39 -0
  70. package/backend/dist/harness/ledger.js +83 -0
  71. package/backend/dist/harness/maintenance.d.ts +115 -0
  72. package/backend/dist/harness/maintenance.js +603 -0
  73. package/backend/dist/harness/manifest.d.ts +31 -0
  74. package/backend/dist/harness/manifest.js +234 -0
  75. package/backend/dist/harness/net.d.ts +86 -0
  76. package/backend/dist/harness/net.js +113 -0
  77. package/backend/dist/harness/opencode-cafe.d.ts +40 -0
  78. package/backend/dist/harness/opencode-cafe.js +85 -0
  79. package/backend/dist/harness/opencode-ecosystem.d.ts +34 -0
  80. package/backend/dist/harness/opencode-ecosystem.js +246 -0
  81. package/backend/dist/harness/pi-dev.d.ts +81 -0
  82. package/backend/dist/harness/pi-dev.js +187 -0
  83. package/backend/dist/harness/probe.d.ts +33 -0
  84. package/backend/dist/harness/probe.js +85 -0
  85. package/backend/dist/harness/registry.d.ts +2 -0
  86. package/backend/dist/harness/registry.js +26 -0
  87. package/backend/dist/harness/scopes.d.ts +21 -0
  88. package/backend/dist/harness/scopes.js +22 -0
  89. package/backend/dist/harness/skill-md.d.ts +18 -0
  90. package/backend/dist/harness/skill-md.js +71 -0
  91. package/backend/dist/harness/skills-sh.d.ts +109 -0
  92. package/backend/dist/harness/skills-sh.js +178 -0
  93. package/backend/dist/harness/smithery.d.ts +64 -0
  94. package/backend/dist/harness/smithery.js +146 -0
  95. package/backend/dist/harness/sources/awesome-opencode.d.ts +11 -0
  96. package/backend/dist/harness/sources/awesome-opencode.js +39 -0
  97. package/backend/dist/harness/sources/clawhub.d.ts +2 -0
  98. package/backend/dist/harness/sources/clawhub.js +83 -0
  99. package/backend/dist/harness/sources/github.d.ts +9 -0
  100. package/backend/dist/harness/sources/github.js +202 -0
  101. package/backend/dist/harness/sources/mcp-official.d.ts +2 -0
  102. package/backend/dist/harness/sources/mcp-official.js +110 -0
  103. package/backend/dist/harness/sources/npm.d.ts +2 -0
  104. package/backend/dist/harness/sources/npm.js +152 -0
  105. package/backend/dist/harness/sources/opencode-cafe.d.ts +11 -0
  106. package/backend/dist/harness/sources/opencode-cafe.js +41 -0
  107. package/backend/dist/harness/sources/smithery.d.ts +2 -0
  108. package/backend/dist/harness/sources/smithery.js +81 -0
  109. package/backend/dist/harness/spi.d.ts +98 -0
  110. package/backend/dist/harness/spi.js +8 -0
  111. package/backend/dist/harness/stars.d.ts +70 -0
  112. package/backend/dist/harness/stars.js +202 -0
  113. package/backend/dist/harness/translation.d.ts +142 -0
  114. package/backend/dist/harness/translation.js +567 -0
  115. package/backend/dist/harness/tree.d.ts +13 -0
  116. package/backend/dist/harness/tree.js +19 -0
  117. package/backend/dist/harness/types.d.ts +286 -0
  118. package/backend/dist/harness/types.js +8 -0
  119. package/backend/dist/harness/writers/extension.d.ts +116 -0
  120. package/backend/dist/harness/writers/extension.js +219 -0
  121. package/backend/dist/harness/writers/mcp.d.ts +72 -0
  122. package/backend/dist/harness/writers/mcp.js +195 -0
  123. package/backend/dist/harness/writers/skill.d.ts +60 -0
  124. package/backend/dist/harness/writers/skill.js +146 -0
  125. package/backend/dist/opencode/agents.d.ts +5 -0
  126. package/backend/dist/opencode/agents.js +10 -1
  127. package/backend/dist/opencode/catalog/cache.js +2 -1
  128. package/backend/dist/opencode/catalog/logos.js +2 -1
  129. package/backend/dist/opencode/catalog/ocr-store.js +2 -1
  130. package/backend/dist/opencode/catalog/overrides-store.js +2 -1
  131. package/backend/dist/opencode/credentials/factory.js +10 -27
  132. package/backend/dist/opencode/credentials/ocr-store.js +2 -1
  133. package/backend/dist/opencode/provider-defs.js +2 -1
  134. package/backend/dist/opencode/user-config.js +8 -16
  135. package/backend/dist/providers/registry.d.ts +15 -4
  136. package/backend/dist/providers/registry.js +29 -5
  137. package/backend/dist/providers/virtual-meta.d.ts +13 -0
  138. package/backend/dist/providers/virtual-meta.js +18 -0
  139. package/backend/dist/quota/store.js +2 -1
  140. package/backend/dist/resilience/breaker-state.js +2 -1
  141. package/backend/dist/resilience/credential-state.js +2 -1
  142. package/backend/dist/routes/console.js +137 -15
  143. package/backend/dist/routes/harness.d.ts +2 -0
  144. package/backend/dist/routes/harness.js +622 -0
  145. package/backend/dist/server.js +4 -0
  146. package/backend/dist/session/session-manager.js +2 -1
  147. package/backend/dist/surfaces/systemone-probe.d.ts +25 -0
  148. package/backend/dist/surfaces/systemone-probe.js +74 -0
  149. package/backend/dist/utils/atomic-write.d.ts +12 -0
  150. package/backend/dist/utils/atomic-write.js +29 -0
  151. package/bin/ocr.js +2 -2
  152. package/frontend/dist/assets/{index-DEo2iAT7.css → index-1o7qI-KJ.css} +1 -1
  153. package/frontend/dist/assets/index-DvXKvNxl.js +962 -0
  154. package/frontend/dist/index.html +2 -2
  155. package/package.json +87 -87
  156. package/backend/dist/budget/budget-manager.d.ts +0 -25
  157. package/backend/dist/budget/budget-manager.js +0 -54
  158. package/backend/dist/config/governance-limits.d.ts +0 -68
  159. package/backend/dist/config/governance-limits.js +0 -261
  160. package/backend/dist/flywheel/collector.d.ts +0 -74
  161. package/backend/dist/flywheel/collector.js +0 -235
  162. package/backend/dist/flywheel/dataset.d.ts +0 -130
  163. package/backend/dist/flywheel/dataset.js +0 -638
  164. package/backend/dist/flywheel/decision-capture.d.ts +0 -68
  165. package/backend/dist/flywheel/decision-capture.js +0 -85
  166. package/backend/dist/flywheel/prune.d.ts +0 -133
  167. package/backend/dist/flywheel/prune.js +0 -495
  168. package/backend/dist/flywheel/schema.d.ts +0 -108
  169. package/backend/dist/flywheel/schema.js +0 -117
  170. package/backend/dist/flywheel/trainer.d.ts +0 -84
  171. package/backend/dist/flywheel/trainer.js +0 -198
  172. package/backend/dist/opencode/catalog/custom-store.d.ts +0 -50
  173. package/backend/dist/opencode/catalog/custom-store.js +0 -144
  174. package/backend/dist/opencode/credentials/push.d.ts +0 -38
  175. package/backend/dist/opencode/credentials/push.js +0 -116
  176. package/backend/dist/opencode/credentials/reconcile.d.ts +0 -49
  177. package/backend/dist/opencode/credentials/reconcile.js +0 -216
  178. package/backend/dist/opencode/sync.d.ts +0 -29
  179. package/backend/dist/opencode/sync.js +0 -186
  180. package/backend/dist/pipeline/account-selection.d.ts +0 -101
  181. package/backend/dist/pipeline/account-selection.js +0 -112
  182. package/backend/dist/providers/systemone.d.ts +0 -29
  183. package/backend/dist/providers/systemone.js +0 -170
  184. package/backend/dist/ratelimit/duration.d.ts +0 -24
  185. package/backend/dist/ratelimit/duration.js +0 -43
  186. package/backend/dist/ratelimit/governance-runtime.d.ts +0 -121
  187. package/backend/dist/ratelimit/governance-runtime.js +0 -183
  188. package/backend/dist/ratelimit/index.d.ts +0 -4
  189. package/backend/dist/ratelimit/index.js +0 -4
  190. package/backend/dist/ratelimit/limiter.d.ts +0 -157
  191. package/backend/dist/ratelimit/limiter.js +0 -244
  192. package/backend/dist/ratelimit/sliding-window-counter.d.ts +0 -63
  193. package/backend/dist/ratelimit/sliding-window-counter.js +0 -103
  194. package/backend/dist/ratelimit/subject.d.ts +0 -26
  195. package/backend/dist/ratelimit/subject.js +0 -28
  196. package/backend/dist/resilience/account-state.d.ts +0 -84
  197. package/backend/dist/resilience/account-state.js +0 -228
  198. package/backend/dist/router/layer1-classifier.d.ts +0 -111
  199. package/backend/dist/router/layer1-classifier.js +0 -467
  200. package/backend/dist/router/layer2-judge.d.ts +0 -111
  201. package/backend/dist/router/layer2-judge.js +0 -373
  202. package/backend/dist/router/retry-escalation.d.ts +0 -89
  203. package/backend/dist/router/retry-escalation.js +0 -99
  204. package/backend/dist/routes/flywheel.d.ts +0 -3
  205. package/backend/dist/routes/flywheel.js +0 -268
  206. package/backend/dist/routes/systemone.d.ts +0 -3
  207. package/backend/dist/routes/systemone.js +0 -90
  208. package/backend/dist/surfaces/governance-envelope.d.ts +0 -34
  209. package/backend/dist/surfaces/governance-envelope.js +0 -47
  210. package/backend/dist/utils/token-estimator.d.ts +0 -7
  211. package/backend/dist/utils/token-estimator.js +0 -20
  212. package/frontend/dist/assets/index-nwgWkmU1.js +0 -840
@@ -1,495 +0,0 @@
1
- /**
2
- * Flywheel dataset lifecycle engine — the single implementation of the four
3
- * sanctioned deletion operations (prune, retention sweep, batch delete, reset),
4
- * shared by the HTTP console, the hourly collector sweep and the offline CLI.
5
- * Spec: docs/design/flywheel-deletion.md (D1–D3, D9).
6
- *
7
- * Invariants (red-lines R1–R3):
8
- * - A record is never mutated: whole-line discard only, survivor lines are
9
- * copied byte-for-byte verbatim.
10
- * - Every rewrite is atomic tmp+rename, so a reader never sees a partial file.
11
- * - Backup matrix: prune/reset write a full `.bak-<ts>` (rotated, newest 3);
12
- * batch delete appends removed lines verbatim to the `.deleted.jsonl`
13
- * sidecar (O(deleted), restore = append back); the retention sweep writes
14
- * nothing — bounded disk IS the feature, and the knobs are default-off.
15
- * - Every removal path purges dead ids from the labels overlay, so the
16
- * overlay never accumulates orphans keyed to removed records (D9).
17
- *
18
- * SYNC-STALL CEILING (marked, cp-marked): a rewrite reads and writes the whole
19
- * file synchronously — roughly 1–3 s at ~800 MB. Same trade-off as the sync
20
- * training loop (trainer.ts:11-15): HTTP calls are explicit operator actions
21
- * and the automated sweep is hourly, so the stall is rare and intentional.
22
- * Upgrade path if the ceiling is ever hit: move the rewrite into a worker
23
- * thread / streaming copy.
24
- *
25
- * No lock is needed (D2): rewrites are fully synchronous and JS is
26
- * single-threaded, so no in-process writer can interleave with one. External
27
- * rewrites (offline CLI, timer sweep) swap the inode and are picked up by the
28
- * inode guard in dataset.ts `ensureIndexed()`.
29
- */
30
- import fs from 'node:fs';
31
- import path from 'node:path';
32
- import { detectSynthetic, migrateRecord } from './schema.js';
33
- // ---- shared path conventions ------------------------------------------------
34
- /** Sidecar overlay path for human label corrections — mirrors FlywheelDataset. */
35
- export function labelsPathFor(datasetPath) {
36
- return `${datasetPath}.labels.json`;
37
- }
38
- /** Backup sidecar for batch-deleted lines (D3): removed rows land here verbatim. */
39
- export function sidecarPathFor(datasetPath) {
40
- return `${datasetPath}.deleted.jsonl`;
41
- }
42
- /**
43
- * Pure prune planner — no fs at all, so a preview can never write. Decision
44
- * order is identical to the historic CLI: synthetic → duplicate; malformed
45
- * (unparseable) lines are dropped unconditionally — hygiene IS prune's job
46
- * (D4). Valid-JSON lines that are not records are kept verbatim (CLI parity).
47
- */
48
- export function planPrune(lines, opts) {
49
- const keptLines = [];
50
- const removedLines = [];
51
- const keptIds = new Set();
52
- const seenIds = new Set();
53
- const dropped = { synthetic: 0, duplicate: 0, malformed: 0 };
54
- let total = 0;
55
- for (const line of lines) {
56
- const trimmed = line.trim();
57
- if (!trimmed)
58
- continue; // blank lines never count and never survive a rewrite
59
- total++;
60
- // JSON.parse output is untyped by nature; every access below is optional-
61
- // chained or coerced, and the duplicate/kept-id path goes through
62
- // migrateRecord, which validates property by property.
63
- let parsed;
64
- try {
65
- parsed = JSON.parse(trimmed);
66
- }
67
- catch {
68
- dropped.malformed++;
69
- removedLines.push(line);
70
- continue;
71
- }
72
- // Reuse the collector's own detector so a prune can never disagree with
73
- // what the console labels as test traffic. migrateRecord validates
74
- // property by property; a pre-v2 line comes back null and is kept
75
- // verbatim unless a drop option applies.
76
- const exec = parsed?.execution;
77
- const isSynthetic = exec?.isSynthetic === true ||
78
- detectSynthetic(String(parsed?.id ?? ''), String(exec?.modelUsed ?? ''), exec?.fallbackReason);
79
- if (opts.dropSynthetic && isSynthetic) {
80
- dropped.synthetic++;
81
- removedLines.push(line);
82
- continue;
83
- }
84
- const rec = migrateRecord(parsed);
85
- const id = rec?.id ?? trimmed;
86
- if (opts.dropDuplicates && seenIds.has(id)) {
87
- dropped.duplicate++;
88
- removedLines.push(line);
89
- continue;
90
- }
91
- seenIds.add(id);
92
- keptLines.push(line);
93
- if (rec)
94
- keptIds.add(rec.id);
95
- }
96
- return { total, keptLines, removedLines, keptIds, dropped };
97
- }
98
- /**
99
- * Prune one dataset file (CLI + HTTP share this). `apply: false` is pure
100
- * preview. Nothing-to-prune → no rewrite, no backup, mtime untouched,
101
- * `applied: false`. Returns null when the dataset file does not exist
102
- * (caller decides 404 vs no-op).
103
- */
104
- export function pruneDataset(datasetPath, opts, apply) {
105
- const read = readDatasetLines(datasetPath);
106
- if (!read)
107
- return null;
108
- const plan = planPrune(read.lines, opts);
109
- if (!apply || plan.removedLines.length === 0) {
110
- return {
111
- total: plan.total,
112
- kept: plan.keptLines.length,
113
- dropped: plan.dropped,
114
- applied: false,
115
- backupPath: null,
116
- removedLabels: 0,
117
- };
118
- }
119
- const res = writeRewrite(datasetPath, plan.keptLines, plan.removedLines, { backup: true, rotateKeep: 3 });
120
- const removedLabels = pruneLabelOverlay(labelsPathFor(datasetPath), plan.keptIds);
121
- return {
122
- total: res.total,
123
- kept: res.kept,
124
- dropped: plan.dropped,
125
- applied: res.rewrote,
126
- backupPath: res.backupPath,
127
- removedLabels,
128
- };
129
- }
130
- /**
131
- * Generic filter-and-rewrite (D2): `filter` is consulted once per non-blank
132
- * line, in file order; a false verdict discards the line verbatim (into the
133
- * sidecar when one is configured). Nothing removed → zero writes.
134
- */
135
- export function rewriteDataset(datasetPath, filter, opts = {}) {
136
- const read = readDatasetLines(datasetPath);
137
- if (!read)
138
- return { total: 0, kept: 0, removed: 0, rewrote: false, backupPath: null };
139
- const kept = [];
140
- const removed = [];
141
- for (const line of read.lines) {
142
- if (line.trim() === '')
143
- continue;
144
- (filter(line) ? kept : removed).push(line);
145
- }
146
- return writeRewrite(datasetPath, kept, removed, opts);
147
- }
148
- /** Sync spin wait — the whole rewrite is synchronous (D2); Atomics.wait is Node's only timer-free sleep. */
149
- function sleepSync(ms) {
150
- Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
151
- }
152
- /**
153
- * Atomic tmp→target swap with a bounded retry. Windows rejects renaming over
154
- * a file an AV/indexer handle momentarily holds open (intermittent EPERM /
155
- * EACCES / EBUSY sharing violations — reproduced ~1/40 runs on the dev host).
156
- * Up to 4 backoff sleeps (10/20/30/40 ms) keeps the engine fully synchronous
157
- * and the stall operator-invisible. On exhaustion: tmp is cleaned, the
158
- * original file is untouched, and the error is rethrown fail-loud (R3 stays
159
- * all-or-nothing). Marked ceiling (cp-marked): upgrade path is platform
160
- * share-flags or a queued writer if contention ever turns chronic.
161
- */
162
- function atomicSwap(tmp, target) {
163
- for (let attempt = 0;; attempt++) {
164
- try {
165
- fs.renameSync(tmp, target);
166
- return;
167
- }
168
- catch (err) {
169
- const transient = ['EPERM', 'EACCES', 'EBUSY'].includes(err?.code);
170
- if (!transient || attempt >= 4) {
171
- try {
172
- fs.rmSync(tmp, { force: true });
173
- }
174
- catch {
175
- /* tmp never materialised */
176
- }
177
- throw err;
178
- }
179
- sleepSync(10 * (attempt + 1));
180
- }
181
- }
182
- }
183
- /**
184
- * The single writer. Order matters for fail-safety: backup first, sidecar
185
- * before the swap (a failed rewrite must never lose the removed lines — a
186
- * re-run re-deletes idempotently), tmp+rename last. The original file is only
187
- * ever replaced by an atomic rename, so a throw leaves it untouched.
188
- */
189
- function writeRewrite(datasetPath, kept, removed, opts) {
190
- const result = {
191
- total: kept.length + removed.length,
192
- kept: kept.length,
193
- removed: removed.length,
194
- rewrote: false,
195
- backupPath: null,
196
- };
197
- if (removed.length === 0)
198
- return result; // nothing to prune — leave mtime untouched
199
- if (opts.backup) {
200
- result.backupPath = `${datasetPath}.bak-${Date.now()}`;
201
- fs.copyFileSync(datasetPath, result.backupPath);
202
- rotateBackups(datasetPath, opts.rotateKeep ?? 3);
203
- }
204
- if (opts.sidecarPath && removed.length) {
205
- fs.appendFileSync(opts.sidecarPath, removed.join('\n') + '\n', 'utf8');
206
- }
207
- // Unique tmp name: the gateway process and the offline CLI can rewrite the
208
- // same dataset concurrently; rename is atomic per file, so the last writer
209
- // wins wholesale and never interleaves two partial outputs.
210
- const tmp = `${datasetPath}.tmp-${process.pid}`;
211
- const content = kept.length ? kept.join('\n') + '\n' : '';
212
- try {
213
- fs.writeFileSync(tmp, content, 'utf8');
214
- }
215
- catch (err) {
216
- try {
217
- fs.rmSync(tmp, { force: true });
218
- }
219
- catch {
220
- /* tmp never materialised */
221
- }
222
- throw err;
223
- }
224
- atomicSwap(tmp, datasetPath);
225
- result.rewrote = true;
226
- return result;
227
- }
228
- /** Read dataset as physical lines; null when the file does not exist. */
229
- function readDatasetLines(datasetPath) {
230
- let raw;
231
- try {
232
- raw = fs.readFileSync(datasetPath, 'utf8');
233
- }
234
- catch (err) {
235
- if (err?.code === 'ENOENT')
236
- return null;
237
- throw err;
238
- }
239
- const lines = raw.split('\n');
240
- if (lines.length > 0 && lines[lines.length - 1] === '')
241
- lines.pop();
242
- return { raw, lines };
243
- }
244
- /** Parse + migrate one line, swallowing both failures (delete ops never classify). */
245
- function migrateQuiet(line) {
246
- try {
247
- return migrateRecord(JSON.parse(line.trim()));
248
- }
249
- catch {
250
- return null;
251
- }
252
- }
253
- /**
254
- * Delete all but the newest `keep` `<path>.bak-<ts>` siblings (rotation keeps
255
- * `.bak` churn bounded — design risk table). Best-effort: a failed unlink
256
- * leaves one stale backup, which must never fail an operation whose backup
257
- * already landed.
258
- */
259
- export function rotateBackups(datasetPath, keep = 3) {
260
- const dir = path.dirname(datasetPath);
261
- const prefix = `${path.basename(datasetPath)}.bak-`;
262
- let names;
263
- try {
264
- names = fs.readdirSync(dir);
265
- }
266
- catch {
267
- return;
268
- }
269
- const backups = names
270
- .filter((n) => n.startsWith(prefix) && /^\d+$/.test(n.slice(prefix.length)))
271
- .sort((a, b) => Number(b.slice(prefix.length)) - Number(a.slice(prefix.length)));
272
- for (const stale of backups.slice(keep)) {
273
- try {
274
- fs.rmSync(path.join(dir, stale), { force: true });
275
- }
276
- catch {
277
- /* best effort — see docstring */
278
- }
279
- }
280
- }
281
- /**
282
- * Partial-success + idempotent batch delete: every line whose record id is in
283
- * `ids` is discarded (all duplicates of a deleted id go — whole-record
284
- * discard), the removed lines are appended verbatim to the sidecar, and the
285
- * labels overlay is purged down to the surviving ids (which also sweeps up
286
- * pre-existing orphans keyed to ids that died earlier).
287
- * Missing dataset file → every id is notFound, zero writes.
288
- */
289
- export function deleteRecordsById(datasetPath, ids) {
290
- const wanted = new Set(ids);
291
- const found = new Set();
292
- const keptIds = new Set();
293
- const sidecarPath = sidecarPathFor(datasetPath);
294
- const res = rewriteDataset(datasetPath, (line) => {
295
- const rec = migrateQuiet(line);
296
- if (!rec)
297
- return true; // malformed / not a record — no id, never matches
298
- if (wanted.has(rec.id)) {
299
- found.add(rec.id);
300
- return false;
301
- }
302
- keptIds.add(rec.id);
303
- return true;
304
- }, { sidecarPath });
305
- const removedLabels = res.rewrote ? pruneLabelOverlay(labelsPathFor(datasetPath), keptIds) : 0;
306
- return {
307
- deleted: res.removed,
308
- notFound: [...wanted].filter((id) => !found.has(id)),
309
- removedLabels,
310
- sidecarPath,
311
- rewrote: res.rewrote,
312
- };
313
- }
314
- /**
315
- * Empty the dataset and clear the labels overlay; both are archived as
316
- * `.bak-<ts>` before the swap (the overlay only when non-empty — D3). Never
317
- * touches the trained model files: data lifecycle ≠ deployed weights (D8).
318
- * Missing/empty dataset → zero removals, no backup, no write (idempotent).
319
- */
320
- export function resetDataset(datasetPath) {
321
- const outcome = {
322
- removedRecords: 0,
323
- removedLabels: 0,
324
- backupPath: null,
325
- labelsBackupPath: null,
326
- datasetRewrote: false,
327
- };
328
- const read = readDatasetLines(datasetPath);
329
- if (read) {
330
- const content = read.lines.filter((l) => l.trim() !== '');
331
- if (content.length > 0) {
332
- const res = writeRewrite(datasetPath, [], content, { backup: true, rotateKeep: 3 });
333
- outcome.removedRecords = res.removed;
334
- outcome.backupPath = res.backupPath;
335
- outcome.datasetRewrote = res.rewrote;
336
- }
337
- }
338
- // Labels overlay: archive the raw bytes verbatim (even a corrupt file is
339
- // data), then clear. A `{}`-shaped overlay is "empty": no backup, no write.
340
- const labelsPath = labelsPathFor(datasetPath);
341
- let raw;
342
- try {
343
- raw = fs.readFileSync(labelsPath, 'utf8');
344
- }
345
- catch (err) {
346
- if (err?.code !== 'ENOENT')
347
- throw err;
348
- raw = null;
349
- }
350
- if (raw !== null && raw.trim() !== '') {
351
- let entries = null;
352
- try {
353
- const parsed = JSON.parse(raw);
354
- if (parsed && typeof parsed === 'object' && !Array.isArray(parsed))
355
- entries = parsed;
356
- }
357
- catch {
358
- /* unparseable overlay: removedLabels stays 0, the bytes still get archived */
359
- }
360
- const nonEmpty = entries === null ? raw.trim() !== '{}' : Object.keys(entries).length > 0;
361
- if (nonEmpty) {
362
- outcome.labelsBackupPath = `${labelsPath}.bak-${Date.now()}`;
363
- fs.copyFileSync(labelsPath, outcome.labelsBackupPath);
364
- rotateBackups(labelsPath);
365
- if (entries)
366
- outcome.removedLabels = Object.keys(entries).length;
367
- writeOverlayJson(labelsPath, {});
368
- }
369
- }
370
- return outcome;
371
- }
372
- /**
373
- * One combined rewrite: the age pass runs first (drop records whose
374
- * `timestamp` is older than retentionDays), then the size pass trims
375
- * oldest-first until the file fits maxFileSizeMB. A record with an
376
- * unparseable timestamp is ALWAYS kept (and treated as newest for the size
377
- * pass); malformed lines are kept too — hygiene is prune's job (D4).
378
- * NO backup is written (D3: retention is the only zero-backup path; the
379
- * knobs are default-off to guard it). Zero removals or both knobs off →
380
- * zero fs writes.
381
- */
382
- export function applyRetention(datasetPath, cfg) {
383
- const days = Math.max(0, Number.isFinite(cfg.retentionDays) ? cfg.retentionDays : 0);
384
- const mb = Math.max(0, Number.isFinite(cfg.maxFileSizeMB) ? cfg.maxFileSizeMB : 0);
385
- if (days === 0 && mb === 0)
386
- return { removed: 0, removedLabels: 0, rewrote: false };
387
- const read = readDatasetLines(datasetPath);
388
- if (!read)
389
- return { removed: 0, removedLabels: 0, rewrote: false };
390
- const cutoff = days > 0 ? Date.now() - days * 86_400_000 : -Infinity;
391
- const survivors = [];
392
- const removedLines = [];
393
- for (const line of read.lines) {
394
- if (line.trim() === '')
395
- continue;
396
- const rec = migrateQuiet(line);
397
- const parsedTs = rec ? Date.parse(rec.timestamp) : NaN;
398
- const ts = Number.isFinite(parsedTs) ? parsedTs : Infinity;
399
- if (rec && ts < cutoff) {
400
- removedLines.push(line);
401
- continue; // age pass
402
- }
403
- survivors.push({ line, bytes: Buffer.byteLength(line, 'utf8') + 1, ts, id: rec?.id ?? null });
404
- }
405
- let keptRows = survivors;
406
- if (mb > 0) {
407
- const maxBytes = mb * 1024 * 1024;
408
- let totalBytes = survivors.reduce((sum, r) => sum + r.bytes, 0);
409
- if (totalBytes > maxBytes) {
410
- const byAge = [...survivors].sort((a, b) => a.ts - b.ts); // Infinity sorts last
411
- const dropped = new Set();
412
- for (const row of byAge) {
413
- if (totalBytes <= maxBytes)
414
- break;
415
- dropped.add(row);
416
- totalBytes -= row.bytes;
417
- }
418
- for (const row of dropped)
419
- removedLines.push(row.line);
420
- keptRows = survivors.filter((r) => !dropped.has(r));
421
- }
422
- }
423
- if (removedLines.length === 0)
424
- return { removed: 0, removedLabels: 0, rewrote: false };
425
- // D9 purge must see the FINAL survivor set: the size pass trims rows after
426
- // the age pass, so keptIds is rebuilt from keptRows — ids collected before
427
- // the trim would keep size-removed labels alive as orphans (finding F1).
428
- const keptIds = new Set();
429
- for (const row of keptRows)
430
- if (row.id !== null)
431
- keptIds.add(row.id);
432
- const res = writeRewrite(datasetPath, keptRows.map((r) => r.line), removedLines, {});
433
- const removedLabels = pruneLabelOverlay(labelsPathFor(datasetPath), keptIds);
434
- return { removed: res.removed, removedLabels, rewrote: res.rewrote };
435
- }
436
- // ---- labels overlay purge (D9, shared by all four paths) -----------------------
437
- /**
438
- * Atomically rewrite the labels overlay. `keepIds === null` clears every
439
- * entry (reset); a Set keeps only entries whose id is still alive in the
440
- * dataset. Missing or unparseable overlay → zero writes (the dataset reader
441
- * already ignores a corrupt overlay; deleting targeted entries from bytes we
442
- * cannot interpret would be data loss). Returns entries removed.
443
- */
444
- export function pruneLabelOverlay(labelsPath, keepIds) {
445
- let parsed;
446
- try {
447
- const raw = fs.readFileSync(labelsPath, 'utf8');
448
- const obj = JSON.parse(raw);
449
- if (!obj || typeof obj !== 'object' || Array.isArray(obj))
450
- return 0;
451
- parsed = obj;
452
- }
453
- catch {
454
- return 0;
455
- }
456
- const ids = Object.keys(parsed);
457
- const doomed = keepIds === null ? ids : ids.filter((id) => !keepIds.has(id));
458
- if (doomed.length === 0)
459
- return 0;
460
- const survivors = {};
461
- if (keepIds !== null) {
462
- for (const [id, value] of Object.entries(parsed)) {
463
- if (keepIds.has(id))
464
- survivors[id] = value;
465
- }
466
- }
467
- writeOverlayJson(labelsPath, survivors);
468
- return doomed.length;
469
- }
470
- /** Atomic overlay swap in the exact format FlywheelDataset.writeOverrides uses. */
471
- function writeOverlayJson(labelsPath, map) {
472
- const dir = path.dirname(labelsPath);
473
- if (!fs.existsSync(dir)) {
474
- try {
475
- fs.mkdirSync(dir, { recursive: true });
476
- }
477
- catch {
478
- /* best effort — the write below surfaces a real problem */
479
- }
480
- }
481
- const tmp = `${labelsPath}.tmp-${process.pid}`;
482
- try {
483
- fs.writeFileSync(tmp, JSON.stringify(map, null, 2), 'utf8');
484
- }
485
- catch (err) {
486
- try {
487
- fs.rmSync(tmp, { force: true });
488
- }
489
- catch {
490
- /* tmp never materialised */
491
- }
492
- throw err;
493
- }
494
- atomicSwap(tmp, labelsPath);
495
- }
@@ -1,108 +0,0 @@
1
- /**
2
- * Flywheel dataset schema (v2) — the on-disk contract between the collector,
3
- * the training pipeline and the console.
4
- *
5
- * v1 stored five derived booleans (`hasCode`, `complexityScore`, …) that the
6
- * trainer cannot consume: `Layer1Classifier.train()` needs the 8-dimensional
7
- * vector produced by `Layer1Classifier.extractFeatures()`. v2 stores THAT
8
- * vector, so a record is trainable the moment it is written. There is no v1
9
- * reader: a v1 line parses as malformed and is dropped with a warning
10
- * (0.0.1 — no dataset outside this install ever existed).
11
- */
12
- import { ReasonParams, TierLevel } from '../types/router.js';
13
- export declare const FLYWHEEL_SCHEMA_VERSION = 2;
14
- export declare const FLYWHEEL_TIERS: TierLevel[];
15
- /** Where the training label came from, strongest last. */
16
- export type FlywheelLabelSource = 'human' | 'runtime_fallback' | 'observed_execution' | 'unlabeled';
17
- export interface FlywheelLabel {
18
- /** Training target. null = not labelled yet. */
19
- tier: TierLevel | null;
20
- source: FlywheelLabelSource;
21
- /** 0..1 — how much the label can be trusted. Drives sample weighting in the UI. */
22
- confidence: number;
23
- /** True when the router wanted a different tier than the one that served. */
24
- overridden: boolean;
25
- /** True when the cheaper-than-target tier could not handle the request. */
26
- isNegativeForLite: boolean;
27
- /** Set by console relabelling. */
28
- updatedAt?: string;
29
- }
30
- export interface FlywheelRecord {
31
- /** schemaVersion — 2 for everything this module writes. */
32
- v: number;
33
- id: string;
34
- timestamp: string;
35
- input: {
36
- userPrompt: string;
37
- /** The 8 features `Layer1Classifier.train()` consumes, in featureNames order. */
38
- featureVector: number[] | null;
39
- featureNames: string[];
40
- tokenCount: number;
41
- turnCount: number;
42
- };
43
- decision: {
44
- targetTier: TierLevel;
45
- confidence: number;
46
- layerUsed: 'layer0' | 'layer1' | 'layer2';
47
- /** Verbatim routing reason — the provenance signal that identifies the real mechanism. */
48
- reason: string;
49
- /**
50
- * Machine-readable reason vocabulary. Optional both ways: rows written
51
- * before it existed parse with `undefined` — no data migration.
52
- */
53
- reasonCode?: string;
54
- reasonParams?: ReasonParams;
55
- };
56
- execution: {
57
- tierUsed: TierLevel;
58
- modelUsed: string;
59
- fallbackOccurred: boolean;
60
- fallbackReason?: string;
61
- latencyMs: number;
62
- /** Bench/test traffic — excluded from training by default. */
63
- isSynthetic: boolean;
64
- };
65
- label: FlywheelLabel;
66
- }
67
- export interface LabelOverride {
68
- tier: TierLevel;
69
- updatedAt: string;
70
- }
71
- /** id -> operator label. Kept beside the append-only dataset so relabelling never rewrites history. */
72
- export type LabelOverrideMap = Record<string, LabelOverride>;
73
- export declare function isTier(value: unknown): value is TierLevel;
74
- export declare function num(value: unknown, fallback?: number): number;
75
- export declare function str(value: unknown, fallback?: string): string;
76
- /**
77
- * The label a record carries when no operator override is in place: the tier
78
- * that actually SERVED the request, never the tier the router asked for.
79
- *
80
- * Single source of truth for that rule — the collector writes it at capture
81
- * time and the dataset re-derives it whenever an override is removed, so
82
- * "clear label" always lands back on the observed value rather than on a
83
- * stale human label.
84
- */
85
- export declare function deriveDefaultLabel(params: {
86
- targetTier: TierLevel | string;
87
- tierUsed: TierLevel | string;
88
- fallbackOccurred: boolean;
89
- }): FlywheelLabel;
90
- /**
91
- * Bench/test traffic detector.
92
- *
93
- * The flywheel is opt-in (default off) and forced off under `bun test`
94
- * (NODE_ENV=test), but if collection is ever on, `bun test` would append its
95
- * fixtures to the production dataset. These three signals are the
96
- * unmistakable fingerprints the test-suite leaves behind (see
97
- * backend/tests/flywheel.test.ts and the tier-pool tests); they are checked
98
- * narrowly so real traffic is never swept up with them.
99
- */
100
- export declare function detectSynthetic(id: string, modelUsed: string, fallbackReason?: string): boolean;
101
- /**
102
- * Parse one dataset line into the current shape. Never throws on malformed
103
- * input: a line that cannot be parsed is a logging concern, not a reason to
104
- * break the console. There is no v1 reader (0.0.1 — no dataset outside this
105
- * install ever existed): a pre-v2 line returns null and the caller counts it
106
- * as malformed.
107
- */
108
- export declare function migrateRecord(raw: any): FlywheelRecord | null;