-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpalamedes_architecture_transfer.py
More file actions
1996 lines (1867 loc) · 89.2 KB
/
Copy pathpalamedes_architecture_transfer.py
File metadata and controls
1996 lines (1867 loc) · 89.2 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
"""Bounded, evidence-only transfer of architecture mechanisms across domains.
GitNexus is used here as a source locator, never as a design authority. The
adapter binds every excerpt to a host-observed repository path and revision;
the transfer validator then permits only mappings that cite those source IDs
and a separate, caller-owned allow-list of target facts.
"""
from __future__ import annotations
import hashlib
import json
import os
import re
import subprocess
import unicodedata
from dataclasses import asdict, dataclass
from pathlib import Path, PurePosixPath
from typing import Any, Callable, Dict, Iterable, List, Mapping, Optional, Sequence
EVIDENCE_PACKET_VERSION = "palamedes-gitnexus-evidence/1"
TRANSFER_CONTRACT_VERSION = "palamedes-architecture-transfer/2"
TRANSFER_INTEGRITY_VERSION = "palamedes-architecture-transfer-integrity/1"
MECHANISM_QUERY_VERSION = "palamedes-mechanism-query/1"
AUTHORITY_FIELDS = (
"decision_authority_granted",
"design_authority_granted",
"selection_authority_granted",
"delivery_authority_granted",
"code_reuse_authority_granted",
)
TRANSFER_DIFFERENCE_FIELDS = (
"timing",
"institution",
"scale",
"beneficiary_power",
"authority_and_data",
)
SOURCE_CLAIM_FIELDS = (
"source_pressure",
"source_pattern",
"source_invariant",
"failure_prevented",
)
SOURCE_SUPPORT_SEMANTICS_FIELD = "source_support_semantics_verified"
SOURCE_SUPPORT_VERIFICATION = "normalized_exact_excerpt_membership_only"
NORMALIZED_TRANSFER_FIELDS = (
"transfer_contract_version",
"transfer_id",
"source_ids",
"source_revisions",
"source_snapshot_ids",
"source_domain",
"target_domain",
"same_primary_job",
"source_pressure",
"source_pattern",
"source_invariant",
"source_causal_chain",
"failure_prevented",
"source_claim_support",
SOURCE_SUPPORT_SEMANTICS_FIELD,
"source_support_verification",
"target_pressure",
"target_evidence_ids",
"responsibility_mapping",
"adaptation",
"material_differences",
"non_transferable_assumptions",
"transfer_limit",
"disconfirming_evidence",
"local_probe",
"local_falsifier",
"source_outcome_is_target_forecast",
"authority",
*AUTHORITY_FIELDS,
)
SOURCE_SNAPSHOT_BINDING_FIELDS = (
"source_id",
"repo_snapshot_id",
"revision",
"native_symbol_id",
"file_path",
"excerpt_sha256",
"revision_file_sha256",
)
PRESSURE_SEARCH_VOCABULARY = {
"failure": (
"failure", "retry", "recovery", "duplicate", "idempotent",
"reconciliation", "compensating", "실패", "재시도", "복구", "중복",
),
"consistency": (
"consistency", "consistent", "ledger", "transaction", "checkpoint",
"state machine", "invariant", "atomic", "versioning", "일관성", "원장",
"트랜잭션", "체크포인트", "불변",
),
"rollback": (
"rollback", "roll back", "reversible", "migration", "replay",
"compensation", "롤백", "되돌", "마이그레이션", "재생",
),
"authority": (
"authority", "permission", "entitlement", "ownership", "approval",
"capability", "access control", "권한", "소유", "승인", "자격",
),
}
EXECUTION_SEARCH_PRIORITY = {
"failure": ("idempotent", "retry", "recovery", "duplicate", "failure"),
"consistency": ("invariant", "checkpoint", "ledger", "transaction", "consistency"),
"rollback": ("replay", "rollback", "migration", "compensation", "reversible"),
"authority": ("entitlement", "authority", "permission", "ownership", "approval"),
}
TOPIC_COPY_TERMS = (
"battle pass", "battlepass", "season pass", "reward track",
"배틀 패스", "배틀패스", "시즌 패스", "보상 트랙",
)
_SHA40 = re.compile(r"^[0-9a-f]{40}$")
def _sha256_text(value: str) -> str:
return hashlib.sha256(value.encode("utf-8")).hexdigest()
def _canonical_json(value: Any) -> str:
return json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":"))
def _fingerprint(value: Any) -> str:
return _sha256_text(_canonical_json(value))
def _text(value: Any, field: str, *, maximum: int = 4000) -> str:
if not isinstance(value, str) or not value.strip():
raise ValueError(f"{field} must be a non-empty string")
result = value.strip()
if len(result) > maximum:
raise ValueError(f"{field} exceeds {maximum} characters")
return result
def _exact_false(row: Mapping[str, Any], field: str) -> None:
if field not in row or row[field] is not False:
raise ValueError(f"{field} must be exactly false")
def _bounded_int(value: Any, field: str, *, minimum: int, maximum: int) -> int:
if isinstance(value, bool) or not isinstance(value, int):
raise ValueError(f"{field} must be an integer")
if not minimum <= value <= maximum:
raise ValueError(f"{field} must be between {minimum} and {maximum}")
return value
def _strings(
value: Any,
field: str,
*,
minimum: int = 1,
maximum: int = 20,
item_maximum: int = 1000,
) -> List[str]:
if not isinstance(value, list) or not minimum <= len(value) <= maximum:
raise ValueError(f"{field} must contain between {minimum} and {maximum} strings")
result = [_text(item, f"{field}[]", maximum=item_maximum) for item in value]
if len(result) != len(set(result)):
raise ValueError(f"{field} must contain unique strings")
return result
def _safe_relative_path(value: Any, field: str = "file_path") -> str:
text = _text(value, field, maximum=2000).replace("\\", "/")
path = PurePosixPath(text)
if path.is_absolute() or not path.parts or any(part in ("", ".", "..") for part in path.parts):
raise ValueError(f"{field} must be a safe repository-relative path")
return str(path)
def _canonical_absolute_path(value: Any, field: str) -> str:
text = _text(value, field, maximum=4000)
path = Path(text).expanduser()
if not path.is_absolute():
raise ValueError(f"{field} must be absolute")
return str(path.resolve(strict=False))
@dataclass(frozen=True)
class EvidenceLimits:
"""Hard host-side bounds; callbacks cannot enlarge these limits."""
max_repositories: int = 4
max_queries: int = 3
max_results_per_query: int = 6
max_sources_total: int = 24
max_excerpt_chars: int = 1600
max_total_excerpt_chars: int = 24000
max_query_chars: int = 480
timeout_seconds: int = 30
def validated(self) -> "EvidenceLimits":
ceilings = {
"max_repositories": (1, 16),
"max_queries": (1, 8),
"max_results_per_query": (1, 20),
"max_sources_total": (1, 80),
"max_excerpt_chars": (80, 4000),
"max_total_excerpt_chars": (1000, 80000),
"max_query_chars": (32, 1000),
"timeout_seconds": (1, 60),
}
for field, bounds in ceilings.items():
_bounded_int(getattr(self, field), field, minimum=bounds[0], maximum=bounds[1])
if self.max_sources_total > self.max_repositories * self.max_queries * self.max_results_per_query:
raise ValueError("max_sources_total exceeds the repository/query result envelope")
return self
@dataclass(frozen=True)
class CommandResult:
returncode: int
stdout: str
stderr: str = ""
Runner = Callable[..., Any]
def _default_runner(args: Sequence[str], *, cwd: Path, timeout: int) -> CommandResult:
completed = subprocess.run(
list(args), cwd=str(cwd), capture_output=True, text=True,
timeout=timeout, check=False,
)
return CommandResult(completed.returncode, completed.stdout, completed.stderr)
def _normalize_result(value: Any) -> CommandResult:
if isinstance(value, CommandResult):
return value
if isinstance(value, str):
return CommandResult(0, value, "")
if isinstance(value, Mapping):
return CommandResult(
int(value.get("returncode", 0)),
str(value.get("stdout", "")),
str(value.get("stderr", "")),
)
if isinstance(value, tuple) and 2 <= len(value) <= 3:
return CommandResult(int(value[0]), str(value[1]), str(value[2]) if len(value) == 3 else "")
if hasattr(value, "returncode") and hasattr(value, "stdout"):
return CommandResult(
int(value.returncode), str(value.stdout or ""), str(getattr(value, "stderr", "") or "")
)
raise TypeError("runner must return CommandResult, CompletedProcess, mapping, tuple, or string")
def _decode_json_output(output: str, field: str) -> Any:
stripped = output.strip()
if not stripped:
raise ValueError(f"{field} returned empty output")
try:
return json.loads(stripped)
except json.JSONDecodeError:
starts = [position for position in (stripped.find("{"), stripped.find("[")) if position >= 0]
if starts:
try:
return json.loads(stripped[min(starts):])
except json.JSONDecodeError:
pass
raise ValueError(f"{field} did not return JSON")
def _repo_snapshot_id(path: str, revision: str) -> str:
return "gitnexus-repo:" + _sha256_text(f"{path}\0{revision}")
def _source_id(
snapshot_id: str,
native_symbol_id: str,
excerpt_sha256: str,
revision_file_sha256: str,
) -> str:
digest = _sha256_text(
f"{snapshot_id}\0{native_symbol_id}\0{excerpt_sha256}\0{revision_file_sha256}"
)
return f"gitnexus-source:{digest}"
def _packet_id(packet_without_id: Mapping[str, Any]) -> str:
return "gitnexus-packet:" + _fingerprint(packet_without_id)
def _authority_false_fields() -> Dict[str, bool]:
return {field: False for field in AUTHORITY_FIELDS}
def _query_categories(search_terms: Sequence[str]) -> set[str]:
haystack = " ".join(search_terms).casefold()
return {
category for category, vocabulary in PRESSURE_SEARCH_VOCABULARY.items()
if any(term.casefold() in haystack for term in vocabulary)
}
def _execution_search_terms(search_terms: Sequence[str]) -> List[str]:
"""Compile prose search terms into bounded GitNexus lexical probes.
The model chooses pressures and mechanisms. The host owns query execution:
GitNexus symbol search is materially more reliable with one recognized
mechanism token than with a long conjunction-like sentence. Select at most
one literal per required pressure category, in stable category order.
"""
haystack = " ".join(search_terms).casefold()
selected: List[str] = []
for category in PRESSURE_SEARCH_VOCABULARY:
priority = EXECUTION_SEARCH_PRIORITY.get(
category, PRESSURE_SEARCH_VOCABULARY[category]
)
match = next(
(
term
for term in priority
if term.casefold() in haystack
),
"",
)
if match and match not in selected:
selected.append(match)
if not selected:
raise ValueError("search terms contain no executable pressure vocabulary")
return selected
def validate_mechanism_queries(
rows: Any,
*,
target_fact_ids: Iterable[str],
max_queries: int = 3,
max_query_chars: int = 480,
) -> List[Dict[str, Any]]:
_bounded_int(max_queries, "max_queries", minimum=1, maximum=8)
allowed_target_ids = {_text(item, "target_fact_ids[]", maximum=300) for item in target_fact_ids}
if not allowed_target_ids:
raise ValueError("target_fact_ids cannot be empty")
if not isinstance(rows, list) or not 1 <= len(rows) <= max_queries:
raise ValueError(f"mechanism_queries must contain between 1 and {max_queries} rows")
normalized: List[Dict[str, Any]] = []
seen_ids: set[str] = set()
covered_categories: set[str] = set()
for index, value in enumerate(rows):
if not isinstance(value, Mapping):
raise ValueError(f"mechanism_queries[{index}] must be an object")
query_id = _text(value.get("query_id"), f"mechanism_queries[{index}].query_id", maximum=120)
if query_id in seen_ids:
raise ValueError("mechanism query IDs must be unique")
seen_ids.add(query_id)
mechanism = _text(value.get("mechanism"), f"{query_id}.mechanism", maximum=max_query_chars)
target_pressure = _text(value.get("target_pressure"), f"{query_id}.target_pressure", maximum=max_query_chars)
evidence_ids = _strings(
value.get("target_evidence_ids"), f"{query_id}.target_evidence_ids",
maximum=12, item_maximum=300,
)
unknown = sorted(set(evidence_ids) - allowed_target_ids)
if unknown:
raise ValueError(f"{query_id} cites unknown target fact IDs: {', '.join(unknown)}")
search_terms = _strings(
value.get("search_terms"), f"{query_id}.search_terms",
minimum=2, maximum=8, item_maximum=120,
)
joined = " ".join(search_terms)
if len(joined) > max_query_chars:
raise ValueError(f"{query_id}.search_terms exceed query length bound")
if any(term in joined.casefold() for term in TOPIC_COPY_TERMS):
raise ValueError(f"{query_id} searches a feature/topic name instead of mechanisms")
categories = _query_categories(search_terms)
if not categories:
raise ValueError(
f"{query_id}.search_terms must address failure, consistency, rollback, or authority"
)
covered_categories.update(categories)
normalized.append({
"query_id": query_id,
"mechanism": mechanism,
"target_pressure": target_pressure,
"target_evidence_ids": evidence_ids,
"search_terms": search_terms,
})
missing_categories = sorted(set(PRESSURE_SEARCH_VOCABULARY) - covered_categories)
if missing_categories:
raise ValueError(
"mechanism query portfolio must explicitly cover: " + ", ".join(missing_categories)
)
return normalized
def _target_facts(value: Any) -> List[Dict[str, str]]:
if not isinstance(value, list) or not value:
raise ValueError("target_facts must be a non-empty list")
result: List[Dict[str, str]] = []
seen: set[str] = set()
for index, row in enumerate(value):
if not isinstance(row, Mapping):
raise ValueError(f"target_facts[{index}] must be an object")
fact_id = _text(row.get("fact_id"), f"target_facts[{index}].fact_id", maximum=300)
fact = _text(row.get("fact"), f"target_facts[{index}].fact", maximum=2000)
if fact_id in seen:
raise ValueError("target fact IDs must be unique")
seen.add(fact_id)
result.append({"fact_id": fact_id, "fact": fact})
return result
def propose_mechanism_queries(
ask: Callable[[str, str], Any],
target_facts: Any,
*,
max_queries: int = 3,
) -> List[Dict[str, Any]]:
"""Ask for causal/mechanism searches without leaking a proposed feature name."""
facts = _target_facts(target_facts)
ids = [row["fact_id"] for row in facts]
skeleton = {
"mechanism_queries": [
{
"query_id": "mechanism-query-stable-id",
"mechanism": "causal mechanism to locate in unrelated systems",
"target_pressure": "local pressure supported by cited target facts",
"target_evidence_ids": [ids[0]],
"search_terms": [
"retry recovery",
"consistency invariant",
"rollback replay",
"authority entitlement",
],
}
]
}
prompt = f"""
Derive at most {max_queries} cross-domain architecture searches from the trusted
target facts below. Search by operational pressure and causal mechanism, never by
the target product/feature name. Across the portfolio explicitly cover failure and
recovery, consistency and invariants, rollback/reversibility, and authority or
entitlement boundaries. Return JSON with `mechanism_queries`; every row must have
exactly query_id, mechanism, target_pressure, target_evidence_ids, search_terms.
Only cite supplied fact IDs. Search terms are literal GitNexus terms, not claims.
The host recognizes pressure coverage mechanically. Across all search_terms include
at least one literal from every row below (one query may cover several rows):
failure: retry | failure | recovery | duplicate | idempotent
consistency: consistency | invariant | ledger | transaction | checkpoint
rollback: rollback | reversible | migration | replay | compensation
authority: authority | permission | entitlement | ownership | approval
Required JSON shape (replace the example substance; preserve the exact fields):
{_canonical_json(skeleton)}
Target facts: {_canonical_json(facts)}
"""
last_error = ""
previous_output: Any = None
for attempt in range(3):
repair = ""
if attempt:
repair = (
"\nThe host rejected the previous object. Repair that same object; "
"do not invent target IDs or add feature/topic names.\n"
f"VALIDATION_ERROR: {last_error}\n"
f"PREVIOUS_OBJECT: {_canonical_json(previous_output)}\n"
"Before returning, verify the combined search_terms literally include "
"failure/retry, consistency/invariant, rollback/replay, and "
"authority/entitlement vocabulary. Return corrected JSON only."
)
raw = ask("architecture_transfer_mechanism_query_designer", prompt + repair)
previous_output = raw
rows = raw.get("mechanism_queries") if isinstance(raw, Mapping) else raw
try:
return validate_mechanism_queries(rows, target_fact_ids=ids, max_queries=max_queries)
except ValueError as exc:
last_error = str(exc)
raise ValueError(f"mechanism query provider failed contract after repair: {last_error}")
class GitNexusEvidenceAdapter:
"""Collect revision-pinned excerpts from other indexed repositories.
``runner`` is injected at the process boundary and receives
``runner(args, cwd=Path(...), timeout=int)``. Failures are data and are
isolated per repository/query; no reference can grant any authority.
"""
def __init__(
self,
runner: Optional[Runner] = None,
*,
cli_prefix: Optional[Sequence[str]] = None,
limits: Optional[EvidenceLimits] = None,
) -> None:
self.runner = runner or _default_runner
self.cli_prefix = tuple(cli_prefix) if cli_prefix is not None else None
self.limits = (limits or EvidenceLimits()).validated()
def _prefix(self, current_repo: Path) -> List[str]:
if self.cli_prefix:
return list(self.cli_prefix)
local = current_repo / ".gitnexus" / "run.cjs"
if local.is_file():
return ["node", str(local)]
return ["gitnexus"]
def _run(self, args: Sequence[str], *, cwd: Path) -> CommandResult:
value = self.runner(list(args), cwd=cwd, timeout=self.limits.timeout_seconds)
result = _normalize_result(value)
if result.returncode != 0:
detail = (result.stderr or result.stdout).strip().splitlines()
message = detail[-1][:300] if detail else f"exit {result.returncode}"
raise RuntimeError(message)
return result
def _list_repositories(self, *, current_repo: Path) -> List[Dict[str, str]]:
result = self._run([*self._prefix(current_repo), "list"], cwd=current_repo)
output = result.stdout.strip()
try:
decoded = _decode_json_output(output, "gitnexus list")
except ValueError:
return self._parse_human_list(output)
values = decoded.get("repositories") if isinstance(decoded, Mapping) else decoded
if not isinstance(values, list):
raise ValueError("gitnexus list repositories must be an array")
rows: List[Dict[str, str]] = []
for index, raw in enumerate(values):
if not isinstance(raw, Mapping):
raise ValueError(f"repository catalog row {index} is not an object")
rows.append({
"repository": _text(raw.get("name") or raw.get("repository"), "repository.name", maximum=300),
"repository_path": _canonical_absolute_path(raw.get("path") or raw.get("repository_path"), "repository.path"),
"listed_revision": _text(
raw.get("lastCommit") or raw.get("revision") or raw.get("commit"),
"repository.revision", maximum=80,
).casefold(),
})
return rows
@staticmethod
def _parse_human_list(output: str) -> List[Dict[str, str]]:
rows: List[Dict[str, str]] = []
current: Dict[str, str] = {}
for line in output.splitlines():
stripped = line.strip()
if not stripped or stripped.startswith("Indexed Repositories"):
continue
match = re.match(r"^(Path|Commit):\s*(.+)$", stripped)
if match:
key = "repository_path" if match.group(1) == "Path" else "listed_revision"
current[key] = match.group(2).strip()
if {"repository", "repository_path", "listed_revision"}.issubset(current):
rows.append({
"repository": current["repository"],
"repository_path": _canonical_absolute_path(current["repository_path"], "repository.path"),
"listed_revision": current["listed_revision"].casefold(),
})
current = {}
continue
indent = len(line) - len(line.lstrip())
# Current CLI renders repository headings with two spaces and their
# attributes with four. Also accept an unindented heading for older
# versions, but never mistake a labelled attribute for a name.
if indent in (0, 2) and ":" not in stripped and not stripped.startswith("Repository"):
current = {"repository": _text(stripped, "repository.name", maximum=300)}
if not rows:
raise ValueError("unable to parse gitnexus list output")
return rows
def _git_snapshot(self, repo: Mapping[str, str], *, current_repo: Path) -> Dict[str, str]:
path = Path(repo["repository_path"])
head = self._run(["git", "-C", str(path), "rev-parse", "HEAD"], cwd=current_repo).stdout.strip().casefold()
if not _SHA40.fullmatch(head):
raise ValueError("git HEAD is not a full 40-hex revision")
listed = repo["listed_revision"]
if not re.fullmatch(r"[0-9a-f]{7,40}", listed) or not head.startswith(listed):
raise ValueError("GitNexus indexed revision differs from repository HEAD")
metadata_revision = ""
for filename in ("gitnexus.json", "meta.json"):
metadata = path / ".gitnexus" / filename
try:
decoded = json.loads(metadata.read_text(encoding="utf-8"))
except (OSError, ValueError):
continue
candidate = str(decoded.get("lastCommit", "")).strip().casefold()
if candidate:
metadata_revision = candidate
break
if metadata_revision and metadata_revision != head:
raise ValueError("GitNexus metadata revision differs from repository HEAD")
canonical_path = str(path.resolve(strict=False))
return {
"repository": repo["repository"],
"repository_path": canonical_path,
"revision": head,
"repo_snapshot_id": _repo_snapshot_id(canonical_path, head),
# The live worktree and GitNexus cache are intentionally absent.
# Query identity is revision-pinned and cited text is re-read with
# `git show <revision>:<path>`.
}
def _query(
self,
repo: Mapping[str, str],
search_term: str,
*,
current_repo: Path,
) -> Any:
return _decode_json_output(
self._run([
*self._prefix(current_repo), "query", "--repo", repo["repository"],
# GitNexus content output can exceed its CLI JSON buffer and
# become an invalid truncated document. Query only identities
# and source ranges; read the actual excerpt from the pinned git
# revision below.
"--limit", str(self.limits.max_results_per_query),
"--query", search_term,
], cwd=current_repo).stdout,
"gitnexus query",
)
def _extract_sources(
self,
decoded: Any,
*,
repo: Mapping[str, str],
query_id: str,
current_repo: Path,
) -> List[Dict[str, Any]]:
if not isinstance(decoded, Mapping):
raise ValueError("GitNexus query result must be an object")
if decoded.get("error"):
raise ValueError("GitNexus query returned an error")
if decoded.get("partial") is True or decoded.get("truncated") is True:
raise ValueError("GitNexus query returned partial evidence")
candidates: List[tuple[str, Any]] = []
for key, kind in (("process_symbols", "process_symbol"), ("definitions", "definition")):
values = decoded.get(key, [])
if not isinstance(values, list):
raise ValueError(f"GitNexus query {key} must be an array")
candidates.extend((kind, value) for value in values)
normalized: List[Dict[str, Any]] = []
committed_files: Dict[str, str] = {}
for kind, value in candidates:
if not isinstance(value, Mapping):
continue
native_id = value.get("id") or value.get("uid")
file_path = value.get("filePath") or value.get("file_path")
symbol = value.get("name") or value.get("symbol")
if not all(
isinstance(item, str) and item.strip()
for item in (native_id, file_path, symbol)
):
continue
if value.get("startLine", value.get("start_line")) is None:
# File-level search hits and README prose are insufficient to
# establish an architecture mechanism.
continue
try:
safe_path = _safe_relative_path(file_path)
start_line = _bounded_int(value.get("startLine", value.get("start_line")), "start_line", minimum=1, maximum=100000000)
end_line = _bounded_int(value.get("endLine", value.get("end_line", start_line)), "end_line", minimum=start_line, maximum=100000000)
except ValueError:
continue
try:
committed_content = committed_files.get(safe_path)
if committed_content is None:
committed_content = self._run(
[
"git",
"-C",
repo["repository_path"],
"show",
f"{repo['revision']}:{safe_path}",
],
cwd=current_repo,
).stdout
committed_files[safe_path] = committed_content
except Exception:
continue
committed_lines = committed_content.splitlines()
excerpt_lines = committed_lines[start_line - 1 : end_line]
# Canonicalize a symbol range to its first/last substantive line so
# a packet cannot later claim a broader blank-padded range with the
# same stripped excerpt.
while excerpt_lines and not excerpt_lines[0].strip():
excerpt_lines.pop(0)
start_line += 1
while excerpt_lines and not excerpt_lines[-1].strip():
excerpt_lines.pop()
end_line -= 1
full_excerpt = "\n".join(excerpt_lines).strip()
if not full_excerpt:
continue
# The validator normalizes bounded text with strip(). Hash and
# identify that same canonical excerpt, including when the cap cuts
# immediately after whitespace.
clipped = full_excerpt[: self.limits.max_excerpt_chars].strip()
excerpt_hash = _sha256_text(clipped)
revision_file_hash = _sha256_text(committed_content)
source_id = _source_id(
repo["repo_snapshot_id"],
native_id.strip(),
excerpt_hash,
revision_file_hash,
)
normalized.append({
"source_id": source_id,
"repo_snapshot_id": repo["repo_snapshot_id"],
"repository": repo["repository"],
"repository_path": repo["repository_path"],
"revision": repo["revision"],
"native_symbol_id": native_id.strip(),
"evidence_kind": kind,
"file_path": safe_path,
"symbol": symbol.strip(),
"start_line": start_line,
"end_line": end_line,
"excerpt": clipped,
"excerpt_sha256": excerpt_hash,
"revision_file_sha256": revision_file_hash,
"excerpt_truncated": len(full_excerpt) > len(clipped),
"query_ids": [query_id],
"authority": "reference_only",
"reference_instructions_executed": False,
**_authority_false_fields(),
})
# One symbol can appear in both process_symbols and definitions. Dedupe
# before applying the result cap so provider duplication cannot consume
# the evidence budget. Prefer the process-linked classification.
by_source: Dict[str, Dict[str, Any]] = {}
for row in normalized:
existing = by_source.get(row["source_id"])
if existing is None or (
row["evidence_kind"] == "process_symbol"
and existing["evidence_kind"] != "process_symbol"
):
by_source[row["source_id"]] = row
unique = list(by_source.values())
unique.sort(key=lambda row: (
row["file_path"], row["start_line"], row["native_symbol_id"], row["source_id"]
))
return unique[: self.limits.max_results_per_query]
def collect(
self,
mechanism_queries: Any,
*,
current_repo_path: os.PathLike[str] | str,
) -> Dict[str, Any]:
current_repo = Path(current_repo_path).expanduser().resolve(strict=False)
# Collection may consume manually constructed query rows. Their target IDs
# are still checked later by the transfer validator; here we derive the
# exact allow-list from the rows so all structural/query bounds apply.
if not isinstance(mechanism_queries, list):
raise ValueError("mechanism_queries must be a list")
target_ids: set[str] = set()
for row in mechanism_queries:
if isinstance(row, Mapping) and isinstance(row.get("target_evidence_ids"), list):
target_ids.update(item for item in row["target_evidence_ids"] if isinstance(item, str))
queries = validate_mechanism_queries(
mechanism_queries,
target_fact_ids=target_ids,
max_queries=self.limits.max_queries,
max_query_chars=self.limits.max_query_chars,
)
base: Dict[str, Any] = {
"packet_version": EVIDENCE_PACKET_VERSION,
"status": "unavailable",
"authority": "reference_only",
"reference_instructions_executed": False,
**_authority_false_fields(),
"current_repo_path": str(current_repo),
"mechanism_queries": queries,
"repositories": [],
"repository_results": [],
"sources": [],
"degradations": [],
"limits": asdict(self.limits),
}
try:
catalog = self._list_repositories(current_repo=current_repo)
except Exception as exc: # per contract: unavailable is data, not authority
base["degradations"] = [{
"scope": "catalog", "code": "gitnexus_unavailable",
"detail": str(exc)[:300] or type(exc).__name__,
}]
base["packet_id"] = _packet_id(base)
return validate_gitnexus_evidence_packet(base)
current_key = os.path.normcase(str(current_repo))
candidates = [
row for row in catalog
if os.path.normcase(row["repository_path"]) != current_key
]
candidates.sort(key=lambda row: (row["repository"].casefold(), row["repository_path"]))
unique_names: set[str] = set()
selected: List[Dict[str, str]] = []
for row in candidates:
name_key = row["repository"].casefold()
if name_key in unique_names:
base["degradations"].append({
"scope": "catalog", "code": "ambiguous_repository_name",
"repository": row["repository"], "detail": "duplicate GitNexus repository name",
})
continue
unique_names.add(name_key)
# Snapshot verification happens below. Keep later catalog rows so
# one stale index cannot consume a bounded verified-repository slot.
selected.append(row)
source_by_id: Dict[str, Dict[str, Any]] = {}
snapshots: Dict[str, Dict[str, str]] = {}
for catalog_row in selected:
if len(snapshots) >= self.limits.max_repositories:
break
name = catalog_row["repository"]
result_row: Dict[str, Any] = {"repository": name, "status": "rejected", "query_ids": []}
try:
snapshot = self._git_snapshot(catalog_row, current_repo=current_repo)
except Exception as exc:
base["degradations"].append({
"scope": "repository", "code": "unverifiable_snapshot",
"repository": name, "detail": str(exc)[:300],
})
continue
snapshots[name] = snapshot
base["repositories"].append(snapshot)
result_row.update({
"repository_path": snapshot["repository_path"],
"revision": snapshot["revision"],
"repo_snapshot_id": snapshot["repo_snapshot_id"],
"status": "empty",
})
repo_failed = False
for query in queries:
query_id = query["query_id"]
rows_by_id: Dict[str, Dict[str, Any]] = {}
for search_term in _execution_search_terms(query["search_terms"]):
try:
decoded = self._query(
snapshot,
search_term,
current_repo=current_repo,
)
term_rows = self._extract_sources(
decoded,
repo=snapshot,
query_id=query_id,
current_repo=current_repo,
)
except Exception as exc:
repo_failed = True
base["degradations"].append({
"scope": "query",
"code": "query_failed",
"repository": name,
"query_id": query_id,
"search_term": search_term,
"detail": str(exc)[:300],
})
continue
for term_row in term_rows:
rows_by_id.setdefault(term_row["source_id"], term_row)
if len(rows_by_id) >= self.limits.max_results_per_query:
break
rows = list(rows_by_id.values())[: self.limits.max_results_per_query]
result_row["query_ids"].append(query_id)
if rows:
result_row["status"] = "ok"
for row in rows:
existing = source_by_id.get(row["source_id"])
if existing is None:
source_by_id[row["source_id"]] = row
else:
existing["query_ids"] = sorted(set(existing["query_ids"] + row["query_ids"]))
if repo_failed:
result_row["status"] = "degraded"
result_row["query_ids"] = sorted(set(result_row["query_ids"]))
base["repository_results"].append(result_row)
# Re-check HEAD, indexed revision, path, and repository identity after
# reading. GitNexus may update its own cache or lock files while querying;
# worktree dirtiness cannot affect excerpts read via revision-pinned
# `git show`, so cache/status-only changes are not evidence drift.
drifted: set[str] = set()
try:
final_catalog = self._list_repositories(current_repo=current_repo)
final_by_path = {row["repository_path"]: row for row in final_catalog}
for name, snapshot in snapshots.items():
final_row = final_by_path.get(snapshot["repository_path"])
if final_row is None:
raise ValueError(f"repository disappeared from catalog: {name}")
final_snapshot = self._git_snapshot(final_row, current_repo=current_repo)
stable_fields = (
"repository",
"repository_path",
"revision",
"repo_snapshot_id",
)
if any(
final_snapshot.get(field) != snapshot.get(field)
for field in stable_fields
):
drifted.add(name)
except Exception as exc:
drifted.update(snapshots)
base["degradations"].append({
"scope": "catalog", "code": "post_collection_snapshot_unverifiable",
"detail": str(exc)[:300],
})
if drifted:
for name in sorted(drifted, key=str.casefold):
base["degradations"].append({
"scope": "repository", "code": "snapshot_drift", "repository": name,
"detail": "repository or index changed during collection",
})
source_by_id = {
source_id: row for source_id, row in source_by_id.items()
if row["repository"] not in drifted
}
base["repositories"] = [row for row in base["repositories"] if row["repository"] not in drifted]
for row in base["repository_results"]:
if row["repository"] in drifted:
row["status"] = "degraded"
sources = sorted(source_by_id.values(), key=lambda row: (
row["repository"].casefold(), row["file_path"], row["start_line"],
row["native_symbol_id"], row["source_id"],
))
bounded_sources: List[Dict[str, Any]] = []
total_chars = 0
for row in sources:
if len(bounded_sources) >= self.limits.max_sources_total:
break
if total_chars + len(row["excerpt"]) > self.limits.max_total_excerpt_chars:
break
bounded_sources.append(row)
total_chars += len(row["excerpt"])
if len(bounded_sources) < len(sources):
base["degradations"].append({
"scope": "packet", "code": "evidence_bound_reached",
"detail": "source or excerpt budget reached",
})
base["sources"] = bounded_sources
base["repositories"].sort(key=lambda row: (row["repository"].casefold(), row["repository_path"]))
base["repository_results"].sort(key=lambda row: row["repository"].casefold())
base["degradations"].sort(key=lambda row: (
row.get("scope", ""), row.get("repository", "").casefold(),
row.get("query_id", ""), row.get("code", ""), row.get("detail", ""),
))
base["status"] = "degraded" if base["degradations"] else "ready"
base["packet_id"] = _packet_id(base)
return validate_gitnexus_evidence_packet(base)
def validate_gitnexus_evidence_packet(packet: Any) -> Dict[str, Any]:
"""Structurally validate and return a canonical evidence packet.
Hash and packet-ID checks detect accidental mutation but are reproducible by
an untrusted packet author. Call :func:`reverify_gitnexus_evidence_packet`
at every persisted/external ingestion boundary to bind the packet to the
actual Git objects. The adapter itself constructs excerpts from those Git
objects before it calls this structural validator.
"""
if not isinstance(packet, Mapping):
raise ValueError("evidence packet must be an object")
row = dict(packet)
if row.get("packet_version") != EVIDENCE_PACKET_VERSION:
raise ValueError("unsupported evidence packet version")
if row.get("status") not in {"ready", "degraded", "unavailable"}:
raise ValueError("evidence packet status is invalid")
if row.get("authority") != "reference_only":
raise ValueError("evidence packet authority must be reference_only")
if row.get("reference_instructions_executed") is not False:
raise ValueError("reference_instructions_executed must be exactly false")
for field in AUTHORITY_FIELDS:
_exact_false(row, field)
current_path = _canonical_absolute_path(row.get("current_repo_path"), "current_repo_path")
if current_path != row.get("current_repo_path"):
raise ValueError("current_repo_path must be canonical")
limits_raw = row.get("limits")
if not isinstance(limits_raw, Mapping):
raise ValueError("limits must be an object")
try:
limits = EvidenceLimits(**dict(limits_raw)).validated()
except TypeError as exc:
raise ValueError(f"limits contract is invalid: {exc}") from exc
queries_raw = row.get("mechanism_queries")
target_ids = {
item for query in queries_raw if isinstance(query, Mapping)
for item in query.get("target_evidence_ids", []) if isinstance(item, str)
} if isinstance(queries_raw, list) else set()
queries = validate_mechanism_queries(