Skip to content

feat(quantum-alignment): Qiskit suite + Layer 101 browser-native sibling#22

Open
slavazeph-coder wants to merge 3 commits into
mainfrom
claude/quantum-alignment-tests-lv0JM
Open

feat(quantum-alignment): Qiskit suite + Layer 101 browser-native sibling#22
slavazeph-coder wants to merge 3 commits into
mainfrom
claude/quantum-alignment-tests-lv0JM

Conversation

@slavazeph-coder

@slavazeph-coder slavazeph-coder commented Apr 26, 2026

Copy link
Copy Markdown
Owner

Summary

This PR now ships both halves of the quantum-alignment work:

Half 1 — Offline Qiskit suite (quantum_alignment/)

A self-contained Qiskit harness that probes the physical meaning of "alignment" in quantum computing — phase coherence, observation collapse, and decoherence — across three execution modes.

  • Experiment 1 — Phase alignment / interference: |0⟩ → H → RZ(θ) → H → Measure swept over θ ∈ {0, π/8, π/4, π/2, 3π/4, π}. Compared against the closed-form ideal p(0) = cos²(θ/2).
  • Experiment 2 — Observation collapse: H · H vs H · Measure · H · Measure. Mid-circuit measurement collapses the superposition and pushes final readout to ~50/50. Gracefully degrades on backends that do not support mid-circuit measurement.
  • Experiment 3 — Decoherence vs depth: |0⟩ → H → (X X)ⁿ → H → Measure with n ∈ {0, 1, 2, 4, 8, 16, 32, 64}. Each X X is logical identity, so any drift away from p(0) = 1 is purely noise.

