This commit is contained in:
2026-06-22 08:55:57 +08:00
parent dbb87823e8
commit 6ade6e8fa9
325 changed files with 41131 additions and 855 deletions
+62
View File
@@ -0,0 +1,62 @@
package run
// exec_dto.go 定义一次性 exec(run_command / run_tests)的请求/响应契约。
// 与 run profile 不同:exec 是同步请求-响应,输出在内存捕获后一次性返回。
// ExecCommandReq 是 run_command 的输入。WorktreeID 为空 → 在 workspace main_path 执行。
type ExecCommandReq struct {
WorkspaceID string `json:"workspace_id"`
WorktreeID string `json:"worktree_id,omitempty"`
Command string `json:"command"`
Args []string `json:"args,omitempty"`
Env map[string]string `json:"env,omitempty"` // 临时覆盖(明文,不落库)
TimeoutSec int `json:"timeout_sec,omitempty"`
}
// ExecCommandResp 是 run_command 的结构化结果。
type ExecCommandResp struct {
ExitCode int `json:"exit_code"`
Stdout string `json:"stdout"`
Stderr string `json:"stderr"`
DurationMs int64 `json:"duration_ms"`
TimedOut bool `json:"timed_out"`
Truncated bool `json:"truncated"`
}
// ExecTestsReq 是 run_tests 的输入:在 run_command 基础上增加 Format(解析格式)。
type ExecTestsReq struct {
WorkspaceID string `json:"workspace_id"`
WorktreeID string `json:"worktree_id,omitempty"`
Command string `json:"command"`
Args []string `json:"args,omitempty"`
Format string `json:"format,omitempty"` // gotest|junit|vitest|auto(默认 auto)
Env map[string]string `json:"env,omitempty"`
TimeoutSec int `json:"timeout_sec,omitempty"`
}
// ExecTestsResp 是 run_tests 的结果:run_command 输出 + 结构化测试摘要。
// ParseError 非空表示解析失败,但原始输出与退出码仍可用——run_tests 永不因解析失败
// 而向 agent 返回错误。
type ExecTestsResp struct {
ExecCommandResp
Summary TestSummary `json:"summary"`
ParseError string `json:"parse_error,omitempty"`
}
// TestSummary 是跨框架(go test / JUnit / vitest)归一化的测试结果摘要。
type TestSummary struct {
Framework string `json:"framework"`
Total int `json:"total"`
Passed int `json:"passed"`
Failed int `json:"failed"`
Skipped int `json:"skipped"`
DurationMs int64 `json:"duration_ms"`
Failures []TestFailure `json:"failures"`
}
// TestFailure 描述单个失败用例。Package 对非 go 框架可能为空。
type TestFailure struct {
Name string `json:"name"`
Package string `json:"package,omitempty"`
Message string `json:"message,omitempty"`
}
+308
View File
@@ -0,0 +1,308 @@
package run
import (
"bufio"
"encoding/json"
"encoding/xml"
"errors"
"strings"
)
// exec_parsers.go 把常见测试输出(go test -json / JUnit XML / vitest --reporter=json)
// 归一化为 TestSummary。所有解析器都是防御性的:永不 panic;无法解析时返回 error,
// 由 RunTests 折成 ParseError(始终保留原始输出)。
// parseTestOutput 按 format 分派;format=="" 或 "auto" 时按内容嗅探。
func parseTestOutput(format, stdout, stderr string) (TestSummary, error) {
combined := stdout
if strings.TrimSpace(combined) == "" {
combined = stderr
}
switch strings.ToLower(strings.TrimSpace(format)) {
case "gotest":
return parseGoTestJSON([]byte(combined))
case "junit":
return parseJUnitXML([]byte(combined))
case "vitest":
return parseVitestJSON([]byte(combined))
case "", "auto":
return sniffAndParse(combined)
default:
return TestSummary{}, errors.New("unknown test format: " + format)
}
}
// sniffAndParse 按首个非空 token 推断框架:JSON 行 + Action 字段 → gotest;
// JSON 对象含 numPassedTests → vitest;'<testsuite' → junit。
func sniffAndParse(s string) (TestSummary, error) {
trimmed := strings.TrimSpace(s)
if trimmed == "" {
return TestSummary{}, errors.New("empty test output")
}
switch trimmed[0] {
case '<':
if strings.Contains(trimmed, "<testsuite") {
return parseJUnitXML([]byte(s))
}
case '{', '[':
// vitest 是单个 JSON 对象(含 numPassedTests);go test -json 是 JSONL(每行含 Action)。
if strings.Contains(trimmed, "numPassedTests") || strings.Contains(trimmed, "testResults") {
return parseVitestJSON([]byte(s))
}
if strings.Contains(trimmed, "\"Action\"") {
return parseGoTestJSON([]byte(s))
}
// 退而求其次:单对象当 vitest,多行当 gotest。
if strings.HasPrefix(trimmed, "{\"Time\"") || strings.HasPrefix(trimmed, "{\"Action\"") {
return parseGoTestJSON([]byte(s))
}
return parseVitestJSON([]byte(s))
}
return TestSummary{}, errors.New("could not sniff test output format")
}
// ===== go test -json =====
type goTestEvent struct {
Action string `json:"Action"`
Package string `json:"Package"`
Test string `json:"Test"`
Output string `json:"Output"`
Elapsed float64 `json:"Elapsed"`
}
// parseGoTestJSON 解析 `go test -json` 的 JSONL 流。只统计具体 test(Test 非空)的
// pass/fail/skip;包级 action 不计入用例数。失败用例汇集其 output 作为 message。
func parseGoTestJSON(data []byte) (TestSummary, error) {
if len(strings.TrimSpace(string(data))) == 0 {
return TestSummary{}, errors.New("empty go test output")
}
sum := TestSummary{Framework: "gotest"}
type key struct{ pkg, test string }
outputs := map[key][]string{}
var totalElapsed float64
var anyEvent bool
sc := bufio.NewScanner(strings.NewReader(string(data)))
sc.Buffer(make([]byte, 0, 64*1024), 4*1024*1024)
for sc.Scan() {
line := strings.TrimSpace(sc.Text())
if line == "" || line[0] != '{' {
continue
}
var ev goTestEvent
if err := json.Unmarshal([]byte(line), &ev); err != nil {
continue // 非 JSON 行(如裸 build 错误)跳过,保持防御性。
}
anyEvent = true
if ev.Test == "" {
// 包级事件:累计耗时。
if ev.Action == "pass" || ev.Action == "fail" {
totalElapsed += ev.Elapsed
}
continue
}
k := key{ev.Package, ev.Test}
switch ev.Action {
case "output":
outputs[k] = append(outputs[k], ev.Output)
case "pass":
sum.Passed++
case "skip":
sum.Skipped++
case "fail":
sum.Failed++
sum.Failures = append(sum.Failures, TestFailure{
Name: ev.Test,
Package: ev.Package,
Message: strings.TrimSpace(strings.Join(outputs[k], "")),
})
}
}
if err := sc.Err(); err != nil {
return sum, err
}
if !anyEvent {
return sum, errors.New("no go test -json events found")
}
sum.Total = sum.Passed + sum.Failed + sum.Skipped
sum.DurationMs = int64(totalElapsed * 1000)
return sum, nil
}
// ===== JUnit XML =====
type junitTestSuites struct {
XMLName xml.Name `xml:"testsuites"`
Suites []junitTestSuite `xml:"testsuite"`
}
type junitTestSuite struct {
XMLName xml.Name `xml:"testsuite"`
Name string `xml:"name,attr"`
Tests int `xml:"tests,attr"`
Failures int `xml:"failures,attr"`
Errors int `xml:"errors,attr"`
Skipped int `xml:"skipped,attr"`
Time float64 `xml:"time,attr"`
TestCases []junitTestCase `xml:"testcase"`
// 嵌套 testsuite(部分工具输出 testsuites>testsuite>testsuite)。
Nested []junitTestSuite `xml:"testsuite"`
}
type junitTestCase struct {
Name string `xml:"name,attr"`
ClassName string `xml:"classname,attr"`
Time float64 `xml:"time,attr"`
Failure *junitDetail `xml:"failure"`
Error *junitDetail `xml:"error"`
Skipped *junitSkipped `xml:"skipped"`
}
type junitDetail struct {
Message string `xml:"message,attr"`
Body string `xml:",chardata"`
}
type junitSkipped struct {
Message string `xml:"message,attr"`
}
// parseJUnitXML 解析 JUnit XML(顶层 testsuites 或裸 testsuite)。按 testcase 逐个
// 统计,failure/error → failed,skipped → skipped,其余 → passed。
func parseJUnitXML(data []byte) (TestSummary, error) {
if strings.TrimSpace(string(data)) == "" {
return TestSummary{}, errors.New("empty junit output")
}
sum := TestSummary{Framework: "junit"}
var suites []junitTestSuite
var root junitTestSuites
if err := xml.Unmarshal(data, &root); err == nil && len(root.Suites) > 0 {
suites = root.Suites
} else {
var single junitTestSuite
if err := xml.Unmarshal(data, &single); err != nil {
return sum, err
}
suites = []junitTestSuite{single}
}
var totalTime float64
var walk func(s junitTestSuite)
walk = func(s junitTestSuite) {
totalTime += s.Time
for _, tc := range s.TestCases {
sum.Total++
pkg := tc.ClassName
switch {
case tc.Failure != nil || tc.Error != nil:
sum.Failed++
d := tc.Failure
if d == nil {
d = tc.Error
}
msg := strings.TrimSpace(d.Message)
if msg == "" {
msg = strings.TrimSpace(d.Body)
}
sum.Failures = append(sum.Failures, TestFailure{Name: tc.Name, Package: pkg, Message: msg})
case tc.Skipped != nil:
sum.Skipped++
default:
sum.Passed++
}
}
for _, n := range s.Nested {
walk(n)
}
}
for _, s := range suites {
walk(s)
}
if sum.Total == 0 {
return sum, errors.New("no junit testcases found")
}
sum.DurationMs = int64(totalTime * 1000)
return sum, nil
}
// ===== vitest --reporter=json =====
type vitestReport struct {
NumTotalTests *int `json:"numTotalTests"`
NumPassedTests *int `json:"numPassedTests"`
NumFailedTests *int `json:"numFailedTests"`
NumPendingTests *int `json:"numPendingTests"`
StartTime *int64 `json:"startTime"`
TestResults []vitestFileResult `json:"testResults"`
}
type vitestFileResult struct {
Name string `json:"name"`
AssertionResults []vitestAssertion `json:"assertionResults"`
}
type vitestAssertion struct {
Title string `json:"title"`
FullName string `json:"fullName"`
Status string `json:"status"` // passed|failed|skipped|pending
FailureMessages []string `json:"failureMessages"`
Duration float64 `json:"duration"`
}
// parseVitestJSON 解析 vitest(jest 兼容)的 JSON 报告。优先使用顶层计数;
// 同时遍历 testResults 收集失败用例名与首条 failureMessage。
func parseVitestJSON(data []byte) (TestSummary, error) {
if strings.TrimSpace(string(data)) == "" {
return TestSummary{}, errors.New("empty vitest output")
}
var rep vitestReport
if err := json.Unmarshal(data, &rep); err != nil {
return TestSummary{}, err
}
sum := TestSummary{Framework: "vitest"}
var durMs float64
for _, fr := range rep.TestResults {
for _, a := range fr.AssertionResults {
switch a.Status {
case "failed":
sum.Failed++
msg := ""
if len(a.FailureMessages) > 0 {
msg = strings.TrimSpace(a.FailureMessages[0])
}
name := a.FullName
if name == "" {
name = a.Title
}
sum.Failures = append(sum.Failures, TestFailure{Name: name, Package: fr.Name, Message: msg})
case "skipped", "pending", "todo":
sum.Skipped++
case "passed":
sum.Passed++
}
durMs += a.Duration
}
}
// 顶层计数优先(更可靠);没有就用遍历得到的计数。
if rep.NumPassedTests != nil {
sum.Passed = *rep.NumPassedTests
}
if rep.NumFailedTests != nil {
sum.Failed = *rep.NumFailedTests
}
if rep.NumPendingTests != nil {
sum.Skipped = *rep.NumPendingTests
}
if rep.NumTotalTests != nil {
sum.Total = *rep.NumTotalTests
} else {
sum.Total = sum.Passed + sum.Failed + sum.Skipped
}
if sum.Total == 0 && len(rep.TestResults) == 0 && rep.NumTotalTests == nil {
return sum, errors.New("not a vitest report")
}
sum.DurationMs = int64(durMs)
return sum, nil
}
+129
View File
@@ -0,0 +1,129 @@
package run
import (
"os"
"path/filepath"
"testing"
)
func readFixture(t *testing.T, name string) []byte {
t.Helper()
b, err := os.ReadFile(filepath.Join("testdata", name))
if err != nil {
t.Fatalf("read fixture %s: %v", name, err)
}
return b
}
func TestParseGoTestJSON(t *testing.T) {
sum, err := parseGoTestJSON(readFixture(t, "gotest.jsonl"))
if err != nil {
t.Fatalf("parse: %v", err)
}
if sum.Framework != "gotest" {
t.Fatalf("framework = %q", sum.Framework)
}
if sum.Passed != 1 || sum.Failed != 1 || sum.Skipped != 1 || sum.Total != 3 {
t.Fatalf("counts p=%d f=%d s=%d t=%d", sum.Passed, sum.Failed, sum.Skipped, sum.Total)
}
if len(sum.Failures) != 1 || sum.Failures[0].Name != "TestFail" || sum.Failures[0].Package != "example/pkg" {
t.Fatalf("failures = %+v", sum.Failures)
}
if sum.Failures[0].Message == "" {
t.Fatal("failure message should not be empty")
}
}
func TestParseJUnitXML(t *testing.T) {
sum, err := parseJUnitXML(readFixture(t, "junit.xml"))
if err != nil {
t.Fatalf("parse: %v", err)
}
if sum.Framework != "junit" {
t.Fatalf("framework = %q", sum.Framework)
}
if sum.Passed != 1 || sum.Failed != 1 || sum.Skipped != 1 || sum.Total != 3 {
t.Fatalf("counts p=%d f=%d s=%d t=%d", sum.Passed, sum.Failed, sum.Skipped, sum.Total)
}
if len(sum.Failures) != 1 || sum.Failures[0].Name != "testFails" {
t.Fatalf("failures = %+v", sum.Failures)
}
if sum.Failures[0].Message != "expected true but was false" {
t.Fatalf("failure message = %q", sum.Failures[0].Message)
}
}
func TestParseVitestJSON(t *testing.T) {
sum, err := parseVitestJSON(readFixture(t, "vitest.json"))
if err != nil {
t.Fatalf("parse: %v", err)
}
if sum.Framework != "vitest" {
t.Fatalf("framework = %q", sum.Framework)
}
if sum.Passed != 1 || sum.Failed != 1 || sum.Skipped != 1 || sum.Total != 3 {
t.Fatalf("counts p=%d f=%d s=%d t=%d", sum.Passed, sum.Failed, sum.Skipped, sum.Total)
}
if len(sum.Failures) != 1 || sum.Failures[0].Name != "sum > subtracts" {
t.Fatalf("failures = %+v", sum.Failures)
}
if sum.Failures[0].Message != "expected 1 to be 2" {
t.Fatalf("failure message = %q", sum.Failures[0].Message)
}
}
// TestParseTestOutput_Auto 验证 auto 嗅探把各格式路由到正确解析器。
func TestParseTestOutput_Auto(t *testing.T) {
cases := []struct {
name string
fixture string
want string
}{
{"gotest", "gotest.jsonl", "gotest"},
{"junit", "junit.xml", "junit"},
{"vitest", "vitest.json", "vitest"},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
sum, err := parseTestOutput("auto", string(readFixture(t, tc.fixture)), "")
if err != nil {
t.Fatalf("parse: %v", err)
}
if sum.Framework != tc.want {
t.Fatalf("framework = %q, want %q", sum.Framework, tc.want)
}
})
}
}
// TestParseTestOutput_Malformed 验证解析失败返回 error(由 RunTests 折成 ParseError),
// 永不 panic。
func TestParseTestOutput_Malformed(t *testing.T) {
cases := []struct {
format string
in string
}{
{"gotest", "not json at all"},
{"junit", "<broken><xml"},
{"vitest", "{not valid"},
{"auto", ""},
{"auto", "random text with no structure"},
}
for _, tc := range cases {
_, err := parseTestOutput(tc.format, tc.in, "")
if err == nil {
t.Fatalf("format %q input %q: expected parse error, got nil", tc.format, tc.in)
}
}
}
// TestParseGoTestJSON_StderrFallback 验证 stdout 为空时退回 stderr。
func TestParseTestOutput_StderrFallback(t *testing.T) {
sum, err := parseTestOutput("auto", "", string(readFixture(t, "gotest.jsonl")))
if err != nil {
t.Fatalf("parse: %v", err)
}
if sum.Framework != "gotest" || sum.Total != 3 {
t.Fatalf("got %+v", sum)
}
}
+246
View File
@@ -0,0 +1,246 @@
package run
import (
"context"
"log/slog"
"path/filepath"
"strings"
"time"
"github.com/google/uuid"
"github.com/yan1h/agent-coding-workflow/internal/audit"
"github.com/yan1h/agent-coding-workflow/internal/infra/crypto"
"github.com/yan1h/agent-coding-workflow/internal/infra/errs"
procgrp "github.com/yan1h/agent-coding-workflow/internal/infra/proc"
"github.com/yan1h/agent-coding-workflow/internal/workspace"
)
// ExecConfig 是 ExecService 的运行参数(派生自 config.RunConfig)。
type ExecConfig struct {
EnvWhitelist []string
DefaultTimeout time.Duration
MaxTimeout time.Duration
MaxOutputBytes int
KillGrace time.Duration
AllowedCommands []string // 空 = 显式不限制命令;生产环境应保持非空白名单
}
// ExecService 提供 agent 自验证用的一次性 exec 原语:RunCommand / RunTests。
// 与 run profile(长驻进程)共享 workspace 鉴权(要求 WRITE,因为 exec 会修改工作树)、
// env 白名单(绝不泄漏 APP_MASTER_KEY / DB DSN / git 凭据)、命令白名单与 proc 树终止。
//
// 无状态、同步:每次调用执行一条命令直至退出/超时后返回,不持有运行态,
// 因此无需 ShutdownAll 注册——超时与 ctx 取消由 proc.RunOnce 内部处理。
type ExecService struct {
wsRepo workspace.Repository
wtSvc workspace.WorktreeService
pa workspace.ProjectAccess
rec audit.Recorder
enc *crypto.Encryptor
cfg ExecConfig
log *slog.Logger
}
// NewExecService 构造 ExecService。enc 当前未用于 exec(请求 env 覆盖是临时明文),
// 保留参数以与 run.Service 装配签名一致并便于将来落库加密。
func NewExecService(
wsRepo workspace.Repository,
wtSvc workspace.WorktreeService,
pa workspace.ProjectAccess,
rec audit.Recorder,
enc *crypto.Encryptor,
cfg ExecConfig,
log *slog.Logger,
) *ExecService {
if log == nil {
log = slog.Default()
}
if cfg.DefaultTimeout <= 0 {
cfg.DefaultTimeout = 60 * time.Second
}
if cfg.MaxTimeout <= 0 {
cfg.MaxTimeout = 600 * time.Second
}
if cfg.MaxOutputBytes <= 0 {
cfg.MaxOutputBytes = 1 << 20
}
return &ExecService{wsRepo: wsRepo, wtSvc: wtSvc, pa: pa, rec: rec, enc: enc, cfg: cfg, log: log}
}
// RunCommand 在指定 workspace(main_path 或某 worktree)执行一条命令并返回结构化结果。
func (s *ExecService) RunCommand(ctx context.Context, c workspace.Caller, req ExecCommandReq) (ExecCommandResp, error) {
spec, _, err := s.prepare(ctx, c, req.WorkspaceID, req.WorktreeID, req.Command, req.Args, req.Env, req.TimeoutSec)
if err != nil {
return ExecCommandResp{}, err
}
res, err := s.run(ctx, c, "exec.run_command", req.WorkspaceID, req.WorktreeID, req.Command, spec)
if err != nil {
return ExecCommandResp{}, err
}
return res, nil
}
// RunTests 执行测试命令并把 stdout 解析为结构化摘要。解析失败时填 ParseError 而非报错,
// 始终返回原始输出与退出码——agent 永远能拿到可用信息。
func (s *ExecService) RunTests(ctx context.Context, c workspace.Caller, req ExecTestsReq) (ExecTestsResp, error) {
spec, _, err := s.prepare(ctx, c, req.WorkspaceID, req.WorktreeID, req.Command, req.Args, req.Env, req.TimeoutSec)
if err != nil {
return ExecTestsResp{}, err
}
cmdRes, err := s.run(ctx, c, "exec.run_tests", req.WorkspaceID, req.WorktreeID, req.Command, spec)
if err != nil {
return ExecTestsResp{}, err
}
resp := ExecTestsResp{ExecCommandResp: cmdRes}
summary, perr := parseTestOutput(req.Format, cmdRes.Stdout, cmdRes.Stderr)
if perr != nil {
resp.ParseError = perr.Error()
}
resp.Summary = summary
return resp, nil
}
// prepare 做命令/超时校验、鉴权、cwd 与 env 解析,产出可直接交给 proc.RunOnce 的 spec。
func (s *ExecService) prepare(
ctx context.Context,
c workspace.Caller,
workspaceID, worktreeID, command string,
args []string,
envOverrides map[string]string,
timeoutSec int,
) (procgrp.ExecSpec, *workspace.Workspace, error) {
if strings.TrimSpace(command) == "" {
return procgrp.ExecSpec{}, nil, errs.New(errs.CodeRunCommandInvalid, "command must not be empty")
}
if err := s.checkAllowed(command); err != nil {
return procgrp.ExecSpec{}, nil, err
}
wsID, err := uuid.Parse(workspaceID)
if err != nil {
return procgrp.ExecSpec{}, nil, errs.Wrap(err, errs.CodeInvalidInput, "workspace_id parse")
}
ws, err := s.wsRepo.GetWorkspaceByID(ctx, wsID)
if err != nil {
return procgrp.ExecSpec{}, nil, err
}
_, canWrite, err := s.pa.ResolveByID(ctx, c.UserID, c.IsAdmin, ws.ProjectID)
if err != nil {
return procgrp.ExecSpec{}, nil, err
}
if !canWrite {
return procgrp.ExecSpec{}, nil, errs.New(errs.CodeForbidden, "no write access to this workspace")
}
dir, err := s.resolveCwd(ctx, c, wsID, ws, worktreeID)
if err != nil {
return procgrp.ExecSpec{}, nil, err
}
spec := procgrp.ExecSpec{
Command: command,
Args: args,
Dir: dir,
Env: buildEnvFromWhitelist(s.cfg.EnvWhitelist, envOverrides),
Timeout: s.clampTimeout(timeoutSec),
KillGrace: s.cfg.KillGrace,
MaxOutputBytes: s.cfg.MaxOutputBytes,
}
return spec, ws, nil
}
// run 执行 spec 并写审计,把 proc 结果折成 ExecCommandResp。超时映射为 run.exec_timeout。
func (s *ExecService) run(
ctx context.Context,
c workspace.Caller,
action, workspaceID, worktreeID, command string,
spec procgrp.ExecSpec,
) (ExecCommandResp, error) {
res, err := procgrp.RunOnce(ctx, spec)
if err != nil {
return ExecCommandResp{}, errs.Wrap(err, errs.CodeRunExecFailed, "exec command")
}
resp := ExecCommandResp{
ExitCode: res.ExitCode,
Stdout: res.Stdout,
Stderr: res.Stderr,
DurationMs: res.Duration.Milliseconds(),
TimedOut: res.TimedOut,
Truncated: res.Truncated,
}
s.audit(ctx, c, action, workspaceID, map[string]any{
"workspace_id": workspaceID,
"worktree_id": worktreeID,
"command": command,
"exit_code": res.ExitCode,
"duration_ms": resp.DurationMs,
"timed_out": res.TimedOut,
})
return resp, nil
}
// checkAllowed 在 AllowedCommands 非空时要求命令 base name(去掉路径与 .exe 后缀)在白名单内。
func (s *ExecService) checkAllowed(command string) error {
if len(s.cfg.AllowedCommands) == 0 {
return nil
}
base := strings.ToLower(filepath.Base(command))
base = strings.TrimSuffix(base, ".exe")
for _, a := range s.cfg.AllowedCommands {
if strings.ToLower(strings.TrimSuffix(a, ".exe")) == base {
return nil
}
}
return errs.New(errs.CodeRunExecCommandNotAllowed, "command not in allowed list: "+base)
}
// clampTimeout 把请求超时夹到 [1s, MaxTimeout];0/负 → DefaultTimeout。
func (s *ExecService) clampTimeout(sec int) time.Duration {
if sec <= 0 {
return s.cfg.DefaultTimeout
}
d := time.Duration(sec) * time.Second
if d < time.Second {
d = time.Second
}
if d > s.cfg.MaxTimeout {
d = s.cfg.MaxTimeout
}
return d
}
// resolveCwd 解析执行目录:worktreeID 非空 → 校验归属并返回其 Path;否则 main_path。
func (s *ExecService) resolveCwd(ctx context.Context, c workspace.Caller, wsID uuid.UUID, ws *workspace.Workspace, worktreeID string) (string, error) {
if strings.TrimSpace(worktreeID) == "" {
return ws.MainPath, nil
}
wtID, err := uuid.Parse(worktreeID)
if err != nil {
return "", errs.Wrap(err, errs.CodeInvalidInput, "worktree_id parse")
}
wts, err := s.wtSvc.List(ctx, c, wsID)
if err != nil {
return "", err
}
for _, wt := range wts {
if wt.ID == wtID {
return wt.Path, nil
}
}
return "", errs.New(errs.CodeNotFound, "worktree not found in workspace")
}
func (s *ExecService) audit(ctx context.Context, c workspace.Caller, action, targetID string, meta map[string]any) {
if s.rec == nil {
return
}
uid := c.UserID
_ = s.rec.Record(ctx, audit.Entry{
UserID: &uid,
Action: action,
TargetType: "workspace",
TargetID: targetID,
Metadata: meta,
})
}
+356
View File
@@ -0,0 +1,356 @@
package run
import (
"context"
"os"
"runtime"
"strings"
"testing"
"time"
"github.com/google/uuid"
"github.com/yan1h/agent-coding-workflow/internal/infra/errs"
"github.com/yan1h/agent-coding-workflow/internal/workspace"
)
// ===== fakes =====
// fakeWsRepo 只实现 GetWorkspaceByID;其余方法经嵌入 interface 满足契约,被调用即 panic。
type fakeWsRepo struct {
workspace.Repository
ws *workspace.Workspace
err error
}
func (f *fakeWsRepo) GetWorkspaceByID(context.Context, uuid.UUID) (*workspace.Workspace, error) {
if f.err != nil {
return nil, f.err
}
return f.ws, nil
}
// fakeWtSvc 只实现 List。
type fakeWtSvc struct {
workspace.WorktreeService
wts []*workspace.Worktree
err error
}
func (f *fakeWtSvc) List(context.Context, workspace.Caller, uuid.UUID) ([]*workspace.Worktree, error) {
return f.wts, f.err
}
// fakePA 返回固定的 read/write 决策。
type fakePA struct {
canRead bool
canWrite bool
err error
}
func (f *fakePA) Resolve(context.Context, uuid.UUID, bool, string) (uuid.UUID, bool, bool, error) {
return uuid.Nil, f.canRead, f.canWrite, f.err
}
func (f *fakePA) ResolveByID(context.Context, uuid.UUID, bool, uuid.UUID) (bool, bool, error) {
return f.canRead, f.canWrite, f.err
}
func newExecSvc(t *testing.T, ws *workspace.Workspace, wts []*workspace.Worktree, pa workspace.ProjectAccess, cfg ExecConfig) *ExecService {
t.Helper()
return NewExecService(
&fakeWsRepo{ws: ws},
&fakeWtSvc{wts: wts},
pa,
nil, // audit recorder: nil → audit no-op
nil, // encryptor unused
cfg,
nil,
)
}
// hasCode 报告 err 是否携带给定 errs.Code。
func hasCode(err error, code errs.Code) bool {
ae, ok := errs.As(err)
return ok && ae.Code == code
}
func shellCmd(script string) (string, []string) {
if runtime.GOOS == "windows" {
return "cmd", []string{"/c", script}
}
return "sh", []string{"-c", script}
}
func baseCfg() ExecConfig {
return ExecConfig{
EnvWhitelist: []string{"PATH"},
DefaultTimeout: 10 * time.Second,
MaxTimeout: 30 * time.Second,
MaxOutputBytes: 1 << 20,
KillGrace: time.Second,
}
}
// ===== tests =====
func TestExecService_RunCommand_Success(t *testing.T) {
dir := t.TempDir()
ws := &workspace.Workspace{ID: uuid.New(), ProjectID: uuid.New(), MainPath: dir}
svc := newExecSvc(t, ws, nil, &fakePA{canRead: true, canWrite: true}, baseCfg())
cmd, args := shellCmd("echo hi")
resp, err := svc.RunCommand(context.Background(), workspace.Caller{UserID: uuid.New()}, ExecCommandReq{
WorkspaceID: ws.ID.String(),
Command: cmd,
Args: args,
})
if err != nil {
t.Fatalf("RunCommand: %v", err)
}
if resp.ExitCode != 0 {
t.Fatalf("exit = %d", resp.ExitCode)
}
if !strings.Contains(resp.Stdout, "hi") {
t.Fatalf("stdout = %q", resp.Stdout)
}
}
func TestExecService_AuthDenied(t *testing.T) {
ws := &workspace.Workspace{ID: uuid.New(), ProjectID: uuid.New(), MainPath: t.TempDir()}
svc := newExecSvc(t, ws, nil, &fakePA{canRead: true, canWrite: false}, baseCfg())
cmd, args := shellCmd("echo hi")
_, err := svc.RunCommand(context.Background(), workspace.Caller{UserID: uuid.New()}, ExecCommandReq{
WorkspaceID: ws.ID.String(),
Command: cmd,
Args: args,
})
if !hasCode(err, errs.CodeForbidden) {
t.Fatalf("err = %v, want forbidden", err)
}
}
func TestExecService_CommandNotAllowed(t *testing.T) {
ws := &workspace.Workspace{ID: uuid.New(), ProjectID: uuid.New(), MainPath: t.TempDir()}
cfg := baseCfg()
cfg.AllowedCommands = []string{"go", "npm"}
svc := newExecSvc(t, ws, nil, &fakePA{canRead: true, canWrite: true}, cfg)
cmd, args := shellCmd("echo hi")
_, err := svc.RunCommand(context.Background(), workspace.Caller{UserID: uuid.New()}, ExecCommandReq{
WorkspaceID: ws.ID.String(),
Command: cmd,
Args: args,
})
if !hasCode(err, errs.CodeRunExecCommandNotAllowed) {
t.Fatalf("err = %v, want run.exec_command_not_allowed", err)
}
}
func TestExecService_EmptyCommand(t *testing.T) {
ws := &workspace.Workspace{ID: uuid.New(), ProjectID: uuid.New(), MainPath: t.TempDir()}
svc := newExecSvc(t, ws, nil, &fakePA{canRead: true, canWrite: true}, baseCfg())
_, err := svc.RunCommand(context.Background(), workspace.Caller{UserID: uuid.New()}, ExecCommandReq{
WorkspaceID: ws.ID.String(),
Command: " ",
})
if !hasCode(err, errs.CodeRunCommandInvalid) {
t.Fatalf("err = %v, want run.command_invalid", err)
}
}
// TestExecService_EnvWhitelist 验证子进程环境仅含白名单变量 + 请求覆盖,
// 绝不泄漏 APP_MASTER_KEY 等敏感宿主变量。
func TestExecService_EnvWhitelist(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("env dump via /bin/sh not portable on windows")
}
t.Setenv("APP_MASTER_KEY", "super-secret")
t.Setenv("PATH", os.Getenv("PATH"))
ws := &workspace.Workspace{ID: uuid.New(), ProjectID: uuid.New(), MainPath: t.TempDir()}
svc := newExecSvc(t, ws, nil, &fakePA{canRead: true, canWrite: true}, baseCfg())
resp, err := svc.RunCommand(context.Background(), workspace.Caller{UserID: uuid.New()}, ExecCommandReq{
WorkspaceID: ws.ID.String(),
Command: "env",
Env: map[string]string{"MY_OVERRIDE": "v1"},
})
if err != nil {
t.Fatalf("RunCommand: %v", err)
}
if strings.Contains(resp.Stdout, "super-secret") || strings.Contains(resp.Stdout, "APP_MASTER_KEY") {
t.Fatalf("env leaked master key:\n%s", resp.Stdout)
}
if !strings.Contains(resp.Stdout, "MY_OVERRIDE=v1") {
t.Fatalf("override missing from env:\n%s", resp.Stdout)
}
if !strings.Contains(resp.Stdout, "PATH=") {
t.Fatalf("whitelisted PATH missing from env:\n%s", resp.Stdout)
}
}
// TestExecService_CwdWorktree 验证 worktree_id 解析到 wt.Path。
func TestExecService_CwdWorktree(t *testing.T) {
mainDir := t.TempDir()
wtDir := t.TempDir()
ws := &workspace.Workspace{ID: uuid.New(), ProjectID: uuid.New(), MainPath: mainDir}
wtID := uuid.New()
wts := []*workspace.Worktree{{ID: wtID, WorkspaceID: ws.ID, Path: wtDir}}
svc := newExecSvc(t, ws, wts, &fakePA{canRead: true, canWrite: true}, baseCfg())
cmd, args := shellCmd(pwdScript())
resp, err := svc.RunCommand(context.Background(), workspace.Caller{UserID: uuid.New()}, ExecCommandReq{
WorkspaceID: ws.ID.String(),
WorktreeID: wtID.String(),
Command: cmd,
Args: args,
})
if err != nil {
t.Fatalf("RunCommand: %v", err)
}
// 比较 base name 规避 /private 软链等差异。
if !strings.Contains(resp.Stdout, lastPathElem(wtDir)) {
t.Fatalf("cwd stdout %q does not contain worktree dir %q", resp.Stdout, wtDir)
}
}
// TestExecService_CwdMainPath 验证无 worktree_id 时使用 main_path。
func TestExecService_CwdMainPath(t *testing.T) {
mainDir := t.TempDir()
ws := &workspace.Workspace{ID: uuid.New(), ProjectID: uuid.New(), MainPath: mainDir}
svc := newExecSvc(t, ws, nil, &fakePA{canRead: true, canWrite: true}, baseCfg())
cmd, args := shellCmd(pwdScript())
resp, err := svc.RunCommand(context.Background(), workspace.Caller{UserID: uuid.New()}, ExecCommandReq{
WorkspaceID: ws.ID.String(),
Command: cmd,
Args: args,
})
if err != nil {
t.Fatalf("RunCommand: %v", err)
}
if !strings.Contains(resp.Stdout, lastPathElem(mainDir)) {
t.Fatalf("cwd stdout %q does not contain main dir %q", resp.Stdout, mainDir)
}
}
func TestExecService_BadWorktree(t *testing.T) {
ws := &workspace.Workspace{ID: uuid.New(), ProjectID: uuid.New(), MainPath: t.TempDir()}
svc := newExecSvc(t, ws, nil, &fakePA{canRead: true, canWrite: true}, baseCfg())
cmd, args := shellCmd("echo hi")
_, err := svc.RunCommand(context.Background(), workspace.Caller{UserID: uuid.New()}, ExecCommandReq{
WorkspaceID: ws.ID.String(),
WorktreeID: uuid.New().String(),
Command: cmd,
Args: args,
})
if !hasCode(err, errs.CodeNotFound) {
t.Fatalf("err = %v, want not_found", err)
}
}
// TestExecService_Timeout 验证超时返回 TimedOut。
func TestExecService_Timeout(t *testing.T) {
ws := &workspace.Workspace{ID: uuid.New(), ProjectID: uuid.New(), MainPath: t.TempDir()}
svc := newExecSvc(t, ws, nil, &fakePA{canRead: true, canWrite: true}, baseCfg())
var cmd string
var args []string
if runtime.GOOS == "windows" {
cmd, args = "cmd", []string{"/c", "ping -n 30 127.0.0.1 >nul"}
} else {
cmd, args = "sh", []string{"-c", "sleep 30"}
}
start := time.Now()
resp, err := svc.RunCommand(context.Background(), workspace.Caller{UserID: uuid.New()}, ExecCommandReq{
WorkspaceID: ws.ID.String(),
Command: cmd,
Args: args,
TimeoutSec: 1,
})
if err != nil {
t.Fatalf("RunCommand: %v", err)
}
if !resp.TimedOut {
t.Fatal("expected TimedOut")
}
if time.Since(start) > 10*time.Second {
t.Fatalf("timeout took too long: %v", time.Since(start))
}
}
// TestExecService_RunTests 端到端跑 go test -json 解析。
func TestExecService_RunTests(t *testing.T) {
if _, err := os.Stat(os.Getenv("GOROOT")); os.Getenv("GOROOT") != "" && err != nil {
t.Skip("GOROOT not available")
}
dir := t.TempDir()
writeGoModule(t, dir)
ws := &workspace.Workspace{ID: uuid.New(), ProjectID: uuid.New(), MainPath: dir}
// 透传完整 PATH 让 go 可被定位。
cfg := baseCfg()
cfg.EnvWhitelist = []string{"PATH", "HOME", "GOPATH", "GOROOT", "GOCACHE", "SystemRoot", "TEMP", "TMP", "USERPROFILE", "LOCALAPPDATA"}
cfg.MaxTimeout = 120 * time.Second
cfg.DefaultTimeout = 120 * time.Second
svc := newExecSvc(t, ws, nil, &fakePA{canRead: true, canWrite: true}, cfg)
resp, err := svc.RunTests(context.Background(), workspace.Caller{UserID: uuid.New()}, ExecTestsReq{
WorkspaceID: ws.ID.String(),
Command: "go",
Args: []string{"test", "-json", "./..."},
Format: "gotest",
TimeoutSec: 100,
})
if err != nil {
t.Fatalf("RunTests: %v\nstderr:\n%s", err, resp.Stderr)
}
if resp.ParseError != "" {
t.Fatalf("parse error: %s\nstdout:\n%s", resp.ParseError, resp.Stdout)
}
if resp.Summary.Framework != "gotest" {
t.Fatalf("framework = %q", resp.Summary.Framework)
}
if resp.Summary.Passed < 1 || resp.Summary.Failed < 1 {
t.Fatalf("summary = %+v\nstdout:\n%s", resp.Summary, resp.Stdout)
}
}
// ===== helpers =====
func pwdScript() string {
if runtime.GOOS == "windows" {
return "cd"
}
return "pwd"
}
func lastPathElem(p string) string {
p = strings.TrimRight(p, "/\\")
if i := strings.LastIndexAny(p, "/\\"); i >= 0 {
return p[i+1:]
}
return p
}
func writeGoModule(t *testing.T, dir string) {
t.Helper()
mustWrite(t, dir+"/go.mod", "module selftest\n\ngo 1.21\n")
src := `package selftest
import "testing"
func TestPasses(t *testing.T) {}
func TestFails(t *testing.T) { t.Fatal("intentional failure") }
`
mustWrite(t, dir+"/selftest_test.go", src)
}
func mustWrite(t *testing.T, path, content string) {
t.Helper()
if err := os.WriteFile(path, []byte(content), 0o644); err != nil {
t.Fatalf("write %s: %v", path, err)
}
}
+8 -1
View File
@@ -318,8 +318,15 @@ func (s *Service) SubscribeLogs(ctx context.Context, c workspace.Caller, profile
// buildEnv 构造被托管命令的环境:宿主白名单基础变量 + profile 覆盖。
// 不继承宿主全部环境,避免泄漏 APP_MASTER_KEY / DB DSN / git 凭据等敏感变量。
func (s *Service) buildEnv(overrides map[string]string) []string {
return buildEnvFromWhitelist(s.cfg.EnvWhitelist, overrides)
}
// buildEnvFromWhitelist 是 env 构造的包级可复用实现:仅透传 whitelist 列出的宿主
// 环境变量,再叠加 overrides。供 run profile(长驻)与 ExecService(一次性 exec)
// 共用,保证两条路径相同的安全取舍——绝不泄漏 APP_MASTER_KEY / DB DSN / git 凭据。
func buildEnvFromWhitelist(whitelist []string, overrides map[string]string) []string {
base := map[string]string{}
for _, k := range s.cfg.EnvWhitelist {
for _, k := range whitelist {
if v, ok := os.LookupEnv(k); ok {
base[k] = v
}
+240 -17
View File
@@ -8,6 +8,7 @@ import (
"net/netip"
"github.com/jackc/pgx/v5/pgtype"
"github.com/pgvector/pgvector-go"
)
type AcpAgentKind struct {
@@ -25,6 +26,11 @@ type AcpAgentKind struct {
ToolAllowlist []string `json:"tool_allowlist"`
ClientType string `json:"client_type"`
EncryptedMcpServers []byte `json:"encrypted_mcp_servers"`
ModelID pgtype.UUID `json:"model_id"`
MaxCostUsd pgtype.Numeric `json:"max_cost_usd"`
MaxTokens *int64 `json:"max_tokens"`
MaxWallClockSeconds *int32 `json:"max_wall_clock_seconds"`
KeyVersion int16 `json:"key_version"`
}
type AcpAgentKindConfigFile struct {
@@ -35,6 +41,7 @@ type AcpAgentKindConfigFile struct {
UpdatedBy pgtype.UUID `json:"updated_by"`
CreatedAt pgtype.Timestamptz `json:"created_at"`
UpdatedAt pgtype.Timestamptz `json:"updated_at"`
KeyVersion int16 `json:"key_version"`
}
type AcpEvent struct {
@@ -64,23 +71,64 @@ type AcpPermissionRequest struct {
}
type AcpSession struct {
ID pgtype.UUID `json:"id"`
WorkspaceID pgtype.UUID `json:"workspace_id"`
ProjectID pgtype.UUID `json:"project_id"`
AgentKindID pgtype.UUID `json:"agent_kind_id"`
UserID pgtype.UUID `json:"user_id"`
IssueID pgtype.UUID `json:"issue_id"`
RequirementID pgtype.UUID `json:"requirement_id"`
AgentSessionID *string `json:"agent_session_id"`
Branch string `json:"branch"`
CwdPath string `json:"cwd_path"`
IsMainWorktree bool `json:"is_main_worktree"`
Status string `json:"status"`
Pid *int32 `json:"pid"`
ExitCode *int32 `json:"exit_code"`
LastError *string `json:"last_error"`
StartedAt pgtype.Timestamptz `json:"started_at"`
EndedAt pgtype.Timestamptz `json:"ended_at"`
ID pgtype.UUID `json:"id"`
WorkspaceID pgtype.UUID `json:"workspace_id"`
ProjectID pgtype.UUID `json:"project_id"`
AgentKindID pgtype.UUID `json:"agent_kind_id"`
UserID pgtype.UUID `json:"user_id"`
IssueID pgtype.UUID `json:"issue_id"`
RequirementID pgtype.UUID `json:"requirement_id"`
AgentSessionID *string `json:"agent_session_id"`
Branch string `json:"branch"`
CwdPath string `json:"cwd_path"`
IsMainWorktree bool `json:"is_main_worktree"`
Status string `json:"status"`
Pid *int32 `json:"pid"`
ExitCode *int32 `json:"exit_code"`
LastError *string `json:"last_error"`
StartedAt pgtype.Timestamptz `json:"started_at"`
EndedAt pgtype.Timestamptz `json:"ended_at"`
LastStopReason *string `json:"last_stop_reason"`
OrchestratorStepID pgtype.UUID `json:"orchestrator_step_id"`
PromptTokens int64 `json:"prompt_tokens"`
CompletionTokens int64 `json:"completion_tokens"`
ThinkingTokens int64 `json:"thinking_tokens"`
TotalCostUsd pgtype.Numeric `json:"total_cost_usd"`
LastActivityAt pgtype.Timestamptz `json:"last_activity_at"`
BudgetMaxCostUsd pgtype.Numeric `json:"budget_max_cost_usd"`
BudgetMaxTokens *int64 `json:"budget_max_tokens"`
BudgetMaxWallClockSeconds *int32 `json:"budget_max_wall_clock_seconds"`
TerminatedReason *string `json:"terminated_reason"`
SandboxMode *string `json:"sandbox_mode"`
CostUsd pgtype.Numeric `json:"cost_usd"`
TokensTotal int64 `json:"tokens_total"`
}
type AcpSessionUsage struct {
ID int64 `json:"id"`
SessionID pgtype.UUID `json:"session_id"`
UserID pgtype.UUID `json:"user_id"`
ProjectID pgtype.UUID `json:"project_id"`
AgentKindID pgtype.UUID `json:"agent_kind_id"`
ModelID pgtype.UUID `json:"model_id"`
PromptTokens int64 `json:"prompt_tokens"`
CompletionTokens int64 `json:"completion_tokens"`
ThinkingTokens int64 `json:"thinking_tokens"`
CostUsd pgtype.Numeric `json:"cost_usd"`
SourceEventID *int64 `json:"source_event_id"`
CreatedAt pgtype.Timestamptz `json:"created_at"`
}
type AcpTurn struct {
ID int64 `json:"id"`
SessionID pgtype.UUID `json:"session_id"`
TurnIndex int32 `json:"turn_index"`
PromptRequestID *string `json:"prompt_request_id"`
Status string `json:"status"`
StopReason *string `json:"stop_reason"`
UpdateCount int32 `json:"update_count"`
StartedAt pgtype.Timestamptz `json:"started_at"`
CompletedAt pgtype.Timestamptz `json:"completed_at"`
}
type AuditLog struct {
@@ -94,6 +142,81 @@ type AuditLog struct {
CreatedAt pgtype.Timestamptz `json:"created_at"`
}
type ChangeRequest struct {
ID pgtype.UUID `json:"id"`
ProjectID pgtype.UUID `json:"project_id"`
WorkspaceID pgtype.UUID `json:"workspace_id"`
RequirementID pgtype.UUID `json:"requirement_id"`
IssueID pgtype.UUID `json:"issue_id"`
Number int32 `json:"number"`
Title string `json:"title"`
Description string `json:"description"`
SourceBranch string `json:"source_branch"`
TargetBranch string `json:"target_branch"`
State string `json:"state"`
ReviewVerdict string `json:"review_verdict"`
CiState string `json:"ci_state"`
Provider string `json:"provider"`
ExternalID *int64 `json:"external_id"`
ExternalUrl string `json:"external_url"`
MergeCommitSha string `json:"merge_commit_sha"`
ReviewedBy pgtype.UUID `json:"reviewed_by"`
ReviewedAt pgtype.Timestamptz `json:"reviewed_at"`
CreatedBy pgtype.UUID `json:"created_by"`
MergedAt pgtype.Timestamptz `json:"merged_at"`
CreatedAt pgtype.Timestamptz `json:"created_at"`
UpdatedAt pgtype.Timestamptz `json:"updated_at"`
}
type CodeChunk struct {
ID pgtype.UUID `json:"id"`
RunID pgtype.UUID `json:"run_id"`
WorkspaceID pgtype.UUID `json:"workspace_id"`
CommitSha string `json:"commit_sha"`
FilePath string `json:"file_path"`
Lang *string `json:"lang"`
StartLine int32 `json:"start_line"`
EndLine int32 `json:"end_line"`
Content string `json:"content"`
ContentSha []byte `json:"content_sha"`
TokenCount *int32 `json:"token_count"`
Embedding *pgvector.Vector `json:"embedding"`
CreatedAt pgtype.Timestamptz `json:"created_at"`
}
type CodeIndexRun struct {
ID pgtype.UUID `json:"id"`
WorkspaceID pgtype.UUID `json:"workspace_id"`
WorktreeID pgtype.UUID `json:"worktree_id"`
Branch string `json:"branch"`
CommitSha string `json:"commit_sha"`
Status string `json:"status"`
EmbeddingEndpointID pgtype.UUID `json:"embedding_endpoint_id"`
EmbeddingModel string `json:"embedding_model"`
Dims int32 `json:"dims"`
FilesIndexed int32 `json:"files_indexed"`
ChunksIndexed int32 `json:"chunks_indexed"`
Error *string `json:"error"`
StartedAt pgtype.Timestamptz `json:"started_at"`
FinishedAt pgtype.Timestamptz `json:"finished_at"`
CreatedAt pgtype.Timestamptz `json:"created_at"`
}
type CommitSummary struct {
ID pgtype.UUID `json:"id"`
WorkspaceID pgtype.UUID `json:"workspace_id"`
WorktreeID pgtype.UUID `json:"worktree_id"`
Branch string `json:"branch"`
CommitSha string `json:"commit_sha"`
Kind string `json:"kind"`
Title *string `json:"title"`
BodyMd string `json:"body_md"`
Model *string `json:"model"`
Status string `json:"status"`
Error *string `json:"error"`
CreatedAt pgtype.Timestamptz `json:"created_at"`
}
type Conversation struct {
ID pgtype.UUID `json:"id"`
UserID pgtype.UUID `json:"user_id"`
@@ -110,6 +233,14 @@ type Conversation struct {
RequirementID pgtype.UUID `json:"requirement_id"`
}
type CryptoKey struct {
Version int32 `json:"version"`
Provider string `json:"provider"`
KeyRef *string `json:"key_ref"`
Status string `json:"status"`
CreatedAt pgtype.Timestamptz `json:"created_at"`
}
type GitCredential struct {
ID pgtype.UUID `json:"id"`
WorkspaceID pgtype.UUID `json:"workspace_id"`
@@ -119,6 +250,7 @@ type GitCredential struct {
Fingerprint *string `json:"fingerprint"`
CreatedAt pgtype.Timestamptz `json:"created_at"`
UpdatedAt pgtype.Timestamptz `json:"updated_at"`
KeyVersion int16 `json:"key_version"`
}
type Issue struct {
@@ -135,6 +267,17 @@ type Issue struct {
CreatedAt pgtype.Timestamptz `json:"created_at"`
UpdatedAt pgtype.Timestamptz `json:"updated_at"`
WorkspaceID pgtype.UUID `json:"workspace_id"`
ParentID pgtype.UUID `json:"parent_id"`
Priority int32 `json:"priority"`
}
type IssueDependency struct {
ID pgtype.UUID `json:"id"`
ProjectID pgtype.UUID `json:"project_id"`
BlockedID pgtype.UUID `json:"blocked_id"`
BlockerID pgtype.UUID `json:"blocker_id"`
CreatedBy pgtype.UUID `json:"created_by"`
CreatedAt pgtype.Timestamptz `json:"created_at"`
}
type Job struct {
@@ -162,6 +305,7 @@ type LlmEndpoint struct {
CreatedBy pgtype.UUID `json:"created_by"`
CreatedAt pgtype.Timestamptz `json:"created_at"`
UpdatedAt pgtype.Timestamptz `json:"updated_at"`
KeyVersion int16 `json:"key_version"`
}
type LlmModel struct {
@@ -252,6 +396,50 @@ type Notification struct {
CreatedAt pgtype.Timestamptz `json:"created_at"`
}
type NotificationPref struct {
UserID pgtype.UUID `json:"user_id"`
EmailEnabled bool `json:"email_enabled"`
ImEnabled bool `json:"im_enabled"`
ImWebhookUrlEnc []byte `json:"im_webhook_url_enc"`
MinSeverity string `json:"min_severity"`
UpdatedAt pgtype.Timestamptz `json:"updated_at"`
}
type OrchestratorRun struct {
ID pgtype.UUID `json:"id"`
ProjectID pgtype.UUID `json:"project_id"`
RequirementID pgtype.UUID `json:"requirement_id"`
WorkspaceID pgtype.UUID `json:"workspace_id"`
OwnerID pgtype.UUID `json:"owner_id"`
Status string `json:"status"`
CurrentPhase string `json:"current_phase"`
Config []byte `json:"config"`
LastError *string `json:"last_error"`
CreatedAt pgtype.Timestamptz `json:"created_at"`
UpdatedAt pgtype.Timestamptz `json:"updated_at"`
EndedAt pgtype.Timestamptz `json:"ended_at"`
}
type OrchestratorStep struct {
ID pgtype.UUID `json:"id"`
RunID pgtype.UUID `json:"run_id"`
Phase string `json:"phase"`
Attempt int32 `json:"attempt"`
ParentStepID pgtype.UUID `json:"parent_step_id"`
Depth int32 `json:"depth"`
Status string `json:"status"`
AgentKindID pgtype.UUID `json:"agent_kind_id"`
AcpSessionID pgtype.UUID `json:"acp_session_id"`
Prompt string `json:"prompt"`
StopReason *string `json:"stop_reason"`
GateResult []byte `json:"gate_result"`
LastError *string `json:"last_error"`
JobID pgtype.UUID `json:"job_id"`
CreatedAt pgtype.Timestamptz `json:"created_at"`
UpdatedAt pgtype.Timestamptz `json:"updated_at"`
EndedAt pgtype.Timestamptz `json:"ended_at"`
}
type Project struct {
ID pgtype.UUID `json:"id"`
Slug string `json:"slug"`
@@ -264,6 +452,30 @@ type Project struct {
UpdatedAt pgtype.Timestamptz `json:"updated_at"`
}
type ProjectMember struct {
ProjectID pgtype.UUID `json:"project_id"`
UserID pgtype.UUID `json:"user_id"`
Role string `json:"role"`
CreatedAt pgtype.Timestamptz `json:"created_at"`
AddedBy pgtype.UUID `json:"added_by"`
}
type ProjectMemory struct {
ID pgtype.UUID `json:"id"`
ProjectID pgtype.UUID `json:"project_id"`
WorkspaceID pgtype.UUID `json:"workspace_id"`
Kind string `json:"kind"`
Title string `json:"title"`
Body string `json:"body"`
Tags []string `json:"tags"`
Source string `json:"source"`
Embedding *pgvector.Vector `json:"embedding"`
EmbeddingModel *string `json:"embedding_model"`
CreatedBy pgtype.UUID `json:"created_by"`
CreatedAt pgtype.Timestamptz `json:"created_at"`
UpdatedAt pgtype.Timestamptz `json:"updated_at"`
}
type PromptTemplate struct {
ID pgtype.UUID `json:"id"`
Name string `json:"name"`
@@ -299,6 +511,16 @@ type RequirementArtifact struct {
SourceMessageID *int64 `json:"source_message_id"`
CreatedBy pgtype.UUID `json:"created_by"`
CreatedAt pgtype.Timestamptz `json:"created_at"`
Verdict string `json:"verdict"`
}
type RequirementPhasePointer struct {
RequirementID pgtype.UUID `json:"requirement_id"`
Phase string `json:"phase"`
ApprovedArtifactID pgtype.UUID `json:"approved_artifact_id"`
ApprovedBy pgtype.UUID `json:"approved_by"`
ApprovedAt pgtype.Timestamptz `json:"approved_at"`
UpdatedAt pgtype.Timestamptz `json:"updated_at"`
}
type User struct {
@@ -354,6 +576,7 @@ type WorkspaceRunProfile struct {
CreatedBy pgtype.UUID `json:"created_by"`
CreatedAt pgtype.Timestamptz `json:"created_at"`
UpdatedAt pgtype.Timestamptz `json:"updated_at"`
KeyVersion int16 `json:"key_version"`
}
type WorkspaceWorktree struct {
+10 -5
View File
@@ -15,7 +15,7 @@ const createRunProfile = `-- name: CreateRunProfile :one
INSERT INTO workspace_run_profiles (
id, workspace_id, slug, name, description, command, args, encrypted_env, enabled, created_by
) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10)
RETURNING id, workspace_id, slug, name, description, command, args, encrypted_env, enabled, last_started_at, last_exit_code, last_error, created_by, created_at, updated_at
RETURNING id, workspace_id, slug, name, description, command, args, encrypted_env, enabled, last_started_at, last_exit_code, last_error, created_by, created_at, updated_at, key_version
`
type CreateRunProfileParams struct {
@@ -61,6 +61,7 @@ func (q *Queries) CreateRunProfile(ctx context.Context, arg CreateRunProfilePara
&i.CreatedBy,
&i.CreatedAt,
&i.UpdatedAt,
&i.KeyVersion,
)
return i, err
}
@@ -75,7 +76,7 @@ func (q *Queries) DeleteRunProfile(ctx context.Context, id pgtype.UUID) error {
}
const getRunProfileByID = `-- name: GetRunProfileByID :one
SELECT id, workspace_id, slug, name, description, command, args, encrypted_env, enabled, last_started_at, last_exit_code, last_error, created_by, created_at, updated_at FROM workspace_run_profiles WHERE id = $1
SELECT id, workspace_id, slug, name, description, command, args, encrypted_env, enabled, last_started_at, last_exit_code, last_error, created_by, created_at, updated_at, key_version FROM workspace_run_profiles WHERE id = $1
`
func (q *Queries) GetRunProfileByID(ctx context.Context, id pgtype.UUID) (WorkspaceRunProfile, error) {
@@ -97,12 +98,13 @@ func (q *Queries) GetRunProfileByID(ctx context.Context, id pgtype.UUID) (Worksp
&i.CreatedBy,
&i.CreatedAt,
&i.UpdatedAt,
&i.KeyVersion,
)
return i, err
}
const listRunProfilesByWorkspace = `-- name: ListRunProfilesByWorkspace :many
SELECT id, workspace_id, slug, name, description, command, args, encrypted_env, enabled, last_started_at, last_exit_code, last_error, created_by, created_at, updated_at FROM workspace_run_profiles
SELECT id, workspace_id, slug, name, description, command, args, encrypted_env, enabled, last_started_at, last_exit_code, last_error, created_by, created_at, updated_at, key_version FROM workspace_run_profiles
WHERE workspace_id = $1
ORDER BY created_at
`
@@ -132,6 +134,7 @@ func (q *Queries) ListRunProfilesByWorkspace(ctx context.Context, workspaceID pg
&i.CreatedBy,
&i.CreatedAt,
&i.UpdatedAt,
&i.KeyVersion,
); err != nil {
return nil, err
}
@@ -150,7 +153,7 @@ SET last_started_at = now(),
last_error = '',
updated_at = now()
WHERE id = $1
RETURNING id, workspace_id, slug, name, description, command, args, encrypted_env, enabled, last_started_at, last_exit_code, last_error, created_by, created_at, updated_at
RETURNING id, workspace_id, slug, name, description, command, args, encrypted_env, enabled, last_started_at, last_exit_code, last_error, created_by, created_at, updated_at, key_version
`
func (q *Queries) MarkRunProfileStarted(ctx context.Context, id pgtype.UUID) (WorkspaceRunProfile, error) {
@@ -172,6 +175,7 @@ func (q *Queries) MarkRunProfileStarted(ctx context.Context, id pgtype.UUID) (Wo
&i.CreatedBy,
&i.CreatedAt,
&i.UpdatedAt,
&i.KeyVersion,
)
return i, err
}
@@ -187,7 +191,7 @@ SET slug = $2,
enabled = $8,
updated_at = now()
WHERE id = $1
RETURNING id, workspace_id, slug, name, description, command, args, encrypted_env, enabled, last_started_at, last_exit_code, last_error, created_by, created_at, updated_at
RETURNING id, workspace_id, slug, name, description, command, args, encrypted_env, enabled, last_started_at, last_exit_code, last_error, created_by, created_at, updated_at, key_version
`
type UpdateRunProfileParams struct {
@@ -229,6 +233,7 @@ func (q *Queries) UpdateRunProfile(ctx context.Context, arg UpdateRunProfilePara
&i.CreatedBy,
&i.CreatedAt,
&i.UpdatedAt,
&i.KeyVersion,
)
return i, err
}
+9
View File
@@ -0,0 +1,9 @@
{"Time":"2026-06-20T10:00:00Z","Action":"run","Package":"example/pkg","Test":"TestPass"}
{"Time":"2026-06-20T10:00:00Z","Action":"output","Package":"example/pkg","Test":"TestPass","Output":"=== RUN TestPass\n"}
{"Time":"2026-06-20T10:00:00Z","Action":"pass","Package":"example/pkg","Test":"TestPass","Elapsed":0.01}
{"Time":"2026-06-20T10:00:00Z","Action":"run","Package":"example/pkg","Test":"TestFail"}
{"Time":"2026-06-20T10:00:00Z","Action":"output","Package":"example/pkg","Test":"TestFail","Output":" foo_test.go:10: want 1 got 2\n"}
{"Time":"2026-06-20T10:00:00Z","Action":"fail","Package":"example/pkg","Test":"TestFail","Elapsed":0.02}
{"Time":"2026-06-20T10:00:00Z","Action":"run","Package":"example/pkg","Test":"TestSkip"}
{"Time":"2026-06-20T10:00:00Z","Action":"skip","Package":"example/pkg","Test":"TestSkip","Elapsed":0}
{"Time":"2026-06-20T10:00:00Z","Action":"fail","Package":"example/pkg","Elapsed":0.05}
+12
View File
@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<testsuites>
<testsuite name="example.suite" tests="3" failures="1" errors="0" skipped="1" time="0.123">
<testcase classname="example.suite" name="testPasses" time="0.010"></testcase>
<testcase classname="example.suite" name="testFails" time="0.020">
<failure message="expected true but was false">AssertionError at line 42</failure>
</testcase>
<testcase classname="example.suite" name="testSkipped" time="0.000">
<skipped message="not implemented"></skipped>
</testcase>
</testsuite>
</testsuites>
+17
View File
@@ -0,0 +1,17 @@
{
"numTotalTests": 3,
"numPassedTests": 1,
"numFailedTests": 1,
"numPendingTests": 1,
"startTime": 1718877600000,
"testResults": [
{
"name": "/repo/src/sum.test.ts",
"assertionResults": [
{ "title": "adds", "fullName": "sum > adds", "status": "passed", "duration": 5, "failureMessages": [] },
{ "title": "subtracts", "fullName": "sum > subtracts", "status": "failed", "duration": 8, "failureMessages": ["expected 1 to be 2"] },
{ "title": "multiplies", "fullName": "sum > multiplies", "status": "skipped", "duration": 0, "failureMessages": [] }
]
}
]
}