yaddd-agents 0.2.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.
- yaddd_agents/__init__.py +5 -0
- yaddd_agents/cli.py +140 -0
- yaddd_agents/discover.py +318 -0
- yaddd_agents/lock.py +40 -0
- yaddd_agents/model.py +147 -0
- yaddd_agents/py.typed +0 -0
- yaddd_agents/render.py +196 -0
- yaddd_agents/resolve.py +232 -0
- yaddd_agents/resources/base/manifest.toml +94 -0
- yaddd_agents/resources/base/rules/application.md +39 -0
- yaddd_agents/resources/base/rules/core.md +71 -0
- yaddd_agents/resources/base/rules/domain.md +28 -0
- yaddd_agents/resources/base/rules/infrastructure.md +19 -0
- yaddd_agents/resources/base/rules/presentation.md +29 -0
- yaddd_agents/resources/base/rules/testing.md +19 -0
- yaddd_agents/resources/base/rules/tooling.md +13 -0
- yaddd_agents-0.2.0.dist-info/METADATA +59 -0
- yaddd_agents-0.2.0.dist-info/RECORD +20 -0
- yaddd_agents-0.2.0.dist-info/WHEEL +4 -0
- yaddd_agents-0.2.0.dist-info/entry_points.txt +2 -0
yaddd_agents/__init__.py
ADDED
yaddd_agents/cli.py
ADDED
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
"""Command-line entry point for yaddd-agents."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import json
|
|
7
|
+
import sys
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from typing import Any
|
|
10
|
+
|
|
11
|
+
from yaddd_agents import __version__
|
|
12
|
+
from yaddd_agents.discover import discover_packs, load_local_operations, load_project
|
|
13
|
+
from yaddd_agents.model import AgentsError, Project, Resolution
|
|
14
|
+
from yaddd_agents.render import check_outputs, expected_outputs, write_outputs
|
|
15
|
+
from yaddd_agents.resolve import explain, pack_summary, resolve
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def _build_parser() -> argparse.ArgumentParser:
|
|
19
|
+
"""Build the command-line parser."""
|
|
20
|
+
parser = argparse.ArgumentParser(prog="yaddd-agents", description="Generate layered AGENTS.md rules.")
|
|
21
|
+
parser.add_argument("--version", action="version", version=f"%(prog)s {__version__}")
|
|
22
|
+
parser.add_argument("--root", type=Path, default=None, help="Project root (default: nearest pyproject.toml).")
|
|
23
|
+
parser.add_argument(
|
|
24
|
+
"--workspace",
|
|
25
|
+
type=Path,
|
|
26
|
+
default=None,
|
|
27
|
+
help="Monorepo root used to discover editable extension packs.",
|
|
28
|
+
)
|
|
29
|
+
subparsers = parser.add_subparsers(dest="command", required=True)
|
|
30
|
+
|
|
31
|
+
subparsers.add_parser("init", help="Create .agents/, .yaddd/ and sync generated files.")
|
|
32
|
+
subparsers.add_parser("sync", help="Rebuild generated rules and configuration.")
|
|
33
|
+
subparsers.add_parser("check", help="Fail when generated files are stale.")
|
|
34
|
+
|
|
35
|
+
explain_parser = subparsers.add_parser("explain", help="Show where a rule comes from.")
|
|
36
|
+
explain_parser.add_argument("rule", help="Rule ID, for example IMPORTS_DOMAIN.")
|
|
37
|
+
explain_parser.add_argument("--json", action="store_true", help="Emit JSON.")
|
|
38
|
+
|
|
39
|
+
list_parser = subparsers.add_parser("list", help="List active packs and rules.")
|
|
40
|
+
list_parser.add_argument("--json", action="store_true", help="Emit JSON.")
|
|
41
|
+
return parser
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def main(argv: list[str] | None = None) -> int:
|
|
45
|
+
"""Run the CLI."""
|
|
46
|
+
parser = _build_parser()
|
|
47
|
+
args = parser.parse_args(argv)
|
|
48
|
+
try:
|
|
49
|
+
project = load_project(args.root)
|
|
50
|
+
workspace = args.workspace.resolve() if args.workspace is not None else None
|
|
51
|
+
if args.command == "init":
|
|
52
|
+
return _init(project, workspace)
|
|
53
|
+
if args.command == "sync":
|
|
54
|
+
return _sync(project, workspace)
|
|
55
|
+
if args.command == "check":
|
|
56
|
+
return _check(project, workspace)
|
|
57
|
+
resolution = _resolve(project, workspace)
|
|
58
|
+
if args.command == "explain":
|
|
59
|
+
return _explain(resolution, args.rule, args.json)
|
|
60
|
+
if args.command == "list":
|
|
61
|
+
return _list(resolution, args.json)
|
|
62
|
+
except AgentsError as exc:
|
|
63
|
+
print(f"error: {exc}", file=sys.stderr)
|
|
64
|
+
return 2
|
|
65
|
+
parser.error(f"unknown command: {args.command}")
|
|
66
|
+
return 2
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def _resolve(project: Project, workspace: Path | None) -> Resolution:
|
|
70
|
+
"""Discover packs and resolve every active rule."""
|
|
71
|
+
packs = discover_packs(project, workspace)
|
|
72
|
+
return resolve(project, packs, load_local_operations(project))
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def _init(project: Project, workspace: Path | None) -> int:
|
|
76
|
+
"""Create directories and sync generated content."""
|
|
77
|
+
project.local_rules_dir.mkdir(parents=True, exist_ok=True)
|
|
78
|
+
keep = project.local_rules_dir / ".gitkeep"
|
|
79
|
+
if not keep.exists():
|
|
80
|
+
keep.write_text("", encoding="utf-8")
|
|
81
|
+
return _sync(project, workspace)
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _sync(project: Project, workspace: Path | None) -> int:
|
|
85
|
+
"""Render and write every generated file."""
|
|
86
|
+
resolution = _resolve(project, workspace)
|
|
87
|
+
outputs = expected_outputs(project, resolution)
|
|
88
|
+
write_outputs(project, outputs)
|
|
89
|
+
print(f"Synced {len(outputs)} files from {len(resolution.packs)} packs.")
|
|
90
|
+
return 0
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def _check(project: Project, workspace: Path | None) -> int:
|
|
94
|
+
"""Verify that generated files match the active packs."""
|
|
95
|
+
resolution = _resolve(project, workspace)
|
|
96
|
+
problems = check_outputs(project, expected_outputs(project, resolution))
|
|
97
|
+
if problems:
|
|
98
|
+
for problem in problems:
|
|
99
|
+
print(problem, file=sys.stderr)
|
|
100
|
+
print("Run `yaddd-agents sync` to update generated files.", file=sys.stderr)
|
|
101
|
+
return 1
|
|
102
|
+
print(f"Agent rules are up to date ({len(resolution.rules)} rules).")
|
|
103
|
+
return 0
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def _explain(resolution: Resolution, rule_id: str, as_json: bool) -> int:
|
|
107
|
+
"""Print one resolved rule."""
|
|
108
|
+
payload = explain(resolution, rule_id)
|
|
109
|
+
if as_json:
|
|
110
|
+
print(json.dumps(payload, indent=2, sort_keys=True))
|
|
111
|
+
return 0
|
|
112
|
+
print(f"{payload['id']} ({payload['layer']}, {payload['kind']})")
|
|
113
|
+
print(f"enabled: {'yes' if payload['enabled'] else 'no'}")
|
|
114
|
+
print(f"allow first-party: {', '.join(payload['effective_first_party']) or '-'}")
|
|
115
|
+
print(f"allow third-party: {', '.join(payload['effective_third_party']) or '-'}")
|
|
116
|
+
print(f"deny first-party: {', '.join(payload['deny_first_party']) or '-'}")
|
|
117
|
+
print(f"deny third-party: {', '.join(payload['deny_third_party']) or '-'}")
|
|
118
|
+
print(f"sources: {', '.join(payload['sources']) or '-'}")
|
|
119
|
+
print(f"docs: {', '.join(payload['docs']) or '-'}")
|
|
120
|
+
return 0
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def _list(resolution: Resolution, as_json: bool) -> int:
|
|
124
|
+
"""Print active packs and rules."""
|
|
125
|
+
payload: dict[str, Any] = {
|
|
126
|
+
"packs": pack_summary(resolution.packs),
|
|
127
|
+
"rules": {rule_id: explain(resolution, rule_id) for rule_id in sorted(resolution.rules)},
|
|
128
|
+
}
|
|
129
|
+
if as_json:
|
|
130
|
+
print(json.dumps(payload, indent=2, sort_keys=True))
|
|
131
|
+
return 0
|
|
132
|
+
for pack in payload["packs"]:
|
|
133
|
+
print(f"{pack['name']} {pack['version']}")
|
|
134
|
+
for rule_id in sorted(resolution.rules):
|
|
135
|
+
print(f" {rule_id}")
|
|
136
|
+
return 0
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
if __name__ == "__main__":
|
|
140
|
+
sys.exit(main())
|
yaddd_agents/discover.py
ADDED
|
@@ -0,0 +1,318 @@
|
|
|
1
|
+
"""Project and pack discovery."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import importlib.metadata
|
|
6
|
+
import importlib.util
|
|
7
|
+
import re
|
|
8
|
+
import tomllib
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
from typing import Any, cast
|
|
11
|
+
|
|
12
|
+
from yaddd_agents.model import (
|
|
13
|
+
SCHEMA_VERSION,
|
|
14
|
+
DiscoveryError,
|
|
15
|
+
ManifestError,
|
|
16
|
+
Operation,
|
|
17
|
+
Pack,
|
|
18
|
+
Project,
|
|
19
|
+
Rule,
|
|
20
|
+
normalize_name,
|
|
21
|
+
)
|
|
22
|
+
|
|
23
|
+
_REQUIREMENT_NAME = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_.-]*")
|
|
24
|
+
_SKIP_DEPENDENCIES = frozenset({"yaddd", "yaddd-agents", "yaddd-linter"})
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def find_project_root(start: Path) -> Path:
|
|
28
|
+
"""Walk up from ``start`` until a ``pyproject.toml`` is found."""
|
|
29
|
+
current = start.resolve()
|
|
30
|
+
for candidate in [current, *current.parents]:
|
|
31
|
+
if (candidate / "pyproject.toml").is_file():
|
|
32
|
+
return candidate
|
|
33
|
+
raise DiscoveryError(f"No pyproject.toml found above {start}")
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def load_project(root: Path | None = None) -> Project:
|
|
37
|
+
"""Load the project description needed for pack discovery."""
|
|
38
|
+
project_root = find_project_root(root or Path.cwd())
|
|
39
|
+
pyproject_path = project_root / "pyproject.toml"
|
|
40
|
+
try:
|
|
41
|
+
raw = tomllib.loads(pyproject_path.read_text(encoding="utf-8"))
|
|
42
|
+
except (OSError, tomllib.TOMLDecodeError) as exc:
|
|
43
|
+
raise DiscoveryError(f"Cannot read {pyproject_path}: {exc}") from exc
|
|
44
|
+
|
|
45
|
+
dependencies = _collect_dependencies(raw)
|
|
46
|
+
tool = cast(dict[str, Any], raw.get("tool", {}))
|
|
47
|
+
agents = cast(dict[str, Any], tool.get("yaddd", {}).get("agents", {}))
|
|
48
|
+
extensions = cast(dict[str, Any], agents.get("extensions", {}))
|
|
49
|
+
extension_paths = {str(name): str(path) for name, path in extensions.items()}
|
|
50
|
+
return Project(
|
|
51
|
+
root=project_root,
|
|
52
|
+
pyproject_path=pyproject_path,
|
|
53
|
+
dependencies=dependencies,
|
|
54
|
+
extension_paths=extension_paths,
|
|
55
|
+
)
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _collect_dependencies(raw: dict[str, Any]) -> dict[str, str]:
|
|
59
|
+
"""Collect runtime and development dependencies from pyproject.toml."""
|
|
60
|
+
collected: dict[str, str] = {}
|
|
61
|
+
project = cast(dict[str, Any], raw.get("project", {}))
|
|
62
|
+
_add_requirements(collected, project.get("dependencies", []))
|
|
63
|
+
optional = cast(dict[str, Any], project.get("optional-dependencies", {}))
|
|
64
|
+
for requirements in optional.values():
|
|
65
|
+
_add_requirements(collected, requirements)
|
|
66
|
+
|
|
67
|
+
groups = cast(dict[str, Any], raw.get("dependency-groups", {}))
|
|
68
|
+
_collect_groups(collected, groups, set())
|
|
69
|
+
return collected
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def _collect_groups(collected: dict[str, str], groups: dict[str, Any], seen: set[str]) -> None:
|
|
73
|
+
"""Collect dependency-group entries, following ``include-group``."""
|
|
74
|
+
for name, entries in groups.items():
|
|
75
|
+
if name in seen:
|
|
76
|
+
continue
|
|
77
|
+
seen.add(name)
|
|
78
|
+
if not isinstance(entries, list):
|
|
79
|
+
continue
|
|
80
|
+
for entry in cast(list[Any], entries):
|
|
81
|
+
if isinstance(entry, str):
|
|
82
|
+
_add_requirements(collected, [entry])
|
|
83
|
+
elif isinstance(entry, dict):
|
|
84
|
+
data = cast(dict[str, object], entry)
|
|
85
|
+
if "include-group" not in data:
|
|
86
|
+
continue
|
|
87
|
+
included = str(data["include-group"])
|
|
88
|
+
nested = groups.get(included)
|
|
89
|
+
if isinstance(nested, list):
|
|
90
|
+
_collect_groups(collected, {included: nested}, seen)
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def _add_requirements(collected: dict[str, str], requirements: Any) -> None:
|
|
94
|
+
"""Add requirement strings to a normalized name -> requirement mapping."""
|
|
95
|
+
if not isinstance(requirements, list):
|
|
96
|
+
return
|
|
97
|
+
for requirement in cast(list[Any], requirements):
|
|
98
|
+
if not isinstance(requirement, str):
|
|
99
|
+
continue
|
|
100
|
+
match = _REQUIREMENT_NAME.match(requirement.strip())
|
|
101
|
+
if match is None:
|
|
102
|
+
continue
|
|
103
|
+
name = normalize_name(match.group(0))
|
|
104
|
+
collected.setdefault(name, requirement.strip())
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def load_pack(manifest_path: Path, source: str = "") -> Pack:
|
|
108
|
+
"""Load one pack manifest and its Markdown resources."""
|
|
109
|
+
try:
|
|
110
|
+
raw = tomllib.loads(manifest_path.read_text(encoding="utf-8"))
|
|
111
|
+
except (OSError, tomllib.TOMLDecodeError) as exc:
|
|
112
|
+
raise ManifestError(f"Cannot read {manifest_path}: {exc}") from exc
|
|
113
|
+
|
|
114
|
+
schema = raw.get("schema")
|
|
115
|
+
if schema != SCHEMA_VERSION:
|
|
116
|
+
raise ManifestError(f"{manifest_path}: unsupported schema {schema!r}; expected {SCHEMA_VERSION}")
|
|
117
|
+
|
|
118
|
+
name = str(raw.get("name") or manifest_path.parent.parent.name)
|
|
119
|
+
version = str(raw.get("version") or "0.0.0")
|
|
120
|
+
core_doc = str(raw.get("core") or "")
|
|
121
|
+
docs = _load_docs(manifest_path.parent)
|
|
122
|
+
rules = _parse_rules(raw, manifest_path, docs)
|
|
123
|
+
operations = _parse_operations(raw, source or name)
|
|
124
|
+
return Pack(
|
|
125
|
+
name=name,
|
|
126
|
+
version=version,
|
|
127
|
+
manifest_path=manifest_path,
|
|
128
|
+
rules=tuple(rules),
|
|
129
|
+
operations=tuple(operations),
|
|
130
|
+
docs=docs,
|
|
131
|
+
core_doc=core_doc,
|
|
132
|
+
)
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def _load_docs(base_dir: Path) -> dict[str, str]:
|
|
136
|
+
"""Load every Markdown file below ``base_dir/rules``."""
|
|
137
|
+
rules_dir = base_dir / "rules"
|
|
138
|
+
if not rules_dir.is_dir():
|
|
139
|
+
return {}
|
|
140
|
+
docs: dict[str, str] = {}
|
|
141
|
+
for path in sorted(rules_dir.rglob("*.md")):
|
|
142
|
+
docs[path.relative_to(base_dir).as_posix()] = path.read_text(encoding="utf-8")
|
|
143
|
+
return docs
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def _parse_rules(raw: dict[str, Any], manifest_path: Path, docs: dict[str, str]) -> list[Rule]:
|
|
147
|
+
"""Parse the ``[rules.<ID>]`` tables."""
|
|
148
|
+
rules_raw = raw.get("rules", {})
|
|
149
|
+
if not isinstance(rules_raw, dict):
|
|
150
|
+
raise ManifestError(f"{manifest_path}: [rules] must be a table")
|
|
151
|
+
rules: list[Rule] = []
|
|
152
|
+
for rule_id, value in cast(dict[str, Any], rules_raw).items():
|
|
153
|
+
if not isinstance(value, dict):
|
|
154
|
+
raise ManifestError(f"{manifest_path}: rule {rule_id!r} must be a table")
|
|
155
|
+
data = cast(dict[str, Any], value)
|
|
156
|
+
layer = str(data.get("layer") or "")
|
|
157
|
+
if not layer:
|
|
158
|
+
raise ManifestError(f"{manifest_path}: rule {rule_id!r} has no layer")
|
|
159
|
+
doc = str(data.get("doc") or "")
|
|
160
|
+
if doc and doc not in docs:
|
|
161
|
+
raise ManifestError(f"{manifest_path}: rule {rule_id!r} references missing doc {doc!r}")
|
|
162
|
+
rules.append(
|
|
163
|
+
Rule(
|
|
164
|
+
id=rule_id,
|
|
165
|
+
layer=layer,
|
|
166
|
+
kind=str(data.get("kind") or "guidance"),
|
|
167
|
+
doc=doc,
|
|
168
|
+
allow_first_party=_string_set(data.get("allow_first_party")),
|
|
169
|
+
allow_third_party=_string_set(data.get("allow_third_party")),
|
|
170
|
+
deny_first_party=_string_set(data.get("deny_first_party")),
|
|
171
|
+
deny_third_party=_string_set(data.get("deny_third_party")),
|
|
172
|
+
enabled=bool(data.get("enabled", True)),
|
|
173
|
+
)
|
|
174
|
+
)
|
|
175
|
+
return rules
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
def _parse_operations(raw: dict[str, Any], source: str) -> list[Operation]:
|
|
179
|
+
"""Parse relax/restrict/replace/disable arrays."""
|
|
180
|
+
operations: list[Operation] = []
|
|
181
|
+
for kind, key in (
|
|
182
|
+
("relax", "relaxes"),
|
|
183
|
+
("restrict", "restricts"),
|
|
184
|
+
("replace", "replaces"),
|
|
185
|
+
("disable", "disables"),
|
|
186
|
+
):
|
|
187
|
+
entries = raw.get(key, [])
|
|
188
|
+
if not isinstance(entries, list):
|
|
189
|
+
raise ManifestError(f"{source}: {key} must be an array of tables")
|
|
190
|
+
for entry in cast(list[Any], entries):
|
|
191
|
+
if not isinstance(entry, dict):
|
|
192
|
+
raise ManifestError(f"{source}: {key} entries must be tables")
|
|
193
|
+
operations.append(_parse_operation(kind, cast(dict[str, Any], entry), source))
|
|
194
|
+
return operations
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def _parse_operation(kind: str, data: dict[str, Any], source: str) -> Operation:
|
|
198
|
+
"""Parse one operation table."""
|
|
199
|
+
rule = str(data.get("rule") or "")
|
|
200
|
+
reason = str(data.get("reason") or "")
|
|
201
|
+
if not rule:
|
|
202
|
+
raise ManifestError(f"{source}: {kind} operation has no rule")
|
|
203
|
+
if not reason:
|
|
204
|
+
raise ManifestError(f"{source}: {kind} operation for {rule!r} has no reason")
|
|
205
|
+
when = data.get("when", {})
|
|
206
|
+
if not isinstance(when, dict):
|
|
207
|
+
raise ManifestError(f"{source}: {kind} operation for {rule!r} has invalid when")
|
|
208
|
+
when_data = cast(dict[str, Any], when)
|
|
209
|
+
dependency = when_data.get("dependency")
|
|
210
|
+
specifier = when_data.get("specifier")
|
|
211
|
+
return Operation(
|
|
212
|
+
kind=kind,
|
|
213
|
+
rule=rule,
|
|
214
|
+
reason=reason,
|
|
215
|
+
allow_add=_string_set(data.get("allow_add")),
|
|
216
|
+
deny_add=_string_set(data.get("deny_add")),
|
|
217
|
+
allow_first_party=_optional_string_set(data, "allow_first_party"),
|
|
218
|
+
allow_third_party=_optional_string_set(data, "allow_third_party"),
|
|
219
|
+
deny_first_party=_optional_string_set(data, "deny_first_party"),
|
|
220
|
+
deny_third_party=_optional_string_set(data, "deny_third_party"),
|
|
221
|
+
when_dependency=normalize_name(str(dependency)) if dependency else None,
|
|
222
|
+
when_specifier=str(specifier) if specifier else None,
|
|
223
|
+
source=source,
|
|
224
|
+
)
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
def _string_set(value: Any) -> frozenset[str]:
|
|
228
|
+
"""Coerce a list of strings into a frozen set."""
|
|
229
|
+
if not isinstance(value, list):
|
|
230
|
+
return frozenset()
|
|
231
|
+
return frozenset(str(item) for item in cast(list[Any], value))
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
def _optional_string_set(data: dict[str, Any], key: str) -> frozenset[str] | None:
|
|
235
|
+
"""Return a frozen set for a key, or None when the key is absent."""
|
|
236
|
+
if key not in data:
|
|
237
|
+
return None
|
|
238
|
+
return _string_set(data.get(key))
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
def discover_packs(project: Project, workspace_root: Path | None = None) -> tuple[Pack, ...]:
|
|
242
|
+
"""Discover the base pack and every active extension pack."""
|
|
243
|
+
base_path = Path(__file__).resolve().parent / "resources" / "base" / "manifest.toml"
|
|
244
|
+
packs: list[Pack] = [load_pack(base_path, source="base")]
|
|
245
|
+
seen = {normalize_name(packs[0].name)}
|
|
246
|
+
|
|
247
|
+
for name, path in sorted(project.extension_paths.items()):
|
|
248
|
+
manifest = (project.root / path).resolve()
|
|
249
|
+
if not manifest.is_file():
|
|
250
|
+
raise DiscoveryError(f"Explicit extension {name!r} points to missing {manifest}")
|
|
251
|
+
pack = load_pack(manifest, source=f"explicit:{name}")
|
|
252
|
+
_append_pack(packs, seen, pack)
|
|
253
|
+
|
|
254
|
+
for dependency in sorted(project.dependencies):
|
|
255
|
+
if dependency in _SKIP_DEPENDENCIES or not dependency.startswith("yaddd-"):
|
|
256
|
+
continue
|
|
257
|
+
manifest = None
|
|
258
|
+
if workspace_root is not None:
|
|
259
|
+
manifest = _workspace_manifest(dependency, workspace_root)
|
|
260
|
+
if manifest is None:
|
|
261
|
+
manifest = _installed_manifest(dependency)
|
|
262
|
+
if manifest is None:
|
|
263
|
+
continue
|
|
264
|
+
pack = load_pack(manifest, source=f"dependency:{dependency}")
|
|
265
|
+
_append_pack(packs, seen, pack)
|
|
266
|
+
|
|
267
|
+
return tuple(packs)
|
|
268
|
+
|
|
269
|
+
|
|
270
|
+
def _append_pack(packs: list[Pack], seen: set[str], pack: Pack) -> None:
|
|
271
|
+
"""Append a pack unless one with the same normalized name is already loaded."""
|
|
272
|
+
key = normalize_name(pack.name)
|
|
273
|
+
if key in seen:
|
|
274
|
+
return
|
|
275
|
+
seen.add(key)
|
|
276
|
+
packs.append(pack)
|
|
277
|
+
|
|
278
|
+
|
|
279
|
+
def _workspace_manifest(name: str, workspace_root: Path) -> Path | None:
|
|
280
|
+
"""Find a pack manifest in a monorepo workspace."""
|
|
281
|
+
module = normalize_name(name).replace("-", "_")
|
|
282
|
+
matches = sorted(workspace_root.glob(f"packages/*/src/{module}/agents/manifest.toml"))
|
|
283
|
+
if matches:
|
|
284
|
+
return matches[0]
|
|
285
|
+
candidate = workspace_root / "packages" / name / "src" / module / "agents" / "manifest.toml"
|
|
286
|
+
return candidate if candidate.is_file() else None
|
|
287
|
+
|
|
288
|
+
|
|
289
|
+
def _installed_manifest(name: str) -> Path | None:
|
|
290
|
+
"""Find a pack manifest inside an installed or editable distribution."""
|
|
291
|
+
module = normalize_name(name).replace("-", "_")
|
|
292
|
+
try:
|
|
293
|
+
spec = importlib.util.find_spec(module)
|
|
294
|
+
except (ImportError, ValueError):
|
|
295
|
+
spec = None
|
|
296
|
+
if spec is not None and spec.submodule_search_locations:
|
|
297
|
+
candidate = Path(next(iter(spec.submodule_search_locations))) / "agents" / "manifest.toml"
|
|
298
|
+
if candidate.is_file():
|
|
299
|
+
return candidate
|
|
300
|
+
|
|
301
|
+
try:
|
|
302
|
+
distribution = importlib.metadata.distribution(name)
|
|
303
|
+
except importlib.metadata.PackageNotFoundError:
|
|
304
|
+
return None
|
|
305
|
+
candidate = cast(Path, distribution.locate_file(f"{module}/agents/manifest.toml"))
|
|
306
|
+
return candidate if candidate.is_file() else None
|
|
307
|
+
|
|
308
|
+
|
|
309
|
+
def load_local_operations(project: Project) -> tuple[Operation, ...]:
|
|
310
|
+
"""Load hand-written local overrides, if any."""
|
|
311
|
+
path = project.overrides_path
|
|
312
|
+
if not path.is_file():
|
|
313
|
+
return ()
|
|
314
|
+
try:
|
|
315
|
+
raw = tomllib.loads(path.read_text(encoding="utf-8"))
|
|
316
|
+
except (OSError, tomllib.TOMLDecodeError) as exc:
|
|
317
|
+
raise ManifestError(f"Cannot read {path}: {exc}") from exc
|
|
318
|
+
return tuple(_parse_operations(raw, source="local"))
|
yaddd_agents/lock.py
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
"""Deterministic lock file for generated agent rules."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import hashlib
|
|
6
|
+
import json
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
from yaddd_agents import __version__
|
|
10
|
+
from yaddd_agents.model import Project, Resolution
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def sha256_text(value: str) -> str:
|
|
14
|
+
"""Return the SHA-256 digest of a UTF-8 string."""
|
|
15
|
+
return hashlib.sha256(value.encode("utf-8")).hexdigest()
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def sha256_file(path: Path) -> str:
|
|
19
|
+
"""Return the SHA-256 digest of a file."""
|
|
20
|
+
return hashlib.sha256(path.read_bytes()).hexdigest()
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def build_lock(project: Project, resolution: Resolution, outputs: dict[Path, str]) -> str:
|
|
24
|
+
"""Build a deterministic ``manifest.lock.json`` payload."""
|
|
25
|
+
packs = [
|
|
26
|
+
{
|
|
27
|
+
"name": pack.name,
|
|
28
|
+
"version": pack.version,
|
|
29
|
+
"manifest_sha256": sha256_file(pack.manifest_path),
|
|
30
|
+
}
|
|
31
|
+
for pack in resolution.packs
|
|
32
|
+
]
|
|
33
|
+
payload = {
|
|
34
|
+
"schema": 1,
|
|
35
|
+
"generator": {"name": "yaddd-agents", "version": __version__},
|
|
36
|
+
"project": project.pyproject_path.name,
|
|
37
|
+
"packs": packs,
|
|
38
|
+
"outputs": {path.as_posix(): sha256_text(content) for path, content in sorted(outputs.items())},
|
|
39
|
+
}
|
|
40
|
+
return json.dumps(payload, indent=2, sort_keys=True) + "\n"
|
yaddd_agents/model.py
ADDED
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
"""Data model shared by discovery, resolution and rendering."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass, field
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
|
|
8
|
+
SCHEMA_VERSION = 1
|
|
9
|
+
LAYERS: tuple[str, ...] = ("domain", "application", "infrastructure", "presentation", "testing", "tooling")
|
|
10
|
+
MANAGED_BEGIN = "<!-- yaddd-agents:begin -->"
|
|
11
|
+
MANAGED_END = "<!-- yaddd-agents:end -->"
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class AgentsError(Exception):
|
|
15
|
+
"""Base error for user-facing yaddd-agents failures."""
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class DiscoveryError(AgentsError):
|
|
19
|
+
"""A project or pack could not be discovered."""
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class ManifestError(AgentsError):
|
|
23
|
+
"""A manifest is invalid."""
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class ResolveError(AgentsError):
|
|
27
|
+
"""Rules cannot be resolved."""
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def normalize_name(name: str) -> str:
|
|
31
|
+
"""Return the PEP 503 normalized distribution name."""
|
|
32
|
+
return name.strip().lower().replace("_", "-").replace(".", "-")
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def is_layer(value: str) -> bool:
|
|
36
|
+
"""Return True when a value names an architectural layer."""
|
|
37
|
+
return value in LAYERS
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
@dataclass(frozen=True, slots=True)
|
|
41
|
+
class Rule:
|
|
42
|
+
"""A rule declared by a pack."""
|
|
43
|
+
|
|
44
|
+
id: str
|
|
45
|
+
layer: str
|
|
46
|
+
kind: str = "guidance"
|
|
47
|
+
doc: str = ""
|
|
48
|
+
allow_first_party: frozenset[str] = frozenset()
|
|
49
|
+
allow_third_party: frozenset[str] = frozenset()
|
|
50
|
+
deny_first_party: frozenset[str] = frozenset()
|
|
51
|
+
deny_third_party: frozenset[str] = frozenset()
|
|
52
|
+
enabled: bool = True
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
@dataclass(frozen=True, slots=True)
|
|
56
|
+
class Operation:
|
|
57
|
+
"""A pack's request to relax, restrict, replace or disable a rule."""
|
|
58
|
+
|
|
59
|
+
kind: str
|
|
60
|
+
rule: str
|
|
61
|
+
reason: str
|
|
62
|
+
allow_add: frozenset[str] = frozenset()
|
|
63
|
+
deny_add: frozenset[str] = frozenset()
|
|
64
|
+
allow_first_party: frozenset[str] | None = None
|
|
65
|
+
allow_third_party: frozenset[str] | None = None
|
|
66
|
+
deny_first_party: frozenset[str] | None = None
|
|
67
|
+
deny_third_party: frozenset[str] | None = None
|
|
68
|
+
when_dependency: str | None = None
|
|
69
|
+
when_specifier: str | None = None
|
|
70
|
+
source: str = ""
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
@dataclass(frozen=True, slots=True)
|
|
74
|
+
class Pack:
|
|
75
|
+
"""A loaded pack: base, extension or local overrides."""
|
|
76
|
+
|
|
77
|
+
name: str
|
|
78
|
+
version: str
|
|
79
|
+
manifest_path: Path
|
|
80
|
+
rules: tuple[Rule, ...] = ()
|
|
81
|
+
operations: tuple[Operation, ...] = ()
|
|
82
|
+
docs: dict[str, str] = field(default_factory=dict[str, str])
|
|
83
|
+
core_doc: str = ""
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
@dataclass(slots=True)
|
|
87
|
+
class ResolvedRule:
|
|
88
|
+
"""A rule after every active pack has been applied."""
|
|
89
|
+
|
|
90
|
+
id: str
|
|
91
|
+
layer: str
|
|
92
|
+
kind: str
|
|
93
|
+
docs: list[str] = field(default_factory=list[str])
|
|
94
|
+
allow_first_party: set[str] = field(default_factory=set[str])
|
|
95
|
+
allow_third_party: set[str] = field(default_factory=set[str])
|
|
96
|
+
deny_first_party: set[str] = field(default_factory=set[str])
|
|
97
|
+
deny_third_party: set[str] = field(default_factory=set[str])
|
|
98
|
+
enabled: bool = True
|
|
99
|
+
sources: list[str] = field(default_factory=list[str])
|
|
100
|
+
|
|
101
|
+
@property
|
|
102
|
+
def effective_first_party(self) -> set[str]:
|
|
103
|
+
"""Allowed first-party imports after deny wins."""
|
|
104
|
+
return self.allow_first_party - self.deny_first_party
|
|
105
|
+
|
|
106
|
+
@property
|
|
107
|
+
def effective_third_party(self) -> set[str]:
|
|
108
|
+
"""Allowed third-party imports after deny wins."""
|
|
109
|
+
return self.allow_third_party - self.deny_third_party
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
@dataclass(frozen=True, slots=True)
|
|
113
|
+
class Resolution:
|
|
114
|
+
"""All resolved rules and the packs that produced them."""
|
|
115
|
+
|
|
116
|
+
packs: tuple[Pack, ...]
|
|
117
|
+
rules: dict[str, ResolvedRule]
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
@dataclass(frozen=True, slots=True)
|
|
121
|
+
class Project:
|
|
122
|
+
"""A project that consumes yaddd-agents."""
|
|
123
|
+
|
|
124
|
+
root: Path
|
|
125
|
+
pyproject_path: Path
|
|
126
|
+
dependencies: dict[str, str]
|
|
127
|
+
extension_paths: dict[str, str]
|
|
128
|
+
|
|
129
|
+
@property
|
|
130
|
+
def agents_dir(self) -> Path:
|
|
131
|
+
"""Directory with generated and hand-written agent rules."""
|
|
132
|
+
return self.root / ".agents"
|
|
133
|
+
|
|
134
|
+
@property
|
|
135
|
+
def yaddd_dir(self) -> Path:
|
|
136
|
+
"""Directory with machine-readable yaddd configuration."""
|
|
137
|
+
return self.root / ".yaddd"
|
|
138
|
+
|
|
139
|
+
@property
|
|
140
|
+
def local_rules_dir(self) -> Path:
|
|
141
|
+
"""Hand-written project-specific rules."""
|
|
142
|
+
return self.agents_dir / "rules" / "local"
|
|
143
|
+
|
|
144
|
+
@property
|
|
145
|
+
def overrides_path(self) -> Path:
|
|
146
|
+
"""Hand-written local overrides."""
|
|
147
|
+
return self.agents_dir / "overrides.toml"
|
yaddd_agents/py.typed
ADDED
|
File without changes
|