Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
4 changes: 3 additions & 1 deletion docs/architecture/native-workspace-preparation.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,9 @@ The public mutation requires the verified Mainloop service principal and an expl

The request binds the original Create request ID, Session, full source commit SHA and named branch, D image/platform/policy identity, controller-selected R, prepared revision, active runtime generation and Actor UID. The service reads the exact current Actor and its original immutable template, checks the retained composition snapshot, enforcing Git proxy configuration and original credential references, and fingerprints the compiled configuration and Mainloop MCP setup. Callback assertions never select these values.

The separately digested overlay is fixed `supervisor` or `child` standing context. It instructs discovery through `whoami` then `task_get`, and contains no task facts, owner brief, previous transcript, credential reference or inherited consent. Claude appends it through `append_system_prompt`; Codex uses `developer_instruction`. Original native instructions and compiled MCP configuration remain the base. Claude preserves compiler-selected `RequireApproval` protection through its existing authenticated approval broker, permission settings and MCP bridge; constructing those inputs requires no native turn.
The separately digested overlay is fixed `supervisor`, `child` or `agent` standing context. The delegated profiles instruct discovery through `whoami` then `task_get`. The `agent` profile is for an owner working directly in the workspace Session, with no delegation or `task_get`/`report` duties and no implied approval or consent. All profiles contain no task facts, owner brief, previous transcript or credential reference. Claude appends the overlay through `append_system_prompt`; Codex uses `developer_instruction`. Original native instructions and compiled MCP configuration remain the base. Claude preserves compiler-selected `RequireApproval` protection through its existing authenticated approval broker, permission settings and MCP bridge; constructing those inputs requires no native turn.

The `agent` profile uses the same digest validation, immutable selection and generation fencing as the delegated profiles. It preserves the owner workspace Session/context identity and selected development environment. Adding it does not change existing `supervisor`/`child` standing bytes, setup digests, durable receipts or admission requirements; unknown profiles remain rejected.

## Durable assignment and completion

Expand Down
8 changes: 4 additions & 4 deletions go/api/gen/kagent/api/v1alpha1/sessions.pb.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

8 changes: 4 additions & 4 deletions go/api/gen/kagent/api/v1alpha1/task_store.pb.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

81 changes: 57 additions & 24 deletions go/core/internal/grpcserver/protovalidate_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import (
"google.golang.org/grpc/status"
"google.golang.org/protobuf/proto"
"google.golang.org/protobuf/types/known/durationpb"
"google.golang.org/protobuf/types/known/timestamppb"
)

