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,101 @@
1
+ """Import an approved principle draft into the authoritative project library."""
2
+ from __future__ import annotations
3
+
4
+ from dataclasses import dataclass
5
+ from pathlib import Path
6
+ from typing import Literal
7
+
8
+ from trigrams_toolkit.shared.errors import ProtocolError, require
9
+ from trigrams_toolkit.shared.files import atomic_write
10
+ from .guide_headers import guide_header
11
+ from .guides import GuideCatalog
12
+ from .location import sources_for_project
13
+ from trigrams_toolkit.shared.paths import confined, path_key
14
+ from .project_resources import prepare_project_resources
15
+ from trigrams_toolkit.shared.schema import SchemaCatalog
16
+
17
+
18
+ @dataclass(frozen=True)
19
+ class PrincipleImportResult:
20
+ resource_id: str
21
+ entry_path: Path
22
+ operation: Literal["created", "updated"]
23
+
24
+ def as_dict(self) -> dict:
25
+ return {"ok": True, "resourceId": self.resource_id,
26
+ "entryPath": str(self.entry_path), "operation": self.operation}
27
+
28
+
29
+ def import_principle(project: Path, source: Path, scope: str, name: str,
30
+ schemas: SchemaCatalog, *, replace: bool = False, agent: str | None = None) -> PrincipleImportResult:
31
+ """Preflight, publish declaration/body, then confirm the real discovery chain.
32
+
33
+ Source bytes survive unchanged. Write/discovery failures retain partial files
34
+ and report their confirmed state through ProtocolError.current.
35
+ """
36
+ for label, token in (("scope", scope), ("name", name)):
37
+ try:
38
+ schemas.validate("urn:harness:common#/$defs/token", token)
39
+ except ProtocolError as error:
40
+ raise ProtocolError("invalid_arguments", f"Invalid principle {label}: {token}") from error
41
+ try:
42
+ project, source = project.resolve(), source.resolve()
43
+ entry = confined(project, f"docs/knowledge/principles/{scope}/{name}/PRINCIPLE.md")
44
+ require(source.is_file(), "invalid_reference", f"Draft file is unavailable: {source}", str(source))
45
+ exists = entry.exists()
46
+ require(not exists or not source.samefile(entry), "invalid_arguments",
47
+ "The draft and formal entry must be different files.", str(source))
48
+ raw = _draft_bytes(source, schemas)
49
+ if replace:
50
+ require(entry.is_file(), "invalid_reference", f"Replacement target is unavailable: {entry}", str(entry))
51
+ else:
52
+ require(not exists, "resource_conflict", f"Principle already exists; use --replace: {entry}", str(entry))
53
+ declaration = prepare_project_resources(project, ["knowledge/principles"], schemas)
54
+ except OSError as error:
55
+ raise ProtocolError("io_error", f"Cannot prepare principle import: {error}") from error
56
+
57
+ identity = f"project:principle:{scope}/{name}"
58
+ current = {"packagePath": str(declaration.path), "packageWritten": False,
59
+ "entryPath": str(entry), "entryWritten": False}
60
+ try:
61
+ current["packageWritten"] = declaration.write()
62
+ try:
63
+ atomic_write(entry, raw)
64
+ except OSError:
65
+ current["entryWritten"] = _written(entry, raw)
66
+ raise
67
+ current["entryWritten"] = True
68
+ packages = sources_for_project(project, schemas, agent)
69
+ catalog = GuideCatalog.discover(list(packages.values()), project, schemas)
70
+ require(path_key(catalog.resolve(identity).path) == path_key(entry), "identity_conflict",
71
+ f"Imported identity resolves to another entry: {identity}")
72
+ except ProtocolError as error:
73
+ raise ProtocolError(error.code, str(error), conflicts=error.conflicts,
74
+ current={**current, **(error.current or {})}) from error
75
+ except OSError as error:
76
+ raise ProtocolError("io_error", f"Cannot complete principle import: {error}", current=current) from error
77
+ return PrincipleImportResult(identity, entry, "updated" if replace else "created")
78
+
79
+
80
+ def _draft_bytes(source: Path, schemas: SchemaCatalog) -> bytes:
81
+ """Validate principle metadata and a nonblank UTF-8 body without rewriting."""
82
+ guide_header(source, schemas, kind="principle")
83
+ raw = source.read_bytes()
84
+ try:
85
+ lines = raw.decode("utf-8-sig").splitlines()
86
+ except UnicodeError as error:
87
+ raise ProtocolError("invalid_schema", f"Draft must be UTF-8: {source}", conflicts=(str(source),)) from error
88
+ closing = next(index for index, line in enumerate(lines[1:], 1) if line == "---")
89
+ require(bool("\n".join(lines[closing + 1:]).strip()), "invalid_schema",
90
+ f"Principle draft body is empty: {source}", str(source))
91
+ return raw
92
+
93
+
94
+ def _written(path: Path, raw: bytes) -> bool | None:
95
+ """Confirm a failed publication's actual target; unreadable results stay unknown."""
96
+ try:
97
+ return path.read_bytes() == raw
98
+ except (FileNotFoundError, NotADirectoryError):
99
+ return False
100
+ except OSError:
101
+ return None
@@ -0,0 +1,80 @@
1
+ """Prepare and publish the project package declaration for resource imports."""
2
+ from __future__ import annotations
3
+
4
+ from dataclasses import dataclass
5
+ from pathlib import Path
6
+ from typing import Sequence, Any
7
+
8
+ from trigrams_toolkit.shared.errors import ProtocolError, require
9
+ from trigrams_toolkit.shared.files import atomic_write
10
+ from .package import manifest_owner, package_manifest, resource_root
11
+ from trigrams_toolkit.shared.paths import confined
12
+ from trigrams_toolkit.shared.schema import SchemaCatalog
13
+ from trigrams_toolkit.shared.serialization import canonical
14
+
15
+
16
+ @dataclass(frozen=True)
17
+ class ProjectResourceDeclaration:
18
+ """A validated preparation; callers use path, changed and write()."""
19
+
20
+ path: Path
21
+ changed: bool
22
+ _content: bytes
23
+
24
+ def write(self) -> bool:
25
+ """Publish changed bytes; report the actual file result after I/O failure."""
26
+ if not self.changed:
27
+ return False
28
+ try:
29
+ atomic_write(self.path, self._content)
30
+ except OSError as error:
31
+ try:
32
+ written = self.path.read_bytes() == self._content
33
+ except (FileNotFoundError, NotADirectoryError):
34
+ written = False
35
+ except OSError:
36
+ written = None
37
+ raise ProtocolError("io_error", f"Cannot publish project declaration {self.path}: {error}",
38
+ current={"packagePath": str(self.path), "packageWritten": written}) from error
39
+ return True
40
+
41
+
42
+ def prepare_project_resources(project: Path, resource_roots: Sequence[str],
43
+ schemas: SchemaCatalog) -> ProjectResourceDeclaration:
44
+ """Validate and merge roots without creating directories or files.
45
+
46
+ Existing fields and root spellings survive. An existing parent covers its
47
+ descendants; a requested parent conflicting with an existing child fails.
48
+ """
49
+ docs = confined(project, "docs")
50
+ path = confined(project, "docs/resources.json")
51
+ try:
52
+ exists = path.exists()
53
+ manifest: dict[str, Any] = package_manifest(docs, schemas, filename="resources.json") if exists else {
54
+ "schemaVersion": 1, "source": "project", "version": "1.0.0",
55
+ "resourceRoots": [], "install": []}
56
+ require(manifest_owner(manifest) == "project", "identity_conflict",
57
+ f"Project declaration source must be project: {path}", str(path))
58
+ roots = list(manifest["resourceRoots"])
59
+ locations: list[Path] = []
60
+ for relative in roots:
61
+ location = resource_root(docs, relative)
62
+ require(not any(location.is_relative_to(existing) or existing.is_relative_to(location)
63
+ for existing in locations), "resource_conflict",
64
+ f"Project resource roots overlap: {relative}", str(path))
65
+ locations.append(location)
66
+ changed = not exists
67
+ for relative in resource_roots:
68
+ requested = resource_root(docs, relative)
69
+ if any(requested.is_relative_to(existing) for existing in locations):
70
+ continue
71
+ require(not any(existing.is_relative_to(requested) for existing in locations),
72
+ "resource_conflict", f"Requested resource root overlaps an existing child: {relative}", str(path))
73
+ roots.append(relative)
74
+ locations.append(requested)
75
+ changed = True
76
+ manifest = {**manifest, "resourceRoots": roots}
77
+ schemas.validate("urn:harness:guides#/$defs/resourceManifest", manifest)
78
+ return ProjectResourceDeclaration(path, changed, canonical(manifest) + b"\n")
79
+ except OSError as error:
80
+ raise ProtocolError("io_error", f"Cannot prepare project declaration {path}: {error}") from error
@@ -0,0 +1,59 @@
1
+ """Guide sources carried by installed core and extension setup Skills."""
2
+ from __future__ import annotations
3
+
4
+ from pathlib import Path
5
+
6
+ from trigrams_toolkit.shared.errors import require
7
+ from trigrams_toolkit.shared.paths import confined
8
+ from trigrams_toolkit.shared.schema import SchemaCatalog
9
+ from trigrams_toolkit.shared.skill_installations import SkillAgent, installed_skill, skill_directory
10
+ from .package import ProviderPackage, package_manifest, resource_paths, yaml_mapping
11
+ from .sources import ProviderSource
12
+
13
+
14
+ def _check_name(root: Path, expected: str) -> None:
15
+ path = confined(root, "SKILL.md")
16
+ with path.open(encoding="utf-8-sig") as stream:
17
+ opener = stream.readline().rstrip("\r\n")
18
+ lines = []
19
+ for line in stream:
20
+ if line.rstrip("\r\n") == "---":
21
+ break
22
+ lines.append(line)
23
+ else:
24
+ lines.clear()
25
+ require(opener == "---" and bool(lines) and yaml_mapping("".join(lines)).get("name") == expected,
26
+ "identity_conflict", f"Expected Skill name {expected}: {path}.")
27
+
28
+
29
+ def global_core(agent: SkillAgent) -> ProviderPackage | None:
30
+ sources = []
31
+ for skill, directory in (("principles", "principles"), ("workbook", "workbooks")):
32
+ root = installed_skill(skill, agent, required=False)
33
+ if root is not None:
34
+ _check_name(root, skill)
35
+ sources.append(ProviderSource(root, "installed-skill", resource_paths(root, [directory])))
36
+ if not sources:
37
+ return None
38
+ manifest = {"schemaVersion": 1, "source": "core", "version": "1.0.0",
39
+ "resourceRoots": [], "install": []}
40
+ return ProviderPackage(skill_directory(agent), manifest, tuple(sources))
41
+
42
+
43
+ def setup_package(project: Path, provider: str, agent: SkillAgent, schemas: SchemaCatalog) -> ProviderPackage:
44
+ name = f"extension-setup-{provider}"
45
+ skill = installed_skill(name, agent, project)
46
+ assert skill is not None
47
+ _check_name(skill, name)
48
+ root = confined(skill, "assets")
49
+ manifest = package_manifest(root, schemas, filename="extension.json", expected_provider=provider)
50
+ paths = snapshot_resource_paths(root, manifest)
51
+ return ProviderPackage(root, manifest, (ProviderSource(root, "installed-skill", paths),))
52
+
53
+
54
+ def snapshot_resource_paths(root: Path, manifest: dict) -> tuple[Path, ...]:
55
+ for name in manifest["resourceRoots"]:
56
+ require(name.split("/")[0] in ("principles", "workbooks"), "invalid_reference",
57
+ f"Snapshot resources must be in principles/ or workbooks/: {name}")
58
+ require(confined(root, name).is_dir(), "invalid_reference", f"Resource directory is missing: {root / name}")
59
+ return resource_paths(root, manifest["resourceRoots"])
@@ -0,0 +1,55 @@
1
+ """Read repository provider declarations without generating runtime payloads."""
2
+ from __future__ import annotations
3
+
4
+ from pathlib import Path
5
+
6
+ from trigrams_toolkit.shared.errors import require
7
+ from .guides import GuideCatalog
8
+ from .package import ProviderPackage, resource_paths
9
+ from trigrams_toolkit.shared.paths import confined
10
+ from trigrams_toolkit.resources import resource_path, schema_paths
11
+ from trigrams_toolkit.shared.schema import SchemaCatalog
12
+ from trigrams_toolkit.shared.serialization import read_json
13
+ from .sources import ProviderSource
14
+
15
+
16
+ def source_packages(toolkit: Path, schemas: SchemaCatalog) -> list[ProviderPackage]:
17
+ """Compose source-only declarations; core types have one contract authority."""
18
+ toolkit = toolkit.resolve()
19
+ manifest = read_json(toolkit / "toolkit.json")
20
+ components = [("core", manifest["core"]), *manifest.get("extensions", {}).items()]
21
+ packages = []
22
+ for provider, component in components:
23
+ relative = component.get("manifest") or component["package"]
24
+ path = confined(toolkit, relative)
25
+ require(not (toolkit / relative).is_symlink(), "path_outside_root",
26
+ f"Linked resource declaration: {path}")
27
+ declaration = read_json(path)
28
+ require(isinstance(declaration, dict), "invalid_schema", f"Resource declaration must be an object: {path}")
29
+ owner = declaration.get("source") if provider == "core" else declaration.get("extension")
30
+ require(owner == provider, "identity_conflict",
31
+ f"Resource declaration differs from toolkit index: {path}")
32
+ if provider == "core":
33
+ require(not {"artifactTypes", "relationTypes"} & declaration.keys(), "invalid_schema",
34
+ "Core types belong only in resources/state/core-types.json.")
35
+ types = read_json(resource_path("state/core-types.json"))
36
+ declaration = {**declaration, "artifactTypes": types["artifactTypes"],
37
+ "relationTypes": types["relationTypes"]}
38
+ schema_id = ("urn:harness:guides#/$defs/resourceManifest" if provider == "core"
39
+ else "urn:harness:guides#/$defs/extensionManifest")
40
+ schemas.validate(schema_id, declaration)
41
+ for kind in declaration.get("artifactTypes", []) + [item["kind"] for item in declaration.get("relationTypes", [])]:
42
+ require(kind.split(":")[0] == provider, "invalid_reference", f"Foreign provider type: {kind}")
43
+ root = path.parent
44
+ source = ProviderSource(root, "package", resource_paths(root, declaration["resourceRoots"]),
45
+ tuple(declaration.get("install", [])))
46
+ packages.append(ProviderPackage(root, declaration, (source,)))
47
+ return packages
48
+
49
+
50
+ def validate_source_catalog(toolkit: Path) -> dict:
51
+ """Validate provider identities, guide metadata and cross-resource references."""
52
+ schemas = SchemaCatalog(schema_paths())
53
+ catalog = GuideCatalog.discover(source_packages(toolkit, schemas), toolkit, schemas)
54
+ catalog.validate()
55
+ return {"resources": len(catalog.list()["resources"]), "sources": sorted(catalog.packages)}
@@ -0,0 +1,16 @@
1
+ """Physical ownership boundaries for complete packages and installed guides."""
2
+ from __future__ import annotations
3
+
4
+ from dataclasses import dataclass
5
+ from pathlib import Path
6
+ from typing import Any, Literal
7
+
8
+
9
+ @dataclass(frozen=True)
10
+ class ProviderSource:
11
+ """Discover entry paths without reading bodies or computing source hashes."""
12
+
13
+ root: Path
14
+ kind: Literal["package", "installed-resource", "installed-skill"]
15
+ resource_paths: tuple[Path, ...]
16
+ install: tuple[dict[str, Any], ...] = ()
File without changes
@@ -0,0 +1,50 @@
1
+ """Move explicitly selected project paths out of the active tool layout."""
2
+ from datetime import datetime, timezone
3
+ from pathlib import Path
4
+ from uuid import uuid4
5
+
6
+ from trigrams_toolkit.shared.errors import require
7
+ from trigrams_toolkit.shared.paths import confined, is_link, relative_path
8
+
9
+
10
+ def archive_project(root: Path, paths: list[str]) -> dict:
11
+ root = root.resolve()
12
+ require(root.is_dir(), "invalid_reference", "Archive root must be an existing project directory.")
13
+ require(bool(paths), "invalid_arguments", "Select the project paths to archive.")
14
+ sources: list[tuple[Path, Path]] = []
15
+ for name in paths:
16
+ relative_path(name)
17
+ relative = Path(name)
18
+ parent = root if relative.parent == Path(".") else confined(root, relative.parent.as_posix())
19
+ source = parent / relative.name
20
+ linked = is_link(source)
21
+ # The selected link itself is the archived object.
22
+ if not linked:
23
+ source = confined(root, name)
24
+ require(all(path.parts[0].casefold() not in (".git", ".harness-archive")
25
+ for path in (relative, source.relative_to(root))),
26
+ "invalid_reference", "Archive selections cannot include Git or archive storage.")
27
+ require(linked or source.exists(), "invalid_reference", f"Archive source missing: {name}")
28
+ for selected, actual in sources:
29
+ require(not (relative.is_relative_to(selected) or selected.is_relative_to(relative)
30
+ or source.is_relative_to(actual) or actual.is_relative_to(source)),
31
+ "invalid_arguments", "Archive selections overlap.")
32
+ sources.append((relative, source))
33
+ destination = root / ".harness-archive"
34
+ require(not is_link(destination) and destination.resolve().is_relative_to(root),
35
+ "path_outside_root", "Archive storage escapes the project.")
36
+ batch = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ") + "-" + uuid4().hex[:8]
37
+ destination = destination / batch
38
+ moved = []
39
+ try:
40
+ for relative, source in sources:
41
+ target = destination / relative
42
+ target.parent.mkdir(parents=True, exist_ok=True)
43
+ source.rename(target)
44
+ moved.append((source, target))
45
+ except OSError:
46
+ for source, target in reversed(moved):
47
+ source.parent.mkdir(parents=True, exist_ok=True)
48
+ target.rename(source)
49
+ raise
50
+ return {"archive": str(destination), "paths": [relative.as_posix() for relative, _ in sources]}
@@ -0,0 +1,45 @@
1
+ """Complete missing global Skills for the confirmed installation agent."""
2
+ from __future__ import annotations
3
+
4
+ import os
5
+ from pathlib import Path
6
+ import shutil
7
+ from subprocess import DEVNULL, TimeoutExpired, run
8
+
9
+ from trigrams_toolkit.resources import resource_path
10
+ from trigrams_toolkit.shared.errors import ProtocolError
11
+ from trigrams_toolkit.shared.serialization import read_json
12
+ from trigrams_toolkit.shared.skill_installations import SkillAgent, skill_directory
13
+
14
+
15
+ def _failure(agent: SkillAgent, name: str, reason: str, *, code: str = "dependency_failed") -> ProtocolError:
16
+ return ProtocolError(code, f"Global Skill {name} for {agent.name}: {reason}",
17
+ details={"skill": name, "agent": agent.name})
18
+
19
+
20
+ def ensure_global_skills(agent: SkillAgent, project: Path) -> None:
21
+ directory = skill_directory(agent)
22
+ dependencies = read_json(resource_path("installation/global-skills.json"))["dependencies"]
23
+ missing = [item for item in dependencies if not (directory / item["name"] / "SKILL.md").is_file()]
24
+ if not missing:
25
+ return
26
+ npx = shutil.which("npx.cmd" if os.name == "nt" else "npx")
27
+ if npx is None:
28
+ raise _failure(agent, missing[0]["name"], "npx is unavailable. Install Node.js with npm and retry.",
29
+ code="missing_capability")
30
+
31
+ for item in missing:
32
+ name = item["name"]
33
+ command = [npx, "-y", item["package"], "add", item["source"], "--skill", name,
34
+ "--agent", agent.name, "--global", "--copy", "--yes"]
35
+ try:
36
+ result = run(command, cwd=project, stdin=DEVNULL, check=False, capture_output=True,
37
+ encoding="utf-8", errors="replace", timeout=120,
38
+ env={**os.environ, "DISABLE_TELEMETRY": "1", "NO_COLOR": "1"})
39
+ except (OSError, TimeoutExpired) as error:
40
+ raise _failure(agent, name, str(error)) from error
41
+ if result.returncode:
42
+ reason = (result.stderr.strip() or result.stdout.strip() or f"Exit code {result.returncode}.")[-800:]
43
+ raise _failure(agent, name, reason)
44
+ if not (directory / name / "SKILL.md").is_file():
45
+ raise _failure(agent, name, f"Installation did not create {directory / name / 'SKILL.md'}.")
@@ -0,0 +1,89 @@
1
+ """Project resource snapshots: read-only preview and idempotent apply."""
2
+ from __future__ import annotations
3
+
4
+ import argparse
5
+ import json
6
+ from pathlib import Path
7
+ import sys
8
+ from typing import NoReturn, Sequence
9
+
10
+ from trigrams_toolkit.project_context import current_project_root
11
+ from trigrams_toolkit.resources import schema_paths as source_schema_paths
12
+ from trigrams_toolkit.shared.cli_help import help_requested
13
+ from trigrams_toolkit.shared.errors import ProtocolError, require
14
+ from trigrams_toolkit.shared.schema import SchemaCatalog
15
+ from trigrams_toolkit.shared.serialization import parse_json
16
+ from trigrams_toolkit.version import version
17
+ from .archive_project import archive_project
18
+ from .installation_candidate import build_candidate
19
+ from .installation_help import help_text
20
+ from .installation_service import apply_installation
21
+
22
+
23
+ class Parser(argparse.ArgumentParser):
24
+ def error(self, message: str) -> NoReturn:
25
+ raise ProtocolError("invalid_arguments", message)
26
+
27
+
28
+ def main(argv: Sequence[str] | None = None) -> int:
29
+ if hasattr(sys.stdout, "reconfigure"):
30
+ sys.stdout.reconfigure(encoding="utf-8")
31
+ arguments = list(sys.argv[1:] if argv is None else argv)
32
+ if arguments in (["-v"], ["--version"]):
33
+ print(version())
34
+ return 0
35
+ parser = Parser(description=__doc__)
36
+ parser.add_argument("group", choices=["install"])
37
+ parser.add_argument("command", choices=["preview", "apply"])
38
+ parser.add_argument("--input", required=True)
39
+ parser.add_argument("--request-id")
40
+ parser.add_argument("--expected-revision", type=int)
41
+ operation, request_id = "install", None
42
+ try:
43
+ if help_requested(arguments):
44
+ print(help_text("harness-install", arguments), end="")
45
+ return 0
46
+ if arguments and arguments[0] == "archive":
47
+ return _archive(arguments[1:])
48
+ for flag in ("--input", "--request-id", "--expected-revision"):
49
+ require(sum(argument == flag or argument.startswith(flag + "=") for argument in arguments) <= 1,
50
+ "invalid_arguments", f"Duplicate option: {flag}")
51
+ args = parser.parse_args(arguments)
52
+ operation, request_id = "install " + args.command, args.request_id
53
+ project = current_project_root()
54
+ schemas = SchemaCatalog(source_schema_paths())
55
+ data = parse_json(sys.stdin.buffer.read() if args.input == "-" else (project / args.input).read_bytes())
56
+ require(isinstance(data, dict), "invalid_schema", "Installation input must be an object.")
57
+ if args.command == "preview":
58
+ require(args.request_id is None and args.expected_revision is None,
59
+ "invalid_arguments", "Preview rejects mutation options.")
60
+ result = build_candidate(project, data, schemas).preview
61
+ else:
62
+ require(args.request_id is not None and args.expected_revision is not None,
63
+ "invalid_arguments", "Mutation requires request ID and expected revision.")
64
+ result = apply_installation(project, data, schemas, args.request_id, args.expected_revision)
65
+ response = {"ok": True, "operation": operation, "requestId": request_id, "data": result}
66
+ except ProtocolError as error:
67
+ response = {"ok": False, "operation": operation, "requestId": request_id, "error": error.as_dict()}
68
+ except (OSError, ValueError) as error:
69
+ response = {"ok": False, "operation": operation, "requestId": request_id,
70
+ "error": ProtocolError("io_error", str(error)).as_dict()}
71
+ print(json.dumps(response, ensure_ascii=False))
72
+ return 0 if response["ok"] else 1
73
+
74
+ def _archive(arguments: list[str]) -> int:
75
+ parser = Parser(prog="harness-install archive", description="Archive selected project paths without reading their formats.")
76
+ parser.add_argument("paths", nargs="+", help="Project-relative files or directories to archive.")
77
+ try:
78
+ args = parser.parse_args(arguments)
79
+ response = {"ok": True, "data": archive_project(current_project_root(), args.paths)}
80
+ except ProtocolError as error:
81
+ response = {"ok": False, "error": error.as_dict()}
82
+ except OSError as error:
83
+ response = {"ok": False, "error": ProtocolError("io_error", str(error)).as_dict()}
84
+ print(json.dumps(response, ensure_ascii=False))
85
+ return 0 if response["ok"] else 1
86
+
87
+
88
+ if __name__ == "__main__":
89
+ raise SystemExit(main())
@@ -0,0 +1,135 @@
1
+ """Preview snapshot writes and ownership changes without modifying the project."""
2
+ from __future__ import annotations
3
+
4
+ import os
5
+ from pathlib import Path
6
+ from uuid import uuid4
7
+
8
+ from trigrams_toolkit.handbook.guides import GuideCatalog
9
+ from trigrams_toolkit.handbook.package import ProviderPackage, manifest_owner, package_manifest, resource_paths
10
+ from trigrams_toolkit.handbook.skill_sources import global_core, setup_package, snapshot_resource_paths
11
+ from trigrams_toolkit.handbook.sources import ProviderSource
12
+ from trigrams_toolkit.resources import adapter_files
13
+ from trigrams_toolkit.shared.errors import require
14
+ from trigrams_toolkit.shared.paths import is_link
15
+ from trigrams_toolkit.shared.schema import SchemaCatalog
16
+ from trigrams_toolkit.shared.serialization import canonical
17
+ from trigrams_toolkit.shared.skill_installations import SkillAgent, skill_agent
18
+ from .installation_materials import ProjectMaterials
19
+ from .installation_sources import INSTALLATION, SNAPSHOT_SCHEMA, installation_record
20
+ from .operation_files import blocked_parent, file_record, matches, target_path, validate_owned_paths
21
+ from .operation_runtime import OperationCandidate
22
+
23
+
24
+ def _explicit_packages(project: Path, supplied: list[str], schemas: SchemaCatalog) -> list[ProviderPackage]:
25
+ roots: list[Path | ProviderPackage] = []
26
+ for value in supplied:
27
+ path = Path(value)
28
+ require(path.is_absolute(), "path_outside_root", f"Package source must be absolute: {value}")
29
+ root = path.resolve()
30
+ filename = "extension.json" if (root / "extension.json").is_file() else "resources.json"
31
+ manifest = package_manifest(root, schemas, filename=filename)
32
+ owner = manifest_owner(manifest)
33
+ resources = (resource_paths(root, manifest["resourceRoots"]) if owner == "core"
34
+ else snapshot_resource_paths(root, manifest))
35
+ roots.append(ProviderPackage(root, manifest, (ProviderSource(root, "package", resources),)))
36
+ return list(GuideCatalog.discover(roots, project, schemas).packages.values())
37
+
38
+
39
+ def _sources(project: Path, parameters: dict, agent: SkillAgent, schemas: SchemaCatalog) -> list[ProviderPackage]:
40
+ selected = set(parameters["extensions"])
41
+ if "packages" in parameters:
42
+ packages = _explicit_packages(project, parameters["packages"], schemas)
43
+ else:
44
+ core = global_core(agent)
45
+ packages = [core] if core is not None else []
46
+ packages.extend(setup_package(project, provider, agent, schemas) for provider in sorted(selected))
47
+ require({manifest_owner(p.manifest) for p in packages} - {"core"} == selected, "missing_capability",
48
+ "Supply exactly the selected extensions. A core source is optional in packages.")
49
+ GuideCatalog.discover(packages, project, schemas).validate()
50
+ return packages
51
+
52
+
53
+ def _changes(project: Path, previous: dict, desired: dict[str, dict]) -> tuple[list[dict], list[str]]:
54
+ old = {item["path"]: item for item in previous["managed"]}
55
+ conflicts: set[str] = set()
56
+ changes = []
57
+ for path in sorted(set(old) | set(desired)):
58
+ before, after = old.get(path), desired.get(path)
59
+ target = target_path(project, path)
60
+ present = os.path.lexists(target)
61
+ owned = matches(target, before) if present else True
62
+ if after is not None and blocked_parent(project, target):
63
+ conflicts.add(path)
64
+ if present and not owned:
65
+ conflicts.add(path)
66
+ if (before == after and owned and present) or (after is None and not present):
67
+ continue
68
+ changes.append({"path": path, "action": "write" if after else "remove",
69
+ "before": before if present else None, "after": after})
70
+ return changes, sorted(conflicts)
71
+
72
+
73
+ def _is_uninstall(previous: dict, desired: dict, changes: list[dict]) -> bool:
74
+ before = {(entry["extension"], entry["version"]) for entry in previous["extensions"]}
75
+ after = {(entry["extension"], entry["version"]) for entry in desired["extensions"]}
76
+ old_platforms, new_platforms = set(previous["platforms"]), set(desired["platforms"])
77
+ return (previous.get("agent") == desired["agent"] and after <= before and new_platforms <= old_platforms
78
+ and (after < before or new_platforms < old_platforms)
79
+ and all(change["action"] == "remove" for change in changes))
80
+
81
+
82
+ def build_candidate(project: Path, data: dict, schemas: SchemaCatalog, operation_id: str | None = None) -> OperationCandidate:
83
+ schemas.validate("urn:harness:installation-cli#/$defs/installPreviewInput", data)
84
+ state_file = target_path(project, INSTALLATION)
85
+ require(not any((project / name).exists() for name in (".agents/harness.yaml", ".agents/harness-lock.json")),
86
+ "archive_required", "Archive retired state before installing project materials.")
87
+ previous = installation_record(state_file, schemas)
88
+ agent = skill_agent(data.get("agent") or previous.get("agent"))
89
+ selected = data.get("extensions", [item["extension"] for item in previous["extensions"]])
90
+ parameters = {**data, "agent": agent.name, "extensions": sorted(selected)}
91
+ packages = _sources(project, parameters, agent, schemas)
92
+ material = ProjectMaterials(parameters["platforms"])
93
+ extensions = []
94
+ for package in packages:
95
+ owner = manifest_owner(package.manifest)
96
+ if owner != "core":
97
+ container = project / ".agents/extensions" / owner
98
+ require(not any(is_link(p) for p in (container.parent, container))
99
+ and (not container.exists() or container.is_dir()),
100
+ "invalid_reference", f"Extension container must be a real directory: {container}")
101
+ material.extension(package)
102
+ extensions.append({"extension": owner, "version": package.manifest["version"]})
103
+ material.declared(package)
104
+ for platform in parameters["platforms"]:
105
+ for target, raw in adapter_files(platform).items():
106
+ material.add(target, "core", raw)
107
+ validate_owned_paths(list(material.records), INSTALLATION)
108
+ changes, conflicts = _changes(project, previous, material.records)
109
+ source_roots = {manifest_owner(p.manifest): str(p.root) for p in packages if manifest_owner(p.manifest) != "core"}
110
+ for change in changes:
111
+ target = project / change["path"]
112
+ for root in source_roots.values():
113
+ source = Path(root)
114
+ require(not target.is_relative_to(source) and not source.is_relative_to(target),
115
+ "path_outside_root", f"Installation target overlaps its source: {change['path']}")
116
+ state = {"schemaVersion": 2, "stateRevision": previous["stateRevision"] + 1, "agent": agent.name,
117
+ "extensions": sorted(extensions, key=lambda item: item["extension"]),
118
+ "platforms": parameters["platforms"],
119
+ "managed": [material.records[path] for path in sorted(material.records)]}
120
+ schemas.validate(SNAPSHOT_SCHEMA, state)
121
+ dependency_agent = None if _is_uninstall(previous, state, changes) else agent
122
+ raw = canonical(state)
123
+ before = file_record(INSTALLATION, "core", state_file.read_bytes()) if state_file.is_file() else None
124
+ changes.append({"path": INSTALLATION, "action": "write", "before": before,
125
+ "after": file_record(INSTALLATION, "core", raw)})
126
+ preview = {"schemaVersion": 2, "operationId": operation_id or "operation_" + uuid4().hex,
127
+ "kind": "install", "projectRoot": str(project), "parameters": parameters,
128
+ "baseRevision": previous["stateRevision"], "sources": source_roots,
129
+ "changes": changes, "conflicts": conflicts}
130
+ schemas.validate("urn:harness:installation#/$defs/preview", preview)
131
+ files = {item["path"]: material.files[item["path"]] for item in changes
132
+ if item["action"] == "write" and item["path"] != INSTALLATION}
133
+ files[INSTALLATION] = raw
134
+ changed = len(changes) > 1 or state != {**previous, "stateRevision": state["stateRevision"]}
135
+ return OperationCandidate(preview, files, INSTALLATION, changed, dependency_agent)