harness-reflex 0.0.0-stage → 0.3.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 (164) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/README.md +266 -2
  3. package/USER_GUIDE.md +639 -0
  4. package/dist/adapters/agy.d.ts +8 -0
  5. package/dist/adapters/agy.js +80 -0
  6. package/dist/adapters/agy.js.map +1 -0
  7. package/dist/adapters/claude.d.ts +13 -0
  8. package/dist/adapters/claude.js +46 -0
  9. package/dist/adapters/claude.js.map +1 -0
  10. package/dist/adapters/codex.d.ts +139 -0
  11. package/dist/adapters/codex.js +368 -0
  12. package/dist/adapters/codex.js.map +1 -0
  13. package/dist/backend/defaults.d.ts +31 -0
  14. package/dist/backend/defaults.js +32 -0
  15. package/dist/backend/defaults.js.map +1 -0
  16. package/dist/backend/factory.d.ts +11 -0
  17. package/dist/backend/factory.js +40 -0
  18. package/dist/backend/factory.js.map +1 -0
  19. package/dist/backend/jev.d.ts +524 -0
  20. package/dist/backend/jev.js +1486 -0
  21. package/dist/backend/jev.js.map +1 -0
  22. package/dist/backend/mock.d.ts +26 -0
  23. package/dist/backend/mock.js +320 -0
  24. package/dist/backend/mock.js.map +1 -0
  25. package/dist/backend/route-prompt.d.ts +37 -0
  26. package/dist/backend/route-prompt.js +42 -0
  27. package/dist/backend/route-prompt.js.map +1 -0
  28. package/dist/backend/simple-jev.d.ts +35 -0
  29. package/dist/backend/simple-jev.js +273 -0
  30. package/dist/backend/simple-jev.js.map +1 -0
  31. package/dist/backend/types.d.ts +270 -0
  32. package/dist/backend/types.js +5 -0
  33. package/dist/backend/types.js.map +1 -0
  34. package/dist/cli/index.d.ts +2 -0
  35. package/dist/cli/index.js +278 -0
  36. package/dist/cli/index.js.map +1 -0
  37. package/dist/core/calibrate.d.ts +56 -0
  38. package/dist/core/calibrate.js +144 -0
  39. package/dist/core/calibrate.js.map +1 -0
  40. package/dist/core/closing.d.ts +90 -0
  41. package/dist/core/closing.js +111 -0
  42. package/dist/core/closing.js.map +1 -0
  43. package/dist/core/evidence.d.ts +119 -0
  44. package/dist/core/evidence.js +209 -0
  45. package/dist/core/evidence.js.map +1 -0
  46. package/dist/core/gate.d.ts +25 -0
  47. package/dist/core/gate.js +114 -0
  48. package/dist/core/gate.js.map +1 -0
  49. package/dist/core/judge.d.ts +221 -0
  50. package/dist/core/judge.js +251 -0
  51. package/dist/core/judge.js.map +1 -0
  52. package/dist/core/ledger.d.ts +67 -0
  53. package/dist/core/ledger.js +173 -0
  54. package/dist/core/ledger.js.map +1 -0
  55. package/dist/core/orchestrate-closing.d.ts +237 -0
  56. package/dist/core/orchestrate-closing.js +250 -0
  57. package/dist/core/orchestrate-closing.js.map +1 -0
  58. package/dist/core/orchestrate-correction.d.ts +209 -0
  59. package/dist/core/orchestrate-correction.js +141 -0
  60. package/dist/core/orchestrate-correction.js.map +1 -0
  61. package/dist/core/orchestrate-host.d.ts +225 -0
  62. package/dist/core/orchestrate-host.js +80 -0
  63. package/dist/core/orchestrate-host.js.map +1 -0
  64. package/dist/core/orchestrate-stagnation.d.ts +259 -0
  65. package/dist/core/orchestrate-stagnation.js +270 -0
  66. package/dist/core/orchestrate-stagnation.js.map +1 -0
  67. package/dist/core/orchestrate.d.ts +357 -0
  68. package/dist/core/orchestrate.js +418 -0
  69. package/dist/core/orchestrate.js.map +1 -0
  70. package/dist/core/policy.d.ts +122 -0
  71. package/dist/core/policy.js +102 -0
  72. package/dist/core/policy.js.map +1 -0
  73. package/dist/core/prune-plan.d.ts +141 -0
  74. package/dist/core/prune-plan.js +390 -0
  75. package/dist/core/prune-plan.js.map +1 -0
  76. package/dist/core/prune.d.ts +30 -0
  77. package/dist/core/prune.js +73 -0
  78. package/dist/core/prune.js.map +1 -0
  79. package/dist/core/route.d.ts +35 -0
  80. package/dist/core/route.js +39 -0
  81. package/dist/core/route.js.map +1 -0
  82. package/dist/core/score.d.ts +40 -0
  83. package/dist/core/score.js +49 -0
  84. package/dist/core/score.js.map +1 -0
  85. package/dist/core/screen.d.ts +22 -0
  86. package/dist/core/screen.js +117 -0
  87. package/dist/core/screen.js.map +1 -0
  88. package/dist/core/stagnation.d.ts +23 -0
  89. package/dist/core/stagnation.js +93 -0
  90. package/dist/core/stagnation.js.map +1 -0
  91. package/dist/core/text.d.ts +36 -0
  92. package/dist/core/text.js +66 -0
  93. package/dist/core/text.js.map +1 -0
  94. package/dist/hook/cli.d.ts +9 -0
  95. package/dist/hook/cli.js +52 -0
  96. package/dist/hook/cli.js.map +1 -0
  97. package/dist/hook/contract.d.ts +125 -0
  98. package/dist/hook/contract.js +159 -0
  99. package/dist/hook/contract.js.map +1 -0
  100. package/dist/hook/decision.d.ts +97 -0
  101. package/dist/hook/decision.js +955 -0
  102. package/dist/hook/decision.js.map +1 -0
  103. package/dist/hook/memory-store.d.ts +81 -0
  104. package/dist/hook/memory-store.js +157 -0
  105. package/dist/hook/memory-store.js.map +1 -0
  106. package/dist/hook/payload.d.ts +55 -0
  107. package/dist/hook/payload.js +129 -0
  108. package/dist/hook/payload.js.map +1 -0
  109. package/dist/hook/run.d.ts +48 -0
  110. package/dist/hook/run.js +218 -0
  111. package/dist/hook/run.js.map +1 -0
  112. package/dist/hook/store-port.d.ts +72 -0
  113. package/dist/hook/store-port.js +2 -0
  114. package/dist/hook/store-port.js.map +1 -0
  115. package/dist/index.d.ts +18 -0
  116. package/dist/index.js +19 -0
  117. package/dist/index.js.map +1 -0
  118. package/dist/mcp/server.d.ts +12 -0
  119. package/dist/mcp/server.js +368 -0
  120. package/dist/mcp/server.js.map +1 -0
  121. package/dist/ports/audit.d.ts +18 -0
  122. package/dist/ports/audit.js +11 -0
  123. package/dist/ports/audit.js.map +1 -0
  124. package/dist/ports/clock.d.ts +14 -0
  125. package/dist/ports/clock.js +11 -0
  126. package/dist/ports/clock.js.map +1 -0
  127. package/dist/ports/decision.d.ts +75 -0
  128. package/dist/ports/decision.js +2 -0
  129. package/dist/ports/decision.js.map +1 -0
  130. package/dist/ports/index.d.ts +14 -0
  131. package/dist/ports/index.js +2 -0
  132. package/dist/ports/index.js.map +1 -0
  133. package/dist/ports/log.d.ts +22 -0
  134. package/dist/ports/log.js +12 -0
  135. package/dist/ports/log.js.map +1 -0
  136. package/dist/ports/state.d.ts +46 -0
  137. package/dist/ports/state.js +13 -0
  138. package/dist/ports/state.js.map +1 -0
  139. package/dist/state/clock.d.ts +40 -0
  140. package/dist/state/clock.js +43 -0
  141. package/dist/state/clock.js.map +1 -0
  142. package/dist/state/file-store.d.ts +340 -0
  143. package/dist/state/file-store.js +849 -0
  144. package/dist/state/file-store.js.map +1 -0
  145. package/dist/state/paths.d.ts +41 -0
  146. package/dist/state/paths.js +73 -0
  147. package/dist/state/paths.js.map +1 -0
  148. package/docs/USER_GUIDE.en.md +721 -0
  149. package/docs/claude-code.md +281 -0
  150. package/docs/design/v0.2.0-harness-plugins.md +381 -0
  151. package/docs/design/v0.3.0-orchestration-unification.md +580 -0
  152. package/docs/dsh-plugin.md +578 -0
  153. package/docs/reflex-ui-regression-2026-10-20.md +34 -0
  154. package/docs/release-checklist-v0.1.0.md +315 -0
  155. package/docs/release-handbook-porting-notes.md +106 -0
  156. package/docs/release-handbook.md +393 -0
  157. package/docs/release-notes-v0.1.0.md +63 -0
  158. package/docs/release-notes-v0.3.0.md +152 -0
  159. package/docs/research/claude-code-harness.md +607 -0
  160. package/docs/research/pi-harness.md +621 -0
  161. package/experiments/data/calibration_sample.json +14 -0
  162. package/experiments/index.ts +29 -0
  163. package/experiments/runner.ts +156 -0
  164. package/package.json +82 -4
