Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
29 commits
Select commit Hold shift + click to select a range
03704e6
Define agent-driven project lifecycle contracts
raphael Nov 19, 2026
257392f
Bind agent lifecycle operations to control plane owners
raphael Nov 19, 2026
f038190
Initialize Surla projects in the workspace root
raphael Nov 19, 2026
da56e1a
Merge the approved build on the current project branch
raphael Nov 19, 2026
b77d347
Start Surla without Herdr and report running project status
raphael Nov 19, 2026
3dc152f
Read compatible status without hashing the CLI executable
raphael Nov 19, 2026
ec52417
Adapt checkpoint views to the team contract
raphael Nov 19, 2026
dde70f7
Read live merge state and migrate lifecycle fixtures
raphael Nov 19, 2026
c130fe5
Read saved project status and merged build state
raphael Nov 19, 2026
1d026d5
Use the project team contract in CLI server fixtures
raphael Nov 19, 2026
770791d
Give live guide attachment its bounded desktop deadline
raphael Nov 19, 2026
8b84487
Verify explicit agent choices and close worker lifetimes before stores
raphael Nov 19, 2026
9d16fc2
Run bounded headless worker turns for the current build
raphael Nov 19, 2026
8df2e33
Attach the running guide and manage only requested Surla workers
raphael Nov 19, 2026
00421b7
Verify privileges for agent lifecycle endpoints
raphael Nov 19, 2026
2e23586
Rebuild checkpoint client for agent lifecycle operations
raphael Nov 19, 2026
fa4f16a
Verify Git rollback and protect ignored work during merge
raphael Nov 19, 2026
7c987bc
Pass a literal pathname to the Git ignore check
raphael Nov 19, 2026
a1fdfab
Document project startup and agent lifecycle
raphael Nov 19, 2026
77f8d46
Honor installed agent model and effort choices
raphael Nov 19, 2026
b7ea584
Guide users to an existing agent session
raphael Nov 19, 2026
1911157
Observe historical merge completion and wake failed verification turns
raphael Nov 19, 2026
38bcb1e
Match the documented worker start action
raphael Nov 19, 2026
7052ff1
Include private views handoff in the MCP catalog contract
raphael Nov 19, 2026
b3082e0
Refuse merges that can select Git content helpers
raphael Nov 19, 2026
6c09722
Let surla stdio read a registered agent's credential
raphael Nov 19, 2026
67cb388
Document safe Git merge support and update owning callers
raphael Nov 19, 2026
612a257
Keep checkpoint tests on the current team contract
raphael Nov 19, 2026
1448f0c
Bind the starter journey to an unavailable agent inventory
raphael Nov 19, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
180 changes: 67 additions & 113 deletions README.md

Large diffs are not rendered by default.

13 changes: 13 additions & 0 deletions cmd/surla/controlplane_fixture_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@
package main

