forked from Steake/GodelOS
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrepo_architect.py
More file actions
4640 lines (4146 loc) · 197 KB
/
repo_architect.py
File metadata and controls
4640 lines (4146 loc) · 197 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
from __future__ import annotations
import argparse
import ast
import dataclasses
import datetime as dt
import hashlib
import json
import os
import pathlib
import re
import subprocess
import sys
import textwrap
import time
import traceback
import urllib.error
import urllib.parse
import urllib.request
from typing import Any, Dict, Iterable, List, Optional, Sequence, Set, Tuple
APP_NAME = "repo-architect"
VERSION = "2.1.0"
AGENT_DIRNAME = ".agent"
STATE_FILE = "repo_architect_state.json"
ANALYSIS_FILE = "latest_analysis.json"
GRAPH_FILE = "code_graph.json"
ROADMAP_FILE = "roadmap.json"
ARTIFACT_MANIFEST_FILE = "artifacts_manifest.json"
WORKFLOW_PATH = pathlib.Path(".github/workflows/repo-architect.yml")
DEFAULT_REPORT_DIR = pathlib.Path("docs/repo_architect")
DEFAULT_REPORT_PATH = DEFAULT_REPORT_DIR / "runtime_inventory.md"
DEFAULT_IGNORE_DIRS = {
".git", AGENT_DIRNAME, ".hg", ".svn", ".venv", "venv", "node_modules",
"dist", "build", "__pycache__", ".mypy_cache", ".pytest_cache", ".ruff_cache",
".idea", ".vscode", ".next", ".turbo"
}
DEBUG_MARKER_RE = re.compile(r"#\s*(DEBUG|DBG|debug)\b")
PRINT_RE = re.compile(r"\bprint\s*\(")
ENTRYPOINT_HINTS = (
'if __name__ == "__main__"',
"if __name__ == '__main__'",
'uvicorn.run(',
'app.run(',
'FastAPI(',
'typer.run(',
'click.command(',
)
GITHUB_API = "https://api.github.com"
GITHUB_MODELS_CATALOG = "https://models.github.ai/catalog/models"
GITHUB_MODELS_CHAT = "https://models.github.ai/inference/chat/completions"
GITHUB_API_VERSION = "2026-03-10"
REPORT_SUITE = {
"runtime_inventory": DEFAULT_REPORT_DIR / "runtime_inventory.md",
"circular_dependencies": DEFAULT_REPORT_DIR / "circular_dependencies.md",
"parse_errors": DEFAULT_REPORT_DIR / "parse_errors.md",
"entrypoint_clusters": DEFAULT_REPORT_DIR / "entrypoint_clusters.md",
"top_risks": DEFAULT_REPORT_DIR / "top_risks.md",
}
# Model selection defaults
DEFAULT_PREFERRED_MODEL = "openai/gpt-5"
DEFAULT_FALLBACK_MODEL = "openai/o3"
# Preferred resolution order for automatic model selection
PREFERRED_MODEL_ORDER: Tuple[str, ...] = ("openai/gpt-5", "openai/o3")
# Substrings in HTTP error bodies that indicate the model itself is unavailable (not a transient error)
_MODEL_UNAVAILABLE_SIGNALS = frozenset({
"unknown_model", "model_not_found", "unsupported_model", "unsupported model",
"not found", "does not exist", "invalid model", "no such model",
})
# Canonical lane execution order for mutate / campaign modes
MUTATION_LANE_ORDER: Tuple[str, ...] = ("parse_errors", "import_cycles", "entrypoint_consolidation", "hygiene", "report")
# Issue-first mode (default safe operating mode per charter governance policy)
ISSUE_MODE = "issue"
# Modes that perform direct code mutation – retained as charter-validated secondary modes
# (per GODELOS_REPO_IMPLEMENTATION_CHARTER §9–§10 self-modification lanes) but not the
# default execution path. Issue-first mode is the default safe path; mutation modes
# require explicit opt-in via --mode mutate or --mode campaign.
CHARTER_MUTATION_MODES: Tuple[str, ...] = ("mutate", "campaign")
# Directory for dry-run issue artifacts
ISSUE_REPORT_DIR = DEFAULT_REPORT_DIR / "issues"
# Standard labels for the issue-first governance system
ARCH_GAP_LABELS: Tuple[str, ...] = (
"arch-gap", "copilot-task", "needs-implementation",
"ready-for-validation",
"ready-for-delegation", "delegation-requested", "in-progress",
"pr-open", "pr-draft", "merged", "closed-unmerged", "stale",
"blocked-by-dependency", "superseded-by-issue", "superseded-by-pr",
"failed-delegation",
)
SUBSYSTEM_LABELS: Tuple[str, ...] = (
"workflow", "runtime", "reporting", "docs",
"model-routing", "issue-orchestration",
"core", "knowledge", "agents", "consciousness",
)
# Priority levels for detected architectural gaps
ISSUE_PRIORITY_LEVELS: Tuple[str, ...] = ("critical", "high", "medium", "low")
# Charter-defined mutation lanes (§10 GODELOS_REPO_IMPLEMENTATION_CHARTER)
# Maps lane number to (name, subsystem, description)
CHARTER_LANE_MAP: Dict[int, Tuple[str, str, str]] = {
0: ("report", "reporting", "Report generation — architecture packets, inventories, risk docs"),
1: ("hygiene", "runtime", "Hygiene — remove debug prints, dead code, internal clutter"),
2: ("parse_errors", "runtime", "Parse repair — fix syntax errors, restore parsability"),
3: ("import_cycles", "runtime", "Circular dependency elimination — break import cycles structurally"),
4: ("entrypoint_consolidation", "runtime", "Entrypoint consolidation — reduce runtime duplication"),
5: ("contract_repair", "core", "Contract repair — normalise interfaces, repair adapter mismatches"),
6: ("runtime_extraction", "runtime", "Runtime extraction — move orchestration logic into runtime modules"),
7: ("agent_boundary", "agents", "Agent boundary enforcement — isolate agent state, use messages/interfaces"),
8: ("knowledge_normalisation", "knowledge", "Knowledge substrate normalisation — centralise persistent knowledge access"),
9: ("consciousness_instrumentation", "consciousness", "Consciousness instrumentation — metrics, traces, introspection paths"),
}
# Charter §14 Current Priority Order (GODELOS_REPO_IMPLEMENTATION_CHARTER)
CHARTER_PRIORITY_ORDER: Tuple[str, ...] = (
"restore or preserve parse correctness",
"eliminate import cycles",
"reduce runtime entrypoint ambiguity",
"normalise knowledge substrate boundaries",
"isolate agent boundaries",
"add explicit machine-consciousness instrumentation seams",
"build toward durable Gödlø-P persistence semantics",
"progressively enable validated self-modification loops",
)
# Machine-readable companion files (§15 GODELOS_REPO_IMPLEMENTATION_CHARTER)
CHARTER_COMPANION_FILES: Tuple[str, ...] = (
"docs/repo_architect/policy.json",
"docs/repo_architect/mutation_lanes.json",
"docs/repo_architect/dependency_contract.json",
)
# Canonical architectural charter files (relative to git root)
CHARTER_PATHS: Tuple[str, ...] = (
"docs/architecture/GODELOS_ARCHITECTURAL_CHARTER.md",
"docs/architecture/GODELOS_REPO_IMPLEMENTATION_CHARTER.md",
)
# §16 Minimal Agent Instruction Contract (GODELOS_REPO_IMPLEMENTATION_CHARTER)
AGENT_INSTRUCTION_CONTRACT: Tuple[str, ...] = (
"Work only in one mutation lane at a time.",
"Preserve canonical runtime convergence toward backend/unified_server.py.",
"Break import cycles structurally, not cosmetically.",
"Do not widen coupling between runtime, core, knowledge, agents, and interface layers.",
"Do not bypass knowledge-store interfaces for persistent memory operations.",
"Do not make claims about consciousness without adding measurable instrumentation or evidence paths.",
"Prefer thin, verifiable PRs over broad rewrites.",
"Every PR must explain objective, architectural effect, validation, and next follow-up lane.",
)
# Maximum characters from each charter file injected into model context
_MAX_CHARTER_CHARS_PER_FILE = 3000
# Maximum characters of source code sent to the model per file snippet
_MAX_SOURCE_SNIPPET_CHARS = 4000
_MAX_CYCLE_SNIPPET_CHARS = 3000
# Maximum total branch-name length (git max ref is 255; leave margin for remote path prefix)
_MAX_BRANCH_NAME_LEN = 220
# Minimum backend server entrypoints before entrypoint_consolidation lane activates
_ENTRYPOINT_CONSOLIDATION_THRESHOLD = 4
# When building entrypoint snippets: consider this many candidates, send at most this many to model
_ENTRYPOINT_CONSOLIDATION_CANDIDATES = 8
_ENTRYPOINT_CONSOLIDATION_SNIPPETS = 5
# Maximum number of file/evidence items shown inline in Copilot prompt or issue body sections
_MAX_INLINE_FILE_DISPLAY = 5
# Maximum number of violations shown in issue body for Lane 5/7 gaps
_MAX_VIOLATIONS_DISPLAY = 5
# ---------------------------------------------------------------------------
# Closed-loop execution / memory lane constants
# ---------------------------------------------------------------------------
# Durable work-state file stored in .agent/ (gitignored alongside other artifacts)
WORK_STATE_FILE = "work_state.json"
# New operating modes for the execution and reconciliation lanes
EXECUTION_MODE = "execution"
RECONCILE_MODE = "reconcile"
# Factual lifecycle labels — represent observed facts, not planning interpretations.
LIFECYCLE_LABELS: Tuple[str, ...] = (
"ready-for-delegation",
"delegation-requested",
"in-progress",
"pr-open",
"pr-draft",
"merged",
"closed-unmerged",
"stale",
"blocked-by-dependency",
"superseded-by-issue",
"superseded-by-pr",
"failed-delegation",
)
# Backward-compatible legacy lifecycle labels still recognised for filtering.
LEGACY_LIFECYCLE_LABELS: Tuple[str, ...] = ("blocked", "superseded")
# Ranking used when reconciling multiple candidate PR matches.
MATCH_CONFIDENCE_RANK: Dict[str, int] = {"exact": 3, "strong": 2, "weak": 1}
# Priority order for PR linkage evidence.
PR_MATCH_METHOD_PRIORITY: Tuple[str, ...] = (
"fingerprint_marker",
"linkage_block",
"branch_convention",
"closing_reference",
"issue_reference",
)
# Labels required for an issue to be eligible for execution selection
EXECUTION_ELIGIBLE_LABELS: Tuple[str, ...] = ("arch-gap", "copilot-task", "needs-implementation")
# GitHub Copilot coding agent assignee username
COPILOT_AGENT_ASSIGNEE = "copilot"
# Canonical architectural objectives aligned with charter §14 priority order
OBJECTIVE_LABELS: Dict[str, str] = {
"restore-parse-correctness": "Restore or preserve parse correctness (Lane 2)",
"eliminate-import-cycles": "Eliminate import cycles (Lane 3)",
"converge-runtime-structure": "Converge runtime entrypoint structure (Lane 4)",
"normalise-knowledge-substrate": "Normalise knowledge substrate boundaries (Lane 8)",
"isolate-agent-boundaries": "Isolate agent boundaries (Lane 7)",
"reduce-architecture-score-risk": "Reduce architecture score risk (Lanes 0–9)",
"add-consciousness-instrumentation": "Add consciousness instrumentation (Lane 9)",
}
class RepoArchitectError(Exception):
pass
@dataclasses.dataclass
class Config:
git_root: pathlib.Path
agent_dir: pathlib.Path
state_path: pathlib.Path
analysis_path: pathlib.Path
graph_path: pathlib.Path
roadmap_path: pathlib.Path
artifact_manifest_path: pathlib.Path
workflow_path: pathlib.Path
step_summary_path: Optional[pathlib.Path]
github_token: Optional[str]
github_repo: Optional[str]
github_base_branch: Optional[str]
github_admin_token: Optional[str]
github_model: Optional[str]
allow_dirty: bool
mode: str
interval: int
log_json: bool
report_path: pathlib.Path
mutation_budget: int
configure_branch_protection: bool
# Model selection (preferred may fall back to fallback on unavailability)
preferred_model: Optional[str] = None
fallback_model: Optional[str] = None
# Explicit fallback model from GITHUB_FALLBACK_MODEL env var (overrides fallback_model if set)
github_fallback_model: Optional[str] = None
# Explicit lane order override (None = use MUTATION_LANE_ORDER)
campaign_lanes: Optional[Tuple[str, ...]] = None
# Issue-first mode options
dry_run: bool = False # write issue bodies to disk but do not call GitHub API
max_issues: int = 1 # maximum issues to open/update per run in issue mode
issue_subsystem: Optional[str] = None # target a specific subsystem (None = all)
# Closed-loop execution / reconciliation options
work_state_path: Optional[pathlib.Path] = None # path to durable work state JSON; defaults to agent_dir/WORK_STATE_FILE
enable_live_delegation: bool = False # False = dry-run only; True = actually assign/label on GitHub
max_concurrent_delegated: int = 1 # max number of issues simultaneously delegated
active_objective: Optional[str] = None # restrict execution selection to this objective key
lane_filter: Optional[str] = None # restrict execution selection to this lane name
stale_timeout_days: int = 14 # days before a delegated-but-PR-less item is marked stale
reconciliation_window_days: int = 30 # days of PRs to consider during reconciliation
@dataclasses.dataclass
class PyFileInfo:
path: str
module: str
imports: List[str]
local_imports: List[str]
entrypoint: bool
debug_print_lines: List[int]
parse_error: Optional[str] = None
@dataclasses.dataclass
class PatchPlan:
task: str
reason: str
file_changes: Dict[str, str]
metadata: Dict[str, Any]
pr_title: str
pr_body: str
stable_branch_hint: str
@dataclasses.dataclass
class ArchGap:
"""A concrete architectural or operational gap detected by the system."""
subsystem: str # one of SUBSYSTEM_LABELS (e.g. "runtime", "workflow")
issue_key: str # short deterministic slug (e.g. "import-cycles-backend")
title: str # short human-readable title for the GitHub issue
summary: str # 1-2 sentence description
problem: str # detailed problem statement
why_it_matters: str # justification
scope: str # bounded scope description
suggested_files: List[str] # repo-relative file paths relevant to the fix
implementation_notes: str # guidance for implementer / Copilot
acceptance_criteria: List[str]
validation_commands: List[str]
out_of_scope: str
copilot_prompt: str # ready-to-paste Copilot Chat / agent mode prompt
priority: str # one of ISSUE_PRIORITY_LEVELS
confidence: float # 0.0-1.0
@dataclasses.dataclass
class IssueAction:
"""Result of a single issue synthesis operation."""
action: str # "created" | "updated" | "dry_run" | "error"
issue_number: Optional[int]
issue_url: Optional[str]
labels_applied: List[str] # labels *requested* by the orchestration layer (sent to GitHub API)
dedupe_result: str # "new" | "existing_open" | "lookup_failed" | "create_failed" | "n/a"
fingerprint: str
dry_run_path: Optional[str]
gap_title: str
gap_subsystem: str
error: Optional[str] = None
labels_confirmed: Optional[List[str]] = None # labels actually *confirmed* by GitHub API response; None when no API call was made (dry-run/error)
@dataclasses.dataclass
class WorkItem:
"""Durable record of a single unit of work tracked through planning → execution → PR → reconciliation.
Stored in .agent/work_state.json (gitignored). The work state is the memory lane:
it feeds back into future planning passes to prevent duplicate/overlapping issues.
"""
fingerprint: str # 12-hex deterministic fingerprint (from issue_fingerprint())
objective: str # active objective at time of creation (e.g. "eliminate-import-cycles")
lane: str # charter lane name (e.g. "import_cycles")
issue_number: Optional[int]
issue_state: str # "open" | "closed"
delegation_state: str # "ready-for-delegation" | "delegation-requested" | "delegation-confirmed" | "delegation-failed" | "delegation-unconfirmed"
assignee: Optional[str] # GitHub username delegated to (e.g. "copilot")
pr_number: Optional[int]
pr_url: Optional[str]
pr_state: Optional[str] # "open" | "draft" | "merged" | "closed_unmerged" | "stale" | None
merged: bool
closed_unmerged: bool
blocked: bool
superseded: bool
created_at: str # ISO-8601 UTC
updated_at: str # ISO-8601 UTC
run_id: str # workflow run provenance
gap_title: str
gap_subsystem: str
delegation_mechanism: Optional[str] = None
delegation_requested_at: Optional[str] = None
delegation_confirmed_at: Optional[str] = None
delegation_confirmation_evidence: Optional[Dict[str, Any]] = None
delegation_comment_url: Optional[str] = None
delegation_comment_id: Optional[int] = None
delegation_assignment_evidence: Optional[Dict[str, Any]] = None
pr_match_method: Optional[str] = None
pr_match_confidence: Optional[str] = None
pr_match_evidence: Optional[Dict[str, Any]] = None
lifecycle_fact_state: str = "ready-for-delegation"
lifecycle_inferred_state: Optional[str] = None
def log(message: str, *, data: Optional[Dict[str, Any]] = None, json_mode: bool = False) -> None:
if json_mode:
payload: Dict[str, Any] = {"ts": int(time.time()), "message": message}
if data is not None:
payload["data"] = data
sys.stderr.write(json.dumps(payload, sort_keys=True) + "\n")
else:
line = f"[{APP_NAME}] {message}"
if data:
line += " | " + json.dumps(data, sort_keys=True)
sys.stderr.write(line + "\n")
sys.stderr.flush()
def atomic_write_text(path: pathlib.Path, content: str) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
tmp = path.with_suffix(path.suffix + ".tmp")
tmp.write_text(content, encoding="utf-8")
tmp.replace(path)
def atomic_write_json(path: pathlib.Path, payload: Any) -> None:
atomic_write_text(path, json.dumps(payload, indent=2, sort_keys=True) + "\n")
def read_json(path: pathlib.Path, default: Any) -> Any:
if not path.exists():
return default
return json.loads(path.read_text(encoding="utf-8"))
def sha256_text(text: str) -> str:
return hashlib.sha256(text.encode("utf-8")).hexdigest()
def discover_git_root() -> pathlib.Path:
proc = subprocess.run(["git", "rev-parse", "--show-toplevel"], capture_output=True, text=True)
if proc.returncode != 0:
raise RepoArchitectError("Not inside a git repository.")
return pathlib.Path(proc.stdout.strip()).resolve()
def run_cmd(cmd: Sequence[str], *, cwd: pathlib.Path, check: bool = True, capture: bool = True, env: Optional[Dict[str, str]] = None) -> subprocess.CompletedProcess:
merged = os.environ.copy()
if env:
merged.update(env)
return subprocess.run(list(cmd), cwd=str(cwd), text=True, capture_output=capture, check=check, env=merged)
def git_current_branch(root: pathlib.Path) -> str:
return run_cmd(["git", "rev-parse", "--abbrev-ref", "HEAD"], cwd=root).stdout.strip()
def git_head_sha(root: pathlib.Path) -> str:
return run_cmd(["git", "rev-parse", "HEAD"], cwd=root).stdout.strip()
def git_status_porcelain(root: pathlib.Path) -> str:
return run_cmd(["git", "status", "--porcelain=v1", "-uall"], cwd=root).stdout
def git_is_dirty(root: pathlib.Path) -> bool:
return bool(git_status_porcelain(root).strip())
def git_checkout_branch(root: pathlib.Path, branch: str) -> None:
run_cmd(["git", "checkout", "-B", branch], cwd=root)
def git_checkout(root: pathlib.Path, branch: str) -> None:
run_cmd(["git", "checkout", branch], cwd=root)
def git_delete_branch(root: pathlib.Path, branch: str) -> None:
run_cmd(["git", "branch", "-D", branch], cwd=root, check=False)
def git_stage_and_commit(root: pathlib.Path, paths: Sequence[str], message: str) -> None:
run_cmd(["git", "add", "--", *paths], cwd=root)
run_cmd(["git", "commit", "-m", message], cwd=root)
def git_push_branch(root: pathlib.Path, branch: str) -> None:
run_cmd(["git", "push", "--set-upstream", "origin", branch], cwd=root)
def git_has_remote_origin(root: pathlib.Path) -> bool:
proc = subprocess.run(["git", "remote", "get-url", "origin"], cwd=str(root), capture_output=True, text=True)
return proc.returncode == 0
def git_remote_branch_exists(root: pathlib.Path, branch: str) -> bool:
"""Return True if *branch* already exists on the origin remote."""
proc = subprocess.run(
["git", "ls-remote", "--exit-code", "--heads", "origin", f"refs/heads/{branch}"],
cwd=str(root), capture_output=True, text=True,
)
return proc.returncode == 0
def safe_branch_name(stable_hint: str) -> str:
slug = re.sub(r"[^a-zA-Z0-9._/-]+", "-", stable_hint).strip("-/").lower()
return slug[:100]
def with_unique_branch_suffix(branch: str) -> str:
"""Append a per-run unique suffix to *branch* so repeated workflow runs
never collide on the same remote branch name.
Suffix precedence:
1. REPO_ARCHITECT_BRANCH_SUFFIX env var (if set and non-empty)
2. GITHUB_RUN_ID-GITHUB_RUN_ATTEMPT (both env vars must be non-empty)
3. UTC timestamp fallback (YYYYmmddHHMMSS)
The suffix is sanitised to contain only: A-Z a-z 0-9 . _ -
If sanitisation produces an empty string the timestamp fallback is used.
The total branch name is capped at _MAX_BRANCH_NAME_LEN characters.
"""
# Compute a stable timestamp once so both fallback paths use the same value.
ts_fallback = dt.datetime.now(dt.timezone.utc).strftime("%Y%m%d%H%M%S")
raw = os.environ.get("REPO_ARCHITECT_BRANCH_SUFFIX", "").strip()
if not raw:
run_id = os.environ.get("GITHUB_RUN_ID", "").strip()
run_attempt = os.environ.get("GITHUB_RUN_ATTEMPT", "").strip()
if run_id and run_attempt:
raw = f"{run_id}-{run_attempt}"
if not raw:
raw = ts_fallback
suffix = re.sub(r"[^a-zA-Z0-9._-]", "-", raw).strip("-")
# Guard: if all chars were invalid, use the pre-computed timestamp fallback
if not suffix:
suffix = ts_fallback
full = f"{branch}-{suffix}"
return full[:_MAX_BRANCH_NAME_LEN]
def git_identity_present(root: pathlib.Path) -> bool:
a = subprocess.run(["git", "config", "user.email"], cwd=str(root), capture_output=True, text=True)
b = subprocess.run(["git", "config", "user.name"], cwd=str(root), capture_output=True, text=True)
return a.returncode == 0 and b.returncode == 0 and bool(a.stdout.strip()) and bool(b.stdout.strip())
# -----------------------------
# GitHub / GitHub Models
# -----------------------------
def github_request(token: str, path: str, *, method: str = "GET", payload: Optional[Any] = None) -> Any:
body = None if payload is None else json.dumps(payload).encode("utf-8")
req = urllib.request.Request(
f"{GITHUB_API}{path}",
method=method,
data=body,
headers={
"Authorization": f"Bearer {token}",
"Accept": "application/vnd.github+json",
"Content-Type": "application/json",
"User-Agent": APP_NAME,
"X-GitHub-Api-Version": GITHUB_API_VERSION,
},
)
try:
with urllib.request.urlopen(req, timeout=30) as resp:
raw = resp.read().decode("utf-8")
return json.loads(raw) if raw else {}
except urllib.error.HTTPError as exc:
raw = exc.read().decode("utf-8", errors="replace")
raise RepoArchitectError(f"GitHub API {method} {path} failed: {exc.code} {raw}") from exc
except urllib.error.URLError as exc:
raise RepoArchitectError(f"GitHub API {method} {path} network error: {exc.reason}") from exc
def github_models_catalog(token: str) -> List[Dict[str, Any]]:
req = urllib.request.Request(
GITHUB_MODELS_CATALOG,
method="GET",
headers={
"Authorization": f"Bearer {token}",
"Accept": "application/json",
"User-Agent": APP_NAME,
},
)
try:
with urllib.request.urlopen(req, timeout=30) as resp:
raw = resp.read().decode("utf-8")
payload = json.loads(raw)
if isinstance(payload, dict) and isinstance(payload.get("data"), list):
return payload["data"]
if isinstance(payload, list):
return payload
return []
except urllib.error.HTTPError as exc:
raw = exc.read().decode("utf-8", errors="replace")
raise RepoArchitectError(f"GitHub Models catalog failed: {exc.code} {raw}") from exc
def model_available(catalog: List[Dict[str, Any]], model: str) -> bool:
for item in catalog:
identifier = item.get("id") or item.get("name") or item.get("model")
if identifier == model:
return True
return False
def _resolve_models(
available: Set[str],
catalog_ok: bool,
env_model: str = "",
env_fallback: str = "",
order: Sequence[str] = PREFERRED_MODEL_ORDER,
) -> Tuple[str, str]:
"""Resolve preferred and fallback model IDs using override-first, then catalog-order logic.
Args:
available: Set of model IDs returned by the catalog.
catalog_ok: Whether the catalog fetch succeeded.
env_model: Explicit primary override (GITHUB_MODEL env var). Empty → auto-resolve.
env_fallback: Explicit fallback override (GITHUB_FALLBACK_MODEL env var). Empty → auto-resolve.
order: Preferred resolution order; defaults to PREFERRED_MODEL_ORDER.
Returns:
(preferred, fallback) — never the same value for both unless only one model exists.
"""
order_list = list(order)
def first_available(candidates: Sequence[str]) -> Optional[str]:
for c in candidates:
if c in available:
return c
return None
def deterministic_available(exclude: Optional[str] = None) -> Optional[str]:
candidates = sorted(m for m in available if m != exclude)
return candidates[0] if candidates else None
if env_model:
preferred = env_model
elif catalog_ok and available:
preferred = first_available(order_list) or deterministic_available() or order_list[0]
else:
preferred = order_list[0]
if env_fallback:
fallback = env_fallback
elif catalog_ok and available:
fallback = (
first_available([c for c in order_list if c != preferred])
or deterministic_available(exclude=preferred)
or preferred
)
else:
fallback = order_list[1] if len(order_list) > 1 and order_list[1] != preferred else order_list[0]
if not isinstance(preferred, str) or not preferred:
preferred = order_list[0]
if not isinstance(fallback, str) or not fallback:
fallback = order_list[1] if len(order_list) > 1 and order_list[1] != preferred else order_list[0]
return preferred, fallback
def github_models_chat(token: str, model: str, messages: List[Dict[str, str]]) -> Dict[str, Any]:
req = urllib.request.Request(
GITHUB_MODELS_CHAT,
method="POST",
data=json.dumps({"model": model, "messages": messages, "temperature": 0.2}).encode("utf-8"),
headers={
"Authorization": f"Bearer {token}",
"Accept": "application/json",
"Content-Type": "application/json",
"User-Agent": APP_NAME,
},
)
try:
with urllib.request.urlopen(req, timeout=45) as resp:
return json.loads(resp.read().decode("utf-8"))
except urllib.error.HTTPError as exc:
raw = exc.read().decode("utf-8", errors="replace")
raise RepoArchitectError(f"GitHub Models inference failed: {exc.code} {raw}") from exc
except urllib.error.URLError as exc:
raise RepoArchitectError(f"GitHub Models inference network error: {exc.reason}") from exc
def parse_model_text(resp: Dict[str, Any]) -> str:
try:
return resp["choices"][0]["message"]["content"].strip()
except Exception as exc:
raise RepoArchitectError(f"Could not parse GitHub Models response: {exc}")
def _is_model_unavailable_error(msg: str) -> bool:
"""Return True if the HTTP error body suggests the model itself is unavailable/unknown."""
lower = msg.lower()
return any(sig in lower for sig in _MODEL_UNAVAILABLE_SIGNALS)
# Regex matching HTTP status codes that warrant a fallback retry:
# 403 (permission/forbidden), 404 (not found), 429 (rate-limit/quota), 5xx (provider failure)
_FALLBACK_HTTP_CODE_RE = re.compile(r"(?:inference failed|network error).*?:\s*(403|404|429|5\d\d)\b")
# Timeout signals in lowercased error text
_TIMEOUT_SIGNALS = frozenset({"timed out", "timeout"})
def _should_try_fallback(msg: str) -> bool:
"""Return True if the error warrants retrying with the fallback model.
Triggers on: model unavailability, HTTP 403/404/429, timeout, and 5xx provider errors.
Does NOT trigger on bare non-code error strings (e.g. generic "rate limit exceeded"
without an HTTP status code) to keep the trigger set narrow and deterministic.
"""
if _is_model_unavailable_error(msg):
return True
lower = msg.lower()
if any(sig in lower for sig in _TIMEOUT_SIGNALS):
return True
if _FALLBACK_HTTP_CODE_RE.search(msg):
return True
return False
def extract_json_from_model_text(text: str) -> Any:
"""Extract the first JSON object or array from model-returned text (handles fences)."""
try:
return json.loads(text)
except json.JSONDecodeError:
pass
for fence in ("```json", "```"):
if fence in text:
inner = text.split(fence, 1)[1].rsplit("```", 1)[0].strip()
try:
return json.loads(inner)
except json.JSONDecodeError:
pass
for start_char, end_char in (("{", "}"), ("[", "]")):
start = text.find(start_char)
if start == -1:
continue
depth = 0
for i, ch in enumerate(text[start:], start):
if ch == start_char:
depth += 1
elif ch == end_char:
depth -= 1
if depth == 0:
try:
return json.loads(text[start:i + 1])
except json.JSONDecodeError:
break
raise RepoArchitectError("Could not parse JSON from model response")
def call_models_with_fallback_or_none(
token: str,
preferred: str,
fallback: Optional[str],
messages: List[Dict[str, str]],
) -> Tuple[Optional[Dict[str, Any]], str, Optional[str], bool]:
"""Call GitHub Models with preferred model, auto-falling back if it is unavailable.
Returns (response_or_None, requested_model, fallback_reason, fallback_occurred).
Returns a None response (instead of raising) if all attempts fail, so callers
can continue the run without model-generated output.
"""
try:
resp = github_models_chat(token, preferred, messages)
return resp, preferred, None, False
except RepoArchitectError as exc:
reason = str(exc)
if fallback and fallback != preferred and _should_try_fallback(reason):
try:
resp = github_models_chat(token, fallback, messages)
return resp, preferred, reason, True
except RepoArchitectError as exc2:
return None, preferred, f"{reason}; fallback also failed: {exc2}", True
return None, preferred, reason, False
def find_existing_open_pr(config: Config, branch: str) -> Optional[Dict[str, Any]]:
if not config.github_repo or not config.github_token:
return None
owner = config.github_repo.split("/")[0]
path = (
f"/repos/{config.github_repo}/pulls?state=open&head="
f"{urllib.parse.quote(owner + ':' + branch, safe='')}&base="
f"{urllib.parse.quote(config.github_base_branch or 'main', safe='')}"
)
prs = github_request(config.github_token, path)
if isinstance(prs, list) and prs:
return prs[0]
return None
def create_or_update_pull_request(config: Config, branch: str, title: str, body: str) -> Dict[str, Any]:
if not config.github_token or not config.github_repo:
raise RepoArchitectError("Missing GITHUB_TOKEN or GITHUB_REPO for PR creation.")
existing = find_existing_open_pr(config, branch)
if existing:
number = existing["number"]
return github_request(config.github_token, f"/repos/{config.github_repo}/pulls/{number}", method="PATCH", payload={"title": title, "body": body})
payload = {
"title": title,
"head": branch,
"base": config.github_base_branch or "main",
"body": body,
"maintainer_can_modify": True,
}
return github_request(config.github_token, f"/repos/{config.github_repo}/pulls", method="POST", payload=payload)
# -----------------------------------------------------------------------
# Issue-first orchestration
# -----------------------------------------------------------------------
def issue_fingerprint(subsystem: str, issue_key: str) -> str:
"""Return a deterministic 12-hex-char fingerprint for deduplication.
12 hex characters (48 bits) gives ~1-in-281-trillion collision probability
per pair, which is adequate for the bounded set of architectural gap types
per repository (typically ≤ 30 distinct gap keys).
"""
canonical = f"{subsystem}:{issue_key}".lower().strip()
return hashlib.sha256(canonical.encode("utf-8")).hexdigest()[:12]
def render_issue_body(gap: ArchGap, config: Config, run_id: str) -> str:
"""Render a structured GitHub issue body from an ArchGap."""
fp = issue_fingerprint(gap.subsystem, gap.issue_key)
generated_at = dt.datetime.now(dt.timezone.utc).isoformat()
criteria_md = "\n".join(f"- [ ] {c}" for c in gap.acceptance_criteria)
validation_md = "\n".join(f"```\n{v}\n```" for v in gap.validation_commands)
files_md = "\n".join(f"- `{f}`" for f in gap.suggested_files) if gap.suggested_files else "_See implementation notes._"
machine_meta = json.dumps({
"subsystem": gap.subsystem,
"priority": gap.priority,
"confidence": gap.confidence,
"mode": ISSUE_MODE,
"generated_at": generated_at,
"run_id": run_id,
"repo": config.github_repo or "unknown",
"issue_key": gap.issue_key,
"fingerprint": fp,
}, indent=2, sort_keys=True)
# Build without textwrap.dedent so embedded multi-line content (JSON, copilot prompt)
# does not interfere with whitespace stripping.
parts = [
"## Summary", "", gap.summary, "",
"## Problem", "", gap.problem, "",
"## Why it matters", "", gap.why_it_matters, "",
"## Scope", "", gap.scope, "",
"## Suggested files", "", files_md, "",
"## Implementation notes", "", gap.implementation_notes, "",
"## Copilot implementation prompt", "",
"> Paste the block below directly into **Copilot Chat** or **agent mode** to begin implementation.", "",
"```", gap.copilot_prompt, "```", "",
"## Acceptance criteria", "", criteria_md, "",
"## Validation", "", validation_md, "",
"## Out of scope", "", gap.out_of_scope, "",
"---",
f"<!-- arch-gap-fingerprint: {fp} -->",
"<details>",
"<summary>Machine metadata</summary>", "",
"```json", machine_meta, "```",
"</details>", "",
]
return "\n".join(parts)
def find_existing_github_issue(config: Config, fingerprint: str) -> Optional[Dict[str, Any]]:
"""Search open GitHub Issues for one containing the arch-gap fingerprint marker.
Returns the matching issue dict, or ``None`` if no match is found.
Raises :class:`RepoArchitectError` for **any** failure during the lookup
(network, HTTP, JSON decode, etc.) so that
callers always receive a single normalised exception type and can decide
whether to skip issue creation on dedupe failure.
"""
if not config.github_token or not config.github_repo:
return None
try:
marker = f"arch-gap-fingerprint: {fingerprint}"
query = urllib.parse.urlencode({"q": f"repo:{config.github_repo} is:issue is:open {marker}", "per_page": "5"})
result = github_request(config.github_token, f"/search/issues?{query}")
items = result.get("items", []) if isinstance(result, dict) else []
for item in items:
body = item.get("body") or ""
if marker in body:
return item
return None
except RepoArchitectError:
raise # already normalised
except Exception as exc:
raise RepoArchitectError(f"Dedupe lookup failed: {exc}") from exc
def ensure_github_labels(config: Config, label_names: Sequence[str]) -> None:
"""Create any missing repo labels (best-effort; errors are non-fatal)."""
if not config.github_token or not config.github_repo:
return
# Palette: alternating colours for visibility
_COLOURS = ["0075ca", "e4e669", "d93f0b", "0052cc", "5319e7", "1d76db", "b60205", "006b75"]
try:
existing_raw = github_request(config.github_token, f"/repos/{config.github_repo}/labels?per_page=100")
existing = {item["name"] for item in existing_raw} if isinstance(existing_raw, list) else set()
except RepoArchitectError:
existing = set()
for i, name in enumerate(label_names):
if name in existing:
continue
colour = _COLOURS[i % len(_COLOURS)]
try:
github_request(
config.github_token,
f"/repos/{config.github_repo}/labels",
method="POST",
payload={"name": name, "color": colour},
)
except RepoArchitectError:
pass # label already exists race or insufficient permissions
def create_github_issue_api(
config: Config, title: str, body: str, labels: List[str]
) -> Dict[str, Any]:
"""Create a GitHub Issue and return the API response."""
if not config.github_token or not config.github_repo:
raise RepoArchitectError("Missing GITHUB_TOKEN or GITHUB_REPO for issue creation.")
payload: Dict[str, Any] = {"title": title, "body": body}
if labels:
payload["labels"] = labels
return github_request(config.github_token, f"/repos/{config.github_repo}/issues", method="POST", payload=payload)
def update_github_issue_api(
config: Config, issue_number: int, comment: str
) -> Dict[str, Any]:
"""Add a comment to an existing GitHub Issue."""
if not config.github_token or not config.github_repo:
raise RepoArchitectError("Missing GITHUB_TOKEN or GITHUB_REPO for issue update.")
return github_request(
config.github_token,
f"/repos/{config.github_repo}/issues/{issue_number}/comments",
method="POST",
payload={"body": comment},
)
def set_github_issue_labels(
config: Config, issue_number: int, labels: List[str]
) -> Dict[str, Any]:
"""PATCH labels on an existing GitHub Issue so they reflect the current computed set."""
if not config.github_token or not config.github_repo:
raise RepoArchitectError("Missing GITHUB_TOKEN or GITHUB_REPO for label update.")
return github_request(
config.github_token,
f"/repos/{config.github_repo}/issues/{issue_number}",
method="PATCH",
payload={"labels": labels},
)
def _extract_confirmed_labels(api_response: Any) -> Optional[List[str]]:
"""Extract label names from a GitHub API issue response (create or PATCH).
Returns a list of label name strings confirmed by the API, or ``None``
when the response shape is unexpected.
"""
if not isinstance(api_response, dict):
return None
raw_labels = api_response.get("labels")
if not isinstance(raw_labels, list):
return None
return [lbl["name"] for lbl in raw_labels if isinstance(lbl, dict) and "name" in lbl]
def synthesize_issue(
config: Config, gap: ArchGap, run_id: str, dry_run: bool
) -> IssueAction:
"""Synthesize one GitHub Issue for a detected ArchGap.
Behavior:
- Renders the full structured issue body.
- In dry_run mode: writes the body to disk under ISSUE_REPORT_DIR.
- In live mode: deduplicates against open issues then creates or updates.
"""
fp = issue_fingerprint(gap.subsystem, gap.issue_key)
body = render_issue_body(gap, config, run_id)
labels: List[str] = ["arch-gap", "copilot-task", "needs-implementation", "ready-for-delegation"]
if gap.subsystem in SUBSYSTEM_LABELS:
labels.append(gap.subsystem)
if gap.priority in ("critical", "high"):
labels.append(f"priority:{gap.priority}")
if dry_run:
out_dir = config.git_root / ISSUE_REPORT_DIR
out_dir.mkdir(parents=True, exist_ok=True)
out_path = out_dir / f"{fp}.md"
header = f"# {gap.title}\n\n_Dry-run preview — not submitted to GitHub._\n\n"
atomic_write_text(out_path, header + body)
return IssueAction(
action="dry_run",
issue_number=None,
issue_url=None,
labels_applied=labels,
dedupe_result="n/a",
fingerprint=fp,
dry_run_path=str(out_path.relative_to(config.git_root)),
gap_title=gap.title,
gap_subsystem=gap.subsystem,
)
if not config.github_token or not config.github_repo:
# No credentials: fall back to dry-run automatically
out_dir = config.git_root / ISSUE_REPORT_DIR
out_dir.mkdir(parents=True, exist_ok=True)
out_path = out_dir / f"{fp}.md"
header = f"# {gap.title}\n\n_No GitHub credentials — saved locally only._\n\n"
atomic_write_text(out_path, header + body)
return IssueAction(
action="dry_run",
issue_number=None,
issue_url=None,
labels_applied=labels,
dedupe_result="n/a",
fingerprint=fp,
dry_run_path=str(out_path.relative_to(config.git_root)),
gap_title=gap.title,
gap_subsystem=gap.subsystem,
)
# Ensure required labels exist
ensure_github_labels(config, labels)
# Deduplication: search for an existing open issue with the same fingerprint
try:
existing = find_existing_github_issue(config, fp)
except RepoArchitectError as exc:
# Dedupe lookup failed — skip creation to avoid duplicates
log("Deduplication lookup failed; skipping issue creation to avoid duplicates",
data={"fingerprint": fp, "error": str(exc)},
json_mode=config.log_json)
return IssueAction(