Compare commits

..
Author SHA1 Message Date
chenyunda218 9e699f3b4e docs+test:空輸出判決 #37——維持 []/null、補 stalled 空輸出測試 2026-09-12 23:43:29 +08:00
queena d689107eea Merge pull request 'internal/workflow:directLastActivity 排除跨 issue 引用事件(#34)' (#36) from fix/issue34-direct-last-activity into main 2026-09-12 15:24:23 +08:00
ceo 027ed1ade9 workflow_test:fakeSource.OpenIssues 依 number 排序,消除 map 迭代隨機性
審核意見(PR #36):issue 1 與 issue 3 在新邏輯下同為 10h,
sort.SliceStable 平手時順序取決於 map 迭代隨機順序,
TestScanStalledIssueReasons 的 got[0].Number != 1 斷言不穩定。

採建議修法 1:fakeSource.OpenIssues 回傳前依 number 遞增排序,
對齊真實 Gitea API(issues 依 id 遞增)行為。實作未動。

go build / go vet / go test ./... 全綠;
TestScanStalledIssueReasons -count=50 重跑全綠。
2026-09-12 15:21:21 +08:00
ceo e4212b9c90 internal/workflow:directLastActivity 排除跨 issue 引用事件(#34)
同步 agents #34/#38/#40 三個停滯判定修補到 Go 端:

- Source 介面新增 IssueTimeline(GET /repos/{o}/{r}/issues/{n}/timeline,分頁),
  giteaapi.go 與 cmd/xcheck 同步實作
- 新增 directLastActivity:updated_at 晚於全部已知直接活動時拉 timeline 核對,
  排除 comment_ref/issue_ref 引用事件後取最晚;全為引用事件回退已知直接活動
  最晚時刻(agents #40);timeline 失敗保守沿用 updated_at
- considerIssue/considerPull 對自身 updated_at、childActivity 對子項 updated_at
  (含子項 created_at 入已知活動)套用同一排除邏輯(agents #38)
- 回歸測試:子項 updated_at 被引用刷新(TestRunStalledChildXrefRefresh)、
  timeline 全引用事件回退與拉取失敗保守路徑(TestRunStalledTimelineAllXrefFallback)
- 修正 workflow_test.go:timelines 須在 ScanStalled 呼叫前設定

驗證:go build/vet/test 全綠;xcheck 對真實 API 掃描,
stalled 輸出與 gitea.py(agents @ 78769ec)位元組一致(5833 bytes)。
2026-09-12 15:10:31 +08:00
queena a2baf55fce Merge pull request 'dailyops:list 命令 --state all 明確帶 state=all(#33)' (#35) from fix/issue33-state-all into main 2026-09-11 11:32:53 +08:00
chenyunda218 1f6806ff99 dailyops:list 命令 --state all 明確帶 state=all(#33)
issues/milestones 端點省略 state 時 API 預設 open,closed 項目漏列;
pulls 端點省略時雖回全部,仍明確帶上避免依賴端點預設。三處同修並補
回歸測試(TestStateAllSendsExplicitParam)。
2026-09-11 11:29:00 +08:00
9 changed files with 345 additions and 32 deletions
+7 -3
View File
@@ -299,7 +299,7 @@ teai whoami # 目前帳號(讀 tea 組態)
| 碼 | 意義 | | 碼 | 意義 |
| --- | --- | | --- | --- |
| 0 | 成功(含「沒有工作」→ 輸出 `null`/`[]`) | | 0 | 成功(含「沒有結果」→ 清單類命令輸出 `[]`、`next` 輸出 `null`;#37 判決) |
| 2 | 用法錯誤(未知命令/參數) | | 2 | 用法錯誤(未知命令/參數) |
| 3 | API 錯誤(連線失敗、401、403、5xx) | | 3 | API 錯誤(連線失敗、401、403、5xx) |
@@ -318,8 +318,12 @@ teai whoami # 目前帳號(讀 tea 組態)
已知輸出差異(刻意保留,機器可讀優先): 已知輸出差異(刻意保留,機器可讀優先):
- **空清單**:`gitea.py` 的 `_dump` 對空清單**不輸出任何內容**;teai 的清單類命令 - **空清單**:`gitea.py` 的 `_dump` 對空清單**不輸出任何內容**;teai 的清單類命令
(`mine`/`pulls`/`milestones` 總覽)空清單輸出 `[]`。對 JSON 消費者來說 `[]` 比「無輸出」更明確, (`mine`/`pulls`/`stalled`/`milestones` 總覽)空清單一律輸出 `[]`(exit 0)。對 JSON
交叉驗證時以此差異為準。`next` 兩者語義相同(無工作 → `null`/「沒有未完成的工作」)。 消費者來說 `[]` 比「無輸出」更明確(可區分「沒有結果」與「查詢失敗無輸出」),交叉驗證時
以此差異為準。`next` 兩者語義相同:無工作時 teai 輸出 `null`(exit 0)、`gitea.py` 印
「沒有未完成的工作」。**判決 #37:維持 teai 現行 JSON 一致性(方向 2)**——消費端
(agents 倉庫巡邏提示與觸發腳本)應以「輸出 `[]`/`null` 且 exit 0」為「沒有」判據,
不得以「無輸出」判斷;`members [--has-work]` 維持逐行帳號、空時無輸出(兩者一致,不受影響)。
- **清單欄位集(`mine`/`pulls`)**:`gitea.py` 直接傾倒完整 Gitea API 物件 - **清單欄位集(`mine`/`pulls`)**:`gitea.py` 直接傾倒完整 Gitea API 物件
(`_dump` 的副作用,欄位集隨 Gitea 版本浮動);teai 輸出策展摘要欄位 (`_dump` 的副作用,欄位集隨 Gitea 版本浮動);teai 輸出策展摘要欄位
(`mine`:repo/number/title/url;`pulls`:number/title/state/author/ (`mine`:repo/number/title/url;`pulls`:number/title/state/author/
+8
View File
@@ -165,6 +165,14 @@ func (s *apiSource) IssueComments(owner, repo string, number int64) ([]workflow.
return comments, nil return comments, nil
} }
func (s *apiSource) IssueTimeline(owner, repo string, number int64) ([]workflow.TimelineEvent, error) {
var events []workflow.TimelineEvent
if err := s.listAll(fmt.Sprintf("repos/%s/%s/issues/%d/timeline", owner, repo, number), nil, &events); err != nil {
return nil, err
}
return events, nil
}
func (s *apiSource) TryGetIssue(owner, repo string, number int64) (workflow.Issue, bool, error) { func (s *apiSource) TryGetIssue(owner, repo string, number int64) (workflow.Issue, bool, error) {
var issue workflow.Issue var issue workflow.Issue
body, code, err := s.get(fmt.Sprintf("repos/%s/%s/issues/%d", owner, repo, number), nil) body, code, err := s.get(fmt.Sprintf("repos/%s/%s/issues/%d", owner, repo, number), nil)
+46
View File
@@ -220,6 +220,52 @@ func TestLabelsMilestonesReleasesList(t *testing.T) {
} }
} }
// TestStateAllSendsExplicitParam 是 #33 的回歸測試:issues/milestones
// 端點省略 state 時 API 預設 open,closed 項目會漏列,因此 --state all
// 必須明確帶 state=all;pulls 端點雖省略時也回全部,同樣明確帶上。
func TestStateAllSendsExplicitParam(t *testing.T) {
cases := []struct {
args []string
resp string
wantOut string
}{
{
args: []string{"issues", "list", "--repo", "a/b", "--state", "all"},
resp: `[{"number":30,"title":"open","state":"open","user":{"login":"ceo"},"updated_at":"t"},{"number":12,"title":"closed","state":"closed","user":{"login":"ceo"},"updated_at":"t"}]`,
wantOut: `"title":"closed"`,
},
{
args: []string{"pulls", "list", "--repo", "a/b", "--state", "all"},
resp: `[{"number":5,"title":"open PR","state":"open","user":{"login":"ceo"},"head":{"ref":"f"},"base":{"ref":"main"},"updated_at":"t"},{"number":2,"title":"closed PR","state":"closed","user":{"login":"ceo"},"head":{"ref":"f2"},"base":{"ref":"main"},"updated_at":"t"}]`,
wantOut: `"title":"closed PR"`,
},
{
args: []string{"milestones", "list", "--repo", "a/b", "--state", "all"},
resp: `[{"title":"v2","state":"open","description":"","due_on":""},{"title":"v1","state":"closed","description":"","due_on":""}]`,
wantOut: `"title":"v1"`,
},
}
for _, tc := range cases {
t.Run(strings.Join(tc.args, " "), func(t *testing.T) {
var gotQuery string
run := opsTestServer(t, func(w http.ResponseWriter, r *http.Request) {
gotQuery = r.URL.RawQuery
fmt.Fprint(w, tc.resp)
})
stdout, _, code := run(tc.args...)
if code != 0 {
t.Fatalf("%v 應回 0,得到 %d", tc.args, code)
}
if !strings.Contains(gotQuery, "state=all") {
t.Errorf("%v 應明確帶 state=all(省略時 issues/milestones 端點預設 open),得到查詢 %q", tc.args, gotQuery)
}
if !strings.Contains(stdout, tc.wantOut) {
t.Errorf("%v 輸出應含 closed 項目 %s,得到:%s", tc.args, tc.wantOut, stdout)
}
})
}
}
// TestAPIDirectPassthrough 驗證 teai api 原樣輸出、GET 免 --yes、 // TestAPIDirectPassthrough 驗證 teai api 原樣輸出、GET 免 --yes、
// POST 未帶 --yes 被擋。 // POST 未帶 --yes 被擋。
func TestAPIDirectPassthrough(t *testing.T) { func TestAPIDirectPassthrough(t *testing.T) {
+21
View File
@@ -46,6 +46,9 @@ func (s *stubStalledSource) TryGetIssue(owner, repo string, number int64) (workf
i, ok := s.issues[owner+"/"+repo][number] i, ok := s.issues[owner+"/"+repo][number]
return i, ok, nil return i, ok, nil
} }
func (s *stubStalledSource) IssueTimeline(owner, repo string, number int64) ([]workflow.TimelineEvent, error) {
return nil, nil
}
func (s *stubStalledSource) GetIssue(owner, repo string, number int64) (workflow.Issue, error) { func (s *stubStalledSource) GetIssue(owner, repo string, number int64) (workflow.Issue, error) {
if s.getErr != nil { if s.getErr != nil {
return workflow.Issue{}, s.getErr return workflow.Issue{}, s.getErr
@@ -114,6 +117,24 @@ func TestWiringStalled(t *testing.T) {
} }
} }
// TestWiringStalledEmpty 驗證 stalled 無任何條目時輸出 []、exit 0(#37)。
func TestWiringStalledEmpty(t *testing.T) {
newStubStalledEnv(t, &stubStalledSource{
username: "ceo",
orgs: []string{"alterminal"},
repos: map[string][]workflow.Repo{"alterminal": {}},
issues: map[string]map[int64]workflow.Issue{},
comments: map[string][]workflow.Comment{},
}, time.Date(2026, 9, 10, 8, 0, 0, 0, time.UTC))
stdout, _, code := run("stalled")
if code != 0 {
t.Fatalf("stalled 空情境應回 0,得到 %d(stdout=%q)", code, stdout)
}
if strings.TrimSpace(stdout) != "[]" {
t.Fatalf("stalled 無條目應輸出 [],得到 %q", stdout)
}
}
// TestWiringStalledHoursFlag 驗證 --hours 覆寫門檻與非正數被攔。 // TestWiringStalledHoursFlag 驗證 --hours 覆寫門檻與非正數被攔。
func TestWiringStalledHoursFlag(t *testing.T) { func TestWiringStalledHoursFlag(t *testing.T) {
freeze := time.Date(2026, 9, 10, 8, 0, 0, 0, time.UTC) freeze := time.Date(2026, 9, 10, 8, 0, 0, 0, time.UTC)
+6 -6
View File
@@ -170,10 +170,10 @@ func (o *Ops) ListIssues(ctx context.Context, owner, repo, state string) ([]Issu
if state == "" { if state == "" {
state = "open" state = "open"
} }
// state 一律明確傳給 API:issues/milestones 端點省略 state 時預設
// open(#33),closed 項目會漏列;all 也不能省略。
extra := url.Values{} extra := url.Values{}
if state != "all" {
extra.Set("state", state) extra.Set("state", state)
}
// type=issues:排除 PR(PR 在此端點帶 pull_request 欄位)。 // type=issues:排除 PR(PR 在此端點帶 pull_request 欄位)。
extra.Set("type", "issues") extra.Set("type", "issues")
var issues []Issue var issues []Issue
@@ -246,10 +246,10 @@ func (o *Ops) ListPulls(ctx context.Context, owner, repo, state string) ([]Pull,
if state == "" { if state == "" {
state = "open" state = "open"
} }
// state 一律明確傳給 API:pulls 端點省略 state 時雖回全部,仍明確
// 帶上,避免依賴端點預設值(#33)。
extra := url.Values{} extra := url.Values{}
if state != "all" {
extra.Set("state", state) extra.Set("state", state)
}
var pulls []Pull var pulls []Pull
if err := o.Client.ListAll(ctx, repoPath(owner, repo)+"/pulls", gitea.ListOptions{Extra: extra}, &pulls); err != nil { if err := o.Client.ListAll(ctx, repoPath(owner, repo)+"/pulls", gitea.ListOptions{Extra: extra}, &pulls); err != nil {
return nil, err return nil, err
@@ -320,10 +320,10 @@ func (o *Ops) ListMilestones(ctx context.Context, owner, repo, state string) ([]
if state == "" { if state == "" {
state = "open" state = "open"
} }
// state 一律明確傳給 API:milestones 端點省略 state 時預設 open
// (#33),closed 項目會漏列。
extra := url.Values{} extra := url.Values{}
if state != "all" {
extra.Set("state", state) extra.Set("state", state)
}
var ms []Milestone var ms []Milestone
if err := o.Client.ListAll(ctx, repoPath(owner, repo)+"/milestones", gitea.ListOptions{Extra: extra}, &ms); err != nil { if err := o.Client.ListAll(ctx, repoPath(owner, repo)+"/milestones", gitea.ListOptions{Extra: extra}, &ms); err != nil {
return nil, err return nil, err
+13
View File
@@ -150,6 +150,19 @@ func (a *APIClient) TryGetIssue(owner, repo string, number int64) (Issue, bool,
return issue, true, nil return issue, true, nil
} }
// IssueTimeline 回傳 issue 的 timeline 事件(Source 面向;對應 gitea.py
// _direct_last_activity 拉取的 repos/{o}/{r}/issues/{n}/timeline)。
// 分頁由 ListAll 處理(與 gitea.py api_get_list 的 limit=50 逐頁一致)。
func (a *APIClient) IssueTimeline(owner, repo string, number int64) ([]TimelineEvent, error) {
var events []TimelineEvent
path := "/repos/" + url.PathEscape(owner) + "/" + url.PathEscape(repo) +
"/issues/" + strconv.FormatInt(number, 10) + "/timeline"
if err := a.Client.ListAll(context.Background(), path, gitea.ListOptions{}, &events); err != nil {
return nil, err
}
return events, nil
}
// MyOrganizations 委派 ListOrgs(Source 面向)。 // MyOrganizations 委派 ListOrgs(Source 面向)。
func (a *APIClient) MyOrganizations() ([]string, error) { return a.ListOrgs() } func (a *APIClient) MyOrganizations() ([]string, error) { return a.ListOrgs() }
+103
View File
@@ -3,6 +3,8 @@
package workflow package workflow
import ( import (
"errors"
"fmt"
"strings" "strings"
"testing" "testing"
"time" "time"
@@ -14,10 +16,22 @@ type fakeStalledSource struct {
username string username string
// getIssueErr 模擬 GetIssue 失敗(xrefs 的 404 路徑)。 // getIssueErr 模擬 GetIssue 失敗(xrefs 的 404 路徑)。
getIssueErr error getIssueErr error
// timeline[owner/repo/number]:issue timeline 事件(無則回空清單,
// 模擬 API 成功但無事件;timelineErr 模擬拉取失敗)。
timeline map[string][]TimelineEvent
timelineErr map[string]error
} }
func (f *fakeStalledSource) CurrentUser() (string, error) { return f.username, nil } func (f *fakeStalledSource) CurrentUser() (string, error) { return f.username, nil }
func (f *fakeStalledSource) IssueTimeline(owner, repo string, number int64) ([]TimelineEvent, error) {
key := fmt.Sprintf("%s/%s/%d", owner, repo, number)
if err := f.timelineErr[key]; err != nil {
return nil, err
}
return f.timeline[key], nil
}
func (f *fakeStalledSource) GetIssue(owner, repo string, number int64) (Issue, error) { func (f *fakeStalledSource) GetIssue(owner, repo string, number int64) (Issue, error) {
if f.getIssueErr != nil { if f.getIssueErr != nil {
return Issue{}, f.getIssueErr return Issue{}, f.getIssueErr
@@ -229,3 +243,92 @@ func TestResolveIssueXrefsEmptyBody(t *testing.T) {
} }
_ = time.Now // time 僅供 iso/at 使用;保留 import。 _ = time.Now // time 僅供 iso/at 使用;保留 import。
} }
// TestRunStalledChildXrefRefresh 回歸測試(agents #38、teai #34):
// 子項 updated_at 被跨 issue 引用(comment_ref)刷新時,子項有效活動
// 應經 directLastActivity 排除引用事件後採計,父追蹤項的停滯時鐘
// 不被虛假刷新。
func TestRunStalledChildXrefRefresh(t *testing.T) {
src := newStalledFixture()
// 子項 teai#2:直接活動為 created(-500) 與留言(-90),
// updated_at 卻是 -10(他處留言提及刷新)。
issue := src.issues["alterminal/teai"][2]
issue.UpdatedAt = iso(-10)
src.issues["alterminal/teai"][2] = issue
// timeline:-10 的刷新是 comment_ref(引用事件,排除),
// -90 有直接事件(label)可對應 → 有效活動 -90。
src.timeline = map[string][]TimelineEvent{
"alterminal/teai/2": {
{Type: "label", CreatedAt: iso(-90)},
{Type: "comment_ref", CreatedAt: iso(-10)},
},
}
// 門檻 1 小時:父項 last_activity 取子項有效活動 -90 → 停滯 1.5h 列入;
// 若誤採被刷新的 -10,父項與子項都不會列入。
items, err := RunStalled(src, 1, at(0))
if err != nil {
t.Fatalf("RunStalled: %v", err)
}
if len(items) != 2 {
t.Fatalf("應有兩筆(父追蹤項+子項),得到 %d:%+v", len(items), items)
}
var parent *Item
for i := range items {
if items[i].Repo == "alterminal/agents" && items[i].Number == 1 {
parent = &items[i]
}
}
if parent == nil {
t.Fatalf("找不到 agents#1:%+v", items)
}
if parent.Reason != "parent-tracking" {
t.Fatalf("agents#1 應為 parent-tracking,得到 %s", parent.Reason)
}
if parent.StalledHours != 1.5 {
t.Fatalf("父項停滯應以子項有效活動(-90m → 1.5h)計,得到 %.1f", parent.StalledHours)
}
}
// TestRunStalledTimelineAllXrefFallback 回歸測試(agents #40、teai #34):
// issue 自身 updated_at 晚於全部已知直接活動、且 timeline 全為引用事件時,
// 回退已知直接活動的最晚時刻(不高估活動、不低估停滯);
// timeline 拉取失敗則保守沿用 updated_at。
func TestRunStalledTimelineAllXrefFallback(t *testing.T) {
src := newStalledFixture()
setIssueBody(src, "alterminal", "agents", 1, "") // 移除父項引用,teai#2 獨立判定
delete(src.comments, "alterminal/teai/2")
// agents#1 給一則近期留言,避免本身停滯(10h)干擾本測試的斷言。
src.comments["alterminal/agents/1"] = []Comment{
{CreatedAt: iso(-10), User: &User{UserName: "alex"}},
}
// teai#2:僅有 created(-500) 此一已知直接活動,
// updated_at -10 完全由他處提及刷新。
issue := src.issues["alterminal/teai"][2]
issue.UpdatedAt = iso(-10)
src.issues["alterminal/teai"][2] = issue
// 情境一:timeline 全為引用事件 → 回退 knownMax(created -500)
// → 停滯 8.3h,超過預設門檻 4h,列入。
src.timeline = map[string][]TimelineEvent{
"alterminal/teai/2": {{Type: "issue_ref", CreatedAt: iso(-10)}},
}
items, err := RunStalled(src, 0, at(0))
if err != nil {
t.Fatalf("RunStalled: %v", err)
}
if len(items) != 1 || items[0].Number != 2 {
t.Fatalf("全引用事件應回退直接活動 → teai#2 停滯 8.3h 列入,得到 %+v", items)
}
if items[0].StalledHours != 8.3 {
t.Fatalf("回退 created(-500) → 停滯應 8.3h,得到 %.1f", items[0].StalledHours)
}
// 情境二:timeline 拉取失敗 → 保守沿用 updated_at(-10) → 0.2h 未達門檻,不列入。
src.timeline = nil
src.timelineErr = map[string]error{"alterminal/teai/2": errors.New("boom")}
items, err = RunStalled(src, 0, at(0))
if err != nil {
t.Fatalf("RunStalled: %v", err)
}
if len(items) != 0 {
t.Fatalf("timeline 失敗應保守沿用 updated_at → 不列入,得到 %+v", items)
}
}
+115 -16
View File
@@ -30,6 +30,11 @@ const (
NudgeCooldownHours = 24.0 NudgeCooldownHours = 24.0
) )
// xrefTimelineTypes 對應 gitea.py 的 XREF_TIMELINE_TYPES:他處留言/issue
// 提及本編號時產生的 timeline 引用事件。這類事件會刷新 updated_at,但不是
// 本 issue 的直接活動,directLastActivity 會予以排除(agents issue #34)。
var xrefTimelineTypes = map[string]bool{"comment_ref": true, "issue_ref": true}
// xrefPattern 對應 gitea.py 的 XREF_PATTERN:#N、repo#N、owner/repo#N。 // xrefPattern 對應 gitea.py 的 XREF_PATTERN:#N、repo#N、owner/repo#N。
// //
// 前面不得是文數字/底線/斜線(避免切進 alterminal/bear#47 的後半段); // 前面不得是文數字/底線/斜線(避免切進 alterminal/bear#47 的後半段);
@@ -149,6 +154,9 @@ type Source interface {
IssueComments(owner, repo string, number int64) ([]Comment, error) IssueComments(owner, repo string, number int64) ([]Comment, error)
// TryGetIssue 寬容版單一 issue 查詢:失敗(含 404)回 (零值, false, nil)。 // TryGetIssue 寬容版單一 issue 查詢:失敗(含 404)回 (零值, false, nil)。
TryGetIssue(owner, repo string, number int64) (Issue, bool, error) TryGetIssue(owner, repo string, number int64) (Issue, bool, error)
// IssueTimeline 回傳 issue 的 timeline 事件(GET /repos/{o}/{r}/issues/{n}/timeline,
// 分頁)。directLastActivity 用來排除跨 issue 引用事件(agents issue #34)。
IssueTimeline(owner, repo string, number int64) ([]TimelineEvent, error)
} }
// iterXrefs 產出文字中的 (prefix, number) 配對(對應 _iter_issue_xrefs)。 // iterXrefs 產出文字中的 (prefix, number) 配對(對應 _iter_issue_xrefs)。
@@ -268,8 +276,11 @@ func childActivity(src Source, org, repo string, parent Issue, comments []Commen
if pcOK && ccOK && !childCreated.After(parentCreated) { if pcOK && ccOK && !childCreated.After(parentCreated) {
continue // 上行引用(父項回指更早或同時的 issue);時間未知則不排除 continue // 上行引用(父項回指更早或同時的 issue);時間未知則不排除
} }
// 子項的直接活動:created_at、state 變更(closed_at)、留言(agents #32)。
// 原始 updated_at 不放入已知活動,另經 directLastActivity 核對後採計
//(與 considerIssue/considerPull 對本 issue 自身的處理同構)。
var ms []time.Time var ms []time.Time
if m, ok := parseMoment(child.UpdatedAt); ok { if m, ok := parseMoment(child.CreatedAt); ok {
ms = append(ms, m) ms = append(ms, m)
} }
if m, ok := parseMoment(child.ClosedAt); ok { if m, ok := parseMoment(child.ClosedAt); ok {
@@ -282,6 +293,14 @@ func childActivity(src Source, org, repo string, parent Issue, comments []Commen
} }
} }
} }
if childUpdated, ok := parseMoment(child.UpdatedAt); ok {
// 子項 updated_at 可能被 comment_ref/issue_ref 引用事件刷新
//(agents #38):走與本 issue 自身相同的 directLastActivity 排除
// 邏輯(同源判定,不漂移);timeline 失敗時保守沿用 updated_at。
if d, ok := directLastActivity(src, t.Owner, t.Repo, t.Number, childUpdated, true, ms); ok {
ms = append(ms, d)
}
}
var last *string var last *string
if len(ms) > 0 { if len(ms) > 0 {
latest := maxTime(ms) latest := maxTime(ms)
@@ -302,6 +321,71 @@ func childActivity(src Source, org, repo string, parent Issue, comments []Commen
return moments, children return moments, children
} }
// TimelineEvent 是 issue timeline 的單一事件(僅取判斷所需欄位;
// 對應 gitea.py _direct_last_activity 讀取的 timeline 物件)。
type TimelineEvent struct {
Type string `json:"type"`
CreatedAt string `json:"created_at"`
}
// directLastActivity 排除跨 issue 引用事件後,本 issue 的最後直接活動時刻
// (對應 gitea.py 的 _direct_last_activity;agents issues #34/#38/#40)。
//
// 他處留言/issue 提及本編號(comment_ref/issue_ref)也會刷新 updated_at,
// 直接採用會虛假刷新停滯時鐘(false negative)並低估 stalled_hours。
// updated_at 不晚於已知直接活動(留言、created_at、#32 納入的子項活動)時,
// updated_at 本身可信,不必多打一次 timeline API;只有 updated_at 晚於全部
// 已知活動時才拉 timeline 核對:排除引用類事件後取最晚事件時刻;若最晚的
// 都是引用事件(本 issue 無直接活動可對應 updated_at),則回退已知直接活動
// 的最晚時刻(agents #40)。timeline 拉取失敗時沿用 updated_at(不中斷掃描、
// 寧可少報不誤報缺失活動)。
func directLastActivity(src Source, org, repo string, number int64, updatedAt time.Time, hasUpdated bool, known []time.Time) (time.Time, bool) {
if !hasUpdated {
return time.Time{}, false
}
var knownMax *time.Time
for i := range known {
if known[i].IsZero() {
continue
}
if knownMax == nil || known[i].After(*knownMax) {
m := known[i]
knownMax = &m
}
}
if knownMax == nil || !updatedAt.After(*knownMax) {
return updatedAt, true
}
timeline, err := src.IssueTimeline(org, repo, number)
if err != nil {
return updatedAt, true
}
var moments []time.Time
for _, e := range timeline {
if xrefTimelineTypes[e.Type] {
continue
}
if m, ok := parseMoment(e.CreatedAt); ok {
moments = append(moments, m)
}
}
if len(moments) == 0 {
// timeline 全為引用事件:updated_at 完全由他處提及刷新,本 issue 沒有
// 可對應的直接活動。回退已知直接活動的最晚時刻,避免把被刷新的
// updated_at 當活動、低估停滯時數(agents #40);連已知活動都沒有時才
// 保守沿用 updated_at(不中斷掃描、寧可少報不誤報缺失活動)。
if knownMax != nil {
return *knownMax, true
}
return updatedAt, true
}
latest := maxTime(moments)
if latest.Before(updatedAt) {
return latest, true
}
return updatedAt, true
}
func maxTime(ts []time.Time) time.Time { func maxTime(ts []time.Time) time.Time {
best := ts[0] best := ts[0]
for _, t := range ts[1:] { for _, t := range ts[1:] {
@@ -382,7 +466,7 @@ func ScanStalled(src Source, username string, threshold float64, now time.Time)
if err != nil { if err != nil {
continue continue
} }
if item, ok := considerPull(pr, comments, username, threshold, now); ok { if item, ok := considerPull(src, org, r.Name, pr, comments, username, threshold, now); ok {
items = append(items, item) items = append(items, item)
} }
} }
@@ -398,19 +482,27 @@ func ScanStalled(src Source, username string, threshold float64, now time.Time)
func considerIssue(src Source, org, repo string, issue Issue, comments []Comment, username string, threshold float64, now time.Time, myOrgs map[string]bool, orgRepos func(string) ([]string, error)) (Item, bool) { func considerIssue(src Source, org, repo string, issue Issue, comments []Comment, username string, threshold float64, now time.Time, myOrgs map[string]bool, orgRepos func(string) ([]string, error)) (Item, bool) {
childMoments, children := childActivity(src, org, repo, issue, comments, myOrgs, orgRepos) childMoments, children := childActivity(src, org, repo, issue, comments, myOrgs, orgRepos)
assignees := AssigneeNames(&issue) assignees := AssigneeNames(&issue)
var moments []time.Time // 已知直接活動:留言、created_at、#32 納入的子項活動。
if m, ok := parseMoment(issue.UpdatedAt); ok { var known []time.Time
moments = append(moments, m)
}
if m, ok := parseMoment(issue.CreatedAt); ok { if m, ok := parseMoment(issue.CreatedAt); ok {
moments = append(moments, m) known = append(known, m)
} }
for _, c := range comments { for _, c := range comments {
if m, ok := parseMoment(c.CreatedAt); ok { if m, ok := parseMoment(c.CreatedAt); ok {
moments = append(moments, m) known = append(known, m)
} }
} }
moments = append(moments, childMoments...) known = append(known, childMoments...)
// 跨 issue 引用(comment_ref/issue_ref)也會刷新 updated_at(agents #34):
// updated_at 晚於全部已知直接活動時,先排除引用事件核對後才採用,
// 避免停滯時鐘被虛假刷新或低估 stalled_hours。
var moments []time.Time
if m, ok := parseMoment(issue.UpdatedAt); ok {
if d, ok2 := directLastActivity(src, org, repo, issue.issueNumber(), m, ok, known); ok2 {
moments = append(moments, d)
}
}
moments = append(moments, known...)
if len(moments) == 0 { if len(moments) == 0 {
return Item{}, false return Item{}, false
} }
@@ -455,21 +547,28 @@ func considerIssue(src Source, org, repo string, issue Issue, comments []Comment
} }
// considerPull 對單一 PR 套用停滯判定(對應 _consider 的 pull 分支)。 // considerPull 對單一 PR 套用停滯判定(對應 _consider 的 pull 分支)。
func considerPull(pr PullRequest, comments []Comment, username string, threshold float64, now time.Time) (Item, bool) { func considerPull(src Source, org, repo string, pr PullRequest, comments []Comment, username string, threshold float64, now time.Time) (Item, bool) {
reviewers := ReviewerNames(&pr) reviewers := ReviewerNames(&pr)
author := pr.Author() author := pr.Author()
var moments []time.Time // 已知直接活動:留言、created_at。
if m, ok := parseMoment(pr.UpdatedAt); ok { var known []time.Time
moments = append(moments, m)
}
if m, ok := parseMoment(pr.CreatedAt); ok { if m, ok := parseMoment(pr.CreatedAt); ok {
moments = append(moments, m) known = append(known, m)
} }
for _, c := range comments { for _, c := range comments {
if m, ok := parseMoment(c.CreatedAt); ok { if m, ok := parseMoment(c.CreatedAt); ok {
moments = append(moments, m) known = append(known, m)
} }
} }
// 跨 issue 引用也會刷新 PR 的 updated_at(agents #34):與 issue 同一道
// directLastActivity 排除邏輯(同源判定,不漂移)。
var moments []time.Time
if m, ok := parseMoment(pr.UpdatedAt); ok {
if d, ok2 := directLastActivity(src, org, repo, pr.Number, m, ok, known); ok2 {
moments = append(moments, d)
}
}
moments = append(moments, known...)
if len(moments) == 0 { if len(moments) == 0 {
return Item{}, false return Item{}, false
} }
+19
View File
@@ -9,6 +9,7 @@ import (
"encoding/json" "encoding/json"
"errors" "errors"
"fmt" "fmt"
"sort"
"strings" "strings"
"testing" "testing"
"time" "time"
@@ -28,6 +29,8 @@ type fakeSource struct {
pulls map[string][]PullRequest pulls map[string][]PullRequest
// comments[owner/repo/number] // comments[owner/repo/number]
comments map[string][]Comment comments map[string][]Comment
// timelines[owner/repo/number]:issue timeline 事件(nil → 空 timeline)。
timelines map[string][]TimelineEvent
} }
func (f *fakeSource) MyOrganizations() ([]string, error) { return f.orgs, nil } func (f *fakeSource) MyOrganizations() ([]string, error) { return f.orgs, nil }
@@ -41,6 +44,8 @@ func (f *fakeSource) OpenIssues(owner, repo string) ([]Issue, error) {
for _, i := range f.issues[owner+"/"+repo] { for _, i := range f.issues[owner+"/"+repo] {
out = append(out, i) out = append(out, i)
} }
// 對齊真實 API:issues 依 id(=number)遞增回傳,消除 map 迭代隨機性。
sort.Slice(out, func(a, b int) bool { return out[a].Number < out[b].Number })
return out, nil return out, nil
} }
@@ -52,6 +57,10 @@ func (f *fakeSource) IssueComments(owner, repo string, number int64) ([]Comment,
return f.comments[fmt.Sprintf("%s/%s/%d", owner, repo, number)], nil return f.comments[fmt.Sprintf("%s/%s/%d", owner, repo, number)], nil
} }
func (f *fakeSource) IssueTimeline(owner, repo string, number int64) ([]TimelineEvent, error) {
return f.timelines[fmt.Sprintf("%s/%s/%d", owner, repo, number)], nil
}
func (f *fakeSource) TryGetIssue(owner, repo string, number int64) (Issue, bool, error) { func (f *fakeSource) TryGetIssue(owner, repo string, number int64) (Issue, bool, error) {
i, ok := f.issues[owner+"/"+repo][number] i, ok := f.issues[owner+"/"+repo][number]
if !ok { if !ok {
@@ -314,6 +323,13 @@ func TestScanStalledParentTrackingNotChild(t *testing.T) {
}, },
}, },
} }
// timeline:#47 的 updated_at 對應直接事件(assignees)、#39 對應 label
//(agents #34 後 updated_at 需經 timeline 核對才採計;直接事件可對應 → 採用)。
// 必須在 ScanStalled 之前設定——掃描當下讀不到的事後修改無效。
src.timelines = map[string][]TimelineEvent{
"alterminal/teai/47": {{Type: "assignees", CreatedAt: iso(-600)}},
"alterminal/teai/39": {{Type: "label", CreatedAt: iso(-60)}},
}
got, err := ScanStalled(src, "admin", 4.0, now) got, err := ScanStalled(src, "admin", 4.0, now)
if err != nil { if err != nil {
t.Fatalf("ScanStalled: %v", err) t.Fatalf("ScanStalled: %v", err)
@@ -515,6 +531,9 @@ func (e errSource) IssueComments(string, string, int64) ([]Comment, error) {
func (e errSource) TryGetIssue(string, string, int64) (Issue, bool, error) { func (e errSource) TryGetIssue(string, string, int64) (Issue, bool, error) {
return Issue{}, false, errors.New("boom") return Issue{}, false, errors.New("boom")
} }
func (e errSource) IssueTimeline(string, string, int64) ([]TimelineEvent, error) {
return nil, errors.New("boom")
}
// TestRound1 round1 十進位舍入到一位小數(與 Python round(x,1) 半偶數一致)。 // TestRound1 round1 十進位舍入到一位小數(與 Python round(x,1) 半偶數一致)。
func TestRound1(t *testing.T) { func TestRound1(t *testing.T) {