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

+232
View File
@@ -0,0 +1,232 @@
// Package workspace describes where one session's files live inside a remote
// sandbox and the lexical path rules the manager and the agent tools share.
//
// It is a leaf package. internal/sandbox re-exports Layout as
// sandbox.WorkspaceLayout, so this package must never import it back.
package workspace
import (
"crypto/sha256"
"encoding/hex"
"fmt"
"path"
"strings"
)
// Fixed paths inside every remote sandbox image.
const (
Root = "/workspace"
InputDir = "/workspace/input"
OutputDir = "/workspace/output"
GitDir = "/var/lib/academy/workspace.git"
SkillsImageRoot = "/opt/academy/tenant/skills"
TmpRoot = "/tmp"
// UserSessionsRoot holds one directory per session on a machine that
// several sessions of one owner share; UserGitRoot holds their checkpoint
// repositories, outside the work trees for the same reason GitDir is.
UserSessionsRoot = Root + "/sessions"
UserGitRoot = "/var/lib/academy/sessions"
)
// Origin says what kind of workspace a layout describes. Isolation policy
// (work_dir clamping, inspect enforcement, prompt copy) follows Origin, never
// the Root string: a host project can itself be /workspace.
type Origin int
const (
// OriginUnspecified is the zero value. Tools treat it as remote.
OriginUnspecified Origin = iota
// OriginRemote is a disposable container one session owns outright.
OriginRemote
// OriginHost is a directory on the user's machine.
OriginHost
// OriginRemoteShared is a remote machine shared by several sessions of
// one owner. Tools must stay inside the layout's roots.
OriginRemoteShared
)
// Layout describes the shape of one session's workspace. It is pure data, so
// remote managers and local adapters can both produce it and the tools can
// consume it for prompts and tool-layer scope.
//
// It is not a symlink-safe privilege boundary. A host SessionFileStore must
// still enforce the OS-sandbox PathGuard on every read and write. Empty
// InputDir / OutputDir is the host shape: there is no separate attachment or
// collect tree, and scanning Root would upload the user's project.
type Layout struct {
// Origin selects remote vs host vs shared-remote policy.
Origin Origin
// Root anchors relative paths and is the shell's working directory.
Root string
// WriteRoots are the directories write/edit tools may create files under.
// A root itself is a directory, not a writable file path.
WriteRoots []string
// ReadRoots are the directories read/list tools may inspect, ordered
// most-specific-first so the reported root names the narrowest match.
ReadRoots []string
// InputDir holds read-only user attachments. Empty when the backend has none.
InputDir string
// OutputDir is what artifact collection sweeps. Empty when it collects none.
OutputDir string
// Hint is the wording tools put in descriptions and scope errors.
Hint string
// GitDir is the checkpoint repository for Root. Empty when the backend
// does not version the workspace (host).
GitDir string
// WorkDirRoots limits shell work_dir on a shared machine. Empty means
// unrestricted for remote layouts; host layouts clamp to WriteRoots.
WorkDirRoots []string
}
// IsHost reports a local OS workspace. Host adapters must set Origin; a
// non-empty Root that is not /workspace is not enough (Gitpod uses /workspace).
func (l Layout) IsHost() bool { return l.Origin == OriginHost }
// IsSharedRemote reports a remote machine shared by several sessions.
func (l Layout) IsSharedRemote() bool { return l.Origin == OriginRemoteShared }
// HasRoot reports a usable workspace root.
func (l Layout) HasRoot() bool { return strings.TrimSpace(l.Root) != "" }
// Normalized cleans every path in the layout and drops empty roots.
//
// Scope checks compare cleaned paths against these entries verbatim, so an
// adapter that hands back a trailing slash or an uncleaned path would silently
// deny every write and work_dir inside its own workspace.
func (l Layout) Normalized() Layout {
l.Root = cleanLayoutPath(l.Root)
l.InputDir = cleanLayoutPath(l.InputDir)
l.OutputDir = cleanLayoutPath(l.OutputDir)
l.GitDir = cleanLayoutPath(l.GitDir)
l.WriteRoots = cleanLayoutRoots(l.WriteRoots)
l.ReadRoots = cleanLayoutRoots(l.ReadRoots)
l.WorkDirRoots = cleanLayoutRoots(l.WorkDirRoots)
l.Hint = strings.TrimSpace(l.Hint)
return l
}
// Remote is the /workspace layout of a machine one session owns.
func Remote() Layout {
return Layout{
Origin: OriginRemote,
Root: Root,
WriteRoots: []string{Root, OutputDir},
ReadRoots: []string{OutputDir, InputDir, Root},
InputDir: InputDir,
OutputDir: OutputDir,
Hint: Root,
GitDir: GitDir,
}
}
// UserSession is the layout of sessionID on a machine its owner's sessions
// share. Only canonical lower-case UUIDs are accepted, so the id can never
// carry a path segment of its own. The directory name is SessionDirName, not
// the full UUID: the model sees this path on every turn. The session root
// anchors commands and artifact collection; it is not a tool-layer access
// boundary — tools treat the machine like a session-owned one.
func UserSession(sessionID string) (Layout, error) {
name, err := SessionDirName(sessionID)
if err != nil {
return Layout{}, err
}
root := path.Join(UserSessionsRoot, name)
input := path.Join(root, "input")
output := path.Join(root, "output")
return Layout{
Origin: OriginRemoteShared,
Root: root,
WriteRoots: []string{Root, OutputDir},
ReadRoots: []string{output, input, root, SkillsImageRoot},
InputDir: input,
OutputDir: output,
Hint: root,
GitDir: path.Join(UserGitRoot, name+".git"),
}, nil
}
// SessionDirName is the on-disk directory for a canonical session UUID: the
// first 12 hex characters of the id's SHA-256. The hash uses every bit of the
// UUID, so a collision needs roughly a million sessions on one machine, and
// the name is deterministic: no mapping is stored anywhere. The full id stays
// the session's identity everywhere else.
func SessionDirName(sessionID string) (string, error) {
if !IsCanonicalUUID(sessionID) {
return "", fmt.Errorf("workspace: session id %q is not a canonical UUID", sessionID)
}
sum := sha256.Sum256([]byte(sessionID))
return hex.EncodeToString(sum[:])[:12], nil
}
// FailedHost is what tools and prompts use when a layout provider exists but
// errors: do not fall back to /workspace.
func FailedHost() Layout { return Layout{Origin: OriginHost} }
// IsCanonicalUUID reports the 36-character lower-case form uuid.New().String()
// produces.
func IsCanonicalUUID(s string) bool {
if len(s) != 36 {
return false
}
for i := 0; i < len(s); i++ {
c := s[i]
switch i {
case 8, 13, 18, 23:
if c != '-' {
return false
}
default:
if (c < '0' || c > '9') && (c < 'a' || c > 'f') {
return false
}
}
}
return true
}
// PromptSafePath returns p when it can be embedded verbatim in prompt text,
// and "" when it cannot. Callers fall back to generic wording instead of
// sanitizing, so a real path is never shown wrong.
func PromptSafePath(p string) string {
p = strings.TrimSpace(p)
if p == "" {
return ""
}
for _, r := range p {
if r < 0x20 || r == 0x7f || r == '<' || r == '>' || r == '&' {
return ""
}
}
return p
}
func cleanLayoutPath(p string) string {
p = strings.TrimSpace(p)
if p == "" {
return ""
}
return path.Clean(p)
}
// cleanLayoutRoots preserves order (ReadRoots is most-specific-first) and
// drops duplicates that only differed before cleaning.
func cleanLayoutRoots(roots []string) []string {
if len(roots) == 0 {
return roots
}
out := make([]string, 0, len(roots))
seen := make(map[string]struct{}, len(roots))
for _, root := range roots {
clean := cleanLayoutPath(root)
if clean == "" {
continue
}
if _, dup := seen[clean]; dup {
continue
}
seen[clean] = struct{}{}
out = append(out, clean)
}
return out
}
+61
View File
@@ -0,0 +1,61 @@
package workspace
import (
"testing"
"github.com/stretchr/testify/require"
)
const testSessionID = "0f8fad5b-d9cb-469f-a165-70867728950e"
func TestRemoteLayoutKeepsTheHistoricalContract(t *testing.T) {
l := Remote()
require.Equal(t, OriginRemote, l.Origin)
require.Equal(t, "/workspace", l.Root)
require.Equal(t, []string{"/workspace", "/workspace/output"}, l.WriteRoots)
require.Equal(t, []string{"/workspace/output", "/workspace/input", "/workspace"}, l.ReadRoots)
require.Equal(t, "/workspace/input", l.InputDir)
require.Equal(t, "/workspace/output", l.OutputDir)
require.Equal(t, "/workspace", l.Hint)
require.Equal(t, "/var/lib/academy/workspace.git", l.GitDir)
require.Empty(t, l.WorkDirRoots, "a session-owned machine keeps unrestricted work_dir")
require.False(t, l.IsSharedRemote())
}
func TestUserSessionLayoutUsesMachineWideWriteRoots(t *testing.T) {
l, err := UserSession(testSessionID)
require.NoError(t, err)
name, err := SessionDirName(testSessionID)
require.NoError(t, err)
require.Equal(t, "c812e1edb644", name, "the first 12 hex chars of the id's SHA-256")
root := "/workspace/sessions/" + name
require.Equal(t, OriginRemoteShared, l.Origin)
require.True(t, l.IsSharedRemote())
require.False(t, l.IsHost())
require.Equal(t, root, l.Root)
require.Equal(t, root+"/input", l.InputDir)
require.Equal(t, root+"/output", l.OutputDir)
require.Equal(t, []string{Root, OutputDir}, l.WriteRoots,
"tools treat the machine like a session-owned one: the whole /workspace is writable")
require.Equal(t, []string{root + "/output", root + "/input", root, SkillsImageRoot}, l.ReadRoots)
require.Empty(t, l.WorkDirRoots, "no work_dir whitelist: any absolute directory is allowed")
require.Equal(t, "/var/lib/academy/sessions/"+name+".git", l.GitDir)
require.Equal(t, root, l.Hint)
}
func TestUserSessionRejectsNonCanonicalIDs(t *testing.T) {
for _, id := range []string{
"", "abc", "../etc", testSessionID + "x",
"0F8FAD5B-D9CB-469F-A165-70867728950E", // upper case is not what uuid.New().String() emits
"0f8fad5b_d9cb_469f_a165_70867728950e",
} {
_, err := UserSession(id)
require.Error(t, err, id)
}
}
func TestNormalizedCleansNewFields(t *testing.T) {
l := Layout{GitDir: " /var/lib/x.git/ ", WorkDirRoots: []string{"/tmp/", "/tmp", ""}}.Normalized()
require.Equal(t, "/var/lib/x.git", l.GitDir)
require.Equal(t, []string{"/tmp"}, l.WorkDirRoots)
}
+143
View File
@@ -0,0 +1,143 @@
package workspace
import (
"fmt"
"path"
"strings"
)
// ResolvePathIn anchors a relative path at the layout root.
func ResolvePathIn(l Layout, value string) string {
value = strings.TrimSpace(value)
if !path.IsAbs(value) {
root := l.Root
if root == "" {
root = Root
}
return path.Join(root, value)
}
return path.Clean(value)
}
// IsUnder reports whether p is root or lies beneath it. Both must be clean.
func IsUnder(p, root string) bool {
if root == "/" {
return strings.HasPrefix(p, "/")
}
return p == root || strings.HasPrefix(p, root+"/")
}
func underAny(p string, roots []string) bool {
for _, root := range roots {
if IsUnder(p, root) {
return true
}
}
return false
}
// ReadOnlyInputRoot returns the attachment root containing a clean absolute
// path. Shared machines reserve every session's input tree, not only the
// caller's: widening file access must not make another session's originals
// writable. This is a lexical tool rule, not an OS permission boundary.
func (l Layout) ReadOnlyInputRoot(clean string) string {
if l.InputDir != "" && IsUnder(clean, l.InputDir) {
return l.InputDir
}
if !l.IsSharedRemote() {
return ""
}
if IsUnder(clean, InputDir) {
return InputDir
}
relative, ok := strings.CutPrefix(clean, UserSessionsRoot+"/")
if !ok {
return ""
}
name, _, ok := strings.Cut(relative, "/")
if !ok || name == "" {
return ""
}
input := path.Join(UserSessionsRoot, name, "input")
if IsUnder(clean, input) {
return input
}
return ""
}
// CleanWriteFileIn normalizes a model-authored sandbox write and protects the
// attachment tree. The rule is the same on a session-owned and a shared
// machine: tools enforce WriteRoots at the tool layer.
func CleanWriteFileIn(l Layout, filePath string) (string, error) {
clean := ResolvePathIn(l, filePath)
if !path.IsAbs(clean) || clean == "." || clean == "/" {
return "", fmt.Errorf("sandbox: workspace write path %q must be an absolute file path", filePath)
}
if clean == l.Root || clean == l.OutputDir || clean == l.InputDir {
return "", fmt.Errorf("sandbox: workspace write path %q is a directory, not a file", filePath)
}
if input := l.ReadOnlyInputRoot(clean); input != "" {
return "", fmt.Errorf("sandbox: session input %s is read-only", input)
}
return clean, nil
}
// CleanInputPathIn requires a path inside the layout's attachment tree.
func CleanInputPathIn(l Layout, filePath string) (string, error) {
clean := path.Clean(strings.TrimSpace(filePath))
if l.InputDir != "" && IsUnder(clean, l.InputDir) {
return clean, nil
}
return "", fmt.Errorf("sandbox: session input path %q is outside %s", filePath, l.InputDir)
}
// CleanWorkDirIn requires an absolute working directory. Install calls keep
// the workspace/skills scope; every other layout allows any directory on the
// machine. None of these checks changes filesystem privileges.
func CleanWorkDirIn(l Layout, workDir string, allowSkillsRoot bool) (string, error) {
clean := path.Clean(strings.TrimSpace(workDir))
if !path.IsAbs(clean) {
return "", fmt.Errorf("sandbox: work dir %q must be absolute", workDir)
}
if allowSkillsRoot {
allowed := []string{l.Root, SkillsImageRoot}
if underAny(clean, allowed) {
return clean, nil
}
return "", fmt.Errorf("sandbox: work dir %q is outside allowed roots (%s)",
workDir, strings.Join(allowed, ", "))
}
return clean, nil
}
// ValidOutputDirIn reports whether dir may be used as the artifact directory.
// The workspace root itself is refused: it is the whole workspace, drafts
// included, and artifact collection reads that as "collects nothing".
func ValidOutputDirIn(l Layout, dir string) (string, bool) {
root := l.Root
if root == "" {
root = Root
}
clean := path.Clean(strings.TrimSpace(dir))
if !strings.HasPrefix(clean, root+"/") {
return "", false
}
return clean, true
}
// RunnableScriptIn reports whether scriptPath is a session-writable file that
// may be executed with an installed skill's interpreter. The attachment tree
// and the directory roots themselves are excluded.
func RunnableScriptIn(l Layout, scriptPath string) (string, bool) {
clean := path.Clean(strings.TrimSpace(scriptPath))
if clean == l.Root || clean == l.OutputDir || clean == l.InputDir {
return "", false
}
if !strings.HasPrefix(clean, l.Root+"/") {
return "", false
}
if l.InputDir != "" && strings.HasPrefix(clean, l.InputDir+"/") {
return "", false
}
return clean, true
}
+127
View File
@@ -0,0 +1,127 @@
package workspace
import (
"path"
"testing"
"github.com/stretchr/testify/require"
)
func userLayout(t *testing.T) Layout {
t.Helper()
l, err := UserSession(testSessionID)
require.NoError(t, err)
return l
}
func TestCleanWriteFileInRemoteMatchesHistoricalErrors(t *testing.T) {
l := Remote()
got, err := CleanWriteFileIn(l, "notes/a.md")
require.NoError(t, err)
require.Equal(t, "/workspace/notes/a.md", got)
got, err = CleanWriteFileIn(l, "/opt/elsewhere.txt")
require.NoError(t, err, "a session-owned machine still lets the manager write anywhere; tools enforce WriteRoots")
require.Equal(t, "/opt/elsewhere.txt", got)
_, err = CleanWriteFileIn(l, "/workspace/output")
require.EqualError(t, err, `sandbox: workspace write path "/workspace/output" is a directory, not a file`)
_, err = CleanWriteFileIn(l, "/workspace/input/a.pdf")
require.EqualError(t, err, "sandbox: session input /workspace/input is read-only")
_, err = CleanWriteFileIn(l, "/")
require.EqualError(t, err, `sandbox: workspace write path "/" must be an absolute file path`)
}
func TestCleanWriteFileInSharedAllowsTheWholeMachine(t *testing.T) {
l := userLayout(t)
got, err := CleanWriteFileIn(l, "report.md")
require.NoError(t, err)
require.Equal(t, l.Root+"/report.md", got)
got, err = CleanWriteFileIn(l, "/workspace/sessions/11111111-2222-4333-8444-555555555555/a.md")
require.NoError(t, err, "a sibling session's directory is not refused any more")
require.Equal(t, "/workspace/sessions/11111111-2222-4333-8444-555555555555/a.md", got)
_, err = CleanWriteFileIn(l, l.InputDir+"/x")
require.ErrorContains(t, err, "read-only")
}
func TestSharedWritesProtectEverySessionInput(t *testing.T) {
l := userLayout(t)
sibling, err := UserSession("7c9e6679-7425-40de-944b-e07fc1f90ae7")
require.NoError(t, err)
for _, p := range []string{
l.InputDir + "/original.txt",
sibling.InputDir,
sibling.InputDir + "/original.txt",
sibling.InputDir + "/nested/original.txt",
sibling.Root + "/output/../input/original.txt",
"../" + path.Base(sibling.Root) + "/input/original.txt",
InputDir + "/original.txt",
} {
_, err := CleanWriteFileIn(l, p)
require.ErrorContains(t, err, "read-only", p)
}
for _, p := range []string{
sibling.Root + "/notes.txt",
sibling.OutputDir + "/report.txt",
sibling.Root + "/input-copy/original.txt",
sibling.Root + "/project/input/data.txt",
} {
got, err := CleanWriteFileIn(l, p)
require.NoError(t, err, p)
require.Equal(t, p, got)
}
// A host project may legitimately contain a sessions/name/input tree.
host := Layout{Origin: OriginHost, Root: Root}
require.Empty(t, host.ReadOnlyInputRoot(sibling.InputDir+"/data.txt"))
require.Empty(t, Remote().ReadOnlyInputRoot(sibling.InputDir+"/data.txt"))
}
func TestCleanWorkDirIn(t *testing.T) {
remote := Remote()
got, err := CleanWorkDirIn(remote, "/opt/build", false)
require.NoError(t, err)
require.Equal(t, "/opt/build", got)
_, err = CleanWorkDirIn(remote, "/opt/build", true)
require.EqualError(t, err,
`sandbox: work dir "/opt/build" is outside allowed roots (/workspace, /opt/academy/tenant/skills)`)
_, err = CleanWorkDirIn(remote, "rel", false)
require.EqualError(t, err, `sandbox: work dir "rel" must be absolute`)
shared := userLayout(t)
for _, ok := range []string{shared.Root, "/workspace", "/workspace/sessions", "/tmp", "/opt", "/"} {
_, err := CleanWorkDirIn(shared, ok, false)
require.NoError(t, err, ok)
}
_, err = CleanWorkDirIn(shared, "/opt/build", true)
require.EqualError(t, err,
`sandbox: work dir "/opt/build" is outside allowed roots (`+shared.Root+`, /opt/academy/tenant/skills)`)
}
func TestCleanInputPathIn(t *testing.T) {
shared := userLayout(t)
got, err := CleanInputPathIn(shared, shared.InputDir+"/a.pdf")
require.NoError(t, err)
require.Equal(t, shared.InputDir+"/a.pdf", got)
_, err = CleanInputPathIn(shared, "/workspace/input/a.pdf")
require.Error(t, err)
}
func TestValidOutputDirAndRunnableScript(t *testing.T) {
remote := Remote()
got, ok := ValidOutputDirIn(remote, "/workspace/out2/")
require.True(t, ok)
require.Equal(t, "/workspace/out2", got)
_, ok = ValidOutputDirIn(remote, "/workspace")
require.False(t, ok)
shared := userLayout(t)
_, ok = ValidOutputDirIn(shared, "/workspace/output")
require.False(t, ok, "another session's tree is not a delivery directory")
_, ok = RunnableScriptIn(shared, shared.Root+"/run.py")
require.True(t, ok)
_, ok = RunnableScriptIn(shared, shared.InputDir+"/run.py")
require.False(t, ok)
_, ok = RunnableScriptIn(shared, "/workspace/run.py")
require.False(t, ok)
}