package main import ( "crypto/rand" "encoding/hex" "encoding/json" "errors" "net/http" "time" ) // POST /proposals: the AI VM registers a layer-2 proposal (design 6.5). Response carries the approval token that the // Discord approval hands back; approved=true in the body records the approval directly (used by tests and by the AI VM // after the button round-trip). Execution then goes through /actions/execute with that token. type ProposalRequest struct { RunID *string `json:"run_id"` ScenarioID *string `json:"scenario_id"` ActionID string `json:"action_id"` Target map[string]any `json:"target"` Diagnosis map[string]any `json:"diagnosis"` Approved bool `json:"approved"` ApprovedBy string `json:"approved_by"` TTLSeconds int `json:"ttl_seconds"` } func (a *App) handleProposal(w http.ResponseWriter, r *http.Request) { var req ProposalRequest if err := json.NewDecoder(r.Body).Decode(&req); err != nil { writeErr(w, 400, err) return } if catalogEntry(req.ActionID) == nil { writeErr(w, 400, errors.New("action_id not in the catalogue")) return } if cur := a.runs.current(); cur != nil && req.RunID == nil { req.RunID = &cur.RunID if cur.ScenarioID != "" { req.ScenarioID = &cur.ScenarioID } } ttl := 15 * time.Minute // design 2.1: no approval within 15 minutes -> layer 3 if req.TTLSeconds > 0 { ttl = time.Duration(req.TTLSeconds) * time.Second } b := make([]byte, 24) _, _ = rand.Read(b) token := "apr-" + hex.EncodeToString(b) if err := a.store.InsertProposal(r.Context(), token, req.RunID, req.ScenarioID, req.ActionID, req.Target, ttl); err != nil { writeErr(w, 500, err) return } a.store.Event(r.Context(), req.RunID, req.ScenarioID, "proposal", "ai", map[string]any{"action_id": req.ActionID, "target": req.Target, "diagnosis": req.Diagnosis, "token_suffix": token[len(token)-6:]}) if req.Approved { by := req.ApprovedBy if by == "" { by = "unspecified" } _ = a.store.ApproveProposal(r.Context(), token, by) a.store.Event(r.Context(), req.RunID, req.ScenarioID, "approval", by, map[string]any{"action_id": req.ActionID, "token_suffix": token[len(token)-6:]}) } writeJSON(w, 201, map[string]any{"token": token, "expires_in_s": ttl.Seconds(), "approved": req.Approved}) } // POST /proposals/{token}/approve is not needed while the AI VM marks approval itself; kept out to keep the surface small.