import (
"context"

genproject "github.com/goadesign/surla/gen/project"
"github.com/goadesign/surla/internal/controlplane"
"github.com/goadesign/surla/internal/project"
)
Expand All @@ -25,3 +28,13 @@ func openFixtureProjectCards(state *project.State) (*controlplane.ControlPlane,
func fixtureWorkflowTeam(owner string) *controlplane.TeamBinding {
return &controlplane.TeamBinding{Owner: owner, Service: &workflowTeamFixture{}}
}

// attachFixtureGuide issues a role through the project owner without a desktop pane.
func attachFixtureGuide(
ctx context.Context, state *project.State, server *project.Server,
) (*genproject.AttachGuideResult, error) {
management := controlplane.WithPrincipal(ctx, controlplane.Principal{
ID: state.Record.Owner, CallerID: "management", Kind: controlplane.CallerManagement,
})
return server.AttachGuide(management, &genproject.AttachGuidePayload{})
}
84 changes: 84 additions & 0 deletions cmd/surla/daemon.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
// This file launches a project server when no Herdr terminal is available.
package main

import (
"context"
"errors"
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
"syscall"

"github.com/goadesign/surla/internal/project"
)

// projectDaemon holds the launch's particular log file through the readiness
// probe, even if a concurrent start later replaces the directory entry.
type projectDaemon struct {
log *os.File
process *os.Process
exited <-chan error
}

// startProjectDaemon starts the same private-state serve entry as Herdr, with a
// detached process session and no inherited terminal or standard I/O pipes.
// The caller holds the project's start lock and closes the returned log.
func startProjectDaemon(state *project.State, self string) (*projectDaemon, error) {
log, err := os.CreateTemp(state.Dir, ".serve-startup-*")
if err != nil {
return nil, fmt.Errorf("create project server startup log: %w", err)
}
// Replace the old file instead of opening and truncating any existing
// link. The new regular file is created with private permissions.
if err := os.Rename(log.Name(), filepath.Join(state.Dir, "serve-startup.log")); err != nil {
return nil, errors.Join(fmt.Errorf("publish project server startup log: %w", err), log.Close(), os.Remove(log.Name()))
}
command := exec.Command(self, "serve", "-state", state.Dir)
command.Dir = state.Record.Directory
command.Env = append(os.Environ(), "HC_TERMINAL_ID=")
command.SysProcAttr = &syscall.SysProcAttr{Setsid: true}
command.Stdout = log
command.Stderr = log
if err := command.Start(); err != nil {
return nil, errors.Join(fmt.Errorf("start background project server: %w", err), log.Close())
}
exited := make(chan error, 1)
go func() {
exited <- command.Wait()
close(exited)
}()
return &projectDaemon{log: log, process: command.Process, exited: exited}, nil
}

// wait observes exit during readiness. Cancellation stops only the observer.
func (d *projectDaemon) wait(ctx context.Context) (bool, error) {
select {
case err := <-d.exited:
return true, err
case <-ctx.Done():
// Prefer an exit that the reaper has already reported.
select {
case err := <-d.exited:
return true, err
default:
return false, nil
}
}
}

// startupOutput reads only the bounded tail of our ended daemon's private log.
func (d *projectDaemon) startupOutput() (string, error) {
info, err := d.log.Stat()
if err != nil {
return "", err
}
size := min(info.Size(), startOutputBytes)
text := make([]byte, size)
n, err := d.log.ReadAt(text, info.Size()-size)
if err != nil && !errors.Is(err, io.EOF) {
return "", err
}
return string(text[:n]), nil
}
166 changes: 166 additions & 0 deletions cmd/surla/daemon_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,166 @@
// This file verifies detached project launch using only test-owned processes.
package main

import (
"bytes"
"context"
"encoding/json"
"io"
"os"
"path/filepath"
"strings"
"testing"
"time"

"github.com/goadesign/surla/internal/controlplane"
"github.com/goadesign/surla/internal/project"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"golang.org/x/sys/unix"
)

// TestDetachedProjectServerStartsAndStops exercises the real serve entrypoint
// and management status without reaching Herdr, desktop opening, or an agent.
func TestDetachedProjectServerStartsAndStops(t *testing.T) {
isolateServeWorkspace(t)
isolateProviderFamilies(t)
t.Setenv("OTEL_EXPORTER_OTLP_ENDPOINT", "")
t.Setenv("OTEL_EXPORTER_OTLP_TRACES_ENDPOINT", "")
t.Setenv("HC_TERMINAL_ID", "fixture-caller-terminal")
self, err := os.Executable()
require.NoError(t, err)
runtime := testProjectRuntime()
runtime.preflight = func(bool) error { return nil }
runtime.startTerminal = func(ctx context.Context, state *project.State) (string, error) {
return startProjectTerminal(ctx, state, func() (string, error) { return "", errProjectHerdrMissing })
}
var daemon *projectDaemon
runtime.startDaemon = func(state *project.State) (*projectDaemon, error) {
active, err := startProjectDaemon(state, self)
daemon = active
return active, err
}
t.Cleanup(func() {
if daemon == nil {
return
}
if err := daemon.process.Kill(); err != nil {
assert.ErrorIs(t, err, os.ErrProcessDone)
}
select {
case <-daemon.exited:
case <-time.After(5 * time.Second):
t.Error("failed to reap the fixture daemon")
}
})
browserLink := ""
runtime.openViews = func(_ context.Context, link string) error { browserLink = link; return nil }

var report bytes.Buffer
require.NoError(t, runWithRuntime(nil, &report, runtime))
require.NotNil(t, daemon)
state, err := runtime.discover()
require.NoError(t, err)
running, err := state.ReadRunning()
require.NoError(t, err)
assert.Equal(t, daemon.process.Pid, running.PID)
assert.Empty(t, running.Terminal, "the daemon must not publish its caller's terminal")
sid, err := unix.Getsid(running.PID)
require.NoError(t, err)
assert.Equal(t, running.PID, sid, "the server is the leader of a new session")
assert.Contains(t, browserLink, "/views#link=")
assert.NotContains(t, report.String(), "#link=")
logPath := filepath.Join(state.Dir, "serve-startup.log")
info, err := os.Stat(logPath)
require.NoError(t, err)
assert.Equal(t, os.FileMode(0o600), info.Mode().Perm())
raw, err := os.ReadFile(logPath)
require.NoError(t, err)
assert.False(t, strings.Contains(string(raw), running.ManagementCredential), "the private startup log contains no management credential")
assert.False(t, strings.Contains(string(raw), browserLink), "the private startup log contains no browser link")

report.Reset()
require.NoError(t, runWithRuntime([]string{"status", "--json"}, &report, runtime))
var status struct {
Running bool `json:"running"`
Directory string `json:"directory"`
Stage string `json:"stage"`
Roles []json.RawMessage `json:"roles"`
}
require.NoError(t, json.Unmarshal(report.Bytes(), &status))
assert.True(t, status.Running)
assert.Equal(t, state.Record.Directory, status.Directory)
assert.Equal(t, "describe", status.Stage)
assert.Empty(t, status.Roles, "bare start does not attach an agent")
assert.False(t, strings.Contains(report.String(), running.ManagementCredential), "status contains no management credential")
assert.NotContains(t, report.String(), "#link=")

require.NoError(t, runWithRuntime([]string{"stop"}, io.Discard, runtime))
select {
case err := <-daemon.exited:
require.NoError(t, err)
case <-time.After(5 * time.Second):
t.Fatal("detached server did not exit")
}
_, err = state.ReadRunning()
require.ErrorIs(t, err, os.ErrNotExist)
held, err := controlplane.CardStoreInUse(state.CardsDir())
require.NoError(t, err)
assert.False(t, held)
report.Reset()
require.NoError(t, runWithRuntime([]string{"status", "--json"}, &report, runtime))
assert.JSONEq(t, `{"running":false}`, report.String())
}

// TestDetachedStartReportsBoundedEarlyExit proves the watcher detects a child
// exit, captures both streams, and replaces the log without following a link.
func TestDetachedStartReportsBoundedEarlyExit(t *testing.T) {
isolateServeWorkspace(t)
state, err := fixtureProjectState("")
require.NoError(t, err)
previous := filepath.Join(t.TempDir(), "previous-log")
require.NoError(t, os.WriteFile(previous, []byte("old data\n"), 0o600))
log := filepath.Join(state.Dir, "serve-startup.log")
require.NoError(t, os.Symlink(previous, log))

child := filepath.Join(t.TempDir(), "serve-fixture")
script := `#!/bin/sh
printf 'discard this first line\n'
i=0
while [ "$i" -lt 180 ]; do
printf 'long line from stdout without sensitive data\n'
i=$((i+1))
done
if read -r line; then
printf 'unexpected input\n'
else
printf 'stdin reached EOF\n'
fi
printf '\033[31mconfiguration could not load\033[0m\n' >&2
exit 37
`
require.NoError(t, os.WriteFile(child, []byte(script), 0o700))
runtime := testProjectRuntime()
runtime.startTerminal = func(context.Context, *project.State) (string, error) {
return "", errProjectHerdrMissing
}
runtime.startDaemon = func(state *project.State) (*projectDaemon, error) {
return startProjectDaemon(state, child)
}
ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second)
defer cancel()
_, _, err = runtime.attachProject(ctx, state)
require.ErrorContains(t, err, "the project server stopped while starting")
assert.ErrorContains(t, err, "stdin reached EOF")
assert.ErrorContains(t, err, "configuration could not load")
assert.NotContains(t, err.Error(), "discard this first line")
assert.NotContains(t, err.Error(), "\x1b")
assert.Less(t, len(err.Error()), startOutputBytes+100)
raw, err := os.ReadFile(previous)
require.NoError(t, err)
assert.Equal(t, "old data\n", string(raw), "an existing link is replaced without truncating its target")
info, err := os.Lstat(log)
require.NoError(t, err)
assert.True(t, info.Mode().IsRegular())
assert.Equal(t, os.FileMode(0o600), info.Mode().Perm())
}
16 changes: 9 additions & 7 deletions cmd/surla/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -71,21 +71,21 @@ Usage:
Commands:

