Repository navigation
Expand file tree
/
Copy pathsetup.py
More file actions
618 lines (539 loc) · 21.1 KB
/
Copy pathsetup.py
File metadata and controls
618 lines (539 loc) · 21.1 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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# SPDX-License-Identifier: MIT
"""
BACH Setup Script — Drei-Säulen-Modell (Säule 1: SCRIPT)
=========================================================
Automatisierte Erstinstallation von BACH.
Führt deterministische Schritte aus die kein LLM brauchen.
Schritte (S1-S7):
S1: Python-Pakete installieren (requirements.txt)
S2: Frische bach.db aus dem aktuellen Schema initialisieren
S3: Ausstehende Migrationen anhand des gebuchten Stands ausführen
S4: Pflichtverzeichnisse anlegen
S5: user/secrets/secrets.json Skeleton
S6: system_identity in DB
S7: user_config.json Default
Extras (optional):
S8-S12: GUI, PDF, Docs, Voice, Analytics via bach[extra]
S13: Domain-Schemas (steuer, agents)
Referenz: SQ015, ENT-28, INSTALL_KONZEPT.md
Datum: 2026-02-19
"""
import argparse
import json
import os
import secrets
import sqlite3
import subprocess
import sys
from datetime import datetime
from pathlib import Path
from tempfile import TemporaryDirectory
try: # pragma: no cover - Importpfad haengt vom Aufrufkontext ab
from system.tools.installer_manifest import (
InstallerVerificationError,
MutationJournal,
file_digest,
load_manifest,
load_product_profile,
payload_digest,
plan_rollback,
resolve_components,
verify_component_set,
verify_grant,
)
except ImportError: # direkter Aufruf: setup.py als Skript neben system/
sys.path.insert(0, str(Path(__file__).parent))
from system.tools.installer_manifest import (
InstallerVerificationError,
MutationJournal,
file_digest,
load_manifest,
load_product_profile,
payload_digest,
plan_rollback,
resolve_components,
verify_component_set,
verify_grant,
)
from system.core.db import Database, migration_filenames, read_applied_migration_filenames
_PACKAGING_COMMANDS = {
"egg_info",
"dist_info",
"editable_wheel",
"bdist_wheel",
"sdist",
"develop",
}
_CONSOLE_REQUIREMENT = (
"ellmos-unified-gui @ "
"git+https://github.com/ellmos-ai/unified-gui.git@"
"a0d59afe95a227cc73c7494d5f1ccea1cdb6b987"
)
def _read_requirements(requirements_path: Path) -> list[str]:
"""Liest requirements.txt fuer setuptools packaging."""
if not requirements_path.exists():
return []
requirements = []
for raw_line in requirements_path.read_text(encoding="utf-8").splitlines():
line = raw_line.strip()
if not line or line.startswith("#"):
continue
if "#" in line:
line = line.split("#", 1)[0].strip()
if line:
requirements.append(line)
return requirements
def _run_packaging_setup() -> None:
"""Bedient setuptools-Buildhooks fuer pip install -e ."""
from setuptools import setup as setuptools_setup
root = Path(__file__).parent
readme_path = root / "README.md"
long_description = ""
if readme_path.exists():
long_description = readme_path.read_text(encoding="utf-8")
setuptools_setup(
name="ellmos-bach",
version="3.15.0",
description="BACH root-level editable install shim",
long_description=long_description,
long_description_content_type="text/markdown",
python_requires=">=3.10",
license="MIT",
py_modules=["bach", "bach_api", "bach_report_client"],
install_requires=_read_requirements(root / "requirements.txt"),
extras_require={
"console": [_CONSOLE_REQUIREMENT],
"worker-policy": [
"taskplan @ git+https://github.com/ellmos-ai/task-master.git@"
"23ddcb3b66bdbff03342872adf5a096333a4a30c"
],
},
entry_points={
"console_scripts": ["bach=bach:main"],
"ellmos.report_clients": [
"bach-control=bach_report_client:create_report_control_client",
],
},
)
if any(arg in _PACKAGING_COMMANDS for arg in sys.argv[1:]):
_run_packaging_setup()
raise SystemExit(0)
class BACHSetup:
"""BACH Installation Manager."""
def __init__(
self,
bach_root: Path = None,
manifest_path=None,
grant_path=None,
product_profile_path=None,
grant_key=None,
):
"""
Args:
bach_root: BACH Root-Verzeichnis (default: Script-Parent)
manifest_path: Komponentenmanifest (default: bach-core.v1.json)
grant_path: Signatur-Grant-Datei (default: keine)
product_profile_path: Produktprofil (default: bach-default.v1.json)
grant_key: HMAC-Verifikationsschluessel (default: ENV BACH_INSTALLER_GRANT_KEY)
"""
if bach_root is None:
# Script liegt im BACH-Root
bach_root = Path(__file__).parent
self.root = Path(bach_root)
self.system = self.root / "system"
self.data = self.system / "data"
self.db_path = self.data / "bach.db"
self.schema_dir = self.data / "schema"
self.sql_dir = self.data / "sql"
self.user_dir = self.root / "user"
self.manifest_path = (
Path(manifest_path)
if manifest_path
else self.data / "installer" / "manifests" / "bach-core.v1.json"
)
self.product_profile_path = (
Path(product_profile_path)
if product_profile_path
else self.data / "installer" / "profiles" / "bach-default.v1.json"
)
self.grant_path = Path(grant_path) if grant_path else None
self.grant_key = (
grant_key
if grant_key is not None
else os.environ.get("BACH_INSTALLER_GRANT_KEY")
)
self.journal_path = self.data / "installer" / "mutation-journal.jsonl"
# Lazy: MutationJournal erst bei Bedarf anlegen, damit verify() keine
# Verzeichnisse erzeugt (Fail-closed: keine Mutation vor der Pruefung).
self._journal = None
self._created_database = False
@property
def journal(self):
"""Mutationsjournal (lazy initialisiert)."""
if self._journal is None:
self._journal = MutationJournal(self.journal_path)
return self._journal
def verify(self) -> bool:
"""Fail-closed Vorabpruefung von Manifest, Komponentenmenge und Grant."""
if not self.manifest_path or not Path(self.manifest_path).exists():
raise InstallerVerificationError(
f"Komponentenmanifest fehlt: {self.manifest_path}"
)
if not self.grant_path or not Path(self.grant_path).exists():
raise InstallerVerificationError(
f"Signatur-Grant fehlt: {self.grant_path}"
)
manifest = load_manifest(self.manifest_path)
profile = load_product_profile(self.product_profile_path)
resolved = resolve_components(manifest)
verify_component_set(resolved, profile["components"])
digest = payload_digest(manifest)
verify_grant(self.grant_path, digest, profile, self.grant_key)
self.journal.record("verify", self.manifest_path, digest=digest)
return True
def check(self) -> bool:
"""Prueft ob BACH korrekt installiert ist. Exit-Code 0=OK, 2=Probleme."""
checks = []
all_ok = True
# DB
if self.db_path.exists():
conn = sqlite3.connect(str(self.db_path))
count = conn.execute("SELECT COUNT(*) FROM sqlite_master WHERE type='table'").fetchone()[0]
conn.close()
checks.append(f"[OK] bach.db ({count} Tabellen)")
else:
checks.append("[!!] bach.db fehlt")
all_ok = False
# Verzeichnisse
for d in [self.data / "logs", self.user_dir]:
if d.exists():
checks.append(f"[OK] {d.name}/")
else:
checks.append(f"[!!] {d.name}/ fehlt")
all_ok = False
# requirements
req = self.root / "requirements.txt"
checks.append(f"[OK] requirements.txt" if req.exists() else "[!!] requirements.txt fehlt")
print("\n".join(checks))
print(f"\nStatus: {'OK' if all_ok else 'Probleme gefunden'}")
return all_ok
def run(self, skip_pip: bool = False, extras: list = None, quiet: bool = False):
"""Führt komplettes Setup aus."""
try:
self.verify()
except InstallerVerificationError as e:
print(f"[ABBRUCH] Verifikation fehlgeschlagen: {e}")
return False
if not quiet:
print("=" * 70)
print(" BACH Setup — Drei-Säulen-Modell")
print("=" * 70)
print(f"BACH Root: {self.root}")
print(f"System: {self.system}")
print(f"DB: {self.db_path}")
print()
steps = [
("S1", "Python-Pakete installieren", self._step_s1_pip_install, not skip_pip),
("S2", "bach.db initialisieren", self._step_s2_db_init, True),
("S3", "Migrations ausführen", self._step_s3_migrations, True),
("S4", "Pflichtverzeichnisse anlegen", self._step_s4_directories, True),
("S5", "Zugangsdaten-Skeleton", self._step_s5_secrets_skeleton, True),
("S6", "system_identity in DB", self._step_s6_system_identity, True),
("S7", "user_config.json Default", self._step_s7_user_config, True),
("S8", "MEMORY.md mit Silo-Index generieren", self._step_s8_memory_md, True),
]
success_count = 0
for step_id, step_name, step_func, enabled in steps:
if not enabled:
print("Schritt übersprungen")
continue
print("Schritt wird ausgeführt...")
try:
step_func(extras if step_id == "S1" else None)
print(f" ✓ OK")
success_count += 1
self._journal_step(step_id)
except Exception as e:
print(f" ✗ FEHLER: {e}")
return False
print()
print("=" * 70)
print(f"Setup abgeschlossen: {success_count}/{len([s for s in steps if s[3]])} Schritte erfolgreich")
print("=" * 70)
print()
print("Nächste Schritte:")
print(" 1. Starte BACH: cd system && python bach.py --startup")
print(" 2. LLM arbeitet Onboarding-Tasks ab (Säule 2)")
print(" 3. Optional: API-Keys eintragen, Connectors einrichten (Säule 3)")
print()
return True
def _journal_step(self, step_id: str):
"""Protokolliert die von einem Schritt mutierten Ziele im Mutationsjournal."""
if step_id == "S2":
if self._created_database:
self.journal.record(
"create", self.db_path, digest=file_digest(self.db_path), component="S2"
)
return
targets = []
if step_id == "S4":
targets = [
self.data / "logs",
self.data / "_backups",
self.data / "messages",
self.data / "sessions",
self.data / "dist",
self.user_dir / "secrets",
]
elif step_id == "S5":
targets = [self.user_dir / "secrets" / "secrets.json"]
elif step_id == "S7":
targets = [self.system / "config" / "user_config.json"]
for target in targets:
if target.exists():
self.journal.record("create", target, component=step_id)
def rollback(self) -> bool:
"""Setzt die im Mutationsjournal protokollierten Mutationen zurueck.
Fail-closed: Der Loeschplan wird vollstaendig geprueft, bevor irgendein
Ziel entfernt wird. Schlaegt die Pruefung fehl, bleibt das System unberuehrt.
"""
try:
expected = load_product_profile(self.product_profile_path)["components"]
plan = plan_rollback(self.journal_path, expected_components=expected)
except InstallerVerificationError as e:
print(f"[ABBRUCH] Rollback verweigert: {e}")
return False
for raw_target in plan:
target = Path(raw_target)
try:
if target.is_dir():
target.rmdir()
else:
target.unlink()
except FileNotFoundError:
print(f" [SKIP] bereits entfernt: {target}")
continue
except OSError as e:
print(f"[ABBRUCH] Rollback unvollstaendig bei {target}: {e}")
return False
self.journal.record("rollback", target)
print(f"Rollback abgeschlossen: {len(plan)} Ziel(e) zurueckgesetzt")
return True
def _step_s1_pip_install(self, extras: list = None):
"""S1: Python-Pakete installieren."""
requirements = self.root / "requirements.txt"
if not requirements.exists():
print(f" [SKIP] requirements.txt nicht gefunden")
return
# Base requirements
subprocess.run(
[sys.executable, "-m", "pip", "install", "-r", str(requirements)],
check=True,
capture_output=True, encoding='utf-8', errors='replace'
)
# Extras (falls angegeben)
if extras:
extras_str = ",".join(extras)
subprocess.run(
[sys.executable, "-m", "pip", "install", f"bach[{extras_str}]"],
check=True,
capture_output=True, encoding='utf-8', errors='replace'
)
def _step_s2_db_init(self, _):
"""S2: Vollschema und Migrationsstand einer frischen DB anlegen."""
self._created_database = False
schema_sql = self.schema_dir / "schema.sql"
if not schema_sql.is_file():
raise FileNotFoundError(f"schema.sql nicht gefunden: {schema_sql}")
if self.db_path.exists():
print(f" [SKIP] Bestehende Datenbank: {self.db_path}")
return
self.db_path.parent.mkdir(parents=True, exist_ok=True)
# Erst die fertige DB veröffentlichen. Ein paralleler Setup-Lauf
# darf eine bereits veröffentlichte Datenbank nicht ersetzen.
with TemporaryDirectory(prefix=".bach-setup-", dir=self.db_path.parent) as staging:
staged_path = Path(staging) / self.db_path.name
db = Database(staged_path, self.schema_dir)
db.init_schema()
db.apply_seed_migrations()
db.baseline_migrations()
os.link(staged_path, self.db_path)
self._created_database = True
print(f" DB initialisiert: {self.db_path}")
def _step_s3_migrations(self, _):
"""S3: Ausstehende Migrationen einer bereits gebuchten DB ausführen."""
names = migration_filenames(self.schema_dir / "migrations")
if not names:
return
if not read_applied_migration_filenames(self.db_path):
raise RuntimeError(
"Der Datenbank fehlt der Migrationsstand. "
"Prüfe den Stand mit bach update migrations list, bevor du die Baseline buchst."
)
db = Database(self.db_path, self.schema_dir)
backlog = db.migration_backlog()
if backlog:
raise RuntimeError(
"Der Datenbank fehlen ältere Migrationsbuchungen: " + ", ".join(backlog)
)
applied, error = db.run_migrations()
if error:
raise RuntimeError(error)
for name in applied:
print(f" Migration angewendet: {name}")
def _step_s4_directories(self, _):
"""S4: Pflichtverzeichnisse anlegen."""
required_dirs = [
self.data / "logs",
self.data / "_backups",
self.data / "messages",
self.data / "sessions",
self.data / "dist",
self.user_dir / "secrets",
]
for d in required_dirs:
d.mkdir(parents=True, exist_ok=True)
print(f" {len(required_dirs)} Verzeichnisse angelegt")
def _step_s5_secrets_skeleton(self, _):
"""S5: user/secrets/secrets.json Skeleton."""
secrets_file = self.user_dir / "secrets" / "secrets.json"
if secrets_file.exists():
print(f" [SKIP] secrets.json existiert bereits")
return
secrets_file.parent.mkdir(parents=True, exist_ok=True)
secrets_file.write_text(
json.dumps({}, indent=2, ensure_ascii=False),
encoding='utf-8'
)
def _step_s6_system_identity(self, _):
"""S6: system_identity in DB."""
conn = sqlite3.connect(str(self.db_path))
# Prüfen ob identity bereits existiert
cursor = conn.execute("SELECT COUNT(*) FROM instance_identity")
if cursor.fetchone()[0] > 0:
print(f" [SKIP] system_identity existiert bereits")
conn.close()
return
instance_id = f"bach-{datetime.now().strftime('%Y-%m-%d')}-{secrets.token_hex(2)}"
now = datetime.now().isoformat()
conn.execute("""
INSERT INTO instance_identity (
instance_id, instance_name, created, seal_status
) VALUES (?, ?, ?, ?)
""", (instance_id, "BACH-Instanz", now, "intact"))
conn.commit()
conn.close()
print(f" Instance ID: {instance_id}")
def _step_s7_user_config(self, _):
"""S7: user_config.json Default."""
config_file = self.system / "config" / "user_config.json"
if config_file.exists():
print(f" [SKIP] user_config.json existiert bereits")
return
config_file.parent.mkdir(parents=True, exist_ok=True)
config_file.write_text(
json.dumps({"startup_mode": "text"}, indent=2, ensure_ascii=False),
encoding='utf-8'
)
def _step_s8_memory_md(self, _):
"""S8: MEMORY.md mit Silo-Index generieren (SQ039/SQ065)."""
memory_md = self.root / "MEMORY.md"
if memory_md.exists():
print(f" [SKIP] MEMORY.md existiert bereits")
return
# Import memory_sync dynamisch (vermeidet zirkuläre Imports)
sys.path.insert(0, str(self.system / "tools"))
try:
from memory_sync import MemorySync
sync = MemorySync(self.root)
success, msg = sync.generate()
if success:
print(f" {msg}")
else:
print(f" [WARN] Konnte MEMORY.md nicht generieren: {msg}")
except ImportError as e:
print(f" [WARN] memory_sync.py nicht gefunden, erstelle Template")
# Fallback: Minimales Template
memory_md.write_text(
"# BACH Memory\n\n## Manual Notes\n\n(Schreibe hier deine Notizen)\n",
encoding='utf-8'
)
def main():
parser = argparse.ArgumentParser(
description="BACH Setup — Automatisierte Installation (Säule 1)"
)
parser.add_argument(
"--skip-pip",
action="store_true",
help="Überspringe pip install (falls Pakete bereits installiert)"
)
parser.add_argument(
"--extras",
nargs="+",
choices=["gui", "pdf", "docs", "voice", "analytics"],
help="Optionale Extra-Pakete installieren"
)
parser.add_argument(
"--non-interactive",
action="store_true",
help="Non-interactive Modus fuer CI/CD (Standard-Werte, keine Prompts)"
)
parser.add_argument(
"--quiet", "-q",
action="store_true",
help="Minimale Ausgabe (nur Fehler)"
)
parser.add_argument(
"--manifest",
type=Path,
default=None,
help="Pfad zum Komponentenmanifest (Default: data/installer/manifests/bach-core.v1.json)"
)
parser.add_argument(
"--grant",
type=Path,
default=None,
help="Pfad zum Signatur-Grant (HMAC-gesicherte Freigabe)"
)
parser.add_argument(
"--product-profile",
type=Path,
default=None,
help="Pfad zum Produktprofil (Default: data/installer/profiles/bach-default.v1.json)"
)
parser.add_argument(
"--rollback",
action="store_true",
help="Letzte Mutationen aus dem Journal zuruecksetzen (fail-closed)"
)
parser.add_argument(
"command",
nargs="?",
default="install",
choices=["install", "check", "verify", "rollback"],
help="Setup-Befehl (default: install). 'verify' prueft Manifest/Profil/Grant ohne Mutation."
)
args = parser.parse_args()
setup = BACHSetup(
manifest_path=args.manifest,
grant_path=args.grant,
product_profile_path=args.product_profile,
)
if args.command == "check":
ok = setup.check()
sys.exit(0 if ok else 2)
elif args.command == "verify":
sys.exit(0 if setup.verify() else 2)
elif args.command == "rollback":
sys.exit(0 if setup.rollback() else 1)
elif args.command == "install":
success = setup.run(
skip_pip=args.skip_pip,
extras=args.extras,
quiet=args.quiet
)
sys.exit(0 if success else 1)
if __name__ == "__main__":
main()