nutshell

package
v0.2.5 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 18, 2026 License: MIT Imports: 24 Imported by: 0

Documentation

Index

Constants

View Source
const (
	SpecVersion = "0.2.0"
	MagicBytes  = "NUT\x01"
)
View Source
const (
	DefaultClawNetAddr = "http://localhost:3998"
)
View Source
const (
	MagicEncrypted = "NUT\x02" // encrypted bundle magic

)

Variables

This section is empty.

Functions

func Check

func Check(dir string) (*Manifest, *ValidationResult, error)

Check performs a completeness check on a bundle directory. Returns what's present, what's missing, and warnings.

func DecryptBundle added in v0.2.2

func DecryptBundle(encPath string, privKey ed25519.PrivateKey) ([]byte, error)

DecryptBundle decrypts an encrypted .nut bundle using the recipient's Ed25519 private key. Returns the decrypted plaintext bytes (a valid NUT\x01 bundle).

func EncryptBundle added in v0.2.2

func EncryptBundle(plainPath, outPath string, recipientEd25519Pub ed25519.PublicKey) error

EncryptBundle encrypts a .nut bundle for a specific recipient.

Format: "NUT\x02" (4) + ephemeralPub (32) + nonce (24) + ciphertext

func GenerateID

func GenerateID() string

GenerateID creates a new nutshell bundle ID.

func HashBundle

func HashBundle(path string) (string, error)

HashBundle computes SHA-256 of the packed .nut file contents (after magic bytes).

func IsEncryptedBundle added in v0.2.2

func IsEncryptedBundle(path string) bool

IsEncryptedBundle checks if a file starts with the encrypted magic bytes.

func IsIgnored

func IsIgnored(relPath string, patterns []string) bool

IsIgnored checks if a relative path matches any ignore pattern.

func LoadClawNetIdentity added in v0.2.2

func LoadClawNetIdentity() (ed25519.PrivateKey, error)

LoadClawNetIdentity loads the Ed25519 private key from ClawNet's default data directory.

func LoadIdentityKey added in v0.2.2

func LoadIdentityKey(path string) (ed25519.PrivateKey, error)

LoadIdentityKey reads a libp2p-marshaled Ed25519 private key file.

func LoadIgnorePatterns

func LoadIgnorePatterns(dir string) []string

LoadIgnorePatterns reads .nutignore from dir and returns patterns.

func ManifestToClawNetExtension

func ManifestToClawNetExtension(peerID, taskID string, reward float64) json.RawMessage

ManifestToClawNetExtension returns the extensions.clawnet JSON for embedding in a nutshell manifest.

func PackWithCompression

func PackWithCompression(srcDir, output string, level CompressionLevel) (*Manifest, *CompressionPlan, error)

PackWithCompression creates a .nut bundle with context-aware compression strategy. level controls the overall compression aggressiveness.

func ParsePeerPubKey added in v0.2.2

func ParsePeerPubKey(s string) (ed25519.PublicKey, error)

ParsePeerPubKey parses a hex-encoded Ed25519 public key (64 hex chars = 32 bytes).

func Schema

func Schema() string

Schema returns the JSON Schema for nutshell.json manifests. This enables IDE auto-completion and validation.

func ServeViewer

func ServeViewer(target string, port int) (string, *http.Server, error)

ServeViewer starts a local HTTP server for inspecting a .nut bundle or directory. Returns the actual address and a shutdown function.

func Set

func Set(dir, key, value string) error

Set updates a field in nutshell.json using dot-path notation. Supported paths: task.title, task.summary, task.priority, task.estimated_effort, bundle_type, publisher.name, publisher.contact, publisher.tool, context.requirements, context.architecture, context.references, harness.agent_type_hint, harness.execution_strategy, harness.context_budget_hint, harness.checkpoints, parent_id, expires_at.

func ValidateFile

func ValidateFile(path string) (*Manifest, *ValidationResult, error)

ValidateFile validates a .nut file or directory.

Types

type APIConfig

