memorycontract

package
v2.3.4 Latest Latest
Warning

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

Go to latest
Published: Sep 2, 2026 License: MIT Imports: 10 Imported by: 0

Documentation

Overview

Package memorycontract is the shared, pure MCP contract for the durable memory write surface (design RD6, REM-SAVE-001, REM-MCP-001).

It defines the tool names, hint annotations, the exact structured output schema, the handoff input schema, and the lowering of domain write results and errors into the structured payloads published by cortex_save and cortex_handoff. The local MCP server and the authenticated server runtime both consume this package so the published contract is byte-identical on every route; the proxy forwards results without reinterpreting them.

The package is deliberately pure: no I/O, no stores, no transport clients. It depends only on the domain model, the pure transport policy, and the standard library, and never logs or embeds payloads, idempotency keys, hashes, or tokens.

Index

Constants

View Source
const (
	// ToolSave is the proactive memory save tool.
	ToolSave = "cortex_save"
	// ToolHandoff is the durable, idempotent handoff tool.
	ToolHandoff = "cortex_handoff"
)

Tool names in the cortex_* namespace (REQ-MCP-001). Single source of truth for local and server registration.

View Source
const (
	CodeValidation      = string(domain.HandoffErrorValidation)
	CodePayloadTooLarge = string(domain.HandoffErrorPayloadTooLarge)
	CodeUnauthorized    = string(domain.HandoffErrorUnauthorized)
	CodeForbidden       = string(domain.HandoffErrorForbidden)
	CodeConflict        = string(domain.HandoffErrorConflict)
	CodeUnavailable     = string(domain.HandoffErrorUnavailable)
	CodeTimeout         = string(domain.HandoffErrorTimeout)
	CodePersistence     = string(domain.HandoffErrorPersistence)
	CodeTransport       = "transport"
)

Stable, machine-readable structured error codes (design: error contract). The domain handoff codes are reused verbatim; transport is the proxy-only classification for failures that never produced an MCP result.

View Source
const MaxErrorMessageLength = 200

MaxErrorMessageLength bounds every structured error message so a hostile or verbose underlying failure can never leak unbounded text into a result.

Variables

View Source
var (
	// SaveHints annotates cortex_save.
	SaveHints = Hints{Title: "Save Memory"}
	// HandoffHints annotates cortex_handoff.
	HandoffHints = Hints{Title: "Record Handoff", Idempotent: true}
)
View Source
var HandoffInputSchemaJSON = json.RawMessage(`{
	"type": "object",
	"properties": {
		"idempotency_key": {
			"type": "string",
			"minLength": 1,
			"description": "Stable idempotency key; identical key+payload replays, differing payload conflicts"
		},
		"observation": {
			"type": "object",
			"properties": {
				"title":       {"type": "string", "minLength": 1},
				"content":     {"type": "string", "minLength": 1},
				"type":        {"type": "string"},
				"project":     {"type": "string"},
				"scope":       {"type": "string", "enum": ["project", "personal"]},
				"session_id":  {"type": "string", "description": "Session the observation belongs to; the local runtime requires a preexisting session and validates it before any mutation"},
				"topic_key":   {"type": "string"},
				"confidence":  {"type": "number", "minimum": 0, "maximum": 1},
				"source":      {"type": "string"},
				"tags":        {"type": "array", "items": {"type": "string"}}
			},
			"required": ["title", "content"],
			"additionalProperties": false
		},
		"relation": {
			"type": "object",
			"properties": {
				"target": {
					"oneOf": [
						{
							"type": "object",
							"properties": {"local_id": {"type": "integer", "minimum": 1}},
							"required": ["local_id"],
							"additionalProperties": false
						},
						{
							"type": "object",
							"properties": {"public_id": {"type": "string", "format": "uuid"}},
							"required": ["public_id"],
							"additionalProperties": false
						}
					]
				},
				"type":       {"type": "string", "minLength": 1},
				"weight":     {"type": "number"},
				"confidence": {"type": "number"},
				"reasoning":  {"type": "string"}
			},
			"required": ["target", "type"],
			"additionalProperties": false
		},
		"capability_tuple": {
			"description": "Opaque JSON evidence forwarded with the handoff; stored as data, never interpreted"
		}
	},
	"required": ["idempotency_key", "observation"],
	"additionalProperties": false
}`)

