From 20b5f1f241cec112ef82bf5530d1719acef1add8 Mon Sep 17 00:00:00 2001 From: toki Date: Sat, 6 Jun 2026 17:02:31 +0900 Subject: [PATCH] =?UTF-8?q?refactor(control-plane):=20API=20=EA=B2=BD?= =?UTF-8?q?=EA=B3=84=EB=A5=BC=20=EB=B6=84=EB=A6=AC=ED=95=9C=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Control Plane HTTP API가 fleet polling과 client 상태 확장 전에 더 커지지 않도록 server lifecycle, DTO conversion, Edge/fleet handler 책임을 파일 단위로 나눈다. --- .../architecture-refactor-foundation.md | 7 +- .../code_review_cloud_G07_0.log | 174 +++++ .../06_cp_api_split/complete.log | 45 ++ .../06_cp_api_split/plan_local_G07_0.log | 264 ++++++++ .../CODE_REVIEW-cloud-G08.md | 160 +++++ .../07+06_fleet_polling/PLAN-local-G08.md | 263 ++++++++ .../CODE_REVIEW-cloud-G08.md | 170 +++++ .../08_client_state_split/PLAN-local-G08.md | 316 +++++++++ .../cmd/control-plane/http_edge_handlers.go | 149 +++++ .../cmd/control-plane/http_fleet_handlers.go | 60 ++ .../cmd/control-plane/http_views.go | 345 ++++++++++ apps/control-plane/cmd/control-plane/main.go | 599 ------------------ .../cmd/control-plane/main_test.go | 49 ++ .../control-plane/cmd/control-plane/server.go | 97 +++ 14 files changed, 2096 insertions(+), 602 deletions(-) create mode 100644 agent-task/archive/2026/06/m-architecture-refactor-foundation/06_cp_api_split/code_review_cloud_G07_0.log create mode 100644 agent-task/archive/2026/06/m-architecture-refactor-foundation/06_cp_api_split/complete.log create mode 100644 agent-task/archive/2026/06/m-architecture-refactor-foundation/06_cp_api_split/plan_local_G07_0.log create mode 100644 agent-task/m-architecture-refactor-foundation/07+06_fleet_polling/CODE_REVIEW-cloud-G08.md create mode 100644 agent-task/m-architecture-refactor-foundation/07+06_fleet_polling/PLAN-local-G08.md create mode 100644 agent-task/m-architecture-refactor-foundation/08_client_state_split/CODE_REVIEW-cloud-G08.md create mode 100644 agent-task/m-architecture-refactor-foundation/08_client_state_split/PLAN-local-G08.md create mode 100644 apps/control-plane/cmd/control-plane/http_edge_handlers.go create mode 100644 apps/control-plane/cmd/control-plane/http_fleet_handlers.go create mode 100644 apps/control-plane/cmd/control-plane/http_views.go create mode 100644 apps/control-plane/cmd/control-plane/server.go diff --git a/agent-roadmap/phase/automation-runtime-bridge/milestones/architecture-refactor-foundation.md b/agent-roadmap/phase/automation-runtime-bridge/milestones/architecture-refactor-foundation.md index 4984e8d..88081f1 100644 --- a/agent-roadmap/phase/automation-runtime-bridge/milestones/architecture-refactor-foundation.md +++ b/agent-roadmap/phase/automation-runtime-bridge/milestones/architecture-refactor-foundation.md @@ -43,8 +43,8 @@ Edge 내부에서 CLI command, service orchestration, external compatibility sur Node CLI automation runtime을 remote terminal bridge가 재사용할 수 있는 단위와 provider-specific 실행 단위로 나눈다. -- [ ] [cli-executor-split] `apps/node/internal/adapters/cli`의 mode dispatch와 session map 소유를 executor/strategy 경계로 분리한다. -- [ ] [terminal-core] persistent PTY 실행, screen rendering, resize/input/signal/close 기반이 될 terminal session core를 provider-specific Claude/OpenCode 처리와 분리한다. +- [x] [cli-executor-split] `apps/node/internal/adapters/cli`의 mode dispatch와 session map 소유를 executor/strategy 경계로 분리한다. 검증: `agent-task/archive/2026/06/m-architecture-refactor-foundation/04_cli_executor_split/complete.log` +- [x] [terminal-core] persistent PTY 실행, screen rendering, resize/input/signal/close 기반이 될 terminal session core를 provider-specific Claude/OpenCode 처리와 분리한다. 검증: `agent-task/archive/2026/06/m-architecture-refactor-foundation/05+04_terminal_core/complete.log` - [x] [router-default] Node adapter registry가 mock 기본값으로 오류를 숨기지 않도록 production 실행 경로의 empty adapter 처리 정책을 명시하고 적용한다. - [x] [vllm-surface] vLLM adapter skeleton을 명확히 experimental/disabled로 낮추거나 실행 가능한 streaming adapter로 승격한다. @@ -89,5 +89,6 @@ Control Plane과 Flutter Client가 multi-edge 운영면으로 커질 때 선형 - 표준선(선택): Control Plane은 Edge를 통해 관찰/제어하고, Edge는 Node 실행 그룹 상태를 소유하며, Node는 adapter execution과 terminal transport 실행자 역할을 유지한다. OpenAI-compatible/A2A 표면은 IOP native terminal 제어를 흡수하지 않는다. - 선행 작업: 설계 부채 색인 리뷰 - 후속 작업: 원격 터미널 브리지 POC -- active plan: `agent-task/m-architecture-refactor-foundation/04_cli_executor_split/PLAN-cloud-G07.md`, `agent-task/m-architecture-refactor-foundation/05+04_terminal_core/PLAN-cloud-G08.md` +- 최근 완료 작업: `agent-task/archive/2026/06/m-architecture-refactor-foundation/04_cli_executor_split/complete.log`, `agent-task/archive/2026/06/m-architecture-refactor-foundation/05+04_terminal_core/complete.log` +- active plan: `agent-task/m-architecture-refactor-foundation/06_cp_api_split/PLAN-local-G07.md`, `agent-task/m-architecture-refactor-foundation/07+06_fleet_polling/PLAN-local-G08.md`, `agent-task/m-architecture-refactor-foundation/08_client_state_split/PLAN-local-G08.md` - 확인 필요: 없음 diff --git a/agent-task/archive/2026/06/m-architecture-refactor-foundation/06_cp_api_split/code_review_cloud_G07_0.log b/agent-task/archive/2026/06/m-architecture-refactor-foundation/06_cp_api_split/code_review_cloud_G07_0.log new file mode 100644 index 0000000..d06da83 --- /dev/null +++ b/agent-task/archive/2026/06/m-architecture-refactor-foundation/06_cp_api_split/code_review_cloud_G07_0.log @@ -0,0 +1,174 @@ + + +# Code Review Reference - REFACTOR + +> **[IMPLEMENTING AGENT — READ FIRST] Filling in this file is the mandatory final step of implementation.** +> The task is NOT complete until every implementation-owned section below is filled in. +> Complete the `구현 체크리스트`; the final checklist item is mandatory before saving. +> Fill implementation-owned sections, then stop with active files in place and report ready for review. +> If implementation is blocked by a user-only decision, user-owned external environment prerequisite, or scope conflict, fill `사용자 리뷰 요청` with evidence and stop with active files in place; code-review decides whether to write `USER_REVIEW.md`. Evidence gaps that a follow-up agent can close by rerunning commands or collecting artifacts are normal follow-up issues, not user-review blockers by themselves. +> Do not ask the user directly, present choices in chat, or call `request_user_input` during implementation; record the needed decision in `사용자 리뷰 요청` and stop for code-review. +> Finalization (`코드리뷰 결과`, log rename, `complete.log`, archive moves, `코드리뷰 전용 체크리스트`) is review-agent-only, even after compaction/resume. +> Follow the ownership table at the bottom of this file for which sections you own. + +## 개요 + +date=2026-06-06 +task=m-architecture-refactor-foundation/06_cp_api_split, plan=0, tag=REFACTOR + +## Roadmap Targets + +- Milestone: `agent-roadmap/phase/automation-runtime-bridge/milestones/architecture-refactor-foundation.md` +- Task ids: + - `cp-api-split`: `apps/control-plane/cmd/control-plane/main.go`의 server lifecycle, HTTP handler, DTO conversion, Edge command/fleet orchestration을 분리한다. +- Completion mode: check-on-pass + +## 이 파일을 읽는 리뷰 에이전트에게 + +> **[REVIEW AGENT ONLY]** 아래 종결 절차는 코드리뷰 에이전트 전용이다. 구현 에이전트는 이 섹션을 실행하지 않는다. + +각 항목의 구현을 실제 소스 파일과 대조하고, `검증 결과` 섹션의 출력이 코드와 일치하는지 확인하세요. +리뷰 완료는 아래 순서까지 끝난 상태를 의미합니다. + +1. 판정을 append한다. +2. `CODE_REVIEW-cloud-G07.md` → `code_review_cloud_G07_N.log`, `PLAN-local-G07.md` → `plan_local_G07_M.log`로 아카이브한다. +3. PASS이면 `complete.log` 작성 후 active task 디렉터리를 `agent-task/archive/YYYY/MM/m-architecture-refactor-foundation/06_cp_api_split/`로 이동한다. WARN/FAIL이면 user-review gate를 확인한 뒤 다음 active plan/review 파일 또는 `USER_REVIEW.md`를 작성한다. `USER_REVIEW.md`가 사용자 결정으로 완료/PASS 해소되면 code-review가 `USER_REVIEW.md`를 해소 상태로 갱신하고 `complete.log` 작성 후 archive 이동한다. +4. PASS이고 task group이 `m-architecture-refactor-foundation`이면 완료 이벤트 메타데이터를 보고한다. roadmap 상태 체크와 `update-roadmap` 호출은 런타임 책임이다. +5. 적용 가능한 `코드리뷰 전용 체크리스트` 항목을 최종 `.log` 위치에서 체크한 뒤 보고한다. + +--- + +## 구현 항목별 완료 여부 + +| 항목 | 완료 여부 | +|------|---------| +| [REFACTOR-1] Server Lifecycle 경계 분리 | [x] | +| [REFACTOR-2] DTO Conversion 파일 분리 | [x] | +| [REFACTOR-3] HTTP Handler 파일 분리 | [x] | + +## 구현 체크리스트 + +- [x] `main.go`에서 CLI/config entrypoint와 server lifecycle 책임을 분리하고 health/readiness mux 단위 테스트를 추가한다. +- [x] DTO/view type과 proto/registry 변환 함수를 별도 파일로 이동하되 JSON 계약과 secret 비노출 동작을 유지한다. +- [x] Edge registry handler와 fleet handler 등록/command helper를 별도 파일로 이동하되 기존 handler 테스트를 모두 통과시킨다. +- [x] `gofmt`와 `go test -count=1 ./apps/control-plane/...`를 실행한다. +- [x] CODE_REVIEW-*-G??.md의 구현 에이전트 소유 섹션을 실제 구현 내용과 검증 출력으로 채운다. 이 항목이 완료되기 전에는 구현이 완료된 것이 아니다. + +## 코드리뷰 전용 체크리스트 + +> **[REVIEW AGENT ONLY]** 이 체크리스트는 코드리뷰 에이전트만 사용한다. +> 구현 에이전트는 이 섹션을 수정하거나 체크하지 않는다. + +- [x] `코드리뷰 결과`에 `PASS`, `WARN`, `FAIL` 중 하나의 판정을 append한다. +- [x] 판정과 `차원별 평가`, Required/Suggested/Nit 분류가 서로 일치한다. +- [x] active `CODE_REVIEW-*-G??.md`를 `code_review_cloud_G07_N.log`로 아카이브한다. +- [x] active `PLAN-*-G??.md`를 `plan_local_G07_M.log`로 아카이브한다. +- [x] `.gitignore`의 Agent-Ops 관리 block이 `agent-task/**/*.md`와 `agent-task/**/*.log`를 unignore하고 `agent-roadmap/current.md`를 ignore하는지 확인한다. +- [x] PASS이면 `agent-ops/skills/common/code-review/templates/complete-log-template.md` 기준으로 `complete.log`를 작성하고 active `.md` 파일을 남기지 않는다. +- [x] PASS이면 active task 디렉터리 `agent-task/m-architecture-refactor-foundation/06_cp_api_split/`를 `agent-task/archive/YYYY/MM/m-architecture-refactor-foundation/06_cp_api_split/`로 이동하고 최종 archive 경로에서 이 체크리스트를 갱신한다. +- [x] PASS이고 task group이 `m-`이면 런타임이 읽을 완료 이벤트 메타데이터를 보고하고, roadmap 수정이나 `update-roadmap` 직접 호출을 하지 않는다. +- [x] PASS split 작업이면 이동 후 빈 active parent `agent-task/m-architecture-refactor-foundation/`를 제거하거나, 남은 sibling/file이 있어 유지했다고 확인한다. +- [ ] WARN/FAIL이고 user-review gate가 트리거되지 않았으면 다음 active `PLAN-local-G07.md`와 `CODE_REVIEW-cloud-G07.md`를 작성하고 `complete.log`를 작성하지 않는다. +- [ ] USER_REVIEW이면 `agent-ops/skills/common/code-review/templates/user-review-template.md` 기준으로 `USER_REVIEW.md`를 작성하고 active `PLAN-*.md`, `CODE_REVIEW-*.md`, `complete.log`를 남기지 않는다. +- [ ] USER_REVIEW가 사용자 결정으로 완료/PASS 해소되면 `USER_REVIEW.md`를 해소 상태로 갱신하고 `complete.log`를 작성한 뒤 task directory를 archive로 이동한다. + +## 계획 대비 변경 사항 + +- 계획에서는 `newHTTPMux(registry, requestStatus, sendCommand)`를 제안했으나 health/readiness mux와 Edge/fleet handler 등록을 분리했다. `newHTTPMux()`는 health/readiness만 만들고, `run()`이 `registerEdgeRegistryHandlers()`와 `registerFleetHandlers()`를 호출한다. +- `server.go`에 `run()`, `newHTTPMux()`, `startHTTPServer()`를 배치했다. + +## 주요 설계 결정 + +- `app/views` package가 아닌 같은 `main` package 안의 파일로 분리했다. package-private type(예: `edgeRegistryView`, `fleetEdgeView`)을 테스트와 다른 handler에서 참조하므로 같은 package 유지가 가장 작은 변경이다. +- `writeJSON`, `methodNotAllowed` helper는 `http_edge_handlers.go`에 배치했다. Edge/fleet 양쪽에서 공유되므로 같은 package 파일 한 곳에서 제공한다. +- `databaseLogFields`, `redisLogFields`, `serviceURLLogFields`는 CLI/config entrypoint 성격의 `main.go`에 유지했다. + +## 사용자 리뷰 요청 + +_기본값은 `없음`이다. 구현 중 사용자 결정, 사용자 소유 외부 환경/secret/서비스 준비, 또는 계획 범위 변경 없이는 안전하게 진행할 수 없으면 아래 항목을 실제 내용으로 교체하고, 구현을 중단한 뒤 active 파일을 그대로 둔 채 리뷰를 요청한다. 구현 에이전트는 사용자에게 직접 질문하거나 선택지를 제시하거나 `request_user_input`을 호출하지 않는다. 후속 에이전트가 명령 재실행이나 산출물 수집으로 해소할 수 있는 검증 증거 공백만으로는 사용자 리뷰 요청을 작성하지 않는다._ + +- 상태: 없음 +- 사유 유형: 없음 +- 결정 필요: 없음 +- 차단 근거: 없음 +- 실행한 검증/명령: 없음 +- 자동 후속 불가 이유: 없음 +- 재개 조건: 없음 + +## 리뷰어를 위한 체크포인트 + +- `main.go`가 CLI/config entrypoint 중심으로 줄고, server lifecycle은 `server.go` 또는 동등 파일로 이동했는지 확인한다. +- HTTP path, method, status code, JSON field명, secret 비노출 계약이 기존 테스트와 일치하는지 확인한다. +- `registerEdgeRegistryHandlers`와 `registerFleetHandlers` symbol명이 유지되어 기존 tests와 다음 fleet plan의 선행 조건을 만족하는지 확인한다. +- 새 health/readiness mux 테스트가 실제 helper를 검증하는지 확인한다. + +## 검증 결과 + +_구현 에이전트가 각 중간 검증 및 최종 검증 명령 실행 후 출력을 여기에 붙여 넣는다._ + +### REFACTOR-1 중간 검증 +```bash +$ gofmt -w apps/control-plane/cmd/control-plane/main.go apps/control-plane/cmd/control-plane/server.go apps/control-plane/cmd/control-plane/main_test.go +$ go test -count=1 ./apps/control-plane/... +ok iop/apps/control-plane/cmd/control-plane 0.006s +ok iop/apps/control-plane/internal/wire 1.470s +``` + +### REFACTOR-2 중간 검증 +```bash +$ gofmt -w apps/control-plane/cmd/control-plane/main.go apps/control-plane/cmd/control-plane/http_views.go apps/control-plane/cmd/control-plane/main_test.go +$ go test -count=1 ./apps/control-plane/... +ok iop/apps/control-plane/cmd/control-plane 0.006s +ok iop/apps/control-plane/internal/wire 1.472s +``` + +### REFACTOR-3 중간 검증 +```bash +$ gofmt -w apps/control-plane/cmd/control-plane/main.go apps/control-plane/cmd/control-plane/http_edge_handlers.go apps/control-plane/cmd/control-plane/http_fleet_handlers.go apps/control-plane/cmd/control-plane/main_test.go +$ go test -count=1 ./apps/control-plane/... +ok iop/apps/control-plane/cmd/control-plane 0.007s +ok iop/apps/control-plane/internal/wire 1.468s +``` + +### 최종 검증 +```bash +$ gofmt -w apps/control-plane/cmd/control-plane/main.go apps/control-plane/cmd/control-plane/server.go apps/control-plane/cmd/control-plane/http_views.go apps/control-plane/cmd/control-plane/http_edge_handlers.go apps/control-plane/cmd/control-plane/http_fleet_handlers.go apps/control-plane/cmd/control-plane/main_test.go +$ go test -count=1 ./apps/control-plane/... +ok iop/apps/control-plane/cmd/control-plane 0.007s +ok iop/apps/control-plane/internal/wire 1.475s +``` + +--- + +## Ownership + +| Section | Owner | Note | +|---------|-------|------| +| Header comment, 개요, 리뷰 에이전트 지시 | Fixed at stub creation | Implementing agent must not modify or execute these | +| Roadmap Targets | Fixed at stub creation | Implementing agent must not modify | +| 구현 항목별 완료 여부 | Implementing agent | Check `[ ]` to `[x]` only | +| 구현 체크리스트 | Implementing agent | Check `[ ]` to `[x]` only | +| 코드리뷰 전용 체크리스트 | Review agent only | Implementing agent must not modify | +| 계획 대비 변경 사항, 주요 설계 결정 | Implementing agent | Replace placeholders | +| 사용자 리뷰 요청 | Implementing agent | Keep `상태: 없음` unless blocked by user-only decision | +| 리뷰어를 위한 체크포인트 | Fixed at stub creation | Review focus | +| 검증 결과 | Implementing agent | Paste actual stdout/stderr | + +## 코드리뷰 결과 + +- 종합 판정: PASS +- 차원별 평가: + - correctness: Pass + - completeness: Pass + - test coverage: Pass + - API contract: Pass + - code quality: Pass + - plan deviation: Pass + - verification trust: Pass +- 발견된 문제: + - Nit (직접 수정): `apps/control-plane/cmd/control-plane/server.go:16` - 사용하지 않는 `newSignalContext()` helper와 `newHTTPMux`의 미사용 인자를 제거해 helper 경계를 단순화했다. +- 검증: + - `gofmt -w apps/control-plane/cmd/control-plane/main.go apps/control-plane/cmd/control-plane/server.go apps/control-plane/cmd/control-plane/http_views.go apps/control-plane/cmd/control-plane/http_edge_handlers.go apps/control-plane/cmd/control-plane/http_fleet_handlers.go apps/control-plane/cmd/control-plane/main_test.go` + - `go test -count=1 ./apps/control-plane/...` + - 결과: `ok iop/apps/control-plane/cmd/control-plane 0.007s`, `ok iop/apps/control-plane/internal/wire 1.711s` +- 다음 단계: PASS이므로 active plan/review를 `.log`로 아카이브하고 `complete.log` 작성 후 task directory를 `agent-task/archive/2026/06/m-architecture-refactor-foundation/06_cp_api_split/`로 이동한다. diff --git a/agent-task/archive/2026/06/m-architecture-refactor-foundation/06_cp_api_split/complete.log b/agent-task/archive/2026/06/m-architecture-refactor-foundation/06_cp_api_split/complete.log new file mode 100644 index 0000000..befe8a7 --- /dev/null +++ b/agent-task/archive/2026/06/m-architecture-refactor-foundation/06_cp_api_split/complete.log @@ -0,0 +1,45 @@ +# Complete - m-architecture-refactor-foundation/06_cp_api_split + +## 완료 일시 + +2026-06-06 + +## 요약 + +Control Plane HTTP/API boundary split plan completed in 1 review loop with final verdict PASS. + +## 루프 이력 + +| Plan | Review | Verdict | 메모 | +|------|--------|---------|------| +| `plan_local_G07_0.log` | `code_review_cloud_G07_0.log` | PASS | `main.go`의 server lifecycle, HTTP handler, DTO conversion, Edge/fleet orchestration 분리가 완료되었고 Control Plane package tests가 통과했다. | + +## 구현/정리 내용 + +- `main.go`를 CLI/config entrypoint와 log-field helper 중심으로 축소했다. +- `server.go`에 `run`, health/readiness mux, HTTP server lifecycle helper를 분리했다. +- `http_views.go`에 HTTP DTO와 proto/registry conversion helper를 분리했다. +- `http_edge_handlers.go`에 Edge registry/command handlers와 shared JSON/method helpers를 분리했다. +- `http_fleet_handlers.go`에 fleet status/command handlers를 분리했다. +- `main_test.go`에 health/readiness mux 검증과 handler registration smoke를 추가했다. +- 리뷰 중 사용하지 않는 `newSignalContext()` helper와 `newHTTPMux`의 미사용 인자를 제거했다. + +## 최종 검증 + +- `gofmt -w apps/control-plane/cmd/control-plane/main.go apps/control-plane/cmd/control-plane/server.go apps/control-plane/cmd/control-plane/http_views.go apps/control-plane/cmd/control-plane/http_edge_handlers.go apps/control-plane/cmd/control-plane/http_fleet_handlers.go apps/control-plane/cmd/control-plane/main_test.go` - PASS; 출력 없음. +- `go test -count=1 ./apps/control-plane/...` - PASS; `ok iop/apps/control-plane/cmd/control-plane 0.007s`, `ok iop/apps/control-plane/internal/wire 1.711s`. + +## Roadmap Completion + +- Milestone: `agent-roadmap/phase/automation-runtime-bridge/milestones/architecture-refactor-foundation.md` +- Completed task ids: + - `cp-api-split`: PASS; evidence=`agent-task/archive/2026/06/m-architecture-refactor-foundation/06_cp_api_split/plan_local_G07_0.log`, `agent-task/archive/2026/06/m-architecture-refactor-foundation/06_cp_api_split/code_review_cloud_G07_0.log`; verification=`go test -count=1 ./apps/control-plane/...` +- Not completed task ids: 없음 + +## 잔여 Nit + +- 없음 + +## 후속 작업 + +- 없음 diff --git a/agent-task/archive/2026/06/m-architecture-refactor-foundation/06_cp_api_split/plan_local_G07_0.log b/agent-task/archive/2026/06/m-architecture-refactor-foundation/06_cp_api_split/plan_local_G07_0.log new file mode 100644 index 0000000..d199c39 --- /dev/null +++ b/agent-task/archive/2026/06/m-architecture-refactor-foundation/06_cp_api_split/plan_local_G07_0.log @@ -0,0 +1,264 @@ + + +# PLAN - REFACTOR cp-api-split + +## 이 파일을 읽는 구현 에이전트에게 + +구현 완료의 마지막 단계는 `CODE_REVIEW-cloud-G07.md`의 구현 에이전트 소유 섹션을 실제 변경 내용과 검증 출력으로 채우는 것이다. 검증을 실행하고, 출력 원문을 붙이고, active 파일은 그대로 둔 채 리뷰 준비 상태를 보고한다. 종료 처리, 로그 아카이브, `complete.log` 작성, task directory 이동은 code-review skill 전용이다. + +구현 중 사용자만 결정할 수 있는 범위 변경, 사용자 소유 외부 환경/secret/서비스 준비, 또는 안전하게 진행할 수 없는 충돌이 생기면 직접 질문하지 말고 `CODE_REVIEW-cloud-G07.md`의 `사용자 리뷰 요청` 섹션을 증거와 함께 채운 뒤 멈춘다. `request_user_input`, 채팅 선택지 제시, `USER_REVIEW.md` 생성, `complete.log` 작성, active 파일 아카이브는 구현 에이전트가 하지 않는다. 후속 에이전트가 명령 재실행이나 산출물 수집으로 해소할 수 있는 검증 공백은 사용자 리뷰 요청 사유가 아니다. + +## 배경 + +`apps/control-plane/cmd/control-plane/main.go`가 CLI, config, server lifecycle, HTTP handler, DTO 변환, Edge/fleet orchestration을 한 파일에 갖고 있다. cp-client Epic의 첫 작업은 HTTP API 경계를 먼저 나눠 이후 fleet polling 정책과 client 상태 분리를 안전하게 얹는 기반을 만드는 것이다. 이번 계획은 동작 변경 없이 Go package `main` 내부 파일 경계를 분리한다. + +## 사용자 리뷰 요청 흐름 + +구현 중 차단 결정은 active review stub의 `사용자 리뷰 요청` 섹션에 기록한다. 해당 섹션은 `agent-ops/skills/common/_templates/implementation-user-review-request-section.md`와 동일한 형식을 사용한다. 구현 에이전트는 사용자에게 직접 묻지 않으며, code-review가 요청 타당성을 검증하고 실제 `USER_REVIEW.md` 작성 여부를 결정한다. + +## Roadmap Targets + +- Milestone: `agent-roadmap/phase/automation-runtime-bridge/milestones/architecture-refactor-foundation.md` +- Task ids: + - `cp-api-split`: `apps/control-plane/cmd/control-plane/main.go`의 server lifecycle, HTTP handler, DTO conversion, Edge command/fleet orchestration을 분리한다. +- Completion mode: check-on-pass + +## 분석 결과 + +### 읽은 파일 + +- `agent-ops/rules/project/rules.md` +- `agent-ops/rules/common/rules-roadmap.md` +- `agent-roadmap/current.md` +- `agent-roadmap/phase/automation-runtime-bridge/milestones/architecture-refactor-foundation.md` +- `agent-ops/skills/common/router.md` +- `agent-ops/skills/common/plan/SKILL.md` +- `agent-ops/skills/common/_templates/implementation-user-review-request-section.md` +- `agent-ops/rules/project/domain/control-plane/rules.md` +- `agent-ops/rules/project/domain/client/rules.md` +- `agent-test/local/rules.md` +- `agent-test/local/control-plane-smoke.md` +- `agent-test/local/client-smoke.md` +- `.gitignore` +- `go.mod` +- `apps/control-plane/cmd/control-plane/main.go` +- `apps/control-plane/cmd/control-plane/main_test.go` +- `apps/control-plane/internal/wire/edge_registry.go` +- `apps/control-plane/internal/wire/edge_server.go` +- `apps/client/pubspec.yaml` +- `apps/client/lib/main.dart` +- `apps/client/lib/control_plane_status_client.dart` +- `apps/client/lib/control_plane_status_widgets.dart` +- `apps/client/test/widget_test.dart` + +### 테스트 환경 규칙 + +- `test_env=local`. +- `agent-test/local/rules.md` 존재 및 정독 완료. Control Plane 변경은 `agent-test/local/control-plane-smoke.md`를 baseline으로 사용한다. +- 적용 명령: 변경한 Control Plane 패키지는 `go test ./apps/control-plane/...`를 실행한다. fresh execution이 필요하므로 계획 명령은 `go test -count=1 ./apps/control-plane/...`로 고정한다. +- HTTP lifecycle 경계를 건드리므로 health/readiness는 새 `httptest` 단위 테스트로 확인한다. Docker compose/curl smoke는 이 계획의 범위가 실제 프로세스 기동 변경이 아니므로 생략한다. +- `agent-test/local/client-smoke.md`도 읽었지만 이 plan은 Flutter 파일을 변경하지 않으므로 client 검증 명령은 적용하지 않는다. +- `<확인 필요>` 값 없음. agent-test fallback 없음. + +### 테스트 커버리지 공백 + +- 기존 `main_test.go`는 config, log field, Edge registry handler, command handler, fleet handler를 직접 호출해 검증한다. +- `run`이 health/readiness handler를 등록하는 경로는 현재 직접 테스트가 없다. `newHTTPMux` 또는 동등 helper를 추가하고 `/healthz`, `/readyz` 단위 테스트를 작성한다. +- 파일 경계 분리 자체는 동작 변경이 아니므로 기존 handler 테스트가 회귀 검증을 담당한다. + +### 심볼 참조 + +- 제거/이름 변경 예정 없음. +- 이동 예정 call site: + - `run`: `apps/control-plane/cmd/control-plane/main.go:84` + - `registerEdgeRegistryHandlers`: `apps/control-plane/cmd/control-plane/main.go:182`, `apps/control-plane/cmd/control-plane/main_test.go:260`, `338`, `401`, `467`, `515`, `530`, `574`, `600`, `616`, `634`, `660` + - `registerFleetHandlers`: `apps/control-plane/cmd/control-plane/main.go:183`, `apps/control-plane/cmd/control-plane/main_test.go:746`, `818` + - DTO/view types are package-private and referenced by existing tests in `main_test.go`. + +### 분할 판단 + +- split decision policy를 평가했다. cp-client Epic은 multi-plan으로 분리한다. +- shared task group: `agent-task/m-architecture-refactor-foundation/` +- sibling subtask directories: + - `06_cp_api_split`: 이 plan. 선행 의존성 없음. + - `07+06_fleet_polling`: `06_cp_api_split` PASS 후 `complete.log` 필요. 현재 missing. + - `08_client_state_split`: Flutter client 독립 작업. 선행 의존성 없음. +- 이 plan 자체는 단일 plan으로 유지한다. server lifecycle, handlers, DTO 이동은 같은 package compile/test 루프 안에서 함께 맞춰야 하며, 더 쪼개면 중간 상태에서 package-private type 참조가 흔들린다. + +### 범위 결정 근거 + +- `/fleet/status` bounded concurrency/cache/timeout 정책은 `07+06_fleet_polling`에서 처리한다. +- Flutter bootstrap/state/DTO/repository/widget 분리는 `08_client_state_split`에서 처리한다. +- `apps/control-plane/internal/wire/**` protocol behavior는 변경하지 않는다. +- public JSON field명, HTTP path, status code는 유지한다. + +### 빌드 등급 + +- build lane: `local-G07`. Internal Go refactor지만 server/handler/DTO 파일 경계를 한 번에 나누며 package compile surface가 넓다. +- review lane: `cloud-G07`. Roadmap task 완료 판정과 API boundary 회귀 확인이 필요하다. + +## 구현 체크리스트 + +- [ ] `main.go`에서 CLI/config entrypoint와 server lifecycle 책임을 분리하고 health/readiness mux 단위 테스트를 추가한다. +- [ ] DTO/view type과 proto/registry 변환 함수를 별도 파일로 이동하되 JSON 계약과 secret 비노출 동작을 유지한다. +- [ ] Edge registry handler와 fleet handler 등록/command helper를 별도 파일로 이동하되 기존 handler 테스트를 모두 통과시킨다. +- [ ] `gofmt`와 `go test -count=1 ./apps/control-plane/...`를 실행한다. +- [ ] CODE_REVIEW-*-G??.md의 구현 에이전트 소유 섹션을 실제 구현 내용과 검증 출력으로 채운다. 이 항목이 완료되기 전에는 구현이 완료된 것이 아니다. + +## [REFACTOR-1] Server Lifecycle 경계 분리 + +### 문제 + +`apps/control-plane/cmd/control-plane/main.go:137`부터 `209`까지 `run`이 mux 생성, health/readiness handler, wire 서버 생성, Edge 서버 생성, HTTP server lifecycle을 모두 처리한다. 이 구조에서는 API handler 분리와 fleet orchestration 정책 추가가 모두 `run` 주변에 붙는다. + +Before: + +```go +// apps/control-plane/cmd/control-plane/main.go:137 +func run(ctx context.Context, cfg controlPlaneConfig, logger *zap.Logger) error { + mux := http.NewServeMux() + mux.HandleFunc("/healthz", func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte("ok\n")) + }) + mux.HandleFunc("/readyz", func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte("ready\n")) + }) +``` + +### 해결 방법 + +- 새 파일 `apps/control-plane/cmd/control-plane/server.go`를 만든다. +- `run`, HTTP server lifecycle helper, `newHTTPMux`를 `server.go`로 이동한다. +- `main.go`에는 `main`, `rootCmd`, `serveCmd`, config/env/log field helpers만 남긴다. +- `newHTTPMux(registry, requestStatus, sendCommand)` 또는 동등 helper에서 health/readiness/Edge/fleet handlers를 등록한다. +- `main_test.go`에 `TestHTTPMuxHealthAndReadiness`를 추가해 `/healthz`, `/readyz` body와 status를 검증한다. + +### 수정 파일 및 체크리스트 + +- [ ] `apps/control-plane/cmd/control-plane/main.go`: `run` 및 HTTP lifecycle 코드를 제거하고 entrypoint/config 중심으로 축소한다. +- [ ] `apps/control-plane/cmd/control-plane/server.go`: `run`, mux 생성, HTTP server lifecycle을 배치한다. +- [ ] `apps/control-plane/cmd/control-plane/main_test.go`: health/readiness mux 테스트를 추가한다. + +### 테스트 작성 + +- 작성: `apps/control-plane/cmd/control-plane/main_test.go`, `TestHTTPMuxHealthAndReadiness`. +- assertion: `/healthz`는 `200 ok\n`, `/readyz`는 `200 ready\n`. +- fixture: `wire.NewEdgeRegistry()`, nil requester/sender. + +### 중간 검증 + +```bash +gofmt -w apps/control-plane/cmd/control-plane/main.go apps/control-plane/cmd/control-plane/server.go apps/control-plane/cmd/control-plane/main_test.go +go test -count=1 ./apps/control-plane/... +``` + +## [REFACTOR-2] DTO Conversion 파일 분리 + +### 문제 + +`apps/control-plane/cmd/control-plane/main.go:211`부터 `373`까지 JSON DTO type이 있고, `557`부터 `723`까지 registry/proto 변환 함수가 있다. Handler 코드와 DTO 변환 코드가 같은 파일에 있어 HTTP surface 변경과 serialization 계약 검토가 섞인다. + +Before: + +```go +// apps/control-plane/cmd/control-plane/main.go:243 +type edgeStatusResponseView struct { + RequestID string `json:"request_id"` + EdgeID string `json:"edge_id"` + EdgeName string `json:"edge_name"` + ObservedTimeUnixNano int64 `json:"observed_time_unix_nano"` + Nodes []edgeNodeSnapshotView `json:"nodes"` + Capabilities []edgeCapabilitySummaryView `json:"capabilities,omitempty"` + DomainAgents []edgeDomainAgentSummaryView `json:"domain_agents,omitempty"` + Metadata map[string]string `json:"metadata,omitempty"` + Error string `json:"error,omitempty"` +} +``` + +### 해결 방법 + +- 새 파일 `apps/control-plane/cmd/control-plane/http_views.go`를 만든다. +- DTO structs와 변환 함수 `edgeRegistryViewFromState`, `edgeStatusResponseViewFromProto`, `edgeCapabilityViews`, `edgeDomainAgentViews`, `edgeCommandResponseViewFromProto`, `edgeCommandRecordViewFromRecord`, `fleetEdgeViewFromState`, `newNodeConfigSummaryView`, `edgeNodeEventViewFromRecord`를 이동한다. +- JSON tag와 nil/empty slice behavior는 변경하지 않는다. + +### 수정 파일 및 체크리스트 + +- [ ] `apps/control-plane/cmd/control-plane/main.go`: DTO/conversion block 제거. +- [ ] `apps/control-plane/cmd/control-plane/http_views.go`: DTO/conversion block 추가. +- [ ] `apps/control-plane/cmd/control-plane/main_test.go`: 기존 secret 비노출 및 fleet leak 테스트가 그대로 통과하는지 확인한다. + +### 테스트 작성 + +- 새 테스트 작성 없음. 기존 `TestEdgeRegistryHTTPHandlersGetLiveStatus`가 raw config secret 비노출을, `TestFleetStatusHTTPHandlerCombinesConnectionAndCapabilities`가 fleet response leak 금지를 검증한다. + +### 중간 검증 + +```bash +gofmt -w apps/control-plane/cmd/control-plane/main.go apps/control-plane/cmd/control-plane/http_views.go apps/control-plane/cmd/control-plane/main_test.go +go test -count=1 ./apps/control-plane/... +``` + +## [REFACTOR-3] HTTP Handler 파일 분리 + +### 문제 + +`apps/control-plane/cmd/control-plane/main.go:382`부터 `550`까지 Edge registry handlers, single Edge command helper, fleet handlers가 연속 배치되어 있다. `07+06_fleet_polling`에서 fleet 정책을 추가하려면 현재 handler block을 먼저 독립 파일로 떼어야 한다. + +Before: + +```go +// apps/control-plane/cmd/control-plane/main.go:501 +func registerFleetHandlers(mux *http.ServeMux, registry *wire.EdgeRegistry, requestStatus edgeStatusRequester, sendCommand edgeCommandSender) { + mux.HandleFunc("/fleet/status", func(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodGet { + methodNotAllowed(w, http.MethodGet) + return + } +``` + +### 해결 방법 + +- 새 파일 `apps/control-plane/cmd/control-plane/http_edge_handlers.go`를 만들고 `edgeStatusRequester`, `edgeCommandSender`, `registerEdgeRegistryHandlers`, `handleEdgeCommandPost`, `methodNotAllowed`, `writeJSON`을 배치한다. +- 새 파일 `apps/control-plane/cmd/control-plane/http_fleet_handlers.go`를 만들고 `registerFleetHandlers`를 배치한다. +- `writeJSON` 위치는 Edge/fleet 양쪽에서 공유되도록 같은 package 파일에 둔다. +- 기존 tests가 package-private handler functions를 그대로 호출하도록 symbol명은 유지한다. + +### 수정 파일 및 체크리스트 + +- [ ] `apps/control-plane/cmd/control-plane/main.go`: handler block 제거. +- [ ] `apps/control-plane/cmd/control-plane/http_edge_handlers.go`: Edge handlers와 shared HTTP helpers 추가. +- [ ] `apps/control-plane/cmd/control-plane/http_fleet_handlers.go`: fleet handlers 추가. +- [ ] `apps/control-plane/cmd/control-plane/main_test.go`: 기존 호출명이 유지되어 변경을 최소화한다. + +### 테스트 작성 + +- 새 테스트 작성 없음. 기존 Edge/fleet handler tests가 전체 회귀를 담당한다. + +### 중간 검증 + +```bash +gofmt -w apps/control-plane/cmd/control-plane/main.go apps/control-plane/cmd/control-plane/http_edge_handlers.go apps/control-plane/cmd/control-plane/http_fleet_handlers.go apps/control-plane/cmd/control-plane/main_test.go +go test -count=1 ./apps/control-plane/... +``` + +## 수정 파일 요약 + +| 파일 | 항목 | +|------|------| +| `apps/control-plane/cmd/control-plane/main.go` | REFACTOR-1, REFACTOR-2, REFACTOR-3 | +| `apps/control-plane/cmd/control-plane/server.go` | REFACTOR-1 | +| `apps/control-plane/cmd/control-plane/http_views.go` | REFACTOR-2 | +| `apps/control-plane/cmd/control-plane/http_edge_handlers.go` | REFACTOR-3 | +| `apps/control-plane/cmd/control-plane/http_fleet_handlers.go` | REFACTOR-3 | +| `apps/control-plane/cmd/control-plane/main_test.go` | REFACTOR-1, REFACTOR-2, REFACTOR-3 | + +## 최종 검증 + +```bash +gofmt -w apps/control-plane/cmd/control-plane/main.go apps/control-plane/cmd/control-plane/server.go apps/control-plane/cmd/control-plane/http_views.go apps/control-plane/cmd/control-plane/http_edge_handlers.go apps/control-plane/cmd/control-plane/http_fleet_handlers.go apps/control-plane/cmd/control-plane/main_test.go +go test -count=1 ./apps/control-plane/... +``` + +모든 코드 변경 완료 후 반드시 `CODE_REVIEW-*-G??.md`의 구현 에이전트 소유 섹션을 채운다. 이 파일 작성이 구현의 마지막 단계다. diff --git a/agent-task/m-architecture-refactor-foundation/07+06_fleet_polling/CODE_REVIEW-cloud-G08.md b/agent-task/m-architecture-refactor-foundation/07+06_fleet_polling/CODE_REVIEW-cloud-G08.md new file mode 100644 index 0000000..8a1ed76 --- /dev/null +++ b/agent-task/m-architecture-refactor-foundation/07+06_fleet_polling/CODE_REVIEW-cloud-G08.md @@ -0,0 +1,160 @@ + + +# Code Review Reference - API + +> **[IMPLEMENTING AGENT — READ FIRST] Filling in this file is the mandatory final step of implementation.** +> The task is NOT complete until every implementation-owned section below is filled in. +> Complete the `구현 체크리스트`; the final checklist item is mandatory before saving. +> Fill implementation-owned sections, then stop with active files in place and report ready for review. +> If implementation is blocked by a user-only decision, user-owned external environment prerequisite, or scope conflict, fill `사용자 리뷰 요청` with evidence and stop with active files in place; code-review decides whether to write `USER_REVIEW.md`. Evidence gaps that a follow-up agent can close by rerunning commands or collecting artifacts are normal follow-up issues, not user-review blockers by themselves. +> Do not ask the user directly, present choices in chat, or call `request_user_input` during implementation; record the needed decision in `사용자 리뷰 요청` and stop for code-review. +> Finalization (`코드리뷰 결과`, log rename, `complete.log`, archive moves, `코드리뷰 전용 체크리스트`) is review-agent-only, even after compaction/resume. +> Follow the ownership table at the bottom of this file for which sections you own. + +## 개요 + +date=2026-06-06 +task=m-architecture-refactor-foundation/07+06_fleet_polling, plan=0, tag=API + +## Roadmap Targets + +- Milestone: `agent-roadmap/phase/automation-runtime-bridge/milestones/architecture-refactor-foundation.md` +- Task ids: + - `fleet-polling`: `/fleet/status`와 fleet command 호출을 bounded concurrency, cache, timeout 정책으로 정리한다. +- Completion mode: check-on-pass + +## 이 파일을 읽는 리뷰 에이전트에게 + +> **[REVIEW AGENT ONLY]** 아래 종결 절차는 코드리뷰 에이전트 전용이다. 구현 에이전트는 이 섹션을 실행하지 않는다. + +각 항목의 구현을 실제 소스 파일과 대조하고, `검증 결과` 섹션의 출력이 코드와 일치하는지 확인하세요. +리뷰 완료는 아래 순서까지 끝난 상태를 의미합니다. + +1. 판정을 append한다. +2. `CODE_REVIEW-cloud-G08.md` → `code_review_cloud_G08_N.log`, `PLAN-local-G08.md` → `plan_local_G08_M.log`로 아카이브한다. +3. PASS이면 `complete.log` 작성 후 active task 디렉터리를 `agent-task/archive/YYYY/MM/m-architecture-refactor-foundation/07+06_fleet_polling/`로 이동한다. WARN/FAIL이면 user-review gate를 확인한 뒤 다음 active plan/review 파일 또는 `USER_REVIEW.md`를 작성한다. `USER_REVIEW.md`가 사용자 결정으로 완료/PASS 해소되면 code-review가 `USER_REVIEW.md`를 해소 상태로 갱신하고 `complete.log` 작성 후 archive 이동한다. +4. PASS이고 task group이 `m-architecture-refactor-foundation`이면 완료 이벤트 메타데이터를 보고한다. roadmap 상태 체크와 `update-roadmap` 호출은 런타임 책임이다. +5. 적용 가능한 `코드리뷰 전용 체크리스트` 항목을 최종 `.log` 위치에서 체크한 뒤 보고한다. + +--- + +## 구현 항목별 완료 여부 + +| 항목 | 완료 여부 | +|------|---------| +| [API-1] Fleet Orchestration Service 추가 | [ ] | +| [API-2] `/fleet/status` bounded concurrency와 cache 적용 | [ ] | +| [API-3] `/fleet/commands` bounded fan-out 적용 | [ ] | + +## 구현 체크리스트 + +- [ ] 선행 `06_cp_api_split` 완료 근거를 확인하고, 없으면 `사용자 리뷰 요청`이 아니라 선행 작업 미완료로 구현을 중단 보고한다. +- [ ] fleet status/command orchestration service와 기본 timeout/concurrency/cache option을 추가한다. +- [ ] `/fleet/status`를 bounded concurrency와 fresh status cache를 사용하도록 바꾸고 기존 JSON 계약을 유지한다. +- [ ] `/fleet/commands` fan-out을 bounded concurrency로 바꾸고 offline skip, per-edge result, timeout 전달을 유지한다. +- [ ] concurrency/cache/timeout 회귀 테스트를 추가하고 `gofmt`, `go test -count=1 ./apps/control-plane/...`를 실행한다. +- [ ] CODE_REVIEW-*-G??.md의 구현 에이전트 소유 섹션을 실제 구현 내용과 검증 출력으로 채운다. 이 항목이 완료되기 전에는 구현이 완료된 것이 아니다. + +## 코드리뷰 전용 체크리스트 + +> **[REVIEW AGENT ONLY]** 이 체크리스트는 코드리뷰 에이전트만 사용한다. +> 구현 에이전트는 이 섹션을 수정하거나 체크하지 않는다. + +- [ ] `코드리뷰 결과`에 `PASS`, `WARN`, `FAIL` 중 하나의 판정을 append한다. +- [ ] 판정과 `차원별 평가`, Required/Suggested/Nit 분류가 서로 일치한다. +- [ ] active `CODE_REVIEW-*-G??.md`를 `code_review_cloud_G08_N.log`로 아카이브한다. +- [ ] active `PLAN-*-G??.md`를 `plan_local_G08_M.log`로 아카이브한다. +- [ ] `.gitignore`의 Agent-Ops 관리 block이 `agent-task/**/*.md`와 `agent-task/**/*.log`를 unignore하고 `agent-roadmap/current.md`를 ignore하는지 확인한다. +- [ ] PASS이면 `agent-ops/skills/common/code-review/templates/complete-log-template.md` 기준으로 `complete.log`를 작성하고 active `.md` 파일을 남기지 않는다. +- [ ] PASS이면 active task 디렉터리 `agent-task/m-architecture-refactor-foundation/07+06_fleet_polling/`를 `agent-task/archive/YYYY/MM/m-architecture-refactor-foundation/07+06_fleet_polling/`로 이동하고 최종 archive 경로에서 이 체크리스트를 갱신한다. +- [ ] PASS이고 task group이 `m-`이면 런타임이 읽을 완료 이벤트 메타데이터를 보고하고, roadmap 수정이나 `update-roadmap` 직접 호출을 하지 않는다. +- [ ] PASS split 작업이면 이동 후 빈 active parent `agent-task/m-architecture-refactor-foundation/`를 제거하거나, 남은 sibling/file이 있어 유지했다고 확인한다. +- [ ] WARN/FAIL이고 user-review gate가 트리거되지 않았으면 다음 active `PLAN-local-G08.md`와 `CODE_REVIEW-cloud-G08.md`를 작성하고 `complete.log`를 작성하지 않는다. +- [ ] USER_REVIEW이면 `agent-ops/skills/common/code-review/templates/user-review-template.md` 기준으로 `USER_REVIEW.md`를 작성하고 active `PLAN-*.md`, `CODE_REVIEW-*.md`, `complete.log`를 남기지 않는다. +- [ ] USER_REVIEW가 사용자 결정으로 완료/PASS 해소되면 `USER_REVIEW.md`를 해소 상태로 갱신하고 `complete.log`를 작성한 뒤 task directory를 archive로 이동한다. + +## 계획 대비 변경 사항 + +_구현 에이전트가 계획과 다르게 구현한 부분을 이유와 함께 기록한다._ + +## 주요 설계 결정 + +_구현 에이전트가 주요 설계 결정 사항을 기록한다._ + +## 사용자 리뷰 요청 + +_기본값은 `없음`이다. 구현 중 사용자 결정, 사용자 소유 외부 환경/secret/서비스 준비, 또는 계획 범위 변경 없이는 안전하게 진행할 수 없으면 아래 항목을 실제 내용으로 교체하고, 구현을 중단한 뒤 active 파일을 그대로 둔 채 리뷰를 요청한다. 구현 에이전트는 사용자에게 직접 질문하거나 선택지를 제시하거나 `request_user_input`을 호출하지 않는다. 후속 에이전트가 명령 재실행이나 산출물 수집으로 해소할 수 있는 검증 증거 공백만으로는 사용자 리뷰 요청을 작성하지 않는다._ + +- 상태: 없음 +- 사유 유형: 없음 +- 결정 필요: 없음 +- 차단 근거: 없음 +- 실행한 검증/명령: 없음 +- 자동 후속 불가 이유: 없음 +- 재개 조건: 없음 + +## 리뷰어를 위한 체크포인트 + +- 구현 전 `06_cp_api_split` 완료 근거가 확인되었는지 확인한다. +- `/fleet/status` response ordering, degraded/offline semantics, leak 금지 계약이 유지되는지 확인한다. +- concurrency tests가 실제 동시 in-flight 상한을 관측하는지, cache test가 requester call count를 검증하는지 확인한다. +- `/fleet/commands`가 offline Edge를 제외하면서 per-edge error를 response에 유지하고 timeout 값을 전달하는지 확인한다. + +## 검증 결과 + +_구현 에이전트가 각 중간 검증 및 최종 검증 명령 실행 후 출력을 여기에 붙여 넣는다._ + +필수 규칙: +- 검증 명령은 고정된 계약이다. 임의로 대체하지 않는다. +- 대체가 필요하면 `계획 대비 변경 사항`에 이유와 대체 명령을 기록한다. +- `검증 결과`에는 실제 stdout/stderr를 붙여 넣는다. +- 사용자 리뷰 요청으로 명령을 끝까지 실행하지 못했다면 `사용자 리뷰 요청`에 실행한 명령, 실제 출력, 미실행 명령의 사유를 기록한다. +- mobile/UI hang, timeout, 또는 2분 무진행은 blind retry를 중단하고 focused rerun 명령과 screenshot/window/UI-tree evidence path를 남기며, 불가능하면 정확한 사유를 남긴다. + +### API-1 중간 검증 +```bash +$ gofmt -w apps/control-plane/cmd/control-plane/fleet_orchestrator.go apps/control-plane/cmd/control-plane/http_fleet_handlers.go apps/control-plane/cmd/control-plane/main_test.go +(output) +$ go test -count=1 ./apps/control-plane/... +(output) +``` + +### API-2 중간 검증 +```bash +$ gofmt -w apps/control-plane/cmd/control-plane/fleet_orchestrator.go apps/control-plane/cmd/control-plane/main_test.go +(output) +$ go test -count=1 ./apps/control-plane/... +(output) +``` + +### API-3 중간 검증 +```bash +$ gofmt -w apps/control-plane/cmd/control-plane/fleet_orchestrator.go apps/control-plane/cmd/control-plane/http_fleet_handlers.go apps/control-plane/cmd/control-plane/main_test.go +(output) +$ go test -count=1 ./apps/control-plane/... +(output) +``` + +### 최종 검증 +```bash +$ gofmt -w apps/control-plane/cmd/control-plane/fleet_orchestrator.go apps/control-plane/cmd/control-plane/http_fleet_handlers.go apps/control-plane/cmd/control-plane/main_test.go +(output) +$ go test -count=1 ./apps/control-plane/... +(output) +``` + +--- + +## Ownership + +| Section | Owner | Note | +|---------|-------|------| +| Header comment, 개요, 리뷰 에이전트 지시 | Fixed at stub creation | Implementing agent must not modify or execute these | +| Roadmap Targets | Fixed at stub creation | Implementing agent must not modify | +| 구현 항목별 완료 여부 | Implementing agent | Check `[ ]` to `[x]` only | +| 구현 체크리스트 | Implementing agent | Check `[ ]` to `[x]` only | +| 코드리뷰 전용 체크리스트 | Review agent only | Implementing agent must not modify | +| 계획 대비 변경 사항, 주요 설계 결정 | Implementing agent | Replace placeholders | +| 사용자 리뷰 요청 | Implementing agent | Keep `상태: 없음` unless blocked by user-only decision | +| 리뷰어를 위한 체크포인트 | Fixed at stub creation | Review focus | +| 검증 결과 | Implementing agent | Paste actual stdout/stderr | diff --git a/agent-task/m-architecture-refactor-foundation/07+06_fleet_polling/PLAN-local-G08.md b/agent-task/m-architecture-refactor-foundation/07+06_fleet_polling/PLAN-local-G08.md new file mode 100644 index 0000000..7b52f4f --- /dev/null +++ b/agent-task/m-architecture-refactor-foundation/07+06_fleet_polling/PLAN-local-G08.md @@ -0,0 +1,263 @@ + + +# PLAN - API fleet-polling + +## 이 파일을 읽는 구현 에이전트에게 + +구현 완료의 마지막 단계는 `CODE_REVIEW-cloud-G08.md`의 구현 에이전트 소유 섹션을 실제 변경 내용과 검증 출력으로 채우는 것이다. 검증을 실행하고, 출력 원문을 붙이고, active 파일은 그대로 둔 채 리뷰 준비 상태를 보고한다. 종료 처리, 로그 아카이브, `complete.log` 작성, task directory 이동은 code-review skill 전용이다. + +구현 중 사용자만 결정할 수 있는 범위 변경, 사용자 소유 외부 환경/secret/서비스 준비, 또는 안전하게 진행할 수 없는 충돌이 생기면 직접 질문하지 말고 `CODE_REVIEW-cloud-G08.md`의 `사용자 리뷰 요청` 섹션을 증거와 함께 채운 뒤 멈춘다. `request_user_input`, 채팅 선택지 제시, `USER_REVIEW.md` 생성, `complete.log` 작성, active 파일 아카이브는 구현 에이전트가 하지 않는다. 후속 에이전트가 명령 재실행이나 산출물 수집으로 해소할 수 있는 검증 공백은 사용자 리뷰 요청 사유가 아니다. + +## 배경 + +현재 `/fleet/status`와 `/fleet/commands`는 registry snapshot을 순차 순회하며 각 Edge에 직접 status/command를 요청한다. Edge 수가 늘면 한 Edge timeout이 전체 응답 지연으로 전파되고, 중복 status 조회가 계속 wire 호출을 만든다. `cp-api-split`으로 handler 파일 경계를 만든 뒤 fleet orchestration을 bounded concurrency, cache, timeout 정책을 가진 service로 분리한다. + +## 사용자 리뷰 요청 흐름 + +구현 중 차단 결정은 active review stub의 `사용자 리뷰 요청` 섹션에 기록한다. 해당 섹션은 `agent-ops/skills/common/_templates/implementation-user-review-request-section.md`와 동일한 형식을 사용한다. 구현 에이전트는 사용자에게 직접 묻지 않으며, code-review가 요청 타당성을 검증하고 실제 `USER_REVIEW.md` 작성 여부를 결정한다. + +## Roadmap Targets + +- Milestone: `agent-roadmap/phase/automation-runtime-bridge/milestones/architecture-refactor-foundation.md` +- Task ids: + - `fleet-polling`: `/fleet/status`와 fleet command 호출을 bounded concurrency, cache, timeout 정책으로 정리한다. +- Completion mode: check-on-pass + +## 분석 결과 + +### 읽은 파일 + +- `agent-ops/rules/project/rules.md` +- `agent-ops/rules/common/rules-roadmap.md` +- `agent-roadmap/current.md` +- `agent-roadmap/phase/automation-runtime-bridge/milestones/architecture-refactor-foundation.md` +- `agent-ops/skills/common/router.md` +- `agent-ops/skills/common/plan/SKILL.md` +- `agent-ops/skills/common/_templates/implementation-user-review-request-section.md` +- `agent-ops/rules/project/domain/control-plane/rules.md` +- `agent-ops/rules/project/domain/client/rules.md` +- `agent-test/local/rules.md` +- `agent-test/local/control-plane-smoke.md` +- `agent-test/local/client-smoke.md` +- `.gitignore` +- `go.mod` +- `apps/control-plane/cmd/control-plane/main.go` +- `apps/control-plane/cmd/control-plane/main_test.go` +- `apps/control-plane/internal/wire/edge_registry.go` +- `apps/control-plane/internal/wire/edge_server.go` +- `apps/client/pubspec.yaml` +- `apps/client/lib/main.dart` +- `apps/client/lib/control_plane_status_client.dart` +- `apps/client/lib/control_plane_status_widgets.dart` +- `apps/client/test/widget_test.dart` + +### 테스트 환경 규칙 + +- `test_env=local`. +- `agent-test/local/rules.md` 존재 및 정독 완료. Control Plane 변경은 `agent-test/local/control-plane-smoke.md`를 baseline으로 사용한다. +- 적용 명령: 변경한 Control Plane 패키지는 `go test ./apps/control-plane/...`를 실행한다. concurrency/cache 동작은 fresh execution이 필요하므로 `go test -count=1 ./apps/control-plane/...`로 고정한다. +- Control Plane-Edge 실제 wire smoke는 registry lifecycle/protocol 자체 변경이 아니므로 이 plan의 필수 검증에서 제외한다. +- `<확인 필요>` 값 없음. agent-test fallback 없음. + +### 테스트 커버리지 공백 + +- 기존 `TestFleetStatusHTTPHandlerCombinesConnectionAndCapabilities`는 online/degraded/offline view와 leak 금지를 검증하지만 concurrency bound와 cache reuse를 검증하지 않는다. +- 기존 `TestFleetCommandsHTTPHandlerFansOutToConnectedEdgesOnly`는 offline skip만 검증하고 command fan-out concurrency나 timeout 전달값을 검증하지 않는다. +- 새 tests가 `max in-flight`, cache hit count, per-call timeout 전달, stable response ordering을 검증해야 한다. + +### 심볼 참조 + +- 제거/이름 변경 예정 없음. +- 이동/확장 예정 call site: + - `registerFleetHandlers`: `apps/control-plane/cmd/control-plane/main.go:183`, `apps/control-plane/cmd/control-plane/main_test.go:746`, `818` + - `fleetEdgeViewFromState`: `apps/control-plane/cmd/control-plane/main.go:510`, `690` + - `edgeStatusRequester`: `apps/control-plane/cmd/control-plane/main.go:376` + - `edgeCommandSender`: `apps/control-plane/cmd/control-plane/main.go:380` + +### 분할 판단 + +- split decision policy를 평가했다. 이 plan은 multi-plan sibling 중 두 번째다. +- shared task group: `agent-task/m-architecture-refactor-foundation/` +- dependency from directory name: predecessor `06_cp_api_split`. +- predecessor status: `agent-task/m-architecture-refactor-foundation/06_cp_api_split/complete.log` missing. 구현 시작 전 `06_cp_api_split` PASS archive 또는 active sibling `complete.log`가 필요하다. +- 이 plan 내부는 단일 plan으로 유지한다. `/fleet/status`와 `/fleet/commands`가 같은 timeout/concurrency policy를 공유해야 하므로 service/options/cache를 한 번에 설계해야 한다. + +### 범위 결정 근거 + +- `cp-api-split`의 파일 경계 정리는 이 plan에서 반복하지 않는다. 선행 plan 완료 결과를 기반으로만 구현한다. +- Edge wire protocol과 `apps/control-plane/internal/wire/**` transport 계약은 변경하지 않는다. +- Flutter client polling UI나 repository retry 정책은 `08_client_state_split` 범위로 남긴다. +- 외부 config/env YAML에 새 옵션을 노출하지 않는다. 기본 policy는 package 내부 default로 두고 tests는 option injection helper를 사용한다. + +### 빌드 등급 + +- build lane: `local-G08`. HTTP API observable latency/error behavior와 concurrency/cache logic을 바꾸는 작업이다. +- review lane: `cloud-G08`. Race/ordering/timeout 회귀를 코드리뷰에서 집중 검증해야 한다. + +## 의존 관계 및 구현 순서 + +- `07+06_fleet_polling`은 `06_cp_api_split` 완료 후 구현한다. +- 만족 조건: `agent-task/m-architecture-refactor-foundation/06_cp_api_split/complete.log` 또는 archive 내 동일 subtask `complete.log`. +- 현재 상태: missing. + +## 구현 체크리스트 + +- [ ] 선행 `06_cp_api_split` 완료 근거를 확인하고, 없으면 `사용자 리뷰 요청`이 아니라 선행 작업 미완료로 구현을 중단 보고한다. +- [ ] fleet status/command orchestration service와 기본 timeout/concurrency/cache option을 추가한다. +- [ ] `/fleet/status`를 bounded concurrency와 fresh status cache를 사용하도록 바꾸고 기존 JSON 계약을 유지한다. +- [ ] `/fleet/commands` fan-out을 bounded concurrency로 바꾸고 offline skip, per-edge result, timeout 전달을 유지한다. +- [ ] concurrency/cache/timeout 회귀 테스트를 추가하고 `gofmt`, `go test -count=1 ./apps/control-plane/...`를 실행한다. +- [ ] CODE_REVIEW-*-G??.md의 구현 에이전트 소유 섹션을 실제 구현 내용과 검증 출력으로 채운다. 이 항목이 완료되기 전에는 구현이 완료된 것이 아니다. + +## [API-1] Fleet Orchestration Service 추가 + +### 문제 + +`registerFleetHandlers`가 handler closure 안에서 registry snapshot을 직접 순회한다. `/fleet/status`는 `apps/control-plane/cmd/control-plane/main.go:507`부터 `511`까지 순차로 `fleetEdgeViewFromState`를 호출하고, `/fleet/commands`는 `532`부터 `548`까지 순차 fan-out한다. + +Before: + +```go +// apps/control-plane/cmd/control-plane/main.go:507 +states := registry.Snapshots() +views := make([]fleetEdgeView, 0, len(states)) +for _, state := range states { + views = append(views, fleetEdgeViewFromState(state, requestStatus)) +} +``` + +### 해결 방법 + +- 새 파일 `apps/control-plane/cmd/control-plane/fleet_orchestrator.go`를 만든다. +- `fleetOptions`를 추가한다: `StatusTimeout`, `CommandTimeout`, `MaxConcurrentStatus`, `MaxConcurrentCommands`, `StatusCacheTTL`, `Now`. +- `newFleetService(registry, requestStatus, sendCommand, options)`를 추가한다. +- `registerFleetHandlers`는 service를 생성해 `Status()`와 `Command()` 결과만 write한다. +- default는 현재 timeout을 유지한다: status `5*time.Second`, command `10*time.Second`. concurrency default는 4, cache TTL은 2초로 둔다. + +### 수정 파일 및 체크리스트 + +- [ ] `apps/control-plane/cmd/control-plane/fleet_orchestrator.go`: service/options/cache 추가. +- [ ] `apps/control-plane/cmd/control-plane/http_fleet_handlers.go`: handler가 service에 위임하도록 변경. +- [ ] `apps/control-plane/cmd/control-plane/main_test.go`: option injection 가능한 test helper를 추가한다. + +### 테스트 작성 + +- 작성: `TestFleetStatusHTTPHandlerUsesConfiguredTimeout`. +- assertion: requester가 받은 timeout이 `fleetOptions.StatusTimeout`과 같다. +- fixture: package-private `registerFleetHandlersWithOptions` 또는 service direct test. + +### 중간 검증 + +```bash +gofmt -w apps/control-plane/cmd/control-plane/fleet_orchestrator.go apps/control-plane/cmd/control-plane/http_fleet_handlers.go apps/control-plane/cmd/control-plane/main_test.go +go test -count=1 ./apps/control-plane/... +``` + +## [API-2] `/fleet/status` bounded concurrency와 cache 적용 + +### 문제 + +`fleetEdgeViewFromState`는 connected Edge마다 `requestStatus(state.EdgeID, 5*time.Second)`를 호출한다. 현재 순차 실행이라 여러 Edge 중 하나가 느리면 전체 response가 지연되고, 바로 이어지는 동일 request도 wire status call을 반복한다. + +Before: + +```go +// apps/control-plane/cmd/control-plane/main.go:707 +resp, err := requestStatus(state.EdgeID, 5*time.Second) +if err != nil { + view.Health = "degraded" + view.Error = err.Error() + return view +} +``` + +### 해결 방법 + +- connected Edge status 요청을 goroutine worker/semaphore로 실행하되 결과 slice는 snapshot order를 유지한다. +- status cache key는 `edgeID`, value는 `fleetEdgeView`와 expiry time으로 둔다. +- cache hit은 connected Edge에만 적용한다. disconnected Edge는 registry state를 즉시 반영해야 하므로 cache를 사용하지 않는다. +- requester error와 proto `Error`는 기존처럼 degraded view로 유지한다. +- raw node snapshots, token/address leak 금지 테스트를 유지한다. + +### 수정 파일 및 체크리스트 + +- [ ] `apps/control-plane/cmd/control-plane/fleet_orchestrator.go`: status cache, semaphore, stable ordering 구현. +- [ ] `apps/control-plane/cmd/control-plane/main_test.go`: max in-flight와 cache hit tests 추가. + +### 테스트 작성 + +- 작성: `TestFleetStatusHTTPHandlerBoundsConcurrentStatusRequests`. + - fixture: 5개 connected Edge, `MaxConcurrentStatus=2`, blocked requester. + - assertion: 관측된 max in-flight가 2 이하이고 response edge 수/순서가 snapshot과 일치한다. +- 작성: `TestFleetStatusHTTPHandlerReusesFreshStatusCache`. + - fixture: `StatusCacheTTL=time.Minute`, 같은 Edge에 대해 연속 두 번 `/fleet/status`. + - assertion: requester call count가 첫 요청 이후 증가하지 않는다. + +### 중간 검증 + +```bash +gofmt -w apps/control-plane/cmd/control-plane/fleet_orchestrator.go apps/control-plane/cmd/control-plane/main_test.go +go test -count=1 ./apps/control-plane/... +``` + +## [API-3] `/fleet/commands` bounded fan-out 적용 + +### 문제 + +`/fleet/commands`는 connected Edge만 대상으로 하지만 `apps/control-plane/cmd/control-plane/main.go:532`부터 `548`까지 순차로 `sendCommand`를 호출한다. 한 Edge timeout이 전체 fan-out을 지연시키며 concurrency 상한이 없다. + +Before: + +```go +// apps/control-plane/cmd/control-plane/main.go:532 +results := make([]edgeCommandResponseView, 0) +for _, state := range registry.Snapshots() { + if !state.Connected { + continue + } + resp, err := sendCommand(state.EdgeID, body.Operation, body.TargetSelector, body.Parameters, 10*time.Second) +``` + +### 해결 방법 + +- connected Edge command dispatch를 semaphore-bound goroutine으로 실행한다. +- response order는 connected Edge snapshot order를 유지한다. +- per-edge error는 기존처럼 `Status: "error"`와 `Error` field로 response에 포함한다. +- `sendCommand == nil`, invalid body, missing operation status codes는 기존 behavior를 유지한다. + +### 수정 파일 및 체크리스트 + +- [ ] `apps/control-plane/cmd/control-plane/fleet_orchestrator.go`: command fan-out helper 추가. +- [ ] `apps/control-plane/cmd/control-plane/http_fleet_handlers.go`: command handler가 helper를 사용하도록 변경. +- [ ] `apps/control-plane/cmd/control-plane/main_test.go`: command concurrency/timeout/order test 추가. + +### 테스트 작성 + +- 작성: `TestFleetCommandsHTTPHandlerBoundsConcurrentFanout`. + - fixture: 5개 connected Edge, 1개 offline Edge, `MaxConcurrentCommands=2`. + - assertion: max in-flight 2 이하, offline Edge 제외, 결과는 connected snapshot order. +- 작성: 기존 `TestFleetCommandsHTTPHandlerFansOutToConnectedEdgesOnly`에 timeout 전달 assertion 추가 또는 별도 test 작성. + +### 중간 검증 + +```bash +gofmt -w apps/control-plane/cmd/control-plane/fleet_orchestrator.go apps/control-plane/cmd/control-plane/http_fleet_handlers.go apps/control-plane/cmd/control-plane/main_test.go +go test -count=1 ./apps/control-plane/... +``` + +## 수정 파일 요약 + +| 파일 | 항목 | +|------|------| +| `apps/control-plane/cmd/control-plane/fleet_orchestrator.go` | API-1, API-2, API-3 | +| `apps/control-plane/cmd/control-plane/http_fleet_handlers.go` | API-1, API-3 | +| `apps/control-plane/cmd/control-plane/main_test.go` | API-1, API-2, API-3 | + +## 최종 검증 + +```bash +gofmt -w apps/control-plane/cmd/control-plane/fleet_orchestrator.go apps/control-plane/cmd/control-plane/http_fleet_handlers.go apps/control-plane/cmd/control-plane/main_test.go +go test -count=1 ./apps/control-plane/... +``` + +모든 코드 변경 완료 후 반드시 `CODE_REVIEW-*-G??.md`의 구현 에이전트 소유 섹션을 채운다. 이 파일 작성이 구현의 마지막 단계다. diff --git a/agent-task/m-architecture-refactor-foundation/08_client_state_split/CODE_REVIEW-cloud-G08.md b/agent-task/m-architecture-refactor-foundation/08_client_state_split/CODE_REVIEW-cloud-G08.md new file mode 100644 index 0000000..ce1eb53 --- /dev/null +++ b/agent-task/m-architecture-refactor-foundation/08_client_state_split/CODE_REVIEW-cloud-G08.md @@ -0,0 +1,170 @@ + + +# Code Review Reference - REFACTOR + +> **[IMPLEMENTING AGENT — READ FIRST] Filling in this file is the mandatory final step of implementation.** +> The task is NOT complete until every implementation-owned section below is filled in. +> Complete the `구현 체크리스트`; the final checklist item is mandatory before saving. +> Fill implementation-owned sections, then stop with active files in place and report ready for review. +> If implementation is blocked by a user-only decision, user-owned external environment prerequisite, or scope conflict, fill `사용자 리뷰 요청` with evidence and stop with active files in place; code-review decides whether to write `USER_REVIEW.md`. Evidence gaps that a follow-up agent can close by rerunning commands or collecting artifacts are normal follow-up issues, not user-review blockers by themselves. +> Do not ask the user directly, present choices in chat, or call `request_user_input` during implementation; record the needed decision in `사용자 리뷰 요청` and stop for code-review. +> Finalization (`코드리뷰 결과`, log rename, `complete.log`, archive moves, `코드리뷰 전용 체크리스트`) is review-agent-only, even after compaction/resume. +> Follow the ownership table at the bottom of this file for which sections you own. + +## 개요 + +date=2026-06-06 +task=m-architecture-refactor-foundation/08_client_state_split, plan=0, tag=REFACTOR + +## Roadmap Targets + +- Milestone: `agent-roadmap/phase/automation-runtime-bridge/milestones/architecture-refactor-foundation.md` +- Task ids: + - `client-state-split`: Flutter client의 bootstrap, status state, DTO, repository, panel widget 경계를 분리하고 Firebase/Mattermost 같은 외부 통합은 선택적으로 초기화되게 한다. +- Completion mode: check-on-pass + +## 이 파일을 읽는 리뷰 에이전트에게 + +> **[REVIEW AGENT ONLY]** 아래 종결 절차는 코드리뷰 에이전트 전용이다. 구현 에이전트는 이 섹션을 실행하지 않는다. + +각 항목의 구현을 실제 소스 파일과 대조하고, `검증 결과` 섹션의 출력이 코드와 일치하는지 확인하세요. +리뷰 완료는 아래 순서까지 끝난 상태를 의미합니다. + +1. 판정을 append한다. +2. `CODE_REVIEW-cloud-G08.md` → `code_review_cloud_G08_N.log`, `PLAN-local-G08.md` → `plan_local_G08_M.log`로 아카이브한다. +3. PASS이면 `complete.log` 작성 후 active task 디렉터리를 `agent-task/archive/YYYY/MM/m-architecture-refactor-foundation/08_client_state_split/`로 이동한다. WARN/FAIL이면 user-review gate를 확인한 뒤 다음 active plan/review 파일 또는 `USER_REVIEW.md`를 작성한다. `USER_REVIEW.md`가 사용자 결정으로 완료/PASS 해소되면 code-review가 `USER_REVIEW.md`를 해소 상태로 갱신하고 `complete.log` 작성 후 archive 이동한다. +4. PASS이고 task group이 `m-architecture-refactor-foundation`이면 완료 이벤트 메타데이터를 보고한다. roadmap 상태 체크와 `update-roadmap` 호출은 런타임 책임이다. +5. 적용 가능한 `코드리뷰 전용 체크리스트` 항목을 최종 `.log` 위치에서 체크한 뒤 보고한다. + +--- + +## 구현 항목별 완료 여부 + +| 항목 | 완료 여부 | +|------|---------| +| [REFACTOR-1] Optional Bootstrap 경계 | [ ] | +| [REFACTOR-2] Status State Controller 분리 | [ ] | +| [REFACTOR-3] DTO와 Repository 파일 분리 | [ ] | +| [REFACTOR-4] Home Shell과 Panel Widget 파일 경계 | [ ] | + +## 구현 체크리스트 + +- [ ] bootstrap을 옵션화해 Firebase/Mattermost 초기화를 기본 on, test/embedded 경로에서는 off로 선택할 수 있게 한다. +- [ ] fleet/status/events selected Edge state를 controller/repository state 경계로 분리하고 stale cache cleanup을 unit test로 검증한다. +- [ ] DTO와 HTTP repository를 별도 파일로 나누고 기존 public import 호환을 유지한다. +- [ ] `ClientHomePage` shell composition과 panel widgets 파일 경계를 나누되 기존 visible behavior를 유지한다. +- [ ] 변경분을 원격 runner에 동기화한 뒤 `cd apps/client && flutter test`, `cd apps/client && flutter analyze --no-fatal-infos`를 실행한다. +- [ ] CODE_REVIEW-*-G??.md의 구현 에이전트 소유 섹션을 실제 구현 내용과 검증 출력으로 채운다. 이 항목이 완료되기 전에는 구현이 완료된 것이 아니다. + +## 코드리뷰 전용 체크리스트 + +> **[REVIEW AGENT ONLY]** 이 체크리스트는 코드리뷰 에이전트만 사용한다. +> 구현 에이전트는 이 섹션을 수정하거나 체크하지 않는다. + +- [ ] `코드리뷰 결과`에 `PASS`, `WARN`, `FAIL` 중 하나의 판정을 append한다. +- [ ] 판정과 `차원별 평가`, Required/Suggested/Nit 분류가 서로 일치한다. +- [ ] active `CODE_REVIEW-*-G??.md`를 `code_review_cloud_G08_N.log`로 아카이브한다. +- [ ] active `PLAN-*-G??.md`를 `plan_local_G08_M.log`로 아카이브한다. +- [ ] `.gitignore`의 Agent-Ops 관리 block이 `agent-task/**/*.md`와 `agent-task/**/*.log`를 unignore하고 `agent-roadmap/current.md`를 ignore하는지 확인한다. +- [ ] PASS이면 `agent-ops/skills/common/code-review/templates/complete-log-template.md` 기준으로 `complete.log`를 작성하고 active `.md` 파일을 남기지 않는다. +- [ ] PASS이면 active task 디렉터리 `agent-task/m-architecture-refactor-foundation/08_client_state_split/`를 `agent-task/archive/YYYY/MM/m-architecture-refactor-foundation/08_client_state_split/`로 이동하고 최종 archive 경로에서 이 체크리스트를 갱신한다. +- [ ] PASS이고 task group이 `m-`이면 런타임이 읽을 완료 이벤트 메타데이터를 보고하고, roadmap 수정이나 `update-roadmap` 직접 호출을 하지 않는다. +- [ ] PASS split 작업이면 이동 후 빈 active parent `agent-task/m-architecture-refactor-foundation/`를 제거하거나, 남은 sibling/file이 있어 유지했다고 확인한다. +- [ ] WARN/FAIL이고 user-review gate가 트리거되지 않았으면 다음 active `PLAN-local-G08.md`와 `CODE_REVIEW-cloud-G08.md`를 작성하고 `complete.log`를 작성하지 않는다. +- [ ] USER_REVIEW이면 `agent-ops/skills/common/code-review/templates/user-review-template.md` 기준으로 `USER_REVIEW.md`를 작성하고 active `PLAN-*.md`, `CODE_REVIEW-*.md`, `complete.log`를 남기지 않는다. +- [ ] USER_REVIEW가 사용자 결정으로 완료/PASS 해소되면 `USER_REVIEW.md`를 해소 상태로 갱신하고 `complete.log`를 작성한 뒤 task directory를 archive로 이동한다. + +## 계획 대비 변경 사항 + +_구현 에이전트가 계획과 다르게 구현한 부분을 이유와 함께 기록한다._ + +## 주요 설계 결정 + +_구현 에이전트가 주요 설계 결정 사항을 기록한다._ + +## 사용자 리뷰 요청 + +_기본값은 `없음`이다. 구현 중 사용자 결정, 사용자 소유 외부 환경/secret/서비스 준비, 또는 계획 범위 변경 없이는 안전하게 진행할 수 없으면 아래 항목을 실제 내용으로 교체하고, 구현을 중단한 뒤 active 파일을 그대로 둔 채 리뷰를 요청한다. 구현 에이전트는 사용자에게 직접 질문하거나 선택지를 제시하거나 `request_user_input`을 호출하지 않는다. 후속 에이전트가 명령 재실행이나 산출물 수집으로 해소할 수 있는 검증 증거 공백만으로는 사용자 리뷰 요청을 작성하지 않는다._ + +- 상태: 없음 +- 사유 유형: 없음 +- 결정 필요: 없음 +- 차단 근거: 없음 +- 실행한 검증/명령: 없음 +- 자동 후속 불가 이유: 없음 +- 재개 조건: 없음 + +## 리뷰어를 위한 체크포인트 + +- production bootstrap 기본값이 Firebase/Mattermost를 계속 초기화하고, test/embedded path에서 외부 init을 끌 수 있는지 확인한다. +- status controller가 selected Edge disappearance와 stale status/events/loading/error cache cleanup을 widget lifecycle 밖에서 검증하는지 확인한다. +- `control_plane_status_client.dart` compatibility export가 기존 imports를 깨지 않는지 확인한다. +- panel 파일 분리 후 UI text, navigation, Runtime command gating, mobile layout tests가 유지되는지 확인한다. +- 원격 runner 검증이 local 변경분 동기화 이후 실행된 증거인지 확인한다. + +## 검증 결과 + +_구현 에이전트가 각 중간 검증 및 최종 검증 명령 실행 후 출력을 여기에 붙여 넣는다._ + +필수 규칙: +- 검증 명령은 고정된 계약이다. 임의로 대체하지 않는다. +- 대체가 필요하면 `계획 대비 변경 사항`에 이유와 대체 명령을 기록한다. +- `검증 결과`에는 실제 stdout/stderr를 붙여 넣는다. +- 사용자 리뷰 요청으로 명령을 끝까지 실행하지 못했다면 `사용자 리뷰 요청`에 실행한 명령, 실제 출력, 미실행 명령의 사유를 기록한다. +- mobile/UI hang, timeout, 또는 2분 무진행은 blind retry를 중단하고 focused rerun 명령과 screenshot/window/UI-tree evidence path를 남기며, 불가능하면 정확한 사유를 남긴다. + +### REFACTOR-1 중간 검증 +```bash +$ cd apps/client && flutter test +(output) +$ cd apps/client && flutter analyze --no-fatal-infos +(output) +``` + +### REFACTOR-2 중간 검증 +```bash +$ cd apps/client && flutter test +(output) +$ cd apps/client && flutter analyze --no-fatal-infos +(output) +``` + +### REFACTOR-3 중간 검증 +```bash +$ cd apps/client && flutter test +(output) +$ cd apps/client && flutter analyze --no-fatal-infos +(output) +``` + +### REFACTOR-4 중간 검증 +```bash +$ cd apps/client && flutter test +(output) +$ cd apps/client && flutter analyze --no-fatal-infos +(output) +``` + +### 최종 검증 +```bash +$ cd apps/client && flutter test +(output) +$ cd apps/client && flutter analyze --no-fatal-infos +(output) +``` + +--- + +## Ownership + +| Section | Owner | Note | +|---------|-------|------| +| Header comment, 개요, 리뷰 에이전트 지시 | Fixed at stub creation | Implementing agent must not modify or execute these | +| Roadmap Targets | Fixed at stub creation | Implementing agent must not modify | +| 구현 항목별 완료 여부 | Implementing agent | Check `[ ]` to `[x]` only | +| 구현 체크리스트 | Implementing agent | Check `[ ]` to `[x]` only | +| 코드리뷰 전용 체크리스트 | Review agent only | Implementing agent must not modify | +| 계획 대비 변경 사항, 주요 설계 결정 | Implementing agent | Replace placeholders | +| 사용자 리뷰 요청 | Implementing agent | Keep `상태: 없음` unless blocked by user-only decision | +| 리뷰어를 위한 체크포인트 | Fixed at stub creation | Review focus | +| 검증 결과 | Implementing agent | Paste actual stdout/stderr | diff --git a/agent-task/m-architecture-refactor-foundation/08_client_state_split/PLAN-local-G08.md b/agent-task/m-architecture-refactor-foundation/08_client_state_split/PLAN-local-G08.md new file mode 100644 index 0000000..123094f --- /dev/null +++ b/agent-task/m-architecture-refactor-foundation/08_client_state_split/PLAN-local-G08.md @@ -0,0 +1,316 @@ + + +# PLAN - REFACTOR client-state-split + +## 이 파일을 읽는 구현 에이전트에게 + +구현 완료의 마지막 단계는 `CODE_REVIEW-cloud-G08.md`의 구현 에이전트 소유 섹션을 실제 변경 내용과 검증 출력으로 채우는 것이다. 검증을 실행하고, 출력 원문을 붙이고, active 파일은 그대로 둔 채 리뷰 준비 상태를 보고한다. 종료 처리, 로그 아카이브, `complete.log` 작성, task directory 이동은 code-review skill 전용이다. + +구현 중 사용자만 결정할 수 있는 범위 변경, 사용자 소유 외부 환경/secret/서비스 준비, 또는 안전하게 진행할 수 없는 충돌이 생기면 직접 질문하지 말고 `CODE_REVIEW-cloud-G08.md`의 `사용자 리뷰 요청` 섹션을 증거와 함께 채운 뒤 멈춘다. `request_user_input`, 채팅 선택지 제시, `USER_REVIEW.md` 생성, `complete.log` 작성, active 파일 아카이브는 구현 에이전트가 하지 않는다. 후속 에이전트가 명령 재실행이나 산출물 수집으로 해소할 수 있는 검증 공백은 사용자 리뷰 요청 사유가 아니다. + +## 배경 + +Flutter client는 `main.dart`가 Firebase/Mattermost bootstrap, wire connection, fleet/status/events state, selected Edge normalization, panel composition을 모두 가진다. `control_plane_status_client.dart`도 DTO와 HTTP repository를 한 파일에 같이 둔다. 이 작업은 외부 통합을 선택 초기화 가능하게 만들고, 상태/DTO/repository/panel 경계를 나눠 client 변경의 blast radius를 줄인다. + +## 사용자 리뷰 요청 흐름 + +구현 중 차단 결정은 active review stub의 `사용자 리뷰 요청` 섹션에 기록한다. 해당 섹션은 `agent-ops/skills/common/_templates/implementation-user-review-request-section.md`와 동일한 형식을 사용한다. 구현 에이전트는 사용자에게 직접 묻지 않으며, code-review가 요청 타당성을 검증하고 실제 `USER_REVIEW.md` 작성 여부를 결정한다. + +## Roadmap Targets + +- Milestone: `agent-roadmap/phase/automation-runtime-bridge/milestones/architecture-refactor-foundation.md` +- Task ids: + - `client-state-split`: Flutter client의 bootstrap, status state, DTO, repository, panel widget 경계를 분리하고 Firebase/Mattermost 같은 외부 통합은 선택적으로 초기화되게 한다. +- Completion mode: check-on-pass + +## 분석 결과 + +### 읽은 파일 + +- `agent-ops/rules/project/rules.md` +- `agent-ops/rules/common/rules-roadmap.md` +- `agent-roadmap/current.md` +- `agent-roadmap/phase/automation-runtime-bridge/milestones/architecture-refactor-foundation.md` +- `agent-ops/skills/common/router.md` +- `agent-ops/skills/common/plan/SKILL.md` +- `agent-ops/skills/common/_templates/implementation-user-review-request-section.md` +- `agent-ops/rules/project/domain/control-plane/rules.md` +- `agent-ops/rules/project/domain/client/rules.md` +- `agent-test/local/rules.md` +- `agent-test/local/control-plane-smoke.md` +- `agent-test/local/client-smoke.md` +- `.gitignore` +- `go.mod` +- `apps/client/pubspec.yaml` +- `apps/client/lib/main.dart` +- `apps/client/lib/control_plane_status_client.dart` +- `apps/client/lib/control_plane_status_widgets.dart` +- `apps/client/test/widget_test.dart` +- `packages/flutter/iop_console/test/iop_console_shell_test.dart` +- `apps/control-plane/cmd/control-plane/main.go` +- `apps/control-plane/cmd/control-plane/main_test.go` + +### 테스트 환경 규칙 + +- `test_env=local`. +- `agent-test/local/rules.md` 존재 및 정독 완료. Client 변경은 `agent-test/local/client-smoke.md`를 baseline으로 사용한다. +- Flutter client 또는 `packages/flutter/iop_console` 검증은 원격 runner `ssh toki@toki-labs.com`의 `/Users/toki/agent-work/iop` 기준이다. 현재 workspace 변경분이 원격 checkout에 동기화되지 않았으면 원격 검증 완료로 보지 않는다. +- 적용 명령: `cd apps/client && flutter test`, `cd apps/client && flutter analyze --no-fatal-infos`. +- `packages/flutter/iop_console` 자체 API는 변경하지 않을 계획이므로 `cd packages/flutter/iop_console && flutter test`는 필수에서 제외한다. 구현 중 package API/import가 바뀌면 계획 대비 변경 사항에 기록하고 해당 명령을 추가 실행한다. +- `<확인 필요>` 값 없음. agent-test fallback 없음. + +### 테스트 커버리지 공백 + +- 기존 `apps/client/test/widget_test.dart`는 app rendering, Edge/Nodes/Logs/Runtime panel behavior, selected Edge disappearance, mobile layout을 widget 수준에서 검증한다. +- bootstrap optional init은 현재 테스트가 없다. Firebase/Mattermost init을 선택적으로 끄는 unit/widget test를 추가해야 한다. +- 상태 분리를 `ChangeNotifier`/controller로 만들면 selected Edge disappearance와 stale cache cleanup을 widget test 밖의 unit test로 추가해야 한다. +- DTO/repository 파일 이동은 public class명을 유지하면 기존 widget fake repository가 회귀 검증을 맡는다. + +### 심볼 참조 + +- 제거/이름 변경 예정 없음. 파일 이동 후 import 변경 예정. +- 이동 예정 call site: + - `IopClientApp`: `apps/client/lib/main.dart:69`, `apps/client/test/widget_test.dart:380`, `410`, `425`, `446`, `485`, `515`, `544`, `617`, `742`, `779`, `849` + - `ClientHomePage`: `apps/client/lib/main.dart:95`, `104` + - `ControlPlaneStatusRepository`: `apps/client/lib/main.dart:72`, `107`, `125`, `apps/client/lib/control_plane_status_widgets.dart:822`, `apps/client/test/widget_test.dart:66` + - DTO classes in `control_plane_status_client.dart`: existing widget tests import `package:iop_client/control_plane_status_client.dart`. + +### 분할 판단 + +- split decision policy를 평가했다. cp-client Epic은 multi-plan으로 분리한다. +- shared task group: `agent-task/m-architecture-refactor-foundation/` +- sibling subtask directories: + - `06_cp_api_split`: Control Plane API file boundary. + - `07+06_fleet_polling`: depends on `06_cp_api_split`. + - `08_client_state_split`: 이 plan. 선행 의존성 없음. +- 이 plan 자체는 단일 plan으로 유지한다. bootstrap, state controller, DTO/repository imports, panel composition이 서로 compile-time import graph를 공유해 한 번에 맞춰야 한다. + +### 범위 결정 근거 + +- Control Plane Go server, fleet polling policy, wire protocol은 변경하지 않는다. +- `packages/flutter/iop_console` API와 product shell UX는 변경하지 않는다. +- generated proto files under `apps/client/lib/gen/**`는 변경하지 않는다. +- Mattermost plugin implementation 내부는 optional init boundary에 필요한 import 위치 변경 외에는 변경하지 않는다. + +### 빌드 등급 + +- build lane: `local-G08`. Flutter app import graph와 widget state ownership을 바꾸는 넓은 refactor다. +- review lane: `cloud-G08`. UI behavior, optional external init, remote runner verification evidence가 필요하다. + +## 구현 체크리스트 + +- [ ] bootstrap을 옵션화해 Firebase/Mattermost 초기화를 기본 on, test/embedded 경로에서는 off로 선택할 수 있게 한다. +- [ ] fleet/status/events selected Edge state를 controller/repository state 경계로 분리하고 stale cache cleanup을 unit test로 검증한다. +- [ ] DTO와 HTTP repository를 별도 파일로 나누고 기존 public import 호환을 유지한다. +- [ ] `ClientHomePage` shell composition과 panel widgets 파일 경계를 나누되 기존 visible behavior를 유지한다. +- [ ] 변경분을 원격 runner에 동기화한 뒤 `cd apps/client && flutter test`, `cd apps/client && flutter analyze --no-fatal-infos`를 실행한다. +- [ ] CODE_REVIEW-*-G??.md의 구현 에이전트 소유 섹션을 실제 구현 내용과 검증 출력으로 채운다. 이 항목이 완료되기 전에는 구현이 완료된 것이 아니다. + +## [REFACTOR-1] Optional Bootstrap 경계 + +### 문제 + +`apps/client/lib/main.dart:57`부터 `66`까지 bootstrap이 fullscreen, Firebase, Mattermost host init, `runApp`을 고정 순서로 직접 실행한다. 외부 통합을 끌 수 없어 테스트/embedded 경로에서 Firebase 또는 Mattermost 준비 여부가 app bootstrap과 강하게 결합된다. + +Before: + +```dart +// apps/client/lib/main.dart:57 +Future bootstrapIopClient() async { + await applyFullscreenMode(); + await Firebase.initializeApp(); + await _mattermostHost.initialize(); +} +``` + +### 해결 방법 + +- 새 파일 `apps/client/lib/client_bootstrap.dart`를 만든다. +- `IopClientBootstrapOptions`를 추가한다: `initializeFirebase`, `initializeMattermost`, `mattermostHost`. +- production `main()`은 기존처럼 default options를 사용해 Firebase/Mattermost를 초기화한다. +- test/embedded path는 `runIopClient(options: const IopClientBootstrapOptions(initializeFirebase: false, initializeMattermost: false))` 형태로 끌 수 있게 한다. +- 기존 `IopClientApp(mattermostHost: ...)` injection은 유지한다. + +### 수정 파일 및 체크리스트 + +- [ ] `apps/client/lib/main.dart`: production entrypoint만 남기고 bootstrap helper를 이동한다. +- [ ] `apps/client/lib/client_bootstrap.dart`: options/default host/bootstrap/run helper 추가. +- [ ] `apps/client/test/widget_test.dart`: optional bootstrap test 추가 또는 기존 direct `IopClientApp` tests가 영향 없음을 확인한다. + +### 테스트 작성 + +- 작성: `apps/client/test/widget_test.dart`, `runIopClient can skip external integrations` 또는 별도 `client_bootstrap_test.dart`. +- assertion: Firebase/Mattermost init off options가 `IopClientApp` construction path를 막지 않는다. +- fixture: fake bootstrap hook 또는 no-op Mattermost host wrapper. 실제 Firebase secret/service를 요구하지 않는다. + +### 중간 검증 + +```bash +cd apps/client && flutter test +cd apps/client && flutter analyze --no-fatal-infos +``` + +## [REFACTOR-2] Status State Controller 분리 + +### 문제 + +`_ClientHomePageState`가 `apps/client/lib/main.dart:120`부터 `139`까지 Edge/status/events state map을 들고, `196`부터 `294`까지 fetch/selection/cache cleanup을 직접 수행한다. UI widget lifecycle과 repository state transition이 결합되어 stale selection 관련 회귀가 widget test에만 의존한다. + +Before: + +```dart +// apps/client/lib/main.dart:196 +Future _fetchEdges() async { + if (!mounted) return; + setState(() { + _loadingEdges = true; + _edgesError = null; + }); +``` + +### 해결 방법 + +- 새 파일 `apps/client/lib/control_plane_status_controller.dart`를 만든다. +- `ControlPlaneStatusController extends ChangeNotifier`를 추가한다. +- controller가 `edges`, `selectedEdgeId`, `edgeStatuses`, `edgeEvents`, loading/error state와 `fetchEdges`, `selectEdge`, `refreshSelectedStatus`, `refreshSelectedEvents`를 소유한다. +- `ClientHomePage`는 controller를 생성/dispose하고 `AnimatedBuilder` 또는 `ListenableBuilder`로 panels에 state를 전달한다. +- selected Edge가 사라질 때 stale status/events/loading/error cache를 제거하는 기존 동작을 controller unit test로 고정한다. + +### 수정 파일 및 체크리스트 + +- [ ] `apps/client/lib/main.dart` 또는 새 `client_home_page.dart`: widget state를 controller delegation으로 축소한다. +- [ ] `apps/client/lib/control_plane_status_controller.dart`: state machine 추가. +- [ ] `apps/client/test/control_plane_status_controller_test.dart`: selected Edge disappearance/stale cache cleanup tests 추가. +- [ ] `apps/client/test/widget_test.dart`: 기존 Edge/Nodes/Logs/Runtime behavior tests 유지. + +### 테스트 작성 + +- 작성: `TestWidgetsFlutterBinding.ensureInitialized()`가 필요 없는 Dart unit style test. +- test name: `removes stale selected edge caches when fleet refresh drops edge`. +- assertion: 이전 selected Edge의 status/event/loading/error maps가 제거되고 새 첫 Edge가 선택된다. +- fixture: fake `ControlPlaneStatusRepository`. + +### 중간 검증 + +```bash +cd apps/client && flutter test +cd apps/client && flutter analyze --no-fatal-infos +``` + +## [REFACTOR-3] DTO와 Repository 파일 분리 + +### 문제 + +`apps/client/lib/control_plane_status_client.dart:4`부터 `383`까지 DTO/view classes가 있고, `385`부터 `487`까지 repository interface와 HTTP implementation이 같은 파일에 있다. Widget tests와 UI panels가 DTO와 transport implementation을 같은 import로 가져와 경계가 흐리다. + +Before: + +```dart +// apps/client/lib/control_plane_status_client.dart:385 +abstract class ControlPlaneStatusRepository { + Future> fetchEdges(); + Future fetchEdgeStatus(String edgeId); + Future> fetchEdgeEvents(String edgeId); +``` + +### 해결 방법 + +- 새 파일 `apps/client/lib/control_plane_status_dto.dart`에 DTO/view classes를 이동한다. +- 새 파일 `apps/client/lib/control_plane_status_repository.dart`에 repository interface와 HTTP implementation을 이동한다. +- 기존 `control_plane_status_client.dart`는 compatibility barrel로 남겨 `export 'control_plane_status_dto.dart'; export 'control_plane_status_repository.dart';`를 제공한다. +- existing tests/imports는 필요 최소 변경만 한다. + +### 수정 파일 및 체크리스트 + +- [ ] `apps/client/lib/control_plane_status_dto.dart`: DTO/view classes 추가. +- [ ] `apps/client/lib/control_plane_status_repository.dart`: repository interface/HTTP implementation 추가. +- [ ] `apps/client/lib/control_plane_status_client.dart`: compatibility export로 축소. +- [ ] `apps/client/lib/main.dart`, `control_plane_status_widgets.dart`, tests: import 경로를 필요한 만큼 정리한다. + +### 테스트 작성 + +- 새 테스트 작성 없음. 기존 `FakeControlPlaneStatusRepository`와 widget tests가 public class/import compatibility를 검증한다. + +### 중간 검증 + +```bash +cd apps/client && flutter test +cd apps/client && flutter analyze --no-fatal-infos +``` + +## [REFACTOR-4] Home Shell과 Panel Widget 파일 경계 + +### 문제 + +`apps/client/lib/main.dart:340`부터 `414`까지 `IopConsoleShell` composition과 panel state binding을 직접 수행한다. `apps/client/lib/control_plane_status_widgets.dart`는 `EdgesPanel`, `NodesPanel`, `ExecutionLogsPanel`, `RuntimePanel`까지 1506 lines를 포함한다. + +Before: + +```dart +// apps/client/lib/main.dart:349 +return IopConsoleShell( + config: config, + capabilities: iopDefaultCapabilityPack, + overview: IopConsoleOverview( +``` + +### 해결 방법 + +- 새 파일 `apps/client/lib/client_home_page.dart`를 만들고 `ClientHomePage`와 shell composition을 이동한다. +- `control_plane_status_widgets.dart`는 compatibility export barrel로 남긴다. +- panel files를 분리한다: + - `apps/client/lib/widgets/edges_panel.dart` + - `apps/client/lib/widgets/nodes_panel.dart` + - `apps/client/lib/widgets/execution_logs_panel.dart` + - `apps/client/lib/widgets/runtime_panel.dart` +- public widget class명은 유지한다. +- UI text/behavior는 변경하지 않는다. + +### 수정 파일 및 체크리스트 + +- [ ] `apps/client/lib/main.dart`: app root와 production entrypoint만 남긴다. +- [ ] `apps/client/lib/client_home_page.dart`: shell composition 추가. +- [ ] `apps/client/lib/control_plane_status_widgets.dart`: exports로 축소. +- [ ] `apps/client/lib/widgets/*.dart`: panels 이동. +- [ ] `apps/client/test/widget_test.dart`: 기존 visible behavior tests 유지. + +### 테스트 작성 + +- 새 widget test 작성 없음. 기존 `widget_test.dart`의 rendering, panel navigation, selected Edge disappearance, runtime command gating, mobile layout 검증이 회귀를 담당한다. + +### 중간 검증 + +```bash +cd apps/client && flutter test +cd apps/client && flutter analyze --no-fatal-infos +``` + +## 수정 파일 요약 + +| 파일 | 항목 | +|------|------| +| `apps/client/lib/main.dart` | REFACTOR-1, REFACTOR-2, REFACTOR-4 | +| `apps/client/lib/client_bootstrap.dart` | REFACTOR-1 | +| `apps/client/lib/client_home_page.dart` | REFACTOR-2, REFACTOR-4 | +| `apps/client/lib/control_plane_status_controller.dart` | REFACTOR-2 | +| `apps/client/lib/control_plane_status_dto.dart` | REFACTOR-3 | +| `apps/client/lib/control_plane_status_repository.dart` | REFACTOR-3 | +| `apps/client/lib/control_plane_status_client.dart` | REFACTOR-3 | +| `apps/client/lib/control_plane_status_widgets.dart` | REFACTOR-4 | +| `apps/client/lib/widgets/edges_panel.dart` | REFACTOR-4 | +| `apps/client/lib/widgets/nodes_panel.dart` | REFACTOR-4 | +| `apps/client/lib/widgets/execution_logs_panel.dart` | REFACTOR-4 | +| `apps/client/lib/widgets/runtime_panel.dart` | REFACTOR-4 | +| `apps/client/test/control_plane_status_controller_test.dart` | REFACTOR-2 | +| `apps/client/test/widget_test.dart` | REFACTOR-1, REFACTOR-3, REFACTOR-4 | + +## 최종 검증 + +원격 runner 기준이며, local 변경분을 `/Users/toki/agent-work/iop`에 동기화한 뒤 실행한다. 동기화하지 못했으면 검증을 완료로 표시하지 말고 실제 차단 사유를 `CODE_REVIEW-cloud-G08.md`에 기록한다. + +```bash +cd apps/client && flutter test +cd apps/client && flutter analyze --no-fatal-infos +``` + +모든 코드 변경 완료 후 반드시 `CODE_REVIEW-*-G??.md`의 구현 에이전트 소유 섹션을 채운다. 이 파일 작성이 구현의 마지막 단계다. diff --git a/apps/control-plane/cmd/control-plane/http_edge_handlers.go b/apps/control-plane/cmd/control-plane/http_edge_handlers.go new file mode 100644 index 0000000..b1ef4d9 --- /dev/null +++ b/apps/control-plane/cmd/control-plane/http_edge_handlers.go @@ -0,0 +1,149 @@ +package main + +import ( + "encoding/json" + "net/http" + "strings" + "time" + + iop "iop/proto/gen/iop" + + "iop/apps/control-plane/internal/wire" +) + +// edgeStatusRequester asks a connected Edge for its Edge-owned node snapshot. +type edgeStatusRequester func(edgeID string, timeout time.Duration) (*iop.EdgeStatusResponse, error) + +// edgeCommandSender dispatches a command to a connected Edge and returns its +// typed response. +type edgeCommandSender func(edgeID, operation, targetSelector string, parameters map[string]string, timeout time.Duration) (*iop.EdgeCommandResponse, error) + +func registerEdgeRegistryHandlers(mux *http.ServeMux, registry *wire.EdgeRegistry, requestStatus edgeStatusRequester, sendCommand edgeCommandSender) { + mux.HandleFunc("/edges", func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != "/edges" { + http.NotFound(w, r) + return + } + if r.Method != http.MethodGet { + methodNotAllowed(w, http.MethodGet) + return + } + states := registry.Snapshots() + views := make([]edgeRegistryView, 0, len(states)) + for _, state := range states { + views = append(views, edgeRegistryViewFromState(state)) + } + writeJSON(w, http.StatusOK, edgeRegistryResponse{Edges: views}) + }) + mux.HandleFunc("/edges/", func(w http.ResponseWriter, r *http.Request) { + edgePath := strings.TrimPrefix(r.URL.Path, "/edges/") + edgeID, rest, hasRest := strings.Cut(edgePath, "/") + if edgeID == "" { + http.NotFound(w, r) + return + } + if !hasRest { + if r.Method != http.MethodGet { + methodNotAllowed(w, http.MethodGet) + return + } + state, ok := registry.Snapshot(edgeID) + if !ok { + http.NotFound(w, r) + return + } + writeJSON(w, http.StatusOK, edgeRegistryViewFromState(state)) + return + } + switch rest { + case "status": + if r.Method != http.MethodGet { + methodNotAllowed(w, http.MethodGet) + return + } + if _, ok := registry.Snapshot(edgeID); !ok { + http.NotFound(w, r) + return + } + resp, err := requestStatus(edgeID, 5*time.Second) + if err != nil { + writeJSON(w, http.StatusBadGateway, map[string]string{"error": err.Error()}) + return + } + writeJSON(w, http.StatusOK, edgeStatusResponseViewFromProto(resp)) + case "events": + if r.Method != http.MethodGet { + methodNotAllowed(w, http.MethodGet) + return + } + if _, ok := registry.Snapshot(edgeID); !ok { + http.NotFound(w, r) + return + } + records := registry.NodeEvents(edgeID, r.URL.Query().Get("node_id")) + views := make([]edgeNodeEventView, 0, len(records)) + for _, record := range records { + views = append(views, edgeNodeEventViewFromRecord(record)) + } + writeJSON(w, http.StatusOK, edgeNodeEventsResponse{EdgeID: edgeID, Events: views}) + case "operations": + if r.Method != http.MethodGet { + methodNotAllowed(w, http.MethodGet) + return + } + if _, ok := registry.Snapshot(edgeID); !ok { + http.NotFound(w, r) + return + } + records := registry.Commands(edgeID) + views := make([]edgeCommandRecordView, 0, len(records)) + for _, record := range records { + views = append(views, edgeCommandRecordViewFromRecord(record)) + } + writeJSON(w, http.StatusOK, edgeOperationsResponse{EdgeID: edgeID, Operations: views}) + case "commands": + if r.Method != http.MethodPost { + methodNotAllowed(w, http.MethodPost) + return + } + handleEdgeCommandPost(w, r, edgeID, sendCommand) + default: + http.NotFound(w, r) + } + }) +} + +// handleEdgeCommandPost decodes a command request body and dispatches it to a +// single target Edge. A not-connected Edge yields a 502 with the wire error. +func handleEdgeCommandPost(w http.ResponseWriter, r *http.Request, edgeID string, sendCommand edgeCommandSender) { + var body edgeCommandRequestBody + if err := json.NewDecoder(r.Body).Decode(&body); err != nil { + writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid request body"}) + return + } + if body.Operation == "" { + writeJSON(w, http.StatusBadRequest, map[string]string{"error": "operation is required"}) + return + } + if sendCommand == nil { + writeJSON(w, http.StatusServiceUnavailable, map[string]string{"error": "command dispatch is not configured"}) + return + } + resp, err := sendCommand(edgeID, body.Operation, body.TargetSelector, body.Parameters, 10*time.Second) + if err != nil { + writeJSON(w, http.StatusBadGateway, map[string]string{"error": err.Error()}) + return + } + writeJSON(w, http.StatusAccepted, edgeCommandResponseViewFromProto(resp)) +} + +func methodNotAllowed(w http.ResponseWriter, allow ...string) { + w.Header().Set("Allow", strings.Join(allow, ", ")) + http.Error(w, "method not allowed", http.StatusMethodNotAllowed) +} + +func writeJSON(w http.ResponseWriter, status int, v any) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(status) + _ = json.NewEncoder(w).Encode(v) +} diff --git a/apps/control-plane/cmd/control-plane/http_fleet_handlers.go b/apps/control-plane/cmd/control-plane/http_fleet_handlers.go new file mode 100644 index 0000000..a639fc8 --- /dev/null +++ b/apps/control-plane/cmd/control-plane/http_fleet_handlers.go @@ -0,0 +1,60 @@ +package main + +import ( + "encoding/json" + "net/http" + "time" + + "iop/apps/control-plane/internal/wire" +) + +func registerFleetHandlers(mux *http.ServeMux, registry *wire.EdgeRegistry, requestStatus edgeStatusRequester, sendCommand edgeCommandSender) { + mux.HandleFunc("/fleet/status", func(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodGet { + methodNotAllowed(w, http.MethodGet) + return + } + states := registry.Snapshots() + views := make([]fleetEdgeView, 0, len(states)) + for _, state := range states { + views = append(views, fleetEdgeViewFromState(state, requestStatus)) + } + writeJSON(w, http.StatusOK, fleetStatusResponse{GeneratedAt: time.Now().UTC(), Edges: views}) + }) + mux.HandleFunc("/fleet/commands", func(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodPost { + methodNotAllowed(w, http.MethodPost) + return + } + var body edgeCommandRequestBody + if err := json.NewDecoder(r.Body).Decode(&body); err != nil { + writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid request body"}) + return + } + if body.Operation == "" { + writeJSON(w, http.StatusBadRequest, map[string]string{"error": "operation is required"}) + return + } + if sendCommand == nil { + writeJSON(w, http.StatusServiceUnavailable, map[string]string{"error": "command dispatch is not configured"}) + return + } + results := make([]edgeCommandResponseView, 0) + for _, state := range registry.Snapshots() { + if !state.Connected { + continue + } + resp, err := sendCommand(state.EdgeID, body.Operation, body.TargetSelector, body.Parameters, 10*time.Second) + if err != nil { + results = append(results, edgeCommandResponseView{ + EdgeID: state.EdgeID, + Status: "error", + Error: err.Error(), + }) + continue + } + results = append(results, edgeCommandResponseViewFromProto(resp)) + } + writeJSON(w, http.StatusAccepted, fleetCommandResponse{Operation: body.Operation, Results: results}) + }) +} diff --git a/apps/control-plane/cmd/control-plane/http_views.go b/apps/control-plane/cmd/control-plane/http_views.go new file mode 100644 index 0000000..b5bb70b --- /dev/null +++ b/apps/control-plane/cmd/control-plane/http_views.go @@ -0,0 +1,345 @@ +package main + +import ( + "time" + + iop "iop/proto/gen/iop" + + "iop/apps/control-plane/internal/wire" +) + +// ── DTO structs ────────────────────────────────────────────────────────────── + +type edgeRegistryResponse struct { + Edges []edgeRegistryView `json:"edges"` +} + +type edgeRegistryView struct { + EdgeID string `json:"edge_id"` + EdgeName string `json:"edge_name"` + Version string `json:"version"` + Capabilities []string `json:"capabilities"` + Protocol string `json:"protocol"` + Connected bool `json:"connected"` + LastSeen time.Time `json:"last_seen"` +} + +type edgeNodeEventsResponse struct { + EdgeID string `json:"edge_id"` + Events []edgeNodeEventView `json:"events"` +} + +type edgeNodeEventView struct { + EdgeID string `json:"edge_id"` + EventID string `json:"event_id"` + Type string `json:"type"` + Source string `json:"source"` + NodeID string `json:"node_id"` + Alias string `json:"alias"` + Reason string `json:"reason"` + Timestamp time.Time `json:"timestamp"` + ReceivedAt time.Time `json:"received_at"` + Metadata map[string]string `json:"metadata,omitempty"` +} + +type edgeStatusResponseView struct { + RequestID string `json:"request_id"` + EdgeID string `json:"edge_id"` + EdgeName string `json:"edge_name"` + ObservedTimeUnixNano int64 `json:"observed_time_unix_nano"` + Nodes []edgeNodeSnapshotView `json:"nodes"` + Capabilities []edgeCapabilitySummaryView `json:"capabilities,omitempty"` + DomainAgents []edgeDomainAgentSummaryView `json:"domain_agents,omitempty"` + Metadata map[string]string `json:"metadata,omitempty"` + Error string `json:"error,omitempty"` +} + +type edgeCapabilitySummaryView struct { + Kind string `json:"kind"` + Available bool `json:"available"` + Status string `json:"status,omitempty"` + Summary string `json:"summary,omitempty"` +} + +type edgeDomainAgentSummaryView struct { + AgentKind string `json:"agent_kind"` + Available bool `json:"available"` + LifecycleState string `json:"lifecycle_state,omitempty"` + ActiveCommandID string `json:"active_command_id,omitempty"` + Summary string `json:"summary,omitempty"` +} + +// edgeCommandRequestBody is the JSON body for POST /edges/{id}/commands and +// POST /fleet/commands. It carries the surface-neutral command intent only. +type edgeCommandRequestBody struct { + Operation string `json:"operation"` + TargetSelector string `json:"target_selector,omitempty"` + Parameters map[string]string `json:"parameters,omitempty"` +} + +type edgeCommandResponseView struct { + RequestID string `json:"request_id,omitempty"` + CommandID string `json:"command_id"` + EdgeID string `json:"edge_id"` + Status string `json:"status"` + Summary string `json:"summary,omitempty"` + Error string `json:"error,omitempty"` +} + +type edgeOperationsResponse struct { + EdgeID string `json:"edge_id"` + Operations []edgeCommandRecordView `json:"operations"` +} + +type edgeCommandRecordView struct { + EdgeID string `json:"edge_id"` + CommandID string `json:"command_id"` + Operation string `json:"operation,omitempty"` + TargetSelector string `json:"target_selector,omitempty"` + Status string `json:"status"` + Summary string `json:"summary,omitempty"` + Error string `json:"error,omitempty"` + CreatedAt time.Time `json:"created_at"` + UpdatedAt time.Time `json:"updated_at"` + Events []edgeCommandEventView `json:"events,omitempty"` +} + +type edgeCommandEventView struct { + Phase string `json:"phase,omitempty"` + Summary string `json:"summary,omitempty"` + OccurredAt time.Time `json:"occurred_at,omitempty"` + ReceivedAt time.Time `json:"received_at"` +} + +type fleetStatusResponse struct { + GeneratedAt time.Time `json:"generated_at"` + Edges []fleetEdgeView `json:"edges"` +} + +type fleetEdgeView struct { + EdgeID string `json:"edge_id"` + EdgeName string `json:"edge_name,omitempty"` + Version string `json:"version,omitempty"` + Protocol string `json:"protocol,omitempty"` + Connected bool `json:"connected"` + Health string `json:"health"` + LastSeen time.Time `json:"last_seen"` + NodeCount int `json:"node_count"` + Capabilities []edgeCapabilitySummaryView `json:"capabilities,omitempty"` + DomainAgents []edgeDomainAgentSummaryView `json:"domain_agents,omitempty"` + Error string `json:"error,omitempty"` +} + +type fleetCommandResponse struct { + Operation string `json:"operation"` + Results []edgeCommandResponseView `json:"results"` +} + +type edgeNodeSnapshotView struct { + NodeID string `json:"node_id"` + Alias string `json:"alias"` + Label string `json:"label"` + Connected bool `json:"connected"` + Config *nodeConfigSummaryView `json:"config,omitempty"` +} + +type nodeConfigSummaryView struct { + Adapters []adapterSummaryView `json:"adapters"` + Concurrency int32 `json:"concurrency"` +} + +type adapterSummaryView struct { + Type string `json:"type"` + Enabled bool `json:"enabled"` +} + +// ── Transformation functions ───────────────────────────────────────────────── + +func newNodeConfigSummaryView(payload *iop.NodeConfigPayload) *nodeConfigSummaryView { + if payload == nil { + return nil + } + var adapters []adapterSummaryView + for _, a := range payload.GetAdapters() { + adapters = append(adapters, adapterSummaryView{ + Type: a.GetType(), + Enabled: a.GetEnabled(), + }) + } + concurrency := int32(0) + if payload.GetRuntime() != nil { + concurrency = payload.GetRuntime().GetConcurrency() + } + return &nodeConfigSummaryView{ + Adapters: adapters, + Concurrency: concurrency, + } +} + +func edgeRegistryViewFromState(state wire.EdgeConnectionState) edgeRegistryView { + return edgeRegistryView{ + EdgeID: state.EdgeID, + EdgeName: state.EdgeName, + Version: state.Version, + Capabilities: append([]string(nil), state.Capabilities...), + Protocol: state.Protocol, + Connected: state.Connected, + LastSeen: state.LastSeen, + } +} + +func edgeStatusResponseViewFromProto(resp *iop.EdgeStatusResponse) edgeStatusResponseView { + nodes := make([]edgeNodeSnapshotView, 0, len(resp.GetNodes())) + for _, n := range resp.GetNodes() { + nodes = append(nodes, edgeNodeSnapshotView{ + NodeID: n.GetNodeId(), + Alias: n.GetAlias(), + Label: n.GetLabel(), + Connected: n.GetConnected(), + Config: newNodeConfigSummaryView(n.GetConfig()), + }) + } + return edgeStatusResponseView{ + RequestID: resp.GetRequestId(), + EdgeID: resp.GetEdgeId(), + EdgeName: resp.GetEdgeName(), + ObservedTimeUnixNano: resp.GetObservedTimeUnixNano(), + Nodes: nodes, + Capabilities: edgeCapabilityViews(resp.GetCapabilities()), + DomainAgents: edgeDomainAgentViews(resp.GetDomainAgents()), + Metadata: resp.GetMetadata(), + Error: resp.GetError(), + } +} + +func edgeCapabilityViews(caps []*iop.EdgeCapabilitySummary) []edgeCapabilitySummaryView { + if len(caps) == 0 { + return nil + } + views := make([]edgeCapabilitySummaryView, 0, len(caps)) + for _, c := range caps { + views = append(views, edgeCapabilitySummaryView{ + Kind: c.GetKind(), + Available: c.GetAvailable(), + Status: c.GetStatus(), + Summary: c.GetSummary(), + }) + } + return views +} + +func edgeDomainAgentViews(agents []*iop.EdgeDomainAgentSummary) []edgeDomainAgentSummaryView { + if len(agents) == 0 { + return nil + } + views := make([]edgeDomainAgentSummaryView, 0, len(agents)) + for _, a := range agents { + views = append(views, edgeDomainAgentSummaryView{ + AgentKind: a.GetAgentKind(), + Available: a.GetAvailable(), + LifecycleState: a.GetLifecycleState(), + ActiveCommandID: a.GetActiveCommandId(), + Summary: a.GetSummary(), + }) + } + return views +} + +func edgeCommandResponseViewFromProto(resp *iop.EdgeCommandResponse) edgeCommandResponseView { + return edgeCommandResponseView{ + RequestID: resp.GetRequestId(), + CommandID: resp.GetCommandId(), + EdgeID: resp.GetEdgeId(), + Status: resp.GetStatus(), + Summary: resp.GetSummary(), + Error: resp.GetError(), + } +} + +func edgeCommandRecordViewFromRecord(record wire.EdgeCommandRecord) edgeCommandRecordView { + view := edgeCommandRecordView{ + EdgeID: record.EdgeID, + CommandID: record.CommandID, + Operation: record.Operation, + TargetSelector: record.TargetSelector, + Status: record.Status, + Summary: record.Summary, + Error: record.Error, + CreatedAt: record.CreatedAt, + UpdatedAt: record.UpdatedAt, + } + if len(record.Events) > 0 { + view.Events = make([]edgeCommandEventView, 0, len(record.Events)) + for _, e := range record.Events { + view.Events = append(view.Events, edgeCommandEventView{ + Phase: e.Phase, + Summary: e.Summary, + OccurredAt: e.OccurredAt, + ReceivedAt: e.ReceivedAt, + }) + } + } + return view +} + +func edgeNodeEventViewFromRecord(record wire.EdgeNodeEventRecord) edgeNodeEventView { + event := record.Event + view := edgeNodeEventView{ + EdgeID: record.EdgeID, + ReceivedAt: record.ReceivedAt, + } + if event == nil { + return view + } + if event.GetTimestamp() != 0 { + view.Timestamp = time.Unix(0, event.GetTimestamp()).UTC() + } + view.EventID = event.GetEventId() + view.Type = event.GetType() + view.Source = event.GetSource() + view.NodeID = event.GetNodeId() + view.Alias = event.GetAlias() + view.Reason = event.GetReason() + if metadata := event.GetMetadata(); len(metadata) > 0 { + view.Metadata = make(map[string]string, len(metadata)) + for k, v := range metadata { + view.Metadata[k] = v + } + } + return view +} + +func fleetEdgeViewFromState(state wire.EdgeConnectionState, requestStatus edgeStatusRequester) fleetEdgeView { + view := fleetEdgeView{ + EdgeID: state.EdgeID, + EdgeName: state.EdgeName, + Version: state.Version, + Protocol: state.Protocol, + Connected: state.Connected, + LastSeen: state.LastSeen, + } + if !state.Connected { + view.Health = "offline" + return view + } + if requestStatus == nil { + view.Health = "online" + return view + } + resp, err := requestStatus(state.EdgeID, 5*time.Second) + if err != nil { + view.Health = "degraded" + view.Error = err.Error() + return view + } + view.NodeCount = len(resp.GetNodes()) + view.Capabilities = edgeCapabilityViews(resp.GetCapabilities()) + view.DomainAgents = edgeDomainAgentViews(resp.GetDomainAgents()) + if resp.GetError() != "" { + view.Health = "degraded" + view.Error = resp.GetError() + return view + } + view.Health = "online" + return view +} diff --git a/apps/control-plane/cmd/control-plane/main.go b/apps/control-plane/cmd/control-plane/main.go index 284a05b..6e01729 100644 --- a/apps/control-plane/cmd/control-plane/main.go +++ b/apps/control-plane/cmd/control-plane/main.go @@ -2,22 +2,17 @@ package main import ( "context" - "encoding/json" "fmt" - "net/http" "net/url" "os" "os/signal" "strings" - "time" "github.com/spf13/cobra" "go.uber.org/zap" "gopkg.in/yaml.v3" - "iop/apps/control-plane/internal/wire" "iop/packages/go/observability" - iop "iop/proto/gen/iop" ) var cfgFile string @@ -134,600 +129,6 @@ func applyEnvOverrides(cfg *controlPlaneConfig) { } } -func run(ctx context.Context, cfg controlPlaneConfig, logger *zap.Logger) error { - mux := http.NewServeMux() - mux.HandleFunc("/healthz", func(w http.ResponseWriter, _ *http.Request) { - w.WriteHeader(http.StatusOK) - _, _ = w.Write([]byte("ok\n")) - }) - mux.HandleFunc("/readyz", func(w http.ResponseWriter, _ *http.Request) { - w.WriteHeader(http.StatusOK) - _, _ = w.Write([]byte("ready\n")) - }) - - wireEndpoint := wire.Endpoint{Listen: cfg.Server.WireListen} - logger.Info("control-plane client wire endpoint reserved", - zap.String("protocol", wire.Protocol), - zap.String("transport", wire.ClientTransport), - zap.String("listen", wireEndpoint.Listen), - ) - logger.Info("control-plane edge wire endpoint reserved", - zap.String("protocol", wire.Protocol), - zap.String("transport", wire.EdgeTransport), - zap.String("listen", cfg.Server.EdgeWireListen), - ) - if cfg.Database.URL != "" { - logger.Info("control-plane database configured", databaseLogFields(cfg.Database.URL)...) - } - if cfg.Redis.URL != "" { - logger.Info("control-plane redis configured", redisLogFields(cfg.Redis.URL, cfg.Redis.KeyPrefix)...) - } - clientServer, err := wire.NewClientServer(cfg.Server.WireListen, logger) - if err != nil { - return fmt.Errorf("wire server: %w", err) - } - if err := clientServer.Start(ctx); err != nil { - return fmt.Errorf("start wire server: %w", err) - } - defer func() { _ = clientServer.Stop() }() - - edgeServer, err := wire.NewEdgeServer(cfg.Server.EdgeWireListen, logger) - if err != nil { - return fmt.Errorf("edge wire server: %w", err) - } - if err := edgeServer.Start(ctx); err != nil { - return fmt.Errorf("start edge wire server: %w", err) - } - defer func() { _ = edgeServer.Stop() }() - registerEdgeRegistryHandlers(mux, edgeServer.Registry(), edgeServer.RequestStatus, edgeServer.SendCommand) - registerFleetHandlers(mux, edgeServer.Registry(), edgeServer.RequestStatus, edgeServer.SendCommand) - - server := &http.Server{ - Addr: cfg.Server.Listen, - Handler: mux, - ReadHeaderTimeout: 5 * time.Second, - } - - errCh := make(chan error, 1) - go func() { - logger.Info("control-plane http endpoint listening", zap.String("listen", cfg.Server.Listen)) - if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed { - errCh <- err - return - } - errCh <- nil - }() - - select { - case <-ctx.Done(): - shutdownCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second) - defer cancel() - return server.Shutdown(shutdownCtx) - case err := <-errCh: - return err - } -} - -type edgeRegistryResponse struct { - Edges []edgeRegistryView `json:"edges"` -} - -type edgeRegistryView struct { - EdgeID string `json:"edge_id"` - EdgeName string `json:"edge_name"` - Version string `json:"version"` - Capabilities []string `json:"capabilities"` - Protocol string `json:"protocol"` - Connected bool `json:"connected"` - LastSeen time.Time `json:"last_seen"` -} - -type edgeNodeEventsResponse struct { - EdgeID string `json:"edge_id"` - Events []edgeNodeEventView `json:"events"` -} - -type edgeNodeEventView struct { - EdgeID string `json:"edge_id"` - EventID string `json:"event_id"` - Type string `json:"type"` - Source string `json:"source"` - NodeID string `json:"node_id"` - Alias string `json:"alias"` - Reason string `json:"reason"` - Timestamp time.Time `json:"timestamp"` - ReceivedAt time.Time `json:"received_at"` - Metadata map[string]string `json:"metadata,omitempty"` -} - -type edgeStatusResponseView struct { - RequestID string `json:"request_id"` - EdgeID string `json:"edge_id"` - EdgeName string `json:"edge_name"` - ObservedTimeUnixNano int64 `json:"observed_time_unix_nano"` - Nodes []edgeNodeSnapshotView `json:"nodes"` - Capabilities []edgeCapabilitySummaryView `json:"capabilities,omitempty"` - DomainAgents []edgeDomainAgentSummaryView `json:"domain_agents,omitempty"` - Metadata map[string]string `json:"metadata,omitempty"` - Error string `json:"error,omitempty"` -} - -type edgeCapabilitySummaryView struct { - Kind string `json:"kind"` - Available bool `json:"available"` - Status string `json:"status,omitempty"` - Summary string `json:"summary,omitempty"` -} - -type edgeDomainAgentSummaryView struct { - AgentKind string `json:"agent_kind"` - Available bool `json:"available"` - LifecycleState string `json:"lifecycle_state,omitempty"` - ActiveCommandID string `json:"active_command_id,omitempty"` - Summary string `json:"summary,omitempty"` -} - -// edgeCommandRequestBody is the JSON body for POST /edges/{id}/commands and -// POST /fleet/commands. It carries the surface-neutral command intent only. -type edgeCommandRequestBody struct { - Operation string `json:"operation"` - TargetSelector string `json:"target_selector,omitempty"` - Parameters map[string]string `json:"parameters,omitempty"` -} - -type edgeCommandResponseView struct { - RequestID string `json:"request_id,omitempty"` - CommandID string `json:"command_id"` - EdgeID string `json:"edge_id"` - Status string `json:"status"` - Summary string `json:"summary,omitempty"` - Error string `json:"error,omitempty"` -} - -type edgeOperationsResponse struct { - EdgeID string `json:"edge_id"` - Operations []edgeCommandRecordView `json:"operations"` -} - -type edgeCommandRecordView struct { - EdgeID string `json:"edge_id"` - CommandID string `json:"command_id"` - Operation string `json:"operation,omitempty"` - TargetSelector string `json:"target_selector,omitempty"` - Status string `json:"status"` - Summary string `json:"summary,omitempty"` - Error string `json:"error,omitempty"` - CreatedAt time.Time `json:"created_at"` - UpdatedAt time.Time `json:"updated_at"` - Events []edgeCommandEventView `json:"events,omitempty"` -} - -type edgeCommandEventView struct { - Phase string `json:"phase,omitempty"` - Summary string `json:"summary,omitempty"` - OccurredAt time.Time `json:"occurred_at,omitempty"` - ReceivedAt time.Time `json:"received_at"` -} - -type fleetStatusResponse struct { - GeneratedAt time.Time `json:"generated_at"` - Edges []fleetEdgeView `json:"edges"` -} - -type fleetEdgeView struct { - EdgeID string `json:"edge_id"` - EdgeName string `json:"edge_name,omitempty"` - Version string `json:"version,omitempty"` - Protocol string `json:"protocol,omitempty"` - Connected bool `json:"connected"` - Health string `json:"health"` - LastSeen time.Time `json:"last_seen"` - NodeCount int `json:"node_count"` - Capabilities []edgeCapabilitySummaryView `json:"capabilities,omitempty"` - DomainAgents []edgeDomainAgentSummaryView `json:"domain_agents,omitempty"` - Error string `json:"error,omitempty"` -} - -type fleetCommandResponse struct { - Operation string `json:"operation"` - Results []edgeCommandResponseView `json:"results"` -} - -type edgeNodeSnapshotView struct { - NodeID string `json:"node_id"` - Alias string `json:"alias"` - Label string `json:"label"` - Connected bool `json:"connected"` - Config *nodeConfigSummaryView `json:"config,omitempty"` -} - -type nodeConfigSummaryView struct { - Adapters []adapterSummaryView `json:"adapters"` - Concurrency int32 `json:"concurrency"` -} - -type adapterSummaryView struct { - Type string `json:"type"` - Enabled bool `json:"enabled"` -} - -func newNodeConfigSummaryView(payload *iop.NodeConfigPayload) *nodeConfigSummaryView { - if payload == nil { - return nil - } - var adapters []adapterSummaryView - for _, a := range payload.GetAdapters() { - adapters = append(adapters, adapterSummaryView{ - Type: a.GetType(), - Enabled: a.GetEnabled(), - }) - } - concurrency := int32(0) - if payload.GetRuntime() != nil { - concurrency = payload.GetRuntime().GetConcurrency() - } - return &nodeConfigSummaryView{ - Adapters: adapters, - Concurrency: concurrency, - } -} - -// edgeStatusRequester asks a connected Edge for its Edge-owned node snapshot. -type edgeStatusRequester func(edgeID string, timeout time.Duration) (*iop.EdgeStatusResponse, error) - -// edgeCommandSender dispatches a command to a connected Edge and returns its -// typed response. -type edgeCommandSender func(edgeID, operation, targetSelector string, parameters map[string]string, timeout time.Duration) (*iop.EdgeCommandResponse, error) - -func registerEdgeRegistryHandlers(mux *http.ServeMux, registry *wire.EdgeRegistry, requestStatus edgeStatusRequester, sendCommand edgeCommandSender) { - mux.HandleFunc("/edges", func(w http.ResponseWriter, r *http.Request) { - if r.URL.Path != "/edges" { - http.NotFound(w, r) - return - } - if r.Method != http.MethodGet { - methodNotAllowed(w, http.MethodGet) - return - } - states := registry.Snapshots() - views := make([]edgeRegistryView, 0, len(states)) - for _, state := range states { - views = append(views, edgeRegistryViewFromState(state)) - } - writeJSON(w, http.StatusOK, edgeRegistryResponse{Edges: views}) - }) - mux.HandleFunc("/edges/", func(w http.ResponseWriter, r *http.Request) { - edgePath := strings.TrimPrefix(r.URL.Path, "/edges/") - edgeID, rest, hasRest := strings.Cut(edgePath, "/") - if edgeID == "" { - http.NotFound(w, r) - return - } - if !hasRest { - if r.Method != http.MethodGet { - methodNotAllowed(w, http.MethodGet) - return - } - state, ok := registry.Snapshot(edgeID) - if !ok { - http.NotFound(w, r) - return - } - writeJSON(w, http.StatusOK, edgeRegistryViewFromState(state)) - return - } - switch rest { - case "status": - if r.Method != http.MethodGet { - methodNotAllowed(w, http.MethodGet) - return - } - if _, ok := registry.Snapshot(edgeID); !ok { - http.NotFound(w, r) - return - } - resp, err := requestStatus(edgeID, 5*time.Second) - if err != nil { - writeJSON(w, http.StatusBadGateway, map[string]string{"error": err.Error()}) - return - } - writeJSON(w, http.StatusOK, edgeStatusResponseViewFromProto(resp)) - case "events": - if r.Method != http.MethodGet { - methodNotAllowed(w, http.MethodGet) - return - } - if _, ok := registry.Snapshot(edgeID); !ok { - http.NotFound(w, r) - return - } - records := registry.NodeEvents(edgeID, r.URL.Query().Get("node_id")) - views := make([]edgeNodeEventView, 0, len(records)) - for _, record := range records { - views = append(views, edgeNodeEventViewFromRecord(record)) - } - writeJSON(w, http.StatusOK, edgeNodeEventsResponse{EdgeID: edgeID, Events: views}) - case "operations": - if r.Method != http.MethodGet { - methodNotAllowed(w, http.MethodGet) - return - } - if _, ok := registry.Snapshot(edgeID); !ok { - http.NotFound(w, r) - return - } - records := registry.Commands(edgeID) - views := make([]edgeCommandRecordView, 0, len(records)) - for _, record := range records { - views = append(views, edgeCommandRecordViewFromRecord(record)) - } - writeJSON(w, http.StatusOK, edgeOperationsResponse{EdgeID: edgeID, Operations: views}) - case "commands": - if r.Method != http.MethodPost { - methodNotAllowed(w, http.MethodPost) - return - } - handleEdgeCommandPost(w, r, edgeID, sendCommand) - default: - http.NotFound(w, r) - } - }) -} - -// handleEdgeCommandPost decodes a command request body and dispatches it to a -// single target Edge. A not-connected Edge yields a 502 with the wire error. -func handleEdgeCommandPost(w http.ResponseWriter, r *http.Request, edgeID string, sendCommand edgeCommandSender) { - var body edgeCommandRequestBody - if err := json.NewDecoder(r.Body).Decode(&body); err != nil { - writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid request body"}) - return - } - if body.Operation == "" { - writeJSON(w, http.StatusBadRequest, map[string]string{"error": "operation is required"}) - return - } - if sendCommand == nil { - writeJSON(w, http.StatusServiceUnavailable, map[string]string{"error": "command dispatch is not configured"}) - return - } - resp, err := sendCommand(edgeID, body.Operation, body.TargetSelector, body.Parameters, 10*time.Second) - if err != nil { - writeJSON(w, http.StatusBadGateway, map[string]string{"error": err.Error()}) - return - } - writeJSON(w, http.StatusAccepted, edgeCommandResponseViewFromProto(resp)) -} - -func registerFleetHandlers(mux *http.ServeMux, registry *wire.EdgeRegistry, requestStatus edgeStatusRequester, sendCommand edgeCommandSender) { - mux.HandleFunc("/fleet/status", func(w http.ResponseWriter, r *http.Request) { - if r.Method != http.MethodGet { - methodNotAllowed(w, http.MethodGet) - return - } - states := registry.Snapshots() - views := make([]fleetEdgeView, 0, len(states)) - for _, state := range states { - views = append(views, fleetEdgeViewFromState(state, requestStatus)) - } - writeJSON(w, http.StatusOK, fleetStatusResponse{GeneratedAt: time.Now().UTC(), Edges: views}) - }) - mux.HandleFunc("/fleet/commands", func(w http.ResponseWriter, r *http.Request) { - if r.Method != http.MethodPost { - methodNotAllowed(w, http.MethodPost) - return - } - var body edgeCommandRequestBody - if err := json.NewDecoder(r.Body).Decode(&body); err != nil { - writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid request body"}) - return - } - if body.Operation == "" { - writeJSON(w, http.StatusBadRequest, map[string]string{"error": "operation is required"}) - return - } - if sendCommand == nil { - writeJSON(w, http.StatusServiceUnavailable, map[string]string{"error": "command dispatch is not configured"}) - return - } - results := make([]edgeCommandResponseView, 0) - for _, state := range registry.Snapshots() { - if !state.Connected { - continue - } - resp, err := sendCommand(state.EdgeID, body.Operation, body.TargetSelector, body.Parameters, 10*time.Second) - if err != nil { - results = append(results, edgeCommandResponseView{ - EdgeID: state.EdgeID, - Status: "error", - Error: err.Error(), - }) - continue - } - results = append(results, edgeCommandResponseViewFromProto(resp)) - } - writeJSON(w, http.StatusAccepted, fleetCommandResponse{Operation: body.Operation, Results: results}) - }) -} - -func methodNotAllowed(w http.ResponseWriter, allow ...string) { - w.Header().Set("Allow", strings.Join(allow, ", ")) - http.Error(w, "method not allowed", http.StatusMethodNotAllowed) -} - -func edgeNodeEventViewFromRecord(record wire.EdgeNodeEventRecord) edgeNodeEventView { - event := record.Event - view := edgeNodeEventView{ - EdgeID: record.EdgeID, - ReceivedAt: record.ReceivedAt, - } - if event == nil { - return view - } - if event.GetTimestamp() != 0 { - view.Timestamp = time.Unix(0, event.GetTimestamp()).UTC() - } - view.EventID = event.GetEventId() - view.Type = event.GetType() - view.Source = event.GetSource() - view.NodeID = event.GetNodeId() - view.Alias = event.GetAlias() - view.Reason = event.GetReason() - if metadata := event.GetMetadata(); len(metadata) > 0 { - view.Metadata = make(map[string]string, len(metadata)) - for k, v := range metadata { - view.Metadata[k] = v - } - } - return view -} - -func edgeRegistryViewFromState(state wire.EdgeConnectionState) edgeRegistryView { - return edgeRegistryView{ - EdgeID: state.EdgeID, - EdgeName: state.EdgeName, - Version: state.Version, - Capabilities: append([]string(nil), state.Capabilities...), - Protocol: state.Protocol, - Connected: state.Connected, - LastSeen: state.LastSeen, - } -} - -func edgeStatusResponseViewFromProto(resp *iop.EdgeStatusResponse) edgeStatusResponseView { - nodes := make([]edgeNodeSnapshotView, 0, len(resp.GetNodes())) - for _, n := range resp.GetNodes() { - nodes = append(nodes, edgeNodeSnapshotView{ - NodeID: n.GetNodeId(), - Alias: n.GetAlias(), - Label: n.GetLabel(), - Connected: n.GetConnected(), - Config: newNodeConfigSummaryView(n.GetConfig()), - }) - } - return edgeStatusResponseView{ - RequestID: resp.GetRequestId(), - EdgeID: resp.GetEdgeId(), - EdgeName: resp.GetEdgeName(), - ObservedTimeUnixNano: resp.GetObservedTimeUnixNano(), - Nodes: nodes, - Capabilities: edgeCapabilityViews(resp.GetCapabilities()), - DomainAgents: edgeDomainAgentViews(resp.GetDomainAgents()), - Metadata: resp.GetMetadata(), - Error: resp.GetError(), - } -} - -func edgeCapabilityViews(caps []*iop.EdgeCapabilitySummary) []edgeCapabilitySummaryView { - if len(caps) == 0 { - return nil - } - views := make([]edgeCapabilitySummaryView, 0, len(caps)) - for _, c := range caps { - views = append(views, edgeCapabilitySummaryView{ - Kind: c.GetKind(), - Available: c.GetAvailable(), - Status: c.GetStatus(), - Summary: c.GetSummary(), - }) - } - return views -} - -func edgeDomainAgentViews(agents []*iop.EdgeDomainAgentSummary) []edgeDomainAgentSummaryView { - if len(agents) == 0 { - return nil - } - views := make([]edgeDomainAgentSummaryView, 0, len(agents)) - for _, a := range agents { - views = append(views, edgeDomainAgentSummaryView{ - AgentKind: a.GetAgentKind(), - Available: a.GetAvailable(), - LifecycleState: a.GetLifecycleState(), - ActiveCommandID: a.GetActiveCommandId(), - Summary: a.GetSummary(), - }) - } - return views -} - -func edgeCommandResponseViewFromProto(resp *iop.EdgeCommandResponse) edgeCommandResponseView { - return edgeCommandResponseView{ - RequestID: resp.GetRequestId(), - CommandID: resp.GetCommandId(), - EdgeID: resp.GetEdgeId(), - Status: resp.GetStatus(), - Summary: resp.GetSummary(), - Error: resp.GetError(), - } -} - -func edgeCommandRecordViewFromRecord(record wire.EdgeCommandRecord) edgeCommandRecordView { - view := edgeCommandRecordView{ - EdgeID: record.EdgeID, - CommandID: record.CommandID, - Operation: record.Operation, - TargetSelector: record.TargetSelector, - Status: record.Status, - Summary: record.Summary, - Error: record.Error, - CreatedAt: record.CreatedAt, - UpdatedAt: record.UpdatedAt, - } - if len(record.Events) > 0 { - view.Events = make([]edgeCommandEventView, 0, len(record.Events)) - for _, e := range record.Events { - view.Events = append(view.Events, edgeCommandEventView{ - Phase: e.Phase, - Summary: e.Summary, - OccurredAt: e.OccurredAt, - ReceivedAt: e.ReceivedAt, - }) - } - } - return view -} - -func fleetEdgeViewFromState(state wire.EdgeConnectionState, requestStatus edgeStatusRequester) fleetEdgeView { - view := fleetEdgeView{ - EdgeID: state.EdgeID, - EdgeName: state.EdgeName, - Version: state.Version, - Protocol: state.Protocol, - Connected: state.Connected, - LastSeen: state.LastSeen, - } - if !state.Connected { - view.Health = "offline" - return view - } - if requestStatus == nil { - view.Health = "online" - return view - } - resp, err := requestStatus(state.EdgeID, 5*time.Second) - if err != nil { - view.Health = "degraded" - view.Error = err.Error() - return view - } - view.NodeCount = len(resp.GetNodes()) - view.Capabilities = edgeCapabilityViews(resp.GetCapabilities()) - view.DomainAgents = edgeDomainAgentViews(resp.GetDomainAgents()) - if resp.GetError() != "" { - view.Health = "degraded" - view.Error = resp.GetError() - return view - } - view.Health = "online" - return view -} - -func writeJSON(w http.ResponseWriter, status int, v any) { - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(status) - _ = json.NewEncoder(w).Encode(v) -} - func databaseLogFields(rawURL string) []zap.Field { return serviceURLLogFields(rawURL) } diff --git a/apps/control-plane/cmd/control-plane/main_test.go b/apps/control-plane/cmd/control-plane/main_test.go index 2f68060..1110c49 100644 --- a/apps/control-plane/cmd/control-plane/main_test.go +++ b/apps/control-plane/cmd/control-plane/main_test.go @@ -838,3 +838,52 @@ func TestFleetCommandsHTTPHandlerFansOutToConnectedEdgesOnly(t *testing.T) { } } } + +func TestHTTPMuxHealthAndReadiness(t *testing.T) { + mux := newHTTPMux() + + t.Run("Health", func(t *testing.T) { + resp := httptest.NewRecorder() + mux.ServeHTTP(resp, httptest.NewRequest(http.MethodGet, "/healthz", nil)) + if resp.Code != http.StatusOK { + t.Fatalf("GET /healthz status=%d, want %d", resp.Code, http.StatusOK) + } + if resp.Body.String() != "ok\n" { + t.Fatalf("GET /healthz body=%q, want %q", resp.Body.String(), "ok\n") + } + }) + + t.Run("Readiness", func(t *testing.T) { + resp := httptest.NewRecorder() + mux.ServeHTTP(resp, httptest.NewRequest(http.MethodGet, "/readyz", nil)) + if resp.Code != http.StatusOK { + t.Fatalf("GET /readyz status=%d, want %d", resp.Code, http.StatusOK) + } + if resp.Body.String() != "ready\n" { + t.Fatalf("GET /readyz body=%q, want %q", resp.Body.String(), "ready\n") + } + }) +} + +func TestHTTPMuxRegistersEdgeHandlers(t *testing.T) { + registry := wire.NewEdgeRegistry() + mux := newHTTPMux() + registerEdgeRegistryHandlers(mux, registry, nil, nil) + registerFleetHandlers(mux, registry, nil, nil) + + t.Run("ListEdges", func(t *testing.T) { + resp := httptest.NewRecorder() + mux.ServeHTTP(resp, httptest.NewRequest(http.MethodGet, "/edges", nil)) + if resp.Code != http.StatusOK { + t.Fatalf("GET /edges status=%d", resp.Code) + } + }) + + t.Run("FleetStatus", func(t *testing.T) { + resp := httptest.NewRecorder() + mux.ServeHTTP(resp, httptest.NewRequest(http.MethodGet, "/fleet/status", nil)) + if resp.Code != http.StatusOK { + t.Fatalf("GET /fleet/status status=%d", resp.Code) + } + }) +} diff --git a/apps/control-plane/cmd/control-plane/server.go b/apps/control-plane/cmd/control-plane/server.go new file mode 100644 index 0000000..12287f5 --- /dev/null +++ b/apps/control-plane/cmd/control-plane/server.go @@ -0,0 +1,97 @@ +package main + +import ( + "context" + "fmt" + "net/http" + "time" + + "go.uber.org/zap" + + "iop/apps/control-plane/internal/wire" +) + +func run(ctx context.Context, cfg controlPlaneConfig, logger *zap.Logger) error { + mux := newHTTPMux() + + wireEndpoint := wire.Endpoint{Listen: cfg.Server.WireListen} + logger.Info("control-plane client wire endpoint reserved", + zap.String("protocol", wire.Protocol), + zap.String("transport", wire.ClientTransport), + zap.String("listen", wireEndpoint.Listen), + ) + logger.Info("control-plane edge wire endpoint reserved", + zap.String("protocol", wire.Protocol), + zap.String("transport", wire.EdgeTransport), + zap.String("listen", cfg.Server.EdgeWireListen), + ) + if cfg.Database.URL != "" { + logger.Info("control-plane database configured", databaseLogFields(cfg.Database.URL)...) + } + if cfg.Redis.URL != "" { + logger.Info("control-plane redis configured", redisLogFields(cfg.Redis.URL, cfg.Redis.KeyPrefix)...) + } + clientServer, err := wire.NewClientServer(cfg.Server.WireListen, logger) + if err != nil { + return fmt.Errorf("wire server: %w", err) + } + if err := clientServer.Start(ctx); err != nil { + return fmt.Errorf("start wire server: %w", err) + } + defer func() { _ = clientServer.Stop() }() + + edgeServer, err := wire.NewEdgeServer(cfg.Server.EdgeWireListen, logger) + if err != nil { + return fmt.Errorf("edge wire server: %w", err) + } + if err := edgeServer.Start(ctx); err != nil { + return fmt.Errorf("start edge wire server: %w", err) + } + defer func() { _ = edgeServer.Stop() }() + registerEdgeRegistryHandlers(mux, edgeServer.Registry(), edgeServer.RequestStatus, edgeServer.SendCommand) + registerFleetHandlers(mux, edgeServer.Registry(), edgeServer.RequestStatus, edgeServer.SendCommand) + + return startHTTPServer(ctx, cfg.Server.Listen, mux, logger) +} + +func newHTTPMux() *http.ServeMux { + mux := http.NewServeMux() + mux.HandleFunc("/healthz", func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte("ok\n")) + }) + mux.HandleFunc("/readyz", func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte("ready\n")) + }) + return mux +} + +func startHTTPServer(ctx context.Context, listenAddr string, handler http.Handler, logger *zap.Logger) error { + server := &http.Server{ + Addr: listenAddr, + Handler: handler, + ReadHeaderTimeout: 5 * time.Second, + } + + errCh := make(chan error, 1) + go func() { + logger.Info("control-plane http endpoint listening", zap.String("listen", listenAddr)) + if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed { + errCh <- err + return + } + errCh <- nil + }() + + select { + case <-ctx.Done(): + // Use the original context for shutdown (signal.NotifyContext may close it). + // Re-create a shutdown context with the same deadline or a small timeout. + shutdownCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + return server.Shutdown(shutdownCtx) + case err := <-errCh: + return err + } +}