type APIConfig struct {
	EndpointsSpec string            `json:"endpoints_spec,omitempty"`
	BaseURLs      map[string]string `json:"base_urls,omitempty"`
	AuthMethod    string            `json:"auth_method,omitempty"`
	CredentialRef string            `json:"credential_ref,omitempty"`
}

type Acceptance

type Acceptance struct {
	CriteriaFile        string   `json:"criteria_file,omitempty"`
	TestScripts         []string `json:"test_scripts,omitempty"`
	AutoVerifiable      bool     `json:"auto_verifiable,omitempty"`
	HumanReviewRequired bool     `json:"human_review_required,omitempty"`
	Checklist           []string `json:"checklist,omitempty"`
}

type Bundle

type Bundle struct {
	// contains filtered or unexported fields
}

Bundle provides programmatic access to a .nut bundle's contents.

func Open

func Open(nutPath string) (*Bundle, error)

Open reads a .nut bundle and returns a Bundle for programmatic access.

func (*Bundle) FilesByPrefix

func (b *Bundle) FilesByPrefix(prefix string) []string

FilesByPrefix returns all files under a given prefix (e.g. "context/").

func (*Bundle) HasFile

func (b *Bundle) HasFile(path string) bool

HasFile checks whether a file exists in the bundle.

func (*Bundle) ListFiles

func (b *Bundle) ListFiles() []string

ListFiles returns all file paths in the bundle.

func (*Bundle) Manifest

func (b *Bundle) Manifest() *Manifest

Manifest returns the parsed bundle manifest.

func (*Bundle) ManifestJSON

func (b *Bundle) ManifestJSON() ([]byte, error)

ManifestJSON returns the raw manifest JSON bytes.

func (*Bundle) ReadContext

func (b *Bundle) ReadContext() ([]byte, error)

ReadContext returns the content of the requirements file referenced in the manifest.

func (*Bundle) ReadFile

func (b *Bundle) ReadFile(path string) ([]byte, error)

ReadFile returns the raw contents of a file inside the bundle.

func (*Bundle) ReadFileString

func (b *Bundle) ReadFileString(path string) (string, error)

ReadFileString is a convenience wrapper that returns file content as string.

func (*Bundle) Repack

func (b *Bundle) Repack(w io.Writer) error

Repack writes the bundle contents to a writer in .nut format.

type BundleHash

type BundleHash struct {
	Algorithm string `json:"algorithm,omitempty"` // "sha256"
	Digest    string `json:"digest,omitempty"`
}

BundleHash holds the content-address of a packed bundle.

type ClawNetClient

type ClawNetClient struct {
	BaseURL    string
	HTTPClient *http.Client
}

ClawNetClient talks to a local ClawNet daemon HTTP API. Nutshell has zero compile-time dependency on ClawNet — all interaction is through the REST API.

func NewClawNetClient

func NewClawNetClient(addr string) *ClawNetClient

NewClawNetClient creates a client for the local ClawNet daemon.

func (*ClawNetClient) DownloadBundle

func (c *ClawNetClient) DownloadBundle(taskID, outPath string) error

DownloadBundle downloads the .nut bundle attached to a ClawNet task.

func (*ClawNetClient) GetCreditBalance

func (c *ClawNetClient) GetCreditBalance() (*CreditBalance, error)

GetCreditBalance fetches the credit balance from the ClawNet daemon.

func (*ClawNetClient) GetTask

func (c *ClawNetClient) GetTask(taskID string) (*ClawNetTask, error)

GetTask fetches task details from ClawNet.

func (*ClawNetClient) ListOpenTasks

func (c *ClawNetClient) ListOpenTasks() ([]*ClawNetTask, error)

ListOpenTasks lists open tasks from ClawNet.

func (*ClawNetClient) Ping

func (c *ClawNetClient) Ping() (*ClawNetStatus, error)

Ping checks if the ClawNet daemon is reachable.

func (*ClawNetClient) PublishTask