HandoffInputSchemaJSON is the shared input schema for cortex_handoff. The relation target accepts both namespaces at the schema level so the server runtime can publish the identical contract; the LOCAL handler accepts only local_id because the local namespace is SQLite-only (REM-MCP-001: local uses local_id, server/proxy use public_id UUID).

View Source
var WriteOutputSchemaJSON = json.RawMessage(`{
	"type": "object",
	"properties": {
		"observation_ref": {
			"oneOf": [
				{
					"type": "object",
					"properties": {
						"local_id": {"type": "integer", "minimum": 1}
					},
					"required": ["local_id"],
					"additionalProperties": false
				},
				{
					"type": "object",
					"properties": {
						"public_id": {"type": "string", "format": "uuid"}
					},
					"required": ["public_id"],
					"additionalProperties": false
				}
			]
		},
		"status": {"type": "string", "enum": ["created", "replayed", "updated"]},
		"error": {
			"type": "object",
			"properties": {
				"code": {"type": "string"},
				"message": {"type": "string"}
			},
			"required": ["code", "message"],
			"additionalProperties": false
		}
	},
	"additionalProperties": false
}`)

WriteOutputSchemaJSON is the exact output schema for cortex_save and cortex_handoff results: a structured payload carrying the exclusive observation reference (local_id XOR public_id) and the closed write status, or a structured error payload.

Functions

func ValidStatus

func ValidStatus(status domain.WriteStatus) bool

ValidStatus reports whether status belongs to the closed write-status set.

Types

type ErrorBody

type ErrorBody struct {
	Code      string `json:"code"`
	Message   string `json:"message"`
	Retryable bool   `json:"retryable"`
}

ErrorBody is the stable, redacted, bounded error classification.

type ErrorStructured

type ErrorStructured struct {
	Error ErrorBody `json:"error"`
}

ErrorStructured is the structuredContent payload of a failed tool call. It never carries a reference, status, key, hash, payload, or token.

func FromError

func FromError(err error) ErrorStructured

FromError lowers any error into the stable structured error contract. Messages for generic classifications are CONSTANT and redacted; typed handoff and validation errors contribute only their safe, pre-redacted message, always bounded to MaxErrorMessageLength runes. Transport failures are detected ONLY through explicit typed matches — *url.Error, net.Error, and *transportpolicy.Error — never through a generic Unwrap probe, which would misclassify wrapped persistence failures (SQL errors, busy locks) as transport problems.

func Unavailablef

func Unavailablef(format string, args ...any) ErrorStructured

Unavailablef builds an unavailable error payload for a missing dependency.

func Validationf

func Validationf(format string, args ...any) ErrorStructured

Validationf builds a validation error payload with a formatted, bounded message. Use for request-shape rejections before any persistence runs.

type Hints

type Hints struct {
	Title       string
	ReadOnly    bool
	Destructive bool
	Idempotent  bool
	OpenWorld   bool
}

Shared hint annotations for the durable write tools. Both are read/write, non-destructive, closed-world; handoff is additionally idempotent because the same (scope, key, payload) replays the same observation (REM-HANDOFF-002).

type ObservationRefPayload

type ObservationRefPayload struct {
	LocalID  *int64  `json:"local_id,omitempty"`
	PublicID *string `json:"public_id,omitempty"`
}

ObservationRefPayload is the wire form of domain.ObservationRef: exactly one namespace set (XOR), matching the output schema's oneOf.

func NewLocalRefPayload

func NewLocalRefPayload(id int64) (ObservationRefPayload, error)

NewLocalRefPayload builds a validated local-namespace reference.

func NewPublicRefPayload

func NewPublicRefPayload(id string) (ObservationRefPayload, error)

NewPublicRefPayload builds a validated public-namespace reference.

func (ObservationRefPayload) Validate

func (p ObservationRefPayload) Validate() error

Validate enforces the exclusive union invariant.

type SaveStructured

type SaveStructured struct {
	ObservationRef ObservationRefPayload `json:"observation_ref"`
	Status         string                `json:"status"`
}

SaveStructured is the structuredContent payload of a successful cortex_save or cortex_handoff call.

func FromWriteResult

func FromWriteResult(result domain.ObservationWriteResult) (SaveStructured, error)

FromWriteResult lowers a validated domain write result into the structured payload. It fails closed: an invalid reference or status produces an error, never a fabricated success payload.

Jump to

Keyboard shortcuts

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