Compare commits

...
7 Commits
Author SHA1 Message Date
wangdefa 74e815bedf ci: 移除已过时的 TempDir 重试兜底,测试改为单跑
ci / frontend (push) Successful in 53s
ci / backend (push) Successful in 2m11s
release / release (push) Successful in 8m30s
db 跨轮污染(f8454d3)与 server TempDir 竞态(98515a3)均已根治,
重试兜底的前提不复存在:恢复为 go test 单跑,红了即真红。
2026-10-20 23:20:17 -07:00
wangdefa 1e3536f571 test: 对齐 coverage.scope 移除、测试改名,删掉 CI -skip
06a43f3 已有意删除 coverage.scope(范围根资产+company 富化)以精简规划上
下文,但该测试仍断言此字段。去掉相关断言、改名为 TestAssociatedCompany
AssetsEnterTaskContext(仍校验公司资产进入任务上下文),并移除 CI 里的 -skip。
2026-10-20 23:16:31 -07:00
wangdefa 98515a3974 fix: 优雅停机停等任务 goroutine,根治 TempDir 清理竞态
ci / frontend (push) Successful in 53s
ci / backend (push) Successful in 2m11s
新增 Server.Close / Engine.StopAll:取消 ctx 后依次等 side-flusher、
后台循环、各任务 planner/worker、归档 worker 退出;测试用 defer s.Close()
在清理前排空 goroutine,遂把 tempDir 兜底改回 t.TempDir() 并删除 helper。
2026-10-20 23:08:21 -07:00
wangdefa f8454d310b test: 公司归属测试结束删公司,修复 CI 重试跨轮污染
ci / frontend (push) Successful in 55s
ci / backend (push) Failing after 2m38s
2026-10-20 22:32:42 -07:00
wangdefa 99ea805880 ci: 测试步骤加重试,兜住既有的 TempDir 清理竞态
ci / frontend (push) Successful in 53s
ci / backend (push) Failing after 2m50s
server 包的后台 worker 会在测试结束后继续写 t.TempDir(),清理时报
"TempDir RemoveAll cleanup: directory not empty"(单测单独跑则通过)。
根因是 Manager.Close() 只关数据库、不等 task goroutine 退出,属既有问题。
真实失败两次都会失败,不会被重试掩盖。
2026-10-20 22:19:05 -07:00
wangdefa d26dcd7621 ci: backend 改为在 job 内启动 PostgreSQL
ci / frontend (push) Successful in 53s
ci / backend (push) Failing after 2m6s
这台 runner 的 services 不可用(服务名解析不了、端口也没发布到 job),
改为装 PostgreSQL 并 initdb 一个临时集群:

- apt 安装 postgresql,顺带提供 psql 客户端,去掉单独的安装步骤
- root 下切 postgres 用户 initdb --auth=trust,pg_ctl 起在 127.0.0.1:55432
- 把 PG* 与 ARTEX_PG_DSN 写入 GITHUB_ENV,后续步骤与测试直接使用
- 已在 debian:bookworm-slim 容器内实跑验证整段脚本
2026-10-20 22:03:30 -07:00
wangdefa ba2f4b4b06 ci: 修复首次运行的两处失败
ci / frontend (push) Successful in 52s
ci / backend (push) Failing after 1m31s
- backend:日志显示服务名 postgres 无法解析(runner 为 host 网络,services 只
  发布端口、不提供容器别名)。给 service 加 55432:5432 端口映射,并改为依次
  探测 postgres:5432 与 127.0.0.1:55432,连上后写入 PG* 与 ARTEX_PG_DSN;
  都不通时打印解析结果,便于判断网络模式。
- frontend/release:setup-node 的 cache 只接受 npm/yarn/pnpm,之前的
  cache: false 会导致 "Caching for 'false' is not supported" 直接失败,去掉该键。
2026-10-20 21:54:06 -07:00
14 changed files with 148 additions and 65 deletions

No files matched your search

