Spaces:
Running
Running
chore(sync): mirror backend .py + Dockerfile to Space (hf-sync-backend)
Browse filesAutomated backend sync from szl-holdings/a11oy main via hf-sync-backend.
Updated (differed from the Space): Dockerfile, serve.py, szl3d_holographic.py, szl_brainground.py
Deleted (gone from the repo + Dockerfile COPY set): (none)
Keeps the Space-built backend (serve.py + the Dockerfile-COPY'd .py
modules) identical to GitHub main so the Space never rebuilds from a
stale backend, new endpoints don't 404 there, and orphaned modules
removed from the repo don't linger in the Space tree.
- Dockerfile +11 -0
- serve.py +19 -0
- szl3d_holographic.py +1 -0
- szl_brainground.py +524 -0
Dockerfile
CHANGED
|
@@ -1528,6 +1528,17 @@ COPY szl_honestywall.py ./szl_honestywall.py
|
|
| 1528 |
# adds NOTHING to the locked-8; Λ = Conjecture 1; trust ceiling 0.97; no green.
|
| 1529 |
COPY szl_agentos.py ./szl_agentos.py
|
| 1530 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1531 |
# WAVE R Dev 1 — boot-resilience env/secret preflight. Per-file COPY (this
|
| 1532 |
# Dockerfile has NO `COPY . .`; the copy-completeness guard requires every module
|
| 1533 |
# reachable from serve.py to appear in the COPY set). szl_boot_preflight.py is
|
|
|
|
| 1528 |
# adds NOTHING to the locked-8; Λ = Conjecture 1; trust ceiling 0.97; no green.
|
| 1529 |
COPY szl_agentos.py ./szl_agentos.py
|
| 1530 |
|
| 1531 |
+
# BRAINGROUND (feat/frontier-brainground) — per-file COPY (this Dockerfile has NO
|
| 1532 |
+
# `COPY . .`; the copy-completeness guard requires every module reachable from
|
| 1533 |
+
# serve.py to appear in the COPY set). szl_brainground.py is imported by serve.py and
|
| 1534 |
+
# scores the brain's OWN grounding_subgraph (szl_brain_api, COPY'd above) into a
|
| 1535 |
+
# grounding_confidence + honest verdict (GROUNDED/WEAK-GROUNDING/INSUFFICIENT-
|
| 1536 |
+
# GROUNDING) so the brain can honestly abstain when the grounding is weak. Its 3D
|
| 1537 |
+
# surface brainground.js ships via the existing whole-tree `COPY static/3d/
|
| 1538 |
+
# ./static/3d/` above. Read-only over knowledge-graph retrieval — adds NOTHING to the
|
| 1539 |
+
# locked-8; Λ = Conjecture 1; trust ceiling 0.97; MODELED (never MEASURED); no green.
|
| 1540 |
+
COPY szl_brainground.py ./szl_brainground.py
|
| 1541 |
+
|
| 1542 |
# WAVE R Dev 1 — boot-resilience env/secret preflight. Per-file COPY (this
|
| 1543 |
# Dockerfile has NO `COPY . .`; the copy-completeness guard requires every module
|
| 1544 |
# reachable from serve.py to appear in the COPY set). szl_boot_preflight.py is
|
serve.py
CHANGED
|
@@ -842,6 +842,25 @@ try:
|
|
| 842 |
except Exception as _szl_agentos_e: # pragma: no cover
|
| 843 |
print(f"[a11oy] Agent OS map NOT registered: {_szl_agentos_e!r}; SPA + API unaffected", file=__import__("sys").stderr)
|
| 844 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 845 |
# Operational STATUS aggregate (Wave R Dev 2) — GET /api/a11oy/v1/status is the honest
|
| 846 |
# operational-dashboard back-end: for every registered surface it reports the honest data
|
| 847 |
# label its OWN backend emits (VERBATIM) + a derived per-surface/subsystem health, rolled
|
|
|
|
| 842 |
except Exception as _szl_agentos_e: # pragma: no cover
|
| 843 |
print(f"[a11oy] Agent OS map NOT registered: {_szl_agentos_e!r}; SPA + API unaffected", file=__import__("sys").stderr)
|
| 844 |
|
| 845 |
+
# BRAINGROUND (feat/frontier-brainground) — grounding-confidence + honest-abstention layer over
|
| 846 |
+
# the brain's retrieval. GET /api/a11oy/v1/brain/ground?q=&k= scores the brain's REAL
|
| 847 |
+
# grounding_subgraph (szl_brain_api.ask, hippoRAG-PPR local ⊕ graphRAG-community global) across
|
| 848 |
+
# four explainable components (seed coverage, subgraph cohesion, salience mass, community
|
| 849 |
+
# consistency) into one grounding_confidence ∈ [0,1] and returns an honest verdict —
|
| 850 |
+
# GROUNDED / WEAK-GROUNDING / INSUFFICIENT-GROUNDING. When grounding is weak (confidence < 0.45
|
| 851 |
+
# or too few nodes) it states the brain SHOULD ABSTAIN rather than answer. Reuses the brain's OWN
|
| 852 |
+
# honest labels VERBATIM (MODELED/UNAVAILABLE), never upgraded; grounding_confidence is MODELED,
|
| 853 |
+
# never MEASURED. GET info/ground are PURE READS (sign/mint nothing); POST ground/receipt mints
|
| 854 |
+
# ONE unsigned SHA-256 content-digest receipt (RECEIPT-ON-WRITE-NOT-ON-READ). Pure honesty over
|
| 855 |
+
# knowledge-graph retrieval — advances no detection/fusion/effector/targeting/cueing capability.
|
| 856 |
+
# Adds NOTHING to the locked-8; Λ stays Conjecture 1; trust ceiling 0.97, never 100%. Additive,
|
| 857 |
+
# try/except-guarded, BEFORE the SPA catch-all.
|
| 858 |
+
try:
|
| 859 |
+
import szl_brainground as _szl_brainground
|
| 860 |
+
print("[a11oy] " + _szl_brainground.register(app, ns="a11oy"), file=__import__("sys").stderr)
|
| 861 |
+
except Exception as _szl_brainground_e: # pragma: no cover
|
| 862 |
+
print(f"[a11oy] Brainground NOT registered: {_szl_brainground_e!r}; SPA + API unaffected", file=__import__("sys").stderr)
|
| 863 |
+
|
| 864 |
# Operational STATUS aggregate (Wave R Dev 2) — GET /api/a11oy/v1/status is the honest
|
| 865 |
# operational-dashboard back-end: for every registered surface it reports the honest data
|
| 866 |
# label its OWN backend emits (VERBATIM) + a derived per-surface/subsystem health, rolled
|
szl3d_holographic.py
CHANGED
|
@@ -137,6 +137,7 @@ SURFACES: List[Dict[str, str]] = [
|
|
| 137 |
{"id": "whatsnew", "cat": "brain", "title": "What's New · honest auto-derived estate changelog · recently-added surfaces w/ verbatim labels + citations from real git history (drift-proof)", "owner": "WaveS-Dev5"},
|
| 138 |
{"id": "honestywall", "cat": "governance", "title": "Honesty Wall · live \"can this system lie right now?\" integrity aggregation · reads each surface's OWN honest label VERBATIM + estate honesty invariants → INTACT/DEGRADED/VIOLATED verdict, unsigned SHA-256 receipt-on-write (drift-proof)", "owner": "WaveS-Dev6"},
|
| 139 |
{"id": "agentos", "cat": "governance", "flag": True, "title": "Agent OS Map · live self-honest operator's-eye map of the agent OS · nodes (daily loop←agentops, trust ledger←anatomy+receipts+honestywall, standing goals←doctrine+locked-8, optional loops←governedagent/governedrag/loopforge/mesh) with LIVE per-node verdict from the honestywall aggregate → OPERATING/DEGRADED/HALTED-HONEST, never OPERATING if anything VIOLATED, unsigned SHA-256 receipt-on-write (drift-proof)", "owner": "WaveS-Dev7"},
|
|
|
|
| 140 |
]
|
| 141 |
|
| 142 |
# Content-type by extension (the only extensions we serve from the 3d tree).
|
|
|
|
| 137 |
{"id": "whatsnew", "cat": "brain", "title": "What's New · honest auto-derived estate changelog · recently-added surfaces w/ verbatim labels + citations from real git history (drift-proof)", "owner": "WaveS-Dev5"},
|
| 138 |
{"id": "honestywall", "cat": "governance", "title": "Honesty Wall · live \"can this system lie right now?\" integrity aggregation · reads each surface's OWN honest label VERBATIM + estate honesty invariants → INTACT/DEGRADED/VIOLATED verdict, unsigned SHA-256 receipt-on-write (drift-proof)", "owner": "WaveS-Dev6"},
|
| 139 |
{"id": "agentos", "cat": "governance", "flag": True, "title": "Agent OS Map · live self-honest operator's-eye map of the agent OS · nodes (daily loop←agentops, trust ledger←anatomy+receipts+honestywall, standing goals←doctrine+locked-8, optional loops←governedagent/governedrag/loopforge/mesh) with LIVE per-node verdict from the honestywall aggregate → OPERATING/DEGRADED/HALTED-HONEST, never OPERATING if anything VIOLATED, unsigned SHA-256 receipt-on-write (drift-proof)", "owner": "WaveS-Dev7"},
|
| 140 |
+
{"id": "brainground", "cat": "brain", "title": "Brainground · grounding-confidence + honest abstention over brain retrieval · scores the brain's REAL grounding_subgraph (seed coverage · subgraph cohesion · salience mass · community consistency) → GROUNDED/WEAK-GROUNDING/INSUFFICIENT-GROUNDING, brain abstains when grounding is weak, MODELED (never MEASURED), unsigned SHA-256 receipt-on-write", "owner": "WaveT-Dev1"},
|
| 141 |
]
|
| 142 |
|
| 143 |
# Content-type by extension (the only extensions we serve from the 3d tree).
|
szl_brainground.py
ADDED
|
@@ -0,0 +1,524 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
# SPDX-License-Identifier: Apache-2.0
|
| 3 |
+
# © 2026 Lutar, Stephen P. Jr. — SZL Holdings · ORCID 0009-0001-0110-4173
|
| 4 |
+
# Doctrine v11 LOCKED · Λ = Conjecture 1
|
| 5 |
+
# Sign-off: Stephen P. Lutar Jr. <stephenlutar2@gmail.com>
|
| 6 |
+
"""szl_brainground.py — BRAINGROUND: a governed grounding-confidence + honest-abstention layer
|
| 7 |
+
over the brain's retrieval.
|
| 8 |
+
|
| 9 |
+
WHAT IT IS. A deterministic, explainable read on ONE question the brain must answer honestly
|
| 10 |
+
before it speaks: *do I have enough grounding to answer this query, or should I abstain?* It
|
| 11 |
+
scores the REAL grounding_subgraph the brain returns for a query (szl_brain_api.BrainIndex.ask,
|
| 12 |
+
hippoRAG-PPR local ⊕ graphRAG-community global) and, when the grounding is weak, returns the
|
| 13 |
+
honest verdict INSUFFICIENT-GROUNDING — the point being that the brain can truthfully say
|
| 14 |
+
"I don't have enough grounding" rather than answer anyway.
|
| 15 |
+
|
| 16 |
+
This is PURE honesty / provenance capability over knowledge-graph retrieval. It advances NO
|
| 17 |
+
detection / fusion / effector / targeting / cueing capability. It computes nothing about the
|
| 18 |
+
world — only about how well the estate's OWN knowledge graph grounds a query.
|
| 19 |
+
|
| 20 |
+
THE SCORE (0..1 grounding_confidence, every component reported separately — no black box):
|
| 21 |
+
(a) seed_coverage — fraction of query terms that matched a retrieved seed node.
|
| 22 |
+
(b) subgraph_cohesion — link density of the grounding nodes (edges / max simple edges).
|
| 23 |
+
(c) salience_mass — PPR mass concentrated in the top grounding nodes (normalized).
|
| 24 |
+
(d) community_consistency — dominant-community share of the grounding nodes (few vs scattered).
|
| 25 |
+
The four are combined by a fixed, published weight vector into grounding_confidence; the math
|
| 26 |
+
is shown honestly and each component is emitted verbatim so the number can never hide a weak
|
| 27 |
+
part.
|
| 28 |
+
|
| 29 |
+
HONEST ABSTENTION. If grounding_confidence < WEAK_THRESHOLD OR node_count < MIN_GROUNDING_NODES,
|
| 30 |
+
the verdict is INSUFFICIENT-GROUNDING and the surface states the brain SHOULD ABSTAIN. A middle
|
| 31 |
+
band is WEAK-GROUNDING (answer with caution); only a strong grounding is GROUNDED. High
|
| 32 |
+
confidence is NEVER claimed when the components are weak.
|
| 33 |
+
|
| 34 |
+
RECEIPTS — RECEIPT-ON-WRITE, NOT ON-READ. The GET info/ground reads mint NOTHING. Only the POST
|
| 35 |
+
receipt endpoint emits an UNSIGNED SHA-256 content digest over the computed result (mirrors the
|
| 36 |
+
honestywall content-digest pattern) — a plain content hash, never a fabricated signature.
|
| 37 |
+
|
| 38 |
+
DOCTRINE v11:
|
| 39 |
+
- Adds NOTHING to the locked-8 {F1,F4,F7,F11,F12,F18,F19,F22}; touches no locked formula and
|
| 40 |
+
no kernel. Reuses the brain's OWN honest labels (LBL_MODELED / LBL_UNAVAILABLE) VERBATIM and
|
| 41 |
+
never upgrades a label. grounding_confidence is MODELED (a deterministic graph statistic,
|
| 42 |
+
never a MEASURED semantic truth).
|
| 43 |
+
- Λ stays Conjecture 1; introduces no theorem, no green/1.0. Khipu BFT stays Conjecture 2.
|
| 44 |
+
Trust ceiling 0.97, never 100%.
|
| 45 |
+
- Pure stdlib + numpy. Additive routes, registered before the SPA catch-all; 0 runtime CDN.
|
| 46 |
+
"""
|
| 47 |
+
|
| 48 |
+
import datetime
|
| 49 |
+
import hashlib
|
| 50 |
+
import json
|
| 51 |
+
import math
|
| 52 |
+
import re
|
| 53 |
+
from typing import Any
|
| 54 |
+
|
| 55 |
+
import numpy as np
|
| 56 |
+
|
| 57 |
+
# Honest Doctrine v11 labels — reuse the brain's OWN vocabulary VERBATIM (never upgraded).
|
| 58 |
+
# Restated as a guarded fallback so a broken import can never silently blank the label.
|
| 59 |
+
try:
|
| 60 |
+
from szl_brain_api import LBL_MODELED, LBL_UNAVAILABLE
|
| 61 |
+
except Exception: # pragma: no cover — label vocabulary must never be blank
|
| 62 |
+
LBL_MODELED = "MODELED"
|
| 63 |
+
LBL_UNAVAILABLE = "UNAVAILABLE"
|
| 64 |
+
|
| 65 |
+
# This surface's own id (must match szl3d_holographic.SURFACES + holographic.html).
|
| 66 |
+
SURFACE_ID = "brainground"
|
| 67 |
+
|
| 68 |
+
# Doctrine constants (never inflated).
|
| 69 |
+
LOCKED_SET = ["F1", "F4", "F7", "F11", "F12", "F18", "F19", "F22"]
|
| 70 |
+
LOCKED_COUNT = 8
|
| 71 |
+
TRUST_CEILING = 0.97
|
| 72 |
+
|
| 73 |
+
# Verdicts (honest abstention band).
|
| 74 |
+
VERDICT_GROUNDED = "GROUNDED"
|
| 75 |
+
VERDICT_WEAK = "WEAK-GROUNDING"
|
| 76 |
+
VERDICT_INSUFFICIENT = "INSUFFICIENT-GROUNDING"
|
| 77 |
+
|
| 78 |
+
# Component weights — fixed and PUBLISHED (sum to 1.0). Deterministic; no tuning at request time.
|
| 79 |
+
WEIGHTS = {
|
| 80 |
+
"seed_coverage": 0.30,
|
| 81 |
+
"subgraph_cohesion": 0.25,
|
| 82 |
+
"salience_mass": 0.25,
|
| 83 |
+
"community_consistency": 0.20,
|
| 84 |
+
}
|
| 85 |
+
|
| 86 |
+
# Abstention thresholds. Below WEAK_THRESHOLD (or too few nodes) -> abstain honestly.
|
| 87 |
+
WEAK_THRESHOLD = 0.45 # < this OR too few nodes => INSUFFICIENT-GROUNDING (abstain)
|
| 88 |
+
GROUNDED_THRESHOLD = 0.62 # >= this => GROUNDED; in-between => WEAK-GROUNDING
|
| 89 |
+
MIN_GROUNDING_NODES = 3 # fewer grounding nodes than this => abstain regardless of score
|
| 90 |
+
|
| 91 |
+
# Fraction of grounding nodes treated as "top" when measuring salience concentration.
|
| 92 |
+
TOP_MASS_FRACTION = 0.30
|
| 93 |
+
|
| 94 |
+
_TOKEN_RE = re.compile(r"[a-z0-9]+")
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def _now_iso() -> str:
|
| 98 |
+
return datetime.datetime.now(datetime.timezone.utc).isoformat()
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
def _terms(text: str) -> list:
|
| 102 |
+
"""Lowercase alnum tokens (len >= 2) — the query terms we test for grounding coverage."""
|
| 103 |
+
return [t for t in _TOKEN_RE.findall((text or "").lower()) if len(t) >= 2]
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def _clamp01(x: float) -> float:
|
| 107 |
+
if x != x: # NaN
|
| 108 |
+
return 0.0
|
| 109 |
+
return float(min(1.0, max(0.0, x)))
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
# --------------------------------------------------------------------------- #
|
| 113 |
+
# The four grounding-confidence components (each explainable, each in [0,1]).
|
| 114 |
+
# All operate on the brain's OWN ask() output; nothing about the world is invented.
|
| 115 |
+
# --------------------------------------------------------------------------- #
|
| 116 |
+
def _seed_coverage(query: str, seeds: list) -> dict:
|
| 117 |
+
"""(a) Fraction of query terms that matched a retrieved seed node's text."""
|
| 118 |
+
terms = _terms(query)
|
| 119 |
+
if not terms:
|
| 120 |
+
return {"value": 0.0, "matched_terms": 0, "query_terms": 0,
|
| 121 |
+
"note": "no usable query terms -> 0 coverage (honest)"}
|
| 122 |
+
seed_text = " ".join(
|
| 123 |
+
f"{s.get('id', '')} {s.get('title', '')}" for s in (seeds or [])
|
| 124 |
+
).lower()
|
| 125 |
+
seed_tokens = set(_TOKEN_RE.findall(seed_text))
|
| 126 |
+
matched = sum(1 for t in set(terms) if t in seed_tokens)
|
| 127 |
+
distinct = len(set(terms))
|
| 128 |
+
return {"value": _clamp01(matched / distinct), "matched_terms": matched,
|
| 129 |
+
"query_terms": distinct,
|
| 130 |
+
"note": "fraction of distinct query terms with a matching seed node"}
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
def _subgraph_cohesion(node_count: int, link_count: int) -> dict:
|
| 134 |
+
"""(b) Link density of the grounding nodes: edges / max simple undirected edges."""
|
| 135 |
+
if node_count < 2:
|
| 136 |
+
return {"value": 0.0, "node_count": node_count, "link_count": link_count,
|
| 137 |
+
"max_edges": 0, "note": "fewer than 2 nodes -> no cohesion (honest 0)"}
|
| 138 |
+
max_edges = node_count * (node_count - 1) / 2.0
|
| 139 |
+
return {"value": _clamp01(link_count / max_edges), "node_count": node_count,
|
| 140 |
+
"link_count": link_count, "max_edges": int(max_edges),
|
| 141 |
+
"note": "actual edges / maximum simple undirected edges among grounding nodes"}
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
def _salience_mass(nodes: list) -> dict:
|
| 145 |
+
"""(c) PPR mass concentrated in the top grounding nodes (normalized to [0,1])."""
|
| 146 |
+
ppr = np.array([float(n.get("ppr", 0.0) or 0.0) for n in (nodes or [])], dtype=float)
|
| 147 |
+
used = "ppr"
|
| 148 |
+
if ppr.size == 0 or float(ppr.sum()) <= 0.0:
|
| 149 |
+
# honest fallback: if no PPR mass, use the node salience field (still MODELED).
|
| 150 |
+
ppr = np.array([float(n.get("salience", 0.0) or 0.0) for n in (nodes or [])], dtype=float)
|
| 151 |
+
used = "salience"
|
| 152 |
+
total = float(ppr.sum())
|
| 153 |
+
n = int(ppr.size)
|
| 154 |
+
if n == 0 or total <= 0.0:
|
| 155 |
+
return {"value": 0.0, "top_k": 0, "node_count": n, "mass_field": used,
|
| 156 |
+
"note": "no retrieval mass on the grounding nodes -> 0 (honest)"}
|
| 157 |
+
top_k = max(1, int(math.ceil(n * TOP_MASS_FRACTION)))
|
| 158 |
+
top_sum = float(np.sort(ppr)[::-1][:top_k].sum())
|
| 159 |
+
return {"value": _clamp01(top_sum / total), "top_k": top_k, "node_count": n,
|
| 160 |
+
"mass_field": used,
|
| 161 |
+
"note": f"share of retrieval mass held by the top {top_k} of {n} grounding nodes"}
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
def _community_consistency(nodes: list) -> dict:
|
| 165 |
+
"""(d) Dominant-community share of the grounding nodes (clustered vs scattered)."""
|
| 166 |
+
comms = [n.get("community") for n in (nodes or []) if n.get("community") is not None]
|
| 167 |
+
total = len(comms)
|
| 168 |
+
if total == 0:
|
| 169 |
+
return {"value": 0.0, "distinct_communities": 0, "grounded_nodes": 0,
|
| 170 |
+
"note": "no community assignments on grounding nodes -> 0 (honest)"}
|
| 171 |
+
counts: dict = {}
|
| 172 |
+
for c in comms:
|
| 173 |
+
counts[c] = counts.get(c, 0) + 1
|
| 174 |
+
dominant = max(counts.values())
|
| 175 |
+
return {"value": _clamp01(dominant / total), "distinct_communities": len(counts),
|
| 176 |
+
"grounded_nodes": total, "dominant_community_share": round(dominant / total, 6),
|
| 177 |
+
"note": "share of grounding nodes in the single dominant community (few vs scattered)"}
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
def compute_confidence(ask_result: dict) -> dict:
|
| 181 |
+
"""Deterministic grounding-confidence over ONE brain ask() result.
|
| 182 |
+
|
| 183 |
+
Returns the four components (each verbatim, each in [0,1]), the weighted
|
| 184 |
+
grounding_confidence in [0,1], the honest verdict, and whether the brain
|
| 185 |
+
SHOULD ABSTAIN. Pure computation — mints nothing, invents nothing."""
|
| 186 |
+
ask_result = ask_result or {}
|
| 187 |
+
query = str(ask_result.get("query", "") or "")
|
| 188 |
+
seeds = ask_result.get("seeds") or []
|
| 189 |
+
grounding = ask_result.get("grounding_subgraph") or {}
|
| 190 |
+
nodes = grounding.get("nodes") or []
|
| 191 |
+
node_count = int(grounding.get("node_count", len(nodes)) or 0)
|
| 192 |
+
link_count = int(grounding.get("link_count", 0) or 0)
|
| 193 |
+
|
| 194 |
+
comp = {
|
| 195 |
+
"seed_coverage": _seed_coverage(query, seeds),
|
| 196 |
+
"subgraph_cohesion": _subgraph_cohesion(node_count, link_count),
|
| 197 |
+
"salience_mass": _salience_mass(nodes),
|
| 198 |
+
"community_consistency": _community_consistency(nodes),
|
| 199 |
+
}
|
| 200 |
+
|
| 201 |
+
confidence = 0.0
|
| 202 |
+
for name, w in WEIGHTS.items():
|
| 203 |
+
confidence += w * float(comp[name]["value"])
|
| 204 |
+
confidence = _clamp01(confidence)
|
| 205 |
+
|
| 206 |
+
too_few = node_count < MIN_GROUNDING_NODES
|
| 207 |
+
if confidence < WEAK_THRESHOLD or too_few:
|
| 208 |
+
verdict = VERDICT_INSUFFICIENT
|
| 209 |
+
abstain = True
|
| 210 |
+
elif confidence < GROUNDED_THRESHOLD:
|
| 211 |
+
verdict = VERDICT_WEAK
|
| 212 |
+
abstain = False
|
| 213 |
+
else:
|
| 214 |
+
verdict = VERDICT_GROUNDED
|
| 215 |
+
abstain = False
|
| 216 |
+
|
| 217 |
+
reason = {
|
| 218 |
+
VERDICT_GROUNDED: (f"grounding_confidence {confidence:.3f} >= {GROUNDED_THRESHOLD} "
|
| 219 |
+
f"with {node_count} grounding nodes"),
|
| 220 |
+
VERDICT_WEAK: (f"grounding_confidence {confidence:.3f} in "
|
| 221 |
+
f"[{WEAK_THRESHOLD}, {GROUNDED_THRESHOLD}) — answer with caution"),
|
| 222 |
+
VERDICT_INSUFFICIENT: (
|
| 223 |
+
f"grounding_confidence {confidence:.3f} < {WEAK_THRESHOLD}"
|
| 224 |
+
+ (f" and node_count {node_count} < {MIN_GROUNDING_NODES}" if too_few else "")
|
| 225 |
+
+ " — the brain SHOULD ABSTAIN rather than answer"),
|
| 226 |
+
}[verdict]
|
| 227 |
+
|
| 228 |
+
return {
|
| 229 |
+
"label": LBL_MODELED,
|
| 230 |
+
"surface_id": SURFACE_ID,
|
| 231 |
+
"query": query,
|
| 232 |
+
"grounding_confidence": round(confidence, 6),
|
| 233 |
+
"verdict": verdict,
|
| 234 |
+
"should_abstain": abstain,
|
| 235 |
+
"verdict_reason": reason,
|
| 236 |
+
"components": comp,
|
| 237 |
+
"weights": dict(WEIGHTS),
|
| 238 |
+
"thresholds": {
|
| 239 |
+
"weak_threshold": WEAK_THRESHOLD,
|
| 240 |
+
"grounded_threshold": GROUNDED_THRESHOLD,
|
| 241 |
+
"min_grounding_nodes": MIN_GROUNDING_NODES,
|
| 242 |
+
},
|
| 243 |
+
"grounding_stats": {
|
| 244 |
+
"node_count": node_count,
|
| 245 |
+
"link_count": link_count,
|
| 246 |
+
"seed_count": len(seeds),
|
| 247 |
+
"community_context_count": len(ask_result.get("community_context") or []),
|
| 248 |
+
},
|
| 249 |
+
"formula": ("grounding_confidence = "
|
| 250 |
+
"0.30·seed_coverage + 0.25·subgraph_cohesion + "
|
| 251 |
+
"0.25·salience_mass + 0.20·community_consistency; "
|
| 252 |
+
"each component ∈ [0,1], reported verbatim; "
|
| 253 |
+
"abstain if confidence < 0.45 or node_count < 3"),
|
| 254 |
+
"note": ("grounding_confidence is MODELED — a deterministic statistic over the brain's "
|
| 255 |
+
"REAL grounding_subgraph, NEVER a MEASURED semantic truth. A weak grounding "
|
| 256 |
+
"yields INSUFFICIENT-GROUNDING so the brain can honestly abstain; high "
|
| 257 |
+
"confidence is never claimed when the components are weak."),
|
| 258 |
+
}
|
| 259 |
+
|
| 260 |
+
|
| 261 |
+
# --------------------------------------------------------------------------- #
|
| 262 |
+
# Retrieval bridge — run the brain's OWN ask() (guarded; honest UNAVAILABLE on failure).
|
| 263 |
+
# --------------------------------------------------------------------------- #
|
| 264 |
+
def _run_ask(q: str, k: int, ns: str) -> tuple:
|
| 265 |
+
"""Return (ask_result, error). Never raises: an unreachable brain degrades honestly."""
|
| 266 |
+
try:
|
| 267 |
+
import szl_brain_api as brain
|
| 268 |
+
idx = brain.get_index(ns)
|
| 269 |
+
return idx.ask(q, max(1, int(k))), None
|
| 270 |
+
except Exception as exc: # brain graph unavailable -> honest UNAVAILABLE, never fabricated
|
| 271 |
+
return None, str(exc)[:200]
|
| 272 |
+
|
| 273 |
+
|
| 274 |
+
def evaluate(q: str, k: int = 12, ns: str = "a11oy") -> dict:
|
| 275 |
+
"""Run retrieval via the brain and compute the grounding-confidence result. PURE READ."""
|
| 276 |
+
ask_result, err = _run_ask(q, k, ns)
|
| 277 |
+
if ask_result is None:
|
| 278 |
+
return {
|
| 279 |
+
"ok": False,
|
| 280 |
+
"label": LBL_UNAVAILABLE,
|
| 281 |
+
"surface_id": SURFACE_ID,
|
| 282 |
+
"endpoint": "brain/ground",
|
| 283 |
+
"query": q,
|
| 284 |
+
"verdict": VERDICT_INSUFFICIENT,
|
| 285 |
+
"should_abstain": True,
|
| 286 |
+
"verdict_reason": "brain retrieval unavailable — no grounding to score; brain SHOULD ABSTAIN",
|
| 287 |
+
"error": err,
|
| 288 |
+
"note": "no grounding could be retrieved; no confidence fabricated (honest UNAVAILABLE).",
|
| 289 |
+
"timestamp_utc": _now_iso(),
|
| 290 |
+
}
|
| 291 |
+
out = compute_confidence(ask_result)
|
| 292 |
+
out["ok"] = True
|
| 293 |
+
out["endpoint"] = "brain/ground"
|
| 294 |
+
out["k"] = max(1, int(k))
|
| 295 |
+
out["retrieval"] = ask_result.get("retrieval")
|
| 296 |
+
out["answer_label"] = ask_result.get("answer_label")
|
| 297 |
+
out["cited_node_ids"] = ask_result.get("cited_node_ids")
|
| 298 |
+
out["timestamp_utc"] = _now_iso()
|
| 299 |
+
return out
|
| 300 |
+
|
| 301 |
+
|
| 302 |
+
# --------------------------------------------------------------------------- #
|
| 303 |
+
# Receipt — UNSIGNED SHA-256 content digest. RECEIPT-ON-WRITE (POST), NEVER on a GET read.
|
| 304 |
+
# --------------------------------------------------------------------------- #
|
| 305 |
+
def _canonical_core(result: dict) -> str:
|
| 306 |
+
"""Deterministic canonical serialization of the grounding-bearing content (excludes the
|
| 307 |
+
volatile timestamp), so the digest attests the VERDICT + confidence + components."""
|
| 308 |
+
comp = result.get("components", {}) or {}
|
| 309 |
+
core = {
|
| 310 |
+
"query": result.get("query"),
|
| 311 |
+
"verdict": result.get("verdict"),
|
| 312 |
+
"should_abstain": result.get("should_abstain"),
|
| 313 |
+
"grounding_confidence": result.get("grounding_confidence"),
|
| 314 |
+
"components": {k: round(float(comp.get(k, {}).get("value", 0.0)), 6) for k in WEIGHTS},
|
| 315 |
+
"weights": result.get("weights"),
|
| 316 |
+
"thresholds": result.get("thresholds"),
|
| 317 |
+
"grounding_stats": result.get("grounding_stats"),
|
| 318 |
+
"label": result.get("label"),
|
| 319 |
+
}
|
| 320 |
+
return json.dumps(core, sort_keys=True, separators=(",", ":"), default=str)
|
| 321 |
+
|
| 322 |
+
|
| 323 |
+
def content_receipt(result: dict) -> dict:
|
| 324 |
+
"""An UNSIGNED SHA-256 content-digest receipt over a grounding result (no signature)."""
|
| 325 |
+
canonical = _canonical_core(result)
|
| 326 |
+
digest = hashlib.sha256(canonical.encode("utf-8")).hexdigest()
|
| 327 |
+
return {
|
| 328 |
+
"kind": "szl.brainground.grounding",
|
| 329 |
+
"algorithm": "sha256",
|
| 330 |
+
"content_sha256": digest,
|
| 331 |
+
"signed": False,
|
| 332 |
+
"mode": "UNSIGNED-CONTENT-DIGEST",
|
| 333 |
+
"receipt_on": "write (POST ground/receipt)",
|
| 334 |
+
"note": ("unsigned SHA-256 content digest of the grounding result; "
|
| 335 |
+
"RECEIPT-ON-WRITE, never on a GET read. No signature fabricated."),
|
| 336 |
+
"computed_at": _now_iso(),
|
| 337 |
+
}
|
| 338 |
+
|
| 339 |
+
|
| 340 |
+
# --------------------------------------------------------------------------- #
|
| 341 |
+
# Handlers.
|
| 342 |
+
# --------------------------------------------------------------------------- #
|
| 343 |
+
def handle_info(ns: str = "a11oy") -> dict:
|
| 344 |
+
"""GET /brain/ground/info — static self-describing manifest (no compute). PURE READ."""
|
| 345 |
+
base = f"/api/{ns}/v1/brain/ground"
|
| 346 |
+
return {
|
| 347 |
+
"ok": True,
|
| 348 |
+
"endpoint": "brain/ground/info",
|
| 349 |
+
"service": "a11oy.brain.ground",
|
| 350 |
+
"surface_id": SURFACE_ID,
|
| 351 |
+
"title": "Brainground — grounding-confidence + honest abstention over brain retrieval",
|
| 352 |
+
"label": LBL_MODELED,
|
| 353 |
+
"what": ("scores the brain's REAL grounding_subgraph for a query and returns an honest "
|
| 354 |
+
"verdict — GROUNDED / WEAK-GROUNDING / INSUFFICIENT-GROUNDING. When the "
|
| 355 |
+
"grounding is weak, the brain SHOULD ABSTAIN rather than answer. Pure "
|
| 356 |
+
"honesty/provenance over knowledge-graph retrieval; advances no "
|
| 357 |
+
"detection/fusion/effector/targeting/cueing capability."),
|
| 358 |
+
"endpoints": {
|
| 359 |
+
"info": f"GET {base}/info",
|
| 360 |
+
"ground": f"GET {base}?q=&k=",
|
| 361 |
+
"receipt": f"POST {base}/receipt?q=&k=",
|
| 362 |
+
},
|
| 363 |
+
"verdicts": [VERDICT_GROUNDED, VERDICT_WEAK, VERDICT_INSUFFICIENT],
|
| 364 |
+
"components": {
|
| 365 |
+
"seed_coverage": "fraction of query terms with a matching seed node",
|
| 366 |
+
"subgraph_cohesion": "link density of the grounding nodes",
|
| 367 |
+
"salience_mass": "PPR mass concentrated in the top grounding nodes",
|
| 368 |
+
"community_consistency": "dominant-community share of the grounding nodes",
|
| 369 |
+
},
|
| 370 |
+
"weights": dict(WEIGHTS),
|
| 371 |
+
"thresholds": {
|
| 372 |
+
"weak_threshold": WEAK_THRESHOLD,
|
| 373 |
+
"grounded_threshold": GROUNDED_THRESHOLD,
|
| 374 |
+
"min_grounding_nodes": MIN_GROUNDING_NODES,
|
| 375 |
+
},
|
| 376 |
+
"formula": ("grounding_confidence = 0.30·seed_coverage + 0.25·subgraph_cohesion + "
|
| 377 |
+
"0.25·salience_mass + 0.20·community_consistency ∈ [0,1]; "
|
| 378 |
+
"abstain if confidence < 0.45 or node_count < 3"),
|
| 379 |
+
"doctrine": {
|
| 380 |
+
"label_top": LBL_MODELED,
|
| 381 |
+
"locked_proven": LOCKED_COUNT,
|
| 382 |
+
"locked_set": LOCKED_SET,
|
| 383 |
+
"adds_to_locked_8": 0,
|
| 384 |
+
"lambda": "Conjecture 1",
|
| 385 |
+
"khipu_bft": "Conjecture 2",
|
| 386 |
+
"trust_ceiling": TRUST_CEILING,
|
| 387 |
+
"trust_100_percent": False,
|
| 388 |
+
"runtime_cdn": 0,
|
| 389 |
+
"note": ("additive read-only surface over knowledge-graph retrieval; reuses the "
|
| 390 |
+
"brain's honest labels VERBATIM, never upgraded; confidence is MODELED, "
|
| 391 |
+
"never MEASURED; GET reads mint nothing; POST receipt digests only."),
|
| 392 |
+
},
|
| 393 |
+
"receipt_policy": ("RECEIPT-ON-WRITE-NOT-ON-READ — GET info/ground mint nothing; "
|
| 394 |
+
"POST receipt emits an unsigned SHA-256 content digest."),
|
| 395 |
+
"honest_labels_reused": [LBL_MODELED, LBL_UNAVAILABLE],
|
| 396 |
+
"timestamp_utc": _now_iso(),
|
| 397 |
+
}
|
| 398 |
+
|
| 399 |
+
|
| 400 |
+
def handle_ground(q: str = "", k: int = 12, ns: str = "a11oy") -> dict:
|
| 401 |
+
"""GET /brain/ground — compute grounding confidence + verdict. PURE READ (mints nothing)."""
|
| 402 |
+
return evaluate(q, k, ns)
|
| 403 |
+
|
| 404 |
+
|
| 405 |
+
def handle_receipt(q: str = "", k: int = 12, ns: str = "a11oy") -> dict:
|
| 406 |
+
"""POST /brain/ground/receipt — compute + mint an UNSIGNED SHA-256 receipt (RECEIPT-ON-WRITE)."""
|
| 407 |
+
result = evaluate(q, k, ns)
|
| 408 |
+
out = dict(result)
|
| 409 |
+
out["endpoint"] = "brain/ground/receipt"
|
| 410 |
+
out["receipt"] = content_receipt(result)
|
| 411 |
+
return out
|
| 412 |
+
|
| 413 |
+
|
| 414 |
+
# --------------------------------------------------------------------------- #
|
| 415 |
+
# FastAPI registration.
|
| 416 |
+
# GET info/ground — normal FastAPI GET handlers.
|
| 417 |
+
# POST receipt — raw-Request handler via app.router.add_route (Starlette passes the
|
| 418 |
+
# Request positionally), with app.add_api_route as the fallback. The
|
| 419 |
+
# handler is annotated request: fastapi.Request. Registered BEFORE the
|
| 420 |
+
# SPA catch-all by serve.py.
|
| 421 |
+
# --------------------------------------------------------------------------- #
|
| 422 |
+
def register(app, ns: str = "a11oy") -> str:
|
| 423 |
+
from fastapi.responses import JSONResponse
|
| 424 |
+
|
| 425 |
+
base = f"/api/{ns}/v1/brain/ground"
|
| 426 |
+
|
| 427 |
+
@app.get(f"{base}/info")
|
| 428 |
+
def _brainground_info():
|
| 429 |
+
"""Self-describing brainground manifest (pure read; mints nothing)."""
|
| 430 |
+
return JSONResponse(handle_info(ns))
|
| 431 |
+
|
| 432 |
+
@app.get(base)
|
| 433 |
+
def _brainground_ground(q: str = "", k: int = 12): # noqa: ANN202
|
| 434 |
+
"""Grounding-confidence + honest verdict for a query (pure read; mints nothing)."""
|
| 435 |
+
return JSONResponse(handle_ground(q, k, ns))
|
| 436 |
+
|
| 437 |
+
async def _brainground_receipt(request):
|
| 438 |
+
"""POST: compute + UNSIGNED SHA-256 content digest (RECEIPT-ON-WRITE)."""
|
| 439 |
+
q = request.query_params.get("q", "")
|
| 440 |
+
try:
|
| 441 |
+
k = int(request.query_params.get("k", "12"))
|
| 442 |
+
except Exception:
|
| 443 |
+
k = 12
|
| 444 |
+
return JSONResponse(handle_receipt(q, k, ns))
|
| 445 |
+
|
| 446 |
+
# Annotate the raw-Request handler as fastapi.Request so any FastAPI signature analysis (in
|
| 447 |
+
# the add_api_route fallback path) treats the param as the request object.
|
| 448 |
+
try:
|
| 449 |
+
import fastapi as _fastapi
|
| 450 |
+
_brainground_receipt.__annotations__["request"] = _fastapi.Request
|
| 451 |
+
except Exception: # noqa: BLE001 — annotation is best-effort only
|
| 452 |
+
pass
|
| 453 |
+
|
| 454 |
+
rec_path = f"{base}/receipt"
|
| 455 |
+
add_route = getattr(getattr(app, "router", None), "add_route", None)
|
| 456 |
+
add_api_route = getattr(app, "add_api_route", None)
|
| 457 |
+
try:
|
| 458 |
+
if callable(add_route):
|
| 459 |
+
app.router.add_route(rec_path, _brainground_receipt, methods=["POST"])
|
| 460 |
+
elif callable(add_api_route):
|
| 461 |
+
app.add_api_route(rec_path, _brainground_receipt, methods=["POST"])
|
| 462 |
+
else: # pragma: no cover — last-resort Starlette Route append
|
| 463 |
+
from starlette.routing import Route
|
| 464 |
+
app.router.routes.append(Route(rec_path, _brainground_receipt, methods=["POST"]))
|
| 465 |
+
except Exception as exc: # additive register must never break boot
|
| 466 |
+
print(f"[{ns}] brainground receipt POST route NOT wired (guarded): {exc!r}",
|
| 467 |
+
file=__import__("sys").stderr)
|
| 468 |
+
return "brainground-wired:2(get-only)"
|
| 469 |
+
|
| 470 |
+
return "brainground-wired:3"
|
| 471 |
+
|
| 472 |
+
|
| 473 |
+
# --------------------------------------------------------------------------- #
|
| 474 |
+
# Self-test — honest verdicts, components in range, abstention fires, receipt only on write.
|
| 475 |
+
# --------------------------------------------------------------------------- #
|
| 476 |
+
if __name__ == "__main__":
|
| 477 |
+
import sys as _sys
|
| 478 |
+
|
| 479 |
+
print("=" * 72)
|
| 480 |
+
print("szl_brainground — self-test (grounding-confidence + honest abstention)")
|
| 481 |
+
print("=" * 72)
|
| 482 |
+
|
| 483 |
+
# 1) empty grounding -> every component 0, INSUFFICIENT, abstain.
|
| 484 |
+
empty = compute_confidence({"query": "anything", "seeds": [],
|
| 485 |
+
"grounding_subgraph": {"node_count": 0, "link_count": 0, "nodes": []}})
|
| 486 |
+
assert 0.0 <= empty["grounding_confidence"] <= 1.0
|
| 487 |
+
assert empty["verdict"] == VERDICT_INSUFFICIENT and empty["should_abstain"] is True
|
| 488 |
+
print(f"[1] empty grounding -> {empty['verdict']}, abstain, conf={empty['grounding_confidence']} OK")
|
| 489 |
+
|
| 490 |
+
# 2) a strong synthetic grounding -> GROUNDED, all components in [0,1].
|
| 491 |
+
nodes = [{"id": f"n{i}", "title": "brain graph node", "ppr": 0.5 if i == 0 else 0.05,
|
| 492 |
+
"salience": 0.1, "community": "c1"} for i in range(6)]
|
| 493 |
+
strong = compute_confidence({
|
| 494 |
+
"query": "brain graph",
|
| 495 |
+
"seeds": [{"id": "n0", "title": "brain graph node"}],
|
| 496 |
+
"grounding_subgraph": {"node_count": 6, "link_count": 13, "nodes": nodes},
|
| 497 |
+
})
|
| 498 |
+
for name in WEIGHTS:
|
| 499 |
+
v = strong["components"][name]["value"]
|
| 500 |
+
assert 0.0 <= v <= 1.0, f"{name} out of range: {v}"
|
| 501 |
+
assert strong["verdict"] == VERDICT_GROUNDED, strong["verdict"]
|
| 502 |
+
print(f"[2] strong grounding -> {strong['verdict']}, conf={strong['grounding_confidence']} OK")
|
| 503 |
+
|
| 504 |
+
# 3) receipt is a deterministic sha256 (RECEIPT-ON-WRITE); same result -> same digest.
|
| 505 |
+
r1 = content_receipt(strong)
|
| 506 |
+
r2 = content_receipt(strong)
|
| 507 |
+
assert r1["algorithm"] == "sha256" and len(r1["content_sha256"]) == 64
|
| 508 |
+
assert r1["signed"] is False and r1["content_sha256"] == r2["content_sha256"]
|
| 509 |
+
print(f"[3] receipt sha256={r1['content_sha256'][:16]}… unsigned, deterministic OK")
|
| 510 |
+
|
| 511 |
+
# 4) labels are the brain's OWN vocabulary, never upgraded.
|
| 512 |
+
assert strong["label"] == LBL_MODELED == "MODELED"
|
| 513 |
+
print("[4] label MODELED (brain vocabulary, never upgraded) OK")
|
| 514 |
+
|
| 515 |
+
# 5) doctrine: locked-8 exact, Λ Conjecture 1, trust 0.97 not 100%.
|
| 516 |
+
info = handle_info("a11oy")
|
| 517 |
+
d = info["doctrine"]
|
| 518 |
+
assert d["locked_proven"] == 8 and d["locked_set"] == LOCKED_SET
|
| 519 |
+
assert d["adds_to_locked_8"] == 0 and d["lambda"] == "Conjecture 1"
|
| 520 |
+
assert d["trust_ceiling"] == 0.97 and d["trust_100_percent"] is False
|
| 521 |
+
print("[5] doctrine: locked-8 exact, +0, Λ=Conjecture 1, trust 0.97 (not 100%) OK")
|
| 522 |
+
|
| 523 |
+
print("\nok:true checks:5")
|
| 524 |
+
_sys.exit(0)
|