okstra 0.229.0 → 0.231.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 (150) hide show
  1. package/README.md +1 -5
  2. package/dist/cli-registry.mjs +0 -18
  3. package/dist/cli-registry.mjs.map +1 -1
  4. package/dist/commands/lifecycle/doctor.mjs +0 -15
  5. package/dist/commands/lifecycle/doctor.mjs.map +1 -1
  6. package/dist/lib/skill-catalog.mjs +4 -4
  7. package/dist/lib/skill-catalog.mjs.map +1 -1
  8. package/docs/architecture/storage-model.md +168 -18
  9. package/docs/architecture.md +15 -14
  10. package/docs/coding-rules.md +15 -0
  11. package/docs/contributor-change-matrix.md +5 -5
  12. package/docs/project-structure-overview.md +13 -19
  13. package/package.json +2 -3
  14. package/runtime/BUILD.json +2 -2
  15. package/runtime/bin/lib/okstra/interactive.sh +2 -1
  16. package/runtime/prompts/coding-preflight/clean-code.md +8 -0
  17. package/runtime/prompts/coding-preflight/overview.md +1 -0
  18. package/runtime/prompts/launch.template.md +7 -5
  19. package/runtime/prompts/lead/convergence.md +4 -4
  20. package/runtime/prompts/lead/okstra-lead-contract.md +19 -18
  21. package/runtime/prompts/lead/phase-routing.md +1 -1
  22. package/runtime/prompts/lead/report-writer.md +3 -3
  23. package/runtime/prompts/lead/team-contract.md +3 -3
  24. package/runtime/prompts/profiles/_coding-conventions-preflight.md +2 -0
  25. package/runtime/python/okstra_ctl/agent/invocation.py +190 -9
  26. package/runtime/python/okstra_ctl/agent/prompt_cli/materialize.py +31 -1
  27. package/runtime/python/okstra_ctl/blocking_checks.py +10 -0
  28. package/runtime/python/okstra_ctl/cmux.py +4 -2
  29. package/runtime/python/okstra_ctl/code_review_census.py +194 -0
  30. package/runtime/python/okstra_ctl/code_review_coverage.py +3 -1
  31. package/runtime/python/okstra_ctl/code_review_scope.py +9 -6
  32. package/runtime/python/okstra_ctl/code_review_target.py +38 -2
  33. package/runtime/python/okstra_ctl/conformance.py +30 -0
  34. package/runtime/python/okstra_ctl/conformance_evidence.py +316 -0
  35. package/runtime/python/okstra_ctl/correction_round.py +19 -13
  36. package/runtime/python/okstra_ctl/dispatch_core.py +1 -1
  37. package/runtime/python/okstra_ctl/dispatch_state.py +1 -0
  38. package/runtime/python/okstra_ctl/execution_mutation_audit.py +13 -1
  39. package/runtime/python/okstra_ctl/generated_input.py +21 -0
  40. package/runtime/python/okstra_ctl/ids.py +1 -41
  41. package/runtime/python/okstra_ctl/incremental_carry.py +7 -4
  42. package/runtime/python/okstra_ctl/initial_prompt_materialization.py +30 -0
  43. package/runtime/python/okstra_ctl/interactive_cli.py +5 -0
  44. package/runtime/python/okstra_ctl/locks.py +28 -1
  45. package/runtime/python/okstra_ctl/model_io/renderers.py +7 -0
  46. package/runtime/python/okstra_ctl/paths.py +90 -33
  47. package/runtime/python/okstra_ctl/phases/catalog.py +3 -0
  48. package/runtime/python/okstra_ctl/phases/change_impact_analysis/spec.md +2 -2
  49. package/runtime/python/okstra_ctl/phases/discussion/spec.md +63 -63
  50. package/runtime/python/okstra_ctl/phases/discussion/wizard.py +2 -11
  51. package/runtime/python/okstra_ctl/phases/error_analysis/report_assets/error-analysis-input.template.md +1 -1
  52. package/runtime/python/okstra_ctl/phases/error_analysis/spec.md +2 -2
  53. package/runtime/python/okstra_ctl/phases/feature_analysis/spec.md +1 -1
  54. package/runtime/python/okstra_ctl/phases/final_verification/profile.md +5 -4
  55. package/runtime/python/okstra_ctl/phases/final_verification/report_assets/final-verification-input.template.md +1 -1
  56. package/runtime/python/okstra_ctl/phases/final_verification/report_assets/final-verification.template.html +8 -0
  57. package/runtime/python/okstra_ctl/phases/final_verification/spec.md +5 -4
  58. package/runtime/python/okstra_ctl/phases/final_verification/validation.py +53 -0
  59. package/runtime/python/okstra_ctl/phases/implementation/host-rules.md +6 -2
  60. package/runtime/python/okstra_ctl/phases/implementation/instructions/_implementation-deliverable.md +4 -2
  61. package/runtime/python/okstra_ctl/phases/implementation/instructions/_implementation-executor.md +1 -1
  62. package/runtime/python/okstra_ctl/phases/implementation/instructions/_implementation-verifier.md +23 -7
  63. package/runtime/python/okstra_ctl/phases/implementation/report_assets/implementation-input.template.md +1 -1
  64. package/runtime/python/okstra_ctl/phases/implementation/report_assets/implementation.template.html +1 -1
  65. package/runtime/python/okstra_ctl/phases/implementation/spec.md +6 -4
  66. package/runtime/python/okstra_ctl/phases/implementation/validation.py +152 -30
  67. package/runtime/python/okstra_ctl/phases/implementation_option_selection/spec.md +2 -2
  68. package/runtime/python/okstra_ctl/phases/implementation_planning/authoring.py +16 -22
  69. package/runtime/python/okstra_ctl/phases/implementation_planning/instructions/plan-body-verification.md +12 -12
  70. package/runtime/python/okstra_ctl/phases/implementation_planning/plan_body.py +14 -0
  71. package/runtime/python/okstra_ctl/phases/implementation_planning/profile.md +4 -4
  72. package/runtime/python/okstra_ctl/phases/implementation_planning/report_assets/implementation-planning-input.template.md +1 -1
  73. package/runtime/python/okstra_ctl/phases/implementation_planning/spec.md +1 -1
  74. package/runtime/python/okstra_ctl/phases/implementation_planning/wizard.py +11 -4
  75. package/runtime/python/okstra_ctl/phases/project_analysis/spec.md +2 -2
  76. package/runtime/python/okstra_ctl/phases/release_handoff/entry.py +7 -3
  77. package/runtime/python/okstra_ctl/phases/release_handoff/operations.py +4 -5
  78. package/runtime/python/okstra_ctl/phases/release_handoff/profile.md +1 -1
  79. package/runtime/python/okstra_ctl/phases/release_handoff/report_assets/release-handoff-input.template.md +1 -1
  80. package/runtime/python/okstra_ctl/phases/release_handoff/spec.md +4 -4
  81. package/runtime/python/okstra_ctl/phases/technical_verification/spec.md +1 -1
  82. package/runtime/python/okstra_ctl/plan_items.py +28 -0
  83. package/runtime/python/okstra_ctl/process_group.py +26 -3
  84. package/runtime/python/okstra_ctl/qa_commands.py +5 -1
  85. package/runtime/python/okstra_ctl/recap.py +1 -2
  86. package/runtime/python/okstra_ctl/render.py +25 -2
  87. package/runtime/python/okstra_ctl/report_assembly.py +102 -1
  88. package/runtime/python/okstra_ctl/report_execution_evidence.py +220 -0
  89. package/runtime/python/okstra_ctl/report_finalize.py +3 -3
  90. package/runtime/python/okstra_ctl/report_inputs.py +28 -0
  91. package/runtime/python/okstra_ctl/report_narrative.py +12 -3
  92. package/runtime/python/okstra_ctl/report_synthesis_packet.py +5 -0
  93. package/runtime/python/okstra_ctl/run.py +40 -20
  94. package/runtime/python/okstra_ctl/stage_close.py +52 -6
  95. package/runtime/python/okstra_ctl/stage_command_commits.py +143 -0
  96. package/runtime/python/okstra_ctl/stage_fix_carry.py +21 -1
  97. package/runtime/python/okstra_ctl/stage_integrate.py +90 -25
  98. package/runtime/python/okstra_ctl/verification_capture.py +291 -0
  99. package/runtime/python/okstra_ctl/verification_conformance.py +28 -9
  100. package/runtime/python/okstra_ctl/verification_dispatch.py +136 -0
  101. package/runtime/python/okstra_ctl/verification_evidence.py +671 -0
  102. package/runtime/python/okstra_ctl/verification_generation.py +34 -16
  103. package/runtime/python/okstra_ctl/verification_input_ref.py +9 -0
  104. package/runtime/python/okstra_ctl/verification_input_types.py +2 -0
  105. package/runtime/python/okstra_ctl/verification_inputs.py +83 -2
  106. package/runtime/python/okstra_ctl/verification_invocation.py +140 -0
  107. package/runtime/python/okstra_ctl/verification_target.py +10 -3
  108. package/runtime/python/okstra_ctl/wizard/engine.py +23 -0
  109. package/runtime/python/okstra_ctl/wizard/registry.py +2 -1
  110. package/runtime/python/okstra_ctl/wizard/render.py +2 -1
  111. package/runtime/python/okstra_ctl/wizard/sources.py +14 -3
  112. package/runtime/python/okstra_ctl/wizard/steps_identity.py +2 -1
  113. package/runtime/python/okstra_ctl/wizard/steps_plan.py +6 -2
  114. package/runtime/python/okstra_ctl/worker_runner.py +1 -1
  115. package/runtime/python/okstra_ctl/worktree/git_ops.py +8 -1
  116. package/runtime/python/okstra_ctl/worktree/rebase.py +5 -2
  117. package/runtime/python/okstra_ctl/worktree_lock_cli.py +70 -17
  118. package/runtime/python/okstra_ctl/worktree_registry.py +4 -0
  119. package/runtime/schemas/final-report-v3.0.schema.json +184 -1
  120. package/runtime/skills/okstra-code-review/SKILL.md +7 -5
  121. package/runtime/skills/okstra-code-review/references/census-rules.md +2 -2
  122. package/runtime/skills/okstra-explain-flow/SKILL.md +1 -1
  123. package/runtime/skills/okstra-run/SKILL.md +11 -7
  124. package/runtime/skills/okstra-schedule-gen/SKILL.md +3 -3
  125. package/runtime/skills/okstra-setup/SKILL.md +2 -3
  126. package/runtime/templates/reports/html/i18n/en.json +7 -0
  127. package/runtime/templates/reports/html/i18n/ko.json +7 -0
  128. package/runtime/validators/validate-run.py +130 -20
  129. package/runtime/validators/validate-workflow.sh +1 -1
  130. package/docs/cli.md +0 -1060
  131. package/docs/container.md +0 -100
  132. package/docs/follow-ups/2026-07-10-final-report-option-3.md +0 -51
  133. package/docs/performance-improvement-plan-v2.md +0 -369
  134. package/runtime/python/okstra_ctl/container.py +0 -702
  135. package/runtime/python/okstra_ctl/rollup.py +0 -241
  136. package/runtime/python/okstra_ctl/usage_report.py +0 -362
  137. package/runtime/skills/okstra-container-build/SKILL.md +0 -139
  138. package/runtime/skills/okstra-inspect/SKILL.md +0 -100
  139. package/runtime/skills/okstra-inspect/facets/cost.md +0 -84
  140. package/runtime/skills/okstra-inspect/facets/error-zip.md +0 -41
  141. package/runtime/skills/okstra-inspect/facets/errors.md +0 -69
  142. package/runtime/skills/okstra-inspect/facets/history.md +0 -86
  143. package/runtime/skills/okstra-inspect/facets/logs.md +0 -89
  144. package/runtime/skills/okstra-inspect/facets/recap.md +0 -167
  145. package/runtime/skills/okstra-inspect/facets/report.md +0 -57
  146. package/runtime/skills/okstra-inspect/facets/run-audit.md +0 -34
  147. package/runtime/skills/okstra-inspect/facets/status.md +0 -163
  148. package/runtime/skills/okstra-inspect/facets/time.md +0 -57
  149. package/runtime/skills/okstra-rollup/SKILL.md +0 -75
  150. package/runtime/skills/okstra-usage/SKILL.md +0 -71