func TestProtovalidateUnaryInterceptor(t *testing.T) {
Expand Down Expand Up @@ -206,30 +207,62 @@ func TestSessionCredentialRequestValidation(t *testing.T) {
}

func TestPreparationRequestIntrinsicValidation(t *testing.T) {
base := &apiv1alpha1.PrepareSessionWorkspaceRequest{SessionId: "11111111-1111-4111-8111-111111111111", ActionId: "create:prepare", CreateRequestId: "create", GenerationId: "11111111-1111-4111-8111-111111111111", ActorUid: "owned", PreparedRevision: "original", Workspace: &apiv1alpha1.Workspace{Repo: "https://github.com/owner/repo.git", Ref: strings.Repeat("a", 40), Branch: "feature"}, DevelopmentEnvironment: &apiv1alpha1.DevelopmentEnvironment{Image: "fixture.test/d@sha256:" + strings.Repeat("a", 64), Platform: "linux/amd64", PolicyIdentity: "v1"}, RuntimeComposition: &apiv1alpha1.RuntimeComposition{}, SetupProfile: "child", SetupDigest: strings.Repeat("a", 64)}
if err := protovalidate.Validate(base); err != nil {
t.Fatal(err)
for _, profile := range []string{"supervisor", "child", "agent"} {
t.Run(profile, func(t *testing.T) {
base := &apiv1alpha1.PrepareSessionWorkspaceRequest{SessionId: "11111111-1111-4111-8111-111111111111", ActionId: "create:prepare", CreateRequestId: "create", GenerationId: "11111111-1111-4111-8111-111111111111", ActorUid: "owned", PreparedRevision: "original", Workspace: &apiv1alpha1.Workspace{Repo: "https://github.com/owner/repo.git", Ref: strings.Repeat("a", 40), Branch: "feature"}, DevelopmentEnvironment: &apiv1alpha1.DevelopmentEnvironment{Image: "fixture.test/d@sha256:" + strings.Repeat("a", 64), Platform: "linux/amd64", PolicyIdentity: "v1"}, RuntimeComposition: &apiv1alpha1.RuntimeComposition{}, SetupProfile: profile, SetupDigest: strings.Repeat("a", 64)}
if err := protovalidate.Validate(base); err != nil {
t.Fatal(err)
}
for _, field := range []string{"Session", "action", "generation", "HEAD", "branch", "profile", "empty profile", "digest"} {
request := proto.CloneOf(base)
switch field {
case "Session":
request.SessionId = "wrong"
case "action":
request.ActionId = strings.Repeat("a", 129)
case "generation":
request.GenerationId = "wrong"
case "HEAD":
request.Workspace.Ref = "main"
case "branch":
request.Workspace.Branch = ""
case "profile":
request.SetupProfile = "arbitrary"
case "empty profile":
request.SetupProfile = ""
case "digest":
request.SetupDigest = strings.Repeat("a", 16)
}
if err := protovalidate.Validate(request); err == nil {
t.Errorf("accepted invalid %s", field)
}
}
})
}
for _, field := range []string{"Session", "action", "generation", "HEAD", "branch", "profile", "digest"} {
request := proto.CloneOf(base)
switch field {
case "Session":
request.SessionId = "wrong"
case "action":
request.ActionId = strings.Repeat("a", 129)
case "generation":
request.GenerationId = "wrong"
case "HEAD":
request.Workspace.Ref = "main"
case "branch":
request.Workspace.Branch = ""
case "profile":
request.SetupProfile = "arbitrary"
case "digest":
request.SetupDigest = strings.Repeat("a", 16)
}
if err := protovalidate.Validate(request); err == nil {
t.Errorf("accepted invalid %s", field)
}
}

func TestPreparationAssignmentProfileValidation(t *testing.T) {
const id = "11111111-1111-4111-8111-111111111111"
for _, test := range []struct {
profile string
valid bool
}{{"supervisor", true}, {"child", true}, {"agent", true}, {"owner", false}, {"", false}} {
t.Run(test.profile, func(t *testing.T) {
assignment := &apiv1alpha1.NativeWorkspacePreparation{
SessionId: id, ContextId: id, CreateRequestId: "create", ActionId: "create:prepare",
RequestDigest: strings.Repeat("a", 64), ExecutionId: id, ChallengeId: id, GenerationId: id,
Atespace: "kagent", ActorName: "actor", ActorUid: "owned", PreparedRevision: "original",
Workspace: &apiv1alpha1.Workspace{Repo: "https://github.com/owner/repo.git", Ref: strings.Repeat("a", 40), Branch: "feature"},
DevelopmentImage: "fixture.test/d@sha256:" + strings.Repeat("a", 64), Platform: "linux/amd64", PolicyIdentity: "v1",
PayloadImage: "fixture.test/r@sha256:" + strings.Repeat("b", 64), Provider: "codex", Schema: 1, CliVersion: "1.0",
Profile: test.profile, SetupDigest: strings.Repeat("a", 64), ConfigDigest: strings.Repeat("b", 64), McpDigest: strings.Repeat("c", 64),
}
callback := &apiv1alpha1.TaskStoreServiceCompleteWorkspacePreparationRequest{SessionId: id, Assignment: assignment, ObservedAt: timestamppb.Now()}
for _, message := range []proto.Message{assignment, callback} {
if err := protovalidate.Validate(message); (err == nil) != test.valid {
t.Errorf("%T valid=%v, error=%v", message, test.valid, err)
}
}
})
}
}
26 changes: 19 additions & 7 deletions go/core/internal/grpcserver/session_native_handoff_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -137,24 +137,30 @@ func nativeGit(t *testing.T) (string, []string) {

func TestNativePreparationInstalledGRPCPostgres(t *testing.T) {
for _, provider := range []string{"claude", "codex"} {
t.Run(provider, func(t *testing.T) { nativePreparationInstalled(t, provider, "ordinary") })
t.Run(provider, func(t *testing.T) { nativePreparationInstalled(t, provider, "ordinary", "child") })
}
}

func TestNativePreparationOwnerWorkspaceGRPCPostgres(t *testing.T) {
for _, provider := range []string{"claude", "codex"} {
t.Run(provider, func(t *testing.T) { nativePreparationInstalled(t, provider, "lifecycle", "agent") })
}
}

func TestNativePreparationLifecycleContinuationPostgres(t *testing.T) {
for _, provider := range []string{"claude", "codex"} {
t.Run(provider, func(t *testing.T) { nativePreparationInstalled(t, provider, "lifecycle") })
t.Run(provider, func(t *testing.T) { nativePreparationInstalled(t, provider, "lifecycle", "child") })
}
}

func TestNativePreparationClaudeDurableRestartPostgres(t *testing.T) {
for _, scenario := range []string{"restart", "restart-protected"} {
t.Run(scenario, func(t *testing.T) { nativePreparationInstalled(t, "claude", scenario) })
t.Run(scenario, func(t *testing.T) { nativePreparationInstalled(t, "claude", scenario, "child") })
}
}

func TestNativePreparationClaudeProtectedMCPPostgres(t *testing.T) {
nativePreparationInstalled(t, "claude", "protected")
nativePreparationInstalled(t, "claude", "protected", "child")
}

// The first callback is committed but its reply is lost. A fresh executor must
Expand Down Expand Up @@ -189,7 +195,7 @@ func (c capturedPreparationReply) CompleteWorkspacePreparation(ctx context.Conte
return err
}

func nativePreparationInstalled(t *testing.T, provider, scenario string) {
func nativePreparationInstalled(t *testing.T, provider, scenario, profile string) {
t.Helper()
if testing.Short() {
t.Skip("real PostgreSQL integration")
Expand Down Expand Up @@ -289,9 +295,9 @@ func nativePreparationInstalled(t *testing.T, provider, scenario string) {
require.NoError(t, err)
association := original.Session.RuntimeAssociation
require.NotNil(t, association)
setup, err := workspace.SetupDigest("child")
setup, err := workspace.SetupDigest(profile)
require.NoError(t, err)
input := &api.PrepareSessionWorkspaceRequest{SessionId: created.Session.Id, ActionId: "native-create:prepare", CreateRequestId: creation.RequestId, GenerationId: association.GenerationId, ActorUid: association.ActorUid, PreparedRevision: original.Session.PreparedRevision, Workspace: proto.CloneOf(original.Session.Workspace), DevelopmentEnvironment: proto.CloneOf(environment), RuntimeComposition: proto.CloneOf(composition), SetupProfile: "child", SetupDigest: setup}
input := &api.PrepareSessionWorkspaceRequest{SessionId: created.Session.Id, ActionId: "native-create:prepare", CreateRequestId: creation.RequestId, GenerationId: association.GenerationId, ActorUid: association.ActorUid, PreparedRevision: original.Session.PreparedRevision, Workspace: proto.CloneOf(original.Session.Workspace), DevelopmentEnvironment: proto.CloneOf(environment), RuntimeComposition: proto.CloneOf(composition), SetupProfile: profile, SetupDigest: setup}
assigned, err := client.PrepareSessionWorkspace(owner, input)
require.NoError(t, err)
require.Equal(t, "pending", assigned.Receipt.Classification)
Expand Down Expand Up @@ -356,6 +362,12 @@ func nativePreparationInstalled(t *testing.T, provider, scenario string) {
completed = r.Session
return completed.GetWorkspacePreparation().GetClassification() == "confirmed" || completed.GetWorkspacePreparation().GetClassification() == "definite-failure"
}, 15*time.Second, 20*time.Millisecond)
require.Equal(t, created.Session.Id, completed.Id)
require.Equal(t, created.Session.ContextId, completed.ContextId)
require.Equal(t, original.Session.PreparedRevision, completed.PreparedRevision)
require.True(t, proto.Equal(environment, completed.DevelopmentEnvironment))
require.True(t, proto.Equal(composition, completed.RuntimeComposition))
require.True(t, proto.Equal(input, completed.WorkspacePreparation.Original))
require.Equal(t, "confirmed", completed.WorkspacePreparation.Classification)
require.Equal(t, sha, completed.WorkspacePreparation.Head)
require.NotNil(t, completed.WorkspacePreparation.EffectObservedAt)
Expand Down
63 changes: 36 additions & 27 deletions go/core/internal/service/session/native_handoff_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,34 +51,43 @@ func TestNativePreparationServiceRequiresExactServicePrincipal(t *testing.T) {
}

func TestNativePreparationServiceRejectsIntrinsicAndForeignInputs(t *testing.T) {
policy, err := controlauth.New(controlauth.Config{Namespace: "kagent", Agents: []string{"mainloop-main"}})
require.NoError(t, err)
for _, name := range []string{"unknown", "oversize", "setup", "creator", "Agent", "namespace", "share"} {
t.Run(name, func(t *testing.T) {
input := nativeServiceInput(t)
session := &api.Session{Id: input.SessionId, Creator: "mainloop", Agent: &api.ResourceReference{Namespace: "kagent", Name: "mainloop-main"}, Workspace: input.Workspace, DevelopmentEnvironment: input.DevelopmentEnvironment}
store := &nativeTestStore{serviceTestStore: &serviceTestStore{getResult: session}}
service := NewService(store, policy, serviceTestWorkflow{})
ctx := auth.AuthSessionTo(t.Context(), mainloopSession{})
switch name {
case "unknown":
input.ProtoReflect().SetUnknown([]byte{0xf8, 0x07, 0x01})
case "oversize":
input.RuntimeComposition.CliVersion = strings.Repeat("x", 8193)
case "setup":
input.SetupDigest = strings.Repeat("0", 64)
case "creator":
session.Creator = "other"
case "Agent":
session.Agent.Name = "other"
case "namespace":
session.Agent.Namespace = "other"
case "share":
ctx = auth.ShareContextTo(ctx, &auth.ShareContext{SessionID: session.Id, UserID: "mainloop", ReadOnly: false})
for _, profile := range []string{"supervisor", "child", "agent"} {
t.Run(profile, func(t *testing.T) {
policy, err := controlauth.New(controlauth.Config{Namespace: "kagent", Agents: []string{"mainloop-main"}})
require.NoError(t, err)
for _, name := range []string{"unknown", "oversize", "setup", "profile", "creator", "Agent", "namespace", "share"} {
t.Run(name, func(t *testing.T) {
input := nativeServiceInput(t)
input.SetupProfile = profile
input.SetupDigest, err = workspace.SetupDigest(profile)
require.NoError(t, err)
session := &api.Session{Id: input.SessionId, Creator: "mainloop", Agent: &api.ResourceReference{Namespace: "kagent", Name: "mainloop-main"}, Workspace: input.Workspace, DevelopmentEnvironment: input.DevelopmentEnvironment}
store := &nativeTestStore{serviceTestStore: &serviceTestStore{getResult: session}}
service := NewService(store, policy, serviceTestWorkflow{})
ctx := auth.AuthSessionTo(t.Context(), mainloopSession{})
switch name {
case "unknown":
input.ProtoReflect().SetUnknown([]byte{0xf8, 0x07, 0x01})
case "oversize":
input.RuntimeComposition.CliVersion = strings.Repeat("x", 8193)
case "setup":
input.SetupDigest = strings.Repeat("0", 64)
case "profile":
input.SetupProfile = "owner"
case "creator":
session.Creator = "other"
case "Agent":
session.Agent.Name = "other"
case "namespace":
session.Agent.Namespace = "other"
case "share":
ctx = auth.ShareContextTo(ctx, &auth.ShareContext{SessionID: session.Id, UserID: "mainloop", ReadOnly: false})
}
_, err := service.PrepareWorkspace(ctx, input)
require.Error(t, err)
require.Zero(t, store.prepares)
})
}
_, err := service.PrepareWorkspace(ctx, input)
require.Error(t, err)
require.Zero(t, store.prepares)
})
}
}
Expand Down
Loading
Loading