+58 -36
View File
@@ -1,15 +1,15 @@
# Gitea Actions:push 到 main 时跑后端测试与前端构建。
# 刻意不接 pull_request:solo 开发时同一提交会跑两遍,浪费 CI 时间。
#
# 前置条件(缺一不可):
# 前置条件:
# 1. 仓库 Settings → Actions 勾选 “Enable Repository Actions”
# 2. 已注册带 ubuntu-latest-amd64 标签、且以 Docker 模式运行的 Gitea Runner
# (services 容器只在 Docker 模式下可用)
# 现有 Runner:runner-amd64 → ubuntu-latest-amd64 / ubuntu-22.04-amd64 / ubuntu-20.04-amd64
# runner-arm64 → ubuntu-latest-arm64 / ubuntu-22.04-arm64 / ubuntu-20.04-arm64
# 想跑在 arm64 上把下面的 runs-on 换成 ubuntu-latest-arm64 即可。
# 3. Runner 能出网:actions/checkout 与 actions/setup-go 默认从 github.com 拉取,
# setup-go 还要从 go.dev 下载工具链
# 2. 已注册带 ubuntu-latest-amd64 标签的 Gitea Runner
# runner-amd64 → ubuntu-latest-amd64 / ubuntu-22.04-amd64 / ubuntu-20.04-amd64
# runner-arm64 → ubuntu-latest-arm64 / ubuntu-22.04-arm64 / ubuntu-20.04-arm64
# 3. Runner 能出网:actions/checkout 从 github.com 拉 action,setup-go 从 go.dev 下工具链
#
# 数据库不用 services:这台 runner 上服务容器的服务名解析不了、端口也没发布到 job,
# 所以改为在 job 内装 PostgreSQL 并 initdb 一个临时集群(见「启动 PostgreSQL」)。
name: ci
on:
@@ -23,39 +23,62 @@ jobs:
backend:
runs-on: ubuntu-latest-amd64
timeout-minutes: 40
services:
postgres:
image: postgres:16-alpine
env:
POSTGRES_USER: artex
POSTGRES_PASSWORD: artex
POSTGRES_DB: artex
options: >-
--health-cmd "pg_isready -U artex"
--health-interval 5s
--health-timeout 5s
--health-retries 30
env:
ARTEX_PG_DSN: postgres://artex:artex@postgres:5432/artex?sslmode=disable
steps:
- uses: actions/checkout@v4
- uses: actions/setup-go@v5
with:
go-version: "1.26"
# Runner 没开缓存服务时 actions/cache 会失败,这里先关掉保稳。
# setup-go 的 cache 是布尔输入,false 表示不做缓存(依赖 Runner 的缓存服务)。
cache: false
- name: 安装 psql 客户端
- name: 启动 PostgreSQL
run: |
command -v psql >/dev/null 2>&1 && exit 0
apt-get update -qq
apt-get install -y -qq postgresql-client
set -euo pipefail
# Debian/Ubuntu 把服务器端装在 /usr/lib/postgresql/<ver>/bin。装包自动创建的
# 集群要靠 systemd 启动,容器里起不来,所以这里自己 initdb 一个临时集群。
if ! ls /usr/lib/postgresql/*/bin/initdb >/dev/null 2>&1; then
apt-get update -qq
DEBIAN_FRONTEND=noninteractive apt-get install -y -qq postgresql
fi
BIN="$(ls -d /usr/lib/postgresql/*/bin | sort -V | tail -1)"
echo "使用 $BIN"
PGDATA=/tmp/pgdata
rm -rf "$PGDATA"
mkdir -p "$PGDATA"
# initdb 不允许以 root 运行:root 下切到 postgres 用户,否则用当前用户。
pg_as() {
if [ "$(id -u)" = 0 ]; then
su postgres -s /bin/sh -c "cd /tmp && $*"
else
sh -c "cd /tmp && $*"
fi
}
if [ "$(id -u)" = 0 ]; then chown postgres:postgres "$PGDATA"; fi
pg_as "$BIN/initdb -D $PGDATA -U artex --auth=trust --encoding=UTF8" > /tmp/initdb.log 2>&1 \
|| { echo "initdb 失败:"; cat /tmp/initdb.log; exit 1; }
pg_as "$BIN/pg_ctl -D $PGDATA -l /tmp/pg.log -o '-p 55432 -k /tmp' -w start" \
|| { echo "pg_ctl 启动失败:"; cat /tmp/pg.log; exit 1; }
pg_as "$BIN/psql -h /tmp -p 55432 -U artex -d postgres -c 'CREATE DATABASE artex'"
{
echo "PGHOST=127.0.0.1"
echo "PGPORT=55432"
echo "PGUSER=artex"
echo "PGDATABASE=artex"
echo "ARTEX_PG_DSN=postgres://artex@127.0.0.1:55432/artex?sslmode=disable"
} >> "$GITHUB_ENV"
psql -h 127.0.0.1 -p 55432 -U artex -d artex -tAc "select version()"
- name: 初始化数据库 schema
env:
PGPASSWORD: artex
run: psql -h postgres -U artex -d artex -v ON_ERROR_STOP=1 -q -f db/schema.sql
run: |
psql -v ON_ERROR_STOP=1 -q -f db/schema.sql
echo "schema 应用完成,表数:$(psql -tAc "select count(*) from information_schema.tables where table_schema='public'")"
- name: 初始化运行时表(llm_usage)
run: |
@@ -91,11 +114,8 @@ jobs:
run: go vet ./...
- name: 测试
run: |
# -p 1:各包共用一个库,串行执行避免跨包数据竞争。
# -skip:TestGraphOverviewExpandsAssociatedCompanyScope 在当前代码上
# 已失败(coverage["scope"] 为 nil),与本流程无关,修好后请删掉。
go test -p 1 ./... -count=1 -skip 'TestGraphOverviewExpandsAssociatedCompanyScope'
# -p 1:各包共用一个库,串行执行避免跨包数据竞争。
run: go test -p 1 ./... -count=1
frontend:
runs-on: ubuntu-latest-amd64
@@ -106,7 +126,9 @@ jobs:
- uses: actions/setup-node@v4
with:
node-version: "22"
cache: false
# 注意:这里不能写 cache: false —— setup-node 的 cache 只接受
# npm / yarn / pnpm,传布尔值会报 "Caching for 'false' is not supported"。
# 需要缓存时改成 cache: npm(要求 Runner 开了缓存服务)。
- name: 安装依赖
working-directory: web
+1 -1
View File
@@ -43,7 +43,7 @@ jobs:
- uses: actions/setup-node@v4
with:
node-version: "22"
cache: false
# cache 只接受 npm / yarn / pnpm,写 false 会直接报错。
- name: 补齐打包工具
run: |
+9 -22
View File
@@ -25,7 +25,15 @@ func callReadJSON(t *testing.T, tool actool.CoreTool, input string) any {
return out
}
func TestGraphOverviewExpandsAssociatedCompanyScope(t *testing.T) {
// TestAssociatedCompanyAssetsEnterTaskContext verifies that an asset attributed
// to a task's company surfaces in the agent's task context: it is linked to the
// task with company provenance, counted in coverage.host_count, and reachable via
// list_untested_assets / list_assets and as an intent target — with or without the
// coverage feature. It no longer asserts coverage.scope: that overview field (scope
// root assets + company enrichment) was intentionally dropped in 06a43f3 to slim the
// per-round planner context; the association itself still holds through the checks
// below.
func TestAssociatedCompanyAssetsEnterTaskContext(t *testing.T) {
d := testDB(t)
defer d.Close()
@@ -82,27 +90,6 @@ func TestGraphOverviewExpandsAssociatedCompanyScope(t *testing.T) {
if !ok {
t.Fatalf("coverage missing: %#v", overview["coverage"])
}
scopeRows, ok := coverage["scope"].([]map[string]any)
if !ok || len(scopeRows) != 1 {
t.Fatalf("task scope missing: %#v", coverage["scope"])
}
companyScope, ok := scopeRows[0]["company_scope"].([]map[string]any)
if !ok || len(companyScope) != len(inputs) {
t.Fatalf("company scope not expanded: %#v", scopeRows[0])
}
kinds := make(map[string]string, len(companyScope))
for _, rule := range companyScope {
kinds[fmt.Sprint(rule["kind"])] = fmt.Sprint(rule["value"])
}
for _, input := range inputs {
if kinds[input.Kind] != input.Value {
t.Errorf("scope %s=%q want %q", input.Kind, kinds[input.Kind], input.Value)
}
}
keywords, ok := scopeRows[0]["company_keywords"].([]string)
if !ok || len(keywords) != 1 || keywords[0] != keyword {
t.Fatalf("company keywords missing: %#v", scopeRows[0]["company_keywords"])
}
if hc, _ := coverage["host_count"].(int); hc < 1 {
t.Fatalf("company asset host not counted in agent context: %#v", coverage["host_count"])
}
+5
View File
@@ -342,6 +342,11 @@ func TestCompanyScopeAttribution(t *testing.T) {
if err != nil {
t.Fatalf("UpsertCompany: %v", err)
}
// 公司名每轮唯一,但 CIDR(198.51.100.0/24)是硬编码的。CI 重试会复用同一个库,
// 若不删公司,上一轮留下的 scope 行会和本轮争夺同一网段——IP 归属按 company_id 升序
// 取第一个,于是落到上一轮那个更小的 id 上(曾现 company_id=26, want 64)。删公司会
// 级联清掉 company_scope,让重试从干净状态开始。LIFO:本清理先于上面的删资产+关库跑。
t.Cleanup(func() { _ = cs.DeleteCompany(cid) })
// a pre-existing asset (inserted BEFORE any scope) — must be back-filled.
preID, err := as.UpsertSubdomain(UpsertSubdomainReq{Domain: sub})
+2
View File
@@ -19,6 +19,7 @@ func TestChatUnavailableReasonDistinguishesStates(t *testing.T) {
defer m.Close()
td := t.TempDir()
s := New(context.Background(), m, td, td, td)
defer s.Close()
// Start from a clean profile table; other tests in the shared DB may have left rows.
existing, _ := m.pg.ListProfiles()
@@ -69,6 +70,7 @@ func TestResolveChatAgentHonoursConversationProfile(t *testing.T) {
defer m.Close()
td := t.TempDir()
s := New(context.Background(), m, td, td, td)
defer s.Close()
// Force the global fallback to nil so a non-nil result can ONLY come from the
// conversation's own profile — this is exactly the situation the user hit
+1
View File
@@ -25,6 +25,7 @@ func TestCoreTaskLifecyclePG(t *testing.T) {
defer m.Close()
td := t.TempDir()
s := New(context.Background(), m, td, td, td)
defer s.Close()
h := s.Handler()
tok, err := signJWT(s.jwtKey)
if err != nil {
+21
View File
@@ -290,6 +290,27 @@ func (e *Engine) StopTask(taskID string) {
e.deleteMu.Unlock()
}
// StopAll cancels every live task runtime and waits for its planner, worker and
// deadline goroutines to return. Used on server shutdown (Server.Close): unlike
// StopTask it does not purge the per-task Engine maps — the process/Server is going
// away — it only makes sure no task goroutine survives to keep writing (e.g., into
// a test's data dir while Go's t.TempDir cleanup is removing it). Cancelling the
// server context already signals these loops; this blocks until they have exited.
func (e *Engine) StopAll() {
e.runtimeMu.Lock()
rts := make([]*taskRuntime, 0, len(e.runtimes))
for _, rt := range e.runtimes {
rts = append(rts, rt)
}
e.runtimeMu.Unlock()
for _, rt := range rts {
rt.cancel()
}
for _, rt := range rts {
rt.wg.Wait()
}
}
// cancelExec cancels a task's current per-task exec context (any in-flight
// planner.Plan / worker.Execute), if present. Shared by Pause and the settle
// sequence's hard-drain backstop.
+1
View File
@@ -53,6 +53,7 @@ func TestInheritedActivityDetailAndRelationDeletion(t *testing.T) {
}
s := New(context.Background(), m, t.TempDir(), t.TempDir(), t.TempDir())
defer s.Close()
token, err := signJWT(s.jwtKey)
if err != nil {
t.Fatal(err)
+1
View File
@@ -20,6 +20,7 @@ func TestMgmtAPI(t *testing.T) {
}
td := t.TempDir()
s := New(context.Background(), m, td, td, td)
defer s.Close()
h := s.Handler()
tok, err := signJWT(s.jwtKey)
if err != nil {
+43 -6
View File
@@ -42,6 +42,12 @@ type Server struct {
m *Manager
engine *Engine
ctx context.Context
// cancel tears down ctx; Close() calls it to stop every background goroutine
// started by New (scheduler, notifier, evidence GC, task-archive worker and all
// per-task planner/worker/deadline loops). bgWG tracks the server-level loops so
// Close can wait for them to return before the data dir is removed.
cancel context.CancelFunc
bgWG sync.WaitGroup
skillDir string // root directory for skill subdirectories
jwtKey []byte // HS256 signing key loaded from / generated into dataDir/jwt.key
@@ -145,7 +151,11 @@ func New(ctx context.Context, m *Manager, skillDir string, dataDir string, keyDi
if err != nil {
log.Fatalf("[auth] JWT key: %v", err)
}
s := &Server{m: m, engine: NewEngine(m), ctx: ctx, skillDir: skillDir, jwtKey: key, chatBusy: map[string]bool{},
// Own a cancelable child of the caller's ctx so Close() can stop every
// background goroutine below even when the caller passed a context that never
// cancels (e.g. context.Background() in tests).
ctx, cancel := context.WithCancel(ctx)
s := &Server{m: m, engine: NewEngine(m), ctx: ctx, cancel: cancel, skillDir: skillDir, jwtKey: key, chatBusy: map[string]bool{},
chatCancel: map[string]context.CancelCauseFunc{}, triggerQ: map[string][]triggeredRun{},
triggerActive: map[string]int{}, triggerCfg: map[string]triggerBehavior{},
profChatAgents: map[int64]*agent.ChatAgent{},
@@ -225,12 +235,17 @@ func New(ctx context.Context, m *Manager, skillDir string, dataDir string, keyDi
if err := s.seedFindingRetester(); err != nil {
log.Printf("[retester] seed: %v", err)
}
go s.evidenceStore().RunGC(s.ctx)
s.seedPythonInterpreter() // 自定义脚本工具:开机检测 python 解释器入库(仅空时)
go newScheduler(s).Run(s.ctx) // P3 触发器调度(定时/finding/目标事件),仅自定义 agent
s.bgWG.Add(1)
go func() { defer s.bgWG.Done(); s.evidenceStore().RunGC(s.ctx) }()
s.seedPythonInterpreter() // 自定义脚本工具:开机检测 python 解释器入库(仅空时)
sc := newScheduler(s)
s.bgWG.Add(1)
go func() { defer s.bgWG.Done(); sc.Run(s.ctx) }() // P3 触发器调度(定时/finding/目标事件),仅自定义 agent
// 漏洞 IM 推送投递引擎。与 Scheduler 并列但独立:推送的实时性要求(3s)
// 与触发器的业务节奏不同,且两者失败互不牵连——推送卡住不该影响 agent 触发。
go newNotifier(s).Run(s.ctx)
nt := newNotifier(s)
s.bgWG.Add(1)
go func() { defer s.bgWG.Done(); nt.Run(s.ctx) }()
// Fill the tool cache for any enabled MCP that has none yet (notably the
// seeded browser MCP on first run). Async so it never blocks startup.
go s.discoverEmptyMCPsOnStartup()
@@ -253,12 +268,34 @@ func New(ctx context.Context, m *Manager, skillDir string, dataDir string, keyDi
log.Printf("[engine] no LLM provider configured — engine idle until set via /api/llm or env")
}
s.restoreTaskRuntimes()
go s.reconcileConcurrency()
s.bgWG.Add(1)
go func() { defer s.bgWG.Done(); s.reconcileConcurrency() }()
s.startTaskArchiveWorker()
s.wireInterceptReviewer() // LLM 兜底审批:未命中拦截规则的命令交给模型判定
return s
}
// Close stops every background goroutine started by New and waits for them to
// return, so nothing writes into the data dir afterwards. It cancels the server
// context (stopping the scheduler, notifier, evidence GC, task-archive worker and
// every task's planner/worker/deadline loops), then waits: first the server-level
// loops, then the per-task runtimes, then the archive worker. Call it before
// Manager.Close() (which closes the DB) and before the data dir is removed — in
// tests, before t.TempDir() cleanup runs, which otherwise races a late task-file or
// archive write ("TempDir RemoveAll cleanup: directory not empty"). Safe to call
// once; the engine waits are idempotent for already-exited runtimes.
func (s *Server) Close() {
if s.cancel != nil {
s.cancel()
}
if s.side != nil {
<-s.side.done // side-question snapshot flusher (final flush on ctx.Done)
}
s.bgWG.Wait() // scheduler / notifier / evidence GC / startup reconcile
s.engine.StopAll() // per-task planner / worker / deadline loops
s.archiveWG.Wait() // cold task-archive worker
}
// Restored deadline and worker loops must inherit the same context as new tasks,
// including the side-question checkpoint publisher installed during startup.
func (s *Server) restoreTaskRuntimes() {
+1
View File
@@ -22,6 +22,7 @@ func TestTaskCategoryBatchRoute(t *testing.T) {
td := t.TempDir()
s := New(context.Background(), m, td, td, td)
defer s.Close()
h := s.Handler()
token, err := signJWT(s.jwtKey)
if err != nil {
+1
View File
@@ -17,6 +17,7 @@ func TestWorkerControlRoutes(t *testing.T) {
td := t.TempDir()
s := New(context.Background(), m, td, td, td)
defer s.Close()
h := s.Handler()
token, err := signJWT(s.jwtKey)
if err != nil {
+2
View File
@@ -25,6 +25,7 @@ func TestTaskMetadataPatchReturnsRenameAndPin(t *testing.T) {
taskID, _ := strconv.ParseInt(task.ID, 10, 64)
defer func() { _ = m.pg.DeleteTask(taskID) }()
s := New(context.Background(), m, t.TempDir(), t.TempDir(), t.TempDir())
defer s.Close()
token, err := signJWT(s.jwtKey)
if err != nil {
t.Fatal(err)
@@ -67,6 +68,7 @@ func TestConversationBatchDeleteReportsMissing(t *testing.T) {
}
defer m.Close()
s := New(context.Background(), m, t.TempDir(), t.TempDir(), t.TempDir())
defer s.Close()
first, err := m.pg.CreateConversation("mainagent", "batch-http-first", nil)
if err != nil {
t.Fatal(err)
+2
View File
@@ -21,6 +21,7 @@ func TestTaskTemplateHTTPCRUD(t *testing.T) {
}
defer m.Close()
s := New(context.Background(), m, t.TempDir(), t.TempDir(), t.TempDir())
defer s.Close()
h := s.Handler()
token, err := signJWT(s.jwtKey)
if err != nil {
@@ -91,6 +92,7 @@ func TestConversationPatchReturnsPinState(t *testing.T) {
}
defer m.Close()
s := New(context.Background(), m, t.TempDir(), t.TempDir(), t.TempDir())
defer s.Close()
conversation, err := m.pg.CreateConversation("mainagent", "pin through http", nil)
if err != nil {
t.Fatal(err)