codersforge 0.0.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. codersforge/__init__.py +4 -0
  2. codersforge/__main__.py +8 -0
  3. codersforge/_core/CORE_VERSION +33 -0
  4. codersforge/_core/__init__.py +8 -0
  5. codersforge/_core/archive.py +319 -0
  6. codersforge/_core/backup.py +417 -0
  7. codersforge/_core/config.py +206 -0
  8. codersforge/_core/domain.py +382 -0
  9. codersforge/_core/errors.py +36 -0
  10. codersforge/_core/events.py +381 -0
  11. codersforge/_core/findings.py +265 -0
  12. codersforge/_core/gates.py +395 -0
  13. codersforge/_core/identity.py +259 -0
  14. codersforge/_core/index.py +262 -0
  15. codersforge/_core/items.py +513 -0
  16. codersforge/_core/ledger.py +194 -0
  17. codersforge/_core/lessons.py +142 -0
  18. codersforge/_core/messages.py +293 -0
  19. codersforge/_core/migrate.py +221 -0
  20. codersforge/_core/output.py +41 -0
  21. codersforge/_core/paths.py +62 -0
  22. codersforge/_core/py.typed +0 -0
  23. codersforge/_core/schema.py +113 -0
  24. codersforge/_core/ulid.py +36 -0
  25. codersforge/_core/upgrade.py +57 -0
  26. codersforge/_core/versions.py +20 -0
  27. codersforge/_core/views.py +67 -0
  28. codersforge/_core/walls.py +231 -0
  29. codersforge/_core/workflow.py +745 -0
  30. codersforge/_docs.py +33 -0
  31. codersforge/checks.py +94 -0
  32. codersforge/cli.py +865 -0
  33. codersforge/domain.py +270 -0
  34. codersforge/py.typed +0 -0
  35. codersforge/workflows.yaml +129 -0
  36. codersforge-0.0.1.dist-info/METADATA +81 -0
  37. codersforge-0.0.1.dist-info/RECORD +41 -0
  38. codersforge-0.0.1.dist-info/WHEEL +4 -0
  39. codersforge-0.0.1.dist-info/entry_points.txt +2 -0
  40. codersforge-0.0.1.dist-info/licenses/LICENSE +202 -0
  41. codersforge-0.0.1.dist-info/licenses/NOTICE +7 -0
