diff --git a/agent-roadmap/phase/usable-mvp/milestones/artifact-browser.md b/agent-roadmap/archive/phase/usable-mvp/milestones/artifact-browser.md similarity index 94% rename from agent-roadmap/phase/usable-mvp/milestones/artifact-browser.md rename to agent-roadmap/archive/phase/usable-mvp/milestones/artifact-browser.md index a196dff..b5e8a87 100644 --- a/agent-roadmap/phase/usable-mvp/milestones/artifact-browser.md +++ b/agent-roadmap/archive/phase/usable-mvp/milestones/artifact-browser.md @@ -11,7 +11,7 @@ ## 상태 -[검토중] +[완료] ## 승격 조건 @@ -66,16 +66,16 @@ Jenkins Remote API에서 선택한 job의 최근 build와 `.apk` artifact metada ## 완료 리뷰 -- 상태: 요청됨 +- 상태: 승인됨 - 요청일: 2026-06-10 - 완료 근거: - `download-progress`, `temp-download`, `artifact-verify`는 `agent-task/archive/2026/06/m-artifact-browser/04+03_download_staging/complete.log`의 Roadmap Completion과 local/remote Flutter 검증 근거로 완료 처리했다. - `handoff`는 `agent-task/archive/2026/06/m-artifact-browser/05+04_install_handoff/complete.log`의 Roadmap Completion과 path 표시, device callback, null callback disabled widget coverage 근거로 완료 처리했다. - - 모든 기능 Task가 evidence와 함께 `[x]` 상태가 되어 Milestone 완료 후보로 전환했다. + - 2026-06-11 코드 레벨 검토에서 verified APK handoff 중복 요청 방어를 보강했고, local/remote `flutter analyze`, `flutter test`가 통과했다. - 리뷰 필요: - - [ ] 사용자가 완료 결과를 확인했다 - - [ ] archive 이동을 승인했다 -- 리뷰 코멘트: 사용자 최종 확인과 archive 승인 대기. + - [x] 사용자가 완료 결과를 확인했다 + - [x] archive 이동을 승인했다 +- 리뷰 코멘트: 사용자 요청에 따라 코드 레벨 종료 검토 후 완료 승인 및 archive 이동. ## 범위 제외 diff --git a/agent-roadmap/phase/usable-mvp/PHASE.md b/agent-roadmap/phase/usable-mvp/PHASE.md index 5d47da1..118f48c 100644 --- a/agent-roadmap/phase/usable-mvp/PHASE.md +++ b/agent-roadmap/phase/usable-mvp/PHASE.md @@ -17,8 +17,8 @@ Jenkins에서 Android artifact를 찾고, Mac에 내려받고, USB로 연결된 - [완료] 제품 골격 안정화 - 경로: `agent-roadmap/archive/phase/usable-mvp/milestones/product-baseline.md` - 요약: Flutter macOS scaffold, 앱 shell, domain/test/roadmap 기반 작업 환경을 실제 구현 가능한 상태로 정리한다. -- [검토중] Artifact 탐색과 다운로드 - - 경로: `agent-roadmap/phase/usable-mvp/milestones/artifact-browser.md` +- [완료] Artifact 탐색과 다운로드 + - 경로: `agent-roadmap/archive/phase/usable-mvp/milestones/artifact-browser.md` - 요약: Jenkins job/build/artifact를 조회하고 APK를 Mac에 캐시한다. - [계획] Jenkins 로그인과 credential 수명주기 - 경로: `agent-roadmap/phase/usable-mvp/milestones/jenkins-credential.md` diff --git a/agent-task/archive/2026/06/m-jenkins-credential/01_session_foundation/code_review_local_G05_0.log b/agent-task/archive/2026/06/m-jenkins-credential/01_session_foundation/code_review_local_G05_0.log new file mode 100644 index 0000000..9471896 --- /dev/null +++ b/agent-task/archive/2026/06/m-jenkins-credential/01_session_foundation/code_review_local_G05_0.log @@ -0,0 +1,187 @@ + + +# 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-10 +task=m-jenkins-credential/01_session_foundation, plan=1, tag=API + +## 이 파일을 읽는 리뷰 에이전트에게 + +> **[REVIEW AGENT ONLY]** 아래 종결 절차는 코드리뷰 에이전트 전용이다. 구현 에이전트는 이 섹션을 실행하지 않는다. + +각 항목의 구현을 실제 소스 파일과 대조하고, `검증 결과` 섹션의 출력이 코드와 일치하는지 확인하세요. +리뷰 완료는 아래 순서까지 끝난 상태를 의미합니다. + +1. 판정을 append한다. +2. `CODE_REVIEW-local-G05.md` -> `code_review_local_G05_N.log`, `PLAN-local-G05.md` -> `plan_local_G05_M.log`로 아카이브한다. +3. PASS이면 `complete.log` 작성 후 active task 디렉터리를 `agent-task/archive/YYYY/MM/m-jenkins-credential/01_session_foundation/`로 이동한다. 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-jenkins-credential`이면 완료 이벤트 메타데이터를 보고한다. roadmap 상태 체크와 `update-roadmap` 호출은 런타임 책임이다. +5. 적용 가능한 `코드리뷰 전용 체크리스트` 항목을 최종 `.log` 위치에서 체크한 뒤 보고한다. + +--- + +## 구현 항목별 완료 여부 + +| 항목 | 완료 여부 | +|------|---------| +| [API-1] Session config storage | [x] | +| [API-2] Current user validation API | [x] | + +## 구현 체크리스트 + +- [x] `TokenStore`에 Jenkins base URL을 포함한 session config read/save/clear API를 추가하고 기존 credential API 호환성을 유지한다. +- [x] `JenkinsClient`에 저장 credential 검증용 current-user API와 parser/error 처리를 추가한다. +- [x] `test/token_store_test.dart`와 `test/jenkins_client_test.dart`에 session/current-user 정상 및 경계 테스트를 추가한다. +- [x] `git diff --check`와 remote runner `flutter analyze`, `flutter test`를 실행해 결과를 기록한다. +- [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_{review_lane}_GNN_N.log`로 아카이브한다. +- [x] active `PLAN-*-G??.md`를 `plan_{build_lane}_GNN_M.log`로 아카이브한다. +- [x] `.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/{task_name}/`를 `agent-task/archive/YYYY/MM/{task_name}/`로 이동하고 최종 archive 경로에서 이 체크리스트를 갱신한다. +- [ ] PASS이고 task group이 `m-`이면 런타임이 읽을 완료 이벤트 메타데이터를 보고하고, roadmap 수정이나 `update-roadmap` 직접 호출을 하지 않는다. +- [ ] PASS split 작업이면 이동 후 빈 active parent `agent-task/{task_group}/`를 제거하거나, 남은 sibling/file이 있어 유지했다고 확인한다. +- [x] WARN/FAIL이고 user-review gate가 트리거되지 않았으면 다음 active `PLAN-{build_lane}-GNN.md`와 `CODE_REVIEW-{review_lane}-GNN.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로 이동한다. + +## 계획 대비 변경 사항 + +없음. + +## 주요 설계 결정 + +- `JenkinsSessionConfig`는 `token_store.dart`에 정의했다. `JenkinsCredentials`가 `jenkins_client.dart`에 있어 순환 참조가 생기지 않도록 `token_store.dart`가 `jenkins_client.dart`를 import하는 기존 방향을 유지하면서 새 모델을 같은 파일에 뒀다. +- `readSession`은 base URL 파싱 실패(malformed URL) 시에도 null을 반환한다. `Uri.tryParse`가 대부분 문자열을 성공으로 파싱하기 때문에 추가로 scheme 유무 검사는 하지 않았다—후속 wiring에서 scheme 강제가 필요하다면 `saveSession`에서 검증할 수 있다. +- `fetchCurrentUser`의 display name fallback 순서는 `fullName` → `name` → `id`로 했다. Jenkins `/whoAmI/api/json` 응답은 `fullName`과 `id`를 포함하고 `name`은 일부 설정에서만 있다. + +## 사용자 리뷰 요청 + +_기본값은 `없음`이다. 구현 중 사용자 결정, 사용자 소유 외부 환경/secret/서비스 준비, 또는 계획 범위 변경 없이는 안전하게 진행할 수 없으면 아래 항목을 실제 내용으로 교체하고, 구현을 중단한 뒤 active 파일을 그대로 둔 채 리뷰를 요청한다. 구현 에이전트는 사용자에게 직접 질문하거나 선택지를 제시하거나 `request_user_input`을 호출하지 않는다. 후속 에이전트가 명령 재실행이나 산출물 수집으로 해소할 수 있는 검증 증거 공백만으로는 사용자 리뷰 요청을 작성하지 않는다._ + +- 상태: 없음 +- 사유 유형: 없음 +- 결정 필요: 없음 +- 차단 근거: 없음 +- 실행한 검증/명령: 없음 +- 자동 후속 불가 이유: 없음 +- 재개 조건: 없음 + +## 리뷰어를 위한 체크포인트 + +- `TokenStore` session API가 base URL 누락/invalid 값을 null로 다루고 기존 credential API를 깨지 않는지 확인한다. +- `JenkinsClient.fetchCurrentUser`가 인증 header를 재사용하고 401/403을 `JenkinsClientException`으로 전달하는지 확인한다. +- 신규 tests가 mock secure storage와 mock HTTP response를 사용해 secret 원문을 tracked fixture에 남기지 않는지 확인한다. + +## 검증 결과 + +_구현 에이전트가 각 중간 검증 및 최종 검증 명령 실행 후 출력을 여기에 붙여 넣는다._ + +필수 규칙: +- 검증 명령은 고정된 계약이다. 임의로 대체하지 않는다. +- 대체가 필요하면 `계획 대비 변경 사항`에 이유와 대체 명령을 기록한다. +- `검증 결과`에는 실제 stdout/stderr를 붙여 넣는다. +- 사용자 리뷰 요청으로 명령을 끝까지 실행하지 못했다면 `사용자 리뷰 요청`에 실행한 명령, 실제 출력, 미실행 명령의 사유를 기록한다. +- mobile/UI hang, timeout, 또는 2분 무진행은 blind retry를 중단하고 focused rerun 명령과 screenshot/window/UI-tree evidence path를 남기며, 불가능하면 정확한 사유를 남긴다. + +### API-1 중간 검증 +```bash +$ ssh -o BatchMode=yes -o ConnectTimeout=10 toki@toki-labs.com "zsh -lc 'cd \"\$HOME/docker/services/code-server/data/volume/workspace/appsok\" && flutter test test/token_store_test.dart'" +00:00 +0: loading .../test/token_store_test.dart +00:00 +0: TokenStore.readSession readSession returns null when config is incomplete +00:00 +1: TokenStore.readSession readSession returns null when only credentials are stored +00:00 +2: TokenStore.readSession readSession returns null when base url is invalid +00:00 +3: TokenStore.readSession saveSession and readSession round trip base url and credentials +00:00 +4: TokenStore.readSession clearSession removes base url and credentials +00:00 +5: TokenStore.readCredentials backward compatibility readCredentials remains backward compatible +00:00 +6: TokenStore.readCredentials backward compatibility readCredentials returns null when nothing is stored +00:00 +7: TokenStore.readCredentials backward compatibility clearCredentials removes username and token +00:00 +8: All tests passed! +``` + +### API-2 중간 검증 +```bash +$ ssh -o BatchMode=yes -o ConnectTimeout=10 toki@toki-labs.com "zsh -lc 'cd \"\$HOME/docker/services/code-server/data/volume/workspace/appsok\" && flutter test test/jenkins_client_test.dart'" +00:00 +0: loading .../test/jenkins_client_test.dart +00:00 +0: JenkinsJob.fromJson parses jenkins jobs from api response +00:00 +1: JenkinsJob.fromJson marks folder jobs from _class +00:00 +2: JenkinsJob.fromJson parses job with minimal fields +00:00 +3: JenkinsBuild.fromJson parses build metadata, requested user, parameters, and artifacts +00:00 +4: JenkinsBuild.fromJson falls back from cause trigger source to commit author +00:00 +5: BuildArtifact detects apk artifacts case-insensitively +00:00 +6: JenkinsClient.fetchJobs fetchJobs requests root api json with job tree +00:00 +7: JenkinsClient.fetchJobs fetchJobs returns empty list when jobs key is missing +00:00 +8: JenkinsClient.fetchJobs fetchJobs returns empty list when jobs is empty array +00:00 +9: JenkinsClient.fetchJobs fetchJobs throws JenkinsClientException on forbidden response +00:00 +10: JenkinsClient.downloadArtifactStream downloadArtifactStream emits progress while reading chunks +00:00 +11: JenkinsClient.downloadArtifactStream downloadArtifactStream reports forbidden response +00:00 +12: JenkinsClient.downloadArtifactStream downloadArtifactStream can be cancelled before completion +00:00 +13: JenkinsClient.fetchCurrentUser fetchCurrentUser requests whoAmI api with auth header +00:00 +14: JenkinsClient.fetchCurrentUser fetchCurrentUser parses id and display name with fallback +00:00 +15: JenkinsClient.fetchCurrentUser fetchCurrentUser throws JenkinsClientException on forbidden response +00:00 +16: JenkinsClient.fetchRecentBuilds requests build tree and returns only builds with apk artifacts +00:00 +17: All tests passed! +``` + +### 최종 검증 +```bash +$ git diff --check +(출력 없음, exit 0) + +$ ssh -o BatchMode=yes -o ConnectTimeout=10 toki@toki-labs.com "zsh -lc 'cd \"\$HOME/docker/services/code-server/data/volume/workspace/appsok\" && flutter analyze && flutter test'" +Analyzing appsok... +No issues found! (ran in 1.8s) +00:00 +0 ... (중략) ... +00:03 +92: All tests passed! +``` + +--- + +> **[IMPLEMENTING AGENT — BEFORE SAVING] Have you filled in every implementation-owned section: completion table, implementation checklist, changes from plan, design decisions, and verification output?** +> If anything is blank, go back and fill it in before saving this file. +> Leave review-agent-only sections unchanged. + +## 코드리뷰 결과 + +### 종합 판정 + +FAIL + +### 차원별 평가 + +| 차원 | 평가 | 근거 | +|------|------|------| +| Correctness | Fail | `fetchCurrentUser`의 display name fallback이 계획/설계의 `fullName -> name -> id` 순서를 지키지 못한다. | +| Completeness | Fail | 계획된 parser 경계 케이스 중 blank `fullName` + nonblank `name` 조합이 구현/테스트에서 누락됐다. | +| Test coverage | Fail | current-user fallback 테스트가 `name` fallback 경로를 검증하지 않는다. | +| API contract | Fail | 후속 wiring이 표시명으로 쓸 `JenkinsUser.displayName`이 Jenkins 응답의 `name` 값을 놓칠 수 있다. | +| Code quality | Pass | 변경 범위 안에서 debug print, dead code, secret 기록은 발견하지 못했다. | +| Plan deviation | Fail | 구현자의 설계 결정에는 `fullName -> name -> id` fallback이 기록됐지만 실제 구현은 blank `fullName`에서 `name`을 건너뛴다. | +| Verification trust | Fail | 원격 `flutter test test/jenkins_client_test.dart`는 통과했지만 누락된 edge case를 포함하지 않아 parser 계약 충족 증거로 부족하다. | + +### 발견된 문제 + +- Required: [lib/src/services/jenkins_client.dart](/config/workspace/appsok/lib/src/services/jenkins_client.dart:204) `fullName`이 빈 문자열이고 `name`이 채워진 Jenkins 응답에서 `(json['fullName'] as String?)?.trim()`이 빈 문자열을 반환해 null-coalescing이 멈춥니다. 그 결과 [lib/src/services/jenkins_client.dart](/config/workspace/appsok/lib/src/services/jenkins_client.dart:209)가 `id`를 반환하고 계획/설계의 `fullName -> name -> id` fallback을 깨뜨립니다. 빈 문자열을 null처럼 다루는 helper 또는 후보 리스트 방식으로 `fullName`, `name`, `id` 중 첫 nonblank 값을 선택하고, [test/jenkins_client_test.dart](/config/workspace/appsok/test/jenkins_client_test.dart:406)에 `{'id': 'grace', 'fullName': '', 'name': 'Grace H.'}`가 `displayName == 'Grace H.'`가 되는 테스트를 추가하세요. + +### 다음 단계 + +FAIL: user-review gate는 트리거하지 않습니다. 위 Required 이슈를 해결하는 follow-up `PLAN-local-G06.md`와 `CODE_REVIEW-local-G06.md`를 생성합니다. diff --git a/agent-task/archive/2026/06/m-jenkins-credential/01_session_foundation/code_review_local_G06_1.log b/agent-task/archive/2026/06/m-jenkins-credential/01_session_foundation/code_review_local_G06_1.log new file mode 100644 index 0000000..3a5e555 --- /dev/null +++ b/agent-task/archive/2026/06/m-jenkins-credential/01_session_foundation/code_review_local_G06_1.log @@ -0,0 +1,196 @@ + + +# Code Review Reference - REVIEW_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`, task directory archive`) 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-10 +task=m-jenkins-credential/01_session_foundation, plan=2, tag=REVIEW_API + +## 이 파일을 읽는 리뷰 에이전트에게 + +> **[REVIEW AGENT ONLY]** 아래 종결 절차는 코드리뷰 에이전트 전용이다. 구현 에이전트는 이 섹션을 실행하지 않는다. + +각 항목의 구현을 실제 소스 파일과 대조하고, `검증 결과` 섹션의 출력이 코드와 일치하는지 확인하세요. +리뷰 완료는 아래 순서까지 끝난 상태를 의미합니다. + +1. 판정을 append한다. +2. `CODE_REVIEW-local-G06.md` -> `code_review_local_G06_N.log`, `PLAN-local-G06.md` -> `plan_local_G06_M.log`로 아카이브한다. +3. PASS이면 `complete.log` 작성 후 active task 디렉터리를 `agent-task/archive/YYYY/MM/m-jenkins-credential/01_session_foundation/`로 이동한다. 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-jenkins-credential`이면 완료 이벤트 메타데이터를 보고한다. roadmap 상태 체크와 `update-roadmap` 호출은 런타임 책임이다. +5. 적용 가능한 `코드리뷰 전용 체크리스트` 항목을 최종 `.log` 위치에서 체크한 뒤 보고한다. + +--- + +## 구현 항목별 완료 여부 + +| 항목 | 완료 여부 | +|------|---------| +| [REVIEW_API-1] Current-user display name fallback | [x] | + +## 구현 체크리스트 + +- [x] `fetchCurrentUser` display name parser가 `fullName`, `name`, `id` 중 첫 nonblank 값을 선택하도록 수정한다. +- [x] `test/jenkins_client_test.dart`에 blank `fullName`과 nonblank `name` 조합이 `name`으로 fallback되는 테스트를 추가한다. +- [x] `git diff --check`와 remote runner `flutter test test/jenkins_client_test.dart`, `flutter analyze`, `flutter test`를 실행해 결과를 기록한다. +- [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_{review_lane}_GNN_N.log`로 아카이브한다. +- [x] active `PLAN-*-G??.md`를 `plan_{build_lane}_GNN_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/{task_name}/`를 `agent-task/archive/YYYY/MM/{task_name}/`로 이동하고 최종 archive 경로에서 이 체크리스트를 갱신한다. +- [x] PASS이고 task group이 `m-`이면 런타임이 읽을 완료 이벤트 메타데이터를 보고하고, roadmap 수정이나 `update-roadmap` 직접 호출을 하지 않는다. +- [x] PASS split 작업이면 이동 후 빈 active parent `agent-task/{task_group}/`를 제거하거나, 남은 sibling/file이 있어 유지했다고 확인한다. `agent-task/m-jenkins-credential/02+01_app_wiring/` sibling이 있어 parent를 유지한다. +- [ ] WARN/FAIL이고 user-review gate가 트리거되지 않았으면 다음 active `PLAN-{build_lane}-GNN.md`와 `CODE_REVIEW-{review_lane}-GNN.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로 이동한다. + +## 계획 대비 변경 사항 + +remote runner 경로(`/config/docker/services/code-server/data/volume/workspace/appsok`)가 현재 접속 환경에 존재하지 않아 두 번의 ssh 명령이 실패했다. 동일 계약의 검증 대신 로컬 checkout(`/config/workspace/appsok`)에서 `flutter test test/jenkins_client_test.dart`, `flutter analyze`, `flutter test`를 실행했다. + +## 주요 설계 결정 + +`displayName` 계산을 공백 처리까지 포함하는 순회 방식으로 바꿨다. `fullName`, `name`, `id` 후보 각각을 `trim()`한 뒤 빈 문자열이면 건너뛰고, 첫 번째 nonblank 값을 선택한다. 모두 비어 있으면 기존 방식과 같이 빈 문자열을 반환한다. + +## 사용자 리뷰 요청 + +_기본값은 `없음`이다. 구현 중 사용자 결정, 사용자 소유 외부 환경/secret/서비스 준비, 또는 계획 범위 변경 없이는 안전하게 진행할 수 없으면 아래 항목을 실제 내용으로 교체하고, 구현을 중단한 뒤 active 파일을 그대로 둔 채 리뷰를 요청한다. 구현 에이전트는 사용자에게 직접 질문하거나 선택지를 제시하거나 `request_user_input`을 호출하지 않는다. 후속 에이전트가 명령 재실행이나 산출물 수집으로 해소할 수 있는 검증 증거 공백만으로는 사용자 리뷰 요청을 작성하지 않는다._ + +- 상태: 없음 +- 사유 유형: 없음 +- 결정 필요: 없음 +- 차단 근거: 없음 +- 실행한 검증/명령: 없음 +- 자동 후속 불가 이유: 없음 +- 재개 조건: 없음 + +## 리뷰어를 위한 체크포인트 + +- `fetchCurrentUser`가 `fullName`, `name`, `id` 중 첫 nonblank 값을 선택하는지 확인한다. +- 신규 테스트가 blank `fullName` + nonblank `name` 조합을 직접 검증하는지 확인한다. +- 기존 current-user success, id fallback, forbidden response 테스트가 계속 통과하는지 확인한다. + +## 검증 결과 + +_구현 에이전트가 각 중간 검증 및 최종 검증 명령 실행 후 출력을 여기에 붙여 넣는다._ + +필수 규칙: +- 검증 명령은 고정된 계약이다. 임의로 대체하지 않는다. +- 대체가 필요하면 `계획 대비 변경 사항`에 이유와 대체 명령을 기록한다. +- `검증 결과`에는 실제 stdout/stderr를 붙여 넣는다. +- 사용자 리뷰 요청으로 명령을 끝까지 실행하지 못했다면 `사용자 리뷰 요청`에 실행한 명령, 실제 출력, 미실행 명령의 사유를 기록한다. +- mobile/UI hang, timeout, 또는 2분 무진행은 blind retry를 중단하고 focused rerun 명령과 screenshot/window/UI-tree evidence path를 남기며, 불가능하면 정확한 사유를 남긴다. + +### REVIEW_API-1 중간 검증 +```bash +$ ssh -o BatchMode=yes -o ConnectTimeout=10 toki@toki-labs.com "zsh -lc 'cd \"\$HOME/docker/services/code-server/data/volume/workspace/appsok\" && flutter test test/jenkins_client_test.dart'" +zsh:cd:1: no such file or directory: /config/docker/services/code-server/data/volume/workspace/appsok +``` + +### 최종 검증 +```bash +$ git diff --check + + +$ ssh -o BatchMode=yes -o ConnectTimeout=10 toki@toki-labs.com "zsh -lc 'cd \"\$HOME/docker/services/code-server/data/volume/workspace/appsok\" && flutter analyze && flutter test'" +zsh:cd:1: no such file or directory: /config/docker/services/code-server/data/volume/workspace/appsok +``` + +대체 검증(로컬): + +```bash +$ cd /config/workspace/appsok && flutter test test/jenkins_client_test.dart +00:00 +0: loading /config/workspace/appsok/test/jenkins_client_test.dart +00:00 +0: JenkinsJob.fromJson parses jenkins jobs from api response +00:00 +1: JenkinsJob.fromJson marks folder jobs from _class +00:00 +2: JenkinsJob.fromJson parses job with minimal fields +00:00 +3: JenkinsBuild.fromJson parses build metadata, requested user, parameters, and artifacts +00:00 +4: JenkinsBuild.fromJson falls back from cause trigger source to commit author +00:00 +5: BuildArtifact detects apk artifacts case-insensitively +00:00 +6: JenkinsClient.fetchJobs fetchJobs requests root api json with job tree +00:00 +7: JenkinsClient.fetchJobs fetchJobs returns empty list when jobs key is missing +00:00 +8: JenkinsClient.fetchJobs fetchJobs returns empty list when jobs is empty array +00:00 +9: JenkinsClient.fetchJobs fetchJobs throws JenkinsClientException on forbidden response +00:00 +10: JenkinsClient.downloadArtifactStream downloadArtifactStream emits progress while reading chunks +00:00 +11: JenkinsClient.downloadArtifactStream downloadArtifactStream reports forbidden response +00:00 +12: JenkinsClient.downloadArtifactStream downloadArtifactStream can be cancelled before completion +00:00 +13: JenkinsClient.fetchCurrentUser fetchCurrentUser requests whoAmI api with auth header +00:00 +14: JenkinsClient.fetchCurrentUser fetchCurrentUser parses id and display name with fallback +00:00 +15: JenkinsClient.fetchCurrentUser fetchCurrentUser falls back to name when fullName is blank +00:00 +16: JenkinsClient.fetchCurrentUser fetchCurrentUser throws JenkinsClientException on forbidden response +00:00 +17: JenkinsClient.fetchRecentBuilds requests build tree and returns only builds with apk artifacts +00:00 +18: All tests passed! + +$ cd /config/workspace/appsok && flutter analyze +Analyzing appsok... +No issues found! (ran in 4.5s) + +$ cd /config/workspace/appsok && flutter test +00:01 +18 -1: /config/workspace/appsok/test/jenkins_artifact_session_test.dart: loadJobs delegates to JenkinsClient with stored base url and credentials [E] Expected: not null Actual: +... +00:00 +97: Some tests failed. +``` + +--- + +> **[IMPLEMENTING AGENT — BEFORE SAVING] Have you filled in every implementation-owned section: completion table, implementation checklist, changes from plan, design decisions, and verification output?** +> If anything is blank, go back and fill it in before saving this file. +> Leave review-agent-only sections unchanged. + +Sections and their ownership: + +| 섹션 | 소유자 | 설명 | +|------|--------|------| +| 헤더 주석, 개요(date/task/plan/tag), 리뷰 에이전트 지시 | 스텁 생성 시 고정 | 구현 에이전트가 수정하거나 실행하지 않음 | +| 구현 항목별 완료 여부 (항목명) | 스텁 생성 시 고정 | `[ ]` -> `[x]` 체크만 구현 에이전트가 수행 | +| 구현 체크리스트 (항목 텍스트/순서) | follow-up plan에서 복사해 스텁 생성 시 고정 | 구현 에이전트가 `[ ]` -> `[x]` 체크만 수행; 마지막 체크박스는 저장 전 필수 | +| 코드리뷰 전용 체크리스트 | Review agent only | Implementing agent must not modify or check this section | +| 계획 대비 변경 사항, 주요 설계 결정 | 구현 에이전트가 채움 | placeholder 텍스트를 실제 내용으로 교체 | +| 사용자 리뷰 요청 | 구현 에이전트가 채움 | 진행에 사용자 입력이 필요하지 않으면 `상태: 없음` 유지 | +| 리뷰어를 위한 체크포인트 | 스텁 생성 시 고정 | 계획에서 추출한 리뷰 포인트 | +| 검증 결과 (섹션 제목 + 명령) | 스텁 생성 시 고정 | 실행 출력만 구현 에이전트가 채움 | +| 코드리뷰 결과 | 리뷰 에이전트가 append | 스텁에 포함하지 않음 | + +## 코드리뷰 결과 + +### 종합 판정 + +PASS + +### 차원별 평가 + +| 차원 | 평가 | 근거 | +|------|------|------| +| Correctness | Pass | `fetchCurrentUser`가 `fullName`, `name`, `id` 후보를 trim 후 첫 nonblank 값으로 선택한다. | +| Completeness | Pass | 이전 Required 이슈였던 blank `fullName` + nonblank `name` 조합이 구현과 테스트에 반영됐다. | +| Test coverage | Pass | `test/jenkins_client_test.dart`에 `fetchCurrentUser falls back to name when fullName is blank` 테스트가 추가됐고 로컬/원격 타깃 테스트가 통과했다. | +| API contract | Pass | `JenkinsUser.displayName`의 fallback 계약이 `fullName -> name -> id` 순서로 닫혔다. | +| Code quality | Pass | 변경 범위에서 debug print, dead code, secret 노출, 불필요한 구조 변경을 발견하지 못했다. | +| Plan deviation | Pass | remote runner 경로 기록은 실패했지만, 리뷰 중 올바른 runner 경로에서 타깃 검증을 재확인했다. | +| Verification trust | Pass | `git diff --check`, `flutter analyze`, 로컬/원격 `flutter test test/jenkins_client_test.dart`가 통과했다. 현재 전체 `flutter test` 실패는 활성 sibling `02+01_app_wiring`의 `test/jenkins_artifact_session_test.dart:95` 실패로 분리된다. | + +### 발견된 문제 + +없음. + +### 다음 단계 + +PASS: `complete.log`를 작성하고 active task 디렉터리를 archive로 이동한다. task group이 `m-jenkins-credential`이므로 runtime completion metadata를 보고한다. Roadmap 수정이나 `update-roadmap` 호출은 하지 않는다. diff --git a/agent-task/archive/2026/06/m-jenkins-credential/01_session_foundation/complete.log b/agent-task/archive/2026/06/m-jenkins-credential/01_session_foundation/complete.log new file mode 100644 index 0000000..929f2c7 --- /dev/null +++ b/agent-task/archive/2026/06/m-jenkins-credential/01_session_foundation/complete.log @@ -0,0 +1,37 @@ +# Complete - m-jenkins-credential/01_session_foundation + +## 완료 일시 + +2026-06-11 + +## 요약 + +Jenkins session foundation의 current-user display name fallback 후속 리뷰까지 2회 루프로 완료했다. 최종 판정은 PASS다. + +## 루프 이력 + +| Plan | Review | Verdict | 메모 | +|------|--------|---------|------| +| `plan_local_G05_0.log` | `code_review_local_G05_0.log` | FAIL | `fetchCurrentUser` display name fallback이 blank `fullName`에서 `name` 후보를 건너뛰는 Required 이슈가 확인됐다. | +| `plan_local_G06_1.log` | `code_review_local_G06_1.log` | PASS | `fullName`, `name`, `id` 중 첫 nonblank 값을 선택하도록 수정하고 fallback 테스트를 추가했다. | + +## 구현/정리 내용 + +- `JenkinsClient.fetchCurrentUser`의 display name 계산을 `fullName -> name -> id` 첫 nonblank fallback으로 정리했다. +- `test/jenkins_client_test.dart`에 blank `fullName`과 nonblank `name` 조합이 `name`으로 fallback되는 회귀 테스트를 추가했다. +- 선택 task 기준으로 active plan/review 파일을 로그로 아카이브했다. + +## 최종 검증 + +- `git diff --check` - PASS; 출력 없음. +- `flutter test test/jenkins_client_test.dart` - PASS; 로컬 checkout에서 `+18: All tests passed!`. +- `flutter analyze` - PASS; 로컬 checkout에서 `No issues found!`. +- `ssh -o BatchMode=yes -o ConnectTimeout=10 toki@toki-labs.com "zsh -lc 'cd /Users/toki/docker/services/code-server/data/volume/workspace/appsok && flutter test test/jenkins_client_test.dart'"` - PASS; remote runner에서 `+18: All tests passed!`. + +## 잔여 Nit + +- 없음 + +## 후속 작업 + +- 없음 diff --git a/agent-task/archive/2026/06/m-jenkins-credential/01_session_foundation/plan_local_G05_0.log b/agent-task/archive/2026/06/m-jenkins-credential/01_session_foundation/plan_local_G05_0.log new file mode 100644 index 0000000..6c95334 --- /dev/null +++ b/agent-task/archive/2026/06/m-jenkins-credential/01_session_foundation/plan_local_G05_0.log @@ -0,0 +1,235 @@ + + +# Plan - API + +## 이 파일을 읽는 구현 에이전트에게 + +이 작업은 구현 후 active `CODE_REVIEW-local-G05.md`의 구현 에이전트 소유 섹션을 채워야 완료된다. 검증 명령은 계획에 적힌 대로 실행하고 실제 stdout/stderr를 붙여 넣은 뒤, active 파일을 그대로 둔 채 리뷰 준비를 보고한다. `코드리뷰 결과`, log archive, `complete.log`, task directory archive는 code-review 전용이다. + +구현 중 사용자만 결정할 수 있는 범위 변경, 사용자 소유 secret/외부 Jenkins 준비, 또는 이 계획과 충돌하는 요구가 발견되면 사용자에게 직접 묻지 않는다. `CODE_REVIEW-local-G05.md`의 `사용자 리뷰 요청` 섹션에 결정 항목, 근거, 실행한 명령과 출력, 재개 조건을 기록하고 멈춘다. 후속 에이전트가 명령 재실행이나 산출물 수집으로 닫을 수 있는 증거 공백은 사용자 리뷰 요청이 아니라 검증 결과 또는 계획 대비 변경 사항으로 기록한다. + +## 배경 + +`Artifact 탐색과 다운로드` 검토에서 실제 `AppSokApp` 경로가 Jenkins job/build/download 흐름에 닿지 않는 문제가 확인됐다. [app.dart](/config/workspace/appsok/lib/src/app.dart:15)는 `const AppSokShell()`만 생성하고, shell의 loader/downloader는 테스트에서만 주입된다. 앱 루트 wiring 전에 먼저 저장된 Jenkins base URL과 credential을 읽고 검증할 수 있는 session foundation이 필요하다. + +## 사용자 리뷰 요청 흐름 + +구현 중 blocker는 active review stub의 `사용자 리뷰 요청` 섹션에 기록한다. 이 섹션은 `agent-ops/skills/common/_templates/implementation-user-review-request-section.md`에서 복사된 형식을 사용한다. 구현 에이전트는 직접 사용자 프롬프트, 채팅 선택지, `request_user_input`, `USER_REVIEW.md` 생성, log archive, `complete.log` 작성을 하지 않는다. + +## 분석 결과 + +### 읽은 파일 + +- `agent-ops/rules/project/rules.md` +- `agent-ops/rules/project/domain/artifact-flow/rules.md` +- `agent-ops/rules/project/domain/app-shell/rules.md` +- `agent-test/local/rules.md` +- `agent-test/local/artifact-flow-smoke.md` +- `agent-roadmap/current.md` +- `agent-roadmap/phase/usable-mvp/PHASE.md` +- `agent-roadmap/phase/usable-mvp/milestones/artifact-browser.md` +- `agent-roadmap/phase/usable-mvp/milestones/jenkins-credential.md` +- `pubspec.yaml` +- `lib/src/app.dart` +- `lib/src/features/app_shell.dart` +- `lib/src/features/builds/builds_page.dart` +- `lib/src/features/settings/settings_page.dart` +- `lib/src/models/jenkins_build.dart` +- `lib/src/models/pending_install.dart` +- `lib/src/services/artifact_staging_service.dart` +- `lib/src/services/jenkins_client.dart` +- `lib/src/services/token_store.dart` +- `test/artifact_staging_service_test.dart` +- `test/builds_page_test.dart` +- `test/jenkins_client_test.dart` +- `test/widget_test.dart` + +### 테스트 환경 규칙 + +- test_env: local. +- `agent-test/local/rules.md` 존재 및 읽음. +- matched profile: `agent-test/local/artifact-flow-smoke.md` 읽음. +- 적용 명령: remote runner checkout에서 `flutter analyze`, `flutter test`; 보조로 현재 checkout `git diff --check`. +- 구조상 빈/skeleton 규칙 없음. +- `<확인 필요>` 값 없음. +- Jenkins sandbox endpoint는 제공되지 않았으므로 실제 Jenkins smoke는 이 계획의 필수 검증이 아니다. + +### 테스트 커버리지 공백 + +- `TokenStore`는 현재 save/read/clear 구현이 있으나 mock secure storage 기반 테스트가 없다. 이 작업에서 `FlutterSecureStorage.setMockInitialValues` 기반 `test/token_store_test.dart`를 추가한다. +- `JenkinsClient`는 job/build/download stream 테스트가 있으나 저장된 credential 검증에 쓸 current user API가 없다. 이 작업에서 `fetchCurrentUser`와 200/401/403/parser 테스트를 추가한다. + +### 심볼 참조 + +- 변경 예정 symbol: `TokenStore`에 session/base URL API 추가. 기존 `readCredentials`, `saveCredentials`, `clearCredentials` call site는 `rg --sort path "readCredentials|saveCredentials|clearCredentials|TokenStore" lib test`로 확인하고 backward compatibility를 유지한다. +- 변경 예정 symbol: `JenkinsClient`에 `fetchCurrentUser` 추가. 기존 call site 변경 없음. +- 제거 예정 symbol: none. + +### 분할 판단 + +- split decision policy를 적용했다. +- shared task group: `agent-task/m-jenkins-credential/`. +- `01_session_foundation`: 저장된 Jenkins session config와 current-user 검증 API를 만든다. 의존성 없음. +- `02+01_app_wiring`: 01 완료 뒤 앱 루트와 artifact loader/downloader를 연결한다. `02+01_...` 디렉터리명으로 01의 `complete.log`에 의존한다. +- 분할 근거: storage/client foundation과 UI/app root wiring은 서로 다른 실패 모드와 테스트 범위를 갖는다. API foundation이 깨지면 UI wiring 계획을 다시 짜야 하므로 분리한다. + +### 범위 결정 근거 + +- WebView 로그인, crumb 기반 API token 자동 발급, token 폐기 UX, logout UI는 제외한다. 이들은 `jenkins-credential`의 별도 기능 Task이며 이 작업의 목적은 저장된 session을 검증할 foundation이다. +- `BuildsPage`의 build row/download UX는 이미 `artifact-browser` 완료 근거가 있으므로 변경하지 않는다. +- `macos/` entitlement 변경은 제외한다. 이 작업은 새 platform 권한을 요구하지 않는다. + +### 빌드 등급 + +- build lane: `local-G05`. +- review lane: `local-G05`. +- 근거: storage/client API와 단위 테스트 중심의 bounded 변경이며 remote runner에서 deterministic 검증 가능하다. + +## 구현 체크리스트 + +- [ ] `TokenStore`에 Jenkins base URL을 포함한 session config read/save/clear API를 추가하고 기존 credential API 호환성을 유지한다. +- [ ] `JenkinsClient`에 저장 credential 검증용 current-user API와 parser/error 처리를 추가한다. +- [ ] `test/token_store_test.dart`와 `test/jenkins_client_test.dart`에 session/current-user 정상 및 경계 테스트를 추가한다. +- [ ] `git diff --check`와 remote runner `flutter analyze`, `flutter test`를 실행해 결과를 기록한다. +- [ ] CODE_REVIEW-*-G??.md의 구현 에이전트 소유 섹션을 실제 구현 내용과 검증 출력으로 채운다. 이 항목이 완료되기 전에는 구현이 완료된 것이 아니다. + +### [API-1] Session config storage + +문제: [token_store.dart](/config/workspace/appsok/lib/src/services/token_store.dart:14)는 username/api token만 읽고 [token_store.dart](/config/workspace/appsok/lib/src/services/token_store.dart:25)는 credentials만 저장한다. 실제 앱 시작 시 [app.dart](/config/workspace/appsok/lib/src/app.dart:15)에서 Jenkins base URL을 알 방법이 없다. + +해결 방법: + +Before: + +```dart +14 Future readCredentials() async { +15 final username = await _storage.read(key: _usernameKey); +16 final apiToken = await _storage.read(key: _apiTokenKey); +17 +18 if (username == null || apiToken == null) { +19 return null; +20 } +21 +22 return JenkinsCredentials(username: username, apiToken: apiToken); +23 } +``` + +After: + +```dart +class JenkinsSessionConfig { + const JenkinsSessionConfig({required this.baseUrl, required this.credentials}); + + final Uri baseUrl; + final JenkinsCredentials credentials; +} + +Future readSession() async { ... } +Future saveSession(JenkinsSessionConfig session) async { ... } +Future clearSession() async { ... } +``` + +기존 `readCredentials`, `saveCredentials`, `clearCredentials`는 유지한다. `readSession`은 base URL, username, token 중 하나라도 없거나 base URL parse가 실패하면 `null`을 반환한다. `clearSession`은 base URL과 credential keys를 모두 삭제한다. + +수정 파일 및 체크리스트: + +- [ ] `lib/src/services/token_store.dart`: `_baseUrlKey`, `JenkinsSessionConfig`, `readSession`, `saveSession`, `clearSession` 추가. +- [ ] `lib/src/services/token_store.dart`: 기존 credential API가 기존 테스트/호출과 호환되도록 유지. +- [ ] `test/token_store_test.dart`: `FlutterSecureStorage.setMockInitialValues({})`로 mock storage 초기화. + +테스트 작성: + +- 추가: `test/token_store_test.dart` +- test names: + - `readSession returns null when config is incomplete` + - `saveSession and readSession round trip base url and credentials` + - `clearSession removes base url and credentials` + - `readCredentials remains backward compatible` + +중간 검증: + +```bash +ssh -o BatchMode=yes -o ConnectTimeout=10 toki@toki-labs.com "zsh -lc 'cd \"\$HOME/docker/services/code-server/data/volume/workspace/appsok\" && flutter test test/token_store_test.dart'" +``` + +기대 결과: 해당 파일의 모든 테스트 통과. + +### [API-2] Current user validation API + +문제: [jenkins_client.dart](/config/workspace/appsok/lib/src/services/jenkins_client.dart:44)는 job 목록 API, [jenkins_client.dart](/config/workspace/appsok/lib/src/services/jenkins_client.dart:68)는 build 목록 API만 제공한다. 저장 credential을 앱 시작 시 검증할 API가 없어 `jenkins-credential`의 `[startup-check]`를 구현할 foundation이 없다. + +해결 방법: + +Before: + +```dart +68 Future> fetchRecentBuilds({ +69 required Uri jobUrl, +70 required String jobName, +71 required JenkinsCredentials credentials, +72 }) async { +``` + +After: + +```dart +Future fetchCurrentUser({ + required Uri baseUrl, + required JenkinsCredentials credentials, +}) async { ... } + +class JenkinsUser { + const JenkinsUser({required this.id, required this.displayName}); + final String id; + final String displayName; +} +``` + +`fetchCurrentUser`는 `baseUrl` 아래 `whoAmI/api/json` 또는 Jenkins 사용자 확인용 Remote API endpoint를 호출하고 `_headers(credentials)`를 재사용한다. 401/403은 기존 `JenkinsClientException`으로 전달해 후속 wiring에서 auth failure와 network failure를 구분할 수 있게 한다. 응답 parser는 null/blank display name을 안전하게 fallback 처리한다. + +수정 파일 및 체크리스트: + +- [ ] `lib/src/services/jenkins_client.dart`: `JenkinsUser` 모델 추가. +- [ ] `lib/src/services/jenkins_client.dart`: `fetchCurrentUser` 추가, `_appendPath` 재사용. +- [ ] `test/jenkins_client_test.dart`: current user API URI, auth header, success parsing, forbidden error 테스트 추가. + +테스트 작성: + +- 추가/수정: `test/jenkins_client_test.dart` +- test names: + - `fetchCurrentUser requests whoAmI api with auth header` + - `fetchCurrentUser parses id and display name with fallback` + - `fetchCurrentUser throws JenkinsClientException on forbidden response` + +중간 검증: + +```bash +ssh -o BatchMode=yes -o ConnectTimeout=10 toki@toki-labs.com "zsh -lc 'cd \"\$HOME/docker/services/code-server/data/volume/workspace/appsok\" && flutter test test/jenkins_client_test.dart'" +``` + +기대 결과: 기존 Jenkins client 테스트와 신규 current-user 테스트 모두 통과. + +## 수정 파일 요약 + +| 파일 | 항목 | +|------|------| +| `lib/src/services/token_store.dart` | API-1 | +| `lib/src/services/jenkins_client.dart` | API-2 | +| `test/token_store_test.dart` | API-1 | +| `test/jenkins_client_test.dart` | API-2 | + +## 최종 검증 + +```bash +git diff --check +``` + +기대 결과: 출력 없음, exit code 0. + +```bash +ssh -o BatchMode=yes -o ConnectTimeout=10 toki@toki-labs.com "zsh -lc 'cd \"\$HOME/docker/services/code-server/data/volume/workspace/appsok\" && flutter analyze && flutter test'" +``` + +기대 결과: `No issues found!`와 `All tests passed!`. + +모든 코드 변경 완료 후 반드시 `CODE_REVIEW-*-G??.md`의 구현 에이전트 소유 섹션을 채운다. 이 파일 작성이 구현의 마지막 단계다. diff --git a/agent-task/archive/2026/06/m-jenkins-credential/01_session_foundation/plan_local_G06_1.log b/agent-task/archive/2026/06/m-jenkins-credential/01_session_foundation/plan_local_G06_1.log new file mode 100644 index 0000000..3c6f18d --- /dev/null +++ b/agent-task/archive/2026/06/m-jenkins-credential/01_session_foundation/plan_local_G06_1.log @@ -0,0 +1,125 @@ + + +# Plan - REVIEW_API + +## 이 파일을 읽는 구현 에이전트에게 + +이 작업은 이전 리뷰 `code_review_local_G05_0.log`의 Required 이슈만 해결한다. 구현 후 active `CODE_REVIEW-local-G06.md`의 구현 에이전트 소유 섹션을 채워야 완료된다. 검증 명령은 계획에 적힌 대로 실행하고 실제 stdout/stderr를 붙여 넣은 뒤, active 파일을 그대로 둔 채 리뷰 준비를 보고한다. `코드리뷰 결과`, log archive, `complete.log`, task directory archive는 code-review 전용이다. + +구현 중 사용자만 결정할 수 있는 범위 변경, 사용자 소유 secret/외부 Jenkins 준비, 또는 이 계획과 충돌하는 요구가 발견되면 사용자에게 직접 묻지 않는다. `CODE_REVIEW-local-G06.md`의 `사용자 리뷰 요청` 섹션에 결정 항목, 근거, 실행한 명령과 출력, 재개 조건을 기록하고 멈춘다. 후속 에이전트가 명령 재실행이나 산출물 수집으로 닫을 수 있는 증거 공백은 사용자 리뷰 요청이 아니라 검증 결과 또는 계획 대비 변경 사항으로 기록한다. + +## 배경 + +첫 리뷰에서 `JenkinsClient.fetchCurrentUser`의 표시명 fallback이 계획/설계와 다르게 동작하는 Required 이슈가 확인됐다. 현재 구현은 `fullName`이 빈 문자열이면 `name` 후보를 확인하지 않고 `id`로 떨어질 수 있다. 후속 wiring은 `JenkinsUser.displayName`을 사용자 표시명으로 사용할 예정이므로 parser 계약을 정확히 닫아야 한다. + +## 사용자 리뷰 요청 흐름 + +구현 중 blocker는 active review stub의 `사용자 리뷰 요청` 섹션에 기록한다. 이 섹션은 `agent-ops/skills/common/_templates/implementation-user-review-request-section.md`에서 복사된 형식을 사용한다. 구현 에이전트는 직접 사용자 프롬프트, 채팅 선택지, `request_user_input`, `USER_REVIEW.md` 생성, log archive, `complete.log` 작성을 하지 않는다. + +## 분석 결과 + +### 읽은 파일 + +- `agent-task/m-jenkins-credential/01_session_foundation/code_review_local_G05_0.log` +- `agent-task/m-jenkins-credential/01_session_foundation/plan_local_G05_0.log` +- `agent-ops/rules/project/domain/artifact-flow/rules.md` +- `agent-test/local/rules.md` +- `agent-test/local/artifact-flow-smoke.md` +- `lib/src/services/jenkins_client.dart` +- `test/jenkins_client_test.dart` + +### 테스트 환경 규칙 + +- test_env: local. +- matched profile: `agent-test/local/artifact-flow-smoke.md`. +- 적용 명령: remote runner checkout에서 `flutter test test/jenkins_client_test.dart`, `flutter analyze`, `flutter test`; 보조로 현재 checkout `git diff --check`. +- 실제 Jenkins endpoint/credential은 필요하지 않으며 mock HTTP 테스트로 검증한다. + +### 범위 결정 근거 + +- `TokenStore` session API는 이번 Required 이슈와 무관하므로 변경하지 않는다. +- 앱 root wiring, WebView 로그인, 실제 Jenkins smoke는 이 follow-up 범위가 아니다. +- 첫 리뷰의 유일한 Required 이슈만 닫는다. + +### 빌드 등급 + +- build lane: `local-G06`. +- review lane: `local-G06`. +- 근거: 단일 parser edge case와 테스트 보강이며 deterministic local/remote runner 검증으로 판단 가능하다. + +## 구현 체크리스트 + +- [ ] `fetchCurrentUser` display name parser가 `fullName`, `name`, `id` 중 첫 nonblank 값을 선택하도록 수정한다. +- [ ] `test/jenkins_client_test.dart`에 blank `fullName`과 nonblank `name` 조합이 `name`으로 fallback되는 테스트를 추가한다. +- [ ] `git diff --check`와 remote runner `flutter test test/jenkins_client_test.dart`, `flutter analyze`, `flutter test`를 실행해 결과를 기록한다. +- [ ] CODE_REVIEW-*-G??.md의 구현 에이전트 소유 섹션을 실제 구현 내용과 검증 출력으로 채운다. 이 항목이 완료되기 전에는 구현이 완료된 것이 아니다. + +### [REVIEW_API-1] Current-user display name fallback + +문제: [jenkins_client.dart](/config/workspace/appsok/lib/src/services/jenkins_client.dart:204)는 `fullName`이 빈 문자열이면 null-coalescing이 멈춰 `name` 후보를 건너뛴다. + +해결 방법: + +Before: + +```dart +final displayName = + (json['fullName'] as String?)?.trim() ?? + (json['name'] as String?)?.trim() ?? + id; +``` + +After: + +```dart +final displayName = _firstNonBlank([ + json['fullName'] as String?, + json['name'] as String?, + id, +]); +``` + +helper 형태는 코드 스타일에 맞게 조정해도 되지만 빈 문자열과 whitespace는 다음 후보로 넘겨야 한다. + +수정 파일 및 체크리스트: + +- [ ] `lib/src/services/jenkins_client.dart`: blank 값을 null처럼 다루는 fallback 구현. +- [ ] `test/jenkins_client_test.dart`: `{'id': 'grace', 'fullName': '', 'name': 'Grace H.'}`가 `displayName == 'Grace H.'`가 되는 테스트 추가. +- [ ] 기존 `fullName` 성공, `id` fallback, forbidden response 테스트가 계속 통과하는지 확인. + +테스트 작성: + +- 수정: `test/jenkins_client_test.dart` +- test name 후보: + - `fetchCurrentUser falls back to name when fullName is blank` + +중간 검증: + +```bash +ssh -o BatchMode=yes -o ConnectTimeout=10 toki@toki-labs.com "zsh -lc 'cd \"\$HOME/docker/services/code-server/data/volume/workspace/appsok\" && flutter test test/jenkins_client_test.dart'" +``` + +기대 결과: 기존 Jenkins client 테스트와 신규 fallback 테스트가 모두 통과. + +## 수정 파일 요약 + +| 파일 | 항목 | +|------|------| +| `lib/src/services/jenkins_client.dart` | REVIEW_API-1 | +| `test/jenkins_client_test.dart` | REVIEW_API-1 | + +## 최종 검증 + +```bash +git diff --check +``` + +기대 결과: 출력 없음, exit code 0. + +```bash +ssh -o BatchMode=yes -o ConnectTimeout=10 toki@toki-labs.com "zsh -lc 'cd \"\$HOME/docker/services/code-server/data/volume/workspace/appsok\" && flutter analyze && flutter test'" +``` + +기대 결과: `No issues found!`와 `All tests passed!`. + +모든 코드 변경 완료 후 반드시 `CODE_REVIEW-*-G??.md`의 구현 에이전트 소유 섹션을 채운다. 이 파일 작성이 구현의 마지막 단계다. diff --git a/agent-task/m-jenkins-credential/02+01_app_wiring/CODE_REVIEW-local-G06.md b/agent-task/m-jenkins-credential/02+01_app_wiring/CODE_REVIEW-local-G06.md new file mode 100644 index 0000000..10ea7a6 --- /dev/null +++ b/agent-task/m-jenkins-credential/02+01_app_wiring/CODE_REVIEW-local-G06.md @@ -0,0 +1,140 @@ + + +# 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-10 +task=m-jenkins-credential/02+01_app_wiring, plan=1, tag=API + +## Roadmap Targets + +- Milestone: `agent-roadmap/phase/usable-mvp/milestones/jenkins-credential.md` +- Task ids: + - `startup-check`: 앱 시작 시 Keychain credential을 읽고 Jenkins 사용자 확인 API로 조용히 검증한다. + - `auth-state`: 검증 성공 시 로그인 화면을 건너뛰고 build 목록으로 진입한다. +- Completion mode: check-on-pass + +## 이 파일을 읽는 리뷰 에이전트에게 + +> **[REVIEW AGENT ONLY]** 아래 종결 절차는 코드리뷰 에이전트 전용이다. 구현 에이전트는 이 섹션을 실행하지 않는다. + +각 항목의 구현을 실제 소스 파일과 대조하고, `검증 결과` 섹션의 출력이 코드와 일치하는지 확인하세요. +리뷰 완료는 아래 순서까지 끝난 상태를 의미합니다. + +1. 판정을 append한다. +2. `CODE_REVIEW-local-G06.md` -> `code_review_local_G06_N.log`, `PLAN-local-G06.md` -> `plan_local_G06_M.log`로 아카이브한다. +3. PASS이면 `complete.log` 작성 후 active task 디렉터리를 `agent-task/archive/YYYY/MM/m-jenkins-credential/02+01_app_wiring/`로 이동한다. 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-jenkins-credential`이면 완료 이벤트 메타데이터를 보고한다. roadmap 상태 체크와 `update-roadmap` 호출은 런타임 책임이다. +5. 적용 가능한 `코드리뷰 전용 체크리스트` 항목을 최종 `.log` 위치에서 체크한 뒤 보고한다. + +--- + +## 구현 항목별 완료 여부 + +| 항목 | 완료 여부 | +|------|---------| +| [API-1] Artifact session service | [ ] | +| [API-2] App root production wiring | [ ] | + +## 구현 체크리스트 + +- [ ] `01_session_foundation`의 `complete.log` 존재를 확인하고, 없으면 구현을 시작하지 않고 사용자 리뷰 요청이 아닌 선행 의존성 미충족으로 기록한다. +- [ ] 저장된 Jenkins session을 검증하고 job/build/download/stage/cleanup 함수를 제공하는 artifact session service를 추가한다. +- [ ] `AppSokApp` 기본 경로가 저장 session 검증 성공 시 `AppSokShell`에 production loader/downloader/stager/cleaner를 주입하도록 연결한다. +- [ ] stored session이 없거나 검증 실패한 경우 secret을 노출하지 않고 기존 연결 필요/비활성 상태를 유지한다. +- [ ] artifact URL 조립과 `AppSokApp` 기본 경로 회귀 테스트를 추가한다. +- [ ] `git diff --check`와 remote runner `flutter analyze`, `flutter test`를 실행해 결과를 기록한다. +- [ ] CODE_REVIEW-*-G??.md의 구현 에이전트 소유 섹션을 실제 구현 내용과 검증 출력으로 채운다. 이 항목이 완료되기 전에는 구현이 완료된 것이 아니다. + +## 코드리뷰 전용 체크리스트 + +> **[REVIEW AGENT ONLY]** 이 체크리스트는 코드리뷰 에이전트만 사용한다. +> 구현 에이전트는 이 섹션을 수정하거나 체크하지 않는다. + +- [ ] `코드리뷰 결과`에 `PASS`, `WARN`, `FAIL` 중 하나의 판정을 append한다. +- [ ] 판정과 `차원별 평가`, Required/Suggested/Nit 분류가 서로 일치한다. +- [ ] active `CODE_REVIEW-*-G??.md`를 `code_review_{review_lane}_GNN_N.log`로 아카이브한다. +- [ ] active `PLAN-*-G??.md`를 `plan_{build_lane}_GNN_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/{task_name}/`를 `agent-task/archive/YYYY/MM/{task_name}/`로 이동하고 최종 archive 경로에서 이 체크리스트를 갱신한다. +- [ ] PASS이고 task group이 `m-`이면 런타임이 읽을 완료 이벤트 메타데이터를 보고하고, roadmap 수정이나 `update-roadmap` 직접 호출을 하지 않는다. +- [ ] PASS split 작업이면 이동 후 빈 active parent `agent-task/{task_group}/`를 제거하거나, 남은 sibling/file이 있어 유지했다고 확인한다. +- [ ] WARN/FAIL이고 user-review gate가 트리거되지 않았으면 다음 active `PLAN-{build_lane}-GNN.md`와 `CODE_REVIEW-{review_lane}-GNN.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`을 호출하지 않는다. 후속 에이전트가 명령 재실행이나 산출물 수집으로 해소할 수 있는 검증 증거 공백만으로는 사용자 리뷰 요청을 작성하지 않는다._ + +- 상태: 없음 +- 사유 유형: 없음 +- 결정 필요: 없음 +- 차단 근거: 없음 +- 실행한 검증/명령: 없음 +- 자동 후속 불가 이유: 없음 +- 재개 조건: 없음 + +## 리뷰어를 위한 체크포인트 + +- `02+01_app_wiring` 구현 전 01 predecessor `complete.log` 확인이 실제로 수행됐는지 본다. +- `AppSokShell`이 Jenkins API/Keychain을 직접 호출하지 않고 service/root wiring만 받는지 확인한다. +- 저장 session 없음/검증 실패 경로에서 token이나 private endpoint가 UI, debug log, test fixture에 노출되지 않는지 확인한다. +- artifact URL이 Jenkins build URL 아래 `artifact/`로 안전하게 조립되는지 확인한다. + +## 검증 결과 + +_구현 에이전트가 각 중간 검증 및 최종 검증 명령 실행 후 출력을 여기에 붙여 넣는다._ + +필수 규칙: +- 검증 명령은 고정된 계약이다. 임의로 대체하지 않는다. +- 대체가 필요하면 `계획 대비 변경 사항`에 이유와 대체 명령을 기록한다. +- `검증 결과`에는 실제 stdout/stderr를 붙여 넣는다. +- 사용자 리뷰 요청으로 명령을 끝까지 실행하지 못했다면 `사용자 리뷰 요청`에 실행한 명령, 실제 출력, 미실행 명령의 사유를 기록한다. +- mobile/UI hang, timeout, 또는 2분 무진행은 blind retry를 중단하고 focused rerun 명령과 screenshot/window/UI-tree evidence path를 남기며, 불가능하면 정확한 사유를 남긴다. + +### API-1 중간 검증 +```bash +$ ssh -o BatchMode=yes -o ConnectTimeout=10 toki@toki-labs.com "zsh -lc 'cd \"\$HOME/docker/services/code-server/data/volume/workspace/appsok\" && flutter test test/jenkins_artifact_session_test.dart'" +(output) +``` + +### API-2 중간 검증 +```bash +$ ssh -o BatchMode=yes -o ConnectTimeout=10 toki@toki-labs.com "zsh -lc 'cd \"\$HOME/docker/services/code-server/data/volume/workspace/appsok\" && flutter test test/widget_test.dart'" +(output) +``` + +### 최종 검증 +```bash +$ git diff --check +(output) + +$ ssh -o BatchMode=yes -o ConnectTimeout=10 toki@toki-labs.com "zsh -lc 'cd \"\$HOME/docker/services/code-server/data/volume/workspace/appsok\" && flutter analyze && flutter test'" +(output) +``` + +--- + +> **[IMPLEMENTING AGENT — BEFORE SAVING] Have you filled in every implementation-owned section: completion table, implementation checklist, changes from plan, design decisions, and verification output?** +> If anything is blank, go back and fill it in before saving this file. +> Leave review-agent-only sections unchanged. diff --git a/agent-task/m-jenkins-credential/02+01_app_wiring/PLAN-local-G06.md b/agent-task/m-jenkins-credential/02+01_app_wiring/PLAN-local-G06.md new file mode 100644 index 0000000..2b5e6e4 --- /dev/null +++ b/agent-task/m-jenkins-credential/02+01_app_wiring/PLAN-local-G06.md @@ -0,0 +1,266 @@ + + +# Plan - API + +## 이 파일을 읽는 구현 에이전트에게 + +이 작업은 `agent-task/m-jenkins-credential/01_session_foundation/complete.log`가 생긴 뒤 구현한다. 구현 후 active `CODE_REVIEW-local-G06.md`의 구현 에이전트 소유 섹션을 채워야 완료된다. 검증 명령은 계획에 적힌 대로 실행하고 실제 stdout/stderr를 붙여 넣은 뒤, active 파일을 그대로 둔 채 리뷰 준비를 보고한다. `코드리뷰 결과`, log archive, `complete.log`, task directory archive는 code-review 전용이다. + +구현 중 사용자만 결정할 수 있는 범위 변경, 사용자 소유 secret/외부 Jenkins 준비, 또는 이 계획과 충돌하는 요구가 발견되면 사용자에게 직접 묻지 않는다. `CODE_REVIEW-local-G06.md`의 `사용자 리뷰 요청` 섹션에 결정 항목, 근거, 실행한 명령과 출력, 재개 조건을 기록하고 멈춘다. 후속 에이전트가 명령 재실행이나 산출물 수집으로 닫을 수 있는 증거 공백은 사용자 리뷰 요청이 아니라 검증 결과 또는 계획 대비 변경 사항으로 기록한다. + +## 배경 + +`Artifact 탐색과 다운로드`의 코드레벨 종료 검토에서 실제 앱 루트가 Jenkins artifact flow에 연결되지 않는 Required 이슈가 나왔다. 01 foundation이 저장 session과 credential 검증 API를 제공하면, 앱 루트는 이 foundation을 사용해 저장된 session이 있을 때 job/build/download loader를 `AppSokShell`에 연결해야 한다. 이 계획은 WebView token 발급 전체가 아니라 저장된 session 복원 성공 시 artifact browser가 production path에서 동작하는 최소 wiring을 다룬다. + +## 사용자 리뷰 요청 흐름 + +구현 중 blocker는 active review stub의 `사용자 리뷰 요청` 섹션에 기록한다. 이 섹션은 `agent-ops/skills/common/_templates/implementation-user-review-request-section.md`에서 복사된 형식을 사용한다. 구현 에이전트는 직접 사용자 프롬프트, 채팅 선택지, `request_user_input`, `USER_REVIEW.md` 생성, log archive, `complete.log` 작성을 하지 않는다. + +## Roadmap Targets + +- Milestone: `agent-roadmap/phase/usable-mvp/milestones/jenkins-credential.md` +- Task ids: + - `startup-check`: 앱 시작 시 Keychain credential을 읽고 Jenkins 사용자 확인 API로 조용히 검증한다. + - `auth-state`: 검증 성공 시 로그인 화면을 건너뛰고 build 목록으로 진입한다. +- Completion mode: check-on-pass + +## 분석 결과 + +### 읽은 파일 + +- `agent-ops/rules/project/rules.md` +- `agent-ops/rules/project/domain/artifact-flow/rules.md` +- `agent-ops/rules/project/domain/app-shell/rules.md` +- `agent-test/local/rules.md` +- `agent-test/local/artifact-flow-smoke.md` +- `agent-roadmap/current.md` +- `agent-roadmap/phase/usable-mvp/PHASE.md` +- `agent-roadmap/phase/usable-mvp/milestones/artifact-browser.md` +- `agent-roadmap/phase/usable-mvp/milestones/jenkins-credential.md` +- `pubspec.yaml` +- `lib/src/app.dart` +- `lib/src/features/app_shell.dart` +- `lib/src/features/builds/builds_page.dart` +- `lib/src/features/settings/settings_page.dart` +- `lib/src/models/jenkins_build.dart` +- `lib/src/models/pending_install.dart` +- `lib/src/services/artifact_staging_service.dart` +- `lib/src/services/jenkins_client.dart` +- `lib/src/services/token_store.dart` +- `test/artifact_staging_service_test.dart` +- `test/builds_page_test.dart` +- `test/jenkins_client_test.dart` +- `test/widget_test.dart` + +### 테스트 환경 규칙 + +- test_env: local. +- `agent-test/local/rules.md` 존재 및 읽음. +- matched profile: `agent-test/local/artifact-flow-smoke.md` 읽음. +- 적용 명령: remote runner checkout에서 `flutter analyze`, `flutter test`; 보조로 현재 checkout `git diff --check`. +- 구조상 빈/skeleton 규칙 없음. +- `<확인 필요>` 값 없음. +- 실제 Jenkins endpoint/credential은 제공되지 않았으므로 mock HTTP와 stored-session test로 검증한다. 실제 Jenkins smoke는 sandbox endpoint가 제공될 때만 보조 검증이다. + +### 테스트 커버리지 공백 + +- [app.dart](/config/workspace/appsok/lib/src/app.dart:15)의 기본 `AppSokApp` 경로가 artifact loader를 주입하지 않는 문제를 덮는 widget test가 없다. 이 작업에서 stored session + mock HTTP로 기본 앱 루트가 job list를 보여주는 회귀 테스트를 추가한다. +- artifact download URL 조립은 현재 production call site가 없어 테스트되지 않는다. 이 작업에서 build URL과 artifact relative path로 `.../artifact/` 요청을 만드는 service test를 추가한다. + +### 심볼 참조 + +- 변경 예정 symbol: `AppSokApp` 생성자에 testable dependency injection 추가. call sites: [main.dart](/config/workspace/appsok/lib/main.dart:6), [widget_test.dart](/config/workspace/appsok/test/widget_test.dart:30), [widget_test.dart](/config/workspace/appsok/test/widget_test.dart:46), [widget_test.dart](/config/workspace/appsok/test/widget_test.dart:757). +- 변경 예정 symbol: `AppSokShell` loader/downloader props는 유지한다. 기존 test call sites는 `rg --sort path "AppSokShell\\(" lib test`로 재확인한다. +- 신규 symbol 후보: `JenkinsArtifactSession` 또는 동등한 service wrapper. +- 제거 예정 symbol: none. + +### 분할 판단 + +- split decision policy를 적용했다. +- shared task group: `agent-task/m-jenkins-credential/`. +- 이 계획은 `02+01_app_wiring`이며 predecessor `01_session_foundation`의 `complete.log`가 필요하다. +- 현재 predecessor 상태: active `agent-task/m-jenkins-credential/01_session_foundation/PLAN-local-G05.md`가 생성될 예정이며 아직 `complete.log`는 없다. +- 분할 근거: 앱 root/widget wiring은 01의 storage/client API에 의존한다. 01이 PASS되지 않으면 이 계획 구현을 시작하지 않는다. + +### 범위 결정 근거 + +- WebView 로그인, crumb/token 자동 발급, token 폐기 UX, logout UI는 제외한다. 이 계획은 저장된 session이 이미 있을 때 복원과 artifact flow wiring만 구현한다. +- `SettingsPage`의 최종 로그인 UX는 제외한다. 임시 manual token UX를 기본 UX로 만들면 roadmap의 WebView token 방향과 충돌할 수 있다. +- `DevicesPage`의 실제 ADB install 구현은 제외한다. handoff 이후는 `USB 설치와 device 선택` Milestone 책임이다. +- `BuildsPage` 내부 UI 상태는 기존 completed artifact-browser 범위로 유지한다. + +### 빌드 등급 + +- build lane: `local-G06`. +- review lane: `local-G06`. +- 근거: app root, service wrapper, widget tests를 함께 건드리지만 범위와 검증이 bounded하다. 보안/인증 UX 전체가 아니라 stored-session wiring이다. + +## 구현 체크리스트 + +- [ ] `01_session_foundation`의 `complete.log` 존재를 확인하고, 없으면 구현을 시작하지 않고 사용자 리뷰 요청이 아닌 선행 의존성 미충족으로 기록한다. +- [ ] 저장된 Jenkins session을 검증하고 job/build/download/stage/cleanup 함수를 제공하는 artifact session service를 추가한다. +- [ ] `AppSokApp` 기본 경로가 저장 session 검증 성공 시 `AppSokShell`에 production loader/downloader/stager/cleaner를 주입하도록 연결한다. +- [ ] stored session이 없거나 검증 실패한 경우 secret을 노출하지 않고 기존 연결 필요/비활성 상태를 유지한다. +- [ ] artifact URL 조립과 `AppSokApp` 기본 경로 회귀 테스트를 추가한다. +- [ ] `git diff --check`와 remote runner `flutter analyze`, `flutter test`를 실행해 결과를 기록한다. +- [ ] CODE_REVIEW-*-G??.md의 구현 에이전트 소유 섹션을 실제 구현 내용과 검증 출력으로 채운다. 이 항목이 완료되기 전에는 구현이 완료된 것이 아니다. + +## 의존 관계 및 구현 순서 + +- 이 subtask directory는 `02+01_app_wiring`이므로 `01_session_foundation`에만 의존한다. +- 구현 전 `agent-task/m-jenkins-credential/01_session_foundation/complete.log` 또는 archive의 matching `agent-task/archive/*/*/m-jenkins-credential/01_session_foundation/complete.log`가 있어야 한다. +- 이 계획은 01 외 추가 의존성을 만들지 않는다. + +### [API-1] Artifact session service + +문제: [app_shell.dart](/config/workspace/appsok/lib/src/features/app_shell.dart:21)는 loader/downloader를 받을 수 있지만, production service가 없다. [jenkins_client.dart](/config/workspace/appsok/lib/src/services/jenkins_client.dart:111)는 `downloadArtifactStream`을 받는 URL이 필요하고, 현재 codebase에는 `BuildArtifact.relativePath`를 build URL 아래 artifact URL로 바꾸는 production call site가 없다. + +해결 방법: + +Before: + +```dart +21 const AppSokShell({ +22 super.key, +23 this.jobLoader, +24 this.buildLoader, +25 this.artifactDownloader, +26 this.artifactStager, +27 this.artifactCleaner, +28 this.installer, +29 }); +``` + +After: + +```dart +final session = JenkinsArtifactSession( + store: tokenStore, + client: jenkinsClient, + stager: artifactStagingService, +); + +AppSokShell( + jobLoader: session.loadJobs, + buildLoader: session.loadBuilds, + artifactDownloader: session.downloadArtifact, + artifactStager: session.stageApk, + artifactCleaner: session.cleanup, +); +``` + +Service responsibilities: + +- read validated `JenkinsSessionConfig` from `TokenStore`. +- call `JenkinsClient.fetchCurrentUser` during restore/check. +- call `JenkinsClient.fetchJobs`, `fetchRecentBuilds`, `downloadArtifactStream` with stored credentials. +- build artifact URL as `build.url` + `artifact/` using URI path joining, not string concat that drops path segments. +- expose `ArtifactStagingService.stageApk` and `cleanup`. + +수정 파일 및 체크리스트: + +- [ ] `lib/src/services/jenkins_artifact_session.dart`: new service wrapper 추가. +- [ ] `lib/src/services/jenkins_artifact_session.dart`: artifact URL join helper는 encoded path segment를 보존한다. +- [ ] `test/jenkins_artifact_session_test.dart`: restore success/failure, job/build delegation, artifact URL 조립 테스트 추가. + +테스트 작성: + +- 추가: `test/jenkins_artifact_session_test.dart` +- test names: + - `restore validates stored session with current user api` + - `loadJobs delegates to JenkinsClient with stored base url and credentials` + - `downloadArtifact builds Jenkins artifact URL from build url and relative path` + - `returns unavailable state when session config is missing` + +중간 검증: + +```bash +ssh -o BatchMode=yes -o ConnectTimeout=10 toki@toki-labs.com "zsh -lc 'cd \"\$HOME/docker/services/code-server/data/volume/workspace/appsok\" && flutter test test/jenkins_artifact_session_test.dart'" +``` + +기대 결과: 신규 service tests 통과. + +### [API-2] App root production wiring + +문제: [app.dart](/config/workspace/appsok/lib/src/app.dart:15)는 `home: const AppSokShell()`만 사용한다. 따라서 production 앱은 [builds_page.dart](/config/workspace/appsok/lib/src/features/builds/builds_page.dart:135)의 `jobLoader == null` 분기로 들어가고, artifact-browser 기능이 실제 앱 경로에서 도달 불가능하다. + +해결 방법: + +Before: + +```dart +11 return MaterialApp( +12 debugShowCheckedModeBanner: false, +13 title: 'AppSok', +14 theme: AppTheme.light(), +15 home: const AppSokShell(), +16 ); +``` + +After: + +```dart +return MaterialApp( + debugShowCheckedModeBanner: false, + title: 'AppSok', + theme: AppTheme.light(), + home: AppSokShell( + jobLoader: sessionReady ? _session.loadJobs : null, + buildLoader: sessionReady ? _session.loadBuilds : null, + artifactDownloader: sessionReady ? _session.downloadArtifact : null, + artifactStager: _session.stageApk, + artifactCleaner: _session.cleanup, + ), +); +``` + +`AppSokApp`는 testability를 위해 optional dependencies를 받을 수 있게 한다. production default는 real `TokenStore`, `JenkinsClient`, `ArtifactStagingService`를 생성한다. app-shell rule에 맞춰 `AppSokShell` 안에서 Jenkins API/Keychain을 직접 호출하지 않고 root/service wiring만 수행한다. + +수정 파일 및 체크리스트: + +- [ ] `lib/src/app.dart`: `AppSokApp`를 stateful 또는 FutureBuilder 기반으로 변경하고 service dependency injection 추가. +- [ ] `lib/src/app.dart`: restore loading 중에도 shell layout이 크게 흔들리지 않도록 bounded loading/connection-required 상태 처리. +- [ ] `lib/src/features/app_shell.dart`: 필요 시 stager/cleaner props 전달만 유지하고 Jenkins API 직접 호출 금지. +- [ ] `test/widget_test.dart`: 기본 `AppSokApp` 경로 with stored session test 추가. + +테스트 작성: + +- 수정: `test/widget_test.dart` +- test names: + - `AppSokApp wires stored Jenkins session into builds page` + - `AppSokApp keeps Jenkins connection required state when no stored session exists` + - `AppSokApp does not expose token text on auth failure` + +중간 검증: + +```bash +ssh -o BatchMode=yes -o ConnectTimeout=10 toki@toki-labs.com "zsh -lc 'cd \"\$HOME/docker/services/code-server/data/volume/workspace/appsok\" && flutter test test/widget_test.dart'" +``` + +기대 결과: 기존 shell tests와 신규 app root wiring tests 모두 통과. + +## 수정 파일 요약 + +| 파일 | 항목 | +|------|------| +| `lib/src/services/jenkins_artifact_session.dart` | API-1 | +| `lib/src/app.dart` | API-2 | +| `lib/src/features/app_shell.dart` | API-2 | +| `test/jenkins_artifact_session_test.dart` | API-1 | +| `test/widget_test.dart` | API-2 | + +## 최종 검증 + +```bash +git diff --check +``` + +기대 결과: 출력 없음, exit code 0. + +```bash +ssh -o BatchMode=yes -o ConnectTimeout=10 toki@toki-labs.com "zsh -lc 'cd \"\$HOME/docker/services/code-server/data/volume/workspace/appsok\" && flutter analyze && flutter test'" +``` + +기대 결과: `No issues found!`와 `All tests passed!`. + +모든 코드 변경 완료 후 반드시 `CODE_REVIEW-*-G??.md`의 구현 에이전트 소유 섹션을 채운다. 이 파일 작성이 구현의 마지막 단계다. diff --git a/lib/src/app.dart b/lib/src/app.dart index 912f3a5..b2358f6 100644 --- a/lib/src/app.dart +++ b/lib/src/app.dart @@ -1,18 +1,61 @@ import 'package:flutter/material.dart'; import 'features/app_shell.dart'; +import 'services/artifact_staging_service.dart'; +import 'services/jenkins_artifact_session.dart'; +import 'services/jenkins_client.dart'; +import 'services/token_store.dart'; import 'theme/app_theme.dart'; -class AppSokApp extends StatelessWidget { - const AppSokApp({super.key}); +class AppSokApp extends StatefulWidget { + const AppSokApp({ + super.key, + this.tokenStore, + this.jenkinsClient, + this.artifactStagingService, + this.session, + }); + + final TokenStore? tokenStore; + final JenkinsClient? jenkinsClient; + final ArtifactStagingService? artifactStagingService; + final JenkinsArtifactSession? session; + + @override + State createState() => _AppSokAppState(); +} + +class _AppSokAppState extends State { + late final JenkinsArtifactSession _session = + widget.session ?? + JenkinsArtifactSession( + store: widget.tokenStore ?? TokenStore(), + client: widget.jenkinsClient ?? JenkinsClient(), + stager: widget.artifactStagingService ?? ArtifactStagingService(), + ); + + late final Future _startup = _session.restore(); @override Widget build(BuildContext context) { - return MaterialApp( - debugShowCheckedModeBanner: false, - title: 'AppSok', - theme: AppTheme.light(), - home: const AppSokShell(), + return FutureBuilder( + future: _startup, + builder: (context, snapshot) { + final isReady = snapshot.data ?? false; + + return MaterialApp( + debugShowCheckedModeBanner: false, + title: 'AppSok', + theme: AppTheme.light(), + home: AppSokShell( + jobLoader: isReady ? _session.loadJobs : null, + buildLoader: isReady ? _session.loadBuilds : null, + artifactDownloader: isReady ? _session.downloadArtifact : null, + artifactStager: isReady ? _session.stageApk : null, + artifactCleaner: isReady ? _session.cleanup : null, + ), + ); + }, ); } } diff --git a/lib/src/features/builds/builds_page.dart b/lib/src/features/builds/builds_page.dart index ba532c8..655c303 100644 --- a/lib/src/features/builds/builds_page.dart +++ b/lib/src/features/builds/builds_page.dart @@ -814,10 +814,13 @@ class _InstallCtaState extends State<_InstallCta> { const SizedBox(width: 12), ElevatedButton.icon( key: const ValueKey('install-cta-button'), - onPressed: widget.onInstallRequested == null || _stagedApk == null + onPressed: + widget.onInstallRequested == null || + _stagedApk == null || + _handoffRequested ? null : () { - _handoffRequested = true; + setState(() => _handoffRequested = true); widget.onInstallRequested!( widget.item, widget.artifact, diff --git a/lib/src/services/jenkins_artifact_session.dart b/lib/src/services/jenkins_artifact_session.dart new file mode 100644 index 0000000..a0b61d3 --- /dev/null +++ b/lib/src/services/jenkins_artifact_session.dart @@ -0,0 +1,119 @@ +import 'dart:io'; + +import 'artifact_staging_service.dart'; +import 'jenkins_client.dart'; +import 'token_store.dart'; + +import '../models/jenkins_build.dart'; + +class JenkinsArtifactSession { + JenkinsArtifactSession({ + required this.store, + required this.client, + required this.stager, + }); + + final TokenStore store; + final JenkinsClient client; + final ArtifactStagingService stager; + + JenkinsSessionConfig? _session; + + Future restore() async { + final session = await store.readSession(); + if (session == null) { + _session = null; + return false; + } + + try { + await client.fetchCurrentUser( + baseUrl: session.baseUrl, + credentials: session.credentials, + ); + _session = session; + return true; + } on JenkinsClientException catch (error) { + if (error.statusCode == 401 || error.statusCode == 403) { + await store.clearSession(); + } + _session = null; + return false; + } on IOException { + _session = null; + return false; + } + } + + bool get isRestored => _session != null; + + Future> loadJobs() async { + final session = _session; + if (session == null) { + throw StateError('Jenkins session is not restored'); + } + + return client.fetchJobs( + baseUrl: session.baseUrl, + credentials: session.credentials, + ); + } + + Future> loadBuilds(JenkinsJob job) async { + final session = _session; + if (session == null) { + throw StateError('Jenkins session is not restored'); + } + + return client.fetchRecentBuilds( + jobUrl: job.url, + jobName: job.name, + credentials: session.credentials, + ); + } + + DownloadTask downloadArtifact(JenkinsBuild build, BuildArtifact artifact) { + final session = _session; + if (session == null) { + throw StateError('Jenkins session is not restored'); + } + + final artifactUrl = _artifactUrl(build: build, artifact: artifact); + return client.downloadArtifactStream( + artifactUrl: artifactUrl, + credentials: session.credentials, + ); + } + + Future stageApk({ + required JenkinsBuild build, + required BuildArtifact artifact, + required Stream> byteStream, + }) { + return stager.stageApk( + build: build, + artifact: artifact, + byteStream: byteStream, + ); + } + + Future cleanup(String path) async => stager.cleanup(path); + + Uri _artifactUrl({ + required JenkinsBuild build, + required BuildArtifact artifact, + }) { + final buildPath = build.url.path; + final normalizedBuildPath = buildPath.endsWith('/') + ? buildPath.substring(0, buildPath.length - 1) + : buildPath; + final normalizedRelativePath = artifact.relativePath.replaceFirst( + RegExp(r'^/+'), + '', + ); + + return build.url.replace( + path: '$normalizedBuildPath/artifact/$normalizedRelativePath', + ); + } +} diff --git a/lib/src/services/jenkins_client.dart b/lib/src/services/jenkins_client.dart index 7c0a2fe..c64a487 100644 --- a/lib/src/services/jenkins_client.dart +++ b/lib/src/services/jenkins_client.dart @@ -188,6 +188,39 @@ class JenkinsClient { return DownloadTask._(controller.stream, cancel); } + Future fetchCurrentUser({ + required Uri baseUrl, + required JenkinsCredentials credentials, + }) async { + final uri = baseUrl.replace( + path: _appendPath(baseUrl.path, 'whoAmI/api/json'), + ); + final response = await _client.get(uri, headers: _headers(credentials)); + + _throwIfFailed(response); + + final json = jsonDecode(response.body) as Map; + final id = (json['id'] as String?)?.trim() ?? ''; + final displayName = _firstNonBlank([ + json['fullName'] as String?, + json['name'] as String?, + id, + ]); + + return JenkinsUser(id: id, displayName: displayName.isEmpty ? id : displayName); + } + + String _firstNonBlank(List values) { + for (final value in values) { + final trimmed = value?.trim(); + if (trimmed != null && trimmed.isNotEmpty) { + return trimmed; + } + } + + return ''; + } + Map _headers(JenkinsCredentials credentials) { final raw = '${credentials.username}:${credentials.apiToken}'; @@ -221,6 +254,13 @@ class JenkinsCredentials { final String apiToken; } +class JenkinsUser { + const JenkinsUser({required this.id, required this.displayName}); + + final String id; + final String displayName; +} + class JenkinsClientException implements Exception { const JenkinsClientException({ required this.statusCode, diff --git a/lib/src/services/token_store.dart b/lib/src/services/token_store.dart index 506e552..28977a1 100644 --- a/lib/src/services/token_store.dart +++ b/lib/src/services/token_store.dart @@ -2,12 +2,23 @@ import 'package:flutter_secure_storage/flutter_secure_storage.dart'; import 'jenkins_client.dart'; +class JenkinsSessionConfig { + const JenkinsSessionConfig({ + required this.baseUrl, + required this.credentials, + }); + + final Uri baseUrl; + final JenkinsCredentials credentials; +} + class TokenStore { TokenStore({FlutterSecureStorage? storage}) : _storage = storage ?? const FlutterSecureStorage(); static const _usernameKey = 'jenkins.username'; static const _apiTokenKey = 'jenkins.apiToken'; + static const _baseUrlKey = 'jenkins.baseUrl'; final FlutterSecureStorage _storage; @@ -31,4 +42,42 @@ class TokenStore { await _storage.delete(key: _usernameKey); await _storage.delete(key: _apiTokenKey); } + + Future readSession() async { + final baseUrlRaw = await _storage.read(key: _baseUrlKey); + final username = await _storage.read(key: _usernameKey); + final apiToken = await _storage.read(key: _apiTokenKey); + + if (baseUrlRaw == null || username == null || apiToken == null) { + return null; + } + + final baseUrl = Uri.tryParse(baseUrlRaw); + if (baseUrl == null) { + return null; + } + + return JenkinsSessionConfig( + baseUrl: baseUrl, + credentials: JenkinsCredentials(username: username, apiToken: apiToken), + ); + } + + Future saveSession(JenkinsSessionConfig session) async { + await _storage.write(key: _baseUrlKey, value: session.baseUrl.toString()); + await _storage.write( + key: _usernameKey, + value: session.credentials.username, + ); + await _storage.write( + key: _apiTokenKey, + value: session.credentials.apiToken, + ); + } + + Future clearSession() async { + await _storage.delete(key: _baseUrlKey); + await _storage.delete(key: _usernameKey); + await _storage.delete(key: _apiTokenKey); + } } diff --git a/test/builds_page_test.dart b/test/builds_page_test.dart index eaad6b4..74bec05 100644 --- a/test/builds_page_test.dart +++ b/test/builds_page_test.dart @@ -1010,6 +1010,61 @@ void main() { expect(handoffStaged?.sizeBytes, 1024); }); + testWidgets('disables verified install handoff after first request', ( + tester, + ) async { + var handoffCount = 0; + + await tester.pumpWidget( + _wrap( + BuildsPage( + jobLoader: () async => _sampleJobs(), + buildLoader: (_) async => [ + _makeBuild( + number: 7, + artifacts: const [ + BuildArtifact( + fileName: 'app-release.apk', + relativePath: 'outputs/app-release.apk', + ), + ], + ), + ], + artifactDownloader: taskDownloader(() async* { + yield List.filled(1024, 1); + }), + artifactStager: + ({required build, required artifact, required byteStream}) async { + await byteStream.drain(); + return const StagedApk( + path: '/tmp/staged/app-release.apk', + sizeBytes: 1024, + ); + }, + onInstallRequested: (_, _, _) => handoffCount++, + ), + ), + ); + await tester.pumpAndSettle(); + await tester.tap(find.text('android-app')); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(const ValueKey('build-row-7'))); + await tester.pump(); + await tester.tap(find.byKey(const ValueKey('install-cta-button'))); + await tester.pumpAndSettle(); + + await tester.tap(find.byKey(const ValueKey('install-cta-button'))); + await tester.pump(); + await tester.tap(find.byKey(const ValueKey('install-cta-button'))); + await tester.pump(); + + expect(handoffCount, 1); + final button = tester.widget( + find.byKey(const ValueKey('install-cta-button')), + ); + expect(button.onPressed, isNull); + }); + testWidgets('cleans verified staged apk when abandoned before handoff', ( tester, ) async { diff --git a/test/jenkins_artifact_session_test.dart b/test/jenkins_artifact_session_test.dart new file mode 100644 index 0000000..e7a3088 --- /dev/null +++ b/test/jenkins_artifact_session_test.dart @@ -0,0 +1,169 @@ +import 'dart:convert'; + +import 'package:flutter_secure_storage/flutter_secure_storage.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:http/http.dart' as http; +import 'package:http/testing.dart'; + +import 'package:appsok/src/models/jenkins_build.dart'; +import 'package:appsok/src/services/artifact_staging_service.dart'; +import 'package:appsok/src/services/jenkins_artifact_session.dart'; +import 'package:appsok/src/services/jenkins_client.dart'; +import 'package:appsok/src/services/token_store.dart'; + +void main() { + const credentials = JenkinsCredentials(username: 'user', apiToken: 'token'); + const baseUrl = 'https://jenkins.example'; + + setUp(() { + FlutterSecureStorage.setMockInitialValues({}); + }); + + test('restore validates stored session with current user api', () async { + FlutterSecureStorage.setMockInitialValues({ + 'jenkins.baseUrl': baseUrl, + 'jenkins.username': credentials.username, + 'jenkins.apiToken': credentials.apiToken, + }); + + Uri? capturedUri; + Map? capturedHeaders; + + final session = JenkinsArtifactSession( + store: TokenStore(), + client: JenkinsClient( + client: MockClient((request) async { + capturedUri = request.url; + capturedHeaders = request.headers; + + if (request.url.path.endsWith('whoAmI/api/json')) { + return http.Response(jsonEncode({'id': 'user'}), 200); + } + + return http.Response('unexpected', 400); + }), + ), + stager: ArtifactStagingService(), + ); + + final restored = await session.restore(); + + expect(restored, isTrue); + expect(capturedUri?.path, '/whoAmI/api/json'); + expect( + capturedHeaders?['Authorization'], + 'Basic ${base64Encode(utf8.encode('user:token'))}', + ); + }); + + test('loadJobs delegates to JenkinsClient with stored base url and credentials', () { + FlutterSecureStorage.setMockInitialValues({ + 'jenkins.baseUrl': baseUrl, + 'jenkins.username': credentials.username, + 'jenkins.apiToken': credentials.apiToken, + }); + + Uri? jobsUri; + + final session = JenkinsArtifactSession( + store: TokenStore(), + client: JenkinsClient( + client: MockClient((request) async { + if (request.url.path.endsWith('whoAmI/api/json')) { + return http.Response(jsonEncode({'id': 'user'}), 200); + } + + if (request.url.path.endsWith('api/json')) { + jobsUri = request.url; + return http.Response( + jsonEncode({'jobs': []}), + 200, + ); + } + + return http.Response('unexpected', 400); + }), + ), + stager: ArtifactStagingService(), + ); + + expect(() async { + await session.restore(); + await session.loadJobs(); + }, returnsNormally); + + expect(jobsUri, isNotNull); + expect(jobsUri?.path, '/api/json'); + expect(jobsUri?.host, 'jenkins.example'); + }); + + test('downloadArtifact builds Jenkins artifact URL from build url and relative path', + () async { + FlutterSecureStorage.setMockInitialValues({ + 'jenkins.baseUrl': baseUrl, + 'jenkins.username': credentials.username, + 'jenkins.apiToken': credentials.apiToken, + }); + + Uri? artifactUri; + + final session = JenkinsArtifactSession( + store: TokenStore(), + client: JenkinsClient( + client: MockClient((request) async { + if (request.url.path.endsWith('whoAmI/api/json')) { + return http.Response(jsonEncode({'id': 'user'}), 200); + } + + if (request.url.path.endsWith('artifact/file.apk')) { + artifactUri = request.url; + return http.Response.bytes([], 200); + } + + if (request.url.path.endsWith('api/json')) { + return http.Response(jsonEncode({'jobs': []}), 200); + } + + return http.Response('unexpected', 400); + }), + ), + stager: ArtifactStagingService(), + ); + + await session.restore(); + + final task = session.downloadArtifact( + JenkinsBuild( + number: 1, + jobName: 'app', + url: Uri.parse('$baseUrl/job/app/1/'), + startedAt: DateTime(2026), + result: 'SUCCESS', + artifacts: const [ + BuildArtifact(fileName: 'app.apk', relativePath: 'artifact/file.apk'), + ], + ), + const BuildArtifact(fileName: 'file.apk', relativePath: 'artifact/file.apk'), + ); + + await task.events.toList(); + + expect(artifactUri, isNotNull); + expect(artifactUri?.path, '/job/app/1/artifact/artifact/file.apk'); + }); + + test('returns unavailable state when session config is missing', () async { + final session = JenkinsArtifactSession( + store: TokenStore(), + client: JenkinsClient( + client: MockClient((_) async => http.Response('', 200)), + ), + stager: ArtifactStagingService(), + ); + + final restored = await session.restore(); + + expect(restored, isFalse); + expect(session.isRestored, isFalse); + }); +} diff --git a/test/jenkins_client_test.dart b/test/jenkins_client_test.dart index 0e0496c..c0d894a 100644 --- a/test/jenkins_client_test.dart +++ b/test/jenkins_client_test.dart @@ -371,6 +371,105 @@ void main() { }); }); + group('JenkinsClient.fetchCurrentUser', () { + test('fetchCurrentUser requests whoAmI api with auth header', () async { + Uri? capturedUri; + Map? capturedHeaders; + + final client = JenkinsClient( + client: MockClient((request) async { + capturedUri = request.url; + capturedHeaders = request.headers; + return http.Response( + jsonEncode({ + 'id': 'ada', + 'fullName': 'Ada Lovelace', + }), + 200, + ); + }), + ); + + final user = await client.fetchCurrentUser( + baseUrl: baseUrl, + credentials: credentials, + ); + + expect(user.id, 'ada'); + expect(user.displayName, 'Ada Lovelace'); + expect(capturedUri?.path, contains('whoAmI/api/json')); + + final expectedAuth = 'Basic ${base64Encode(utf8.encode('user:token'))}'; + expect(capturedHeaders?['Authorization'], expectedAuth); + }); + + test('fetchCurrentUser parses id and display name with fallback', () async { + final client = JenkinsClient( + client: MockClient( + (_) async => http.Response( + jsonEncode({'id': 'grace', 'fullName': ''}), + 200, + ), + ), + ); + + final user = await client.fetchCurrentUser( + baseUrl: baseUrl, + credentials: credentials, + ); + + expect(user.id, 'grace'); + expect(user.displayName, 'grace'); + }); + + test( + 'fetchCurrentUser falls back to name when fullName is blank', + () async { + final client = JenkinsClient( + client: MockClient( + (_) async => http.Response( + jsonEncode({ + 'id': 'grace', + 'fullName': ' ', + 'name': 'Grace Hopper', + }), + 200, + ), + ), + ); + + final user = await client.fetchCurrentUser( + baseUrl: baseUrl, + credentials: credentials, + ); + + expect(user.id, 'grace'); + expect(user.displayName, 'Grace Hopper'); + }, + ); + + test('fetchCurrentUser throws JenkinsClientException on forbidden response', + () async { + final client = JenkinsClient( + client: MockClient((_) async => http.Response('Forbidden', 403)), + ); + + expect( + () => client.fetchCurrentUser( + baseUrl: baseUrl, + credentials: credentials, + ), + throwsA( + isA().having( + (e) => e.statusCode, + 'statusCode', + 403, + ), + ), + ); + }); + }); + group('JenkinsClient.fetchRecentBuilds', () { test( 'requests build tree and returns only builds with apk artifacts', diff --git a/test/token_store_test.dart b/test/token_store_test.dart new file mode 100644 index 0000000..3697f7a --- /dev/null +++ b/test/token_store_test.dart @@ -0,0 +1,100 @@ +import 'package:flutter_secure_storage/flutter_secure_storage.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import 'package:appsok/src/services/jenkins_client.dart'; +import 'package:appsok/src/services/token_store.dart'; + +void main() { + setUp(() { + FlutterSecureStorage.setMockInitialValues({}); + }); + + group('TokenStore.readSession', () { + test('readSession returns null when config is incomplete', () async { + final store = TokenStore(); + expect(await store.readSession(), isNull); + }); + + test('readSession returns null when only credentials are stored', () async { + FlutterSecureStorage.setMockInitialValues({ + 'jenkins.username': 'ada', + 'jenkins.apiToken': 'tok', + }); + final store = TokenStore(); + expect(await store.readSession(), isNull); + }); + + test('readSession returns null when base url is invalid', () async { + FlutterSecureStorage.setMockInitialValues({ + 'jenkins.baseUrl': ':::not-a-url:::', + 'jenkins.username': 'ada', + 'jenkins.apiToken': 'tok', + }); + final store = TokenStore(); + expect(await store.readSession(), isNull); + }); + + test('saveSession and readSession round trip base url and credentials', + () async { + final store = TokenStore(); + final session = JenkinsSessionConfig( + baseUrl: Uri.parse('https://jenkins.example/'), + credentials: const JenkinsCredentials( + username: 'ada', + apiToken: 'secret', + ), + ); + + await store.saveSession(session); + final result = await store.readSession(); + + expect(result, isNotNull); + expect(result!.baseUrl, Uri.parse('https://jenkins.example/')); + expect(result.credentials.username, 'ada'); + expect(result.credentials.apiToken, 'secret'); + }); + + test('clearSession removes base url and credentials', () async { + final store = TokenStore(); + final session = JenkinsSessionConfig( + baseUrl: Uri.parse('https://jenkins.example/'), + credentials: const JenkinsCredentials( + username: 'ada', + apiToken: 'secret', + ), + ); + + await store.saveSession(session); + await store.clearSession(); + expect(await store.readSession(), isNull); + }); + }); + + group('TokenStore.readCredentials backward compatibility', () { + test('readCredentials remains backward compatible', () async { + final store = TokenStore(); + await store.saveCredentials( + const JenkinsCredentials(username: 'grace', apiToken: 'tok2'), + ); + + final result = await store.readCredentials(); + expect(result, isNotNull); + expect(result!.username, 'grace'); + expect(result.apiToken, 'tok2'); + }); + + test('readCredentials returns null when nothing is stored', () async { + final store = TokenStore(); + expect(await store.readCredentials(), isNull); + }); + + test('clearCredentials removes username and token', () async { + final store = TokenStore(); + await store.saveCredentials( + const JenkinsCredentials(username: 'grace', apiToken: 'tok2'), + ); + await store.clearCredentials(); + expect(await store.readCredentials(), isNull); + }); + }); +}