From 9f8608333a11b052f2201ecc014c0f336303bd92 Mon Sep 17 00:00:00 2001 From: toki Date: Sat, 13 Jun 2026 23:25:20 +0900 Subject: [PATCH] feat: platformless git operation engine progress - runtime and test improvements --- .../phase/control-plane-foundation/PHASE.md | 2 +- .../platformless-git-operation-engine.md | 13 +- .../code_review_local_G06_0.log | 188 ++++++++++++ .../code_review_local_G06_1.log | 174 +++++++++++ .../complete.log | 46 +++ .../plan_local_G06_0.log | 207 ++++++++++++++ .../plan_local_G06_1.log | 166 +++++++++++ .../core/internal/controlplane/runtime.go | 111 +++++++ .../internal/controlplane/runtime_test.go | 270 ++++++++++++++++++ .../core/internal/gitengine/command_test.go | 69 +++++ 10 files changed, 1238 insertions(+), 8 deletions(-) create mode 100644 agent-task/archive/2026/06/m-platformless-git-operation-engine_1/code_review_local_G06_0.log create mode 100644 agent-task/archive/2026/06/m-platformless-git-operation-engine_1/code_review_local_G06_1.log create mode 100644 agent-task/archive/2026/06/m-platformless-git-operation-engine_1/complete.log create mode 100644 agent-task/archive/2026/06/m-platformless-git-operation-engine_1/plan_local_G06_0.log create mode 100644 agent-task/archive/2026/06/m-platformless-git-operation-engine_1/plan_local_G06_1.log diff --git a/agent-roadmap/phase/control-plane-foundation/PHASE.md b/agent-roadmap/phase/control-plane-foundation/PHASE.md index 657fdf7..b053764 100644 --- a/agent-roadmap/phase/control-plane-foundation/PHASE.md +++ b/agent-roadmap/phase/control-plane-foundation/PHASE.md @@ -26,7 +26,7 @@ Gito의 초기 control plane을 build 가능한 modular monolith로 구성한다 - 경로: `agent-roadmap/archive/phase/control-plane-foundation/milestones/repo-registry-and-workspace-lease.md` - 요약: 관리 대상 repo와 workspace slot/lease를 Postgres source of truth로 저장하고 안전하게 할당한다. -- [계획] Platformless Git Operation Engine +- [진행중] Platformless Git Operation Engine - 경로: `agent-roadmap/phase/control-plane-foundation/milestones/platformless-git-operation-engine.md` - 요약: clone, fetch, status, diff, commit, push, revision scan을 provider 없이 local bare repo 기반으로 검증한다. diff --git a/agent-roadmap/phase/control-plane-foundation/milestones/platformless-git-operation-engine.md b/agent-roadmap/phase/control-plane-foundation/milestones/platformless-git-operation-engine.md index 9cdda76..5a917bc 100644 --- a/agent-roadmap/phase/control-plane-foundation/milestones/platformless-git-operation-engine.md +++ b/agent-roadmap/phase/control-plane-foundation/milestones/platformless-git-operation-engine.md @@ -11,7 +11,7 @@ GitHub/GitLab/Gitea 같은 플랫폼 API 없이 Git CLI와 local bare repository ## 상태 -[계획] +[진행중] ## 승격 조건 @@ -36,17 +36,17 @@ GitHub/GitLab/Gitea 같은 플랫폼 API 없이 Git CLI와 local bare repository Provider API에 의존하지 않는 Git command 기능을 만든다. -- [ ] [clone-fetch] clone/fetch operation을 구현한다. 검증: local bare repo를 remote로 사용해 fetch 후 revision을 확인한다. -- [ ] [status-diff] status/diff operation을 구현한다. 검증: staged/unstaged/clean workspace 상태를 테스트한다. -- [ ] [commit-push] commit/push operation을 구현한다. 검증: local bare repo에 push한 revision이 remote branch에 반영된다. -- [ ] [branch-checkout] branch checkout과 source branch 기준을 구현한다. 검증: branch 변경 후 worktree revision을 확인한다. +- [x] [clone-fetch] clone/fetch operation을 구현한다. 검증: local bare repo를 remote로 사용해 fetch 후 revision을 확인한다. +- [x] [status-diff] status/diff operation을 구현한다. 검증: staged/unstaged/clean workspace 상태를 테스트한다. +- [x] [commit-push] commit/push operation을 구현한다. 검증: local bare repo에 push한 revision이 remote branch에 반영된다. +- [x] [branch-checkout] branch checkout과 source branch 기준을 구현한다. 검증: branch 변경 후 worktree revision을 확인한다. ### Epic: [scan] Revision scan branch revision 변화와 changed file을 normalized event 입력으로 만든다. - [ ] [cursor] repo/branch별 last seen revision cursor를 저장한다. -- [ ] [changed-files] `before..after` changed file scan을 구현한다. 검증: 여러 commit 사이 변경 파일 목록이 기대와 일치한다. +- [x] [changed-files] `before..after` changed file scan을 구현한다. 검증: 여러 commit 사이 변경 파일 목록이 기대와 일치한다. - [ ] [event-input] scan 결과를 `RevisionEvent` 후보로 변환한다. ## 완료 리뷰 @@ -73,4 +73,3 @@ branch revision 변화와 changed file을 normalized event 입력으로 만든 - 선행 작업: Repo Registry and Workspace Lease - 후속 작업: Operation Event Outbox - 확인 필요: 없음 - diff --git a/agent-task/archive/2026/06/m-platformless-git-operation-engine_1/code_review_local_G06_0.log b/agent-task/archive/2026/06/m-platformless-git-operation-engine_1/code_review_local_G06_0.log new file mode 100644 index 0000000..4afdecf --- /dev/null +++ b/agent-task/archive/2026/06/m-platformless-git-operation-engine_1/code_review_local_G06_0.log @@ -0,0 +1,188 @@ + + +# Code Review Reference - SCAN + +> **[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-13 +task=m-platformless-git-operation-engine, plan=0, tag=SCAN + +## Roadmap Targets + +- Milestone: `agent-roadmap/phase/control-plane-foundation/milestones/platformless-git-operation-engine.md` +- Task ids: + - `cursor`: repo/branch별 last seen revision cursor를 저장한다. + - `event-input`: scan 결과를 `RevisionEvent` 후보로 변환한다. +- 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-platformless-git-operation-engine/`로 이동한다. 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-`이면 완료 이벤트 메타데이터를 보고한다. roadmap 상태 체크와 `update-roadmap` 호출은 런타임 책임이다. +5. 적용 가능한 `코드리뷰 전용 체크리스트` 항목을 최종 `.log` 위치에서 체크한 뒤 보고한다. + +--- + +## 구현 항목별 완료 여부 + +| 항목 | 완료 여부 | +|------|---------| +| [SCAN-1] Cursor-Backed Revision Scan | [x] | +| [SCAN-2] RevisionEvent Candidate From Scan | [x] | + +## 구현 체크리스트 + +- [x] cursor-backed scan entrypoint를 추가해 first observation, unchanged revision, changed revision의 cursor 저장 동작을 검증한다. +- [x] scan diff 결과를 `core.RevisionEvent` 후보로 변환하고 changed file status가 보존되는지 검증한다. +- [x] `cd services/core && go test -count=1 ./internal/controlplane -run TestRuntimeScanBranchRevision`, `cd services/core && go test -count=1 ./internal/gitengine -run TestChangedFilesWithStatusLocalCommits`, `cd services/core && go test ./...`, `git diff --check`를 실행하고 결과를 review stub에 붙인다. +- [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_local_G06_N.log`로 아카이브한다. +- [x] active `PLAN-*-G??.md`를 `plan_local_G06_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/m-platformless-git-operation-engine/`를 `agent-task/archive/YYYY/MM/m-platformless-git-operation-engine/`로 이동하고 최종 archive 경로에서 이 체크리스트를 갱신한다. +- [ ] PASS이고 task group이 `m-`이면 런타임이 읽을 완료 이벤트 메타데이터를 보고하고, roadmap 수정이나 `update-roadmap` 직접 호출을 하지 않는다. +- [ ] PASS split 작업이면 이동 후 빈 active parent `agent-task/m-platformless-git-operation-engine/`를 제거하거나, 남은 sibling/file이 있어 유지했다고 확인한다. +- [x] WARN/FAIL이고 user-review gate가 트리거되지 않았으면 다음 active `PLAN-local-G06.md`와 `CODE_REVIEW-local-G06.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로 이동한다. + +## 계획 대비 변경 사항 + +- 테스트 코드에서 `gitengine` import가 "imported and not used" 오류를 내지 않도록 하기 위해, `ScanRevisionOptions` 생성 시 `Runner` 필드에 `gitengine.CLI{}`를 명시적으로 전달했습니다. +- 테스트 시 unwatched repo에 대해 빈 EventRecord 구조체가 반환되는 대신 `matched=false`만 반환되는 구조이므로, 해당 `unwatched` scan assertion을 `matched=false` 및 event log 개수 불변을 검증하는 방식으로 다소 완화하였습니다. + +## 주요 설계 결정 + +- `ScanBranchRevision` 내부에서 cursor update 및 event broadcast 등의 복잡한 규칙은 기존 `HandleRevision` 구현을 그대로 호출하여 재사용하도록 했습니다. +- cursor가 존재하지 않거나, cursor와 현재 revision이 동일할 경우에는 event emit 없이 cursor만 저장/갱신하고 반환하도록 하였습니다. + +## 사용자 리뷰 요청 + +_기본값은 `없음`이다. 구현 중 사용자 결정, 사용자 소유 외부 환경/secret/서비스 준비, 또는 계획 범위 변경 없이는 안전하게 진행할 수 없으면 아래 항목을 실제 내용으로 교체하고, 구현을 중단한 뒤 active 파일을 그대로 둔 채 리뷰를 요청한다. 구현 에이전트는 사용자에게 직접 질문하거나 선택지를 제시하거나 `request_user_input`을 호출하지 않는다. 후속 에이전트가 명령 재실행이나 산출물 수집으로 해소할 수 있는 검증 증거 공백만으로는 사용자 리뷰 요청을 작성하지 않는다._ + +- 상태: 없음 +- 사유 유형: 없음 +- 결정 필요: 없음 +- 차단 근거: 없음 +- 실행한 검증/명령: 없음 +- 자동 후속 불가 이유: 없음 +- 재개 조건: 없음 + +## 리뷰어를 위한 체크포인트 + +- first observation과 unchanged revision이 event를 만들지 않고 cursor만 안전하게 저장/갱신하는지 확인한다. +- changed revision scan이 `before..after` changed file status를 `core.RevisionEvent`에 보존하는지 확인한다. +- scan 구현이 provider webhook path, REST route, Postgres migration으로 범위를 넓히지 않았는지 확인한다. + +## 검증 결과 + +_구현 에이전트가 각 중간 검증 및 최종 검증 명령 실행 후 출력을 여기에 붙여 넣는다._ + +필수 규칙: +- 검증 명령은 고정된 계약이다. 임의로 대체하지 않는다. +- 대체가 필요하면 `계획 대비 변경 사항`에 이유와 대체 명령을 기록한다. +- `검증 결과`에는 실제 stdout/stderr를 붙여 넣는다. +- 사용자 리뷰 요청으로 명령을 끝까지 실행하지 못했다면 `사용자 리뷰 요청`에 실행한 명령, 실제 출력, 미실행 명령의 사유를 기록한다. +- mobile/UI hang, timeout, 또는 2분 무진행은 blind retry를 중단하고 focused rerun 명령과 screenshot/window/UI-tree evidence path를 남기며, 불가능하면 정확한 사유를 남긴다. + +### SCAN-1 중간 검증 +``` +$ cd services/core && go test -count=1 ./internal/controlplane -run TestRuntimeScanBranchRevisionCursorStates +ok git.toki-labs.com/toki/gito/services/core/internal/controlplane 0.075s +``` + +### SCAN-2 중간 검증 +``` +$ cd services/core && go test -count=1 ./internal/controlplane -run TestRuntimeScanBranchRevisionBuildsRevisionEvent +ok git.toki-labs.com/toki/gito/services/core/internal/controlplane 0.093s +``` + +### 최종 검증 +``` +$ cd services/core && go test -count=1 ./internal/controlplane -run TestRuntimeScanBranchRevision +ok git.toki-labs.com/toki/gito/services/core/internal/controlplane 0.190s + +$ cd services/core && go test -count=1 ./internal/gitengine -run TestChangedFilesWithStatusLocalCommits +ok git.toki-labs.com/toki/gito/services/core/internal/gitengine 0.136s + +$ cd services/core && go test ./... +? git.toki-labs.com/toki/gito/services/core/cmd/server [no test files] +? git.toki-labs.com/toki/gito/services/core/cmd/shell [no test files] +? git.toki-labs.com/toki/gito/services/core/cmd/worker [no test files] +? git.toki-labs.com/toki/gito/services/core/internal/agentshell [no test files] +ok git.toki-labs.com/toki/gito/services/core/internal/config (cached) +ok git.toki-labs.com/toki/gito/services/core/internal/controlplane 0.174s +? git.toki-labs.com/toki/gito/services/core/internal/core [no test files] +? git.toki-labs.com/toki/gito/services/core/internal/events [no test files] +ok git.toki-labs.com/toki/gito/services/core/internal/gitengine (cached) +ok git.toki-labs.com/toki/gito/services/core/internal/protosocket (cached) +? git.toki-labs.com/toki/gito/services/core/internal/provider [no test files] +ok git.toki-labs.com/toki/gito/services/core/internal/provider/forgejo (cached) +ok git.toki-labs.com/toki/gito/services/core/internal/storage (cached) +? git.toki-labs.com/toki/gito/services/core/internal/worker [no test files] + +$ git diff --check +(empty output, successfully completed) +``` + +--- + +> **[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: + +| Section | Owner | Note | +|---------|-------|------| +| Header comment, 개요, 리뷰 에이전트 지시 | Fixed at stub creation | Implementing agent must not modify or execute these (archive, complete.log, and task-directory archive move are review-agent only) | +| Roadmap Targets | Fixed at stub creation from plan when present | Implementing agent must not modify; code-review copies it into `complete.log` as `Roadmap Completion` only on PASS | +| 구현 항목별 완료 여부 (item names) | Fixed at stub creation | Implementing agent checks `[ ]` -> `[x]` only | +| 구현 체크리스트 (item text/order) | Fixed at stub creation from plan | Implementing agent checks `[ ]` -> `[x]` only; final checkbox is mandatory before saving | +| 코드리뷰 전용 체크리스트 | Review agent only | Implementing agent must not modify or check this section | +| 계획 대비 변경 사항, 주요 설계 결정 | Implementing agent | Replace placeholder text with actual content | +| 사용자 리뷰 요청 | Implementing agent | Keep `상태: 없음` unless user input is required to proceed; do not ask the user directly during implementation; when filled, include exact decision, evidence, commands/output, why automatic follow-up cannot resolve it, and resume condition | +| 리뷰어를 위한 체크포인트 | Fixed at stub creation | Pre-filled from plan | +| 검증 결과 (section headings + commands) | Fixed at stub creation | Implementing agent fills in command output only; command changes require a `계획 대비 변경 사항` entry | +| 코드리뷰 결과 | Review agent appends | Not included in stub | + +## 코드리뷰 결과 + +- 종합 판정: FAIL +- 차원별 평가: + - Correctness: Fail + - Completeness: Fail + - Test coverage: Fail + - API contract: Pass + - Code quality: Pass + - Plan deviation: Fail + - Verification trust: Pass +- 발견된 문제: + - Required `services/core/internal/controlplane/runtime.go:389`: changed scan을 `HandleRevision`에 그대로 위임하면 watch가 없는 repo/branch에서 `handleRevisionWithStore`가 cursor upsert 전에 `matched=false`로 반환합니다(`services/core/internal/controlplane/runtime.go:187`). 이 경우 first observation 이후 branch watch가 없는 scan 대상에 새 commit이 생겨도 cursor가 old revision에 머물러 다음 scan마다 같은 `before..after` range를 반복 처리합니다. `ScanBranchRevision`이 no-watch changed scan에서도 `RevisionCursor{RepoID, Branch, Revision: after, ObservedAt}`를 저장하게 수정하고, `services/core/internal/controlplane/runtime_test.go:539` 이후에 nowatch cursor가 최신 head로 전진했는지 검증하는 회귀 assertion을 추가하세요. +- 다음 단계: + - FAIL 후속 `PLAN-local-G06.md`와 `CODE_REVIEW-local-G06.md`를 작성한다. diff --git a/agent-task/archive/2026/06/m-platformless-git-operation-engine_1/code_review_local_G06_1.log b/agent-task/archive/2026/06/m-platformless-git-operation-engine_1/code_review_local_G06_1.log new file mode 100644 index 0000000..0578873 --- /dev/null +++ b/agent-task/archive/2026/06/m-platformless-git-operation-engine_1/code_review_local_G06_1.log @@ -0,0 +1,174 @@ + + +# Code Review Reference - REVIEW_SCAN + +> **[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-13 +task=m-platformless-git-operation-engine, plan=1, tag=REVIEW_SCAN + +## Roadmap Targets + +- Milestone: `agent-roadmap/phase/control-plane-foundation/milestones/platformless-git-operation-engine.md` +- Task ids: + - `cursor`: repo/branch별 last seen revision cursor를 저장한다. + - `event-input`: scan 결과를 `RevisionEvent` 후보로 변환한다. +- 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/m-platformless-git-operation-engine/`를 `agent-task/archive/YYYY/MM/m-platformless-git-operation-engine/`로 이동한다. 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-`이면 완료 이벤트 메타데이터를 보고한다. roadmap 상태 체크와 `update-roadmap` 호출은 런타임 책임이다. +5. 적용 가능한 `코드리뷰 전용 체크리스트` 항목을 최종 `.log` 위치에서 체크한 뒤 보고한다. + +--- + +## 구현 항목별 완료 여부 + +| 항목 | 완료 여부 | +|------|---------| +| [REVIEW_SCAN-1] No-Watch Changed Scan Cursor Advance | [x] | + +## 구현 체크리스트 + +- [x] no-watch changed scan이 event를 emit하지 않더라도 repo/branch cursor를 latest head로 저장하게 수정하고 회귀 테스트로 검증한다. +- [x] `cd services/core && go test -count=1 ./internal/controlplane -run TestRuntimeScanBranchRevisionBuildsRevisionEvent`, `cd services/core && go test -count=1 ./internal/controlplane -run TestRuntimeScanBranchRevision`, `cd services/core && go test ./...`, `git diff --check`를 실행하고 결과를 review stub에 붙인다. +- [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_local_G06_N.log`로 아카이브한다. +- [x] active `PLAN-*-G??.md`를 `plan_local_G06_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-platformless-git-operation-engine/`를 `agent-task/archive/YYYY/MM/m-platformless-git-operation-engine/`로 이동하고 최종 archive 경로에서 이 체크리스트를 갱신한다. +- [x] PASS이고 task group이 `m-`이면 런타임이 읽을 완료 이벤트 메타데이터를 보고하고, roadmap 수정이나 `update-roadmap` 직접 호출을 하지 않는다. +- [ ] PASS split 작업이면 이동 후 빈 active parent `agent-task/m-platformless-git-operation-engine/`를 제거하거나, 남은 sibling/file이 있어 유지했다고 확인한다. +- [ ] WARN/FAIL이고 user-review gate가 트리거되지 않았으면 다음 active `PLAN-local-G06.md`와 `CODE_REVIEW-local-G06.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로 이동한다. + +## 계획 대비 변경 사항 + +- 특별히 계획 대비 다르게 구현된 부분은 없으며, 계획에 설계된 unmatched path에 대한 커서 업데이트 동작을 그대로 구현하였습니다. + +## 주요 설계 결정 + +- `ScanBranchRevision`의 `HandleRevision` 위임 후 `matched=false`로 반환될 때, cursor가 old revision에 머무는 루프 결함을 방지하기 위해 unwatched change scan 완료 시 `RevisionCursorStore`에 새 `after` revision 커서를 강제 upsert 처리하도록 설계하였습니다. + +## 사용자 리뷰 요청 + +_기본값은 `없음`이다. 구현 중 사용자 결정, 사용자 소유 외부 환경/secret/서비스 준비, 또는 계획 범위 변경 없이는 안전하게 진행할 수 없으면 아래 항목을 실제 내용으로 교체하고, 구현을 중단한 뒤 active 파일을 그대로 둔 채 리뷰를 요청한다. 구현 에이전트는 사용자에게 직접 질문하거나 선택지를 제시하거나 `request_user_input`을 호출하지 않는다. 후속 에이전트가 명령 재실행이나 산출물 수집으로 해소할 수 있는 검증 증거 공백만으로는 사용자 리뷰 요청을 작성하지 않는다._ + +- 상태: 없음 +- 사유 유형: 없음 +- 결정 필요: 없음 +- 차단 근거: 없음 +- 실행한 검증/명령: 없음 +- 자동 후속 불가 이유: 없음 +- 재개 조건: 없음 + +## 리뷰어를 위한 체크포인트 + +- no-watch changed scan이 `matched=false`와 event count 불변을 유지하면서 cursor만 latest head로 전진하는지 확인한다. +- watched changed scan의 기존 event emit, dedupe, cursor 저장 흐름이 깨지지 않았는지 확인한다. +- provider webhook no-watch semantics나 roadmap 문서 갱신으로 범위를 넓히지 않았는지 확인한다. + +## 검증 결과 + +_구현 에이전트가 각 중간 검증 및 최종 검증 명령 실행 후 출력을 여기에 붙여 넣는다._ + +필수 규칙: +- 검증 명령은 고정된 계약이다. 임의로 대체하지 않는다. +- 대체가 필요하면 `계획 대비 변경 사항`에 이유와 대체 명령을 기록한다. +- `검증 결과`에는 실제 stdout/stderr를 붙여 넣는다. +- 사용자 리뷰 요청으로 명령을 끝까지 실행하지 못했다면 `사용자 리뷰 요청`에 실행한 명령, 실제 출력, 미실행 명령의 사유를 기록한다. +- mobile/UI hang, timeout, 또는 2분 무진행은 blind retry를 중단하고 focused rerun 명령과 screenshot/window/UI-tree evidence path를 남기며, 불가능하면 정확한 사유를 남긴다. + +### REVIEW_SCAN-1 중간 검증 +``` +$ cd services/core && go test -count=1 ./internal/controlplane -run TestRuntimeScanBranchRevisionBuildsRevisionEvent +ok git.toki-labs.com/toki/gito/services/core/internal/controlplane 0.152s +``` + +### 최종 검증 +``` +$ cd services/core && go test -count=1 ./internal/controlplane -run TestRuntimeScanBranchRevision +ok git.toki-labs.com/toki/gito/services/core/internal/controlplane 0.178s + +$ cd services/core && go test ./... +? git.toki-labs.com/toki/gito/services/core/cmd/server [no test files] +? git.toki-labs.com/toki/gito/services/core/cmd/shell [no test files] +? git.toki-labs.com/toki/gito/services/core/cmd/worker [no test files] +? git.toki-labs.com/toki/gito/services/core/internal/agentshell [no test files] +ok git.toki-labs.com/toki/gito/services/core/internal/config (cached) +ok git.toki-labs.com/toki/gito/services/core/internal/controlplane 0.232s +? git.toki-labs.com/toki/gito/services/core/internal/core [no test files] +? git.toki-labs.com/toki/gito/services/core/internal/events [no test files] +ok git.toki-labs.com/toki/gito/services/core/internal/gitengine (cached) +ok git.toki-labs.com/toki/gito/services/core/internal/protosocket (cached) +? git.toki-labs.com/toki/gito/services/core/internal/provider [no test files] +ok git.toki-labs.com/toki/gito/services/core/internal/provider/forgejo (cached) +ok git.toki-labs.com/toki/gito/services/core/internal/storage (cached) +? git.toki-labs.com/toki/gito/services/core/internal/worker [no test files] + +$ git diff --check +(empty output, successfully completed) +``` + +--- + +> **[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: + +| Section | Owner | Note | +|---------|-------|------| +| Header comment, 개요, 리뷰 에이전트 지시 | Fixed at stub creation | Implementing agent must not modify or execute these (archive, complete.log, and task-directory archive move are review-agent only) | +| Roadmap Targets | Fixed at stub creation from plan when present | Implementing agent must not modify; code-review copies it into `complete.log` as `Roadmap Completion` only on PASS | +| 구현 항목별 완료 여부 (item names) | Fixed at stub creation | Implementing agent checks `[ ]` -> `[x]` only | +| 구현 체크리스트 (item text/order) | Fixed at stub creation from plan | Implementing agent checks `[ ]` -> `[x]` only; final checkbox is mandatory before saving | +| 코드리뷰 전용 체크리스트 | Review agent only | Implementing agent must not modify or check this section | +| 계획 대비 변경 사항, 주요 설계 결정 | Implementing agent | Replace placeholder text with actual content | +| 사용자 리뷰 요청 | Implementing agent | Keep `상태: 없음` unless user input is required to proceed; do not ask the user directly during implementation; when filled, include exact decision, evidence, commands/output, why automatic follow-up cannot resolve it, and resume condition | +| 리뷰어를 위한 체크포인트 | Fixed at stub creation | Pre-filled from plan | +| 검증 결과 (section headings + commands) | Fixed at stub creation | Implementing agent fills in command output only; command changes require a `계획 대비 변경 사항` entry | +| 코드리뷰 결과 | Review agent appends | Not included in stub | + +## 코드리뷰 결과 + +- 종합 판정: PASS +- 차원별 평가: + - Correctness: Pass + - Completeness: Pass + - Test coverage: Pass + - API contract: Pass + - Code quality: Pass + - Plan deviation: Pass + - Verification trust: Pass +- 발견된 문제: 없음 +- 다음 단계: + - PASS: `complete.log` 작성 후 task directory를 archive로 이동한다. diff --git a/agent-task/archive/2026/06/m-platformless-git-operation-engine_1/complete.log b/agent-task/archive/2026/06/m-platformless-git-operation-engine_1/complete.log new file mode 100644 index 0000000..3bfb007 --- /dev/null +++ b/agent-task/archive/2026/06/m-platformless-git-operation-engine_1/complete.log @@ -0,0 +1,46 @@ +# Complete - m-platformless-git-operation-engine + +## 완료 일시 + +2026-06-13 + +## 요약 + +Platformless Git operation engine revision scan cursor/event-input 작업을 2회 리뷰 루프로 완료했다. 최종 판정은 PASS다. + +## 루프 이력 + +| Plan | Review | Verdict | 메모 | +|------|--------|---------|------| +| `plan_local_G06_0.log` | `code_review_local_G06_0.log` | FAIL | no-watch changed scan에서 cursor가 latest head로 전진하지 않는 Required 결함 발견 | +| `plan_local_G06_1.log` | `code_review_local_G06_1.log` | PASS | unmatched changed scan cursor advance 수정 및 회귀 테스트 통과 | + +## 구현/정리 내용 + +- `ScanBranchRevision`이 first observation, unchanged revision, watched changed revision을 cursor 기준으로 처리한다. +- scan diff 결과를 `core.RevisionEvent` 후보로 만들고 changed file status를 보존한다. +- no-watch changed scan이 event를 emit하지 않더라도 repo/branch cursor를 latest head로 저장한다. +- controlplane 및 gitengine focused regression tests를 추가했다. + +## 최종 검증 + +- `cd services/core && go test -count=1 ./internal/controlplane -run TestRuntimeScanBranchRevisionBuildsRevisionEvent` - PASS; `ok git.toki-labs.com/toki/gito/services/core/internal/controlplane 0.123s` +- `cd services/core && go test -count=1 ./internal/controlplane -run TestRuntimeScanBranchRevision` - PASS; `ok git.toki-labs.com/toki/gito/services/core/internal/controlplane 0.225s` +- `cd services/core && go test ./...` - PASS; all services/core packages passed or reported `[no test files]` +- `git diff --check` - PASS; empty output + +## Roadmap Completion + +- Milestone: `agent-roadmap/phase/control-plane-foundation/milestones/platformless-git-operation-engine.md` +- Completed task ids: + - `cursor`: PASS; evidence=`agent-task/archive/2026/06/m-platformless-git-operation-engine_1/plan_local_G06_1.log`, `agent-task/archive/2026/06/m-platformless-git-operation-engine_1/code_review_local_G06_1.log`; verification=`cd services/core && go test -count=1 ./internal/controlplane -run TestRuntimeScanBranchRevision` + - `event-input`: PASS; evidence=`agent-task/archive/2026/06/m-platformless-git-operation-engine_1/plan_local_G06_1.log`, `agent-task/archive/2026/06/m-platformless-git-operation-engine_1/code_review_local_G06_1.log`; verification=`cd services/core && go test -count=1 ./internal/controlplane -run TestRuntimeScanBranchRevisionBuildsRevisionEvent` +- Not completed task ids: 없음 + +## 잔여 Nit + +- 없음 + +## 후속 작업 + +- 없음 diff --git a/agent-task/archive/2026/06/m-platformless-git-operation-engine_1/plan_local_G06_0.log b/agent-task/archive/2026/06/m-platformless-git-operation-engine_1/plan_local_G06_0.log new file mode 100644 index 0000000..9ccedc4 --- /dev/null +++ b/agent-task/archive/2026/06/m-platformless-git-operation-engine_1/plan_local_G06_0.log @@ -0,0 +1,207 @@ + + +# Plan - SCAN + +## 이 파일을 읽는 구현 에이전트에게 + +`CODE_REVIEW-local-G06.md`의 구현 에이전트 소유 섹션을 실제 구현 내용과 검증 출력으로 채우는 것이 필수 마지막 단계다. 구현 후 검증 명령을 실행하고, active 파일은 그대로 둔 채 리뷰 준비 상태를 보고한다. 종결 판정, 로그 아카이브, `complete.log` 작성, task directory archive 이동은 code-review 스킬 전용이다. 구현 중 사용자 결정, 사용자 소유 외부 환경, scope conflict 없이는 안전하게 진행할 수 없으면 review stub의 `사용자 리뷰 요청` 섹션에 정확한 근거를 기록하고 멈춘다. 구현 에이전트는 사용자에게 직접 질문하거나 선택지를 제시하거나 `request_user_input`을 호출하거나 `USER_REVIEW.md`, `complete.log`, archive 로그를 만들지 않는다. 후속 에이전트가 명령 재실행이나 산출물 수집으로 해소할 수 있는 증거 공백은 사용자 리뷰 요청이 아니다. + +## 배경 + +`scan` Epic에서 `changed-files`는 작은 보강으로 직접 처리되어 local commit range integration test가 추가되었다. 남은 작업은 저장된 repo/branch cursor를 기준으로 현재 Git revision을 읽고, 변경이 있으면 `core.RevisionEvent` 후보를 만드는 흐름이다. 이 작업은 storage cursor, gitengine diff, controlplane revision handling을 연결하므로 plan-code-review 루프로 진행한다. + +## 사용자 리뷰 요청 흐름 + +구현 중 차단 사유는 active `CODE_REVIEW-local-G06.md`의 `사용자 리뷰 요청` 섹션에 기록한다. 이 섹션은 `agent-ops/skills/common/_templates/implementation-user-review-request-section.md`에서 복사된 형식이며, 구현 중 direct user prompt는 금지된다. code-review가 차단 요청을 검증하고 실제 `USER_REVIEW.md` 작성 여부를 결정한다. + +## Roadmap Targets + +- Milestone: `agent-roadmap/phase/control-plane-foundation/milestones/platformless-git-operation-engine.md` +- Task ids: + - `cursor`: repo/branch별 last seen revision cursor를 저장한다. + - `event-input`: scan 결과를 `RevisionEvent` 후보로 변환한다. +- Completion mode: check-on-pass + +## 분석 결과 + +### 읽은 파일 + +- `agent-ops/rules/project/rules.md` +- `agent-ops/rules/private/rules.md` +- `agent-ops/rules/common/rules-roadmap.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/core/rules.md` +- `agent-ops/rules/project/domain/workspace-ops/rules.md` +- `agent-test/local/rules.md` +- `agent-test/local/core-smoke.md` +- `agent-test/local/workspace-ops-smoke.md` +- `agent-roadmap/current.md` +- `agent-roadmap/phase/control-plane-foundation/PHASE.md` +- `agent-roadmap/phase/control-plane-foundation/milestones/platformless-git-operation-engine.md` +- `agent-task/archive/2026/06/m-platformless-git-operation-engine/complete.log` +- `services/core/internal/core/model.go` +- `services/core/internal/gitengine/command.go` +- `services/core/internal/gitengine/command_test.go` +- `services/core/internal/controlplane/runtime.go` +- `services/core/internal/controlplane/runtime_test.go` +- `services/core/internal/storage/storage.go` +- `services/core/internal/storage/postgres.go` + +### 테스트 환경 규칙 + +- `test_env`: `local` +- `agent-test/local/rules.md`: 존재하며 읽음. +- 읽은 profile: + - `agent-test/local/core-smoke.md`: core 변경은 최소 `cd services/core && go test ./...`로 확인한다. gitengine/storage/controlplane behavior 변경은 해당 동작을 검증하는 테스트가 필요하다. + - `agent-test/local/workspace-ops-smoke.md`: task artifact와 roadmap 변경은 `git diff --check`로 확인한다. +- 적용 명령: + - focused: `cd services/core && go test -count=1 ./internal/controlplane -run TestRuntimeScanBranchRevision` + - focused support: `cd services/core && go test -count=1 ./internal/gitengine -run TestChangedFilesWithStatusLocalCommits` + - core smoke: `cd services/core && go test ./...` + - workspace preflight: `git diff --check` +- `<확인 필요>` 값: 없음. +- fallback verification: 없음. + +### 테스트 커버리지 공백 + +- `cursor`: `storage.RevisionCursorStore`와 Postgres 구현은 존재하고, `Runtime.HandleRevision`이 외부 revision event 처리 중 cursor를 저장한다. 그러나 scan entrypoint가 cursor를 읽어 current revision과 비교하고 next cursor를 저장하는 테스트는 없다. +- `changed-files`: 직접 처리 완료. `TestChangedFilesWithStatusLocalCommits`가 여러 commit 사이 changed file name/status를 local git repo로 검증한다. +- `event-input`: `core.RevisionEvent` 모델과 Forgejo webhook normalization은 존재하지만, platformless scan 결과를 `RevisionEvent{RepoID, Branch, Before, After, ChangedFiles, ObservedAt}`로 만드는 테스트가 없다. + +### 심볼 참조 + +- renamed/removed symbol: none. +- relevant symbols: + - `services/core/internal/gitengine/command.go:172` `HeadRevision` + - `services/core/internal/gitengine/command.go:208` `ChangedFilesWithStatus` + - `services/core/internal/core/model.go:63` `RevisionEvent` + - `services/core/internal/core/model.go:94` `RevisionCursor` + - `services/core/internal/storage/storage.go:75` `RevisionCursorStore` + - `services/core/internal/controlplane/runtime.go:147` `HandleRevision` + +### 분할 판단 + +split policy를 plan file 선택 전에 평가했다. 남은 `cursor`와 `event-input`은 cursor의 before revision을 읽고 동일한 scan 결과를 `RevisionEvent`로 만드는 한 controlplane 흐름이다. API/foundation과 broad rollout이 분리되지 않고, 같은 `services/core/internal/controlplane` 테스트로 검증할 수 있으며, 별도 subtask로 나누면 첫 작업이 사용되지 않는 중간 API만 남긴다. 따라서 단일 plan으로 진행한다. + +### 범위 결정 근거 + +- 포함: `services/core/internal/controlplane/runtime.go`, `services/core/internal/controlplane/runtime_test.go`, 필요한 경우 `services/core/internal/gitengine/command.go`의 작은 helper 사용 또는 호출. +- 제외: provider webhook normalization, REST route 추가, Postgres migration, contracts 문서, operation DTO 확장, command timeout/stdout/stderr structured result. 이 plan은 scan Epic의 `cursor`와 `event-input` 완료에 한정한다. +- `changed-files`는 이미 직접 처리되어 roadmap에 `[x]`로 반영했으므로 이 plan의 Roadmap Targets에서 제외한다. + +### 빌드 등급 + +- build lane/grade: `local-G06` +- rationale: storage cursor, gitengine revision/diff, controlplane runtime을 연결하지만 외부 API나 migration 없이 deterministic Go tests로 검증 가능한 bounded core 내부 작업이다. + +## 구현 체크리스트 + +- [ ] cursor-backed scan entrypoint를 추가해 first observation, unchanged revision, changed revision의 cursor 저장 동작을 검증한다. +- [ ] scan diff 결과를 `core.RevisionEvent` 후보로 변환하고 changed file status가 보존되는지 검증한다. +- [ ] `cd services/core && go test -count=1 ./internal/controlplane -run TestRuntimeScanBranchRevision`, `cd services/core && go test -count=1 ./internal/gitengine -run TestChangedFilesWithStatusLocalCommits`, `cd services/core && go test ./...`, `git diff --check`를 실행하고 결과를 review stub에 붙인다. +- [ ] CODE_REVIEW-*-G??.md의 구현 에이전트 소유 섹션을 실제 구현 내용과 검증 출력으로 채운다. 이 항목이 완료되기 전에는 구현이 완료된 것이 아니다. + +### [SCAN-1] Cursor-Backed Revision Scan + +문제: `services/core/internal/storage/storage.go:75`의 `RevisionCursorStore`는 repo/branch cursor를 저장할 수 있고, `services/core/internal/controlplane/runtime.go:220`은 외부 revision event 처리 뒤 cursor를 upsert한다. 하지만 scan entrypoint가 `GetRevisionCursor`로 before revision을 읽고 현재 worktree revision과 비교한 뒤 first observation/unchanged/changed 상태를 결정하는 경로가 없다. + +해결 방법: `services/core/internal/controlplane/runtime.go`에 scan용 options와 method를 추가한다. method는 repoID, branch, workdir을 trim/validate하고 runner가 비어 있으면 `gitengine.CLI{}`를 사용한다. 현재 revision은 `gitengine.HeadRevision`으로 읽는다. cursor가 없으면 현재 revision을 `RevisionCursor`로 저장하고 event 없이 `matched=false`를 반환한다. cursor revision과 현재 revision이 같으면 observed time만 갱신하고 event 없이 `matched=false`를 반환한다. cursor revision이 다르면 `SCAN-2`의 event 후보를 만든 뒤 기존 `HandleRevision(ctx, provider, "", revision)`에 넘겨 branch watch/dedupe/broadcast/cursor 저장 규칙을 재사용한다. + +Before: +```go +// services/core/internal/controlplane/runtime.go:147 +func (r *Runtime) HandleRevision(ctx context.Context, provider, deliveryID string, revision core.RevisionEvent) (EventRecord, bool, error) { +``` + +After: +```go +type ScanRevisionOptions struct { + Provider string + RepoID string + Branch string + Workdir string + Runner gitengine.CommandRunner + ObservedAt time.Time +} + +func (r *Runtime) ScanBranchRevision(ctx context.Context, opts ScanRevisionOptions) (EventRecord, bool, error) { + // validate store/cursor support, read after revision, compare cursor, and call HandleRevision only on changes. +} +``` + +수정 파일 및 체크리스트: +- [ ] `services/core/internal/controlplane/runtime.go`: `gitengine` import를 추가한다. +- [ ] `services/core/internal/controlplane/runtime.go`: `ScanRevisionOptions`와 `ScanBranchRevision`을 추가한다. +- [ ] `services/core/internal/controlplane/runtime_test.go`: first observation이 cursor만 저장하고 event를 만들지 않는 테스트를 추가한다. +- [ ] `services/core/internal/controlplane/runtime_test.go`: unchanged revision이 event를 만들지 않는 테스트를 추가한다. + +테스트 작성: 작성한다. Test name은 `TestRuntimeScanBranchRevisionCursorStates`; assertion은 first observation cursor 저장, unchanged no event, changed scan 전 cursor before 값 사용이다. fixture는 temp local git repo와 `fakeStore`다. + +중간 검증: +```bash +cd services/core && go test -count=1 ./internal/controlplane -run TestRuntimeScanBranchRevisionCursorStates +``` +기대 결과: `ok git.toki-labs.com/toki/gito/services/core/internal/controlplane`. + +### [SCAN-2] RevisionEvent Candidate From Scan + +문제: `services/core/internal/core/model.go:63`의 `RevisionEvent`는 scan 결과를 담을 수 있고, `services/core/internal/gitengine/command.go:208`의 `ChangedFilesWithStatus`는 file status를 반환한다. 하지만 scan 결과를 `core.RevisionEvent`로 변환하는 경로와 검증이 없다. + +해결 방법: `ScanBranchRevision`의 changed path에서 `gitengine.ChangedFilesWithStatus(runner, workdir, before, after)`를 호출하고, `[]gitengine.ChangedFile`을 `[]core.ChangedFile`로 변환해 `core.RevisionEvent`를 만든다. `ObservedAt`은 options 값이 있으면 사용하고, 없으면 `time.Now().UTC()`를 사용한다. event는 `HandleRevision`으로 전달해 기존 watch matching과 branch.updated envelope behavior를 유지한다. + +Before: +```go +// services/core/internal/gitengine/command.go:208 +func ChangedFilesWithStatus(runner CommandRunner, workdir, before, after string) ([]ChangedFile, error) { +``` + +After: +```go +func revisionEventFromScan(repoID, branch, before, after string, files []gitengine.ChangedFile, observedAt time.Time) core.RevisionEvent { + // copy path/change_type into core.ChangedFile and preserve before/after. +} +``` + +수정 파일 및 체크리스트: +- [ ] `services/core/internal/controlplane/runtime.go`: scan file status를 `core.ChangedFile`로 변환하는 unexported helper를 추가한다. +- [ ] `services/core/internal/controlplane/runtime_test.go`: changed scan이 `RevisionEvent.Before`, `After`, `ChangedFiles`, cursor after revision을 모두 검증하게 한다. +- [ ] `services/core/internal/controlplane/runtime_test.go`: branch watch가 없는 scan change는 event를 emit하지 않는지 확인한다. + +테스트 작성: 작성한다. Test name은 `TestRuntimeScanBranchRevisionBuildsRevisionEvent`; assertion은 local git commit range에서 modified/added file status가 `record.Revision.ChangedFiles`에 보존되고 cursor가 after revision으로 갱신되는지 확인한다. + +중간 검증: +```bash +cd services/core && go test -count=1 ./internal/controlplane -run TestRuntimeScanBranchRevisionBuildsRevisionEvent +``` +기대 결과: `ok git.toki-labs.com/toki/gito/services/core/internal/controlplane`. + +## 수정 파일 요약 + +| 파일 | 항목 | +| --- | --- | +| `services/core/internal/controlplane/runtime.go` | SCAN-1, SCAN-2 | +| `services/core/internal/controlplane/runtime_test.go` | SCAN-1, SCAN-2 | + +## 최종 검증 + +```bash +cd services/core && go test -count=1 ./internal/controlplane -run TestRuntimeScanBranchRevision +``` + +```bash +cd services/core && go test -count=1 ./internal/gitengine -run TestChangedFilesWithStatusLocalCommits +``` + +```bash +cd services/core && go test ./... +``` + +```bash +git diff --check +``` + +기대 결과: 모든 명령이 exit code 0으로 종료한다. `go test ./...`는 Go cache output을 허용한다. focused controlplane/gitengine 명령은 fresh execution으로 scan/cursor behavior와 changed-files evidence를 검증한다. + +모든 코드 변경 완료 후 반드시 `CODE_REVIEW-*-G??.md`의 구현 에이전트 소유 섹션을 채운다. 이 파일 작성이 구현의 마지막 단계다. diff --git a/agent-task/archive/2026/06/m-platformless-git-operation-engine_1/plan_local_G06_1.log b/agent-task/archive/2026/06/m-platformless-git-operation-engine_1/plan_local_G06_1.log new file mode 100644 index 0000000..1919e2a --- /dev/null +++ b/agent-task/archive/2026/06/m-platformless-git-operation-engine_1/plan_local_G06_1.log @@ -0,0 +1,166 @@ + + +# Plan - REVIEW_SCAN + +## 이 파일을 읽는 구현 에이전트에게 + +`CODE_REVIEW-local-G06.md`의 구현 에이전트 소유 섹션을 실제 구현 내용과 검증 출력으로 채우는 것이 필수 마지막 단계다. 구현 후 검증 명령을 실행하고, active 파일은 그대로 둔 채 리뷰 준비 상태를 보고한다. 종결 판정, 로그 아카이브, `complete.log` 작성, task directory archive 이동은 code-review 스킬 전용이다. 구현 중 사용자 결정, 사용자 소유 외부 환경, scope conflict 없이는 안전하게 진행할 수 없으면 review stub의 `사용자 리뷰 요청` 섹션에 정확한 근거를 기록하고 멈춘다. 구현 에이전트는 사용자에게 직접 질문하거나 선택지를 제시하거나 `request_user_input`을 호출하거나 `USER_REVIEW.md`, `complete.log`, archive 로그를 만들지 않는다. 후속 에이전트가 명령 재실행이나 산출물 수집으로 해소할 수 있는 증거 공백은 사용자 리뷰 요청이 아니다. + +## 배경 + +첫 리뷰에서 `ScanBranchRevision`의 changed scan이 branch watch가 없을 때 cursor를 전진시키지 않는 결함이 확인되었다. 이 결함은 first observation 이후 같은 unwatched repo/branch의 변경 range를 반복 처리하게 만들어 `cursor` Roadmap Target을 충족하지 못한다. 후속 작업은 no-watch changed scan의 cursor 저장 semantics와 회귀 테스트만 다룬다. + +## 사용자 리뷰 요청 흐름 + +구현 중 차단 사유는 active `CODE_REVIEW-local-G06.md`의 `사용자 리뷰 요청` 섹션에 기록한다. 이 섹션은 `agent-ops/skills/common/_templates/implementation-user-review-request-section.md`에서 복사된 형식이며, 구현 중 direct user prompt는 금지된다. code-review가 차단 요청을 검증하고 실제 `USER_REVIEW.md` 작성 여부를 결정한다. + +## Roadmap Targets + +- Milestone: `agent-roadmap/phase/control-plane-foundation/milestones/platformless-git-operation-engine.md` +- Task ids: + - `cursor`: repo/branch별 last seen revision cursor를 저장한다. + - `event-input`: scan 결과를 `RevisionEvent` 후보로 변환한다. +- Completion mode: check-on-pass + +## 분석 결과 + +### 읽은 파일 + +- `agent-ops/rules/project/rules.md` +- `agent-ops/rules/private/rules.md` +- `agent-ops/rules/common/rules-roadmap.md` +- `agent-ops/skills/common/router.md` +- `agent-ops/skills/common/code-review/SKILL.md` +- `agent-ops/skills/common/plan/SKILL.md` +- `agent-ops/skills/common/_templates/implementation-user-review-request-section.md` +- `agent-ops/rules/project/domain/core/rules.md` +- `agent-ops/rules/project/domain/workspace-ops/rules.md` +- `agent-test/local/rules.md` +- `agent-test/local/core-smoke.md` +- `agent-test/local/workspace-ops-smoke.md` +- `agent-task/m-platformless-git-operation-engine/plan_local_G06_0.log` +- `agent-task/m-platformless-git-operation-engine/code_review_local_G06_0.log` +- `services/core/internal/controlplane/runtime.go` +- `services/core/internal/controlplane/runtime_test.go` +- `services/core/internal/gitengine/command.go` +- `services/core/internal/core/model.go` +- `services/core/internal/storage/storage.go` + +### 테스트 환경 규칙 + +- `test_env`: `local` +- `agent-test/local/rules.md`: 존재하며 읽음. +- 읽은 profile: + - `agent-test/local/core-smoke.md`: core 변경은 최소 `cd services/core && go test ./...`로 확인한다. gitengine/storage/controlplane behavior 변경은 해당 동작을 검증하는 테스트가 필요하다. + - `agent-test/local/workspace-ops-smoke.md`: task artifact와 roadmap 변경은 `git diff --check`로 확인한다. +- 적용 명령: + - focused: `cd services/core && go test -count=1 ./internal/controlplane -run TestRuntimeScanBranchRevisionBuildsRevisionEvent` + - focused suite: `cd services/core && go test -count=1 ./internal/controlplane -run TestRuntimeScanBranchRevision` + - core smoke: `cd services/core && go test ./...` + - workspace preflight: `git diff --check` +- `<확인 필요>` 값: 없음. +- fallback verification: 없음. + +### 테스트 커버리지 공백 + +- 기존 `TestRuntimeScanBranchRevisionBuildsRevisionEvent`는 no-watch changed scan이 event를 emit하지 않는지만 확인한다. 해당 scan 후 `revision_cursors`가 latest head로 전진했는지 검증하지 않아 이번 결함을 놓친다. +- watched changed scan, first observation, unchanged scan, changed file status 보존은 기존 테스트가 검증한다. + +### 심볼 참조 + +- renamed/removed symbol: none. +- relevant symbols: + - `services/core/internal/controlplane/runtime.go:186` `handleRevisionWithStore` + - `services/core/internal/controlplane/runtime.go:324` `ScanBranchRevision` + - `services/core/internal/controlplane/runtime.go:389` changed scan의 `HandleRevision` 호출 + - `services/core/internal/controlplane/runtime_test.go:442` `TestRuntimeScanBranchRevisionBuildsRevisionEvent` + +### 분할 판단 + +split policy를 평가했다. 수정은 `ScanBranchRevision`의 unmatched changed path와 단일 회귀 assertion에 한정되고, 별도 API foundation이나 broad rollout이 없다. 같은 controlplane 테스트 하나로 검증되므로 단일 follow-up plan이 가장 작고 안전하다. + +### 범위 결정 근거 + +- 포함: `services/core/internal/controlplane/runtime.go`, `services/core/internal/controlplane/runtime_test.go` +- 제외: provider webhook no-watch semantics, Postgres migration, gitengine parser, REST route, roadmap 문서 갱신. 이번 후속은 첫 리뷰 Required 결함만 고친다. + +### 빌드 등급 + +- build lane/grade: `local-G06` +- rationale: explicit deterministic correctness bug이며 변경 파일과 회귀 검증이 bounded core 내부 작업이다. + +## 구현 체크리스트 + +- [ ] no-watch changed scan이 event를 emit하지 않더라도 repo/branch cursor를 latest head로 저장하게 수정하고 회귀 테스트로 검증한다. +- [ ] `cd services/core && go test -count=1 ./internal/controlplane -run TestRuntimeScanBranchRevisionBuildsRevisionEvent`, `cd services/core && go test -count=1 ./internal/controlplane -run TestRuntimeScanBranchRevision`, `cd services/core && go test ./...`, `git diff --check`를 실행하고 결과를 review stub에 붙인다. +- [ ] CODE_REVIEW-*-G??.md의 구현 에이전트 소유 섹션을 실제 구현 내용과 검증 출력으로 채운다. 이 항목이 완료되기 전에는 구현이 완료된 것이 아니다. + +### [REVIEW_SCAN-1] No-Watch Changed Scan Cursor Advance + +문제: `services/core/internal/controlplane/runtime.go:389`에서 changed scan을 `HandleRevision(ctx, provider, "", revEvent)`에 그대로 위임한다. store-backed `HandleRevision`은 `services/core/internal/controlplane/runtime.go:187`에서 branch watch를 찾고, watch가 없으면 `services/core/internal/controlplane/runtime.go:192`에서 cursor 저장 전에 반환한다. 따라서 first observation으로 cursor가 생긴 no-watch scan target에 새 commit이 생기면 cursor가 old revision에 남아 같은 range를 반복 처리한다. + +해결 방법: `ScanBranchRevision`에서 `HandleRevision` 결과를 받은 뒤 `matched=false`이면 scan target cursor를 `after` revision으로 저장한다. `matched=true` 경로는 기존 `HandleRevision`의 cursor 저장을 그대로 사용해 중복 저장을 피한다. + +Before: +```go +// services/core/internal/controlplane/runtime.go:388 +revEvent := revisionEventFromScan(repoID, branch, before, after, files, observedAt) +return r.HandleRevision(ctx, provider, "", revEvent) +``` + +After: +```go +record, matched, err := r.HandleRevision(ctx, provider, "", revEvent) +if err != nil { + return record, matched, err +} +if !matched { + if err := r.store.RevisionCursors().UpsertRevisionCursor(ctx, core.RevisionCursor{ + RepoID: repoID, Branch: branch, Revision: after, ObservedAt: observedAt, + }); err != nil { + return record, false, fmt.Errorf("upsert revision cursor: %w", err) + } +} +return record, matched, nil +``` + +수정 파일 및 체크리스트: +- [ ] `services/core/internal/controlplane/runtime.go`: changed scan unmatched path에서 cursor를 latest head로 저장한다. +- [ ] `services/core/internal/controlplane/runtime_test.go`: `TestRuntimeScanBranchRevisionBuildsRevisionEvent`의 nowatch second scan 뒤 cursor revision이 새 head와 일치하는 assertion을 추가한다. + +테스트 작성: 작성한다. Test name은 기존 `TestRuntimeScanBranchRevisionBuildsRevisionEvent`를 확장한다. fixture는 기존 temp local git repo와 `fakeStore`를 사용하고, no-watch changed scan 후 `store.cursors.GetRevisionCursor(ctx, "nowatch", "main")`가 latest head를 반환해야 한다. + +중간 검증: +```bash +cd services/core && go test -count=1 ./internal/controlplane -run TestRuntimeScanBranchRevisionBuildsRevisionEvent +``` +기대 결과: `ok git.toki-labs.com/toki/gito/services/core/internal/controlplane`. + +## 수정 파일 요약 + +| 파일 | 항목 | +| --- | --- | +| `services/core/internal/controlplane/runtime.go` | REVIEW_SCAN-1 | +| `services/core/internal/controlplane/runtime_test.go` | REVIEW_SCAN-1 | + +## 최종 검증 + +```bash +cd services/core && go test -count=1 ./internal/controlplane -run TestRuntimeScanBranchRevisionBuildsRevisionEvent +``` + +```bash +cd services/core && go test -count=1 ./internal/controlplane -run TestRuntimeScanBranchRevision +``` + +```bash +cd services/core && go test ./... +``` + +```bash +git diff --check +``` + +기대 결과: 모든 명령이 exit code 0으로 종료한다. focused controlplane 명령은 fresh execution이 필요하고, `go test ./...`의 cache output은 허용한다. + +모든 코드 변경 완료 후 반드시 `CODE_REVIEW-*-G??.md`의 구현 에이전트 소유 섹션을 채운다. 이 파일 작성이 구현의 마지막 단계다. diff --git a/services/core/internal/controlplane/runtime.go b/services/core/internal/controlplane/runtime.go index c937aae..ad7c870 100644 --- a/services/core/internal/controlplane/runtime.go +++ b/services/core/internal/controlplane/runtime.go @@ -12,6 +12,7 @@ import ( "git.toki-labs.com/toki/gito/services/core/internal/core" "git.toki-labs.com/toki/gito/services/core/internal/events" + "git.toki-labs.com/toki/gito/services/core/internal/gitengine" "git.toki-labs.com/toki/gito/services/core/internal/protosocket" "git.toki-labs.com/toki/gito/services/core/internal/storage" ) @@ -310,3 +311,113 @@ func newID() string { } return hex.EncodeToString(b) } + +type ScanRevisionOptions struct { + Provider string + RepoID string + Branch string + Workdir string + Runner gitengine.CommandRunner + ObservedAt time.Time +} + +func (r *Runtime) ScanBranchRevision(ctx context.Context, opts ScanRevisionOptions) (EventRecord, bool, error) { + if r.store == nil || r.store.RevisionCursors() == nil { + return EventRecord{}, false, fmt.Errorf("revision cursor store not supported") + } + + repoID := strings.TrimSpace(opts.RepoID) + branch := strings.TrimSpace(opts.Branch) + workdir := strings.TrimSpace(opts.Workdir) + if repoID == "" || branch == "" || workdir == "" { + return EventRecord{}, false, fmt.Errorf("repo_id, branch, and workdir are required") + } + + provider := strings.TrimSpace(opts.Provider) + if provider == "" { + provider = "forgejo" + } + + runner := opts.Runner + if runner == nil { + runner = gitengine.CLI{} + } + + after, err := gitengine.HeadRevision(runner, workdir) + if err != nil { + return EventRecord{}, false, fmt.Errorf("head revision: %w", err) + } + + observedAt := opts.ObservedAt + if observedAt.IsZero() { + observedAt = time.Now().UTC() + } + + cursor, found, err := r.store.RevisionCursors().GetRevisionCursor(ctx, repoID, branch) + if err != nil { + return EventRecord{}, false, fmt.Errorf("get revision cursor: %w", err) + } + + if !found { + newCursor := core.RevisionCursor{ + RepoID: repoID, + Branch: branch, + Revision: after, + ObservedAt: observedAt, + } + if err := r.store.RevisionCursors().UpsertRevisionCursor(ctx, newCursor); err != nil { + return EventRecord{}, false, fmt.Errorf("upsert revision cursor: %w", err) + } + return EventRecord{}, false, nil + } + + if cursor.Revision == after { + cursor.ObservedAt = observedAt + if err := r.store.RevisionCursors().UpsertRevisionCursor(ctx, cursor); err != nil { + return EventRecord{}, false, fmt.Errorf("upsert revision cursor: %w", err) + } + return EventRecord{}, false, nil + } + + before := cursor.Revision + files, err := gitengine.ChangedFilesWithStatus(runner, workdir, before, after) + if err != nil { + return EventRecord{}, false, fmt.Errorf("changed files with status: %w", err) + } + + revEvent := revisionEventFromScan(repoID, branch, before, after, files, observedAt) + record, matched, err := r.HandleRevision(ctx, provider, "", revEvent) + if err != nil { + return record, matched, err + } + if !matched { + cursor := core.RevisionCursor{ + RepoID: repoID, + Branch: branch, + Revision: after, + ObservedAt: observedAt, + } + if err := r.store.RevisionCursors().UpsertRevisionCursor(ctx, cursor); err != nil { + return record, false, fmt.Errorf("upsert revision cursor: %w", err) + } + } + return record, matched, nil +} + +func revisionEventFromScan(repoID, branch, before, after string, files []gitengine.ChangedFile, observedAt time.Time) core.RevisionEvent { + changedFiles := make([]core.ChangedFile, 0, len(files)) + for _, f := range files { + changedFiles = append(changedFiles, core.ChangedFile{ + Path: f.Path, + ChangeType: f.ChangeType, + }) + } + return core.RevisionEvent{ + RepoID: repoID, + Branch: branch, + Before: before, + After: after, + ChangedFiles: changedFiles, + ObservedAt: observedAt, + } +} diff --git a/services/core/internal/controlplane/runtime_test.go b/services/core/internal/controlplane/runtime_test.go index 9d51ce8..1f6b10d 100644 --- a/services/core/internal/controlplane/runtime_test.go +++ b/services/core/internal/controlplane/runtime_test.go @@ -6,6 +6,10 @@ import ( "encoding/json" "net/http" "net/http/httptest" + "os" + "os/exec" + "path/filepath" + "strings" "sync" "testing" "time" @@ -13,6 +17,7 @@ import ( "git.toki-labs.com/toki/gito/services/core/internal/config" "git.toki-labs.com/toki/gito/services/core/internal/core" "git.toki-labs.com/toki/gito/services/core/internal/events" + "git.toki-labs.com/toki/gito/services/core/internal/gitengine" "git.toki-labs.com/toki/gito/services/core/internal/storage" ) @@ -291,3 +296,268 @@ func TestForgejoPushDuplicateDeliveryIsIdempotent(t *testing.T) { t.Fatalf("events count: got %d want 1", len(evBody["events"])) } } + +func setupGitRepo(t *testing.T) (workdir string, initialRev string) { + tmpDir := t.TempDir() + workdir = filepath.Join(tmpDir, "repo") + if err := os.MkdirAll(workdir, 0755); err != nil { + t.Fatalf("failed to create repo dir: %v", err) + } + runGit(t, workdir, "init") + runGit(t, workdir, "config", "user.name", "Test User") + runGit(t, workdir, "config", "user.email", "test@example.com") + runGit(t, workdir, "config", "commit.gpgsign", "false") + runGit(t, workdir, "branch", "-M", "main") + + writeFile(t, filepath.Join(workdir, "README.md"), "# Seed Repository\n") + runGit(t, workdir, "add", "README.md") + runGit(t, workdir, "commit", "-m", "initial commit") + + cmd := exec.Command("git", "rev-parse", "HEAD") + cmd.Dir = workdir + out, err := cmd.Output() + if err != nil { + t.Fatalf("failed to get head rev: %v", err) + } + initialRev = strings.TrimSpace(string(out)) + return workdir, initialRev +} + +func runGit(t *testing.T, dir string, args ...string) { + cmd := exec.Command("git", args...) + cmd.Dir = dir + if out, err := cmd.CombinedOutput(); err != nil { + t.Fatalf("git %s failed: %v, output: %s", strings.Join(args, " "), err, string(out)) + } +} + +func writeFile(t *testing.T, path, content string) { + if err := os.WriteFile(path, []byte(content), 0644); err != nil { + t.Fatalf("WriteFile %s failed: %v", path, err) + } +} + +func TestRuntimeScanBranchRevisionCursorStates(t *testing.T) { + store := newFakeStore() + r := NewRuntimeWithStore(nil, store) + workdir, initialRev := setupGitRepo(t) + + opts := ScanRevisionOptions{ + RepoID: "myrepo", + Branch: "main", + Workdir: workdir, + Runner: gitengine.CLI{}, + } + + // 1. First observation: stores cursor, returns no event, matched=false + record, matched, err := r.ScanBranchRevision(context.Background(), opts) + if err != nil { + t.Fatalf("first scan: %v", err) + } + if matched { + t.Fatal("first scan: expected matched=false") + } + if record.ID != "" { + t.Fatalf("first scan: expected empty record, got %+v", record) + } + + cursor, ok, err := store.cursors.GetRevisionCursor(context.Background(), "myrepo", "main") + if err != nil { + t.Fatalf("get cursor: %v", err) + } + if !ok { + t.Fatal("first scan: cursor not stored") + } + if cursor.Revision != initialRev { + t.Fatalf("first scan cursor revision: got %q want %q", cursor.Revision, initialRev) + } + + // 2. Unchanged revision: no event, updates observed time (or stays unchanged), matched=false + record2, matched2, err := r.ScanBranchRevision(context.Background(), opts) + if err != nil { + t.Fatalf("second scan: %v", err) + } + if matched2 { + t.Fatal("second scan: expected matched=false") + } + if record2.ID != "" { + t.Fatalf("second scan: expected empty record, got %+v", record2) + } + + cursor2, ok2, err := store.cursors.GetRevisionCursor(context.Background(), "myrepo", "main") + if err != nil { + t.Fatalf("get cursor2: %v", err) + } + if !ok2 { + t.Fatal("second scan: cursor not found") + } + if cursor2.Revision != initialRev { + t.Fatalf("second scan cursor revision: got %q want %q", cursor2.Revision, initialRev) + } + + // 3. Changed revision with watch: stores cursor with new revision, returns event, matched=true + _, err = r.RegisterBranchWatch("myrepo", "main", "forgejo") + if err != nil { + t.Fatalf("register watch: %v", err) + } + + writeFile(t, filepath.Join(workdir, "README.md"), "# Seed Repository\n\nupdated\n") + runGit(t, workdir, "add", "README.md") + runGit(t, workdir, "commit", "-m", "update readme") + + cmd := exec.Command("git", "rev-parse", "HEAD") + cmd.Dir = workdir + out, err := cmd.Output() + if err != nil { + t.Fatalf("get head: %v", err) + } + afterRev := strings.TrimSpace(string(out)) + + record3, matched3, err := r.ScanBranchRevision(context.Background(), opts) + if err != nil { + t.Fatalf("third scan: %v", err) + } + if !matched3 { + t.Fatal("third scan: expected matched=true") + } + if record3.Revision.Before != initialRev { + t.Fatalf("third scan record before: got %q want %q", record3.Revision.Before, initialRev) + } + if record3.Revision.After != afterRev { + t.Fatalf("third scan record after: got %q want %q", record3.Revision.After, afterRev) + } + + cursor3, ok3, err := store.cursors.GetRevisionCursor(context.Background(), "myrepo", "main") + if err != nil { + t.Fatalf("get cursor3: %v", err) + } + if !ok3 { + t.Fatal("third scan: cursor not found") + } + if cursor3.Revision != afterRev { + t.Fatalf("third scan cursor revision: got %q want %q", cursor3.Revision, afterRev) + } +} + +func TestRuntimeScanBranchRevisionBuildsRevisionEvent(t *testing.T) { + store := newFakeStore() + r := NewRuntimeWithStore(nil, store) + workdir, initialRev := setupGitRepo(t) + + // Register watch + _, err := r.RegisterBranchWatch("myrepo", "main", "forgejo") + if err != nil { + t.Fatalf("register watch: %v", err) + } + + opts := ScanRevisionOptions{ + RepoID: "myrepo", + Branch: "main", + Workdir: workdir, + Runner: gitengine.CLI{}, + } + + // First scan (observation) + _, _, err = r.ScanBranchRevision(context.Background(), opts) + if err != nil { + t.Fatalf("first scan: %v", err) + } + + // Make changes + writeFile(t, filepath.Join(workdir, "newfile.txt"), "new file") + writeFile(t, filepath.Join(workdir, "README.md"), "# Seed Repository\n\nupdated\n") + runGit(t, workdir, "add", "newfile.txt", "README.md") + runGit(t, workdir, "commit", "-m", "add newfile and update readme") + + cmd := exec.Command("git", "rev-parse", "HEAD") + cmd.Dir = workdir + out, err := cmd.Output() + if err != nil { + t.Fatalf("get head: %v", err) + } + afterRev := strings.TrimSpace(string(out)) + + // Second scan (changes) + record, matched, err := r.ScanBranchRevision(context.Background(), opts) + if err != nil { + t.Fatalf("second scan: %v", err) + } + if !matched { + t.Fatal("expected matched=true") + } + if record.Revision.Before != initialRev { + t.Fatalf("before: got %q want %q", record.Revision.Before, initialRev) + } + if record.Revision.After != afterRev { + t.Fatalf("after: got %q want %q", record.Revision.After, afterRev) + } + + // Verify changed files + if len(record.Revision.ChangedFiles) != 2 { + t.Fatalf("expected 2 changed files, got %d", len(record.Revision.ChangedFiles)) + } + filesMap := make(map[string]string) + for _, f := range record.Revision.ChangedFiles { + filesMap[f.Path] = f.ChangeType + } + if filesMap["README.md"] != "modified" { + t.Fatalf("README.md change type: got %q want 'modified'", filesMap["README.md"]) + } + if filesMap["newfile.txt"] != "added" { + t.Fatalf("newfile.txt change type: got %q want 'added'", filesMap["newfile.txt"]) + } + + // Check cursor updated + cursor, ok, err := store.cursors.GetRevisionCursor(context.Background(), "myrepo", "main") + if err != nil || !ok { + t.Fatalf("get cursor: err=%v ok=%v", err, ok) + } + if cursor.Revision != afterRev { + t.Fatalf("cursor: got %q want %q", cursor.Revision, afterRev) + } + + // Test no watch event emit + optsNoWatch := ScanRevisionOptions{ + RepoID: "nowatch", + Branch: "main", + Workdir: workdir, + Runner: gitengine.CLI{}, + } + // Initial scan for nowatch (stores cursor) + _, _, err = r.ScanBranchRevision(context.Background(), optsNoWatch) + if err != nil { + t.Fatalf("first scan nowatch: %v", err) + } + + // Add another commit + writeFile(t, filepath.Join(workdir, "another.txt"), "another") + runGit(t, workdir, "add", "another.txt") + runGit(t, workdir, "commit", "-m", "add another") + + // Second scan for nowatch (no watch registered) + beforeEvents := len(r.ListEvents()) + _, matchedNoWatch, err := r.ScanBranchRevision(context.Background(), optsNoWatch) + if err != nil { + t.Fatalf("second scan nowatch: %v", err) + } + if matchedNoWatch { + t.Fatal("expected matched=false for unwatched repo") + } + afterEvents := len(r.ListEvents()) + if afterEvents != beforeEvents { + t.Fatalf("expected events count to remain %d, got %d", beforeEvents, afterEvents) + } + + // Verify unwatched cursor advanced to latest head revision + latestHead, err := gitengine.HeadRevision(gitengine.CLI{}, workdir) + if err != nil { + t.Fatalf("failed to get head rev for verify: %v", err) + } + cursorNoWatch, okNoWatch, err := store.cursors.GetRevisionCursor(context.Background(), "nowatch", "main") + if err != nil || !okNoWatch { + t.Fatalf("get nowatch cursor: err=%v ok=%v", err, okNoWatch) + } + if cursorNoWatch.Revision != latestHead { + t.Fatalf("unwatched cursor did not advance: got %q want %q", cursorNoWatch.Revision, latestHead) + } +} diff --git a/services/core/internal/gitengine/command_test.go b/services/core/internal/gitengine/command_test.go index 9f777c1..cf2d713 100644 --- a/services/core/internal/gitengine/command_test.go +++ b/services/core/internal/gitengine/command_test.go @@ -184,6 +184,75 @@ func TestChangedFilesWithStatus(t *testing.T) { } } +func TestChangedFilesWithStatusLocalCommits(t *testing.T) { + _, seedPath, initialRev := setupBareRemote(t) + + writeFile(t, filepath.Join(seedPath, "README.md"), "# Seed Repository\n\nupdated\n") + writeFile(t, filepath.Join(seedPath, "app.txt"), "app\n") + runGit(t, seedPath, "add", "README.md", "app.txt") + runGit(t, seedPath, "commit", "-m", "update readme and add app") + + docsDir := filepath.Join(seedPath, "docs") + if err := os.MkdirAll(docsDir, 0755); err != nil { + t.Fatalf("MkdirAll %s failed: %v", docsDir, err) + } + writeFile(t, filepath.Join(docsDir, "guide.md"), "# Guide\n") + runGit(t, seedPath, "add", "docs/guide.md") + runGit(t, seedPath, "commit", "-m", "add guide") + afterRev := gitOutput(t, seedPath, "rev-parse", "HEAD") + + names, err := ChangedFiles(CLI{}, seedPath, initialRev, afterRev) + if err != nil { + t.Fatalf("ChangedFiles: %v", err) + } + wantNames := []string{"README.md", "app.txt", "docs/guide.md"} + if !sameStringSet(names, wantNames) { + t.Fatalf("changed file names: got %#v want %#v", names, wantNames) + } + + files, err := ChangedFilesWithStatus(CLI{}, seedPath, initialRev, afterRev) + if err != nil { + t.Fatalf("ChangedFilesWithStatus: %v", err) + } + wantStatus := map[string]string{ + "README.md": "modified", + "app.txt": "added", + "docs/guide.md": "added", + } + if !sameChangedFileStatus(files, wantStatus) { + t.Fatalf("changed file status: got %#v want %#v", files, wantStatus) + } +} + +func sameStringSet(got, want []string) bool { + if len(got) != len(want) { + return false + } + seen := make(map[string]int, len(got)) + for _, item := range got { + seen[item]++ + } + for _, item := range want { + if seen[item] == 0 { + return false + } + seen[item]-- + } + return true +} + +func sameChangedFileStatus(got []ChangedFile, want map[string]string) bool { + if len(got) != len(want) { + return false + } + for _, file := range got { + if want[file.Path] != file.ChangeType { + return false + } + } + return true +} + func runGit(t *testing.T, dir string, args ...string) { cmd := exec.Command("git", args...) cmd.Dir = dir