@@ -1,702 +0,0 @@
1
- """container compose 의 env 합성 + up argv 순수 함수.
2
-
3
- 이 task 는 docker 실행 없는 순수 함수만 담는다(서비스 목록/라벨은 인자로 받아
4
- generator 가 순수하게 유지된다). 실제 compose 파일 파싱·override 파일 쓰기·docker
5
- 실행은 후속 task/e2e 로 미룬다.
6
-
7
- env 우선순위(spec §6): compose 가 `--env-file <worktree .env>` 다음에
8
- `--env-file <override>` 를 읽어 중복 키는 override 가 이긴다.
9
-
10
- 라벨 SSOT(spec §7): 모든 컨테이너는 `okstra.task-key`/`okstra.project-name`/
11
- `okstra.run-trace` 라벨을 달아야 후속 status/down 이 라벨 질의로 그룹을 찾는다.
12
- `docker compose up` 에는 `--label` 플래그가 없으므로(compose v5 `up --help` +
13
- docker compose 문서로 확인), 라벨은 `-f <override.yml>` override 파일이 각 서비스
14
- 밑에 `labels:` 를 합쳐 주입한다.
15
- """
16
- from __future__ import annotations
17
-
18
- import argparse
19
- import json
20
- import re
21
- import subprocess
22
- import sys
23
- import time
24
- from pathlib import Path
25
- from typing import Callable, Iterable
26
-
27
- from .stage_targets import PrepareError # 단일 PrepareError 타입 재노출(run.py 와 공유)
28
- from .stage_map import StageMapError, parse_stage_map_file, stage_map_records
29
- from .json_boundary import JsonBoundaryError, load_owned_object, write_owned_object_atomic
30
- from .fixed_text import line
31
-
32
- OKSTRA_LABEL_KEYS = ("okstra.task-key", "okstra.project-name", "okstra.run-trace")
33
-
34
- COMPOSE_FILENAME = "docker-compose.yml"
35
-
36
- def merge_env(base_env: dict, override: dict) -> dict:
37
- """base_env 위에 override 를 얹는다. 동일 키는 override 가 이긴다."""
38
- return {**base_env, **override}
39
-
40
-
41
- def build_label_override_yaml(services: list[str], labels: dict) -> str:
42
- """각 서비스 밑에 `labels:` 를 주입하는 compose override yaml 본문을 낸다.
43
-
44
- docker compose 가 `-f` 로 합칠 때 이 본문이 컨테이너 라벨을 단다. 디스크 쓰기는
45
- 호출자(후속 task) 몫이며 이 함수는 문자열만 반환한다.
46
- """
47
- lines = ["services:"]
48
- for service in services:
49
- lines.append(f" {service}:")
50
- lines.append(" labels:")
51
- for key, value in labels.items():
52
- lines.append(f" {key}: {_yaml_quote(value)}")
53
- return "\n".join(lines) + "\n"
54
-
55
-
56
- def _yaml_quote(value: str) -> str:
57
- """라벨 값을 YAML double-quoted scalar 로 감싼다.
58
-
59
- task-key 는 raw 보존(slugify 안 함)이라 ` #`(주석), `{`/`[`(flow), `&`/`*`
60
- (anchor/alias), `:` 같은 indicator 문자가 들어올 수 있다. 무인용으로 쓰면
61
- override 파일이 깨져 `up` 이 중단되거나 라벨이 silently 잘린다 — double-quote
62
- 안에서 `\\`·`"` 만 이스케이프하면 모든 indicator 가 평문으로 안전해진다."""
63
- escaped = str(value).replace("\\", "\\\\").replace('"', '\\"')
64
- return f'"{escaped}"'
65
-
66
-
67
- def build_compose_up_argv(
68
- *,
69
- project_name: str,
70
- compose_path: str,
71
- worktree_env_path: str,
72
- override_env_path: str,
73
- label_override_path: str,
74
- ) -> list[str]:
75
- """`docker compose up -d` argv 를 낸다.
76
-
77
- - `-f` 는 base compose → label override 순서다. `-f` 가 하나라도 명시되면
78
- docker compose 는 cwd 의 docker-compose.yml 자동탐색을 끄므로, 베이스 파일을
79
- 반드시 첫 `-f` 로 직접 넘겨야 한다(누락 시 라벨 override 만 머지돼 'no image'
80
- 로 실패). label override 가 뒤에 와서 base 위에 `labels:` 만 덧입힌다.
81
- - `--env-file` 은 worktree → override 순서라 override 가 나중(우선)에 온다.
82
- worktree `.env` 가 없으면 그 플래그를 통째로 뺀다 — docker compose v2 는
83
- 존재하지 않는 명시적 `--env-file` 을 hard error 로 처리하므로(implicit `.env`
84
- 와 달리) 빈 경로를 넣으면 `.env` 없는 평범한 프로젝트가 전부 up 실패한다.
85
- - 라벨은 `-f <label_override_path>` 로 배선한다(`up --label` 미지원).
86
- """
87
- argv = [
88
- "docker", "compose",
89
- "-p", project_name,
90
- "-f", compose_path,
91
- "-f", label_override_path,
92
- ]
93
- if worktree_env_path:
94
- argv += ["--env-file", worktree_env_path]
95
- argv += ["--env-file", override_env_path, "up", "-d"]
96
- return argv
97
-
98
-
99
- # --------------------------------------------------------------------------- #
100
- # compose 파싱 — docker 가 정본(canonical). 손수 정규식 파서는 라벨 SSOT 를
101
- # silent 하게 깨므로 쓰지 않는다(inline comment / quoted name / 4-space 들여쓰기
102
- # 오파싱 → 라벨 미부착 → status/down 라벨 쿼리가 빈 결과 → 컨테이너 leak).
103
- # `docker compose config` 는 parse 일 뿐(run 아님)이라 up 전에 호출 가능하다.
104
- # --------------------------------------------------------------------------- #
105
-
106
- _SERVICES_BLOCK_RE = re.compile(r"^services:\s*$", re.M)
107
-
108
-
109
- def compose_has_services_block(compose_text: str) -> bool:
110
- """top-level `services:` 아래에 들여쓰기된 내용이 한 줄이라도 있으면 True.
111
-
112
- docker 파싱 결과가 0개일 때 '빈 compose(정상 0개)' 인지 '오파싱(loud abort)'
113
- 인지 가르는 ground-truth 다. YAML 의미 파싱이 아니라 블록 존재만 본다."""
114
- lines = compose_text.splitlines()
115
- for i, line in enumerate(lines):
116
- if not _SERVICES_BLOCK_RE.match(line):
117
- continue
118
- for nxt in lines[i + 1:]:
119
- if not nxt.strip() or nxt.lstrip().startswith("#"):
120
- continue
121
- return nxt.startswith((" ", "\t")) # 들여쓰기된 첫 콘텐츠 줄
122
- return False
123
-
124
-
125
- def _compose_config_argv(
126
- compose_path: Path, env_files: Iterable[str], tail: list[str],
127
- ) -> list[str]:
128
- """`docker compose [--env-file ...] -f <compose> config <tail>` argv.
129
-
130
- `--env-file` 과 cwd 는 up 과 반드시 동일해야 한다 — config 가 변수
131
- interpolation 을 다른 env 로 해소하면 bind-mount escape 탐지/서비스 파싱이
132
- 실제 배포와 다른 값으로 계산된다."""
133
- argv = ["docker", "compose"]
134
- for env_file in env_files:
135
- argv += ["--env-file", env_file]
136
- argv += ["-f", str(compose_path), "config", *tail]
137
- return argv
138
-
139
-
140
- def resolve_compose_services(
141
- compose_path: Path, env_files: Iterable[str] = (), cwd: str | None = None,
142
- ) -> list[str]:
143
- """`docker compose -f <compose> config --services` 로 서비스 목록을 얻는다.
144
-
145
- docker 가 정본 파서다. services 블록이 비어있지 않은데 0개가 나오면(docker
146
- 부재/파싱 실패 포함) 라벨 없는 컨테이너를 띄우느니 PrepareError 로 loud 하게
147
- 중단한다 — 라벨 SSOT 를 silent 하게 깨지 않는다. `--env-file`/cwd 는 up 과
148
- 동일하게 넘겨 interpolation 결과를 일치시킨다."""
149
- out = _docker_run(
150
- _compose_config_argv(compose_path, env_files, ["--services"]), cwd=cwd)
151
- services = [s.strip() for s in out.splitlines() if s.strip()]
152
- if not services and compose_has_services_block(
153
- compose_path.read_text(encoding="utf-8")):
154
- raise PrepareError(
155
- f"container up: {compose_path.name} 에 services 가 정의돼 있으나 "
156
- "`docker compose config --services` 가 빈 목록을 반환했습니다 "
157
- "(docker 부재 또는 compose 파싱 실패). 라벨 미부착 컨테이너 leak 을 "
158
- "막기 위해 중단합니다 — docker 가용성과 compose 문법을 확인하세요.")
159
- return services
160
-
161
-
162
- def scan_escaping_host_paths(
163
- compose_path: Path, worktree_root: Path,
164
- env_files: Iterable[str] = (), cwd: str | None = None,
165
- ) -> list[str]:
166
- """worktree 밖(절대경로 or `../`)을 가리키는 bind mount host 경로를 모은다.
167
-
168
- spec §6: worktree 를 벗어나는 마운트는 경고 후 진행(중단 아님). docker 가
169
- 정규화한 config(`--format json`)의 volumes 를 보므로 short/long-form 모두
170
- 커버한다. docker 실패 시 빈 목록(경고만 누락, 진행에는 영향 없음). `--env-file`/
171
- cwd 는 up 과 동일하게 넘겨 `${VAR}` 마운트 경로가 실제 배포와 일치하게 한다."""
172
- out = _docker_run(
173
- _compose_config_argv(compose_path, env_files, ["--format", "json"]), cwd=cwd)
174
- try:
175
- config = json.loads(out) if out.strip() else {}
176
- except json.JSONDecodeError:
177
- return []
178
- escaping: list[str] = []
179
- for svc in (config.get("services") or {}).values():
180
- for vol in (svc.get("volumes") or []):
181
- source = vol.get("source") if isinstance(vol, dict) else None
182
- if isinstance(source, str) and _is_escaping_host_path(source):
183
- escaping.append(source)
184
- return escaping
185
-
186
-
187
- def _is_escaping_host_path(source: str) -> bool:
188
- """named volume(슬래시 없음)은 제외, 절대경로/`../` host 경로만 escape."""
189
- if source.startswith("/") or source.startswith("..") or "/../" in source:
190
- return True
191
- return False
192
-
193
-
194
- # --------------------------------------------------------------------------- #
195
- # docker 얇은 래퍼(daemon 필요 — 게이트 로직과 분리해 유닛 테스트 가능하게)
196
- # --------------------------------------------------------------------------- #
197
-
198
- def _compose_ps(project_name: str, cwd: str, include_stopped: bool = False) -> list[dict]:
199
- argv = ["docker", "compose", "-p", project_name, "ps"]
200
- if include_stopped:
201
- argv.append("-a")
202
- argv += ["--format", "json"]
203
- result = subprocess.run(argv, capture_output=True, text=True, check=False, cwd=cwd)
204
- rows: list[dict] = []
205
- for line in (result.stdout or "").splitlines():
206
- line = line.strip()
207
- if not line:
208
- continue
209
- try:
210
- rows.append(json.loads(line))
211
- except json.JSONDecodeError:
212
- continue
213
- return rows
214
-
215
-
216
- def _docker_run(argv: list[str], cwd: str | None = None, *, check: bool = False) -> str:
217
- """docker 명령을 돌려 stdout 을 돌려준다.
218
-
219
- `check=True` 면 0 이 아닌 종료를 PrepareError 로 올린다. status 가 빈 목록을,
220
- down 이 성공을 보고하는데 실제로는 docker 가 실패한 경우를 막는다. config 계열
221
- 조회는 실패해도 진행하도록 설계돼 있어 기본값은 그대로 둔다."""
222
- result = subprocess.run(argv, capture_output=True, text=True, check=False, cwd=cwd)
223
- if check and result.returncode != 0:
224
- detail = (result.stderr or result.stdout or "").strip().splitlines()
225
- raise PrepareError(
226
- f"`{' '.join(argv[:4])}` 가 exit {result.returncode} 로 실패했습니다: "
227
- f"{detail[-1] if detail else '출력 없음'}")
228
- return result.stdout or ""
229
-
230
-
231
- def query_containers_by_label(project_name: str) -> list[dict]:
232
- """라벨 SSOT(spec §11): `okstra.project-name` 으로 컨테이너를 질의한다.
233
-
234
- registry 가 아니라 docker 라벨이 컨테이너 존재의 기준값이다."""
235
- out = _docker_run(check=True, argv=[
236
- "docker", "ps", "-a", "--filter",
237
- f"label=okstra.project-name={project_name}",
238
- "--format", (
239
- "{{.ID}}\t{{.Names}}\t{{.State}}\t"
240
- '{{.Label "com.docker.compose.service"}}\t{{.Ports}}'
241
- ),
242
- ])
243
- rows: list[dict] = []
244
- for line in out.splitlines():
245
- parts = line.split("\t")
246
- if len(parts) >= 5:
247
- rows.append({
248
- "id": parts[0], "name": parts[1], "state": parts[2],
249
- "service": parts[3], "ports": parts[4],
250
- })
251
- return rows
252
-
253
-
254
- def _service_state(row: dict) -> str:
255
- return (row.get("State") or row.get("state") or "").lower()
256
-
257
-
258
- def _service_health(row: dict) -> str:
259
- return (row.get("Health") or row.get("health") or "").lower()
260
-
261
-
262
- def poll_healthcheck(
263
- *, project_name: str, cwd: str, services: list[str],
264
- healthcheck_timeout_seconds: int, healthcheck_interval_seconds: int,
265
- sleep: Callable[[float], None] = time.sleep,
266
- ) -> list[str]:
267
- """healthy(또는 healthcheck 미정의 시 running)까지 폴링. 미기동 서비스명 반환.
268
-
269
- healthcheck 가 정의된 서비스는 Health=healthy 를, 없는 서비스는 State=running
270
- 을 성공 조건으로 본다(spec §4 step6). `deploy.replicas`>1 이면 `ps` 가 한
271
- 서비스에 여러 컨테이너 행을 내므로, 서비스명별로 묶어 **모든** 레플리카가
272
- ready 일 때만 통과시킨다(한 행으로 collapse 하면 건강한 레플리카가 비정상
273
- 형제를 가린다). 빈 리스트면 전부 기동.
274
-
275
- `-a`(include_stopped)로 폴링해 크래시-종료한 컨테이너 행까지 본다 —
276
- `_started_services` 와 같은 가시성. 안 그러면 멀티-레플리카에서 죽은 레플리카가
277
- running-only ps 에 행이 없어, 살아있는 형제만으로 `all(ready)` 가 통과해 죽은
278
- 배포를 healthy 로 오인한다(exited 행은 _container_ready 가 False 를 돌려준다)."""
279
- deadline = time.monotonic() + healthcheck_timeout_seconds
280
- pending = set(services)
281
- while pending and time.monotonic() < deadline:
282
- by_service = _group_ps_rows_by_service(
283
- _compose_ps(project_name, cwd, include_stopped=True))
284
- for svc in list(pending):
285
- rows = by_service.get(svc)
286
- if rows and all(_container_ready(r) for r in rows):
287
- pending.discard(svc)
288
- if pending:
289
- sleep(healthcheck_interval_seconds)
290
- return sorted(pending)
291
-
292
-
293
- def _group_ps_rows_by_service(rows: list[dict]) -> dict[str, list[dict]]:
294
- out: dict[str, list[dict]] = {}
295
- for row in rows:
296
- key = row.get("Service") or row.get("Name")
297
- if key:
298
- out.setdefault(key, []).append(row)
299
- return out
300
-
301
-
302
- def _container_ready(row: dict) -> bool:
303
- health = _service_health(row)
304
- if health:
305
- return health == "healthy"
306
- return _service_state(row) == "running"
307
-
308
-
309
- # --------------------------------------------------------------------------- #
310
- # up 흐름 (provision_container_group) — 단계별 헬퍼로 분해
311
- # --------------------------------------------------------------------------- #
312
-
313
- def _split_task_key(task_key: str) -> tuple[str, str, str]:
314
- parts = task_key.split(":")
315
- if len(parts) != 3 or not all(parts):
316
- raise PrepareError(
317
- f"container: task-key 형식은 '<project-id>:<task-group>:<task-id>' 이어야 "
318
- f"합니다(받음: {task_key!r})")
319
- return parts[0], parts[1], parts[2]
320
-
321
-
322
- def _resolve_up_inputs(project_root: Path, task_key: str) -> dict:
323
- """task-key 로 up 에 필요한 입력(worktree/stage_map/done_rows/anchor)을 모은다."""
324
- from . import worktree_registry as _reg
325
- from .consumers import read_stage_consumer_state
326
- from .plan_run_root import resolve_plan_run_root_by_task_key
327
-
328
- project_id, group, task_id = _split_task_key(task_key)
329
- entry = _reg.lookup(project_id, group, task_id)
330
- if entry is None or not entry.worktree_path:
331
- raise PrepareError(
332
- f"container up: task-key {task_key} 의 task worktree 가 registry 에 "
333
- "없습니다. 먼저 해당 task 의 phase 를 한 번 실행해 worktree 를 만드세요.")
334
- plan = resolve_plan_run_root_by_task_key(
335
- project_root=project_root, task_group=group, task_id=task_id)
336
- done_rows = read_stage_consumer_state(
337
- plan.run_root, recover_from_carry=True,
338
- ).done_rows
339
- stage_map = _plan_stage_map(plan.approved_plan_path)
340
- anchor = _reg.get_implementation_base(project_id, group, task_id) or ""
341
- return {
342
- "project_id": project_id, "task_group": group, "task_id": task_id,
343
- "worktree_path": entry.worktree_path, "stage_map": stage_map,
344
- "done_rows": done_rows, "anchor_base": anchor,
345
- }
346
-
347
-
348
- def _plan_stage_map(approved_plan_path: str) -> list[dict]:
349
- """Parse the approved plan's complete Stage Map for container gating."""
350
- try:
351
- return stage_map_records(parse_stage_map_file(Path(approved_plan_path)))
352
- except StageMapError as exc:
353
- raise PrepareError(
354
- "approved-plan 의 Stage Map 을 신뢰할 수 없어 거부합니다 "
355
- f"({approved_plan_path}): {exc.reason}. plan 의 Stage Map 을 점검하세요."
356
- ) from exc
357
-
358
-
359
- def _verify_compose_present(worktree_root: Path) -> Path:
360
- compose = worktree_root / COMPOSE_FILENAME
361
- if not compose.is_file():
362
- raise PrepareError(
363
- f"container up: worktree 루트에 {COMPOSE_FILENAME} 가 없습니다 "
364
- f"({compose}). okstra 는 compose 파일을 생성하지 않습니다 — "
365
- "프로젝트에 직접 추가한 뒤 다시 시도하세요.")
366
- return compose
367
-
368
-
369
- def _synthesize_env_override(worktree_root: Path, cp: dict) -> tuple[str, str]:
370
- """worktree `.env`(okstra-owned 입력) → env.override 합성. (worktree_env, override) 반환.
371
-
372
- spec §6 artifact-home: 입력 `.env` 는 raw project root 가 아니라 worktree
373
- 트리에서 해소한다. override 는 container_dir 밑에 쓴다."""
374
- worktree_env = worktree_root / ".env"
375
- base = _read_env_file(worktree_env)
376
- override = merge_env(base, {})
377
- cp["container_dir"].mkdir(parents=True, exist_ok=True)
378
- cp["env_override"].write_text(
379
- "".join(f"{k}={v}\n" for k, v in override.items()), encoding="utf-8")
380
- # 파일이 없으면 빈 경로를 반환해 up argv 가 `--env-file <missing>` 을 넣지
381
- # 않게 한다(존재하는 override 는 항상 위에서 써 두므로 그 쪽은 안전).
382
- worktree_env_arg = str(worktree_env) if worktree_env.is_file() else ""
383
- return worktree_env_arg, str(cp["env_override"])
384
-
385
-
386
- def _read_env_file(path: Path) -> dict:
387
- out: dict[str, str] = {}
388
- if not path.is_file():
389
- return out
390
- for line in path.read_text(encoding="utf-8").splitlines():
391
- line = line.strip()
392
- if not line or line.startswith("#") or "=" not in line:
393
- continue
394
- k, v = line.split("=", 1)
395
- out[k.strip()] = v.strip()
396
- return out
397
-
398
-
399
- def _write_label_override(cp: dict, services: list[str], labels: dict) -> str:
400
- cp["container_dir"].mkdir(parents=True, exist_ok=True)
401
- path = cp["container_dir"] / "labels.override.yml"
402
- path.write_text(build_label_override_yaml(services, labels), encoding="utf-8")
403
- return str(path)
404
-
405
-
406
- def provision_container_group(
407
- *, project_root, task_key: str,
408
- healthcheck_timeout_seconds: int = 120,
409
- healthcheck_interval_seconds: int = 3,
410
- ) -> dict:
411
- """skill / bin okstra / okstra.sh 가 수렴하는 container up 단일 진입점."""
412
- from . import paths
413
- from .ids import compose_project_name, build_container_run_trace
414
-
415
- project_root = Path(project_root)
416
- inputs = _resolve_up_inputs(project_root, task_key)
417
- worktree = Path(_integrate_source_tree(inputs))
418
- compose = _verify_compose_present(worktree)
419
- cp = paths.container_paths(project_root, inputs["task_group"], inputs["task_id"])
420
- project_name = compose_project_name(
421
- inputs["project_id"], inputs["task_group"], inputs["task_id"])
422
- run_trace = build_container_run_trace(
423
- inputs["project_id"], inputs["task_group"], inputs["task_id"])
424
- worktree_env, override_env = _synthesize_env_override(worktree, cp)
425
- env_files = [p for p in (worktree_env, override_env) if p]
426
- warnings = scan_escaping_host_paths(compose, worktree, env_files, str(worktree))
427
- services = resolve_compose_services(compose, env_files, str(worktree))
428
- started = _compose_up(
429
- cp=cp, worktree=worktree, compose=compose, project_name=project_name,
430
- task_key=task_key, run_trace=run_trace, services=services,
431
- worktree_env=worktree_env, override_env=override_env)
432
- if not started:
433
- # ps 가 빈 출력(데몬 일시 오류)이거나 모든 서비스가 미생성이면 started 가
434
- # 비는데, 빈 리스트는 poll_healthcheck 를 vacuous 통과시켜 검증 없이 성공으로
435
- # 보고된다. fail-open 대신 raise 하되, `up -d` 후 컨테이너가 떠 있을 수도
436
- # 있으므로(transient ps 실패) deploy-state 를 먼저 써 `down --all` 이 회수
437
- # 가능하게 한다 — 실제 기동분을 모르니 full services 를 best-effort 로 기록.
438
- _write_deploy_state(
439
- cp, project_name=project_name, task_key=task_key, services=services,
440
- warnings=warnings)
441
- raise PrepareError(
442
- f"container up: `up -d` 후 기동된 컨테이너가 없습니다(`docker compose -p "
443
- f"{project_name} ps -a` 로 확인). compose 정의·활성 profile 을 점검한 뒤 "
444
- f"`{_down_hint(project_root, task_key)}` 로 정리하고 다시 시도하세요.")
445
- failed = poll_healthcheck(
446
- project_name=project_name, cwd=str(worktree), services=started,
447
- healthcheck_timeout_seconds=healthcheck_timeout_seconds,
448
- healthcheck_interval_seconds=healthcheck_interval_seconds)
449
- if failed:
450
- # 컨테이너는 이미 떠 있다(unhealthy/느림) — deploy-state 를 먼저 써 둬야
451
- # `down --all` 스윕(deploy-state.json 있는 task 만 발견)이 회수할 수 있다.
452
- _write_deploy_state(
453
- cp, project_name=project_name, task_key=task_key, services=started,
454
- warnings=warnings, healthcheckFailed=failed)
455
- raise PrepareError(
456
- f"container up: 다음 서비스가 시간 내 기동하지 못했습니다: {', '.join(failed)} "
457
- f"(timeout={healthcheck_timeout_seconds}s). `docker compose -p "
458
- f"{project_name} logs` 로 원인을 확인한 뒤 "
459
- f"`{_down_hint(project_root, task_key)}` 로 정리하세요.")
460
- # deploy-state 는 실제 기동된 started 만 기록한다 — full services 를 쓰면
461
- # profiles 로 안 뜬 서비스가 `down --all` 스윕의 대상으로 남는다.
462
- _write_deploy_state(cp, project_name=project_name, task_key=task_key,
463
- services=started, warnings=warnings)
464
- return {"projectName": project_name, "services": started,
465
- "warnings": warnings}
466
-
467
-
468
- def _integrate_source_tree(inputs: dict) -> str:
469
- """stage 통합(teardown=False)으로 소스트리를 확정하고 worktree 경로를 반환."""
470
- from .stage_targets import resolve_and_integrate_whole_task
471
-
472
- resolve_and_integrate_whole_task(
473
- teardown=False, project_id=inputs["project_id"],
474
- task_group=inputs["task_group"], task_id=inputs["task_id"],
475
- task_worktree_path=inputs["worktree_path"], stage_map=inputs["stage_map"],
476
- done_rows=inputs["done_rows"], anchor_base=inputs["anchor_base"])
477
- return inputs["worktree_path"]
478
-
479
-
480
- def _compose_up(
481
- *, cp: dict, worktree: Path, compose: Path, project_name: str, task_key: str,
482
- run_trace: str, services: list[str], worktree_env: str, override_env: str,
483
- ) -> list[str]:
484
- """label override 주입 → compose up → 실제 기동된 서비스명 반환.
485
-
486
- 반환은 `up -d` 가 실제로 생성한 서비스만(=ps 행 존재) 추린 목록이다 — compose
487
- `profiles:` 로 비활성화돼 기동되지 않은 서비스를 healthcheck 대기 대상에서
488
- 빼, 영영 pending 으로 남아 오탐 timeout 을 내지 않게 한다."""
489
- labels = {
490
- "okstra.task-key": task_key,
491
- "okstra.project-name": project_name,
492
- # run-trace 는 이 기능의 trace 식별자로 채워 project-name 과
493
- # distinct 하게 둔다(M1).
494
- "okstra.run-trace": run_trace,
495
- }
496
- label_path = _write_label_override(cp, services, labels)
497
- argv = build_compose_up_argv(
498
- project_name=project_name, compose_path=str(compose),
499
- worktree_env_path=worktree_env, override_env_path=override_env,
500
- label_override_path=label_path)
501
- result = subprocess.run(argv, cwd=str(worktree), check=False)
502
- if result.returncode != 0:
503
- raise PrepareError(
504
- f"container up: `docker compose up` 가 실패했습니다(exit "
505
- f"{result.returncode}). `docker compose -p {project_name} logs` 로 "
506
- "원인을 확인하세요.")
507
- return _started_services(project_name, str(worktree), services)
508
-
509
-
510
- def _started_services(project_name: str, cwd: str, services: list[str]) -> list[str]:
511
- """`up -d` 로 실제 생성된(running 또는 exited) 서비스만 입력 순서대로 추린다.
512
-
513
- `-a` 로 종료된 컨테이너까지 본다 — 부팅 직후 크래시-종료한 서비스를 profiles
514
- 로 아예 안 뜬 서비스와 구분하려는 것. 전자는 ps 행이 남아 healthcheck 대기
515
- 대상에 포함되고 running 이 아니라 timeout 으로 실패한다(죽은 배포를 성공으로
516
- 오인 차단). 후자는 `-a` 에도 행이 없어 제외된다."""
517
- created = set(_group_ps_rows_by_service(
518
- _compose_ps(project_name, cwd, include_stopped=True)))
519
- return [s for s in services if s in created]
520
-
521
-
522
- def _write_deploy_state(cp: dict, **state) -> None:
523
- cp["container_dir"].mkdir(parents=True, exist_ok=True)
524
- write_owned_object_atomic(cp["deploy_state"], state, artifact="container deploy state")
525
-
526
-
527
- # --------------------------------------------------------------------------- #
528
- # status / down
529
- # --------------------------------------------------------------------------- #
530
-
531
- def status_container_group(*, project_root, task_key: str) -> dict:
532
- """라벨 쿼리 — 컨테이너 존재 여부의 기준값(SSOT)."""
533
- from .ids import compose_project_name
534
-
535
- project_id, group, task_id = _split_task_key(task_key)
536
- project_name = compose_project_name(project_id, group, task_id)
537
- return {"projectName": project_name,
538
- "containers": query_containers_by_label(project_name)}
539
-
540
-
541
- def _down_hint(project_root, task_key: str) -> str:
542
- """실패 메시지가 안내하는 정리 명령. 파서가 요구하는 인자를 모두 싣는다."""
543
- return f"okstra container down --project-root {project_root} --task-key {task_key}"
544
-
545
-
546
- def down_container_group(*, project_root, task_key: str = "", all_groups: bool = False) -> dict:
547
- """compose 프로젝트 이름으로 task 의 컨테이너 그룹을 down 한다."""
548
- from .ids import compose_project_name
549
-
550
- project_root = Path(project_root)
551
- results = []
552
- failures: list[str] = []
553
- for project_id, group, task_id in _down_targets(project_root, task_key, all_groups):
554
- project_name = compose_project_name(project_id, group, task_id)
555
- # `docker rm -f` 는 컨테이너만 지우고 compose 가 만든 네트워크를 누수시킨다.
556
- # compose 정본 teardown 으로 프로젝트(라벨 com.docker.compose.project=<name>)
557
- # 단위 컨테이너+네트워크를 회수한다. `-v` 는 의도적으로 빼서 compose 에
558
- # 선언된 named volume(예: DB 데이터)을 보존한다 — down 한 번에 사용자
559
- # 영속 데이터를 파괴하지 않는다.
560
- try:
561
- _docker_run(["docker", "compose", "-p", project_name, "down",
562
- "--remove-orphans"], check=True)
563
- except PrepareError as exc:
564
- failures.append(f"{project_name}: {exc}")
565
- continue
566
- results.append({"projectName": project_name})
567
- if failures:
568
- # 나머지 대상은 끝까지 내리고, 실패한 것만 모아 알린다.
569
- raise PrepareError("container down 실패 — " + "; ".join(failures))
570
- return {"downed": results}
571
-
572
-
573
- def _down_targets(project_root, task_key: str, all_groups: bool) -> list[tuple[str, str, str]]:
574
- if all_groups:
575
- return _discover_container_task_keys(Path(project_root))
576
- if not task_key:
577
- raise PrepareError("container down: task-key 또는 --all 중 하나가 필요합니다.")
578
- return [_split_task_key(task_key)]
579
-
580
-
581
- def _discover_container_task_keys(project_root: Path) -> list[tuple[str, str, str]]:
582
- """프로젝트 안에서 container deploy-state 가 있는 task-key 들을 찾는다."""
583
- from okstra_project.dirs import project_json_path, tasks_root as _tasks_root
584
-
585
- project_id = _read_project_id(project_json_path(project_root))
586
- tasks_root = _tasks_root(project_root)
587
- out: list[tuple[str, str, str]] = []
588
- if not tasks_root.is_dir():
589
- return out
590
- for group_dir in tasks_root.iterdir():
591
- for task_dir in (group_dir.iterdir() if group_dir.is_dir() else []):
592
- if (task_dir / "container" / "deploy-state.json").is_file():
593
- out.append((project_id, group_dir.name, task_dir.name))
594
- return out
595
-
596
-
597
- def _read_project_id(project_json: Path) -> str:
598
- if not project_json.is_file():
599
- return ""
600
- try:
601
- return load_owned_object(project_json, artifact="project configuration").get(
602
- "projectId", ""
603
- )
604
- except JsonBoundaryError:
605
- return ""
606
-
607
-
608
- # --------------------------------------------------------------------------- #
609
- # argparse 디스패치(recap.py 패턴)
610
- # --------------------------------------------------------------------------- #
611
-
612
- _CLI_EPILOG = r"""Usage:
613
- okstra container up [options]
614
- okstra container status [options]
615
- okstra container down [options]
616
- """
617
- _CLI_DESCRIPTION = "Manage the okstra container runtime."
618
-
619
-
620
- def main(argv: list[str] | None = None) -> int:
621
- parser = argparse.ArgumentParser(
622
- description=_CLI_DESCRIPTION,
623
- epilog=_CLI_EPILOG,
624
- formatter_class=argparse.RawDescriptionHelpFormatter,
625
- prog="okstra container")
626
- sub = parser.add_subparsers(dest="command", required=True)
627
- for name in ("up", "status", "down"):
628
- sp = sub.add_parser(name)
629
- sp.add_argument("--project-root", required=True)
630
- sp.add_argument("--task-key", default="")
631
- sp.add_argument("--text", action="store_true")
632
- if name == "down":
633
- sp.add_argument("--all", action="store_true")
634
- args = parser.parse_args(argv)
635
- result = _dispatch(args)
636
- print(
637
- render_container_text(args.command, result)
638
- if args.text
639
- else json.dumps(result, ensure_ascii=False, indent=2)
640
- )
641
- return 0
642
-
643
-
644
- def render_container_text(command: str, payload: dict) -> str:
645
- """container 명령별 승인된 상태만 고정 순서로 투영한다."""
646
- if command not in {"up", "status", "down"}:
647
- raise ValueError("unknown container text purpose")
648
- rows = [f"Okstra container {command}\n", line("Status", "ready")]
649
- for label, key in (("Project name", "projectName"), ("Note", "note")):
650
- if key in payload:
651
- rows.append(line(label, payload.get(key)))
652
- if command == "up":
653
- rows.extend(_render_container_up(payload))
654
- elif command == "status":
655
- rows.extend(_render_container_status(payload))
656
- else:
657
- rows.extend(_render_container_down(payload))
658
- return "".join(rows)
659
-
660
-
661
- def _render_container_up(payload: dict) -> list[str]:
662
- rows: list[str] = []
663
- for index, service in enumerate(payload.get("services") or [], 1):
664
- rows.append(line(f"Service {index} name", service))
665
- for index, warning in enumerate(payload.get("warnings") or [], 1):
666
- rows.append(line(f"Warning {index} text", warning))
667
- return rows
668
-
669
-
670
- def _render_container_status(payload: dict) -> list[str]:
671
- containers = payload.get("containers") if isinstance(payload.get("containers"), list) else []
672
- rows: list[str] = []
673
- for index, item in enumerate(containers, 1):
674
- values = item if isinstance(item, dict) else {}
675
- for label, key in (("name", "name"), ("service", "service"), ("state", "state"),
676
- ("status", "status"), ("ports", "ports")):
677
- if key in values:
678
- rows.append(line(f"Container {index} {label}", values.get(key)))
679
- return rows
680
-
681
-
682
- def _render_container_down(payload: dict) -> list[str]:
683
- downed = payload.get("downed") if isinstance(payload.get("downed"), list) else []
684
- rows: list[str] = []
685
- for index, item in enumerate(downed, 1):
686
- values = item if isinstance(item, dict) else {}
687
- rows.append(line(f"Downed {index} project name", values.get("projectName")))
688
- return rows
689
-
690
-
691
- def _dispatch(args) -> dict:
692
- pr = args.project_root
693
- if args.command == "up":
694
- return provision_container_group(project_root=pr, task_key=args.task_key)
695
- if args.command == "status":
696
- return status_container_group(project_root=pr, task_key=args.task_key)
697
- return down_container_group(
698
- project_root=pr, task_key=args.task_key, all_groups=args.all)
699
-
700
-
701
- if __name__ == "__main__":
702
- raise SystemExit(main(sys.argv[1:]))