oficina / equipo Public

feat: relay fenced questions and permission responses

codex agent, operated by paul@keymail.dev pushed by claude agent, operated by paul@keymail.dev 8ff3974ffe16516c02e223585929d544b73b1286 parent 36011ef
23 files changed, +2,267 −5
  • cmd/equipo-runner/main.go +24 −0
  • cmd/equipo-runner/main_test.go +17 −0
  • internal/equipo/app.go +9 −1
  • internal/equipo/copy.go +24 −0
  • internal/equipo/migrations/0016_questions.sql +2 −0
  • internal/equipo/migrations/schema.sql +3 −0
  • internal/equipo/models.go +1 −1
  • internal/equipo/question_handlers.go +43 −0
  • internal/equipo/questions.go +232 −0
  • internal/equipo/runner_api.go +1 −1
  • internal/equipo/runner_execution_models.go +1 −0
  • internal/equipo/runner_mutations.go +6 −0
  • internal/equipotest/questions_test.go +253 −0
  • internal/runner/journal.go +4 −2
  • internal/runner/questions.go +198 −0
  • internal/runner/questions_test.go +215 −0
  • internal/runner/tool_journal.go +97 −0
  • internal/runner/tool_socket.go +399 −0
  • internal/runner/tool_socket_test.go +281 −0
  • internal/runner/tools.go +237 −0
  • internal/runner/tools_test.go +101 −0
  • internal/runnerproto/questions.go +118 −0
  • internal/runnerproto/types.go +1 −0

CI failed — run details

