teaimforge 0.19.0__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.
teaimforge/config.py ADDED
@@ -0,0 +1,207 @@
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
+ "state_file_mb": Field("int", default=5, minimum=1),
37
+ },
38
+ ),
39
+ "models": Field("map", default={}, item=Field("str")),
40
+ "messaging": Field(
41
+ "section",
42
+ children={
43
+ "pairs_remove": Field("list", default=[], item=Field("str")),
44
+ "urgent_escalate_after": Field("duration", default="2h"),
45
+ },
46
+ ),
47
+ "notify": Field(
48
+ "section",
49
+ children={
50
+ "adapters": Field("map", default={}, item=Field("map", item=Field("str"))),
51
+ "digest": Field("str", default=None),
52
+ "quiet_hours": Field("str", default=None),
53
+ "desk_only": Field("list", default=[], item=Field("str")),
54
+ },
55
+ ),
56
+ "workflows": OVERRIDES_SCHEMA,
57
+ "publish": Field(
58
+ "section",
59
+ children={
60
+ "kind": Field("enum", default="none", choices=("none", "github", "forgejo")),
61
+ "repo": Field("str", default=None),
62
+ "mode": Field("enum", default="push", choices=("push", "push+intake")),
63
+ "sanitize": Field("str", default="none"),
64
+ },
65
+ ),
66
+ "backup": Field(
67
+ "section",
68
+ children={
69
+ "recipients": Field("list", default=[], item=Field("str")),
70
+ "dir": Field("str", default=None),
71
+ },
72
+ ),
73
+ }
74
+
75
+
76
+ @dataclass(frozen=True)
77
+ class Config:
78
+ """A validated configuration: core keys plus the domain's keys."""
79
+
80
+ data: Mapping[str, Any]
81
+ path: Path
82
+
83
+ def __getitem__(self, key: str) -> Any:
84
+ return self.data[key]
85
+
86
+
87
+ def schema_for(domain: Domain) -> Field:
88
+ """The full schema: core keys plus the domain's. A domain may not redefine a core key."""
89
+ clash = sorted(set(CORE_SCHEMA) & set(domain.config_schema))
90
+ if clash:
91
+ raise ValueError(f"domain {domain.name!r} redefines core config keys: {clash}")
92
+ return Field("section", children={**CORE_SCHEMA, **domain.config_schema})
93
+
94
+
95
+ def parse_config(text: str, domain: Domain, path: Path) -> Config:
96
+ """Validate config text. Unknown keys and wrong types exit 5 (DATA)."""
97
+ try:
98
+ raw = yaml.safe_load(text)
99
+ except yaml.YAMLError as exc:
100
+ raise ForgeError(ExitCode.DATA, "config_parse", f"{path}: {exc}") from exc
101
+ if raw is None:
102
+ raw = {}
103
+ raw = upgrade("config", raw, domain, str(path))
104
+ data = validate(raw, schema_for(domain), "")
105
+ if data["schema"] > CONFIG_SCHEMA_VERSION:
106
+ raise ForgeError(
107
+ ExitCode.DATA,
108
+ "config_schema_newer",
109
+ f"{path}: schema {data['schema']} is newer than this version supports "
110
+ f"({CONFIG_SCHEMA_VERSION}); upgrade {domain.name}",
111
+ )
112
+ if data["workflows"]:
113
+ apply_overrides(domain.workflows, data["workflows"], domain.all_checks, domain)
114
+ try:
115
+ domain.check_desk_only(data["notify"]["desk_only"])
116
+ except ValueError as exc:
117
+ raise ForgeError(ExitCode.DATA, "config_invalid", f"{path}: notify.{exc}") from exc
118
+ try:
119
+ domain.check_pairs_remove(data["messaging"]["pairs_remove"])
120
+ except ValueError as exc:
121
+ raise ForgeError(ExitCode.DATA, "config_invalid", f"{path}: messaging.{exc}") from exc
122
+ return Config(data=data, path=path)
123
+
124
+
125
+ def load_config(layout: Layout, domain: Domain) -> Config:
126
+ """Load ``<state>/config.yaml``."""
127
+ try:
128
+ text = layout.config.read_text(encoding="utf-8")
129
+ except FileNotFoundError as exc:
130
+ raise ForgeError(
131
+ ExitCode.NOT_FOUND, "config_missing", f"{layout.config} does not exist"
132
+ ) from exc
133
+ return parse_config(text, domain, layout.config)
134
+
135
+
136
+ def default_config_text(domain: Domain, project: str) -> str:
137
+ """The config written by ``init``: core essentials plus the domain's defaults."""
138
+ lines = [
139
+ f"# {domain.title} configuration. Unknown keys are errors.",
140
+ f"schema: {CONFIG_SCHEMA_VERSION}",
141
+ f"project: {json.dumps(project, ensure_ascii=False)}", # JSON strings are valid YAML
142
+ "autonomy: gated",
143
+ ]
144
+ text = "\n".join(lines) + "\n"
145
+ if domain.default_config:
146
+ text += domain.default_config.rstrip("\n") + "\n"
147
+ return text
148
+
149
+
150
+ def init_project(root: Path, domain: Domain, project: str | None = None) -> Layout:
151
+ """Create the state folder, its config and event log, and the .gitignore entry.
152
+
153
+ Refuses (exit 2) if the state folder already exists.
154
+ """
155
+ layout = Layout.at(root, domain)
156
+ if not layout.root.is_dir():
157
+ raise ForgeError(ExitCode.NOT_FOUND, "root_missing", f"{layout.root} does not exist")
158
+ if layout.state.exists():
159
+ raise ForgeError(ExitCode.REFUSED, "already_initialized", f"{layout.state} already exists")
160
+ name = project or layout.root.name
161
+ text = default_config_text(domain, name)
162
+ parse_config(text, domain, layout.config) # the default must always validate
163
+ layout.state.mkdir(mode=0o700)
164
+ layout.config.write_text(text, encoding="utf-8")
165
+ layout.events.touch(mode=0o600)
166
+ ensure_gitignored(layout.root, domain)
167
+ init_state_repo(layout)
168
+ return layout
169
+
170
+
171
+ #: Kept out of the state folder's own git history: the lock and caches.
172
+ STATE_GITIGNORE = ".lock\n.index.sqlite\n.*.tmp\n"
173
+
174
+
175
+ def init_state_repo(layout: Layout) -> bool:
176
+ """Make the state folder a git repository of its own. False if git is not installed.
177
+
178
+ History, diffs and an encrypted private remote come from this repository; it
179
+ never shares history with the product repository, which ignores the folder.
180
+ """
181
+ git = shutil.which("git")
182
+ if git is None:
183
+ return False
184
+ (layout.state / ".gitignore").write_text(STATE_GITIGNORE, encoding="utf-8")
185
+ try:
186
+ subprocess.run( # noqa: S603 - fixed arguments, git from PATH
187
+ [git, "init", "--quiet", str(layout.state)],
188
+ check=True,
189
+ capture_output=True,
190
+ ) # nosec B603
191
+ except (OSError, subprocess.CalledProcessError):
192
+ return False
193
+ return True
194
+
195
+
196
+ def ensure_gitignored(root: Path, domain: Domain) -> bool:
197
+ """Make sure ``.gitignore`` ignores the state folder. Returns True if it was added."""
198
+ entry = f"/{domain.state_dir}/"
199
+ gitignore = root / ".gitignore"
200
+ existing = gitignore.read_text(encoding="utf-8") if gitignore.exists() else ""
201
+ accepted = {entry, f"{domain.state_dir}/", domain.state_dir, f"/{domain.state_dir}"}
202
+ if any(line.strip() in accepted for line in existing.splitlines()):
203
+ return False
204
+ prefix = "" if not existing or existing.endswith("\n") else "\n"
205
+ note = f"# {domain.title} state is private and never committed\n"
206
+ gitignore.write_text(existing + prefix + note + entry + "\n", encoding="utf-8")
207
+ return True