Repository navigation
Expand file tree
/
Copy pathDoc_Chunker.py
More file actions
3196 lines (2751 loc) · 129 KB
/
Copy pathDoc_Chunker.py
File metadata and controls
3196 lines (2751 loc) · 129 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
"""
Doc_Chunker.py
Document Chunker & Manager — BEJSON 104db Document System + Project Chunker
Version: 2.4.0
Date: 2026-11-12
Author: Elton Boehnen
Contact: eltonboehnen@gmail.com | boehnenelton2024.pages.dev | github.com/boehnenelton
RELATIONAL_ID: d9799926-cc05-4a47-894d-a89909452469
Changelog:
v2.0.0 — Added Document Management System (MODE 2).
v2.1.0 — Renamed to Doc_Chunker. Added duplicate-doc, rename-doc, export-doc.
v2.2.0 — Tier 1: diff on chunk save, --doc-find, --doc-stats.
Tier 2: chunk tags + status fields in schema, --doc-chunk-tag,
--doc-chunk-set-status, --doc-compile-filtered, --doc-merge,
--doc-import-file, --doc-lock, --doc-unlock, --doc-snapshot,
--doc-restore-snapshot.
v2.2.1 — Updated lib imports to new lib_bejson_* naming scheme (Core/Utility families).
Fixed OSError ENAMETOOLONG crash in cmd_doc_chunk_write when chunk content
was passed as a long text string (Android PATH_MAX guard added).
v2.3.0 — Fixed aliasing bug in _shift_chunk_pos (chunk move up/down): reading
swap positions from `siblings` mid-loop returned already-mutated values
since `siblings` rows are the same objects as `values` rows, causing
both chunks to collapse onto the same index_pos instead of swapping.
Now snapshots both original positions before mutating either row.
Added cmd_doc_chunk_rename_label (relabel an existing chunk without
touching content/tags/status). Added cmd_doc_archive_delete (zips the
full doc dir to Document_Project_Archive/, then removes it from
Document_Project/, clearing any active-doc/mount-state reference).
"""
import os
import sys
import json
import argparse
import time
import uuid
import shutil
import difflib
import zipfile
import base64
import hashlib
import logging
import tempfile
import types
from dataclasses import dataclass, field
from pathlib import Path
from datetime import datetime, timezone
from typing import Any, Dict, List, Optional, Set, Union
VERSION = "2.4.0"
# ── Self-locate ────────────────────────────────────────────────────────────────
BASE_DIR = Path(__file__).resolve().parent
CONFIG_FILE = BASE_DIR / "config" / "config.json"
sys.path.append(str(BASE_DIR / "lib"))
# BEGIN EMBEDDED LIBRARY CODE
# Originally external dependencies loaded from ./lib at runtime. Embedded here
# so this file has zero dependency on the lib/ folder. Original library files
# are left untouched on disk (Library Immutability policy) — this is a merged
# standalone build, not a modification of the source libraries.
#
# Embedded sources:
# lib_bejson_Core_bejson_env.py v2.1.2
# lib_bejson_Core_bejson_errors.py v2.3.0
# lib_bejson_Core_bejson_core.py v2.0.3
# lib_bejson_Core_bejson_validator.py v2.0.2
# lib_bejson_Utility_bejson_utility.py v2.3.2
# ════════════════════════════════════════════════════════════════════════════
# ── lib_bejson_Core_bejson_env.py (v2.1.2) ─────────────────────────────────────
def _load_json_or_bejson(file_path: Path) -> dict:
if not file_path.exists():
return {}
try:
data = json.loads(file_path.read_text(encoding="utf-8"))
return data
except Exception:
return {}
def source_env(override_path: str = None) -> bool:
"""
Mandatory Environment Sourcing (Section 4.5 / Section 11).
Loads environment variable definitions from paths.json and secureenv_file.json
as specified in config/config.json without hardcoding paths.
"""
sourced = False
config_data = _load_json_or_bejson(CONFIG_FILE)
paths_env_file = None
secure_env_file = None
if config_data and "Values" in config_data:
fields = {f.get("name"): i for i, f in enumerate(config_data.get("Fields", []))}
name_idx = fields.get("setting_name", 0)
val_idx = fields.get("setting_value", 1)
for row in config_data.get("Values", []):
if len(row) > max(name_idx, val_idx):
if row[name_idx] == "paths_env_file":
paths_env_file = str(row[val_idx])
elif row[name_idx] == "secure_env_file":
secure_env_file = str(row[val_idx])
if override_path:
target_files = [Path(override_path)]
else:
target_files = [
Path(paths_env_file) if paths_env_file else Path("/storage/emulated/0/.env/user/paths.json"),
Path(secure_env_file) if secure_env_file else Path("/storage/emulated/0/.env/secure/secureenv_file.json")
]
for p in target_files:
if p and p.exists():
doc = _load_json_or_bejson(p)
if doc and "Values" in doc:
fields = {f.get("name"): i for i, f in enumerate(doc.get("Fields", []))}
name_idx = fields.get("var_name", 0)
val_idx = fields.get("var_value", 1)
for row in doc.get("Values", []):
if len(row) > max(name_idx, val_idx):
var_k = str(row[name_idx]).strip()
var_v = str(row[val_idx]).strip()
if var_k and var_k not in os.environ:
os.environ[var_k] = var_v
sourced = True
if "INTERNAL_STORAGE" not in os.environ:
os.environ["INTERNAL_STORAGE"] = "/storage/emulated/0"
if "SD_CARD" not in os.environ:
os.environ["SD_CARD"] = "/storage/9C33-6BBD" if os.path.exists("/storage/9C33-6BBD") else "/storage/sdcard1"
return sourced
def get_storage_roots():
source_env()
internal_path = os.environ.get("INTERNAL_STORAGE", "/storage/emulated/0")
if not os.path.exists(internal_path):
internal_path = "/storage/emulated/0"
sd_path = os.environ.get("SD_CARD", "/storage/9C33-6BBD")
if not os.path.exists(sd_path):
if os.path.exists("/storage/sdcard1"):
sd_path = "/storage/sdcard1"
else:
sd_path = "/storage/emulated/0"
return [
{"label": "Internal", "path": internal_path, "type": "internal", "enabled": True},
{"label": "SD", "path": sd_path, "type": "sd", "enabled": True}
]
def resolve_path(path_str: str) -> str:
"""
Resolves system placeholders and absolute paths to environment-relative paths.
Prioritizes environment variables (ADMIN_ROOT, BEJSON_LIB_ROOT, etc).
"""
if not path_str:
return path_str
# Define standard roots with defaults
home = os.environ.get("HOME", os.path.expanduser("~"))
# Storage and Admin Roots
# Fallback to HOME if storage root is unset to avoid hardcodes.
storage_root = os.environ.get("BEJSON_STORAGE_ROOT", home)
admin_root = os.environ.get("ADMIN_ROOT", os.path.join(storage_root, "Admin"))
# Library Root Resolution (Admin/libraries fallback to ~/libraries)
lib_root = os.environ.get("BEJSON_LIB_ROOT")
if not lib_root:
candidate_admin = os.path.join(admin_root, "libraries")
candidate_home = os.path.join(home, "libraries")
lib_root = candidate_admin if os.path.exists(candidate_admin) else candidate_home
mappings = {
"{BEJSON_LIB_ROOT}": lib_root,
"{ADMIN_ROOT}": admin_root,
"{INTERNAL_STORAGE}": storage_root,
"{HOME}": home
}
# Legacy absolute paths to be replaced
# Only replace if storage_root is explicitly set to avoid "Vanishing Data".
if os.environ.get("BEJSON_STORAGE_ROOT"):
mappings["/storage/emulated/0"] = storage_root
mappings["/data/data/com.termux/files/home"] = home
resolved = str(path_str)
# Sort keys by length descending to avoid partial matches (e.g. {HOME}_STUFF)
for placeholder in sorted(mappings.keys(), key=len, reverse=True):
actual = mappings[placeholder]
if actual:
resolved = resolved.replace(placeholder, actual)
# Handle home expansion
resolved = os.path.expanduser(resolved)
# Handle environment variables in path (e.g. $VAR)
resolved = os.path.expandvars(resolved)
return os.path.normpath(resolved)
def get_env_path(env_var: str, default: str) -> str:
"""Retrieves an environment variable and resolves it as a path."""
val = os.getenv(env_var, default)
return resolve_path(val)
# ── lib_bejson_Core_bejson_errors.py (v2.3.0) ──────────────────────────────────
# BEJSON Validation (1-16)
E_INVALID_JSON = 1
E_MISSING_MANDATORY_KEY = 2
E_INVALID_FORMAT = 3
E_INVALID_VERSION = 4
E_INVALID_RECORDS_TYPE = 5
E_INVALID_FIELDS = 6
E_INVALID_VALUES = 7
E_TYPE_MISMATCH = 8
E_RECORD_LENGTH_MISMATCH = 9
E_RESERVED_KEY_COLLISION = 10
E_INVALID_RECORD_TYPE_PARENT = 11
E_NULL_VIOLATION = 12
E_FILE_NOT_FOUND = 13
E_PERMISSION_DENIED = 14
E_ATOMIC_WRITE_FAILED = 15
E_INVALID_FORMAT_CREATOR = 16
# BEJSON Core ops (17-29)
E_CORE_PARSE_ERROR = 17
E_CORE_SERIALIZATION_ERROR = 18
E_CORE_NULL_DOCUMENT = 19
E_CORE_INVALID_VERSION = 20
E_CORE_INVALID_OPERATION = 21
E_CORE_INDEX_OUT_OF_BOUNDS = 22
E_CORE_FIELD_NOT_FOUND = 23
E_CORE_TYPE_CONVERSION_FAILED = 24
E_CORE_BACKUP_FAILED = 25
E_CORE_WRITE_FAILED = 26
E_CORE_QUERY_FAILED = 27
E_CORE_ENCRYPTION_FAILED = 28
E_CORE_DECRYPTION_FAILED = 29
# Aliases
E_CORE_UNSUPPORTED_OPERATION = E_CORE_INVALID_OPERATION
E_CORE_WRITE_TYPE_MISMATCH = E_TYPE_MISMATCH
E_CORE_WRITE_LENGTH_MISMATCH = E_RECORD_LENGTH_MISMATCH
# MFDB Validation (30-42)
E_MFDB_NOT_MANIFEST = 30
E_MFDB_NOT_ENTITY_FILE = 31
E_MFDB_MANIFEST_RECORDS_TYPE = 32
E_MFDB_ENTITY_NOT_FOUND = 33
E_MFDB_ENTITY_NAME_MISMATCH = 34
E_MFDB_DUPLICATE_ENTRY = 35
E_MFDB_NO_PARENT_HIERARCHY = 36
E_MFDB_MANIFEST_NOT_FOUND = 37
E_MFDB_BIDIRECTIONAL_FAIL = 38
E_MFDB_FK_UNRESOLVED = 39
E_MFDB_MISSING_REQUIRED_FIELD = 40
E_MFDB_NULL_REQUIRED = 41
E_MFDB_INVALID_ARCHIVE = 42
# MFDB Core ops (50-72)
E_MFDB_CORE_MANIFEST_NOT_FOUND = 50
E_MFDB_CORE_ENTITY_NOT_FOUND = 51
E_MFDB_CORE_WRITE_FAILED = 52
E_MFDB_CORE_LOCK_FAILED = 53
E_MFDB_CORE_INVALID_OPERATION = 54
E_MFDB_CORE_INDEX_OUT_OF_BOUNDS = 55
E_MFDB_CORE_JOIN_FAILED = 56
E_MFDB_CORE_DUPLICATE_ENTITY_NAME = 57
E_MFDB_CORE_RECORD_COUNT_SYNC_FAILED = 58
E_MFDB_CORE_NULL_MANIFEST = 59
E_MFDB_CORE_ENTITY_NOT_IN_MANIFEST = 60
E_MFDB_CORE_ARCHIVE_ERROR = 70
E_MFDB_CORE_MOUNT_CONFLICT = 71
E_MFDB_CORE_CREATE_FAILED = 72
# Core_Nesting (130-159)
E_NESTING_INVALID_CELL = 130
E_NESTING_NOT_BEJSON = 131
E_NESTING_DEPTH_EXCEEDED = 132
E_NESTING_CACHE_MISS = 133
E_NESTING_SCHEMA_MISMATCH = 134
E_NESTING_CIRCULAR_REF = 135
E_NESTING_VALIDATION_FAILED = 136
E_NESTING_FIELD_MAP_FAILED = 137
# Cognition (270-289)
E_COGNITION_INVALID_MATRIX = 270
E_COGNITION_AGENT_NOT_FOUND = 271
E_COGNITION_INDEX_MISSING = 272
E_COGNITION_PATCH_FAILED = 273
E_COGNITION_SCHEMA_VIOLATION = 274
E_COGNITION_LOCK_TIMEOUT = 275
# ── lib_bejson_Core_bejson_core.py (v2.0.3) ────────────────────────────────────
class BEJSONCoreError(Exception):
"""Raised when a BEJSON core operation fails."""
def __init__(self, message: str, code: int = None):
super().__init__(message)
self.code = code
class ResilientPIDLock:
def __init__(self, target_path: Union[str, Path], timeout_seconds: int = 10):
self.target = Path(target_path)
self.lock_dir = Path(f"{target_path}.lockdir")
self.meta_file = self.lock_dir / "lock_meta.json"
self.timeout = timeout_seconds
def acquire(self) -> bool:
start_time = time.time()
while time.time() - start_time < self.timeout:
try:
self.lock_dir.mkdir(exist_ok=False)
self.meta_file.write_text(json.dumps({
"pid": os.getpid(),
"timestamp": int(time.time())
}))
return True
except FileExistsError:
if self.meta_file.exists():
try:
meta = json.loads(self.meta_file.read_text())
owner_pid = meta.get("pid")
if owner_pid:
os.kill(owner_pid, 0) # Signal 0: check if alive
except (ProcessLookupError, OSError):
# Owner is dead — safely reclaim
self.release()
continue
except Exception:
pass
time.sleep(0.1)
return False
def release(self):
if self.meta_file.exists():
try:
self.meta_file.unlink()
except OSError:
pass
try:
self.lock_dir.rmdir()
except OSError:
pass
def __enter__(self):
if not self.acquire():
raise OSError(53, "Mutex lock timeout expired (E_MFDB_CORE_LOCK_FAILED)")
return self
def __exit__(self, *_):
self.release()
def bejson_core_load_file(path: str) -> Optional[dict]:
"""Loads a BEJSON file and returns the dictionary."""
path = resolve_path(path)
if not path:
return None
try:
with open(path, 'r', encoding='utf-8') as f:
return json.load(f)
except Exception as e:
logging.error(f"[BEJSON_CORE] Failed to load {path}: {e}")
return None
def bejson_core_atomic_write(path: str, data: dict) -> bool:
"""Writes a BEJSON file atomically using a temp file and sync."""
target_dir = os.path.dirname(os.path.abspath(path))
os.makedirs(target_dir, exist_ok=True)
# Strip internal metadata keys (starting with _) before write
clean_data = {k: v for k, v in data.items() if not k.startswith("_")}
fd, tmp_path = tempfile.mkstemp(dir=target_dir, suffix=".tmp")
try:
with os.fdopen(fd, 'w', encoding='utf-8') as f:
json.dump(clean_data, f, indent=2)
f.flush()
os.fsync(f.fileno())
os.replace(tmp_path, path)
return True
except Exception as e:
logging.error(f"[BEJSON_CORE] Atomic write failed for {path}: {e}")
if os.path.exists(tmp_path):
os.unlink(tmp_path)
return False
def bejson_core_acquire_lock(file_path: str, timeout: int = 10) -> bool:
"""Acquire a simple directory-based lock."""
lock_path = file_path + ".lock"
start_time = time.time()
while time.time() - start_time < timeout:
try:
os.mkdir(lock_path)
return True
except FileExistsError:
time.sleep(0.1)
return False
def bejson_core_release_lock(file_path: str) -> None:
"""Release the simple directory-based lock."""
lock_path = file_path + ".lock"
try:
os.rmdir(lock_path)
except OSError:
pass
# Global Field Map Cache
# Key: tuple of field names (sorted or as-is)
# Value: dict of {name: index}
_FIELD_MAP_CACHE: Dict[tuple, Dict[str, int]] = {}
def bejson_core_get_field_map(doc: dict) -> Dict[str, int]:
"""
Returns a mapping of field name to index.
Utilizes both in-document caching and a global cache for performance.
"""
# High-performance in-document cache check
if "_bejson_field_map" in doc:
return doc["_bejson_field_map"]
fields = doc.get("Fields", [])
if not fields:
return {}
# Create a unique key for this field structure for the global cache
field_names = tuple(f["name"] for f in fields)
cache_key = (doc.get("Format_Version"), field_names)
if cache_key in _FIELD_MAP_CACHE:
field_map = _FIELD_MAP_CACHE[cache_key]
else:
# Build and update global cache
field_map = {f["name"]: i for i, f in enumerate(fields)}
_FIELD_MAP_CACHE[cache_key] = field_map
# Inject into document for subsequent O(1) lookups
try:
doc["_bejson_field_map"] = field_map
except Exception:
pass # In case doc is immutable or not a dict
return field_map
def bejson_core_get_field_index(doc: dict, field_name: str) -> int:
"""Returns the positional index of a field name using the cache."""
field_map = bejson_core_get_field_map(doc)
return field_map.get(field_name, -1)
def bejson_core_create_104(record_type: str, fields: list, values: list) -> dict:
return {
"Format": "BEJSON",
"Format_Version": "104",
"Format_Creator": "Elton Boehnen",
"Records_Type": [record_type],
"Fields": fields,
"Values": values
}
def bejson_core_create_104a(record_type: str, fields: list, values: list, **custom) -> dict:
doc = {
"Format": "BEJSON",
"Format_Version": "104a",
"Format_Creator": "Elton Boehnen",
"Records_Type": [record_type],
"Fields": fields,
"Values": values
}
doc.update(custom)
return doc
def bejson_core_create_104db(record_types: list, fields: list, values: list) -> dict:
return {
"Format": "BEJSON",
"Format_Version": "104db",
"Format_Creator": "Elton Boehnen",
"Records_Type": record_types,
"Fields": fields,
"Values": values
}
# --- Missing Functions for MFDB and Parser Compatibility ---
def bejson_core_load_string(content: str) -> Optional[dict]:
try:
return json.loads(content)
except Exception as e:
logging.error(f"[BEJSON_CORE] Failed to load JSON string: {e}")
return None
def bejson_core_get_record_count(doc: dict) -> int:
return len(doc.get("Values", []))
def bejson_core_add_record(doc: dict, record: list) -> bool:
if len(record) != len(doc.get("Fields", [])):
return False
doc.setdefault("Values", []).append(record)
return True
def bejson_core_remove_record(doc: dict, index: int) -> bool:
values = doc.get("Values", [])
if 0 <= index < len(values):
values.pop(index)
return True
return False
def bejson_core_update_field(doc: dict, row_index: int, field_name: str, value: Any) -> bool:
idx = bejson_core_get_field_index(doc, field_name)
if idx == -1: return False
values = doc.get("Values", [])
if 0 <= row_index < len(values):
values[row_index][idx] = value
return True
return False
def bejson_core_filter_rows(doc: dict, field_name: str, value: Any) -> list:
idx = bejson_core_get_field_index(doc, field_name)
if idx == -1: return []
return [row for row in doc.get("Values", []) if row[idx] == value]
def bejson_core_sort_by_field(doc: dict, field_name: str, reverse: bool = False) -> None:
idx = bejson_core_get_field_index(doc, field_name)
if idx == -1: return
doc["Values"].sort(key=lambda x: x[idx] if x[idx] is not None else "", reverse=reverse)
def bejson_core_is_valid(doc: dict) -> bool:
# Simplified validity check
required = ["Format", "Format_Version", "Format_Creator", "Records_Type", "Fields", "Values"]
return all(k in doc for k in required)
def bejson_core_get_version(doc: dict) -> str:
return doc.get("Format_Version", "unknown")
def bejson_core_get_stats(doc: dict) -> dict:
return {
"record_count": bejson_core_get_record_count(doc),
"field_count": len(doc.get("Fields", [])),
"version": bejson_core_get_version(doc)
}
# ── lib_bejson_Core_bejson_validator.py (v2.0.2) ───────────────────────────────
VALID_VERSIONS = {"104", "104a", "104db"}
MANDATORY_KEYS = ("Format", "Format_Version", "Format_Creator", "Records_Type", "Fields", "Values")
@dataclass
class ValidationResult:
valid: bool = True
errors: List[str] = field(default_factory=list)
warnings: List[str] = field(default_factory=list)
current_file: str = ""
def add_error(self, message: str):
self.valid = False
self.errors.append(message)
def add_warning(self, message: str):
self.warnings.append(message)
class BEJSONValidationError(Exception):
def __init__(self, message: str, code: int):
super().__init__(message)
self.code = code
def bejson_validator_check_json_syntax(input_, res: ValidationResult, is_file=False):
if is_file:
path = Path(input_)
if not path.exists(): raise BEJSONValidationError(f"File not found: {input_}", E_FILE_NOT_FOUND)
text = path.read_text(encoding="utf-8")
res.current_file = str(path)
else: text = input_
if isinstance(text, dict): return text
try: return json.loads(text)
except Exception as e: raise BEJSONValidationError(f"Invalid JSON: {e}", E_INVALID_JSON)
def bejson_validator_check_mandatory_keys(doc):
for key in MANDATORY_KEYS:
if key not in doc: raise BEJSONValidationError(f"Missing key: {key}", E_MISSING_MANDATORY_KEY)
if doc["Format"] != "BEJSON": raise BEJSONValidationError("Invalid Format", E_INVALID_FORMAT)
if doc["Format_Creator"] != "Elton Boehnen":
raise BEJSONValidationError("Invalid Format_Creator: Must be 'Elton Boehnen'", E_INVALID_FORMAT)
version = doc.get("Format_Version", "")
if version not in VALID_VERSIONS: raise BEJSONValidationError(f"Invalid version: {version}", E_INVALID_VERSION)
return version
def bejson_validator_check_records_type(doc, version):
rt = doc["Records_Type"]
if not isinstance(rt, list):
raise BEJSONValidationError("Records_Type must be a list", E_INVALID_RECORDS_TYPE)
count = len(rt)
if version in ("104", "104a"):
if count != 1:
raise BEJSONValidationError(f"BEJSON {version} must have exactly 1 record type. Found {count}.", E_INVALID_RECORDS_TYPE)
elif version == "104db":
if count < 2:
raise BEJSONValidationError("104db requires 2+ types", E_INVALID_RECORDS_TYPE)
def bejson_validator_check_record_type_parent(doc, version):
if version != "104db": return True
fields = doc["Fields"]
if not fields or fields[0].get("name") != "Record_Type_Parent":
raise BEJSONValidationError("104db first field must be 'Record_Type_Parent'", E_INVALID_RECORD_TYPE_PARENT)
valid_types = set(doc["Records_Type"])
for i, record in enumerate(doc["Values"]):
if not record: continue
rtp = record[0]
if rtp not in valid_types:
raise BEJSONValidationError(f"Invalid Record_Type_Parent '{rtp}' at row {i}", E_INVALID_RECORD_TYPE_PARENT)
return True
def bejson_validator_check_fields_structure(doc, version):
fields = doc["Fields"]
for i, f in enumerate(fields):
fname = f.get("name")
ftype = f.get("type")
if not fname or not ftype:
raise BEJSONValidationError(f"Field {i} missing name or type", E_INVALID_FIELDS)
if version == "104a" and ftype in ("array", "object"):
raise BEJSONValidationError(f"104a forbids complex type: {ftype}", E_INVALID_FIELDS)
if version == "104db" and fname != "Record_Type_Parent" and "Record_Type_Parent" not in f:
raise BEJSONValidationError(f"Field '{fname}' missing Record_Type_Parent in 104db", E_INVALID_RECORD_TYPE_PARENT)
return len(fields)
def bejson_validator_check_values(doc, version, fields_count):
fields = doc["Fields"]
for i, record in enumerate(doc["Values"]):
if len(record) != fields_count:
raise BEJSONValidationError(f"Length mismatch at row {i}", E_RECORD_LENGTH_MISMATCH)
for j, val in enumerate(record):
ftype = fields[j].get("type")
if val is None: continue
# Full type validation including array/object
if ftype == "string" and not isinstance(val, str):
raise BEJSONValidationError(f"Type mismatch at row {i}, col {j} ({fields[j]['name']}): expected string", E_TYPE_MISMATCH)
elif ftype == "integer" and (not isinstance(val, int) or isinstance(val, bool)):
raise BEJSONValidationError(f"Type mismatch at row {i}, col {j} ({fields[j]['name']}): expected integer", E_TYPE_MISMATCH)
elif ftype == "number" and (not isinstance(val, (int, float)) or isinstance(val, bool)):
# bool is a subclass of int in Python, so True/False pass isinstance(int,float).
# Explicitly exclude bool — BEJSON "number" means a numeric value, not a boolean.
raise BEJSONValidationError(f"Type mismatch at row {i}, col {j} ({fields[j]['name']}): expected number, got bool", E_TYPE_MISMATCH)
elif ftype == "boolean" and not isinstance(val, bool):
raise BEJSONValidationError(f"Type mismatch at row {i}, col {j} ({fields[j]['name']}): expected boolean", E_TYPE_MISMATCH)
elif ftype == "array" and not isinstance(val, list):
raise BEJSONValidationError(f"Type mismatch at row {i}, col {j} ({fields[j]['name']}): expected array", E_TYPE_MISMATCH)
elif ftype == "object" and not isinstance(val, dict):
raise BEJSONValidationError(f"Type mismatch at row {i}, col {j} ({fields[j]['name']}): expected object", E_TYPE_MISMATCH)
def bejson_validator_check_custom_headers(doc, version):
mandatory_set = set(MANDATORY_KEYS)
for key in doc:
if key in mandatory_set or key == "Parent_Hierarchy": continue
if version in ("104", "104db"):
raise BEJSONValidationError(f"Custom key '{key}' forbidden in {version}", E_RESERVED_KEY_COLLISION)
# 104a: Custom headers allowed, no strict PascalCase enforcement
# Audit 2 Finding: Removed warning to avoid conflict with 104db rigidity.
def validate_bejson(input_data: Union[str, dict], is_file: bool = False) -> ValidationResult:
"""Thread-safe validation. Returns a ValidationResult object."""
res = ValidationResult()
try:
doc = bejson_validator_check_json_syntax(input_data, res, is_file=is_file)
version = bejson_validator_check_mandatory_keys(doc)
bejson_validator_check_custom_headers(doc, version)
bejson_validator_check_records_type(doc, version)
bejson_validator_check_record_type_parent(doc, version)
fields_count = bejson_validator_check_fields_structure(doc, version)
bejson_validator_check_values(doc, version, fields_count)
except BEJSONValidationError as e:
res.add_error(str(e))
except Exception as e:
res.add_error(f"Unexpected validation error: {e}")
return res
def bejson_validator_get_report(input_data, is_file: bool = False) -> str:
"""Return a human-readable validation report string."""
res = validate_bejson(input_data, is_file=is_file)
lines = ["BEJSON Validation Report"]
lines.append(" File: " + (res.current_file or "<string>"))
lines.append(" Valid: " + str(res.valid))
if res.errors:
lines.append(" Errors:")
for e in res.errors:
lines.append(" - " + e)
if res.warnings:
lines.append(" Warnings:")
for w in res.warnings:
lines.append(" - " + w)
return "\n".join(lines)
# Compatibility wrappers (now internal state is gone)
def bejson_validator_validate_string(json_string):
res = validate_bejson(json_string)
if not res.valid:
raise BEJSONValidationError(res.errors[0], E_INVALID_FORMAT)
return True
def bejson_validator_validate_file(file_path):
res = validate_bejson(file_path, is_file=True)
if not res.valid:
raise BEJSONValidationError(res.errors[0], E_INVALID_FORMAT)
return True
# ── lib_bejson_Utility_bejson_utility.py (v2.3.2) ──────────────────────────────
DEFAULT_EXTENSIONS = [".py", ".js", ".ts", ".html", ".css", ".md", ".json", ".sh", ".txt", ".bejson", ".tsx", ".jsx"]
# "chunked5" is CLI_Chunker's own Chunk-in-Target output directory (see
# CHUNK_TARGET_DIRNAME below). It is always excluded from chunking so a
# repeated chunk run never walks into its own previous output.
CHUNK_TARGET_DIRNAME = "chunked5"
# Contextualize Chunk: filename written into the target directory root before
# chunking. The "!" prefix (ASCII 0x21) sorts before digits/letters, and
# combined with the files.sort()/dirs.sort() determinism added to every walk
# below, this guarantees it is the first record in the resulting chunk.
CONTEXT_FILENAME = "!-CONTEXT.txt"
DEFAULT_EXCLUDES = [".git", "__pycache__", "node_modules", "lib", "output", ".mfdb_lock", "dist", "build", CHUNK_TARGET_DIRNAME]
# Text Chunk Separators (Standardized)
SEP_START = "--- FILE: "
SEP_END = " ---"
# Official CLI_CHUNKER Schema (BEJSON 104db)
SCHEMA_CLI_CHUNKER = [
{"name": "Record_Type_Parent", "type": "string"},
{"name": "project_name", "type": "string", "Record_Type_Parent": "ProjectMeta"},
{"name": "version", "type": "string", "Record_Type_Parent": "ProjectMeta"},
{"name": "root_path", "type": "string", "Record_Type_Parent": "ProjectMeta"},
{"name": "file_path", "type": "string", "Record_Type_Parent": "FileContent"},
{"name": "file_name", "type": "string", "Record_Type_Parent": "FileContent"},
{"name": "content", "type": "string", "Record_Type_Parent": "FileContent"},
{"name": "is_binary", "type": "boolean", "Record_Type_Parent": "FileContent"}
]
# Official MFDB_V5 Entity Schema (BEJSON 104)
SCHEMA_MFDB_ENTITY = [
{"name": "version", "type": "string"},
{"name": "file_path", "type": "string"},
{"name": "file_name", "type": "string"},
{"name": "content", "type": "string"},
{"name": "is_binary", "type": "boolean"},
{"name": "is_base64", "type": "boolean"},
]
def bejson_utility_sanitize_name(name: str) -> str:
"""Sanitizes names for filesystem safety without using regex."""
invalid = '<>:"/\\|?*'
sanitized = name
for char in invalid:
sanitized = sanitized.replace(char, '_')
return sanitized
def bejson_utility_slugify(text: str) -> str:
"""Creates a simple lowercase alphanumeric slug without regex."""
slug = ""
for char in text.lower():
if char.isalnum():
slug += char
elif char in " -_":
slug += "_"
return slug
def bejson_utility_is_binary(file_path: Union[str, Path]) -> bool:
"""Detection logic matching official chunker tools."""
try:
with open(file_path, 'tr', encoding='utf-8') as f:
f.read(1024)
return False
except (UnicodeDecodeError, PermissionError):
return True
def bejson_utility_encode_file(file_path: Union[str, Path], use_base64: bool = False) -> tuple:
"""
Reads file content and returns (content, is_binary, is_base64).
Matches MFDB v5 lossless binary logic.
"""
is_bin = bejson_utility_is_binary(file_path)
if not is_bin:
try:
return Path(file_path).read_text(encoding="utf-8"), False, False
except Exception:
return "", True, False
if use_base64:
try:
raw = Path(file_path).read_bytes()
return base64.b64encode(raw).decode('utf-8'), True, True
except Exception:
return "", True, True
return "", True, False
def bejson_utility_create_cli_chunk(target_dir: str, project_name: str, version: str) -> dict:
"""Generates a BEJSON 104db document compatible with Cli_Chunker."""
target_path = Path(target_dir).resolve()
values = []
# Dynamic Field Mapping for Creation (Phase 7.3.4)
fm = {f["name"]: i for i, f in enumerate(SCHEMA_CLI_CHUNKER)}
f_count = len(SCHEMA_CLI_CHUNKER)
# Meta record
meta_row = [None] * f_count
meta_row[fm["Record_Type_Parent"]] = "ProjectMeta"
meta_row[fm["project_name"]] = project_name
meta_row[fm["version"]] = version
meta_row[fm["root_path"]] = str(target_path)
values.append(meta_row)
for root, dirs, files in os.walk(target_path):
dirs.sort()
dirs[:] = [d for d in dirs if d not in DEFAULT_EXCLUDES]
files.sort()
for file in files:
f_path = Path(root) / file
if f_path.suffix.lower() in DEFAULT_EXTENSIONS:
try:
rel_path = f_path.relative_to(target_path)
content, binary, _ = bejson_utility_encode_file(f_path, use_base64=False)
file_row = [None] * f_count
file_row[fm["Record_Type_Parent"]] = "FileContent"
file_row[fm["file_path"]] = str(rel_path)
file_row[fm["file_name"]] = file
file_row[fm["content"]] = content
file_row[fm["is_binary"]] = binary
values.append(file_row)
except Exception: continue
return bejson_core_create_104db(["ProjectMeta", "FileContent"], SCHEMA_CLI_CHUNKER, values)
def bejson_utility_create_mfdb_version(target_dir: str, version: str, use_base64: bool = True) -> list:
"""
Generates a list of values for an MFDB v5 Entity file (BEJSON 104).
"""
target_path = Path(target_dir).resolve()
rows = []
fm = {f["name"]: i for i, f in enumerate(SCHEMA_MFDB_ENTITY)}
f_count = len(SCHEMA_MFDB_ENTITY)
for root, dirs, files in os.walk(target_path):
dirs.sort()
dirs[:] = [d for d in dirs if d not in DEFAULT_EXCLUDES]
files.sort()
for file in files:
f_path = Path(root) / file
if f_path.suffix.lower() in DEFAULT_EXTENSIONS:
try:
rel_path = f_path.relative_to(target_path)
content, binary, b64 = bejson_utility_encode_file(f_path, use_base64=use_base64)
row = [None] * f_count
row[fm["version"]] = version
row[fm["file_path"]] = str(rel_path)
row[fm["file_name"]] = file
row[fm["content"]] = content
row[fm["is_binary"]] = binary
row[fm["is_base64"]] = b64
rows.append(row)
except Exception: continue
return rows
def bejson_utility_chunk_to_text(target_dir: str) -> str:
"""Concatenates files into a single text block with separators."""
target_path = Path(target_dir).resolve()
output = []
for root, dirs, files in os.walk(target_path):
dirs.sort()
dirs[:] = [d for d in dirs if d not in DEFAULT_EXCLUDES]
files.sort()
for file in files:
f_path = Path(root) / file
if f_path.suffix.lower() in DEFAULT_EXTENSIONS and not bejson_utility_is_binary(f_path):
try:
rel_path = f_path.relative_to(target_path)
content = f_path.read_text(encoding="utf-8")
output.append(f"{SEP_START}{rel_path}{SEP_END}")
output.append(content)
output.append("\n")
except Exception: continue
return "\n".join(output)
def bejson_utility_unchunk_from_text(text: str, output_dir: str) -> int:
"""Restores files from a text block using strictly string splitting."""
count = 0
out_root = Path(output_dir).resolve()
# Split by the start separator
parts = text.split(SEP_START)
for part in parts:
if not part.strip(): continue
# Each part starts with: filename --- content
if SEP_END in part:
header, content = part.split(SEP_END, 1)
rel_path = header.strip()
if rel_path:
target_file = out_root / rel_path
target_file.parent.mkdir(parents=True, exist_ok=True)
target_file.write_text(content.lstrip("\n"), encoding="utf-8")
count += 1
return count
def bejson_utility_parse_json(text: str) -> Any:
"""Robust JSON parsing using strictly the json module."""
try:
return json.loads(text)
except json.JSONDecodeError:
# Best practice: try to find the actual JSON object in a dirty string
start = text.find("{")
end = text.rfind("}")
if start != -1 and end != -1 and end > start:
return json.loads(text[start:end+1])
raise
def bejson_utility_save_chunk(path: str, doc: dict) -> bool:
"""Standardized atomic write for all chunking operations."""
return bejson_core_atomic_write(path, doc)
def bejson_utility_get_timestamp() -> str:
"""ISO 8601 UTC timestamp for manifest consistency."""
return time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
# ── Chunked-104 schema (optional 104a chunk mode, added 2026-07-10) ────────────
# Matches Chunked-104a_Template.bejson.json — a flat, one-record-per-file BEJSON
# 104a schema, offered as an opt-in alternative to the default 104db schema above.
CHUNKED_104_FIELDS = [
{"name": "File_Name", "type": "string"},
{"name": "File_Extension", "type": "string"},
{"name": "File_Content", "type": "string"},
{"name": "File_Version", "type": "string"},
{"name": "File_Hash", "type": "string"},
{"name": "Relative_Path", "type": "string"},
{"name": "Is_Binary", "type": "boolean"},
{"name": "Is_Mounted", "type": "boolean"},
]
def bejson_utility_hash_file_bytes(raw_bytes: bytes) -> str:
"""SHA-1 hash (hex digest) used for the Chunked-104 schema's File_Hash field."""
return hashlib.sha1(raw_bytes).hexdigest()
def bejson_utility_create_chunked_104(target_dir: str, version: str = "latest",
extensions: Optional[List[str]] = None,
exclude_dirs: Optional[List[str]] = None) -> dict:
"""
Generates a BEJSON 104a document matching the Chunked-104 schema template:
one flat record per file (File_Name/File_Extension/File_Content/File_Version/
File_Hash/Relative_Path/Is_Binary/Is_Mounted).
extensions/exclude_dirs let the caller override DEFAULT_EXTENSIONS /
DEFAULT_EXCLUDES with custom patterns for this run only; pass None to use
the existing defaults.
"""
target_path = Path(target_dir).resolve()
exts = extensions if extensions is not None else DEFAULT_EXTENSIONS
excl = exclude_dirs if exclude_dirs is not None else DEFAULT_EXCLUDES
values = []
for root, dirs, files in os.walk(target_path):
dirs.sort()
dirs[:] = [d for d in dirs if d not in excl]
files.sort()
for file in files:
f_path = Path(root) / file
if f_path.suffix.lower() in exts:
try:
rel_path = f_path.relative_to(target_path)
is_bin = bejson_utility_is_binary(f_path)
if is_bin:
raw_bytes = f_path.read_bytes()
content = ""
else:
raw_bytes = f_path.read_bytes()
content = f_path.read_text(encoding="utf-8")
file_hash = bejson_utility_hash_file_bytes(raw_bytes)
values.append([
f_path.name, # File_Name
f_path.suffix, # File_Extension
content, # File_Content
version, # File_Version
file_hash, # File_Hash
str(rel_path), # Relative_Path
is_bin, # Is_Binary
False, # Is_Mounted (per-file; not a live mount)