planledger 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.
planledger/__init__.py ADDED
@@ -0,0 +1,12 @@
1
+ from __future__ import annotations
2
+
3
+ from importlib.metadata import PackageNotFoundError, version
4
+
5
+
6
+ try:
7
+ __version__ = version("planledger")
8
+ except PackageNotFoundError: # pragma: no cover
9
+ __version__ = "0.0.0"
10
+
11
+
12
+ __all__ = ["__version__"]
planledger/_version.py ADDED
@@ -0,0 +1,24 @@
1
+ # file generated by vcs-versioning
2
+ # don't change, don't track in version control
3
+ from __future__ import annotations
4
+
5
+ __all__ = [
6
+ "__version__",
7
+ "__version_tuple__",
8
+ "version",
9
+ "version_tuple",
10
+ "__commit_id__",
11
+ "commit_id",
12
+ ]
13
+
14
+ version: str
15
+ __version__: str
16
+ __version_tuple__: tuple[int | str, ...]
17
+ version_tuple: tuple[int | str, ...]
18
+ commit_id: str | None
19
+ __commit_id__: str | None
20
+
21
+ __version__ = version = '0.1.0'
22
+ __version_tuple__ = version_tuple = (0, 1, 0)
23
+
24
+ __commit_id__ = commit_id = None
planledger/bundle.py ADDED
@@ -0,0 +1,251 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import sys
5
+ from pathlib import Path
6
+ from typing import Any
7
+
8
+ from planledger.errors import PlanledgerError
9
+ from planledger.guardrails import validate_handoff_contents
10
+ from planledger.render import build_plan
11
+ from planledger.storage import (
12
+ VALID_STATUSES,
13
+ Workspace,
14
+ apply_plan_mutations,
15
+ component_spec,
16
+ create_plan,
17
+ load_component_contents,
18
+ load_plan,
19
+ preview_plan_id,
20
+ validate_plan,
21
+ )
22
+
23
+ STRUCTURED_PLAN_SCHEMA = "planledger.structured_plan.v1"
24
+
25
+
26
+ def load_bundle(path: Path) -> dict[str, Any]:
27
+ if path.as_posix() == "-":
28
+ content = sys.stdin.read()
29
+ else:
30
+ try:
31
+ content = path.read_text(encoding="utf-8")
32
+ except FileNotFoundError as exc:
33
+ raise PlanledgerError(
34
+ "not_found",
35
+ f"Bundle file does not exist: {path}",
36
+ ) from exc
37
+ try:
38
+ loaded = json.loads(content)
39
+ except json.JSONDecodeError as exc:
40
+ raise PlanledgerError(
41
+ "invalid_bundle",
42
+ f"Bundle is not valid JSON: {exc}",
43
+ ) from exc
44
+ if not isinstance(loaded, dict):
45
+ raise PlanledgerError(
46
+ "invalid_bundle",
47
+ "Bundle must be a JSON object.",
48
+ )
49
+ return loaded
50
+
51
+
52
+ def _validate_components(
53
+ components: Any,
54
+ *,
55
+ section_name: str,
56
+ errors: list[str],
57
+ ) -> dict[str, str]:
58
+ if components is None:
59
+ return {}
60
+ if not isinstance(components, dict):
61
+ errors.append(f"{section_name} must be an object.")
62
+ return {}
63
+ validated: dict[str, str] = {}
64
+ for key, value in components.items():
65
+ try:
66
+ component_spec(key)
67
+ except PlanledgerError as exc:
68
+ errors.append(exc.message)
69
+ continue
70
+ if not isinstance(value, str):
71
+ errors.append(f"Component {key!r} must be a string.")
72
+ continue
73
+ validated[key] = value
74
+ return validated
75
+
76
+
77
+ def _validate_bundle_status(
78
+ status: Any,
79
+ *,
80
+ label: str,
81
+ errors: list[str],
82
+ ) -> None:
83
+ if status is not None and status not in VALID_STATUSES:
84
+ errors.append(f"{label} status is invalid.")
85
+
86
+
87
+ def _validate_create_bundle(bundle: dict[str, Any], errors: list[str]) -> None:
88
+ plan = bundle.get("plan")
89
+ if not isinstance(plan, dict):
90
+ errors.append("Create bundles require a 'plan' object.")
91
+ return
92
+ title = plan.get("title")
93
+ if not isinstance(title, str) or not title.strip():
94
+ errors.append("Create bundles require plan.title.")
95
+ request = plan.get("request")
96
+ if not isinstance(request, str) or not request.strip():
97
+ errors.append("Create bundles require plan.request.")
98
+ _validate_bundle_status(plan.get("status"), label="Create bundle", errors=errors)
99
+ components = _validate_components(
100
+ plan.get("components"),
101
+ section_name="plan.components",
102
+ errors=errors,
103
+ )
104
+ if plan.get("status") == "done":
105
+ errors.extend(validate_handoff_contents(components))
106
+
107
+
108
+ def _validate_done_update(
109
+ workspace: Workspace,
110
+ plan_id: str,
111
+ components: dict[str, str],
112
+ errors: list[str],
113
+ ) -> None:
114
+ plan = load_plan(workspace, plan_id)
115
+ current_contents = load_component_contents(plan)
116
+ current_contents.update(components)
117
+ for key, spec in plan.components.items():
118
+ if spec.required and not current_contents.get(key, "").strip():
119
+ errors.append(
120
+ f"Required component {key!r} would be empty "
121
+ "when setting status to done."
122
+ )
123
+ errors.extend(validate_handoff_contents(current_contents))
124
+
125
+
126
+ def _validate_update_bundle(
127
+ bundle: dict[str, Any],
128
+ workspace: Workspace | None,
129
+ errors: list[str],
130
+ ) -> None:
131
+ plan_id = bundle.get("plan_id")
132
+ if not isinstance(plan_id, str) or not plan_id.strip():
133
+ errors.append("Update bundles require plan_id.")
134
+ return
135
+ reason = bundle.get("reason")
136
+ if not isinstance(reason, str) or not reason.strip():
137
+ errors.append("Update bundles require reason.")
138
+ status = bundle.get("status")
139
+ _validate_bundle_status(status, label="Update bundle", errors=errors)
140
+ components = _validate_components(
141
+ bundle.get("components"),
142
+ section_name="Update bundle components",
143
+ errors=errors,
144
+ )
145
+ if workspace is None or errors:
146
+ return
147
+ plan = load_plan(workspace, plan_id)
148
+ if plan.status == "cancelled" and bundle.get("force") is not True:
149
+ errors.append("Update targets a cancelled plan without --force.")
150
+ if status == "done":
151
+ _validate_done_update(workspace, plan_id, components, errors)
152
+
153
+
154
+ def validate_structured_plan_bundle(
155
+ bundle: dict[str, Any],
156
+ workspace: Workspace | None = None,
157
+ ) -> list[str]:
158
+ errors: list[str] = []
159
+ schema = bundle.get("schema")
160
+ if schema != STRUCTURED_PLAN_SCHEMA:
161
+ errors.append(
162
+ "Missing or invalid schema: expected 'planledger.structured_plan.v1'."
163
+ )
164
+ operation = bundle.get("operation")
165
+ if operation not in {"create", "update"}:
166
+ errors.append("Operation must be 'create' or 'update'.")
167
+ return errors
168
+ if operation == "create":
169
+ _validate_create_bundle(bundle, errors)
170
+ else:
171
+ _validate_update_bundle(bundle, workspace, errors)
172
+ return errors
173
+
174
+
175
+ def apply_structured_plan_bundle(
176
+ workspace: Workspace,
177
+ bundle: dict[str, Any],
178
+ *,
179
+ dry_run: bool = False,
180
+ ) -> dict[str, Any]:
181
+ errors = validate_structured_plan_bundle(bundle, workspace)
182
+ if errors:
183
+ raise PlanledgerError(
184
+ "invalid_bundle",
185
+ "Structured plan bundle validation failed.",
186
+ remediation=errors,
187
+ )
188
+ operation = str(bundle["operation"])
189
+ if operation == "create":
190
+ plan_section = bundle["plan"]
191
+ assert isinstance(plan_section, dict)
192
+ components = plan_section.get("components", {})
193
+ assert isinstance(components, dict)
194
+ if dry_run:
195
+ return {
196
+ "operation": "create",
197
+ "dry_run": True,
198
+ "plan_id": preview_plan_id(workspace),
199
+ "title": str(plan_section["title"]),
200
+ "status": str(plan_section.get("status", "new")),
201
+ "component_keys": sorted(components),
202
+ }
203
+ created = create_plan(
204
+ workspace,
205
+ title=str(plan_section["title"]),
206
+ request=str(plan_section["request"]),
207
+ status=str(plan_section.get("status", "new")),
208
+ components={key: str(value) for key, value in components.items()},
209
+ )
210
+ built = build_plan(workspace, created.plan_id)
211
+ return {
212
+ "operation": "create",
213
+ "dry_run": False,
214
+ "plan": built,
215
+ }
216
+ plan_id = str(bundle["plan_id"])
217
+ reason = str(bundle["reason"])
218
+ components = bundle.get("components", {})
219
+ assert isinstance(components, dict)
220
+ plan_before = load_plan(workspace, plan_id)
221
+ if dry_run:
222
+ return {
223
+ "operation": "update",
224
+ "dry_run": True,
225
+ "plan_id": plan_id,
226
+ "current_version": plan_before.version,
227
+ "next_version": plan_before.version + 1,
228
+ "status": bundle.get("status", plan_before.status),
229
+ "component_keys": sorted(components),
230
+ }
231
+ updated = apply_plan_mutations(
232
+ workspace,
233
+ plan_id,
234
+ component_updates={key: str(value) for key, value in components.items()},
235
+ status=str(bundle["status"]) if "status" in bundle else None,
236
+ reason=reason,
237
+ force=bool(bundle.get("force", False)),
238
+ )
239
+ validation_errors = validate_plan(updated, for_done=updated.status == "done")
240
+ if validation_errors:
241
+ raise PlanledgerError(
242
+ "invalid_plan",
243
+ "Updated plan failed validation.",
244
+ remediation=validation_errors,
245
+ )
246
+ built = build_plan(workspace, plan_id)
247
+ return {
248
+ "operation": "update",
249
+ "dry_run": False,
250
+ "plan": built,
251
+ }