@@ -0,0 +1,278 @@
1
+ #!/usr/bin/env node
2
+ import * as path from 'path';
3
+ import * as fs from 'fs';
4
+ import { fileURLToPath } from 'url';
5
+ import { ReflexMcpServer } from '../mcp/server.js';
6
+ import { ClaudeAdapter } from '../adapters/claude.js';
7
+ import { CodexAdapter } from '../adapters/codex.js';
8
+ import { AgyAdapter } from '../adapters/agy.js';
9
+ import { createDecisionBackend } from '../backend/factory.js';
10
+ import { ReflexGateService } from '../core/gate.js';
11
+ import { ToolResultPruner } from '../core/prune.js';
12
+ import { DecisionLedger } from '../core/ledger.js';
13
+ import { ReflexScreenService } from '../core/screen.js';
14
+ import { fitIsotonicRegression, calculateECE } from '../core/calibrate.js';
15
+ import { runHookCli } from '../hook/cli.js';
16
+ const __filename = fileURLToPath(import.meta.url);
17
+ const __dirname = path.dirname(__filename);
18
+ async function main() {
19
+ const args = process.argv.slice(2);
20
+ const command = args[0] || 'help';
21
+ switch (command) {
22
+ case 'mcp': {
23
+ const server = new ReflexMcpServer();
24
+ server.start();
25
+ break;
26
+ }
27
+ case 'setup': {
28
+ const target = args[1] || 'all';
29
+ const workspaceDir = process.cwd();
30
+ // Locate the CLI entrypoint
31
+ const entrypoint = path.resolve(__dirname, 'index.js');
32
+ console.log(`[Harness Reflex] Setting up plugin for target: ${target}`);
33
+ console.log(`[Harness Reflex] Workspace: ${workspaceDir}`);
34
+ console.log(`[Harness Reflex] Binary: ${entrypoint}\n`);
35
+ if (target === 'claude' || target === 'all') {
36
+ const { configPath } = ClaudeAdapter.configureMcp(workspaceDir, entrypoint);
37
+ console.log(` ✓ Claude Code MCP config written to ${configPath}`);
38
+ console.log(` (Added 'harness-reflex' server to .mcp.json)`);
39
+ }
40
+ if (target === 'codex' || target === 'all') {
41
+ const { configPath } = CodexAdapter.configureCodex(workspaceDir, entrypoint);
42
+ console.log(` ✓ Codex CLI MCP config written to ${configPath}`);
43
+ }
44
+ if (target === 'agy' || target === 'all') {
45
+ const { pluginDir } = AgyAdapter.configureAgy(workspaceDir, entrypoint);
46
+ console.log(` ✓ Antigravity (AGY) plugin written to ${pluginDir}`);
47
+ console.log(` (Includes plugin.json, mcp_config.json, hooks.json, rules/AGENTS.md)`);
48
+ }
49
+ console.log('\nSetup complete! You can now start or reload Claude Code, Codex, or AGY.');
50
+ break;
51
+ }
52
+ case 'gate': {
53
+ // CLI gate runner: harness-reflex gate --statement "Tests pass" --evidence "..."
54
+ let statement = '';
55
+ let evidence = '';
56
+ for (let i = 1; i < args.length; i++) {
57
+ if (args[i] === '--statement' || args[i] === '-s')
58
+ statement = args[++i];
59
+ if (args[i] === '--evidence' || args[i] === '-e')
60
+ evidence = args[++i];
61
+ }
62
+ if (!statement) {
63
+ console.error('Error: --statement is required.');
64
+ process.exit(1);
65
+ }
66
+ if (!evidence && !process.stdin.isTTY) {
67
+ // Read evidence from stdin
68
+ evidence = fs.readFileSync(0, 'utf8');
69
+ }
70
+ const backend = createDecisionBackend();
71
+ const gate = new ReflexGateService(backend);
72
+ const res = await gate.verify([{ statement }], evidence);
73
+ console.log(JSON.stringify(res, null, 2));
74
+ process.exit(res.passed ? 0 : 1);
75
+ }
76
+ case 'prune': {
77
+ let intent = 'extract error and results';
78
+ let raw = '';
79
+ for (let i = 1; i < args.length; i++) {
80
+ if (args[i] === '--intent')
81
+ intent = args[++i];
82
+ }
83
+ if (!process.stdin.isTTY) {
84
+ raw = fs.readFileSync(0, 'utf8');
85
+ }
86
+ const backend = createDecisionBackend();
87
+ const pruner = new ToolResultPruner(backend);
88
+ const res = await pruner.prune(raw, { intent });
89
+ console.log(res.processedOutput);
90
+ break;
91
+ }
92
+ case 'ledger': {
93
+ const ledger = DecisionLedger.getInstance();
94
+ const summary = ledger.getSummary();
95
+ console.log('=== Harness Reflex Decision Ledger ===');
96
+ console.log(`Total Decisions: ${summary.totalCalls}`);
97
+ console.log(`Calls by Type: ${JSON.stringify(summary.callsByType)}`);
98
+ console.log(`Tokens Saved: ${summary.totalTokensSaved.toLocaleString()}`);
99
+ console.log(`Est. Cost Saved: $${summary.estimatedCostSavedUsd.toFixed(4)} USD`);
100
+ console.log(`Avg Latency: ${summary.avgLatencyMs} ms`);
101
+ console.log(`Gate Pass/Fail: ${summary.gatePassedCount} passed / ${summary.gateFailedCount} failed`);
102
+ console.log(`Stagnation Alarms: ${summary.stagnationAlerts}`);
103
+ break;
104
+ }
105
+ case 'screen': {
106
+ let content = '';
107
+ let strict = false;
108
+ for (let i = 1; i < args.length; i++) {
109
+ if (args[i] === '--content' || args[i] === '-c')
110
+ content = args[++i];
111
+ if (args[i] === '--strict')
112
+ strict = true;
113
+ }
114
+ if (!content && !process.stdin.isTTY) {
115
+ content = fs.readFileSync(0, 'utf8');
116
+ }
117
+ const backend = createDecisionBackend();
118
+ const screener = new ReflexScreenService(backend);
119
+ const res = await screener.screen({ content, strict });
120
+ console.log(JSON.stringify(res, null, 2));
121
+ process.exit(res.isSafe ? 0 : 1);
122
+ }
123
+ case 'choice': {
124
+ let question = '';
125
+ let optionsStr = '';
126
+ let context = '';
127
+ for (let i = 1; i < args.length; i++) {
128
+ if (args[i] === '--question' || args[i] === '-q')
129
+ question = args[++i];
130
+ if (args[i] === '--options' || args[i] === '-o')
131
+ optionsStr = args[++i];
132
+ if (args[i] === '--context')
133
+ context = args[++i];
134
+ }
135
+ if (!question || !optionsStr) {
136
+ console.error('Usage: harness-reflex choice --question "..." --options "opt1,opt2" [--context "..."]');
137
+ process.exit(1);
138
+ }
139
+ const options = optionsStr.split(',').map((o) => o.trim());
140
+ const backend = createDecisionBackend();
141
+ const res = await backend.choice({ question, options, context });
142
+ console.log(JSON.stringify(res, null, 2));
143
+ break;
144
+ }
145
+ case 'score': {
146
+ let statement = '';
147
+ let criteria = 'Rate alignment on a scale from 0.0 to 1.0';
148
+ for (let i = 1; i < args.length; i++) {
149
+ if (args[i] === '--statement' || args[i] === '-s')
150
+ statement = args[++i];
151
+ if (args[i] === '--criteria' || args[i] === '-c')
152
+ criteria = args[++i];
153
+ }
154
+ if (!statement && !process.stdin.isTTY) {
155
+ statement = fs.readFileSync(0, 'utf8');
156
+ }
157
+ const backend = createDecisionBackend();
158
+ const evalRes = await backend.choice({
159
+ question: `Evaluate statement against criteria: "${criteria}". Is alignment high, moderate, or low?`,
160
+ options: ['High alignment (~0.9)', 'Moderate alignment (~0.5)', 'Poor alignment (~0.1)'],
161
+ context: statement
162
+ });
163
+ const pHigh = evalRes.options.find((o) => o.label.includes('High'))?.probability || 0;
164
+ const pMed = evalRes.options.find((o) => o.label.includes('Moderate'))?.probability || 0;
165
+ const pLow = evalRes.options.find((o) => o.label.includes('Poor'))?.probability || 0;
166
+ const score = Number((pHigh * 0.9 + pMed * 0.5 + pLow * 0.1).toFixed(3));
167
+ console.log(JSON.stringify({ statement, score, distribution: { pHigh, pMed, pLow } }, null, 2));
168
+ break;
169
+ }
170
+ case 'calibrate': {
171
+ let datasetPath = '';
172
+ let outputPath = path.join(process.cwd(), '.reflex', 'calibration.json');
173
+ let targetModel = process.env.SYSTEM_ONE_MODEL || 'default-model';
174
+ for (let i = 1; i < args.length; i++) {
175
+ if (args[i] === '--dataset' || args[i] === '-d')
176
+ datasetPath = args[++i];
177
+ if (args[i] === '--output' || args[i] === '-o')
178
+ outputPath = args[++i];
179
+ if (args[i] === '--model' || args[i] === '-m')
180
+ targetModel = args[++i];
181
+ }
182
+ if (!datasetPath) {
183
+ console.error('Error: --dataset <file.json> is required for calibration.');
184
+ process.exit(1);
185
+ }
186
+ console.log(`[Calibration] Loading samples from ${datasetPath}...`);
187
+ const rawData = fs.readFileSync(datasetPath, 'utf8');
188
+ const samples = JSON.parse(rawData);
189
+ // Samples format: Array<{ rawProbability: number, groundTruth: 0 | 1 }>
190
+ // If samples contain assertions/evidence, run backend.gate() first to obtain raw probabilities
191
+ const fittedSamples = [];
192
+ const backend = createDecisionBackend();
193
+ for (const s of samples) {
194
+ if (typeof s.rawProbability === 'number') {
195
+ fittedSamples.push({ rawProbability: s.rawProbability, groundTruth: s.groundTruth });
196
+ }
197
+ else if (s.assertion && s.evidence) {
198
+ const res = await backend.gate({
199
+ assertions: [{ statement: s.assertion }],
200
+ evidence: s.evidence
201
+ });
202
+ const rawProb = res.results[0]?.confidence ?? 0.5;
203
+ fittedSamples.push({ rawProbability: rawProb, groundTruth: s.groundTruth });
204
+ }
205
+ }
206
+ console.log(`[Calibration] Fitting Isotonic Regression on ${fittedSamples.length} samples...`);
207
+ const bins = fitIsotonicRegression(fittedSamples);
208
+ const eceBefore = calculateECE(fittedSamples.map((s) => ({ probability: s.rawProbability, groundTruth: s.groundTruth })));
209
+ // Calibrate samples to compute ECE after
210
+ const calibratedSamples = fittedSamples.map((s) => {
211
+ let cal = s.rawProbability;
212
+ for (const bin of bins) {
213
+ if (s.rawProbability >= bin.rawMin && s.rawProbability <= bin.rawMax) {
214
+ cal = bin.calibrated;
215
+ break;
216
+ }
217
+ }
218
+ return { probability: cal, groundTruth: s.groundTruth };
219
+ });
220
+ const eceAfter = calculateECE(calibratedSamples);
221
+ const curve = {
222
+ targetModel,
223
+ taskType: 'gate_verification',
224
+ method: 'isotonic',
225
+ createdAt: new Date().toISOString(),
226
+ bins,
227
+ eceBefore,
228
+ eceAfter
229
+ };
230
+ const outDir = path.dirname(outputPath);
231
+ if (!fs.existsSync(outDir)) {
232
+ fs.mkdirSync(outDir, { recursive: true });
233
+ }
234
+ fs.writeFileSync(outputPath, JSON.stringify(curve, null, 2), 'utf8');
235
+ console.log(`✓ Calibration curve saved to ${outputPath}`);
236
+ console.log(` Target Model: ${targetModel}`);
237
+ console.log(` ECE Before: ${eceBefore} -> ECE After: ${eceAfter} (${(((eceBefore - eceAfter) / (eceBefore || 1)) * 100).toFixed(1)}% error reduction)`);
238
+ console.log(` Fitted Bins: ${bins.length}`);
239
+ break;
240
+ }
241
+ case 'hook': {
242
+ // Command-hook dispatcher: reads one host event on stdin and writes one
243
+ // protocol JSON object on stdout. See docs/design/v0.2.0-harness-plugins.md §2.5.
244
+ await runHookCli(args.slice(1));
245
+ break;
246
+ }
247
+ case 'help':
248
+ default: {
249
+ console.log(`
250
+ Harness Reflex - System One Decision Runtime for Codex, Claude Code & AGY
251
+
252
+ Usage:
253
+ harness-reflex <command> [options]
254
+
255
+ Commands:
256
+ mcp Start Model Context Protocol (MCP) server over stdio
257
+ setup [target] Configure target harness (claude | codex | agy | all)
258
+ gate [options] Evaluate assertions against evidence (fail-closed)
259
+ prune [options] Prune lengthy tool outputs on stdin
260
+ hook <event> Command-hook entry (pretooluse|posttooluse|postfailure|stop|substop|sessionstart|sessionend)
261
+ ledger Show decision ledger summary and token savings
262
+ help Display this help message
263
+
264
+ Environment Variables:
265
+ SYSTEM_ONE_BACKEND System One provider: 'jev' | 'vllm' | 'simple-jev' | 'mock' (default: mock)
266
+ SYSTEM_ONE_API_KEY API key for the chosen System One provider (or JEV_API_KEY)
267
+ SYSTEM_ONE_BASE_URL Base URL for System One provider (or JEV_BASE_URL, VLLM_BASE_URL)
268
+ SYSTEM_ONE_MODEL Model identifier (e.g. 'jev-1.13.0', 'Qwen/Qwen2.5-7B-Instruct')
269
+ `);
270
+ break;
271
+ }
272
+ }
273
+ }
274
+ main().catch((err) => {
275
+ console.error('[Harness Reflex Error]', err);
276
+ process.exit(1);
277
+ });
278
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/cli/index.ts"],"names":[],"mappings":";AACA,OAAO,KAAK,IAAI,MAAM,MAAM,CAAC;AAC7B,OAAO,KAAK,EAAE,MAAM,IAAI,CAAC;AACzB,OAAO,EAAE,aAAa,EAAE,MAAM,KAAK,CAAC;AACpC,OAAO,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAC;AACnD,OAAO,EAAE,aAAa,EAAE,MAAM,uBAAuB,CAAC;AACtD,OAAO,EAAE,YAAY,EAAE,MAAM,sBAAsB,CAAC;AACpD,OAAO,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAChD,OAAO,EAAE,qBAAqB,EAAE,MAAM,uBAAuB,CAAC;AAC9D,OAAO,EAAE,iBAAiB,EAAE,MAAM,iBAAiB,CAAC;AACpD,OAAO,EAAE,gBAAgB,EAAE,MAAM,kBAAkB,CAAC;AACpD,OAAO,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAC;AACnD,OAAO,EAAE,mBAAmB,EAAE,MAAM,mBAAmB,CAAC;AACxD,OAAO,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AS,CAAC,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC,EAAE,MAAM,CAAC,CAAC;YAErE,OAAO,CAAC,GAAG,CAAC,gCAAgC,UAAU,EAAE,CAAC,CAAC;YAC1D,OAAO,CAAC,GAAG,CAAC,mBAAmB,WAAW,EAAE,CAAC,CAAC;YAC9C,OAAO,CAAC,GAAG,CAAC,mBAAmB,SAAS,kBAAkB,QAAQ,KAAK,CAAC,CAAC,CAAC,SAAS,GAAG,QAAQ,CAAC,GAAG,CAAC,SAAS,IAAI,CAAC,CAAC,CAAC,GAAG,GAAG,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,oBAAoB,CAAC,CAAC;YAC3J,OAAO,CAAC,GAAG,CAAC,mBAAmB,IAAI,CAAC,MAAM,EAAE,CAAC,CAAC;YAC9C,MAAM;QACR,CAAC;QAED,KAAK,MAAM,CAAC,CAAC,CAAC;YACZ,wEAAwE;YACxE,kFAAkF;YAClF,MAAM,UAAU,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC;YAChC,MAAM;QACR,CAAC;QAED,KAAK,MAAM,CAAC;QACZ,OAAO,CAAC,CAAC,CAAC;YACR,OAAO,CAAC,GAAG,CAAC;;;;;;;;;;;;;;;;;;;;CAoBjB,CAAC,CAAC;YACG,MAAM;QACR,CAAC;IACH,CAAC;AACH,CAAC;AAED,IAAI,EAAE,CAAC,KAAK,CAAC,CAAC,GAAG,EAAE,EAAE;IACnB,OAAO,CAAC,KAAK,CAAC,wBAAwB,EAAE,GAAG,CAAC,CAAC;IAC7C,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AAClB,CAAC,CAAC,CAAC","sourcesContent":["#!/usr/bin/env node\nimport * as path from 'path';\nimport * as fs from 'fs';\nimport { fileURLToPath } from 'url';\nimport { ReflexMcpServer } from '../mcp/server.js';\nimport { ClaudeAdapter } from '../adapters/claude.js';\nimport { CodexAdapter } from '../adapters/codex.js';\nimport { AgyAdapter } from '../adapters/agy.js';\nimport { createDecisionBackend } from '../backend/factory.js';\nimport { ReflexGateService } from '../core/gate.js';\nimport { ToolResultPruner } from '../core/prune.js';\nimport { DecisionLedger } from '../core/ledger.js';\nimport { ReflexScreenService } from '../core/screen.js';\nimport { fitIsotonicRegression, calculateECE, CalibrationCurve, Calibrator } from '../core/calibrate.js';\nimport { runHookCli } from '../hook/cli.js';\n\nconst __filename = fileURLToPath(import.meta.url);\nconst __dirname = path.dirname(__filename);\n\nasync function main() {\n const args = process.argv.slice(2);\n const command = args[0] || 'help';\n\n switch (command) {\n case 'mcp': {\n const server = new ReflexMcpServer();\n server.start();\n break;\n }\n\n case 'setup': {\n const target = args[1] || 'all';\n const workspaceDir = process.cwd();\n // Locate the CLI entrypoint\n const entrypoint = path.resolve(__dirname, 'index.js');\n\n console.log(`[Harness Reflex] Setting up plugin for target: ${target}`);\n console.log(`[Harness Reflex] Workspace: ${workspaceDir}`);\n console.log(`[Harness Reflex] Binary: ${entrypoint}\\n`);\n\n if (target === 'claude' || target === 'all') {\n const { configPath } = ClaudeAdapter.configureMcp(workspaceDir, entrypoint);\n console.log(` ✓ Claude Code MCP config written to ${configPath}`);\n console.log(` (Added 'harness-reflex' server to .mcp.json)`);\n }\n\n if (target === 'codex' || target === 'all') {\n const { configPath } = CodexAdapter.configureCodex(workspaceDir, entrypoint);\n console.log(` ✓ Codex CLI MCP config written to ${configPath}`);\n }\n\n if (target === 'agy' || target === 'all') {\n const { pluginDir } = AgyAdapter.configureAgy(workspaceDir, entrypoint);\n console.log(` ✓ Antigravity (AGY) plugin written to ${pluginDir}`);\n console.log(` (Includes plugin.json, mcp_config.json, hooks.json, rules/AGENTS.md)`);\n }\n\n console.log('\\nSetup complete! You can now start or reload Claude Code, Codex, or AGY.');\n break;\n }\n\n case 'gate': {\n // CLI gate runner: harness-reflex gate --statement \"Tests pass\" --evidence \"...\"\n let statement = '';\n let evidence = '';\n for (let i = 1; i < args.length; i++) {\n if (args[i] === '--statement' || args[i] === '-s') statement = args[++i];\n if (args[i] === '--evidence' || args[i] === '-e') evidence = args[++i];\n }\n\n if (!statement) {\n console.error('Error: --statement is required.');\n process.exit(1);\n }\n\n if (!evidence && !process.stdin.isTTY) {\n // Read evidence from stdin\n evidence = fs.readFileSync(0, 'utf8');\n }\n\n const backend = createDecisionBackend();\n const gate = new ReflexGateService(backend);\n const res = await gate.verify([{ statement }], evidence);\n\n console.log(JSON.stringify(res, null, 2));\n process.exit(res.passed ? 0 : 1);\n }\n\n case 'prune': {\n let intent = 'extract error and results';\n let raw = '';\n for (let i = 1; i < args.length; i++) {\n if (args[i] === '--intent') intent = args[++i];\n }\n\n if (!process.stdin.isTTY) {\n raw = fs.readFileSync(0, 'utf8');\n }\n\n const backend = createDecisionBackend();\n const pruner = new ToolResultPruner(backend);\n const res = await pruner.prune(raw, { intent });\n\n console.log(res.processedOutput);\n break;\n }\n\n case 'ledger': {\n const ledger = DecisionLedger.getInstance();\n const summary = ledger.getSummary();\n console.log('=== Harness Reflex Decision Ledger ===');\n console.log(`Total Decisions: ${summary.totalCalls}`);\n console.log(`Calls by Type: ${JSON.stringify(summary.callsByType)}`);\n console.log(`Tokens Saved: ${summary.totalTokensSaved.toLocaleString()}`);\n console.log(`Est. Cost Saved: $${summary.estimatedCostSavedUsd.toFixed(4)} USD`);\n console.log(`Avg Latency: ${summary.avgLatencyMs} ms`);\n console.log(`Gate Pass/Fail: ${summary.gatePassedCount} passed / ${summary.gateFailedCount} failed`);\n console.log(`Stagnation Alarms: ${summary.stagnationAlerts}`);\n break;\n }\n\n case 'screen': {\n let content = '';\n let strict = false;\n for (let i = 1; i < args.length; i++) {\n if (args[i] === '--content' || args[i] === '-c') content = args[++i];\n if (args[i] === '--strict') strict = true;\n }\n if (!content && !process.stdin.isTTY) {\n content = fs.readFileSync(0, 'utf8');\n }\n\n const backend = createDecisionBackend();\n const screener = new ReflexScreenService(backend);\n const res = await screener.screen({ content, strict });\n console.log(JSON.stringify(res, null, 2));\n process.exit(res.isSafe ? 0 : 1);\n }\n\n case 'choice': {\n let question = '';\n let optionsStr = '';\n let context = '';\n for (let i = 1; i < args.length; i++) {\n if (args[i] === '--question' || args[i] === '-q') question = args[++i];\n if (args[i] === '--options' || args[i] === '-o') optionsStr = args[++i];\n if (args[i] === '--context') context = args[++i];\n }\n if (!question || !optionsStr) {\n console.error('Usage: harness-reflex choice --question \"...\" --options \"opt1,opt2\" [--context \"...\"]');\n process.exit(1);\n }\n const options = optionsStr.split(',').map((o) => o.trim());\n const backend = createDecisionBackend();\n const res = await backend.choice({ question, options, context });\n console.log(JSON.stringify(res, null, 2));\n break;\n }\n\n case 'score': {\n let statement = '';\n let criteria = 'Rate alignment on a scale from 0.0 to 1.0';\n for (let i = 1; i < args.length; i++) {\n if (args[i] === '--statement' || args[i] === '-s') statement = args[++i];\n if (args[i] === '--criteria' || args[i] === '-c') criteria = args[++i];\n }\n if (!statement && !process.stdin.isTTY) {\n statement = fs.readFileSync(0, 'utf8');\n }\n const backend = createDecisionBackend();\n const evalRes = await backend.choice({\n question: `Evaluate statement against criteria: \"${criteria}\". Is alignment high, moderate, or low?`,\n options: ['High alignment (~0.9)', 'Moderate alignment (~0.5)', 'Poor alignment (~0.1)'],\n context: statement\n });\n const pHigh = evalRes.options.find((o) => o.label.includes('High'))?.probability || 0;\n const pMed = evalRes.options.find((o) => o.label.includes('Moderate'))?.probability || 0;\n const pLow = evalRes.options.find((o) => o.label.includes('Poor'))?.probability || 0;\n const score = Number((pHigh * 0.9 + pMed * 0.5 + pLow * 0.1).toFixed(3));\n console.log(JSON.stringify({ statement, score, distribution: { pHigh, pMed, pLow } }, null, 2));\n break;\n }\n\n case 'calibrate': {\n let datasetPath = '';\n let outputPath = path.join(process.cwd(), '.reflex', 'calibration.json');\n let targetModel = process.env.SYSTEM_ONE_MODEL || 'default-model';\n for (let i = 1; i < args.length; i++) {\n if (args[i] === '--dataset' || args[i] === '-d') datasetPath = args[++i];\n if (args[i] === '--output' || args[i] === '-o') outputPath = args[++i];\n if (args[i] === '--model' || args[i] === '-m') targetModel = args[++i];\n }\n\n if (!datasetPath) {\n console.error('Error: --dataset <file.json> is required for calibration.');\n process.exit(1);\n }\n\n console.log(`[Calibration] Loading samples from ${datasetPath}...`);\n const rawData = fs.readFileSync(datasetPath, 'utf8');\n const samples = JSON.parse(rawData);\n\n // Samples format: Array<{ rawProbability: number, groundTruth: 0 | 1 }>\n // If samples contain assertions/evidence, run backend.gate() first to obtain raw probabilities\n const fittedSamples: Array<{ rawProbability: number; groundTruth: 0 | 1 }> = [];\n const backend = createDecisionBackend();\n\n for (const s of samples) {\n if (typeof s.rawProbability === 'number') {\n fittedSamples.push({ rawProbability: s.rawProbability, groundTruth: s.groundTruth });\n } else if (s.assertion && s.evidence) {\n const res = await backend.gate({\n assertions: [{ statement: s.assertion }],\n evidence: s.evidence\n });\n const rawProb = res.results[0]?.confidence ?? 0.5;\n fittedSamples.push({ rawProbability: rawProb, groundTruth: s.groundTruth });\n }\n }\n\n console.log(`[Calibration] Fitting Isotonic Regression on ${fittedSamples.length} samples...`);\n const bins = fitIsotonicRegression(fittedSamples);\n const eceBefore = calculateECE(fittedSamples.map((s) => ({ probability: s.rawProbability, groundTruth: s.groundTruth })));\n\n // Calibrate samples to compute ECE after\n const calibratedSamples = fittedSamples.map((s) => {\n let cal = s.rawProbability;\n for (const bin of bins) {\n if (s.rawProbability >= bin.rawMin && s.rawProbability <= bin.rawMax) {\n cal = bin.calibrated;\n break;\n }\n }\n return { probability: cal, groundTruth: s.groundTruth };\n });\n const eceAfter = calculateECE(calibratedSamples);\n\n const curve: CalibrationCurve = {\n targetModel,\n taskType: 'gate_verification',\n method: 'isotonic',\n createdAt: new Date().toISOString(),\n bins,\n eceBefore,\n eceAfter\n };\n\n const outDir = path.dirname(outputPath);\n if (!fs.existsSync(outDir)) {\n fs.mkdirSync(outDir, { recursive: true });\n }\n fs.writeFileSync(outputPath, JSON.stringify(curve, null, 2), 'utf8');\n\n console.log(`✓ Calibration curve saved to ${outputPath}`);\n console.log(` Target Model: ${targetModel}`);\n console.log(` ECE Before: ${eceBefore} -> ECE After: ${eceAfter} (${(((eceBefore - eceAfter) / (eceBefore || 1)) * 100).toFixed(1)}% error reduction)`);\n console.log(` Fitted Bins: ${bins.length}`);\n break;\n }\n\n case 'hook': {\n // Command-hook dispatcher: reads one host event on stdin and writes one\n // protocol JSON object on stdout. See docs/design/v0.2.0-harness-plugins.md §2.5.\n await runHookCli(args.slice(1));\n break;\n }\n\n case 'help':\n default: {\n console.log(`\nHarness Reflex - System One Decision Runtime for Codex, Claude Code & AGY\n\nUsage:\n harness-reflex <command> [options]\n\nCommands:\n mcp Start Model Context Protocol (MCP) server over stdio\n setup [target] Configure target harness (claude | codex | agy | all)\n gate [options] Evaluate assertions against evidence (fail-closed)\n prune [options] Prune lengthy tool outputs on stdin\n hook <event> Command-hook entry (pretooluse|posttooluse|postfailure|stop|substop|sessionstart|sessionend)\n ledger Show decision ledger summary and token savings\n help Display this help message\n\nEnvironment Variables:\n SYSTEM_ONE_BACKEND System One provider: 'jev' | 'vllm' | 'simple-jev' | 'mock' (default: mock)\n SYSTEM_ONE_API_KEY API key for the chosen System One provider (or JEV_API_KEY)\n SYSTEM_ONE_BASE_URL Base URL for System One provider (or JEV_BASE_URL, VLLM_BASE_URL)\n SYSTEM_ONE_MODEL Model identifier (e.g. 'jev-1.13.0', 'Qwen/Qwen2.5-7B-Instruct')\n`);\n break;\n }\n }\n}\n\nmain().catch((err) => {\n console.error('[Harness Reflex Error]', err);\n process.exit(1);\n});\n"]}
@@ -0,0 +1,56 @@
1
+ export interface CalibrationBin {
2
+ rawMin: number;
3
+ rawMax: number;
4
+ calibrated: number;
5
+ }
6
+ export interface CalibrationCurve {
7
+ targetModel: string;
8
+ taskType: string;
9
+ method: 'isotonic' | 'platt';
10
+ createdAt: string;
11
+ bins: CalibrationBin[];
12
+ plattParams?: {
13
+ a: number;
14
+ b: number;
15
+ };
16
+ eceBefore: number;
17
+ eceAfter: number;
18
+ }
19
+ export interface CalibrationSample {
20
+ id?: string;
21
+ rawProbability: number;
22
+ groundTruth: 0 | 1;
23
+ }
24
+ /**
25
+ * Isotonic Regression using the Pool Adjacent Violators Algorithm (PAVA)
26
+ * Fits a non-decreasing, non-parametric mapping from raw probabilities to calibrated probabilities.
27
+ */
28
+ export declare function fitIsotonicRegression(samples: CalibrationSample[]): CalibrationBin[];
29
+ /**
30
+ * Calculates Expected Calibration Error (ECE)
31
+ */
32
+ export declare function calculateECE(samples: Array<{
33
+ probability: number;
34
+ groundTruth: 0 | 1;
35
+ }>, numBins?: number): number;
36
+ /**
37
+ * Online Calibration Engine
38
+ * Loads pre-fitted curves and maps raw probabilities to calibrated true probabilities.
39
+ */
40
+ export declare class Calibrator {
41
+ private static instance;
42
+ private curve;
43
+ constructor(customCurvePath?: string);
44
+ static getInstance(): Calibrator;
45
+ loadFromDisk(filePath: string): boolean;
46
+ setCurve(curve: CalibrationCurve): void;
47
+ isLoaded(): boolean;
48
+ getCurve(): CalibrationCurve | null;
49
+ /**
50
+ * Calibrate a raw probability
51
+ */
52
+ calibrate(rawProb: number): {
53
+ calibrated: number;
54
+ isCalibrated: boolean;
55
+ };
56
+ }
@@ -0,0 +1,144 @@
1
+ import * as fs from 'fs';
2
+ import * as path from 'path';
3
+ /**
4
+ * Isotonic Regression using the Pool Adjacent Violators Algorithm (PAVA)
5
+ * Fits a non-decreasing, non-parametric mapping from raw probabilities to calibrated probabilities.
6
+ */
7
+ export function fitIsotonicRegression(samples) {
8
+ if (samples.length === 0)
9
+ return [];
10
+ // Sort samples ascending by rawProbability
11
+ const sorted = [...samples].sort((a, b) => a.rawProbability - b.rawProbability);
12
+ const blocks = sorted.map((s) => ({
13
+ weight: 1,
14
+ sumY: s.groundTruth,
15
+ value: s.groundTruth,
16
+ xMin: s.rawProbability,
17
+ xMax: s.rawProbability
18
+ }));
19
+ // PAVA: Merge adjacent blocks that violate monotonicity (value[i] > value[i+1])
20
+ let i = 0;
21
+ while (i < blocks.length - 1) {
22
+ if (blocks[i].value > blocks[i + 1].value) {
23
+ // Pool adjacent violators
24
+ const pooledWeight = blocks[i].weight + blocks[i + 1].weight;
25
+ const pooledSumY = blocks[i].sumY + blocks[i + 1].sumY;
26
+ const pooledValue = pooledSumY / pooledWeight;
27
+ blocks[i] = {
28
+ weight: pooledWeight,
29
+ sumY: pooledSumY,
30
+ value: pooledValue,
31
+ xMin: blocks[i].xMin,
32
+ xMax: blocks[i + 1].xMax
33
+ };
34
+ blocks.splice(i + 1, 1);
35
+ // Check backward to restore monotonicity
36
+ if (i > 0) {
37
+ i--;
38
+ }
39
+ }
40
+ else {
41
+ i++;
42
+ }
43
+ }
44
+ // Convert blocks to continuous CalibrationBins spanning 0.0 to 1.0
45
+ const bins = [];
46
+ for (let k = 0; k < blocks.length; k++) {
47
+ const prevMax = k === 0 ? 0.0 : bins[k - 1].rawMax;
48
+ const nextMin = k === blocks.length - 1 ? 1.0 : (blocks[k].xMax + blocks[k + 1].xMin) / 2;
49
+ bins.push({
50
+ rawMin: Number(prevMax.toFixed(4)),
51
+ rawMax: Number(nextMin.toFixed(4)),
52
+ calibrated: Number(Math.min(1.0, Math.max(0.0, blocks[k].value)).toFixed(4))
53
+ });
54
+ }
55
+ // Ensure last bin caps at 1.0
56
+ if (bins.length > 0) {
57
+ bins[bins.length - 1].rawMax = 1.0;
58
+ }
59
+ return bins;
60
+ }
61
+ /**
62
+ * Calculates Expected Calibration Error (ECE)
63
+ */
64
+ export function calculateECE(samples, numBins = 10) {
65
+ if (samples.length === 0)
66
+ return 0;
67
+ const binStep = 1.0 / numBins;
68
+ let totalEce = 0;
69
+ const n = samples.length;
70
+ for (let i = 0; i < numBins; i++) {
71
+ const binMin = i * binStep;
72
+ const binMax = (i + 1) * binStep;
73
+ const inBin = samples.filter((s) => s.probability >= binMin && (i === numBins - 1 ? s.probability <= binMax : s.probability < binMax));
74
+ if (inBin.length === 0)
75
+ continue;
76
+ const binAcc = inBin.reduce((acc, s) => acc + s.groundTruth, 0) / inBin.length;
77
+ const binConf = inBin.reduce((acc, s) => acc + s.probability, 0) / inBin.length;
78
+ totalEce += (inBin.length / n) * Math.abs(binAcc - binConf);
79
+ }
80
+ return Number(totalEce.toFixed(4));
81
+ }
82
+ /**
83
+ * Online Calibration Engine
84
+ * Loads pre-fitted curves and maps raw probabilities to calibrated true probabilities.
85
+ */
86
+ export class Calibrator {
87
+ static instance;
88
+ curve = null;
89
+ constructor(customCurvePath) {
90
+ const defaultPath = path.join(process.cwd(), '.reflex', 'calibration.json');
91
+ const targetPath = customCurvePath || process.env.SYSTEM_ONE_CALIBRATION_FILE || defaultPath;
92
+ this.loadFromDisk(targetPath);
93
+ }
94
+ static getInstance() {
95
+ if (!Calibrator.instance) {
96
+ Calibrator.instance = new Calibrator();
97
+ }
98
+ return Calibrator.instance;
99
+ }
100
+ loadFromDisk(filePath) {
101
+ try {
102
+ if (fs.existsSync(filePath)) {
103
+ const data = fs.readFileSync(filePath, 'utf8');
104
+ this.curve = JSON.parse(data);
105
+ return true;
106
+ }
107
+ }
108
+ catch {
109
+ // ignore
110
+ }
111
+ return false;
112
+ }
113
+ setCurve(curve) {
114
+ this.curve = curve;
115
+ }
116
+ isLoaded() {
117
+ return this.curve !== null;
118
+ }
119
+ getCurve() {
120
+ return this.curve;
121
+ }
122
+ /**
123
+ * Calibrate a raw probability
124
+ */
125
+ calibrate(rawProb) {
126
+ if (!this.curve || !this.curve.bins || this.curve.bins.length === 0) {
127
+ return { calibrated: rawProb, isCalibrated: false };
128
+ }
129
+ const clamped = Math.max(0.0, Math.min(1.0, rawProb));
130
+ // Linear interpolation or bin lookup
131
+ for (const bin of this.curve.bins) {
132
+ if (clamped >= bin.rawMin && clamped <= bin.rawMax) {
133
+ return { calibrated: bin.calibrated, isCalibrated: true };
134
+ }
135
+ }
136
+ // Fallback to nearest boundary
137
+ if (clamped < this.curve.bins[0].rawMin) {
138
+ return { calibrated: this.curve.bins[0].calibrated, isCalibrated: true };
139
+ }
140
+ const last = this.curve.bins[this.curve.bins.length - 1];
141
+ return { calibrated: last.calibrated, isCalibrated: true };
142
+ }
143
+ }
144
+ //# sourceMappingURL=calibrate.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"calibrate.js","sourceRoot":"","sources":["../../src/core/calibrate.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,IAAI,CAAC;AACzB,OAAO,KAAK,IAAI,MAAM,MAAM,CAAC;AAyB7B;;;GAGG;AACH,MAAM,UAAU,qBAAqB,CAAC,OAA4B;IAChE,IAAI,OAAO,CAAC,MAAM,KAAK,CAAC;QAAE,OAAO,EAAE,CAAC;IAEpC,2CAA2C;IAC3C,MAAM,MAAM,GAAG,CAAC,GAAG,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,cAAc,GAAG,CAAC,CAAC,cAAc,CAAC,CAAC;IAWhF,MAAM,MAAM,GAAY,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC;QACzC,MAAM,EAAE,CAAC;QACT,IAAI,EAAE,CAAC,CAAC,WAAW;QACnB,KAAK,EAAE,CAAC,CAAC,WAAW;QACpB,IAAI,EAAE,CAAC,CAAC,cAAc;QACtB,IAAI,EAAE,CAAC,CAAC,cAAc;KACvB,CAAC,CAAC,CAAC;IAEJ,gFAAgF;IAChF,IAAI,CAAC,GAAG,CAAC,CAAC;IACV,OAAO,CAAC,GAAG,MAAM,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;QAC7B,IAAI,MAAM,CAAC,CAAC,CAAC,CAAC,KAAK,GAAG,MAAM,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,KAAK,EAAE,CAAC;YAC1C,0BAA0B;YAC1B,MAAM,YAAY,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC,MAAM,GAAG,MAAM,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,MAAM,CAAC;YAC7D,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AC;YAC5D,CAAC;QACH,CAAC;QAED,+BAA+B;QAC/B,IAAI,OAAO,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,MAAM,EAAE,CAAC;YACxC,OAAO,EAAE,UAAU,EAAE,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,UAAU,EAAE,YAAY,EAAE,IAAI,EAAE,CAAC;QAC3E,CAAC;QACD,MAAM,IAAI,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;QACzD,OAAO,EAAE,UAAU,EAAE,IAAI,CAAC,UAAU,EAAE,YAAY,EAAE,IAAI,EAAE,CAAC;IAC7D,CAAC;CACF","sourcesContent":["import * as fs from 'fs';\nimport * as path from 'path';\n\nexport interface CalibrationBin {\n rawMin: number;\n rawMax: number;\n calibrated: number;\n}\n\nexport interface CalibrationCurve {\n targetModel: string;\n taskType: string;\n method: 'isotonic' | 'platt';\n createdAt: string;\n bins: CalibrationBin[];\n plattParams?: { a: number; b: number };\n eceBefore: number;\n eceAfter: number;\n}\n\nexport interface CalibrationSample {\n id?: string;\n rawProbability: number;\n groundTruth: 0 | 1;\n}\n\n/**\n * Isotonic Regression using the Pool Adjacent Violators Algorithm (PAVA)\n * Fits a non-decreasing, non-parametric mapping from raw probabilities to calibrated probabilities.\n */\nexport function fitIsotonicRegression(samples: CalibrationSample[]): CalibrationBin[] {\n if (samples.length === 0) return [];\n\n // Sort samples ascending by rawProbability\n const sorted = [...samples].sort((a, b) => a.rawProbability - b.rawProbability);\n\n // Initialize blocks: each block has weight, sum of y, and range of x\n interface Block {\n weight: number;\n sumY: number;\n value: number; // mean y\n xMin: number;\n xMax: number;\n }\n\n const blocks: Block[] = sorted.map((s) => ({\n weight: 1,\n sumY: s.groundTruth,\n value: s.groundTruth,\n xMin: s.rawProbability,\n xMax: s.rawProbability\n }));\n\n // PAVA: Merge adjacent blocks that violate monotonicity (value[i] > value[i+1])\n let i = 0;\n while (i < blocks.length - 1) {\n if (blocks[i].value > blocks[i + 1].value) {\n // Pool adjacent violators\n const pooledWeight = blocks[i].weight + blocks[i + 1].weight;\n const pooledSumY = blocks[i].sumY + blocks[i + 1].sumY;\n const pooledValue = pooledSumY / pooledWeight;\n\n blocks[i] = {\n weight: pooledWeight,\n sumY: pooledSumY,\n value: pooledValue,\n xMin: blocks[i].xMin,\n xMax: blocks[i + 1].xMax\n };\n blocks.splice(i + 1, 1);\n\n // Check backward to restore monotonicity\n if (i > 0) {\n i--;\n }\n } else {\n i++;\n }\n }\n\n // Convert blocks to continuous CalibrationBins spanning 0.0 to 1.0\n const bins: CalibrationBin[] = [];\n for (let k = 0; k < blocks.length; k++) {\n const prevMax = k === 0 ? 0.0 : bins[k - 1].rawMax;\n const nextMin = k === blocks.length - 1 ? 1.0 : (blocks[k].xMax + blocks[k + 1].xMin) / 2;\n\n bins.push({\n rawMin: Number(prevMax.toFixed(4)),\n rawMax: Number(nextMin.toFixed(4)),\n calibrated: Number(Math.min(1.0, Math.max(0.0, blocks[k].value)).toFixed(4))\n });\n }\n\n // Ensure last bin caps at 1.0\n if (bins.length > 0) {\n bins[bins.length - 1].rawMax = 1.0;\n }\n\n return bins;\n}\n\n/**\n * Calculates Expected Calibration Error (ECE)\n */\nexport function calculateECE(\n samples: Array<{ probability: number; groundTruth: 0 | 1 }>,\n numBins = 10\n): number {\n if (samples.length === 0) return 0;\n\n const binStep = 1.0 / numBins;\n let totalEce = 0;\n const n = samples.length;\n\n for (let i = 0; i < numBins; i++) {\n const binMin = i * binStep;\n const binMax = (i + 1) * binStep;\n\n const inBin = samples.filter((s) => s.probability >= binMin && (i === numBins - 1 ? s.probability <= binMax : s.probability < binMax));\n if (inBin.length === 0) continue;\n\n const binAcc = inBin.reduce((acc, s) => acc + s.groundTruth, 0) / inBin.length;\n const binConf = inBin.reduce((acc, s) => acc + s.probability, 0) / inBin.length;\n\n totalEce += (inBin.length / n) * Math.abs(binAcc - binConf);\n }\n\n return Number(totalEce.toFixed(4));\n}\n\n/**\n * Online Calibration Engine\n * Loads pre-fitted curves and maps raw probabilities to calibrated true probabilities.\n */\nexport class Calibrator {\n private static instance: Calibrator;\n private curve: CalibrationCurve | null = null;\n\n constructor(customCurvePath?: string) {\n const defaultPath = path.join(process.cwd(), '.reflex', 'calibration.json');\n const targetPath = customCurvePath || process.env.SYSTEM_ONE_CALIBRATION_FILE || defaultPath;\n this.loadFromDisk(targetPath);\n }\n\n static getInstance(): Calibrator {\n if (!Calibrator.instance) {\n Calibrator.instance = new Calibrator();\n }\n return Calibrator.instance;\n }\n\n loadFromDisk(filePath: string): boolean {\n try {\n if (fs.existsSync(filePath)) {\n const data = fs.readFileSync(filePath, 'utf8');\n this.curve = JSON.parse(data);\n return true;\n }\n } catch {\n // ignore\n }\n return false;\n }\n\n setCurve(curve: CalibrationCurve): void {\n this.curve = curve;\n }\n\n isLoaded(): boolean {\n return this.curve !== null;\n }\n\n getCurve(): CalibrationCurve | null {\n return this.curve;\n }\n\n /**\n * Calibrate a raw probability\n */\n calibrate(rawProb: number): { calibrated: number; isCalibrated: boolean } {\n if (!this.curve || !this.curve.bins || this.curve.bins.length === 0) {\n return { calibrated: rawProb, isCalibrated: false };\n }\n\n const clamped = Math.max(0.0, Math.min(1.0, rawProb));\n\n // Linear interpolation or bin lookup\n for (const bin of this.curve.bins) {\n if (clamped >= bin.rawMin && clamped <= bin.rawMax) {\n return { calibrated: bin.calibrated, isCalibrated: true };\n }\n }\n\n // Fallback to nearest boundary\n if (clamped < this.curve.bins[0].rawMin) {\n return { calibrated: this.curve.bins[0].calibrated, isCalibrated: true };\n }\n const last = this.curve.bins[this.curve.bins.length - 1];\n return { calibrated: last.calibrated, isCalibrated: true };\n }\n}\n"]}
@@ -0,0 +1,90 @@
1
+ /** Completion claim candidates submitted to one closing judgment. */
2
+ export declare const MAX_CLAIMS = 3;
3
+ /** Minimum sentence length worth classifying as a claim candidate. */
4
+ export declare const MIN_CLAIM_CHARS = 8;
5
+ /** One classified candidate. */
6
+ export interface ClaimClassificationLike {
7
+ readonly statement: string;
8
+ readonly isClaim: boolean;
9
+ readonly confidence: number;
10
+ }
11
+ /** The classification half of a closing judgment's answer. */
12
+ export interface ClaimClassificationResponseLike {
13
+ readonly results: readonly ClaimClassificationLike[];
14
+ readonly latencyMs: number;
15
+ }
16
+ /** One verification result. */
17
+ export interface ClosingResultLike {
18
+ readonly statement: string;
19
+ readonly outcome: string;
20
+ readonly confidence: number;
21
+ }
22
+ /** The verification half of a closing judgment's answer. */
23
+ export interface ClosingVerdictLike {
24
+ readonly passed: boolean;
25
+ readonly results: readonly ClosingResultLike[];
26
+ }
27
+ /**
28
+ * The *candidate* sentences of one turn's assistant text.
29
+ *
30
+ * Deterministic and semantic-free on purpose: splitting, de-duplication, the
31
+ * length floor, and the last-{@link MAX_CLAIMS} bound are all the local work
32
+ * this module may do. Whether a candidate really claims completion is the
33
+ * backend's answer — an English word list would miss a Chinese "全部通过" and
34
+ * read `not complete` as the opposite, so there is none here.
35
+ *
36
+ * @param text - the turn's assistant text.
37
+ * @returns bounded, deduplicated candidates in their original order.
38
+ */
39
+ export declare function claimCandidates(text: string): string[];
40
+ /**
41
+ * The classified statements that really claim completion, above the confidence
42
+ * floor.
43
+ * @param classification - the backend's answer.
44
+ * @param minConfidence - the resolved claim floor.
45
+ * @returns one assertion per accepted claim.
46
+ */
47
+ export declare function claimsOf(classification: ClaimClassificationResponseLike, minConfidence: number): Array<{
48
+ statement: string;
49
+ }>;
50
+ /**
51
+ * The contradicted statements, clipped for the corrective message.
52
+ * @param verdict - the verification answer.
53
+ * @returns the statements whose evidence contradicts them.
54
+ */
55
+ export declare function contradictedOf(verdict: ClosingVerdictLike): string[];
56
+ /**
57
+ * How many verification results could not decide.
58
+ * @param verdict - the verification answer.
59
+ * @returns the `escalate` count.
60
+ */
61
+ export declare function undecidedOf(verdict: ClosingVerdictLike): number;
62
+ /**
63
+ * The skip reason of a closing judgment that does not object.
64
+ *
65
+ * `escalate` is not a contradiction: it means the gate could not decide — an
66
+ * unavailable backend degrades exactly this way — and steering a turn on an
67
+ * undecided verdict would turn a backend failure into a model-visible objection.
68
+ *
69
+ * @param verdict - the verification answer.
70
+ * @param contradicted - the statements that really contradict.
71
+ * @returns the machine reason to record, or `undefined` when the turn is steered.
72
+ */
73
+ export declare function closingSkipReason(verdict: ClosingVerdictLike, contradicted: readonly string[]): string | undefined;
74
+ /**
75
+ * Tokens the classification request reasoned about.
76
+ * @param statements - submitted candidates.
77
+ * @returns the estimated token count.
78
+ */
79
+ export declare function classificationTokens(statements: readonly string[]): number;
80
+ /**
81
+ * Tokens the verification request reasoned about: the classification batch plus
82
+ * the evidence the gate read.
83
+ * @param classificationTokensSpent - tokens of the classification request.
84
+ * @param claims - accepted claims submitted to verification.
85
+ * @param evidence - the assembled evidence text.
86
+ * @returns the estimated token count.
87
+ */
88
+ export declare function verificationTokens(classificationTokensSpent: number, claims: readonly {
89
+ statement: string;
90
+ }[], evidence: string): number;