diff --git a/cmd/equipo-runner/main.go b/cmd/equipo-runner/main.go
new file mode 100644
index 00000000..cc7ad6d3
--- /dev/null
+++ b/cmd/equipo-runner/main.go
@@ -0,0 +1,24 @@
+package main
+
+import (
+ "amadan.net/oficina/equipo/internal/equipo"
+ "amadan.net/oficina/equipo/internal/runner"
+ "context"
+ "io"
+ "os"
+)
+
+func run(ctx context.Context, args []string, input io.Reader, output, errorOutput io.Writer, getenv func(string) string) int {
+ if len(args) != 1 || args[0] != "tool" {
+ _, _ = io.WriteString(errorOutput, equipo.CopyToolRejected+"\n")
+ return 1
+ }
+ if runner.ServeTools(ctx, input, output, getenv("EQUIPO_TOOL_SOCKET"), getenv("EQUIPO_TOOL_CAPABILITY_FILE")) != nil {
+ _, _ = io.WriteString(errorOutput, equipo.CopyToolRejected+"\n")
+ return 1
+ }
+ return 0
+}
+func main() {
+ os.Exit(run(context.Background(), os.Args[1:], os.Stdin, os.Stdout, os.Stderr, os.Getenv))
+}
diff --git a/cmd/equipo-runner/main_test.go b/cmd/equipo-runner/main_test.go
new file mode 100644
index 00000000..bcdf7c24
--- /dev/null
+++ b/cmd/equipo-runner/main_test.go
@@ -0,0 +1,17 @@
+package main
+
+import (
+ "bytes"
+ "context"
+ "strings"
+ "testing"
+)
+
+func TestToolVerbClosed(t *testing.T) {
+ for _, args := range [][]string{nil, {"serve"}, {"tool", "secret"}, {"tool"}} {
+ var out, log bytes.Buffer
+ if run(context.Background(), args, strings.NewReader(""), &out, &log, func(string) string { return "/missing" }) != 1 || strings.Contains(log.String(), "secret") || out.Len() != 0 {
+ t.Fatal("unsafe tool failure", args)
+ }
+ }
+}
diff --git a/internal/equipo/app.go b/internal/equipo/app.go
index 10e6a230..1f1f11e5 100644
--- a/internal/equipo/app.go
+++ b/internal/equipo/app.go
@@ -59,6 +59,14 @@ func App(d *db.DB, cfg Config, mailer mail.Sender, logger *slog.Logger) (*http.S
// Router applies the schema and builds the routes.
func Router(d *db.DB, cfg Config, mailer mail.Sender, logger *slog.Logger) (chi.Router, error) {
+ return RouterWithStore(d, cfg, mailer, logger, NewStore(d))
+}
+
+// RouterWithStore composes the verified session routes with a startup-configured store.
+func RouterWithStore(d *db.DB, cfg Config, mailer mail.Sender, logger *slog.Logger, store *Store) (chi.Router, error) {
+ if store == nil || store.db != d {
+ return nil, ErrInvalid
+ }
if err := cfg.validate(); err != nil {
return nil, err
}
@@ -81,7 +89,6 @@ func Router(d *db.DB, cfg Config, mailer mail.Sender, logger *slog.Logger) (chi.
logger.Info(copyMigrate, "applied", migrated.Applied,
"skipped", migrated.Skipped, "adopted", migrated.Adopted)
- store := NewStore(d)
if err := store.Bootstrap(context.Background(), cfg.Owners); err != nil {
return nil, err
}
@@ -117,6 +124,7 @@ func Router(d *db.DB, cfg Config, mailer mail.Sender, logger *slog.Logger) (chi.
r.Get("/people", a.people)
r.Get("/runners/enrol", a.enrolmentPage)
r.Post("/tasks", a.createBug)
+ r.Post("/tasks/{id}/questions/{question}/answer", a.answerQuestion)
r.Post("/runners/enrol", a.approveEnrolment)
r.Post("/runners/{id}/revoke", a.revokeRunner)
r.Post("/projects/{id}/connections", a.saveConnectionChoice)
diff --git a/internal/equipo/copy.go b/internal/equipo/copy.go
index 90b49869..34107e76 100644
--- a/internal/equipo/copy.go
+++ b/internal/equipo/copy.go
@@ -1,5 +1,7 @@
package equipo
+import "amadan.net/oficina/equipo/internal/runner"
+
// COPY APPROVED BY DELEGATION (Luna pass, 2026-11-01, house rules).
// App-owned runtime strings belong here, including boot diagnostics.
const (
@@ -165,3 +167,25 @@ var pageCopy = map[string]string{
func copyText(key string) string { return pageCopy[key] }
func RunnerCopy(key string) string { return copyText(key) }
+
+// COPY REVIEW REQUIRED: Task 13 tool acknowledgement.
+const CopyToolAccepted = "Saved for validation."
+
+// COPY REVIEW REQUIRED: Task 13 bounded tool refusal.
+const CopyToolRejected = "This tool request could not be accepted."
+
+// COPY REVIEW REQUIRED: Task 13 tool description.
+const CopyToolAsk = "Ask a person a question about this task. Reuse the request ID only for an identical retry."
+
+// COPY REVIEW REQUIRED: Task 13 tool description.
+const CopyToolCandidate = "Submit a candidate commit for this task. Reuse the request ID only for an identical retry."
+
+// COPY REVIEW REQUIRED: Task 13 tool description.
+const CopyToolReview = "Submit a review of this task's candidate. Reuse the request ID only for an identical retry."
+
+// COPY REVIEW REQUIRED: Task 13 tool description.
+const CopyToolReproduction = "Submit reproduction files and test names for this task. Encode file bytes as base64. Reuse the request ID only for an identical retry."
+
+func RunnerToolCopy() runner.ToolCopy {
+ return runner.ToolCopy{Accepted: CopyToolAccepted, Rejected: CopyToolRejected, Ask: CopyToolAsk, Candidate: CopyToolCandidate, Review: CopyToolReview, Reproduction: CopyToolReproduction}
+}
diff --git a/internal/equipo/migrations/0016_questions.sql b/internal/equipo/migrations/0016_questions.sql
new file mode 100644
index 00000000..07adbf39
--- /dev/null
+++ b/internal/equipo/migrations/0016_questions.sql
@@ -0,0 +1,2 @@
+CREATE TABLE questions (id text, assignment_id text, task_id text, server_id text, agent_id text, session_id text, permission_id text, kind text, attempt integer, fence integer, revision integer, raw_request text, input_hash text, state text, answer text, answered_by text, expires_at datetime, PRIMARY KEY(id));
+CREATE INDEX question_assignment ON questions(assignment_id);
diff --git a/internal/equipo/migrations/schema.sql b/internal/equipo/migrations/schema.sql
index 12888530..aae1617b 100644
--- a/internal/equipo/migrations/schema.sql
+++ b/internal/equipo/migrations/schema.sql
@@ -340,3 +340,6 @@ CREATE TABLE runner_event_ids (runner_id text, event_id text, event_key text, PR
CREATE TABLE runner_timelines (stream_key text, assignment_id text, epoch text, high_water integer, blocked numeric, isolation text, PRIMARY KEY(stream_key));
CREATE INDEX runner_timeline_assignment ON runner_timelines(assignment_id);
CREATE TABLE runner_artifact_requests (assignment_id text, request_id text, payload_hash text, artifact_id integer, PRIMARY KEY(assignment_id, request_id));
+
+CREATE TABLE questions (id text, assignment_id text, task_id text, server_id text, agent_id text, session_id text, permission_id text, kind text, attempt integer, fence integer, revision integer, raw_request text, input_hash text, state text, answer text, answered_by text, expires_at datetime, PRIMARY KEY(id));
+CREATE INDEX question_assignment ON questions(assignment_id);
diff --git a/internal/equipo/models.go b/internal/equipo/models.go
index 6c852d25..16d63199 100644
--- a/internal/equipo/models.go
+++ b/internal/equipo/models.go
@@ -2,7 +2,7 @@ package equipo
import "time"
-var Models = append([]any{&runnerEvent{}, &runnerEventID{}, &runnerTimeline{}, &runnerArtifactRequest{}, &artifactBlob{}, &artifactBlobUpload{}, &runnerAssignment{}, &runnerCleanup{}, &runnerObservation{}, &runnerRotation{}, &executionAdmissionTicket{}, &Task{}, &taskOutbox{}, &Team{}, &Member{}, &AuditEvent{}, &Account{}, &Project{}, &DecisionOwner{}, &projectRequest{}, &budgetRecord{}, &Specialist{}, &runnerRecord{}, &runnerEnrolment{}, &runnerCredentialRecord{}, &runnerRate{}, &connectionRecord{}, &connectionChoiceRecord{}, &isolationAcknowledgementRecord{}, &ConnectionInvalidation{}}, executionModels...)
+var Models = append([]any{&questionRecord{}, &runnerEvent{}, &runnerEventID{}, &runnerTimeline{}, &runnerArtifactRequest{}, &artifactBlob{}, &artifactBlobUpload{}, &runnerAssignment{}, &runnerCleanup{}, &runnerObservation{}, &runnerRotation{}, &executionAdmissionTicket{}, &Task{}, &taskOutbox{}, &Team{}, &Member{}, &AuditEvent{}, &Account{}, &Project{}, &DecisionOwner{}, &projectRequest{}, &budgetRecord{}, &Specialist{}, &runnerRecord{}, &runnerEnrolment{}, &runnerCredentialRecord{}, &runnerRate{}, &connectionRecord{}, &connectionChoiceRecord{}, &isolationAcknowledgementRecord{}, &ConnectionInvalidation{}}, executionModels...)
type Role string
diff --git a/internal/equipo/question_handlers.go b/internal/equipo/question_handlers.go
new file mode 100644
index 00000000..3cf4c0b0
--- /dev/null
+++ b/internal/equipo/question_handlers.go
@@ -0,0 +1,43 @@
+package equipo
+
+import (
+ "amadan.net/oficina/equipo/internal/runnerproto"
+ "amadan.net/rastrillo/rastrillo/auth"
+ "encoding/json"
+ "github.com/go-chi/chi/v5"
+ "net/http"
+ "strconv"
+)
+
+func (a *application) answerQuestion(w http.ResponseWriter, r *http.Request) {
+ r.Body = http.MaxBytesReader(w, r.Body, 32<<10)
+ if r.ParseForm() != nil || len(r.URL.Query()) != 0 {
+ a.failure(w, r, ErrInvalid)
+ return
+ }
+ for k, v := range r.PostForm {
+ if len(v) != 1 || (k != "revision" && k != "behavior" && k != "updated_input") {
+ a.failure(w, r, ErrInvalid)
+ return
+ }
+ }
+ actor, ok := auth.From(r)
+ if !ok {
+ a.failure(w, r, ErrForbidden)
+ return
+ }
+ rev, err := strconv.ParseInt(r.PostForm.Get("revision"), 10, 64)
+ if err != nil {
+ a.failure(w, r, ErrInvalid)
+ return
+ }
+ answer := runnerproto.QuestionAnswer{Behavior: r.PostForm.Get("behavior")}
+ if raw := r.PostForm.Get("updated_input"); raw != "" {
+ answer.UpdatedInput = json.RawMessage(raw)
+ }
+ if err := a.store.answerQuestion(r.Context(), Actor{Address: actor.Address}, chi.URLParam(r, "id"), chi.URLParam(r, "question"), rev, answer); err != nil {
+ a.failure(w, r, err)
+ return
+ }
+ http.Redirect(w, r, "/needs-you", http.StatusSeeOther)
+}
diff --git a/internal/equipo/questions.go b/internal/equipo/questions.go
new file mode 100644
index 00000000..f3ec2321
--- /dev/null
+++ b/internal/equipo/questions.go
@@ -0,0 +1,232 @@
+package equipo
+
+import (
+ "amadan.net/oficina/equipo/internal/equipo/team"
+ "amadan.net/oficina/equipo/internal/runner"
+ "amadan.net/oficina/equipo/internal/runnerproto"
+ "context"
+ "encoding/json"
+ "errors"
+ "gorm.io/gorm"
+ "time"
+)
+
+type questionRecord struct {
+ ID string `gorm:"primaryKey"`
+ AssignmentID string `gorm:"index:question_assignment"`
+ TaskID, ServerID, AgentID, SessionID, PermissionID, Kind string
+ Attempt, Fence, Revision int64
+ RawRequest, InputHash, State, Answer, AnsweredBy string
+ ExpiresAt time.Time
+}
+
+func (questionRecord) TableName() string { return "questions" }
+func (q questionRecord) value() (runnerproto.Question, error) {
+ v := runnerproto.Question{ID: q.ID, TaskID: q.TaskID, AssignmentID: q.AssignmentID, ServerID: q.ServerID, AgentID: q.AgentID, SessionID: q.SessionID, PermissionID: q.PermissionID, Kind: q.Kind, Attempt: q.Attempt, Fence: q.Fence, Revision: q.Revision, RawRequest: json.RawMessage(q.RawRequest), AnsweredBy: q.AnsweredBy, ExpiresAt: q.ExpiresAt}
+ if q.Answer != "" {
+ if err := json.Unmarshal([]byte(q.Answer), &v.Answer); err != nil {
+ return v, ErrUnavailable
+ }
+ }
+ return v, nil
+}
+func (e *Execution) recordQuestion(ctx context.Context, tx *gorm.DB, a runnerAssignment, value Assignment, r RunnerRequest) (any, error) {
+ if a.Kind != "step" || r.Question == nil || r.Question.Validate() != nil || r.Question.TaskID != a.TaskID || e.validators.Question == nil {
+ return nil, ErrInvalid
+ }
+ if err := e.validators.Question(ctx, value, r); err != nil {
+ return nil, err
+ }
+ q := *r.Question
+ if q.Answer != nil || q.AnsweredBy != "" || q.Revision != 1 {
+ return nil, ErrInvalid
+ }
+ hash := runnerproto.EventHash(q)
+ if err := observeQuestion(tx, a, "questions", r, e.store.runnerClock.Now()); err != nil {
+ return nil, err
+ }
+ q.RawRequest = runner.RedactJSON(q.RawRequest, nil)
+ var old questionRecord
+ err := tx.First(&old, "id=?", q.ID).Error
+ if err == nil {
+ if old.AssignmentID != a.ID || old.InputHash != hash {
+ return nil, ErrConflict
+ }
+ return old.value()
+ }
+ if !errors.Is(err, gorm.ErrRecordNotFound) {
+ return nil, storeError(err)
+ }
+ // A new pending request replaces earlier permission authority for this agent,
+ // including a changed provider session. Replayed old IDs never reactivate it.
+ if err := tx.Model(&questionRecord{}).Where("assignment_id=? AND state IN ?", a.ID, []string{"pending", "answered"}).Select("State").Updates(&questionRecord{State: "invalid"}).Error; err != nil {
+ return nil, storeError(err)
+ }
+ row := questionRecord{ID: q.ID, TaskID: a.TaskID, AssignmentID: a.ID, ServerID: q.ServerID, AgentID: q.AgentID, SessionID: q.SessionID, PermissionID: q.PermissionID, Kind: q.Kind, Attempt: a.AttemptID, Fence: a.Fence, Revision: 1, RawRequest: string(q.RawRequest), InputHash: hash, State: "pending", ExpiresAt: a.LeaseDeadline}
+ if err := tx.Create(&row).Error; err != nil {
+ return nil, storeError(err)
+ }
+ if err := appendAudit(tx, Actor{Address: a.Person}, "question.create", q.ID); err != nil {
+ return nil, err
+ }
+ return row.value()
+}
+func (e *Execution) questionCurrent(ctx context.Context, tx *gorm.DB, q questionRecord) error {
+ now := e.store.runnerClock.Now()
+ if (q.State != "pending" && q.State != "answered") || !now.Before(q.ExpiresAt) {
+ return ErrConflict
+ }
+ var a runnerAssignment
+ if err := tx.First(&a, "id=?", q.AssignmentID).Error; err != nil {
+ return storeError(err)
+ }
+ if a.TaskID != q.TaskID || a.State != "claimed" || a.AttemptID != q.Attempt || a.Fence != q.Fence || !now.Before(a.LeaseDeadline) {
+ return ErrConflict
+ }
+ if err := runnerTimelineAvailable(tx, a.ID); err != nil {
+ return err
+ }
+ var cred runnerCredentialRecord
+ if err := tx.Where("runner_id=? AND revoked_at IS NULL AND expires_at>?", a.RunnerID, now).First(&cred).Error; err != nil {
+ return storeError(err)
+ }
+ if _, err := e.assignmentCurrent(ctx, tx, RunnerPrincipal{RunnerID: a.RunnerID, Person: a.Person, CredentialID: cred.ID}, a); err != nil {
+ return err
+ }
+ return e.Core.ValidateHandle(ctx, team.Scope{Account: team.AccountID(a.TeamID), Job: team.JobID(a.JobID)}, team.Handle{Attempt: team.AttemptID(a.AttemptID), Fence: a.Fence, Runner: a.RunnerID})
+}
+func (s *Store) AnswerQuestion(ctx context.Context, actor Actor, id string, revision int64, answer runnerproto.QuestionAnswer) error {
+ return s.answerQuestion(ctx, actor, "", id, revision, answer)
+}
+func (s *Store) answerQuestion(ctx context.Context, actor Actor, taskID, id string, revision int64, answer runnerproto.QuestionAnswer) error {
+ if s.execution == nil {
+ return ErrUnavailable
+ }
+ return s.execution.atomic(ctx, func(ctx context.Context, tx *gorm.DB) error {
+ member, err := memberAt(tx, actor.Address)
+ if err != nil {
+ return err
+ }
+ if !member.Active {
+ return ErrForbidden
+ }
+ var q questionRecord
+ if err := tx.First(&q, "id=?", id).Error; err != nil {
+ return storeError(err)
+ }
+ if taskID != "" && q.TaskID != taskID {
+ return ErrForbidden
+ }
+ var task Task
+ if err := tx.First(&task, "id=?", q.TaskID).Error; err != nil {
+ return storeError(err)
+ }
+ if member.Address != task.Requester && member.Role != RoleOwner {
+ return ErrForbidden
+ }
+ if q.Revision != revision {
+ return ErrConflict
+ }
+ if err := s.execution.questionCurrent(ctx, tx, q); err != nil {
+ return err
+ }
+ value, err := q.value()
+ if err != nil {
+ return err
+ }
+ if value.ValidateAnswer(answer) != nil {
+ return ErrInvalid
+ }
+ raw, _ := json.Marshal(answer)
+ // Canonicalize opaque answers so object key order cannot create new effects.
+ var canonical any
+ _ = json.Unmarshal(raw, &canonical)
+ raw, _ = json.Marshal(canonical)
+ if q.State == "answered" {
+ if q.Answer != string(raw) || q.AnsweredBy != member.Address {
+ return ErrConflict
+ }
+ return nil
+ }
+ q.State = "answered"
+ q.Answer = string(raw)
+ q.AnsweredBy = member.Address
+ if err := tx.Model(&questionRecord{}).Where("id=?", id).Select("State", "Answer", "AnsweredBy").Updates(&q).Error; err != nil {
+ return storeError(err)
+ }
+ return appendAudit(tx, actor, "question.answer", id)
+ })
+}
+func (e *Execution) questionAnswers(ctx context.Context, tx *gorm.DB, a runnerAssignment) ([]runnerproto.Question, error) {
+ var rows []questionRecord
+ if err := tx.Where("assignment_id=? AND state='answered'", a.ID).Order("id").Find(&rows).Error; err != nil {
+ return nil, storeError(err)
+ }
+ out := []runnerproto.Question{}
+ for _, q := range rows {
+ if !e.store.runnerClock.Now().Before(q.ExpiresAt) {
+ continue
+ }
+ if err := e.questionCurrent(ctx, tx, q); err != nil {
+ return nil, err
+ }
+ // An answerer's removal/demotion must also revoke an undelivered answer.
+ member, err := memberAt(tx, q.AnsweredBy)
+ if err != nil {
+ return nil, err
+ }
+ if !member.Active || (member.Address != a.Person && member.Role != RoleOwner) {
+ return nil, ErrForbidden
+ }
+ v, err := q.value()
+ if err != nil {
+ return nil, err
+ }
+ out = append(out, v)
+ }
+ return out, nil
+}
+
+func observeQuestion(tx *gorm.DB, a runnerAssignment, op string, q RunnerRequest, now time.Time) error {
+ hash := runnerproto.EventHash(q)
+ var old runnerObservation
+ err := tx.First(&old, "assignment_id=? AND request_id=?", a.ID, q.RequestID).Error
+ if err == nil {
+ if old.Operation != op || old.PayloadHash != hash {
+ return ErrConflict
+ }
+ return nil
+ }
+ if !errors.Is(err, gorm.ErrRecordNotFound) {
+ return storeError(err)
+ }
+ // Full sanitized input lives in questions, never in a second raw observation.
+ return storeError(tx.Create(&runnerObservation{AssignmentID: a.ID, RequestID: q.RequestID, Operation: op, PayloadHash: hash, At: now}).Error)
+}
+
+func (e *Execution) resolveQuestion(ctx context.Context, tx *gorm.DB, a runnerAssignment, value Assignment, r RunnerRequest) error {
+ if r.Question == nil || e.validators.Question == nil {
+ return ErrInvalid
+ }
+ if err := e.validators.Question(ctx, value, r); err != nil {
+ return err
+ }
+ q := r.Question
+ var old questionRecord
+ if err := tx.First(&old, "id=?", q.ID).Error; err != nil {
+ return storeError(err)
+ }
+ if old.AssignmentID != a.ID || old.ServerID != q.ServerID || old.AgentID != q.AgentID || old.SessionID != q.SessionID || old.PermissionID != q.PermissionID {
+ return ErrForbidden
+ }
+ if err := observeQuestion(tx, a, "question_resolved", r, e.store.runnerClock.Now()); err != nil {
+ return err
+ }
+ if old.State == "invalid" {
+ return nil
+ }
+ if err := tx.Model(&questionRecord{}).Where("id=?", old.ID).Select("State").Updates(&questionRecord{State: "invalid"}).Error; err != nil {
+ return storeError(err)
+ }
+ return appendAudit(tx, Actor{Address: a.Person}, "question.resolve", old.ID)
+}
diff --git a/internal/equipo/runner_api.go b/internal/equipo/runner_api.go
index e621643e..b99af79a 100644
--- a/internal/equipo/runner_api.go
+++ b/internal/equipo/runner_api.go
@@ -19,7 +19,7 @@ func (s *Store) RunnerHandler() http.Handler {
r.Post("/blobs", s.runnerPutBlob)
r.Post("/blobs/read", s.runnerReadBlob)
r.Post("/claim", s.runnerClaim)
- for _, op := range []string{"renew", "prepare", "events", "artifacts", "intend", "admit", "receipts", "lost", "complete", "release", "stop", "contained"} {
+ for _, op := range []string{"question_resolved", "questions", "answers", "renew", "prepare", "events", "artifacts", "intend", "admit", "receipts", "lost", "complete", "release", "stop", "contained"} {
r.Post("/"+op, s.runnerMutation(op))
}
r.Post("/connections", s.runnerConnections)
diff --git a/internal/equipo/runner_execution_models.go b/internal/equipo/runner_execution_models.go
index b201eaee..edf23e04 100644
--- a/internal/equipo/runner_execution_models.go
+++ b/internal/equipo/runner_execution_models.go
@@ -68,6 +68,7 @@ type executionAdmissionTicket struct {
func (executionAdmissionTicket) TableName() string { return "admission_tickets" }
type RunnerValidators struct {
+ Question func(context.Context, Assignment, RunnerRequest) error
Receipt func(context.Context, Assignment, RunnerRequest) (team.Receipt, error)
Containment func(context.Context, Assignment, RunnerRequest) error
Prepare func(context.Context, Assignment, RunnerRequest) (PreparedBug, error)
diff --git a/internal/equipo/runner_mutations.go b/internal/equipo/runner_mutations.go
index aba4437f..8300e9f0 100644
--- a/internal/equipo/runner_mutations.go
+++ b/internal/equipo/runner_mutations.go
@@ -166,6 +166,12 @@ func (e *Execution) mutateAt(ctx context.Context, tx *gorm.DB, a runnerAssignmen
}
}
switch op {
+ case "question_resolved":
+ return nil, e.resolveQuestion(ctx, tx, a, value, q)
+ case "questions":
+ return e.recordQuestion(ctx, tx, a, value, q)
+ case "answers":
+ return e.questionAnswers(ctx, tx, a)
case "renew":
deadline := now.Add(30 * time.Second)
if a.Kind == "step" {
diff --git a/internal/equipotest/questions_test.go b/internal/equipotest/questions_test.go
new file mode 100644
index 00000000..3c3a02fa
--- /dev/null
+++ b/internal/equipotest/questions_test.go
@@ -0,0 +1,253 @@
+package equipotest
+
+import (
+ "amadan.net/oficina/equipo/internal/equipo"
+ "amadan.net/oficina/equipo/internal/runnerproto"
+ "context"
+ "encoding/json"
+ "net/http/httptest"
+ "net/url"
+ "strings"
+ "testing"
+ "time"
+)
+
+func questionFixture(t *testing.T) (runnerFixture, runnerproto.Question) {
+ t.Helper()
+ f := runnerFixtureNew(t, true)
+ f.x.SetRunnerValidators(equipo.RunnerValidators{Question: func(_ context.Context, _ equipo.Assignment, _ equipo.RunnerRequest) error { return nil }})
+ q := runnerproto.Question{ID: "question", TaskID: f.a.TaskID, ServerID: "server", AgentID: "agent", SessionID: "session", PermissionID: "permission", Kind: "question", Revision: 1, RawRequest: json.RawMessage(`{"id":"permission","kind":"question","provider":"claude","name":"AskUserQuestion","input":{"questions":[{"question":"Which?","header":"Which?"}]}}`)}
+ request := f.request()
+ request.Question = &q
+ _, err := f.x.Mutate(connectionContext, f.principal, "questions", request)
+ executionMust(t, err)
+ return f, q
+}
+func TestQuestionStaleAnswer(t *testing.T) {
+ for _, change := range []string{"revision", "fence", "cancel", "lease", "replaced"} {
+ t.Run(change, func(t *testing.T) {
+ f, q := questionFixture(t)
+ revision := int64(1)
+ switch change {
+ case "revision":
+ revision++
+ case "fence":
+ mustSQL(t, f.d, "UPDATE runner_assignments SET fence=fence+1")
+ case "cancel":
+ _, err := f.x.Core.Cancel(connectionContext, f.claim.Scope, "test", "cancel")
+ executionMust(t, err)
+ case "lease":
+ f.clock.Advance(time.Minute)
+ case "replaced":
+ q.ID = "replacement"
+ q.PermissionID = "new"
+ q.RawRequest = json.RawMessage(`{"id":"new","kind":"question"}`)
+ r := f.request()
+ r.RequestID = "replacement"
+ r.Question = &q
+ _, err := f.x.Mutate(connectionContext, f.principal, "questions", r)
+ executionMust(t, err)
+ }
+ if err := f.s.AnswerQuestion(connectionContext, ownerActor, "question", revision, runnerproto.QuestionAnswer{Behavior: "deny"}); err == nil {
+ t.Fatal("stale answer accepted", change)
+ }
+ })
+ }
+}
+func TestQuestionBrowserAuthority(t *testing.T) {
+ f, q := questionFixture(t)
+ answer := runnerproto.QuestionAnswer{Behavior: "allow", UpdatedInput: json.RawMessage(`{"answers":{"Which?":"Blue"}}`)}
+ mustSQL(t, f.d, "INSERT INTO members(address,role,active,revision,session_epoch) VALUES(?, ?, 1, 1, 0)", "reader@example.com", equipo.RoleMember)
+ if f.s.AnswerQuestion(connectionContext, equipo.Actor{Address: "reader@example.com"}, q.ID, 1, answer) == nil {
+ t.Fatal("unrelated reader answered")
+ }
+ executionMust(t, f.s.AnswerQuestion(connectionContext, ownerActor, q.ID, 1, answer))
+ executionMust(t, f.s.AnswerQuestion(connectionContext, ownerActor, q.ID, 1, answer))
+ answer.Behavior = "deny"
+ answer.UpdatedInput = nil
+ if f.s.AnswerQuestion(connectionContext, ownerActor, q.ID, 1, answer) == nil {
+ t.Fatal("changed replay accepted")
+ }
+ if scalar(t, f.d, "SELECT count(*) FROM audit_events WHERE kind='question.answer'") != 1 {
+ t.Fatal("replay duplicated effect")
+ }
+ r := f.request()
+ r.RequestID = "answers"
+ result, err := f.x.Mutate(connectionContext, f.principal, "answers", r)
+ executionMust(t, err)
+ if len(result.([]runnerproto.Question)) != 1 {
+ t.Fatal("answer not polled")
+ }
+ mustSQL(t, f.d, "UPDATE members SET active=0 WHERE address=?", ownerAddress)
+ if f.s.AnswerQuestion(connectionContext, ownerActor, q.ID, 1, answer) == nil {
+ t.Fatal("removed member answered")
+ }
+}
+
+func TestQuestionBrowserAuthorityHTTP(t *testing.T) {
+ f, q := questionFixture(t)
+ m := &capturingMailer{}
+ router, err := equipo.RouterWithStore(f.d, testConfig(testOrigin), m, nil, f.s)
+ executionMust(t, err)
+ server := httptest.NewServer(router)
+ t.Cleanup(server.Close)
+ c := signinClient(t, server.URL)
+ signinEmail(t, c, server.URL, testOrigin, m, ownerAddress)
+ path := server.URL + "/tasks/" + f.a.TaskID + "/questions/" + q.ID + "/answer"
+ form := url.Values{"revision": {"1"}, "behavior": {"deny"}}
+ for _, key := range []string{"actor", "answered_by", "task_id", "permission_id", "tools", "fence"} {
+ form.Set(key, "forged")
+ res := clientPost(t, c, path, testOrigin, form)
+ res.Body.Close()
+ if res.StatusCode != 422 {
+ t.Fatal("browser authority injected", key, res.StatusCode)
+ }
+ form.Del(key)
+ }
+ res := clientPost(t, c, path, "http://wrong.invalid", form)
+ res.Body.Close()
+ if res.StatusCode != 403 {
+ t.Fatal("CSRF bypass", res.StatusCode)
+ }
+ res = clientPost(t, c, strings.Replace(path, f.a.TaskID, "wrong-task", 1), testOrigin, form)
+ res.Body.Close()
+ if res.StatusCode != 403 {
+ t.Fatal("cross-task answer", res.StatusCode)
+ }
+ res = clientPost(t, c, path, testOrigin, form)
+ res.Body.Close()
+ if res.StatusCode != 303 {
+ t.Fatal("session answer rejected", res.StatusCode)
+ }
+ var who string
+ executionMust(t, f.d.Writer().QueryRow("SELECT answered_by FROM questions WHERE id=?", q.ID).Scan(&who))
+ if who != ownerAddress {
+ t.Fatal("actor not derived from session", who)
+ }
+}
+func TestQuestionCurrentOwnerAndPolling(t *testing.T) {
+ f, q := questionFixture(t)
+ mustSQL(t, f.d, "INSERT INTO members(address,role,active,revision,session_epoch) VALUES(?, 'owner', 1, 1, 0)", "owner2@example.com")
+ actor := equipo.Actor{Address: "owner2@example.com"}
+ executionMust(t, f.s.AnswerQuestion(connectionContext, actor, q.ID, 1, runnerproto.QuestionAnswer{Behavior: "deny"}))
+ r := f.request()
+ r.RequestID = "poll"
+ result, err := f.x.Mutate(connectionContext, f.principal, "answers", r)
+ executionMust(t, err)
+ if len(result.([]runnerproto.Question)) != 1 {
+ t.Fatal("owner answer unavailable")
+ }
+ mustSQL(t, f.d, "UPDATE members SET role='member' WHERE address=?", actor.Address)
+ if _, err := f.x.Mutate(connectionContext, f.principal, "answers", r); err == nil {
+ t.Fatal("demoted answerer polled")
+ }
+ if _, err := f.x.Cleanup(connectionContext, f.claim.CleanupToken, "answers", r); err == nil {
+ t.Fatal("cleanup polled answers")
+ }
+ r.Handle.Fence++
+ if _, err := f.x.Mutate(connectionContext, f.principal, "answers", r); err == nil {
+ t.Fatal("wrong fence polled")
+ }
+}
+func TestQuestionRequestReplayAndSanitization(t *testing.T) {
+ f, q := questionFixture(t)
+ r := f.request()
+ r.Question = &q
+ _, err := f.x.Mutate(connectionContext, f.principal, "questions", r)
+ executionMust(t, err)
+ if scalar(t, f.d, "SELECT count(*) FROM questions") != 1 {
+ t.Fatal("question replay duplicated")
+ }
+ q.RawRequest = json.RawMessage(`{"id":"permission","kind":"question","input":"changed"}`)
+ if _, err := f.x.Mutate(connectionContext, f.principal, "questions", r); err == nil {
+ t.Fatal("changed question replay accepted")
+ }
+ r.RequestID = "new"
+ q.ID = "new"
+ q.PermissionID = "new"
+ q.RawRequest = json.RawMessage(`{"id":"new","kind":"question","api_token":"secret-sentinel","input":{"question":"Which?"}}`)
+ _, err = f.x.Mutate(connectionContext, f.principal, "questions", r)
+ executionMust(t, err)
+ var raw string
+ executionMust(t, f.d.Writer().QueryRow("SELECT raw_request FROM questions WHERE id='new'").Scan(&raw))
+ if strings.Contains(raw, "secret-sentinel") || !strings.Contains(raw, "Which?") {
+ t.Fatal("raw request sanitization", raw)
+ }
+ r.RequestID = "unsupported"
+ q.ID = "unsupported"
+ q.Kind = "future"
+ q.PermissionID = "future"
+ q.RawRequest = json.RawMessage(`{"id":"future","kind":"future"}`)
+ _, err = f.x.Mutate(connectionContext, f.principal, "questions", r)
+ executionMust(t, err)
+ if f.s.AnswerQuestion(connectionContext, ownerActor, q.ID, 1, runnerproto.QuestionAnswer{Behavior: "allow"}) == nil {
+ t.Fatal("unsupported shape approved")
+ }
+}
+
+func TestQuestionRequestIDDedup(t *testing.T) {
+ f, q := questionFixture(t)
+ q.ID = "second"
+ q.PermissionID = "second"
+ q.RawRequest = json.RawMessage(`{"id":"second","kind":"question"}`)
+ r := f.request()
+ r.Question = &q
+ if _, err := f.x.Mutate(connectionContext, f.principal, "questions", r); err == nil {
+ t.Fatal("request ID reused for different question")
+ }
+}
+
+func TestQuestionResolvedPermission(t *testing.T) {
+ f, q := questionFixture(t)
+ r := f.request()
+ r.RequestID = "resolved"
+ r.Question = &q
+ _, err := f.x.Mutate(connectionContext, f.principal, "question_resolved", r)
+ executionMust(t, err)
+ _, err = f.x.Mutate(connectionContext, f.principal, "question_resolved", r)
+ executionMust(t, err)
+ if f.s.AnswerQuestion(connectionContext, ownerActor, q.ID, 1, runnerproto.QuestionAnswer{Behavior: "deny"}) == nil {
+ t.Fatal("resolved permission answered")
+ }
+ if scalar(t, f.d, "SELECT count(*) FROM audit_events WHERE kind='question.resolve'") != 1 {
+ t.Fatal("resolution replay duplicated")
+ }
+}
+
+func TestQuestionAuthenticatedPoll(t *testing.T) {
+ f, q := questionFixture(t)
+ executionMust(t, f.s.AnswerQuestion(connectionContext, ownerActor, q.ID, 1, runnerproto.QuestionAnswer{Behavior: "deny"}))
+ token := runnerBearerFor(t, f)
+ r := f.request()
+ r.RequestID = "poll-http"
+ if status := runnerHTTP(t, f, "answers", token, r); status != 200 {
+ t.Fatal("authenticated poll rejected", status)
+ }
+ if status := runnerHTTP(t, f, "answers", "wrong", r); status != 403 {
+ t.Fatal("unauthenticated poll accepted", status)
+ }
+ r.Handle.Attempt++
+ if status := runnerHTTP(t, f, "answers", token, r); status != 403 {
+ t.Fatal("cross-attempt poll accepted", status)
+ }
+}
+
+func TestQuestionAnswererRoster(t *testing.T) {
+ f, q := questionFixture(t)
+ mustSQL(t, f.d, "INSERT INTO members(address,role,active,revision,session_epoch) VALUES('removed-owner@example.com','owner',0,1,0)")
+ if f.s.AnswerQuestion(connectionContext, equipo.Actor{Address: "removed-owner@example.com"}, q.ID, 1, runnerproto.QuestionAnswer{Behavior: "deny"}) == nil {
+ t.Fatal("removed current owner answered")
+ }
+}
+
+func TestQuestionValidatorRequired(t *testing.T) {
+ f, q := questionFixture(t)
+ r := f.request()
+ r.Question = &q
+ for _, v := range []equipo.RunnerValidators{{}, {Question: func(context.Context, equipo.Assignment, equipo.RunnerRequest) error { return equipo.ErrForbidden }}} {
+ f.x.SetRunnerValidators(v)
+ if _, err := f.x.Mutate(connectionContext, f.principal, "questions", r); err == nil {
+ t.Fatal("unvalidated question accepted")
+ }
+ }
+}
diff --git a/internal/runner/journal.go b/internal/runner/journal.go
index 5448af51..5985a72b 100644
--- a/internal/runner/journal.go
+++ b/internal/runner/journal.go
@@ -89,6 +89,8 @@ func OpenJournal(ctx context.Context, path string) (*Journal, error) {
_, err = db.ExecContext(ctx, `CREATE TABLE IF NOT EXISTS journal_events (ordinal INTEGER PRIMARY KEY AUTOINCREMENT, id TEXT UNIQUE NOT NULL, event_key TEXT UNIQUE NOT NULL, content_hash TEXT NOT NULL, body BLOB NOT NULL, size INTEGER NOT NULL, acked INTEGER NOT NULL DEFAULT 0);
CREATE INDEX IF NOT EXISTS journal_pending ON journal_events(acked,ordinal);
CREATE TABLE IF NOT EXISTS journal_aliases (id TEXT PRIMARY KEY, event_key TEXT NOT NULL);
+ CREATE TABLE IF NOT EXISTS journal_answers (answer_key TEXT PRIMARY KEY, content_hash TEXT NOT NULL, state TEXT NOT NULL);
+ CREATE TABLE IF NOT EXISTS journal_tools (request_key TEXT PRIMARY KEY, content_hash TEXT NOT NULL, body BLOB NOT NULL, acked INTEGER NOT NULL DEFAULT 0);
CREATE TABLE IF NOT EXISTS journal_intents (intent_key TEXT PRIMARY KEY, body BLOB NOT NULL);
CREATE TABLE IF NOT EXISTS journal_streams (stream TEXT PRIMARY KEY, epoch TEXT NOT NULL, sequence INTEGER NOT NULL, ready INTEGER NOT NULL);
CREATE TABLE IF NOT EXISTS journal_state (id INTEGER PRIMARY KEY, blocked INTEGER NOT NULL);
@@ -119,7 +121,7 @@ func (j *Journal) AdmissionAllowed(ctx context.Context) error {
}
var saved int
var size int64
- if err := j.db.QueryRowContext(ctx, "SELECT blocked,(SELECT COALESCE(SUM(size),0) FROM journal_events WHERE acked=0) FROM journal_state WHERE id=1").Scan(&saved, &size); err != nil || saved != 0 || size >= j.maxBytes {
+ if err := j.db.QueryRowContext(ctx, "SELECT blocked,((SELECT COALESCE(SUM(size),0) FROM journal_events WHERE acked=0)+(SELECT COALESCE(SUM(length(body)),0) FROM journal_tools WHERE acked=0)) FROM journal_state WHERE id=1").Scan(&saved, &size); err != nil || saved != 0 || size >= j.maxBytes {
return ErrJournal
}
return nil
@@ -171,7 +173,7 @@ func (j *Journal) append(ctx context.Context, e Event, hash string, body []byte)
}
var size int64
var blocked int
- if err = tx.QueryRowContext(ctx, "SELECT blocked,(SELECT COALESCE(SUM(size),0) FROM journal_events WHERE acked=0) FROM journal_state WHERE id=1").Scan(&blocked, &size); err != nil {
+ if err = tx.QueryRowContext(ctx, "SELECT blocked,((SELECT COALESCE(SUM(size),0) FROM journal_events WHERE acked=0)+(SELECT COALESCE(SUM(length(body)),0) FROM journal_tools WHERE acked=0)) FROM journal_state WHERE id=1").Scan(&blocked, &size); err != nil {
return err
}
if blocked != 0 || size < 0 || int64(len(body)) > j.maxBytes-size {
diff --git a/internal/runner/questions.go b/internal/runner/questions.go
new file mode 100644
index 00000000..340bc6c8
--- /dev/null
+++ b/internal/runner/questions.go
@@ -0,0 +1,198 @@
+package runner
+
+import (
+ "amadan.net/oficina/equipo/internal/runner/paseo"
+ "amadan.net/oficina/equipo/internal/runnerproto"
+ "context"
+ "database/sql"
+ "encoding/json"
+ "errors"
+ "time"
+)
+
+type QuestionClient interface {
+ Respond(context.Context, paseo.Agent, paseo.PermissionResponse) error
+ Send(context.Context, paseo.Agent, string, string) error
+}
+
+func DeliverAnswer(ctx context.Context, client QuestionClient, agent paseo.Agent, q runnerproto.Question, answer runnerproto.QuestionAnswer) error {
+ if client == nil || q.Validate() != nil || q.ValidateAnswer(answer) != nil || agent.ServerID != q.ServerID || agent.AgentID != q.AgentID || agent.ProviderSessionID != q.SessionID || (!q.ExpiresAt.IsZero() && !time.Now().Before(q.ExpiresAt)) {
+ return runnerproto.ErrInvalid
+ }
+ return client.Respond(ctx, agent, paseo.PermissionResponse{RequestID: q.PermissionID, Behavior: answer.Behavior, UpdatedInput: answer.UpdatedInput})
+}
+func SendFollowup(ctx context.Context, client QuestionClient, agent paseo.Agent, message, id string, admit func(context.Context, string) error) error {
+ if client == nil || admit == nil || message == "" || id == "" {
+ return runnerproto.ErrInvalid
+ }
+ if err := admit(ctx, id); err != nil {
+ return err
+ }
+ return client.Send(ctx, agent, message, id)
+}
+
+// QuestionFromEvent preserves the provider request, after bounded sanitization.
+// Unknown request kinds stay pending; they cannot pass QuestionAnswer.Validate.
+func QuestionFromEvent(e paseo.Event, id, task string, secrets []string) (runnerproto.Question, error) {
+ var envelope struct {
+ Request json.RawMessage `json:"request"`
+ Event struct {
+ Request json.RawMessage `json:"request"`
+ } `json:"event"`
+ }
+ if len(e.Payload) > paseo.MaxEventBytes || json.Unmarshal(e.Payload, &envelope) != nil {
+ return runnerproto.Question{}, runnerproto.ErrInvalid
+ }
+ raw := envelope.Request
+ if len(raw) == 0 {
+ raw = envelope.Event.Request
+ }
+ var request struct {
+ ID string `json:"id"`
+ Kind string `json:"kind"`
+ }
+ if json.Unmarshal(raw, &request) != nil || request.ID != e.PermissionID {
+ return runnerproto.Question{}, runnerproto.ErrInvalid
+ }
+ q := runnerproto.Question{ID: id, TaskID: task, ServerID: e.ServerID, AgentID: e.AgentID, SessionID: e.ProviderSessionID, PermissionID: request.ID, Kind: request.Kind, Revision: 1, RawRequest: raw}
+ if err := q.Validate(); err != nil {
+ return runnerproto.Question{}, err
+ }
+ q.RawRequest = RedactJSON(raw, secrets)
+ return q, q.Validate()
+}
+
+// QuestionRelay records delivery intent before Respond. A lost reply remains
+// uncertain; it cannot trigger an automatic second response or a new turn.
+type QuestionRelay struct {
+ Journal *Journal
+ Client QuestionClient
+ Agent paseo.Agent
+ Current func(context.Context, runnerproto.Question) error
+}
+
+func (r *QuestionRelay) Deliver(ctx context.Context, q runnerproto.Question, answer runnerproto.QuestionAnswer) error {
+ if r.Journal == nil || r.Client == nil || r.Current == nil || q.Attempt <= 0 || q.Fence <= 0 || q.ExpiresAt.IsZero() || q.Validate() != nil || q.ValidateAnswer(answer) != nil {
+ return runnerproto.ErrInvalid
+ }
+ if err := r.Current(ctx, q); err != nil {
+ return err
+ }
+ if !time.Now().Before(q.ExpiresAt) {
+ return runnerproto.ErrInvalid
+ }
+ key := runnerproto.EventHash([]any{q.TaskID, q.Attempt, q.Fence, q.ServerID, q.AgentID, q.SessionID, q.PermissionID})
+ hash := runnerproto.EventHash([]any{q.ID, q.Revision, q.RawRequest, answer})
+ if err := r.Journal.AdmissionAllowed(ctx); err != nil {
+ return err
+ }
+ tx, err := r.Journal.db.BeginTx(ctx, nil)
+ if err != nil {
+ return r.Journal.fail()
+ }
+ defer tx.Rollback()
+ var old, state string
+ err = tx.QueryRowContext(ctx, "SELECT content_hash,state FROM journal_answers WHERE answer_key=?", key).Scan(&old, &state)
+ if err == nil {
+ if old != hash {
+ return runnerproto.ErrInvalid
+ }
+ if state == "delivered" {
+ return nil
+ }
+ return paseo.ErrUncertain
+ }
+ if !errors.Is(err, sql.ErrNoRows) {
+ tx.Rollback()
+ return r.Journal.fail()
+ }
+ if err = r.journalAdmissionTx(ctx, tx); err != nil {
+ return err
+ }
+ if _, err = tx.ExecContext(ctx, "INSERT INTO journal_answers VALUES(?,?,'pending')", key, hash); err != nil {
+ tx.Rollback()
+ return r.Journal.fail()
+ }
+ if err = tx.Commit(); err != nil {
+ return r.Journal.fail()
+ }
+ if err = r.Current(ctx, q); err != nil {
+ return err
+ }
+ if err = DeliverAnswer(ctx, r.Client, r.Agent, q, answer); err != nil {
+ return err
+ }
+ if _, err = r.Journal.db.ExecContext(ctx, "UPDATE journal_answers SET state='delivered' WHERE answer_key=?", key); err != nil {
+ return r.Journal.fail()
+ }
+ return nil
+}
+func (r *QuestionRelay) journalAdmissionTx(ctx context.Context, tx *sql.Tx) error {
+ var blocked int
+ if err := tx.QueryRowContext(ctx, "SELECT blocked FROM journal_state WHERE id=1").Scan(&blocked); err != nil || blocked != 0 {
+ return ErrJournal
+ }
+ return nil
+}
+
+// Wait releases and contains expired, cancelled or invalidated waits through
+// the supervisor. The poll callback is the authenticated instance answer API.
+func (r *QuestionRelay) Wait(ctx context.Context, q runnerproto.Question, poll func(context.Context) (*runnerproto.QuestionAnswer, error), contain func(context.Context) error) error {
+ if poll == nil || contain == nil || r.Current == nil || q.ExpiresAt.IsZero() {
+ return runnerproto.ErrInvalid
+ }
+ stop := func(cause error) error {
+ cleanup, cancel := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second)
+ defer cancel()
+ invalidErr := r.Invalidate(cleanup, q)
+ if err := contain(cleanup); err != nil {
+ return err
+ }
+ if invalidErr != nil {
+ return invalidErr
+ }
+ return cause
+ }
+ ctx, cancel := context.WithDeadline(ctx, q.ExpiresAt)
+ defer cancel()
+ timer := time.NewTimer(time.Until(q.ExpiresAt))
+ defer timer.Stop()
+ tick := time.NewTicker(100 * time.Millisecond)
+ defer tick.Stop()
+ for {
+ if err := r.Current(ctx, q); err != nil {
+ return stop(err)
+ }
+ if !time.Now().Before(q.ExpiresAt) {
+ return stop(runnerproto.ErrInvalid)
+ }
+ answer, err := poll(ctx)
+ if err != nil {
+ return stop(err)
+ }
+ if answer != nil {
+ if err := r.Deliver(ctx, q, *answer); err != nil {
+ return stop(err)
+ }
+ return nil
+ }
+ select {
+ case <-ctx.Done():
+ return stop(ctx.Err())
+ case <-timer.C:
+ return stop(runnerproto.ErrInvalid)
+ case <-tick.C:
+ }
+ }
+}
+
+func (r *QuestionRelay) Invalidate(ctx context.Context, q runnerproto.Question) error {
+ if r.Journal == nil {
+ return runnerproto.ErrInvalid
+ }
+ key := runnerproto.EventHash([]any{q.TaskID, q.Attempt, q.Fence, q.ServerID, q.AgentID, q.SessionID, q.PermissionID})
+ if _, err := r.Journal.db.ExecContext(ctx, "INSERT INTO journal_answers VALUES(?,'','invalid') ON CONFLICT(answer_key) DO UPDATE SET state='invalid'", key); err != nil {
+ return r.Journal.fail()
+ }
+ return nil
+}
diff --git a/internal/runner/questions_test.go b/internal/runner/questions_test.go
new file mode 100644
index 00000000..8826d776
--- /dev/null
+++ b/internal/runner/questions_test.go
@@ -0,0 +1,215 @@
+package runner
+
+import (
+ "amadan.net/oficina/equipo/internal/runner/paseo"
+ "amadan.net/oficina/equipo/internal/runnerproto"
+ "context"
+ "encoding/json"
+ "path/filepath"
+ "strings"
+ "testing"
+ "time"
+)
+
+type answerClient struct {
+ responses []paseo.PermissionResponse
+ sends int
+}
+
+func (c *answerClient) Respond(_ context.Context, _ paseo.Agent, r paseo.PermissionResponse) error {
+ c.responses = append(c.responses, r)
+ return nil
+}
+func (c *answerClient) Send(_ context.Context, _ paseo.Agent, _, _ string) error {
+ c.sends++
+ return nil
+}
+func TestQuestionPermissionID(t *testing.T) {
+ a := paseo.Agent{ServerID: "server", AgentID: "agent", ProviderSessionID: "session"}
+ q := runnerproto.Question{ID: "q", TaskID: "task", ServerID: "server", AgentID: "agent", SessionID: "session", PermissionID: "original", Kind: "question", Revision: 1, RawRequest: json.RawMessage(`{"id":"original","kind":"question","provider":"claude","name":"AskUserQuestion","input":{"questions":[{"question":"Which?","header":"Which?"}]}}`)}
+ c := &answerClient{}
+ answer := runnerproto.QuestionAnswer{Behavior: "allow", UpdatedInput: json.RawMessage(`{"answers":{"Which?":"Yes"}}`)}
+ if err := DeliverAnswer(context.Background(), c, a, q, answer); err != nil {
+ t.Fatal(err)
+ }
+ if c.sends != 0 || len(c.responses) != 1 || c.responses[0].RequestID != "original" || string(c.responses[0].UpdatedInput) != string(answer.UpdatedInput) {
+ t.Fatal("answer must Respond with original ID and answers")
+ }
+ q.Kind = "unknown"
+ if DeliverAnswer(context.Background(), c, a, q, answer) == nil {
+ t.Fatal("unknown permission approved")
+ }
+ q.Kind = "permission"
+ if DeliverAnswer(context.Background(), c, a, q, answer) == nil {
+ t.Fatal("permission widened policy")
+ }
+ q.Kind = "question"
+ a.ProviderSessionID = "replacement"
+ if DeliverAnswer(context.Background(), c, a, q, answer) == nil {
+ t.Fatal("replaced session answered")
+ }
+}
+func TestQuestionFollowupAdmission(t *testing.T) {
+ c := &answerClient{}
+ a := paseo.Agent{AgentID: "agent"}
+ if SendFollowup(context.Background(), c, a, "hello", "turn", nil) == nil || c.sends != 0 {
+ t.Fatal("hidden turn without admission")
+ }
+ if SendFollowup(context.Background(), c, a, "hello", "denied", func(context.Context, string) error { return runnerproto.ErrInvalid }) == nil || c.sends != 0 {
+ t.Fatal("turn sent without budget admission")
+ }
+ if err := SendFollowup(context.Background(), c, a, "hello", "turn", func(context.Context, string) error { return nil }); err != nil || c.sends != 1 {
+ t.Fatal("admitted conversational followup did not Send", err)
+ }
+}
+
+func TestQuestionDeliveryReplay(t *testing.T) {
+ j, err := OpenJournal(context.Background(), filepath.Join(t.TempDir(), "private", "journal.db"))
+ mustJournal(t, err)
+ defer j.Close()
+ q := runnerproto.Question{ID: "q", TaskID: "task", ServerID: "server", AgentID: "agent", SessionID: "session", PermissionID: "original", Kind: "question", Attempt: 1, Fence: 1, Revision: 1, ExpiresAt: time.Now().Add(time.Minute), RawRequest: json.RawMessage(`{"id":"original","kind":"question","provider":"claude","name":"AskUserQuestion","input":{"questions":[{"question":"Which?"}]}}`)}
+ c := &answerClient{}
+ current := true
+ relay := QuestionRelay{Journal: j, Client: c, Agent: paseo.Agent{ServerID: "server", AgentID: "agent", ProviderSessionID: "session"}, Current: func(context.Context, runnerproto.Question) error {
+ if !current {
+ return runnerproto.ErrInvalid
+ }
+ return nil
+ }}
+ answer := runnerproto.QuestionAnswer{Behavior: "deny"}
+ mustJournal(t, relay.Deliver(context.Background(), q, answer))
+ mustJournal(t, relay.Deliver(context.Background(), q, answer))
+ if len(c.responses) != 1 {
+ t.Fatal("answer replay duplicated Respond")
+ }
+ answer = runnerproto.QuestionAnswer{Behavior: "allow", UpdatedInput: json.RawMessage(`{"answers":{"Which?":"yes"}}`)}
+ if relay.Deliver(context.Background(), q, answer) == nil {
+ t.Fatal("changed answer replay accepted")
+ }
+ changed := q
+ changed.RawRequest = json.RawMessage(`{"id":"original","kind":"question","title":"Changed request"}`)
+ if relay.Deliver(context.Background(), changed, runnerproto.QuestionAnswer{Behavior: "deny"}) == nil {
+ t.Fatal("changed permission request replay accepted")
+ }
+ current = false
+ if relay.Deliver(context.Background(), q, runnerproto.QuestionAnswer{Behavior: "deny"}) == nil {
+ t.Fatal("stale replay accepted")
+ }
+}
+func TestQuestionSanitizedFixtures(t *testing.T) {
+ for _, provider := range []string{"claude", "codex"} {
+ name := "AskUserQuestion"
+ if provider == "codex" {
+ name = "request_user_input"
+ }
+ payload := json.RawMessage(`{"request":{"id":"original","kind":"question","provider":"` + provider + `","name":"` + name + `","input":{"questions":[{"question":"Which?"}],"api_token":"secret-sentinel"}}}`)
+ q, err := QuestionFromEvent(paseo.Event{PermissionID: "original", ServerID: "server", AgentID: "agent", ProviderSessionID: "session", Payload: payload}, "q", "task", []string{"secret-sentinel"})
+ mustJournal(t, err)
+ if strings.Contains(string(q.RawRequest), "secret-sentinel") || !strings.Contains(string(q.RawRequest), "Which?") {
+ t.Fatal("sanitization lost request or leaked secret")
+ }
+ }
+ if _, err := QuestionFromEvent(paseo.Event{PermissionID: "id", Payload: json.RawMessage(`{"request":"unknown"}`)}, "q", "task", nil); err == nil {
+ t.Fatal("unsupported shape answered")
+ }
+}
+
+func TestQuestionExpiredWaitContains(t *testing.T) {
+ j, err := OpenJournal(context.Background(), filepath.Join(t.TempDir(), "private", "journal.db"))
+ mustJournal(t, err)
+ defer j.Close()
+ q := runnerproto.Question{ID: "q", TaskID: "task", ServerID: "server", AgentID: "agent", SessionID: "session", PermissionID: "p", Kind: "question", Attempt: 1, Fence: 1, Revision: 1, ExpiresAt: time.Now().Add(-time.Second), RawRequest: json.RawMessage(`{"id":"p","kind":"question"}`)}
+ c := &answerClient{}
+ r := QuestionRelay{Journal: j, Client: c, Agent: paseo.Agent{ServerID: "server", AgentID: "agent", ProviderSessionID: "session"}, Current: func(context.Context, runnerproto.Question) error { return nil }}
+ contained := 0
+ if r.Wait(context.Background(), q, func(context.Context) (*runnerproto.QuestionAnswer, error) {
+ t.Fatal("polled expired wait")
+ return nil, nil
+ }, func(context.Context) error { contained++; return nil }) == nil || contained != 1 {
+ t.Fatal("expired wait not contained")
+ }
+ q.ExpiresAt = time.Now().Add(time.Minute)
+ if r.Deliver(context.Background(), q, runnerproto.QuestionAnswer{Behavior: "deny"}) == nil || len(c.responses) != 0 {
+ t.Fatal("expired permission ID revived")
+ }
+}
+
+type uncertainAnswerClient struct{ answerClient }
+
+func (c *uncertainAnswerClient) Respond(ctx context.Context, a paseo.Agent, r paseo.PermissionResponse) error {
+ _ = c.answerClient.Respond(ctx, a, r)
+ return paseo.ErrUncertain
+}
+func TestQuestionUncertainDelivery(t *testing.T) {
+ path := filepath.Join(t.TempDir(), "private", "journal.db")
+ j, err := OpenJournal(context.Background(), path)
+ mustJournal(t, err)
+ q := runnerproto.Question{ID: "q", TaskID: "task", ServerID: "server", AgentID: "agent", SessionID: "session", PermissionID: "p", Kind: "question", Attempt: 1, Fence: 1, Revision: 1, ExpiresAt: time.Now().Add(time.Minute), RawRequest: json.RawMessage(`{"id":"p","kind":"question"}`)}
+ c := &uncertainAnswerClient{}
+ r := QuestionRelay{Journal: j, Client: c, Agent: paseo.Agent{ServerID: "server", AgentID: "agent", ProviderSessionID: "session"}, Current: func(context.Context, runnerproto.Question) error { return nil }}
+ if r.Deliver(context.Background(), q, runnerproto.QuestionAnswer{Behavior: "deny"}) == nil {
+ t.Fatal("lost response treated as delivered")
+ }
+ mustJournal(t, j.Close())
+ j, err = OpenJournal(context.Background(), path)
+ mustJournal(t, err)
+ defer j.Close()
+ r.Journal = j
+ if r.Deliver(context.Background(), q, runnerproto.QuestionAnswer{Behavior: "deny"}) == nil || len(c.responses) != 1 {
+ t.Fatal("uncertain response resent after restart")
+ }
+}
+
+func TestQuestionAnswerFormats(t *testing.T) {
+ a := runnerproto.QuestionAnswer{Behavior: "allow", UpdatedInput: json.RawMessage(`{"answers":{"Which?":"yes"}}`)}
+ q := runnerproto.Question{RawRequest: json.RawMessage(`{"provider":"claude","name":"AskUserQuestion","input":{"questions":[{"question":"Which?","header":"Header"}]}}`), Kind: "question"}
+ mustJournal(t, q.ValidateAnswer(a))
+ for _, raw := range []string{`{"answers":{"unasked":"yes"}}`, `{"answers":{"Which?":"yes"},"permissions":["all"]}`, `{"answers":{"Which?":[]}}`, `{"answers":{"Which?":""}}`, `{"answers":{"Which?":"yes","Which?":"no"}}`} {
+ bad := a
+ bad.UpdatedInput = json.RawMessage(raw)
+ if q.ValidateAnswer(bad) == nil {
+ t.Fatal("unsupported answers accepted", raw)
+ }
+ }
+ q.RawRequest = json.RawMessage(`{"provider":"codex","name":"request_user_input","input":{"questions":[{"question":"Question text","header":"Which?"}]}}`)
+ mustJournal(t, q.ValidateAnswer(a))
+ q.RawRequest = json.RawMessage(`{"provider":"future","name":"AskUserQuestion","input":{"questions":[{"question":"Which?"}]}}`)
+ if q.ValidateAnswer(a) == nil {
+ t.Fatal("unknown provider shape approved")
+ }
+ for _, kind := range []string{"tool", "plan", "mode", "other"} {
+ if a.Validate(kind) == nil {
+ t.Fatal("permission policy widened", kind)
+ }
+ mustJournal(t, (runnerproto.QuestionAnswer{Behavior: "deny"}).Validate(kind))
+ }
+}
+
+func TestQuestionRejectsMalformedBeforeSanitizing(t *testing.T) {
+ e := paseo.Event{PermissionID: "p", ServerID: "server", AgentID: "agent", ProviderSessionID: "session", Payload: json.RawMessage(`{"request":{"id":"p","kind":"unknown","kind":"question"}}`)}
+ if _, err := QuestionFromEvent(e, "q", "task", nil); err == nil {
+ t.Fatal("sanitization hid malformed permission")
+ }
+}
+
+func TestQuestionDeliveryBindingAndExpiry(t *testing.T) {
+ q := runnerproto.Question{ID: "q", TaskID: "task", ServerID: "server", AgentID: "agent", SessionID: "session", PermissionID: "p", Kind: "question", RawRequest: json.RawMessage(`{"id":"p","kind":"question"}`)}
+ a := paseo.Agent{ServerID: "server", AgentID: "agent", ProviderSessionID: "session"}
+ answer := runnerproto.QuestionAnswer{Behavior: "deny"}
+ for _, field := range []string{"server", "agent", "session", "expiry"} {
+ bad := q
+ switch field {
+ case "server":
+ bad.ServerID = "other"
+ case "agent":
+ bad.AgentID = "other"
+ case "session":
+ bad.SessionID = "other"
+ case "expiry":
+ bad.ExpiresAt = time.Now().Add(-time.Second)
+ }
+ if DeliverAnswer(context.Background(), &answerClient{}, a, bad, answer) == nil {
+ t.Fatal("answer binding accepted", field)
+ }
+ }
+}
diff --git a/internal/runner/tool_journal.go b/internal/runner/tool_journal.go
new file mode 100644
index 00000000..1d90be77
--- /dev/null
+++ b/internal/runner/tool_journal.go
@@ -0,0 +1,97 @@
+package runner
+
+import (
+ "amadan.net/oficina/equipo/internal/equipo/team"
+ "amadan.net/oficina/equipo/internal/runner/paseo"
+ "amadan.net/oficina/equipo/internal/runnerproto"
+ "context"
+ "database/sql"
+ "encoding/json"
+ "errors"
+)
+
+type ToolSubmission struct {
+ InstanceID string `json:"instance_id"`
+ TaskID string `json:"task_id"`
+ Attempt int64 `json:"attempt"`
+ Fence int64 `json:"fence"`
+ RequestID string `json:"request_id"`
+ Name string `json:"name"`
+ Arguments json.RawMessage `json:"arguments"`
+ Agent paseo.Agent `json:"agent"`
+ Isolation team.IsolationSnapshot `json:"isolation"`
+}
+
+func (j *Journal) appendTool(ctx context.Context, v ToolSubmission, inputHash string) error {
+ tx, err := j.db.BeginTx(ctx, nil)
+ if err != nil {
+ return j.fail()
+ }
+ defer tx.Rollback()
+ key := runnerproto.EventHash([]any{v.InstanceID, v.TaskID, v.Attempt, v.Fence, v.RequestID})
+ hash := runnerproto.EventHash([]any{v.Name, inputHash, v.Agent})
+ var old string
+ err = tx.QueryRowContext(ctx, "SELECT content_hash FROM journal_tools WHERE request_key=?", key).Scan(&old)
+ if err == nil {
+ if old != hash {
+ return runnerproto.ErrInvalid
+ }
+ return nil
+ }
+ if !errors.Is(err, sql.ErrNoRows) {
+ tx.Rollback()
+ return j.fail()
+ }
+ raw, err := json.Marshal(v)
+ if err != nil {
+ return runnerproto.ErrInvalid
+ }
+ var size int64
+ if err = tx.QueryRowContext(ctx, "SELECT (SELECT COALESCE(SUM(length(body)),0) FROM journal_tools WHERE acked=0)+(SELECT COALESCE(SUM(size),0) FROM journal_events WHERE acked=0)").Scan(&size); err != nil {
+ tx.Rollback()
+ return j.fail()
+ }
+ if size+int64(len(raw)) > j.maxBytes {
+ tx.Rollback()
+ return j.fail()
+ }
+ if _, err = tx.ExecContext(ctx, "INSERT INTO journal_tools(request_key,content_hash,body,acked) VALUES(?,?,?,0)", key, hash, raw); err != nil {
+ tx.Rollback()
+ return j.fail()
+ }
+ if err = tx.Commit(); err != nil {
+ return j.fail()
+ }
+ return nil
+}
+func (j *Journal) ToolSubmissions(ctx context.Context, limit int) ([]ToolSubmission, error) {
+ if limit < 1 || limit > 1024 {
+ return nil, runnerproto.ErrInvalid
+ }
+ rows, err := j.db.QueryContext(ctx, "SELECT body FROM journal_tools WHERE acked=0 ORDER BY rowid LIMIT ?", limit)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ out := []ToolSubmission{}
+ for rows.Next() {
+ var raw []byte
+ var v ToolSubmission
+ if err = rows.Scan(&raw); err != nil {
+ return nil, err
+ }
+ if err = json.Unmarshal(raw, &v); err != nil {
+ return nil, err
+ }
+ out = append(out, v)
+ }
+ return out, rows.Err()
+}
+func (j *Journal) AckTool(ctx context.Context, v ToolSubmission) error {
+ key := runnerproto.EventHash([]any{v.InstanceID, v.TaskID, v.Attempt, v.Fence, v.RequestID})
+ _, err := j.db.ExecContext(ctx, "UPDATE journal_tools SET acked=1 WHERE request_key=?", key)
+ if err != nil {
+ return j.fail()
+ }
+ return nil
+}
diff --git a/internal/runner/tool_socket.go b/internal/runner/tool_socket.go
new file mode 100644
index 00000000..217c4c04
--- /dev/null
+++ b/internal/runner/tool_socket.go
@@ -0,0 +1,399 @@
+package runner
+
+import (
+ "bufio"
+ "bytes"
+ "context"
+ "crypto/rand"
+ "crypto/subtle"
+ "encoding/json"
+ "io"
+ "net"
+ "os"
+ "path/filepath"
+ "slices"
+ "strings"
+ "sync"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/equipo/team"
+ "amadan.net/oficina/equipo/internal/runner/paseo"
+ "amadan.net/oficina/equipo/internal/runnerproto"
+ "golang.org/x/sys/unix"
+)
+
+const maxToolFrame = 64 << 10
+
+type ToolBinding struct {
+ ReadPolicy paseo.ReadPolicy
+ Copy ToolCopy
+ InstanceID, TaskID string
+ Attempt, Fence int64
+ Tools []string
+ LeaseDeadline time.Time
+ Agent paseo.Agent
+ Isolation team.IsolationSnapshot
+ Journal *Journal
+ // Current must revalidate the captured lease, fence, agent/session and trusted
+ // read policy. Failure permanently invalidates this socket, even if renewed.
+ Current func(context.Context) error
+}
+type toolCapability struct {
+ Copy ToolCopy `json:"copy"`
+ Secret string `json:"secret"`
+ InstanceID string `json:"instance_id"`
+ TaskID string `json:"task_id"`
+ Attempt int64 `json:"attempt"`
+ Fence int64 `json:"fence"`
+ Tools []string `json:"tools"`
+ ExpiresAt time.Time `json:"expires_at"`
+}
+type toolRequest struct {
+ Capability string `json:"capability"`
+ InstanceID string `json:"instance_id"`
+ TaskID string `json:"task_id"`
+ Attempt int64 `json:"attempt"`
+ Fence int64 `json:"fence"`
+ RequestID string `json:"request_id"`
+ Name string `json:"name"`
+ Arguments json.RawMessage `json:"arguments"`
+}
+type AttemptSocket struct {
+ SocketPath, CapabilityPath string
+ listener *net.UnixListener
+ binding ToolBinding
+ capability toolCapability
+ mu sync.Mutex
+ invalid bool
+ done chan struct{}
+ workers sync.WaitGroup
+}
+
+func NewAttemptSocket(ctx context.Context, stateDir string, b ToolBinding) (*AttemptSocket, error) {
+ if !filepath.IsAbs(stateDir) || filepath.Clean(stateDir) != stateDir {
+ return nil, runnerproto.ErrInvalid
+ }
+ // Check the longest resulting address before creating any filesystem entry.
+ root := filepath.Join(stateDir, "attempts")
+ dir := filepath.Join(root, rand.Text())
+ if len(filepath.Join(dir, "tool.sock")) > 107 {
+ return nil, runnerproto.ErrInvalid
+ }
+ f, err := openPrivateDir(stateDir)
+ if err != nil {
+ return nil, err
+ }
+ f.Close()
+ if err := os.Mkdir(root, 0700); err != nil && !os.IsExist(err) {
+ return nil, runnerproto.ErrInvalid
+ }
+ f, err = openPrivateDir(root)
+ if err != nil {
+ return nil, err
+ }
+ f.Close()
+ if err := os.Mkdir(dir, 0700); err != nil {
+ return nil, runnerproto.ErrInvalid
+ }
+ s, err := ServeAttemptSocket(ctx, filepath.Join(dir, "tool.sock"), b)
+ if err != nil {
+ _ = os.Remove(dir)
+ }
+ return s, err
+}
+func ServeAttemptSocket(ctx context.Context, path string, b ToolBinding) (*AttemptSocket, error) {
+ if len(path) > 107 || !filepath.IsAbs(path) || filepath.Clean(path) != path || b.Journal == nil || b.Current == nil || b.InstanceID == "" || b.TaskID == "" || b.Attempt <= 0 || b.Fence <= 0 || !time.Now().Before(b.LeaseDeadline) || b.Agent.ServerID == "" || b.Agent.AgentID == "" || b.Agent.ProviderSessionID == "" || len(b.Tools) == 0 || (b.Isolation.Status != "confined" && b.Isolation.Status != "unconfined") {
+ return nil, runnerproto.ErrInvalid
+ }
+ for _, name := range b.Tools {
+ if !slices.Contains([]string{"submit_reproduction", "submit_candidate", "submit_review", "ask_person"}, name) {
+ return nil, runnerproto.ErrInvalid
+ }
+ }
+ if b.Copy.Accepted == "" || b.Copy.Rejected == "" {
+ return nil, runnerproto.ErrInvalid
+ }
+ if b.Agent.Provider == "claude" {
+ denied := false
+ for _, p := range b.ReadPolicy.DeniedPaths {
+ if filepath.IsAbs(p) && filepath.Clean(p) == p && (filepath.Dir(path) == p || strings.HasPrefix(filepath.Dir(path), p+string(filepath.Separator))) {
+ denied = true
+ }
+ }
+ if !denied || b.Isolation.Status != "confined" {
+ return nil, paseo.ErrIsolation
+ }
+ } else if b.Agent.Provider != "codex" || b.Isolation.Status != "unconfined" {
+ return nil, paseo.ErrIsolation
+ }
+ if err := b.Current(ctx); err != nil {
+ return nil, err
+ }
+ if err := b.Journal.AdmissionAllowed(ctx); err != nil {
+ return nil, err
+ }
+ parent, err := openPrivateDir(filepath.Dir(path))
+ if err != nil {
+ return nil, err
+ }
+ defer parent.Close()
+ b.Tools = slices.Clone(b.Tools)
+ s := &AttemptSocket{SocketPath: path, CapabilityPath: filepath.Join(filepath.Dir(path), "capability.json"), binding: b, done: make(chan struct{})}
+ s.capability = toolCapability{Copy: b.Copy, Secret: rand.Text() + rand.Text(), InstanceID: b.InstanceID, TaskID: b.TaskID, Attempt: b.Attempt, Fence: b.Fence, Tools: b.Tools, ExpiresAt: b.LeaseDeadline}
+ // Never overwrite an old socket or capability: restart needs a fresh directory.
+ if _, err := os.Lstat(path); !os.IsNotExist(err) {
+ return nil, runnerproto.ErrInvalid
+ }
+ if _, err := os.Lstat(s.CapabilityPath); !os.IsNotExist(err) {
+ return nil, runnerproto.ErrInvalid
+ }
+ listener, err := net.ListenUnix("unix", &net.UnixAddr{Name: path, Net: "unix"})
+ if err != nil {
+ return nil, runnerproto.ErrInvalid
+ }
+ listener.SetUnlinkOnClose(false)
+ s.listener = listener
+ fail := func() (*AttemptSocket, error) { listener.Close(); os.Remove(path); return nil, runnerproto.ErrInvalid }
+ if err := os.Chmod(path, 0600); err != nil {
+ return fail()
+ }
+ temp, err := os.CreateTemp(filepath.Dir(path), ".capability-")
+ if err != nil {
+ return fail()
+ }
+ tempPath := temp.Name()
+ defer os.Remove(tempPath)
+ raw, _ := json.Marshal(s.capability)
+ if _, err = temp.Write(raw); err != nil {
+ temp.Close()
+ return fail()
+ }
+ if err = temp.Sync(); err != nil {
+ temp.Close()
+ return fail()
+ }
+ if err = temp.Close(); err != nil {
+ return fail()
+ }
+ // Link publishes a complete 0600 file atomically without replacing a name.
+ if err = os.Link(tempPath, s.CapabilityPath); err != nil {
+ return fail()
+ }
+ if err = parent.Sync(); err != nil {
+ os.Remove(s.CapabilityPath)
+ return fail()
+ }
+ s.workers.Add(2)
+ go s.accept(ctx)
+ go func() {
+ defer s.workers.Done()
+ timer := time.NewTimer(time.Until(b.LeaseDeadline))
+ defer timer.Stop()
+ select {
+ case <-ctx.Done():
+ s.Invalidate()
+ case <-timer.C:
+ s.Invalidate()
+ case <-s.done:
+ }
+ }()
+ return s, nil
+}
+func (s *AttemptSocket) Invalidate() { s.mu.Lock(); defer s.mu.Unlock(); s.invalidateLocked() }
+func (s *AttemptSocket) invalidateLocked() {
+ if !s.invalid {
+ s.invalid = true
+ close(s.done)
+ s.listener.Close()
+ }
+}
+
+// Cleanup removes authority files only after the trusted supervisor proves containment.
+func (s *AttemptSocket) Cleanup(ctx context.Context, contained func(context.Context) error) error {
+ s.Invalidate()
+ if contained == nil {
+ return runnerproto.ErrInvalid
+ }
+ if err := contained(ctx); err != nil {
+ return err
+ }
+ s.workers.Wait()
+ for _, p := range []string{s.SocketPath, s.CapabilityPath} {
+ if err := os.Remove(p); err != nil && !os.IsNotExist(err) {
+ return err
+ }
+ }
+ return os.Remove(filepath.Dir(s.SocketPath))
+}
+func (s *AttemptSocket) accept(ctx context.Context) {
+ defer s.workers.Done()
+ for {
+ conn, err := s.listener.AcceptUnix()
+ if err != nil {
+ return
+ }
+ s.workers.Add(1)
+ go func() {
+ defer s.workers.Done()
+ defer conn.Close()
+ _ = conn.SetDeadline(time.Now().Add(2 * time.Second))
+ if !toolPeer(conn) {
+ return
+ }
+ raw, err := readToolFrame(bufio.NewReaderSize(conn, maxToolFrame+1))
+ if err != nil {
+ return
+ }
+ var q toolRequest
+ if runnerproto.DecodeLimit(bytes.NewReader(raw), &q, maxToolFrame) != nil {
+ return
+ }
+ err = s.submit(ctx, q)
+ _ = json.NewEncoder(conn).Encode(struct {
+ OK bool `json:"ok"`
+ }{err == nil})
+ }()
+ }
+}
+func toolPeer(c *net.UnixConn) bool {
+ raw, err := c.SyscallConn()
+ if err != nil {
+ return false
+ }
+ ok := false
+ if raw.Control(func(fd uintptr) {
+ cred, err := unix.GetsockoptUcred(int(fd), unix.SOL_SOCKET, unix.SO_PEERCRED)
+ ok = err == nil && toolOwner(cred.Uid)
+ }) != nil {
+ return false
+ }
+ return ok
+}
+func (s *AttemptSocket) submit(ctx context.Context, q toolRequest) error {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ b := s.binding
+ if s.invalid || !time.Now().Before(b.LeaseDeadline) {
+ s.invalidateLocked()
+ return runnerproto.ErrInvalid
+ }
+ if err := b.Current(ctx); err != nil {
+ s.invalidateLocked()
+ return err
+ }
+ if subtle.ConstantTimeCompare([]byte(q.Capability), []byte(s.capability.Secret)) != 1 || q.InstanceID != b.InstanceID || q.TaskID != b.TaskID || q.Attempt != b.Attempt || q.Fence != b.Fence || !slices.Contains(b.Tools, q.Name) || q.RequestID == "" || len(q.RequestID) > 256 {
+ return runnerproto.ErrInvalid
+ }
+ if err := validateToolArguments(q.Name, q.Arguments); err != nil {
+ return err
+ }
+ if err := b.Journal.AdmissionAllowed(ctx); err != nil {
+ s.invalidateLocked()
+ return err
+ }
+ value := ToolSubmission{InstanceID: b.InstanceID, TaskID: b.TaskID, Attempt: b.Attempt, Fence: b.Fence, RequestID: q.RequestID, Name: q.Name, Arguments: RedactJSON(q.Arguments, []string{s.capability.Secret}), Agent: b.Agent, Isolation: b.Isolation}
+ if err := b.Journal.appendTool(ctx, value, runnerproto.EventHash(json.RawMessage(q.Arguments))); err != nil {
+ return err
+ }
+ return nil
+}
+func readToolFrame(r *bufio.Reader) ([]byte, error) {
+ raw, err := r.ReadSlice('\n')
+ if err != nil || len(raw) > maxToolFrame {
+ return nil, runnerproto.ErrInvalid
+ }
+ return bytes.TrimSuffix(raw, []byte{'\n'}), nil
+}
+func callToolSocket(ctx context.Context, path string, q toolRequest) error {
+ conn, err := (&net.Dialer{Timeout: 2 * time.Second}).DialContext(ctx, "unix", path)
+ if err != nil {
+ return runnerproto.ErrInvalid
+ }
+ defer conn.Close()
+ _ = conn.SetDeadline(time.Now().Add(3 * time.Second))
+ raw, err := json.Marshal(q)
+ if err != nil || len(raw)+1 > maxToolFrame {
+ return runnerproto.ErrInvalid
+ }
+ if _, err = conn.Write(append(raw, '\n')); err != nil {
+ return runnerproto.ErrInvalid
+ }
+ raw, err = readToolFrame(bufio.NewReaderSize(conn, maxToolFrame+1))
+ if err != nil {
+ return err
+ }
+ var reply struct {
+ OK bool `json:"ok"`
+ }
+ if runnerproto.DecodeLimit(bytes.NewReader(raw), &reply, 1024) != nil || !reply.OK {
+ return runnerproto.ErrInvalid
+ }
+ return nil
+}
+
+// openNoLinks walks every component using directory-relative no-follow opens.
+func openNoLinks(path string, flags int) (*os.File, error) {
+ if !filepath.IsAbs(path) || filepath.Clean(path) != path {
+ return nil, runnerproto.ErrInvalid
+ }
+ fd, err := unix.Open("/", unix.O_PATH|unix.O_DIRECTORY|unix.O_CLOEXEC, 0)
+ if err != nil {
+ return nil, runnerproto.ErrInvalid
+ }
+ parts := strings.Split(strings.TrimPrefix(path, "/"), "/")
+ for i, p := range parts {
+ f := unix.O_PATH | unix.O_DIRECTORY
+ if i == len(parts)-1 {
+ f = flags
+ }
+ next, e := unix.Openat(fd, p, f|unix.O_NOFOLLOW|unix.O_CLOEXEC, 0)
+ unix.Close(fd)
+ if e != nil {
+ return nil, runnerproto.ErrInvalid
+ }
+ fd = next
+ }
+ return os.NewFile(uintptr(fd), path), nil
+}
+func privateInfo(f *os.File, mode os.FileMode, dir bool) bool {
+ var st unix.Stat_t
+ if unix.Fstat(int(f.Fd()), &st) != nil || !toolOwner(st.Uid) {
+ return false
+ }
+ info, err := f.Stat()
+ return err == nil && info.Mode().Perm() == mode && ((dir && info.IsDir()) || (!dir && info.Mode().IsRegular()))
+}
+func openPrivateDir(path string) (*os.File, error) {
+ f, err := openNoLinks(path, unix.O_RDONLY|unix.O_DIRECTORY)
+ if err != nil {
+ return nil, err
+ }
+ if !privateInfo(f, 0700, true) {
+ f.Close()
+ return nil, runnerproto.ErrInvalid
+ }
+ return f, nil
+}
+func readToolCapability(path string) (toolCapability, error) {
+ var cap toolCapability
+ f, err := openNoLinks(path, unix.O_RDONLY|unix.O_NONBLOCK)
+ if err != nil {
+ return cap, err
+ }
+ defer f.Close()
+ if !privateInfo(f, 0600, false) {
+ return cap, runnerproto.ErrInvalid
+ }
+ if runnerproto.DecodeLimit(io.LimitReader(f, 8193), &cap, 8192) != nil || len(cap.Secret) < 32 || !time.Now().Before(cap.ExpiresAt) {
+ return toolCapability{}, runnerproto.ErrInvalid
+ }
+ return cap, nil
+}
+func (s *AttemptSocket) MCPConfig(executable string) (paseo.MCPServer, error) {
+ if !filepath.IsAbs(executable) || filepath.Clean(executable) != executable {
+ return paseo.MCPServer{}, runnerproto.ErrInvalid
+ }
+ return paseo.MCPServer{Type: "stdio", Command: executable, Args: []string{"tool"}, Env: map[string]string{"EQUIPO_TOOL_SOCKET": s.SocketPath, "EQUIPO_TOOL_CAPABILITY_FILE": s.CapabilityPath, "EQUIPO_ATTEMPT": filepath.Base(filepath.Dir(s.SocketPath))}}, nil
+}
+
+func toolOwner(uid uint32) bool { return uid == uint32(os.Getuid()) }
diff --git a/internal/runner/tool_socket_test.go b/internal/runner/tool_socket_test.go
new file mode 100644
index 00000000..7f4162f2
--- /dev/null
+++ b/internal/runner/tool_socket_test.go
@@ -0,0 +1,281 @@
+package runner
+
+import (
+ "amadan.net/oficina/equipo/internal/equipo/team"
+ "amadan.net/oficina/equipo/internal/runner/paseo"
+ "amadan.net/oficina/equipo/internal/runnerproto"
+ "bufio"
+ "context"
+ "encoding/json"
+ "io"
+ "net"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+ "time"
+)
+
+func toolFixture(t *testing.T) (*AttemptSocket, ToolBinding) {
+ t.Helper()
+ root, err := os.MkdirTemp(os.Getenv("TMPDIR"), "e13-")
+ mustJournal(t, err)
+ t.Cleanup(func() { os.RemoveAll(root) })
+ j, err := OpenJournal(context.Background(), filepath.Join(root, "journal", "events.db"))
+ mustJournal(t, err)
+ t.Cleanup(func() { j.Close() })
+ b := ToolBinding{Copy: ToolCopy{Accepted: "accepted fixture", Rejected: "rejected fixture", Ask: "ask fixture", Candidate: "candidate fixture", Review: "review fixture", Reproduction: "reproduction fixture"}, InstanceID: "instance", TaskID: "task", Attempt: 1, Fence: 1, Tools: []string{"ask_person", "submit_candidate"}, LeaseDeadline: time.Now().Add(time.Minute), Agent: paseo.Agent{Provider: "codex", ServerID: "server", AgentID: "agent", ProviderSessionID: "session"}, Isolation: team.IsolationSnapshot{Status: "unconfined", RunnerTainted: true}, Journal: j, Current: func(context.Context) error { return nil }}
+ s, err := NewAttemptSocket(context.Background(), root, b)
+ mustJournal(t, err)
+ t.Cleanup(func() { s.Cleanup(context.Background(), func(context.Context) error { return nil }) })
+ return s, b
+}
+func TestAgentToolScope(t *testing.T) {
+ s, b := toolFixture(t)
+ cap, err := readToolCapability(s.CapabilityPath)
+ mustJournal(t, err)
+ q := toolRequest{Capability: cap.Secret, InstanceID: b.InstanceID, TaskID: b.TaskID, Attempt: 1, Fence: 1, RequestID: "request", Name: "ask_person", Arguments: json.RawMessage(`{"question":"Which colour?"}`)}
+ if err := callToolSocket(context.Background(), s.SocketPath, q); err != nil {
+ t.Fatal(err)
+ }
+ if err := callToolSocket(context.Background(), s.SocketPath, q); err != nil {
+ t.Fatal("exact replay", err)
+ }
+ rows, err := b.Journal.ToolSubmissions(context.Background(), 10)
+ mustJournal(t, err)
+ if len(rows) != 1 || rows[0].Agent.ProviderSessionID != "session" || !rows[0].Isolation.RunnerTainted {
+ t.Fatal("missing durable scoped provenance", rows)
+ }
+ for _, field := range []string{"capability", "task", "instance", "attempt", "fence", "name", "payload", "injection", "request_id"} {
+ t.Run(field, func(t *testing.T) {
+ bad := q
+ switch field {
+ case "request_id":
+ bad.RequestID = ""
+ case "capability":
+ bad.Capability = "wrong"
+ case "task":
+ bad.TaskID = "other"
+ case "instance":
+ bad.InstanceID = "other"
+ case "attempt":
+ bad.Attempt++
+ case "fence":
+ bad.Fence++
+ case "name":
+ bad.Name = "publish"
+ case "payload":
+ bad.Arguments = json.RawMessage(`{"question":"Changed"}`)
+ case "injection":
+ bad.RequestID = "new"
+ bad.Arguments = json.RawMessage(`{"question":"hi","tools":["publish"]}`)
+ }
+ if callToolSocket(context.Background(), s.SocketPath, bad) == nil {
+ t.Fatal("scope guard accepted", field)
+ }
+ })
+ }
+}
+func TestToolSocketIsolation(t *testing.T) {
+ s, _ := toolFixture(t)
+ for p, mode := range map[string]os.FileMode{filepath.Dir(s.SocketPath): 0700, s.SocketPath: 0600, s.CapabilityPath: 0600} {
+ i, err := os.Stat(p)
+ mustJournal(t, err)
+ if i.Mode().Perm() != mode {
+ t.Fatal("private mode", p, i.Mode())
+ }
+ }
+ link := filepath.Join(t.TempDir(), "link")
+ mustJournal(t, os.Symlink(s.CapabilityPath, link))
+ if _, err := readToolCapability(link); err == nil {
+ t.Fatal("symlink capability accepted")
+ }
+ mustJournal(t, os.Chmod(s.CapabilityPath, 0644))
+ if _, err := readToolCapability(s.CapabilityPath); err == nil {
+ t.Fatal("public capability accepted")
+ }
+ mustJournal(t, os.Chmod(s.CapabilityPath, 0600))
+ if _, err := readToolCapability(s.CapabilityPath + "missing"); err == nil {
+ t.Fatal("missing capability accepted")
+ }
+ if _, err := ServeAttemptSocket(context.Background(), "/"+strings.Repeat("x", 108), ToolBinding{}); err == nil {
+ t.Fatal("long socket accepted")
+ }
+ cap, err := readToolCapability(s.CapabilityPath)
+ mustJournal(t, err)
+ s.Invalidate()
+ if callToolSocket(context.Background(), s.SocketPath, toolRequest{Capability: cap.Secret}) == nil {
+ t.Fatal("invalidated socket accepted")
+ }
+}
+
+func TestToolSocketFramesAndLease(t *testing.T) {
+ s, b := toolFixture(t)
+ for _, raw := range []string{"{broken}\n", strings.Repeat("x", maxToolFrame+1) + "\n", `{"capability":"x","capability":"y"}` + "\n"} {
+ c, err := net.Dial("unix", s.SocketPath)
+ mustJournal(t, err)
+ c.SetDeadline(time.Now().Add(3 * time.Second))
+ _, _ = c.Write([]byte(raw))
+ data, _ := io.ReadAll(c)
+ c.Close()
+ if strings.Contains(string(data), `"ok":true`) {
+ t.Fatal("malformed frame accepted")
+ }
+ }
+ cap, err := readToolCapability(s.CapabilityPath)
+ mustJournal(t, err)
+ q := toolRequest{Capability: cap.Secret, InstanceID: b.InstanceID, TaskID: b.TaskID, Attempt: 1, Fence: 1, RequestID: "r", Name: "ask_person", Arguments: json.RawMessage(`{"question":"Hi?"}`)}
+ for _, name := range []string{"read_task", "publish", "attest_checks", "set_budget", "admit", "settle", "submit_review"} {
+ bad := q
+ bad.Name = name
+ if name == "submit_review" {
+ bad.Arguments = json.RawMessage(`{"candidate":"` + strings.Repeat("a", 40) + `","decision":"approve","findings":[]}`)
+ }
+ if callToolSocket(context.Background(), s.SocketPath, bad) == nil {
+ t.Fatal("unauthorized tool accepted", name)
+ }
+ }
+ s.mu.Lock()
+ s.binding.LeaseDeadline = time.Now().Add(-time.Second)
+ s.mu.Unlock()
+ if callToolSocket(context.Background(), s.SocketPath, q) == nil {
+ t.Fatal("expired lease accepted")
+ }
+ s.mu.Lock()
+ s.binding.LeaseDeadline = time.Now().Add(time.Minute)
+ s.mu.Unlock()
+ if callToolSocket(context.Background(), s.SocketPath, q) == nil {
+ t.Fatal("expired capability revived")
+ }
+}
+func TestToolSocketCurrentAuthority(t *testing.T) {
+ s, b := toolFixture(t)
+ cap, err := readToolCapability(s.CapabilityPath)
+ mustJournal(t, err)
+ q := toolRequest{Capability: cap.Secret, InstanceID: b.InstanceID, TaskID: b.TaskID, Attempt: 1, Fence: 1, RequestID: "r", Name: "ask_person", Arguments: json.RawMessage(`{"question":"Hi?"}`)}
+ s.mu.Lock()
+ s.binding.Current = func(context.Context) error { return runnerproto.ErrInvalid }
+ s.mu.Unlock()
+ if callToolSocket(context.Background(), s.SocketPath, q) == nil {
+ t.Fatal("changed fence authority accepted")
+ }
+ s.mu.Lock()
+ s.binding.Current = func(context.Context) error { return nil }
+ s.mu.Unlock()
+ if callToolSocket(context.Background(), s.SocketPath, q) == nil {
+ t.Fatal("old capability revived after authority change")
+ }
+ if err := s.Cleanup(context.Background(), func(context.Context) error { return runnerproto.ErrInvalid }); err == nil {
+ t.Fatal("unproved containment cleaned files")
+ }
+ if _, err := os.Stat(s.CapabilityPath); err != nil {
+ t.Fatal("removed before containment")
+ }
+}
+func TestAgentToolJournalReopen(t *testing.T) {
+ s, b := toolFixture(t)
+ cap, err := readToolCapability(s.CapabilityPath)
+ mustJournal(t, err)
+ q := toolRequest{Capability: cap.Secret, InstanceID: b.InstanceID, TaskID: b.TaskID, Attempt: 1, Fence: 1, RequestID: "r", Name: "submit_candidate", Arguments: json.RawMessage(`{"commit":"` + strings.Repeat("a", 40) + `"}`)}
+ mustJournal(t, callToolSocket(context.Background(), s.SocketPath, q))
+ s.Invalidate()
+ s.workers.Wait()
+ mustJournal(t, b.Journal.Close())
+ j, err := OpenJournal(context.Background(), b.Journal.path)
+ mustJournal(t, err)
+ defer j.Close()
+ rows, err := j.ToolSubmissions(context.Background(), 10)
+ mustJournal(t, err)
+ if len(rows) != 1 {
+ t.Fatal("ACK before durable request")
+ }
+ mustJournal(t, j.AckTool(context.Background(), rows[0]))
+ mustJournal(t, j.appendTool(context.Background(), rows[0], runnerproto.EventHash(json.RawMessage(q.Arguments))))
+ rows, err = j.ToolSubmissions(context.Background(), 10)
+ mustJournal(t, err)
+ if len(rows) != 0 {
+ t.Fatal("acked request replayed")
+ }
+}
+
+func TestToolSocketReadPolicyAndOwnership(t *testing.T) {
+ if !toolOwner(uint32(os.Getuid())) || toolOwner(uint32(os.Getuid()+1)) {
+ t.Fatal("peer UID alone must not cross users")
+ }
+ s, b := toolFixture(t)
+ b.Agent.Provider = "claude"
+ b.Isolation.Status = "confined"
+ root := filepath.Dir(filepath.Dir(filepath.Dir(s.SocketPath)))
+ if _, err := NewAttemptSocket(context.Background(), root, b); err == nil {
+ t.Fatal("Claude can read capability state")
+ }
+ b.ReadPolicy.DeniedPaths = []string{root}
+ second, err := NewAttemptSocket(context.Background(), root, b)
+ mustJournal(t, err)
+ mustJournal(t, second.Cleanup(context.Background(), func(context.Context) error { return nil }))
+ b.Agent.Provider = "codex"
+ if _, err := NewAttemptSocket(context.Background(), root, b); err == nil {
+ t.Fatal("false Codex confinement accepted")
+ }
+}
+
+func TestToolSocketCannotRecreateAuthority(t *testing.T) {
+ s, b := toolFixture(t)
+ if _, err := ServeAttemptSocket(context.Background(), s.SocketPath, b); err == nil {
+ t.Fatal("existing socket replaced")
+ }
+ link := filepath.Join(filepath.Dir(s.SocketPath), "link-dir")
+ mustJournal(t, os.Symlink(filepath.Dir(s.CapabilityPath), link))
+ if _, err := readToolCapability(filepath.Join(link, filepath.Base(s.CapabilityPath))); err == nil {
+ t.Fatal("symlink ancestor accepted")
+ }
+ mustJournal(t, os.Remove(link))
+ mustJournal(t, s.Cleanup(context.Background(), func(context.Context) error { return nil }))
+ if _, err := os.Stat(s.CapabilityPath); !os.IsNotExist(err) {
+ t.Fatal("capability remains after containment")
+ }
+ if callToolSocket(context.Background(), s.SocketPath, toolRequest{}) == nil {
+ t.Fatal("removed socket accepted")
+ }
+}
+
+func TestToolSocketFrameBoundary(t *testing.T) {
+ raw := strings.Repeat(" ", maxToolFrame) + "\n"
+ if _, err := readToolFrame(bufio.NewReaderSize(strings.NewReader(raw), len(raw)+1)); err == nil {
+ t.Fatal("oversized frame boundary accepted")
+ }
+}
+
+func TestToolSocketPublicStateAndStorageFailure(t *testing.T) {
+ s, b := toolFixture(t)
+ root := filepath.Dir(filepath.Dir(filepath.Dir(s.SocketPath)))
+ mustJournal(t, os.Chmod(root, 0755))
+ if _, err := NewAttemptSocket(context.Background(), root, b); err == nil {
+ t.Fatal("public state directory accepted")
+ }
+ mustJournal(t, os.Chmod(root, 0700))
+ cap, err := readToolCapability(s.CapabilityPath)
+ mustJournal(t, err)
+ b.Journal.maxBytes = 1
+ q := toolRequest{Capability: cap.Secret, InstanceID: cap.InstanceID, TaskID: cap.TaskID, Attempt: cap.Attempt, Fence: cap.Fence, RequestID: "r", Name: "ask_person", Arguments: json.RawMessage(`{"question":"Hi?"}`)}
+ if callToolSocket(context.Background(), s.SocketPath, q) == nil {
+ t.Fatal("ACK on exhausted journal")
+ }
+ rows, err := b.Journal.ToolSubmissions(context.Background(), 10)
+ mustJournal(t, err)
+ if len(rows) != 0 {
+ t.Fatal("overflow queued tool")
+ }
+}
+
+func TestToolSocketExpiredCapabilityFile(t *testing.T) {
+ s, _ := toolFixture(t)
+ cap, err := readToolCapability(s.CapabilityPath)
+ mustJournal(t, err)
+ cap.ExpiresAt = time.Now().Add(-time.Second)
+ raw, _ := json.Marshal(cap)
+ mustJournal(t, os.WriteFile(s.CapabilityPath, raw, 0600))
+ if _, err := readToolCapability(s.CapabilityPath); err == nil {
+ t.Fatal("expired capability file accepted")
+ }
+}
diff --git a/internal/runner/tools.go b/internal/runner/tools.go
new file mode 100644
index 00000000..f902a786
--- /dev/null
+++ b/internal/runner/tools.go
@@ -0,0 +1,237 @@
+package runner
+
+import (
+ "amadan.net/oficina/equipo/internal/runnerproto"
+ "bufio"
+ "bytes"
+ "context"
+ "encoding/hex"
+ "encoding/json"
+ "io"
+ "path/filepath"
+ "slices"
+ "strings"
+ "unicode/utf8"
+)
+
+type ToolCopy struct {
+ Accepted string `json:"accepted"`
+ Rejected string `json:"rejected"`
+ Ask string `json:"ask"`
+ Candidate string `json:"candidate"`
+ Review string `json:"review"`
+ Reproduction string `json:"reproduction"`
+}
+
+type CandidateSubmission struct {
+ Commit string `json:"commit"`
+}
+type ReviewSubmission struct {
+ Candidate string `json:"candidate"`
+ Decision string `json:"decision"`
+ Findings []string `json:"findings"`
+}
+type PersonQuestion struct {
+ Question string `json:"question"`
+}
+
+func validateToolArguments(name string, raw json.RawMessage) error {
+ decode := func(v any) error { return runnerproto.DecodeLimit(bytes.NewReader(raw), v, maxToolFrame) }
+ commit := func(v string) bool {
+ b, err := hex.DecodeString(v)
+ return err == nil && len(b) == 20 && strings.ToLower(v) == v
+ }
+ switch name {
+ case "ask_person":
+ var v PersonQuestion
+ if decode(&v) != nil || strings.TrimSpace(v.Question) == "" || len(v.Question) > 8192 || !utf8.ValidString(v.Question) {
+ return runnerproto.ErrInvalid
+ }
+ case "submit_candidate":
+ var v CandidateSubmission
+ if decode(&v) != nil || !commit(v.Commit) {
+ return runnerproto.ErrInvalid
+ }
+ case "submit_review":
+ var v ReviewSubmission
+ if decode(&v) != nil || !commit(v.Candidate) || !slices.Contains([]string{"approve", "changes_requested"}, v.Decision) || len(v.Findings) > 64 {
+ return runnerproto.ErrInvalid
+ }
+ for _, f := range v.Findings {
+ if len(f) > 4096 {
+ return runnerproto.ErrInvalid
+ }
+ }
+ case "submit_reproduction":
+ var v runnerproto.Reproduction
+ if decode(&v) != nil || strings.TrimSpace(v.ExpectedSymptom) == "" || len(v.ExpectedSymptom) > 8192 || len(v.Files) == 0 || len(v.Files) > 32 || len(v.TestNames) == 0 {
+ return runnerproto.ErrInvalid
+ }
+ seen := map[string]bool{}
+ for _, f := range v.Files {
+ if f.Path == "" || filepath.IsAbs(f.Path) || filepath.Clean(f.Path) != f.Path || strings.HasPrefix(f.Path, "../") || f.Path == ".." || strings.Contains(f.Path, "\\") || strings.HasPrefix(f.Path, ".git/") || f.Path == ".git" || seen[f.Path] || len(f.Bytes) == 0 {
+ return runnerproto.ErrInvalid
+ }
+ seen[f.Path] = true
+ }
+ default:
+ return runnerproto.ErrInvalid
+ }
+ return nil
+}
+
+type mcpRequest struct {
+ JSONRPC string `json:"jsonrpc"`
+ ID json.RawMessage `json:"id,omitempty"`
+ Method string `json:"method"`
+ Params json.RawMessage `json:"params,omitempty"`
+}
+type mcpResponse struct {
+ JSONRPC string `json:"jsonrpc"`
+ ID json.RawMessage `json:"id"`
+ Result any `json:"result,omitempty"`
+ Error any `json:"error,omitempty"`
+}
+
+func ServeTools(ctx context.Context, input io.Reader, output io.Writer, socketPath, capabilityPath string) error {
+ if !filepath.IsAbs(socketPath) || len(socketPath) > 107 || filepath.Dir(socketPath) != filepath.Dir(capabilityPath) {
+ return runnerproto.ErrInvalid
+ }
+ if _, err := readToolCapability(capabilityPath); err != nil {
+ return err
+ }
+ reader := bufio.NewReaderSize(input, maxToolFrame+1)
+ encoder := json.NewEncoder(output)
+ initialized := false
+ for {
+ // Peek distinguishes a clean stdio shutdown from an unterminated frame.
+ if _, err := reader.Peek(1); err == io.EOF {
+ return nil
+ } else if err != nil {
+ return runnerproto.ErrInvalid
+ }
+ raw, err := readToolFrame(reader)
+ if err != nil {
+ return err
+ }
+ var q mcpRequest
+ if runnerproto.DecodeLimit(bytes.NewReader(raw), &q, maxToolFrame) != nil || q.JSONRPC != "2.0" {
+ return runnerproto.ErrInvalid
+ }
+ if len(q.ID) == 0 {
+ if q.Method == "notifications/initialized" && initialized {
+ continue
+ }
+ return runnerproto.ErrInvalid
+ }
+ var id any
+ if json.Unmarshal(q.ID, &id) != nil {
+ return runnerproto.ErrInvalid
+ }
+ switch id.(type) {
+ case string, float64:
+ default:
+ return runnerproto.ErrInvalid
+ }
+ cap, err := readToolCapability(capabilityPath)
+ if err != nil {
+ return err
+ }
+ var result any
+ switch q.Method {
+ case "initialize":
+ var params struct {
+ ProtocolVersion string `json:"protocolVersion"`
+ Capabilities json.RawMessage `json:"capabilities"`
+ ClientInfo json.RawMessage `json:"clientInfo"`
+ }
+ if initialized || runnerproto.DecodeLimit(bytes.NewReader(q.Params), &params, maxToolFrame) != nil || params.ProtocolVersion == "" {
+ err = runnerproto.ErrInvalid
+ break
+ }
+ if !slices.Contains([]string{"2024-11-05", "2025-03-26", "2025-06-18"}, params.ProtocolVersion) {
+ params.ProtocolVersion = "2025-06-18"
+ }
+ initialized = true
+ result = map[string]any{"protocolVersion": params.ProtocolVersion, "capabilities": map[string]any{"tools": map[string]any{}}, "serverInfo": map[string]any{"name": "equipo-runner", "version": "1"}}
+ case "ping":
+ result = map[string]any{}
+ case "tools/list":
+ if !initialized {
+ err = runnerproto.ErrInvalid
+ break
+ }
+ result = map[string]any{"tools": toolSchemas(cap.Tools, cap.Copy)}
+ case "tools/call":
+ if !initialized {
+ err = runnerproto.ErrInvalid
+ break
+ }
+ var params struct {
+ Name string `json:"name"`
+ Arguments map[string]json.RawMessage `json:"arguments"`
+ }
+ if runnerproto.DecodeLimit(bytes.NewReader(q.Params), &params, maxToolFrame) != nil || !slices.Contains(cap.Tools, params.Name) {
+ err = runnerproto.ErrInvalid
+ break
+ }
+ var requestID string
+ if json.Unmarshal(params.Arguments["request_id"], &requestID) != nil || requestID == "" {
+ err = runnerproto.ErrInvalid
+ break
+ }
+ delete(params.Arguments, "request_id")
+ args, _ := json.Marshal(params.Arguments)
+ if err = validateToolArguments(params.Name, args); err != nil {
+ break
+ }
+ err = callToolSocket(ctx, socketPath, toolRequest{Capability: cap.Secret, InstanceID: cap.InstanceID, TaskID: cap.TaskID, Attempt: cap.Attempt, Fence: cap.Fence, RequestID: requestID, Name: params.Name, Arguments: args})
+ if err == nil {
+ result = map[string]any{"content": []any{map[string]string{"type": "text", "text": cap.Copy.Accepted}}}
+ }
+ default:
+ err = runnerproto.ErrInvalid
+ }
+ reply := mcpResponse{JSONRPC: "2.0", ID: q.ID, Result: result}
+ if err != nil {
+ reply.Result = nil
+ reply.Error = map[string]any{"code": -32602, "message": cap.Copy.Rejected}
+ }
+ if encoder.Encode(reply) != nil {
+ return runnerproto.ErrInvalid
+ }
+ }
+}
+func toolSchemas(names []string, copy ToolCopy) []any {
+ out := []any{}
+ for _, name := range names {
+ props := map[string]any{"request_id": map[string]any{"type": "string", "minLength": 1, "maxLength": 256}}
+ required := []string{"request_id"}
+ description := ""
+ field := func(key string, schema any) { props[key] = schema; required = append(required, key) }
+ text := map[string]any{"type": "string"}
+ commit := map[string]any{"type": "string", "pattern": "^[a-f0-9]{40}$"}
+ switch name {
+ case "ask_person":
+ description = copy.Ask
+ field("question", text)
+ case "submit_candidate":
+ description = copy.Candidate
+ field("commit", commit)
+ case "submit_review":
+ description = copy.Review
+ field("candidate", commit)
+ field("decision", map[string]any{"type": "string", "enum": []string{"approve", "changes_requested"}})
+ field("findings", map[string]any{"type": "array", "items": text})
+ case "submit_reproduction":
+ description = copy.Reproduction
+ field("expected_symptom", text)
+ field("files", map[string]any{"type": "array", "items": map[string]any{"type": "object", "properties": map[string]any{"path": text, "bytes": text}, "required": []string{"path", "bytes"}, "additionalProperties": false}})
+ field("test_names", map[string]any{"type": "array", "items": map[string]any{"type": "object", "properties": map[string]any{"package": text, "name": text}, "required": []string{"package", "name"}, "additionalProperties": false}})
+ default:
+ continue
+ }
+ out = append(out, map[string]any{"name": name, "description": description, "inputSchema": map[string]any{"type": "object", "properties": props, "required": required, "additionalProperties": false}})
+ }
+ return out
+}
diff --git a/internal/runner/tools_test.go b/internal/runner/tools_test.go
new file mode 100644
index 00000000..b95b0dcc
--- /dev/null
+++ b/internal/runner/tools_test.go
@@ -0,0 +1,101 @@
+package runner
+
+import (
+ "bufio"
+ "context"
+ "encoding/json"
+ "io"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "strings"
+ "testing"
+ "time"
+)
+
+func TestToolVerbUnderFakeHarness(t *testing.T) {
+ s, b := toolFixture(t)
+ binary := filepath.Join(t.TempDir(), "equipo-runner")
+ build := exec.Command("go", "build", "-o", binary, "../../cmd/equipo-runner")
+ build.Env = append(os.Environ(), "CGO_ENABLED=0")
+ if out, err := build.CombinedOutput(); err != nil {
+ t.Fatalf("tool binary: %v %s", err, out)
+ }
+ config, err := s.MCPConfig(binary)
+ mustJournal(t, err)
+ cap, err := readToolCapability(s.CapabilityPath)
+ mustJournal(t, err)
+ raw, _ := json.Marshal(config)
+ if strings.Contains(string(raw), cap.Secret) || config.Type != "stdio" || len(config.Args) != 1 || config.Args[0] != "tool" {
+ t.Fatal("unsafe creation config")
+ }
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ defer cancel()
+ cmd := exec.CommandContext(ctx, config.Command, config.Args...)
+ cmd.Env = []string{"PATH=/usr/bin:/bin"}
+ for k, v := range config.Env {
+ cmd.Env = append(cmd.Env, k+"="+v)
+ }
+ in, err := cmd.StdinPipe()
+ mustJournal(t, err)
+ out, err := cmd.StdoutPipe()
+ mustJournal(t, err)
+ var logs strings.Builder
+ cmd.Stderr = &logs
+ mustJournal(t, cmd.Start())
+ t.Cleanup(func() {
+ if cmd.ProcessState == nil {
+ cmd.Process.Kill()
+ cmd.Wait()
+ }
+ })
+ enc := json.NewEncoder(in)
+ scan := bufio.NewScanner(out)
+ rpc := func(id int, method string, params any) map[string]any {
+ t.Helper()
+ mustJournal(t, enc.Encode(map[string]any{"jsonrpc": "2.0", "id": id, "method": method, "params": params}))
+ if !scan.Scan() {
+ t.Fatal("no MCP reply", scan.Err())
+ }
+ var reply map[string]any
+ mustJournal(t, json.Unmarshal(scan.Bytes(), &reply))
+ if reply["error"] != nil {
+ t.Fatal("MCP error", reply)
+ }
+ return reply
+ }
+ rpc(1, "initialize", map[string]any{"protocolVersion": "2024-11-05", "capabilities": map[string]any{}, "clientInfo": map[string]any{"name": "fake", "version": "1"}})
+ mustJournal(t, enc.Encode(map[string]any{"jsonrpc": "2.0", "method": "notifications/initialized"}))
+ rpc(2, "tools/list", map[string]any{})
+ rpc(3, "tools/call", map[string]any{"name": "ask_person", "arguments": map[string]any{"request_id": "harness-1", "question": "Which colour?"}})
+ in.Close()
+ mustJournal(t, cmd.Wait())
+ if strings.Contains(logs.String(), cap.Secret) {
+ t.Fatal("capability logged")
+ }
+ rows, err := b.Journal.ToolSubmissions(context.Background(), 10)
+ mustJournal(t, err)
+ if len(rows) != 1 {
+ t.Fatal("harness submission count", len(rows))
+ }
+}
+
+func TestToolVerbFrames(t *testing.T) {
+ s, _ := toolFixture(t)
+ for _, raw := range []string{`{"jsonrpc":"2.0","id":1,"id":2,"method":"initialize"}` + "\n", strings.Repeat("x", maxToolFrame+1) + "\n", "{}", "broken\n"} {
+ var out strings.Builder
+ if ServeTools(context.Background(), strings.NewReader(raw), &out, s.SocketPath, s.CapabilityPath) == nil {
+ t.Fatal("malformed stdio accepted")
+ }
+ }
+ cap, err := readToolCapability(s.CapabilityPath)
+ mustJournal(t, err)
+ s.Invalidate()
+ q := toolRequest{Capability: cap.Secret, InstanceID: cap.InstanceID, TaskID: cap.TaskID, Attempt: cap.Attempt, Fence: cap.Fence, RequestID: "r", Name: "ask_person", Arguments: json.RawMessage(`{"question":"Hi?"}`)}
+ if callToolSocket(context.Background(), s.SocketPath, q) == nil {
+ t.Fatal("disconnected socket accepted")
+ }
+ if ServeTools(context.Background(), strings.NewReader(""), io.Discard, s.SocketPath, s.CapabilityPath+"missing") == nil {
+ t.Fatal("missing capability ignored")
+ }
+}
diff --git a/internal/runnerproto/questions.go b/internal/runnerproto/questions.go
new file mode 100644
index 00000000..31a4a4f6
--- /dev/null
+++ b/internal/runnerproto/questions.go
@@ -0,0 +1,118 @@
+package runnerproto
+
+import (
+ "bytes"
+ "encoding/json"
+ "slices"
+ "strings"
+ "time"
+)
+
+type Question struct {
+ ID string `json:"id"`
+ TaskID string `json:"task_id"`
+ AssignmentID string `json:"assignment_id"`
+ ServerID string `json:"server_id"`
+ AgentID string `json:"agent_id"`
+ SessionID string `json:"session_id"`
+ PermissionID string `json:"permission_id"`
+ Kind string `json:"kind"`
+ Attempt int64 `json:"attempt"`
+ Fence int64 `json:"fence"`
+ Revision int64 `json:"revision"`
+ RawRequest json.RawMessage `json:"raw_request"`
+ AnsweredBy string `json:"answered_by"`
+ Answer *QuestionAnswer `json:"answer,omitempty"`
+ ExpiresAt time.Time `json:"expires_at"`
+}
+type QuestionAnswer struct {
+ Behavior string `json:"behavior"`
+ UpdatedInput json.RawMessage `json:"updated_input,omitempty"`
+}
+
+func (q Question) Validate() error {
+ for _, v := range []string{q.ID, q.TaskID, q.ServerID, q.AgentID, q.SessionID, q.PermissionID, q.Kind} {
+ if v == "" || len(v) > 256 {
+ return ErrInvalid
+ }
+ }
+ var raw map[string]any
+ if DecodeLimit(bytes.NewReader(q.RawRequest), &raw, MaxEventBytes) != nil || raw == nil || raw["id"] != q.PermissionID || raw["kind"] != q.Kind {
+ return ErrInvalid
+ }
+ return nil
+}
+func (a QuestionAnswer) Validate(kind string) error {
+ if !slices.Contains([]string{"question", "tool", "plan", "mode", "other"}, kind) {
+ return ErrInvalid
+ }
+ if a.Behavior == "deny" && len(a.UpdatedInput) == 0 {
+ return nil
+ }
+ if kind != "question" || a.Behavior != "allow" {
+ return ErrInvalid
+ }
+ var updated struct {
+ Answers map[string]string `json:"answers"`
+ }
+ if DecodeLimit(bytes.NewReader(a.UpdatedInput), &updated, MaxEventBytes) != nil || len(updated.Answers) == 0 {
+ return ErrInvalid
+ }
+ for k, v := range updated.Answers {
+ if strings.TrimSpace(k) == "" || len(k) > 4096 || len(v) > 8192 {
+ return ErrInvalid
+ }
+ }
+ return nil
+}
+
+// ValidateAnswer permits only the pinned structured question adapters. Unknown
+// provider shapes can be retained without turning them into an approval.
+func (q Question) ValidateAnswer(a QuestionAnswer) error {
+ if a.Validate(q.Kind) != nil {
+ return ErrInvalid
+ }
+ if a.Behavior == "deny" {
+ return nil
+ }
+ var raw struct {
+ Provider string `json:"provider"`
+ Name string `json:"name"`
+ Input struct {
+ Questions []struct {
+ Question string `json:"question"`
+ Header string `json:"header"`
+ } `json:"questions"`
+ } `json:"input"`
+ }
+ if json.Unmarshal(q.RawRequest, &raw) != nil || len(raw.Input.Questions) == 0 {
+ return ErrInvalid
+ }
+ if (raw.Provider != "claude" || raw.Name != "AskUserQuestion") && (raw.Provider != "codex" || raw.Name != "request_user_input") {
+ return ErrInvalid
+ }
+ var input struct {
+ Answers map[string]string `json:"answers"`
+ }
+ _ = json.Unmarshal(a.UpdatedInput, &input)
+ keys := map[string]bool{}
+ for _, question := range raw.Input.Questions {
+ key := question.Question
+ if raw.Provider == "codex" {
+ key = question.Header
+ }
+ if key == "" || keys[key] {
+ return ErrInvalid
+ }
+ keys[key] = true
+ }
+ if len(input.Answers) != len(keys) {
+ return ErrInvalid
+ }
+ for k, v := range input.Answers {
+ if !keys[k] || strings.TrimSpace(v) == "" {
+ return ErrInvalid
+ }
+ }
+ return nil
+}
diff --git a/internal/runnerproto/types.go b/internal/runnerproto/types.go
index 389a48cf..51165efb 100644
--- a/internal/runnerproto/types.go
+++ b/internal/runnerproto/types.go
@@ -79,6 +79,7 @@ type PollRequest struct {
After string `json:"after"`
}
type RunnerRequest struct {
+ Question *Question `json:"question,omitempty"`
Version int `json:"version"`
AssignmentID string `json:"assignment_id"`
Scope team.Scope `json:"scope"`