func (c *ClawNetClient) PublishTask(m *Manifest, nutHash string, reward float64, targetPeer string) (*ClawNetTask, error)

PublishTask creates a task in ClawNet's Task Bazaar from a nutshell manifest. If reward > 0, it is sent to the daemon; otherwise the daemon applies its default. If targetPeer is non-empty, the task is targeted to that specific peer.

func (*ClawNetClient) SubmitDelivery

func (c *ClawNetClient) SubmitDelivery(taskID, result, deliveryHash string) error

SubmitDelivery submits a delivery result for a task, optionally with a .nut bundle hash.

func (*ClawNetClient) UploadBundle

func (c *ClawNetClient) UploadBundle(taskID, nutPath string) error

UploadBundle uploads a .nut file to ClawNet as a task bundle attachment.

type ClawNetStatus

type ClawNetStatus struct {
	PeerID    string `json:"peer_id"`
	PeerCount int    `json:"peer_count"`
	AgentName string `json:"agent_name"`
}

ClawNetStatus represents the ClawNet daemon status.

type ClawNetTask

type ClawNetTask struct {
	ID          string  `json:"id"`
	AuthorID    string  `json:"author_id"`
	AuthorName  string  `json:"author_name"`
	Title       string  `json:"title"`
	Description string  `json:"description"`
	Tags        string  `json:"tags"`
	Deadline    string  `json:"deadline"`
	Reward      float64 `json:"reward"`
	Status      string  `json:"status"`
	AssignedTo  string  `json:"assigned_to"`
	Result      string  `json:"result"`
	// Nutshell extension fields (Phase 5)
	NutshellHash string `json:"nutshell_hash,omitempty"`
	NutshellID   string `json:"nutshell_id,omitempty"`
	BundleType   string `json:"bundle_type,omitempty"`
}

ClawNetTask represents a task in the ClawNet Task Bazaar.

type Completeness

type Completeness struct {
	Status   string   `json:"status"` // "draft" | "incomplete" | "ready"
	Missing  []string `json:"missing,omitempty"`
	Warnings []string `json:"warnings,omitempty"`
}

type Compression

type Compression struct {
	Algorithm             string `json:"algorithm,omitempty"`
	OriginalSizeBytes     int64  `json:"original_size_bytes,omitempty"`
	CompressedSizeBytes   int64  `json:"compressed_size_bytes,omitempty"`
	ContextTokensEstimate int    `json:"context_tokens_estimate,omitempty"`
}

type CompressionLevel

type CompressionLevel int

CompressionLevel controls how aggressively to compress.

const (
	CompressNone    CompressionLevel = 0
	CompressFast    CompressionLevel = 1
	CompressDefault CompressionLevel = 6
	CompressBest    CompressionLevel = 9
)

type CompressionPlan

type CompressionPlan struct {
	Files           []FileStrategy `json:"files"`
	TotalOriginal   int64          `json:"total_original"`
	TextBytes       int64          `json:"text_bytes"`
	PrecompBytes    int64          `json:"precompressed_bytes"`
	EstimatedTokens int            `json:"estimated_tokens"` // rough token count for text files
}

CompressionPlan is the analysis result for a directory.

func AnalyzeCompression

func AnalyzeCompression(dir string) (*CompressionPlan, error)

AnalyzeCompression builds a context-aware compression plan for a directory.

type Context

type Context struct {
	Requirements string   `json:"requirements,omitempty"`
	Architecture string   `json:"architecture,omitempty"`
	References   string   `json:"references,omitempty"`
	Additional   []string `json:"additional,omitempty"`
}

type CredentialScope

type CredentialScope struct {
	Name        string `json:"name"`
	Type        string `json:"type"`
	AccessLevel string `json:"access_level,omitempty"`
	RateLimit   string `json:"rate_limit,omitempty"`
	ExpiresAt   string `json:"expires_at,omitempty"`
}

type CredentialStatus

type CredentialStatus struct {
	Name      string `json:"name"`
	Type      string `json:"type"`
	ExpiresAt string `json:"expires_at,omitempty"`
	Status    string `json:"status"` // "valid", "expiring_soon", "expired", "no_expiry"
	DaysLeft  int    `json:"days_left,omitempty"`
}