Three modes:

  • --mode idealAerSimulator (no token, no network)
  • --mode noisyAerSimulator.from_backend(GenericBackendV2(...)) (no token; uses qiskit core's fake backend)
  • --mode real — real IBM hardware via qiskit-ibm-runtime SamplerV2. Lazy-imported. Reads IBM_QUANTUM_TOKEN from env only — never logged, never written to disk.

Outputs: results.csv, phase_alignment_plot.png, noise_depth_plot.png, report.md.

Half 2 — Browser-native BrainSNN layer (Layer 101 — Quantum Coherence Lab)

The original task asked for "browser-native first, no backend, simulate locally in JavaScript" — that part wasn't built in the first commit. This commit adds it:

  • brainsnn-r3f-app/src/utils/quantumCoherence.js — complex helpers (complex / addComplex / mulComplex / abs2 / normalizeState), gates (applyH / applyX / applyZ / applyRZ), measurement (measureDistribution / sampleShots), three experiments shaped to mirror the Qiskit circuits (runPhaseExperiment / runObservationExperiment / runDecoherenceExperiment), simple dephasing + bit-flip noise, coherenceScore, and mapQuantumToBrainState.
  • brainsnn-r3f-app/src/components/QuantumCoherencePanel.jsx — θ slider (0 → π), shots picker (256 / 1024 / 4096), noise slider, X·X depth slider, observe-midway toggle, Scientific / Metaphor mode toggle, P(0) / P(1) bars, coherence score 0–100, plain-English explanation, and an H → RZ(θ) → H → M circuit visualization.
  • Brain mapping: PFC↑ coherence · AMY↑ noise · THL↑ routing · HPC↑ survival · BG↑ dominance · CBL↑ correction · CTX↑ complexity.
  • Wired into App.jsx; registered in layerCatalog.js as L101 with a new experimental group.
  • 18 unit tests via Node's built-in node:test runner — npm run test:quantum. No new dev deps.
  • README cross-references the Qiskit suite as the hardware-grade offline path. No vendor API keys are added to the frontend — IBM tokens stay in the Python suite.

Both halves explicitly disclaim literal multiverse theory, consciousness collapse, Planck foam, and spiritual-portal claims. Those are framing metaphors only.

Test plan

Qiskit suite:

  • pip install -r quantum_alignment/requirements.txt resolves cleanly
  • python quantum_alignment_tests.py --mode ideal --shots 4096 writes all 4 artifacts
  • python quantum_alignment_tests.py --mode noisy --shots 4096 shows expected fringes / 50-50 collapse / depth drift
  • No IBM_QUANTUM_TOKEN required for ideal/noisy; token only read from env
  • Real-hardware mode (requires a live IBM Quantum account)

BrainSNN layer:

  • npm install succeeds
  • npm run build succeeds (Vite, ~9s)
  • npm run test:quantum — 18/18 passing
  • Open the app, scroll to the Quantum Coherence Lab panel:
    • θ=0 → P(0) bar at ~100%; θ=π → P(1) at ~100%; θ=π/2 → ~50/50
    • Noise slider up → bars approach 50/50, score drops
    • Observe-midway toggle → ~50/50, score < 40
    • X·X depth up → score decays even at noise=0
    • Mode: Scientific ↔ Metaphor flips the explanation
    • "Apply to brain" nudges the 7 regions and toasts

https://claude.ai/code/session_01VYArf8MTS6QdhmswtqNPox


Generated by Claude Code

claude added 2 commits April 26, 2026 16:14
Adds quantum_alignment/ with a single-file Qiskit harness that runs three
experiments (H-RZ-H interference sweep, mid-circuit measurement vs HH,
deepening identity X-X chains) across three execution modes (ideal Aer,
noisy Aer from a synthetic fake backend, and real IBM hardware via
qiskit-ibm-runtime when IBM_QUANTUM_TOKEN is set). Outputs CSV, two
matplotlib plots, and a plain-English report. README documents safe token
handling and explicitly frames the suite as a test of quantum phase
coherence/interference/noise -- not literal multiverse theory.
…e Qiskit suite

Completes the in-browser side of the quantum-alignment work that landed in
6325d38 (which shipped only the Python/Qiskit harness under
quantum_alignment/). The original task asked for "browser-native first, no
backend, simulate locally in JavaScript" — that part wasn't built. This adds:

- src/utils/quantumCoherence.js: complex/H/X/Z/RZ helpers, three
  experiments (phase / observation / decoherence) shaped to mirror the
  Qiskit circuits in quantum_alignment/quantum_alignment_tests.py, simple
  dephasing + bit-flip noise, coherenceScore, and mapQuantumToBrainState
  (PFC↑ coherence · AMY↑ noise · THL↑ routing · HPC↑ survival ·
  BG↑ dominance · CBL↑ correction · CTX↑ complexity).
- src/components/QuantumCoherencePanel.jsx: theta / shots / noise /
  depth / observe-midway controls, scientific ↔ metaphor mode toggle,
  P(0)/P(1) bars, coherence score 0–100, plain-English explanation,
  circuit-row visualization. Cross-links the Qiskit suite as the
  hardware-grade offline path.
- App.jsx: wired with onApplyToBrain that nudges the 7 region levels.
- layerCatalog: registered as L101 with new "experimental" group.
- Tests: 18 cases via node:test (theta=0/π, observation, decoherence,
  noise/depth scaling, brain mapping). `npm run test:quantum`.
- Docs: README section explicitly disclaims literal multiverse /
  consciousness / Planck / spiritual claims; cross-references the Qiskit
  suite for hardware runs. No vendor API keys in the frontend — IBM
  tokens stay in the Python suite (IBM_QUANTUM_TOKEN at runtime).

npm install + npm run build pass.

https://claude.ai/code/session_01VYArf8MTS6QdhmswtqNPox
@slavazeph-coder slavazeph-coder changed the title feat(quantum_alignment): Qiskit suite for phase / collapse / decoherence feat(quantum-alignment): Qiskit suite + Layer 101 browser-native sibling Apr 27, 2026
@slavazeph-coder slavazeph-coder marked this pull request as ready for review April 27, 2026 13:06

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 8cb1b5e49c

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +137 to +138
state[0],
complex(state[1].re, state[1].im * k),

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Model dephasing on both coherence components

This dephasing step only damps state[1].im, so states with purely real coherence are unaffected even at high noise. In runPhaseExperiment, the common θ=0 branch reaches [1/√2, 1/√2] before dephasing, making this function a no-op and preventing the expected interference damping toward 50/50. That yields systematically wrong phase/noise behavior for part of the sweep.

Useful? React with 👍 / 👎.

Comment on lines +248 to +250
let state = [complex(1, 0), complex(0, 0)];
for (let i = 0; i < pairs; i += 1) {
state = applyX(state);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Add missing Hadamards in decoherence experiment

The function claims to mirror |0⟩ → H → (X X)^n → H → M, but it initializes |0⟩ and immediately enters the X X loop with no surrounding Hadamards. Without those H gates, the state stays in the computational basis, so the dephasing term cannot act on superposition and the experiment no longer matches the intended circuit semantics or the Qiskit sibling.

Useful? React with 👍 / 👎.

Comment on lines +110 to +112
const noisy = runDecoherenceExperiment({ xxPairs: 6, shots: SHOTS, noise: 0.7 });
assert.ok(
noisy.distribution[0] < ideal.distribution[0],

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Make decoherence noise test deterministic

This assertion compares a single noisy run against ideal even though runDecoherenceExperiment is stochastic (Math.random), so it intermittently fails when noisy and ideal both return P(0)=1. I reproduced this failure by rerunning the test several times. Averaging multiple trials or controlling randomness is needed to avoid CI flakiness.

Useful? React with 👍 / 👎.

Completes the quantum cluster on top of L101. All three layers are
browser-native, no backend, no vendor API keys.

Layer 102 — Bell Pair Lab
- bellPair.js: 2-qubit state (4 amplitudes), H/X/RY/RZ-on-qubit, CNOT,
  joint distribution + sampling, signed correlationStrength.
- runBellPairExperiment: |00⟩ → H ⊗ I → CNOT(0,1) → optional RY(θ) on
  qubit 0 → joint measurement. Depolarizing noise mixes the pure
  distribution with uniform [0.25 × 4] by weight `noise`.
- mapBellToBrainState: HPC↑ correlation, PFC↑ |correlation|, CTX↑ shots,
  AMY↑ noise, THL↑ rotation, BG↑ dominance, CBL↑ noise·(1-|corr|).
- BellPairPanel: RY-θ slider, noise slider, shots picker, joint bars
  for |00⟩|01⟩|10⟩|11⟩, signed correlation strength card, ASCII circuit
  diagram, Scientific ↔ Metaphor mode, Apply-to-brain.
- 12 tests covering Hadamard / CNOT / Bell construction / rotation
  breakdown / noise damping / brain mapping bounds.

Layer 103 — Quantum Sweep
- quantumSweep.js: runSweep(kind: 'phase' | 'noise' | 'depth'), CSV
  serialization with the same column shape as
  quantum_alignment/results/results.csv, sweepSummary stats.
- QuantumSweepPanel: kind picker, steps / shots / fixed-noise / fixed-θ /
  max-depth controls, inline SVG line chart of P(0) / P(1) vs the ideal
  curve, "Download CSV" button.
- 9 tests covering sweep correctness, CSV escaping, summary math.

Layer 104 — Quantum Glossary
- QuantumGlossaryPanel: searchable reference card (23 terms across
  states / gates / processes / noise / metrics) with plain-language,
  math, and metaphor columns side-by-side. Complements the Metaphor
  toggle in L101 and L102.

L101 noise model
- Replaced random per-gate bit-flips with a single depolarizing-style
  distribution mix (matches L102 / L103). This makes runs deterministic
  in expectation, fixes a flaky decoherence test, and aligns with the
  "noise = mix toward uniform" reading the panel and glossary teach.

Wiring
- App.jsx: 3 new ErrorBoundary blocks, L102 wired with onApplyToBrain.
- layerCatalog.js: L102 / L103 / L104 registered under the experimental
  group.
- README.md: file-map rows for 102/103/104; Quantum Coherence Lab
  section gains a "cluster siblings" subsection summarizing all three.
- package.json: test:quantum runs all three test files.

39/39 tests pass (`npm run test:quantum`). `npm run build` ✓ — index
bundle 648 → 676 KB (+27 KB / +7 KB gzipped) for three new layers.

https://claude.ai/code/session_01VYArf8MTS6QdhmswtqNPox

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 3121c1a720

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +186 to +187
depth: Math.max(1, depth + 1),
observedMidway: observeMidway,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Exclude depth penalty when midway observation is active

When observeMidway is enabled, the panel runs runObservationExperiment (which ignores depth), but this score calculation still applies depth + 1, so users can lower coherence just by moving the depth slider without changing the executed circuit. That makes the reported coherence inconsistent with the actual experiment and can show severe false degradation after toggling observation on with a previously high depth.

Useful? React with 👍 / 👎.

// depth-driven decoherence growth.
const ideal = [1, 0];
const perPair = Math.max(0, Math.min(1, noise));
const effective = pairs === 0 ? perPair : 1 - Math.pow(1 - perPair, pairs);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Make zero-depth noise lower than one X·X pair

This formula makes xxPairs=0 and xxPairs=1 produce the same effective noise (perPair) whenever noise is nonzero, so adding the first X·X pair has no impact on the decoherence curve. That flattens the early depth sweep and conflicts with the documented per-pair compounding model, where each additional pair should increase degradation.

Useful? React with 👍 / 👎.

slavazeph-coder pushed a commit that referenced this pull request May 2, 2026
Roll the homepage repositioning across the in-product app, build the
Brand Risk Scorecard layer, and replace the homepage gallery
placeholders with real scan illustrations.

brainsnn-r3f-app
- index.html title + og + twitter meta now lead with "affective-
  intelligence engine" and the four-outcome positioning sentence.
- OnboardingWalkthrough STEPS rewritten — step 1 leads with the
  positioning sentence, the Cognitive Firewall is framed as "the
  engine," the new Brand Risk Scorecard gets its own step, and the
  ordering puts the engine before the visualization layer.
- MilestonePanel intro paragraph updated to the new framing.
- Layer 106 (Brand Risk Scorecard) added to layerCatalog and mounted
  in App.jsx behind an ErrorBoundary, after the Milestone panel.

L106 — Brand Risk Scorecard
- src/utils/brandRisk.js: splitItems / scoreItem / computeBrandRisk /
  brandBriefMarkdown. Pure functions, no side effects. Aggregates
  Cognitive Firewall (L4) + Propaganda Templates (L39) + Ad
  Transparency archetypes (L48) into a single 0–100 score with a
  4-tier classification (Clean / Watch / At risk / Critical).
- src/components/BrandRiskPanel.jsx: brand input + items textarea +
  load-sample helper, headline score card, dominant archetypes,
  most-fired templates, top 5 worst items, copy-brief-as-Markdown.
- Score formula: 60% mean pressure + 25% peak pressure + 15% high-
  risk archetype share. High-risk archetypes: abusive-domestic,
  phishing, conspiracy-hook, political-attack, cult-recruitment.
- Number 106 picked to avoid colliding with the open L101 PRs (#22,
  #24, #25 — see PR #27 description for the suggested resolution).

ui/brainsnn-site gallery
- public/scan-fear-cascade.svg, scan-certainty-theater.svg, and
  scan-affective-trajectory.svg — three hand-rolled SVG cards that
  match the new gallery copy. 4-dim score bars, brain proxy with the
  appropriate region glowing, evidence chips.
- GALLERY_ITEMS now carries an `image` field; App.jsx reads it with
  the demo-placeholder.svg as a fallback.

Builds
- npm run build --prefix ui/brainsnn-site — 624 modules, 8.03s, clean.
- npm run build --prefix brainsnn-r3f-app — 912 modules, 6.19s, clean.

https://claude.ai/code/session_brainsnn-ui-build-28ebr
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants