chore: 初始化仓库,导入项目基线代码

Academy v0.8.3 完整代码基线:Go 后端(internal/cmd/cli/mcp-server/docreader)、
Vue 前端(frontend)、数据库迁移(migrations)、部署编排(docker/helm/deploy)与文档。
今日开发的培训推送管理改动随后单独提交。
This commit is contained in:
runny committed 2026-11-16 18:12:23 +08:00
commit 7ec21f35b0
5767 files changed
+1436788

No files matched your search

@@ -0,0 +1,168 @@
package allocation
import (
"strings"
"testing"
"github.com/stretchr/testify/require"
)
const sid = "0f8fad5b-d9cb-469f-a165-70867728950e"
func TestParseMode(t *testing.T) {
for in, want := range map[string]Mode{"": ModeSession, "session": ModeSession, " user ": ModeUser} {
got, err := ParseMode(in)
require.NoError(t, err)
require.Equal(t, want, got)
}
_, err := ParseMode("machine")
require.Error(t, err)
}
func TestDecideMatrix(t *testing.T) {
web := Owner{TenantID: 7, ID: "u-1", Kind: KindWebUser, Source: SourceWeb}
ext := Owner{TenantID: 7, ID: "api_external_user:7:alice", Kind: KindAPIExternalUser, Source: SourceAPISignedToken}
base := DecideInput{ConfigMode: ModeUser, Purpose: PurposeChat, SessionID: sid, UserModeAvailable: true}
cases := []struct {
name string
mutate func(*DecideInput)
mode Mode
reason FallbackReason
}{
{"web user shares", func(in *DecideInput) { in.Owner = web }, ModeUser, ReasonNone},
{"signed external user shares", func(in *DecideInput) { in.Owner = ext }, ModeUser, ReasonNone},
{"direct external user shares", func(in *DecideInput) {
in.Owner = ext
in.Owner.Source = SourceAPIDirectHeader
}, ModeUser, ReasonNone},
{"session config never shares", func(in *DecideInput) {
in.Owner = web
in.ConfigMode = ModeSession
}, ModeSession, ReasonNone},
{"maintenance first", func(in *DecideInput) {
in.Owner = web
in.Purpose = PurposeMaintenance
}, ModeSession, ReasonMaintenanceDedicated},
{"gate off", func(in *DecideInput) {
in.Owner = web
in.UserModeAvailable = false
}, ModeSession, ReasonUserModeUnavailable},
{"tenant api key", func(in *DecideInput) {
in.Owner = Owner{TenantID: 7, ID: "api_tenant_key:7:3", Kind: KindAPITenantKey, Source: SourceAPITenantKey}
}, ModeSession, ReasonSharedAPIKey},
{"platform api key", func(in *DecideInput) {
in.Owner = Owner{TenantID: 7, ID: "api_platform:3", Kind: KindAPIPlatformKey, Source: SourceAPIPlatformKey}
}, ModeSession, ReasonSharedAPIKey},
{"mcp endpoint", func(in *DecideInput) {
in.Owner = Owner{TenantID: 7, ID: "mcp_endpoint:7:e", Kind: KindMCPEndpoint, Source: SourceMCPEndpoint}
}, ModeSession, ReasonSharedMCPEndpoint},
{"embed", func(in *DecideInput) {
in.Owner = Owner{TenantID: 7, ID: "embed_session:7:c:s", Kind: KindEmbed}
}, ModeSession, ReasonChannelIdentity},
{"im", func(in *DecideInput) {
in.Owner = Owner{TenantID: 7, ID: "x", Kind: KindIM}
}, ModeSession, ReasonChannelIdentity},
{"empty owner", func(in *DecideInput) {
in.Owner = Owner{TenantID: 7}
}, ModeSession, ReasonOwnerIdentityUnverified},
{"web without web source", func(in *DecideInput) {
in.Owner = web
in.Owner.Source = SourceInternal
}, ModeSession, ReasonOwnerIdentityUnverified},
{"external with unknown source", func(in *DecideInput) {
in.Owner = ext
in.Owner.Source = SourceUnknown
}, ModeSession, ReasonOwnerIdentityUnverified},
{"unknown kind", func(in *DecideInput) {
in.Owner = Owner{TenantID: 7, ID: "u", Source: SourceWeb}
}, ModeSession, ReasonOwnerIdentityUnverified},
{"owner with braces", func(in *DecideInput) {
in.Owner = web
in.Owner.ID = "u{1}"
}, ModeSession, ReasonOwnerIdentityInvalid},
{"owner too long", func(in *DecideInput) {
in.Owner = web
in.Owner.ID = strings.Repeat("a", 513)
}, ModeSession, ReasonOwnerIdentityInvalid},
{"session id not uuid", func(in *DecideInput) {
in.Owner = web
in.SessionID = "abc"
}, ModeSession, ReasonSessionIDNotUUID},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
in := base
tc.mutate(&in)
got := Decide(in)
require.Equal(t, tc.mode, got.Mode)
require.Equal(t, tc.reason, got.Reason)
})
}
}
func TestEligibleForUser(t *testing.T) {
require.True(t, EligibleForUser(KindWebUser, SourceWeb))
require.True(t, EligibleForUser(KindAPIExternalUser, SourceAPISignedToken))
require.True(t, EligibleForUser(KindAPIExternalUser, SourceAPIDirectHeader))
require.False(t, EligibleForUser(KindWebUser, SourceInternal))
require.False(t, EligibleForUser(KindAPITenantKey, SourceAPITenantKey))
require.False(t, EligibleForUser(KindUnknown, SourceWeb))
}
func TestUserMachineDigestIsStableAndUnambiguous(t *testing.T) {
m := UserMachine{OwnerTenantID: 7, OwnerID: "u-1", ConfigTenantID: 9, ConfigID: "cfg"}
require.NoError(t, m.Validate())
d := m.Digest("academy")
require.Len(t, d, 64)
require.Equal(t, d, m.Digest("academy"))
require.NotEqual(t, d, m.Digest("other"))
// Length-prefixing keeps field boundaries: these two must not collide.
a := UserMachine{OwnerTenantID: 7, OwnerID: "ab", ConfigTenantID: 9, ConfigID: "c"}
b := UserMachine{OwnerTenantID: 7, OwnerID: "a", ConfigTenantID: 9, ConfigID: "bc"}
require.NotEqual(t, a.Digest("n"), b.Digest("n"))
require.Error(t, UserMachine{OwnerID: "u", ConfigTenantID: 9, ConfigID: "c"}.Validate())
require.Error(t, UserMachine{OwnerTenantID: 7, ConfigTenantID: 9, ConfigID: "c"}.Validate())
require.Error(t, UserMachine{OwnerTenantID: 7, OwnerID: "u", ConfigID: "c"}.Validate())
require.Error(t, UserMachine{OwnerTenantID: 7, OwnerID: "u", ConfigTenantID: 9}.Validate())
}
func TestAssignmentLayout(t *testing.T) {
s := Assignment{SessionID: sid, ConfigTenantID: 9, ConfigID: "cfg"}
require.Equal(t, ModeSession, s.Mode())
l, err := s.Layout()
require.NoError(t, err)
require.Equal(t, "/workspace", l.Root)
_, ok := s.UserMachine()
require.False(t, ok)
want := UserMachine{OwnerTenantID: 7, OwnerID: "u-1", ConfigTenantID: 9, ConfigID: "cfg"}
u := Assignment{SessionID: sid, ConfigTenantID: 9, ConfigID: "cfg", Machine: want}
require.Equal(t, ModeUser, u.Mode())
l, err = u.Layout()
require.NoError(t, err)
require.Equal(t, "/workspace/sessions/c812e1edb644", l.Root)
m, ok := u.UserMachine()
require.True(t, ok)
require.Equal(t, want, m)
}
func TestRetention(t *testing.T) {
require.Equal(t, 7, EffectiveRetentionDays(0))
require.Equal(t, 30, EffectiveRetentionDays(30))
require.NoError(t, ValidateRetentionDays(0))
require.NoError(t, ValidateRetentionDays(90))
require.Error(t, ValidateRetentionDays(-1))
require.Error(t, ValidateRetentionDays(91))
}
func TestGate(t *testing.T) {
t.Cleanup(func() { SetUserModeAvailable(false) })
require.False(t, UserModeAvailable())
SetUserModeAvailable(true)
require.True(t, UserModeAvailable())
t.Setenv(UserModeEnvVar, "enabled")
require.True(t, UserModeRequestedByEnv())
t.Setenv(UserModeEnvVar, "nope")
require.False(t, UserModeRequestedByEnv())
}
+49
View File
@@ -0,0 +1,49 @@
package allocation
import (
"time"
"academy/internal/sandbox/workspace"
)
// Assignment is the persisted placement of one session. Only the config
// address, the shared machine (if any) and the release time are stored; the
// mode and the workspace layout follow from whether there is a machine, and
// the session keeps both for life whatever the config switch says later.
type Assignment struct {
SessionID string
ConfigTenantID uint64
ConfigID string
// Machine is the shared machine of a user-mode session; zero for a
// session with a machine of its own.
Machine UserMachine
ReleasedAt *time.Time
}
// Released reports a session whose workspace has been given back.
func (a Assignment) Released() bool { return a.ReleasedAt != nil }
// Mode is ModeUser for a session on a shared machine, ModeSession otherwise.
func (a Assignment) Mode() Mode {
if a.Machine != (UserMachine{}) {
return ModeUser
}
return ModeSession
}
// IsUser reports a session on a shared machine.
func (a Assignment) IsUser() bool { return a.Mode() == ModeUser }
// UserMachine returns the shared machine a user-mode session lives on.
func (a Assignment) UserMachine() (UserMachine, bool) {
return a.Machine, a.IsUser()
}
// Layout is the workspace the session was assigned, independent of the
// config's current switch.
func (a Assignment) Layout() (workspace.Layout, error) {
if a.IsUser() {
return workspace.UserSession(a.SessionID)
}
return workspace.Remote(), nil
}
+30
View File
@@ -0,0 +1,30 @@
package allocation
import (
"os"
"strings"
"sync/atomic"
)
// UserModeEnvVar opts a deployment into user-mode allocation. It must be set
// on every replica before any config is switched to "user".
const UserModeEnvVar = "ACADEMY_SANDBOX_USER_ALLOCATION"
var userModeAvailable atomic.Bool
// UserModeRequestedByEnv reports whether the operator asked for user mode.
func UserModeRequestedByEnv() bool {
switch strings.ToLower(strings.TrimSpace(os.Getenv(UserModeEnvVar))) {
case "1", "true", "on", "enabled":
return true
default:
return false
}
}
// SetUserModeAvailable is called once by the container after it knows whether
// the deployment can coordinate shared machines (env opt-in and Redis).
func SetUserModeAvailable(available bool) { userModeAvailable.Store(available) }
// UserModeAvailable reports the deployment gate.
func UserModeAvailable() bool { return userModeAvailable.Load() }
+58
View File
@@ -0,0 +1,58 @@
package allocation
import (
"crypto/sha256"
"encoding/binary"
"encoding/hex"
"errors"
"strconv"
"strings"
)
// UserMachine is the logical identity of one shared machine: one owner, one
// sandbox config. It is comparable so it can key maps. ConfigID must already
// be normalized (sandbox.NormalizeConfigID) and ConfigTenantID resolved.
type UserMachine struct {
OwnerTenantID uint64
OwnerID string
ConfigTenantID uint64
ConfigID string
}
// Validate rejects identities that cannot address a machine.
func (m UserMachine) Validate() error {
if m.OwnerTenantID == 0 {
return errors.New("allocation: user machine requires an owner tenant")
}
if err := ValidateOwnerID(m.OwnerID); err != nil {
return err
}
if m.ConfigTenantID == 0 {
return errors.New("allocation: user machine requires a resolved config tenant")
}
if strings.TrimSpace(m.ConfigID) == "" {
return errors.New("allocation: user machine requires a config id")
}
return nil
}
// Digest is the hex SHA-256 of a length-prefixed canonical encoding, so no
// two identities share a digest by field-boundary ambiguity. The namespace is
// part of it: two deployments sharing one Redis never address each other's
// machines. It is the Redis hash tag, the DB key and the provider metadata.
func (m UserMachine) Digest(namespace string) string {
h := sha256.New()
write := func(s string) {
var n [8]byte
binary.BigEndian.PutUint64(n[:], uint64(len(s)))
h.Write(n[:])
h.Write([]byte(s))
}
write("academy-user-sandbox/v1")
write(namespace)
write(strconv.FormatUint(m.OwnerTenantID, 10))
write(m.OwnerID)
write(strconv.FormatUint(m.ConfigTenantID, 10))
write(m.ConfigID)
return hex.EncodeToString(h.Sum(nil))
}
+59
View File
@@ -0,0 +1,59 @@
// Package allocation is the domain model for placing a session on a remote
// sandbox: which mode it uses, whether its owner may share a machine, and the
// identity of a shared machine. It performs no I/O.
package allocation
import (
"fmt"
"strings"
)
// Mode is how a session is placed on remote machines.
type Mode string
const (
// ModeSession gives the session a machine of its own (historical behaviour).
ModeSession Mode = "session"
// ModeUser places the session in a directory on its owner's shared machine.
ModeUser Mode = "user"
)
// ParseMode accepts the stored config value. Empty means session.
func ParseMode(raw string) (Mode, error) {
switch strings.TrimSpace(raw) {
case "", string(ModeSession):
return ModeSession, nil
case string(ModeUser):
return ModeUser, nil
default:
return "", fmt.Errorf("allocation: unknown mode %q", raw)
}
}
// Purpose is why a session uses a sandbox.
type Purpose string
// Placement purposes. PurposeChat is an ordinary session.
// PurposeMaintenance is a skill-install session and stays on its own machine.
const (
PurposeChat Purpose = "chat"
PurposeMaintenance Purpose = "maintenance"
)
// FallbackReason explains why a session did not get the config's mode. The
// values are stable, non-sensitive tokens safe to show an admin.
type FallbackReason string
// Reasons a placement stayed on a per-session machine.
const (
ReasonNone FallbackReason = ""
ReasonMaintenanceDedicated FallbackReason = "MAINTENANCE_DEDICATED"
ReasonUserModeUnavailable FallbackReason = "USER_MODE_UNAVAILABLE"
ReasonOwnerIdentityInvalid FallbackReason = "OWNER_IDENTITY_INVALID"
ReasonSharedAPIKey FallbackReason = "SHARED_API_KEY"
ReasonSharedMCPEndpoint FallbackReason = "SHARED_MCP_ENDPOINT"
ReasonChannelIdentity FallbackReason = "CHANNEL_IDENTITY_NOT_SUPPORTED"
ReasonOwnerIdentityUnverified FallbackReason = "OWNER_IDENTITY_UNVERIFIED"
ReasonSessionIDNotUUID FallbackReason = "SESSION_ID_NOT_UUID"
ReasonLegacySessionSandbox FallbackReason = "LEGACY_SESSION_SANDBOX"
)
+142
View File
@@ -0,0 +1,142 @@
package allocation
import (
"errors"
"strings"
"unicode"
"academy/internal/sandbox/workspace"
)
// OwnerKind classifies who sessions.user_id names.
type OwnerKind string
// Kinds derived from owner_auth_source and the shape of user_id.
const (
KindUnknown OwnerKind = ""
KindWebUser OwnerKind = "web_user"
KindAPIExternalUser OwnerKind = "api_external_user"
KindAPITenantKey OwnerKind = "api_tenant_key"
KindAPIPlatformKey OwnerKind = "api_platform_key"
KindMCPEndpoint OwnerKind = "mcp_endpoint"
KindEmbed OwnerKind = "embed"
KindIM OwnerKind = "im"
)
// AuthSource is how the server authenticated the owner when the session was
// created or its owner was first bound. It is recorded server-side only.
type AuthSource string
// Sources stamped by the server. SourceUnknown is an empty or legacy row.
const (
SourceUnknown AuthSource = "unknown"
SourceWeb AuthSource = "web"
SourceAPIDirectHeader AuthSource = "api_direct_header"
SourceAPISignedToken AuthSource = "api_signed_token"
SourceAPITenantKey AuthSource = "api_tenant_key"
SourceAPIPlatformKey AuthSource = "api_platform_key"
SourceMCPEndpoint AuthSource = "mcp_endpoint"
SourceEmbed AuthSource = "embed"
SourceIM AuthSource = "im"
SourceInternal AuthSource = "internal"
)
// MaxOwnerIDLength matches sessions.user_id.
const MaxOwnerIDLength = 512
// Owner is the persisted owner of a session as the allocator sees it.
type Owner struct {
TenantID uint64
ID string
Kind OwnerKind
Source AuthSource
}
// ValidateOwnerID rejects ids that cannot be part of a machine identity.
func ValidateOwnerID(id string) error {
if strings.TrimSpace(id) == "" {
return errors.New("allocation: owner id is empty")
}
if len(id) > MaxOwnerIDLength {
return errors.New("allocation: owner id is too long")
}
if strings.ContainsAny(id, "{}") {
return errors.New("allocation: owner id must not contain braces")
}
for _, r := range id {
if unicode.IsControl(r) {
return errors.New("allocation: owner id must not contain control characters")
}
}
return nil
}
// DecideInput is everything Decide needs; callers load it, Decide is pure.
type DecideInput struct {
ConfigMode Mode
Purpose Purpose
Owner Owner
SessionID string
UserModeAvailable bool
}
// Decision is the mode a session gets and why it differs from the config.
type Decision struct {
Mode Mode
Reason FallbackReason
}
// Decide applies the user-mode admission whitelist. Only a server-verified web
// account or API external user may share a machine; every other owner keeps a
// machine per session. Checks run in a fixed order so the recorded reason is
// deterministic: maintenance, deployment gate, invalid owner, shared entry or
// channel, unverified identity, session id shape.
func Decide(in DecideInput) Decision {
session := func(reason FallbackReason) Decision { return Decision{Mode: ModeSession, Reason: reason} }
if in.Purpose == PurposeMaintenance {
return session(ReasonMaintenanceDedicated)
}
if in.ConfigMode != ModeUser {
return session(ReasonNone)
}
if !in.UserModeAvailable {
return session(ReasonUserModeUnavailable)
}
if strings.TrimSpace(in.Owner.ID) == "" {
return session(ReasonOwnerIdentityUnverified)
}
if ValidateOwnerID(in.Owner.ID) != nil {
return session(ReasonOwnerIdentityInvalid)
}
if EligibleForUser(in.Owner.Kind, in.Owner.Source) {
if !workspace.IsCanonicalUUID(in.SessionID) {
return session(ReasonSessionIDNotUUID)
}
return Decision{Mode: ModeUser}
}
switch in.Owner.Kind {
case KindAPITenantKey, KindAPIPlatformKey:
return session(ReasonSharedAPIKey)
case KindMCPEndpoint:
return session(ReasonSharedMCPEndpoint)
case KindEmbed, KindIM:
return session(ReasonChannelIdentity)
default:
return session(ReasonOwnerIdentityUnverified)
}
}
// EligibleForUser is the whitelist itself: a server-verified web account, or
// an API external user whose subject came from the direct header or a signed
// token. Decide applies it at first use; the manager re-applies it to stored
// assignments so a row whose identity is no longer acceptable stops running.
func EligibleForUser(kind OwnerKind, source AuthSource) bool {
switch kind {
case KindWebUser:
return source == SourceWeb
case KindAPIExternalUser:
return source == SourceAPIDirectHeader || source == SourceAPISignedToken
default:
return false
}
}
+28
View File
@@ -0,0 +1,28 @@
package allocation
import "fmt"
const (
// DefaultEmptyRetentionDays is how long a user machine with no live
// session is kept when the config leaves the value unset.
DefaultEmptyRetentionDays = 7
// MaxEmptyRetentionDays bounds the setting; there is no "keep forever".
MaxEmptyRetentionDays = 90
)
// EffectiveRetentionDays maps the stored value (0 = unset) onto days.
func EffectiveRetentionDays(stored int) int {
if stored <= 0 {
return DefaultEmptyRetentionDays
}
return stored
}
// ValidateRetentionDays accepts 0 (use the default) through 90.
func ValidateRetentionDays(stored int) error {
if stored < 0 || stored > MaxEmptyRetentionDays {
return fmt.Errorf("user_sandbox_empty_retention_days must be between 1 and %d, or 0 for the default of %d",
MaxEmptyRetentionDays, DefaultEmptyRetentionDays)
}
return nil
}