Compare commits

...
Author SHA1 Message Date
BaaRai 507309c94d Merge pull request #888 from BaaRai/fix/web-auth-401-followup
fix(web): keep the session on auth 401s and pin the API tests
2026-12-03 02:28:46 +01:00
BaaRai 2f065a958e Merge pull request #882 from AdrianSantamariaR/claude/dropdown-close-form-focus-824957
fix(web): keep side-panel forms open when you close a dropdown
2026-12-03 02:11:27 +01:00
BaaRai 95afea7d5c Merge pull request #878 from thecorporatetractor/refactor/route-permissions
refactor(server): register API routes with a permission
2026-12-03 02:04:04 +01:00
AdrianSantamariaRandClaude Opus 5.5 5b711855a1 fix(web): treat an open Base UI Combobox as an open popup; test the guard
With the category Combobox of the New task sheet open, an overlay click
closed the whole sheet: isRadixOverlayOpenNow did not match the Base UI
popup, whose open state is data-open, not data-state. Add
[data-slot='combobox-content'][data-open] to the selector.

Add web/src/lib/utils.test.mjs, run by test:reducers: a DOM-free test of
preventDismissUnlessOverlayClick with a stub document, covering Select,
popper content, Combobox, menu triggers, the open sheet/dialog trigger
and an expanded Collapsible. The alias loader now adds the JSON import
attribute so tests can import modules that depend on @/i18n.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 00:47:42 +01:00
Marco Azarmaneche eb045647cf fix(server): apply the route permission and test the production chain
requirePerm now applies the recorded permission instead of only checking
that one exists: a perm.Authenticated pattern answers 401 without a valid
session. requireAuth exempts /api/auth/ by prefix, so a wildcard pattern
such as "GET /api/{kind}/items" would otherwise be public for
/api/auth/items.

Handler builds its chain with handlerFor, and TestUntaggedRouteIsForbidden
uses handlerFor, so removing requirePerm from the production chain fails
the test. A wildcard route is tested with a path under /api/auth/.

TestNoRawRouteRegistration allows only root.Handle("/api/", ...) and
root.HandleFunc("/", ...) in server.go; any other root route would skip
requireAuth.