init create a starter service with an agent and an evaluator suite
status read this project's running server, checkpoint and team status
stop stop this project's server in order
verification set, show or remove this project's verification settings
promotion set, show or remove this project's promotion settings

Running surla starts or attaches to this folder's project server, starts Chorus
and the Herdr app when they are not running, prepares the project's team of
agents in Herdr and opens the views page. The server runs in its own
parentless Herdr terminal.
Running surla starts or attaches to this folder's project server and opens the
views page. The server runs in a parentless Herdr terminal when hc is available,
or as a detached background process otherwise. Use surla status --json to read
the running project's status as JSON.

Use --print-link to start or attach and print {"url":"...","expires_at":"..."} JSON on
stdout instead of opening a browser. Notices and team instructions go to stderr;
stdout instead of opening a browser. Notices go to stderr and
no browser opener is required. The link grants user-page access to its first
consumer for two minutes: keep it out of shared logs. Run the command again for
a fresh link after use, expiry or page reload. A team-only failure may still
print a usable link while returning a nonzero exit and explaining it on stderr.
a fresh link after use, expiry or page reload.

Other commands:
preview print the architecture, agent policies and tool contracts a design
Expand Down Expand Up @@ -163,6 +163,8 @@ func dispatch(sub string, args []string, stdout io.Writer, runtime projectRuntim
return runtime.serve(stateDir)
case "stop":
return runtime.stop(args, stdout)
case "status":
return runtime.status(args, stdout)
case "verification", "promotion":
return runtime.settings(sub, args, stdout)
case "preview":
Expand Down
2 changes: 1 addition & 1 deletion cmd/surla/management_lifetime_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -499,7 +499,7 @@ func TestManagementCredentialStaysOutOfMetadata(t *testing.T) {
require.NoError(t, management.PublishRunning(os.Getpid(), "test"))
running, err := state.ReadRunning()
require.NoError(t, err)
agent, err := management.StartAgents(t.Context())
agent, err := attachFixtureGuide(t.Context(), state, management)
require.NoError(t, err)
roster, err := json.Marshal(state.Record)
require.NoError(t, err)
Expand Down
Loading
Loading