Pepguy commited on
Commit
3017841
Β·
verified Β·
1 Parent(s): e2aa1ff

Update app.js

Browse files
Files changed (1) hide show
  1. app.js +82 -84
app.js CHANGED
@@ -8,7 +8,7 @@
8
  * matching the depth the AI produces (scope_depth 2-3, EMERGES,
9
  * CONTRADICT, CONSERVES, STEP/CANDIDATE where applicable)
10
  * 2. POST-PROCESSING NORMALIZER: every sample's c_values are mapped
11
- * to [0,1] relative to declared bounds before saving. No more
12
  * raw voltages, payoffs, or angles in c_values.
13
  * 3. VALIDATION: catches string c_values, missing VARS prefix,
14
  * mask length mismatch, non-finite b_raw β€” all logged and rejected.
@@ -31,6 +31,7 @@
31
  */
32
 
33
  import express from "express";
 
34
  import { randomUUID } from "crypto";
35
  import fs from "fs";
36
  import path from "path";
@@ -42,14 +43,14 @@ import {
42
  // ── CONFIG ────────────────────────────────────────────────────────────────────
43
  const PORT = parseInt(process.env.PORT || "7860");
44
  const AWS_REGION = process.env.AWS_REGION || "us-east-1";
45
- const BEDROCK_MODEL = "arn:aws:bedrock:us-east-1:106774395747:inference-profile/global.anthropic.claude-sonnet-4-6";
46
- //"arn:aws:bedrock:us-east-1:106774395747:inference-profile/global.anthropic.claude-haiku-4-5-20251001-v1:0";
47
 
48
  const DATASET_PATH = process.env.DATASET_PATH || "axl_dataset.json";
49
  const DEFAULT_RPS = parseFloat(process.env.DEFAULT_RPS || "3");
50
  const MAX_RPS = parseFloat(process.env.MAX_RPS || "8");
51
  const SAMPLES_PER_CALL = parseInt(process.env.SAMPLES_PER_CALL || "20");
52
  const SCALE_K = 30.0;
 
53
 
54
  // ── LOGGING ───────────────────────────────────────────────────────────────────
55
  const ts = () => new Date().toISOString().slice(11, 23);
@@ -76,9 +77,11 @@ const randchoice = (arr) => arr[Math.floor(Math.random() * arr.length)];
76
  */
77
  function normalizeSample(s) {
78
  const parsed = parseVarsBounds(s.vars_text, s.n_vars);
79
- const raw = s.c_values;
80
-
81
- if (!Array.isArray(raw) || raw.length !== s.n_vars) return null;
 
 
82
 
83
  const normalized = raw.map((v, i) => {
84
  if (typeof v !== "number" || !isFinite(v)) return null;
@@ -89,8 +92,8 @@ function normalizeSample(s) {
89
 
90
  if (normalized.includes(null)) return null;
91
 
92
- // Rebuild mask to correct length (always LATENT_D_MAX inferred from data)
93
- const mask = Array(s.n_vars).fill(1);
94
 
95
  return {
96
  ...s,
@@ -102,14 +105,14 @@ function normalizeSample(s) {
102
  }
103
 
104
  function parseVarsBounds(varsText, nVars) {
105
- // Returns [[lo,hi], ...] for each variable
106
  const bounds = [];
107
- const re = /IN\s*[\[({]?\s*(-?[\d.e+\-]+)\s+(-?[\d.e+\-]+)\s*[\])}]?/gi;
108
  let m;
109
  while ((m = re.exec(varsText)) !== null) {
110
  bounds.push([parseFloat(m[1]), parseFloat(m[2])]);
111
  }
112
- // Pad with [0,1] if fewer bounds than vars
113
  while (bounds.length < nVars) bounds.push([0, 1]);
114
  return bounds;
115
  }
@@ -122,7 +125,7 @@ function ensureVarsPrefix(vt) {
122
 
123
  // ── VALIDATION ────────────────────────────────────────────────────────────────
124
  function validateSample(s) {
125
- const required = ["domain","sense","n_vars","vars_text","expr_text",
126
  "sense_text","b_raw","c_values","mask"];
127
  for (const f of required) {
128
  if (s[f] === undefined || s[f] === null) {
@@ -131,7 +134,7 @@ function validateSample(s) {
131
  }
132
  }
133
  if (!Array.isArray(s.c_values)) { log(`Reject: c_values not array`, "WARN"); return false; }
134
- if (s.c_values.length !== s.n_vars) { log(`Reject: c_values len mismatch`, "WARN"); return false; }
135
  if (s.c_values.some(v => typeof v !== "number" || !isFinite(v))) {
136
  log(`Reject: non-numeric c_values in ${s.domain}`, "WARN"); return false;
137
  }
@@ -152,7 +155,7 @@ function validateSample(s) {
152
  // ── PHYSICS ───────────────────────────────────────────────────────────────────
153
  function synthPhysicsSamples(n) {
154
  const samples = [];
155
- const templates = [
156
  {
157
  name: "Kinetic Energy",
158
  fn: (c) => 0.5 * (c[0]) * (c[1])**2,
@@ -218,7 +221,7 @@ function synthPhysicsSamples(n) {
218
  ` ASSUME ${t.conserves}`,
219
  `END SCOPE`,
220
  ``,
221
- `SCOPE ${t.name.toLowerCase().replace(/ /g,"_")} [level: 1]`,
222
  ` ASSUME physics_primitives SCOPE HOLDS`,
223
  ``,
224
  ` ENTITY physical_system`,
@@ -255,7 +258,7 @@ function synthPhysicsSamples(n) {
255
  b_raw: fmt(bRaw), b_norm: fmt(safeNorm(bRaw), 8),
256
  c_values: cRaw.map(v => fmt(v)),
257
  mask: Array(nVars).fill(1),
258
- candidates: [], step_count: 0, axl_source: axl,
259
  metadata: {
260
  description: `${t.name} constraint inversion: ${t.formula} = ${bRaw.toFixed(4)}`,
261
  units: t.units, difficulty: "medium",
@@ -269,7 +272,7 @@ function synthPhysicsSamples(n) {
269
 
270
  // ── FINANCE ───────────────────────────────────────────────────────────────────
271
  function synthFinanceSamples(n) {
272
- const samples = [];
273
  for (let i = 0; i < n; i++) {
274
  const kind = randchoice(["compound","loan","portfolio_variance","sharpe"]);
275
  try {
@@ -292,9 +295,9 @@ function synthFinanceSamples(n) {
292
  subdomain = "loan_payment";
293
  desc = `Monthly payment: ${bRaw.toFixed(2)}`;
294
  } else if (kind === "portfolio_variance") {
295
- const w = [rnd(0,1), rnd(0,1), rnd(0,1)];
296
  const s = w.reduce((a,b)=>a+b,0); w[0]/=s; w[1]/=s; w[2]/=s;
297
- const sig = [rnd(0.05,0.3), rnd(0.02,0.15), rnd(0.01,0.08)];
298
  const rho01 = rnd(-0.3,0.5), rho02 = rnd(-0.2,0.4), rho12 = rnd(-0.1,0.3);
299
  bRaw = w[0]**2*sig[0]**2 + w[1]**2*sig[1]**2 + w[2]**2*sig[2]**2
300
  + 2*w[0]*w[1]*rho01*sig[0]*sig[1]
@@ -306,9 +309,9 @@ function synthFinanceSamples(n) {
306
  subdomain = "portfolio_variance";
307
  desc = `Minimum variance portfolio: variance=${bRaw.toFixed(5)}`;
308
  } else {
309
- const ret = [rnd(0.05,0.25), rnd(0.02,0.12), rnd(0.01,0.05)];
310
- const risk = [rnd(0.1,0.4), rnd(0.05,0.2), rnd(0.01,0.05)];
311
- const w = [rnd(0.2,0.6), rnd(0.1,0.4), rnd(0.05,0.3)];
312
  const s = w.reduce((a,b)=>a+b,0); w[0]/=s; w[1]/=s; w[2]/=s;
313
  const portRet = w.reduce((a,v,j)=>a+v*ret[j],0);
314
  const portRisk = Math.sqrt(w.reduce((a,v,j)=>a+v**2*risk[j]**2,0));
@@ -368,7 +371,7 @@ function synthFinanceSamples(n) {
368
  b_raw: fmt(bRaw), b_norm: fmt(safeNorm(bRaw), 8),
369
  c_values: cRaw.map(v => fmt(v)),
370
  mask: Array(nVars).fill(1),
371
- candidates: [], step_count: 0, axl_source: axl,
372
  metadata: {
373
  description: desc, units: "currency",
374
  difficulty: "medium", scope_depth: 2,
@@ -382,7 +385,7 @@ function synthFinanceSamples(n) {
382
 
383
  // ── CRYPTOGRAPHY (full depth β€” from synthCryptoSamples.js) ───────────────────
384
  function synthXorSamples(n) {
385
- const samples = [];
386
  for (let i = 0; i < n; i++) {
387
  const key = randint(0,255), plain = randint(0,255);
388
  const cipher = key ^ plain;
@@ -399,7 +402,7 @@ function synthXorSamples(n) {
399
  ].join("\n")).join("\n");
400
 
401
  const axl = [
402
- `SCOPE xor_bit_level [level: 0]`,
403
  ` ASSUME bit EXISTS`,
404
  ` ASSUME bit DISCRETE VALUES {0, 1}`,
405
  ` TRANSFORM xor_gate`,
@@ -431,7 +434,7 @@ function synthXorSamples(n) {
431
  ` DERIVES raw FROM {key_byte.raw, plain_byte.raw} BY xor_byte_transform`,
432
  ` END ENTITY`,
433
  ` TRANSFORM xor_byte_transform`,
434
- ` INPUT {key: INTEGER BOUND [0,255], plain: INTEGER BOUND [0,255]}`,
435
  ` OUTPUT {cipher: INTEGER BOUND [0,255]}`,
436
  ` CONSERVES nothing`,
437
  ` CHANGES cipher`,
@@ -450,12 +453,12 @@ function synthXorSamples(n) {
450
  samples.push({
451
  id: randomUUID(), domain: "cryptography", subdomain: "xor_byte",
452
  sense: "EQUAL", n_vars: 1,
453
- vars_text: "VARS c0 IN [0 1]",
454
  expr_text: `EXPR XOR plain=${plain} cipher=${cipher} key=UNKNOWN`,
455
  sense_text: "SENSE EQUAL",
456
  b_raw: fmt(cipher), b_norm: fmt(safeNorm(cipher), 8),
457
- c_values: [fmt(key/255.0)],
458
- mask: [1], candidates: [], step_count: 0, axl_source: axl,
459
  metadata: {
460
  description: `XOR byte: plain=${plain} key=${key} β†’ cipher=${cipher}`,
461
  units: "character_code", difficulty: "medium",
@@ -469,7 +472,7 @@ function synthXorSamples(n) {
469
  }
470
 
471
  function synthCaesarSamples(n) {
472
- const samples = [];
473
  for (let i = 0; i < n; i++) {
474
  const msgLen = randint(1,4);
475
  const shift = randint(0,25);
@@ -491,7 +494,7 @@ function synthCaesarSamples(n) {
491
  ` ASSUME modular_arithmetic HOLDS`,
492
  ` ENTITY alphabet`,
493
  ` FIELD size: INTEGER EQUALS 26`,
494
- ` BOUND any_char WITHIN [0, 25]`,
495
  ` END ENTITY`,
496
  ` TRANSFORM modular_add`,
497
  ` INPUT {a: INTEGER, b: INTEGER, mod: INTEGER}`,
@@ -521,7 +524,7 @@ function synthCaesarSamples(n) {
521
  `SCOPE caesar_message [level: 2]`,
522
  ` ASSUME caesar_char SCOPE HOLDS`,
523
  ` ENTITY message`,
524
- ` FIELD plaintext: VECTOR OF INTEGER EQUALS [${plains.join(", ")}]`,
525
  ` FIELD ciphertext: VECTOR OF INTEGER`,
526
  ` FIELD length: INTEGER EQUALS ${msgLen}`,
527
  ` DERIVES ciphertext FROM {plaintext, shift_key.raw} BY caesar_transform APPLIED_TO_EACH`,
@@ -540,12 +543,12 @@ function synthCaesarSamples(n) {
540
  samples.push({
541
  id: randomUUID(), domain: "cryptography", subdomain: "caesar",
542
  sense: "EQUAL", n_vars: 1,
543
- vars_text: "VARS c0 IN [0 1]",
544
  expr_text: `EXPR CAESAR plains=[${plains}] ciphers=[${ciphers}] shift=UNKNOWN`,
545
  sense_text: "SENSE EQUAL",
546
  b_raw: fmt(bRaw), b_norm: fmt(safeNorm(bRaw), 8),
547
- c_values: [fmt(shift/25.0)],
548
- mask: [1], candidates: [], step_count: 0, axl_source: axl,
549
  metadata: {
550
  description: `Caesar: shift=${shift} plains=[${plains}] β†’ [${ciphers}]`,
551
  units: "character_code_sum",
@@ -558,7 +561,7 @@ function synthCaesarSamples(n) {
558
  }
559
 
560
  function synthVigenereSamples(n) {
561
- const samples = [];
562
  for (let i = 0; i < n; i++) {
563
  const keyLen = randint(2,5);
564
  const key = Array.from({length:keyLen},()=>randint(0,25));
@@ -570,7 +573,7 @@ function synthVigenereSamples(n) {
570
  ` ENTITY position_${idx}`,
571
  ` FIELD plaintext: INTEGER EQUALS ${p}`,
572
  ` FIELD key_char: INTEGER BOUND [0, 25]`,
573
- ` FIELD ciphertext: INTEGER BOUND [0, 25]`,
574
  ` DERIVES ciphertext FROM {plaintext, key_char} BY modular_add_26`,
575
  ` END ENTITY`,
576
  ].join("\n")).join("\n");
@@ -599,7 +602,7 @@ function synthVigenereSamples(n) {
599
  ` ASSUME vigenere_position SCOPE HOLDS`,
600
  ` ENTITY key_vector`,
601
  ` FIELD chars: VECTOR OF INTEGER BOUND [0, 25]`,
602
- ` FIELD normalised: VECTOR OF REAL BOUND [0, 1]`,
603
  ` DERIVES normalised FROM chars BY divide_each_by_25`,
604
  ` END ENTITY`,
605
  ` ENTITY plaintext_vector`,
@@ -610,7 +613,7 @@ function synthVigenereSamples(n) {
610
  ` DERIVES chars FROM {plaintext_vector.chars, key_vector.chars}`,
611
  ` BY modular_add_26 APPLIED_PAIRWISE`,
612
  ` END ENTITY`,
613
- ` OBSERVE ciphertext_vector.chars EQUALS [${cipher.join(", ")}]`,
614
  ` OBSERVE SUM(ciphertext_vector.chars) EQUALS ${bRaw}`,
615
  ` UNKNOWN key_vector.normalised: VECTOR OF REAL BOUND [0, 1]`,
616
  ` COLLAPSE vigenere_composition`,
@@ -621,7 +624,7 @@ function synthVigenereSamples(n) {
621
  `END SCOPE`,
622
  ].join("\n");
623
 
624
- const varsText = `VARS ${Array.from({length:keyLen},(_,j)=>`c${j} IN [0 1]`).join(" ")}`;
625
  samples.push({
626
  id: randomUUID(), domain: "cryptography",
627
  subdomain: `vigenere_${keyLen}char`,
@@ -629,9 +632,9 @@ function synthVigenereSamples(n) {
629
  expr_text: `EXPR VIGENERE keyLen=${keyLen} plains=[${plain}] ciphers=[${cipher}] key=UNKNOWN`,
630
  sense_text: "SENSE EQUAL",
631
  b_raw: fmt(bRaw), b_norm: fmt(safeNorm(bRaw), 8),
632
- c_values: key.map(k=>fmt(k/25.0)),
633
  mask: Array(keyLen).fill(1),
634
- candidates: [], step_count: 0, axl_source: axl,
635
  metadata: {
636
  description: `VigenΓ¨re ${keyLen}-char key=[${key}]`,
637
  units: "character_code_sum",
@@ -644,9 +647,9 @@ function synthVigenereSamples(n) {
644
  }
645
 
646
  function synthAffineSamples(n) {
647
- const VALID_A = [1,3,5,7,9,11,15,17,19,21,23,25];
648
  const INV_A_MAP = {1:1,3:9,5:21,7:15,9:3,11:19,15:7,17:23,19:11,21:5,23:17,25:25};
649
- const samples = [];
650
  for (let i = 0; i < n; i++) {
651
  const aIdx = randint(0,11);
652
  const a = VALID_A[aIdx];
@@ -657,7 +660,7 @@ function synthAffineSamples(n) {
657
  const verify = ((aInv*(cipher-b))%26+26)%26;
658
  if (verify !== p) continue;
659
 
660
- const axl = [
661
  `SCOPE modular_arithmetic [level: 0]`,
662
  ` ASSUME integer EXISTS`,
663
  ` TRANSFORM modular_multiply_add`,
@@ -677,8 +680,8 @@ function synthAffineSamples(n) {
677
  ` ASSUME modular_arithmetic SCOPE HOLDS`,
678
  ` ENTITY affine_key`,
679
  ` FIELD a: INTEGER DISCRETE VALUES {1,3,5,7,9,11,15,17,19,21,23,25}`,
680
- ` FIELD b: INTEGER BOUND [0, 25]`,
681
- ` FIELD a_idx: INTEGER BOUND [0, 11]`,
682
  ` FIELD a_norm: REAL BOUND [0, 1]`,
683
  ` FIELD b_norm: REAL BOUND [0, 1]`,
684
  ` DERIVES a FROM a_idx BY lookup_valid_a`,
@@ -687,16 +690,14 @@ function synthAffineSamples(n) {
687
  ` BOUND a COPRIME_TO 26`,
688
  ` END ENTITY`,
689
  ` ENTITY affine_transform_result`,
690
- ` FIELD plaintext: INTEGER BOUND [0, 25] EQUALS ${p}`,
691
  ` FIELD ciphertext: INTEGER BOUND [0, 25]`,
692
  ` DERIVES ciphertext FROM {affine_key.a, plaintext, affine_key.b} BY modular_multiply_add`,
693
- ` # f(${p}) = (${a} * ${p} + ${b}) mod 26 = ${cipher}`,
694
  ` END ENTITY`,
695
  ` ENTITY affine_inverse`,
696
  ` FIELD a_inv: INTEGER EQUALS ${aInv}`,
697
  ` FIELD recovery: INTEGER`,
698
  ` DERIVES recovery FROM {a_inv, ciphertext, b} BY modular_multiply_add`,
699
- ` # a_inv*(cipher-b) mod 26 = ${p} βœ“`,
700
  ` END ENTITY`,
701
  ` CONTRADICT invertible WITH non_coprime_a`,
702
  ` AT SCOPE affine_cipher`,
@@ -716,12 +717,12 @@ function synthAffineSamples(n) {
716
  samples.push({
717
  id: randomUUID(), domain: "cryptography", subdomain: "affine",
718
  sense: "EQUAL", n_vars: 2,
719
- vars_text: "VARS c0 IN [0 1] c1 IN [0 1]",
720
  expr_text: `EXPR AFFINE a=${a}(idx=${aIdx}) b=${b} plain=${p} cipher=${cipher}`,
721
  sense_text: "SENSE EQUAL",
722
  b_raw: fmt(cipher), b_norm: fmt(safeNorm(cipher), 8),
723
- c_values: [fmt(aIdx/11.0), fmt(b/25.0)],
724
- mask: [1,1], candidates: [], step_count: 0, axl_source: axl,
725
  metadata: {
726
  description: `Affine a=${a} b=${b} plain=${p} β†’ cipher=${cipher}`,
727
  units: "character_code", difficulty: "hard",
@@ -735,7 +736,7 @@ function synthAffineSamples(n) {
735
 
736
  // ── OPTIMIZATION (deep AXL, not just a label) ─────────────────────────────────
737
  function synthOptimizationSamples(n) {
738
- const samples = [];
739
  for (let i = 0; i < n; i++) {
740
  const sense = randchoice(["MINIMIZE","MAXIMIZE"]);
741
  const nVars = randint(2,6);
@@ -746,7 +747,7 @@ function synthOptimizationSamples(n) {
746
  const bRaw = cVals.reduce((acc,v,j)=>acc+v*coeffs[j],0);
747
  const exprStr = coeffs.map((c,j)=>`${c.toFixed(3)}*c${j}`).join(" + ");
748
 
749
- const axl = [
750
  `SCOPE constraint_primitives [level: 0]`,
751
  ` ASSUME variable EXISTS`,
752
  ` ASSUME variable BOUND [0, 1]`,
@@ -793,13 +794,13 @@ function synthOptimizationSamples(n) {
793
  id: randomUUID(), domain: "optimization",
794
  subdomain: `linear_${sense.toLowerCase()}_${nVars}var`,
795
  sense, n_vars: nVars,
796
- vars_text: `VARS ${Array.from({length:nVars},(_,j)=>`c${j} IN [0 1]`).join(" ")}`,
797
  expr_text: `EXPR ${exprStr}`,
798
  sense_text: `SENSE ${sense}`,
799
  b_raw: fmt(bRaw), b_norm: fmt(safeNorm(bRaw), 8),
800
  c_values: cVals.map(v=>fmt(v)),
801
  mask: Array(nVars).fill(1),
802
- candidates: [], step_count: 0, axl_source: axl,
803
  metadata: {
804
  description: `Linear ${sense.toLowerCase()} over ${nVars} variables`,
805
  units: "objective", difficulty: "easy",
@@ -824,7 +825,7 @@ const SYNTHETIC_GENERATORS = {
824
 
825
  // ── FOCUS TRACKER ─────────────────────────────────────────────────────────────
826
  const tracker = {
827
- recent: [], counts: {}, total: 0,
828
  record(domain) {
829
  this.recent.push(domain);
830
  if (this.recent.length > 100) this.recent.shift();
@@ -837,7 +838,7 @@ const tracker = {
837
  };
838
 
839
  // ── DATASET STATE ─────────────────────────────────────────────────────────────
840
- let dataset = [];
841
  function loadDataset() {
842
  if (fs.existsSync(DATASET_PATH)) {
843
  dataset = JSON.parse(fs.readFileSync(DATASET_PATH,"utf8"));
@@ -852,7 +853,6 @@ function saveDataset() {
852
  // ── BEDROCK CLIENT ────────────────────────────────────────────────────────────
853
  const bedrock = new BedrockRuntimeClient({ region: AWS_REGION });
854
 
855
- // USER: replace this string with the full AXL spec text
856
  const AXL_SPEC = `
857
  # AXL β€” Abstraction Exchange Language
858
  ### A Constraint-First, Bidirectionally Navigable Abstraction Language
@@ -995,7 +995,7 @@ The system will work backwards from this to find what
995
  configuration of unknowns is consistent with it.
996
 
997
  OBSERVE <field | entity | state> EQUALS <value>
998
- OBSERVE <field> WITHIN [<min>, <max>]
999
  OBSERVE <pattern> IN <output>
1000
 
1001
  ---
@@ -1184,7 +1184,7 @@ SCOPE quantum[level: 0]
1184
  END ENTITY
1185
 
1186
  ENTITY gluon
1187
- FIELD charge: BOUND [0, 0] CONSERVES
1188
  FIELD color: SYMBOLIC # carries color charge
1189
  TENDS quark_binding MAX # gluons maximize binding
1190
  END ENTITY
@@ -1223,7 +1223,7 @@ SCOPE hadron [level: 1]
1223
  END SCOPE
1224
 
1225
 
1226
- SCOPE nucleus [level: 2]
1227
 
1228
  ASSUME hadron SCOPE HOLDS
1229
 
@@ -1262,7 +1262,7 @@ SCOPE atom [level: 3]
1262
  ASSUME nucleus SCOPE HOLDS
1263
 
1264
  ENTITY electron
1265
- FIELD charge: BOUND [-1, -1] CONSERVES
1266
  FIELD mass: BOUND[9.109e-31, 9.109e-31] CONSERVES
1267
  FIELD spin: DISCRETE VALUES {-0.5, 0.5}
1268
  FIELD orbital: DISCRETE VALUES {s, p, d, f}
@@ -1376,7 +1376,7 @@ SCOPE sha256_internals [level: 1]
1376
  END SCOPE
1377
 
1378
 
1379
- SCOPE block_header [level: 2]
1380
 
1381
  ASSUME sha256_internals SCOPE HOLDS
1382
 
@@ -1386,7 +1386,7 @@ SCOPE block_header [level: 2]
1386
  FIELD merkle_root: bit_array BOUND length EQUALS 256 # GIVEN, fixed
1387
  FIELD timestamp: INTEGER # GIVEN, approximately fixed
1388
  FIELD bits: INTEGER # GIVEN, encodes target
1389
- FIELD nonce: INTEGER BOUND [0, 4294967295] # UNKNOWN β€” 32 bits of freedom
1390
  END ENTITY
1391
 
1392
  DERIVE target
@@ -1750,7 +1750,7 @@ STRICT REQUIREMENTS:
1750
  3. b_raw must be a computed finite float matching the AXL program's logic.
1751
  4. c_values must be in RAW domain units matching the declared bounds in vars_text.
1752
  DO NOT pre-normalize to [0,1] β€” the pipeline does that. Example: if
1753
- vars_text says "VARS c0 IN [200 800]" then c_values should be like [650, 210].
1754
  5. Every vars_text MUST start with the word VARS.
1755
  6. Every sample must use a DIFFERENT domain or structural pattern.
1756
  7. Vary: sense (EQUAL/MINIMIZE/MAXIMIZE/SELECT/TEND), n_vars (1-${maxVars}),
@@ -1769,14 +1769,14 @@ JSON SCHEMA (output array of these):
1769
  "subdomain": "<specific topic>",
1770
  "sense": "<EQUAL|MINIMIZE|MAXIMIZE|SELECT|TEND>",
1771
  "n_vars": <integer>,
1772
- "vars_text": "VARS c0 IN [lo hi] c1 IN [lo hi] ...",
1773
  "expr_text": "EXPR <description>",
1774
  "sense_text": "SENSE <EQUAL|MINIMIZE|MAXIMIZE|SELECT|TEND>",
1775
  "b_raw": <float>,
1776
  "b_norm": <sign(b)*log(1+|b|)/30>,
1777
- "c_values": [<raw domain values matching bounds>],
1778
  "mask": [1,1,...],
1779
- "candidates": [],
1780
  "step_count": <integer>,
1781
  "axl_source": "<full multi-scope AXL program as single string>",
1782
  "metadata": {
@@ -1811,7 +1811,7 @@ async function callBedrock(prompt) {
1811
  const raw = JSON.parse(Buffer.from(res.body).toString("utf8"));
1812
  const text = raw.content[0].text;
1813
  log(`Bedrock call ${((Date.now()-t0)/1000).toFixed(1)}s β€” ${text.length} chars`);
1814
- const tokenUsage = res.usage ? (res.usage.inputTokens + res.usage.outputTokens) : 0;
1815
  console.log(tokenUsage)
1816
  return text;
1817
  }
@@ -1824,12 +1824,12 @@ function parseAIResponse(text) {
1824
  if (t.endsWith("```")) t = t.slice(0,-3);
1825
  t = t.trim();
1826
  const start = t.indexOf("["), end = t.lastIndexOf("]");
1827
- if (start === -1 || end === -1) return [];
1828
  try {
1829
  return JSON.parse(t.slice(start, end+1));
1830
  } catch(e) {
1831
  log(`JSON parse error: ${e.message} β€” attempting salvage`, "WARN");
1832
- const saved = [];
1833
  let depth = 0, buf = "", inObj = false;
1834
  for (const ch of t.slice(start+1, end)) {
1835
  if (ch === "{") { depth++; inObj = true; }
@@ -1849,6 +1849,7 @@ function parseAIResponse(text) {
1849
 
1850
  // ── EXPRESS APP ───────────────────────────────────────────────────────────────
1851
  const app = express();
 
1852
  app.use(express.json());
1853
 
1854
  app.get("/status", (_, res) => res.json({
@@ -1862,14 +1863,14 @@ app.get("/status", (_, res) => res.json({
1862
  app.get("/domains", (_, res) => res.json(tracker.stats()));
1863
 
1864
  app.post("/generate", async (req, res) => {
1865
- const n = parseInt(req.query.n || "50");
1866
- const rps = Math.min(parseFloat(req.query.rps || DEFAULT_RPS), MAX_RPS);
1867
- const syntheticFraction = parseFloat(req.query.synthetic_fraction || "0.4");
1868
- const maxVars = parseInt(req.query.max_vars || "20");
1869
 
1870
  log(`Generation request: n=${n} rps=${rps} synthetic=${(syntheticFraction*100).toFixed(0)}%`, "HEAD");
1871
 
1872
- const generated = [];
1873
  let errors = 0;
1874
 
1875
  // ── SYNTHETIC BATCH ──
@@ -1877,7 +1878,7 @@ app.post("/generate", async (req, res) => {
1877
  if (nSynthetic > 0) {
1878
  const gens = Object.values(SYNTHETIC_GENERATORS);
1879
  const perGen = Math.max(1, Math.ceil(nSynthetic / gens.length));
1880
- for (const [name, genFn] of Object.entries(SYNTHETIC_GENERATORS)) {
1881
  for (const raw of genFn(perGen)) {
1882
  if (!validateSample(raw)) { errors++; continue; }
1883
  const norm = normalizeSample(raw);
@@ -1948,7 +1949,7 @@ app.get("/dataset/download", (req, res) => {
1948
 
1949
  app.post("/dataset/clear", (_, res) => {
1950
  const count = dataset.length;
1951
- dataset = [];
1952
  if (fs.existsSync(DATASET_PATH)) fs.unlinkSync(DATASET_PATH);
1953
  log(`Cleared ${count} samples`, "OK");
1954
  res.json({ cleared: count });
@@ -1962,12 +1963,9 @@ app.get("/dataset/sample", (req, res) => {
1962
 
1963
  // ── STARTUP ───────────────────────────────────────────────────────────────────
1964
  loadDataset();
1965
- app.listen(PORT, () => {
1966
  log(`AXL Dataset Server listening on :${PORT}`, "OK");
1967
  log(`Model: ${BEDROCK_MODEL}`);
1968
  log(`Dataset: ${DATASET_PATH}`);
1969
  log(`RPS: ${DEFAULT_RPS} default / ${MAX_RPS} max`);
1970
- if (AXL_SPEC === "[PASTE_AXL_SPEC_HERE]") {
1971
- log("⚠ AXL_SPEC placeholder not replaced β€” AI quality will be degraded", "WARN");
1972
- }
1973
  });
 
8
  * matching the depth the AI produces (scope_depth 2-3, EMERGES,
9
  * CONTRADICT, CONSERVES, STEP/CANDIDATE where applicable)
10
  * 2. POST-PROCESSING NORMALIZER: every sample's c_values are mapped
11
+ * to[0,1] relative to declared bounds before saving. No more
12
  * raw voltages, payoffs, or angles in c_values.
13
  * 3. VALIDATION: catches string c_values, missing VARS prefix,
14
  * mask length mismatch, non-finite b_raw β€” all logged and rejected.
 
31
  */
32
 
33
  import express from "express";
34
+ import cors from "cors";
35
  import { randomUUID } from "crypto";
36
  import fs from "fs";
37
  import path from "path";
 
43
  // ── CONFIG ────────────────────────────────────────────────────────────────────
44
  const PORT = parseInt(process.env.PORT || "7860");
45
  const AWS_REGION = process.env.AWS_REGION || "us-east-1";
46
+ const BEDROCK_MODEL = "arn:aws:bedrock:us-east-1:106774395747:inference-profile/global.anthropic.claude-sonnet-4-6";
 
47
 
48
  const DATASET_PATH = process.env.DATASET_PATH || "axl_dataset.json";
49
  const DEFAULT_RPS = parseFloat(process.env.DEFAULT_RPS || "3");
50
  const MAX_RPS = parseFloat(process.env.MAX_RPS || "8");
51
  const SAMPLES_PER_CALL = parseInt(process.env.SAMPLES_PER_CALL || "20");
52
  const SCALE_K = 30.0;
53
+ const LATENT_D_MAX = 8; // Added for correct mask padding
54
 
55
  // ── LOGGING ───────────────────────────────────────────────────────────────────
56
  const ts = () => new Date().toISOString().slice(11, 23);
 
77
  */
78
  function normalizeSample(s) {
79
  const parsed = parseVarsBounds(s.vars_text, s.n_vars);
80
+
81
+ if (!Array.isArray(s.c_values) || s.c_values.length < s.n_vars) return null;
82
+
83
+ // Tolerate if AI appended extra zeros by slicing to exact n_vars
84
+ const raw = s.c_values.slice(0, s.n_vars);
85
 
86
  const normalized = raw.map((v, i) => {
87
  if (typeof v !== "number" || !isFinite(v)) return null;
 
92
 
93
  if (normalized.includes(null)) return null;
94
 
95
+ // Pad mask to the global LATENT_D_MAX requirement
96
+ const mask =[...Array(s.n_vars).fill(1), ...Array(Math.max(0, LATENT_D_MAX - s.n_vars)).fill(0)];
97
 
98
  return {
99
  ...s,
 
105
  }
106
 
107
  function parseVarsBounds(varsText, nVars) {
108
+ // Returns [[lo,hi], ...] for each variable. [FIX]: Now tolerates commas
109
  const bounds = [];
110
+ const re = /IN\s*[\[({]?\s*(-?[\d.e+\-]+)[\s,]+(-?[\d.e+\-]+)\s*[\])}]?/gi;
111
  let m;
112
  while ((m = re.exec(varsText)) !== null) {
113
  bounds.push([parseFloat(m[1]), parseFloat(m[2])]);
114
  }
115
+ // Pad with[0,1] if fewer bounds than vars
116
  while (bounds.length < nVars) bounds.push([0, 1]);
117
  return bounds;
118
  }
 
125
 
126
  // ── VALIDATION ────────────────────────────────────────────────────────────────
127
  function validateSample(s) {
128
+ const required =["domain","sense","n_vars","vars_text","expr_text",
129
  "sense_text","b_raw","c_values","mask"];
130
  for (const f of required) {
131
  if (s[f] === undefined || s[f] === null) {
 
134
  }
135
  }
136
  if (!Array.isArray(s.c_values)) { log(`Reject: c_values not array`, "WARN"); return false; }
137
+ if (s.c_values.length < s.n_vars) { log(`Reject: c_values len mismatch`, "WARN"); return false; }
138
  if (s.c_values.some(v => typeof v !== "number" || !isFinite(v))) {
139
  log(`Reject: non-numeric c_values in ${s.domain}`, "WARN"); return false;
140
  }
 
155
  // ── PHYSICS ───────────────────────────────────────────────────────────────────
156
  function synthPhysicsSamples(n) {
157
  const samples = [];
158
+ const templates =[
159
  {
160
  name: "Kinetic Energy",
161
  fn: (c) => 0.5 * (c[0]) * (c[1])**2,
 
221
  ` ASSUME ${t.conserves}`,
222
  `END SCOPE`,
223
  ``,
224
+ `SCOPE ${t.name.toLowerCase().replace(/ /g,"_")}[level: 1]`,
225
  ` ASSUME physics_primitives SCOPE HOLDS`,
226
  ``,
227
  ` ENTITY physical_system`,
 
258
  b_raw: fmt(bRaw), b_norm: fmt(safeNorm(bRaw), 8),
259
  c_values: cRaw.map(v => fmt(v)),
260
  mask: Array(nVars).fill(1),
261
+ candidates:[], step_count: 0, axl_source: axl,
262
  metadata: {
263
  description: `${t.name} constraint inversion: ${t.formula} = ${bRaw.toFixed(4)}`,
264
  units: t.units, difficulty: "medium",
 
272
 
273
  // ── FINANCE ───────────────────────────────────────────────────────────────────
274
  function synthFinanceSamples(n) {
275
+ const samples =[];
276
  for (let i = 0; i < n; i++) {
277
  const kind = randchoice(["compound","loan","portfolio_variance","sharpe"]);
278
  try {
 
295
  subdomain = "loan_payment";
296
  desc = `Monthly payment: ${bRaw.toFixed(2)}`;
297
  } else if (kind === "portfolio_variance") {
298
+ const w =[rnd(0,1), rnd(0,1), rnd(0,1)];
299
  const s = w.reduce((a,b)=>a+b,0); w[0]/=s; w[1]/=s; w[2]/=s;
300
+ const sig =[rnd(0.05,0.3), rnd(0.02,0.15), rnd(0.01,0.08)];
301
  const rho01 = rnd(-0.3,0.5), rho02 = rnd(-0.2,0.4), rho12 = rnd(-0.1,0.3);
302
  bRaw = w[0]**2*sig[0]**2 + w[1]**2*sig[1]**2 + w[2]**2*sig[2]**2
303
  + 2*w[0]*w[1]*rho01*sig[0]*sig[1]
 
309
  subdomain = "portfolio_variance";
310
  desc = `Minimum variance portfolio: variance=${bRaw.toFixed(5)}`;
311
  } else {
312
+ const ret =[rnd(0.05,0.25), rnd(0.02,0.12), rnd(0.01,0.05)];
313
+ const risk =[rnd(0.1,0.4), rnd(0.05,0.2), rnd(0.01,0.05)];
314
+ const w =[rnd(0.2,0.6), rnd(0.1,0.4), rnd(0.05,0.3)];
315
  const s = w.reduce((a,b)=>a+b,0); w[0]/=s; w[1]/=s; w[2]/=s;
316
  const portRet = w.reduce((a,v,j)=>a+v*ret[j],0);
317
  const portRisk = Math.sqrt(w.reduce((a,v,j)=>a+v**2*risk[j]**2,0));
 
371
  b_raw: fmt(bRaw), b_norm: fmt(safeNorm(bRaw), 8),
372
  c_values: cRaw.map(v => fmt(v)),
373
  mask: Array(nVars).fill(1),
374
+ candidates:[], step_count: 0, axl_source: axl,
375
  metadata: {
376
  description: desc, units: "currency",
377
  difficulty: "medium", scope_depth: 2,
 
385
 
386
  // ── CRYPTOGRAPHY (full depth β€” from synthCryptoSamples.js) ───────────────────
387
  function synthXorSamples(n) {
388
+ const samples =[];
389
  for (let i = 0; i < n; i++) {
390
  const key = randint(0,255), plain = randint(0,255);
391
  const cipher = key ^ plain;
 
402
  ].join("\n")).join("\n");
403
 
404
  const axl = [
405
+ `SCOPE xor_bit_level[level: 0]`,
406
  ` ASSUME bit EXISTS`,
407
  ` ASSUME bit DISCRETE VALUES {0, 1}`,
408
  ` TRANSFORM xor_gate`,
 
434
  ` DERIVES raw FROM {key_byte.raw, plain_byte.raw} BY xor_byte_transform`,
435
  ` END ENTITY`,
436
  ` TRANSFORM xor_byte_transform`,
437
+ ` INPUT {key: INTEGER BOUND[0,255], plain: INTEGER BOUND [0,255]}`,
438
  ` OUTPUT {cipher: INTEGER BOUND [0,255]}`,
439
  ` CONSERVES nothing`,
440
  ` CHANGES cipher`,
 
453
  samples.push({
454
  id: randomUUID(), domain: "cryptography", subdomain: "xor_byte",
455
  sense: "EQUAL", n_vars: 1,
456
+ vars_text: "VARS c0 IN[0 255]",
457
  expr_text: `EXPR XOR plain=${plain} cipher=${cipher} key=UNKNOWN`,
458
  sense_text: "SENSE EQUAL",
459
  b_raw: fmt(cipher), b_norm: fmt(safeNorm(cipher), 8),
460
+ c_values: [key],
461
+ mask: [1], candidates:[], step_count: 0, axl_source: axl,
462
  metadata: {
463
  description: `XOR byte: plain=${plain} key=${key} β†’ cipher=${cipher}`,
464
  units: "character_code", difficulty: "medium",
 
472
  }
473
 
474
  function synthCaesarSamples(n) {
475
+ const samples =[];
476
  for (let i = 0; i < n; i++) {
477
  const msgLen = randint(1,4);
478
  const shift = randint(0,25);
 
494
  ` ASSUME modular_arithmetic HOLDS`,
495
  ` ENTITY alphabet`,
496
  ` FIELD size: INTEGER EQUALS 26`,
497
+ ` BOUND any_char WITHIN[0, 25]`,
498
  ` END ENTITY`,
499
  ` TRANSFORM modular_add`,
500
  ` INPUT {a: INTEGER, b: INTEGER, mod: INTEGER}`,
 
524
  `SCOPE caesar_message [level: 2]`,
525
  ` ASSUME caesar_char SCOPE HOLDS`,
526
  ` ENTITY message`,
527
+ ` FIELD plaintext: VECTOR OF INTEGER EQUALS[${plains.join(", ")}]`,
528
  ` FIELD ciphertext: VECTOR OF INTEGER`,
529
  ` FIELD length: INTEGER EQUALS ${msgLen}`,
530
  ` DERIVES ciphertext FROM {plaintext, shift_key.raw} BY caesar_transform APPLIED_TO_EACH`,
 
543
  samples.push({
544
  id: randomUUID(), domain: "cryptography", subdomain: "caesar",
545
  sense: "EQUAL", n_vars: 1,
546
+ vars_text: "VARS c0 IN[0 25]",
547
  expr_text: `EXPR CAESAR plains=[${plains}] ciphers=[${ciphers}] shift=UNKNOWN`,
548
  sense_text: "SENSE EQUAL",
549
  b_raw: fmt(bRaw), b_norm: fmt(safeNorm(bRaw), 8),
550
+ c_values: [shift],
551
+ mask: [1], candidates:[], step_count: 0, axl_source: axl,
552
  metadata: {
553
  description: `Caesar: shift=${shift} plains=[${plains}] β†’ [${ciphers}]`,
554
  units: "character_code_sum",
 
561
  }
562
 
563
  function synthVigenereSamples(n) {
564
+ const samples =[];
565
  for (let i = 0; i < n; i++) {
566
  const keyLen = randint(2,5);
567
  const key = Array.from({length:keyLen},()=>randint(0,25));
 
573
  ` ENTITY position_${idx}`,
574
  ` FIELD plaintext: INTEGER EQUALS ${p}`,
575
  ` FIELD key_char: INTEGER BOUND [0, 25]`,
576
+ ` FIELD ciphertext: INTEGER BOUND[0, 25]`,
577
  ` DERIVES ciphertext FROM {plaintext, key_char} BY modular_add_26`,
578
  ` END ENTITY`,
579
  ].join("\n")).join("\n");
 
602
  ` ASSUME vigenere_position SCOPE HOLDS`,
603
  ` ENTITY key_vector`,
604
  ` FIELD chars: VECTOR OF INTEGER BOUND [0, 25]`,
605
+ ` FIELD normalised: VECTOR OF REAL BOUND[0, 1]`,
606
  ` DERIVES normalised FROM chars BY divide_each_by_25`,
607
  ` END ENTITY`,
608
  ` ENTITY plaintext_vector`,
 
613
  ` DERIVES chars FROM {plaintext_vector.chars, key_vector.chars}`,
614
  ` BY modular_add_26 APPLIED_PAIRWISE`,
615
  ` END ENTITY`,
616
+ ` OBSERVE ciphertext_vector.chars EQUALS[${cipher.join(", ")}]`,
617
  ` OBSERVE SUM(ciphertext_vector.chars) EQUALS ${bRaw}`,
618
  ` UNKNOWN key_vector.normalised: VECTOR OF REAL BOUND [0, 1]`,
619
  ` COLLAPSE vigenere_composition`,
 
624
  `END SCOPE`,
625
  ].join("\n");
626
 
627
+ const varsText = `VARS ${Array.from({length:keyLen},(_,j)=>`c${j} IN [0 25]`).join(" ")}`;
628
  samples.push({
629
  id: randomUUID(), domain: "cryptography",
630
  subdomain: `vigenere_${keyLen}char`,
 
632
  expr_text: `EXPR VIGENERE keyLen=${keyLen} plains=[${plain}] ciphers=[${cipher}] key=UNKNOWN`,
633
  sense_text: "SENSE EQUAL",
634
  b_raw: fmt(bRaw), b_norm: fmt(safeNorm(bRaw), 8),
635
+ c_values: key,
636
  mask: Array(keyLen).fill(1),
637
+ candidates:[], step_count: 0, axl_source: axl,
638
  metadata: {
639
  description: `VigenΓ¨re ${keyLen}-char key=[${key}]`,
640
  units: "character_code_sum",
 
647
  }
648
 
649
  function synthAffineSamples(n) {
650
+ const VALID_A =[1,3,5,7,9,11,15,17,19,21,23,25];
651
  const INV_A_MAP = {1:1,3:9,5:21,7:15,9:3,11:19,15:7,17:23,19:11,21:5,23:17,25:25};
652
+ const samples =[];
653
  for (let i = 0; i < n; i++) {
654
  const aIdx = randint(0,11);
655
  const a = VALID_A[aIdx];
 
660
  const verify = ((aInv*(cipher-b))%26+26)%26;
661
  if (verify !== p) continue;
662
 
663
+ const axl =[
664
  `SCOPE modular_arithmetic [level: 0]`,
665
  ` ASSUME integer EXISTS`,
666
  ` TRANSFORM modular_multiply_add`,
 
680
  ` ASSUME modular_arithmetic SCOPE HOLDS`,
681
  ` ENTITY affine_key`,
682
  ` FIELD a: INTEGER DISCRETE VALUES {1,3,5,7,9,11,15,17,19,21,23,25}`,
683
+ ` FIELD b: INTEGER BOUND[0, 25]`,
684
+ ` FIELD a_idx: INTEGER BOUND[0, 11]`,
685
  ` FIELD a_norm: REAL BOUND [0, 1]`,
686
  ` FIELD b_norm: REAL BOUND [0, 1]`,
687
  ` DERIVES a FROM a_idx BY lookup_valid_a`,
 
690
  ` BOUND a COPRIME_TO 26`,
691
  ` END ENTITY`,
692
  ` ENTITY affine_transform_result`,
693
+ ` FIELD plaintext: INTEGER BOUND[0, 25] EQUALS ${p}`,
694
  ` FIELD ciphertext: INTEGER BOUND [0, 25]`,
695
  ` DERIVES ciphertext FROM {affine_key.a, plaintext, affine_key.b} BY modular_multiply_add`,
 
696
  ` END ENTITY`,
697
  ` ENTITY affine_inverse`,
698
  ` FIELD a_inv: INTEGER EQUALS ${aInv}`,
699
  ` FIELD recovery: INTEGER`,
700
  ` DERIVES recovery FROM {a_inv, ciphertext, b} BY modular_multiply_add`,
 
701
  ` END ENTITY`,
702
  ` CONTRADICT invertible WITH non_coprime_a`,
703
  ` AT SCOPE affine_cipher`,
 
717
  samples.push({
718
  id: randomUUID(), domain: "cryptography", subdomain: "affine",
719
  sense: "EQUAL", n_vars: 2,
720
+ vars_text: "VARS c0 IN [0 11] c1 IN[0 25]",
721
  expr_text: `EXPR AFFINE a=${a}(idx=${aIdx}) b=${b} plain=${p} cipher=${cipher}`,
722
  sense_text: "SENSE EQUAL",
723
  b_raw: fmt(cipher), b_norm: fmt(safeNorm(cipher), 8),
724
+ c_values: [aIdx, b],
725
+ mask: [1,1], candidates:[], step_count: 0, axl_source: axl,
726
  metadata: {
727
  description: `Affine a=${a} b=${b} plain=${p} β†’ cipher=${cipher}`,
728
  units: "character_code", difficulty: "hard",
 
736
 
737
  // ── OPTIMIZATION (deep AXL, not just a label) ─────────────────────────────────
738
  function synthOptimizationSamples(n) {
739
+ const samples =[];
740
  for (let i = 0; i < n; i++) {
741
  const sense = randchoice(["MINIMIZE","MAXIMIZE"]);
742
  const nVars = randint(2,6);
 
747
  const bRaw = cVals.reduce((acc,v,j)=>acc+v*coeffs[j],0);
748
  const exprStr = coeffs.map((c,j)=>`${c.toFixed(3)}*c${j}`).join(" + ");
749
 
750
+ const axl =[
751
  `SCOPE constraint_primitives [level: 0]`,
752
  ` ASSUME variable EXISTS`,
753
  ` ASSUME variable BOUND [0, 1]`,
 
794
  id: randomUUID(), domain: "optimization",
795
  subdomain: `linear_${sense.toLowerCase()}_${nVars}var`,
796
  sense, n_vars: nVars,
797
+ vars_text: `VARS ${Array.from({length:nVars},(_,j)=>`c${j} IN[0 1]`).join(" ")}`,
798
  expr_text: `EXPR ${exprStr}`,
799
  sense_text: `SENSE ${sense}`,
800
  b_raw: fmt(bRaw), b_norm: fmt(safeNorm(bRaw), 8),
801
  c_values: cVals.map(v=>fmt(v)),
802
  mask: Array(nVars).fill(1),
803
+ candidates:[], step_count: 0, axl_source: axl,
804
  metadata: {
805
  description: `Linear ${sense.toLowerCase()} over ${nVars} variables`,
806
  units: "objective", difficulty: "easy",
 
825
 
826
  // ── FOCUS TRACKER ─────────────────────────────────────────────────────────────
827
  const tracker = {
828
+ recent:[], counts: {}, total: 0,
829
  record(domain) {
830
  this.recent.push(domain);
831
  if (this.recent.length > 100) this.recent.shift();
 
838
  };
839
 
840
  // ── DATASET STATE ─────────────────────────────────────────────────────────────
841
+ let dataset =[];
842
  function loadDataset() {
843
  if (fs.existsSync(DATASET_PATH)) {
844
  dataset = JSON.parse(fs.readFileSync(DATASET_PATH,"utf8"));
 
853
  // ── BEDROCK CLIENT ────────────────────────────────────────────────────────────
854
  const bedrock = new BedrockRuntimeClient({ region: AWS_REGION });
855
 
 
856
  const AXL_SPEC = `
857
  # AXL β€” Abstraction Exchange Language
858
  ### A Constraint-First, Bidirectionally Navigable Abstraction Language
 
995
  configuration of unknowns is consistent with it.
996
 
997
  OBSERVE <field | entity | state> EQUALS <value>
998
+ OBSERVE <field> WITHIN[<min>, <max>]
999
  OBSERVE <pattern> IN <output>
1000
 
1001
  ---
 
1184
  END ENTITY
1185
 
1186
  ENTITY gluon
1187
+ FIELD charge: BOUND[0, 0] CONSERVES
1188
  FIELD color: SYMBOLIC # carries color charge
1189
  TENDS quark_binding MAX # gluons maximize binding
1190
  END ENTITY
 
1223
  END SCOPE
1224
 
1225
 
1226
+ SCOPE nucleus[level: 2]
1227
 
1228
  ASSUME hadron SCOPE HOLDS
1229
 
 
1262
  ASSUME nucleus SCOPE HOLDS
1263
 
1264
  ENTITY electron
1265
+ FIELD charge: BOUND[-1, -1] CONSERVES
1266
  FIELD mass: BOUND[9.109e-31, 9.109e-31] CONSERVES
1267
  FIELD spin: DISCRETE VALUES {-0.5, 0.5}
1268
  FIELD orbital: DISCRETE VALUES {s, p, d, f}
 
1376
  END SCOPE
1377
 
1378
 
1379
+ SCOPE block_header[level: 2]
1380
 
1381
  ASSUME sha256_internals SCOPE HOLDS
1382
 
 
1386
  FIELD merkle_root: bit_array BOUND length EQUALS 256 # GIVEN, fixed
1387
  FIELD timestamp: INTEGER # GIVEN, approximately fixed
1388
  FIELD bits: INTEGER # GIVEN, encodes target
1389
+ FIELD nonce: INTEGER BOUND[0, 4294967295] # UNKNOWN β€” 32 bits of freedom
1390
  END ENTITY
1391
 
1392
  DERIVE target
 
1750
  3. b_raw must be a computed finite float matching the AXL program's logic.
1751
  4. c_values must be in RAW domain units matching the declared bounds in vars_text.
1752
  DO NOT pre-normalize to [0,1] β€” the pipeline does that. Example: if
1753
+ vars_text says "VARS c0 IN [200 800]" then c_values should be like[650, 210].
1754
  5. Every vars_text MUST start with the word VARS.
1755
  6. Every sample must use a DIFFERENT domain or structural pattern.
1756
  7. Vary: sense (EQUAL/MINIMIZE/MAXIMIZE/SELECT/TEND), n_vars (1-${maxVars}),
 
1769
  "subdomain": "<specific topic>",
1770
  "sense": "<EQUAL|MINIMIZE|MAXIMIZE|SELECT|TEND>",
1771
  "n_vars": <integer>,
1772
+ "vars_text": "VARS c0 IN[lo hi] c1 IN [lo hi] ...",
1773
  "expr_text": "EXPR <description>",
1774
  "sense_text": "SENSE <EQUAL|MINIMIZE|MAXIMIZE|SELECT|TEND>",
1775
  "b_raw": <float>,
1776
  "b_norm": <sign(b)*log(1+|b|)/30>,
1777
+ "c_values":[<raw domain values matching bounds>],
1778
  "mask": [1,1,...],
1779
+ "candidates":[],
1780
  "step_count": <integer>,
1781
  "axl_source": "<full multi-scope AXL program as single string>",
1782
  "metadata": {
 
1811
  const raw = JSON.parse(Buffer.from(res.body).toString("utf8"));
1812
  const text = raw.content[0].text;
1813
  log(`Bedrock call ${((Date.now()-t0)/1000).toFixed(1)}s β€” ${text.length} chars`);
1814
+ const tokenUsage = raw.usage ? (raw.usage.input_tokens + raw.usage.output_tokens) : 0;
1815
  console.log(tokenUsage)
1816
  return text;
1817
  }
 
1824
  if (t.endsWith("```")) t = t.slice(0,-3);
1825
  t = t.trim();
1826
  const start = t.indexOf("["), end = t.lastIndexOf("]");
1827
+ if (start === -1 || end === -1) return[];
1828
  try {
1829
  return JSON.parse(t.slice(start, end+1));
1830
  } catch(e) {
1831
  log(`JSON parse error: ${e.message} β€” attempting salvage`, "WARN");
1832
+ const saved =[];
1833
  let depth = 0, buf = "", inObj = false;
1834
  for (const ch of t.slice(start+1, end)) {
1835
  if (ch === "{") { depth++; inObj = true; }
 
1849
 
1850
  // ── EXPRESS APP ───────────────────────────────────────────────────────────────
1851
  const app = express();
1852
+ app.use(cors());
1853
  app.use(express.json());
1854
 
1855
  app.get("/status", (_, res) => res.json({
 
1863
  app.get("/domains", (_, res) => res.json(tracker.stats()));
1864
 
1865
  app.post("/generate", async (req, res) => {
1866
+ const n = parseInt(req.query.n ?? req.body.n ?? "50");
1867
+ const rps = Math.min(parseFloat(req.query.rps ?? req.body.rps ?? DEFAULT_RPS.toString()), MAX_RPS);
1868
+ const syntheticFraction = parseFloat(req.query.synthetic_fraction ?? req.body.synthetic_fraction ?? "0.4");
1869
+ const maxVars = parseInt(req.query.max_vars ?? req.body.max_vars ?? "20");
1870
 
1871
  log(`Generation request: n=${n} rps=${rps} synthetic=${(syntheticFraction*100).toFixed(0)}%`, "HEAD");
1872
 
1873
+ const generated =[];
1874
  let errors = 0;
1875
 
1876
  // ── SYNTHETIC BATCH ──
 
1878
  if (nSynthetic > 0) {
1879
  const gens = Object.values(SYNTHETIC_GENERATORS);
1880
  const perGen = Math.max(1, Math.ceil(nSynthetic / gens.length));
1881
+ for (const[name, genFn] of Object.entries(SYNTHETIC_GENERATORS)) {
1882
  for (const raw of genFn(perGen)) {
1883
  if (!validateSample(raw)) { errors++; continue; }
1884
  const norm = normalizeSample(raw);
 
1949
 
1950
  app.post("/dataset/clear", (_, res) => {
1951
  const count = dataset.length;
1952
+ dataset =[];
1953
  if (fs.existsSync(DATASET_PATH)) fs.unlinkSync(DATASET_PATH);
1954
  log(`Cleared ${count} samples`, "OK");
1955
  res.json({ cleared: count });
 
1963
 
1964
  // ── STARTUP ───────────────────────────────────────────────────────────────────
1965
  loadDataset();
1966
+ app.listen(PORT, '0.0.0.0', () => {
1967
  log(`AXL Dataset Server listening on :${PORT}`, "OK");
1968
  log(`Model: ${BEDROCK_MODEL}`);
1969
  log(`Dataset: ${DATASET_PATH}`);
1970
  log(`RPS: ${DEFAULT_RPS} default / ${MAX_RPS} max`);
 
 
 
1971
  });