trigrams-toolkit 0.1.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.
Files changed (103) hide show
  1. trigrams_toolkit/__init__.py +1 -0
  2. trigrams_toolkit/handbook/__init__.py +6 -0
  3. trigrams_toolkit/handbook/cli.py +122 -0
  4. trigrams_toolkit/handbook/guide_headers.py +43 -0
  5. trigrams_toolkit/handbook/guides.py +141 -0
  6. trigrams_toolkit/handbook/location.py +79 -0
  7. trigrams_toolkit/handbook/model.py +4 -0
  8. trigrams_toolkit/handbook/package.py +165 -0
  9. trigrams_toolkit/handbook/principle_import.py +101 -0
  10. trigrams_toolkit/handbook/project_resources.py +80 -0
  11. trigrams_toolkit/handbook/skill_sources.py +59 -0
  12. trigrams_toolkit/handbook/source_catalog.py +55 -0
  13. trigrams_toolkit/handbook/sources.py +16 -0
  14. trigrams_toolkit/installation/__init__.py +0 -0
  15. trigrams_toolkit/installation/archive_project.py +50 -0
  16. trigrams_toolkit/installation/global_skills.py +45 -0
  17. trigrams_toolkit/installation/harness_install.py +89 -0
  18. trigrams_toolkit/installation/installation_candidate.py +135 -0
  19. trigrams_toolkit/installation/installation_help.py +49 -0
  20. trigrams_toolkit/installation/installation_materials.py +73 -0
  21. trigrams_toolkit/installation/installation_service.py +14 -0
  22. trigrams_toolkit/installation/installation_sources.py +34 -0
  23. trigrams_toolkit/installation/operation_files.py +94 -0
  24. trigrams_toolkit/installation/operation_runtime.py +144 -0
  25. trigrams_toolkit/installation/package_metadata.py +48 -0
  26. trigrams_toolkit/plan/__init__.py +5 -0
  27. trigrams_toolkit/plan/cli.py +136 -0
  28. trigrams_toolkit/plan/definitions.py +131 -0
  29. trigrams_toolkit/plan/model.py +61 -0
  30. trigrams_toolkit/plan/scheduling.py +126 -0
  31. trigrams_toolkit/plan/service.py +139 -0
  32. trigrams_toolkit/plan/state.py +146 -0
  33. trigrams_toolkit/project_context/__init__.py +16 -0
  34. trigrams_toolkit/project_context/paths.py +36 -0
  35. trigrams_toolkit/py.typed +0 -0
  36. trigrams_toolkit/resources/__init__.py +35 -0
  37. trigrams_toolkit/resources/adapters/claude/README.md +7 -0
  38. trigrams_toolkit/resources/adapters/claude/evaluator.md +7 -0
  39. trigrams_toolkit/resources/adapters/claude/task_developer.md +7 -0
  40. trigrams_toolkit/resources/adapters/codex/README.md +9 -0
  41. trigrams_toolkit/resources/adapters/codex/evaluator.toml +6 -0
  42. trigrams_toolkit/resources/adapters/codex/task_developer.toml +6 -0
  43. trigrams_toolkit/resources/adapters/pi-web/evaluator.md +7 -0
  44. trigrams_toolkit/resources/adapters/pi-web/task_developer.md +7 -0
  45. trigrams_toolkit/resources/handbook/PROTOCOL.md +82 -0
  46. trigrams_toolkit/resources/handbook/README.md +45 -0
  47. trigrams_toolkit/resources/handbook/commands.json +31 -0
  48. trigrams_toolkit/resources/handbook/guides.schema.json +253 -0
  49. trigrams_toolkit/resources/installation/PROTOCOL.md +35 -0
  50. trigrams_toolkit/resources/installation/cli.schema.json +89 -0
  51. trigrams_toolkit/resources/installation/commands.json +23 -0
  52. trigrams_toolkit/resources/installation/examples/install-apply-input.json +48 -0
  53. trigrams_toolkit/resources/installation/examples/install-preview-input.json +7 -0
  54. trigrams_toolkit/resources/installation/examples/installation.json +20 -0
  55. trigrams_toolkit/resources/installation/global-skills.json +6 -0
  56. trigrams_toolkit/resources/installation/installation.schema.json +295 -0
  57. trigrams_toolkit/resources/plan/PROTOCOL.md +89 -0
  58. trigrams_toolkit/resources/plan/README.md +61 -0
  59. trigrams_toolkit/resources/plan/commands.json +36 -0
  60. trigrams_toolkit/resources/plan/plan.schema.json +192 -0
  61. trigrams_toolkit/resources/shared/GLOBAL-TOOLS.md +31 -0
  62. trigrams_toolkit/resources/shared/common.schema.json +234 -0
  63. trigrams_toolkit/resources/state/PROTOCOL.md +85 -0
  64. trigrams_toolkit/resources/state/README.md +88 -0
  65. trigrams_toolkit/resources/state/cli.schema.json +326 -0
  66. trigrams_toolkit/resources/state/commands.json +55 -0
  67. trigrams_toolkit/resources/state/core-types.json +5 -0
  68. trigrams_toolkit/resources/state/help.json +86 -0
  69. trigrams_toolkit/resources/state/sources.schema.json +89 -0
  70. trigrams_toolkit/resources/state/state.schema.json +200 -0
  71. trigrams_toolkit/shared/__init__.py +1 -0
  72. trigrams_toolkit/shared/cli_help.py +195 -0
  73. trigrams_toolkit/shared/errors.py +29 -0
  74. trigrams_toolkit/shared/files.py +66 -0
  75. trigrams_toolkit/shared/locking.py +49 -0
  76. trigrams_toolkit/shared/paths.py +89 -0
  77. trigrams_toolkit/shared/process_lock.py +77 -0
  78. trigrams_toolkit/shared/schema.py +60 -0
  79. trigrams_toolkit/shared/serialization.py +84 -0
  80. trigrams_toolkit/shared/skill_installations.py +66 -0
  81. trigrams_toolkit/shared/state_json.py +45 -0
  82. trigrams_toolkit/state/__init__.py +4 -0
  83. trigrams_toolkit/state/arguments.py +68 -0
  84. trigrams_toolkit/state/cli.py +37 -0
  85. trigrams_toolkit/state/frontmatter.py +176 -0
  86. trigrams_toolkit/state/help.py +25 -0
  87. trigrams_toolkit/state/identity.py +123 -0
  88. trigrams_toolkit/state/location.py +59 -0
  89. trigrams_toolkit/state/model.py +76 -0
  90. trigrams_toolkit/state/providers.py +77 -0
  91. trigrams_toolkit/state/registration.py +82 -0
  92. trigrams_toolkit/state/relations.py +105 -0
  93. trigrams_toolkit/state/service.py +90 -0
  94. trigrams_toolkit/state/store.py +33 -0
  95. trigrams_toolkit/state/views.py +64 -0
  96. trigrams_toolkit/version.py +6 -0
  97. trigrams_toolkit-0.1.0.dist-info/METADATA +69 -0
  98. trigrams_toolkit-0.1.0.dist-info/RECORD +103 -0
  99. trigrams_toolkit-0.1.0.dist-info/WHEEL +5 -0
  100. trigrams_toolkit-0.1.0.dist-info/entry_points.txt +5 -0
  101. trigrams_toolkit-0.1.0.dist-info/licenses/LICENSE +21 -0
  102. trigrams_toolkit-0.1.0.dist-info/licenses/THIRD_PARTY_NOTICES.md +18 -0
  103. trigrams_toolkit-0.1.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,123 @@
