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 @@
1
+ """Shared Python services and command-line tools for Trigrams toolkit."""
@@ -0,0 +1,6 @@
1
+ """Work guide discovery and package ownership."""
2
+ from .guides import Guide, GuideCatalog
3
+ from .sources import ProviderSource
4
+ from .package import ProviderPackage
5
+
6
+ __all__ = ["Guide", "GuideCatalog", "ProviderSource", "ProviderPackage"]
@@ -0,0 +1,122 @@
1
+ """Browse work guides and import approved principles into the project library."""
2
+ from __future__ import annotations
3
+
4
+ from trigrams_toolkit.version import version
5
+
6
+ from typing import NoReturn
7
+ import argparse
8
+ import json
9
+ from pathlib import Path
10
+ import sys
11
+
12
+ from trigrams_toolkit.shared.cli_help import HelpFormatter
13
+ from trigrams_toolkit.shared.errors import ProtocolError, require
14
+ from .guides import GuideCatalog
15
+ from .location import sources_for_project
16
+ from .principle_import import import_principle
17
+ from trigrams_toolkit.project_context import current_project_root
18
+ from trigrams_toolkit.resources import schema_paths
19
+ from trigrams_toolkit.shared.schema import SchemaCatalog
20
+ from trigrams_toolkit.shared.serialization import read_json
21
+ from trigrams_toolkit.shared.skill_installations import AGENTS
22
+
23
+
24
+ class Parser(argparse.ArgumentParser):
25
+ def error(self, message: str) -> NoReturn:
26
+ raise ProtocolError("invalid_arguments", message)
27
+
28
+
29
+ def _agent_option(parser: Parser) -> None:
30
+ parser.add_argument("--agent", choices=AGENTS, default=argparse.SUPPRESS,
31
+ help="Vercel skills agent for global core resources; defaults to the project installation or codex.")
32
+
33
+
34
+ def _parser() -> Parser:
35
+ parser = Parser(prog="handbook", description=f"{__doc__} Run commands from the target project root.",
36
+ formatter_class=HelpFormatter)
37
+ _agent_option(parser)
38
+ parser.add_argument("-v", "--version", action="store_true", help="Show the deployed toolkit version.")
39
+ commands = parser.add_subparsers(dest="command", parser_class=Parser, title="Commands")
40
+ descriptions = {"scopes": "List principle scope directories and workbook prefixes in the current project.",
41
+ "list": "List only resourceId and description for each guide.",
42
+ "load": "Read full IDs or unique short names, following workbook includes, with content and sources.",
43
+ "validate": "Check guide layout, headers, identities and includes references.",
44
+ "import-principle": "Import an approved draft into the project principle library."}
45
+ for command, description in descriptions.items():
46
+ child = commands.add_parser(command, help=description, description=description,
47
+ formatter_class=HelpFormatter)
48
+ _agent_option(child)
49
+ if command in ("scopes", "list"):
50
+ child.add_argument("--kind", choices=("workbook", "principle"), help="Only list this kind.")
51
+ if command == "list":
52
+ child.add_argument("--scope", action="append", default=[],
53
+ help="Match an exact scope from scopes; repeat for a union; omit for all guides.")
54
+ if command == "load":
55
+ child.add_argument("id", nargs="+", metavar="ID",
56
+ help="Full guide IDs or unique short names (scope/principle for principles).")
57
+ if command == "import-principle":
58
+ child.add_argument("file", type=Path, metavar="FILE", help="Approved UTF-8 draft; relative to the project root.")
59
+ child.add_argument("--scope", required=True, help="Principle scope, using lowercase hyphenated tokens.")
60
+ child.add_argument("--name", required=True, help="Principle name, using lowercase hyphenated tokens.")
61
+ child.add_argument("--replace", action="store_true", help="Replace an existing principle; fail if absent.")
62
+ child.epilog = ("Output: JSON with resourceId, entryPath and operation; exit 0 on success, 1 on error. "
63
+ "Existing targets require --replace. Write failures report error.current."
64
+ if command == "import-principle" else "Output: JSON; exit 0 on success, 1 on error.")
65
+ return parser
66
+
67
+
68
+
69
+ def _catalog(root: Path, args: argparse.Namespace) -> GuideCatalog:
70
+ schemas = SchemaCatalog(schema_paths())
71
+ packages = sources_for_project(root, schemas, getattr(args, "agent", None))
72
+ require(bool(packages), "missing_capability",
73
+ "No guide sources are available. Install global principles and workbook Skills for the selected agent.")
74
+ return GuideCatalog.discover(list(packages.values()), root, schemas)
75
+
76
+
77
+ def _dispatch(args: argparse.Namespace, root: Path) -> dict:
78
+ if args.command == "import-principle":
79
+ schemas = SchemaCatalog(schema_paths())
80
+ return import_principle(root, root / args.file, args.scope, args.name,
81
+ schemas, replace=args.replace, agent=getattr(args, "agent", None)).as_dict()
82
+ catalog = _catalog(root, args)
83
+ if args.command == "scopes":
84
+ return catalog.scopes(args.kind)
85
+ if args.command == "list":
86
+ return catalog.list(args.kind, args.scope)
87
+ if args.command == "load":
88
+ return catalog.load(args.id)
89
+ return catalog.validate()
90
+
91
+
92
+ def main(argv: list[str] | None = None) -> int:
93
+ if hasattr(sys.stdout, "reconfigure"):
94
+ sys.stdout.reconfigure(encoding="utf-8")
95
+ try:
96
+ parser = _parser()
97
+ try:
98
+ args = parser.parse_args(sys.argv[1:] if argv is None else argv)
99
+ except SystemExit as status:
100
+ return int(status.code or 0)
101
+ if args.version:
102
+ require(args.command is None, "invalid_arguments", "--version is a root command option.")
103
+ print(version())
104
+ return 0
105
+ require(args.command is not None, "invalid_arguments", "Choose a command; use handbook --help.")
106
+ result = _dispatch(args, current_project_root())
107
+ print(json.dumps(result, ensure_ascii=False))
108
+ return 0
109
+ except ProtocolError as error:
110
+ result = {"ok": False, "error": {"code": error.code, "message": str(error)}}
111
+ if error.conflicts:
112
+ result["error"]["conflicts"] = list(error.conflicts)
113
+ if error.current is not None:
114
+ result["error"]["current"] = error.current
115
+ except (OSError, ValueError) as error:
116
+ result = {"ok": False, "error": {"code": "io_error", "message": str(error)}}
117
+ print(json.dumps(result, ensure_ascii=False))
118
+ return 1
119
+
120
+
121
+ if __name__ == "__main__":
122
+ raise SystemExit(main())
@@ -0,0 +1,43 @@
1
+ """Read guide front matter without opening accompanying documents."""
2
+ from __future__ import annotations
3
+
4
+ from pathlib import Path
5
+ from typing import BinaryIO, Literal
6
+
7
+ import yaml
8
+ from yaml.tokens import AliasToken, AnchorToken, TagToken
9
+
10
+ from trigrams_toolkit.shared.errors import ProtocolError, require
11
+ from .package import yaml_mapping
12
+ from trigrams_toolkit.shared.schema import SchemaCatalog
13
+
14
+
15
+ def _read_header(stream: BinaryIO) -> dict:
16
+ first = stream.readline().removeprefix(b"\xef\xbb\xbf").rstrip(b"\r\n")
17
+ require(first == b"---", "invalid_schema", "Add a YAML header starting with ---.")
18
+ lines = []
19
+ for line in stream:
20
+ if line.rstrip(b"\r\n") == b"---":
21
+ break
22
+ lines.append(line)
23
+ else:
24
+ raise ProtocolError("invalid_schema", "Close the YAML header with ---.")
25
+ text = b"".join(lines).decode("utf-8")
26
+ require(not any(isinstance(token, (AliasToken, AnchorToken, TagToken)) for token in yaml.scan(text)),
27
+ "invalid_schema", "Guide headers cannot use YAML anchors, aliases or custom tags.")
28
+ value = yaml_mapping(text)
29
+ return {key: item.strip() if isinstance(item, str) else item for key, item in value.items()}
30
+
31
+
32
+ def guide_header(path: Path, schemas: SchemaCatalog, *,
33
+ kind: Literal["workbook", "principle"] | None = None) -> dict:
34
+ """Validate the explicit draft kind or derive the kind from an entry filename."""
35
+ try:
36
+ with path.open("rb") as stream:
37
+ value = _read_header(stream)
38
+ principle = kind == "principle" if kind is not None else path.name == "PRINCIPLE.md"
39
+ definition = "principleHeader" if principle else "header"
40
+ schemas.validate(f"urn:harness:guides#/$defs/{definition}", value)
41
+ return value
42
+ except (ProtocolError, yaml.YAMLError, UnicodeError) as error:
43
+ raise ProtocolError("invalid_schema", f"{path}: {error}", conflicts=(str(path),)) from error
@@ -0,0 +1,141 @@
1
+ """Read-only workbook and principle discovery and includes loading."""
2
+ from __future__ import annotations
3
+
4
+ from dataclasses import dataclass
5
+ from pathlib import Path
6
+ from typing import Sequence
7
+
8
+ from trigrams_toolkit.shared.errors import require
9
+ from .guide_headers import guide_header
10
+ from .package import ProviderPackage, load_packages, manifest_owner
11
+ from trigrams_toolkit.shared.paths import path_key
12
+ from trigrams_toolkit.shared.schema import SchemaCatalog
13
+
14
+ ENTRY_KINDS = {"WORKBOOK.md": "workbook", "PRINCIPLE.md": "principle"}
15
+
16
+
17
+ @dataclass(frozen=True)
18
+ class Guide:
19
+ resource_id: str
20
+ kind: str
21
+ path: Path
22
+ source: Path
23
+ header: dict
24
+
25
+ @property
26
+ def scope(self) -> str:
27
+ if self.kind == "principle":
28
+ return self.path.parent.parent.name
29
+ return self.path.parent.name.split("-", 1)[0]
30
+
31
+ def description(self) -> dict:
32
+ name = self.path.parent.name if self.kind == "principle" else self.header["name"]
33
+ result = {"resourceId": self.resource_id, "kind": self.kind, "name": name,
34
+ "description": self.header["description"], "entryPath": str(self.path), "source": str(self.source)}
35
+ if self.header.get("includes"):
36
+ result["includes"] = self.header["includes"]
37
+ return result
38
+
39
+
40
+ def _guide(path: Path, package: ProviderPackage, schemas: SchemaCatalog, source: Path) -> Guide:
41
+ kind = ENTRY_KINDS[path.name]
42
+ header = guide_header(path, schemas)
43
+ provider = manifest_owner(package.manifest)
44
+ if kind == "principle":
45
+ require(path.parent.parent.parent.name == "principles", "invalid_schema",
46
+ "Principles require principles/<scope>/<principle>/PRINCIPLE.md.", str(path))
47
+ for name in (path.parent.parent.name, path.parent.name):
48
+ schemas.validate("urn:harness:common#/$defs/token", name)
49
+ identity = f"{provider}:principle:{path.parent.parent.name}/{path.parent.name}"
50
+ else:
51
+ identity = header.get("resourceId", f"{provider}:{kind}:{path.parent.name}")
52
+ schemas.validate("urn:harness:guides#/$defs/guideId", identity)
53
+ require(identity.split(":")[:2] == [provider, kind], "identity_conflict",
54
+ f"Guide ID must match its package and entry kind: {identity}", str(path))
55
+ return Guide(identity, kind, path, source, header)
56
+
57
+
58
+ class GuideCatalog:
59
+ def __init__(self, packages: dict[str, ProviderPackage], schemas: SchemaCatalog) -> None:
60
+ self.packages = packages
61
+ self._guides: dict[str, Guide] = {}
62
+ physical: set[str] = set()
63
+ for package in packages.values():
64
+ self._index_package(package, schemas, physical)
65
+
66
+ def _index_package(self, package: ProviderPackage, schemas: SchemaCatalog, physical: set[str]) -> None:
67
+ for source in package.sources:
68
+ for path in source.resource_paths:
69
+ guide = _guide(path, package, schemas, source.root)
70
+ require(guide.resource_id not in self._guides, "resource_conflict",
71
+ f"Duplicate guide ID: {guide.resource_id}", str(guide.path))
72
+ require(path_key(guide.path) not in physical, "resource_conflict",
73
+ f"Guide entry has multiple source paths: {guide.path}")
74
+ physical.add(path_key(guide.path))
75
+ self._guides[guide.resource_id] = guide
76
+
77
+ @classmethod
78
+ def discover(cls, roots: Sequence[Path | ProviderPackage], project: Path,
79
+ schemas: SchemaCatalog) -> GuideCatalog:
80
+ return cls(load_packages(list(roots), project, schemas), schemas)
81
+
82
+ def resolve(self, identity: str) -> Guide:
83
+ exact = self._guides.get(identity)
84
+ if exact is not None:
85
+ return exact
86
+ candidates = [self._guides[key] for key in sorted(self._guides)
87
+ if key.rsplit(":", 1)[-1] == identity]
88
+ require(bool(candidates), "invalid_reference", f"Guide unavailable: {identity}. Use handbook list.")
89
+ require(len(candidates) == 1, "resource_conflict",
90
+ f"Guide name is ambiguous: {identity}. Use a full ID.",
91
+ *(guide.resource_id for guide in candidates))
92
+ return candidates[0]
93
+
94
+ def scopes(self, kind: str | None = None) -> dict:
95
+ return {"ok": True, "scopes": sorted({guide.scope for guide in self._guides.values()
96
+ if kind is None or guide.kind == kind})}
97
+
98
+ def list(self, kind: str | None = None, scopes: Sequence[str] = ()) -> dict:
99
+ requested = set(scopes)
100
+ values = []
101
+ for identity in sorted(self._guides):
102
+ guide = self._guides[identity]
103
+ if kind is not None and kind != guide.kind:
104
+ continue
105
+ if requested and guide.scope not in requested:
106
+ continue
107
+ values.append({"resourceId": guide.resource_id, "description": guide.header["description"]})
108
+ return {"ok": True, "resources": values}
109
+
110
+ def _closure(self, identity: str, ancestors: tuple[str, ...], selected: dict[str, Guide]) -> None:
111
+ require(identity not in ancestors, "invalid_reference",
112
+ f"Guide includes cycle: {' -> '.join((*ancestors, identity))}")
113
+ if identity in selected:
114
+ return
115
+ guide = self._guides.get(identity)
116
+ require(guide is not None, "invalid_reference", f"Included guide unavailable: {identity}.")
117
+ assert guide is not None
118
+ if guide.kind == "workbook":
119
+ for child in guide.header.get("includes", []):
120
+ self._closure(child, (*ancestors, identity), selected)
121
+ selected[identity] = guide
122
+
123
+ def load(self, identities: str | Sequence[str]) -> dict:
124
+ inputs = [identities] if isinstance(identities, str) else identities
125
+ require(bool(inputs), "invalid_arguments", "Provide at least one guide ID.")
126
+ selected_ids = list(dict.fromkeys(self.resolve(identity).resource_id for identity in inputs))
127
+ selected: dict[str, Guide] = {}
128
+ for identity in selected_ids:
129
+ self._closure(identity, (), selected)
130
+ values = [{**item.description(), "content": item.path.read_text(encoding="utf-8-sig")}
131
+ for item in selected.values()]
132
+ result = {"ok": True, "selectedIds": selected_ids, "resources": values}
133
+ if len(inputs) == 1:
134
+ result["selected"] = selected_ids[0]
135
+ return result
136
+
137
+ def validate(self) -> dict:
138
+ for identity in self._guides:
139
+ self._closure(identity, (), {})
140
+ return {"ok": True, "checkedSources": sorted({str(package.root) for package in self.packages.values()}),
141
+ "resourceIds": sorted(self._guides)}
@@ -0,0 +1,79 @@
1
+ """Resolve package declarations and installed guide source boundaries."""
2
+ from __future__ import annotations
3
+
4
+ from pathlib import Path, PurePosixPath
5
+
6
+ from trigrams_toolkit.installation.installation_sources import read_installation
7
+ from trigrams_toolkit.shared.errors import require
8
+ from trigrams_toolkit.shared.paths import confined, is_link
9
+ from trigrams_toolkit.shared.skill_installations import skill_agent
10
+ from trigrams_toolkit.shared.schema import SchemaCatalog
11
+ from trigrams_toolkit.shared.serialization import read_json
12
+ from .package import ProviderPackage, load_packages, manifest_owner, package_manifest
13
+ from .skill_sources import global_core
14
+ from .sources import ProviderSource
15
+
16
+
17
+ def project_provider_root(project: Path) -> Path | None:
18
+ root = confined(project, "docs")
19
+ path = confined(root, "resources.json")
20
+ if not path.is_file():
21
+ return None
22
+ value = read_json(path)
23
+ return root if isinstance(value, dict) and value.get("source") == "project" else None
24
+
25
+
26
+ def _snapshot_file(project: Path, relative: str) -> Path:
27
+ target = project / relative
28
+ require(target == confined(project, relative) and target.is_file(), "invalid_reference",
29
+ f"Snapshot file must be a regular project file: {relative}")
30
+ return target
31
+
32
+
33
+ def _installed_extension(project: Path, item: dict, managed: list[dict],
34
+ schemas: SchemaCatalog, *, guides: bool) -> ProviderPackage:
35
+ extension = item["extension"]
36
+ prefix = f".agents/extensions/{extension}"
37
+ container = project / prefix
38
+ require(not any(is_link(part) for part in (project / ".agents", container.parent, container)),
39
+ "invalid_reference", f"Extension container must be a real directory: {container}")
40
+ confined(project, prefix)
41
+ records = {record["path"]: record for record in managed if record["source"] == extension}
42
+ relative = prefix + "/extension.json"
43
+ require(relative in records, "invalid_reference", f"Snapshot declaration is not registered: {relative}")
44
+ _snapshot_file(project, relative)
45
+ manifest = package_manifest(container, schemas, filename="extension.json", expected_provider=extension)
46
+ require(manifest["version"] == item["version"],
47
+ "identity_conflict", f"Installed snapshot identity or version differs: {relative}")
48
+ if not guides:
49
+ return ProviderPackage(container, manifest, ())
50
+ starts = [PurePosixPath(prefix, name) for name in manifest["resourceRoots"]]
51
+ entries = tuple(_snapshot_file(project, rel) for rel in sorted(records)
52
+ if PurePosixPath(rel).name in ("WORKBOOK.md", "PRINCIPLE.md")
53
+ and any(PurePosixPath(rel).is_relative_to(start) for start in starts))
54
+ return ProviderPackage(container, manifest, (ProviderSource(container, "installed-resource", entries),))
55
+
56
+
57
+ def installed_extensions(project: Path, record: dict | None, schemas: SchemaCatalog,
58
+ *, guides: bool = True) -> list[ProviderPackage]:
59
+ if record is None:
60
+ return []
61
+ return [_installed_extension(project, item, record["managed"], schemas, guides=guides)
62
+ for item in record["extensions"]]
63
+
64
+
65
+ def sources_for_project(project: Path, schemas: SchemaCatalog,
66
+ agent: str | None = None) -> dict[str, ProviderPackage]:
67
+ """Resolve current provider declarations without Plan or Registry reads."""
68
+ project = project.resolve()
69
+ record = read_installation(project, schemas)
70
+ core = global_core(skill_agent(agent or (record or {}).get("agent")))
71
+ packages: dict[str, ProviderPackage] = {}
72
+ if core is not None:
73
+ packages["core"] = core
74
+ for package in installed_extensions(project, record, schemas):
75
+ packages[manifest_owner(package.manifest)] = package
76
+ local = project_provider_root(project)
77
+ if local is not None:
78
+ packages.update(load_packages([local], project, schemas))
79
+ return dict(sorted(packages.items()))
@@ -0,0 +1,4 @@
1
+ """JSON values at the resource protocol boundary."""
2
+ from typing import Any
3
+
4
+ JsonObject = dict[str, Any]
@@ -0,0 +1,165 @@
1
+ """Package metadata and declared resource source boundaries."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+ import os
7
+ from pathlib import Path
8
+
9
+ import yaml
10
+
11
+ from trigrams_toolkit.shared.errors import ProtocolError, require
12
+ from .model import JsonObject
13
+ from trigrams_toolkit.shared.paths import confined, files_under, path_key
14
+ from .sources import ProviderSource
15
+ from trigrams_toolkit.shared.schema import SchemaCatalog
16
+ from trigrams_toolkit.shared.serialization import read_json
17
+
18
+ _GENERATED = frozenset({".agents", ".git", "node_modules", "__pycache__",
19
+ ".pytest_cache", ".cache"})
20
+ _RUNTIME_CACHE = frozenset({"__pycache__", ".pytest_cache", ".cache"})
21
+
22
+
23
+ class _UniqueYaml(yaml.SafeLoader):
24
+ pass
25
+
26
+
27
+ def _yaml_object(loader: _UniqueYaml, node: yaml.MappingNode) -> dict:
28
+ result = {}
29
+ for key_node, value_node in node.value:
30
+ key = loader.construct_object(key_node, deep=True)
31
+ require(isinstance(key, str) and key not in result, "invalid_json", "Duplicate/non-string YAML key.")
32
+ result[key] = loader.construct_object(value_node, deep=True)
33
+ return result
34
+
35
+
36
+ _UniqueYaml.add_constructor(yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG, _yaml_object)
37
+
38
+
39
+ def yaml_mapping(source: str) -> JsonObject:
40
+ try:
41
+ value = yaml.load(source, Loader=_UniqueYaml)
42
+ except yaml.YAMLError as error:
43
+ raise ProtocolError("invalid_json", "Invalid YAML metadata.") from error
44
+ require(isinstance(value, dict), "invalid_schema", "Metadata must be a mapping.")
45
+ return value
46
+
47
+
48
+ def _generated(relative: str) -> bool:
49
+ return any(os.path.normcase(part) in _GENERATED for part in relative.split("/"))
50
+
51
+
52
+ def runtime_cache(relative: str) -> bool:
53
+ """Interpreter/test caches are excluded from managed sources."""
54
+ return relative.endswith(".pyc") or any(part in _RUNTIME_CACHE for part in relative.split("/"))
55
+
56
+
57
+ @dataclass(frozen=True)
58
+ class ProviderPackage:
59
+ root: Path
60
+ manifest: JsonObject
61
+ sources: tuple[ProviderSource, ...]
62
+
63
+
64
+ def manifest_owner(manifest: JsonObject) -> str:
65
+ owner = manifest.get("extension") or manifest.get("source")
66
+ require(isinstance(owner, str) and bool(owner), "invalid_schema", "Manifest owner is missing.")
67
+ assert isinstance(owner, str)
68
+ return owner
69
+
70
+
71
+ def package_manifest(root: Path, schemas: SchemaCatalog, *, filename: str = "resources.json",
72
+ expected_provider: str | None = None) -> JsonObject:
73
+ """Read the complete package declaration without reading source payloads."""
74
+ path = confined(root, filename)
75
+ require(path.is_file(), "invalid_schema",
76
+ f"Resource declaration is missing: {path}.", str(root))
77
+ return _validate_manifest(read_json(path), path, schemas, expected_provider)
78
+
79
+
80
+ def _validate_manifest(manifest: JsonObject, path: Path, schemas: SchemaCatalog,
81
+ expected_provider: str | None = None) -> JsonObject:
82
+ if isinstance(manifest, dict):
83
+ manifest = {key: value for key, value in manifest.items() if key != "contentDigest"}
84
+ schema_id = (
85
+ "urn:harness:guides#/$defs/extensionManifest" if path.name == "extension.json"
86
+ else "urn:harness:guides#/$defs/resourceManifest" if path.name == "resources.json"
87
+ else "urn:harness:guides#/$defs/package"
88
+ )
89
+ try:
90
+ schemas.validate(schema_id, manifest)
91
+ except ProtocolError as error:
92
+ recovery = " Archive previous state and rebuild." if path.name == "resources.json" else ""
93
+ raise ProtocolError(error.code, f"{path}: {error}.{recovery}",
94
+ conflicts=(str(path),)) from error
95
+ owner = manifest_owner(manifest)
96
+ require(expected_provider is None or expected_provider == owner, "identity_conflict",
97
+ f"Expected {expected_provider}, found {owner}: {path}")
98
+ for kind in manifest.get("artifactTypes", []) + [item["kind"] for item in manifest.get("relationTypes", [])]:
99
+ require(kind.split(":")[0] == owner, "invalid_reference", f"Foreign type: {kind}")
100
+ return manifest
101
+
102
+
103
+ def resource_root(root: Path, relative: str) -> Path:
104
+ """Validate the shared guide source boundary without scanning its content."""
105
+ start = confined(root, relative)
106
+ require(not _generated(relative), "invalid_reference", f"Generated resource root: {relative}")
107
+ return start
108
+
109
+
110
+ def resource_paths(root: Path, roots: list[str] | None, *, split: bool = False) -> tuple[Path, ...]:
111
+ """Find guide entries within each declared physical source boundary."""
112
+ root = root.resolve()
113
+ if roots is None:
114
+ roots = [child.name for child in sorted(root.iterdir()) if not _generated(child.name)]
115
+ paths: dict[str, Path] = {}
116
+ for relative in roots:
117
+ start = resource_root(root, relative)
118
+ if split and not start.exists():
119
+ continue
120
+ for path in files_under(root, start, exclude=_generated):
121
+ name = path.relative_to(root).as_posix()
122
+ if runtime_cache(name):
123
+ continue
124
+ require(not (_generated(name) or _generated(path.resolve().relative_to(root).as_posix())),
125
+ "invalid_reference", "Generated content cannot be a guide source.", str(path))
126
+ require(path.name not in ("resource.json", "resource.yaml", "resource.yml", "provider.json", "package.json", "extension.json", "resources.json"),
127
+ "invalid_schema", f"Unsupported guide declaration: {path}. Archive previous state and rebuild.")
128
+ if path.name in ("WORKBOOK.md", "PRINCIPLE.md"):
129
+ key = path_key(path)
130
+ require(key not in paths, "resource_conflict", "Guide entry has multiple physical paths.", str(path))
131
+ paths[key] = path
132
+ return tuple(paths.values())
133
+
134
+
135
+ def load_packages(roots: list[Path | ProviderPackage], project: Path, schemas: SchemaCatalog) -> dict[str, ProviderPackage]:
136
+ """Load complete provider packages and preserve their physical owners."""
137
+ packages: dict[str, ProviderPackage] = {}
138
+ seen_roots: set[str] = set()
139
+ for supplied in roots:
140
+ if isinstance(supplied, ProviderPackage):
141
+ name = "extension.json" if "extension" in supplied.manifest else "resources.json"
142
+ _validate_manifest(supplied.manifest, supplied.root / name, schemas)
143
+ package = supplied
144
+ else:
145
+ require(supplied.is_absolute(), "path_outside_root", "Source roots must be absolute.", str(supplied))
146
+ root = supplied.resolve()
147
+ key = path_key(root)
148
+ if key in seen_roots:
149
+ continue
150
+ seen_roots.add(key)
151
+ filename = "extension.json" if (root / "extension.json").is_file() else "resources.json"
152
+ manifest = package_manifest(root, schemas, filename=filename)
153
+ source = ProviderSource(root, "package", resource_paths(root, manifest["resourceRoots"]), tuple(manifest["install"]))
154
+ package = ProviderPackage(root, manifest, (source,))
155
+ owner = manifest_owner(package.manifest)
156
+ require(owner != "project" or package.root.is_relative_to(project.resolve()), "path_outside_root",
157
+ "The project resource source must belong to the current project.", str(package.root))
158
+ require(owner not in packages, "resource_conflict", f"Multiple package sources for source: {owner}")
159
+ packages[owner] = package
160
+ return packages
161
+
162
+
163
+ def load_package(root: Path, project: Path, schemas: SchemaCatalog) -> ProviderPackage:
164
+ packages = load_packages([root], project, schemas)
165
+ return next(iter(packages.values()))