Merge branch 'main' into feat/systemone-profile-format

This commit is contained in:
BaaRai
2026-11-23 22:58:48 +01:00
committed by GitHub
13 changed files with 278 additions and 41 deletions
+38
View File
@@ -0,0 +1,38 @@
package server
import "testing"
func TestParseTargetURLFollowedByPunctuation(t *testing.T) {
cases := []struct {
text string
scheme string
host string
port int
}{
{"Assess http://juiceshop:3000, then report.", "http", "juiceshop", 3000},
{"Assess http://juiceshop:3000.", "http", "juiceshop", 3000},
{"Scope: http://juiceshop:3000; nothing else", "http", "juiceshop", 3000},
{"The lab (http://juiceshop:3000) is ours", "http", "juiceshop", 3000},
{"Test https://app.example.com:8080, only the API", "https", "app.example.com", 8080},
{"Target is https://example.com.", "https", "example.com", 443},
{"Start at https://example.com/login?next=/a, then pivot", "https", "example.com", 443},
{"http://juiceshop:3000", "http", "juiceshop", 3000},
{"Assess http://juiceshop.", "http", "juiceshop", 80},
{"Assess http://10.0.0.5.", "http", "10.0.0.5", 80},
{"Assess http://juiceshop:3000。", "http", "juiceshop", 3000},
{"Assess “http://juiceshop:3000”", "http", "juiceshop", 3000},
{"See https://en.wikipedia.org/wiki/Foo_(bar).", "https", "en.wikipedia.org", 443},
{"(https://en.wikipedia.org/wiki/Foo_(bar))", "https", "en.wikipedia.org", 443},
{"http://[::1]", "http", "::1", 80},
{"http://[::1]:8080", "http", "::1", 8080},
{"Assess http://[fd00::10].", "http", "fd00::10", 80},
{"[http://[::1]:8080]", "http", "::1", 8080},
}
for _, c := range cases {
scheme, host, port, ok := parseTarget(c.text)
if !ok || scheme != c.scheme || host != c.host || port != c.port {
t.Errorf("parseTarget(%q) = %q, %q, %d, %v; want %q, %q, %d, true",
c.text, scheme, host, port, ok, c.scheme, c.host, c.port)
}
}
}
+41 -29
View File
@@ -28,7 +28,7 @@ type Scheduler struct {
const (
schedKeyLastFinding = "last_finding_id" // watermark: max finding node id fired for
schedKeyFiredGoals = "fired_goals" // JSON array of goal node ids already fired
schedKeyLastTimeout = "last_timeout_id" // watermark: max task id fired for task timeout
schedKeyFiredTimeouts = "fired_timeouts" // JSON array of task ids already fired for task timeout
schedKeyLastToolCall = "last_toolcall_id" // watermark: max activity id fired for tool call
schedKeyLastTaskCreate = "last_taskcreate_id" // watermark: max task id fired for task create
)
@@ -77,18 +77,16 @@ func (sc *Scheduler) init() {
set[e.NodeID] = true
}
}
sc.saveFiredGoalSet(set)
sc.saveFiredSet(schedKeyFiredGoals, set)
}
if sc.mustState(schedKeyLastTimeout) == "" {
var maxID int64
if evs, err := sc.pg.TimedOutTasksSince(0); err == nil {
if sc.mustState(schedKeyFiredTimeouts) == "" {
set := map[int64]bool{}
if evs, err := sc.pg.TimedOutTasks(); err == nil {
for _, e := range evs {
if e.NodeID > maxID {
maxID = e.NodeID
}
set[e.NodeID] = true
}
}
_ = sc.pg.SetSchedState(schedKeyLastTimeout, strconv.FormatInt(maxID, 10))
sc.saveFiredSet(schedKeyFiredTimeouts, set)
}
if sc.mustState(schedKeyLastToolCall) == "" {
var maxID int64
@@ -195,7 +193,7 @@ func (sc *Scheduler) fireGoals(triggers []*db.AgentTrigger) {
}
// Mark goals as consumed whether or not a trigger is active, so enabling an
// on_goal_met trigger later doesn't replay every already-met goal.
fired := sc.firedGoalSet()
fired := sc.firedSet(schedKeyFiredGoals)
changed := false
for _, e := range events {
if fired[e.NodeID] {
@@ -212,12 +210,14 @@ func (sc *Scheduler) fireGoals(triggers []*db.AgentTrigger) {
}
}
if changed {
sc.saveFiredGoalSet(fired)
sc.saveFiredSet(schedKeyFiredGoals, fired)
}
}
// fireTaskTimeouts fires on_task_timeout triggers for tasks that newly reached
// status='timeout' above the persisted watermark (task id → no double-fire).
// status='timeout'. Tasks time out in deadline order, not id order, so fired
// tasks are kept in a persisted set (like goals) rather than an id watermark:
// a watermark would skip an older task that times out after a newer one.
func (sc *Scheduler) fireTaskTimeouts(triggers []*db.AgentTrigger) {
var want []*db.AgentTrigger
for _, tr := range triggers {
@@ -225,17 +225,8 @@ func (sc *Scheduler) fireTaskTimeouts(triggers []*db.AgentTrigger) {
want = append(want, tr)
}
}
last, _ := strconv.ParseInt(sc.mustState(schedKeyLastTimeout), 10, 64)
events, err := sc.pg.TimedOutTasksSince(last)
if err != nil || len(events) == 0 {
return
}
// Advance the watermark even with no active trigger — see fireFindings.
maxID := last
for _, e := range events {
if e.NodeID > maxID {
maxID = e.NodeID
}
// Consume the timeouts even with no active trigger — see fireFindings.
for _, e := range sc.newTaskTimeouts() {
if len(want) == 0 {
continue
}
@@ -244,7 +235,28 @@ func (sc *Scheduler) fireTaskTimeouts(triggers []*db.AgentTrigger) {
sc.s.StartTriggeredRun(tr.AgentKey, fmt.Sprintf("Timeout trigger · task#%d", e.TaskID), tr.TaskTimeoutMessage+msgCtx, e.TaskID, true, e.TaskDesc, e.TaskGoal)
}
}
_ = sc.pg.SetSchedState(schedKeyLastTimeout, strconv.FormatInt(maxID, 10))
}
// newTaskTimeouts returns the timed-out tasks not fired for yet and records
// them as consumed.
func (sc *Scheduler) newTaskTimeouts() []db.TaskEvent {
events, err := sc.pg.TimedOutTasks()
if err != nil || len(events) == 0 {
return nil
}
fired := sc.firedSet(schedKeyFiredTimeouts)
var out []db.TaskEvent
for _, e := range events {
if fired[e.NodeID] {
continue
}
fired[e.NodeID] = true
out = append(out, e)
}
if len(out) > 0 {
sc.saveFiredSet(schedKeyFiredTimeouts, fired)
}
return out
}
// fireTaskCreates fires on_task_create triggers for tasks newly created above the
@@ -347,9 +359,9 @@ func (sc *Scheduler) mustState(key string) string {
return v
}
func (sc *Scheduler) firedGoalSet() map[int64]bool {
func (sc *Scheduler) firedSet(key string) map[int64]bool {
out := map[int64]bool{}
raw := sc.mustState(schedKeyFiredGoals)
raw := sc.mustState(key)
if raw == "" {
return out
}
@@ -362,13 +374,13 @@ func (sc *Scheduler) firedGoalSet() map[int64]bool {
return out
}
func (sc *Scheduler) saveFiredGoalSet(set map[int64]bool) {
func (sc *Scheduler) saveFiredSet(key string, set map[int64]bool) {
ids := make([]int64, 0, len(set))
for id := range set {
ids = append(ids, id)
}
b, _ := json.Marshal(ids)
if err := sc.pg.SetSchedState(schedKeyFiredGoals, string(b)); err != nil {
log.Printf("[scheduler] save fired goals failed: %v", err)
if err := sc.pg.SetSchedState(key, string(b)); err != nil {
log.Printf("[scheduler] save %s failed: %v", key, err)
}
}
+58
View File
@@ -0,0 +1,58 @@
package server
import (
"testing"
"github.com/Autumn-27/artex/db"
)
// Tasks time out in deadline order, not in id order: a task created later with
// a shorter timeout can time out first. Each timeout must still fire once.
func TestSchedulerTaskTimeoutsFireOutOfIDOrder(t *testing.T) {
skipWithoutDSN(t)
m, err := NewManager(t.TempDir(), "")
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { m.Close() })
sc := &Scheduler{pg: m.pg}
sc.newTaskTimeouts() // consume timeouts other tests left behind
var ids [2]int64
for i := range ids {
task, err := m.pg.CreateTaskWithOptions("timeout order", "goal", db.TaskCreateOptions{})
if err != nil {
t.Fatal(err)
}
ids[i] = task.ID
t.Cleanup(func() { _ = m.pg.DeleteTask(task.ID) })
}
older, newer := ids[0], ids[1]
timeOut := func(id int64) {
t.Helper()
if _, err := m.pg.Exec(`UPDATE tasks SET status='timeout' WHERE id=$1`, id); err != nil {
t.Fatal(err)
}
}
fired := func() []int64 {
var out []int64
for _, e := range sc.newTaskTimeouts() {
if e.TaskID == older || e.TaskID == newer {
out = append(out, e.TaskID)
}
}
return out
}
timeOut(newer)
if got := fired(); len(got) != 1 || got[0] != newer {
t.Fatalf("after the newer task timed out: fired %v, want [%d]", got, newer)
}
timeOut(older)
if got := fired(); len(got) != 1 || got[0] != older {
t.Fatalf("after the older task timed out: fired %v, want [%d]", got, older)
}
if got := fired(); len(got) != 0 {
t.Fatalf("second scan fired %v again, want nothing", got)
}
}
+23
View File
@@ -23,6 +23,7 @@ import (
"sync"
"sync/atomic"
"time"
"unicode/utf8"
"github.com/Autumn-27/artex/agent"
"github.com/Autumn-27/artex/archivestore"
@@ -1945,11 +1946,33 @@ var (
reDomain = regexp.MustCompile(`\b((?:[a-zA-Z0-9-]+\.)+[a-zA-Z]{2,})(?::(\d{1,5}))?`)
)
// trimURLTail drops sentence punctuation that free text puts after a URL
// ("Assess http://host:3000."). A closing bracket is dropped only when it has no
// opener in the URL, so "http://[::1]" keeps its "]".
func trimURLTail(s string) string {
for s != "" {
r, size := utf8.DecodeLastRuneInString(s)
switch r {
case '.', ',', ';', ':', '!', '?', '。', ',', '、', ';', ':', '!', '?', '”', '’':
case ')', ']', '}', '>':
open := string("([{<"[strings.IndexRune(")]}>", r)])
if strings.Count(s, open) >= strings.Count(s, string(r)) {
return s
}
default:
return s
}
s = s[:len(s)-size]
}
return s
}
// parseTarget extracts a target (scheme, host, port) from free text, supporting
// full URLs, IP[:port] and domain[:port]. ok=false when nothing parseable.
func parseTarget(text string) (scheme, host string, port int, ok bool) {
text = strings.TrimSpace(text)
if m := reURL.FindString(text); m != "" {
m = trimURLTail(m)
if u, err := url.Parse(m); err == nil && u.Hostname() != "" {
scheme = strings.ToLower(u.Scheme)
host = strings.ToLower(u.Hostname())
+6
View File
@@ -639,6 +639,12 @@ func writeTaskArchivePackage(path, payloadDir string, snapshot *pgdb.TaskArchive
log.Printf("[task-archive] skipping symlink (unsupported by the archive, other files unaffected): %s", current)
return nil
}
if !entry.IsDir() && !info.Mode().IsRegular() {
// A named pipe, socket or device left by a command: opening a pipe blocks until
// a writer appears, tar refuses a socket, and the unpacker refuses the rest.
log.Printf("[task-archive] skipping a file that is not regular (unsupported by the archive): %s", current)
return nil
}
header, err := tar.FileInfoHeader(info, "")
if err != nil {
return err
+70
View File
@@ -0,0 +1,70 @@
//go:build unix
package server
import (
"net"
"os"
"path/filepath"
"syscall"
"testing"
pgdb "github.com/Autumn-27/artex/db"
)
// A named pipe or a socket left in the task workspace by a command must not
// make the archive unrestorable, nor stop the task from being archived.
func TestTaskArchiveSkipsSpecialFiles(t *testing.T) {
// A short root: a socket path is limited to about 100 bytes.
dataDir, err := os.MkdirTemp("/tmp", "arch")
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { os.RemoveAll(dataDir) })
taskID := "42"
runDir := filepath.Join(dataDir, "tasks", taskID, "main")
if err := os.MkdirAll(runDir, 0o755); err != nil {
t.Fatal(err)
}
evidence := filepath.Join(runDir, "evidence.txt")
if err := os.WriteFile(evidence, []byte("task evidence"), 0o600); err != nil {
t.Fatal(err)
}
if err := syscall.Mkfifo(filepath.Join(runDir, "backpipe"), 0o600); err != nil {
t.Skipf("mkfifo: %v", err)
}
ln, err := net.Listen("unix", filepath.Join(runDir, "ctl.sock"))
if err != nil {
t.Skipf("unix socket: %v", err)
}
ln.(*net.UnixListener).SetUnlinkOnClose(false)
ln.Close()
stage, err := stageTaskArchiveFiles(dataDir, 1, taskID, 7)
if err != nil {
t.Fatal(err)
}
archivePath := taskArchivePath(dataDir, 1, taskID)
snapshot := &pgdb.TaskArchiveSnapshot{FormatVersion: pgdb.TaskArchiveFormatVersion, TaskID: 42, ExplorationID: 7}
_, _, checksum, err := writeTaskArchivePackage(archivePath, stage.payload, snapshot)
if err != nil {
t.Fatalf("the task could not be archived: %v", err)
}
if err := stage.commit(); err != nil {
t.Fatal(err)
}
extracted := filepath.Join(dataDir, "restore")
if err := extractTaskArchivePackage(archivePath, checksum, extracted); err != nil {
t.Fatalf("the archive of the task cannot be restored: %v", err)
}
installed, err := installTaskArchiveFiles(dataDir, extracted, taskID, 1, ExecPrivilege{})
if err != nil {
t.Fatal(err)
}
if err := installed.commit(); err != nil {
t.Fatal(err)
}
if got, err := os.ReadFile(evidence); err != nil || string(got) != "task evidence" {
t.Fatalf("restored %s = %q, %v", evidence, got, err)
}
}