First Commit
ci / go (push) Waiting to run
ci / go-db (agent) (push) Waiting to run
ci / go-db (config) (push) Waiting to run
ci / go-db (db) (push) Waiting to run
ci / go-db (evidence) (push) Waiting to run
ci / go-db (llmrec) (push) Waiting to run
ci / go-db (server) (push) Waiting to run
web / web (push) Waiting to run
docs / links (push) Canceled after 0s
detections / detections (push) Canceled after 0s

This commit is contained in:
dela
2026-10-09 08:38:16 +08:00
commit 0335d572de
756 changed files with 201663 additions and 0 deletions
+160
View File
@@ -0,0 +1,160 @@
// Command artex runs the ARTEX backend: the dual SQLite graph stores,
// the event-driven exploration engine, and the JSON HTTP API consumed by the
// shadcn/ui frontend.
package main
import (
"context"
"flag"
"fmt"
"log"
"net/http"
"os"
"os/signal"
"path/filepath"
"runtime"
"syscall"
"time"
"github.com/Autumn-27/artex/agent"
"github.com/Autumn-27/artex/config"
"github.com/Autumn-27/artex/selfupdate"
"github.com/Autumn-27/artex/server"
)
// version is the build version, injected at release time via
// -ldflags "-X main.version=<tag>". Defaults to "dev" for local builds.
var version = "dev"
const banner = `
_ ____ _____ _______ __
/ \ | _ \_ _| ____\ \/ /
/ _ \ | |_) || | | _| \ /
/ ___ \| _ < | | | |___ / \
/_/ \_\_| \_\|_| |_____/_/\_\
`
// printBanner writes the startup banner + version/runtime info to stdout.
func printBanner(addr string) {
fmt.Print(banner)
fmt.Println(" AI 자율 침투 테스트 시스템")
fmt.Printf(" 버전 %s · %s/%s · %s · 수신 대기 %s\n\n",
version, runtime.GOOS, runtime.GOARCH, runtime.Version(), addr)
}
// main only maps run's result onto the process exit code. The exit code is part
// of the update protocol — the supervising start script reads it to decide
// whether to relaunch us (see selfupdate.ExitRestart) — so the body has to live
// in a function that can *return* rather than os.Exit past its own defers.
func main() {
os.Exit(run())
}
func run() int {
var (
addr = flag.String("addr", ":8787", "HTTP listen address")
dataDir = flag.String("data", filepath.Join(config.BaseDir(), "data"), "data directory for SQLite stores (default: data/ next to the executable)")
proxy = flag.String("proxy", "127.0.0.1:8788", "traffic recording proxy address (empty to disable)")
)
flag.Parse()
// hand the build version to the server package so GET /api/health can report it
// to the frontend top bar.
server.BuildVersion = version
printBanner(*addr)
// capture backend logs into the in-memory sink (still to stderr) so the /logs
// page can show a live log stream. Do this first, to catch startup logs too.
server.StartLogCapture()
// Self-update bootstrap: swap in a staged binary, or count a post-swap boot
// attempt and roll back if the new build keeps dying. Must run before we open
// the stores or bind a port — this may end with "exit and let the start script
// relaunch me", and there is no point paying for either first.
action, upState := selfupdate.Bootstrap()
server.SetBootUpdateState(upState)
if action == selfupdate.Restart {
return selfupdate.ExitRestart
}
// surface which config file the binary reads (absolute, so `go run`'s relative
// "config.json" — resolved against the CWD — is unambiguous).
cfgPath := config.Path()
if abs, e := filepath.Abs(cfgPath); e == nil {
cfgPath = abs
}
if _, e := os.Stat(cfgPath); e == nil {
log.Printf("[config] 설정 파일: %s", cfgPath)
} else {
log.Printf("[config] 설정 파일: %s (파일 없음 · 환경 변수 ARTEX_PG_DSN 만 사용)", cfgPath)
}
sigCtx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
ctx, shutdown := shutdownContext(sigCtx)
defer shutdown(agent.AbortShutdown)
mgr, err := server.NewManager(*dataDir, *proxy)
if err != nil {
log.Fatalf("open stores: %v", err)
}
defer mgr.Close()
// Surviving this long means a freshly swapped-in build actually works, so drop
// the upgrade marker and stop counting attempts. Until it fires, every boot
// increments the count and a build that keeps dying gets rolled back.
settle := time.AfterFunc(selfupdate.SettleDelay, selfupdate.Settle)
defer settle.Stop()
skillDir := config.SkillDir()
if abs, err := filepath.Abs(skillDir); err == nil {
skillDir = abs
}
log.Printf("[config] skill 디렉터리: %s", skillDir)
srv := server.New(ctx, mgr, skillDir, *dataDir, config.BaseDir())
httpSrv := &http.Server{
Addr: *addr,
Handler: srv.Handler(),
ReadHeaderTimeout: 10 * time.Second,
}
go func() {
log.Printf("ARTEX %s backend listening on %s (data=%s, workers=%d)", version, *addr, *dataDir, mgr.Workers())
if err := httpSrv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
log.Fatalf("serve: %v", err)
}
}()
// Two ways out: a signal (normal stop → exit 0, the start script stops looping)
// or a staged update / rollback (→ exit 75, the script relaunches us and the
// bootstrap above installs the new build).
code := 0
select {
case <-ctx.Done():
case <-server.RestartRequested():
code = selfupdate.ExitRestart
shutdown(agent.AbortShutdown)
}
log.Println("shutting down...")
shutdownCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
_ = httpSrv.Shutdown(shutdownCtx)
return code
}
// shutdownContext deliberately does not derive from signalCtx. If it did, the
// parent's plain context.Canceled could win the race before AbortShutdown was
// attached to the child, losing the diagnostic cause in every running Agent.
func shutdownContext(signalCtx context.Context) (context.Context, context.CancelCauseFunc) {
ctx, shutdown := context.WithCancelCause(context.Background())
go func() {
select {
case <-signalCtx.Done():
shutdown(agent.AbortShutdown)
case <-ctx.Done():
}
}()
return ctx, shutdown
}
+78
View File
@@ -0,0 +1,78 @@
package main
import (
"bytes"
"context"
"io"
"os"
"strings"
"testing"
"unicode"
"github.com/Autumn-27/artex/agent"
)
func TestShutdownContextPreservesNamedCause(t *testing.T) {
signalCtx, signalCancel := context.WithCancel(context.Background())
ctx, shutdown := shutdownContext(signalCtx)
defer shutdown(nil)
signalCancel()
<-ctx.Done()
if code, _, _, ok := agent.AbortReason(ctx); !ok || code != "shutdown" {
t.Fatalf("code=%q ok=%v, want shutdown", code, ok)
}
}
// TestPrintBannerLocalized verifies that the startup banner printed to stdout is
// Korean and carries no leftover CJK Han characters. This is the first thing a
// user sees when running ARTEX, so it must not stay in Chinese (backlog F11).
// The "[config] ..." log lines in run() are intentionally out of scope — they
// are logs, which the localization brief ranks lowest (backlog Z2).
func TestPrintBannerLocalized(t *testing.T) {
out := captureStdout(t, func() { printBanner(":8787") })
t.Logf("배너 샘플:\n%s", out)
hasHangul := strings.ContainsFunc(out, func(r rune) bool {
return unicode.Is(unicode.Hangul, r)
})
if !hasHangul {
t.Fatalf("배너에 한글이 없다: %q", out)
}
for _, want := range []string{"자율 침투 테스트 시스템", "버전", "수신 대기", ":8787"} {
if !strings.Contains(out, want) {
t.Errorf("배너에 %q 가 없다: %q", want, out)
}
}
for _, r := range out {
if unicode.Is(unicode.Han, r) {
t.Errorf("배너에 CJK 한자 잔재(%q): %q", r, out)
}
}
}
// captureStdout redirects os.Stdout for the duration of fn and returns whatever
// fn wrote. printBanner uses fmt.Print*, which resolves os.Stdout at call time,
// so swapping it here captures the banner.
func captureStdout(t *testing.T, fn func()) string {
t.Helper()
orig := os.Stdout
r, w, err := os.Pipe()
if err != nil {
t.Fatalf("os.Pipe: %v", err)
}
os.Stdout = w
done := make(chan string, 1)
go func() {
var buf bytes.Buffer
_, _ = io.Copy(&buf, r)
done <- buf.String()
}()
fn()
_ = w.Close()
os.Stdout = orig
return <-done
}