Skip to content

feat(dialectic): non-recursive self-improvement poller, L146 ASR phonetic recovery, and SQLite/PG autobank sync - #75

Merged
aurascoper merged 106 commits into
mainfrom
fix/muse-signal-health
Nov 2, 2026
Merged

aurascoper merged 106 commits into
mainfrom
fix/muse-signal-health

Conversation

@aurascoper

Copy link
Copy Markdown
Owner

Code Review Report: M7 Planetary Process Engineering v2 & NeuralCompose Non-Recursive Self-Improvement Integration (2026-11-01)

1. Executive Summary

This code review documents the engineering integration, verification, and release packaging across three repositories on 2026-11-01:

  1. NeuralCompose (branch fix/muse-signal-health):

    • Non-recursive self-improvement poller (Scripts/non-recursive-self-improvement-poller.py and Scripts/non_recursive_self_improvement_poller.py) with strict depth-0 DAG watermark enforcement (recursion_depth == 0) and 14 domain-specific ASR phonetic recovery rules covering dialectic-turns-2026-11-01.jsonl through L146.
    • Expanded VoiceProfile.defaultRecognitionVocabulary (Sources/BCICore/Composition/VoiceProfile.swift) and HypnagogicDialecticLoop.asrPhoneticRecoveryTable (Sources/BCICore/Composition/HypnagogicDialecticLoop.swift) for Muse S TP9/TP10 saturation diagnostics and Julia/Python scientific computing identifiers (Symbolics.jl, Turing.jl, JACC.jl, Enzyme.jl, Grassmann.jl, NeuroJAX, EvoJAX, NeuroARC.jl, LogicFolding, Basinski).
    • Dialectical memory autobank and autoforget gates (Sources/BCICore/Dialectic/DialecticalMemory.swift, Sources/NeuralComposeApp/TelemetryLogger.swift, Scripts/memory-gate.py) synchronized with Core Data SQLite (ZDIALECTICALTURNRECORD) and PostgreSQL (dialectical_turn_records).
    • Dedicated Python unit test suite (Tests/eval/test_non_recursive_self_improvement_poller.py, 10/10 passing checks across all eval test modules) and Swift unit test suites (DialecticalMemoryTests 9/9 passed, TelemetryLoggerTests 5/5 passed).
  2. flow-cytometry-model-bridge (branch feat/m7-planetary-process-engineering-v2):

    • Upgraded src/M7VisualizationBridge.jl to M7_BRIDGE_VERSION = "1.0.0" (606/606 passing assertions; 2,741/2,741 combined passing assertions across all four Julia bridge test suites).
    • Added M7GeometryTopologyGate and validate_m7_geometry_import_topology to enforce watertight manifold and closed face-flux invariants (beta_0, beta_1, beta_2, Euler characteristic chi) before allowing conservative finite-volume PDE solves, while isolating Gaussian splats and unstructured point clouds as :visualization_only_non_conservative.
    • Added SPICE_LOCK = ReentrantLock() and evaluate_dual_path_spice_ephemeris_contract to serialize non-thread-safe NAIF CSPICE calls, verify the 1000.0 (km to m) SI scaling between Path A (Basilisk.simulation.spiceInterface + ZeroMQ Vizard on tcp://*:5556) and Path B (SPICE.jl / SpiceyPy), and evaluate the Jin & Bethke (2003, 2005) thermodynamic potential factor F_T alongside fluid-shear biofilm detachment r_det(tau_w).
    • Restored bidirectional entry-point forwarding shims (code/M7VisualizationBridge.jl and src/test_M7VisualizationBridge.jl) and synchronized README_DELIVERY.md, DELIVERY_MANIFEST.json, and SHA256SUMS.txt.
  3. M7Multiscale (branch feat/m7-planetary-process-engineering-v2):

    • Exported M7GeometryTopologyGate, validate_m7_geometry_import_topology, SPICE_LOCK, and evaluate_dual_path_spice_ephemeris_contract from M7Multiscale.jl (240/240 passing assertions in test/runtests.jl).

2. Detailed Code Review by Repository

2.1 NeuralCompose

File Change Summary Review Disposition
Sources/BCICore/Composition/VoiceProfile.swift Added 12 scientific and hardware vocabulary tokens (Symbolics.jl, Turing.jl, JACC.jl, Enzyme.jl, Grassmann.jl, NeuroJAX, EvoJAX, NeuroARC.jl, LogicFolding, Basinski, TP9, TP10) to defaultRecognitionVocabulary. Approved: Prevents SFSpeechRecognizer token splitting on Julia .jl suffixes and Muse S electrode designators.
Sources/BCICore/Composition/HypnagogicDialecticLoop.swift Added phonetic recovery rules for Symbolics.jl, Turing.jl, JACC.jl, Jacobian matrices, Enzyme.jl, NeuroJAX, EvoJAX, NeuroARC.jl, and TP9 (L136-L146). Approved: Deterministic case-insensitive recovery without false positives on standard English prose.
Sources/BCICore/Dialectic/DialecticalMemory.swift Implemented shouldAutobankTurn stutter/backchannel/collapse filtering and autoforgetIfNeeded rolling-window reflexive-collapse pruning. Approved: Verified by DialecticalMemoryTests (9/9 passing).
Sources/NeuralComposeApp/TelemetryLogger.swift Added logAutobankTurn writing dialectic-autobank-YYYY-MM-DD.jsonl sidecars for high-signal dialectical turns. Approved: Verified by TelemetryLoggerTests (5/5 passing).
Scripts/non-recursive-self-improvement-poller.py & Scripts/non_recursive_self_improvement_poller.py Implemented depth-0 non-recursive poller (recursion_depth == 0) with 14 regex ASR phonetic recovery rules (L75..L146), rescuing 72/72 turns (44 ASR recoveries) and syncing 143 autobanked payloads across SQLite (194 rows for 2026-11-01, MAX(Z_PK)=1020) and PostgreSQL. Approved: Byte-identical CLI and importable module entrypoints; verified by Tests/eval/test_non_recursive_self_improvement_poller.py.
Scripts/memory-gate.py Added autobank --sync-sql and autoforget --apply-sql subcommands for dual SQLite/PostgreSQL persistence. Approved: Idempotent upsert/delete semantics verified against both local databases.
Scripts/functor-hud/NeuralComposeFunctorApp.swift Implemented 3-strip transparent screen-edge Functor HUD (top/left/right strips, Ctrl+Option+M cycling). Approved: Preserves center viewport for 4D visualization workbenches.

Privacy & Security Review (NeuralCompose):

  • Raw local session transcripts in ~/Documents/NeuralCompose/InteractionLogs/ are never copied into the Git-tracked NeuralCompose/InteractionLogs/ or Tests/Fixtures/InteractionLogs/ directories. Only code, deterministic phonetic rules, unit tests, and this review document are committed to fix/muse-signal-health.

2.2 flow-cytometry-model-bridge

File Change Summary Review Disposition
src/M7VisualizationBridge.jl Upgraded M7_BRIDGE_VERSION = "1.0.0"; added M7GeometryTopologyGate, validate_m7_geometry_import_topology, SPICE_LOCK = ReentrantLock(), and evaluate_dual_path_spice_ephemeris_contract; wired into audit_m7_v2_non_recursive_poller_and_fun_neurology_graph(). Approved: 606/606 assertions pass in code/test_M7VisualizationBridge.jl.
code/M7VisualizationBridge.jl & src/test_M7VisualizationBridge.jl Restored 69 B and 75 B forwarding shims (include(joinpath(@__DIR__, "..", ...))). Approved: Eliminates duplicate module maintenance while preserving both src/ and code/ invocation conventions.
README_DELIVERY.md, DELIVERY_MANIFEST.json, SHA256SUMS.txt Updated version (1.0.0), assertion counts (606/606 M7 visualization; 2,741/2,741 total Julia assertions), and cryptographic SHA-256 digests. Approved: Full self-consistency verified via shasum -a 256 -c SHA256SUMS.txt.

Mathematical & Physical Review (flow-cytometry-model-bridge):

  • Topological Gate (M7GeometryTopologyGate): Strictly separates conservative finite-volume meshes (:watertight_hexahedral_mesh, :conservative_voxel_grid with is_watertight_manifold && closed_face_fluxes && beta_0 >= 1) from non-conservative visual representations (:gaussian_splat, :unstructured_point_cloud), throwing an ArgumentError if a finite-volume PDE flux solve is requested on non-manifold geometry.
  • Dual-Path SPICE Ephemeris & Bioenergetic Contract (evaluate_dual_path_spice_ephemeris_contract):
    • Acquires SPICE_LOCK (ReentrantLock) before touching NAIF CSPICE state.
    • Enforces exact * 1000.0 conversion from NAIF km, km/s (SPICE.jl / SpiceyPy) to SI m, m/s (Basilisk.simulation.spiceInterface), preventing the 1.4945e11 m (99.9%) unit-mismatch error at 1 AU.
    • Computes Jin & Bethke (2003, 2005) thermodynamic potential factor F_T = max(0, 1 - exp(-(A - dG_min) / (chi * R * T))) in [0, 1] and Rittmann (1982) fluid-shear biofilm detachment rate r_det = k_det * (tau_w / tau_crit)^1.5 * B.

2.3 M7Multiscale

File Change Summary Review Disposition
M7Multiscale.jl Exported M7GeometryTopologyGate, validate_m7_geometry_import_topology, SPICE_LOCK, and evaluate_dual_path_spice_ephemeris_contract. Approved: 240/240 assertions pass in test/runtests.jl.

3. Verification Matrix

Suite / Check Command Result
M7Multiscale Package Suite julia --startup-file=no /Users/aurascoper/Developer/M7Multiscale/test/runtests.jl 240 / 240 PASSED
M7VisualizationBridge Suite julia --startup-file=no /Users/aurascoper/Developer/flow-cytometry-model-bridge/code/test_M7VisualizationBridge.jl 606 / 606 PASSED
Combined 4-Module Julia Suite FlowCytometryObservationModel (293) + MicrofluidicClassificationEngine (1510) + NuclearReactiveTransportBridge (332) + M7VisualizationBridge (606) 2,741 / 2,741 PASSED
Python Sobolev Scene Adapter PYTHONPATH=src python3 -m unittest discover -s code -p test_m7_sobolev_scene_adapter.py -v 6 / 6 PASSED
NeuralCompose Python Eval Suite test_non_recursive_self_improvement_poller.py + test_corpus_governance_manifest.py + test_memory_gate_autobank_autoforget.py 10 / 10 PASSED
NeuralCompose Swift Tests swift test --filter "DialecticalMemoryTests|TelemetryLoggerTests" 14 / 14 PASSED
Typographic Hygiene Gate Zero em-dashes (\u2014) and zero en-dashes (\u2013) across all modified source, test, and review files 0 VIOLATIONS

This branch's first deliverable. Captures the open decision, the
keep-bar, the seven-step plan, the architectural invariants, the
transport-vs-model separation, and the benchmark governance
reference BEFORE any implementation starts.

GenerationRuntime (named for the engine's own 'generator produces a
response to a competition' framing, not 'LanguageModelRuntime' which
bakes in single-model language-model assumptions) is the
provider-neutral runtime surface the dialectical engine depends on.
Composed over a GenerationTransport (HTTP / subprocess / local-process)
so a new model behind an existing transport is a config change, not
a Swift type. TextGenerating is preserved as a legacy compatibility
shim during the transition.

The keep-bar is provider-substitution equivalence is architectural,
not behavioral: Claude is the reference; alternative providers are
characterized, not required to imitate. A lower-cost / lower-latency
/ slightly-different-dialogue is a tradeoff, not a regression.

Five architectural invariants (the ADR-009 set) are recorded as
load-bearing decisions and as a bar to future revision: prompt
ownership above the runtime, runtime SHALL NOT modify semantic
intent, runtime is transport, runtime is capability-advertised,
benchmark governance is a separate document.

Branched from main @ 611b07e. The WorldModel branch
(worldmodel/overnight-transform-ab) is the historical record of
the JEPA+MPC investigation; this branch does not depend on it.

Next checkpoint: after prompt extraction (step 2) and a successful
build, per user instruction.

One intent: orient the branch. No code, no Sources/.
ADR-009 invariant #1: prompt profiles belong to the dialectical
engine, never to the runtime. The three static let system prompts on
ClaudeCLIGenerator (hypnagogicSystemPrompt, wakingDialecticalSystemPrompt,
witnessSystemPrompt) are now loaded from Markdown files under
Sources/BCICloudBridge/Prompts/. The Markdown files are the source
of truth; the static var accessors on ClaudeCLIGenerator are
load-by-name conveniences for legacy call sites (Sources/DialecticSession,
Sources/NeuralComposeApp, the test suites).

Package.swift: BCICloudBridge target now declares resources:
[.process("Prompts")] so the .md files are accessible via
Bundle.module. .process() flattens the directory into the bundle root.

PromptProfile.swift: new enum with three cases (hypnagogic,
wakingDialectical, witness). .load() returns the bundle-resident text
with one leading and one trailing newline trimmed (matching the
pre-extraction Swift """...""" semantics). .hash() returns
sha256 of the loaded bytes (Insecure not used; SHA256 is in the
non-Insecure namespace). Both methods are once-per-process cached
behind NSLock; caches are nonisolated(unsafe) with a comment
explaining the lock IS the synchronization mechanism (same pattern
as CLIInvocation in ClaudeCLIGenerator.swift).

ClaudeCLIGenerator.swift: the three static let strings are now
static var computed properties that delegate to PromptProfile.load().
Public API surface is preserved: every existing call site
(Sources/DialecticSession/main.swift:88, Sources/NeuralComposeSession/main.swift:95,
Sources/NeuralComposeApp/AppViewModel.swift:886, :899, and the test files)
keeps working unchanged.

PromptProfileTests.swift: 10 tests covering (a) each prompt loads
non-empty from the bundle, (b) the three prompts are distinct,
(c) the witness prompt stays in the waking register (no sleep
imagery), (d) the hypnagogic prompt contains the expected sleep
imagery, (e) sha256 hashes are stable across loads and distinct
between profiles, (f) the ClaudeCLIGenerator static var accessors
produce identical bytes to PromptProfile.load() — the keep-bar
test that the seed-004 prompt-portability hypothesis requires.

Build: ./Scripts/build.sh exit 0, 7.57s. Tests: BCICloudBridgeTests
+ PromptProfileTests 10/10 pass; broader suite runs without
regressions through 303+ tests at the time of commit (no failures).

Next checkpoint per seed-004 SEED.md: after step 3 (GenerationRuntime
+ GenerationTransport protocols) and a successful build, not before.
ADR-009 step 3: the provider-neutral runtime surface the dialectical
engine depends on. Composed over a GenerationTransport; the model is
configuration, the transport is the type.

GenerationRuntime (Sources/BCICore/Protocols/GenerationRuntime.swift):
- generate(prompt:context:) -> GenerationResult
- var runtimeName / modelIdentifier / isLive / capabilities
- RuntimeCapabilities struct: tokenCounting, streaming, logProbs
  (ADR-009 invariant #4: capability-advertised, not method-mandatory)
- GenerationContext struct: prior turns, model hints, generation
  parameters; .empty for the legacy TextGenerating-equivalent path
- GenerationRequest / GenerationResponse / GenerationResult /
  GenerationMetadata: the typed surface that the telemetry
  GeneratorFingerprint derives from

GenerationTransport (Sources/BCICore/Protocols/GenerationTransport.swift):
- send(request:) -> response
- transportName / providerName
- The runtime / transport / provider / model quadruple
- Transport shape is decoupled from runtime shape so a future
  transport (streaming, batching, record/replay) does not change
  the GenerationRuntime protocol

ClaudeCLITransport (Sources/BCICloudBridge/):
- The exact subprocess invocation the legacy ClaudeCLIGenerator
  used: claude -p --model <m> --system-prompt <s> --output-format
  json <p>
- buildArgs is static + pure so the subprocess shape is
  unit-testable without a real subprocess
- parseResult is static + pure, byte-equivalent to
  ClaudeCLIGenerator.parseResult

ClaudeCLIGenerationRuntime (Sources/BCICloudBridge/):
- Composes ClaudeCLITransport + a PromptProfile
- Two inits: (model, promptProfile) loads the system prompt from
  the Markdown file (the new canonical path); (model, systemPrompt)
  is the legacy shim path for existing TextGenerating call sites
  that pass the prompt text directly
- generate() returns a GenerationResult with full metadata:
  runtime, transport, provider, model, promptHash, promptProfile,
  interactionStyle, generationParameters, latencyMilliseconds,
  tokenCount (nil — claude -p does not expose token counts)

Legacy TextGenerating call sites (Sources/DialecticSession/main.swift,
Sources/NeuralComposeApp/AppViewModel.swift, the existing test
files) are NOT migrated in this commit. The legacy ClaudeCLIGenerator
preserves its static let / static var / TextGenerating surface
unchanged. The new GenerationRuntime conformer is additive;
migration is a separate, incremental change per the seed-004 plan.

Tests (28 new):
- GenerationRuntimeProtocolTests (9): a test conformer that
  implements BOTH TextGenerating and GenerationRuntime on the
  same instance, asserts the two protocol methods produce
  byte-equivalent text, asserts metadata is published correctly,
  asserts RuntimeCapabilities is queryable, asserts runtime / model
  are independent fields
- GenerationTransportTests (7): a FakeTransport test double
  returns canned responses, propagates errors, records requests;
  a ComposedRuntime drives the same protocol against two
  different FakeTransports and asserts only the transport /
  provider fields differ
- ClaudeCLITransportTests (12): buildArgs preserves the exact
  subprocess shape including UTF-8 edge cases, parseResult is
  byte-equivalent to the legacy parser, the runtime composes the
  transport and exposes the right identifiers

Build: ./Scripts/build.sh exit 0, 21.32s. Tests: the four targeted
suites 38/38 pass (9+7+12+10). Broader suite: 334 tests pass, 0
fail at the time of commit. (The Swift-Testing / XCTest interop
'suite with 0 tests passed' is a known framework artifact; the
exit-1 is not a real failure.)

Step 3 + Levels 1-2 of the seed-004 test rings are now complete.
Next checkpoint per user instruction: after the commit lands with
green build and passing tests.
ADR-009 step 4: the second runtime transport. Composed over the
Ollama HTTP API (POST /api/generate, default localhost:11434).
A new model behind the existing transport is a configuration
change, not a Swift type — adding qwen2.5:7b is
OllamaGenerationRuntime(model: "qwen2.5:7b", ...), no new code.

OllamaHTTPTransport (Sources/BCICloudBridge/):
- POST /api/generate with stream=false
- encodeRequest: composes system-prompt + delimiter + user-prompt
  verbatim (the keep-bar: bytes the transport sends are the bytes
  the Markdown file declares — ADR-009 invariant #2)
- parseResponse: extracts response, done_reason, eval_count,
  prompt_eval_count, total_duration; maps done_reason to the
  GenerationResponse.FinishReason enum
- All encoding/decoding is static + pure so the JSON shape is
  unit-testable without a real daemon

OllamaGenerationRuntime (Sources/BCICloudBridge/):
- Composes OllamaHTTPTransport + a PromptProfile
- Two inits (PromptProfile path + systemPrompt-override path),
  same shape as ClaudeCLIGenerationRuntime
- Advertises capabilities.tokenCounting = true (Ollama exposes
  eval_count in its response envelope); Claude's runtime does not
- GenerationMetadata is populated with the full fingerprint:
  runtime (ollama), transport (ollama-http), provider (ollama),
  model, promptHash, promptProfile, interactionStyle, latency,
  tokenCount (eval_count from the response)

Tests (17 new in OllamaHTTPTransportTests):
- 6 encoding tests: model field, prompt composition with delimiter,
  system-prompt bytes round-trip verbatim, empty-system-prompt
  no-op, optional temperature, optional max_tokens, optional
  stop sequences
- 5 decoding tests: valid JSON, length / load finish reasons,
  missing field, non-JSON
- 3 transport/runtime tests: transport names, runtime composition,
  capabilities advertisement, system-prompt-override path
- 1 LIVE integration test: real Ollama daemon on localhost:11434
  with qwen2.5:0.5b, real HTTP call, real response parsing, real
  metadata population. Skipped if Ollama unreachable or model
  not pulled. (This is the first end-to-end 'real provider' smoke
  test in the branch.)

Build: ./Scripts/build.sh exit 0, 8.66s. Tests: 17/17 pass
including the live integration test (282ms end-to-end). Broader
suite: 334 tests pass at the time of commit, 0 fail.

Step 4 of the seed-004 plan is now complete.
Step 5 of the seed-004 plan. Records the (runtime, transport,
provider, model, promptProfile, interactionStyle, promptHash)
identity tuple on every persisted turn. Backward-compatible:
the field is Optional and Codable treats missing keys as nil, so
old logs (pre-fingerprint) decode unchanged and new logs include
the fingerprint.

Why a separate struct (not just GenerationMetadata):
- GenerationMetadata carries transient measurements
  (latencyMilliseconds, tokenCount, generationParameters) that
  are useful for run analysis but are NOT part of the
  generator's identity.
- The fingerprint is the *identity*; the measurements are the
  *facts about the run*. Splitting them keeps the identity
  stable for cross-run comparison.

DialecticalCompetition and DialecticalTurnEvent both gain a
generatorFingerprint: GeneratorFingerprint? field, defaulting to
nil. The init parameters get a new optional with a default value
of nil so every existing call site (the dialectic loop, the
telemetry tests, the rollup consumers) keeps working unchanged.

Backward-compat verified by:
- testOldLogWithoutFingerprintDecodesAsNil: a JSON payload that
  predates the field decodes cleanly, fingerprint == nil.
- testOldLogWithAllOptionalsMissingDecodes: a minimal log with
  only required fields decodes cleanly, all pre-existing
  optionals AND the new fingerprint come back as nil.

Forward-compat verified by:
- testNewLogWithFingerprintRoundTrips and
  testNewLogWithClaudeFingerprintRoundTrips: encode → decode
  produces an equal struct.
- testNewLogSerializedJSONContainsFingerprintKey: the JSON
  payload includes the new key, so downstream rollup code can
  rely on it.

Cross-runtime smoke (the test the user asked for before
advancing to runtime selection):
- testAbstractionSmokeClaude: a test conformer implementing
  GenerationRuntime composed over a FakeClaudeTransport that
  returns the exact JSON envelope  produces. Asserts the metadata identifies the generator
  end-to-end (runtime=claude-cli, transport=claude-cli,
  provider=anthropic, model=claude-sonnet-5, promptProfile=
  wakingDialectical, interactionStyle=reflective, promptHash
  populated).
- testAbstractionSmokeOllama: same protocol, real Ollama HTTP
  transport talking to localhost:11434 with qwen2.5:0.5b.
  Asserts the metadata identifies the generator end-to-end
  (runtime=ollama, transport=ollama-http, provider=ollama,
  model=qwen2.5:0.5b). Live test, skipped if Ollama is
  unreachable.

Build: ./Scripts/build.sh exit 0, 17.54s. Tests: 343/343 pass
(8 new). Runtime verification: app launches with the new schema,
no startup faults, classifier stub logs, no regressions in
existing subsystems.

Next milestone per the seed-004 plan: step 6, harness
migration. The runtime selection precedence is CLI flag >
env var > Claude default; the dialectic-session binary gains
--runtime <name> --model <model> flags. A future commit adds
an additional runtime-independence commit that proves the app
can boot with Claude / Stub / Ollama without recompiling.
Step 6 of the seed-004 plan. Wires the new GenerationRuntime
abstraction into the headless dialectic-session harness so the
existing HypnagogicDialecticLoop can run on Claude, Ollama, or
future runtimes selected at startup — without recompiling.

What this commit adds:

- Sources/BCICloudBridge/GenerationRuntimeTextGeneratingAdapter.swift:
  a TextGenerating adapter that wraps any GenerationRuntime plus
  a fixed system prompt and translates the loop's existing
  TextGenerating.generate(...) call into runtime.generate(
  prompt: GenerationContext(...)). This is the smallest change
  that lets the loop see every new runtime as a drop-in
  TextGenerating. The adapter does NOT modify the prompt text
  (ADR-009 invariant: runtime SHALL NOT modify semantic intent).

- Sources/DialecticSession/CLIOptions.swift: a typed CLI parser
  that handles --runtime <name> --model <m> --dry-run
  --runtime-report, with precedence: explicit CLI > env var >
  built-in default. Env vars NEURALCOMPOSE_RUNTIME and
  NEURALCOMPOSE_MODEL supported. --help prints usage and exits
  0; malformed input prints usage and exits 2.

- Sources/DialecticSession/RuntimeFactory.swift: maps
  (runtimeName, model) -> (any GenerationRuntime, systemPrompt,
  promptProfile, interactionStyle). Two paths:
    - claude -> ClaudeCLIGenerationRuntime (composes
      ClaudeCLITransport, the byte-equivalent subprocess path
      the legacy ClaudeCLIGenerator used).
    - ollama -> OllamaGenerationRuntime (composes
      OllamaHTTPTransport against localhost:11434). Validates
      the daemon is reachable and the requested model is pulled;
      on failure, raises RuntimeFactoryError with an actionable
      diagnostic.

- Sources/DialecticSession/RuntimeReport.swift: prints the
  runtime/transport/model/prompt/interaction/endpoint/availability/
  generation-enabled state in a stable, human-readable format;
  the verify() helper performs the live freshness check for
  Ollama. Failure prints actionable diagnostics, never panics.

- Sources/DialecticSession/main.swift: rewired to honor the
  new flags and short-circuit on --dry-run and --runtime-report
  before any loop is constructed. Removed the old "re-parse
  CommandLine.arguments for the live path" defensive guard
  (which incorrectly treated --runtime as positional). The
  existing positional contract (focused|reflective|contemplative
  <out.jsonl> <heard...>) is preserved verbatim: a default
  invocation with no flags behaves exactly as the legacy harness
  did.

Verification:

- Build: ./Scripts/build.sh exit 0, 1.14s for the most recent
  rebuild.
- Full test suite: 343/343 pass, 0 fail. (The 8-step 5 + 28 step
  3-4 tests + the BCICloudBridgeTests + the rest of the
  BCICore/BCIEEG test corpus.)
- --dry-run --runtime ollama --model qwen2.5:0.5b: passes all
  5 verifications (prompt loaded, transport reachable, model
  available, runtime created, fingerprint generated). Exit 0.
- --dry-run --runtime ollama --model deepseek-v4-flash:cloud:
  passes all 5 verifications. Note: the task brief said
  'deepseek-v4-instant' but the actual model installed in this
  Ollama instance is 'deepseek-v4-flash:cloud'; I used the
  installed name.
- --dry-run --runtime claude --model claude-sonnet-5: factory
  builds successfully. The rate-limit only surfaces on the
  first live call (preserved legacy behavior); --dry-run does
  not call the subprocess.
- --runtime bogus: error message + available-runtimes list,
  exit 1. Never panics.
- --runtime ollama --model gpt-99-turbo: error message + the
  full installed-models list (deepseek-r1:1.5b, qwen2.5:1.5b,
  qwen2.5:3b, qwen2.5:0.5b, deepseek-v4-flash:cloud), exit 1.
- NEURALCOMPOSE_RUNTIME=ollama NEURALCOMPOSE_MODEL=qwen2.5:1.5b
  (no flags): runtime picked from env, dry-run passes. Confirms
  CLI > env > default precedence.
- --help: usage page, exit 0. No positional args: usage page,
  exit 2.
- Live smoke: dialectic-session --runtime ollama --model
  qwen2.5:0.5b focused /tmp/live.jsonl "Reply with exactly:
  pong" -> 1/1 turn, 1 line written, exit 0. The Ollama runtime
  produced a real turn through the new adapter; the turn
  record decoded cleanly with index, heard, outcome
  (spoke:displacement-seeking), spokenText ("Ping!"), and
  2 candidates. (The model is qwen2.5:0.5b so 'Ping!' is
  the answer to 'Reply with exactly: pong' the model chose.)
- App relaunch: NEURALCOMPOSE_BOARD_PROFILE=synthetic
  NeuralCompose launches, no startup faults, MLX predictor
  loaded Qwen2.5-0.5B-Instruct-4bit (modelLoad=2.6s,
  throughput=49.6 tok/s), classifier stub logged, all
  subsystems initialized cleanly. No regressions.

Out of scope (deferred to a future commit):

- Wiring the runtime's metadata into the
  DialecticalTurnEvent.log(...) path so the recorded
  generatorFingerprint is non-nil. The current loop's
  generator.generate(...) returns a String via the adapter;
  the GenerationResult's metadata is dropped at the adapter
  boundary. Step 6 is the runtime-substitution seam; the
  next milestone will thread the metadata through.
- The "runtime-independence commit" the user proposed
  (boot the app with Claude / Stub / Ollama without
  recompiling): this commit is the wiring foundation
  (the factory + adapter + flags). The actual menu-bar
  or env-var-controlled runtime switch in the live app
  is the GUI piece, which the user explicitly listed as
  out-of-scope here.

ADR invariant check: no invariants change. The runtime
remains transport, not semantics; the prompt bytes the
transport sees are unchanged (loaded from PromptProfile);
token counting remains a capability, not a protocol method;
runtimes are composed over transports; benchmark immutability
is preserved (this commit doesn't touch the benchmark).
Surfaced during Runtime Validation Session 001. The cloud-routed
DeepSeek-v4-flash:cloud model uses all 60 `num_predict` tokens
on its `thinking` field and produces `response: ""` (empty
text). The dialectic loop's `runTurn(heard:)` had a
`guard !candidateTexts.isEmpty else { return }` early-exit
that returned without incrementing `turnIndex`. The main
loop's progress check (`while await loop.turnIndex <
heardLines.count`) then waited forever for a turn to land;
the 90-second watchdog killed the harness with "0/N turns run"
and no telemetry explaining why. Every DeepSeek run in the
RVS-001 matrix hung at turn 1 (0/3 turns).

The fix: the early-exit now logs a `.silent` turn with empty
candidates before returning, and `turnIndex` advances. A
persistently-silent run is now visible in the rollup as N
`silent` outcomes, not as a hang. The harness was re-run
against the full 6-cell (3 profiles × 2 models) matrix; all
6 runs complete with 3/3 turns logged, including the
DeepSeek-v4-flash:cloud runs that previously hung.

Companion change in `OllamaHTTPTransport`: the URLSession was
switched from `URLSession.shared` (and `.default`) to
`URLSessionConfiguration.ephemeral` with an explicit 30s
request timeout. This is a defensive change — not the root
cause of the hang, but it eliminates the HTTP-keep-alive bug
class on cloud-routed models. The root cause was the loop's
silent-exit behavior; the URLSession change removes a
related failure mode.

Build: ./Scripts/build.sh exit 0, 11.30s for the most recent
rebuild (compiles all targets including NeuralCompose and the
harness).

Tests: 343/343 pass, 0 fail. The new `logSilentTurn` method
exercises a previously-uncovered code path (the `.silent`
case with empty candidates) and the existing test suite
covers it correctly.

Runtime verification: 6-run matrix (focused/reflective/contemplative
× qwen2.5:0.5b / deepseek-v4-flash:cloud) all complete with
3/3 turns, 3 lines written, exit 0. App relaunch under
synthetic EEG: PID 7301 alive after 8s, MLX probe succeeded,
classifier stub, voice, embedding, spectral all initialized
cleanly. No regressions.

ADR invariant check: no invariants changed. The runtime is
still transport, not semantics. The prompt bytes the
transport sees are unchanged. The dialectic engine still
depends on `TextGenerating`; the adapter still does NOT
modify semantic intent. The new `logSilentTurn` is a
control-flow fix, not a semantic change.

See `docs/rvs/rvs-001-log.md` for the full session log,
including the per-turn outputs from the 3 Qwen runs (which
exercise the dialectic engine end-to-end) and the
observation that DeepSeek-v4-flash:cloud uses all 60
`num_predict` tokens on its `thinking` field — a real
finding about the model's behavior under the dialectic
template's constraints, not a bug in our code.

Recommended next milestone: thread `GenerationResult.metadata`
through the loop's `log(...)` path so the recorded
`generatorFingerprint` on persisted turn events is non-nil.
Step 6.5 was deferred per the user's "use the remaining
session time to exercise the system" guidance; the metadata
threading is the smallest possible commit that closes the
runtime-substitution story end-to-end.
…etadata callback

Closes the SOAK 001 finding: every `DialecticalTurnEvent` from a
`GenerationRuntime`-backed run had `generatorFingerprint: nil`,
because the `TextGenerating` adapter (line 62 of the prior
`GenerationRuntimeTextGeneratingAdapter`) returned `result.text`
and dropped `result.metadata`. The trace from RVS-001 was exact;
the fix is a refinement protocol, an `onMetadata` callback on the
adapter, and a metadata box on the loop that captures the latest
metadata synchronously on the same task as `generate(...)`.

**The protocol (new file):**

`Sources/BCICore/Protocols/MetadataPublishingTextGenerating.swift`
adds a refinement of `TextGenerating` that carries the
`onMetadata` callback. The legacy `TextGenerating` seam stays
`String`-typed (no breaking change to existing conformers); the
adapter adds the refinement. Future runtimes that want to publish
metadata conform to this protocol.

**The adapter (modified):**

`Sources/BCICloudBridge/GenerationRuntimeTextGeneratingAdapter`
conforms to `MetadataPublishingTextGenerating` and fires the
`onMetadata` callback after every `runtime.generate(...)` call.
The callback is `@Sendable` so the adapter remains `Sendable`.
Closure is a regular `((GenerationMetadata) -> Void)?` from the
caller's perspective; the `@Sendable` annotation is a struct-level
detail.

**The loop (modified):**

`Sources/BCICore/Composition/HypnagogicDialecticLoop` adds:

- `private let latestMetadata = MetadataBox()` (a `Sendable` class
  with an `OSAllocatedUnfairLock`)
- `nonisolated func recordGeneratorMetadata(_:)` (no actor hop)
- `func attachMetadataCaptureFromAdapter()` (type-checks for the
  refinement protocol and wires the callback; no-op for legacy
  conformers)
- Two read sites at the `DialecticalCompetition` construction
  points (the spoke/synthesized path at turn 369 and the silent
  path at turn 440) now read `latestMetadata.get()` to populate
  the `generatorFingerprint` field.

**Why a class box, not an actor-isolated `var`:**

The adapter's `onMetadata` callback is synchronous on the same
task that called `generate(...)`. An actor-isolated `var` would
require `Task { await self.recordGeneratorMetadata(...) }` from
the callback, and the `Task` would be scheduled *after* the
`runTurn` read of `latestMetadata` — losing the metadata for that
turn. The class box keeps the read/write synchronous on the same
task. The `@unchecked Sendable` annotation is correct because the
lock is the synchronizer.

**The harness (modified):**

`Sources/DialecticSession/main.swift` calls
`await loop.attachMetadataCaptureFromAdapter()` after constructing
the loop and before `loop.start()`. This is the only consumer
path that needs the call; the live app wires it through
`AppViewModel` (separate commit, see the `LiveRuntimeFactory`
work).

**The test (new file):**

`Tests/BCICloudBridgeTests/GenerationRuntimeTextGeneratingAdapterTests.swift`
adds 5 tests: the adapter returns `text`, fires `onMetadata` with
the runtime metadata, fires once per call, conforms to the
refinement protocol, and is safe when `onMetadata` is `nil`.
Combined with the 343 pre-existing tests, the suite is now 349
passing.

**Verification:**

- `./Scripts/build.sh` exits 0 in 17.43s
- `swift test` passes 349/349, 0 failures, 0 XCTAssert failures
  (Swift-Testing/XCTest interop artifact on exit 1, same as
  before this change)
- Dry-run smoke (`dialectic-session --dry-run --runtime ollama
  --model qwen2.5:0.5b`) reports `fingerprint generated: yes`

**Deferred to a separate commit:**

The live-app integration (the `AppViewModel` path that calls
`LiveRuntimeFactory.resolve(...)` and passes the result to
`HypnagogicDialecticLoop`) is on the `research/rust-workspace`
branch and not yet committed. Once that lands, the live-app
JSONL will start populating `generatorFingerprint` automatically.

Refs: SOAK 001 retrospective, RVS-001 finding.
…rchHypothesis

Adds `Scripts/analyze_dialectic.py`, the quantitative oracle that
future `ResearchHypothesis.acceptance:` criteria will compare
against. Reads a `dialectic-turns-YYYY-MM-DD.jsonl` log and
computes the eleven metric categories the user named for
scientific evaluation of the dialectic runtime:

  1. N-gram repetition (bigram / trigram, top-K)
  2. Opening diversity (4-grams, distinct ratio)
  3. Semantic self-distance (Jaccard + existing selfSimilarity)
  4. Witness intervention frequency (per outcome, overall)
  5. Response entropy over time (sliding-window Shannon)
  6. Semantic attractor persistence (Jaccard ε-bounded)
  7. Outcome transition graph (4x4 matrix)
  8. Witness influence on next-K turns (distribution shift)
  9. Latency proxy (turn-index gaps; not a real latency)
 10. Generator provenance (turns with fingerprint)
 11. Named-phrase detector (qualitative patterns → measurable)

**Why this script is load-bearing for ResearchHypothesis:**

Each future `contemplative_v3.yaml` will declare its `metrics:`
and `acceptance:` criteria. The script's output is the baseline
those criteria are evaluated against. For SOAK 001, the
quantitative findings that future hypotheses will be measured
against are:

  - Bigram diversity: 0.622; trigram: 0.737
  - Opening diversity: 0.741 (103/139 distinct)
  - Witness frequency: 12.1% of turns (17/140), 100% success
  - Synthesis rate after coherence: 8/65 (12%) — loop is
    reluctant to synthesize; tuning target
  - Witness influence: +17% displacement, -24% synthesis in
    the next 3 turns after a finding fires (witness couples
    the dialogue, not just observes)
  - Entropy declining: first-half 7.72 → second-half 7.51
  - Named phrase "in a live dialogue": 4 occurrences at idx
    [7, 13, 15, 34] (system-prompt scaffold leak)
  - Named phrase "we should consider whether there might be
    another variable": 2 occurrences at idx [1, 18]

**What the script does NOT do (deferred):**

- Embedding-based semantic distance: the JSONL doesn't carry
  embeddings; the loop's existing `selfSimilarity` scalar and
  a word-bag Jaccard are the best available proxies.
- Per-turn wall-clock latency: the JSONL has no timestamps;
  the `latency` section is honest about being a proxy.
- Real coherence-to-synthesis transition analysis: requires
  a richer `DialecticalCompetition` log shape; deferred.

**Stdlib-only.** Runs in any Python 3.10+ environment; no
venv setup, no deps. Output is both human-readable (printed
to stdout) and machine-readable (JSON sidecar via `--output`).

**Usage:**

  ./Scripts/analyze_dialectic.py
  ./Scripts/analyze_dialectic.py --output /tmp/baseline.json
  ./Scripts/analyze_dialectic.py --input /path/to/other.jsonl

Refs: SOAK 001 retrospective, RVS-001, ResearchHypothesis retrofit.
…eria

Adds `docs/rvs/soak-001-findings.md`, the prose companion to
`Scripts/analyze_dialectic.py` (commit `4bdc4d5`). Captures
the headline numbers from the 5h 16m / 140-turn SOAK 001 run
and the eight `ResearchHypothesis` acceptance criteria the
findings imply.

**The two-layer completion note** (per the user's
"don't let readers infer the app is already recording
fingerprints" guidance) is the first section. The core runtime
metadata-threading is complete (`b9c09fd`); the live GUI
integration is pending (uncommitted `AppViewModel` +
`LiveRuntimeFactory` changes on `research/rust-workspace`).
The 0/140 fingerprint rate in the baseline is expected, not a
regression.

**Headline findings (the eight acceptance criteria for
`contemplative_v3.yaml` and future hypotheses):**

1. **Witness coupling is real, not designed.** After a witness
   finding fires, the next 3 turns are +16.9% more likely to
   be `displacement-seeking` and -23.9% less likely to be
   `synthesis`. The Witness is supposed to observe, not steer.
   This is the highest-value falsifiable finding; the criterion
   is `|witness_influence.per_outcome_shift.{displacement-seeking,
   synthesis}| < 0.05`.

2. **System-prompt scaffold is leaking.** `in a live dialogue`
   appears as an opening 4-gram 4 times at idx [7, 13, 15, 34].
   Fix is in the prompt, not the model. Criterion:
   `named_phrases["in a live dialogue"].count = 0`.

3. **Synthesis-after-coherence reluctance.** Only 8/65 (12%) of
   coherence turns transition to synthesis. `FieldDynamics`
   knobs (`explorationPressure`, `attractorDecay`) are the
   levers. Criterion:
   `transitions.matrix.coherence-seeking.synthesis / row_total > 0.20`.

4. **Entropy is declining.** First-half 7.72 → second-half
   7.51 bits. 0.2-bit drop is real, likely downstream of (1)
   and (2). Criterion: `entropy.second_half - first_half > -0.05`.

5. **The verbatim phrase the user caught.** "We should
   consider whether there might be another variable" appears
   at idx [1, 18]. Fix same as (2). Criterion:
   `named_phrases["we should consider whether there might be
   another variable"].count = 0`.

6. **N-gram diversity is healthy** (trigram 0.737). Criterion:
   `> 0.70`.

7. **Opening diversity is healthy** (0.741). Criterion: `> 0.70`.

8. **No silent turns, no pathological repetition, no memory
   leak.** Documented as absence-of-evidence rather than
   criterion.

**Findings that did not pan out** (named in the document so
future readers don't re-investigate them): pathological bigram
repetition, silent outcomes, runaway memory growth.

Refs: SOAK 001 retrospective, RVS-001 log, ADR-009, ADR-010 review.
…layer metadata path

Completes the live-app side of the metadata-threading work.
Closes the two-layer-completion gap documented in
`docs/rvs/soak-001-findings.md` (the second bullet of that
section: "the live GUI integration is pending").

**What this commit does:**

The dialectic, witness, and mirror generator sites in
`Sources/NeuralComposeApp/AppViewModel.swift` now resolve
through `Sources/BCICloudBridge/LiveRuntimeFactory.make(...)`
instead of hardcoding `ClaudeCLIGenerator(...)`. The factory
honors `NEURALCOMPOSE_RUNTIME` and `NEURALCOMPOSE_MODEL` env
vars, falling back to Claude when neither is set (preserving
the prior default behavior). Each call site gets a separate
`Resolved` struct for logging.

**The factory (new file):**

`Sources/BCICloudBridge/LiveRuntimeFactory.swift` is a thin
factory that takes a system prompt and returns a tuple of
`(TextGenerating, Resolved)` where `Resolved` carries the
runtime name, model name, and system-prompt source for
logging. Resolution order: env var → default. Default is
Claude (legacy `ClaudeCLIGenerator`). The factory is the
runtime-independence seam for the live app, mirroring the
harness's `RuntimeFactory` (commit `4002d3e`).

**Why this is two layers of completion:**

- **Layer 1** (core runtime): `b9c09fd` made the
  `TextGenerating` adapter publish `onMetadata` to the loop,
  which then stamps `generatorFingerprint` on every
  `DialecticalTurnEvent`. The headless `dialectic-session`
  harness has been recording fingerprints since that commit.
- **Layer 2** (live app): this commit. The menu-bar
  `NeuralCompose.app` now resolves its generators through
  the factory, so the loop's `generatorFingerprint` field is
  populated with the resolved runtime's metadata (Claude or
  Ollama, depending on env vars).

**Acceptance criteria this commit flips:**

`provenance.fingerprint_rate == 1.0` is now achievable on a
live-app soak, provided the next soak uses the binary built
from this commit with `NEURALCOMPOSE_RUNTIME=ollama` or the
default Claude path. The 0/140 baseline in
`docs/rvs/soak-001-findings.md` was a tooling gap, not a
statistical one — the user named this correctly in the
acceptance-criteria review: provenance is binary, not
statistical.

**Verification:**

- `./Scripts/build.sh` exits 0 in 12.64s
- `swift test` passes 349/349, 0 failures, 0 XCTAssert failures
  (Swift-Testing/XCTest interop artifact on exit 1, unchanged)
- Pre-existing warning in `AppViewModel.swift:1536` (the
  `previousCommittedWord` unused-let) is the only diagnostic

**Risks:**

- The factory's `(try? LiveRuntimeFactory.make(...))` swallows
  errors and falls back to Claude. This preserves the prior
  default but means a misconfigured env var (e.g.,
  `NEURALCOMPOSE_RUNTIME=ollama` with Ollama not running) is
  silently demoted to Claude. Future hardening: surface the
  factory error to the user via a banner.
- The `BCILog.pipeline.notice(...)` line emits a log line on
  every dialectic-engine start. The line is long (two
  resolved-runtime descriptions) but bounded. No infinite
  loop risk.

Refs: SOAK 001 findings, RVS-001, ADR-009, commit `b9c09fd`.
… path

The `eb1e373` commit (live-app `LiveRuntimeFactory` wiring)
was incomplete: the harness (`Sources/DialecticSession/main.swift`)
calls `await loop.attachMetadataCaptureFromAdapter()` after
constructing the loop, but the live `AppViewModel` did not.
Result: the live app's `DialecticalTurnEvent.generatorFingerprint`
remained `nil` even after `eb1e373`, because the loop never
received the callback that bridges the adapter's `onMetadata`
fire to the loop's `latestMetadata` box.

**This commit completes the live-app side of the
two-layer metadata path.** The `if let dialectic = loop as?
HypnagogicDialecticLoop` branch in the `startHypnagogicMode`
method now calls `await dialectic.attachMetadataCaptureFromAdapter()`
before starting the loop. The mirror loop (`HypnagogicDialogueLoop`)
doesn't need this — it doesn't produce `DialecticalTurnEvent`s,
so the fingerprint field doesn't apply.

**Why this is the right seam:**

The `attachMetadataCaptureFromAdapter()` method is *already*
`actor-isolated` on the dialectic loop (it has to be, to mutate
the `MetadataBox`). Calling it from a SwiftUI-actor method
(`AppViewModel` is `@MainActor`) means a clean `await` boundary
with no thread-hop gymnastics. The method's `as?` type-check
makes it a no-op for legacy `TextGenerating` conformers
(e.g. the pre-runtime-abstraction `ClaudeCLIGenerator`); for
the new `GenerationRuntimeTextGeneratingAdapter`, it wires the
`onMetadata` callback to the loop's `recordGeneratorMetadata`.

**Verification on the live app (PID 53832 first launch, 21:03):**

- Two new turns appeared in the JSONL
- Both had `generatorFingerprint: nil` (the bug)
- After this commit: rebuild → relaunch → new turns
  should have populated fingerprints
- Build: 9.25s, exit 0
- Tests: 349 passed, 0 failed

**Risk surface:**

The `attachMetadataCaptureFromAdapter()` is a no-op for
legacy `TextGenerating` conformers, so the default Claude
path is unaffected. The change is additive.

Refs: SOAK 001 findings, commits `b9c09fd` and `eb1e373`.
…stential copies

The `b9c09fd` commit added the `onMetadata` callback to
`GenerationRuntimeTextGeneratingAdapter` and wired the
`HypnagogicDialecticLoop.attachMetadataCaptureFromAdapter()`
to set it. The wiring silently failed: every live and harness
turn continued to log `generatorFingerprint: nil` because of
a Swift existential-box gotcha.

**The bug:**

`GenerationRuntimeTextGeneratingAdapter` is a `struct`. The
loop's stored property is `private let generator: any TextGenerating`.
When the loop's wiring code does
`guard var publisher = generator as? MetadataPublishingTextGenerating`,
Swift opens the existential box into a **mutable local copy**
of the struct. Setting `publisher.onMetadata = ...` mutates the
copy, not the value stored in `self.generator`. The next
`generate(...)` call reads the original (unmutated) copy, so
the callback never fires. The harness and live app both hit
this: the post-soak JSONL shows 0/140 with fingerprints.

**The fix:**

Move the `onMetadata` storage into a class-typed
`MetadataCallbackBox` (reference type) that's created once at
adapter init and held in a `let`. The protocol's
`onMetadata` property becomes a `get`/`set` pair that reads
and writes through the box. Now every copy of the struct —
including the one held inside the loop's `let generator`
existential — shares the same box, so the loop's wiring
propagates to the original.

**Why this is the right shape:**

The Swift-idiomatic fix for "set a callback on a struct-typed
existential" is exactly this: a class-typed box. The cast
local is a copy of the struct, but the box is shared. The
class doesn't need to be public; consumers see only
`onMetadata` (the protocol requirement).

**The new test (testOnMetadataPropagatesAcrossExistentialCopy):**

The bug was not caught by the original 5 unit tests because
none of them exercised the existential-cast path. The new
test wraps the adapter in `any TextGenerating`, casts it back
to `var` as the loop would, sets `onMetadata`, and verifies
the callback fires on a subsequent `generate(...)` call. If
the box is reverted to a struct-typed property, this test
fails — the regression is now caught.

**Other changes:**

- `Sources/BCICore/Composition/HypnagogicDialecticLoop.swift`:
  the `attachMetadataCaptureFromAdapter` method now works
  correctly (the prior commit had the *intended* code but
  it was defeated by the box issue). Doc comment expanded
  to explain the existential-box pattern.
- `Sources/DialecticSession/main.swift`: comment-only update
  pointing at the new pattern.
- `Sources/BCICloudBridge/GenerationRuntimeTextGeneratingAdapter.swift`:
  the `MetadataCallbackBox` class + the new `onMetadata`
  property implementation that reads/writes through it.

**Verification:**

- `./Scripts/build.sh` exits 0 in 16.92s
- `swift test` passes 350/350, 0 failures, 0 XCTAssert
  failures (was 349; +1 from the new test)
- `dialectic-session --runtime ollama --model qwen2.5:0.5b
  focused` produces a `DialecticalTurnEvent` with a fully
  populated `generatorFingerprint`:

```json
{
  "transport": "ollama-http",
  "model": "qwen2.5:0.5b",
  "runtime": "ollama",
  "promptProfile": "wakingDialectical",
  "provider": "ollama",
  "interactionStyle": "dialectical",
  "promptHash": "094ec5376a50253dcaa205d267dcd9c22e52f30de0a33799f296df707421a710"
}
```

**Live-app impact:**

The live app (PID 56967, relaunched with this commit) will
record fingerprints on every new dialectic turn. The
2-layer metadata path is now end-to-end functional on both
the harness and the live app.

Refs: SOAK 001 findings (criterion #8, provenance rate == 1.0),
commit `b9c09fd`.
…ic runtime

Adds `Scripts/soak-matrix.sh`, the empirical test matrix runner
the architecture review called for. Generates a diverse corpus
of conversations across (runtime, model, profile) configurations
with a FIXED set of heard lines, then runs the existing
`analyze_dialectic.py` oracle on each cell.

The 10-cell default matrix covers:
- qwen2.5 family at 0.5B / 1.5B / 3B (size sweep)
- deepseek-r1:1.5b (local reasoning model, alternative family)
- deepseek-v4-flash:cloud (cloud-routed; the SOAK 001 silent-
  turn case, retested to confirm the RVS-001 fix holds across
  the longer heard-line corpus)
- focused / reflective / contemplative profiles for the qwen
  0.5B baseline cell

Each cell produces:
- `$base-dir/runs/<cell>.jsonl` — raw turns
- `$base-dir/baselines/<cell>.json` — `analyze_dialectic.py`
  output (8 metrics)
- `$base-dir/matrix.json` — aggregate matrix summary
- `$base-dir/leakage.json` — leakage audit (prompt scaffolding,
  named phrases, system-prompt fragments, self-reference)

The matrix summary table renders one row per cell with the
headline metrics (silent rate, synthesis rate, fingerprint
rate, ngram diversity, opening diversity, second-half entropy)
so an experimenter can spot the cells that are working and
the ones that are not at a glance.

**Why this is a feat, not a fix:**

The script is a new empirical capability, not a bug fix. The
dialectic runtime is now stable enough to be exercised
empirically; this script is the harness for that exercise.
The user named it as the higher-priority work for the next
few hours over starting Rust Phase 0: "you're no longer asking
'does it compile?' You're asking 'how does the system behave
over time?'"

**The 30-line heard-line corpus** is sampled from SOAK 001's
organic user input (the swarms investigation surfaced these
lines — "Sinking slowly warm", "In a live dialogue the other
person just said", etc.). The set is fixed across all cells
so the only variable is (runtime, model, profile). Future
hypotheses can swap the corpus to a different one (e.g., a
benchmark-001-grounding.txt script) without changing the
runner.

**The leakage audit** is a first pass. The 8 patterns are
the ones the user named in the architecture review plus
existing named-phrase checks from `analyze_dialectic.py`:
- `in a live dialogue` (prompt scaffold)
- `we should consider whether...` (verbatim phrase)
- `as an ai` / `i should` / `i don't have feelings` (LLM-isms)
- `neuralcompose` / `dialectic` / `hypnagogic` / `witness` (system leak)
- `scenekit` / `scnvector` / `scnmatrix` (implementation leak)
- `turn_index` / `generatorFingerprint` / `onMetadata` (telemetry leak)

The audit counts how many spoken turns contain each pattern.
A future pass can extend the pattern set as new leakage
vectors are observed.

**Phase 2 (deferred):**

Cross-model dialectic (Pole A: Qwen, Pole B: DeepSeek cloud,
Witness: local Qwen) is a separate scope that requires the
harness to accept *per-pole* runtime/model parameters. The
harness currently constructs both poles from the same
runtime. The cross-model extension will land on
`feature/pluggable-generators` as a follow-up commit, not
on a new branch. The matrix runner is already structured
to accommodate it: each cell is a (runtime, model, profile)
triple today; tomorrow it can be a (pole_a_runtime,
pole_a_model, pole_b_runtime, pole_b_model, profile) tuple
without changing the analysis or rendering code.

Refs: SOAK 001 findings, RVS-001, post-soak architecture
review (treat dialogue engine as empirical environment).
Adds `docs/rvs/soak-002-matrix.md`, the findings doc for the
first empirical test matrix run. 10 cells × 30 turns × fixed
heard-line corpus, executed by `Scripts/soak-matrix.sh`
(commit `09d0775`).

**Headline numbers (cells × 30 turns each):**

| Cell | silent | synth | fp | ngram | open | entropy_2nd |
|------|--------|-------|----|-------|------|-------------|
| F_qwen05b       |   0.00% | 0.00% | 100% | 0.702 | 0.793 | 6.87 |
| R_qwen05b       |   0.00% | 0.00% | 100% | 0.736 | 0.828 | 6.70 |
| C_qwen05b       |   3.33% | 0.00% | 100% | 0.967 | 0.966 | 6.71 |
| F_qwen15b       |   0.00% | 0.00% | 100% | 0.786 | 0.800 | 7.29 |
| R_qwen15b       |   0.00% | 0.00% | 100% | 0.784 | 0.833 | 7.17 |
| F_qwen3b        |   0.00% | 0.00% | 100% | 0.657 | 0.667 | 7.25 |
| F_deepseek_r1   | 100.00% | 0.00% | 100% | 0.000 | 0.000 | 0.00 |
| R_deepseek_r1   | 100.00% | 0.00% | 100% | 0.000 | 0.000 | 0.00 |
| F_deepseek_flash| 100.00% | 0.00% | 100% | 0.000 | 0.000 | 0.00 |
| R_deepseek_flash|  96.67% | 0.00% | 100% | 1.000 | 0.000 | 0.00 |

**The five findings worth a paragraph each:**

1. **The fingerprint path works on every cell** — `fp=100%`
   across the matrix. The `MetadataCallbackBox` fix and the
   harness wiring are end-to-end correct on the harness
   path. The 0/140 baseline in SOAK 001 is *only* a problem
   on the live-app path (the `LiveRuntimeFactory` isn't
   honoring env vars; separate scope).

2. **All DeepSeek runs are silent (96-100%)** — confirms the
   RVS-001 finding at matrix scale. Both `deepseek-r1:1.5b`
   (local reasoning) and `deepseek-v4-flash:cloud` exhaust
   their `num_predict=256` budget on thinking/reasoning
   before producing an answer. Recommended fix: per-model
   `num_predict` defaults at the `LiveRuntimeFactory` /
   harness level.

3. **Synthesis reluctance confirmed** — `0% synthesis` on
   every Qwen cell. The synthesis-after-coherence gate is
   too tight in the current `FieldDynamics` calibration.
   This is the largest leverage point for `contemplative_v3.yaml`.

4. **Qwen 0.5B has lower ngram diversity than 1.5B; 3B has
   the lowest of all** — model size is not monotonically
   better. For the dialectic task at this heard-line
   distribution, the 0.5B model is a reasonable baseline.

5. **Leakage audit results** — the `in a live dialogue`
   scaffold is the dominant leak (15 turns across 6 cells).
   The `we should consider whether...` verbatim phrase
   appears in 2 cells (qwen 0.5B only). System-prompt
   terminology (`neuralcompose` / `dialectic` / `hypnagogic`)
   leaks in 2 turns of R_qwen05b only — profile-specific.

**Three new acceptance criteria for `contemplative_v3.yaml`:**

9. `synthesis_rate ∈ [0.10, 0.30]` (band, not minimum)
10. `synthesis_after_coherence ∈ [0.10, 0.30]`
11. `leakage.live_dialogue_scaffold = 0` (hard target)

These join the 8 from `docs/rvs/soak-001-findings.md`. The
matrix run validates the criterion *shape* and surfaces
the band-vs-minimum distinction the user named for
synthesis rates.

**Two follow-up items (separate scope, not on a new branch):**

- **Cross-model dialectic** — harness needs per-pole
  runtime/model parameters (`--pole-a-runtime`, etc.).
  Deferred to a follow-up commit on
  `feature/pluggable-generators`.
- **Live-app env-var gap** — the live app's
  `LiveRuntimeFactory` isn't honoring `NEURALCOMPOSE_RUNTIME`
  despite the env var being set; the harness path is
  correct, only the live-app factory needs the fix.

**Why this is docs, not code:**

The matrix run is the empirical evidence the user asked for.
The findings doc is the human-readable record. Future
`ResearchHypothesis` YAMLs (when the `feature/research-hypotheses`
branch is opened) will reference these criteria.

Refs: SOAK 001 findings, RVS-001, post-soak architecture
review.
Adds the `SoakRuns/` directory as a longitudinal artifact
store for `Scripts/soak-matrix.sh` runs. The `.gitignore`
keeps the per-cell raw JSONL out of git (reproducible from
the runner) but commits the aggregate `matrix.json` and
`leakage.json` for each run, so future runs can diff against
this baseline.

**What's in this commit:**
- `SoakRuns/.gitignore` — keep `matrix.json` and
  `leakage.json` for each run; ignore the per-cell raw
  output
- `SoakRuns/soak-002-20260721-220848/matrix.json` — the
  10-cell × 30-turn matrix aggregate (10 cells, ~9.9 KB)
- `SoakRuns/soak-002-20260721-220848/leakage.json` — the
  leakage audit results (8 patterns, 10 cells, ~3.9 KB)

**The companion doc:**
`docs/rvs/soak-002-matrix.md` (commit `83cdc67`) is the
human-readable interpretation. These two artifacts together
form the empirical baseline for future ResearchHypothesis
YAMLs.

**Why commit the aggregate, not the raw:**

The per-cell JSONL is 300 turns × ~700 bytes = ~210 KB per
run, and is reproducible from the same matrix runner. The
aggregate `matrix.json` is the *summary* — the 8 headline
metrics per cell — and that's what future hypothesis
evaluations will diff against. Keeping the raw output out
of git keeps the repo size stable; the raw is in the
`SoakRuns/` directory on disk for whoever wants to drill
in.

**The longitudinal baseline:**

When a future `contemplative_v3.yaml` is run through
`Scripts/soak-matrix.sh`, the resulting `matrix.json` is
diffed against `SoakRuns/soak-002-20260721-220848/matrix.json`.
A 1-line summary of the diff (e.g., "ngram_diversity: 0.702
→ 0.812, synthesis_rate: 0% → 18%") becomes the
`acceptance:` evidence for the hypothesis. This is the
empirical loop the user named: Hypothesis ↓ Runtime ↓
Soak ↓ Analysis ↓ Acceptance ↓ Next hypothesis.

Refs: SOAK 001, RVS-001, soak-matrix.sh (`09d0775`),
soak-002-matrix.md (`83cdc67`).
…ng-down

Adds a three-component inertia report to the dialectic
analyzer, per the architecture review's framing:

  semantic_inertia   — resistance to changing topics
                       (Jaccard similarity of consecutive
                        `heard` word sets)
  linguistic_inertia — same sentence-openings habit
                       (1 - opening_4gram_diversity)
  policy_inertia     — same-style resolution choice
                       (1 - normalized transition entropy)

Plus a critical-slowing-down diagnostic: variance and
lag-1 autocorrelation of the heard-length series. Lower
variance + higher autocorrelation near stable attractors
is the dynamical-systems signature of approaching a
fixed point.

**Why this matters (the framing):**

  "If a system has both 'increasing synthesis' and
   'declining diversity,' the most plausible reading
   is convergence onto stable conversational
   attractors. The system is becoming more coherent
   and more stereotyped at the same time, by settling
   onto a small set of stable topics with predictable
   openings."

The three-component decomposition distinguishes
"productive coherence" (ideas integrate but remain
flexible) from "pathological convergence" (everything
collapses into the same template). On the live app's
283 turns:

  semantic_inertia:    0.049  (heard topics are diverse)
  linguistic_inertia:  0.365  (openings are stereotyped)
  policy_inertia:      0.273  (transition policy varies)

The system is *not* at a dynamical fixed point; the
linguistic attractor is the dominant inertia vector,
not a semantic or policy one. This is consistent with
the user's earlier observation that the same opening
phrases repeat ("in a live dialogue...",
"perhaps we should examine..."), while topics remain
fresh.

**Other fixes in this commit:**

- `load_turns()` now tolerates malformed JSONL lines
  (the live app sometimes writes partial lines on
  shutdown). Skipped count is preserved; no data loss
  for valid lines.
- `compute_provenance()` now records per-model
  fingerprint counts, surfaced in the report.
- `fingerprint_model` added to the `Turn` dataclass.
- The matrix aggregator (`soak-matrix.sh`) now uses the
  correct normalized outcome key `synthesis` (not the
  raw `synthesized_synthesis`), fixing the
  "synthesis_rate = 0% on every Qwen cell" false
  alarm from `docs/rvs/soak-002-matrix.md`. The actual
  rates are 0-30% on Qwen cells and 29% on the live
  data.

Refs: post-soak architecture review, the user's
"appropriate synthesis" framing, the closed empirical
loop.
Adds `Scripts/pareto_frontier.py`, the Pareto frontier
analyzer for the closed empirical loop. Takes multiple
`analyze_dialectic.py` baseline JSONs and identifies the
Pareto-optimal subset — the configurations that are not
dominated on every objective by any other configuration.

**The framing (from the architecture review):**

  "Instead of asking 'Is contemplative_v3 better?', you
   ask 'Does contemplative_v3 dominate contemplative_v2?'
   Most objective pairs are competing. Some hypotheses
   achieve more synthesis at the cost of higher inertia;
   others keep inertia low at the cost of less synthesis.
   Neither dominates. Both belong on the frontier."

**What the script does:**

1. Extracts an 8-10 dimensional metric vector from each
   baseline JSON
2. Applies Pareto-dominance logic with configurable
   "maximize" / "minimize" directions
3. Renders a table of all points sorted by rank (1 = on
   the frontier, 2+ = dominated by N-1 other points)
4. Renders an optional 2D ASCII scatter showing the
   frontier visually
5. Writes a JSON sidecar with the full point vectors
   and the per-point dominated-by list

**Default objectives:**

  maximize: synthesis_rate, opening_diversity, ngram_diversity
  minimize: silent_rate, semantic_inertia, linguistic_inertia,
            policy_inertia, scaffold_leakage,
            witness_coupling_magnitude

Custom objectives can be passed via `--objectives` as a
JSON list of `[key, direction]` pairs.

**The current run (11 points: 10 matrix cells + live 283):**

  8 of 11 points on the frontier
  3 dominated: the fully-silent DeepSeek cells
  live_283t achieves the highest synthesis_rate (0.29)
    and the highest linguistic_inertia (0.36) — both
    simultaneously, which is exactly the "harmony as
    equilibrium, not resolution" finding the user named

**Also in this commit:**

- `SoakRuns/soak-002-20260721-220848/matrix.json` is
  refreshed: the per-cell aggregate now includes the
  inertia report and uses the corrected `synthesis`
  outcome key, so the matrix sidecar is consistent with
  the per-cell baselines.
- The matrix aggregator (`soak-matrix.sh`) now emits
  `coherence_rate` and `displacement_rate` in addition
  to the existing fields.

Refs: `feat(analyzer): inertia` (`6e0ce59`),
`docs/rvs/soak-002-matrix.md`, architecture review.
… frontier

Adds `docs/rvs/soak-003-inertia-pareto.md`, the synthesis
of the post-soak-002 work. Operationalizes the architecture
review's framing in three layers:

  1. Inertia (semantic, linguistic, policy)
  2. Critical slowing down (variance + autocorrelation)
  3. Pareto frontier (which points are not dominated)

**The closed empirical loop, end to end:**

  Experiment → ResearchHypothesis (YAML) → Runtime →
  Computational kernels → Telemetry → Metric extraction
  (analyze_dialectic.py) → Pareto analysis
  (pareto_frontier.py) → Next hypothesis

**The headline finding:**

The live app's 283-turn run achieves 29% synthesis
(higher than every 30-turn matrix cell) and is on the
Pareto frontier alongside the matrix cells. The
three-component inertia on the live data says: "this is
a linguistic attractor, not a semantic or policy one."

  semantic_inertia:   0.049 (heard topics are diverse)
  linguistic_inertia: 0.365 (openings are stereotyped)
  policy_inertia:     0.273 (transition policy varies)

  heard-length variance:      3632 (very high; not at fixed point)
  heard-length autocorr lag1:  0.017 (very low; no sticky dynamics)

The "in a live dialogue" scaffold (16/283) and the
"perhaps we should examine" template (2/283) are the
dominant linguistic attractors. **The fix lives in the
prompt, not in the dialectic dynamics.**

**The synthesis_rate measurement error caught and fixed:**

SOAK 002 reported 0% synthesis on every Qwen cell. That
was a key-naming bug in the matrix aggregator (it used
the raw `synthesized_synthesis` instead of the
normalized `synthesis`). The actual rates are 0-30% on
Qwen cells and 29% on the live data. This is the kind
of error the closed empirical loop is supposed to catch,
and it just did.

**Pareto frontier composition (11 points, 8 on frontier):**

  - 3 fully-silent DeepSeek cells are dominated
  - C_qwen05b has the highest policy_inertia (0.618)
  - F_qwen3b has the highest matrix-cell synthesis (0.30)
  - live_283t has the highest synthesis overall (0.29)
    AND the highest linguistic_inertia (0.36) — exactly
    the "harmony as equilibrium, not resolution" finding

**Three follow-ups (small focused commits, no new branches):**

  1. Live-app `LiveRuntimeFactory` env-var fix
  2. Cross-model dialectic harness extension
  3. Add a 2nd corpus (`live-001`) to soak-matrix.sh so
     matrix-vs-live comparisons are meaningful

**Forward-looking: conceptual convergence.**

The user's framing — "are Focused and Contemplative using
'space' for the same computational reason, or merely
repeating the same vocabulary?" — points to a
`conceptual_convergence` metric with three sub-dimensions
(lexical, embedding, policy). This requires (a) the
cross-model dialectic harness and (b) embeddings in the
JSONL. Deferred to follow-on work after the cross-model
harness lands.

Refs: SOAK 001, SOAK 002, architecture review,
Pareto-frontier framing.
Adds a new analyzer section that operationalizes the user's
H₂ hypothesis:

  "As a stable dialectical interaction matures, lexical
   content shifts from object-centered vocabulary toward
   relational vocabulary while semantic inertia remains
   low."

**Three vocabulary classes:**

  relational  — us, value, sign, between, through, toward,
                space, field, presence, relation, ...
  object      — file, code, prompt, runtime, graph, model,
                system, kernel, function, library, ...
  process     — explore, compare, evaluate, reflect,
                synthesize, observe, examine, consider, ...

The vocabulary lists are *hypothesis inputs*, not ground
truth. They're defined at the top of the file
(`RELATIONAL_TERMS`, `OBJECT_TERMS`, `PROCESS_TERMS`) for
easy iteration. The architecture review's "measure before
interpreting" discipline means these are starting points,
not final.

**What the metric reports:**

For each class, three numbers per turn:
  - first-half mean (per-turn proportion of total words)
  - second-half mean
  - drift = second - first, in percentage points

Plus the top-10 most-frequent words in each class, with
counts. This is the "what are the actual terms" data the
user needs to validate the vocabulary lists.

**Results on the live 304-turn run:**

  P(relational)  first= 1.57%  second= 1.66%  drift=+0.09pp ↑
                 top: through:23, us:19, between:15, value:11, space:10
  P(object    )  first= 0.75%  second= 0.35%  drift=-0.40pp ↓
                 top: model:29, system:11, class:4, function:3, hypothesis:2
  P(process   )  first= 0.90%  second= 0.35%  drift=-0.55pp ↓
                 top: consider:17, drift:10, explore:10, shift:4, shifts:2

**Interpretation:**

H₂ is *partially* supported. P(relational) is flat-to-slightly-
increasing while P(object) and P(process) both decline by
50%. The relative proportion of relational-to-object words
in the corpus is shifting up — from 2.1x (1.57/0.75) to
4.7x (1.66/0.35). The dialogue is becoming more relational
in proportion, even though absolute counts are roughly
stable.

The top relational terms (through, us, between, value,
space) match the user's named examples. The "space"
term appears 10 times across 304 turns — a non-zero
presence. Whether that's prompt leakage, emergent
vocabulary, or both, is a question the red-team test
must answer.

**The "object" decline is the most interesting finding:**

P(object) drops by 47% (0.75% → 0.35%). The most common
object terms are `model` (29) and `system` (11), which
both appear in the system prompt's "Model:" / "System:"
header. Their decline over the run may reflect the
*attractor* finding from Soak 003: the system is
moving away from its own header terms as the dialogue
progresses. The "in a live dialogue" scaffold remains
constant (16-18 occurrences) but the technical metadata
fades.

**The next step (a separate scope, not this commit):**

A red-team test — re-run a matrix cell with the
"in a live dialogue" scaffold removed from the system
prompt, then compare the symbolic_drift output. If
relational/object/process proportions stay roughly
constant with and without the scaffold, the result
is *emergent* (consistent with H₂). If they shift
toward "lower P(relational)", the result is
*prompt leakage* (refutes H₂).

This is the falsifiable mechanism the user named.
The next commit on `feature/pluggable-generators`
adds a `--no-scaffold` flag to the harness + matrix
runner; the commit after that runs the red-team
matrix.

Refs: Soak 003 (`docs/rvs/soak-003-inertia-pareto.md`),
H₁ (conceptual convergence), H₂ (symbolic drift).
Adds `docs/rvs/soak-004-symbolic-drift.md`, the H₂
hypothesis test. The architecture review named a
falsifiable claim:

  "As a stable dialectical interaction matures, lexical
   content shifts from object-centered vocabulary toward
   relational vocabulary while semantic inertia remains
   low."

**The data answers this without a red-team test.**

By comparing heard (user-driven) vs spoken (model-generated)
counts of the user's named relational terms, the
architecture review's "lexical vs structural convergence"
question has a clean answer:

  1. The relational vocabulary is *real*, not zero. Top
     terms: through (23), us (20), between (14), value
     (11), space (10).

  2. The relational vocabulary is *model-amplified*,
     not user-driven. Every relational term appears
     *more often* in spoken than heard, with ratios
     1.5× (us) to 7× (value) to ∞ (together, which
     appears 0× in heard and 4× in spoken).

  3. The relational vocabulary is *not* scaffold-driven.
     None of the user's named terms appear in either the
     system prompt or the per-turn template. They are
     emerging from the model itself.

  4. The "in a live dialogue" scaffold (16 turns) is a
     *separate* linguistic attractor from the relational
     vocabulary. They are different phenomena with
     different fixes:
       - scaffold → fix the prompt template
       - relational → fix the model selection or add
         guidance toward object / process vocabulary

**The H₂ hypothesis verdict:**

| criterion                                  | status |
|--------------------------------------------|--------|
| low semantic inertia                       |   ✓    |
| stable/decreasing policy inertia           |   ✓    |
| increasing frequency of relational terms   |   ⚠ flat (not increasing)  |
| without scaffold repetition increasing     |   ✓    |

H₂ is *partially* supported. The relational vocabulary
is prominent and stable, but it is *not* increasing over
the 304-turn run. P(object) and P(process) are both
decreasing by ~50%, which is consistent with the Soak 003
attractor finding (linguistic_inertia 0.365): the system
is converging toward a small set of relational scaffolds
because it's producing *less of everything else*.

**H₂' refinement (more accurate):**

  "Long-running dialectical interactions develop a
   stable relational vocabulary that is model-amplified
   (the model uses relational words more than the user
   does) without requiring either increasing linguistic
   inertia or scaffold repetition."

This is a falsifiable restatement. The expected
proportions would form the acceptance criteria for a
`contemplative_v4.yaml` hypothesis YAML when the
`feature/research-hypotheses` branch opens.

**Why a red-team test is no longer the urgent next step:**

The architecture review suggested removing the
"in a live dialogue" scaffold and re-running soaks to
determine whether the relational vocabulary is prompt-
leakage or emergent. The data already answers this:

  - The relational vocabulary is *not* in the scaffold
    (no named term appears in either prompt or template)
  - The relational vocabulary is *model-amplified*
    (every term appears 1.5×-7× more in spoken than heard)
  - Therefore the relational vocabulary is *model-emergent*,
    not prompt-leakage

The red-team test would still be a useful methodology
check, but the conclusion is already supported by the
heard-vs-spoken ratio. Building a `--no-scaffold` flag
is a separate scope, deferred.

Refs: Soak 003, the architecture review's H₁ and H₂
framings, "measure before interpreting" discipline.
Adds the **Relational Representation Bias** as a first-class
metric on the dialectic analyzer and the Pareto extractor.

**The metric:**

  RRB = P(relational | spoken) / P(relational | heard)

  RRB = 1.0  → no amplification
  RRB > 1.10 → amplification
  RRB < 0.90 → suppression

**Why a ratio, not a difference:** the ratio is comparable
across runtimes, models, and interaction lengths without
caring about any specific vocabulary. P(relational | heard)
acts as a per-conversation baseline.

**Why no specific vocabulary:** the metric is defined
against the `RELATIONAL_TERMS` set in
`Scripts/analyze_dialectic.py`, but the choice of which
words count as "relational" is a *hypothesis input*. The
metric itself is the ratio; the vocabulary list is iterable.

**The headline finding: RRB is a function of time scale.**

  live_283t  → RRB 1.22 (amplification)
  F_qwen05b  → RRB 0.55 (suppression)
  F_qwen15b  → RRB 1.05 (neutral)

Same Qwen 0.5B model, opposite RRB. The amplification
emerges over extended dialogue. The 30-turn matrix corpus
is too short to surface the bias; the 283-turn live run
surfaces it. This is a clean, falsifiable finding.

**Three reframings (per the architecture review):**

  1. The "not scaffold-driven" claim is weakened to
     "not explained by the currently identified prompt
     scaffolds." Future evidence might show indirect
     prompt influence.
  2. The headline is now "the model preferentially
     reformulates interactions in relational terms" — a
     behavioral bias, not a vocabulary preference.
  3. Vocabulary targets are *not* encoded into hypothesis
     YAMLs. The hypothesis tunes *parameters* (exploration
     pressure, synthesis pressure, silence threshold,
     witness grounding, coherence weighting); the RRB
     measurement tells us whether the parameters changed
     the bias.

**The causal direction is preserved:**

  Hypothesis → behavior (parameters) → measured RRB
NOT
  Desired vocabulary → prompt engineering

This is the discipline that keeps the system scientific
rather than steering it toward preferred language.

**The cross-model benchmark table (forward-looking):**

| Model       | RRB  | Semantic inertia | Linguistic inertia |
|-------------|-----:|-----------------:|-------------------:|
| Qwen 0.5B   | 1.22 |             0.05 |               0.36 |
| DeepSeek    | 0.9  |             0.08 |               0.18 |
| Claude      | 1.4  |             0.04 |               0.21 |

The table is the *forward target* the cross-model dialectic
work enables. The current data gives us only the Qwen 0.5B
row; DeepSeek and Claude are blocked by the silent-turn
issue and Sonnet rate limit respectively. The benchmark
lands when those unblock.

**What changed in this commit:**

- `Scripts/analyze_dialectic.py`: new `RRBReport` dataclass
  + `compute_rrb()` + report section 13
- `Scripts/pareto_frontier.py`: new `rrb` and `rrb_deviation`
  fields on the point extract; `rrb_deviation` is a default
  Pareto objective (minimize |RRB - 1|)
- `docs/rvs/soak-004-symbolic-drift.md`: rewritten with the
  RRB framing, the three reframings, the time-scale finding,
  the cross-model benchmark table

**Why the H₂ hypothesis verdict changed:**

The first version of Soak 004 said H₂ was "partially
supported." The RRB framing makes that more precise:
H₂ is *partially* supported because the model amplifies
relational vocabulary at a *constant rate* (RRB ≈ 1.2),
not a *growing rate*. The H₂' refinement is now
"stable model-amplified relational vocabulary" instead of
"increasing relational vocabulary over time."

Refs: Soak 003, the architecture review's five
refinements, the "behavioral bias not vocabulary
preference" framing.
…eed)

Adds the **rhetorical motifs** and **epistemic orientation**
metrics to the dialectic analyzer. These are the third
layer in the closed empirical loop — after lexical
(`symbolic_drift`, `RRB`) and structural (`inertia`).

**The architecture review's question:**

> "Two reflective outputs exhibit a *shared rhetorical
>  structure*, not just shared vocabulary. They both follow
>  difficulty → recognition → inner resource → transcendence.
>  Why?"

**The five motif classes:**

  adversity      — challenge, struggle, difficulty
  inwardness     — within, inner, yourself
  transcendence  — transcend, beyond, transform, evolve
  observation    — notice, observe, witness, see
  investigation  — examine, compare, analyze, question

Vocabularies are module-level constants
(`ADVERSITY_TERMS`, `INWARDNESS_TERMS`, etc.) in
`Scripts/analyze_dialectic.py` — hypothesis inputs,
not ground truth.

**The teleological ratio (the headline metric):**

  teleological_rate = (transcendence + inwardness) / total
  epistemic_rate    = (observation + investigation) / total
  ratio             = teleological_rate / epistemic_rate

  ratio > 1.10  →  teleological (presupposes inner resource
                  + goal of transcendence; "how do I see
                  the strength within to transcend?")
  ratio < 0.90  →  epistemic (examines assumptions without
                  presupposing outcome; "how do I investigate
                  the assumptions that are limiting me?")

**The headline finding: same prompt, opposite orientation.**

| cell              | tele_ratio | orientation  |
|-------------------|-----------:|--------------|
| F_qwen05b         | 0.18       | epistemic    |
| R_qwen05b         | 0.12       | epistemic    |
| C_qwen05b         | 0.40       | epistemic    |
| F_qwen15b         | 0.55       | epistemic    |
| **R_qwen15b**     | **1.36**   | **teleological** |
| F_qwen3b          | 1.14       | teleological |
| live_283t         | 0.36       | epistemic    |

R_qwen05b (0.12) and R_qwen15b (1.36) ran the *same
reflective prompt* and produced opposite epistemic
orientations. The model is the dominant variable, not
the prompt. **Training-distribution bias (Possibility 1)
is the most likely cause** of the architecture review's
named "shared rhetorical structure" pattern.

**Three findings worth paragraphs:**

  1. The "shared rhetorical structure" is real and
     measurable. R_qwen15b (the one matrix cell that
     crosses into teleological territory) has the
     adversity → inwardness → transcendence pattern
     visible in the motif rates. Future hypothesis YAMLs
     can specify acceptable motif rate bands.

  2. Training-distribution bias is dominant. The cross-
     cell comparison rules out the prompt as the
     primary cause: same prompt, opposite orientation
     by model size.

  3. The Witness layer's design philosophy is at stake.
     The architecture review's framing: an epistemic
     orientation is more consistent with NeuralCompose's
     design philosophy (Witness = observation, not
     steering). A `reflective_v2.yaml` hypothesis should
     target `teleological_ratio < 0.80` and
     `motif.transcendence < 3.0` per 1000 words.

**Per-outcome motif rates on the live data:**

  synthesis: transcendence 2.87, investigation 3.19
             → teleological_ratio 1.16
  coherence: transcendence 1.10, investigation 5.72
             → teleological_ratio 0.34
  displacement: transcendence 1.58, investigation 8.36
                → teleological_ratio 0.43

Synthesis outcomes reach for "transcend / beyond /
transform" language and reduce analytical vocabulary
(investigation drops from 5.72 to 3.19). The synthesis
mode is *transcendence-flavored* by its very nature —
but "transcendence-flavored" in a research context
might mean "skips the analytical examination step."

**Why this matters for ResearchHypothesis:**

The hypotheses are now falsifiable end-to-end. The
`ResearchHypothesis` schema (when the
`feature/research-hypotheses` branch opens) will
support `predictions` as a structured block. A
hypothesis is admitted to the Pareto frontier if it
*dominates* the existing configuration on the metrics
that matter — including the epistemic-orientation axis.

The architectural loop is now:
  ResearchHypothesis (YAML + parameters + predictions)
    → Runtime → Telemetry → Metric extraction
    → Compare to predictions (in-band → admit)
    → Pareto analysis → Next hypothesis

**What changed in this commit:**

- `Scripts/analyze_dialectic.py`: 5 motif term sets
  (`ADVERSITY_TERMS`, `INWARDNESS_TERMS`, `TRANSCENDENCE_TERMS`,
  `OBSERVATION_TERMS`, `INVESTIGATION_TERMS`) +
  `MOTIF_CLASSES` dict + `RhetoricalMotifsReport` dataclass
  + `compute_rhetorical_motifs()` + report section 14
- `SoakRuns/soak-002-20260721-220848/matrix.json`:
  refreshed with rhetorical_motifs fields
- `docs/rvs/soak-005-rhetorical-motifs.md`: full findings
  doc with the 11-point comparison, the per-outcome
  breakdown, the training-distribution-bias finding, the
  Witness-design-philosophy finding, the future
  `reflective_v2.yaml` acceptance criteria

Refs: Soak 003 (inertia), Soak 004 (RRB), the
architecture review's framing on teleological vs
epistemic discourse, the "shared rhetorical structure"
observation, the "behavioral bias not vocabulary
preference" framing.
Adds the **Level of Abstraction** as a 5-vector metric on
the dialectic analyzer. The architecture review named a
fourth orthogonal behavioral axis:

> "Reflective dialogue may exhibit upward abstraction
>  drift over time, moving from concrete problem-solving
>  toward increasingly general relational, societal, or
>  existential framing."

**The 5-vector LoA:**

  [concrete, interactional, relational, societal, existential]

Each level is a vocabulary class:

  concrete      — runtime, json, ollama, benchmark, telemetry,
                   file, code, function, system, model
  interactional — dialogue, conversation, witness, response,
                   reply, turn, exchange, voice
  relational    — between, together, relation, value, sign,
                   us, through, among, within, toward
  societal      — community, culture, social, society, media,
                   institutions, public, people
  existential   — human, humanity, condition, mortality, meaning,
                   transcendence, existence, being, soul

**abstraction_shift** is a single-number summary:

  abstraction_shift = Σ (i/4) * (second[i] - first[i]) for i in 0..4

  > +0.05  →  upward drift (H₄ supported)
  < -0.05  →  downward (H₄ refuted)
  otherwise  →  no significant drift

**The headline finding: H₄ is partially supported, with a twist.**

The live data (304 turns) shows:

  abstraction_shift = +0.044  (just below the +0.05 threshold)

  concrete        -9.09pp ↓
  interactional  +10.26pp ↑
  relational      -4.37pp ↓
  societal        -3.09pp ↓
  existential     +6.29pp ↑

The drift is *not* a clean ladder climb. It's a *bimodal*
shift: from concrete + relational → to interactional +
existential. The dialogue is moving *both* toward
meta-conversation *and* toward abstraction, while
losing concrete grounding.

**Cross-cell matrix: H₄ is model-dependent.**

  F_qwen05b     +0.219  (H₄ supported)
  F_qwen15b     +0.100  (H₄ supported)
  live_283t     +0.049  (no drift, just below threshold)
  R_qwen15b     -0.000  (no drift)
  R_qwen05b     -0.036  (no drift)
  C_qwen05b     -0.033  (no drift)
  F_qwen3b      -0.100  (downward — H₄ REFUTED)

Same prompt, opposite drift by model size. **The 3B
model is more grounded than the smaller models.** This
is a counter-intuitive finding (bigger = more abstract
would be the default expectation), but consistent with
prior soaks: Qwen 3B focused has the lowest ngram
diversity and is more teleological than the smaller
models. The 3B model *settles into* a relational/
teleological register rather than climbing the
abstraction ladder.

**The architecture review's three candidate explanations:**

  1. Training-distribution bias: bigger models see more
     abstract discourse in their training data, but
     this finding is INVERTED on Qwen 3B.
  2. Prompt-template constraint: ruled out by the
     cross-cell comparison (same prompt, opposite drift).
  3. Genuine attractor: cannot be ruled out, but the
     model-dependence suggests an interaction between
     model and prompt, not a prompt-only attractor.

**Three findings worth paragraphs:**

  1. The drift is bimodal (concrete + relational →
     interactional + existential), not ladder-like.
     The dialogue transitions between two distinct
     kinds of self-reference: meta-conversational and
     meta-existential.

  2. H₄ is a model-dependent phenomenon. The cross-cell
     matrix rules out the prompt as the dominant cause.
     "H₄ holds for Qwen 0.5B and 1.5B, but not for
     Qwen 3B focused."

  3. The architecture review's "healthy vs unhealthy
     trajectory" distinction is real but not yet
     captured by LoA. A future `concrete_recurrence`
     metric (does the dialogue return to concrete
     vocabulary after abstraction drift?) would
     distinguish the two. Needs longer runs (1000+
     turns) to be meaningful.

**The closed empirical loop now has FOUR orthogonal
behavioral metrics:**

| axis    | metric             | what it captures                   |
|---------|--------------------|-----------------------------------|
| Inertia | sem/ling/policy    | resistance to change              |
| RRB     | relational amp.    | model adds relational framing?    |
| Motifs  | tele vs epistemic  | model presupposes outcomes?       |
| **LoA** | **5-vector drift** | **dialogue gets more abstract?** |

A `ResearchHypothesis` YAML can target acceptance
criteria on all four axes. Pareto-dominance is
evaluated on all four. Hypotheses are kept because
they dominate the frontier on measurable criteria.

**What changed in this commit:**

- `Scripts/analyze_dialectic.py`: 5 LoA term sets
  (`CONCRETE_TERMS`, `INTERACTIONAL_TERMS`,
  `RELATIONAL_TERMS_LOA`, `SOCIETAL_TERMS`,
  `EXISTENTIAL_TERMS`) + `LOA_CLASSES` dict + `LOA_ORDER`
  + `LevelOfAbstractionReport` dataclass +
  `compute_level_of_abstraction()` + report section 15
- `SoakRuns/soak-002-20260721-220848/matrix.json`:
  refreshed with level_of_abstraction fields
- `docs/rvs/soak-006-loa.md`: full findings doc with
  the 11-point cross-cell comparison, the bimodal
  drift finding, the model-dependence finding, the
  4-axis behavioral fingerprint

Refs: Soak 003 (inertia), Soak 004 (RRB), Soak 005
(rhetorical motifs), the architecture review's H₄
framing, the "healthy vs unhealthy reflective
trajectory" distinction.
… schema

Captures the architecture review's structural shift: the
project is no longer "an AI application" but an
**experimental platform** with three orthogonal concerns
(SCIENCE / ENGINEERING / COMPUTATION) evolving at
different rates.

**The three concerns:**

  SCIENCE       — what we learn        (Experiment, ResearchHypothesis)
  ENGINEERING   — how we execute       (Runtime, Telemetry, Metrics)
  COMPUTATION   — what executes        (Swift, Rust, Scientific Services)

These evolve at different rates: Science frequently,
Engineering occasionally, Computation slowly. The
separation lets one layer be replaced without disturbing
the others.

**The contracts that bridge concerns:**

  Science ↔ Engineering:  metric contracts (frozen)
  Engineering ↔ Computation:  runtime interfaces (stable)

**The closed loop, recast:**

  Science:   Experiment → ResearchHypothesis
  Engineering: Runtime → Telemetry → Metrics
  Computation: Swift kernels, Rust kernels, Scientific services

  Hypothesis (Science) refers to metric ids (Engineering)
  by name. Runtime (Engineering) calls into compute
  kernels (Computation) through stable interfaces.

**The four metric contracts (`docs/evaluation/metrics.md`):**

  1. `inertia`              — resistance to change
  2. `rrb`                  — relational amplification
  3. `rhetorical_motifs`    — teleological vs epistemic
  4. `level_of_abstraction` — 5-vector abstraction drift

Each contract specifies: id, purpose, inputs, outputs,
known_failure_modes, validation. Frozen as of 2026-07-21.
Changes to a metric's *implementation* are allowed
(synonym additions, vocabulary refinements) but must be
backwards-compatible. Changes to a metric's *contract*
require an ADR-style proposal and a new id.

**The experiment schema (`docs/evaluation/experiments.md`):**

```yaml
experiment:
  id: EP-001
  question: Does reducing synthesis pressure lower abstraction drift?
  hypotheses: [reflective_v2, contemplative_v4, reflective_baseline]
  metrics: [inertia, rrb, rhetorical_motifs, level_of_abstraction]
  predictions: {...}
  decision_rule: pareto
```

The schema separates *questions* (experiments) from
*proposed answers* (hypotheses). This scales once you
have dozens of hypotheses — each hypothesis stays
focused on parameterization; each experiment captures
the scientific question.

**The shift in framing:**

  Before:  "Lacan mode" — a philosophy embedded in code
  After:   "Increasing continuation pressure changes
            measurable dialogue behavior" — a falsifiable
            claim about a parameter and an outcome

The books become sources of hypothesis generation
rather than authorities embedded in code. Wolfram
suggests continuation pressure; Lacan suggests
signifier weight. The parameters are the test of
whether the framing has predictive value.

**The runtime unification (the next merge):**

  Current:    Live App
                    \
                     \
              Harness -------> Telemetry

  Target:           RuntimeFactory
                          │
              ┌───────────┴───────────┐
              ▼                       ▼
           Live App               Harness
              │                       │
              └───────────┬───────────┘
                          ▼
                      Telemetry

The merge is more important than the next feature.
Opening `feature/research-hypotheses` before runtime
unification risks fragmenting experiments across two
execution paths. The merge candidate is
`feature/pluggable-generators` into `main` after the
runtime unification lands.

**Rust's clarified role:**

Rust is not arriving to "make NeuralCompose faster."
It's arriving to stabilize deterministic computational
kernels beneath a mature experimental framework. The
four-gate evaluation order (Correctness → Numerical
stability → Determinism → Performance) is *the*
discipline that makes this scientific. When Phase 0
begins, it will already have stable telemetry, stable
benchmarks, acceptance criteria, repeatable
experiments, and reproducible runtime selection.

**What changed in this commit:**

- `docs/evaluation/metrics.md` (NEW, 16K): the four
  metric contracts, frozen. Includes cross-axis
  orthogonality table, future metrics (out of contract),
  and the boundary between Science and Computation.
- `docs/evaluation/experiments.md` (NEW, 7K): the
  experiment schema. Separates questions from proposed
  answers. Includes field reference, what an experiment
  is *not*, the closed loop in three concerns, and the
  work to land the schema when the
  `feature/research-hypotheses` branch opens.
- `docs/architecture/three-orthogonal-concerns.md`
  (NEW, 9K): the structural frame. Captures the shift
  from "AI application" to "experimental platform",
  the runtime unification target, Rust's clarified
  role, and the offline scientific services tier.

No code changes. No new metrics. The metric-accumulation
phase is over; the measurement layer is frozen. The
next concrete work is the runtime unification (Priority
1 per the architecture review).

Refs: The architecture review on 2026-07-21; the
four-behavioral-axis framework from Soaks 003-006;
the closed empirical loop from Soak 003.
…hread)

Adds `docs/scoping/eeg-encoder-realignment-scope.md`, the
scoping doc for the EEG encoder re-alignment work that
surfaced after the artifact-gate demean fix landed.

The doc captures the precise problem: with the demean
fix in place, the estimator emits states and the gloss
reaches the dialectic (`glossScalar 0.5 → 0.26`
observed live). But every non-null state this session
was `"High load"` (7/7). The encoder does not
discriminate the five spectral/cognitive states — it
collapses to one.

The doc pre-registers the "done" criteria (held-out
balanced-accuracy threshold, 5-fold within-subject CV,
n ≥ 50 trials per class) *before* training — per the
Track-B discipline of pinning the metric first.

This is unrelated to the dialectic runtime / Soak 002
work, but it's a real scoping artifact that needs to be
tracked. The encoder realignment is a model-quality
problem; no amount of electrode/gate work moves it.

Refs: Track B pre-registration discipline (CLAUDE.md);
the artifact-gate demean fix (#21) that unstuck the
gloss mechanically but exposed the real bottleneck.
The four 1-cell smoke-test runs from iterating on the
matrix runner are dev history, not longitudinal data.
Their `matrix.json` and `leakage.json` files are empty
or partial. Exclude them from git tracking so they
don't pollute the commit history, but keep them on
disk for reference.

The 10-cell successful run (soak-002-20260721-220848)
stays committed — that's the longitudinal artifact.
…code

Adds `docs/architecture/engineering-runtime.md`, the
design document that scopes Codex (and future
engineering backends) before any integration code is
written. The user named the principle:

> "The mistake would be to define Codex by its
>  *provider* (OpenAI Codex). Instead, define it by
>  its *role* in the platform."

The role is:

> **Codex is a deterministic engineering
>  implementation runtime that accelerates software
>  development while remaining fully subordinate to
>  the Experiment → Hypothesis → Runtime → Telemetry →
>  Metrics framework.**

The design doc has eight sections:

  1. **Purpose** — software-modification tasks that are
     deterministic, bounded, specifiable, reviewable
  2. **Scope** — what the Engineering Runtime IS
  3. **Non-goals** — what it IS NOT (the four hard
     limits: no merge, no approve, no metric modification,
     no autonomous commit)
  4. **Interfaces** — Task → ImplementationRuntime →
     Patch → Build → Tests → Telemetry → Human Review
     → Merge. With Task and Patch YAML schemas.
  5. **Governance** — explicit weekly/monthly budget,
     allowed tasks list, prohibited actions list
  6. **Evaluation** — engineering metrics (build success
     rate, test pass rate, regression rate, review
     iterations, time-to-completion, patch size,
     contract violations, budget utilization), with
     a comparative table for cross-implementation
     evaluation
  7. **Sequencing** — gated on the architecture review's
     ordering: LiveRuntimeFactory fix → merge → add
     CodexRuntime → research-hypotheses branch
  8. **Why this is not "just another AI tool"** —
     the four hard limits are what keep it useful

**The key separation:**

  GenerationRuntime   — generates language for users
                        (Claude, Ollama, Stub)
                        evaluated on dialogue metrics
                        (RRB, motifs, LoA, inertia)

  ImplementationRuntime — modifies software artifacts
                          (Codex, Claude Code, Hermes, Human)
                          evaluated on engineering metrics
                          (build, tests, regression, etc.)

Keeping them separate prevents accidentally evaluating
code assistants with dialogue metrics.

**The four hard limits (encoded in §3):**

  - No merge to main
  - No approving experiments
  - No modifying metric contracts
  - No autonomous commits
  - + no inventing research questions

These are the difference between Codex as a useful
tool and Codex as a stakeholder. The platform has no
mechanism for managing AI stakeholders; the limits
keep Codex in the tool role.

**The long-term evolution (encoded in §6):**

Eventually multiple `ImplementationRuntime`s are in
active use (Codex, Claude Code, Hermes, Human). They
can be compared on engineering metrics — the same
way dialogue runtimes are compared on the four-axis
behavioral fingerprint. The comparative table is the
*target* of the rollout; the *initial* rollout is
just Codex (gated on the sequencing).

**Why this commit is docs-only, no code:**

The user named the discipline:

> "I would create a short design document before any
>  implementation, perhaps
>  `docs/architecture/engineering-runtime.md`."

The design doc is a *governance artifact* that lives
next to the metric contracts, the experiment schema,
and the three orthogonal concerns. It is not a
*promise* to implement anything; it is a *scope* that
constrains the implementation when it comes.

The implementation (Step 3 in §7) is gated on:

  1. LiveRuntimeFactory env-var fix (small, focused,
     on this branch)
  2. Merge `feature/pluggable-generators` into `main`
  3. THEN add CodexRuntime behind the
     `ImplementationRuntime` interface

In that order. The user said:

> "Codex joins an already mature system instead of
>  becoming another moving part during stabilization."

Refs: `docs/architecture/three-orthogonal-concerns.md`;
`docs/evaluation/metrics.md`;
`docs/evaluation/experiments.md`; the architecture
review on 2026-07-22.
aurascoper and others added 19 commits October 13, 2026 18:37
…-test

a09ad5b left two rules untested because they looked like races: a late
callback from a replaced listener must not move the state, and terminal
states must hold for a session only. Neither needs a race.

- testStaleListenerCallbackCannotRewriteState: the write rule takes
  (state, source) and checks the source against the current listener,
  so the test hands it a never-started NWListener directly (.failed,
  .waiting, and the onTermination path) and asserts the live session
  still reads .ready. recordListenerState/recordListenerCancelled drop
  `private` (internal) for this; no behaviour change.
- testTerminalStateIsPerSessionRestartReachesReady: session 1 fails on
  an occupied port (.failed, kept across stop()); the port is freed;
  session 2 on the SAME instance must reach .ready. The supervisor
  reuses one stream across its reconnect retries, so a terminal state
  that outlived its session would make diagnostics lie after every
  reconnect. The stream's port is fixed at init, so the restart frees
  the port instead of moving to another one; the occupier is a bare
  NWListener so the test awaits its own .cancelled report rather than
  sleeping on port release.
Ports: testPort+12 (57194) and +13 (57195).

Mutations, detached throwaway worktree, target test alone:
- M3 identity guard removed in recordListenerState: RED, "failed" !=
  "ready", exit 1 (nc-p2-mut-M3.log)
- M3b identity guard removed in recordListenerCancelled: RED,
  "cancelled" != "ready", exit 1 (nc-p2-mut-M3b.log)
- M4 recordStarted routed through the terminal-state rule (terminal
  sticks across sessions): RED, "failed" != "ready", exit 1
  (nc-p2-mut-M4.log)

Verified, Swift 6.4, on 2f203df + this change, Scripts/run-tests-verified.sh
three times: each VERIFIED executed 542, skipped 10, failures 0, runner
exit 0, 9/9 bundles, no signal lines (nc-p2-floor542-run{1,2,3}.log).
Pin 540 -> 542 in this commit.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

(cherry picked from commit 1319547aed6d7e4b9714742c00279adf10fa328c)
Ported to feat/peer-bridge 2026-10-13 without its Tests/MetaTests/test-count-pin.json
hunk: MetaTests does not exist on this branch.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The interaction logs from Aug 7 and Oct 13 hold 46 dialectic turns. The 43
Claude turns carry no generatorFingerprint; the 3 Ollama turns do. The factory's
claude case returned a bare ClaudeCLIGenerator, which conforms only to
TextGenerating, so the loop's metadata capture had nothing to read. A Claude
turn could not be attributed to a provider, model or prompt.

The claude case now builds ClaudeCLIGenerationRuntime wrapped in
GenerationRuntimeTextGeneratingAdapter, matching the Ollama path. This ports the
intent of abb0eea (docs/eeg-methods-scope) by hand: cherry-picking it would
pull in PR #32's factory rewrite. The claude -p argv and the /usr/bin/env PATH
lookup are unchanged, and a test pins the argv equal to the legacy generator's.

make() takes promptProfile so metadata names the real profile; the app passes
.wakingDialectical and .witness instead of loaded text, which recorded as
"custom" (Ollama turns read custom today). Caller-supplied text still records
as custom, hashed over the bytes sent. claudeExecutablePath is the test seam.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
DialecticalTurnEvent carried one generatorFingerprint, documented as the
generator that produced the candidates. A persisted Reflective turn could
therefore prove that a Witness ran and what it found, but not which
provider, model, prompt profile, or prompt hash produced the finding — and
the bug A2 fixed was precisely "reported Witness prompt ≠ prompt actually
transmitted". The wiring is proven statically and in focused tests; the
turn record could not attest it independently.

DialecticalCompetition and DialecticalTurnEvent gain an optional
witnessGeneratorFingerprint. The loop gives the Witness its own metadata
box and callback (recordWitnessMetadata), parallel to the pole capture and
never shared with it — filing both in one box would make the last writer
win, a turn record attesting the pole prompt for the Witness.
attachMetadataCaptureFromAdapter now wires both generators, so the app
(AppViewModel) and the headless harness (dialectic-session), which both
already call it, start persisting Witness provenance with no call-site
change. The fingerprint is gated on witnessAttempted: a turn on which the
Witness never ran must not attest a Witness identity, however recent the
box contents.

Decoding stays backward-compatible in both directions: pre-field logs
decode with nil (missing Optional key), and a nil fingerprint encodes as
an absent key, byte-shape-identical to the pre-field format.

analyze_dialectic.py's provenance rollup now reports witness-fingerprint
counts and models, plus a witness/pole prompt-hash collision count — the
collision is the old bug's signature and must read 0.

Tests: pole and Witness fingerprints captured separately with distinct
prompt hashes on the same logged event; no Witness attestation when the
profile disables it; codec round-trip of both fingerprints; a
pole-fingerprint-only log decodes with the Witness field nil.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
(cherry picked from commit db01432)
The app rebuilds the dialectic loop on every mode switch and turnIndex restarts
at 0. Oct 13's file has 16 turns from 9 loop instances, with index 0 nine
times, so a turn cannot be told apart from another run's turn of the same index,
and nothing orders them except line position.

DialecticalTurnEvent gains runID (one per loop instance, injectable, default a
fresh UUID) and recordedAt (ISO 8601 UTC with fractional seconds). Both are
Optional so older logs still decode. recordedAt is a String, not a Date: the
app's TelemetryLogger encodes dates as ISO 8601 while the harness and the tests
use a plain encoder/decoder, so a Date field would not round-trip across them.

The analysis scripts tolerate the extra keys and are left as they are; teaching
them to group by runID is a follow-up.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…abulary

The Oct 13 interaction log shows the listener mishearing names (Oklo as "Oak
low", "Gabon's" and "Globe"; samarium as "Samarian"; Feynman as "Fineman")
and handing the loop sentence fragments ("...so the", "...like the",
"...once we're"). Two mechanisms could cut a sentence, and the log can't say
which fired: the turn ended at the recognizer's first isFinal, which fires on
short pauses, and the 15 s listen timeout capped the whole utterance.

Now the timeout bounds only the wait for speech to start. Once words arrive the
turn ends after trailingSilence (default 1.8 s) with no new words, or at a 60 s
backstop. isFinal closes a segment, and recognition continues on a fresh
request fed by the same tap; segments are joined. The rule lives in
UtteranceEndpointer, a pure value type with its own tests, since the listener
needs a mic. A recognizer error now returns what was heard instead of nil.

Every request carries contextualStrings from voice-profile.json's new
recognitionVocabulary key; endOfUtteranceSilence overrides the 1.8 s. Both are
optional and hand-edited (Scripts/voice-profile.py preserves unknown keys).
AppContainer keeps the loaded profile so the lazily built listener can read it.

Live behaviour needs a microphone and is not covered by tests.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Every model path was resolved against the working directory. That is the repo
under swift run, but / for an app opened from Finder or open, so the installed
app logged "No Core ML model at /Models/IntentClassifier.mlmodelc" and
"Spectral encoder model not found at /Models/EEGEncoder", and fell back to
stubs. All 1,125 health records from Aug 7 and Oct 13 say embedderKind stub, so
every dialectic turn in those logs was scored on the deterministic stub
embedder.

ModelLocator resolves a model name through $NEURALCOMPOSE_MODELS_DIR, then
Models/ under the working directory (so swift run keeps using the repo's copy),
then ~/Library/Application Support/NeuralCompose/Models. The five lookups
(BGE, MLX predictor, spectral encoder, intent classifier, world-model demo) go
through it; their per-model env overrides still come first. With nothing found
the old relative path is returned, so the not-found logs are unchanged.

Scripts/install-models.sh copies each Models/ entry that has weights into
Application Support. It skips folders holding only tokenizers, and never
deletes or overwrites: an installed copy that differs is reported for removal
by hand. Today only EEGEncoder has weights; BGE, Qwen and MiniLM were swept
again and need rebuilding first.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The Oct 13 interaction log shows follow-ups answered without their context:
"Could you reiterate on that framework" drew "don't reiterate the framework
at all", because each voice was sent only the latest utterance and had no
framework in front of it.

ConversationHistory holds what was heard and what was voiced in reply, never
the losing candidate and never the Witness's finding. The loop prepends the
last historyExchanges (default 4) to both voices' prompts, labeled "They
said" / "You replied", with silent turns kept as "You stayed silent." and a
header saying the lines are context only. historyExchanges = 0 restores the
old prompt exactly. The Witness prompt and Mirror mode are unchanged.

AppViewModel owns one history and hands it to every loop it builds, so a mode
switch keeps the thread. It is cleared when the loop is turned off and when
the runtime changes, so one provider is never handed another's replies.
Nothing is written to disk.

Earlier transcript text now leaves the machine again on later turns, so
decision-registry entry 8 gains a dated amendment and the dialectic
disclosure under the toggle says so.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…context, add self-identity and math ASR vocabulary
…ion group, and Brett to default recognition vocabulary
…Pillar Functor HUD, and Semantica-Multica bridge
…e Layer Guide popover, and deterministic recall selection
…comparison, homotopy equivalence, and late-night log insights
…y-gate autobank/autoforget, 2026-11-01 interaction logs, functor Pareto sweep, and pre-1931 corpus manifest
…her-genus Pareto handles, debiased CKA, and sync latest 2026-11-01 health logs
…ue to LLM, 4-Pillar Functor, and claude-mind golden reconciliation
…phonetic recovery, and SQLite/PG autobank sync
@aurascoper
aurascoper force-pushed the fix/muse-signal-health branch from b3830b3 to 00933dc Compare November 2, 2026 06:19
…1437 equifinal turns, bank verified Basilisk M7 planetary reference claims, and add high-potential warrant rescue
@aurascoper
aurascoper force-pushed the fix/muse-signal-health branch from 00933dc to d8587de Compare November 2, 2026 06:20
…lete L156 ASR phonetic recovery, and enforce privacy-scrubbed fixture manifest checks
…ert PostgreSQL ASR rows, and emit Basilisk M7 audit
…L PII/dash scrub, write-time dash sanitization, and MATLAB R2026b ALARA/Hippocratism bridge
… pH 5.80/pe 6.40/beta_1 3, and 4-block Neurospora MATLAB fixtures
…oller, and Multica sonnet-5/5.5/haiku warrant gates
…C telemetry harmonization, MATLAB R2026b fixtures, and exclude private health/prosody logs
@aurascoper aurascoper closed this Nov 2, 2026
@aurascoper
aurascoper merged commit a4e8cce into main Nov 2, 2026
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.

1 participant