-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient_field_encoder.py
More file actions
executable file
·2071 lines (1860 loc) · 94.8 KB
/
Copy pathclient_field_encoder.py
File metadata and controls
executable file
·2071 lines (1860 loc) · 94.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# Copyright 2026 Shri Narayan Justin Ram / Mushku Nobleworks. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0 OR Commercial
"""Standalone sample client field encoder/decoder.
The script has no project imports. It emits opaque signed-int16 field signals
from local typed atoms with a client-held key and keeps a local append-only map
ledger so returned field identifiers can be resolved back to client files.
"""
from __future__ import annotations
import argparse
import hashlib
import hmac
import json
import os
import re
import subprocess
import sys
from dataclasses import dataclass
from datetime import UTC, datetime
from pathlib import Path
from typing import Any
SCHEMA_VERSION = "openencoder-oezk1-request-v1"
LEDGER_SCHEMA_VERSION = "client-field-map-ledger-v1"
FIELD_RECEIPT_SCHEMA_VERSION = "openencoder-oezk1-field-receipt-v1"
REQUEST_RECEIPT_SCHEMA_VERSION = "openencoder-oezk1-request-receipt-v1"
TYPED_ATOM_SCHEMA_VERSION = "openencoder-oezk1-typed-atom-v1"
REFERENCE_RECIPE_ID = "openencoder-oezk1-signed-int16-typed-atom-v1"
REFERENCE_DTYPE = "int16"
REFERENCE_SHAPE = "dense_fixed_width"
REFERENCE_AXIS_POLICY = "hmac-sha256-typed-atom-axis-v1"
REFERENCE_WEIGHT_POLICY = "hmac-sha256-signed-int16-weight-v1"
REFERENCE_COMBINE_POLICY = "saturating_add"
INT16_FIELD_MIN = -32767
INT16_FIELD_MAX = 32767
DECODE_SCHEMA_VERSION = "openencoder-oezk1-emission-decode-v1"
ANSWER_FOLDER_DECODE_SCHEMA_VERSION = "openencoder-oezk1-answer-folder-decode-v1"
CONFIG_SCHEMA_VERSION = "openencoder-client-field-kit-config-v1"
SUBMISSION_MANIFEST_SCHEMA_VERSION = "client-field-submission-manifest-v1"
CRITICAL_INFO_TABLE_SCHEMA_VERSION = "client-field-critical-info-table-v1"
LEDGER_TIME_ENV = "CLIENT_FIELD_LEDGER_WRITTEN_AT"
TOKEN_RE = re.compile(r"\w+", re.UNICODE)
TOKENIZATION_POLICY = "unicode-word-token-v2"
SECRET_MIN_BYTES = 16
DISALLOWED_CLIENT_SECRETS = {
"example-not-secret",
"sample-client-secret",
}
FIELD_REFERENCE_KEYS = {
"corpus_hash",
"field_id",
"item_id",
"query_payload_hash",
"record_id",
"request_id",
}
WIRE_ROLES = {"corpus": "a", "query": "b"}
COMPATIBILITY_METADATA_KEYS = {"recipe_id", "dtype", "shape", "schema_version", "typed_atom_schema_version"}
ANSWER_TEXT_MAX_CHARS = 200_000
ANSWER_STOPWORDS = {
"a",
"an",
"and",
"are",
"as",
"at",
"be",
"before",
"by",
"do",
"does",
"for",
"from",
"how",
"in",
"is",
"it",
"of",
"on",
"or",
"the",
"to",
"what",
"when",
"where",
"which",
"who",
"why",
}
CLIENT_FIELD_PROTOCOL_REQUIREMENTS = """
OpenEncoder client field protocol requirements for third-party field services:
1. The API receives only field objects, not private source text. The API emits field results plus emission_quality.
2. The local decoder owns answer recovery because it has the private ledger and source files.
3. Every corpus source and every query source MUST be written to the local append-only ledger before sending a request.
4. Every ledger field_map event MUST include role, item_id, field_id, source_label, source_path, text_sha256, signal_sha256, width, context, and calc_hash.
5. Every request_map event MUST bind the client_request_id to the sent request hash, request receipt hash, and all query field ids.
6. Every field_group_map event MUST bind the corpus_hash to all member corpus item ids and member field ids.
7. The field tensor MUST be a fixed-width list of signed int16-compatible integers. This reference kit uses width=64 by default.
8. The reference client emits signed int16 typed-atom tensors in [-32767, 32767].
9. Services MUST preserve recipe_id, dtype, shape, calc_hash, request_sha256, request_receipt_sha256, and returned references needed by the local decoder.
10. calc_hash is an unkeyed recipe_sha256 label over public recipe metadata. If a third-party field service changes tokenization, typed atoms, weighting, width, modality handling, or normalization, it MUST change calc_hash.
11. corpus_hash and query_payload_hash MUST be opaque, content-bound ids that the local ledger can resolve.
12. The API response is correct only for field math. Natural-language answers MUST be decoded locally from the ledger/source files.
13. To answer image/audio/video queries, the third-party field service MUST store local answerable text such as captions, OCR, transcript, or operator-approved descriptions in the ledger. Raw binary bytes alone are not enough for a human answer.
14. The decoder MUST show the original query, the final answer in the query language/dialect, supporting source labels/excerpts, replay status, and emission quality.
15. The decoder MUST fail closed when the ledger hash chain is invalid, source files do not match recorded hashes, field ids do not resolve, encoding compatibility fails, or a query cannot be answered from local source text.
""".strip()
@dataclass(frozen=True)
class SourceItem:
role: str
source_label: str
source_path: str
text: str
order: int
@dataclass(frozen=True)
class EncodedItem:
source: SourceItem
item_id: str
field_id: str
signal: list[int]
text_sha256: str
canonical_text_sha256: str
signal_sha256: str
typed_atom_count: int
typed_atom_sha256: str
field_encoding: dict[str, Any]
field_receipt: dict[str, Any]
field_receipt_sha256: str
def _mac(secret: bytes, *parts: object) -> bytes:
message = "\0".join(str(part) for part in parts).encode()
return hmac.new(secret, message, hashlib.sha256).digest()
def _tokens(text: str) -> list[str]:
return TOKEN_RE.findall(text.lower()) or [""]
def _canonical_token_text(text: str) -> str:
return " ".join(token for token in _tokens(text) if token)
def _typed_atoms(text: str) -> list[dict[str, Any]]:
counts: dict[str, int] = {}
ordered_tokens = [token for token in _tokens(text) if token]
for token in ordered_tokens:
counts[token] = counts.get(token, 0) + 1
atoms = [
{"kind": "token", "value_sha256": _sha256_text(token), "count": count}
for token, count in sorted(counts.items())
]
canonical = " ".join(ordered_tokens)
atoms.append({"kind": "canonical_text", "value_sha256": _sha256_text(canonical), "count": 1})
atoms.append({"kind": "token_count", "value_sha256": _sha256_text(str(len(ordered_tokens))), "count": 1})
return atoms
def _recipe_descriptor(*, width: int, context: str) -> dict[str, Any]:
return {
"schema_version": "openencoder-oezk1-recipe-v1",
"recipe_id": REFERENCE_RECIPE_ID,
"dtype": REFERENCE_DTYPE,
"shape": REFERENCE_SHAPE,
"width": int(width),
"context": context,
"typed_atom_schema_version": TYPED_ATOM_SCHEMA_VERSION,
"tokenization_policy": TOKENIZATION_POLICY,
"axis_policy": REFERENCE_AXIS_POLICY,
"weight_policy": REFERENCE_WEIGHT_POLICY,
"combine_policy": REFERENCE_COMBINE_POLICY,
"range": [INT16_FIELD_MIN, INT16_FIELD_MAX],
}
def _field_encoding(*, width: int, context: str) -> dict[str, Any]:
descriptor = _recipe_descriptor(width=width, context=context)
return {
"recipe_id": REFERENCE_RECIPE_ID,
"dtype": REFERENCE_DTYPE,
"shape": REFERENCE_SHAPE,
"width": int(width),
"typed_atom_schema_version": TYPED_ATOM_SCHEMA_VERSION,
"tokenization_policy": TOKENIZATION_POLICY,
"axis_policy": REFERENCE_AXIS_POLICY,
"weight_policy": REFERENCE_WEIGHT_POLICY,
"combine_policy": REFERENCE_COMBINE_POLICY,
"recipe_sha256": _sha256_json(descriptor),
}
def _saturating_add(current: int, delta: int) -> int:
return max(INT16_FIELD_MIN, min(INT16_FIELD_MAX, current + delta))
def _read_text(path: Path) -> str:
return path.read_text(encoding="utf-8", errors="replace")
def _iter_text_files(path: Path) -> list[Path]:
if path.is_file():
return [path]
if path.is_dir():
files = sorted(candidate for candidate in path.rglob("*") if candidate.is_file())
if files:
return files
raise ValueError(f"path contains no files: {path}")
raise ValueError(f"path does not exist: {path}")
def _source_items_from_paths(raw_paths: list[str], *, role: str, start_order: int = 0) -> list[SourceItem]:
items: list[SourceItem] = []
order = start_order
for raw_path in raw_paths:
root = Path(raw_path)
for file_path in _iter_text_files(root):
source_label = str(file_path if root.is_file() else file_path.relative_to(root))
items.append(
SourceItem(
role=role,
source_label=source_label,
source_path=str(file_path.resolve()),
text=_read_text(file_path),
order=order,
)
)
order += 1
return items
def _source_items_from_literals(values: list[str], *, role: str, start_order: int = 0) -> list[SourceItem]:
return [
SourceItem(role=role, source_label=f"{role}:literal:{start_order + idx}", source_path="", text=value, order=start_order + idx)
for idx, value in enumerate(values)
]
def _canonical_json_bytes(value: Any) -> bytes:
return json.dumps(value, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode()
def _sha256_json(value: Any) -> str:
return hashlib.sha256(_canonical_json_bytes(value)).hexdigest()
def requirements_command(_args: argparse.Namespace | None = None) -> dict[str, Any]:
return {
"schema_version": "openencoder-client-field-protocol-requirements-v1",
"purpose": "requirements for third-party field services that want OpenEncoder field API responses to decode locally into human answers",
"api_decoder_split": {
"api_role": "accept field objects and emit deterministic field results plus emission_quality",
"decoder_role": "use the private local ledger and source files to emit human-readable answers",
"api_must_not": "synthesize private natural-language answers from opaque fields",
},
"human_readable_requirements": CLIENT_FIELD_PROTOCOL_REQUIREMENTS,
"machine_readable_requirements": [
"append_only_local_ledger_required",
"field_map_events_bind_every_source",
"field_group_map_binds_corpus_hash_to_members",
"request_map_binds_client_request_id_to_payload_hash",
"service_emission_binds_request_sha256_and_request_receipt_sha256",
"fixed_width_signed_int16_field_tensor_required",
"typed_atom_recipe_metadata_required",
"compatibility_gated_decode_required",
"calc_hash_is_unkeyed_recipe_sha256",
"local_decoder_generates_natural_language_answer",
"non_text_modalities_require_local_answerable_text",
"decoder_fails_closed_on_unresolved_or_hash_mismatch",
"decoded_output_contains_monospace_table_and_txt_report",
],
}
def _dig(value: Any, *keys: str) -> Any:
current = value
for key in keys:
if not isinstance(current, dict):
return None
current = current.get(key)
return current
def _display_value(value: Any, *, max_len: int = 96) -> str:
if value is True:
text = "true"
elif value is False:
text = "false"
elif value is None:
text = ""
elif isinstance(value, list):
text = ", ".join(_display_value(item, max_len=max_len) for item in value)
elif isinstance(value, dict):
text = json.dumps(value, sort_keys=True, separators=(",", ":"), ensure_ascii=False)
else:
text = str(value)
text = " ".join(text.split())
if len(text) > max_len:
return text[: max_len - 3] + "..."
return text
def _short_hash(value: Any) -> str:
text = str(value or "")
if text.startswith("sha256:"):
digest = text.split(":", 1)[1]
return "sha256:" + digest[:12]
if len(text) == 64 and all(char in "0123456789abcdefABCDEF" for char in text):
return text[:12]
if len(text) > 28:
return text[:25] + "..."
return text
def _render_table(title: str, headers: list[str], rows: list[list[Any]]) -> str:
rendered_rows = [[_display_value(cell, max_len=96) for cell in row] for row in rows]
widths = [len(header) for header in headers]
for row in rendered_rows:
for idx, cell in enumerate(row):
widths[idx] = max(widths[idx], len(cell))
border = "+" + "+".join("-" * (width + 2) for width in widths) + "+"
def render_row(values: list[str]) -> str:
return "| " + " | ".join(value.ljust(widths[idx]) for idx, value in enumerate(values)) + " |"
lines = [title, border, render_row(headers), border]
lines.extend(render_row(row) for row in rendered_rows)
lines.append(border)
return "\n".join(lines)
def _source_labels_from_decoded(decoded: dict[str, Any], *, role: str, max_labels: int = 8) -> str:
labels: list[str] = []
seen: set[str] = set()
for ref in decoded.get("resolved_references") or []:
if not isinstance(ref, dict):
continue
for match in ref.get("matches") or []:
if not isinstance(match, dict):
continue
if match.get("role") == role and match.get("source_label"):
label = str(match["source_label"])
if label not in seen:
seen.add(label)
labels.append(label)
for member in match.get("members") or []:
if isinstance(member, dict) and member.get("role") == role and member.get("source_label"):
label = str(member["source_label"])
if label not in seen:
seen.add(label)
labels.append(label)
if not labels:
return "not resolved"
suffix = f", +{len(labels) - max_labels} more" if len(labels) > max_labels else ""
return ", ".join(labels[:max_labels]) + suffix
def _query_source_for_result(decoded: dict[str, Any], result: dict[str, Any]) -> str:
query_payload_hash = result.get("query_payload_hash") or _dig(result, "core_result", "query_payload_hash")
if not query_payload_hash:
return "not resolved"
for ref in decoded.get("resolved_references") or []:
if not isinstance(ref, dict) or ref.get("value") != query_payload_hash:
continue
for match in ref.get("matches") or []:
if isinstance(match, dict) and match.get("role") == "query" and match.get("source_label"):
return str(match["source_label"])
return "not resolved"
def _critical_status(value: Any) -> str:
return "yes" if value is True else "no" if value is False else "unknown"
def _percent(numerator: int, denominator: int) -> str:
if denominator <= 0:
return "0.0%"
return f"{(float(numerator) / float(denominator)) * 100.0:.1f}%"
def _pass_fail(value: bool) -> str:
return "PASS" if value else "FAIL"
def _resolved_entries(decoded: dict[str, Any], *, role: str) -> list[dict[str, Any]]:
entries: list[dict[str, Any]] = []
seen: set[str] = set()
for ref in decoded.get("resolved_references") or []:
if not isinstance(ref, dict):
continue
for match in ref.get("matches") or []:
if not isinstance(match, dict):
continue
candidates = list(match.get("members") or []) if match.get("event_type") == "field_group_map" else [match]
for candidate in candidates:
if not isinstance(candidate, dict) or candidate.get("role") != role:
continue
identity = str(candidate.get("item_id") or candidate.get("field_id") or candidate.get("source_path") or "")
if identity and identity in seen:
continue
if identity:
seen.add(identity)
entries.append(candidate)
return entries
def _query_entry_for_hash(decoded: dict[str, Any], query_hash: str) -> dict[str, Any] | None:
for ref in decoded.get("resolved_references") or []:
if not isinstance(ref, dict) or ref.get("value") != query_hash:
continue
for match in ref.get("matches") or []:
if isinstance(match, dict) and match.get("role") == "query":
return match
return None
def _read_entry_text(entry: dict[str, Any]) -> tuple[str, bool]:
if isinstance(entry.get("text"), str):
return str(entry["text"]), True
source_path = entry.get("source_path")
if not isinstance(source_path, str) or not source_path:
return "", False
path = Path(source_path)
if not path.exists():
return "", False
try:
text = path.read_text(encoding="utf-8", errors="replace")[:ANSWER_TEXT_MAX_CHARS]
except OSError:
return "", False
expected = str(entry.get("text_sha256") or "")
return text, bool(expected and _sha256_text(text if len(text) < ANSWER_TEXT_MAX_CHARS else path.read_text(encoding="utf-8", errors="replace")) == expected)
def _answer_tokens(text: str) -> set[str]:
return {token for token in _tokens(text) if token and token not in ANSWER_STOPWORDS and len(token) > 1}
def _sentences(text: str) -> list[str]:
parts = re.split(r"(?<=[.!?])\s+|\n+", text)
return [" ".join(part.split()) for part in parts if part.strip()]
def _best_local_answer(query_text: str, corpus_entries: list[dict[str, Any]]) -> dict[str, Any]:
query_tokens = _answer_tokens(query_text)
if not query_tokens:
return {"answer_text": "", "status": "query_text_unavailable", "score": 0}
best: dict[str, Any] = {"answer_text": "", "status": "no_supporting_source_text", "score": 0}
for entry in corpus_entries:
source_text, source_ok = _read_entry_text(entry)
if not source_ok or not source_text.strip():
continue
for sentence in _sentences(source_text)[:200]:
sentence_tokens = _answer_tokens(sentence)
overlap = query_tokens & sentence_tokens
score = (len(overlap) * 100) + min(len(sentence_tokens), 25)
if score > int(best.get("score") or 0):
best = {
"answer_text": sentence,
"answer_source_label": entry.get("source_label") or "",
"answer_source_path": entry.get("source_path") or "",
"matched_query_terms": sorted(overlap),
"status": "answered_from_local_source",
"score": score,
}
return best
def _local_answer_report(decoded: dict[str, Any]) -> dict[str, Any]:
emission = dict(decoded.get("emission") or {}) if isinstance(decoded.get("emission"), dict) else {}
query_results = emission.get("query_results")
if not isinstance(query_results, list) or not query_results:
query_results = [{"query_index": 0, "core_result": emission.get("core_result") or {}}]
corpus_entries = _resolved_entries(decoded, role="corpus")
rows = []
for idx, result in enumerate(query_results):
if not isinstance(result, dict):
continue
result_core = dict(result.get("core_result") or {}) if isinstance(result.get("core_result"), dict) else {}
query_hash = str(result.get("query_payload_hash") or result_core.get("query_payload_hash") or "")
query_entry = _query_entry_for_hash(decoded, query_hash) if query_hash else None
query_text, query_ok = _read_entry_text(query_entry or {}) if query_entry else ("", False)
answer = _best_local_answer(query_text, corpus_entries) if query_ok else {"answer_text": "", "status": "query_source_text_unavailable", "score": 0}
replay_verified = _dig(result, "determinism_verification", "verified")
if replay_verified is None and len(query_results) == 1:
replay_verified = _dig(emission, "determinism_boundary", "deterministic_replay_supported")
answered = bool(answer.get("answer_text")) and answer.get("status") == "answered_from_local_source"
rows.append(
{
"query_index": result.get("query_index", idx),
"query_source_label": (query_entry or {}).get("source_label") or "not resolved",
"query_payload_hash": query_hash,
"query_text": " ".join(query_text.split()) if query_ok else "",
"answer_text": answer.get("answer_text") or "",
"answer_source_label": answer.get("answer_source_label") or "",
"matched_query_terms": answer.get("matched_query_terms") or [],
"status": "answered" if answered else str(answer.get("status") or "not_answered"),
"replay_verified": replay_verified is True,
"source_hash_verified": query_ok,
}
)
compatibility = dict(decoded.get("compatibility") or {}) if isinstance(decoded.get("compatibility"), dict) else {}
compatibility_passed = compatibility.get("passed") is True
required_unresolved_count = int(decoded.get("required_unresolved_reference_count") or 0)
all_answered = bool(rows) and compatibility_passed and required_unresolved_count == 0 and all(row["status"] == "answered" and row["replay_verified"] for row in rows)
question_count = len(rows)
answered_count = sum(1 for row in rows if row["status"] == "answered")
replay_verified_count = sum(1 for row in rows if row["replay_verified"])
source_hash_verified_count = sum(1 for row in rows if row["source_hash_verified"])
query_resolved_count = sum(1 for row in rows if row["query_source_label"] != "not resolved")
ledger_valid = _dig(decoded, "ledger", "hash_chain_valid") is True
unresolved_count = int(decoded.get("unresolved_field_like_reference_count") or 0)
human_success_score = 100.0 if all_answered and ledger_valid else min(
99.0,
(
(answered_count / question_count if question_count else 0.0)
+ (replay_verified_count / question_count if question_count else 0.0)
+ (source_hash_verified_count / question_count if question_count else 0.0)
+ (1.0 if ledger_valid else 0.0)
)
* 25.0,
)
return {
"schema_version": "client-field-local-answer-report-v1",
"answer_language_policy": "answer_text is quoted from the client's local source text, preserving the source language/dialect; third-party field services must store answerable text for non-text sources",
"all_questions_answered": all_answered,
"answered_count": answered_count,
"question_count": question_count,
"replay_verified_count": replay_verified_count,
"source_hash_verified_count": source_hash_verified_count,
"query_resolved_count": query_resolved_count,
"ledger_hash_chain_valid": ledger_valid,
"unresolved_field_like_reference_count": unresolved_count,
"required_unresolved_reference_count": required_unresolved_count,
"incidental_unresolved_reference_count": int(decoded.get("incidental_unresolved_reference_count") or 0),
"compatibility_passed": compatibility_passed,
"compatibility_blocker_count": int(compatibility.get("blocker_count") or 0),
"compatibility_blockers": compatibility.get("blockers") or [],
"answer_coverage_percent": _percent(answered_count, question_count),
"replay_coverage_percent": _percent(replay_verified_count, question_count),
"source_hash_coverage_percent": _percent(source_hash_verified_count, question_count),
"query_resolution_percent": _percent(query_resolved_count, question_count),
"human_success_score_percent": round(human_success_score, 1),
"human_verdict": "PASS: every question has a verified local answer and replay proof" if all_answered and ledger_valid else "FAIL: not every question has a verified local answer, replay proof, and compatible encoding",
"parity_claim": "100_percent_local_parity" if all_answered else "not_all_questions_answered_from_local_sources",
"rows": rows,
}
def _emission_performance_breakdown(emission: dict[str, Any]) -> dict[str, Any]:
performance = emission.get("performance") if isinstance(emission.get("performance"), dict) else {}
quality_performance = _dig(emission, "emission_quality", "performance")
quality_performance = dict(quality_performance) if isinstance(quality_performance, dict) else {}
core_total = performance.get("core_calc_elapsed_ms_total")
if core_total is None:
query_results = [row for row in emission.get("query_results") or [] if isinstance(row, dict)]
core_values = []
for row in query_results:
value = _dig(row, "core_result", "elapsed_ms")
if isinstance(value, int | float):
core_values.append(float(value))
core_total = round(sum(core_values), 4) if core_values else None
api_elapsed = performance.get("api_elapsed_ms", quality_performance.get("api_elapsed_ms"))
overhead = performance.get("api_overhead_elapsed_ms")
if overhead is None and isinstance(api_elapsed, int | float) and isinstance(core_total, int | float):
overhead = round(max(0.0, float(api_elapsed) - float(core_total)), 4)
return {
"api_elapsed_ms": api_elapsed,
"core_calc_elapsed_ms_total": core_total,
"api_overhead_elapsed_ms": overhead,
"ultra_minimal_time_passed": performance.get("ultra_minimal_time_passed", quality_performance.get("ultra_minimal_time_passed")),
}
def _customer_success_scoreboard(decoded: dict[str, Any]) -> str:
emission = dict(decoded.get("emission") or {}) if isinstance(decoded.get("emission"), dict) else {}
report = dict(decoded.get("local_answer_report") or {}) if isinstance(decoded.get("local_answer_report"), dict) else {}
question_count = int(report.get("question_count") or 0)
answered_count = int(report.get("answered_count") or 0)
replay_count = int(report.get("replay_verified_count") or 0)
source_count = int(report.get("source_hash_verified_count") or 0)
query_count = int(report.get("query_resolved_count") or 0)
perf = _emission_performance_breakdown(emission)
quality = emission.get("emission_quality") if isinstance(emission.get("emission_quality"), dict) else {}
accuracy = quality.get("accuracy") if isinstance(quality.get("accuracy"), dict) else {}
validity = quality.get("validity") if isinstance(quality.get("validity"), dict) else {}
mandatory_bar = quality.get("mandatory_emission_bar") if isinstance(quality.get("mandatory_emission_bar"), dict) else emission.get("mandatory_emission_bar")
mandatory_bar = dict(mandatory_bar) if isinstance(mandatory_bar, dict) else {}
system_full_bar = emission.get("system_full_bar_proof") if isinstance(emission.get("system_full_bar_proof"), dict) else {}
accuracy_metrics = accuracy.get("metrics") if isinstance(accuracy.get("metrics"), dict) else {}
benchmark_metric_present = any(str(key).split("@", 1)[0] in {"p", "fp", "recall", "hit_rate", "mrr", "ndcg", "gndcg"} for key in accuracy_metrics)
rows = [
["Field emission", "withheld by failure gate" if emission.get("field_emission_withheld") is True else "emitted", _pass_fail(emission.get("field_emission_withheld") is not True)],
["Overall verdict", report.get("human_verdict") or "FAIL: no local answer report", _pass_fail(bool(report.get("all_questions_answered")) and bool(report.get("ledger_hash_chain_valid")))],
["Questions answered", f"{answered_count}/{question_count} ({report.get('answer_coverage_percent') or '0.0%'})", _pass_fail(question_count > 0 and answered_count == question_count)],
["Query files verified", f"{query_count}/{question_count} ({report.get('query_resolution_percent') or '0.0%'})", _pass_fail(question_count > 0 and query_count == question_count)],
["Source hashes verified", f"{source_count}/{question_count} ({report.get('source_hash_coverage_percent') or '0.0%'})", _pass_fail(question_count > 0 and source_count == question_count)],
["API replay verified", f"{replay_count}/{question_count} ({report.get('replay_coverage_percent') or '0.0%'})", _pass_fail(question_count > 0 and replay_count == question_count)],
["Ledger integrity", f"hash_chain_valid={_critical_status(report.get('ledger_hash_chain_valid'))}", _pass_fail(bool(report.get("ledger_hash_chain_valid")))],
["Mandatory API bar", f"passed={_critical_status(mandatory_bar.get('passed'))}; blockers={', '.join(mandatory_bar.get('blockers') or []) or 'none'}", _pass_fail(mandatory_bar.get("passed") is True)],
["API field accuracy", f"score_floor={accuracy.get('score_floor', 'not reported')}; evidence={accuracy.get('evidence_type') or 'not reported'}", _pass_fail(accuracy.get("proven_100_percent") is True)],
["API validity", f"validity_score={validity.get('validity_score', 'not reported')}", _pass_fail(validity.get("deterministically_valid") is True)],
["System full bar", f"proof_passed={_critical_status(system_full_bar.get('proof_passed'))}; independent={_critical_status(system_full_bar.get('independently_verified'))}", _pass_fail(system_full_bar.get("proof_passed") is True)],
["API quality fields", f"all_three_reported={_critical_status(quality.get('all_three_reported'))}", _pass_fail(quality.get("all_three_reported") is True)],
["API time", f"{perf.get('api_elapsed_ms', 'not reported')} ms total", _pass_fail(perf.get("ultra_minimal_time_passed") is True)],
["Core field math time", f"{perf.get('core_calc_elapsed_ms_total', 'not reported')} ms", "INFO"],
["API overhead", f"{perf.get('api_overhead_elapsed_ms', 'not reported')} ms", "INFO"],
["Benchmark relevance", f"P@K/gNDCG present={_critical_status(benchmark_metric_present)}; reason={accuracy.get('unavailable_reason') or 'reported'}", "INFO"],
["Independent verification", "not independently verified; explicitly flagged", "INFO"],
["Cryptographic full OO", f"separate external claim passed={_critical_status(quality.get('full_oblivious_oracle_claim_passed'))}", "INFO"],
["Human success score", f"{report.get('human_success_score_percent', 0.0)}%", _pass_fail(float(report.get("human_success_score_percent") or 0.0) >= 100.0)],
]
return _render_table("Customer Proof Scoreboard", ["Check", "Result", "Status"], rows)
def _answer_critical_info_table(decoded: dict[str, Any], *, answer_path: str = "") -> str:
emission = dict(decoded.get("emission") or {}) if isinstance(decoded.get("emission"), dict) else {}
core_result = dict(emission.get("core_result") or {}) if isinstance(emission.get("core_result"), dict) else {}
determinism = dict(emission.get("determinism_boundary") or {}) if isinstance(emission.get("determinism_boundary"), dict) else {}
corporate_proof = (
dict(emission.get("corporate_field_groth16_proof") or {})
if isinstance(emission.get("corporate_field_groth16_proof"), dict)
else {}
)
openencoder_status_value = _dig(emission, "openencoder_answer_field", "status")
openencoder_status = dict(openencoder_status_value) if isinstance(openencoder_status_value, dict) else {}
claim_boundary_value = emission.get("claim_boundary") or _dig(emission, "openencoder_answer_field", "claim_boundary")
claim_boundary = dict(claim_boundary_value) if isinstance(claim_boundary_value, dict) else {}
replay_verified = determinism.get("same_normalized_inputs_same_core_build_same_outputs")
if replay_verified is None:
replay_rows = [row for row in determinism.get("replay_verifications") or [] if isinstance(row, dict)]
replay_verified = all(row.get("verified") is True for row in replay_rows) if replay_rows else None
summary_rows = [
["Answer path", answer_path or "direct emission"],
["Object", emission.get("object") or "unknown"],
["Channel", emission.get("channel") or core_result.get("channel") or "unknown"],
["Query mode/count", f"{emission.get('query_mode') or 'single'} / {emission.get('query_count') or core_result.get('process_query_count') or 'unknown'}"],
["Ledger", f"hash_chain_valid={_critical_status(_dig(decoded, 'ledger', 'hash_chain_valid'))}; events={_dig(decoded, 'ledger', 'event_count') or 0}"],
["Resolved refs", f"{decoded.get('resolved_reference_count') or 0} resolved; {decoded.get('unresolved_field_like_reference_count') or 0} unresolved"],
["Corpus sources", _source_labels_from_decoded(decoded, role="corpus")],
["Query sources", _source_labels_from_decoded(decoded, role="query")],
["Deterministic replay", _critical_status(replay_verified)],
["Full ZK proof claim", _critical_status(emission.get("full_zk_proof_claim"))],
["OpenEncoder ready", _critical_status(openencoder_status.get("openencoder_ready"))],
["Groth16 proof", f"requested={_critical_status(corporate_proof.get('proof_requested'))}; ready={_critical_status(corporate_proof.get('proof_ready'))}"],
["Alignment score", core_result.get("alignment_score")],
["Positive/negative", f"{core_result.get('positive_alignment_score')} / {core_result.get('negative_alignment_score')}"],
["Corpus hash", _short_hash(core_result.get("corpus_hash"))],
["Result hash", _short_hash(core_result.get("result_field_sha256"))],
["Emission hash", _short_hash(decoded.get("emission_sha256"))],
["Claim boundary", claim_boundary.get("honest_label") or claim_boundary.get("claim_supported") or "not declared"],
]
query_rows = []
answer_rows = []
answer_report = dict(decoded.get("local_answer_report") or {}) if isinstance(decoded.get("local_answer_report"), dict) else {}
for row in answer_report.get("rows") or []:
if not isinstance(row, dict):
continue
answer_rows.append(
[
row.get("query_index"),
row.get("query_source_label"),
row.get("answer_text") or row.get("status"),
row.get("answer_source_label"),
_critical_status(row.get("replay_verified")),
]
)
query_results = emission.get("query_results") or []
if isinstance(query_results, list):
for idx, result in enumerate(query_results[:10]):
if not isinstance(result, dict):
continue
result_core = dict(result.get("core_result") or {}) if isinstance(result.get("core_result"), dict) else {}
query_rows.append(
[
result.get("query_index", idx),
_query_source_for_result(decoded, result),
result_core.get("alignment_score", ""),
_critical_status(_dig(result, "determinism_verification", "verified")),
_short_hash(result_core.get("result_field_sha256")),
]
)
tables = [
_customer_success_scoreboard(decoded),
_render_table("Critical Info", ["Field", "Value"], summary_rows),
]
if answer_rows:
tables.append(_render_table("Decoded Natural-Language Answers", ["Query", "Question file", "Answer", "Source", "Replay"], answer_rows))
if query_rows:
tables.append(_render_table("Query Results", ["Query", "Source", "Alignment", "Replay", "Result hash"], query_rows))
return "\n\n".join(tables)
def _folder_critical_info_table(decoded_answers: list[dict[str, Any]]) -> str:
rows = []
for idx, item in enumerate(decoded_answers):
decoded = dict(item.get("decoded") or {}) if isinstance(item.get("decoded"), dict) else {}
emission = dict(decoded.get("emission") or {}) if isinstance(decoded.get("emission"), dict) else {}
corporate_proof = dict(emission.get("corporate_field_groth16_proof") or {}) if isinstance(emission.get("corporate_field_groth16_proof"), dict) else {}
openencoder_ready = _dig(emission, "openencoder_answer_field", "status", "openencoder_ready")
deterministic = _dig(emission, "determinism_boundary", "same_normalized_inputs_same_core_build_same_outputs")
rows.append(
[
idx,
Path(str(item.get("answer_path") or "")).name or "direct emission",
emission.get("object") or "unknown",
emission.get("query_count") or _dig(emission, "core_result", "process_query_count") or "unknown",
decoded.get("resolved_reference_count") or 0,
_critical_status(deterministic),
_critical_status(openencoder_ready),
_critical_status(corporate_proof.get("proof_ready")),
]
)
return _render_table(
"Decoded Answers Summary",
["#", "Answer", "Object", "Queries", "Refs", "Replay", "OE", "Proof"],
rows,
)
def _decode_text_report(payload: dict[str, Any]) -> str:
parts = []
if payload.get("critical_info_table"):
parts.append(str(payload["critical_info_table"]))
if isinstance(payload.get("decoded_answers"), list):
for item in payload["decoded_answers"]:
if isinstance(item, dict) and isinstance(item.get("decoded"), dict) and item["decoded"].get("critical_info_table"):
parts.append(str(item["decoded"]["critical_info_table"]))
return "\n\n".join(parts)
def _sha256_text(text: str) -> str:
return hashlib.sha256(text.encode()).hexdigest()
def _config_path(raw_path: str, *, base: Path) -> str:
path = Path(raw_path)
return str(path if path.is_absolute() else base / path)
def _default_frozen_config() -> str | None:
if not getattr(sys, "frozen", False):
return None
config_path = Path(sys.executable).resolve().parent / "config.json"
return str(config_path) if config_path.exists() else None
def _config_path_list(config: dict[str, Any], key: str, *, base: Path) -> list[str]:
values = config.get(key)
if values is None:
return []
if isinstance(values, str):
values = [values]
if not isinstance(values, list):
raise ValueError(f"{key} must be a path string or list of path strings")
return [_config_path(str(value), base=base) for value in values]
def _apply_config(args: argparse.Namespace, *, command: str) -> argparse.Namespace:
args.config_base = ""
if not args.config:
if args.ledger is None:
args.ledger = "client_field_ledger.jsonl"
return args
config_path = Path(args.config).resolve()
config = json.loads(config_path.read_text(encoding="utf-8"))
if config.get("schema_version") not in (None, CONFIG_SCHEMA_VERSION):
raise ValueError(f"unsupported config schema: {config.get('schema_version')}")
base = config_path.parent
args.config_base = str(base)
if not args.corpus_path:
args.corpus_path = _config_path_list(config, "corpus_paths", base=base)
if not args.query_path:
args.query_path = _config_path_list(config, "query_paths", base=base)
if not args.answers_path and config.get("answers_path"):
args.answers_path = _config_path(str(config["answers_path"]), base=base)
if not args.secret and config.get("client_secret"):
args.secret = str(config["client_secret"])
if args.secret_env == "CLIENT_SIGNAL_SECRET" and config.get("secret_env"):
args.secret_env = str(config["secret_env"])
if args.context == "default" and config.get("context"):
args.context = str(config["context"])
if not getattr(args, "session_salt", "") and config.get("session_salt"):
args.session_salt = str(config["session_salt"])
if not getattr(args, "unlinkable", False) and config.get("unlinkable") is True:
args.unlinkable = True
if args.width == 64 and config.get("width") is not None:
args.width = int(config["width"])
if args.limit == 10 and config.get("limit") is not None:
args.limit = int(config["limit"])
if args.ledger is None:
args.ledger = _config_path(str(config.get("ledger") or "client_field_ledger.jsonl"), base=base)
if not args.submission_manifest_output and config.get("submission_manifest_output"):
args.submission_manifest_output = _config_path(str(config["submission_manifest_output"]), base=base)
if not args.request_output and config.get("request_output"):
args.request_output = _config_path(str(config["request_output"]), base=base)
if not args.decode_output and config.get("decode_output"):
args.decode_output = _config_path(str(config["decode_output"]), base=base)
if not args.output:
args.output = args.decode_output if command == "decode" else args.request_output
return args
def _client_display_path(raw_path: str, args: argparse.Namespace) -> str:
base_text = str(getattr(args, "config_base", "") or "")
base = Path(base_text) if base_text else None
path = Path(raw_path)
if base is not None and path.is_absolute():
try:
return str(path.resolve().relative_to(base.resolve()))
except ValueError:
return str(path)
return str(path)
def _sendable_filename(raw_path: str) -> str:
if not raw_path or raw_path == "stdout":
return "stdout"
return Path(raw_path).name
def _public_source_refs(items: list[EncodedItem]) -> list[dict[str, Any]]:
return [
{
"role": item.source.role,
"source_ref": item.item_id,
"field_id": item.field_id,
"source_order": item.source.order,
}
for item in items
]
def encode_texts(texts: list[str], *, secret: bytes, width: int, role: str, context: str) -> list[int]:
if width <= 0:
raise ValueError("width must be positive")
accumulator = [0] * width
for doc_index, text in enumerate(texts):
for atom in _typed_atoms(text):
atom_hash = atom["value_sha256"]
count = int(atom["count"])
axis_digest = _mac(secret, REFERENCE_RECIPE_ID, context, role, doc_index, atom["kind"], atom_hash, "axis")
weight_digest = _mac(secret, REFERENCE_RECIPE_ID, context, role, doc_index, atom["kind"], atom_hash, "weight")
axis = int.from_bytes(axis_digest[:8], "big", signed=False) % width
magnitude = 1 + (int.from_bytes(weight_digest[:2], "big", signed=False) % 1024)
sign = 1 if weight_digest[2] & 1 else -1
accumulator[axis] = _saturating_add(accumulator[axis], sign * magnitude * max(1, count))
return accumulator
def _item_id(secret: bytes, *, source: SourceItem, context: str) -> str:
digest = hmac.new(
secret,
_canonical_json_bytes(
{
"context": context,
"role": source.role,
"source_label": source.source_label,
"source_path": source.source_path,
"text_sha256": _sha256_text(source.text),
}
),
hashlib.sha256,
).hexdigest()
return f"client-item:{digest[:40]}"
def _opaque_id(secret: bytes, *, context: str, role: str, texts: list[str], signal: list[int]) -> str:
payload = json.dumps(
{
"recipe_id": REFERENCE_RECIPE_ID,
"context": context,
"role": role,
"canonical_text_sha256s": [_sha256_text(_canonical_token_text(text)) for text in texts],
"typed_atom_sha256s": [_sha256_json(_typed_atoms(text)) for text in texts],
"signal": signal,
},
sort_keys=True,
separators=(",", ":"),
).encode()
return "sha256:" + hmac.new(secret, payload, hashlib.sha256).hexdigest()
def _field_receipt(
*,
source: SourceItem,
item_id: str,
field_id: str,
width: int,
context: str,
calc_hash: str,
signal: list[int],
) -> dict[str, Any]:
atoms = _typed_atoms(source.text)
return {
"schema_version": FIELD_RECEIPT_SCHEMA_VERSION,
"recipe_id": REFERENCE_RECIPE_ID,
"dtype": REFERENCE_DTYPE,
"shape": REFERENCE_SHAPE,
"role": source.role,
"item_id": item_id,
"field_id": field_id,
"text_sha256": _sha256_text(source.text),
"canonical_text_sha256": _sha256_text(_canonical_token_text(source.text)),
"typed_atom_sha256": _sha256_json(atoms),
"typed_atom_count": len(atoms),
"signal_sha256": _sha256_json(signal),
"width": int(width),
"context": context,
"calc_hash": calc_hash,
}
def encode_source_item(source: SourceItem, *, secret: bytes, width: int, context: str) -> EncodedItem:
wire_role = WIRE_ROLES.get(source.role, source.role)
signal = encode_texts([source.text], secret=secret, width=width, role=wire_role, context=context)
calc_hash = _calc_label(width=width, context=context)
field_id = _opaque_id(secret, context=context, role=wire_role, texts=[source.text], signal=signal)
receipt = _field_receipt(
source=source,
item_id=_item_id(secret, source=source, context=context),
field_id=field_id,
width=width,
context=context,
calc_hash=calc_hash,
signal=signal,
)
return EncodedItem(
source=source,
item_id=str(receipt["item_id"]),
field_id=field_id,
signal=signal,
text_sha256=str(receipt["text_sha256"]),
canonical_text_sha256=str(receipt["canonical_text_sha256"]),
signal_sha256=str(receipt["signal_sha256"]),
typed_atom_count=int(receipt["typed_atom_count"]),
typed_atom_sha256=str(receipt["typed_atom_sha256"]),
field_encoding=_field_encoding(width=width, context=context),
field_receipt=receipt,
field_receipt_sha256=_sha256_json(receipt),
)
def _calc_label(*, width: int, context: str) -> str:
digest = _sha256_json(_recipe_descriptor(width=width, context=context))
return f"{REFERENCE_RECIPE_ID}:{digest[:32]}"
def build_request(
*,
corpus_texts: list[str],
query_texts: list[str],
secret: bytes,
width: int,
limit: int,
context: str,
) -> dict[str, object]:
calc_hash = _calc_label(width=width, context=context)
corpus_signal = encode_texts(corpus_texts, secret=secret, width=width, role="a", context=context)
corpus_atoms = [atom for text in corpus_texts for atom in _typed_atoms(text)]
request: dict[str, object] = {
"schema_version": SCHEMA_VERSION,
"field_encoding": _field_encoding(width=width, context=context),
"corpus_field": {
"corpus_hash": _opaque_id(secret, context=context, role="a", texts=corpus_texts, signal=corpus_signal),
"calc_hash": calc_hash,
"field_tensor": corpus_signal,
"field_encoding": _field_encoding(width=width, context=context),
"typed_atom_count": len(corpus_atoms),
"typed_atom_sha256": _sha256_json(corpus_atoms),
"signal_sha256": _sha256_json(corpus_signal),
},
"limit": int(limit),
}
query_fields = []
for query_text in query_texts:
query_signal = encode_texts([query_text], secret=secret, width=width, role="b", context=context)
query_atoms = _typed_atoms(query_text)
query_fields.append(
{
"query_payload_hash": _opaque_id(secret, context=context, role="b", texts=[query_text], signal=query_signal),
"calc_hash": calc_hash,
"field_tensor": query_signal,
"field_encoding": _field_encoding(width=width, context=context),
"typed_atom_count": len(query_atoms),
"typed_atom_sha256": _sha256_json(query_atoms),
"signal_sha256": _sha256_json(query_signal),
}
)
if len(query_fields) == 1:
request["query_field"] = query_fields[0]
else:
request["query_fields"] = query_fields
return request