trigrams-toolkit 0.1.0__tar.gz

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 (109) hide show
  1. trigrams_toolkit-0.1.0/LICENSE +21 -0
  2. trigrams_toolkit-0.1.0/MANIFEST.in +5 -0
  3. trigrams_toolkit-0.1.0/PKG-INFO +69 -0
  4. trigrams_toolkit-0.1.0/THIRD_PARTY_NOTICES.md +18 -0
  5. trigrams_toolkit-0.1.0/docs/pypi-readme.md +48 -0
  6. trigrams_toolkit-0.1.0/pyproject.toml +47 -0
  7. trigrams_toolkit-0.1.0/setup.cfg +7 -0
  8. trigrams_toolkit-0.1.0/src/trigrams_toolkit/__init__.py +1 -0
  9. trigrams_toolkit-0.1.0/src/trigrams_toolkit/handbook/__init__.py +6 -0
  10. trigrams_toolkit-0.1.0/src/trigrams_toolkit/handbook/cli.py +122 -0
  11. trigrams_toolkit-0.1.0/src/trigrams_toolkit/handbook/guide_headers.py +43 -0
  12. trigrams_toolkit-0.1.0/src/trigrams_toolkit/handbook/guides.py +141 -0
  13. trigrams_toolkit-0.1.0/src/trigrams_toolkit/handbook/location.py +79 -0
  14. trigrams_toolkit-0.1.0/src/trigrams_toolkit/handbook/model.py +4 -0
  15. trigrams_toolkit-0.1.0/src/trigrams_toolkit/handbook/package.py +165 -0
  16. trigrams_toolkit-0.1.0/src/trigrams_toolkit/handbook/principle_import.py +101 -0
  17. trigrams_toolkit-0.1.0/src/trigrams_toolkit/handbook/project_resources.py +80 -0
  18. trigrams_toolkit-0.1.0/src/trigrams_toolkit/handbook/skill_sources.py +59 -0
  19. trigrams_toolkit-0.1.0/src/trigrams_toolkit/handbook/source_catalog.py +55 -0
  20. trigrams_toolkit-0.1.0/src/trigrams_toolkit/handbook/sources.py +16 -0
  21. trigrams_toolkit-0.1.0/src/trigrams_toolkit/installation/__init__.py +0 -0
  22. trigrams_toolkit-0.1.0/src/trigrams_toolkit/installation/archive_project.py +50 -0
  23. trigrams_toolkit-0.1.0/src/trigrams_toolkit/installation/global_skills.py +45 -0
  24. trigrams_toolkit-0.1.0/src/trigrams_toolkit/installation/harness_install.py +89 -0
  25. trigrams_toolkit-0.1.0/src/trigrams_toolkit/installation/installation_candidate.py +135 -0
  26. trigrams_toolkit-0.1.0/src/trigrams_toolkit/installation/installation_help.py +49 -0
  27. trigrams_toolkit-0.1.0/src/trigrams_toolkit/installation/installation_materials.py +73 -0
  28. trigrams_toolkit-0.1.0/src/trigrams_toolkit/installation/installation_service.py +14 -0
  29. trigrams_toolkit-0.1.0/src/trigrams_toolkit/installation/installation_sources.py +34 -0
  30. trigrams_toolkit-0.1.0/src/trigrams_toolkit/installation/operation_files.py +94 -0
  31. trigrams_toolkit-0.1.0/src/trigrams_toolkit/installation/operation_runtime.py +144 -0
  32. trigrams_toolkit-0.1.0/src/trigrams_toolkit/installation/package_metadata.py +48 -0
  33. trigrams_toolkit-0.1.0/src/trigrams_toolkit/plan/__init__.py +5 -0
  34. trigrams_toolkit-0.1.0/src/trigrams_toolkit/plan/cli.py +136 -0
  35. trigrams_toolkit-0.1.0/src/trigrams_toolkit/plan/definitions.py +131 -0
  36. trigrams_toolkit-0.1.0/src/trigrams_toolkit/plan/model.py +61 -0
  37. trigrams_toolkit-0.1.0/src/trigrams_toolkit/plan/scheduling.py +126 -0
  38. trigrams_toolkit-0.1.0/src/trigrams_toolkit/plan/service.py +139 -0
  39. trigrams_toolkit-0.1.0/src/trigrams_toolkit/plan/state.py +146 -0
  40. trigrams_toolkit-0.1.0/src/trigrams_toolkit/project_context/__init__.py +16 -0
  41. trigrams_toolkit-0.1.0/src/trigrams_toolkit/project_context/paths.py +36 -0
  42. trigrams_toolkit-0.1.0/src/trigrams_toolkit/py.typed +0 -0
  43. trigrams_toolkit-0.1.0/src/trigrams_toolkit/resources/__init__.py +35 -0
  44. trigrams_toolkit-0.1.0/src/trigrams_toolkit/resources/adapters/claude/README.md +7 -0
  45. trigrams_toolkit-0.1.0/src/trigrams_toolkit/resources/adapters/claude/evaluator.md +7 -0
  46. trigrams_toolkit-0.1.0/src/trigrams_toolkit/resources/adapters/claude/task_developer.md +7 -0
  47. trigrams_toolkit-0.1.0/src/trigrams_toolkit/resources/adapters/codex/README.md +9 -0
  48. trigrams_toolkit-0.1.0/src/trigrams_toolkit/resources/adapters/codex/evaluator.toml +6 -0
  49. trigrams_toolkit-0.1.0/src/trigrams_toolkit/resources/adapters/codex/task_developer.toml +6 -0
  50. trigrams_toolkit-0.1.0/src/trigrams_toolkit/resources/adapters/pi-web/evaluator.md +7 -0
  51. trigrams_toolkit-0.1.0/src/trigrams_toolkit/resources/adapters/pi-web/task_developer.md +7 -0
  52. trigrams_toolkit-0.1.0/src/trigrams_toolkit/resources/handbook/PROTOCOL.md +82 -0
  53. trigrams_toolkit-0.1.0/src/trigrams_toolkit/resources/handbook/README.md +45 -0
  54. trigrams_toolkit-0.1.0/src/trigrams_toolkit/resources/handbook/commands.json +31 -0
  55. trigrams_toolkit-0.1.0/src/trigrams_toolkit/resources/handbook/guides.schema.json +253 -0
  56. trigrams_toolkit-0.1.0/src/trigrams_toolkit/resources/installation/PROTOCOL.md +35 -0
  57. trigrams_toolkit-0.1.0/src/trigrams_toolkit/resources/installation/cli.schema.json +89 -0
  58. trigrams_toolkit-0.1.0/src/trigrams_toolkit/resources/installation/commands.json +23 -0
  59. trigrams_toolkit-0.1.0/src/trigrams_toolkit/resources/installation/examples/install-apply-input.json +48 -0
  60. trigrams_toolkit-0.1.0/src/trigrams_toolkit/resources/installation/examples/install-preview-input.json +7 -0
  61. trigrams_toolkit-0.1.0/src/trigrams_toolkit/resources/installation/examples/installation.json +20 -0
  62. trigrams_toolkit-0.1.0/src/trigrams_toolkit/resources/installation/global-skills.json +6 -0
  63. trigrams_toolkit-0.1.0/src/trigrams_toolkit/resources/installation/installation.schema.json +295 -0
  64. trigrams_toolkit-0.1.0/src/trigrams_toolkit/resources/plan/PROTOCOL.md +89 -0
  65. trigrams_toolkit-0.1.0/src/trigrams_toolkit/resources/plan/README.md +61 -0
  66. trigrams_toolkit-0.1.0/src/trigrams_toolkit/resources/plan/commands.json +36 -0
  67. trigrams_toolkit-0.1.0/src/trigrams_toolkit/resources/plan/plan.schema.json +192 -0
  68. trigrams_toolkit-0.1.0/src/trigrams_toolkit/resources/shared/GLOBAL-TOOLS.md +31 -0
  69. trigrams_toolkit-0.1.0/src/trigrams_toolkit/resources/shared/common.schema.json +234 -0
  70. trigrams_toolkit-0.1.0/src/trigrams_toolkit/resources/state/PROTOCOL.md +85 -0
  71. trigrams_toolkit-0.1.0/src/trigrams_toolkit/resources/state/README.md +88 -0
  72. trigrams_toolkit-0.1.0/src/trigrams_toolkit/resources/state/cli.schema.json +326 -0
  73. trigrams_toolkit-0.1.0/src/trigrams_toolkit/resources/state/commands.json +55 -0
  74. trigrams_toolkit-0.1.0/src/trigrams_toolkit/resources/state/core-types.json +5 -0
  75. trigrams_toolkit-0.1.0/src/trigrams_toolkit/resources/state/help.json +86 -0
  76. trigrams_toolkit-0.1.0/src/trigrams_toolkit/resources/state/sources.schema.json +89 -0
  77. trigrams_toolkit-0.1.0/src/trigrams_toolkit/resources/state/state.schema.json +200 -0
  78. trigrams_toolkit-0.1.0/src/trigrams_toolkit/shared/__init__.py +1 -0
  79. trigrams_toolkit-0.1.0/src/trigrams_toolkit/shared/cli_help.py +195 -0
  80. trigrams_toolkit-0.1.0/src/trigrams_toolkit/shared/errors.py +29 -0
  81. trigrams_toolkit-0.1.0/src/trigrams_toolkit/shared/files.py +66 -0
  82. trigrams_toolkit-0.1.0/src/trigrams_toolkit/shared/locking.py +49 -0
  83. trigrams_toolkit-0.1.0/src/trigrams_toolkit/shared/paths.py +89 -0
  84. trigrams_toolkit-0.1.0/src/trigrams_toolkit/shared/process_lock.py +77 -0
  85. trigrams_toolkit-0.1.0/src/trigrams_toolkit/shared/schema.py +60 -0
  86. trigrams_toolkit-0.1.0/src/trigrams_toolkit/shared/serialization.py +84 -0
  87. trigrams_toolkit-0.1.0/src/trigrams_toolkit/shared/skill_installations.py +66 -0
  88. trigrams_toolkit-0.1.0/src/trigrams_toolkit/shared/state_json.py +45 -0
  89. trigrams_toolkit-0.1.0/src/trigrams_toolkit/state/__init__.py +4 -0
  90. trigrams_toolkit-0.1.0/src/trigrams_toolkit/state/arguments.py +68 -0
  91. trigrams_toolkit-0.1.0/src/trigrams_toolkit/state/cli.py +37 -0
  92. trigrams_toolkit-0.1.0/src/trigrams_toolkit/state/frontmatter.py +176 -0
  93. trigrams_toolkit-0.1.0/src/trigrams_toolkit/state/help.py +25 -0
  94. trigrams_toolkit-0.1.0/src/trigrams_toolkit/state/identity.py +123 -0
  95. trigrams_toolkit-0.1.0/src/trigrams_toolkit/state/location.py +59 -0
  96. trigrams_toolkit-0.1.0/src/trigrams_toolkit/state/model.py +76 -0
  97. trigrams_toolkit-0.1.0/src/trigrams_toolkit/state/providers.py +77 -0
  98. trigrams_toolkit-0.1.0/src/trigrams_toolkit/state/registration.py +82 -0
  99. trigrams_toolkit-0.1.0/src/trigrams_toolkit/state/relations.py +105 -0
  100. trigrams_toolkit-0.1.0/src/trigrams_toolkit/state/service.py +90 -0
  101. trigrams_toolkit-0.1.0/src/trigrams_toolkit/state/store.py +33 -0
  102. trigrams_toolkit-0.1.0/src/trigrams_toolkit/state/views.py +64 -0
  103. trigrams_toolkit-0.1.0/src/trigrams_toolkit/version.py +6 -0
  104. trigrams_toolkit-0.1.0/src/trigrams_toolkit.egg-info/PKG-INFO +69 -0
  105. trigrams_toolkit-0.1.0/src/trigrams_toolkit.egg-info/SOURCES.txt +108 -0
  106. trigrams_toolkit-0.1.0/src/trigrams_toolkit.egg-info/dependency_links.txt +1 -0
  107. trigrams_toolkit-0.1.0/src/trigrams_toolkit.egg-info/entry_points.txt +5 -0
  108. trigrams_toolkit-0.1.0/src/trigrams_toolkit.egg-info/requires.txt +10 -0
  109. trigrams_toolkit-0.1.0/src/trigrams_toolkit.egg-info/top_level.txt +1 -0
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 LINEBARRELS and contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,5 @@
1
+ include LICENSE THIRD_PARTY_NOTICES.md
2
+ include docs/pypi-readme.md
3
+ graft src/trigrams_toolkit
4
+ prune tests
5
+ global-exclude __pycache__ *.py[cod]
@@ -0,0 +1,69 @@
1
+ Metadata-Version: 2.4
2
+ Name: trigrams-toolkit
3
+ Version: 0.1.0
4
+ Summary: Agent skills, project resources and command-line tools for Trigrams toolkit
5
+ Author: LINEBARRELS
6
+ License-Expression: MIT
7
+ Requires-Python: >=3.11
8
+ Description-Content-Type: text/markdown
9
+ License-File: LICENSE
10
+ License-File: THIRD_PARTY_NOTICES.md
11
+ Requires-Dist: PyYAML==6.0.2
12
+ Requires-Dist: jsonschema==4.24.0
13
+ Requires-Dist: referencing<0.38,>=0.36.2
14
+ Requires-Dist: ruamel.yaml<0.19,>=0.18.15
15
+ Provides-Extra: dev
16
+ Requires-Dist: build<2,>=1.2.2; extra == "dev"
17
+ Requires-Dist: mypy<2,>=1.15; extra == "dev"
18
+ Requires-Dist: types-PyYAML; extra == "dev"
19
+ Requires-Dist: types-jsonschema; extra == "dev"
20
+ Dynamic: license-file
21
+
22
+ # trigrams-toolkit
23
+
24
+ Command-line tools, schemas, core types and platform adapters for **Trigrams toolkit**.
25
+
26
+ ## Requirements
27
+
28
+ - Python 3.11 or newer
29
+
30
+ ## Installation
31
+
32
+ Install the CLI package globally with `uv`:
33
+
34
+ ```sh
35
+ uv tool install trigrams-toolkit
36
+ ```
37
+
38
+ Or install with `pip`:
39
+
40
+ ```sh
41
+ python -m pip install trigrams-toolkit
42
+ ```
43
+
44
+ ## Included CLI Commands
45
+
46
+ | Command | Purpose |
47
+ | --- | --- |
48
+ | `project-state` | Register and query project Modules, Features, Artifacts and relations in `.project-state/state.json`. |
49
+ | `plan-toolkit` | Compile plan snapshots, inspect task dependencies, list runnable tasks and track Plan / Task status. |
50
+ | `handbook` | Discover, load, validate and import workbooks and principles from global Skills, installed extensions and project resources. |
51
+ | `harness-install` | Preview and apply project extension snapshots (`.agents/extensions/`) and host adapters, ensure required global Skills, and archive explicit project paths. |
52
+
53
+ ## Quick Usage
54
+
55
+ Help (`-h` / `--help`) and version (`-v` / `--version`) can be queried from any directory:
56
+
57
+ ```sh
58
+ project-state --version
59
+ project-state --help
60
+ plan-toolkit --help
61
+ handbook --help
62
+ harness-install --help
63
+ ```
64
+
65
+ All other subcommands operate on the current working directory and should be run from the target project root.
66
+
67
+ ## License
68
+
69
+ MIT. See the bundled `LICENSE` and `THIRD_PARTY_NOTICES.md` files for details.
@@ -0,0 +1,18 @@
1
+ # 第三方内容与素材
2
+
3
+ 根目录 [MIT License](LICENSE) 适用于维护者有权授权的原创内容。第三方组件与素材遵循各自许可和来源声明。
4
+
5
+ ## 外部 Skill
6
+
7
+ | 内容 | 来源 | 保留的许可 |
8
+ | --- | --- | --- |
9
+ | smell-check(必需外部依赖,不随包内嵌) | [Zhen-Bo/smell-check](https://github.com/Zhen-Bo/smell-check) | 使用上游安装包携带的许可 |
10
+ | archify(必需外部依赖,不随包内嵌) | [Archify](https://archify.si) | 使用上游安装包携带的许可 |
11
+
12
+ 上述 Skill 通过各自来源安装。`harness-install install apply` 检查并补齐目标 `agent` 缺失的 `archify` 与 `smell-check`。安装来源见[全局依赖声明](src/trigrams_toolkit/resources/installation/global-skills.json)。上游参考材料按其来源标注。
13
+
14
+ ## Python CLI 运行依赖
15
+
16
+ 运行依赖在 [pyproject.toml](pyproject.toml) 维护,由 uv/pip 安装原发行包及其许可。当前直接依赖均采用 MIT:PyYAML、jsonschema、referencing、ruamel.yaml。传递依赖包括 attrs、jsonschema-specifications、rpds-py,以及适用 Python 版本上的 typing-extensions、ruamel.yaml.clib;保留各发行包携带的许可文件。
17
+
18
+ 每次候选包验收在 `.tmp/` 的 `package-check.json` 中记录实际安装版本与依赖闭包。开发用 build、setuptools、mypy 和类型声明属于开发依赖,随各自发行包保留许可。
@@ -0,0 +1,48 @@
1
+ # trigrams-toolkit
2
+
3
+ Command-line tools, schemas, core types and platform adapters for **Trigrams toolkit**.
4
+
5
+ ## Requirements
6
+
7
+ - Python 3.11 or newer
8
+
9
+ ## Installation
10
+
11
+ Install the CLI package globally with `uv`:
12
+
13
+ ```sh
14
+ uv tool install trigrams-toolkit
15
+ ```
16
+
17
+ Or install with `pip`:
18
+
19
+ ```sh
20
+ python -m pip install trigrams-toolkit
21
+ ```
22
+
23
+ ## Included CLI Commands
24
+
25
+ | Command | Purpose |
26
+ | --- | --- |
27
+ | `project-state` | Register and query project Modules, Features, Artifacts and relations in `.project-state/state.json`. |
28
+ | `plan-toolkit` | Compile plan snapshots, inspect task dependencies, list runnable tasks and track Plan / Task status. |
29
+ | `handbook` | Discover, load, validate and import workbooks and principles from global Skills, installed extensions and project resources. |
30
+ | `harness-install` | Preview and apply project extension snapshots (`.agents/extensions/`) and host adapters, ensure required global Skills, and archive explicit project paths. |
31
+
32
+ ## Quick Usage
33
+
34
+ Help (`-h` / `--help`) and version (`-v` / `--version`) can be queried from any directory:
35
+
36
+ ```sh
37
+ project-state --version
38
+ project-state --help
39
+ plan-toolkit --help
40
+ handbook --help
41
+ harness-install --help
42
+ ```
43
+
44
+ All other subcommands operate on the current working directory and should be run from the target project root.
45
+
46
+ ## License
47
+
48
+ MIT. See the bundled `LICENSE` and `THIRD_PARTY_NOTICES.md` files for details.
@@ -0,0 +1,47 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "trigrams-toolkit"
7
+ version = "0.1.0"
8
+ description = "Agent skills, project resources and command-line tools for Trigrams toolkit"
9
+ readme = "docs/pypi-readme.md"
10
+ requires-python = ">=3.11"
11
+ license = "MIT"
12
+ license-files = ["LICENSE", "THIRD_PARTY_NOTICES.md"]
13
+ authors = [{name = "LINEBARRELS"}]
14
+ dependencies = [
15
+ "PyYAML==6.0.2",
16
+ "jsonschema==4.24.0",
17
+ "referencing>=0.36.2,<0.38",
18
+ "ruamel.yaml>=0.18.15,<0.19",
19
+ ]
20
+
21
+ [project.optional-dependencies]
22
+ dev = ["build>=1.2.2,<2", "mypy>=1.15,<2", "types-PyYAML", "types-jsonschema"]
23
+
24
+ [project.scripts]
25
+ project-state = "trigrams_toolkit.state.cli:main"
26
+ plan-toolkit = "trigrams_toolkit.plan.cli:main"
27
+ handbook = "trigrams_toolkit.handbook.cli:main"
28
+ harness-install = "trigrams_toolkit.installation.harness_install:main"
29
+
30
+ [tool.setuptools.packages.find]
31
+ where = ["src"]
32
+
33
+ [tool.setuptools.package-data]
34
+ trigrams_toolkit = ["py.typed", "resources/**/*.json", "resources/**/*.md", "resources/**/*.toml"]
35
+
36
+ [tool.mypy]
37
+ python_version = "3.11"
38
+ files = ["src/trigrams_toolkit"]
39
+ check_untyped_defs = true
40
+ no_implicit_optional = true
41
+ warn_unused_ignores = true
42
+ warn_redundant_casts = true
43
+ cache_dir = ".tmp/mypy-cache"
44
+
45
+ [[tool.mypy.overrides]]
46
+ module = ["trigrams_toolkit.state.*", "trigrams_toolkit.project_context.*", "trigrams_toolkit.resources.*"]
47
+ disallow_untyped_defs = true
@@ -0,0 +1,7 @@
1
+ [build]
2
+ build_base = .tmp/build
3
+
4
+ [egg_info]
5
+ tag_build =
6
+ tag_date = 0
7
+
@@ -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]