CredentialStatus describes the state of a single credential scope.

func AuditCredentials

func AuditCredentials(dir string) ([]CredentialStatus, error)

AuditCredentials checks expiration status of all credential scopes in a bundle.

type Credentials

type Credentials struct {
	Vault      string            `json:"vault,omitempty"`
	Encryption string            `json:"encryption,omitempty"` // "age" | "sops" | "vault" | "none"
	Scopes     []CredentialScope `json:"scopes,omitempty"`
}

type CreditBalance

type CreditBalance struct {
	PeerID  string  `json:"peer_id"`
	Balance float64 `json:"balance"`
	Energy  float64 `json:"energy"`
	Frozen  float64 `json:"frozen"`
}

CreditBalance represents a ClawNet credit account.

type DiffEntry

type DiffEntry struct {
	Field string `json:"field"`
	A     string `json:"a"`
	B     string `json:"b"`
}

DiffEntry represents a single field difference between two manifests.

func Diff

func Diff(pathA, pathB string) ([]DiffEntry, error)

Diff compares two bundles (either .nut files or directories) and returns differences.

type DocRef

type DocRef struct {
	URL   string `json:"url"`
	Title string `json:"title,omitempty"`
}

type FileEntry

type FileEntry struct {
	Path string `json:"path"`
	Size int64  `json:"size"`
	Role string `json:"role,omitempty"` // "scaffold" | "reference" | "specification"
	Hash string `json:"hash,omitempty"` // "sha256:<hex>"
}

type FileManifest

type FileManifest struct {
	TotalCount     int         `json:"total_count"`
	TotalSizeBytes int64       `json:"total_size_bytes"`
	Tree           []FileEntry `json:"tree,omitempty"`
}

type FileStrategy

type FileStrategy struct {
	Path           string `json:"path"`
	OriginalSize   int64  `json:"original_size"`
	Category       string `json:"category"`       // "text", "binary", "precompressed", "media"
	GzipLevel      int    `json:"gzip_level"`     // effective gzip level for this file
	Recommendation string `json:"recommendation"` // "compress", "store", "skip"
}

FileStrategy describes the compression decision for a single file.

type Harness

type Harness struct {
	AgentTypeHint     string   `json:"agent_type_hint,omitempty"`
	ContextBudgetHint float64  `json:"context_budget_hint,omitempty"`
	ExecutionStrategy string   `json:"execution_strategy,omitempty"`
	Checkpoints       bool     `json:"checkpoints,omitempty"`
	Constraints       []string `json:"constraints,omitempty"`
}

type ImageRef

type ImageRef struct {
	Path        string `json:"path"`
	Description string `json:"description,omitempty"`
}

type LinkRef

type LinkRef struct {
	URL   string `json:"url"`
	Title string `json:"title,omitempty"`
}

type Manifest

type Manifest struct {
	NutshellVersion string                     `json:"nutshell_version"`
	BundleType      string                     `json:"bundle_type"` // "request" | "delivery" | "template" | "checkpoint" | "partial"
	ID              string                     `json:"id"`
	CreatedAt       string                     `json:"created_at"`
	ExpiresAt       string                     `json:"expires_at,omitempty"`
	Task            Task                       `json:"task"`
	Tags            Tags                       `json:"tags,omitempty"`
	Publisher       Publisher                  `json:"publisher,omitempty"`
	Context         Context                    `json:"context,omitempty"`
	Files           FileManifest               `json:"files,omitempty"`
	APIs            *APIConfig                 `json:"apis,omitempty"`
	Credentials     *Credentials               `json:"credentials,omitempty"`
	Acceptance      *Acceptance                `json:"acceptance,omitempty"`
	Harness         *Harness                   `json:"harness,omitempty"`
	Resources       *Resources                 `json:"resources,omitempty"`
	Completeness    *Completeness              `json:"completeness,omitempty"`
	ParentID        string                     `json:"parent_id,omitempty"`
	Compression     *Compression               `json:"compression,omitempty"`
	Extensions      map[string]json.RawMessage `json:"extensions,omitempty"`
}