1
+ """Artifact declarations, binary member manifests and byte-preserving edits."""
2
+ from __future__ import annotations
3
+
4
+ from dataclasses import dataclass
5
+ from pathlib import Path
6
+ import re
7
+ from typing import Any, Literal
8
+
9
+ from trigrams_toolkit.project_context.paths import confined, path_key
10
+ from trigrams_toolkit.shared.errors import require
11
+ from trigrams_toolkit.shared.state_json import json_bytes, parse_state_json
12
+ from .frontmatter import metadata, update_metadata
13
+ from .model import Artifact, validate_record
14
+
15
+
16
+ @dataclass(frozen=True)
17
+ class Declaration:
18
+ identity: str | None
19
+ title: str
20
+ module_id: str | None
21
+ feature_ids: list[str]
22
+ mode: Literal["frontmatter", "manifest"]
23
+
24
+
25
+ def _id(value: Any, prefix: str) -> str:
26
+ if not isinstance(value, str) or re.fullmatch(prefix + r"_[A-Za-z0-9_-]+", value) is None:
27
+ raise ValueError(f"Invalid {prefix} identity: {value}")
28
+ return value
29
+
30
+
31
+ def declaration(source: str, path: Path, *, ignore_ownership: bool = False) -> Declaration:
32
+ mode: Literal["frontmatter", "manifest"]
33
+ title: Any
34
+ text = source.removeprefix("\ufeff")
35
+ if text.lstrip().startswith("{"):
36
+ fields = parse_state_json(text)
37
+ if not (isinstance(fields, dict) and type(fields.get("schemaVersion")) is int and fields["schemaVersion"] == 1
38
+ and isinstance(fields.get("members"), list) and fields["members"]
39
+ and all(isinstance(p, str) for p in fields["members"])):
40
+ raise ValueError("Expected identity manifest with schemaVersion 1 and nonempty members.")
41
+ identity, title, mode = _id(fields["id"], "artifact") if "id" in fields else None, path.name, "manifest"
42
+ else:
43
+ lines = re.split(r"\r\n|\n|\r", text)
44
+ end = 0
45
+ if lines[0] == "---":
46
+ require("---" in lines[1:], "invalid_reference", f"Unclosed frontmatter: {path}")
47
+ end = lines.index("---", 1)
48
+ fields = metadata("\n".join(lines[1:end])) if end else {}
49
+ heading = next((re.sub(r"^#\s+", "", line) for line in lines[end + 1 if end else 0:] if re.match(r"^#\s+", line)), path.name)
50
+ title = fields.get("title") if fields.get("title") is not None else heading
51
+ identity, mode = _id(fields["artifact-id"], "artifact") if "artifact-id" in fields else None, "frontmatter"
52
+ if not isinstance(title, str) or not title.strip():
53
+ raise ValueError("Expected nonempty document title")
54
+ module, features = None, []
55
+ if not ignore_ownership:
56
+ if "moduleId" in fields:
57
+ module = _id(fields["moduleId"], "module")
58
+ features = fields.get("featureIds", [])
59
+ if not isinstance(features, list):
60
+ raise ValueError("Expected featureIds array")
61
+ features = [_id(value, "feature") for value in features]
62
+ return Declaration(identity, title.strip(), module, features, mode)
63
+
64
+
65
+ def read_declaration(root: Path, path: Path, *, ignore_ownership: bool = False) -> tuple[str, Declaration]:
66
+ source = path.read_bytes().decode("utf-8")
67
+ value = declaration(source, path, ignore_ownership=ignore_ownership)
68
+ if value.mode == "manifest":
69
+ fields = parse_state_json(source, bom=True)
70
+ members = [confined(root, name) for name in fields["members"]]
71
+ require(len({path_key(p) for p in members}) == len(members), "identity_conflict", "Manifest has duplicate members.")
72
+ for member in members:
73
+ member.read_bytes()
74
+ return source, value
75
+
76
+
77
+ def _registered(fields: dict[str, Any], entity: Artifact, key: str) -> bool:
78
+ return (fields.get(key) == entity["id"] and ("moduleId" in fields) == ("moduleId" in entity)
79
+ and fields.get("moduleId") == entity.get("moduleId")
80
+ and fields.get("featureIds", []) == entity["featureIds"])
81
+
82
+
83
+ def with_registration(source: str, entity: Artifact) -> str:
84
+ bom = "\ufeff" if source.startswith("\ufeff") else ""
85
+ body = source[len(bom):]
86
+ if entity["identityMode"] == "manifest":
87
+ value = parse_state_json(body)
88
+ if _registered(value, entity, "id"):
89
+ return source
90
+ value["id"] = entity["id"]
91
+ for key in ("moduleId", "featureIds"):
92
+ if entity.get(key):
93
+ value[key] = entity[key]
94
+ else:
95
+ value.pop(key, None)
96
+ return bom + json_bytes(value).decode("utf-8")
97
+ match = re.search(r"\r\n|\n|\r", body)
98
+ newline = match[0] if match else "\n"
99
+ opening = re.match(r"^---(?:\r\n|\n|\r)", body)
100
+ if opening:
101
+ rest = body[opening.end():]
102
+ closing = re.search(r"(?:^|(?<=[\r\n]))---(?=\r\n|\n|\r|$)", rest)
103
+ require(closing is not None, "invalid_reference", "Unclosed frontmatter.")
104
+ assert closing is not None
105
+ header, tail = rest[:closing.start()], rest[closing.end():]
106
+ else:
107
+ header, tail = "", newline + body
108
+ if _registered(metadata(header), entity, "artifact-id"):
109
+ return source
110
+ updated = update_metadata(header, entity["id"], entity.get("moduleId"), entity["featureIds"])
111
+ require(_registered(metadata(updated), entity, "artifact-id"), "invalid_reference", "Managed identity or ownership conflicts with YAML merges.")
112
+ updated = updated.replace("\n", newline)
113
+ return f"{bom}---{newline}{updated}---{tail}"
114
+
115
+
116
+ def artifact_from_document(root: Path, path: Path, value: Declaration, identity: str, kind: str,
117
+ module: str | None, features: list[str]) -> Artifact:
118
+ entity: Artifact = {"id": identity, "kind": kind, "title": value.title, "locatorHint": path.relative_to(root).as_posix(),
119
+ "identityMode": value.mode, "featureIds": features}
120
+ if module is not None:
121
+ entity["moduleId"] = module
122
+ validate_record(entity, "artifact")
123
+ return entity
@@ -0,0 +1,59 @@
1
+ """Identity scanning skips linked descendants and resolves only selected bodies."""
2
+ from __future__ import annotations
3
+
4
+ from pathlib import Path
5
+ import re
6
+
7
+ from trigrams_toolkit.project_context.paths import confined, path_key
8
+ from trigrams_toolkit.shared.errors import ProtocolError
9
+ from trigrams_toolkit.shared.paths import is_link
10
+ from .identity import declaration
11
+ from .model import Artifact, RegistryState
12
+
13
+ _EXCLUDED = {".git", ".cas", ".requests", "node_modules", "__pycache__", ".project-state"}
14
+
15
+
16
+ def identity_candidates(project_root: Path, state: RegistryState, extra: tuple[Path, ...] = ()) -> dict[str, set[Path]]:
17
+ found: dict[str, set[Path]] = {}
18
+ visited: set[str] = set()
19
+ docs = confined(project_root, "docs")
20
+ archive = docs / "archives"
21
+
22
+ def scan(path: Path) -> None:
23
+ if not path.exists() or path_key(path) in visited:
24
+ return
25
+ visited.add(path_key(path))
26
+ if path.is_dir():
27
+ for entry in sorted(path.iterdir()):
28
+ if entry != archive and entry.name not in _EXCLUDED and not is_link(entry):
29
+ scan(entry)
30
+ return
31
+ if not path.is_file():
32
+ return
33
+ raw = path.read_bytes()
34
+ start = raw.decode("utf-8", errors="replace").removeprefix("\ufeff").lstrip()
35
+ if not start.startswith(("---", "{")):
36
+ return
37
+ try:
38
+ identity = declaration(raw.decode("utf-8-sig"), path, ignore_ownership=True).identity
39
+ except (ValueError, ProtocolError):
40
+ if start.startswith("---") and re.search(r"^artifact-id:", start, re.MULTILINE):
41
+ raise
42
+ return
43
+ if identity:
44
+ found.setdefault(identity, set()).add(path)
45
+
46
+ scan(docs)
47
+ hints = [artifact["locatorHint"] for artifact in state["artifacts"]]
48
+ paths: tuple[Path | str, ...] = ("plans", *hints, *extra)
49
+ for path in paths:
50
+ scan(confined(project_root, path))
51
+ return found
52
+
53
+
54
+ def artifact_location(project_root: Path, state: RegistryState, artifact: Artifact) -> Path:
55
+ candidates = sorted(identity_candidates(project_root, state).get(artifact["id"], set()))
56
+ if len(candidates) != 1:
57
+ raise ProtocolError("identity_conflict" if candidates else "invalid_reference",
58
+ f"Expected one body declaring {artifact['id']}.", details=[str(p) for p in candidates] or None)
59
+ return candidates[0]
@@ -0,0 +1,76 @@
1
+ """Registry records and schema-validated entity boundaries."""
2
+ from __future__ import annotations
3
+
4
+ from functools import cache
5
+ from typing import Any, Literal, NotRequired, TypedDict, cast
6
+ from jsonschema import Draft202012Validator
7
+
8
+ from trigrams_toolkit.resources import resource_path
9
+ from trigrams_toolkit.shared.errors import ProtocolError
10
+ from trigrams_toolkit.shared.serialization import read_json
11
+
12
+
13
+ class Module(TypedDict):
14
+ id: str
15
+ name: str
16
+
17
+
18
+ class Feature(Module):
19
+ moduleId: str
20
+
21
+
22
+ class Artifact(TypedDict):
23
+ id: str
24
+ kind: str
25
+ title: str
26
+ locatorHint: str
27
+ identityMode: Literal["frontmatter", "manifest"]
28
+ moduleId: NotRequired[str]
29
+ featureIds: list[str]
30
+
31
+
32
+ Entity = Module | Feature | Artifact
33
+
34
+
35
+ # `from` is a Python keyword, so its wire type uses functional TypedDict syntax.
36
+ Edge = TypedDict("Edge", {"kind": str, "from": str, "to": str})
37
+
38
+
39
+ class RegistryState(TypedDict):
40
+ schemaVersion: int
41
+ modules: list[Module]
42
+ features: list[Feature]
43
+ artifacts: list[Artifact]
44
+ relations: list[Edge]
45
+
46
+
47
+ @cache
48
+ def state_schema() -> dict[str, Any]:
49
+ return read_json(resource_path("state/state.schema.json"))
50
+
51
+
52
+ def validate_record(value: Any, definition: str | None = None, *, code: str = "io_error") -> None:
53
+ schema = state_schema()
54
+ if definition:
55
+ schema = {"$defs": schema["$defs"], "$ref": f"#/$defs/{definition}"}
56
+ error = next(Draft202012Validator(schema).iter_errors(value), None)
57
+ if error is not None:
58
+ if error.validator == "uniqueItems":
59
+ raise ProtocolError("invalid_reference", "Duplicate featureIds in Artifact.")
60
+ raise ProtocolError(code, f"{error.json_path}: {error.message}")
61
+
62
+
63
+ def all_entities(state: RegistryState) -> list[Entity]:
64
+ return [*state["modules"], *state["features"], *state["artifacts"]]
65
+
66
+
67
+ def entity_kind(entity: Entity) -> str:
68
+ if "kind" in entity:
69
+ return cast(Artifact, entity)["kind"]
70
+ return "core:feature" if "moduleId" in entity else "core:module"
71
+
72
+
73
+ def identity_sort_key(identity: str) -> tuple[tuple[int, ...], tuple[bool, ...]]:
74
+ """Locale collation for the Registry's ASCII ID alphabet, lowercase first."""
75
+ alphabet = "_-0123456789abcdefghijklmnopqrstuvwxyz"
76
+ return tuple(alphabet.index(c.lower()) for c in identity), tuple(c.isupper() for c in identity)
@@ -0,0 +1,77 @@
1
+ """Artifact and relation types declared by the project and its installed extensions."""
2
+ from __future__ import annotations
3
+
4
+ from dataclasses import dataclass
5
+ from pathlib import Path
6
+ from typing import Any
7
+
8
+ from trigrams_toolkit.handbook.location import installed_extensions
9
+ from trigrams_toolkit.handbook.package import manifest_owner
10
+ from trigrams_toolkit.installation.installation_sources import read_installation
11
+ from trigrams_toolkit.resources import resource_path, schema_paths
12
+ from trigrams_toolkit.shared.errors import require
13
+ from trigrams_toolkit.shared.paths import confined
14
+ from trigrams_toolkit.shared.schema import SchemaCatalog
15
+ from trigrams_toolkit.shared.serialization import read_json
16
+ from trigrams_toolkit.shared.state_json import optional_bytes, parse_state_json
17
+ from jsonschema import Draft202012Validator
18
+
19
+
20
+ @dataclass(frozen=True)
21
+ class Types:
22
+ artifacts: frozenset[str]
23
+ relations: dict[str, dict[str, Any]]
24
+ same_artifact_kind: frozenset[str]
25
+
26
+
27
+ def _validate_project_package(value: Any) -> None:
28
+ schema = read_json(resource_path("state/sources.schema.json"))
29
+ error = next(Draft202012Validator({"$defs": schema["$defs"], "$ref": "#/$defs/package"}).iter_errors(value), None)
30
+ require(error is None, "invalid_schema", "Unsupported source format. Archive the existing state and rebuild it with initialize.")
31
+
32
+
33
+ def _package_at(path: Path) -> dict[str, Any] | None:
34
+ raw = optional_bytes(path)
35
+ if raw is None:
36
+ return None
37
+ value = parse_state_json(raw, bom=True)
38
+ if not isinstance(value, dict) or not any(key in value for key in ("source", "extension")):
39
+ return None
40
+ _validate_project_package(value)
41
+ return _declaration(value)
42
+
43
+
44
+ def _declaration(value: dict[str, Any]) -> dict[str, Any]:
45
+ owner = value.get("extension") or value["source"]
46
+ relations = [{"kind": r["kind"], "fromKinds": r["fromKinds"], "toKinds": r["toKinds"],
47
+ "maxOutgoing": r.get("maxOutgoing"), "maxIncoming": r.get("maxIncoming"), "acyclic": r.get("acyclic", False)}
48
+ for r in value.get("relationTypes", [])]
49
+ for kind in [*value.get("artifactTypes", []), *(r["kind"] for r in relations)]:
50
+ require(kind.startswith(owner + ":"), "identity_conflict", f"Foreign provider type: {kind}")
51
+ return {"source": owner, "artifactTypes": value.get("artifactTypes", []), "relationTypes": relations}
52
+
53
+
54
+ def provider_declarations(project_root: Path) -> list[dict[str, Any]]:
55
+ schemas = SchemaCatalog(schema_paths())
56
+ record = read_installation(project_root, schemas)
57
+ declarations = {manifest_owner(package.manifest): _declaration(package.manifest)
58
+ for package in installed_extensions(project_root, record, schemas, guides=False)}
59
+ for location in ("docs/resources.json", "resources.json"):
60
+ item = _package_at(confined(project_root, location))
61
+ if item is not None and item["source"] == "project":
62
+ require("project" not in declarations, "resource_conflict", "Multiple project provider roots.")
63
+ declarations["project"] = item
64
+ return list(declarations.values())
65
+
66
+
67
+ def provider_types(project_root: Path) -> Types:
68
+ core = read_json(resource_path("state/core-types.json"))
69
+ artifacts = set(core["artifactTypes"])
70
+ relations = {r["kind"]: r for r in core["relationTypes"]}
71
+ for package in provider_declarations(project_root):
72
+ artifacts.update(package["artifactTypes"])
73
+ for relation in package["relationTypes"]:
74
+ existing = relations.get(relation["kind"])
75
+ require(existing is None or existing == relation, "resource_conflict", f"Conflicting relation: {relation['kind']}")
76
+ relations[relation["kind"]] = relation
77
+ return Types(frozenset(artifacts), relations, frozenset(core["sameArtifactKindRelations"]))
@@ -0,0 +1,82 @@
1
+ """Register entities; document publication precedes Registry publication."""
2
+ from __future__ import annotations
3
+
4
+ from pathlib import Path
5
+ import secrets
6
+ import string
7
+ from typing import Any, TypeVar, cast
8
+
9
+ from trigrams_toolkit.project_context.paths import confined, path_key
10
+ from trigrams_toolkit.shared.errors import ProtocolError, require
11
+ from trigrams_toolkit.shared.files import atomic_write
12
+ from .arguments import Invocation
13
+ from .identity import artifact_from_document, read_declaration, with_registration
14
+ from .location import identity_candidates
15
+ from .model import Entity, Feature, Module, RegistryState, all_entities, validate_record
16
+ from .providers import provider_types
17
+ from .relations import validate_identity_graph, validate_ownership, validate_relations
18
+
19
+ _Entity = TypeVar("_Entity", bound=Entity)
20
+
21
+
22
+ def _identity(prefix: str) -> str:
23
+ return prefix + "_" + "".join(secrets.choice(string.digits + string.ascii_uppercase + string.ascii_lowercase) for _ in range(10))
24
+
25
+
26
+ def _save(items: list[_Entity], entity: _Entity) -> list[_Entity]:
27
+ for index, item in enumerate(items):
28
+ if item["id"] == entity["id"]:
29
+ return [*items[:index], entity, *items[index + 1:]]
30
+ return [*items, entity]
31
+
32
+
33
+ def _named(state: RegistryState, invocation: Invocation) -> dict[str, Any]:
34
+ module = invocation.command == "register module"
35
+ identity = invocation.option("--id") or _identity("module" if module else "feature")
36
+ existing = next((e for e in all_entities(state) if e["id"] == identity), None)
37
+ name = invocation.args[0].strip()
38
+ if module:
39
+ require(existing is None or ("kind" not in existing and "moduleId" not in existing), "identity_conflict", f"ID belongs to another entity: {identity}")
40
+ module_entity = Module(id=identity, name=name)
41
+ validate_record(module_entity, "module")
42
+ state["modules"] = _save(state["modules"], module_entity)
43
+ entity: Entity = module_entity
44
+ else:
45
+ owner = invocation.option("--module") or (cast(Any, existing).get("moduleId") if existing else None)
46
+ require(bool(owner), "invalid_arguments", "New Features require --module MODULE_ID.")
47
+ assert owner is not None
48
+ feature_entity = Feature(id=identity, name=name, moduleId=owner)
49
+ validate_record(feature_entity, "feature")
50
+ state["features"] = _save(state["features"], feature_entity)
51
+ entity = feature_entity
52
+ validate_identity_graph(state)
53
+ return {"entity": entity, "changed": False}
54
+
55
+
56
+ def register(state: RegistryState, project_root: Path, invocation: Invocation) -> dict[str, Any]:
57
+ if invocation.command != "register artifact":
58
+ return _named(state, invocation)
59
+ path = confined(project_root, invocation.args[0])
60
+ source, declaration = read_declaration(project_root, path, ignore_ownership=True)
61
+ identity = declaration.identity or _identity("artifact")
62
+ existing = next((a for a in state["artifacts"] if a["id"] == identity), None)
63
+ kind = invocation.option("--kind") or (existing["kind"] if existing else "core:document")
64
+ types = provider_types(project_root)
65
+ require(kind in types.artifacts, "missing_capability", f"No package declares Artifact kind: {kind}")
66
+ explicit = "--module" in invocation.options
67
+ module = invocation.option("--module") if explicit else (existing.get("moduleId") if existing else None)
68
+ features = invocation.options.get("--feature", []) if explicit else (existing["featureIds"] if existing else [])
69
+ # Ownership duplicates use the existing business error, before schema uniqueItems.
70
+ require(len(set(features)) == len(features), "invalid_reference", f"Duplicate featureIds in {identity}.")
71
+ entity = artifact_from_document(project_root, path, declaration, identity, kind, module, list(features))
72
+ validate_ownership(state, entity)
73
+ matches = sorted(identity_candidates(project_root, state, (path,)).get(identity, set()))
74
+ if any(path_key(item) != path_key(path) for item in matches):
75
+ raise ProtocolError("identity_conflict", f"Another body declares {identity}.", details=[str(p) for p in matches])
76
+ state["artifacts"] = _save(state["artifacts"], entity)
77
+ validate_identity_graph(state)
78
+ validate_relations(state, types)
79
+ updated = with_registration(source, entity)
80
+ if updated != source:
81
+ atomic_write(path, updated.encode("utf-8"))
82
+ return {"entity": entity, "changed": updated != source}
@@ -0,0 +1,105 @@
1
+ """Identity, ownership and extra-relation graph invariants."""
2
+ from __future__ import annotations
3
+
4
+ from typing import Any
5
+ from trigrams_toolkit.shared.errors import require
6
+ from .model import Artifact, Edge, Entity, RegistryState, all_entities, entity_kind
7
+ from .providers import Types
8
+
9
+
10
+ def validate_ownership(state: RegistryState, artifact: Artifact) -> None:
11
+ module = artifact.get("moduleId")
12
+ require(module is None or any(m["id"] == module for m in state["modules"]), "invalid_reference", f"Unknown moduleId in {artifact['id']}: {module}")
13
+ features = artifact["featureIds"]
14
+ require(not features or module is not None, "invalid_reference", f"featureIds in {artifact['id']} require moduleId.")
15
+ require(len(set(features)) == len(features), "invalid_reference", f"Duplicate featureIds in {artifact['id']}.")
16
+ for identity in features:
17
+ require(any(f["id"] == identity and f["moduleId"] == module for f in state["features"]),
18
+ "invalid_reference", f"Feature {identity} does not belong to {module}.")
19
+
20
+
21
+ def validate_identity_graph(state: RegistryState) -> None:
22
+ entities = all_entities(state)
23
+ ids = {e["id"] for e in entities}
24
+ require(len(ids) == len(entities), "identity_conflict", "Duplicate Registry identity.")
25
+ for feature in state["features"]:
26
+ require(any(m["id"] == feature["moduleId"] for m in state["modules"]), "invalid_reference", f"Unknown Module: {feature['moduleId']}")
27
+ for artifact in state["artifacts"]:
28
+ validate_ownership(state, artifact)
29
+ edges = state["relations"]
30
+ require(len({(e["kind"], e["from"], e["to"]) for e in edges}) == len(edges), "invalid_reference", "Duplicate relation.")
31
+ for edge in edges:
32
+ require(edge["from"] in ids and edge["to"] in ids and edge["from"] != edge["to"], "invalid_reference", "Invalid relation endpoints.")
33
+
34
+
35
+ def _rule(edge: Edge, entities: dict[str, Entity], types: Types) -> dict[str, Any]:
36
+ source, target = entities.get(edge["from"]), entities.get(edge["to"])
37
+ require(source is not None and target is not None and source["id"] != target["id"], "invalid_reference", "Relation endpoints must be distinct registered entities.")
38
+ assert source is not None and target is not None
39
+ if edge["kind"] in types.same_artifact_kind:
40
+ require("kind" in source and "kind" in target and entity_kind(source) == entity_kind(target),
41
+ "invalid_reference", "supersedes requires Artifacts of the same kind.")
42
+ return {"maxOutgoing": None, "maxIncoming": None, "acyclic": True}
43
+ rule = types.relations.get(edge["kind"])
44
+ require(rule is not None, "missing_capability", f"No package declares relation {edge['kind']}.")
45
+ assert rule is not None
46
+ require(entity_kind(source) in rule["fromKinds"] and entity_kind(target) in rule["toKinds"], "invalid_reference", f"Endpoint kinds differ for {edge['kind']}.")
47
+ return rule
48
+
49
+
50
+ def _no_cycles(edges: list[Edge]) -> None:
51
+ # Kahn's algorithm also handles graphs deeper than Python's recursion limit.
52
+ neighbors: dict[str, list[str]] = {}
53
+ degrees: dict[str, int] = {}
54
+ for edge in edges:
55
+ neighbors.setdefault(edge["from"], []).append(edge["to"])
56
+ degrees.setdefault(edge["from"], 0)
57
+ degrees[edge["to"]] = degrees.get(edge["to"], 0) + 1
58
+ ready = [key for key, count in degrees.items() if count == 0]
59
+ visited = 0
60
+ while ready:
61
+ current = ready.pop()
62
+ visited += 1
63
+ for target in neighbors.get(current, []):
64
+ degrees[target] -= 1
65
+ if degrees[target] == 0:
66
+ ready.append(target)
67
+ require(visited == len(degrees), "invalid_reference", "Relation graph contains a cycle.")
68
+
69
+
70
+ def validate_relations(state: RegistryState, types: Types) -> None:
71
+ entities = {e["id"]: e for e in all_entities(state)}
72
+ for kind in dict.fromkeys(e["kind"] for e in state["relations"]):
73
+ edges = [e for e in state["relations"] if e["kind"] == kind]
74
+ for edge in edges:
75
+ rule = _rule(edge, entities, types)
76
+ for direction, limit in (("from", "maxOutgoing"), ("to", "maxIncoming")):
77
+ require(rule[limit] is None or sum(dict(e)[direction] == dict(edge)[direction] for e in edges) <= rule[limit],
78
+ "invalid_reference", f"Cardinality exceeded: {kind}")
79
+ if rule["acyclic"]:
80
+ _no_cycles(edges)
81
+
82
+
83
+ def change_relation(state: RegistryState, edge: Edge, remove: bool, types: Types) -> bool:
84
+ require(edge["kind"] not in ("core:feature-module", "core:module-spec", "core:feature-spec"), "invalid_arguments",
85
+ "Use register feature --module or register artifact --module/--feature to maintain ownership.")
86
+ _rule(edge, {e["id"]: e for e in all_entities(state)}, types)
87
+ exists = edge in state["relations"]
88
+ if exists == (not remove):
89
+ return False
90
+ if remove:
91
+ state["relations"].remove(edge)
92
+ else:
93
+ state["relations"].append(edge)
94
+ validate_relations(state, types)
95
+ return True
96
+
97
+
98
+ def effective_relations(state: RegistryState) -> list[dict[str, str]]:
99
+ result: list[dict[str, str]] = [{"kind": e["kind"], "from": e["from"], "to": e["to"], "source": "relation"} for e in state["relations"]]
100
+ result.extend({"kind": "core:feature-module", "from": f["id"], "to": f["moduleId"], "source": "feature"} for f in state["features"])
101
+ for artifact in state["artifacts"]:
102
+ if "moduleId" in artifact:
103
+ result.append({"kind": "core:module-spec", "from": artifact["moduleId"], "to": artifact["id"], "source": "document"})
104
+ result.extend({"kind": "core:feature-spec", "from": f, "to": artifact["id"], "source": "document"} for f in artifact["featureIds"])
105
+ return result
@@ -0,0 +1,90 @@
1
+ """Public Registry services, shared by CLI and Plan inspection."""
2
+ from __future__ import annotations
3
+
4
+ from pathlib import Path
5
+ from typing import Any
6
+
7
+ from trigrams_toolkit.project_context import current_project_root
8
+ from trigrams_toolkit.project_context.paths import confined
9
+ from trigrams_toolkit.shared.errors import ProtocolError, require
10
+ from trigrams_toolkit.shared.files import atomic_write
11
+ from trigrams_toolkit.shared.process_lock import state_lock
12
+ from trigrams_toolkit.shared.state_json import json_bytes
13
+ from .arguments import Invocation
14
+ from .identity import read_declaration
15
+ from .location import identity_candidates
16
+ from .model import Edge, RegistryState, all_entities, entity_kind, identity_sort_key, validate_record
17
+ from .providers import provider_types
18
+ from .registration import register
19
+ from .relations import change_relation, effective_relations, validate_relations
20
+ from .store import read_state
21
+ from .views import LocateResult, entity_view, located_entity_view
22
+
23
+
24
+ def locate(project_root: Path, state: RegistryState, identity: str) -> LocateResult:
25
+ entity = next((e for e in all_entities(state) if e["id"] == identity), None)
26
+ require(entity is not None, "invalid_reference", f"Unregistered identity: {identity}. Use list to find the current identity.")
27
+ assert entity is not None
28
+ return located_entity_view(project_root, state, entity)
29
+
30
+
31
+ def _registry_path(project_root: Path) -> Path:
32
+ return confined(project_root, ".project-state/state.json")
33
+
34
+
35
+ def locate_identity(project_root: Path, identity: str) -> LocateResult:
36
+ return locate(project_root, read_state(_registry_path(project_root)), identity)
37
+
38
+
39
+ def _validate(project_root: Path, state: RegistryState) -> dict[str, bool]:
40
+ types = provider_types(project_root)
41
+ validate_relations(state, types)
42
+ identities = identity_candidates(project_root, state)
43
+ for artifact in state["artifacts"]:
44
+ require(artifact["kind"] in types.artifacts, "missing_capability", f"No package declares {artifact['kind']}.")
45
+ matches = sorted(identities.get(artifact["id"], set()))
46
+ if len(matches) != 1:
47
+ raise ProtocolError("identity_conflict" if matches else "invalid_reference", f"Expected one body for {artifact['id']}.", details=[str(p) for p in matches])
48
+ _, declaration = read_declaration(project_root, matches[0])
49
+ require(declaration.module_id == artifact.get("moduleId") and declaration.feature_ids == artifact["featureIds"],
50
+ "declaration_changed", f"Ownership changed in {matches[0]}. Use register artifact to restore registered ownership, or pass --module and --feature to replace it.")
51
+ return {"valid": True}
52
+
53
+
54
+ def _query(project_root: Path, state: RegistryState, invocation: Invocation) -> dict[str, Any]:
55
+ if invocation.command == "list":
56
+ kind = invocation.option("--kind")
57
+ items = [e for e in all_entities(state) if kind is None or kind == entity_kind(e)
58
+ or kind == entity_kind(e).removeprefix("core:") and "kind" not in e or kind == "artifact" and "kind" in e]
59
+ return {"items": [entity_view(e) for e in sorted(items, key=lambda e: identity_sort_key(e["id"]))]}
60
+ if invocation.command == "locate":
61
+ return dict(locate(project_root, state, invocation.args[0]))
62
+ if invocation.command == "related":
63
+ identity, direction = invocation.args[0], invocation.option("--direction") or "both"
64
+ require(any(e["id"] == identity for e in all_entities(state)), "invalid_reference", f"Unregistered identity: {identity}. Use list to find current entities.")
65
+ edges = [e for e in effective_relations(state) if (direction != "incoming" and e["from"] == identity)
66
+ or (direction != "outgoing" and e["to"] == identity)]
67
+ ids = {e[key] for e in edges for key in ("from", "to")} - {identity}
68
+ return {"items": [located_entity_view(project_root, state, e) for e in all_entities(state) if e["id"] in ids], "relations": edges}
69
+ return _validate(project_root, state)
70
+
71
+
72
+ def execute(invocation: Invocation, *, cwd: Path | None = None) -> dict[str, Any]:
73
+ project_root = current_project_root(cwd)
74
+ state_file = _registry_path(project_root)
75
+ if not invocation.command.startswith("register ") and invocation.command != "relate":
76
+ return _query(project_root, read_state(state_file), invocation)
77
+ confined(project_root, state_file.with_name(state_file.name + ".lock.sqlite"))
78
+ with state_lock(state_file):
79
+ state = read_state(state_file)
80
+ before = json_bytes(state)
81
+ if invocation.command == "relate":
82
+ edge: Edge = {"from": invocation.args[0], "kind": invocation.args[1], "to": invocation.args[2]}
83
+ data: dict[str, Any] = {"changed": change_relation(state, edge, "--remove" in invocation.options, provider_types(project_root))}
84
+ else:
85
+ data = register(state, project_root, invocation)
86
+ validate_record(state)
87
+ after = json_bytes(state)
88
+ if after != before:
89
+ atomic_write(state_file, after)
90
+ return {**data, "changed": after != before or data["changed"]}
@@ -0,0 +1,33 @@
1
+ """Read Registry JSON and reject unsupported formats before any mutation."""
2
+ from pathlib import Path
3
+ from typing import cast
4
+
5
+ from trigrams_toolkit.shared.errors import ProtocolError, require
6
+ from trigrams_toolkit.shared.state_json import optional_bytes, parse_state_json
7
+ from .model import RegistryState, validate_record
8
+ from .relations import validate_identity_graph
9
+
10
+
11
+ def read_state(path: Path) -> RegistryState:
12
+ raw = optional_bytes(path)
13
+ if raw is None:
14
+ return {"schemaVersion": 1, "modules": [], "features": [], "artifacts": [], "relations": []}
15
+ try:
16
+ value = parse_state_json(raw, bom=True)
17
+ except ValueError as error:
18
+ raise ProtocolError("io_error", f"Invalid Registry JSON: {path}") from error
19
+ try:
20
+ validate_record(value, code="invalid_schema")
21
+ state = cast(RegistryState, value)
22
+ for entity in [*state["modules"], *state["features"]]:
23
+ entity["name"] = entity["name"].strip()
24
+ require(bool(entity["name"]), "invalid_schema", "Entity names must not be blank.")
25
+ for artifact in state["artifacts"]:
26
+ artifact["title"] = artifact["title"].strip()
27
+ require(bool(artifact["title"]), "invalid_schema", "Artifact titles must not be blank.")
28
+ except ProtocolError as error:
29
+ if error.code != "invalid_schema":
30
+ raise
31
+ raise ProtocolError("invalid_schema", f"Unsupported Registry format: {path}. Archive the existing state and rebuild it with initialize.") from error
32
+ validate_identity_graph(state)
33
+ return state