CodeSampleX

Exemplo

google.golang.org/protobuf v1.36.11

Amostra verificada para golang google.golang.org/protobuf v1.36.11. O contrato rodou em go 1.26 · linux alpine/x64 · docker e passou.

sha256:b0be09da07a3a049c710fdb290e38652329a37c42c55cc8fbdd4bd611a449fcf

Esta rede oferece uma coisa: uma amostra que compila. Ela a executou em um sandbox e guardou o recibo assinado. Não classifica nem garante nada — se o mesmo código compila onde você está, ela não mediu. Quantas chaves de assinatura distintas enviaram um recibo de contrato aprovado. Uma é só o autor; mais de uma significa que outra pessoa também o compilou. Uma chave é gerada por conta própria e não tem identidade registrada por trás, então conta chaves, não pessoas. MIT-0

Evidência de execução

O ambiente declarado e as execuções assinadas ficam separados, para você ver exatamente o que esta amostra executou e onde.

Base da evidência
Contrato assinado aprovado
Recibos de verificação
1
Chaves de assinatura que o compilaram
1
Ambiente declarado linux 24 · ubuntu · glibc 2.39 x64 go

Ambientes das execuções de verificação

Ambiente Contrato Etapas Execução
go 1.26 · linux alpine/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · golang@1golang:1.26-alpine@sha256:28d89ee9cc0f…
2026-08-27

Caso

HOW
Objetivo
verify pkg:golang/google.golang.org/protobuf@v1.36.11
Pacotes
Criado
2026-08-27T20:11:04Z

Contrato

  1. proto.Marshal and proto.Unmarshal correctly round-trip protobuf messages
  2. proto.Equal and proto.Clone maintain message equality and deep-copy semantics
  3. proto.Merge merges populated fields from source message into destination
  4. protojson.Marshal and protojson.Unmarshal convert messages to and from valid JSON
  5. anypb.New and UnmarshalTo pack and unpack arbitrary protobuf messages
  6. structpb.NewStruct and AsMap convert between Go map structures and dynamic protobuf structs

Arquivos

  • PROMPT.md
  • csx.json
  • go.mod
  • go.sum
  • main.go
  • spec.json
  • test/contract.go

Baixar o artefato de código-fonte (tar.gz)

Código-fonte

PROMPT.md
Clean-room public code sample — generation instructions

Write a brand-new, minimal, self-contained code sample in this clean-room directory.
Do not copy, paraphrase, or reference any existing project source. Work only from this spec.

A csx.json manifest scaffold already exists. Do not recreate it from memory. Preserve its case.goal, packages and symbols; fill its empty case.contract with exact assertions and correct its environment, commands and verifierAdapter for the files you generate.

Goal: verify pkg:golang/google.golang.org/protobuf@v1.36.11
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:golang/google.golang.org/protobuf@v1.36.11
Constraints:
  - executionContext: node
Required runtime conditions:
  - ecosystem: npm
  - language: javascript
  - moduleSystem: cjs
  - packageManager: npm@10.9.8
  - runtime: node@22.23.2

Rules:
  - One focused purpose; the smallest project that proves the goal.
  - Include a contract test (test/contract.*) that runs OFFLINE and exits 0 exactly when the goal behavior works.
  - Pin every dependency with a lockfile so resolution is reproducible.
  - No secrets, credentials, or tokens. No real URLs (only example.com or localhost). No absolute paths.
  - No personal names, emails, company names, or project identifiers of any kind.
  - No binaries and no generated output (node_modules, dist, target, venv, .git, .env).
  - Keep it under 200 files and 256KB packed.