@@ -0,0 +1,417 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ """Encrypted backups of the state folder, and verified restores.
3
+
4
+ A backup is a gzipped tar of the state folder (its git history included; the
5
+ lock and caches left out) streamed straight into ``age``, so no unencrypted copy
6
+ ever touches the disk. The archive ends with ``BACKUP.json``: the forge, the
7
+ time, the log's event count and last hash, and the SHA-256 of every file.
8
+
9
+ A restore decrypts into a private folder beside the target, checks every file
10
+ against the manifest and the log's hash chain against the recorded last hash,
11
+ and only then moves the folder into place. It never restores over an existing
12
+ state folder.
13
+
14
+ Both are operator-only: a backup holds every message and decision, and
15
+ ``--recipient`` chooses who can read it.
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import contextlib
21
+ import hashlib
22
+ import io
23
+ import json
24
+ import os
25
+ import shutil
26
+ import subprocess # nosec B404
27
+ import tarfile
28
+ import tempfile
29
+ from collections.abc import Iterator, Mapping, Sequence
30
+ from dataclasses import dataclass
31
+ from datetime import UTC, datetime
32
+ from pathlib import Path, PurePosixPath
33
+ from typing import IO, Any
34
+
35
+ from .config import ensure_gitignored
36
+ from .domain import OPERATOR, Domain
37
+ from .errors import ExitCode, ForgeError
38
+ from .events import EventStore
39
+ from .identity import Identity
40
+ from .paths import Layout
41
+
42
+ MANIFEST = "BACKUP.json"
43
+ PREFIX = "state"
44
+ SUFFIX = ".tar.gz.age"
45
+ #: Not backed up: the lock, the index cache, and interrupted atomic writes.
46
+ SKIPPED = (".lock", ".index.sqlite")
47
+ _RECIPIENT_PREFIXES = ("age1", "ssh-ed25519 ", "ssh-rsa ")
48
+
49
+
50
+ @dataclass(frozen=True)
51
+ class BackupResult:
52
+ path: Path
53
+ events: int
54
+ files: int
55
+ recipients: int
56
+ chain_ok: bool
57
+
58
+ def as_dict(self) -> dict[str, Any]:
59
+ return {
60
+ "path": str(self.path),
61
+ "events": self.events,
62
+ "files": self.files,
63
+ "recipients": self.recipients,
64
+ "chain_ok": self.chain_ok,
65
+ }
66
+
67
+
68
+ @dataclass(frozen=True)
69
+ class RestoreResult:
70
+ state: Path
71
+ archive: Path
72
+ created: str
73
+ events: int
74
+ files: int
75
+
76
+ def as_dict(self) -> dict[str, Any]:
77
+ return {
78
+ "state": str(self.state),
79
+ "archive": str(self.archive),
80
+ "created": self.created,
81
+ "events": self.events,
82
+ "files": self.files,
83
+ }
84
+
85
+
86
+ def find_age() -> str:
87
+ """The ``age`` executable; NOT_FOUND with how to get it."""
88
+ age = shutil.which("age")
89
+ if age is None:
90
+ raise ForgeError(
91
+ ExitCode.NOT_FOUND,
92
+ "age_missing",
93
+ "backups are encrypted with age; install it (https://age-encryption.org) and retry",
94
+ )
95
+ return age
96
+
97
+
98
+ def check_recipient(recipient: str) -> str:
99
+ """USAGE unless ``recipient`` looks like an age or SSH public key."""
100
+ if not recipient.startswith(_RECIPIENT_PREFIXES) or "\n" in recipient:
101
+ raise ForgeError(
102
+ ExitCode.USAGE,
103
+ "recipient_invalid",
104
+ f"{recipient[:24]!r} is not an age public key (age1…) or an SSH public key",
105
+ )
106
+ return recipient
107
+
108
+
109
+ def _sha256(data: bytes) -> str:
110
+ return hashlib.sha256(data).hexdigest()
111
+
112
+
113
+ def _inside(path: Path, folder: Path) -> bool:
114
+ try:
115
+ path.resolve().relative_to(folder.resolve())
116
+ except ValueError:
117
+ return False
118
+ return True
119
+
120
+
121
+ def _require_operator(identity: Identity | None, what: str) -> Identity:
122
+ if identity is None or identity.role != OPERATOR:
123
+ raise ForgeError(ExitCode.REFUSED, "role_not_allowed", f"only the operator {what}")
124
+ return identity
125
+
126
+
127
+ class Backups:
128
+ def __init__(self, layout: Layout, domain: Domain, identity: Identity | None) -> None:
129
+ self.layout = layout
130
+ self.domain = domain
131
+ self.identity = identity
132
+ self.store = EventStore(layout, domain)
133
+
134
+ # ------------------------------------------------------------- backup
135
+
136
+ def files(self) -> Iterator[tuple[str, Path]]:
137
+ """``(path relative to the state folder, path)`` for each file backed up."""
138
+ for top, dirs, names in os.walk(self.layout.state, followlinks=False):
139
+ dirs.sort()
140
+ for name in [*dirs, *names]:
141
+ path = Path(top, name)
142
+ if path.is_symlink():
143
+ rel = path.relative_to(self.layout.state).as_posix()
144
+ raise ForgeError(
145
+ ExitCode.DATA,
146
+ "backup_link",
147
+ f"{self.domain.state_dir}/{rel} is a link; links are not backed up",
148
+ )
149
+ for name in sorted(names):
150
+ path = Path(top, name)
151
+ rel = path.relative_to(self.layout.state).as_posix()
152
+ if rel in SKIPPED or (name.startswith(".") and name.endswith(".tmp")):
153
+ continue
154
+ yield rel, path
155
+
156
+ def create(
157
+ self,
158
+ to: Path,
159
+ recipients: Sequence[str],
160
+ project: str,
161
+ now: datetime | None = None,
162
+ ) -> BackupResult:
163
+ """Write ``<to>/<project>-<UTC time>.tar.gz.age``; operator only."""
164
+ who = _require_operator(self.identity, "makes backups")
165
+ if not recipients:
166
+ raise ForgeError(
167
+ ExitCode.USAGE,
168
+ "no_recipient",
169
+ "name who can decrypt the backup: --recipient, or backup.recipients "
170
+ "in config.yaml (an age public key from age-keygen)",
171
+ )
172
+ keys = [check_recipient(r) for r in recipients]
173
+ to = to.expanduser()
174
+ if _inside(to, self.layout.root):
175
+ raise ForgeError(
176
+ ExitCode.USAGE,
177
+ "backup_inside_project",
178
+ f"{to} is inside the project; choose a folder outside {self.layout.root}",
179
+ )
180
+ if not to.is_dir():
181
+ raise ForgeError(ExitCode.NOT_FOUND, "backup_dir_missing", f"{to} does not exist")
182
+ age = find_age()
183
+ moment = (now or datetime.now(UTC)).astimezone(UTC)
184
+ target = to / f"{project}-{moment.strftime('%Y%m%dT%H%M%SZ')}{SUFFIX}"
185
+ if target.exists():
186
+ raise ForgeError(ExitCode.CONFLICT, "backup_exists", f"{target} already exists")
187
+ with self.store.transaction() as tx:
188
+ check = self.store.verify()
189
+ size, tip = self.store.tip()
190
+ fd, tmp = tempfile.mkstemp(dir=to, prefix=f".{target.name}.", suffix=".tmp")
191
+ try:
192
+ count = self._encrypt(age, keys, fd, moment=moment, events=check.events, tip=tip)
193
+ os.replace(tmp, target)
194
+ except BaseException:
195
+ Path(tmp).unlink(missing_ok=True)
196
+ raise
197
+ tx.append(
198
+ "backed_up",
199
+ actor=who.role,
200
+ session=who.session,
201
+ data={
202
+ "file": target.name,
203
+ "dir": str(to),
204
+ "events": check.events,
205
+ "tip": tip,
206
+ "bytes": size,
207
+ "recipients": len(keys),
208
+ "chain_ok": check.ok,
209
+ },
210
+ )
211
+ return BackupResult(target, check.events, count, len(keys), check.ok)
212
+
213
+ def _encrypt( # noqa: PLR0913 - the pieces of one archive
214
+ self,
215
+ age: str,
216
+ keys: Sequence[str],
217
+ fd: int,
218
+ *,
219
+ moment: datetime,
220
+ events: int,
221
+ tip: str,
222
+ ) -> int:
223
+ args = [age, "--encrypt"]
224
+ for key in keys:
225
+ args += ["--recipient", key]
226
+ with os.fdopen(fd, "wb") as out:
227
+ proc = subprocess.Popen( # noqa: S603 - fixed arguments, age from PATH
228
+ args, stdin=subprocess.PIPE, stdout=out, stderr=subprocess.PIPE
229
+ ) # nosec B603
230
+ if proc.stdin is None: # pragma: no cover - stdin=PIPE above
231
+ raise ForgeError(ExitCode.INTERNAL, "age_failed", "no pipe to age")
232
+ hashes: dict[str, str] = {}
233
+ try:
234
+ self._write_tar(proc.stdin, hashes, moment=moment, events=events, tip=tip)
235
+ except BrokenPipeError:
236
+ pass # age exited early; its status and message say why
237
+ finally:
238
+ with contextlib.suppress(BrokenPipeError):
239
+ proc.stdin.close()
240
+ stderr = proc.stderr.read() if proc.stderr else b""
241
+ code = proc.wait()
242
+ out.flush()
243
+ os.fsync(out.fileno())
244
+ if code != 0:
245
+ raise ForgeError(ExitCode.USAGE, "age_failed", _first_line(stderr))
246
+ return len(hashes)
247
+
248
+ def _write_tar(
249
+ self,
250
+ sink: IO[bytes],
251
+ hashes: dict[str, str],
252
+ moment: datetime,
253
+ events: int,
254
+ tip: str,
255
+ ) -> None:
256
+ with tarfile.open(fileobj=sink, mode="w|gz") as tar:
257
+ for rel, path in self.files():
258
+ data = path.read_bytes()
259
+ hashes[rel] = _sha256(data)
260
+ _add(tar, f"{PREFIX}/{rel}", data)
261
+ manifest = {
262
+ "forge": self.domain.name,
263
+ "created": moment.strftime("%Y-%m-%dT%H:%M:%SZ"),
264
+ "events": events,
265
+ "tip": tip,
266
+ "files": hashes,
267
+ }
268
+ _add(tar, MANIFEST, json.dumps(manifest, indent=1, sort_keys=True).encode())
269
+
270
+ # ------------------------------------------------------------ restore
271
+
272
+ def restore(self, archive: Path, identity_file: Path) -> RestoreResult:
273
+ """Decrypt ``archive`` into this layout's state folder, which must not exist."""
274
+ who = _require_operator(self.identity, "restores backups")
275
+ state = self.layout.state
276
+ if state.exists():
277
+ raise ForgeError(
278
+ ExitCode.REFUSED,
279
+ "already_initialized",
280
+ f"{state} exists; move it aside before restoring over it",
281
+ )
282
+ archive, identity_file = archive.expanduser(), identity_file.expanduser()
283
+ for path, what in ((archive, "archive"), (identity_file, "identity")):
284
+ if not path.is_file():
285
+ raise ForgeError(ExitCode.NOT_FOUND, f"{what}_missing", f"{path} does not exist")
286
+ age = find_age()
287
+ work = Path(tempfile.mkdtemp(dir=self.layout.root, prefix=f".{state.name}.restore-"))
288
+ try:
289
+ manifest = self._decrypt(age, archive, identity_file, work)
290
+ staged = Layout(root=self.layout.root, state=work / PREFIX)
291
+ self._check(manifest, staged)
292
+ os.rename(staged.state, state)
293
+ finally:
294
+ shutil.rmtree(work, ignore_errors=True)
295
+ ensure_gitignored(self.layout.root, self.domain)
296
+ self.store.append(
297
+ "restored",
298
+ actor=who.role,
299
+ session=who.session,
300
+ data={
301
+ "archive": archive.name,
302
+ "created": manifest["created"],
303
+ "events": manifest["events"],
304
+ "tip": manifest["tip"],
305
+ },
306
+ )
307
+ return RestoreResult(
308
+ state,
309
+ archive,
310
+ str(manifest["created"]),
311
+ int(manifest["events"]),
312
+ len(manifest["files"]),
313
+ )
314
+
315
+ def _decrypt(self, age: str, archive: Path, identity: Path, work: Path) -> dict[str, Any]:
316
+ args = [age, "--decrypt", "--identity", str(identity), str(archive)]
317
+ proc = subprocess.Popen( # noqa: S603 - fixed arguments, age from PATH
318
+ args, stdout=subprocess.PIPE, stderr=subprocess.PIPE
319
+ ) # nosec B603
320
+ if proc.stdout is None: # pragma: no cover - stdout=PIPE above
321
+ raise ForgeError(ExitCode.INTERNAL, "age_failed", "no pipe from age")
322
+ manifest: dict[str, Any] | None = None
323
+ try:
324
+ with tarfile.open(fileobj=proc.stdout, mode="r|gz") as tar:
325
+ for member in tar:
326
+ if member.name == MANIFEST and member.isfile():
327
+ manifest = json.loads(_read(tar, member))
328
+ continue
329
+ _extract(tar, member, work)
330
+ except (tarfile.TarError, EOFError, OSError, ValueError) as exc:
331
+ proc.kill()
332
+ stderr = proc.stderr.read() if proc.stderr else b""
333
+ proc.wait()
334
+ detail = _first_line(stderr) if stderr.strip() else str(exc)
335
+ raise ForgeError(ExitCode.DATA, "backup_unreadable", f"{archive}: {detail}") from exc
336
+ finally:
337
+ proc.stdout.close()
338
+ stderr = proc.stderr.read() if proc.stderr else b""
339
+ if proc.wait() != 0:
340
+ raise ForgeError(
341
+ ExitCode.DATA, "backup_unreadable", f"{archive}: {_first_line(stderr)}"
342
+ )
343
+ if manifest is None:
344
+ raise ForgeError(ExitCode.DATA, "backup_invalid", f"{archive} has no {MANIFEST}")
345
+ return manifest
346
+
347
+ def _check(self, manifest: Mapping[str, Any], staged: Layout) -> None:
348
+ def bad(detail: str) -> ForgeError:
349
+ return ForgeError(ExitCode.DATA, "backup_invalid", detail)
350
+
351
+ if manifest.get("forge") != self.domain.name:
352
+ raise bad(
353
+ f"the backup is of a {manifest.get('forge')!r} project, not {self.domain.name}"
354
+ )
355
+ files = manifest.get("files")
356
+ if not isinstance(files, dict):
357
+ raise bad(f"{MANIFEST} has no file list")
358
+ found = (
359
+ {
360
+ p.relative_to(staged.state).as_posix(): p
361
+ for p in staged.state.rglob("*")
362
+ if p.is_file()
363
+ }
364
+ if staged.state.is_dir()
365
+ else {}
366
+ )
367
+ if set(found) != set(files):
368
+ extra = sorted(set(found) ^ set(files))
369
+ raise bad(f"files do not match {MANIFEST}: {', '.join(extra[:5])}")
370
+ for rel, path in found.items():
371
+ if _sha256(path.read_bytes()) != files[rel]:
372
+ raise bad(f"{rel} does not match its recorded hash")
373
+ result = EventStore(staged, self.domain).verify()
374
+ if not result.ok:
375
+ raise bad(f"event log line {result.line}: {result.reason}")
376
+ if (result.events, EventStore(staged, self.domain).tip()[1]) != (
377
+ manifest.get("events"),
378
+ manifest.get("tip"),
379
+ ):
380
+ raise bad("the event log does not end where the backup recorded")
381
+
382
+
383
+ def _add(tar: tarfile.TarFile, name: str, data: bytes) -> None:
384
+ info = tarfile.TarInfo(name)
385
+ info.size = len(data)
386
+ info.mode = 0o600
387
+ tar.addfile(info, io.BytesIO(data))
388
+
389
+
390
+ def _read(tar: tarfile.TarFile, member: tarfile.TarInfo) -> bytes:
391
+ handle: IO[bytes] | None = tar.extractfile(member)
392
+ if handle is None: # pragma: no cover - isfile() was checked
393
+ raise ValueError(f"{member.name} has no data")
394
+ return handle.read()
395
+
396
+
397
+ def _extract(tar: tarfile.TarFile, member: tarfile.TarInfo, work: Path) -> None:
398
+ """Write one regular file under ``work/state``; anything else is refused."""
399
+ name = PurePosixPath(member.name)
400
+ if (
401
+ not member.isfile()
402
+ or name.is_absolute()
403
+ or ".." in name.parts
404
+ or name.parts[:1] != (PREFIX,)
405
+ or len(name.parts) < 2
406
+ ):
407
+ raise ValueError(f"unexpected entry {member.name!r}")
408
+ target = work.joinpath(*name.parts)
409
+ target.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
410
+ fd = os.open(target, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
411
+ with os.fdopen(fd, "wb") as out:
412
+ out.write(_read(tar, member))
413
+
414
+
415
+ def _first_line(stderr: bytes) -> str:
416
+ text = stderr.decode("utf-8", "replace").strip()
417
+ return text.splitlines()[0] if text else "age failed"
@@ -0,0 +1,206 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ """Strict, domain-extensible configuration (CORE.md §3) and project set-up."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import json
7
+ import shutil
8
+ import subprocess # nosec B404
9
+ from collections.abc import Mapping
10
+ from dataclasses import dataclass
11
+ from pathlib import Path
12
+ from typing import Any
13
+
14
+ import yaml
15
+
16
+ from .domain import Domain
17
+ from .errors import ExitCode, ForgeError
18
+ from .paths import Layout
19
+ from .schema import Field, validate
20
+ from .upgrade import upgrade
21
+ from .versions import CONFIG_SCHEMA_VERSION
22
+ from .workflow import OVERRIDES_SCHEMA, apply_overrides
23
+
24
+ AUTONOMY = ("supervised", "gated", "unattended")
25
+
26
+ CORE_SCHEMA: Mapping[str, Field] = {
27
+ "schema": Field("int", required=True, minimum=1),
28
+ "project": Field("str", required=True),
29
+ "autonomy": Field("enum", default="gated", choices=AUTONOMY),
30
+ "limits": Field(
31
+ "section",
32
+ children={
33
+ "build_attempts": Field("int", default=5, minimum=1),
34
+ "verify_cycles": Field("int", default=3, minimum=1),
35
+ "tokens_per_item": Field("int", default=400_000, minimum=1),
36
+ },
37
+ ),
38
+ "models": Field("map", default={}, item=Field("str")),
39
+ "messaging": Field(
40
+ "section",
41
+ children={
42
+ "pairs_remove": Field("list", default=[], item=Field("str")),
43
+ "urgent_escalate_after": Field("duration", default="2h"),
44
+ },
45
+ ),
46
+ "notify": Field(
47
+ "section",
48
+ children={
49
+ "adapters": Field("map", default={}, item=Field("map", item=Field("str"))),
50
+ "digest": Field("str", default=None),
51
+ "quiet_hours": Field("str", default=None),
52
+ "desk_only": Field("list", default=[], item=Field("str")),
53
+ },
54
+ ),
55
+ "workflows": OVERRIDES_SCHEMA,
56
+ "forge": Field(
57
+ "section",
58
+ children={
59
+ "kind": Field("enum", default="none", choices=("none", "github", "forgejo")),
60
+ "repo": Field("str", default=None),
61
+ "mode": Field("enum", default="push", choices=("push", "push+intake")),
62
+ "sanitize": Field("str", default="none"),
63
+ },
64
+ ),
65
+ "backup": Field(
66
+ "section",
67
+ children={
68
+ "recipients": Field("list", default=[], item=Field("str")),
69
+ "dir": Field("str", default=None),
70
+ },
71
+ ),
72
+ }
73
+
74
+
75
+ @dataclass(frozen=True)
76
+ class Config:
77
+ """A validated configuration: core keys plus the domain's keys."""
78
+
79
+ data: Mapping[str, Any]
80
+ path: Path
81
+
82
+ def __getitem__(self, key: str) -> Any:
83
+ return self.data[key]
84
+
85
+
86
+ def schema_for(domain: Domain) -> Field:
87
+ """The full schema: core keys plus the domain's. A domain may not redefine a core key."""
88
+ clash = sorted(set(CORE_SCHEMA) & set(domain.config_schema))
89
+ if clash:
90
+ raise ValueError(f"domain {domain.name!r} redefines core config keys: {clash}")
91
+ return Field("section", children={**CORE_SCHEMA, **domain.config_schema})
92
+
93
+
94
+ def parse_config(text: str, domain: Domain, path: Path) -> Config:
95
+ """Validate config text. Unknown keys and wrong types exit 5 (DATA)."""
96
+ try:
97
+ raw = yaml.safe_load(text)
98
+ except yaml.YAMLError as exc:
99
+ raise ForgeError(ExitCode.DATA, "config_parse", f"{path}: {exc}") from exc
100
+ if raw is None:
101
+ raw = {}
102
+ raw = upgrade("config", raw, domain, str(path))
103
+ data = validate(raw, schema_for(domain), "")
104
+ if data["schema"] > CONFIG_SCHEMA_VERSION:
105
+ raise ForgeError(
106
+ ExitCode.DATA,
107
+ "config_schema_newer",
108
+ f"{path}: schema {data['schema']} is newer than this version supports "
109
+ f"({CONFIG_SCHEMA_VERSION}); upgrade {domain.name}",
110
+ )
111
+ if data["workflows"]:
112
+ apply_overrides(domain.workflows, data["workflows"], domain.all_checks, domain)
113
+ try:
114
+ domain.check_desk_only(data["notify"]["desk_only"])
115
+ except ValueError as exc:
116
+ raise ForgeError(ExitCode.DATA, "config_invalid", f"{path}: notify.{exc}") from exc
117
+ try:
118
+ domain.check_pairs_remove(data["messaging"]["pairs_remove"])
119
+ except ValueError as exc:
120
+ raise ForgeError(ExitCode.DATA, "config_invalid", f"{path}: messaging.{exc}") from exc
121
+ return Config(data=data, path=path)
122
+
123
+
124
+ def load_config(layout: Layout, domain: Domain) -> Config:
125
+ """Load ``<state>/config.yaml``."""
126
+ try:
127
+ text = layout.config.read_text(encoding="utf-8")
128
+ except FileNotFoundError as exc:
129
+ raise ForgeError(
130
+ ExitCode.NOT_FOUND, "config_missing", f"{layout.config} does not exist"
131
+ ) from exc
132
+ return parse_config(text, domain, layout.config)
133
+
134
+
135
+ def default_config_text(domain: Domain, project: str) -> str:
136
+ """The config written by ``init``: core essentials plus the domain's defaults."""
137
+ lines = [
138
+ f"# {domain.title} configuration. Unknown keys are errors.",
139
+ f"schema: {CONFIG_SCHEMA_VERSION}",
140
+ f"project: {json.dumps(project, ensure_ascii=False)}", # JSON strings are valid YAML
141
+ "autonomy: gated",
142
+ ]
143
+ text = "\n".join(lines) + "\n"
144
+ if domain.default_config:
145
+ text += domain.default_config.rstrip("\n") + "\n"
146
+ return text
147
+
148
+
149
+ def init_project(root: Path, domain: Domain, project: str | None = None) -> Layout:
150
+ """Create the state folder, its config and event log, and the .gitignore entry.
151
+
152
+ Refuses (exit 2) if the state folder already exists.
153
+ """
154
+ layout = Layout.at(root, domain)
155
+ if not layout.root.is_dir():
156
+ raise ForgeError(ExitCode.NOT_FOUND, "root_missing", f"{layout.root} does not exist")
157
+ if layout.state.exists():
158
+ raise ForgeError(ExitCode.REFUSED, "already_initialized", f"{layout.state} already exists")
159
+ name = project or layout.root.name
160
+ text = default_config_text(domain, name)
161
+ parse_config(text, domain, layout.config) # the default must always validate
162
+ layout.state.mkdir(mode=0o700)
163
+ layout.config.write_text(text, encoding="utf-8")
164
+ layout.events.touch(mode=0o600)
165
+ ensure_gitignored(layout.root, domain)
166
+ init_state_repo(layout)
167
+ return layout
168
+
169
+
170
+ #: Kept out of the state folder's own git history: the lock and caches.
171
+ STATE_GITIGNORE = ".lock\n.index.sqlite\n.*.tmp\n"
172
+
173
+
174
+ def init_state_repo(layout: Layout) -> bool:
175
+ """Make the state folder a git repository of its own. False if git is not installed.
176
+
177
+ History, diffs and an encrypted private remote come from this repository; it
178
+ never shares history with the product repository, which ignores the folder.
179
+ """
180
+ git = shutil.which("git")
181
+ if git is None:
182
+ return False
183
+ (layout.state / ".gitignore").write_text(STATE_GITIGNORE, encoding="utf-8")
184
+ try:
185
+ subprocess.run( # noqa: S603 - fixed arguments, git from PATH
186
+ [git, "init", "--quiet", str(layout.state)],
187
+ check=True,
188
+ capture_output=True,
189
+ ) # nosec B603
190
+ except (OSError, subprocess.CalledProcessError):
191
+ return False
192
+ return True
193
+
194
+
195
+ def ensure_gitignored(root: Path, domain: Domain) -> bool:
196
+ """Make sure ``.gitignore`` ignores the state folder. Returns True if it was added."""
197
+ entry = f"/{domain.state_dir}/"
198
+ gitignore = root / ".gitignore"
199
+ existing = gitignore.read_text(encoding="utf-8") if gitignore.exists() else ""
200
+ accepted = {entry, f"{domain.state_dir}/", domain.state_dir, f"/{domain.state_dir}"}
201
+ if any(line.strip() in accepted for line in existing.splitlines()):
202
+ return False
203
+ prefix = "" if not existing or existing.endswith("\n") else "\n"
204
+ note = f"# {domain.title} state is private and never committed\n"
205
+ gitignore.write_text(existing + prefix + note + entry + "\n", encoding="utf-8")
206
+ return True