@mriekki/lean 0.0.0-stage → 0.1.0

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 (82) hide show
  1. package/README.md +67 -3
  2. package/assets/components.json +33 -0
  3. package/assets/core/distribution.json +51 -0
  4. package/assets/deployment/distribution.json +34 -0
  5. package/assets/generated/ASSEMBLY.json +382 -0
  6. package/assets/generated/core/core/agents/coach.agent.md +69 -0
  7. package/assets/generated/core/core/agents/reviewer.agent.md +85 -0
  8. package/assets/generated/core/core/instructions/lean-docs.instructions.md +14 -0
  9. package/assets/generated/core/core/instructions/lean-workflow.instructions.md +35 -0
  10. package/assets/generated/core/core/learning/CODING_DRILLS.md +35 -0
  11. package/assets/generated/core/core/learning/DIAGRAM_GUIDE.md +19 -0
  12. package/assets/generated/core/core/learning/ENGINEERING_LEARNING_WORKBOOK.md +82 -0
  13. package/assets/generated/core/core/learning/LEARNING_MAP.md +51 -0
  14. package/assets/generated/core/core/learning/LEARNING_PROGRESS.md +31 -0
  15. package/assets/generated/core/core/learning/RESOURCE_CATALOG.md +25 -0
  16. package/assets/generated/core/core/learning/SQL_DRILLS.md +27 -0
  17. package/assets/generated/core/core/learning/SYSTEM_DESIGN_DRILLS.md +21 -0
  18. package/assets/generated/core/core/process/COACHING_GUIDE.md +57 -0
  19. package/assets/generated/core/core/process/GUIDED_NEXT_STEPS.md +48 -0
  20. package/assets/generated/core/core/process/HUMAN_GATES.md +81 -0
  21. package/assets/generated/core/core/process/INTERACTIVE_SESSION_GUIDE.md +62 -0
  22. package/assets/generated/core/core/process/PRODUCTION_ENABLEMENT.md +59 -0
  23. package/assets/generated/core/core/process/PR_WORKFLOW.md +53 -0
  24. package/assets/generated/core/core/process/SETUP_ACCEPTANCE_CHECKLIST.md +72 -0
  25. package/assets/generated/core/core/process/WORK_ITEM_MODEL.md +56 -0
  26. package/assets/generated/core/core/skills/cleanup-branches/SKILL.md +190 -0
  27. package/assets/generated/core/core/skills/coach/SKILL.md +136 -0
  28. package/assets/generated/core/core/skills/code-walkthrough/SKILL.md +197 -0
  29. package/assets/generated/core/core/skills/core-sync/SKILL.md +220 -0
  30. package/assets/generated/core/core/skills/define-feature/SKILL.md +144 -0
  31. package/assets/generated/core/core/skills/deliver/SKILL.md +315 -0
  32. package/assets/generated/core/core/skills/deploy/SKILL.md +193 -0
  33. package/assets/generated/core/core/skills/grill-me/SKILL.md +77 -0
  34. package/assets/generated/core/core/skills/grill-with-docs/SKILL.md +90 -0
  35. package/assets/generated/core/core/skills/learning-review/SKILL.md +90 -0
  36. package/assets/generated/core/core/skills/next-step/SKILL.md +166 -0
  37. package/assets/generated/core/core/skills/production-readiness/SKILL.md +357 -0
  38. package/assets/generated/core/core/skills/pull-latest/SKILL.md +166 -0
  39. package/assets/generated/core/core/skills/refine-requirements/SKILL.md +207 -0
  40. package/assets/generated/core/core/skills/start-work/SKILL.md +178 -0
  41. package/assets/generated/core/core/skills/tear-down/SKILL.md +138 -0
  42. package/assets/generated/core/core/skills/upstream-fix/SKILL.md +206 -0
  43. package/assets/generated/core/core/skills/wait-what/SKILL.md +86 -0
  44. package/assets/generated/core/core/templates/FEATURE_BRIEF_TEMPLATE.md +27 -0
  45. package/assets/generated/core/core/templates/PRODUCT_BRIEF_TEMPLATE.md +27 -0
  46. package/assets/generated/core/core/templates/PULL_REQUEST_TEMPLATE.md +37 -0
  47. package/assets/generated/core/core/templates/REQUIREMENTS_TEMPLATE.md +17 -0
  48. package/assets/generated/core/profiles/greenfield/lean-workspace.json +12 -0
  49. package/assets/generated/core/tools/package/check_baseline.py +102 -0
  50. package/assets/generated/core/tools/package/check_upstream.py +171 -0
  51. package/assets/generated/deployment/distribution/lean-poc-deploy.py +8 -0
  52. package/assets/generated/deployment/src/lean_poc_deployment/__init__.py +3 -0
  53. package/assets/generated/deployment/src/lean_poc_deployment/__main__.py +3 -0
  54. package/assets/generated/deployment/src/lean_poc_deployment/app_cli.py +140 -0
  55. package/assets/generated/deployment/src/lean_poc_deployment/app_runtime.py +455 -0
  56. package/assets/generated/deployment/src/lean_poc_deployment/app_runtime_remote.py +416 -0
  57. package/assets/generated/deployment/src/lean_poc_deployment/box_platform.py +208 -0
  58. package/assets/generated/deployment/src/lean_poc_deployment/box_platform_assets.py +100 -0
  59. package/assets/generated/deployment/src/lean_poc_deployment/box_platform_remote.py +271 -0
  60. package/assets/generated/deployment/src/lean_poc_deployment/cli.py +437 -0
  61. package/assets/generated/deployment/src/lean_poc_deployment/doctor.py +121 -0
  62. package/assets/generated/deployment/src/lean_poc_deployment/entrypoint.py +25 -0
  63. package/assets/generated/deployment/src/lean_poc_deployment/errors.py +5 -0
  64. package/assets/generated/deployment/src/lean_poc_deployment/keys.py +171 -0
  65. package/assets/generated/deployment/src/lean_poc_deployment/profiles.py +204 -0
  66. package/assets/generated/deployment/src/lean_poc_deployment/route_registry.py +367 -0
  67. package/assets/generated/deployment/src/lean_poc_deployment/route_registry_remote.py +443 -0
  68. package/assets/generated/deployment/src/lean_poc_deployment/security.py +290 -0
  69. package/assets/generated/deployment/src/lean_poc_deployment/sqlite_adapter.py +335 -0
  70. package/assets/generated/deployment/src/lean_poc_deployment/sqlite_adapter_remote.py +340 -0
  71. package/assets/generated/deployment/src/lean_poc_deployment/sqlite_cli.py +86 -0
  72. package/assets/generated/deployment/src/lean_poc_deployment/sqlite_import_recovery.py +437 -0
  73. package/assets/generated/deployment/src/lean_poc_deployment/ssh.py +118 -0
  74. package/assets/generated/deployment/src/lean_poc_deployment/teardown.py +286 -0
  75. package/assets/generated/deployment/src/lean_poc_deployment/teardown_cli.py +120 -0
  76. package/assets/generated/deployment/src/lean_poc_deployment/teardown_remote.py +100 -0
  77. package/assets/generated/deployment/src/lean_poc_deployment/trust.py +278 -0
  78. package/bin/lean.mjs +9 -0
  79. package/package.json +33 -6
  80. package/src/cli.mjs +131 -0
  81. package/src/engine.mjs +243 -0
  82. package/src/package-data.mjs +18 -0