csx.json
{"case":{"caseId":"case:sha256:3c502179395e6ebb652d903e3fc4731d85b324204ab0f82de48bb8c9d7a3d207","contract":["proto.Marshal and proto.Unmarshal correctly round-trip protobuf messages","proto.Equal and proto.Clone maintain message equality and deep-copy semantics","proto.Merge merges populated fields from source message into destination","protojson.Marshal and protojson.Unmarshal convert messages to and from valid JSON","anypb.New and UnmarshalTo pack and unpack arbitrary protobuf messages","structpb.NewStruct and AsMap convert between Go map structures and dynamic protobuf structs"],"goal":"verify pkg:golang/google.golang.org/protobuf@v1.36.11","kind":"HOW","packages":["pkg:golang/google.golang.org/protobuf@v1.36.11"],"schemaVersion":1},"contractCommand":["go","run","./test"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"golang","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"go","schemaVersion":1},"license":"MIT-0","packages":["pkg:golang/google.golang.org/protobuf@v1.36.11"],"schemaVersion":1,"verifierAdapter":"golang@1"}
go.mod
module example.com/sample

go 1.23

require google.golang.org/protobuf v1.36.11
go.sum
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=
google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
main.go
package main

import (
	"fmt"
	"time"

	"google.golang.org/protobuf/encoding/protojson"
	"google.golang.org/protobuf/proto"
	"google.golang.org/protobuf/types/known/anypb"
	"google.golang.org/protobuf/types/known/structpb"
	"google.golang.org/protobuf/types/known/timestamppb"
)

// MetricRecord represents a structured telemetry event.
type MetricRecord struct {
	Timestamp *timestamppb.Timestamp
	Payload   *structpb.Struct
	Detail    *anypb.Any
}

// NewMetricRecord creates a new MetricRecord from standard Go types.
func NewMetricRecord(t time.Time, metadata map[string]any, detail proto.Message) (*MetricRecord, error) {
	st, err := structpb.NewStruct(metadata)
	if err != nil {
		return nil, fmt.Errorf("failed to create structpb: %w", err)
	}

	var anyDetail *anypb.Any
	if detail != nil {
		anyDetail, err = anypb.New(detail)
		if err != nil {
			return nil, fmt.Errorf("failed to create anypb: %w", err)
		}
	}

	return &MetricRecord{
		Timestamp: timestamppb.New(t),
		Payload:   st,
		Detail:    anyDetail,
	}, nil
}

// ToJSON serializes the metric payload into a JSON string using protojson.
func (m *MetricRecord) ToJSON() (string, error) {
	if m.Payload == nil {
		return "{}", nil
	}
	data, err := protojson.Marshal(m.Payload)
	if err != nil {
		return "", fmt.Errorf("protojson marshal failed: %w", err)
	}
	return string(data), nil
}

// CloneTimestamp creates a deep copy of the Timestamp message using proto.Clone.
func (m *MetricRecord) CloneTimestamp() *timestamppb.Timestamp {
	if m.Timestamp == nil {
		return nil
	}
	cloned := proto.Clone(m.Timestamp)
	return cloned.(*timestamppb.Timestamp)
}

func main() {
	now := time.Now()
	meta := map[string]any{
		"metric_name": "cpu_usage",
		"value":       float64(45.2),
		"active":      true,
	}

	record, err := NewMetricRecord(now, meta, timestamppb.New(now))
	if err != nil {
		fmt.Printf("Error creating metric record: %v\n", err)
		return
	}

	jsonStr, err := record.ToJSON()
	if err != nil {
		fmt.Printf("Error encoding to JSON: %v\n", err)
		return
	}

	fmt.Printf("Record created at %v with JSON payload: %s\n", record.Timestamp.AsTime(), jsonStr)

	clonedTs := record.CloneTimestamp()
	if proto.Equal(record.Timestamp, clonedTs) {
		fmt.Println("Timestamp successfully cloned and verified equal.")
	}
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:golang/google.golang.org/protobuf@v1.36.11",
  "kind": "HOW",
  "packages": [
    "pkg:golang/google.golang.org/protobuf@v1.36.11"
  ],
  "constraints": {
    "executionContext": "node"
  },
  "runtimeConditions": {
    "ecosystem": "npm",
    "language": "javascript",
    "moduleSystem": "cjs",
    "packageManager": "npm@10.9.8",
    "runtime": "node@22.23.2"
  }
}
test/contract.go
package main

import (
	"bytes"
	"fmt"
	"os"
	"reflect"
	"time"

	"google.golang.org/protobuf/encoding/protojson"
	"google.golang.org/protobuf/proto"
	"google.golang.org/protobuf/types/known/anypb"
	"google.golang.org/protobuf/types/known/durationpb"
	"google.golang.org/protobuf/types/known/structpb"
	"google.golang.org/protobuf/types/known/timestamppb"
)

func main() {
	// Assertion 1: proto.Marshal and proto.Unmarshal correctly round-trip protobuf messages
	{
		orig := timestamppb.New(time.Date(2026, 8, 19, 12, 30, 0, 500, time.UTC))
		data, err := proto.Marshal(orig)
		if err != nil {
			fmt.Fprintf(os.Stderr, "FAIL: proto.Marshal error: %v\n", err)
			os.Exit(1)
		}

		if len(data) == 0 {
			fmt.Fprintf(os.Stderr, "FAIL: proto.Marshal produced empty byte slice\n")
			os.Exit(1)
		}

		var decoded timestamppb.Timestamp
		if err := proto.Unmarshal(data, &decoded); err != nil {
			fmt.Fprintf(os.Stderr, "FAIL: proto.Unmarshal error: %v\n", err)
			os.Exit(1)
		}

		if !proto.Equal(orig, &decoded) {
			fmt.Fprintf(os.Stderr, "FAIL: unmarshaled message does not equal original\n")
			os.Exit(1)
		}

		if !decoded.AsTime().Equal(orig.AsTime()) {
			fmt.Fprintf(os.Stderr, "FAIL: decoded time %v does not match original %v\n", decoded.AsTime(), orig.AsTime())
			os.Exit(1)
		}
	}

	// Assertion 2: proto.Equal and proto.Clone maintain message equality and deep-copy semantics
	{
		orig := &durationpb.Duration{
			Seconds: 3600,
			Nanos:   500000,
		}

		cloned := proto.Clone(orig).(*durationpb.Duration)
		if !proto.Equal(orig, cloned) {
			fmt.Fprintf(os.Stderr, "FAIL: proto.Clone result is not equal to original\n")
			os.Exit(1)
		}

		// Mutating clone must not affect original
		cloned.Seconds = 7200
		if proto.Equal(orig, cloned) {
			fmt.Fprintf(os.Stderr, "FAIL: mutated clone should not be equal to original\n")
			os.Exit(1)
		}
		if orig.Seconds != 3600 {
			fmt.Fprintf(os.Stderr, "FAIL: modifying clone altered original message\n")
			os.Exit(1)
		}
	}

	// Assertion 3: proto.Merge merges populated fields from source message into destination
	{
		dst := &durationpb.Duration{
			Seconds: 100,
			Nanos:   0,
		}
		src := &durationpb.Duration{
			Seconds: 0,
			Nanos:   500,
		}
		proto.Merge(dst, src)
		if dst.Nanos != 500 {
			fmt.Fprintf(os.Stderr, "FAIL: proto.Merge did not update destination field\n")
			os.Exit(1)
		}
	}

	// Assertion 4: protojson.Marshal and protojson.Unmarshal convert messages to and from valid JSON
	{
		orig := timestamppb.New(time.Date(2026, 1, 15, 8, 0, 0, 0, time.UTC))
		jsonBytes, err := protojson.Marshal(orig)
		if err != nil {
			fmt.Fprintf(os.Stderr, "FAIL: protojson.Marshal error: %v\n", err)
			os.Exit(1)
		}

		if !bytes.Contains(jsonBytes, []byte("2026-01-15T08:00:00Z")) {
			fmt.Fprintf(os.Stderr, "FAIL: JSON output %s does not contain expected RFC3339 timestamp\n", string(jsonBytes))
			os.Exit(1)
		}

		var decoded timestamppb.Timestamp
		if err := protojson.Unmarshal(jsonBytes, &decoded); err != nil {
			fmt.Fprintf(os.Stderr, "FAIL: protojson.Unmarshal error: %v\n", err)
			os.Exit(1)
		}

		if !proto.Equal(orig, &decoded) {
			fmt.Fprintf(os.Stderr, "FAIL: protojson unmarshaled message does not equal original\n")
			os.Exit(1)
		}
	}

	// Assertion 5: anypb.New and UnmarshalTo pack and unpack arbitrary protobuf messages
	{
		inner := &durationpb.Duration{
			Seconds: 120,
			Nanos:   0,
		}

		anyMsg, err := anypb.New(inner)
		if err != nil {
			fmt.Fprintf(os.Stderr, "FAIL: anypb.New error: %v\n", err)
			os.Exit(1)
		}

		if !anyMsg.MessageIs(&durationpb.Duration{}) {
			fmt.Fprintf(os.Stderr, "FAIL: anyMsg.MessageIs returned false for Duration\n")
			os.Exit(1)
		}

		var unpacked durationpb.Duration
		if err := anyMsg.UnmarshalTo(&unpacked); err != nil {
			fmt.Fprintf(os.Stderr, "FAIL: anyMsg.UnmarshalTo error: %v\n", err)
			os.Exit(1)
		}

		if !proto.Equal(inner, &unpacked) {
			fmt.Fprintf(os.Stderr, "FAIL: unpacked any message does not match original\n")
			os.Exit(1)
		}
	}

	// Assertion 6: structpb.NewStruct and AsMap convert between Go map structures and dynamic protobuf structs
	{
		inputMap := map[string]any{
			"string_key": "sample_value",
			"number_key": float64(42),
			"bool_key":   true,
		}

		st, err := structpb.NewStruct(inputMap)
		if err != nil {
			fmt.Fprintf(os.Stderr, "FAIL: structpb.NewStruct error: %v\n", err)
			os.Exit(1)
		}

		outMap := st.AsMap()
		if !reflect.DeepEqual(inputMap, outMap) {
			fmt.Fprintf(os.Stderr, "FAIL: AsMap result %v does not match input %v\n", outMap, inputMap)
			os.Exit(1)
		}
	}

	fmt.Println("PASS: google.golang.org/protobuf contract passed")
}

Seeder de origem

anônimo