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.
- trigrams_toolkit/__init__.py +1 -0
- trigrams_toolkit/handbook/__init__.py +6 -0
- trigrams_toolkit/handbook/cli.py +122 -0
- trigrams_toolkit/handbook/guide_headers.py +43 -0
- trigrams_toolkit/handbook/guides.py +141 -0
- trigrams_toolkit/handbook/location.py +79 -0
- trigrams_toolkit/handbook/model.py +4 -0
- trigrams_toolkit/handbook/package.py +165 -0
- trigrams_toolkit/handbook/principle_import.py +101 -0
- trigrams_toolkit/handbook/project_resources.py +80 -0
- trigrams_toolkit/handbook/skill_sources.py +59 -0
- trigrams_toolkit/handbook/source_catalog.py +55 -0
- trigrams_toolkit/handbook/sources.py +16 -0
- trigrams_toolkit/installation/__init__.py +0 -0
- trigrams_toolkit/installation/archive_project.py +50 -0
- trigrams_toolkit/installation/global_skills.py +45 -0
- trigrams_toolkit/installation/harness_install.py +89 -0
- trigrams_toolkit/installation/installation_candidate.py +135 -0
- trigrams_toolkit/installation/installation_help.py +49 -0
- trigrams_toolkit/installation/installation_materials.py +73 -0
- trigrams_toolkit/installation/installation_service.py +14 -0
- trigrams_toolkit/installation/installation_sources.py +34 -0
- trigrams_toolkit/installation/operation_files.py +94 -0
- trigrams_toolkit/installation/operation_runtime.py +144 -0
- trigrams_toolkit/installation/package_metadata.py +48 -0
- trigrams_toolkit/plan/__init__.py +5 -0
- trigrams_toolkit/plan/cli.py +136 -0
- trigrams_toolkit/plan/definitions.py +131 -0
- trigrams_toolkit/plan/model.py +61 -0
- trigrams_toolkit/plan/scheduling.py +126 -0
- trigrams_toolkit/plan/service.py +139 -0
- trigrams_toolkit/plan/state.py +146 -0
- trigrams_toolkit/project_context/__init__.py +16 -0
- trigrams_toolkit/project_context/paths.py +36 -0
- trigrams_toolkit/py.typed +0 -0
- trigrams_toolkit/resources/__init__.py +35 -0
- trigrams_toolkit/resources/adapters/claude/README.md +7 -0
- trigrams_toolkit/resources/adapters/claude/evaluator.md +7 -0
- trigrams_toolkit/resources/adapters/claude/task_developer.md +7 -0
- trigrams_toolkit/resources/adapters/codex/README.md +9 -0
- trigrams_toolkit/resources/adapters/codex/evaluator.toml +6 -0
- trigrams_toolkit/resources/adapters/codex/task_developer.toml +6 -0
- trigrams_toolkit/resources/adapters/pi-web/evaluator.md +7 -0
- trigrams_toolkit/resources/adapters/pi-web/task_developer.md +7 -0
- trigrams_toolkit/resources/handbook/PROTOCOL.md +82 -0
- trigrams_toolkit/resources/handbook/README.md +45 -0
- trigrams_toolkit/resources/handbook/commands.json +31 -0
- trigrams_toolkit/resources/handbook/guides.schema.json +253 -0
- trigrams_toolkit/resources/installation/PROTOCOL.md +35 -0
- trigrams_toolkit/resources/installation/cli.schema.json +89 -0
- trigrams_toolkit/resources/installation/commands.json +23 -0
- trigrams_toolkit/resources/installation/examples/install-apply-input.json +48 -0
- trigrams_toolkit/resources/installation/examples/install-preview-input.json +7 -0
- trigrams_toolkit/resources/installation/examples/installation.json +20 -0
- trigrams_toolkit/resources/installation/global-skills.json +6 -0
- trigrams_toolkit/resources/installation/installation.schema.json +295 -0
- trigrams_toolkit/resources/plan/PROTOCOL.md +89 -0
- trigrams_toolkit/resources/plan/README.md +61 -0
- trigrams_toolkit/resources/plan/commands.json +36 -0
- trigrams_toolkit/resources/plan/plan.schema.json +192 -0
- trigrams_toolkit/resources/shared/GLOBAL-TOOLS.md +31 -0
- trigrams_toolkit/resources/shared/common.schema.json +234 -0
- trigrams_toolkit/resources/state/PROTOCOL.md +85 -0
- trigrams_toolkit/resources/state/README.md +88 -0
- trigrams_toolkit/resources/state/cli.schema.json +326 -0
- trigrams_toolkit/resources/state/commands.json +55 -0
- trigrams_toolkit/resources/state/core-types.json +5 -0
- trigrams_toolkit/resources/state/help.json +86 -0
- trigrams_toolkit/resources/state/sources.schema.json +89 -0
- trigrams_toolkit/resources/state/state.schema.json +200 -0
- trigrams_toolkit/shared/__init__.py +1 -0
- trigrams_toolkit/shared/cli_help.py +195 -0
- trigrams_toolkit/shared/errors.py +29 -0
- trigrams_toolkit/shared/files.py +66 -0
- trigrams_toolkit/shared/locking.py +49 -0
- trigrams_toolkit/shared/paths.py +89 -0
- trigrams_toolkit/shared/process_lock.py +77 -0
- trigrams_toolkit/shared/schema.py +60 -0
- trigrams_toolkit/shared/serialization.py +84 -0
- trigrams_toolkit/shared/skill_installations.py +66 -0
- trigrams_toolkit/shared/state_json.py +45 -0
- trigrams_toolkit/state/__init__.py +4 -0
- trigrams_toolkit/state/arguments.py +68 -0
- trigrams_toolkit/state/cli.py +37 -0
- trigrams_toolkit/state/frontmatter.py +176 -0
- trigrams_toolkit/state/help.py +25 -0
- trigrams_toolkit/state/identity.py +123 -0
- trigrams_toolkit/state/location.py +59 -0
- trigrams_toolkit/state/model.py +76 -0
- trigrams_toolkit/state/providers.py +77 -0
- trigrams_toolkit/state/registration.py +82 -0
- trigrams_toolkit/state/relations.py +105 -0
- trigrams_toolkit/state/service.py +90 -0
- trigrams_toolkit/state/store.py +33 -0
- trigrams_toolkit/state/views.py +64 -0
- trigrams_toolkit/version.py +6 -0
- trigrams_toolkit-0.1.0.dist-info/METADATA +69 -0
- trigrams_toolkit-0.1.0.dist-info/RECORD +103 -0
- trigrams_toolkit-0.1.0.dist-info/WHEEL +5 -0
- trigrams_toolkit-0.1.0.dist-info/entry_points.txt +5 -0
- trigrams_toolkit-0.1.0.dist-info/licenses/LICENSE +21 -0
- trigrams_toolkit-0.1.0.dist-info/licenses/THIRD_PARTY_NOTICES.md +18 -0
- trigrams_toolkit-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,200 @@
|
|
|
1
|
+
{
|
|
2
|
+
"type": "object",
|
|
3
|
+
"additionalProperties": false,
|
|
4
|
+
"required": [
|
|
5
|
+
"schemaVersion",
|
|
6
|
+
"modules",
|
|
7
|
+
"features",
|
|
8
|
+
"artifacts",
|
|
9
|
+
"relations"
|
|
10
|
+
],
|
|
11
|
+
"properties": {
|
|
12
|
+
"schemaVersion": {
|
|
13
|
+
"const": 1
|
|
14
|
+
},
|
|
15
|
+
"modules": {
|
|
16
|
+
"type": "array",
|
|
17
|
+
"items": {
|
|
18
|
+
"$ref": "#/$defs/module"
|
|
19
|
+
}
|
|
20
|
+
},
|
|
21
|
+
"features": {
|
|
22
|
+
"type": "array",
|
|
23
|
+
"items": {
|
|
24
|
+
"$ref": "#/$defs/feature"
|
|
25
|
+
}
|
|
26
|
+
},
|
|
27
|
+
"artifacts": {
|
|
28
|
+
"type": "array",
|
|
29
|
+
"items": {
|
|
30
|
+
"$ref": "#/$defs/artifact"
|
|
31
|
+
}
|
|
32
|
+
},
|
|
33
|
+
"relations": {
|
|
34
|
+
"type": "array",
|
|
35
|
+
"items": {
|
|
36
|
+
"$ref": "#/$defs/relation"
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
},
|
|
40
|
+
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
|
41
|
+
"$id": "urn:harness:state",
|
|
42
|
+
"$defs": {
|
|
43
|
+
"module": {
|
|
44
|
+
"type": "object",
|
|
45
|
+
"additionalProperties": false,
|
|
46
|
+
"required": [
|
|
47
|
+
"id",
|
|
48
|
+
"name"
|
|
49
|
+
],
|
|
50
|
+
"properties": {
|
|
51
|
+
"id": {
|
|
52
|
+
"type": "string",
|
|
53
|
+
"pattern": "^module_[A-Za-z0-9_-]+(?![\\s\\S])"
|
|
54
|
+
},
|
|
55
|
+
"name": {
|
|
56
|
+
"type": "string",
|
|
57
|
+
"minLength": 1
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
},
|
|
61
|
+
"feature": {
|
|
62
|
+
"type": "object",
|
|
63
|
+
"additionalProperties": false,
|
|
64
|
+
"required": [
|
|
65
|
+
"id",
|
|
66
|
+
"name",
|
|
67
|
+
"moduleId"
|
|
68
|
+
],
|
|
69
|
+
"properties": {
|
|
70
|
+
"id": {
|
|
71
|
+
"type": "string",
|
|
72
|
+
"pattern": "^feature_[A-Za-z0-9_-]+(?![\\s\\S])"
|
|
73
|
+
},
|
|
74
|
+
"name": {
|
|
75
|
+
"type": "string",
|
|
76
|
+
"minLength": 1
|
|
77
|
+
},
|
|
78
|
+
"moduleId": {
|
|
79
|
+
"type": "string",
|
|
80
|
+
"pattern": "^module_[A-Za-z0-9_-]+(?![\\s\\S])"
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
},
|
|
84
|
+
"artifact": {
|
|
85
|
+
"type": "object",
|
|
86
|
+
"additionalProperties": false,
|
|
87
|
+
"required": [
|
|
88
|
+
"id",
|
|
89
|
+
"kind",
|
|
90
|
+
"title",
|
|
91
|
+
"locatorHint",
|
|
92
|
+
"identityMode",
|
|
93
|
+
"featureIds"
|
|
94
|
+
],
|
|
95
|
+
"properties": {
|
|
96
|
+
"id": {
|
|
97
|
+
"type": "string",
|
|
98
|
+
"pattern": "^artifact_[A-Za-z0-9_-]+(?![\\s\\S])"
|
|
99
|
+
},
|
|
100
|
+
"kind": {
|
|
101
|
+
"type": "string",
|
|
102
|
+
"pattern": "^[A-Za-z0-9_-]+:[A-Za-z0-9_-]+(?![\\s\\S])"
|
|
103
|
+
},
|
|
104
|
+
"title": {
|
|
105
|
+
"type": "string",
|
|
106
|
+
"minLength": 1
|
|
107
|
+
},
|
|
108
|
+
"locatorHint": {
|
|
109
|
+
"type": "string",
|
|
110
|
+
"minLength": 1
|
|
111
|
+
},
|
|
112
|
+
"identityMode": {
|
|
113
|
+
"enum": [
|
|
114
|
+
"frontmatter",
|
|
115
|
+
"manifest"
|
|
116
|
+
]
|
|
117
|
+
},
|
|
118
|
+
"moduleId": {
|
|
119
|
+
"type": "string",
|
|
120
|
+
"pattern": "^module_[A-Za-z0-9_-]+(?![\\s\\S])"
|
|
121
|
+
},
|
|
122
|
+
"featureIds": {
|
|
123
|
+
"type": "array",
|
|
124
|
+
"uniqueItems": true,
|
|
125
|
+
"items": {
|
|
126
|
+
"type": "string",
|
|
127
|
+
"pattern": "^feature_[A-Za-z0-9_-]+(?![\\s\\S])"
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
},
|
|
132
|
+
"relation": {
|
|
133
|
+
"type": "object",
|
|
134
|
+
"additionalProperties": false,
|
|
135
|
+
"required": [
|
|
136
|
+
"from",
|
|
137
|
+
"kind",
|
|
138
|
+
"to"
|
|
139
|
+
],
|
|
140
|
+
"properties": {
|
|
141
|
+
"from": {
|
|
142
|
+
"type": "string",
|
|
143
|
+
"minLength": 1
|
|
144
|
+
},
|
|
145
|
+
"kind": {
|
|
146
|
+
"type": "string",
|
|
147
|
+
"minLength": 1
|
|
148
|
+
},
|
|
149
|
+
"to": {
|
|
150
|
+
"type": "string",
|
|
151
|
+
"minLength": 1
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
},
|
|
155
|
+
"entity": {
|
|
156
|
+
"oneOf": [
|
|
157
|
+
{
|
|
158
|
+
"$ref": "#/$defs/module"
|
|
159
|
+
},
|
|
160
|
+
{
|
|
161
|
+
"$ref": "#/$defs/feature"
|
|
162
|
+
},
|
|
163
|
+
{
|
|
164
|
+
"$ref": "#/$defs/artifact"
|
|
165
|
+
}
|
|
166
|
+
]
|
|
167
|
+
},
|
|
168
|
+
"identityManifest": {
|
|
169
|
+
"type": "object",
|
|
170
|
+
"additionalProperties": false,
|
|
171
|
+
"required": [
|
|
172
|
+
"schemaVersion",
|
|
173
|
+
"id",
|
|
174
|
+
"members"
|
|
175
|
+
],
|
|
176
|
+
"properties": {
|
|
177
|
+
"schemaVersion": {
|
|
178
|
+
"const": 1
|
|
179
|
+
},
|
|
180
|
+
"id": {
|
|
181
|
+
"$ref": "urn:harness:common#/$defs/artifactId"
|
|
182
|
+
},
|
|
183
|
+
"members": {
|
|
184
|
+
"type": "array",
|
|
185
|
+
"minItems": 1,
|
|
186
|
+
"uniqueItems": true,
|
|
187
|
+
"items": {
|
|
188
|
+
"$ref": "urn:harness:common#/$defs/path"
|
|
189
|
+
}
|
|
190
|
+
},
|
|
191
|
+
"moduleId": {
|
|
192
|
+
"$ref": "#/$defs/artifact/properties/moduleId"
|
|
193
|
+
},
|
|
194
|
+
"featureIds": {
|
|
195
|
+
"$ref": "#/$defs/artifact/properties/featureIds"
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Shared protocol and file boundaries."""
|
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
"""Read-only, local help rendering shared by the Python public CLIs."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import json
|
|
5
|
+
import argparse
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
import textwrap
|
|
8
|
+
from typing import Any, Sequence, Iterable
|
|
9
|
+
|
|
10
|
+
from trigrams_toolkit.shared.errors import require
|
|
11
|
+
from trigrams_toolkit.shared.serialization import read_json
|
|
12
|
+
|
|
13
|
+
HELP_WIDTH = 100
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def paragraph(value: str) -> str:
|
|
17
|
+
return textwrap.fill(value, width=HELP_WIDTH, break_long_words=False, break_on_hyphens=False)
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def help_rows(rows: Sequence[tuple[str, str]]) -> list[str]:
|
|
21
|
+
lines: list[str] = []
|
|
22
|
+
for label, description in rows:
|
|
23
|
+
prefix = " " + label
|
|
24
|
+
if len(prefix) >= 30:
|
|
25
|
+
lines.append(prefix)
|
|
26
|
+
prefix = " " * 30
|
|
27
|
+
else:
|
|
28
|
+
prefix = prefix.ljust(30)
|
|
29
|
+
lines.extend(textwrap.wrap(description, width=HELP_WIDTH, initial_indent=prefix,
|
|
30
|
+
subsequent_indent=" " * 30, break_long_words=False,
|
|
31
|
+
break_on_hyphens=False) or [prefix.rstrip()])
|
|
32
|
+
return lines
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class HelpFormatter(argparse.HelpFormatter):
|
|
36
|
+
def __init__(self, prog: str) -> None:
|
|
37
|
+
super().__init__(prog, width=HELP_WIDTH, max_help_position=30)
|
|
38
|
+
|
|
39
|
+
def add_usage(self, usage: str | None, actions: Iterable[argparse.Action],
|
|
40
|
+
groups: Iterable[argparse._MutuallyExclusiveGroup], prefix: str | None = None) -> None:
|
|
41
|
+
super().add_usage(usage, actions, groups, prefix="Usage: " if prefix is None else prefix)
|
|
42
|
+
|
|
43
|
+
def start_section(self, heading: str | None) -> None:
|
|
44
|
+
super().start_section({"options": "Options", "positional arguments": "Arguments"}.get(heading or "", heading or ""))
|
|
45
|
+
|
|
46
|
+
def _get_help_string(self, action: argparse.Action) -> str:
|
|
47
|
+
return {"show this help message and exit": "Show help.",
|
|
48
|
+
"show program's version number and exit": "Show toolkit version."}.get(action.help or "", action.help or "")
|
|
49
|
+
|
|
50
|
+
def _fill_text(self, text: str, width: int, indent: str) -> str:
|
|
51
|
+
return "\n\n".join(textwrap.fill(part, width, initial_indent=indent, subsequent_indent=indent,
|
|
52
|
+
break_long_words=False, break_on_hyphens=False)
|
|
53
|
+
for part in text.split("\n\n"))
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def help_requested(argv: Sequence[str]) -> bool:
|
|
57
|
+
return any(arg in ("-h", "--help") for arg in argv)
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def help_selection(argv: Sequence[str], names: Sequence[str], value_options: set[str]) -> tuple[str, bool]:
|
|
61
|
+
"""Select a command/group while skipping declared option values."""
|
|
62
|
+
index = next(i for i, arg in enumerate(argv) if arg in ("-h", "--help"))
|
|
63
|
+
tail = list(argv[index + 1:])
|
|
64
|
+
require(tail in ([], ["schema"]), "invalid_arguments", "Help accepts only the optional 'schema' topic.")
|
|
65
|
+
words: list[str] = []
|
|
66
|
+
tokens = iter(argv[:index])
|
|
67
|
+
for arg in tokens:
|
|
68
|
+
if arg.startswith("-"):
|
|
69
|
+
option, equal, _ = arg.partition("=")
|
|
70
|
+
require(option in value_options, "invalid_arguments", f"Unknown option: {option}")
|
|
71
|
+
if not equal:
|
|
72
|
+
next(tokens, None)
|
|
73
|
+
continue
|
|
74
|
+
words.append(arg)
|
|
75
|
+
selected = " ".join(words)
|
|
76
|
+
if selected not in names:
|
|
77
|
+
matches = [name for name in names if selected.startswith(name + " ")]
|
|
78
|
+
if matches:
|
|
79
|
+
selected = max(matches, key=len)
|
|
80
|
+
require(not selected or selected in names or any(name.startswith(selected + " ") for name in names),
|
|
81
|
+
"invalid_arguments", f"Unknown help command: {selected}")
|
|
82
|
+
require(not tail or selected in names, "invalid_arguments", "Select a leaf command for schema help.")
|
|
83
|
+
return selected, bool(tail)
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
class HelpSchemas:
|
|
87
|
+
def __init__(self, paths: Sequence[Path]) -> None:
|
|
88
|
+
self.documents = {value["$id"]: value for value in map(read_json, paths)}
|
|
89
|
+
|
|
90
|
+
def resolve(self, reference: str) -> Any:
|
|
91
|
+
base, _, fragment = reference.partition("#")
|
|
92
|
+
value = self.documents[base]
|
|
93
|
+
for token in fragment.lstrip("/").split("/") if fragment else []:
|
|
94
|
+
value = value[token.replace("~1", "/").replace("~0", "~")]
|
|
95
|
+
return value
|
|
96
|
+
|
|
97
|
+
def bundle(self, reference: str) -> dict:
|
|
98
|
+
"""Export only reachable definitions, with local refs and cycles preserved."""
|
|
99
|
+
identities: dict[str, str] = {}
|
|
100
|
+
definitions: dict[str, Any] = {}
|
|
101
|
+
|
|
102
|
+
def include(target: str) -> str:
|
|
103
|
+
if target not in identities:
|
|
104
|
+
name = f"D{len(identities)}"
|
|
105
|
+
identities[target] = name
|
|
106
|
+
definitions[name] = transform(self.resolve(target), target.split("#")[0])
|
|
107
|
+
return "#/$defs/" + identities[target]
|
|
108
|
+
|
|
109
|
+
def transform(value: Any, base: str) -> Any:
|
|
110
|
+
if isinstance(value, list):
|
|
111
|
+
return [transform(item, base) for item in value]
|
|
112
|
+
if not isinstance(value, dict):
|
|
113
|
+
return value
|
|
114
|
+
return {key: include(base + item if item.startswith("#") else item) if key == "$ref"
|
|
115
|
+
else transform(item, base) for key, item in value.items() if key not in ("$id", "$schema")}
|
|
116
|
+
|
|
117
|
+
root = include(reference)
|
|
118
|
+
return {"$schema": "https://json-schema.org/draft/2020-12/schema", "$ref": root, "$defs": definitions}
|
|
119
|
+
|
|
120
|
+
def type_label(self, value: dict, base: str) -> str:
|
|
121
|
+
if "$ref" in value:
|
|
122
|
+
ref = base + value["$ref"] if value["$ref"].startswith("#") else value["$ref"]
|
|
123
|
+
return self.type_label(self.resolve(ref), ref.split("#")[0])
|
|
124
|
+
if "const" in value:
|
|
125
|
+
return json.dumps(value["const"], ensure_ascii=False)
|
|
126
|
+
if "enum" in value:
|
|
127
|
+
return "|".join(str(item) if item is not None else "null" for item in value["enum"])
|
|
128
|
+
alternatives = value.get("oneOf", value.get("anyOf"))
|
|
129
|
+
if alternatives is not None:
|
|
130
|
+
return "|".join(dict.fromkeys(self.type_label(item, base) for item in alternatives))
|
|
131
|
+
if "allOf" in value:
|
|
132
|
+
typed = [item for item in value["allOf"] if set(item) & {"$ref", "type", "enum", "const", "oneOf", "anyOf"}]
|
|
133
|
+
return "|".join(dict.fromkeys(self.type_label(item, base) for item in typed)) if typed else "object"
|
|
134
|
+
kind = value.get("type", "object")
|
|
135
|
+
if isinstance(kind, list):
|
|
136
|
+
return "|".join(kind)
|
|
137
|
+
if kind == "array":
|
|
138
|
+
element = self.type_label(value.get("items", {}), base)
|
|
139
|
+
return (f"({element})" if "|" in element else element) + "[]"
|
|
140
|
+
return kind
|
|
141
|
+
|
|
142
|
+
def summary(self, reference: str, descriptions: dict[str, str] | None = None) -> str:
|
|
143
|
+
schema = self.resolve(reference)
|
|
144
|
+
base = reference.split("#")[0]
|
|
145
|
+
if "$ref" in schema:
|
|
146
|
+
ref = schema["$ref"]
|
|
147
|
+
return self.summary(base + ref if ref.startswith("#") else ref, descriptions)
|
|
148
|
+
rows = []
|
|
149
|
+
for key, value in schema.get("properties", {}).items():
|
|
150
|
+
label = key + ("*" if key in schema.get("required", []) else "")
|
|
151
|
+
description = (descriptions or {}).get(key, value.get("description", ""))
|
|
152
|
+
rows.append((label + " " + self.type_label(value, base), description))
|
|
153
|
+
return "Input JSON (* required):\n" + "\n".join(help_rows(rows) if rows else [" {} No input fields."])
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def render_help(tool: str, argv: Sequence[str], commands: Sequence[dict], schemas: HelpSchemas) -> str:
|
|
157
|
+
value_options = {label.split()[0] for item in commands for label, _ in item["options"]
|
|
158
|
+
if len(label.split()) > 1}
|
|
159
|
+
selected, schema_topic = help_selection(argv, [item["name"] for item in commands], value_options)
|
|
160
|
+
leaf = next((item for item in commands if item["name"] == selected), None)
|
|
161
|
+
if leaf is None:
|
|
162
|
+
prefix = selected + " " if selected else ""
|
|
163
|
+
children = sorted({item["name"][len(prefix):].split()[0] for item in commands
|
|
164
|
+
if item["name"].startswith(prefix)})
|
|
165
|
+
rows = []
|
|
166
|
+
for name in children:
|
|
167
|
+
path = prefix + name
|
|
168
|
+
child = next((item for item in commands if item["name"] == path), None)
|
|
169
|
+
summary = child["summary"] if child else next(
|
|
170
|
+
item["group_summary"] for item in commands if item["name"].startswith(path + " "))
|
|
171
|
+
rows.append((name, summary))
|
|
172
|
+
options = [("-h, --help", "Show help.")]
|
|
173
|
+
if not selected:
|
|
174
|
+
options.append(("-v, --version", "Show toolkit version."))
|
|
175
|
+
return (f"Usage: {tool}{' ' + selected if selected else ''} COMMAND [options]\n\nCommands:\n"
|
|
176
|
+
+ "\n".join(help_rows(rows)) + "\n\nOptions:\n" + "\n".join(help_rows(options))
|
|
177
|
+
+ ("\n\nRun commands from the target project root." if not selected else "")
|
|
178
|
+
+ f"\n\nUse {tool}{' ' + selected if selected else ''} COMMAND -h for command details.\n")
|
|
179
|
+
if schema_topic:
|
|
180
|
+
require(bool(leaf.get("input")), "invalid_arguments", "This command uses positional arguments, not input JSON.")
|
|
181
|
+
return json.dumps(schemas.bundle(leaf["input"]), ensure_ascii=False, indent=2) + "\n"
|
|
182
|
+
usage = f"Usage: {tool} {selected} {leaf['usage']}"
|
|
183
|
+
lines = [textwrap.fill(usage, width=HELP_WIDTH, subsequent_indent=" ",
|
|
184
|
+
break_long_words=False, break_on_hyphens=False), "", paragraph(leaf["summary"])]
|
|
185
|
+
if leaf.get("arguments"):
|
|
186
|
+
lines.extend(["", "Arguments:", *help_rows(leaf["arguments"])])
|
|
187
|
+
lines.extend(["", "Options:", *help_rows(leaf["options"]), *help_rows([("-h, --help", "Show help.")])])
|
|
188
|
+
if leaf.get("input"):
|
|
189
|
+
lines.extend(["", leaf.get("input_summary") or schemas.summary(leaf["input"], leaf.get("fields"))])
|
|
190
|
+
lines.extend(["", paragraph("Output: " + leaf["result"] + " Exit 0 on success, 1 on error.")])
|
|
191
|
+
if leaf.get("notes"):
|
|
192
|
+
lines.extend(["", paragraph("Notes: " + leaf["notes"])])
|
|
193
|
+
if leaf.get("input"):
|
|
194
|
+
lines.extend(["", f"Schema: {tool} {selected} --help schema"])
|
|
195
|
+
return "\n".join(lines).rstrip() + "\n"
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
"""Shared protocol failures."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class ProtocolError(Exception):
|
|
9
|
+
def __init__(self, code: str, message: str, *, conflicts: tuple[str, ...] = (),
|
|
10
|
+
current: dict[str, Any] | None = None, details: Any = None) -> None:
|
|
11
|
+
super().__init__(message)
|
|
12
|
+
self.code = code
|
|
13
|
+
self.conflicts = conflicts
|
|
14
|
+
self.current = current
|
|
15
|
+
self.details = details
|
|
16
|
+
|
|
17
|
+
def state_error(self) -> dict[str, Any]:
|
|
18
|
+
return {"code": self.code, "message": str(self),
|
|
19
|
+
**({"details": self.details} if self.details is not None else {})}
|
|
20
|
+
|
|
21
|
+
def as_dict(self) -> dict[str, Any]:
|
|
22
|
+
return {"code": self.code, "message": str(self), "current": self.current,
|
|
23
|
+
"conflicts": list(self.conflicts),
|
|
24
|
+
"recovery": "Inspect the indicated inputs and current state before retrying."}
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def require(condition: bool, code: str, message: str, *objects: str) -> None:
|
|
28
|
+
if not condition:
|
|
29
|
+
raise ProtocolError(code, message, conflicts=tuple(objects))
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
"""Shared atomic file publication, independent of Plan state and locking."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import os
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
import tempfile
|
|
7
|
+
import time
|
|
8
|
+
|
|
9
|
+
from .errors import require
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def atomic_write(path: Path, raw: bytes, *, immutable: bool = False) -> None:
|
|
13
|
+
"""Publish one file using a same-directory temporary and finite retries.
|
|
14
|
+
|
|
15
|
+
Preserve atomic publication invariants: fsync the file, replace (or
|
|
16
|
+
publish immutable), fsync the parent on POSIX, and remove the temporary.
|
|
17
|
+
OSError survives; immutable conflicts use ProtocolError(basis_changed).
|
|
18
|
+
Multi-file installation transactions own their rollback policy.
|
|
19
|
+
"""
|
|
20
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
21
|
+
if immutable and path.exists():
|
|
22
|
+
require(path.read_bytes() == raw, "basis_changed", f"Immutable record differs: {path}")
|
|
23
|
+
return
|
|
24
|
+
descriptor, name = tempfile.mkstemp(prefix=".harness-", suffix=".tmp", dir=path.parent)
|
|
25
|
+
temporary = Path(name)
|
|
26
|
+
try:
|
|
27
|
+
with os.fdopen(descriptor, "wb") as handle:
|
|
28
|
+
handle.write(raw)
|
|
29
|
+
handle.flush()
|
|
30
|
+
os.fsync(handle.fileno())
|
|
31
|
+
if immutable:
|
|
32
|
+
_publish_new(temporary, path, raw)
|
|
33
|
+
else:
|
|
34
|
+
_replace(temporary, path)
|
|
35
|
+
if os.name != "nt":
|
|
36
|
+
directory = os.open(path.parent, os.O_RDONLY)
|
|
37
|
+
try:
|
|
38
|
+
os.fsync(directory)
|
|
39
|
+
finally:
|
|
40
|
+
os.close(directory)
|
|
41
|
+
finally:
|
|
42
|
+
temporary.unlink(missing_ok=True)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _replace(temporary: Path, path: Path) -> None:
|
|
46
|
+
"""A Windows reader may briefly deny replacement; persistent errors survive."""
|
|
47
|
+
for attempt in range(6):
|
|
48
|
+
try:
|
|
49
|
+
os.replace(temporary, path)
|
|
50
|
+
return
|
|
51
|
+
except PermissionError as error:
|
|
52
|
+
if os.name != "nt" or getattr(error, "winerror", None) not in (5, 32) or attempt == 5:
|
|
53
|
+
raise
|
|
54
|
+
time.sleep(0.02 * 2 ** attempt)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _publish_new(temporary: Path, path: Path, raw: bytes) -> None:
|
|
58
|
+
try:
|
|
59
|
+
if os.name == "nt":
|
|
60
|
+
os.rename(temporary, path)
|
|
61
|
+
else:
|
|
62
|
+
os.link(temporary, path)
|
|
63
|
+
except FileExistsError:
|
|
64
|
+
require(path.read_bytes() == raw, "basis_changed", f"Immutable record differs: {path}")
|
|
65
|
+
|
|
66
|
+
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
"""Durable atomic replacement and short-lived OS file ownership."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from contextlib import contextmanager
|
|
6
|
+
import errno
|
|
7
|
+
import os
|
|
8
|
+
import sys
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
import time
|
|
11
|
+
from typing import Iterator
|
|
12
|
+
|
|
13
|
+
from trigrams_toolkit.shared.errors import ProtocolError
|
|
14
|
+
from trigrams_toolkit.shared.files import atomic_write
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def _lock(handle, unlock: bool = False) -> None:
|
|
18
|
+
handle.seek(0)
|
|
19
|
+
if sys.platform == "win32":
|
|
20
|
+
import msvcrt
|
|
21
|
+
msvcrt.locking(handle.fileno(), msvcrt.LK_UNLCK if unlock else msvcrt.LK_NBLCK, 1)
|
|
22
|
+
else:
|
|
23
|
+
import fcntl
|
|
24
|
+
fcntl.flock(handle.fileno(), fcntl.LOCK_UN if unlock else fcntl.LOCK_EX | fcntl.LOCK_NB)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
@contextmanager
|
|
28
|
+
def locked(path: Path, *, timeout: float = 5.0) -> Iterator[None]:
|
|
29
|
+
"""The file remains; the OS releases ownership on process death."""
|
|
30
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
31
|
+
with path.open("a+b") as handle:
|
|
32
|
+
if path.stat().st_size == 0:
|
|
33
|
+
handle.write(b"\0")
|
|
34
|
+
handle.flush()
|
|
35
|
+
deadline = time.monotonic() + timeout
|
|
36
|
+
while True:
|
|
37
|
+
try:
|
|
38
|
+
_lock(handle)
|
|
39
|
+
break
|
|
40
|
+
except OSError as error:
|
|
41
|
+
if error.errno not in (errno.EACCES, errno.EAGAIN, errno.EDEADLK):
|
|
42
|
+
raise
|
|
43
|
+
if time.monotonic() >= deadline:
|
|
44
|
+
raise ProtocolError("lock_busy", f"Another process holds {path}") from error
|
|
45
|
+
time.sleep(0.01)
|
|
46
|
+
try:
|
|
47
|
+
yield
|
|
48
|
+
finally:
|
|
49
|
+
_lock(handle, unlock=True)
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
"""Real filesystem boundaries shared by resource and project references."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
import re
|
|
7
|
+
import stat
|
|
8
|
+
import sys
|
|
9
|
+
from pathlib import Path, PurePath, PureWindowsPath
|
|
10
|
+
from typing import Callable, Iterator
|
|
11
|
+
|
|
12
|
+
from .errors import ProtocolError, require
|
|
13
|
+
|
|
14
|
+
_INVALID = re.compile(r'[\\:*?"<>|\x00-\x1f]')
|
|
15
|
+
_DEVICE = re.compile(r"^(?:CON|PRN|AUX|NUL|CLOCK\$|CONIN\$|CONOUT\$|COM[1-9¹²³]|LPT[1-9¹²³])$", re.I)
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def relative_path(value: str) -> None:
|
|
19
|
+
require(isinstance(value, str) and bool(value), "path_outside_root", "Expected a relative path.")
|
|
20
|
+
parts = value.split("/")
|
|
21
|
+
require(not _INVALID.search(value), "path_outside_root", f"Invalid path: {value}")
|
|
22
|
+
for part in parts:
|
|
23
|
+
require(part not in ("", ".", "..") and not part.endswith((".", " ")),
|
|
24
|
+
"path_outside_root", f"Invalid path component: {value}")
|
|
25
|
+
require(not _DEVICE.match(part.split(".")[0]), "path_outside_root", f"Device alias: {value}")
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _comparison_path(path: PurePath) -> PurePath:
|
|
29
|
+
"""@to-plan P05/S01 Normalize known Windows prefixes only for component comparison."""
|
|
30
|
+
if isinstance(path, PureWindowsPath):
|
|
31
|
+
value = str(path)
|
|
32
|
+
if value[:8].casefold() == "\\\\?\\unc\\":
|
|
33
|
+
return PureWindowsPath("\\\\" + value[8:])
|
|
34
|
+
if value.startswith("\\\\?\\") and re.match(r"^[A-Za-z]:\\", value[4:]):
|
|
35
|
+
return PureWindowsPath(value[4:])
|
|
36
|
+
return path
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def confined(root: Path, relative: str) -> Path:
|
|
40
|
+
relative_path(relative)
|
|
41
|
+
try:
|
|
42
|
+
boundary = root.resolve()
|
|
43
|
+
path = (boundary / relative).resolve()
|
|
44
|
+
except (OSError, RuntimeError) as error:
|
|
45
|
+
raise ProtocolError("path_outside_root", f"Cannot resolve path: {relative}") from error
|
|
46
|
+
require(_comparison_path(path).is_relative_to(_comparison_path(boundary)), "path_outside_root",
|
|
47
|
+
f"Resolved path escapes root: {relative}", str(path))
|
|
48
|
+
return path
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def inside(root: Path, path: Path) -> Path:
|
|
52
|
+
boundary, resolved = root.resolve(), path.resolve()
|
|
53
|
+
boundary_key, resolved_key = _comparison_path(boundary), _comparison_path(resolved)
|
|
54
|
+
require(resolved_key.is_relative_to(boundary_key), "path_outside_root",
|
|
55
|
+
f"Path escapes root: {path}", str(path))
|
|
56
|
+
relative_path(resolved_key.relative_to(boundary_key).as_posix())
|
|
57
|
+
return resolved
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def path_key(path: Path) -> str:
|
|
61
|
+
return os.path.normcase(str(_comparison_path(path.resolve())))
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def is_link(path: Path) -> bool:
|
|
65
|
+
"""Detect symlinks and Windows junctions on Python 3.11 as well."""
|
|
66
|
+
try:
|
|
67
|
+
info = path.lstat()
|
|
68
|
+
except FileNotFoundError:
|
|
69
|
+
return False
|
|
70
|
+
return (stat.S_ISLNK(info.st_mode) or
|
|
71
|
+
(sys.platform == "win32" and info.st_reparse_tag == stat.IO_REPARSE_TAG_MOUNT_POINT))
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def files_under(root: Path, start: Path, *, exclude: Callable[[str], bool] | None = None) -> Iterator[Path]:
|
|
75
|
+
"""Follow internal directory links once; reject cycles and outside targets."""
|
|
76
|
+
def visit(path: Path, ancestors: frozenset[str]) -> Iterator[Path]:
|
|
77
|
+
if exclude is not None and exclude(path.relative_to(root).as_posix()):
|
|
78
|
+
return
|
|
79
|
+
resolved = inside(root, path)
|
|
80
|
+
key = path_key(resolved)
|
|
81
|
+
require(key not in ancestors, "invalid_reference", f"Directory link cycle: {path}")
|
|
82
|
+
if resolved.is_file():
|
|
83
|
+
yield path
|
|
84
|
+
return
|
|
85
|
+
require(resolved.is_dir(), "invalid_reference", f"Source path is unavailable: {path}")
|
|
86
|
+
for child in sorted(path.iterdir()):
|
|
87
|
+
yield from visit(child, ancestors | {key})
|
|
88
|
+
|
|
89
|
+
yield from visit(start, frozenset())
|