Compare commits
9
Commits
fd3b8cbd6b
...
v0.1.0
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
36a50b95ed | ||
|
|
9e699f3b4e | ||
|
|
d689107eea | ||
|
|
027ed1ade9 | ||
|
|
e4212b9c90 | ||
|
|
a2baf55fce | ||
|
|
1f6806ff99 | ||
|
|
87d00ae440 | ||
|
|
744e7ad809 |
@@ -86,6 +86,8 @@ teai pulls comment --repo <owner>/<repo> --body … --yes <number>
|
||||
# labels/milestones/releases/repos
|
||||
teai labels list --repo <owner>/<repo>
|
||||
teai labels create --repo <owner>/<repo> --name … [--color #RRGGBB] [--description …] --yes
|
||||
teai milestones # 跨倉庫 open 里程碑總覽(gitea.py milestones 對應;期限近者在前)
|
||||
teai milestones --repo <owner>/<repo> # 同 milestones list(單倉庫,維持既有語義)
|
||||
teai milestones list --repo <owner>/<repo> [--state open|closed|all]
|
||||
teai milestones create --repo <owner>/<repo> --title … [--description …] [--due RFC3339] --yes
|
||||
teai releases list --repo <owner>/<repo>
|
||||
@@ -207,6 +209,47 @@ PR 改帶 `author` 與 `reviewers` 欄位。`reason` 取值:
|
||||
- issue:`no-assignee`、`assignee-idle`、`no-commenter`、`waiting-outside`、`parent-tracking`
|
||||
- PR:`no-reviewer`、`author-idle`、`reviewer-idle`、`no-commenter`
|
||||
|
||||
### `teai milestones` — 跨倉庫里程碑總覽
|
||||
|
||||
```sh
|
||||
teai milestones # 各倉庫 open 里程碑概況(跨所屬組織;期限近者在前)
|
||||
teai milestones --output table
|
||||
```
|
||||
|
||||
管理者巡邏用(`gitea.py milestones` 對應,agents AGENTS.md 10.1)。帶 `--repo` 時
|
||||
維持現行單倉庫 `list` 語義(`teai milestones --repo a/b` = `teai milestones list --repo a/b`)。
|
||||
|
||||
每筆欄位(鍵集鍵序與 `gitea.py` 全等,實測位元組一致):
|
||||
|
||||
```json
|
||||
{
|
||||
"repo": "alterminal/test",
|
||||
"id": 6,
|
||||
"title": "xcheck31-ms-overdue",
|
||||
"url": "https://gitea.alterminal.com/alterminal/test/milestone/6",
|
||||
"open_issues": 2,
|
||||
"closed_issues": 0,
|
||||
"due_on": "2026-09-08T08:00:00+08:00",
|
||||
"due_hours": 61.3,
|
||||
"overdue": true,
|
||||
"unassigned": [
|
||||
{
|
||||
"type": "issue",
|
||||
"number": 14,
|
||||
"title": "…",
|
||||
"url": "https://gitea.alterminal.com/alterminal/test/issues/14"
|
||||
}
|
||||
],
|
||||
"updated_at": "2026-09-10T21:17:37+08:00"
|
||||
}
|
||||
```
|
||||
|
||||
- **排序**:`due_on` 近者在前;無期限者最後(`gitea.py` 的 `(due_on is None, due_on)` 鍵)。
|
||||
- **`overdue`/`due_hours`**:期限已過為 `true`(`due_hours` 正數);無期限 → `null`。
|
||||
- **`unassigned`**:該里程碑 open 條目(issue 與 PR)中無 assignee 者的摘要;PR 條目另帶 `author`。
|
||||
- **`updated_at`**:里程碑本身與其 open 條目 `updated_at` 的最大值(判斷活躍度用)。
|
||||
- 空輸出 → `[]`(`gitea.py` 無輸出;依 #26 慣例差異)。
|
||||
|
||||
### `teai members [--has-work]`
|
||||
|
||||
```sh
|
||||
@@ -256,7 +299,7 @@ teai whoami # 目前帳號(讀 tea 組態)
|
||||
|
||||
| 碼 | 意義 |
|
||||
| --- | --- |
|
||||
| 0 | 成功(含「沒有工作」→ 輸出 `null`/`[]`) |
|
||||
| 0 | 成功(含「沒有結果」→ 清單類命令輸出 `[]`、`next` 輸出 `null`;#37 判決) |
|
||||
| 2 | 用法錯誤(未知命令/參數) |
|
||||
| 3 | API 錯誤(連線失敗、401、403、5xx) |
|
||||
|
||||
@@ -266,6 +309,7 @@ teai whoami # 目前帳號(讀 tea 組態)
|
||||
| --- | --- | --- |
|
||||
| `next` | `teai next` | 相同:author-PR → reviewer-PR → issue,最久未更新優先 |
|
||||
| `stalled [--hours N]` | `teai stalled [--hours N]` | 相同,含 xref 父子追蹤與冷卻 |
|
||||
| `milestones` | `teai milestones` | 相同:跨倉庫 open 里程碑總覽,期限近者在前(#31) |
|
||||
| `members [--has-work]` | `teai members [--has-work]` | 相同 |
|
||||
| `pulls`/`pulls --mine`/`pulls --reviewer` | `teai pulls [--mine\|--reviewer]` | 相同 |
|
||||
| `mine` | `teai mine` | 相同 |
|
||||
@@ -274,14 +318,18 @@ teai whoami # 目前帳號(讀 tea 組態)
|
||||
已知輸出差異(刻意保留,機器可讀優先):
|
||||
|
||||
- **空清單**:`gitea.py` 的 `_dump` 對空清單**不輸出任何內容**;teai 的清單類命令
|
||||
(`mine`/`pulls`)空清單輸出 `[]`。對 JSON 消費者來說 `[]` 比「無輸出」更明確,
|
||||
交叉驗證時以此差異為準。`next` 兩者語義相同(無工作 → `null`/「沒有未完成的工作」)。
|
||||
(`mine`/`pulls`/`stalled`/`milestones` 總覽)空清單一律輸出 `[]`(exit 0)。對 JSON
|
||||
消費者來說 `[]` 比「無輸出」更明確(可區分「沒有結果」與「查詢失敗無輸出」),交叉驗證時
|
||||
以此差異為準。`next` 兩者語義相同:無工作時 teai 輸出 `null`(exit 0)、`gitea.py` 印
|
||||
「沒有未完成的工作」。**判決 #37:維持 teai 現行 JSON 一致性(方向 2)**——消費端
|
||||
(agents 倉庫巡邏提示與觸發腳本)應以「輸出 `[]`/`null` 且 exit 0」為「沒有」判據,
|
||||
不得以「無輸出」判斷;`members [--has-work]` 維持逐行帳號、空時無輸出(兩者一致,不受影響)。
|
||||
- **清單欄位集(`mine`/`pulls`)**:`gitea.py` 直接傾倒完整 Gitea API 物件
|
||||
(`_dump` 的副作用,欄位集隨 Gitea 版本浮動);teai 輸出策展摘要欄位
|
||||
(`mine`:repo/number/title/url;`pulls`:number/title/state/author/
|
||||
head/base/updated_at…依命令定義)。交叉驗證比對**項目集合**(列出哪些
|
||||
issue/PR)與判定語義,不逐欄位比對;`next`/`stalled` 兩者為策展欄位且
|
||||
鍵集鍵序全等,可逐欄位比對。判定 #26(維持摘要、文件化差異)。
|
||||
issue/PR)與判定語義,不逐欄位比對;`next`/`stalled`/`milestones` 總覽
|
||||
兩者為策展欄位且鍵集鍵序全等,可逐欄位比對(#31 實測位元組一致)。判定 #26(維持摘要、文件化差異)。
|
||||
- **全域選項位置**:teai 的全域選項(`--output` 等)可出現在命令之前或之後,
|
||||
且可與命令旗標交錯(`teai members --has-work --output table`);
|
||||
gitea.py 的旗標剖析較寬鬆,兩者命令列介面以此行為對齊。
|
||||
|
||||
@@ -165,6 +165,14 @@ func (s *apiSource) IssueComments(owner, repo string, number int64) ([]workflow.
|
||||
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) {
|
||||
var issue workflow.Issue
|
||||
body, code, err := s.get(fmt.Sprintf("repos/%s/%s/issues/%d", owner, repo, number), nil)
|
||||
|
||||
@@ -26,7 +26,7 @@ func init() {
|
||||
register(&command{name: "issues", usage: "issues 管理(list/view/create/close/comment)", run: runIssues})
|
||||
register(&command{name: "pulls", usage: "PR 管理(list/view/create/merge/comment;無子命令=工作流清單)", run: runPullsDaily})
|
||||
register(&command{name: "labels", usage: "標籤管理(list/create)", run: runLabels})
|
||||
register(&command{name: "milestones", usage: "里程碑管理(list/create)", run: runMilestones})
|
||||
register(&command{name: "milestones", usage: "里程碑(跨倉庫總覽;list/create 管理單倉庫)", run: runMilestones})
|
||||
register(&command{name: "releases", usage: "發佈清單(list)", run: runReleases})
|
||||
register(&command{name: "repos", usage: "倉庫查詢(list)", run: runRepos})
|
||||
register(&command{name: "api", usage: "任意 API 呼叫(--method/--data;寫入動詞需 --yes)", run: runAPIDirect})
|
||||
@@ -650,10 +650,12 @@ func runLabelsCreate(env *Env, args []string) error {
|
||||
|
||||
// ---- milestones ----
|
||||
|
||||
// runMilestones:teai milestones list|create …
|
||||
// runMilestones:teai milestones [list|create] …;不帶子命令時輸出
|
||||
// 跨倉庫里程碑總覽(#31,對應 gitea.py milestones)。帶 --repo 直接
|
||||
// 跟在 milestones 之後時維持現行單倉庫 list 語義。
|
||||
func runMilestones(env *Env, args []string) error {
|
||||
if len(args) == 0 {
|
||||
return &ErrUsage{Msg: "milestones 需要子命令:list | create"}
|
||||
return runMilestonesOverview(env)
|
||||
}
|
||||
sub, rest := args[0], args[1:]
|
||||
switch sub {
|
||||
@@ -662,7 +664,32 @@ func runMilestones(env *Env, args []string) error {
|
||||
case "create":
|
||||
return runMilestonesCreate(env, rest)
|
||||
default:
|
||||
return &ErrUsage{Msg: fmt.Sprintf("milestones 未知子命令 %q(可用:list | create)", sub)}
|
||||
if !strings.HasPrefix(sub, "-") {
|
||||
return &ErrUsage{Msg: fmt.Sprintf("milestones 未知子命令 %q(可用:list | create;或不帶參數輸出跨倉庫總覽)", sub)}
|
||||
}
|
||||
// milestones 之後直接跟旗標(非子命令):帶 --repo → 整串轉發,
|
||||
// 維持現行單倉庫 list 語義(--state 等旗標一併生效);否則為
|
||||
// 跨倉庫總覽(總覽不接受任何命令旗標,空 FlagSet 讓未知旗標
|
||||
// 報用法錯誤)。
|
||||
hasRepo := false
|
||||
for _, a := range args {
|
||||
if a == "--repo" || strings.HasPrefix(a, "--repo=") {
|
||||
hasRepo = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if hasRepo {
|
||||
return runMilestonesList(env, args)
|
||||
}
|
||||
fs := flag.NewFlagSet("teai milestones", flag.ContinueOnError)
|
||||
fs.SetOutput(env.Err)
|
||||
if err := parseFlags(fs, args); err != nil {
|
||||
return err
|
||||
}
|
||||
if fs.NArg() != 0 {
|
||||
return &ErrUsage{Msg: "milestones 不接受位置參數(子命令:list | create)"}
|
||||
}
|
||||
return runMilestonesOverview(env)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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、
|
||||
// POST 未帶 --yes 被擋。
|
||||
func TestAPIDirectPassthrough(t *testing.T) {
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
// milestones_commands.go — 跨倉庫里程碑總覽命令的 CLI 接線(#31):
|
||||
// teai milestones(不帶 --repo)。
|
||||
//
|
||||
// 核心邏輯在 internal/workflow(MilestoneOverview),本檔只做旗標
|
||||
// 剖析、資料源接線與輸出格式化(與 stalled_commands.go 同模式)。
|
||||
// 輸出與 gitea.py milestones 位元組相容(MilestoneEntry 自訂
|
||||
// MarshalJSON;縮排 2、停用 HTML 轉義、空清單輸出 [],見 #26 慣例)。
|
||||
package cli
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"gitea.alterminal.com/alterminal/teai/internal/gitea"
|
||||
"gitea.alterminal.com/alterminal/teai/internal/workflow"
|
||||
)
|
||||
|
||||
// newMilestoneSourceFunc 建立總覽的資料源;宣告為變數讓接線層測試
|
||||
// 可注入假資料源(與 newStalledSourceFunc 同模式)。
|
||||
var newMilestoneSourceFunc = newMilestoneSource
|
||||
|
||||
// newMilestoneSource 依全域選項建立 workflow.MilestoneSource(API 實作)。
|
||||
func newMilestoneSource(env *Env) (workflow.MilestoneSource, error) {
|
||||
token, _, err := gitea.ResolveToken(gitea.AuthOptions{
|
||||
FlagToken: env.Globals.Token,
|
||||
SiteURL: env.Globals.URL,
|
||||
ConfigPath: env.Globals.ConfigPath,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
client, err := gitea.New(env.Globals.URL, token, env.Globals.Timeout)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &workflow.APIClient{Client: client}, nil
|
||||
}
|
||||
|
||||
// milestonesNowFunc 回傳總覽的基準時刻;宣告為變數讓測試可固定時刻。
|
||||
var milestonesNowFunc = time.Now
|
||||
|
||||
// milestoneEntryRow 把 MilestoneEntry 轉成 table 列(unassigned 僅 JSON
|
||||
// 模式輸出完整摘要;table 給人工抽查用,取計數)。
|
||||
func milestoneEntryRow(e workflow.MilestoneEntry) gitea.Values {
|
||||
dueOn := ""
|
||||
if e.DueOn != nil {
|
||||
dueOn = *e.DueOn
|
||||
}
|
||||
dueHours := ""
|
||||
if e.DueHours != nil {
|
||||
dueHours = fmt.Sprintf("%.1f", *e.DueHours)
|
||||
}
|
||||
updatedAt := ""
|
||||
if e.UpdatedAt != nil {
|
||||
updatedAt = *e.UpdatedAt
|
||||
}
|
||||
id := ""
|
||||
if e.ID != nil {
|
||||
id = fmt.Sprintf("%d", *e.ID)
|
||||
}
|
||||
return gitea.Values{
|
||||
e.Repo, id, e.Title, e.URL,
|
||||
e.OpenIssues, e.ClosedIssues, dueOn, dueHours,
|
||||
e.Overdue, len(e.Unassigned), updatedAt,
|
||||
}
|
||||
}
|
||||
|
||||
// runMilestonesOverview:teai milestones(跨倉庫總覽)。
|
||||
// JSON 輸出與 gitea.py milestones 位元組相容;空清單輸出 [](#26 慣例:
|
||||
// gitea.py 對空清單不輸出,teai 輸出 [] 供 JSON 消費者明確判斷)。
|
||||
func runMilestonesOverview(env *Env) error {
|
||||
src, err := newMilestoneSourceFunc(env)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
entries, err := workflow.MilestoneOverview(src, env.Globals.URL, milestonesNowFunc())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
p := printer(env)
|
||||
if p.Format == gitea.FormatTable {
|
||||
rows := make([]gitea.Values, 0, len(entries))
|
||||
for i := range entries {
|
||||
rows = append(rows, milestoneEntryRow(entries[i]))
|
||||
}
|
||||
return p.PrintList([]gitea.Field{
|
||||
{Name: "repo"}, {Name: "id"}, {Name: "title"}, {Name: "url"},
|
||||
{Name: "open_issues"}, {Name: "closed_issues"}, {Name: "due_on"},
|
||||
{Name: "due_hours"}, {Name: "overdue"}, {Name: "unassigned"}, {Name: "updated_at"},
|
||||
}, rows)
|
||||
}
|
||||
if len(entries) == 0 {
|
||||
_, err := fmt.Fprintln(env.Out, "[]")
|
||||
return err
|
||||
}
|
||||
return printJSON(env.Out, entries)
|
||||
}
|
||||
@@ -0,0 +1,188 @@
|
||||
// milestones_commands_test.go — 跨倉庫里程碑總覽的 CLI 接線層測試(#31):
|
||||
// 注入假 MilestoneSource,驗證 Run→dispatch→輸出完整路徑,不走網路
|
||||
// (與 stalled_commands_test.go 同模式)。
|
||||
package cli
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"gitea.alterminal.com/alterminal/teai/internal/workflow"
|
||||
)
|
||||
|
||||
// stubMilestoneSource 以記憶體資料實作 workflow.MilestoneSource。
|
||||
type stubMilestoneSource struct {
|
||||
orgs []string
|
||||
repos map[string][]workflow.Repo
|
||||
milestones map[string][]workflow.Milestone
|
||||
openIssues map[string][]workflow.Issue // key: owner/repo?milestone=<title>
|
||||
}
|
||||
|
||||
func (s *stubMilestoneSource) MyOrganizations() ([]string, error) { return s.orgs, nil }
|
||||
func (s *stubMilestoneSource) OrganizationRepositories(org string) ([]workflow.Repo, error) {
|
||||
return s.repos[org], nil
|
||||
}
|
||||
func (s *stubMilestoneSource) OpenMilestones(owner, repo string) ([]workflow.Milestone, error) {
|
||||
return s.milestones[owner+"/"+repo], nil
|
||||
}
|
||||
func (s *stubMilestoneSource) MilestoneOpenIssues(owner, repo, title string) ([]workflow.Issue, error) {
|
||||
return s.openIssues[owner+"/"+repo+"?milestone="+title], nil
|
||||
}
|
||||
|
||||
// newStubMilestoneEnv 注入假資料源並固定時刻。
|
||||
func newStubMilestoneEnv(t *testing.T, src *stubMilestoneSource, frozen time.Time) {
|
||||
t.Helper()
|
||||
origSrc, origNow := newMilestoneSourceFunc, milestonesNowFunc
|
||||
newMilestoneSourceFunc = func(env *Env) (workflow.MilestoneSource, error) { return src, nil }
|
||||
milestonesNowFunc = func() time.Time { return frozen }
|
||||
t.Cleanup(func() {
|
||||
newMilestoneSourceFunc, milestonesNowFunc = origSrc, origNow
|
||||
})
|
||||
}
|
||||
|
||||
// stubPullIssue 以 JSON 建構帶 pull_request 標記的條目(pullMarker 未匯出,
|
||||
// 測試從套件外以 API 回應的形狀建構,走 Issue.UnmarshalJSON 同一路徑)。
|
||||
func stubPullIssue(t *testing.T) workflow.Issue {
|
||||
t.Helper()
|
||||
var issue workflow.Issue
|
||||
err := json.Unmarshal([]byte(`{
|
||||
"number": 32, "title": "文件", "state": "open",
|
||||
"updated_at": "2026-09-08T00:00:00Z",
|
||||
"html_url": "https://gitea.alterminal.com/alterminal/agents/pulls/32",
|
||||
"user": {"username": "alex"},
|
||||
"pull_request": {}
|
||||
}`), &issue)
|
||||
if err != nil {
|
||||
t.Fatalf("建構 stub PR 條目失敗:%v", err)
|
||||
}
|
||||
return issue
|
||||
}
|
||||
|
||||
// idPtr/msPtr 是測試用指標 helper(workflow 套件內同名函式未匯出)。
|
||||
func idPtr(i int64) *int64 { return &i }
|
||||
func msPtr(s string) *string { return &s }
|
||||
|
||||
// newStubMilestoneData 建構總覽情境:兩倉庫各一里程碑、一個未分派 PR。
|
||||
func newStubMilestoneData(t *testing.T) *stubMilestoneSource {
|
||||
due := "2026-09-09T00:00:00Z"
|
||||
return &stubMilestoneSource{
|
||||
orgs: []string{"alterminal"},
|
||||
repos: map[string][]workflow.Repo{"alterminal": {
|
||||
{Name: "agents"}, {Name: "teai"},
|
||||
}},
|
||||
milestones: map[string][]workflow.Milestone{
|
||||
"alterminal/agents": {
|
||||
{ID: idPtr(7), Title: "MVP", State: "open",
|
||||
DueOn: &due, UpdatedAt: "2026-09-01T00:00:00Z",
|
||||
OpenIssues: 1, ClosedIssues: 0},
|
||||
},
|
||||
"alterminal/teai": {
|
||||
{ID: idPtr(3), Title: "CLI", State: "open",
|
||||
DueOn: msPtr("2026-09-12T00:00:00Z"), UpdatedAt: "2026-09-05T00:00:00Z",
|
||||
OpenIssues: 1, ClosedIssues: 2},
|
||||
},
|
||||
},
|
||||
openIssues: map[string][]workflow.Issue{
|
||||
"alterminal/agents?milestone=MVP": {stubPullIssue(t)},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// TestWiringMilestonesOverview 驗證 teai milestones 輸出跨倉庫總覽
|
||||
// (JSON 縮排 2、鍵序與欄位齊 gitea.py)。
|
||||
func TestWiringMilestonesOverview(t *testing.T) {
|
||||
newStubMilestoneEnv(t, newStubMilestoneData(t), time.Date(2026, 9, 10, 8, 0, 0, 0, time.UTC))
|
||||
stdout, _, code := run("milestones")
|
||||
if code != 0 {
|
||||
t.Fatalf("milestones 應回 0,得到 %d(stdout=%q)", code, stdout)
|
||||
}
|
||||
for _, want := range []string{
|
||||
`"repo": "alterminal/agents"`,
|
||||
`"title": "MVP"`,
|
||||
`"overdue": true`,
|
||||
`"type": "pull"`,
|
||||
`"author": "alex"`,
|
||||
} {
|
||||
if !strings.Contains(stdout, want) {
|
||||
t.Fatalf("milestones 輸出應含 %q,得到:\n%s", want, stdout)
|
||||
}
|
||||
}
|
||||
// 排序:agents MVP(09-09)在 teai CLI(09-12)前。
|
||||
if strings.Index(stdout, `"title": "MVP"`) > strings.Index(stdout, `"title": "CLI"`) {
|
||||
t.Fatalf("期限近者應在前:\n%s", stdout)
|
||||
}
|
||||
}
|
||||
|
||||
// TestWiringMilestonesEmpty 驗證無里程碑 → [](#26 慣例)。
|
||||
func TestWiringMilestonesEmpty(t *testing.T) {
|
||||
newStubMilestoneEnv(t, &stubMilestoneSource{
|
||||
orgs: []string{"alterminal"},
|
||||
repos: map[string][]workflow.Repo{"alterminal": {{Name: "agents"}}},
|
||||
milestones: map[string][]workflow.Milestone{},
|
||||
openIssues: map[string][]workflow.Issue{},
|
||||
}, time.Date(2026, 9, 10, 8, 0, 0, 0, time.UTC))
|
||||
stdout, _, code := run("milestones")
|
||||
if code != 0 {
|
||||
t.Fatalf("milestones 空清單應回 0,得到 %d", code)
|
||||
}
|
||||
if strings.TrimSpace(stdout) != "[]" {
|
||||
t.Fatalf("無里程碑應輸出 [],得到 %q", stdout)
|
||||
}
|
||||
}
|
||||
|
||||
// TestWiringMilestonesTable 驗證 table 輸出(人工抽查用)。
|
||||
func TestWiringMilestonesTable(t *testing.T) {
|
||||
newStubMilestoneEnv(t, newStubMilestoneData(t), time.Date(2026, 9, 10, 8, 0, 0, 0, time.UTC))
|
||||
stdout, _, code := run("milestones", "--output", "table")
|
||||
if code != 0 {
|
||||
t.Fatalf("milestones --output table 應回 0,得到 %d", code)
|
||||
}
|
||||
for _, want := range []string{"repo", "overdue", "MVP", "alterminal/agents"} {
|
||||
if !strings.Contains(stdout, want) {
|
||||
t.Fatalf("table 輸出應含 %q,得到:\n%s", want, stdout)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestWiringMilestonesRepoFlagCompat 驗證 teai milestones --repo a/b
|
||||
// 維持現行單倉庫 list 語義(#31:帶 --repo 時不變)。
|
||||
func TestWiringMilestonesRepoFlagCompat(t *testing.T) {
|
||||
var gotPath, gotQuery string
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
gotPath, gotQuery = r.URL.Path, r.URL.RawQuery
|
||||
w.Write([]byte(`[{"title":"v1","state":"open","description":"","due_on":""}]`))
|
||||
}))
|
||||
t.Cleanup(srv.Close)
|
||||
stdout, _, code := run("--url", srv.URL, "milestones", "--repo", "a/b")
|
||||
if code != 0 {
|
||||
t.Fatalf("milestones --repo a/b 應回 0,得到 %d", code)
|
||||
}
|
||||
if gotPath != "/api/v1/repos/a/b/milestones" {
|
||||
t.Fatalf("應呼叫 /repos/a/b/milestones,得到 %s", gotPath)
|
||||
}
|
||||
if !strings.Contains(gotQuery, "state=open") {
|
||||
t.Fatalf("查詢應含 state=open,得到 %q", gotQuery)
|
||||
}
|
||||
if !strings.Contains(stdout, `"title":"v1"`) {
|
||||
t.Fatalf("輸出應含 title v1,得到:%s", stdout)
|
||||
}
|
||||
}
|
||||
|
||||
// TestWiringMilestonesUsage 驗證未知子命令與位置參數 → exit 2。
|
||||
func TestWiringMilestonesUsage(t *testing.T) {
|
||||
newStubMilestoneEnv(t, newStubMilestoneData(t), time.Date(2026, 9, 10, 8, 0, 0, 0, time.UTC))
|
||||
if _, _, code := run("milestones", "bogus"); code != int(ExitUsage) {
|
||||
t.Fatalf("milestones bogus 應回 ExitUsage,得到 %d", code)
|
||||
}
|
||||
if _, _, code := run("milestones", "extra", "arg"); code != int(ExitUsage) {
|
||||
t.Fatalf("milestones 位置參數應回 ExitUsage,得到 %d", code)
|
||||
}
|
||||
// milestones list 仍照舊要求 --repo。
|
||||
if _, _, code := run("milestones", "list"); code != int(ExitUsage) {
|
||||
t.Fatalf("milestones list 缺 --repo 應回 ExitUsage,得到 %d", code)
|
||||
}
|
||||
}
|
||||
@@ -46,6 +46,9 @@ func (s *stubStalledSource) TryGetIssue(owner, repo string, number int64) (workf
|
||||
i, ok := s.issues[owner+"/"+repo][number]
|
||||
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) {
|
||||
if s.getErr != nil {
|
||||
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 覆寫門檻與非正數被攔。
|
||||
func TestWiringStalledHoursFlag(t *testing.T) {
|
||||
freeze := time.Date(2026, 9, 10, 8, 0, 0, 0, time.UTC)
|
||||
@@ -157,7 +178,7 @@ func TestWiringXrefs(t *testing.T) {
|
||||
src := newStubStalledData()
|
||||
src.issues["alterminal/agents"][1] = workflow.Issue{
|
||||
Number: 1, Title: "父項", State: "open",
|
||||
Body: "子項:agents#2",
|
||||
Body: "子項:agents#2",
|
||||
Repository: &workflow.Repository{FullName: "alterminal/agents"},
|
||||
}
|
||||
src.issues["alterminal/agents"][2] = workflow.Issue{
|
||||
@@ -185,7 +206,7 @@ func TestWiringXrefsEmpty(t *testing.T) {
|
||||
src := newStubStalledData()
|
||||
src.issues["alterminal/agents"][1] = workflow.Issue{
|
||||
Number: 1, Title: "無引用", State: "open",
|
||||
Body: "沒有任何引用",
|
||||
Body: "沒有任何引用",
|
||||
Repository: &workflow.Repository{FullName: "alterminal/agents"},
|
||||
}
|
||||
newStubStalledEnv(t, src, time.Date(2026, 9, 10, 8, 0, 0, 0, time.UTC))
|
||||
|
||||
@@ -170,10 +170,10 @@ func (o *Ops) ListIssues(ctx context.Context, owner, repo, state string) ([]Issu
|
||||
if state == "" {
|
||||
state = "open"
|
||||
}
|
||||
// state 一律明確傳給 API:issues/milestones 端點省略 state 時預設
|
||||
// open(#33),closed 項目會漏列;all 也不能省略。
|
||||
extra := url.Values{}
|
||||
if state != "all" {
|
||||
extra.Set("state", state)
|
||||
}
|
||||
extra.Set("state", state)
|
||||
// type=issues:排除 PR(PR 在此端點帶 pull_request 欄位)。
|
||||
extra.Set("type", "issues")
|
||||
var issues []Issue
|
||||
@@ -246,10 +246,10 @@ func (o *Ops) ListPulls(ctx context.Context, owner, repo, state string) ([]Pull,
|
||||
if state == "" {
|
||||
state = "open"
|
||||
}
|
||||
// state 一律明確傳給 API:pulls 端點省略 state 時雖回全部,仍明確
|
||||
// 帶上,避免依賴端點預設值(#33)。
|
||||
extra := url.Values{}
|
||||
if state != "all" {
|
||||
extra.Set("state", state)
|
||||
}
|
||||
extra.Set("state", state)
|
||||
var pulls []Pull
|
||||
if err := o.Client.ListAll(ctx, repoPath(owner, repo)+"/pulls", gitea.ListOptions{Extra: extra}, &pulls); err != nil {
|
||||
return nil, err
|
||||
@@ -320,10 +320,10 @@ func (o *Ops) ListMilestones(ctx context.Context, owner, repo, state string) ([]
|
||||
if state == "" {
|
||||
state = "open"
|
||||
}
|
||||
// state 一律明確傳給 API:milestones 端點省略 state 時預設 open
|
||||
// (#33),closed 項目會漏列。
|
||||
extra := url.Values{}
|
||||
if state != "all" {
|
||||
extra.Set("state", state)
|
||||
}
|
||||
extra.Set("state", state)
|
||||
var ms []Milestone
|
||||
if err := o.Client.ListAll(ctx, repoPath(owner, repo)+"/milestones", gitea.ListOptions{Extra: extra}, &ms); err != nil {
|
||||
return nil, err
|
||||
|
||||
@@ -150,6 +150,19 @@ func (a *APIClient) TryGetIssue(owner, repo string, number int64) (Issue, bool,
|
||||
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 面向)。
|
||||
func (a *APIClient) MyOrganizations() ([]string, error) { return a.ListOrgs() }
|
||||
|
||||
@@ -173,5 +186,39 @@ func (a *APIClient) IssueComments(owner, repo string, number int64) ([]Comment,
|
||||
return a.ListComments(owner, repo, number)
|
||||
}
|
||||
|
||||
// 編譯期確認 APIClient 同時實作 Client 與 StalledSource。
|
||||
// ── MilestoneSource 面向(#31 跨倉庫里程碑總覽)────────────────────────
|
||||
// APIClient 在 StalledSource 之外另實作 MilestoneSource,讓 milestones
|
||||
// 總覽命令與既有命令共用同一個 HTTP 用戶端;查詢參數對照 gitea.py 的
|
||||
// list_open_milestones_for_repository/_milestone_open_issues。
|
||||
|
||||
// OpenMilestones 回傳倉庫的 open 里程碑(GET /repos/{o}/{r}/milestones?state=open)。
|
||||
func (a *APIClient) OpenMilestones(owner, repo string) ([]Milestone, error) {
|
||||
var ms []Milestone
|
||||
path := "/repos/" + url.PathEscape(owner) + "/" + url.PathEscape(repo) + "/milestones"
|
||||
opts := gitea.ListOptions{Extra: url.Values{"state": {"open"}}}
|
||||
if err := a.Client.ListAll(context.Background(), path, opts, &ms); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return ms, nil
|
||||
}
|
||||
|
||||
// MilestoneOpenIssues 回傳掛在指定里程碑(依名稱過濾,Gitea 以
|
||||
// milestones=<title> 查詢)的 open 條目。刻意**不**帶 type=issues——
|
||||
// PR 亦屬里程碑條目,保留兩者供覆蓋檢查(同 gitea.py
|
||||
// _milestone_open_issues;PR 帶 pull_request 標記由 workflow 判別)。
|
||||
func (a *APIClient) MilestoneOpenIssues(owner, repo, milestoneTitle string) ([]Issue, error) {
|
||||
var issues []Issue
|
||||
path := "/repos/" + url.PathEscape(owner) + "/" + url.PathEscape(repo) + "/issues"
|
||||
opts := gitea.ListOptions{Extra: url.Values{
|
||||
"state": {"open"},
|
||||
"milestones": {milestoneTitle},
|
||||
}}
|
||||
if err := a.Client.ListAll(context.Background(), path, opts, &issues); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return issues, nil
|
||||
}
|
||||
|
||||
// 編譯期確認 APIClient 同時實作 Client、StalledSource 與 MilestoneSource。
|
||||
var _ StalledSource = (*APIClient)(nil)
|
||||
var _ MilestoneSource = (*APIClient)(nil)
|
||||
|
||||
@@ -0,0 +1,256 @@
|
||||
// milestones.go — 跨倉庫里程碑總覽(teai #31;gitea.py milestones 的對應實作)。
|
||||
//
|
||||
// 各倉庫 open milestone 概況(管理者巡邏用,agents AGENTS.md 10.1):期限近者
|
||||
// 在前的排序、逾期判定、未分派條目摘要與活躍度(updated_at 取里程碑本身與
|
||||
// 其 open 條位的最大值)。判定與輸出規則以 AGENTS.md 為單一來源,行為基準是
|
||||
// gitea.py 的 list_milestone_overview,本檔只實作、不改義。
|
||||
package workflow
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Milestone 是里程碑物件(僅取總覽會用到的欄位)。
|
||||
// ID 與 DueOn 用指標:Gitea 回 null/缺漏時輸出 null
|
||||
// (對應 gitea.py milestone.get("id")/get("due_on") 的 None 語義)。
|
||||
type Milestone struct {
|
||||
ID *int64 `json:"id"`
|
||||
Title string `json:"title"`
|
||||
State string `json:"state"`
|
||||
DueOn *string `json:"due_on"`
|
||||
UpdatedAt string `json:"updated_at"`
|
||||
OpenIssues int64 `json:"open_issues"`
|
||||
ClosedIssues int64 `json:"closed_issues"`
|
||||
}
|
||||
|
||||
// MilestoneSource 是跨倉庫里程碑總覽需要的資料源(CLI 層以 API 實作;
|
||||
// 測試注入假資料,與 Source/StalledSource 同模式)。
|
||||
type MilestoneSource interface {
|
||||
// MyOrganizations 回傳目前帳號所屬組織清單。
|
||||
MyOrganizations() ([]string, error)
|
||||
// OrganizationRepositories 回傳組織的倉庫清單。
|
||||
OrganizationRepositories(org string) ([]Repo, error)
|
||||
// OpenMilestones 回傳倉庫的 open 里程碑。
|
||||
OpenMilestones(owner, repo string) ([]Milestone, error)
|
||||
// MilestoneOpenIssues 回傳掛在指定里程碑(依名稱過濾)的 open
|
||||
// issue 與 PR。刻意不設 type 過濾——兩者都保留供覆蓋檢查
|
||||
//(同 gitea.py _milestone_open_issues 的查詢參數;PR 帶
|
||||
// pull_request 標記,由本套件判別)。
|
||||
MilestoneOpenIssues(owner, repo, milestoneTitle string) ([]Issue, error)
|
||||
}
|
||||
|
||||
// UnassignedEntry 是里程碑 open 條目中未分派者的摘要。
|
||||
type UnassignedEntry struct {
|
||||
Type string
|
||||
Number int64
|
||||
Title string
|
||||
URL string
|
||||
// Author 僅 pull 條目輸出(且作者已知時;對應 gitea.py 只在
|
||||
// _pr_author_username 非空時放 author 鍵)。
|
||||
Author string
|
||||
}
|
||||
|
||||
// MarshalJSON 輸出鍵集與鍵序與 gitea.py 一致的物件。
|
||||
func (u UnassignedEntry) MarshalJSON() ([]byte, error) {
|
||||
var b strings.Builder
|
||||
b.WriteString(`{"type":`)
|
||||
writeJSON(&b, u.Type)
|
||||
b.WriteString(`,"number":`)
|
||||
fmt.Fprintf(&b, "%d", u.Number)
|
||||
b.WriteString(`,"title":`)
|
||||
writeJSON(&b, u.Title)
|
||||
b.WriteString(`,"url":`)
|
||||
writeJSON(&b, u.URL)
|
||||
if u.Author != "" {
|
||||
b.WriteString(`,"author":`)
|
||||
writeJSON(&b, u.Author)
|
||||
}
|
||||
b.WriteString(`}`)
|
||||
return []byte(b.String()), nil
|
||||
}
|
||||
|
||||
// MilestoneEntry 是總覽的單筆輸出(欄位對應 gitea.py list_milestone_overview
|
||||
// 的 dict 鍵序:repo、id、title、url、open_issues、closed_issues、due_on、
|
||||
// due_hours、overdue、unassigned、updated_at)。
|
||||
type MilestoneEntry struct {
|
||||
Repo string
|
||||
ID *int64
|
||||
Title string
|
||||
URL string
|
||||
OpenIssues int64
|
||||
ClosedIssues int64
|
||||
DueOn *string
|
||||
DueHours *float64
|
||||
Overdue bool
|
||||
Unassigned []UnassignedEntry
|
||||
UpdatedAt *string
|
||||
}
|
||||
|
||||
// MarshalJSON 輸出鍵集與鍵序與 gitea.py 完全一致的物件
|
||||
// (與 Item/stalled 的做法相同:手寫鍵序,null/浮點格式對齊 Python)。
|
||||
func (e MilestoneEntry) MarshalJSON() ([]byte, error) {
|
||||
var b strings.Builder
|
||||
b.WriteString(`{"repo":`)
|
||||
writeJSON(&b, e.Repo)
|
||||
b.WriteString(`,"id":`)
|
||||
if e.ID != nil {
|
||||
fmt.Fprintf(&b, "%d", *e.ID)
|
||||
} else {
|
||||
b.WriteString("null")
|
||||
}
|
||||
b.WriteString(`,"title":`)
|
||||
writeJSON(&b, e.Title)
|
||||
b.WriteString(`,"url":`)
|
||||
writeJSON(&b, e.URL)
|
||||
b.WriteString(`,"open_issues":`)
|
||||
fmt.Fprintf(&b, "%d", e.OpenIssues)
|
||||
b.WriteString(`,"closed_issues":`)
|
||||
fmt.Fprintf(&b, "%d", e.ClosedIssues)
|
||||
b.WriteString(`,"due_on":`)
|
||||
writeJSON(&b, e.DueOn)
|
||||
b.WriteString(`,"due_hours":`)
|
||||
if e.DueHours != nil {
|
||||
// Python round(x, 1) 的 json 輸出是 48.0/10.4(定點一位小數)。
|
||||
b.WriteString(strconv.FormatFloat(round1(*e.DueHours), 'f', 1, 64))
|
||||
} else {
|
||||
b.WriteString("null")
|
||||
}
|
||||
b.WriteString(`,"overdue":`)
|
||||
b.WriteString(strconv.FormatBool(e.Overdue))
|
||||
b.WriteString(`,"unassigned":`)
|
||||
writeJSON(&b, e.Unassigned)
|
||||
b.WriteString(`,"updated_at":`)
|
||||
writeJSON(&b, e.UpdatedAt)
|
||||
b.WriteString(`}`)
|
||||
return []byte(b.String()), nil
|
||||
}
|
||||
|
||||
// MilestoneOverview 收集跨組織各倉庫的 open 里程碑概況,依(due_on,
|
||||
// 無則視為最遠)由近到遠排序(穩定排序:同 due_on 者保持掃描順序,
|
||||
// 對應 Python list.sort 的穩定性)。webBase 是站點網址前綴
|
||||
// (scheme://host),空字串時 url 欄位輸出 ""(同 gitea.py 在
|
||||
// GITEA_WEB_DOMAIN 缺漏時的行為)。
|
||||
func MilestoneOverview(src MilestoneSource, webBase string, now time.Time) ([]MilestoneEntry, error) {
|
||||
orgs, err := src.MyOrganizations()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out := []MilestoneEntry{}
|
||||
for _, org := range orgs {
|
||||
repos, err := src.OrganizationRepositories(org)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, repo := range repos {
|
||||
if repo.Name == "" || repo.Empty {
|
||||
continue
|
||||
}
|
||||
ms, err := src.OpenMilestones(org, repo.Name)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for i := range ms {
|
||||
entry, err := milestoneEntry(src, org, repo.Name, &ms[i], webBase, now)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, entry)
|
||||
}
|
||||
}
|
||||
}
|
||||
// gitea.py 的排序鍵:(due_on is None, due_on or "")——有期限者在前、
|
||||
// 期限近者在前;無期限者在後。
|
||||
sort.SliceStable(out, func(a, bb int) bool {
|
||||
x, y := out[a].DueOn, out[bb].DueOn
|
||||
if (x == nil) != (y == nil) {
|
||||
return y == nil
|
||||
}
|
||||
if x != nil {
|
||||
return *x < *y
|
||||
}
|
||||
return false
|
||||
})
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// milestoneEntry 計算單一里程碑的總覽欄位(對應 gitea.py 迴圈體)。
|
||||
func milestoneEntry(src MilestoneSource, org, repo string, m *Milestone, webBase string, now time.Time) (MilestoneEntry, error) {
|
||||
// due_hours/overdue:due_on 缺漏或無法解析 → null/false。
|
||||
// Python 以未捨入值判定 overdue(round 只作用於輸出),
|
||||
// 邊界(如 0.04 小時 → overdue=true、due_hours=0.0)保持一致。
|
||||
var dueHours *float64
|
||||
overdue := false
|
||||
if m.DueOn != nil {
|
||||
if due, ok := parseMoment(*m.DueOn); ok {
|
||||
raw := now.Sub(due).Hours()
|
||||
dueHours = &raw
|
||||
overdue = raw > 0
|
||||
}
|
||||
}
|
||||
openEntries, err := src.MilestoneOpenIssues(org, repo, m.Title)
|
||||
if err != nil {
|
||||
return MilestoneEntry{}, err
|
||||
}
|
||||
// 未分派條目摘要(assignees 為空者);updated_at 取里程碑本身與
|
||||
// 各 open 條目 updated_at 的最大值(供巡邏判斷活躍度)。
|
||||
unassigned := []UnassignedEntry{}
|
||||
moments := []time.Time{}
|
||||
if updated, ok := parseMoment(m.UpdatedAt); ok {
|
||||
moments = append(moments, updated)
|
||||
}
|
||||
for i := range openEntries {
|
||||
entry := &openEntries[i]
|
||||
if updated, ok := parseMoment(entry.UpdatedAt); ok {
|
||||
moments = append(moments, updated)
|
||||
}
|
||||
if len(AssigneeNames(entry)) > 0 {
|
||||
continue
|
||||
}
|
||||
summary := UnassignedEntry{
|
||||
Type: "issue",
|
||||
Number: entry.issueNumber(),
|
||||
Title: entry.Title,
|
||||
URL: entry.WebURL(),
|
||||
}
|
||||
if entry.PullRequest != nil {
|
||||
summary.Type = "pull"
|
||||
if author := entry.User.Name(); author != "" {
|
||||
summary.Author = author
|
||||
}
|
||||
}
|
||||
unassigned = append(unassigned, summary)
|
||||
}
|
||||
var updatedAt *string
|
||||
if len(moments) > 0 {
|
||||
s := FormatMoment(maxTime(moments))
|
||||
updatedAt = &s
|
||||
}
|
||||
return MilestoneEntry{
|
||||
Repo: org + "/" + repo,
|
||||
ID: m.ID,
|
||||
Title: m.Title,
|
||||
URL: milestoneURL(webBase, org, repo, m.ID),
|
||||
OpenIssues: m.OpenIssues,
|
||||
ClosedIssues: m.ClosedIssues,
|
||||
DueOn: m.DueOn,
|
||||
DueHours: dueHours,
|
||||
Overdue: overdue,
|
||||
Unassigned: unassigned,
|
||||
UpdatedAt: updatedAt,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// milestoneURL 組里程碑網頁網址;webBase 空或 id 缺漏回 ""
|
||||
// (對應 gitea.py _milestone_url 的兩個空值條件。Python 原版不做
|
||||
// URL 跳脫——一般組織/倉庫名皆為安全字元,這裡保持一致以求位元組相容)。
|
||||
func milestoneURL(webBase, org, repo string, id *int64) string {
|
||||
if webBase == "" || id == nil {
|
||||
return ""
|
||||
}
|
||||
return strings.TrimRight(webBase, "/") + "/" + org + "/" + repo +
|
||||
"/milestone/" + strconv.FormatInt(*id, 10)
|
||||
}
|
||||
@@ -0,0 +1,262 @@
|
||||
// milestones_test.go — MilestoneOverview 的單元測試(#31)。
|
||||
//
|
||||
// 資料源注入假實作(離線可測);鍵序、null 表示、排序與 overdue
|
||||
// 判定對照 gitea.py list_milestone_overview 的 Python 語義。
|
||||
package workflow
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// fakeMilestoneSource 以記憶體資料實作 MilestoneSource。
|
||||
type fakeMilestoneSource struct {
|
||||
orgs []string
|
||||
repos map[string][]Repo
|
||||
milestones map[string][]Milestone
|
||||
openIssues map[string][]Issue // key: owner/repo?milestone=<title>
|
||||
}
|
||||
|
||||
func (f *fakeMilestoneSource) MyOrganizations() ([]string, error) { return f.orgs, nil }
|
||||
func (f *fakeMilestoneSource) OrganizationRepositories(org string) ([]Repo, error) {
|
||||
return f.repos[org], nil
|
||||
}
|
||||
func (f *fakeMilestoneSource) OpenMilestones(owner, repo string) ([]Milestone, error) {
|
||||
return f.milestones[owner+"/"+repo], nil
|
||||
}
|
||||
func (f *fakeMilestoneSource) MilestoneOpenIssues(owner, repo, title string) ([]Issue, error) {
|
||||
return f.openIssues[owner+"/"+repo+"?milestone="+title], nil
|
||||
}
|
||||
|
||||
func msPtr(s string) *string { return &s }
|
||||
func idPtr(i int64) *int64 { return &i }
|
||||
|
||||
// newMilestoneFixture 建構情境:alterminal 兩倉庫、三里程碑
|
||||
// (teai 有期限將至、agents 有逾期與無期限)。
|
||||
func newMilestoneFixture() *fakeMilestoneSource {
|
||||
return &fakeMilestoneSource{
|
||||
orgs: []string{"alterminal"},
|
||||
repos: map[string][]Repo{"alterminal": {
|
||||
{Name: "agents", HasPullRequests: boolPtr(true)},
|
||||
{Name: "teai", HasPullRequests: boolPtr(true)},
|
||||
{Name: "empty-repo", Empty: true}, // 空倉庫應跳過
|
||||
}},
|
||||
milestones: map[string][]Milestone{
|
||||
"alterminal/agents": {
|
||||
{ID: idPtr(7), Title: "MVP", State: "open",
|
||||
DueOn: msPtr("2026-09-09T00:00:00Z"), UpdatedAt: "2026-09-01T00:00:00Z",
|
||||
OpenIssues: 3, ClosedIssues: 1},
|
||||
{ID: idPtr(8), Title: "v1", State: "open",
|
||||
DueOn: nil, UpdatedAt: "2026-09-02T00:00:00Z",
|
||||
OpenIssues: 1, ClosedIssues: 0},
|
||||
},
|
||||
"alterminal/teai": {
|
||||
{ID: idPtr(3), Title: "CLI", State: "open",
|
||||
DueOn: msPtr("2026-09-12T00:00:00Z"), UpdatedAt: "2026-09-05T00:00:00Z",
|
||||
OpenIssues: 2, ClosedIssues: 5},
|
||||
},
|
||||
},
|
||||
openIssues: map[string][]Issue{
|
||||
// agents MVP:一個未分派 issue、一個未分派 PR、一個已分派 issue。
|
||||
"alterminal/agents?milestone=MVP": {
|
||||
{Number: 31, Title: "總覽命令", State: "open",
|
||||
UpdatedAt: "2026-09-10T01:00:00Z",
|
||||
Repository: &Repository{FullName: "alterminal/agents"},
|
||||
HTMLURL: "https://gitea.alterminal.com/alterminal/agents/issues/31"},
|
||||
{Number: 32, Title: "文件", State: "open",
|
||||
UpdatedAt: "2026-09-08T00:00:00Z",
|
||||
Repository: &Repository{FullName: "alterminal/agents"},
|
||||
HTMLURL: "https://gitea.alterminal.com/alterminal/agents/pulls/32",
|
||||
PullRequest: &pullMarker{}, User: &User{UserName: "alex"}},
|
||||
{Number: 33, Title: "已分派", State: "open",
|
||||
UpdatedAt: "2026-09-07T00:00:00Z",
|
||||
Repository: &Repository{FullName: "alterminal/agents"},
|
||||
HTMLURL: "https://gitea.alterminal.com/alterminal/agents/issues/33",
|
||||
Assignee: &User{UserName: "queena"}},
|
||||
},
|
||||
// agents v1(無期限):條目比里程碑本身新 → updated_at 取條目。
|
||||
"alterminal/agents?milestone=v1": {
|
||||
{Number: 40, Title: "無人理", State: "open",
|
||||
UpdatedAt: "2026-09-09T23:30:00Z",
|
||||
Repository: &Repository{FullName: "alterminal/agents"},
|
||||
HTMLURL: "https://gitea.alterminal.com/alterminal/agents/issues/40"},
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// TestMilestoneOverviewSortAndOverdue 驗證排序(期限近者在前、無期限在後)
|
||||
// 與 overdue/due_hours 計算。
|
||||
func TestMilestoneOverviewSortAndOverdue(t *testing.T) {
|
||||
now := time.Date(2026, 9, 10, 8, 0, 0, 0, time.UTC)
|
||||
entries, err := MilestoneOverview(newMilestoneFixture(), "https://gitea.alterminal.com", now)
|
||||
if err != nil {
|
||||
t.Fatalf("MilestoneOverview: %v", err)
|
||||
}
|
||||
if len(entries) != 3 {
|
||||
t.Fatalf("應有 3 筆(空倉庫跳過),得到 %d", len(entries))
|
||||
}
|
||||
// 排序:MVP(2026-09-09,已過期)→ CLI(2026-09-12)→ v1(無期限)。
|
||||
wantOrder := []string{"alterminal/agents#MVP", "alterminal/teai#CLI", "alterminal/agents#v1"}
|
||||
for i, want := range wantOrder {
|
||||
got := entries[i].Repo + "#" + entries[i].Title
|
||||
if got != want {
|
||||
t.Errorf("第 %d 筆應為 %s,得到 %s", i, want, got)
|
||||
}
|
||||
}
|
||||
// MVP:due 2026-09-09T00:00Z、now 09-10T08:00Z → 32 小時、逾期。
|
||||
if !entries[0].Overdue {
|
||||
t.Errorf("MVP 應逾期")
|
||||
}
|
||||
if entries[0].DueHours == nil || *entries[0].DueHours != 32.0 {
|
||||
t.Errorf("MVP due_hours 應 32.0,得到 %v", entries[0].DueHours)
|
||||
}
|
||||
// CLI:未到期。
|
||||
if entries[1].Overdue {
|
||||
t.Errorf("CLI 不應逾期")
|
||||
}
|
||||
// v1:無期限 → null。
|
||||
if entries[2].DueOn != nil || entries[2].DueHours != nil || entries[2].Overdue {
|
||||
t.Errorf("v1 無期限應為 null/false,得到 %+v", entries[2])
|
||||
}
|
||||
}
|
||||
|
||||
// TestMilestoneOverviewUnassigned 驗證未分派條目摘要(issue 無 author、
|
||||
// pull 帶 author)與 updated_at 取最大值。
|
||||
func TestMilestoneOverviewUnassigned(t *testing.T) {
|
||||
now := time.Date(2026, 9, 10, 8, 0, 0, 0, time.UTC)
|
||||
entries, err := MilestoneOverview(newMilestoneFixture(), "https://gitea.alterminal.com", now)
|
||||
if err != nil {
|
||||
t.Fatalf("MilestoneOverview: %v", err)
|
||||
}
|
||||
var mvp *MilestoneEntry
|
||||
for i := range entries {
|
||||
if entries[i].Title == "MVP" {
|
||||
mvp = &entries[i]
|
||||
}
|
||||
}
|
||||
if mvp == nil {
|
||||
t.Fatalf("找不到 MVP")
|
||||
}
|
||||
// 未分派:#31(issue)、#32(PR, author=alex);#33 已分派不列。
|
||||
if len(mvp.Unassigned) != 2 {
|
||||
t.Fatalf("MVP 應有 2 筆未分派,得到 %d:%+v", len(mvp.Unassigned), mvp.Unassigned)
|
||||
}
|
||||
if mvp.Unassigned[0].Type != "issue" || mvp.Unassigned[0].Number != 31 {
|
||||
t.Errorf("第一筆未分派應為 issue #31,得到 %+v", mvp.Unassigned[0])
|
||||
}
|
||||
if mvp.Unassigned[1].Type != "pull" || mvp.Unassigned[1].Number != 32 || mvp.Unassigned[1].Author != "alex" {
|
||||
t.Errorf("第二筆未分派應為 pull #32(author=alex),得到 %+v", mvp.Unassigned[1])
|
||||
}
|
||||
// updated_at:max(里程碑 09-01, #31 09-10T01:00Z) → 後者。
|
||||
if mvp.UpdatedAt == nil || *mvp.UpdatedAt != "2026-09-10T01:00:00+00:00" {
|
||||
t.Errorf("MVP updated_at 應取條目最大值 2026-09-10T01:00:00+00:00,得到 %v", mvp.UpdatedAt)
|
||||
}
|
||||
// url 組法。
|
||||
if mvp.URL != "https://gitea.alterminal.com/alterminal/agents/milestone/7" {
|
||||
t.Errorf("MVP url 應為 milestone/7,得到 %s", mvp.URL)
|
||||
}
|
||||
}
|
||||
|
||||
// TestMilestoneOverviewJSONKeys 驗證 JSON 鍵集與鍵序與 gitea.py 一致,
|
||||
// 以及 null/陣列空表示(unassigned 空 → [])。
|
||||
func TestMilestoneOverviewJSONKeys(t *testing.T) {
|
||||
now := time.Date(2026, 9, 10, 8, 0, 0, 0, time.UTC)
|
||||
entries, err := MilestoneOverview(newMilestoneFixture(), "", now)
|
||||
if err != nil {
|
||||
t.Fatalf("MilestoneOverview: %v", err)
|
||||
}
|
||||
// v1:無期限、無未分派條目 → due_on/due_hours/updated_at 的 null 表示、
|
||||
// unassigned=[]、webBase 空 → url=""。
|
||||
var v1 *MilestoneEntry
|
||||
for i := range entries {
|
||||
if entries[i].Title == "v1" {
|
||||
v1 = &entries[i]
|
||||
}
|
||||
}
|
||||
if v1 == nil {
|
||||
t.Fatalf("找不到 v1")
|
||||
}
|
||||
// 手寫期望 JSON(縮排 2、鍵序照 gitea.py dict 實字序)。
|
||||
b, err := json.Marshal(v1)
|
||||
if err != nil {
|
||||
t.Fatalf("Marshal: %v", err)
|
||||
}
|
||||
// 以逐鍵比對為準(MarshalIndent 因自訂 MarshalJSON 不縮排內層)。
|
||||
var obj map[string]json.RawMessage
|
||||
if err := json.Unmarshal(b, &obj); err != nil {
|
||||
t.Fatalf("Unmarshal: %v", err)
|
||||
}
|
||||
wantKeys := []string{"repo", "id", "title", "url", "open_issues", "closed_issues",
|
||||
"due_on", "due_hours", "overdue", "unassigned", "updated_at"}
|
||||
// 鍵序:json.Unmarshal 到 map 會失序;改檢查原始字串的鍵出現順序。
|
||||
pos := -1
|
||||
for _, k := range wantKeys {
|
||||
i := strings.Index(string(b), `"`+k+`":`)
|
||||
if i < 0 {
|
||||
t.Fatalf("輸出缺少鍵 %q:%s", k, b)
|
||||
}
|
||||
if i < pos {
|
||||
t.Fatalf("鍵 %q 順序錯誤:%s", k, b)
|
||||
}
|
||||
pos = i
|
||||
}
|
||||
for _, kv := range []struct {
|
||||
key string
|
||||
want string
|
||||
}{
|
||||
{"repo", `"alterminal/agents"`},
|
||||
{"due_on", `null`},
|
||||
{"due_hours", `null`},
|
||||
{"overdue", `false`},
|
||||
{"url", `""`},
|
||||
} {
|
||||
if got := string(obj[kv.key]); got != kv.want {
|
||||
t.Errorf("%s 應為 %s,得到 %s", kv.key, kv.want, got)
|
||||
}
|
||||
}
|
||||
if !strings.Contains(string(b), `"number":40`) {
|
||||
t.Errorf("未分派條目應含 number 40:%s", b)
|
||||
}
|
||||
// pull 條目的 author 鍵:有作者才輸出(無則不該出現 "author")。
|
||||
if strings.Contains(string(obj["unassigned"]), `"author"`) {
|
||||
t.Errorf("issue 條目不應有 author 鍵:%s", obj["unassigned"])
|
||||
}
|
||||
}
|
||||
|
||||
// TestMilestoneOverviewDueHoursRounding 驗證 due_hours 捨入到一位小數,
|
||||
// 且 overdue 以未捨入值判定(0.04h → 0.0 但 overdue=true)。
|
||||
func TestMilestoneOverviewDueHoursRounding(t *testing.T) {
|
||||
src := &fakeMilestoneSource{
|
||||
orgs: []string{"alterminal"},
|
||||
repos: map[string][]Repo{"alterminal": {{Name: "r"}}},
|
||||
milestones: map[string][]Milestone{
|
||||
"alterminal/r": {
|
||||
{ID: idPtr(1), Title: "edge", State: "open",
|
||||
DueOn: msPtr("2026-09-10T07:57:36Z"), UpdatedAt: "2026-09-10T07:00:00Z"},
|
||||
},
|
||||
},
|
||||
openIssues: map[string][]Issue{},
|
||||
}
|
||||
now := time.Date(2026, 9, 10, 8, 0, 0, 0, time.UTC)
|
||||
entries, err := MilestoneOverview(src, "", now)
|
||||
if err != nil {
|
||||
t.Fatalf("MilestoneOverview: %v", err)
|
||||
}
|
||||
if len(entries) != 1 {
|
||||
t.Fatalf("應有 1 筆,得到 %d", len(entries))
|
||||
}
|
||||
// 144 秒 = 0.04 小時 → round1 → 0.0;未捨入 > 0 → overdue=true。
|
||||
b, err := json.Marshal(entries[0])
|
||||
if err != nil {
|
||||
t.Fatalf("Marshal: %v", err)
|
||||
}
|
||||
if !strings.Contains(string(b), `"due_hours":0.0`) {
|
||||
t.Errorf("due_hours 應捨入為 0.0:%s", b)
|
||||
}
|
||||
if !strings.Contains(string(b), `"overdue":true`) {
|
||||
t.Errorf("overdue 應以未捨入值判定為 true:%s", b)
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,10 @@
|
||||
// stalled_entry_test.go — RunStalled/ResolveIssueXrefs 高階入口的單元測試
|
||||
//(#7 CLI 接線;資料源注入假實作,離線可測)。
|
||||
// (#7 CLI 接線;資料源注入假實作,離線可測)。
|
||||
package workflow
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
@@ -14,10 +16,22 @@ type fakeStalledSource struct {
|
||||
username string
|
||||
// getIssueErr 模擬 GetIssue 失敗(xrefs 的 404 路徑)。
|
||||
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) 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) {
|
||||
if f.getIssueErr != nil {
|
||||
return Issue{}, f.getIssueErr
|
||||
@@ -38,7 +52,7 @@ func (e *notFoundError) Error() string { return "404" }
|
||||
func newStalledFixture() *fakeStalledSource {
|
||||
return &fakeStalledSource{
|
||||
fakeSource: &fakeSource{
|
||||
orgs: []string{"alterminal"},
|
||||
orgs: []string{"alterminal"},
|
||||
repos: map[string][]Repo{"alterminal": {
|
||||
{Name: "agents", HasPullRequests: boolPtr(true)},
|
||||
{Name: "teai", HasPullRequests: boolPtr(true)},
|
||||
@@ -229,3 +243,92 @@ func TestResolveIssueXrefsEmptyBody(t *testing.T) {
|
||||
}
|
||||
_ = 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
@@ -30,6 +30,11 @@ const (
|
||||
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。
|
||||
//
|
||||
// 前面不得是文數字/底線/斜線(避免切進 alterminal/bear#47 的後半段);
|
||||
@@ -149,6 +154,9 @@ type Source interface {
|
||||
IssueComments(owner, repo string, number int64) ([]Comment, error)
|
||||
// TryGetIssue 寬容版單一 issue 查詢:失敗(含 404)回 (零值, false, nil)。
|
||||
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)。
|
||||
@@ -268,8 +276,11 @@ func childActivity(src Source, org, repo string, parent Issue, comments []Commen
|
||||
if pcOK && ccOK && !childCreated.After(parentCreated) {
|
||||
continue // 上行引用(父項回指更早或同時的 issue);時間未知則不排除
|
||||
}
|
||||
// 子項的直接活動:created_at、state 變更(closed_at)、留言(agents #32)。
|
||||
// 原始 updated_at 不放入已知活動,另經 directLastActivity 核對後採計
|
||||
//(與 considerIssue/considerPull 對本 issue 自身的處理同構)。
|
||||
var ms []time.Time
|
||||
if m, ok := parseMoment(child.UpdatedAt); ok {
|
||||
if m, ok := parseMoment(child.CreatedAt); ok {
|
||||
ms = append(ms, m)
|
||||
}
|
||||
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
|
||||
if len(ms) > 0 {
|
||||
latest := maxTime(ms)
|
||||
@@ -302,6 +321,71 @@ func childActivity(src Source, org, repo string, parent Issue, comments []Commen
|
||||
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 {
|
||||
best := ts[0]
|
||||
for _, t := range ts[1:] {
|
||||
@@ -382,7 +466,7 @@ func ScanStalled(src Source, username string, threshold float64, now time.Time)
|
||||
if err != nil {
|
||||
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)
|
||||
}
|
||||
}
|
||||
@@ -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) {
|
||||
childMoments, children := childActivity(src, org, repo, issue, comments, myOrgs, orgRepos)
|
||||
assignees := AssigneeNames(&issue)
|
||||
var moments []time.Time
|
||||
if m, ok := parseMoment(issue.UpdatedAt); ok {
|
||||
moments = append(moments, m)
|
||||
}
|
||||
// 已知直接活動:留言、created_at、#32 納入的子項活動。
|
||||
var known []time.Time
|
||||
if m, ok := parseMoment(issue.CreatedAt); ok {
|
||||
moments = append(moments, m)
|
||||
known = append(known, m)
|
||||
}
|
||||
for _, c := range comments {
|
||||
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 {
|
||||
return Item{}, false
|
||||
}
|
||||
@@ -455,21 +547,28 @@ func considerIssue(src Source, org, repo string, issue Issue, comments []Comment
|
||||
}
|
||||
|
||||
// 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)
|
||||
author := pr.Author()
|
||||
var moments []time.Time
|
||||
if m, ok := parseMoment(pr.UpdatedAt); ok {
|
||||
moments = append(moments, m)
|
||||
}
|
||||
// 已知直接活動:留言、created_at。
|
||||
var known []time.Time
|
||||
if m, ok := parseMoment(pr.CreatedAt); ok {
|
||||
moments = append(moments, m)
|
||||
known = append(known, m)
|
||||
}
|
||||
for _, c := range comments {
|
||||
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 {
|
||||
return Item{}, false
|
||||
}
|
||||
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"sort"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
@@ -28,6 +29,8 @@ type fakeSource struct {
|
||||
pulls map[string][]PullRequest
|
||||
// comments[owner/repo/number]
|
||||
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 }
|
||||
@@ -41,6 +44,8 @@ func (f *fakeSource) OpenIssues(owner, repo string) ([]Issue, error) {
|
||||
for _, i := range f.issues[owner+"/"+repo] {
|
||||
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
|
||||
}
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
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) {
|
||||
i, ok := f.issues[owner+"/"+repo][number]
|
||||
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)
|
||||
if err != nil {
|
||||
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) {
|
||||
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) 半偶數一致)。
|
||||
func TestRound1(t *testing.T) {
|
||||
|
||||
Reference in New Issue
Block a user