@@ -0,0 +1,286 @@
1
+ """Scoped destructive tear-down for Kit-managed POC environments and local Docker state."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import re
7
+ import shlex
8
+ import shutil
9
+ import subprocess
10
+ from typing import Any, Iterable
11
+
12
+ from .errors import DeploymentKitError
13
+ from .profiles import load_profile
14
+ from .route_registry import apply_route_change, plan_route_removal, route_inventory
15
+ from .ssh import ssh_args, verify_access
16
+ from .teardown_remote import REMOTE_SCRIPT
17
+
18
+ TEAR_DOWN_WRITE_PHRASE = "[POC TEAR DOWN]"
19
+ PRODUCTION_DATA_DELETE_PHRASE = "[PRODUCTION DATA DELETE]"
20
+ SUPPORTED_SCOPES = ("local", "staging", "production", "all")
21
+
22
+ _SLUG_RE = re.compile(r"^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$")
23
+ _REPO_RE = re.compile(r"^[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+$")
24
+ _TARGET_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_.-]{0,127}$")
25
+ _PACKAGE_RE = re.compile(r"^ghcr\.io/[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+$")
26
+
27
+
28
+ def _slug(value: str, field: str) -> str:
29
+ if not isinstance(value, str) or _SLUG_RE.fullmatch(value) is None:
30
+ raise DeploymentKitError(f"{field} must use lowercase letters, digits, and internal hyphens.")
31
+ return value
32
+
33
+
34
+ def _owner_repo(value: str) -> str:
35
+ if not isinstance(value, str) or _REPO_RE.fullmatch(value) is None:
36
+ raise DeploymentKitError("ownerRepo must use GitHub owner/repository form without URL syntax.")
37
+ return value
38
+
39
+
40
+ def _package(value: str) -> str:
41
+ if not isinstance(value, str) or _PACKAGE_RE.fullmatch(value) is None:
42
+ raise DeploymentKitError("localPackage must use exact ghcr.io/owner/package form.")
43
+ return value
44
+
45
+
46
+ def parse_environment_targets(items: Iterable[str]) -> dict[str, str]:
47
+ result: dict[str, str] = {}
48
+ for item in items:
49
+ if not isinstance(item, str) or "=" not in item:
50
+ raise DeploymentKitError("environment target bindings must use environment=target form.")
51
+ environment, target = item.split("=", 1)
52
+ environment = _slug(environment, "environment")
53
+ if environment not in {"staging", "production"}:
54
+ raise DeploymentKitError("tear-down supports only staging and production environment bindings.")
55
+ if not target or _TARGET_RE.fullmatch(target) is None:
56
+ raise DeploymentKitError("target profile names contain unsupported characters.")
57
+ if environment in result:
58
+ raise DeploymentKitError(f"Duplicate environment target binding: {environment}")
59
+ result[environment] = target
60
+ return dict(sorted(result.items()))
61
+
62
+
63
+ def _remote_environments(scope: str) -> tuple[str, ...]:
64
+ if scope == "staging":
65
+ return ("staging",)
66
+ if scope == "production":
67
+ return ("production",)
68
+ if scope == "all":
69
+ return ("staging", "production")
70
+ return ()
71
+
72
+
73
+ def normalize_teardown_spec(
74
+ *,
75
+ owner_repo: str,
76
+ app_slug: str,
77
+ scope: str,
78
+ environment_targets: dict[str, str] | Iterable[tuple[str, str]],
79
+ local_package: str | None,
80
+ ) -> dict[str, Any]:
81
+ if scope not in SUPPORTED_SCOPES:
82
+ raise DeploymentKitError("scope must be one of: local, staging, production, all.")
83
+
84
+ pairs = environment_targets.items() if isinstance(environment_targets, dict) else environment_targets
85
+ normalized_targets: dict[str, str] = {}
86
+ for environment, target in pairs:
87
+ environment = _slug(environment, "environment")
88
+ if environment not in {"staging", "production"}:
89
+ raise DeploymentKitError("tear-down supports only staging and production environment bindings.")
90
+ if not isinstance(target, str) or _TARGET_RE.fullmatch(target) is None:
91
+ raise DeploymentKitError("target profile names contain unsupported characters.")
92
+ if environment in normalized_targets:
93
+ raise DeploymentKitError(f"Duplicate environment target binding: {environment}")
94
+ normalized_targets[environment] = target
95
+
96
+ selected_targets: dict[str, str] = {}
97
+ for environment in _remote_environments(scope):
98
+ if environment not in normalized_targets:
99
+ raise DeploymentKitError(f"scope {scope!r} requires an explicit {environment}=target binding.")
100
+ selected_targets[environment] = normalized_targets[environment]
101
+
102
+ package = _package(local_package) if local_package is not None else None
103
+ if scope in {"local", "all"} and package is None:
104
+ raise DeploymentKitError(f"scope {scope!r} requires --local-package for exact local Docker ownership.")
105
+
106
+ return {
107
+ "schemaVersion": 1,
108
+ "ownerRepo": _owner_repo(owner_repo),
109
+ "appSlug": _slug(app_slug, "appSlug"),
110
+ "scope": scope,
111
+ "environmentTargets": selected_targets,
112
+ "localPackage": package,
113
+ }
114
+
115
+
116
+ def _find_route(inventory: dict[str, Any], app_slug: str, environment: str) -> dict[str, Any] | None:
117
+ route_id = f"{app_slug}--{environment}"
118
+ return next((item for item in inventory["managedRoutes"] if item["routeId"] == route_id), None)
119
+
120
+
121
+ def _tear_down_route(target: str, owner_repo: str, app_slug: str, environment: str) -> dict[str, Any]:
122
+ inventory = route_inventory(target)
123
+ route = _find_route(inventory, app_slug, environment)
124
+ if route is None:
125
+ return {"state": "absent", "mutated": False}
126
+ if route["ownerRepo"] != owner_repo:
127
+ raise DeploymentKitError(
128
+ f"Route {app_slug}--{environment} is owned by {route['ownerRepo']}, not {owner_repo}."
129
+ )
130
+ plan = plan_route_removal(
131
+ target,
132
+ owner_repo=owner_repo,
133
+ environment=environment,
134
+ app_slug=app_slug,
135
+ )
136
+ apply_route_change(plan)
137
+ return {"state": "removed", "mutated": True, "hostnames": route["hostnames"]}
138
+
139
+
140
+ def _tear_down_remote_environment(
141
+ target: str,
142
+ owner_repo: str,
143
+ app_slug: str,
144
+ environment: str,
145
+ ) -> dict[str, Any]:
146
+ profile = load_profile(target)
147
+ evidence = verify_access(profile)
148
+ command = ssh_args(
149
+ profile,
150
+ evidence["address"],
151
+ command="sudo -n bash -s -- "
152
+ + " ".join(shlex.quote(value) for value in (owner_repo, app_slug, environment)),
153
+ )
154
+ completed = subprocess.run(
155
+ command,
156
+ input=REMOTE_SCRIPT.encode("utf-8"),
157
+ capture_output=True,
158
+ check=False,
159
+ )
160
+ stdout = completed.stdout.decode("utf-8", errors="replace").strip()
161
+ stderr = completed.stderr.decode("utf-8", errors="replace").strip()
162
+ if completed.returncode != 0:
163
+ raise DeploymentKitError(
164
+ "Remote POC tear-down failed: " + (stderr or stdout or f"exit {completed.returncode}")
165
+ )
166
+ parts = stdout.split("\t")
167
+ if len(parts) not in {4, 5} or parts[0] != "TEAR_DOWN" or parts[1] not in {"absent", "removed"}:
168
+ raise DeploymentKitError("Remote POC tear-down returned malformed evidence.")
169
+ if parts[2] != app_slug or parts[3] != environment:
170
+ raise DeploymentKitError("Remote POC tear-down returned mismatched app/environment evidence.")
171
+ result: dict[str, Any] = {"state": parts[1], "mutated": parts[1] == "removed"}
172
+ if len(parts) == 5:
173
+ result["containerName"] = parts[4]
174
+ return result
175
+
176
+
177
+ def _run_local(args: list[str]) -> subprocess.CompletedProcess[str]:
178
+ return subprocess.run(
179
+ args,
180
+ text=True,
181
+ encoding="utf-8",
182
+ errors="replace",
183
+ capture_output=True,
184
+ check=False,
185
+ )
186
+
187
+
188
+ def _image_matches_package(image: str, package: str) -> bool:
189
+ return image == package or image.startswith(package + ":") or image.startswith(package + "@")
190
+
191
+
192
+ def tear_down_workstation_package(package: str) -> dict[str, Any]:
193
+ package = _package(package)
194
+ docker = shutil.which("docker")
195
+ if not docker:
196
+ return {"state": "docker-unavailable", "mutated": False, "containers": [], "images": []}
197
+
198
+ listed = _run_local([docker, "ps", "-a", "--format", "{{.ID}}"])
199
+ if listed.returncode != 0:
200
+ raise DeploymentKitError("Local Docker container inventory failed: " + (listed.stderr or listed.stdout).strip())
201
+
202
+ containers: list[str] = []
203
+ for container_id in [line.strip() for line in listed.stdout.splitlines() if line.strip()]:
204
+ inspected = _run_local([docker, "inspect", "--format", "{{.Config.Image}}", container_id])
205
+ if inspected.returncode != 0:
206
+ raise DeploymentKitError(f"Local Docker inspect failed for container {container_id}.")
207
+ image = inspected.stdout.strip()
208
+ if _image_matches_package(image, package):
209
+ containers.append(container_id)
210
+
211
+ if containers:
212
+ removed = _run_local([docker, "rm", "-f", "-v", *containers])
213
+ if removed.returncode != 0:
214
+ raise DeploymentKitError("Local POC container removal failed: " + (removed.stderr or removed.stdout).strip())
215
+
216
+ images_result = _run_local([docker, "images", "--format", "{{.Repository}}:{{.Tag}}"])
217
+ if images_result.returncode != 0:
218
+ raise DeploymentKitError("Local Docker image inventory failed: " + (images_result.stderr or images_result.stdout).strip())
219
+ image_refs = sorted(
220
+ {
221
+ line.strip()
222
+ for line in images_result.stdout.splitlines()
223
+ if line.strip().startswith(package + ":") and not line.strip().endswith(":<none>")
224
+ }
225
+ )
226
+ if image_refs:
227
+ removed = _run_local([docker, "image", "rm", "-f", *image_refs])
228
+ if removed.returncode != 0:
229
+ raise DeploymentKitError("Local POC image removal failed: " + (removed.stderr or removed.stdout).strip())
230
+
231
+ return {
232
+ "state": "removed" if containers or image_refs else "absent",
233
+ "mutated": bool(containers or image_refs),
234
+ "containers": containers,
235
+ "images": image_refs,
236
+ }
237
+
238
+
239
+ def tear_down_poc(spec: dict[str, Any]) -> dict[str, Any]:
240
+ normalized = normalize_teardown_spec(
241
+ owner_repo=spec.get("ownerRepo"),
242
+ app_slug=spec.get("appSlug"),
243
+ scope=spec.get("scope"),
244
+ environment_targets=(spec.get("environmentTargets") or {}).items(),
245
+ local_package=spec.get("localPackage"),
246
+ )
247
+
248
+ environments: list[dict[str, Any]] = []
249
+ mutated = False
250
+ for environment, target in normalized["environmentTargets"].items():
251
+ route = _tear_down_route(target, normalized["ownerRepo"], normalized["appSlug"], environment)
252
+ runtime = _tear_down_remote_environment(
253
+ target,
254
+ normalized["ownerRepo"],
255
+ normalized["appSlug"],
256
+ environment,
257
+ )
258
+ mutated = mutated or route["mutated"] or runtime["mutated"]
259
+ environments.append(
260
+ {
261
+ "environment": environment,
262
+ "targetName": target,
263
+ "route": route,
264
+ "runtimeAndPersistentData": runtime,
265
+ }
266
+ )
267
+
268
+ workstation: dict[str, Any] = {"state": "not-selected", "mutated": False}
269
+ if normalized["scope"] in {"local", "all"}:
270
+ workstation = tear_down_workstation_package(normalized["localPackage"])
271
+ mutated = mutated or workstation["mutated"]
272
+
273
+ return {
274
+ "schemaVersion": 1,
275
+ "ownerRepo": normalized["ownerRepo"],
276
+ "appSlug": normalized["appSlug"],
277
+ "scope": normalized["scope"],
278
+ "environments": environments,
279
+ "workstation": workstation,
280
+ "productionDataIncluded": normalized["scope"] in {"production", "all"},
281
+ "mutated": mutated,
282
+ }
283
+
284
+
285
+ def render_teardown_summary(result: dict[str, Any]) -> str:
286
+ return json.dumps(result, indent=2, sort_keys=True)
@@ -0,0 +1,120 @@
1
+ """CLI for scoped destructive POC tear-down."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import sys
7
+
8
+ from .errors import DeploymentKitError
9
+ from .teardown import (
10
+ PRODUCTION_DATA_DELETE_PHRASE,
11
+ SUPPORTED_SCOPES,
12
+ TEAR_DOWN_WRITE_PHRASE,
13
+ normalize_teardown_spec,
14
+ parse_environment_targets,
15
+ render_teardown_summary,
16
+ tear_down_poc,
17
+ )
18
+
19
+
20
+ def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
21
+ parser = argparse.ArgumentParser(
22
+ prog="lean-poc-deploy tear-down",
23
+ description=(
24
+ "Remove the selected Kit-managed POC environment(s) and/or exact-package local Docker state. "
25
+ "Remote tear-down deletes persistent application data for the selected environment."
26
+ ),
27
+ )
28
+ parser.add_argument("scope", choices=SUPPORTED_SCOPES)
29
+ parser.add_argument("--owner-repo", required=True)
30
+ parser.add_argument("--app-slug", required=True)
31
+ parser.add_argument(
32
+ "--environment-target",
33
+ action="append",
34
+ default=[],
35
+ metavar="ENV=TARGET",
36
+ help="Explicit staging/production environment-to-target binding; repeat as needed by the selected scope.",
37
+ )
38
+ parser.add_argument(
39
+ "--local-package",
40
+ help="Exact local Docker package identity, e.g. ghcr.io/owner/package; required for local and all scopes.",
41
+ )
42
+ parser.add_argument(
43
+ "--authorization",
44
+ help=f"Required destructive phrase: {TEAR_DOWN_WRITE_PHRASE}",
45
+ )
46
+ parser.add_argument(
47
+ "--production-data-authorization",
48
+ help=(
49
+ "Additional phrase required for production/all because persistent Production data is deleted: "
50
+ f"{PRODUCTION_DATA_DELETE_PHRASE}"
51
+ ),
52
+ )
53
+ return parser.parse_args(argv)
54
+
55
+
56
+ def _preview(spec: dict[str, object]) -> dict[str, object]:
57
+ production = spec["scope"] in {"production", "all"}
58
+ return {
59
+ "schemaVersion": 1,
60
+ "ownerRepo": spec["ownerRepo"],
61
+ "appSlug": spec["appSlug"],
62
+ "scope": spec["scope"],
63
+ "environmentTargets": spec["environmentTargets"],
64
+ "localPackage": spec["localPackage"],
65
+ "destructive": True,
66
+ "deletesPersistentData": bool(spec["environmentTargets"]),
67
+ "deletesProductionData": production,
68
+ "preservesSharedPlatform": True,
69
+ "preservesUnrelatedPocs": True,
70
+ "deletesGhcrPackage": False,
71
+ "requiredAuthorization": TEAR_DOWN_WRITE_PHRASE,
72
+ "requiredProductionDataAuthorization": PRODUCTION_DATA_DELETE_PHRASE if production else None,
73
+ }
74
+
75
+
76
+ def main(argv: list[str] | None = None) -> int:
77
+ try:
78
+ args = parse_args(argv)
79
+ bindings = parse_environment_targets(args.environment_target)
80
+ spec = normalize_teardown_spec(
81
+ owner_repo=args.owner_repo,
82
+ app_slug=args.app_slug,
83
+ scope=args.scope,
84
+ environment_targets=bindings,
85
+ local_package=args.local_package,
86
+ )
87
+ preview = _preview(spec)
88
+
89
+ missing_general = args.authorization != TEAR_DOWN_WRITE_PHRASE
90
+ needs_production = args.scope in {"production", "all"}
91
+ missing_production = needs_production and (
92
+ args.production_data_authorization != PRODUCTION_DATA_DELETE_PHRASE
93
+ )
94
+ if missing_general or missing_production:
95
+ print("POC TEAR-DOWN PREVIEW")
96
+ print(render_teardown_summary(preview))
97
+ if missing_general:
98
+ print(
99
+ f"ERROR: destructive tear-down requires --authorization {TEAR_DOWN_WRITE_PHRASE!r}",
100
+ file=sys.stderr,
101
+ )
102
+ if missing_production:
103
+ print(
104
+ "ERROR: Production persistent-data deletion requires "
105
+ f"--production-data-authorization {PRODUCTION_DATA_DELETE_PHRASE!r}",
106
+ file=sys.stderr,
107
+ )
108
+ return 2
109
+
110
+ result = tear_down_poc(spec)
111
+ print("POC TEAR-DOWN COMPLETE")
112
+ print(render_teardown_summary(result))
113
+ return 0
114
+ except DeploymentKitError as exc:
115
+ print(f"ERROR: {exc}", file=sys.stderr)
116
+ return 2
117
+
118
+
119
+ if __name__ == "__main__":
120
+ raise SystemExit(main())
@@ -0,0 +1,100 @@
1
+ """Remote destructive tear-down for one Kit-managed POC environment."""
2
+
3
+ REMOTE_SCRIPT = r'''#!/usr/bin/env bash
4
+ set -Eeuo pipefail
5
+
6
+ APP_ROOT="/srv/lean-poc-apps"
7
+ OWNER="$1"
8
+ APP="$2"
9
+ ENVIRONMENT="$3"
10
+
11
+ valid_slug() { [[ "$1" =~ ^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$ ]]; }
12
+ valid_repo() { [[ "$1" =~ ^[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+$ ]]; }
13
+ meta_value() {
14
+ local path="$1" key="$2"
15
+ [[ -f "$path" && ! -L "$path" ]] || return 1
16
+ sed -n "s/^${key}=//p" "$path" | head -n1
17
+ }
18
+ assert_owned_marker() {
19
+ local path="$1"
20
+ [[ -f "$path" && ! -L "$path" ]] || return 1
21
+ [[ "$(meta_value "$path" OWNER_REPO || true)" == "$OWNER" && \
22
+ "$(meta_value "$path" APP_SLUG || true)" == "$APP" && \
23
+ "$(meta_value "$path" ENVIRONMENT || true)" == "$ENVIRONMENT" ]]
24
+ }
25
+
26
+ valid_repo "$OWNER" || { echo "Invalid owner repository." >&2; exit 20; }
27
+ valid_slug "$APP" || { echo "Invalid application slug." >&2; exit 20; }
28
+ valid_slug "$ENVIRONMENT" || { echo "Invalid environment slug." >&2; exit 20; }
29
+
30
+ ROOT="$APP_ROOT/$APP/$ENVIRONMENT"
31
+ STATE="$ROOT/deployment.env"
32
+ PERSISTENCE="$ROOT/persistence.env"
33
+
34
+ if [[ ! -e "$ROOT" ]]; then
35
+ printf 'TEAR_DOWN\tabsent\t%s\t%s\n' "$APP" "$ENVIRONMENT"
36
+ exit 0
37
+ fi
38
+
39
+ [[ -d "$ROOT" && ! -L "$ROOT" ]] || {
40
+ echo "POC environment root is not a safe managed directory: $ROOT" >&2
41
+ exit 21
42
+ }
43
+
44
+ HAS_STATE=false
45
+ HAS_PERSISTENCE=false
46
+ [[ -f "$STATE" && ! -L "$STATE" ]] && HAS_STATE=true
47
+ [[ -f "$PERSISTENCE" && ! -L "$PERSISTENCE" ]] && HAS_PERSISTENCE=true
48
+ [[ "$HAS_STATE" == true || "$HAS_PERSISTENCE" == true ]] || {
49
+ echo "POC environment root has no managed ownership marker: $ROOT" >&2
50
+ exit 21
51
+ }
52
+
53
+ if [[ "$HAS_STATE" == true ]] && ! assert_owned_marker "$STATE"; then
54
+ echo "POC deployment ownership mismatch for $ROOT" >&2
55
+ exit 22
56
+ fi
57
+ if [[ "$HAS_PERSISTENCE" == true ]] && ! assert_owned_marker "$PERSISTENCE"; then
58
+ echo "POC persistence ownership mismatch for $ROOT" >&2
59
+ exit 22
60
+ fi
61
+
62
+ CONTAINER=""
63
+ if [[ "$HAS_STATE" == true ]]; then
64
+ CURRENT_RELEASE="$(meta_value "$STATE" CURRENT_RELEASE || true)"
65
+ [[ -n "$CURRENT_RELEASE" && "$CURRENT_RELEASE" != */* && "$CURRENT_RELEASE" != *..* ]] || {
66
+ echo "Managed deployment state has an invalid current release." >&2
67
+ exit 23
68
+ }
69
+
70
+ RELEASE_FILE="$ROOT/releases/$CURRENT_RELEASE/release.env"
71
+ [[ -f "$RELEASE_FILE" && ! -L "$RELEASE_FILE" ]] || {
72
+ echo "Managed current release metadata is missing: $RELEASE_FILE" >&2
73
+ exit 23
74
+ }
75
+ assert_owned_marker "$RELEASE_FILE" || {
76
+ echo "Managed release ownership does not match deployment state." >&2
77
+ exit 23
78
+ }
79
+ CONTAINER="$(meta_value "$RELEASE_FILE" CONTAINER_NAME || true)"
80
+ [[ "$CONTAINER" =~ ^[A-Za-z0-9][A-Za-z0-9_.-]{0,127}$ ]] || {
81
+ echo "Managed release contains an invalid container name." >&2
82
+ exit 23
83
+ }
84
+
85
+ if docker inspect "$CONTAINER" >/dev/null 2>&1; then
86
+ docker rm -f "$CONTAINER" >/dev/null
87
+ fi
88
+ fi
89
+
90
+ # The verified environment root is owned by this POC/environment. Tear-down
91
+ # removes releases, evidence, persistent data, and backups together.
92
+ rm -rf --one-file-system -- "$ROOT"
93
+
94
+ APP_DIR="$APP_ROOT/$APP"
95
+ if [[ -d "$APP_DIR" ]] && ! find "$APP_DIR" -mindepth 1 -print -quit | grep -q .; then
96
+ rmdir "$APP_DIR"
97
+ fi
98
+
99
+ printf 'TEAR_DOWN\tremoved\t%s\t%s\t%s\n' "$APP" "$ENVIRONMENT" "$CONTAINER"
100
+ '''