TestHandlerDeniesAuthenticatedRoutesWithoutSession checks every
authenticated route through the real Handler.
2026-12-03 01:18:22 +02:00
Marco Azarmaneche fe121a2cea refactor(server): register API routes with a permission
Every /api route is now added with s.handle(mux, pattern, perm, h), which
records the permission the route needs. There are two permissions for now:
perm.Public for the routes requireAuth already exempts (/api/auth/*,
/api/health, /api/ready) and perm.Authenticated for all others.

A new check runs after requireAuth and answers 403 when the matched pattern
has no recorded permission, so a route added with a plain HandleFunc call is
denied instead of served. requireAuth itself is unchanged.

Tests check that every route has a permission, that the public routes are
exactly the ones requireAuth exempts, that no file registers a route outside
s.handle, and that an untagged route returns 403.
2026-12-03 01:12:39 +02:00
AdrianSantamariaRandClaude Opus 5.5 693825946e refactor(web): share the overlay-dismiss guard between Sheet and Dialog
SheetContent and DialogContent each carried a copy of the same
onInteractOutside guard, and losing one copy is how the Sheet guard
disappeared. Move it to preventDismissUnlessOverlayClick in lib/utils.ts
and call it from both. No behavior change.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 22:25:56 +01:00
AdrianSantamariaRandClaude Opus 5.5 611f232201 fix(web): let a sheet or dialog opened by its trigger close on overlay click
isRadixOverlayOpenNow treated any element with aria-expanded=true and
data-state=open as an open popover. The trigger of the open sheet or
dialog itself (aria-haspopup=dialog) and an expanded Collapsible match
that selector, so with the guard in place an overlay click never closed
a sheet or dialog that was opened through SheetTrigger/DialogTrigger
(Tasks category management, Agents create dialog). Count only triggers
that announce a non-dialog popup; popover content is still matched by
the Radix popper wrapper.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 22:21:05 +01:00
AdrianSantamariaRandClaude Opus 5.5 60eaf6719d fix(web): keep side-panel forms open when dismissing a dropdown
With a Select/Popover open inside a Sheet, any click (inside the form or
on the backdrop) closed the whole sheet and dropped unsaved input. The
onInteractOutside guard added in aef0376 was lost when 32ec7fe restored
the pre-fix sheet.tsx. Restore it, mirroring DialogContent: only a click
on the overlay with no popover open closes the sheet.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 22:21:05 +01:00
13 changed files with 778 additions and 324 deletions
+9 -8
View File
@@ -16,6 +16,7 @@ import (
"github.com/Autumn-27/artex/agent"
"github.com/Autumn-27/artex/db"
"github.com/Autumn-27/artex/evidence"
"github.com/Autumn-27/artex/server/perm"
actool "github.com/Autumn-27/norma/tool"
)
@@ -79,15 +80,15 @@ WHERE key=$1 AND system AND NOT(COALESCE(schema->'properties','{}'::jsonb) ? $2)
_ = s.m.pg.SetSetting(flag, "true")
}
func (s *Server) registerFindingTraffic(mux *http.ServeMux) {
func (s *Server) registerFindingTraffic(mux *apiMux) {
base := "/api/exploration/findings/{id}/traffic"
mux.HandleFunc("GET "+base, s.getFindingTraffic)
mux.HandleFunc("POST "+base, s.bindFindingTraffic)
mux.HandleFunc("PATCH "+base+"/{binding_id}", s.editFindingTraffic)
mux.HandleFunc("DELETE "+base+"/{binding_id}", s.editFindingTraffic)
mux.HandleFunc("PUT "+base+"/order", s.editFindingTraffic)
mux.HandleFunc("GET "+base+"/{binding_id}", s.getFindingTrafficDetail)
mux.HandleFunc("GET "+base+"/{binding_id}/body", s.getFindingTrafficBody)
s.handle(mux, "GET "+base, perm.Authenticated, s.getFindingTraffic)
s.handle(mux, "POST "+base, perm.Authenticated, s.bindFindingTraffic)
s.handle(mux, "PATCH "+base+"/{binding_id}", perm.Authenticated, s.editFindingTraffic)
s.handle(mux, "DELETE "+base+"/{binding_id}", perm.Authenticated, s.editFindingTraffic)
s.handle(mux, "PUT "+base+"/order", perm.Authenticated, s.editFindingTraffic)
s.handle(mux, "GET "+base+"/{binding_id}", perm.Authenticated, s.getFindingTrafficDetail)
s.handle(mux, "GET "+base+"/{binding_id}/body", perm.Authenticated, s.getFindingTrafficBody)
}
func evidenceError(w http.ResponseWriter, err error) {
+27
View File
@@ -0,0 +1,27 @@
// Package perm lists the permissions an API route can require.
//
// Every route is registered with one of them (Server.handle). For now there
// are only two: Public routes answer without a session, Authenticated routes
// need a valid session. Finer permissions come with user accounts and roles.
package perm
// Perm is the permission a route needs. The zero value means "not set", and
// a route without a permission is denied.
type Perm uint8
const (
// Public routes are served without a session (sign-in, health, ready).
Public Perm = iota + 1
// Authenticated routes need a valid session.
Authenticated
)
func (p Perm) String() string {
switch p {
case Public:
return "public"
case Authenticated:
return "authenticated"
}
return "none"
}
+58
View File
@@ -0,0 +1,58 @@
package server
import (
"net/http"
"github.com/Autumn-27/artex/server/perm"
)
// apiMux is the /api/ mux plus the permission recorded for each pattern.
// Routes are added with Server.handle. requirePerm applies the recorded
// permission and denies a pattern that has none, so a route added with a
// plain HandleFunc call answers 403 instead of being served.
type apiMux struct {
*http.ServeMux
perms map[string]perm.Perm
}
func newAPIMux() *apiMux {
return &apiMux{ServeMux: http.NewServeMux(), perms: map[string]perm.Perm{}}
}
// handle registers h for pattern and records the permission it needs.
func (s *Server) handle(mux *apiMux, pattern string, p perm.Perm, h http.HandlerFunc) {
if p == 0 {
panic("server: route " + pattern + " registered without a permission")
}
mux.perms[pattern] = p
mux.HandleFunc(pattern, h)
}
// requirePerm runs after requireAuth and applies the permission recorded for
// the pattern that would serve the request:
// - no recorded permission: 403, so a route added with a plain HandleFunc
// call is denied instead of served;
// - perm.Authenticated: 401 without a valid session. requireAuth exempts
// paths by prefix (/api/auth/...), and a wildcard pattern such as
// "GET /api/{kind}/items" also matches /api/auth/items; this check keeps
// such a route behind a session.
//
// Requests that match no pattern (404, 405) go to the mux unchanged.
func (s *Server) requirePerm(mux *apiMux) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if _, pattern := mux.Handler(r); pattern != "" {
switch p := mux.perms[pattern]; p {
case perm.Public:
case perm.Authenticated:
if !s.sessionOK(extractToken(r)) {
writeErr(w, 401, "Unauthorized")
return
}
default:
writeErr(w, 403, "Forbidden")
return
}
}
mux.ServeHTTP(w, r)
})
}
+235
View File
@@ -0,0 +1,235 @@
package server
import (
"go/ast"
"go/parser"
"go/token"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"regexp"
"slices"
"strconv"
"strings"
"testing"
"github.com/Autumn-27/artex/server/perm"
)
// The routes requireAuth serves without a session. They must be exactly the
// routes tagged perm.Public.
var wantPublicRoutes = []string{
"GET /api/auth/status",
"POST /api/auth/init",
"POST /api/auth/login",
"POST /api/auth/change-password",
"GET /api/health",
"GET /api/ready",
}
// Every API route is registered with a permission, and the public ones are
// exactly the routes requireAuth exempts.
func TestEveryRouteHasPermission(t *testing.T) {
s := &Server{jwtKey: []byte("0123456789abcdef0123456789abcdef")}
mux := s.apiRoutes()
if len(mux.perms) < 250 {
t.Fatalf("only %d routes recorded; the route table looks incomplete", len(mux.perms))
}
var public []string
for pattern, p := range mux.perms {
switch p {
case perm.Public:
public = append(public, pattern)
case perm.Authenticated:
default:
t.Errorf("%s: unknown permission %v", pattern, p)
}
}
slices.Sort(public)
want := slices.Clone(wantPublicRoutes)
slices.Sort(want)
if !slices.Equal(public, want) {
t.Errorf("public routes = %v, want %v", public, want)
}
// requireAuth without a token: a route is served only if it is public.
wildcard := regexp.MustCompile(`\{[^}]*\}`)
h := s.requireAuth(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(204) }))
for pattern, p := range mux.perms {
method, path, ok := strings.Cut(pattern, " ")
if !ok {
t.Errorf("%s: pattern has no method", pattern)
continue
}
rec := httptest.NewRecorder()
h.ServeHTTP(rec, httptest.NewRequest(method, wildcard.ReplaceAllString(path, "x"), nil))
if exempt := rec.Code == 204; exempt != (p == perm.Public) {
t.Errorf("%s: requireAuth exempt=%v, but permission is %v", pattern, exempt, p)
}
}
}
// No file in the package registers an API route without Server.handle. The
// only allowed direct calls are the one inside handle and the two root mux
// routes that split /api/ from the web UI: root.Handle("/api/", ...) and
// root.HandleFunc("/", ...). Any other root route, such as
// root.HandleFunc("GET /api/leak", ...), would skip requireAuth.
func TestNoRawRouteRegistration(t *testing.T) {
files, err := filepath.Glob("*.go")
if err != nil {
t.Fatal(err)
}
fset := token.NewFileSet()
for _, name := range files {
if strings.HasSuffix(name, "_test.go") {
continue
}
src, err := os.ReadFile(name)
if err != nil {
t.Fatal(err)
}
f, err := parser.ParseFile(fset, name, src, 0)
if err != nil {
t.Fatal(err)
}
ast.Inspect(f, func(n ast.Node) bool {
call, ok := n.(*ast.CallExpr)
if !ok {
return true
}
sel, ok := call.Fun.(*ast.SelectorExpr)
if !ok || (sel.Sel.Name != "HandleFunc" && sel.Sel.Name != "Handle") {
return true
}
recv, _ := sel.X.(*ast.Ident)
switch {
case name == "routes.go" && recv != nil && recv.Name == "mux":
case name == "server.go" && recv != nil && recv.Name == "root" && rootRouteAllowed(sel.Sel.Name, call):
default:
t.Errorf("%s: raw %s call; register API routes with s.handle", fset.Position(call.Pos()), sel.Sel.Name)
}
return true
})
}
}
// rootRouteAllowed reports whether a root mux call registers one of the two
// allowed patterns.
func rootRouteAllowed(method string, call *ast.CallExpr) bool {
if len(call.Args) == 0 {
return false
}
lit, ok := call.Args[0].(*ast.BasicLit)
if !ok || lit.Kind != token.STRING {
return false
}
pattern, err := strconv.Unquote(lit.Value)
if err != nil {
return false
}
return (method == "Handle" && pattern == "/api/") || (method == "HandleFunc" && pattern == "/")
}
// The real handler answers 401 without a session for every authenticated
// route, so the permission check is part of the production chain.
func TestHandlerDeniesAuthenticatedRoutesWithoutSession(t *testing.T) {
s := &Server{jwtKey: []byte("0123456789abcdef0123456789abcdef")}
h := s.Handler()
wildcard := regexp.MustCompile(`\{[^}]*\}`)
for pattern, p := range s.apiRoutes().perms {
if p != perm.Authenticated {
continue
}
method, path, _ := strings.Cut(pattern, " ")
rec := httptest.NewRecorder()
h.ServeHTTP(rec, httptest.NewRequest(method, wildcard.ReplaceAllString(path, "x"), nil))
if rec.Code != 401 {
t.Errorf("%s without a session: status %d, want 401", pattern, rec.Code)
}
}
}
// A route added to the mux without a permission is denied with 403, even
// with a valid session, and an authenticated route needs a session even when
// its path falls under the /api/auth/ prefix that requireAuth exempts.
// Unknown paths and methods behave as before. The routes go through
// handlerFor, the same chain Handler builds.
func TestUntaggedRouteIsForbidden(t *testing.T) {
s := &Server{jwtKey: []byte("0123456789abcdef0123456789abcdef")}
tok, err := signJWT(s.jwtKey)
if err != nil {
t.Fatal(err)
}
mux := newAPIMux()
s.handle(mux, "GET /api/tagged", perm.Authenticated, func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(204) })
s.handle(mux, "GET /api/auth/open", perm.Public, func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(204) })
reached := false
mux.HandleFunc("GET /api/untagged/{id}", func(w http.ResponseWriter, _ *http.Request) {
reached = true
w.WriteHeader(204)
})
mux.HandleFunc("GET /api/auth/untagged", func(w http.ResponseWriter, _ *http.Request) {
reached = true
w.WriteHeader(204)
})
wildcardReached := false
s.handle(mux, "GET /api/{kind}/items/list", perm.Authenticated, func(w http.ResponseWriter, _ *http.Request) {
wildcardReached = true
w.WriteHeader(204)
})
h := s.handlerFor(mux)
for _, tc := range []struct {
method, path string
bearer bool
want int
}{
{"GET", "/api/tagged", true, 204},
{"GET", "/api/tagged", false, 401},
{"GET", "/api/auth/open", false, 204},
{"GET", "/api/untagged/1", true, 403},
{"GET", "/api/untagged/1", false, 401},
{"GET", "/api/auth/untagged", false, 403},
{"GET", "/api/missing", true, 404},
{"POST", "/api/tagged", true, 405},
{"GET", "/api//tagged", true, 307}, // the mux's own path clean-up redirect, as before
} {
reached = false
r := httptest.NewRequest(tc.method, tc.path, nil)
if tc.bearer {
r.Header.Set("Authorization", "Bearer "+tok)
}
rec := httptest.NewRecorder()
h.ServeHTTP(rec, r)
if rec.Code != tc.want || reached {
t.Errorf("%s %s bearer=%v: status=%d reached=%v, want %d", tc.method, tc.path, tc.bearer, rec.Code, reached, tc.want)
}
}
// "GET /api/{kind}/items/list" matches /api/auth/items/list, which requireAuth
// exempts by prefix. The recorded permission still requires a session.
for _, tc := range []struct {
bearer bool
want int
}{{false, 401}, {true, 204}} {
wildcardReached = false
r := httptest.NewRequest("GET", "/api/auth/items/list", nil)
if tc.bearer {
r.Header.Set("Authorization", "Bearer "+tok)
}
rec := httptest.NewRecorder()
h.ServeHTTP(rec, r)
if rec.Code != tc.want || wildcardReached != tc.bearer {
t.Errorf("GET /api/auth/items/list bearer=%v: status=%d reached=%v, want %d", tc.bearer, rec.Code, wildcardReached, tc.want)
}
}
}
func TestHandleWithoutPermissionPanics(t *testing.T) {
defer func() {
if recover() == nil {
t.Fatal("handle with a zero permission did not panic")
}
}()
(&Server{}).handle(newAPIMux(), "GET /api/x", 0, func(http.ResponseWriter, *http.Request) {})
}
+303 -289
View File
@@ -33,6 +33,7 @@ import (
"github.com/Autumn-27/artex/llmpool"
"github.com/Autumn-27/artex/llmrec"
"github.com/Autumn-27/artex/report"
"github.com/Autumn-27/artex/server/perm"
"github.com/Autumn-27/artex/traffic"
"github.com/Autumn-27/norma/llm"
actool "github.com/Autumn-27/norma/tool"
@@ -802,339 +803,352 @@ func (s *Server) chatAgentRef() *agent.ChatAgent {
return s.chatAgent
}
func (s *Server) Handler() http.Handler {
mux := http.NewServeMux()
// apiRoutes builds the /api/ mux with every API route and its permission.
func (s *Server) apiRoutes() *apiMux {
mux := newAPIMux()
s.registerSideRoutes(mux)
s.registerSharedBrowserRoutes(mux)
// Auth routes — exempt from JWT check (handled in requireAuth)
mux.HandleFunc("GET /api/auth/status", s.authStatus)
mux.HandleFunc("POST /api/auth/init", s.authInit)
mux.HandleFunc("POST /api/auth/login", s.authLogin)
mux.HandleFunc("POST /api/auth/change-password", s.authChangePassword)
s.handle(mux, "GET /api/auth/status", perm.Public, s.authStatus)
s.handle(mux, "POST /api/auth/init", perm.Public, s.authInit)
s.handle(mux, "POST /api/auth/login", perm.Public, s.authLogin)
s.handle(mux, "POST /api/auth/change-password", perm.Public, s.authChangePassword)
mux.HandleFunc("GET /api/health", s.health)
mux.HandleFunc("GET /api/ready", s.ready)
mux.HandleFunc("GET /api/stats", s.stats)
mux.HandleFunc("GET /api/logs", s.getLogs)
mux.HandleFunc("GET /api/logs/history", s.getLogsHistory)
mux.HandleFunc("GET /api/logs/stream", s.streamLogs)
s.handle(mux, "GET /api/health", perm.Public, s.health)
s.handle(mux, "GET /api/ready", perm.Public, s.ready)
s.handle(mux, "GET /api/stats", perm.Authenticated, s.stats)
s.handle(mux, "GET /api/logs", perm.Authenticated, s.getLogs)
s.handle(mux, "GET /api/logs/history", perm.Authenticated, s.getLogsHistory)
s.handle(mux, "GET /api/logs/stream", perm.Authenticated, s.streamLogs)
mux.HandleFunc("GET /api/tasks", s.listTasks)
mux.HandleFunc("POST /api/tasks", s.createTask)
mux.HandleFunc("GET /api/skill-gaps", s.skillGaps)
mux.HandleFunc("GET /api/task-categories", s.pgListTaskCategories)
mux.HandleFunc("POST /api/task-categories", s.pgCreateTaskCategory)
mux.HandleFunc("PATCH /api/task-categories/{id}", s.pgRenameTaskCategory)
mux.HandleFunc("DELETE /api/task-categories/{id}", s.pgDeleteTaskCategory)
mux.HandleFunc("POST /api/tasks/category/batch", s.updateTasksCategoryBatch)
mux.HandleFunc("GET /api/task-templates", s.pgListTaskTemplates)
mux.HandleFunc("POST /api/task-templates", s.pgCreateTaskTemplate)
mux.HandleFunc("PATCH /api/task-templates/{id}", s.pgUpdateTaskTemplate)
mux.HandleFunc("DELETE /api/task-templates/{id}", s.pgDeleteTaskTemplate)
mux.HandleFunc("GET /api/tasks/{id}", s.getTask)
mux.HandleFunc("GET /api/tasks/{id}/outcome", s.taskOutcome)
mux.HandleFunc("GET /api/tasks/{id}/lessons", s.taskLessons)
mux.HandleFunc("POST /api/tasks/{id}/lessons/extract", s.extractTaskLessons)
mux.HandleFunc("PATCH /api/tasks/{id}", s.updateTaskMetadata)
mux.HandleFunc("PATCH /api/tasks/{id}/category", s.updateTaskCategory)
s.handle(mux, "GET /api/tasks", perm.Authenticated, s.listTasks)
s.handle(mux, "POST /api/tasks", perm.Authenticated, s.createTask)
s.handle(mux, "GET /api/skill-gaps", perm.Authenticated, s.skillGaps)
s.handle(mux, "GET /api/task-categories", perm.Authenticated, s.pgListTaskCategories)
s.handle(mux, "POST /api/task-categories", perm.Authenticated, s.pgCreateTaskCategory)
s.handle(mux, "PATCH /api/task-categories/{id}", perm.Authenticated, s.pgRenameTaskCategory)
s.handle(mux, "DELETE /api/task-categories/{id}", perm.Authenticated, s.pgDeleteTaskCategory)
s.handle(mux, "POST /api/tasks/category/batch", perm.Authenticated, s.updateTasksCategoryBatch)
s.handle(mux, "GET /api/task-templates", perm.Authenticated, s.pgListTaskTemplates)
s.handle(mux, "POST /api/task-templates", perm.Authenticated, s.pgCreateTaskTemplate)
s.handle(mux, "PATCH /api/task-templates/{id}", perm.Authenticated, s.pgUpdateTaskTemplate)
s.handle(mux, "DELETE /api/task-templates/{id}", perm.Authenticated, s.pgDeleteTaskTemplate)
s.handle(mux, "GET /api/tasks/{id}", perm.Authenticated, s.getTask)
s.handle(mux, "GET /api/tasks/{id}/outcome", perm.Authenticated, s.taskOutcome)
s.handle(mux, "GET /api/tasks/{id}/lessons", perm.Authenticated, s.taskLessons)
s.handle(mux, "POST /api/tasks/{id}/lessons/extract", perm.Authenticated, s.extractTaskLessons)
s.handle(mux, "PATCH /api/tasks/{id}", perm.Authenticated, s.updateTaskMetadata)
s.handle(mux, "PATCH /api/tasks/{id}/category", perm.Authenticated, s.updateTaskCategory)
// task-level asset interception/allow rules
mux.HandleFunc("GET /api/tasks/{id}/intercept-rules", s.taskInterceptListRules)
mux.HandleFunc("POST /api/tasks/{id}/intercept-rules", s.taskInterceptCreateRule)
mux.HandleFunc("PUT /api/tasks/{id}/intercept-rules/{rid}", s.taskInterceptUpdateRule)
mux.HandleFunc("DELETE /api/tasks/{id}/intercept-rules/{rid}", s.taskInterceptDeleteRule)
mux.HandleFunc("POST /api/tasks/{id}/intercept-rules/{rid}/toggle", s.taskInterceptToggleRule)
mux.HandleFunc("GET /api/tasks/{id}/target-pins", s.taskListTargetPins)
mux.HandleFunc("POST /api/tasks/{id}/target-pins/{pid}/revoke", s.taskRevokeTargetPin)
mux.HandleFunc("POST /api/tasks/control/batch", s.controlTasksBatch)
mux.HandleFunc("GET /api/task-archives", s.listTaskArchives)
mux.HandleFunc("GET /api/task-archives/{id}", s.getTaskArchive)
mux.HandleFunc("GET /api/tasks/{id}/credentials", s.listTaskCredentials)
mux.HandleFunc("POST /api/tasks/{id}/credentials", s.addTaskCredential)
mux.HandleFunc("DELETE /api/tasks/{id}/credentials/{cid}", s.deleteTaskCredential)
mux.HandleFunc("POST /api/tasks/{id}/archive", s.queueTaskArchive)
mux.HandleFunc("POST /api/tasks/archive/batch", s.queueTaskArchivesBatch)
mux.HandleFunc("POST /api/task-archives/{id}/restore", s.queueTaskArchiveRestore)
mux.HandleFunc("POST /api/task-archives/restore/batch", s.restoreTaskArchivesBatch)
mux.HandleFunc("DELETE /api/task-archives/{id}", s.queueTaskArchiveDelete)
mux.HandleFunc("POST /api/task-archives/delete/batch", s.deleteTaskArchivesBatch)
mux.HandleFunc("GET /api/tasks/{id}/coverage", s.taskCoverage)
mux.HandleFunc("GET /api/tasks/{id}/coverage-graph", s.taskCoverageGraph)
mux.HandleFunc("GET /api/tasks/{id}/asset-refs", s.taskAssetRefs)
mux.HandleFunc("POST /api/tasks/{id}/assets", s.attachTaskAssets)
mux.HandleFunc("DELETE /api/tasks/{id}/assets/{assetID}", s.detachTaskAsset)
mux.HandleFunc("GET /api/tasks/{id}/intent-assets", s.taskIntentAssets)
s.handle(mux, "GET /api/tasks/{id}/intercept-rules", perm.Authenticated, s.taskInterceptListRules)
s.handle(mux, "POST /api/tasks/{id}/intercept-rules", perm.Authenticated, s.taskInterceptCreateRule)
s.handle(mux, "PUT /api/tasks/{id}/intercept-rules/{rid}", perm.Authenticated, s.taskInterceptUpdateRule)
s.handle(mux, "DELETE /api/tasks/{id}/intercept-rules/{rid}", perm.Authenticated, s.taskInterceptDeleteRule)
s.handle(mux, "POST /api/tasks/{id}/intercept-rules/{rid}/toggle", perm.Authenticated, s.taskInterceptToggleRule)
s.handle(mux, "GET /api/tasks/{id}/target-pins", perm.Authenticated, s.taskListTargetPins)
s.handle(mux, "POST /api/tasks/{id}/target-pins/{pid}/revoke", perm.Authenticated, s.taskRevokeTargetPin)
s.handle(mux, "POST /api/tasks/control/batch", perm.Authenticated, s.controlTasksBatch)
s.handle(mux, "GET /api/task-archives", perm.Authenticated, s.listTaskArchives)
s.handle(mux, "GET /api/task-archives/{id}", perm.Authenticated, s.getTaskArchive)
s.handle(mux, "GET /api/tasks/{id}/credentials", perm.Authenticated, s.listTaskCredentials)
s.handle(mux, "POST /api/tasks/{id}/credentials", perm.Authenticated, s.addTaskCredential)
s.handle(mux, "DELETE /api/tasks/{id}/credentials/{cid}", perm.Authenticated, s.deleteTaskCredential)
s.handle(mux, "POST /api/tasks/{id}/archive", perm.Authenticated, s.queueTaskArchive)
s.handle(mux, "POST /api/tasks/archive/batch", perm.Authenticated, s.queueTaskArchivesBatch)
s.handle(mux, "POST /api/task-archives/{id}/restore", perm.Authenticated, s.queueTaskArchiveRestore)
s.handle(mux, "POST /api/task-archives/restore/batch", perm.Authenticated, s.restoreTaskArchivesBatch)
s.handle(mux, "DELETE /api/task-archives/{id}", perm.Authenticated, s.queueTaskArchiveDelete)
s.handle(mux, "POST /api/task-archives/delete/batch", perm.Authenticated, s.deleteTaskArchivesBatch)
s.handle(mux, "GET /api/tasks/{id}/coverage", perm.Authenticated, s.taskCoverage)
s.handle(mux, "GET /api/tasks/{id}/coverage-graph", perm.Authenticated, s.taskCoverageGraph)
s.handle(mux, "GET /api/tasks/{id}/asset-refs", perm.Authenticated, s.taskAssetRefs)
s.handle(mux, "POST /api/tasks/{id}/assets", perm.Authenticated, s.attachTaskAssets)
s.handle(mux, "DELETE /api/tasks/{id}/assets/{assetID}", perm.Authenticated, s.detachTaskAsset)
s.handle(mux, "GET /api/tasks/{id}/intent-assets", perm.Authenticated, s.taskIntentAssets)
// workspace file manager (over workDir)
mux.HandleFunc("GET /api/workspace/list", s.wsList)
mux.HandleFunc("GET /api/workspace/read", s.wsRead)
mux.HandleFunc("POST /api/workspace/write", s.wsWrite)
mux.HandleFunc("POST /api/workspace/mkdir", s.wsMkdir)
mux.HandleFunc("DELETE /api/workspace/delete", s.wsDelete)
mux.HandleFunc("GET /api/workspace/download", s.wsDownload)
mux.HandleFunc("POST /api/workspace/upload", s.wsUpload)
mux.HandleFunc("GET /api/tasks/{id}/scope", s.taskScopeList)
mux.HandleFunc("POST /api/tasks/{id}/scope", s.taskScopeAdd)
mux.HandleFunc("DELETE /api/tasks/{id}/scope/{sid}", s.taskScopeDelete)
mux.HandleFunc("GET /api/tasks/{id}/goals", s.listGoals) // goal management: list all goals of this task
mux.HandleFunc("POST /api/tasks/{id}/goals", s.addGoal) // goal management: human-added goal (revives the task)
mux.HandleFunc("PATCH /api/tasks/{id}/goals/{gid}", s.editGoal) // goal management: edit a goal (revives the task)
mux.HandleFunc("DELETE /api/tasks/{id}/goals/{gid}", s.deleteGoal) // goal management: hard-delete a goal (no revival)
mux.HandleFunc("GET /api/tasks/{id}/constraints", s.listConstraints) // constraint management: list this task's operation constraints
mux.HandleFunc("POST /api/tasks/{id}/constraints", s.addConstraint) // constraint management: add a constraint (planner not notified)
mux.HandleFunc("PATCH /api/tasks/{id}/constraints/{cid}", s.editConstraint) // constraint management: edit a constraint
mux.HandleFunc("DELETE /api/tasks/{id}/constraints/{cid}", s.deleteConstraint) // constraint management: delete a constraint
mux.HandleFunc("POST /api/tasks/{id}/control", s.control)
mux.HandleFunc("POST /api/tasks/{id}/retarget", s.retargetTaskHandler)
mux.HandleFunc("POST /api/tasks/{id}/extend", s.extendTaskHandler)
mux.HandleFunc("PUT /api/tasks/{id}/llm", s.updateTaskLLMProfiles)
mux.HandleFunc("GET /api/tasks/{id}/llm/resolution", s.taskLLMResolutionHandler)
mux.HandleFunc("POST /api/tasks/{id}/intents/{iid}/control", s.controlIntent)
mux.HandleFunc("POST /api/tasks/{id}/intents/{iid}/messages", s.sendWorkerMessage)
mux.HandleFunc("POST /api/tasks/{id}/intents/{iid}/rerun", s.rerunIntent) // rerun one blocked/exhausted/stopped intent
mux.HandleFunc("POST /api/tasks/{id}/intents/rerun-blocked", s.rerunBlocked) // batch-rerun all blocked intents of this task
mux.HandleFunc("POST /api/active", s.setActive)
s.handle(mux, "GET /api/workspace/list", perm.Authenticated, s.wsList)
s.handle(mux, "GET /api/workspace/read", perm.Authenticated, s.wsRead)
s.handle(mux, "POST /api/workspace/write", perm.Authenticated, s.wsWrite)
s.handle(mux, "POST /api/workspace/mkdir", perm.Authenticated, s.wsMkdir)
s.handle(mux, "DELETE /api/workspace/delete", perm.Authenticated, s.wsDelete)
s.handle(mux, "GET /api/workspace/download", perm.Authenticated, s.wsDownload)
s.handle(mux, "POST /api/workspace/upload", perm.Authenticated, s.wsUpload)
s.handle(mux, "GET /api/tasks/{id}/scope", perm.Authenticated, s.taskScopeList)
s.handle(mux, "POST /api/tasks/{id}/scope", perm.Authenticated, s.taskScopeAdd)
s.handle(mux, "DELETE /api/tasks/{id}/scope/{sid}", perm.Authenticated, s.taskScopeDelete)
s.handle(mux, "GET /api/tasks/{id}/goals", perm.Authenticated, s.listGoals) // goal management: list all goals of this task
s.handle(mux, "POST /api/tasks/{id}/goals", perm.Authenticated, s.addGoal) // goal management: human-added goal (revives the task)
s.handle(mux, "PATCH /api/tasks/{id}/goals/{gid}", perm.Authenticated, s.editGoal) // goal management: edit a goal (revives the task)
s.handle(mux, "DELETE /api/tasks/{id}/goals/{gid}", perm.Authenticated, s.deleteGoal) // goal management: hard-delete a goal (no revival)
s.handle(mux, "GET /api/tasks/{id}/constraints", perm.Authenticated, s.listConstraints) // constraint management: list this task's operation constraints
s.handle(mux, "POST /api/tasks/{id}/constraints", perm.Authenticated, s.addConstraint) // constraint management: add a constraint (planner not notified)
s.handle(mux, "PATCH /api/tasks/{id}/constraints/{cid}", perm.Authenticated, s.editConstraint) // constraint management: edit a constraint
s.handle(mux, "DELETE /api/tasks/{id}/constraints/{cid}", perm.Authenticated, s.deleteConstraint) // constraint management: delete a constraint
s.handle(mux, "POST /api/tasks/{id}/control", perm.Authenticated, s.control)
s.handle(mux, "POST /api/tasks/{id}/retarget", perm.Authenticated, s.retargetTaskHandler)
s.handle(mux, "POST /api/tasks/{id}/extend", perm.Authenticated, s.extendTaskHandler)
s.handle(mux, "PUT /api/tasks/{id}/llm", perm.Authenticated, s.updateTaskLLMProfiles)
s.handle(mux, "GET /api/tasks/{id}/llm/resolution", perm.Authenticated, s.taskLLMResolutionHandler)
s.handle(mux, "POST /api/tasks/{id}/intents/{iid}/control", perm.Authenticated, s.controlIntent)
s.handle(mux, "POST /api/tasks/{id}/intents/{iid}/messages", perm.Authenticated, s.sendWorkerMessage)
s.handle(mux, "POST /api/tasks/{id}/intents/{iid}/rerun", perm.Authenticated, s.rerunIntent) // rerun one blocked/exhausted/stopped intent
s.handle(mux, "POST /api/tasks/{id}/intents/rerun-blocked", perm.Authenticated, s.rerunBlocked) // batch-rerun all blocked intents of this task
s.handle(mux, "POST /api/active", perm.Authenticated, s.setActive)
mux.HandleFunc("GET /api/llm", s.getLLM)
mux.HandleFunc("POST /api/llm", s.setLLM)
mux.HandleFunc("POST /api/llm/test", s.testLLM)
s.handle(mux, "GET /api/llm", perm.Authenticated, s.getLLM)
s.handle(mux, "POST /api/llm", perm.Authenticated, s.setLLM)
s.handle(mux, "POST /api/llm/test", perm.Authenticated, s.testLLM)
// asset system
mux.HandleFunc("GET /api/assets", s.listAssets)
mux.HandleFunc("GET /api/assets/counts", s.assetCounts)
mux.HandleFunc("POST /api/assets", s.insertAssets)
mux.HandleFunc("DELETE /api/assets", s.deleteAssets)
s.handle(mux, "GET /api/assets", perm.Authenticated, s.listAssets)
s.handle(mux, "GET /api/assets/counts", perm.Authenticated, s.assetCounts)
s.handle(mux, "POST /api/assets", perm.Authenticated, s.insertAssets)
s.handle(mux, "DELETE /api/assets", perm.Authenticated, s.deleteAssets)
// company system
mux.HandleFunc("GET /api/companies", s.listCompanies)
mux.HandleFunc("POST /api/companies", s.createCompany)
mux.HandleFunc("GET /api/companies/{id}", s.getCompany)
mux.HandleFunc("DELETE /api/companies/{id}", s.deleteCompany)
mux.HandleFunc("POST /api/companies/{id}/scope", s.addCompanyScope)
mux.HandleFunc("POST /api/companies/reattribute", s.reattribute)
s.handle(mux, "GET /api/companies", perm.Authenticated, s.listCompanies)
s.handle(mux, "POST /api/companies", perm.Authenticated, s.createCompany)
s.handle(mux, "GET /api/companies/{id}", perm.Authenticated, s.getCompany)
s.handle(mux, "DELETE /api/companies/{id}", perm.Authenticated, s.deleteCompany)
s.handle(mux, "POST /api/companies/{id}/scope", perm.Authenticated, s.addCompanyScope)
s.handle(mux, "POST /api/companies/reattribute", perm.Authenticated, s.reattribute)
mux.HandleFunc("GET /api/exploration/frontier", s.frontier)
mux.HandleFunc("GET /api/exploration/findings", s.findings)
mux.HandleFunc("GET /api/exploration/findings/groups", s.findingGroups)
mux.HandleFunc("GET /api/exploration/findings/asset-tree", s.findingAssetTree)
mux.HandleFunc("GET /api/exploration/findings/stats", s.findingStats)
mux.HandleFunc("GET /api/exploration/findings/export", s.findingsExport)
s.handle(mux, "GET /api/exploration/frontier", perm.Authenticated, s.frontier)
s.handle(mux, "GET /api/exploration/findings", perm.Authenticated, s.findings)
s.handle(mux, "GET /api/exploration/findings/groups", perm.Authenticated, s.findingGroups)
s.handle(mux, "GET /api/exploration/findings/asset-tree", perm.Authenticated, s.findingAssetTree)
s.handle(mux, "GET /api/exploration/findings/stats", perm.Authenticated, s.findingStats)
s.handle(mux, "GET /api/exploration/findings/export", perm.Authenticated, s.findingsExport)
s.registerFindingTraffic(mux)
mux.HandleFunc("GET /api/exploration/findings/{id}", s.getFinding)
mux.HandleFunc("GET /api/exploration/findings/{id}/lineage", s.findingLineage)
mux.HandleFunc("POST /api/exploration/findings/{id}/deepen", s.deepenFinding)
mux.HandleFunc("GET /api/exploration/findings/{id}/retests", s.listFindingRetests)
mux.HandleFunc("GET /api/exploration/findings/retests/active", s.listActiveFindingRetests)
mux.HandleFunc("POST /api/exploration/findings/{id}/retests", s.startFindingRetest)
mux.HandleFunc("PATCH /api/exploration/findings/{id}", s.patchFinding)
mux.HandleFunc("POST /api/exploration/findings/bulk-status", s.bulkPatchFindingStatus)
mux.HandleFunc("POST /api/exploration/findings/bulk-report-state", s.bulkPatchFindingReportState)
mux.HandleFunc("DELETE /api/exploration/findings/{id}", s.deleteFinding)
mux.HandleFunc("GET /api/exploration/intents", s.intents)
mux.HandleFunc("GET /api/exploration/graph", s.explorationGraph)
mux.HandleFunc("GET /api/exploration/nodes", s.explorationNodes)
mux.HandleFunc("GET /api/exploration/activity", s.activity)
mux.HandleFunc("GET /api/exploration/activity/history", s.activityHistory)
mux.HandleFunc("GET /api/exploration/main-sessions", s.mainSessions)
mux.HandleFunc("POST /api/exploration/main-session/new", s.newMainSession)
mux.HandleFunc("GET /api/exploration/activity/stream", s.streamActivity)
mux.HandleFunc("GET /api/exploration/activity/{seq}", s.activityDetail)
mux.HandleFunc("GET /api/exploration/tokens", s.tokenStats)
mux.HandleFunc("GET /api/tokens/daily", s.tokenDailyStats)
mux.HandleFunc("GET /api/tokens/conversations", s.conversationTokens)
mux.HandleFunc("GET /api/tokens/usage", s.pgUsageStats) // global llm_usage aggregation (new dashboard view)
s.handle(mux, "GET /api/exploration/findings/{id}", perm.Authenticated, s.getFinding)
s.handle(mux, "GET /api/exploration/findings/{id}/lineage", perm.Authenticated, s.findingLineage)
s.handle(mux, "POST /api/exploration/findings/{id}/deepen", perm.Authenticated, s.deepenFinding)
s.handle(mux, "GET /api/exploration/findings/{id}/retests", perm.Authenticated, s.listFindingRetests)
s.handle(mux, "GET /api/exploration/findings/retests/active", perm.Authenticated, s.listActiveFindingRetests)
s.handle(mux, "POST /api/exploration/findings/{id}/retests", perm.Authenticated, s.startFindingRetest)
s.handle(mux, "PATCH /api/exploration/findings/{id}", perm.Authenticated, s.patchFinding)
s.handle(mux, "POST /api/exploration/findings/bulk-status", perm.Authenticated, s.bulkPatchFindingStatus)
s.handle(mux, "POST /api/exploration/findings/bulk-report-state", perm.Authenticated, s.bulkPatchFindingReportState)
s.handle(mux, "DELETE /api/exploration/findings/{id}", perm.Authenticated, s.deleteFinding)
s.handle(mux, "GET /api/exploration/intents", perm.Authenticated, s.intents)
s.handle(mux, "GET /api/exploration/graph", perm.Authenticated, s.explorationGraph)
s.handle(mux, "GET /api/exploration/nodes", perm.Authenticated, s.explorationNodes)
s.handle(mux, "GET /api/exploration/activity", perm.Authenticated, s.activity)
s.handle(mux, "GET /api/exploration/activity/history", perm.Authenticated, s.activityHistory)
s.handle(mux, "GET /api/exploration/main-sessions", perm.Authenticated, s.mainSessions)
s.handle(mux, "POST /api/exploration/main-session/new", perm.Authenticated, s.newMainSession)
s.handle(mux, "GET /api/exploration/activity/stream", perm.Authenticated, s.streamActivity)
s.handle(mux, "GET /api/exploration/activity/{seq}", perm.Authenticated, s.activityDetail)
s.handle(mux, "GET /api/exploration/tokens", perm.Authenticated, s.tokenStats)
s.handle(mux, "GET /api/tokens/daily", perm.Authenticated, s.tokenDailyStats)
s.handle(mux, "GET /api/tokens/conversations", perm.Authenticated, s.conversationTokens)
s.handle(mux, "GET /api/tokens/usage", perm.Authenticated, s.pgUsageStats) // global llm_usage aggregation (new dashboard view)
mux.HandleFunc("GET /api/audit", s.getAudit)
mux.HandleFunc("POST /api/gc", s.gc)
mux.HandleFunc("GET /api/traffic", s.getTraffic)
mux.HandleFunc("GET /api/traffic/hosts", s.getTrafficHosts)
mux.HandleFunc("DELETE /api/traffic", s.deleteTraffic)
mux.HandleFunc("DELETE /api/traffic/hosts", s.deleteTrafficHosts)
mux.HandleFunc("DELETE /api/traffic/all", s.deleteAllTraffic)
mux.HandleFunc("GET /api/traffic/exchange", s.getTrafficExchange)
mux.HandleFunc("GET /api/traffic/stream", s.getTrafficStream)
mux.HandleFunc("GET /api/traffic/blob", s.getTrafficBlob)
mux.HandleFunc("POST /api/traffic/ingest", s.ingestTraffic)
mux.HandleFunc("POST /api/traffic/replay", s.replayTraffic)
mux.HandleFunc("POST /api/traffic/import/har", s.importTrafficHAR)
mux.HandleFunc("GET /api/traffic/export/har", s.exportTrafficHAR)
mux.HandleFunc("GET /api/commands", s.pgListCommands)
mux.HandleFunc("GET /api/commands/stats", s.pgToolStats) // aggregate call counts per tool
mux.HandleFunc("GET /api/llm/records", s.pgListLLMRecords)
mux.HandleFunc("GET /api/llm/context/summary", s.pgLLMContextSummary)
mux.HandleFunc("DELETE /api/llm/records", s.pgDeleteLLMRecords)
mux.HandleFunc("GET /api/llm/records/tasks", s.pgLLMTasks)
mux.HandleFunc("GET /api/llm/records/by-model", s.pgTokenByModel) // aggregate this task's token usage by model
mux.HandleFunc("GET /api/llm/records/{id}", s.pgGetLLMRecord)
mux.HandleFunc("GET /api/settings", s.getSettings)
mux.HandleFunc("PUT /api/settings", s.putSettings)
mux.HandleFunc("GET /api/settings/noise", s.noiseStatus) // current noise profile + per-host counters (no reset)
s.handle(mux, "GET /api/audit", perm.Authenticated, s.getAudit)
s.handle(mux, "POST /api/gc", perm.Authenticated, s.gc)
s.handle(mux, "GET /api/traffic", perm.Authenticated, s.getTraffic)
s.handle(mux, "GET /api/traffic/hosts", perm.Authenticated, s.getTrafficHosts)
s.handle(mux, "DELETE /api/traffic", perm.Authenticated, s.deleteTraffic)
s.handle(mux, "DELETE /api/traffic/hosts", perm.Authenticated, s.deleteTrafficHosts)
s.handle(mux, "DELETE /api/traffic/all", perm.Authenticated, s.deleteAllTraffic)
s.handle(mux, "GET /api/traffic/exchange", perm.Authenticated, s.getTrafficExchange)
s.handle(mux, "GET /api/traffic/stream", perm.Authenticated, s.getTrafficStream)
s.handle(mux, "GET /api/traffic/blob", perm.Authenticated, s.getTrafficBlob)
s.handle(mux, "POST /api/traffic/ingest", perm.Authenticated, s.ingestTraffic)
s.handle(mux, "POST /api/traffic/replay", perm.Authenticated, s.replayTraffic)
s.handle(mux, "POST /api/traffic/import/har", perm.Authenticated, s.importTrafficHAR)
s.handle(mux, "GET /api/traffic/export/har", perm.Authenticated, s.exportTrafficHAR)
s.handle(mux, "GET /api/commands", perm.Authenticated, s.pgListCommands)
s.handle(mux, "GET /api/commands/stats", perm.Authenticated, s.pgToolStats) // aggregate call counts per tool
s.handle(mux, "GET /api/llm/records", perm.Authenticated, s.pgListLLMRecords)
s.handle(mux, "GET /api/llm/context/summary", perm.Authenticated, s.pgLLMContextSummary)
s.handle(mux, "DELETE /api/llm/records", perm.Authenticated, s.pgDeleteLLMRecords)
s.handle(mux, "GET /api/llm/records/tasks", perm.Authenticated, s.pgLLMTasks)
s.handle(mux, "GET /api/llm/records/by-model", perm.Authenticated, s.pgTokenByModel) // aggregate this task's token usage by model
s.handle(mux, "GET /api/llm/records/{id}", perm.Authenticated, s.pgGetLLMRecord)
s.handle(mux, "GET /api/settings", perm.Authenticated, s.getSettings)
s.handle(mux, "PUT /api/settings", perm.Authenticated, s.putSettings)
s.handle(mux, "GET /api/settings/noise", perm.Authenticated, s.noiseStatus) // current noise profile + per-host counters (no reset)
// Vulnerability IM push. Channels are "multi-instance + per-instance filter rules" resources, so they get their own group of
// REST endpoints instead of being stuffed into the flat /api/settings key-value store.
mux.HandleFunc("GET /api/notify/meta", s.notifyMeta)
mux.HandleFunc("GET /api/notify/channels", s.notifyListChannels)
mux.HandleFunc("POST /api/notify/channels", s.notifyCreateChannel)
mux.HandleFunc("PATCH /api/notify/channels/{id}", s.notifyUpdateChannel)
mux.HandleFunc("DELETE /api/notify/channels/{id}", s.notifyDeleteChannel)
mux.HandleFunc("POST /api/notify/channels/{id}/test", s.notifyTestChannel)
mux.HandleFunc("GET /api/notify/deliveries", s.notifyListDeliveries)
mux.HandleFunc("POST /api/notify/deliveries/{id}/retry", s.notifyRetryDelivery)
s.handle(mux, "GET /api/notify/meta", perm.Authenticated, s.notifyMeta)
s.handle(mux, "GET /api/notify/channels", perm.Authenticated, s.notifyListChannels)
s.handle(mux, "POST /api/notify/channels", perm.Authenticated, s.notifyCreateChannel)
s.handle(mux, "PATCH /api/notify/channels/{id}", perm.Authenticated, s.notifyUpdateChannel)
s.handle(mux, "DELETE /api/notify/channels/{id}", perm.Authenticated, s.notifyDeleteChannel)
s.handle(mux, "POST /api/notify/channels/{id}/test", perm.Authenticated, s.notifyTestChannel)
s.handle(mux, "GET /api/notify/deliveries", perm.Authenticated, s.notifyListDeliveries)
s.handle(mux, "POST /api/notify/deliveries/{id}/retry", perm.Authenticated, s.notifyRetryDelivery)
// Inbound chat bridges, one per transport kind (telegram).
mux.HandleFunc("GET /api/chat-bridges", s.chatBridgeList)
mux.HandleFunc("PUT /api/chat-bridges/{kind}", s.chatBridgeSave)
mux.HandleFunc("POST /api/chat-bridges/{kind}/test", s.chatBridgeTest)
mux.HandleFunc("POST /api/settings/web-search/test", s.testWebSearch)
mux.HandleFunc("GET /api/report", s.getReport)
mux.HandleFunc("GET /api/chat/mentions", s.searchChatMentions)
mux.HandleFunc("POST /api/chat", s.chat)
mux.HandleFunc("POST /api/chat/upload", s.chatUpload) // upload method 1: files land in uploads/ under the conversation/task work dir
mux.HandleFunc("GET /api/tasks/{id}/chat/status", s.taskChatStatus)
mux.HandleFunc("POST /api/tasks/{id}/chat/stop", s.stopChat)
s.handle(mux, "GET /api/chat-bridges", perm.Authenticated, s.chatBridgeList)
s.handle(mux, "PUT /api/chat-bridges/{kind}", perm.Authenticated, s.chatBridgeSave)
s.handle(mux, "POST /api/chat-bridges/{kind}/test", perm.Authenticated, s.chatBridgeTest)
s.handle(mux, "POST /api/settings/web-search/test", perm.Authenticated, s.testWebSearch)
s.handle(mux, "GET /api/report", perm.Authenticated, s.getReport)
s.handle(mux, "GET /api/chat/mentions", perm.Authenticated, s.searchChatMentions)
s.handle(mux, "POST /api/chat", perm.Authenticated, s.chat)
s.handle(mux, "POST /api/chat/upload", perm.Authenticated, s.chatUpload) // upload method 1: files land in uploads/ under the conversation/task work dir
s.handle(mux, "GET /api/tasks/{id}/chat/status", perm.Authenticated, s.taskChatStatus)
s.handle(mux, "POST /api/tasks/{id}/chat/stop", perm.Authenticated, s.stopChat)
// --- Admin API (PostgreSQL data source; new database & admin console plan) ---
mux.HandleFunc("DELETE /api/tasks/{id}", s.pgDeleteTask)
s.handle(mux, "DELETE /api/tasks/{id}", perm.Authenticated, s.pgDeleteTask)
// Agents
// conversations (chat page)
mux.HandleFunc("GET /api/conversations", s.pgListConversations)
mux.HandleFunc("POST /api/conversations", s.pgCreateConversation)
mux.HandleFunc("POST /api/conversations/delete/batch", s.pgDeleteConversationsBatch)
mux.HandleFunc("PATCH /api/conversations/{id}", s.pgRenameConversation)
mux.HandleFunc("PATCH /api/conversations/{id}/profile", s.pgUpdateConversation)
mux.HandleFunc("DELETE /api/conversations/{id}", s.pgDeleteConversation)
mux.HandleFunc("GET /api/conversations/{id}/messages", s.pgConversationMessages)
mux.HandleFunc("POST /api/conversations/{id}/messages", s.pgSendConversationMessage)
mux.HandleFunc("POST /api/conversations/{id}/stop", s.pgStopConversation)
mux.HandleFunc("GET /api/conversations/{id}/messages/{seq}", s.pgConversationMsgDetail)
mux.HandleFunc("GET /api/conversations/{id}/target-pins", s.convListTargetPins)
mux.HandleFunc("POST /api/conversations/{id}/target-pins/{pid}/revoke", s.convRevokeTargetPin)
s.handle(mux, "GET /api/conversations", perm.Authenticated, s.pgListConversations)
s.handle(mux, "POST /api/conversations", perm.Authenticated, s.pgCreateConversation)
s.handle(mux, "POST /api/conversations/delete/batch", perm.Authenticated, s.pgDeleteConversationsBatch)
s.handle(mux, "PATCH /api/conversations/{id}", perm.Authenticated, s.pgRenameConversation)
s.handle(mux, "PATCH /api/conversations/{id}/profile", perm.Authenticated, s.pgUpdateConversation)
s.handle(mux, "DELETE /api/conversations/{id}", perm.Authenticated, s.pgDeleteConversation)
s.handle(mux, "GET /api/conversations/{id}/messages", perm.Authenticated, s.pgConversationMessages)
s.handle(mux, "POST /api/conversations/{id}/messages", perm.Authenticated, s.pgSendConversationMessage)
s.handle(mux, "POST /api/conversations/{id}/stop", perm.Authenticated, s.pgStopConversation)
s.handle(mux, "GET /api/conversations/{id}/messages/{seq}", perm.Authenticated, s.pgConversationMsgDetail)
s.handle(mux, "GET /api/conversations/{id}/target-pins", perm.Authenticated, s.convListTargetPins)
s.handle(mux, "POST /api/conversations/{id}/target-pins/{pid}/revoke", perm.Authenticated, s.convRevokeTargetPin)
mux.HandleFunc("GET /api/agents", s.pgListAgents)
mux.HandleFunc("POST /api/agents", s.pgCreateAgent)
mux.HandleFunc("GET /api/agents/{key}", s.pgGetAgent)
mux.HandleFunc("PATCH /api/agents/{key}", s.pgUpdateAgent)
mux.HandleFunc("DELETE /api/agents/{key}", s.pgDeleteAgent)
mux.HandleFunc("PUT /api/agents/{key}/config", s.pgSaveAgentConfig)
mux.HandleFunc("PUT /api/agents/{key}/prompt", s.pgSavePrompt)
mux.HandleFunc("POST /api/agents/{key}/prompt/reset", s.pgResetPrompt)
mux.HandleFunc("PUT /api/agents/{key}/wrapup", s.pgSaveWrapup)
mux.HandleFunc("POST /api/agents/{key}/wrapup/reset", s.pgResetWrapup)
mux.HandleFunc("PUT /api/agents/{key}/wrapup/task-timeout", s.pgSaveTaskTimeoutWrapup)
mux.HandleFunc("POST /api/agents/{key}/wrapup/task-timeout/reset", s.pgResetTaskTimeoutWrapup)
mux.HandleFunc("GET /api/agents/{key}/triggers", s.pgListTriggers)
mux.HandleFunc("POST /api/agents/{key}/triggers", s.pgCreateTrigger)
mux.HandleFunc("PATCH /api/triggers/{id}", s.pgUpdateTrigger)
mux.HandleFunc("DELETE /api/triggers/{id}", s.pgDeleteTrigger)
mux.HandleFunc("GET /api/agents/{key}/prompts", s.pgListPromptVersions)
mux.HandleFunc("GET /api/agents/{key}/variables", s.pgPromptVars)
mux.HandleFunc("POST /api/agents/{key}/prompt/preview", s.pgPreviewPrompt)
mux.HandleFunc("GET /api/agents/{key}/visibility", s.pgGetAgentVisibility)
mux.HandleFunc("PUT /api/agents/{key}/visibility", s.pgSetAgentVisibility)
s.handle(mux, "GET /api/agents", perm.Authenticated, s.pgListAgents)
s.handle(mux, "POST /api/agents", perm.Authenticated, s.pgCreateAgent)
s.handle(mux, "GET /api/agents/{key}", perm.Authenticated, s.pgGetAgent)
s.handle(mux, "PATCH /api/agents/{key}", perm.Authenticated, s.pgUpdateAgent)
s.handle(mux, "DELETE /api/agents/{key}", perm.Authenticated, s.pgDeleteAgent)
s.handle(mux, "PUT /api/agents/{key}/config", perm.Authenticated, s.pgSaveAgentConfig)
s.handle(mux, "PUT /api/agents/{key}/prompt", perm.Authenticated, s.pgSavePrompt)
s.handle(mux, "POST /api/agents/{key}/prompt/reset", perm.Authenticated, s.pgResetPrompt)
s.handle(mux, "PUT /api/agents/{key}/wrapup", perm.Authenticated, s.pgSaveWrapup)
s.handle(mux, "POST /api/agents/{key}/wrapup/reset", perm.Authenticated, s.pgResetWrapup)
s.handle(mux, "PUT /api/agents/{key}/wrapup/task-timeout", perm.Authenticated, s.pgSaveTaskTimeoutWrapup)
s.handle(mux, "POST /api/agents/{key}/wrapup/task-timeout/reset", perm.Authenticated, s.pgResetTaskTimeoutWrapup)
s.handle(mux, "GET /api/agents/{key}/triggers", perm.Authenticated, s.pgListTriggers)
s.handle(mux, "POST /api/agents/{key}/triggers", perm.Authenticated, s.pgCreateTrigger)
s.handle(mux, "PATCH /api/triggers/{id}", perm.Authenticated, s.pgUpdateTrigger)
s.handle(mux, "DELETE /api/triggers/{id}", perm.Authenticated, s.pgDeleteTrigger)
s.handle(mux, "GET /api/agents/{key}/prompts", perm.Authenticated, s.pgListPromptVersions)
s.handle(mux, "GET /api/agents/{key}/variables", perm.Authenticated, s.pgPromptVars)
s.handle(mux, "POST /api/agents/{key}/prompt/preview", perm.Authenticated, s.pgPreviewPrompt)
s.handle(mux, "GET /api/agents/{key}/visibility", perm.Authenticated, s.pgGetAgentVisibility)
s.handle(mux, "PUT /api/agents/{key}/visibility", perm.Authenticated, s.pgSetAgentVisibility)
// built-in tool catalog (description/param defaults editable, bound per agent; key and handler live in code)
mux.HandleFunc("GET /api/tools", s.pgListTools)
mux.HandleFunc("PUT /api/tools/{key}", s.pgUpdateTool)
mux.HandleFunc("POST /api/tools/custom", s.pgCreateCustomTool)
mux.HandleFunc("POST /api/tools/custom/test", s.pgTestCustomTool)
mux.HandleFunc("PUT /api/tools/custom/{key}", s.pgUpdateCustomTool)
mux.HandleFunc("DELETE /api/tools/custom/{key}", s.pgDeleteCustomTool)
mux.HandleFunc("POST /api/settings/python/detect", s.pgDetectPython)
mux.HandleFunc("POST /api/tools/{key}/reset", s.pgResetTool)
s.handle(mux, "GET /api/tools", perm.Authenticated, s.pgListTools)
s.handle(mux, "PUT /api/tools/{key}", perm.Authenticated, s.pgUpdateTool)
s.handle(mux, "POST /api/tools/custom", perm.Authenticated, s.pgCreateCustomTool)
s.handle(mux, "POST /api/tools/custom/test", perm.Authenticated, s.pgTestCustomTool)
s.handle(mux, "PUT /api/tools/custom/{key}", perm.Authenticated, s.pgUpdateCustomTool)
s.handle(mux, "DELETE /api/tools/custom/{key}", perm.Authenticated, s.pgDeleteCustomTool)
s.handle(mux, "POST /api/settings/python/detect", perm.Authenticated, s.pgDetectPython)
s.handle(mux, "POST /api/tools/{key}/reset", perm.Authenticated, s.pgResetTool)
// MCP CRUD
mux.HandleFunc("GET /api/mcp", s.pgListMCP)
mux.HandleFunc("POST /api/mcp", s.pgSaveMCP)
mux.HandleFunc("DELETE /api/mcp/{id}", s.pgDeleteMCP)
mux.HandleFunc("GET /api/mcp/{id}/tools", s.pgMCPTools)
mux.HandleFunc("POST /api/mcp/{id}/refresh", s.pgRefreshMCP)
s.handle(mux, "GET /api/mcp", perm.Authenticated, s.pgListMCP)
s.handle(mux, "POST /api/mcp", perm.Authenticated, s.pgSaveMCP)
s.handle(mux, "DELETE /api/mcp/{id}", perm.Authenticated, s.pgDeleteMCP)
s.handle(mux, "GET /api/mcp/{id}/tools", perm.Authenticated, s.pgMCPTools)
s.handle(mux, "POST /api/mcp/{id}/refresh", perm.Authenticated, s.pgRefreshMCP)
// asset sync — ScopeSentry data source
mux.HandleFunc("GET /api/sync/scopesentry/status", s.syncSSStatus)
mux.HandleFunc("POST /api/sync/scopesentry/datasource", s.syncSSDatasource)
mux.HandleFunc("GET /api/sync/scopesentry/projects", s.syncSSProjects)
mux.HandleFunc("GET /api/sync/scopesentry/tasks", s.syncSSTasks)
mux.HandleFunc("POST /api/sync/scopesentry/sync", s.syncSSRun)
s.handle(mux, "GET /api/sync/scopesentry/status", perm.Authenticated, s.syncSSStatus)
s.handle(mux, "POST /api/sync/scopesentry/datasource", perm.Authenticated, s.syncSSDatasource)
s.handle(mux, "GET /api/sync/scopesentry/projects", perm.Authenticated, s.syncSSProjects)
s.handle(mux, "GET /api/sync/scopesentry/tasks", perm.Authenticated, s.syncSSTasks)
s.handle(mux, "POST /api/sync/scopesentry/sync", perm.Authenticated, s.syncSSRun)
// Skill CRUD (filesystem)
mux.HandleFunc("GET /api/skills", s.fsListSkills)
mux.HandleFunc("POST /api/skills", s.fsCreateSkill)
mux.HandleFunc("POST /api/skills/upload", s.fsUploadSkill)
mux.HandleFunc("DELETE /api/skills/{name}", s.fsDeleteSkill)
mux.HandleFunc("GET /api/skills/missing", s.fsMissingSkills) // names of skills that were invoked but do not exist
mux.HandleFunc("GET /api/skills/{name}/usage", s.fsSkillUsage) // recent invocations of one skill
mux.HandleFunc("PUT /api/skills/{name}/meta", s.fsUpdateSkillMeta)
mux.HandleFunc("POST /api/skills/{name}/dirs", s.fsCreateDir)
mux.HandleFunc("GET /api/skills/{name}/files", s.fsListFiles)
s.handle(mux, "GET /api/skills", perm.Authenticated, s.fsListSkills)
s.handle(mux, "POST /api/skills", perm.Authenticated, s.fsCreateSkill)
s.handle(mux, "POST /api/skills/upload", perm.Authenticated, s.fsUploadSkill)
s.handle(mux, "DELETE /api/skills/{name}", perm.Authenticated, s.fsDeleteSkill)
s.handle(mux, "GET /api/skills/missing", perm.Authenticated, s.fsMissingSkills) // names of skills that were invoked but do not exist
s.handle(mux, "GET /api/skills/{name}/usage", perm.Authenticated, s.fsSkillUsage) // recent invocations of one skill
s.handle(mux, "PUT /api/skills/{name}/meta", perm.Authenticated, s.fsUpdateSkillMeta)
s.handle(mux, "POST /api/skills/{name}/dirs", perm.Authenticated, s.fsCreateDir)
s.handle(mux, "GET /api/skills/{name}/files", perm.Authenticated, s.fsListFiles)
// {file...} captures path segments including slashes (e.g. scripts/extract.py)
mux.HandleFunc("GET /api/skills/{name}/files/{file...}", s.fsReadFile)
mux.HandleFunc("PUT /api/skills/{name}/files/{file...}", s.fsWriteFile)
mux.HandleFunc("DELETE /api/skills/{name}/files/{file...}", s.fsDeletePath)
s.handle(mux, "GET /api/skills/{name}/files/{file...}", perm.Authenticated, s.fsReadFile)
s.handle(mux, "PUT /api/skills/{name}/files/{file...}", perm.Authenticated, s.fsWriteFile)
s.handle(mux, "DELETE /api/skills/{name}/files/{file...}", perm.Authenticated, s.fsDeletePath)
// MCP resource-side visibility (more specific skill routes match first)
mux.HandleFunc("GET /api/visibility/{kind}/{id}", s.pgResourceVisibility)
mux.HandleFunc("POST /api/visibility/toggle", s.pgToggleVisibility)
s.handle(mux, "GET /api/visibility/{kind}/{id}", perm.Authenticated, s.pgResourceVisibility)
s.handle(mux, "POST /api/visibility/toggle", perm.Authenticated, s.pgToggleVisibility)
// Skill visibility (by name, more specific, takes priority over the wildcard routes above)
mux.HandleFunc("GET /api/visibility/skill/{name}", s.pgSkillVisibility)
mux.HandleFunc("POST /api/visibility/skill/toggle", s.pgToggleSkillVisibility)
s.handle(mux, "GET /api/visibility/skill/{name}", perm.Authenticated, s.pgSkillVisibility)
s.handle(mux, "POST /api/visibility/skill/toggle", perm.Authenticated, s.pgToggleSkillVisibility)
// LLM multi-profile
mux.HandleFunc("GET /api/llm/profiles", s.pgListProfiles)
mux.HandleFunc("POST /api/llm/profiles", s.pgSaveProfile)
mux.HandleFunc("DELETE /api/llm/profiles/{id}", s.pgDeleteProfile)
mux.HandleFunc("POST /api/llm/profiles/active", s.pgActivateProfile)
mux.HandleFunc("GET /api/llm/retry-policy", s.pgGetLLMRetryPolicy)
mux.HandleFunc("POST /api/llm/retry-policy", s.pgSaveLLMRetryPolicy)
mux.HandleFunc("GET /api/llm/pool", s.pgLLMPoolStatus)
mux.HandleFunc("POST /api/llm/pool/reset", s.pgLLMPoolReset)
mux.HandleFunc("POST /api/llm/models", s.pgListModels)
s.handle(mux, "GET /api/llm/profiles", perm.Authenticated, s.pgListProfiles)
s.handle(mux, "POST /api/llm/profiles", perm.Authenticated, s.pgSaveProfile)
s.handle(mux, "DELETE /api/llm/profiles/{id}", perm.Authenticated, s.pgDeleteProfile)
s.handle(mux, "POST /api/llm/profiles/active", perm.Authenticated, s.pgActivateProfile)
s.handle(mux, "GET /api/llm/retry-policy", perm.Authenticated, s.pgGetLLMRetryPolicy)
s.handle(mux, "POST /api/llm/retry-policy", perm.Authenticated, s.pgSaveLLMRetryPolicy)
s.handle(mux, "GET /api/llm/pool", perm.Authenticated, s.pgLLMPoolStatus)
s.handle(mux, "POST /api/llm/pool/reset", perm.Authenticated, s.pgLLMPoolReset)
s.handle(mux, "POST /api/llm/models", perm.Authenticated, s.pgListModels)
// interception rule management
mux.HandleFunc("GET /api/intercept/rules", s.interceptListRules)
mux.HandleFunc("POST /api/intercept/rules", s.interceptCreateRule)
mux.HandleFunc("PUT /api/intercept/rules/{id}", s.interceptUpdateRule)
mux.HandleFunc("DELETE /api/intercept/rules/{id}", s.interceptDeleteRule)
mux.HandleFunc("POST /api/intercept/rules/{id}/toggle", s.interceptToggleRule)
s.handle(mux, "GET /api/intercept/rules", perm.Authenticated, s.interceptListRules)
s.handle(mux, "POST /api/intercept/rules", perm.Authenticated, s.interceptCreateRule)
s.handle(mux, "PUT /api/intercept/rules/{id}", perm.Authenticated, s.interceptUpdateRule)
s.handle(mux, "DELETE /api/intercept/rules/{id}", perm.Authenticated, s.interceptDeleteRule)
s.handle(mux, "POST /api/intercept/rules/{id}/toggle", perm.Authenticated, s.interceptToggleRule)
// capture-proxy rewrite rule management (stored and compiled; not applied by the proxy yet)
mux.HandleFunc("GET /api/traffic/rewrite-rules", s.rewriteListRules)
mux.HandleFunc("POST /api/traffic/rewrite-rules", s.rewriteCreateRule)
mux.HandleFunc("PUT /api/traffic/rewrite-rules/{id}", s.rewriteUpdateRule)
mux.HandleFunc("DELETE /api/traffic/rewrite-rules/{id}", s.rewriteDeleteRule)
mux.HandleFunc("POST /api/traffic/rewrite-rules/{id}/toggle", s.rewriteToggleRule)
s.handle(mux, "GET /api/traffic/rewrite-rules", perm.Authenticated, s.rewriteListRules)
s.handle(mux, "POST /api/traffic/rewrite-rules", perm.Authenticated, s.rewriteCreateRule)
s.handle(mux, "PUT /api/traffic/rewrite-rules/{id}", perm.Authenticated, s.rewriteUpdateRule)
s.handle(mux, "DELETE /api/traffic/rewrite-rules/{id}", perm.Authenticated, s.rewriteDeleteRule)
s.handle(mux, "POST /api/traffic/rewrite-rules/{id}/toggle", perm.Authenticated, s.rewriteToggleRule)
// capture-proxy constrained Go tampering hooks (P4.2, operator-only, opt-in via ARTEX_TAMPER_HOOKS_ENABLED)
mux.HandleFunc("GET /api/traffic/hooks", s.tamperListHooks)
mux.HandleFunc("POST /api/traffic/hooks", s.tamperCreateHook)
mux.HandleFunc("PUT /api/traffic/hooks/{id}", s.tamperUpdateHook)
mux.HandleFunc("DELETE /api/traffic/hooks/{id}", s.tamperDeleteHook)
mux.HandleFunc("POST /api/traffic/hooks/{id}/toggle", s.tamperToggleHook)
mux.HandleFunc("GET /api/traffic/hooks/{id}/versions", s.tamperListHookVersions)
mux.HandleFunc("POST /api/traffic/hooks/{id}/rollback", s.tamperRollbackHook)
mux.HandleFunc("POST /api/traffic/hooks/dry-run", s.tamperDryRunHook)
s.handle(mux, "GET /api/traffic/hooks", perm.Authenticated, s.tamperListHooks)
s.handle(mux, "POST /api/traffic/hooks", perm.Authenticated, s.tamperCreateHook)
s.handle(mux, "PUT /api/traffic/hooks/{id}", perm.Authenticated, s.tamperUpdateHook)
s.handle(mux, "DELETE /api/traffic/hooks/{id}", perm.Authenticated, s.tamperDeleteHook)
s.handle(mux, "POST /api/traffic/hooks/{id}/toggle", perm.Authenticated, s.tamperToggleHook)
s.handle(mux, "GET /api/traffic/hooks/{id}/versions", perm.Authenticated, s.tamperListHookVersions)
s.handle(mux, "POST /api/traffic/hooks/{id}/rollback", perm.Authenticated, s.tamperRollbackHook)
s.handle(mux, "POST /api/traffic/hooks/dry-run", perm.Authenticated, s.tamperDryRunHook)
// asset interception rule management (global blocklist: domains/IPs/URLs/CIDRs)
mux.HandleFunc("GET /api/asset-intercept/rules", s.assetInterceptListRules)
mux.HandleFunc("POST /api/asset-intercept/rules", s.assetInterceptCreateRule)
mux.HandleFunc("PUT /api/asset-intercept/rules/{id}", s.assetInterceptUpdateRule)
mux.HandleFunc("DELETE /api/asset-intercept/rules/{id}", s.assetInterceptDeleteRule)
mux.HandleFunc("POST /api/asset-intercept/rules/{id}/toggle", s.assetInterceptToggleRule)
s.handle(mux, "GET /api/asset-intercept/rules", perm.Authenticated, s.assetInterceptListRules)
s.handle(mux, "POST /api/asset-intercept/rules", perm.Authenticated, s.assetInterceptCreateRule)
s.handle(mux, "PUT /api/asset-intercept/rules/{id}", perm.Authenticated, s.assetInterceptUpdateRule)
s.handle(mux, "DELETE /api/asset-intercept/rules/{id}", perm.Authenticated, s.assetInterceptDeleteRule)
s.handle(mux, "POST /api/asset-intercept/rules/{id}/toggle", perm.Authenticated, s.assetInterceptToggleRule)
mux.HandleFunc("GET /api/intercept/pending", s.interceptListPending)
mux.HandleFunc("GET /api/intercept/pending/{id}", s.interceptGetOne)
mux.HandleFunc("POST /api/intercept/pending/{id}/decide", s.interceptDecide)
mux.HandleFunc("POST /api/intercept/pending/batch-decide", s.interceptBatchDecide)
mux.HandleFunc("POST /api/intercept/pending/{id}/always-allow", s.interceptAlwaysAllow) // creates an argv allow rule; the request stays pending
mux.HandleFunc("GET /api/intercept/history", s.interceptHistory)
mux.HandleFunc("GET /api/intercept/history/{id}", s.interceptDetail)
mux.HandleFunc("GET /api/intercept/history/{id}/execution", s.interceptExecution)
mux.HandleFunc("GET /api/intercept/task/{taskID}", s.interceptListTaskItems)
mux.HandleFunc("GET /api/intercept/task/{taskID}/pending-summary", s.interceptTaskPendingSummary)
mux.HandleFunc("GET /api/intercept/tool-config", s.interceptGetToolConfig)
mux.HandleFunc("PUT /api/intercept/tool-config", s.interceptSetToolConfig)
mux.HandleFunc("GET /api/target-gate/exemptions", s.targetGateGetExemptions)
mux.HandleFunc("PUT /api/target-gate/exemptions", s.targetGateSetExemptions)
mux.HandleFunc("GET /api/target-gate/exemptions/history", s.targetGateExemptionHistory)
mux.HandleFunc("GET /api/intercept/judge", s.interceptGetJudgeConfig)
mux.HandleFunc("PUT /api/intercept/judge", s.interceptSetJudgeConfig)
mux.HandleFunc("GET /api/intercept/judge/usage", s.interceptJudgeUsage) // cumulative token usage of fallback approval
s.handle(mux, "GET /api/intercept/pending", perm.Authenticated, s.interceptListPending)
s.handle(mux, "GET /api/intercept/pending/{id}", perm.Authenticated, s.interceptGetOne)
s.handle(mux, "POST /api/intercept/pending/{id}/decide", perm.Authenticated, s.interceptDecide)
s.handle(mux, "POST /api/intercept/pending/batch-decide", perm.Authenticated, s.interceptBatchDecide)
s.handle(mux, "POST /api/intercept/pending/{id}/always-allow", perm.Authenticated, s.interceptAlwaysAllow) // creates an argv allow rule; the request stays pending
s.handle(mux, "GET /api/intercept/history", perm.Authenticated, s.interceptHistory)
s.handle(mux, "GET /api/intercept/history/{id}", perm.Authenticated, s.interceptDetail)
s.handle(mux, "GET /api/intercept/history/{id}/execution", perm.Authenticated, s.interceptExecution)
s.handle(mux, "GET /api/intercept/task/{taskID}", perm.Authenticated, s.interceptListTaskItems)
s.handle(mux, "GET /api/intercept/task/{taskID}/pending-summary", perm.Authenticated, s.interceptTaskPendingSummary)
s.handle(mux, "GET /api/intercept/tool-config", perm.Authenticated, s.interceptGetToolConfig)
s.handle(mux, "PUT /api/intercept/tool-config", perm.Authenticated, s.interceptSetToolConfig)
s.handle(mux, "GET /api/target-gate/exemptions", perm.Authenticated, s.targetGateGetExemptions)
s.handle(mux, "PUT /api/target-gate/exemptions", perm.Authenticated, s.targetGateSetExemptions)
s.handle(mux, "GET /api/target-gate/exemptions/history", perm.Authenticated, s.targetGateExemptionHistory)
s.handle(mux, "GET /api/intercept/judge", perm.Authenticated, s.interceptGetJudgeConfig)
s.handle(mux, "PUT /api/intercept/judge", perm.Authenticated, s.interceptSetJudgeConfig)
s.handle(mux, "GET /api/intercept/judge/usage", perm.Authenticated, s.interceptJudgeUsage) // cumulative token usage of fallback approval
// /api/* goes through CORS + JWT; everything else is served by the embedded
// frontend (public — auth is enforced client-side and on the API). With the
return mux
}
func (s *Server) Handler() http.Handler {
return s.handlerFor(s.apiRoutes())
}
// handlerFor builds the production handler around an API mux. Handler uses
// it with the real route table; tests use it with their own routes, so they
// exercise the same chain.
func (s *Server) handlerFor(mux *apiMux) http.Handler {
// /api/* goes through CORS, JWT and the route permission check (routes.go);
// everything else is served by the embedded frontend (public — auth is
// enforced client-side and on the API). With the
// no-embed build the webui handler just 404s (run `next dev` separately).
api := cors(s.requireAuth(mux))
api := cors(s.requireAuth(s.requirePerm(mux)))
root := http.NewServeMux()
root.Handle("/api/", api)
webui := s.webuiHandler()
+8 -6
View File
@@ -8,6 +8,8 @@ import (
"net/http"
"strings"
"time"
"github.com/Autumn-27/artex/server/perm"
)
// Shared browser API (Function → Browser in the web UI).
@@ -20,12 +22,12 @@ import (
//
// All of them sit behind requireAuth like every other /api route.
func (s *Server) registerSharedBrowserRoutes(mux *http.ServeMux) {
mux.HandleFunc("GET /api/browser/status", s.browserStatus)
mux.HandleFunc("GET /api/browser/stream", s.browserStream)
mux.HandleFunc("POST /api/browser/start", s.browserStart)
mux.HandleFunc("POST /api/browser/control", s.browserControl)
mux.HandleFunc("POST /api/browser/input", s.browserInput)
func (s *Server) registerSharedBrowserRoutes(mux *apiMux) {
s.handle(mux, "GET /api/browser/status", perm.Authenticated, s.browserStatus)
s.handle(mux, "GET /api/browser/stream", perm.Authenticated, s.browserStream)
s.handle(mux, "POST /api/browser/start", perm.Authenticated, s.browserStart)
s.handle(mux, "POST /api/browser/control", perm.Authenticated, s.browserControl)
s.handle(mux, "POST /api/browser/input", perm.Authenticated, s.browserInput)
}
func (s *Server) browserStatus(w http.ResponseWriter, _ *http.Request) {
+5 -4
View File
@@ -18,6 +18,7 @@ import (
"github.com/Autumn-27/artex/agent"
"github.com/Autumn-27/artex/db"
"github.com/Autumn-27/artex/llmrec"
"github.com/Autumn-27/artex/server/perm"
"github.com/Autumn-27/artex/sidequestion"
"github.com/Autumn-27/norma/llm"
"github.com/Autumn-27/norma/transcript"
@@ -270,10 +271,10 @@ func (s *Server) sideParent(w http.ResponseWriter, r *http.Request, kind string)
return p, true
}
func (s *Server) registerSideRoutes(mux *http.ServeMux) {
func (s *Server) registerSideRoutes(mux *apiMux) {
for _, route := range []struct{ path, kind string }{{"/api/conversations/{id}", "conversation"}, {"/api/tasks/{id}/chat", "main"}, {"/api/tasks/{id}/intents/{iid}", "worker"}} {
for _, method := range []string{"GET", "POST", "DELETE"} {
mux.HandleFunc(method+" "+route.path+"/side-questions", func(w http.ResponseWriter, r *http.Request) {
s.handle(mux, method+" "+route.path+"/side-questions", perm.Authenticated, func(w http.ResponseWriter, r *http.Request) {
p, ok := s.sideParent(w, r, route.kind)
if ok {
s.handleSideQuestions(w, r, p)
@@ -281,8 +282,8 @@ func (s *Server) registerSideRoutes(mux *http.ServeMux) {
})
}
}
mux.HandleFunc("GET /api/side-questions/{requestID}/events", s.sideEvents)
mux.HandleFunc("POST /api/side-questions/{requestID}/cancel", s.cancelSideRequest)
s.handle(mux, "GET /api/side-questions/{requestID}/events", perm.Authenticated, s.sideEvents)
s.handle(mux, "POST /api/side-questions/{requestID}/cancel", perm.Authenticated, s.cancelSideRequest)
}
func (s *Server) handleSideQuestions(w http.ResponseWriter, r *http.Request, p sidequestion.Parent) {
+1 -1
View File
@@ -25,7 +25,7 @@
"test:navigation": "node --test src/lib/navigation.test.mjs",
"test:chat-filter": "node --test src/lib/chat-agent-filter.test.mjs",
"test:openai-compatible": "node --test src/lib/openai-compatible.test.mjs",
"test:reducers": "node --import ./scripts/register-alias.mjs --test \"src/lib/reducers/*.test.mjs\" \"src/**/_state/*.test.mjs\"",
"test:reducers": "node --import ./scripts/register-alias.mjs --test \"src/lib/reducers/*.test.mjs\" \"src/**/_state/*.test.mjs\" src/lib/utils.test.mjs",
"test:activity-merge": "node --test src/lib/activity-merge.test.mjs",
"test:chat-mentions": "node --test src/lib/chat-mentions.test.mjs",
"test:format": "node --test src/lib/format.test.mjs",
+9
View File
@@ -17,3 +17,12 @@ export async function resolve(specifier, context, nextResolve) {
}
return nextResolve(specifier, context);
}
// The bundler imports locale JSON (src/i18n) without `with { type: "json" }`; Node requires the
// attribute, so add it here. This lets tests import modules that depend on @/i18n (e.g. @/lib/utils).
export async function load(url, context, nextLoad) {
if (url.endsWith(".json") && context.importAttributes?.type !== "json") {
return nextLoad(url, { ...context, importAttributes: { ...context.importAttributes, type: "json" } });
}
return nextLoad(url, context);
}
+3 -10
View File
@@ -3,7 +3,7 @@
import * as React from "react"
import { Dialog as DialogPrimitive } from "radix-ui"
import { cn, radixOverlayWasOpenAtPointerDown } from "@/lib/utils"
import { cn, preventDismissUnlessOverlayClick } from "@/lib/utils"
import { t } from "@/i18n"
import { Button } from "@/components/ui/button"
import { XIcon } from "lucide-react"
@@ -62,16 +62,9 @@ function DialogContent({
<DialogOverlay />
<DialogPrimitive.Content
data-slot="dialog-content"
// The only condition that closes the dialog: the click hits the overlay (the gray backdrop) itself, and no Radix popover
// (Select dropdown etc.) is open at that moment. Every other "outside interaction" is blocked (Esc and the ✕ at the top-right still close it):
// · clicking an option in the popover → target is not the overlay → blocked;
// · clicking outside the dialog or on the overlay to dismiss an open popover → a popover is open → blocked (dismiss only the popover, keep the dialog);
// · when the popover closes, Radix misreads the focus move as focus leaving → target is not the overlay → blocked.
// (onInteractOutside fires on both the pointer and focus paths.) Callers can still append their own logic.
// Close only on an overlay click with no popover open (see lib/utils.ts). Callers can still append their own logic.
onInteractOutside={(e) => {
const target = e.detail.originalEvent.target as Element | null
const onOverlay = !!target?.closest?.("[data-slot='dialog-overlay']")
if (!onOverlay || radixOverlayWasOpenAtPointerDown()) e.preventDefault()
preventDismissUnlessOverlayClick(e, "dialog-overlay")
onInteractOutside?.(e)
}}
className={cn(
+7 -1
View File
@@ -3,7 +3,7 @@
import * as React from "react"
import { Dialog as SheetPrimitive } from "radix-ui"
import { cn } from "@/lib/utils"
import { cn, preventDismissUnlessOverlayClick } from "@/lib/utils"
import { t } from "@/i18n"
import { Button } from "@/components/ui/button"
import { XIcon } from "lucide-react"
@@ -51,6 +51,7 @@ function SheetContent({
children,
side = "right",
showCloseButton = true,
onInteractOutside,
...props
}: React.ComponentProps<typeof SheetPrimitive.Content> & {
side?: "top" | "right" | "bottom" | "left"
@@ -62,6 +63,11 @@ function SheetContent({
<SheetPrimitive.Content
data-slot="sheet-content"
data-side={side}
// Close only on an overlay click with no popover open (see lib/utils.ts). Callers can still append their own logic.
onInteractOutside={(e) => {
preventDismissUnlessOverlayClick(e, "sheet-overlay")
onInteractOutside?.(e)
}}
className={cn(
"fixed z-50 flex flex-col gap-4 bg-popover bg-clip-padding text-sm text-popover-foreground shadow-lg transition duration-200 ease-in-out data-[side=bottom]:inset-x-0 data-[side=bottom]:bottom-0 data-[side=bottom]:h-auto data-[side=bottom]:border-t data-[side=left]:inset-y-0 data-[side=left]:left-0 data-[side=left]:h-full data-[side=left]:w-3/4 data-[side=left]:border-r data-[side=right]:inset-y-0 data-[side=right]:right-0 data-[side=right]:h-full data-[side=right]:w-3/4 data-[side=right]:border-l data-[side=top]:inset-x-0 data-[side=top]:top-0 data-[side=top]:h-auto data-[side=top]:border-b data-[side=left]:sm:max-w-sm data-[side=right]:sm:max-w-sm data-open:animate-in data-open:fade-in-0 data-[side=bottom]:data-open:slide-in-from-bottom-10 data-[side=left]:data-open:slide-in-from-left-10 data-[side=right]:data-open:slide-in-from-right-10 data-[side=top]:data-open:slide-in-from-top-10 data-closed:animate-out data-closed:fade-out-0 data-[side=bottom]:data-closed:slide-out-to-bottom-10 data-[side=left]:data-closed:slide-out-to-left-10 data-[side=right]:data-closed:slide-out-to-right-10 data-[side=top]:data-closed:slide-out-to-top-10",
className
+88
View File
@@ -0,0 +1,88 @@
// preventDismissUnlessOverlayClick: the onInteractOutside guard of SheetContent and DialogContent.
// No DOM here: a stub document records the capture-phase pointerdown listener and answers
// querySelector from a list of fake elements, matched by a small attribute-selector matcher.
import assert from "node:assert/strict";
import test from "node:test";
let elements = [];
let onPointerDown = null;
globalThis.document = {
documentElement: {},
addEventListener(type, fn, capture) {
if (type === "pointerdown" && capture === true) onPointerDown = fn;
},
querySelector: (selector) => elements.find((el) => matchesAny(el, selector)) ?? null,
};
const { preventDismissUnlessOverlayClick } = await import("@/lib/utils");
// Supports exactly the selector forms the guard uses: [a], [a='v'] and :not([a='v']), compounded,
// joined by commas. Anything else throws, so a new selector form fails this test instead of silently not matching.
function matchesAny(attrs, selectorList) {
return selectorList.split(",").some((raw) => {
const compound = raw.trim();
const parts = [...compound.matchAll(/(:not\()?\[([\w-]+)(?:='([^']*)')?\]\)?/g)];
if (parts.map((m) => m[0]).join("") !== compound) throw new Error(`unsupported selector: ${compound}`);
return parts.every(([, negated, name, value]) => {
const has = value === undefined ? name in attrs : attrs[name] === value;
return negated ? !has : has;
});
});
}
// Runs one outside interaction: the elements present at pointerdown, then the guard on a target
// that is either the sheet overlay or something else. Returns whether the guard blocked the close.
function blocked(present, { onOverlay = true, slot = "sheet-overlay" } = {}) {
elements = present;
onPointerDown();
const target = { closest: (sel) => (onOverlay && sel === `[data-slot='${slot}']` ? {} : null) };
let prevented = false;
preventDismissUnlessOverlayClick(
{ detail: { originalEvent: { target } }, preventDefault: () => (prevented = true) },
slot,
);
return prevented;
}
const sheetTrigger = {
"aria-haspopup": "dialog",
"aria-expanded": "true",
"data-state": "open",
"data-slot": "button",
};
test("overlay click with nothing open closes the sheet and the dialog", () => {
assert.equal(blocked([]), false);
assert.equal(blocked([], { slot: "dialog-overlay" }), false);
});
test("a click that is not on the overlay never closes", () => {
assert.equal(blocked([], { onOverlay: false }), true);
});
test("overlay click with an open Radix Select only closes the Select", () => {
assert.equal(blocked([{ "data-slot": "select-content", "data-state": "open" }]), true);
assert.equal(blocked([{ role: "listbox", "data-state": "open" }]), true);
});
test("overlay click with an open Radix popper (Popover, DropdownMenu content) only closes it", () => {
assert.equal(blocked([{ "data-radix-popper-content-wrapper": "" }]), true);
});
test("overlay click with an open Base UI Combobox only closes the Combobox", () => {
assert.equal(blocked([{ "data-slot": "combobox-content", "data-open": "" }]), true);
assert.equal(blocked([{ "data-slot": "combobox-content", "data-closed": "" }]), false);
});
test("an open menu trigger counts as an open popup", () => {
assert.equal(blocked([{ "aria-haspopup": "menu", "aria-expanded": "true", "data-state": "open" }]), true);
});
test("the trigger of the open sheet/dialog does not block its own overlay close", () => {
assert.equal(blocked([sheetTrigger]), false);
assert.equal(blocked([sheetTrigger], { slot: "dialog-overlay" }), false);
});
test("an expanded Collapsible (sidebar group) does not block the overlay close", () => {
assert.equal(blocked([{ "aria-expanded": "true", "data-state": "open", "data-slot": "collapsible-trigger" }]), false);
});
+25 -5
View File
@@ -25,7 +25,13 @@ function isRadixOverlayOpenNow(): boolean {
"[data-slot='select-content'][data-state='open']",
"[role='listbox'][data-state='open']",
"[data-radix-popper-content-wrapper]",
"[aria-expanded='true'][data-state='open']",
// Base UI Combobox popup (New task sheet etc.): open state is data-open, not data-state.
"[data-slot='combobox-content'][data-open]",
// An open menu-type trigger (DropdownMenu etc.). Only triggers that announce a popup count: the trigger of the
// open sheet/dialog itself (aria-haspopup="dialog") and an expanded Collapsible/Accordion (no aria-haspopup) also
// carry aria-expanded + data-state=open, and counting them would stop every overlay click from closing that sheet/dialog.
// A Popover trigger is aria-haspopup="dialog" too; its open content is already matched by the popper wrapper above.
"[aria-haspopup]:not([aria-haspopup='dialog'])[aria-expanded='true'][data-state='open']",
].join(","),
);
}
@@ -41,10 +47,24 @@ if (typeof document !== "undefined") {
);
}
// radixOverlayWasOpenAtPointerDown returns whether a Radix popover was open at the most
// recent pointerdown. Sheets/dialogs use it: overlay click with a popover open → dismiss only the popover, keep themselves open.
export function radixOverlayWasOpenAtPointerDown(): boolean {
return overlayOpenAtLastPointerDown;
// The event Radix passes to a Dialog/Sheet onInteractOutside handler (pointer-down-outside or focus-outside).
type InteractOutsideEvent = { detail: { originalEvent: Event }; preventDefault(): void };
// preventDismissUnlessOverlayClick is the shared onInteractOutside guard of SheetContent and DialogContent.
// The only outside interaction it lets close the sheet/dialog: a click on its own overlay (the gray backdrop,
// matched by overlaySlot) while no Radix popover (Select dropdown etc.) was open at that pointerdown.
// Everything else is blocked (Esc and the ✕ button still close it):
// · clicking an option in the popover → target is not the overlay → blocked;
// · clicking inside the sheet/dialog or on the overlay to dismiss an open popover → a popover was open →
// blocked (dismiss only the popover, keep the sheet/dialog and what was typed in it);
// · when the popover closes, Radix misreads the focus move as focus leaving → target is not the overlay → blocked.
export function preventDismissUnlessOverlayClick(
e: InteractOutsideEvent,
overlaySlot: "sheet-overlay" | "dialog-overlay",
): void {
const target = e.detail.originalEvent.target as Element | null;
const onOverlay = !!target?.closest?.(`[data-slot='${overlaySlot}']`);
if (!onOverlay || overlayOpenAtLastPointerDown) e.preventDefault();
}
// copyText writes text to the clipboard and returns whether it succeeded.