mirror of
https://github.com/BaaRai/ARTEX.git
synced 2026-12-03 13:11:05 +00:00
refactor(server): use modern Go idioms
Mechanical modernization of the server package's production code with the gopls/go fix modernizers: range over int, strings.SplitSeq, strings.Cut / CutPrefix, slices.Contains / Backward, maps.Copy, min / max and sync.WaitGroup.Go. No behaviour change. The package's tests follow in a separate PR. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
f427b05b67
commit
ca7fe9dc0a
19 changed files with 49 additions and 87 deletions
|
|
@ -10,6 +10,7 @@ import (
|
|||
"io/fs"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
|
@ -178,10 +179,8 @@ func resolveAskOperatorImage(runDir, src string) (string, error) {
|
|||
if !askOperatorImageExt[ext] {
|
||||
return "", fmt.Errorf("image_path must be a png/jpg/jpeg/webp/gif file, got %q", filepath.Base(src))
|
||||
}
|
||||
for _, el := range strings.Split(filepath.ToSlash(src), "/") {
|
||||
if el == ".." {
|
||||
return "", fmt.Errorf("image_path must stay inside the run directory")
|
||||
}
|
||||
if slices.Contains(strings.Split(filepath.ToSlash(src), "/"), "..") {
|
||||
return "", fmt.Errorf("image_path must stay inside the run directory")
|
||||
}
|
||||
if !filepath.IsAbs(src) {
|
||||
src = filepath.Join(runDir, src)
|
||||
|
|
|
|||
|
|
@ -7,6 +7,7 @@ import (
|
|||
"log"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strings"
|
||||
|
||||
"github.com/Autumn-27/artex/agent"
|
||||
|
|
@ -392,12 +393,7 @@ func wireTools(pg *db.DB, domainReg map[string]actool.CoreTool) {
|
|||
}
|
||||
|
||||
func contains(ss []string, v string) bool {
|
||||
for _, s := range ss {
|
||||
if s == v {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
return slices.Contains(ss, v)
|
||||
}
|
||||
|
||||
// buildDomainReg builds a name→CoreTool registry from a server-level ToolSet
|
||||
|
|
|
|||
|
|
@ -6,6 +6,7 @@ import (
|
|||
"fmt"
|
||||
"log"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
|
|
@ -722,8 +723,7 @@ const emptyTurnNudge = "[Idle-turn reminder] Your last turn produced only thinki
|
|||
// isThinkingOnlyTurn reports whether the latest assistant turn produced neither
|
||||
// text nor a tool call — i.e. the model spent the whole round thinking.
|
||||
func isThinkingOnlyTurn(messages []llm.Message) bool {
|
||||
for i := len(messages) - 1; i >= 0; i-- {
|
||||
m := messages[i]
|
||||
for _, m := range slices.Backward(messages) {
|
||||
if m.Role != llm.RoleAssistant {
|
||||
continue
|
||||
}
|
||||
|
|
@ -992,7 +992,7 @@ func (e *Engine) Run(ctx context.Context, t *Task) {
|
|||
e.touch(t.ID)
|
||||
runTaskRoutine(rt, func(loopCtx context.Context) { e.plannerLoop(loopCtx, t) })
|
||||
runTaskRoutine(rt, func(loopCtx context.Context) { e.claimSweepLoop(loopCtx, t) })
|
||||
for i := 0; i < workers; i++ {
|
||||
for i := range workers {
|
||||
name := fmt.Sprintf("work#%d", i+1)
|
||||
runTaskRoutine(rt, func(loopCtx context.Context) { e.workerLoop(loopCtx, t, name) })
|
||||
}
|
||||
|
|
@ -1010,10 +1010,8 @@ func (e *Engine) Run(ctx context.Context, t *Task) {
|
|||
// plannerHeartbeatInterval parses a task's planner heartbeat interval.
|
||||
// db.CreateTask already normalizes it (anything below 600 is raised to 600); this is one more safety net against abnormal in-memory values.
|
||||
func plannerHeartbeatInterval(t *Task) time.Duration {
|
||||
sec := t.PlanHeartbeatSeconds
|
||||
if sec < db.MinPlanHeartbeatSeconds { // floor = default = 600 (10min)
|
||||
sec = db.MinPlanHeartbeatSeconds
|
||||
}
|
||||
// floor = default = 600 (10min)
|
||||
sec := max(t.PlanHeartbeatSeconds, db.MinPlanHeartbeatSeconds)
|
||||
return time.Duration(sec) * time.Second
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -216,10 +216,7 @@ func (e *Engine) deadlineCoordinator(ctx context.Context, t *Task) {
|
|||
continue
|
||||
}
|
||||
if remaining := time.Until(time.Unix(dl, 0)); remaining > 0 {
|
||||
nap := remaining
|
||||
if nap > deadlineMaxSleep {
|
||||
nap = deadlineMaxSleep
|
||||
}
|
||||
nap := min(remaining, deadlineMaxSleep)
|
||||
if sleepCtx(ctx, nap) {
|
||||
return
|
||||
}
|
||||
|
|
|
|||
|
|
@ -7,6 +7,7 @@ import (
|
|||
"io"
|
||||
"log"
|
||||
"os"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
|
@ -128,12 +129,7 @@ func decodeSealedEnv(b []byte) ([]string, error) {
|
|||
}
|
||||
|
||||
func isSecretName(name string) bool {
|
||||
for _, k := range secretEnv {
|
||||
if k == name {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
return slices.Contains(secretEnv, name)
|
||||
}
|
||||
|
||||
// withoutSecretEnv returns the environment block without the secret entries.
|
||||
|
|
|
|||
|
|
@ -79,7 +79,7 @@ func executorEnv(env []string, keep map[string]bool) []string {
|
|||
// become an agent process, with executorEnv of it and the names in envExecKeep.
|
||||
func sealExecutorEnv() error {
|
||||
keep := map[string]bool{}
|
||||
for _, n := range strings.Split(os.Getenv(envExecKeep), ",") {
|
||||
for n := range strings.SplitSeq(os.Getenv(envExecKeep), ",") {
|
||||
if n = strings.TrimSpace(n); n != "" {
|
||||
keep[n] = true
|
||||
}
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@ package server
|
|||
import (
|
||||
"encoding/json"
|
||||
"log"
|
||||
"slices"
|
||||
|
||||
"github.com/Autumn-27/artex/agent"
|
||||
)
|
||||
|
|
@ -94,12 +95,7 @@ WHERE key='record_fact' AND system AND kind='builtin'
|
|||
}
|
||||
|
||||
func sliceHas(list []string, s string) bool {
|
||||
for _, v := range list {
|
||||
if v == s {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
return slices.Contains(list, s)
|
||||
}
|
||||
|
||||
func (s *Server) seedFactInputSchema() {
|
||||
|
|
|
|||
|
|
@ -51,12 +51,12 @@ func normalizeEvidenceText(s string) string {
|
|||
// returned in place of a failed decode.
|
||||
func decodeEvidenceBody(respHead string, raw []byte, limit int) (out []byte, truncated bool, err error) {
|
||||
coding := ""
|
||||
for _, line := range strings.Split(respHead, "\n") {
|
||||
for line := range strings.SplitSeq(respHead, "\n") {
|
||||
name, value, ok := strings.Cut(line, ":")
|
||||
if !ok || !strings.EqualFold(strings.TrimSpace(name), "Content-Encoding") {
|
||||
continue
|
||||
}
|
||||
for _, v := range strings.Split(value, ",") {
|
||||
for v := range strings.SplitSeq(value, ",") {
|
||||
switch v = strings.ToLower(strings.TrimSpace(v)); v {
|
||||
case "", "identity":
|
||||
case "gzip", "deflate":
|
||||
|
|
|
|||
|
|
@ -5,6 +5,7 @@ import (
|
|||
"net"
|
||||
"net/http"
|
||||
"net/netip"
|
||||
"slices"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
|
@ -156,8 +157,8 @@ func clientIP(r *http.Request, trusted []netip.Prefix) string {
|
|||
return peer
|
||||
}
|
||||
hops := strings.Split(strings.Join(r.Header.Values("X-Forwarded-For"), ","), ",")
|
||||
for i := len(hops) - 1; i >= 0; i-- {
|
||||
hop, err := netip.ParseAddr(strings.TrimSpace(hops[i]))
|
||||
for _, raw := range slices.Backward(hops) {
|
||||
hop, err := netip.ParseAddr(strings.TrimSpace(raw))
|
||||
if err != nil {
|
||||
break // keep the last address a trusted proxy reported
|
||||
}
|
||||
|
|
@ -183,7 +184,7 @@ func isTrusted(a netip.Addr, trusted []netip.Prefix) bool {
|
|||
// bare address means that one host). Empty means no trusted proxy.
|
||||
func ParseTrustedProxies(s string) ([]netip.Prefix, error) {
|
||||
var out []netip.Prefix
|
||||
for _, f := range strings.Split(s, ",") {
|
||||
for f := range strings.SplitSeq(s, ",") {
|
||||
f = strings.TrimSpace(f)
|
||||
if f == "" {
|
||||
continue
|
||||
|
|
|
|||
|
|
@ -10,6 +10,7 @@ import (
|
|||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
|
@ -1937,8 +1938,7 @@ func (s *taskFileDeleteStage) rollback() error {
|
|||
return nil
|
||||
}
|
||||
var errs []error
|
||||
for i := len(s.moves) - 1; i >= 0; i-- {
|
||||
move := s.moves[i]
|
||||
for _, move := range slices.Backward(s.moves) {
|
||||
if _, err := os.Lstat(move.source); err == nil {
|
||||
errs = append(errs, fmt.Errorf("restore destination already exists: %s", move.source))
|
||||
continue
|
||||
|
|
|
|||
|
|
@ -2587,7 +2587,7 @@ func (s *Server) findingsExport(w http.ResponseWriter, r *http.Request) {
|
|||
var filter db.FindingFilter
|
||||
switch scope {
|
||||
case "selected":
|
||||
for _, part := range strings.Split(q.Get("ids"), ",") {
|
||||
for part := range strings.SplitSeq(q.Get("ids"), ",") {
|
||||
part = strings.TrimSpace(part)
|
||||
if part == "" {
|
||||
continue
|
||||
|
|
@ -3225,7 +3225,7 @@ func (s *Server) nodeAnchoredAssets(t *Task, nodeIDs []int64) map[string][]Findi
|
|||
// csvValues splits a comma-separated query parameter, dropping empty entries.
|
||||
func csvValues(s string) []string {
|
||||
out := []string{}
|
||||
for _, part := range strings.Split(s, ",") {
|
||||
for part := range strings.SplitSeq(s, ",") {
|
||||
if v := strings.TrimSpace(part); v != "" {
|
||||
out = append(out, v)
|
||||
}
|
||||
|
|
@ -3487,10 +3487,7 @@ func (s *Server) getLogsHistory(w http.ResponseWriter, r *http.Request) {
|
|||
return
|
||||
}
|
||||
before := int64(atoiDefault(r.URL.Query().Get("before"), 0))
|
||||
limit := atoiDefault(r.URL.Query().Get("limit"), 200)
|
||||
if limit > 500 {
|
||||
limit = 500
|
||||
}
|
||||
limit := min(atoiDefault(r.URL.Query().Get("limit"), 200), 500)
|
||||
// If no before given, return the most recent DB rows (mirrors ring restore).
|
||||
var (
|
||||
rows []*db.DBLog
|
||||
|
|
|
|||
|
|
@ -505,20 +505,14 @@ func (s *Server) pgSaveAgentConfig(w http.ResponseWriter, r *http.Request) {
|
|||
profileChanged = true
|
||||
}
|
||||
if req.MaxTurns != nil {
|
||||
mt := *req.MaxTurns
|
||||
if mt < 0 {
|
||||
mt = 0
|
||||
}
|
||||
mt := max(*req.MaxTurns, 0)
|
||||
if err := pg.SetAgentMaxTurns(a.Key, mt); err != nil {
|
||||
writeErr(w, 500, err.Error())
|
||||
return
|
||||
}
|
||||
}
|
||||
if req.RunSeconds != nil {
|
||||
rs := *req.RunSeconds
|
||||
if rs < 0 {
|
||||
rs = 0
|
||||
}
|
||||
rs := max(*req.RunSeconds, 0)
|
||||
if err := pg.SetAgentRunSeconds(a.Key, rs); err != nil {
|
||||
writeErr(w, 500, err.Error())
|
||||
return
|
||||
|
|
@ -686,10 +680,7 @@ func (s *Server) pgSaveWrapup(w http.ResponseWriter, r *http.Request) {
|
|||
return
|
||||
}
|
||||
if body.MaxTurns != nil {
|
||||
n := *body.MaxTurns
|
||||
if n < 0 {
|
||||
n = 0
|
||||
}
|
||||
n := max(*body.MaxTurns, 0)
|
||||
if err := pg.SetAgentWrapupMaxTurns(a.Key, n); err != nil {
|
||||
writeErr(w, 500, err.Error())
|
||||
return
|
||||
|
|
@ -737,10 +728,7 @@ func (s *Server) pgSaveTaskTimeoutWrapup(w http.ResponseWriter, r *http.Request)
|
|||
}
|
||||
turns := a.TaskTimeoutWrapupMaxTurns // keep the existing value when not provided
|
||||
if body.MaxTurns != nil {
|
||||
turns = *body.MaxTurns
|
||||
if turns < 0 {
|
||||
turns = 0
|
||||
}
|
||||
turns = max(*body.MaxTurns, 0)
|
||||
}
|
||||
if err := pg.SetAgentTaskTimeoutWrapup(a.Key, body.Prompt, turns); err != nil {
|
||||
writeErr(w, 500, err.Error())
|
||||
|
|
@ -1490,8 +1478,8 @@ func rewriteSkillFrontmatter(content []byte, mcps *[]string, description, licens
|
|||
type kv struct{ k, v string }
|
||||
var pairs []kv
|
||||
for _, l := range lines[1:fmEnd] {
|
||||
if idx := strings.IndexByte(l, ':'); idx >= 0 {
|
||||
pairs = append(pairs, kv{strings.TrimSpace(l[:idx]), strings.TrimSpace(l[idx+1:])})
|
||||
if before, after, ok := strings.Cut(l, ":"); ok {
|
||||
pairs = append(pairs, kv{strings.TrimSpace(before), strings.TrimSpace(after)})
|
||||
} else if strings.TrimSpace(l) != "" {
|
||||
pairs = append(pairs, kv{"", l}) // preserve non-key lines verbatim
|
||||
}
|
||||
|
|
@ -2482,7 +2470,7 @@ func urlEffectivePort(u *url.URL) (int, bool) {
|
|||
|
||||
func parsePrivateModelEndpoints(raw string) map[string]bool {
|
||||
out := map[string]bool{}
|
||||
for _, entry := range strings.Split(raw, ",") {
|
||||
for entry := range strings.SplitSeq(raw, ",") {
|
||||
entry = strings.TrimSpace(entry)
|
||||
if entry == "" {
|
||||
continue
|
||||
|
|
|
|||
|
|
@ -497,7 +497,7 @@ func (s *Server) runSide(ctx context.Context, cancel context.CancelFunc, e sideq
|
|||
e.Status = "failed"
|
||||
e.Error = runErr.Error()
|
||||
}
|
||||
for attempt := 0; attempt < 3; attempt++ {
|
||||
for attempt := range 3 {
|
||||
if _, err := persist(); err == nil {
|
||||
break
|
||||
}
|
||||
|
|
|
|||
|
|
@ -378,7 +378,7 @@ func (s *Server) ssProjectMeta(ctx context.Context, cl *mcphttp.Client, projectI
|
|||
if err := json.Unmarshal([]byte(text), &p); err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
for _, line := range strings.Split(p.Target, "\n") {
|
||||
for line := range strings.SplitSeq(p.Target, "\n") {
|
||||
if t := strings.TrimSpace(line); t != "" {
|
||||
roots = append(roots, t)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -12,6 +12,7 @@ import (
|
|||
"log"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
|
|
@ -255,8 +256,7 @@ func (s *taskArchiveFileStage) rollbackFiles() error {
|
|||
}
|
||||
defer root.Close()
|
||||
var errs []error
|
||||
for i := len(s.journal.Moves) - 1; i >= 0; i-- {
|
||||
move := s.journal.Moves[i]
|
||||
for _, move := range slices.Backward(s.journal.Moves) {
|
||||
staged := filepath.Join(s.payload, move.Relative)
|
||||
stagedRel, err := archiveRelUnder(dataDir, staged)
|
||||
if err != nil {
|
||||
|
|
@ -383,8 +383,7 @@ func (s *taskArchiveRestoreFiles) rollback() error {
|
|||
return nil
|
||||
}
|
||||
var errs []error
|
||||
for i := len(s.moves) - 1; i >= 0; i-- {
|
||||
move := s.moves[i]
|
||||
for _, move := range slices.Backward(s.moves) {
|
||||
if _, err := os.Lstat(move.Destination); os.IsNotExist(err) {
|
||||
continue
|
||||
} else if err != nil {
|
||||
|
|
|
|||
|
|
@ -72,9 +72,7 @@ func (s *Server) startTaskArchiveWorker() {
|
|||
log.Printf("[task-archive] worker disabled because startup recovery is incomplete")
|
||||
return
|
||||
}
|
||||
s.archiveWG.Add(1)
|
||||
go func() {
|
||||
defer s.archiveWG.Done()
|
||||
s.archiveWG.Go(func() {
|
||||
ticker := time.NewTicker(taskArchivePollInterval)
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
|
|
@ -88,7 +86,7 @@ func (s *Server) startTaskArchiveWorker() {
|
|||
case <-ticker.C:
|
||||
}
|
||||
}
|
||||
}()
|
||||
})
|
||||
s.notifyTaskArchiveWorker()
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -8,6 +8,7 @@ import (
|
|||
"iter"
|
||||
"log"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
|
|
@ -231,11 +232,8 @@ func (r *taskLLMRuntime) currentFor(ctx context.Context) (taskLLMSelection, erro
|
|||
}
|
||||
sel.profileID = *pt.ActiveLLMProfileID
|
||||
if pin, ok := llmProfilePinFrom(ctx); ok && pin != sel.profileID {
|
||||
for _, id := range pt.ReadyLLMProfileIDs {
|
||||
if id == pin {
|
||||
sel.profileID = pin
|
||||
break
|
||||
}
|
||||
if slices.Contains(pt.ReadyLLMProfileIDs, pin) {
|
||||
sel.profileID = pin
|
||||
}
|
||||
}
|
||||
prov, cfg, ok := r.s.providerForProfile(sel.profileID)
|
||||
|
|
|
|||
|
|
@ -6,6 +6,7 @@ import (
|
|||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"maps"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strconv"
|
||||
|
|
@ -161,9 +162,7 @@ func (m *Manager) reloadTamperHooks() {
|
|||
defs = append(defs, d)
|
||||
}
|
||||
hs, loadErrs := traffic.CompileHooks(defs, db.TrafficTraceKey())
|
||||
for id, msg := range decodeErrs {
|
||||
loadErrs[id] = msg
|
||||
}
|
||||
maps.Copy(loadErrs, decodeErrs)
|
||||
for id, msg := range loadErrs {
|
||||
slog.Warn("[traffic] tampering hook not loaded", "hook_id", id, "msg", msg)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -110,7 +110,7 @@ func assetCompressible(ctype string) bool {
|
|||
|
||||
// gzipAccepted reports whether the client accepts gzip with a non-zero q-value.
|
||||
func gzipAccepted(r *http.Request) bool {
|
||||
for _, part := range strings.Split(r.Header.Get("Accept-Encoding"), ",") {
|
||||
for part := range strings.SplitSeq(r.Header.Get("Accept-Encoding"), ",") {
|
||||
fields := strings.Split(strings.TrimSpace(part), ";")
|
||||
coding := strings.ToLower(strings.TrimSpace(fields[0]))
|
||||
if coding != "gzip" && coding != "*" {
|
||||
|
|
@ -119,8 +119,8 @@ func gzipAccepted(r *http.Request) bool {
|
|||
q := 1.0
|
||||
for _, attr := range fields[1:] {
|
||||
attr = strings.TrimSpace(attr)
|
||||
if strings.HasPrefix(attr, "q=") {
|
||||
if v, err := strconv.ParseFloat(strings.TrimPrefix(attr, "q="), 64); err == nil {
|
||||
if after, ok := strings.CutPrefix(attr, "q="); ok {
|
||||
if v, err := strconv.ParseFloat(after, 64); err == nil {
|
||||
q = v
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue