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

+68
View File
@@ -0,0 +1,68 @@
package automation
import (
"strings"
"time"
)
// RunVars are the values an instruction may reference.
type RunVars struct {
Now time.Time
LastRunAt *time.Time
LastSuccessAt *time.Time
RunID string
AutomationName string
Location *time.Location
}
func formatTime(t *time.Time, loc *time.Location) string {
if t == nil || t.IsZero() {
return ""
}
if loc == nil {
loc = time.UTC
}
return t.In(loc).Format(time.RFC3339)
}
// RenderInstruction substitutes {{now}}, {{last_run_at}},
// {{last_success_at}}, {{run_id}} and {{automation_name}}. Unknown
// placeholders are left alone so a literal "{{" in a prompt survives.
func RenderInstruction(instruction string, v RunVars) string {
now := v.Now
return strings.NewReplacer(
"{{now}}", formatTime(&now, v.Location),
"{{last_run_at}}", formatTime(v.LastRunAt, v.Location),
"{{last_success_at}}", formatTime(v.LastSuccessAt, v.Location),
"{{run_id}}", v.RunID,
"{{automation_name}}", v.AutomationName,
).Replace(instruction)
}
// maxCarriedResult bounds how much of the previous answer a per-run session
// is handed.
const maxCarriedResult = 4000
// RunQuery is the user turn of one run: the rendered instruction, preceded
// by the previous run's answer when the automation carries it over.
func RunQuery(instruction string, v RunVars, lastResult string) string {
query := RenderInstruction(instruction, v)
lastResult = strings.TrimSpace(lastResult)
if lastResult == "" {
return query
}
if r := []rune(lastResult); len(r) > maxCarriedResult {
lastResult = string(r[:maxCarriedResult]) + "…"
}
return "<previous_run_result>\n" + lastResult + "\n</previous_run_result>\n\n" + query
}
// RunNote tells the agent it is running unattended, so it does not wait on
// a user who is not there.
func RunNote(name string, scheduledAt time.Time, loc *time.Location) string {
at := scheduledAt
return "This turn is a scheduled run of the automation \"" + name + "\", fired for " +
formatTime(&at, loc) + ". No user is watching: do not ask clarifying questions; " +
"make reasonable assumptions, state them, and finish the task. Actions that need " +
"approval will wait for the owner."
}
+165
View File
@@ -0,0 +1,165 @@
// Package automation holds the scheduling rules of agent automations: when
// a trigger fires, and what an automation's run is told. It does no I/O.
package automation
import (
"errors"
"fmt"
"strings"
"time"
// Timezones must resolve on hosts without a zoneinfo database (Lite).
_ "time/tzdata"
"github.com/robfig/cron/v3"
"academy/internal/types"
)
// DefaultMinInterval is the shortest gap allowed between two runs.
const DefaultMinInterval = 5 * time.Minute
// ErrInvalidTrigger wraps every trigger validation failure.
var ErrInvalidTrigger = errors.New("invalid trigger")
var (
standardParser = cron.NewParser(
cron.Minute | cron.Hour | cron.Dom | cron.Month | cron.Dow | cron.Descriptor,
)
secondsParser = cron.NewParser(
cron.Second | cron.Minute | cron.Hour | cron.Dom | cron.Month | cron.Dow | cron.Descriptor,
)
)
// Schedule is a validated trigger.
type Schedule struct {
trigger types.AutomationTrigger
location *time.Location
cron cron.Schedule
once time.Time
}
// Wall-clock forms a once trigger accepts, read in its timezone. The first
// match wins, so a zone suffix is never silently dropped.
var onceLayouts = []string{
time.RFC3339Nano,
time.RFC3339,
"2006-01-02T15:04:05",
"2006-01-02 15:04:05",
"2006-01-02T15:04",
"2006-01-02 15:04",
}
func parseOnce(at string, loc *time.Location) (time.Time, error) {
for _, layout := range onceLayouts {
if parsed, err := time.ParseInLocation(layout, at, loc); err == nil {
return parsed.UTC(), nil
}
}
return time.Time{}, invalid("cannot read %q as a time; use RFC3339 or \"2006-01-02 15:04\"", at)
}
func invalid(format string, args ...any) error {
return fmt.Errorf("%w: %s", ErrInvalidTrigger, fmt.Sprintf(format, args...))
}
// Parse validates t. A cron expression has five fields (minute first) or
// six (seconds first), or is a descriptor such as @daily; it is evaluated in
// t.Timezone, which a CRON_TZ= prefix in the expression may not override.
func Parse(t types.AutomationTrigger) (*Schedule, error) {
t.Expr = strings.TrimSpace(t.Expr)
t.Timezone = strings.TrimSpace(t.Timezone)
loc := time.UTC
if t.Timezone != "" {
var err error
if loc, err = time.LoadLocation(t.Timezone); err != nil {
return nil, invalid("unknown timezone %q", t.Timezone)
}
}
s := &Schedule{trigger: t, location: loc}
switch t.Type {
case types.AutomationTriggerCron:
if t.Expr == "" {
return nil, invalid("a cron trigger needs an expression")
}
if strings.HasPrefix(t.Expr, "CRON_TZ=") || strings.HasPrefix(t.Expr, "TZ=") {
return nil, invalid("set the timezone field instead of a TZ prefix")
}
parser := standardParser
if !strings.HasPrefix(t.Expr, "@") && len(strings.Fields(t.Expr)) == 6 {
parser = secondsParser
}
sched, err := parser.Parse(t.Expr)
if err != nil {
return nil, invalid("%v", err)
}
s.cron = sched
case types.AutomationTriggerOnce:
if strings.TrimSpace(t.At) == "" {
return nil, invalid("a once trigger needs a time")
}
if t.Expr != "" {
return nil, invalid("a once trigger takes no expression")
}
at, err := parseOnce(strings.TrimSpace(t.At), loc)
if err != nil {
return nil, err
}
s.once = at
s.trigger.At = at.Format(time.RFC3339)
default:
return nil, invalid("unknown trigger type %q", t.Type)
}
return s, nil
}
// Trigger is the normalized trigger.
func (s *Schedule) Trigger() types.AutomationTrigger { return s.trigger }
// Next is the first time the trigger fires strictly after after, or nil when
// it never fires again.
func (s *Schedule) Next(after time.Time) *time.Time {
if s.cron == nil {
at := s.once
if at.After(after) {
return &at
}
return nil
}
next := s.cron.Next(after.In(s.location))
if next.IsZero() {
return nil
}
next = next.UTC()
return &next
}
// Upcoming is the next n firing times after after.
func (s *Schedule) Upcoming(after time.Time, n int) []time.Time {
var out []time.Time
for len(out) < n {
next := s.Next(after)
if next == nil {
break
}
out = append(out, *next)
after = *next
}
return out
}
// CheckInterval rejects a cron trigger that can fire twice within min. It
// looks at the gaps over the next days, which catches expressions such as
// "* * * * *" and "*/2 9 * * *" alike.
func (s *Schedule) CheckInterval(from time.Time, minInterval time.Duration) error {
if s.cron == nil || minInterval <= 0 {
return nil
}
times := s.Upcoming(from, 64)
for i := 1; i < len(times); i++ {
if gap := times[i].Sub(times[i-1]); gap < minInterval {
return invalid("runs would be %s apart; the minimum is %s", gap, minInterval)
}
}
return nil
}
+99
View File
@@ -0,0 +1,99 @@
package automation
import (
"errors"
"strings"
"testing"
"time"
"github.com/stretchr/testify/require"
"academy/internal/types"
)
func cronTrigger(expr, tz string) types.AutomationTrigger {
return types.AutomationTrigger{Type: types.AutomationTriggerCron, Expr: expr, Timezone: tz}
}
func TestParseRejectsBadTriggers(t *testing.T) {
for name, tr := range map[string]types.AutomationTrigger{
"empty type": {},
"no expr": cronTrigger("", ""),
"garbage": cronTrigger("every day", ""),
"bad timezone": cronTrigger("0 9 * * *", "Mars/Olympus"),
"tz prefix": cronTrigger("CRON_TZ=Asia/Tokyo 0 9 * * *", ""),
"once without": {Type: types.AutomationTriggerOnce},
"once with expr": {Type: types.AutomationTriggerOnce, Expr: "0 9 * * *", At: "2026-10-19T22:09:00Z"},
"once nonsense": {Type: types.AutomationTriggerOnce, At: "tomorrow"},
} {
_, err := Parse(tr)
require.Truef(t, errors.Is(err, ErrInvalidTrigger), "%s: %v", name, err)
}
}
func TestNextHonorsTimezone(t *testing.T) {
s, err := Parse(cronTrigger("0 9 * * *", "Asia/Shanghai"))
require.NoError(t, err)
from := time.Date(2026, 10, 19, 2, 0, 0, 0, time.UTC) // 10:00 Shanghai
next := s.Next(from)
require.NotNil(t, next)
require.Equal(t, time.Date(2026, 10, 20, 1, 0, 0, 0, time.UTC), *next)
require.Equal(t, time.UTC, next.Location())
}
func TestSixFieldsAndDescriptors(t *testing.T) {
from := time.Date(2026, 10, 19, 0, 0, 0, 0, time.UTC)
s, err := Parse(cronTrigger("0 30 9 * * MON", ""))
require.NoError(t, err)
require.Equal(t, time.Date(2026, 10, 19, 9, 30, 0, 0, time.UTC), *s.Next(from))
s, err = Parse(cronTrigger("@daily", ""))
require.NoError(t, err)
require.Equal(t, time.Date(2026, 10, 20, 0, 0, 0, 0, time.UTC), *s.Next(from))
}
func TestOnceFiresOnce(t *testing.T) {
at := time.Date(2026, 10, 20, 7, 0, 0, 0, time.UTC)
for _, given := range []types.AutomationTrigger{
{Type: types.AutomationTriggerOnce, At: "2026-10-20T08:00:00+01:00"},
{Type: types.AutomationTriggerOnce, At: "2026-10-20 15:00", Timezone: "Asia/Shanghai"},
{Type: types.AutomationTriggerOnce, At: "2026-10-20T15:00:00", Timezone: "Asia/Shanghai"},
} {
s, err := Parse(given)
require.NoError(t, err, given.At)
require.Equal(t, "2026-10-20T07:00:00Z", s.Trigger().At)
from := time.Date(2026, 10, 19, 0, 0, 0, 0, time.UTC)
require.Equal(t, at, *s.Next(from))
require.Nil(t, s.Next(at))
require.Len(t, s.Upcoming(from, 3), 1)
}
}
func TestCheckInterval(t *testing.T) {
from := time.Date(2026, 10, 19, 0, 0, 0, 0, time.UTC)
for expr, ok := range map[string]bool{
"* * * * *": false,
"*/2 9 * * *": false,
"*/5 * * * *": true,
"0 9,10 * * *": true,
"0 0 9 * * *": true,
"*/30 * * * * *": false,
} {
s, err := Parse(cronTrigger(expr, ""))
require.NoError(t, err, expr)
err = s.CheckInterval(from, DefaultMinInterval)
require.Equalf(t, ok, err == nil, "%s: %v", expr, err)
}
}
func TestRunQuery(t *testing.T) {
loc, _ := time.LoadLocation("Asia/Shanghai")
now := time.Date(2026, 10, 19, 1, 0, 0, 0, time.UTC)
v := RunVars{Now: now, RunID: "r1", AutomationName: "日报", Location: loc}
q := RunQuery("{{automation_name}} at {{now}} since {{last_run_at}} {{unknown}}", v, "")
require.Equal(t, "日报 at 2026-10-19T09:00:00+08:00 since {{unknown}}", q)
q = RunQuery("go", v, strings.Repeat("长", maxCarriedResult+10))
require.True(t, strings.HasPrefix(q, "<previous_run_result>\n"))
require.True(t, strings.HasSuffix(q, "…\n</previous_run_result>\n\ngo"))
}