Manifest is the nutshell.json schema.

func Inspect

func Inspect(nutPath string) (*Manifest, []string, error)

Inspect reads the manifest from a .nut bundle without extracting.

func InspectReader

func InspectReader(r io.Reader) (*Manifest, []string, error)

InspectReader reads the manifest from a .nut stream (file or stdin).

func Merge

func Merge(dirs []string, outDir string) (*Manifest, error)

Merge combines multiple delivery sub-bundles back into one delivery bundle.

func NewManifest

func NewManifest() *Manifest

NewManifest creates a manifest with defaults.

func Pack

func Pack(srcDir, output string) (*Manifest, error)

Pack creates a .nut bundle from a directory.

func Unpack

func Unpack(nutPath, outDir string) (*Manifest, error)

Unpack extracts a .nut bundle to a directory.

type Publisher

type Publisher struct {
	Name    string `json:"name,omitempty"`
	Contact string `json:"contact,omitempty"`
	Tool    string `json:"tool,omitempty"`
}

type RepoRef

type RepoRef struct {
	URL       string `json:"url"`
	Branch    string `json:"branch,omitempty"`
	Relevance string `json:"relevance,omitempty"`
}

type Resources

type Resources struct {
	Repos  []RepoRef  `json:"repos,omitempty"`
	Docs   []DocRef   `json:"docs,omitempty"`
	Images []ImageRef `json:"images,omitempty"`
	Links  []LinkRef  `json:"links,omitempty"`
}

type RotateResult

type RotateResult struct {
	Scope     string `json:"scope"`
	OldExpiry string `json:"old_expires_at"`
	NewExpiry string `json:"new_expires_at"`
}

RotateResult holds the outcome of a credential rotation.

func RotateCredential

func RotateCredential(dir, scopeName, newExpiry string) (*RotateResult, error)

RotateCredential updates the expiration of a named credential scope. If newExpiry is empty, it extends by 30 days from now.

type SplitPlan

type SplitPlan struct {
	SubTasks []SubTask `json:"sub_tasks"`
}

SplitPlan describes how to split a task into parallel sub-tasks.

type SplitResult

type SplitResult struct {
	Index     int    `json:"index"`
	ID        string `json:"id"`
	Title     string `json:"title"`
	Directory string `json:"directory"`
}

SplitResult holds information about one generated sub-bundle.

func Split

func Split(srcDir string, plan *SplitPlan) ([]SplitResult, error)

Split breaks a task directory into N sub-task directories based on a plan. If plan is nil, it auto-splits by file directories.

type SubTask

type SubTask struct {
	Title       string   `json:"title"`
	Summary     string   `json:"summary,omitempty"`
	Skills      []string `json:"skills,omitempty"`
	Files       []string `json:"files,omitempty"` // file patterns to include in this sub-bundle
	Constraints []string `json:"constraints,omitempty"`
}

SubTask describes one piece of a split task.

type Tags

type Tags struct {
	SkillsRequired []string               `json:"skills_required,omitempty"`
	Domains        []string               `json:"domains,omitempty"`
	DataSources    []string               `json:"data_sources,omitempty"`
	Custom         map[string]interface{} `json:"custom,omitempty"`
}

type Task

type Task struct {
	Title           string `json:"title"`
	Summary         string `json:"summary,omitempty"`
	Priority        string `json:"priority,omitempty"`
	EstimatedEffort string `json:"estimated_effort,omitempty"`
}

type ValidationResult

type ValidationResult struct {
	Errors   []string
	Warnings []string
}

ValidationResult holds errors and warnings from validation.

func Validate

func Validate(manifest *Manifest) *ValidationResult

Validate checks a manifest against the spec.

func (*ValidationResult) IsValid

func (v *ValidationResult) IsValid() bool

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL