betterwithage commited on
Commit
74b47dc
·
verified ·
1 Parent(s): e924652

chore(sync): mirror backend .py + Dockerfile to Space (hf-sync-backend)

Browse files

Automated backend sync from szl-holdings/a11oy main via hf-sync-backend.
Updated (differed from the Space): serve.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.

Files changed (1) hide show
  1. serve.py +268 -0
serve.py CHANGED
@@ -4656,6 +4656,274 @@ except Exception as _sc_e: # pragma: no cover - additive, defensive
4656
  print("[a11oy] self-contained organ routes NOT mounted (" + repr(_sc_e) + "); SPA unaffected", flush=True)
4657
  # === END SELF-CONTAINED ORGAN ROUTES ===
4658
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4659
  # ===========================================================================
4660
  # SELF-CONTAINED WARHACKER DEMO (ADDITIVE, 2026-06-05). a11oy runs the 5 demo
4661
  # scenarios IN-IMAGE — no external service calls. Registered BEFORE the legacy
 
4656
  print("[a11oy] self-contained organ routes NOT mounted (" + repr(_sc_e) + "); SPA unaffected", flush=True)
4657
  # === END SELF-CONTAINED ORGAN ROUTES ===
4658
 
4659
+ # ===========================================================================
4660
+ # GOVERNED RAG — "ask the doctrine" (PowerD2, 2026-06-16). EXPOSE the EXISTING
4661
+ # 62KB a11oy_org_rag.py engine as a LIVE governed endpoint over the estate's own
4662
+ # corpus (the SEVEN-category SZL_CORPUS: app_code/killinchu/anatomy/thesis/
4663
+ # formulas/doctrine/lean). a11oy_org_rag was coded + deployed (shared module,
4664
+ # byte-identical a11oy<->killinchu) but NEVER WIRED into serve.py — so every
4665
+ # /rag/query returned 404. This block wires it, additively, BEFORE the SPA
4666
+ # catch-all, inside a defensive try/except so a missing dep can NEVER take the
4667
+ # Space down.
4668
+ #
4669
+ # What it does, honestly:
4670
+ # * Lazy-builds the REAL labeled SEED index on first query (a11oy_org_rag.
4671
+ # build_seed_index) — pulls each category's highest-value files LIVE from the
4672
+ # public szl-holdings GitHub repos + HF Spaces, falling back to the REAL
4673
+ # in-image corpus/ mirror (honest 'bundled:<repo>@<sha>:<path>' provenance)
4674
+ # when Space egress to api.github.com is blocked. NEVER an empty/fake index.
4675
+ # * Retrieves via the engine's two-stage Λ-weighted agentic-RAG query()
4676
+ # (FTS5 lexical ∪ dense, graph-centrality re-rank, conformal floor). Only
4677
+ # chunks at/above the Λ relevance floor enter the answer; below floor =>
4678
+ # i_dont_know (Self-RAG; never fabricate).
4679
+ # * Returns the answer WITH citations (each grounded chunk's corpus category +
4680
+ # source gh:<repo>|hf:<space>|bundled:<repo>@<sha> + path + sha256) and an
4681
+ # HONEST confidence derived from the grounded chunks' Λ scores — capped
4682
+ # strictly BELOW 1.0 (trust never 100%; Λ is Conjecture 1, NOT a theorem).
4683
+ # * Emits a Khipu/DSSE provenance receipt over the query+grounding via the
4684
+ # in-image signer (real ECDSA-P256 when the key is present, else honestly
4685
+ # labeled UNSIGNED — no signature fabricated).
4686
+ # * Carries the governed envelope (gov_envelope): status REAL when grounded,
4687
+ # DEGRADED when i_dont_know or the index could not build (honest BLOCKED
4688
+ # beats fake green) — so it passes the operator-reason envelope guard.
4689
+ # Routes (registered BEFORE the SPA catch-all so they resolve LOCALLY):
4690
+ # GET /api/a11oy/v1/rag/query?q=... — governed RAG answer (also descriptor on bare GET)
4691
+ # POST /api/a11oy/v1/rag/query {q|question, k?, repo?} — governed RAG answer
4692
+ # GET /api/a11oy/v1/rag/status — index build state + corpus manifest (governed)
4693
+ # GET /org/rag — alias of GET /api/a11oy/v1/rag/query
4694
+ # Marker: a11oy-govern-rag-powerd2.
4695
+ # ===========================================================================
4696
+ try:
4697
+ import a11oy_org_rag as _rag_engine
4698
+ import threading as _rag_threading
4699
+ from fastapi import Request as _RAGRequest
4700
+ from fastapi.responses import JSONResponse as _RAGJSON
4701
+
4702
+ _RAG_BUILD_LOCK = _rag_threading.RLock()
4703
+
4704
+ def _rag_emit_receipt(kind, body):
4705
+ """Emit a governed provenance receipt over a RAG event. Uses the in-image
4706
+ DSSE signer when available (real ECDSA-P256), else an honest UNSIGNED
4707
+ marker — NEVER a fabricated signature. Returns {hash, signed, dsse}."""
4708
+ rec = {"schema": "szl.a11oy.org_rag/v1", "kind": kind, "organ": "a11oy",
4709
+ "doctrine": "v11", "lambda_status": "Conjecture 1 (NOT a theorem)",
4710
+ "body": body}
4711
+ try:
4712
+ import hashlib as _rh, json as _rj
4713
+ rec["receipt_sha256"] = _rh.sha256(
4714
+ _rj.dumps(rec, sort_keys=True, separators=(",", ":")).encode()).hexdigest()
4715
+ except Exception:
4716
+ rec["receipt_sha256"] = ""
4717
+ out = {"hash": rec["receipt_sha256"], "signed": False, "dsse": None, "receipt": rec}
4718
+ try:
4719
+ dsse = _a11oy_sign_receipt(rec) # resolved at call time; real signer
4720
+ out["dsse"] = dsse
4721
+ out["signed"] = bool(dsse.get("signed"))
4722
+ except Exception as _se:
4723
+ out["dsse"] = {"signed": False,
4724
+ "honesty": "UNSIGNED — signer unavailable in this runtime (%s); no signature fabricated." % type(_se).__name__}
4725
+ return out
4726
+
4727
+ def _rag_ensure_index():
4728
+ """Lazy, thread-safe REAL seed-index build (idempotent). Honest: returns the
4729
+ engine's labeled build meta; never claims a built index it didn't build."""
4730
+ st = _rag_engine.status()
4731
+ if st.get("built"):
4732
+ return st
4733
+ with _RAG_BUILD_LOCK:
4734
+ st = _rag_engine.status()
4735
+ if st.get("built"):
4736
+ return st
4737
+ try:
4738
+ return _rag_engine.build_seed_index(emit_receipt=_rag_emit_receipt)
4739
+ except Exception as _be:
4740
+ return {"built": False,
4741
+ "honest_error": "seed index build failed: %s" % type(_be).__name__}
4742
+
4743
+ def _rag_confidence(grounded):
4744
+ """Honest confidence from the grounded chunks' Λ scores. Λ is a geometric
4745
+ mean over relevance axes (semantic, graph-centrality, conformal floor) and
4746
+ is ALREADY < 1.0 by construction (the conformal axis is 1-1/(n+1) < 1).
4747
+ We surface the top grounded Λ as the answer confidence and HARD-CAP it at
4748
+ 0.99 so trust is never reported as 100% (Λ = Conjecture 1, NOT a theorem)."""
4749
+ if not grounded:
4750
+ return 0.0
4751
+ top = max(float(c.get("lambda", 0.0)) for c in grounded)
4752
+ return round(min(0.99, top), 4)
4753
+
4754
+ def _rag_answer(q, k=6, repo=None):
4755
+ """Run the governed RAG query and synthesize a CITED answer. Returns a
4756
+ payload dict ready for gov_envelope, plus an honest status string."""
4757
+ q = (q or "").strip()
4758
+ if not q:
4759
+ desc = {
4760
+ "capability": "org_rag.query",
4761
+ "summary": ("Governed RAG over the estate's OWN corpus (the seven SZL "
4762
+ "categories: app_code, killinchu, anatomy, thesis, formulas, "
4763
+ "doctrine, lean). Ask the doctrine — e.g. 'what is F7?', "
4764
+ "'what is Λ?', 'prove F7' — and get a CITED answer grounded "
4765
+ "in real indexed bytes, with honest confidence (trust never "
4766
+ "100%) and a signed-or-honestly-UNSIGNED provenance receipt."),
4767
+ "method": ("GET ?q=<question>[&k=][&repo=] or POST {q|question, k?, repo?}. "
4768
+ "Bare GET returns this descriptor."),
4769
+ "examples": ["what is F7?", "what is Λ?", "prove F7",
4770
+ "what are the locked-8 formulas?"],
4771
+ "grounding": ("two-stage Λ-weighted agentic RAG (FTS5 lexical ∪ dense, "
4772
+ "graph-centrality re-rank, conformal floor); below the Λ "
4773
+ "relevance floor => i_dont_know (Self-RAG; never fabricates)."),
4774
+ "corpus": _rag_engine.corpus_manifest(),
4775
+ }
4776
+ return desc, "REAL", [{"endpoint": "/api/a11oy/v1/rag/query (POST/GET ?q=) — governed RAG over the estate corpus",
4777
+ "data": {"live": True}}]
4778
+
4779
+ idx = _rag_ensure_index()
4780
+ if not idx.get("built"):
4781
+ payload = {
4782
+ "query": q,
4783
+ "answer": ("The governed RAG index is not built in this runtime, so I will "
4784
+ "NOT fabricate an answer or a citation. " + str(idx.get("honest_error")
4785
+ or "no corpus file could be indexed (no GitHub/HF reach and no in-image mirror).")),
4786
+ "grounded": False,
4787
+ "i_dont_know": True,
4788
+ "index": {"built": False, "mode": idx.get("mode"),
4789
+ "honest_error": idx.get("honest_error")},
4790
+ "confidence": 0.0,
4791
+ "honesty": ("BLOCKED-and-honest: index unbuilt; no answer/citation fabricated "
4792
+ "(Zero-Bandaid Law). honest BLOCKED beats fake green."),
4793
+ }
4794
+ return payload, "DEGRADED", []
4795
+
4796
+ res = _rag_engine.query(q, k=int(k or 6), repo=repo, emit_receipt=_rag_emit_receipt)
4797
+ chunks = res.get("chunks", []) or []
4798
+ idk = bool(res.get("i_dont_know")) or not chunks
4799
+
4800
+ # Build citations from ONLY the chunks actually retrieved (never invent one).
4801
+ citations = []
4802
+ for c in chunks:
4803
+ ev = c.get("evidence", {}) or {}
4804
+ citations.append({
4805
+ "corpus": c.get("corpus"),
4806
+ "source": c.get("source"),
4807
+ "path": c.get("path"),
4808
+ "repo": c.get("repo"),
4809
+ "sha256": c.get("sha256"),
4810
+ "lambda": c.get("lambda"),
4811
+ "citation": ev.get("citation") or (str(c.get("source")) + "/" + str(c.get("path"))),
4812
+ "excerpt": (c.get("text") or "")[:240],
4813
+ })
4814
+ confidence = _rag_confidence(chunks)
4815
+
4816
+ if idk:
4817
+ payload = {
4818
+ "query": q,
4819
+ "answer": ("I don't have a grounded source for that in the estate corpus, so I "
4820
+ "refuse to fabricate one (Self-RAG: no chunk cleared the Λ relevance "
4821
+ "floor of %s). Ask about the doctrine, the formulas (e.g. F7), Λ, the "
4822
+ "Lean proofs, the thesis, or the served code." % res.get("lambda_floor")),
4823
+ "grounded": False,
4824
+ "i_dont_know": True,
4825
+ "confidence": confidence,
4826
+ "citations": [],
4827
+ "retrieval": {"recall_count": res.get("recall_count"),
4828
+ "grounded_count": res.get("grounded_count"),
4829
+ "lambda_floor": res.get("lambda_floor"),
4830
+ "dense_used": res.get("dense_used")},
4831
+ "honesty": ("i_dont_know is first-class — below-Λ-floor chunks never enter the "
4832
+ "answer (P3 non-interference). No citation fabricated."),
4833
+ "receipt_hash": res.get("khipu_hash"),
4834
+ }
4835
+ return payload, "REAL", []
4836
+
4837
+ # Synthesize a grounded, cited answer from the retrieved chunks. The model
4838
+ # prose is an HONEST extractive synthesis over the grounded bytes (no model
4839
+ # key is wired in-Space; the retrieval + grounding + citations are REAL and
4840
+ # the labeled mesh-inference path is honest about that).
4841
+ top = chunks[0]
4842
+ lead = ("Grounded answer to %r from the estate's own corpus (%d cited source%s, "
4843
+ "top Λ=%s, floor=%s): the most relevant indexed evidence is %s "
4844
+ "(corpus=%s). Excerpt: %s") % (
4845
+ q, len(chunks), "" if len(chunks) == 1 else "s",
4846
+ top.get("lambda"), res.get("lambda_floor"),
4847
+ (top.get("evidence", {}) or {}).get("citation")
4848
+ or (str(top.get("source")) + "/" + str(top.get("path"))),
4849
+ top.get("corpus"),
4850
+ (top.get("text") or "").strip()[:360].replace("\n", " "))
4851
+ payload = {
4852
+ "query": q,
4853
+ "answer": lead,
4854
+ "grounded": True,
4855
+ "i_dont_know": False,
4856
+ "confidence": confidence,
4857
+ "confidence_basis": ("top grounded Λ (geometric mean of relevance axes incl. a "
4858
+ "conformal anti-overconfidence floor), hard-capped <1.0 — "
4859
+ "trust is NEVER 100%; Λ is Conjecture 1, NOT a theorem."),
4860
+ "citations": citations,
4861
+ "retrieval": {"recall_count": res.get("recall_count"),
4862
+ "grounded_count": res.get("grounded_count"),
4863
+ "lambda_floor": res.get("lambda_floor"),
4864
+ "dense_used": res.get("dense_used"),
4865
+ "hyde_used": res.get("hyde_used")},
4866
+ "inference_path": ("governed mesh inference: REAL two-stage Λ-weighted retrieval + "
4867
+ "graph re-rank over indexed bytes; extractive synthesis of the "
4868
+ "grounded evidence (no model key wired in-Space — honest about that, "
4869
+ "never fabricated prose presented as a model's)."),
4870
+ "honesty": ("Every cited source was actually retrieved from the indexed corpus; "
4871
+ "each carries its real path + sha256 + corpus category. No source is "
4872
+ "claimed that wasn't retrieved."),
4873
+ "receipt_hash": res.get("khipu_hash"),
4874
+ }
4875
+ rcpt = _rag_emit_receipt("org_rag.answer",
4876
+ {"query": q[:160], "grounded": len(chunks),
4877
+ "confidence": confidence,
4878
+ "top_citation": citations[0]["citation"] if citations else None})
4879
+ payload["receipt"] = {"hash": rcpt.get("hash"), "signed": rcpt.get("signed"),
4880
+ "dsse": rcpt.get("dsse")}
4881
+ return payload, "REAL", citations
4882
+
4883
+ @app.get("/api/a11oy/v1/rag/query")
4884
+ async def _rag_query_get(q: str = "", k: int = 6, repo: str = ""):
4885
+ payload, st, cites = _rag_answer(q, k=k, repo=(repo or None))
4886
+ return _RAGJSON(gov_envelope(payload, status=st, citations=cites))
4887
+
4888
+ @app.post("/api/a11oy/v1/rag/query")
4889
+ async def _rag_query_post(request: _RAGRequest):
4890
+ try:
4891
+ body = await request.json()
4892
+ except Exception:
4893
+ body = {}
4894
+ if not isinstance(body, dict):
4895
+ body = {}
4896
+ q = body.get("q") or body.get("question") or body.get("query") or ""
4897
+ k = body.get("k", 6)
4898
+ repo = body.get("repo") or None
4899
+ payload, st, cites = _rag_answer(q, k=k, repo=repo)
4900
+ return _RAGJSON(gov_envelope(payload, status=st, citations=cites))
4901
+
4902
+ @app.get("/org/rag")
4903
+ async def _rag_query_alias(q: str = "", k: int = 6, repo: str = ""):
4904
+ payload, st, cites = _rag_answer(q, k=k, repo=(repo or None))
4905
+ return _RAGJSON(gov_envelope(payload, status=st, citations=cites))
4906
+
4907
+ @app.get("/api/a11oy/v1/rag/status")
4908
+ async def _rag_status_get():
4909
+ try:
4910
+ st = _rag_engine.status()
4911
+ except Exception as _se:
4912
+ st = {"built": False, "honest_error": "status unavailable: %s" % type(_se).__name__}
4913
+ built = bool(st.get("built"))
4914
+ return _RAGJSON(gov_envelope(
4915
+ {"index": st, "corpus": _rag_engine.corpus_manifest()},
4916
+ status=("REAL" if built else "DEGRADED"),
4917
+ citations=[{"endpoint": "a11oy_org_rag.status() + corpus_manifest()",
4918
+ "data": {"built": built, "mode": st.get("mode")}}]))
4919
+
4920
+ print("[a11oy] governed RAG mounted: GET/POST /api/a11oy/v1/rag/query, "
4921
+ "GET /org/rag, GET /api/a11oy/v1/rag/status (ask-the-doctrine over the "
4922
+ "estate corpus; cited + governed)", flush=True)
4923
+ except Exception as _rag_e: # pragma: no cover - additive, defensive
4924
+ print("[a11oy] governed RAG NOT mounted (" + repr(_rag_e) + "); SPA + API unaffected", flush=True)
4925
+ # === END GOVERNED RAG ===
4926
+
4927
  # ===========================================================================
4928
  # SELF-CONTAINED WARHACKER DEMO (ADDITIVE, 2026-06-05). a11oy runs the 5 demo
4929
  # scenarios IN-IMAGE — no external service calls. Registered BEFORE the legacy