collection

package
v0.6.0 Latest Latest
Warning

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

Go to latest
Published: Nov 12, 2026 License: Apache-2.0 Imports: 36 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package collection manages Markdown documents with stable IDs, typed application data, and a collection-local JSON Schema in MEANS.md.

Getting started

Init and InitConfig create collections without overwriting MEANS.md. Load reads the exact directory supplied and compiles a configuration snapshot. Documents are scanned on each operation; configuration is not automatically reloaded. Call Load again after schema, identity, views, or instructions change. Collection values must be obtained through these constructors; the zero value is not usable. No Close call is needed: each operation closes its files and caches before returning. See the examples for Collection.Create, Collection.Search, Collection.Update, and SetSchema. Watch provides optional change notifications with a separate context-owned lifetime. Cancel its context to release filesystem watches.

MEANS.md contains YAML frontmatter with a required schema and optional title, description, and app views, followed by Markdown workflow instructions. Documents contain only id, title, and data in their YAML frontmatter, followed by a free-form body. The schema validates data, not the means-owned fields. Visible Markdown files in subdirectories belong to the collection, except below another MEANS.md. Hidden paths and symlinks are ignored. MEANS.md itself is configuration, not a document.

Inputs and results

Creation, updates, validation, and list/search filters accept JSON-compatible Go values such as int and []string without changing input maps. Stored values use map[string]any, []any, and json.Number. Supply json.Number to preserve exact large integers and decimals. Do not mutate inputs while an operation uses them. List and search summaries omit hashes: read by ID before changing a document. Their optional body pointers distinguish an omitted body from an empty body.

Create, Update, and ReplaceMarkdown validate application data. Read, List, and Search check document envelopes without enforcing the loaded data schema. Use Doctor to check all documents against that schema. List, Search, and Doctor return document diagnostics separately from fatal errors.

Update and Delete require the hash from Read. Stale hashes return ErrConflict; missing IDs wrap fs.ErrNotExist and duplicate IDs wrap ErrDuplicateID. Hash checks reject observed changes but cannot exclude external writes racing the final replacement or deletion. Creation is not idempotent.

Cancellation and host settings

Operations take a non-nil context. Cancellation is checked before work starts and during embedding requests and cache lock waits. Synchronous filesystem work and schema validation may finish before cancellation is observed. A loaded Collection can be shared by concurrent callers. WithEmbeddings and WithEmbeddingProgress return copies; progress callbacks can run concurrently and must synchronize their own state.

The package does not load user configuration or .env files and does not print output. Embeddings are disabled until the host supplies an EmbeddingConfig. Enabled embedding operations read credentials and endpoint overrides from the process environment as described by EmbeddingConfig. Full-text search writes disposable caches under .means/; ordinary reads, lists, and literal searches remain offline.

Index

Examples

Constants

View Source
const ConfigFilename = "MEANS.md"

ConfigFilename is the collection's configuration and workflow file.

View Source
const DefaultSemanticMinScore = 0.3

DefaultSemanticMinScore is the inclusive cosine threshold used when SearchOptions.MinScore is nil. It does not apply to other search modes.

Variables

View Source
var (
	// ErrConflict means an observed document or configuration change made a hash
	// stale. Reload the current content, reconcile the changes, and use its hash.
	ErrConflict = errors.New("document content has changed")
)
View Source
var ErrDuplicateID = errors.New("duplicate document ID")

ErrDuplicateID means more than one visible document has the requested ID. Read and mutations wrap it; List and Search report duplicates in diagnostics.

View Source
var ErrSchemaIncompatible = errors.New("proposed schema has document violations")

ErrSchemaIncompatible means the proposed schema rejected existing documents. SetSchema also returns a non-nil result with the document diagnostics.

View Source
var ErrValidation = errors.New("document validation failed")

ErrValidation identifies an invalid document envelope or application data. Validate and ValidateData wrap it, as do write failures during schema/envelope validation. The underlying validation error remains available through errors.As. Other invalid arguments or source-parsing failures can return errors without this sentinel.

Functions

func MatchesFilter

func MatchesFilter(data, filter map[string]any) bool

MatchesFilter reports whether data matches a partial metadata filter using the same rules as List and Search. Inputs must already use map[string]any, []any, and json.Number for objects, arrays, and numbers. Unlike List and Search, this helper does not normalize native Go values such as int or []string. Nil or empty filter matches every object. It does not apply datetime filters.

func Watch

func Watch(ctx context.Context, root string) (<-chan WatchEvent, error)

Watch monitors a collection directory until ctx is canceled. The directory must exist, but MEANS.md need not be valid or present. Watch does not load configuration, change files, or contact embedding services.

Start Watch before the initial read. No initial event is sent. Changes are coalesced after 200ms of quiet; events are invalidations, not an operation log. Hidden paths and symlinks below the root are ignored. Nested collections are excluded, but adding or removing their MEANS.md boundary invalidates the parent. Extra invalidations are possible. Delivery depends on filesystem notification support; this is not a durable or lossless subscription.

Cancel ctx when finished. The channel closes after watcher resources are released, even if the consumer stops receiving. The root's parent must remain present; removal and recreation of the root itself are supported. A symlink supplied as the root is resolved once at startup.

Types

type AppConfig

type AppConfig struct {
	// Views contains experimental named TUI views in configuration order. Nil
	// or empty means no custom views; it does not remove the built-in view.
	Views []AppView `json:"views,omitempty"`
}

AppConfig describes optional collection views. Expressions are compiled by the TUI, not by collection operations or MCP.

type AppView

type AppView struct {
	// Title is a unique, nonblank, single-line name for the view.
	Title string `json:"title"`
	// Filter is an optional Expr expression evaluated by the TUI.
	Filter string `json:"filter,omitempty"`
	// Columns selects id, title, or data.FIELD columns. An empty list lets the
	// TUI select its default columns.
	Columns []string `json:"columns,omitempty"`
}

AppView describes one experimental TUI view from MEANS.md. Collection loading validates its structure but does not compile or evaluate the filter expression.

type Collection

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

Collection is a loaded collection with a compiled application data schema. Use Load, Init, or InitConfig; its zero value is not usable. Configuration is a fixed snapshot while document operations scan current files. No Close is needed. Its accessors return copies, and it is safe for concurrent operations.

func Init

func Init(path string, schema []byte) (*Collection, error)

Init validates a schema, then creates the directory and writes MEANS.md without overwriting an existing file. A nil schema selects the example schema. Schema is a JSON Schema object or boolean in JSON bytes, not YAML. Schemas are self-contained; external references are rejected. Draft 2020-12 is the default. The example schema allows only optional tags (an array of strings). Init adds a .means/ rule to .gitignore while preserving existing content. Use InitConfig to supply identity and workflow instructions with the schema.

func InitConfig

func InitConfig(path string, content []byte) (*Collection, error)

InitConfig validates and installs a complete MEANS.md without overwriting it. Content is YAML frontmatter (including schema), followed by optional Markdown instructions. Exact bytes are preserved. Validation occurs before creating files; directory creation and the .gitignore rule follow the Init contract. For example, a minimal content value is:

---
title: Notes
schema: true
---
Review notes before publishing.

func Load

func Load(path string) (*Collection, error)

Load reads the exact directory supplied; it does not search parent directories. The returned configuration is a snapshot. Reload after external config edits. It compiles the schema but does not validate existing documents or create files. Missing MEANS.md wraps fs.ErrNotExist. Document operations do not automatically reload this snapshot after SetSchema or SetInstructions; call Load again and reapply any host embedding settings and progress callback.

func (*Collection) App

func (c *Collection) App() AppConfig

App returns a copy of the optional application views from the loaded snapshot.

func (*Collection) Append

func (c *Collection) Append(ctx context.Context, id, hash, text string) (*Document, error)

Append adds text to the end of a document's Markdown body without inserting separators or newlines. An empty hash appends to the latest stored version; otherwise use the current hash from Read. Empty text leaves the body unchanged. The result must satisfy the loaded schema. Calls serialize on a collection-local append lock with a context-aware wait of up to five seconds. Like a body-only Update, Append preserves frontmatter bytes, filename, and permissions, maintains enabled embeddings before saving, and rejects observed changes with ErrConflict. External writes can still race the final replacement. The returned Document contains the new content hash.

func (*Collection) Create

func (c *Collection) Create(ctx context.Context, opts CreateOptions) (*Document, error)

Create validates and stores a new document. It is not idempotent: every successful call creates another document, even when the options are identical.

Example
package main

import (
	"context"
	"fmt"
	"os"

	"github.com/hmans/means/collection"
)

func main() {
	dir, err := os.MkdirTemp("", "means-example-*")
	if err != nil {
		panic(err)
	}
	defer os.RemoveAll(dir)
	c, err := collection.Init(dir, []byte(`{"type":"object"}`))
	if err != nil {
		panic(err)
	}
	doc, err := c.Create(context.Background(), collection.CreateOptions{
		Title: "First note",
		Data:  map[string]any{"status": "draft"},
		Body:  "Written directly from Go.",
	})
	if err != nil {
		panic(err)
	}
	fmt.Println(doc.Frontmatter["title"])
	fmt.Println(doc.Body)
}
Output:
First note
Written directly from Go.

func (*Collection) Delete

func (c *Collection) Delete(ctx context.Context, id, hash string) (*DeleteResult, error)

Delete removes a document only when its stored bytes match hash. Like Update, this is optimistic: a concurrent write can race the final removal. Application data need not satisfy the current schema, but the envelope must be readable and the ID must be unique within the selected collection. Hash comes from Read. Deletion is permanent and removes only the document file; directories and configuration remain. With embeddings enabled, its cached vector is removed first, without a network request.

func (*Collection) Describe

func (c *Collection) Describe() *Description

Describe returns identity and guidance from the loaded configuration snapshot.

func (*Collection) Doctor

func (c *Collection) Doctor(ctx context.Context) (*DoctorResult, error)

Doctor inspects every visible document against the loaded schema without changing any files. Malformed envelopes and duplicate IDs are also reported.

func (*Collection) Embed

func (c *Collection) Embed(ctx context.Context, opts EmbedOptions) (*ListResult, error)

Embed refreshes derived vectors without changing Markdown. It also prunes deleted, malformed, duplicate, and newly nested documents. Successful batches remain cached if a later batch fails; Force discards previous vectors first. It requires WithEmbeddings settings and provider credentials when vectors need generation. Each vector embeds title plus exact body; data is not embedded. The result lists all valid documents with bodies, including reused vectors, and diagnostics for malformed or duplicate files. It does not enforce the current data schema. It writes disposable cache files under .means/.

func (*Collection) Embeddings

func (c *Collection) Embeddings() *EmbeddingConfig

Embeddings returns a copy of the attached host settings, or nil if disabled.

func (*Collection) List

func (c *Collection) List(ctx context.Context, opts ListOptions) (*ListResult, error)

List returns frontmatter in relative filename order. Invalid documents and duplicate IDs produce individual diagnostics regardless of offset or limit.

func (*Collection) Path

func (c *Collection) Path() string

Path returns the absolute collection directory.

func (*Collection) Read

func (c *Collection) Read(ctx context.Context, id string) (*Document, error)

Read resolves a stored frontmatter ID regardless of filename or subdirectory. Application schema violations remain readable; the means envelope must be valid.

func (*Collection) ReplaceMarkdown

func (c *Collection) ReplaceMarkdown(ctx context.Context, id, hash string, markdown []byte) (*Document, error)

ReplaceMarkdown validates an edited document and replaces its content using the same hash checks and embedding maintenance as Update. Metadata is replaced, not merge-patched, so removed keys and literal null values are preserved. Markdown must contain the original ID, a nonempty title, a data object, and an optional UTF-8 body. Use the current stored hash from Read, not a hash of the edited bytes. The receiver's loaded schema validates the replacement.

func (*Collection) Schema

func (c *Collection) Schema() json.RawMessage

Schema returns a copy of the JSON Schema from the loaded snapshot.

func (*Collection) Search

func (c *Collection) Search(ctx context.Context, opts SearchOptions) (*SearchResult, error)

Search ranks full-text queries using a refreshed collection-local index. Literal and data-only searches scan in filename order. Filter is a recursive partial match of application data; arrays must match completely. Schema-invalid data stays searchable, while malformed and duplicate documents become diagnostics. Full-text and semantic searches sort rank ties by ID. Full-text search writes a disposable .means/ cache; literal and data-only searches remain offline.

Example
package main

import (
	"context"
	"fmt"
	"os"

	"github.com/hmans/means/collection"
)

func main() {
	dir, err := os.MkdirTemp("", "means-example-*")
	if err != nil {
		panic(err)
	}
	defer os.RemoveAll(dir)
	c, err := collection.Init(dir, []byte(`{"type":"object"}`))
	if err != nil {
		panic(err)
	}
	ctx := context.Background()
	for _, note := range []collection.CreateOptions{
		{Title: "Release checklist", Data: map[string]any{"status": "draft", "created_at": "2026-11-02T08:00:00Z"}, Body: "Check the release.\n"},
		{Title: "Release notes", Data: map[string]any{"status": "published", "created_at": "2026-11-02T08:00:00Z"}},
	} {
		if _, err := c.Create(ctx, note); err != nil {
			panic(err)
		}
	}
	result, err := c.Search(ctx, collection.SearchOptions{
		Query:    "release",
		Filter:   map[string]any{"status": "draft"},
		DateTime: []collection.DateTimeFilter{{Field: "created_at", Op: "on_or_after", Value: "2026-11-01T00:00:00Z"}},
		WithBody: true,
		Limit:    10,
	})
	if err != nil {
		panic(err)
	}
	// A successful search can still report malformed files or duplicate IDs.
	if len(result.Diagnostics) != 0 {
		panic(result.Diagnostics)
	}
	for _, hit := range result.Documents {
		fmt.Println(hit.Frontmatter["title"])
		fmt.Print(*hit.Body) // Non-nil because WithBody was set.
	}
}
Output:
Release checklist
Check the release.

func (*Collection) SetInstructions

func (c *Collection) SetInstructions(ctx context.Context, hash, instructions string) (*Description, error)

SetInstructions replaces only the MEANS.md body. The hash covers the complete file, including its frontmatter. External writes can still race replacement. Obtain hash from Describe on a freshly loaded collection. Instructions is the complete UTF-8 replacement body; an empty string clears it. Valid configuration is required, but document data is not checked. Frontmatter bytes and permissions are preserved. Stale hashes return ErrConflict; reload and reconcile before retrying. The returned Description contains the new hash and body, while the receiver retains its old snapshot. Call Load to observe the new instructions.

Example
package main

import (
	"context"
	"fmt"
	"os"

	"github.com/hmans/means/collection"
)

func main() {
	dir, err := os.MkdirTemp("", "means-example-*")
	if err != nil {
		panic(err)
	}
	defer os.RemoveAll(dir)
	c, err := collection.Init(dir, nil)
	if err != nil {
		panic(err)
	}
	ctx := context.Background()
	info := c.Describe() // Configuration hash, not a document hash.
	updated, err := c.SetInstructions(ctx, info.Hash, "Review drafts before publishing.\n")
	if err != nil {
		panic(err)
	}
	fmt.Print(updated.Instructions)
	// The receiver still holds the original snapshot; reload after the change.
	c, err = collection.Load(c.Path())
	if err != nil {
		panic(err)
	}
	cleared, err := c.SetInstructions(ctx, c.Describe().Hash, "")
	if err != nil {
		panic(err)
	}
	fmt.Println("Cleared:", cleared.Instructions == "")
}
Output:
Review drafts before publishing.
Cleared: true

func (*Collection) Update

func (c *Collection) Update(ctx context.Context, id, hash string, patch Patch) (*Document, error)

Update checks the exact stored bytes against hash before applying a patch. Replacement uses a temporary file in the same directory. Hash checks are optimistic: a simultaneous write can still race the final replacement. Use ID and Hash from Read, and supply at least one part of Patch. The loaded schema validates the result. The existing filename is kept even if title changes. Body-only edits preserve the original frontmatter bytes. Enabled embeddings are maintained before the file write; provider or cache failures prevent that write. The returned Document has the new content hash.

Example
package main

import (
	"context"
	"fmt"
	"os"

	"github.com/hmans/means/collection"
)

func main() {
	dir, err := os.MkdirTemp("", "means-example-*")
	if err != nil {
		panic(err)
	}
	defer os.RemoveAll(dir)
	c, err := collection.Init(dir, nil)
	if err != nil {
		panic(err)
	}
	ctx := context.Background()
	doc, err := c.Create(ctx, collection.CreateOptions{Title: "First note"})
	if err != nil {
		panic(err)
	}
	current, err := c.Read(ctx, doc.ID)
	if err != nil {
		panic(err)
	}
	body := "Updated from Go."
	updated, err := c.Update(ctx, current.ID, current.Hash, collection.Patch{Body: &body})
	if err != nil {
		panic(err)
	}
	fmt.Println(updated.Body)
}
Output:
Updated from Go.
Example (Conflict)
package main

import (
	"context"
	"errors"
	"fmt"
	"os"

	"github.com/hmans/means/collection"
)

func main() {
	dir, err := os.MkdirTemp("", "means-example-*")
	if err != nil {
		panic(err)
	}
	defer os.RemoveAll(dir)
	c, err := collection.Init(dir, nil)
	if err != nil {
		panic(err)
	}
	ctx := context.Background()
	created, err := c.Create(ctx, collection.CreateOptions{Title: "Original title"})
	if err != nil {
		panic(err)
	}
	original, err := c.Read(ctx, created.ID)
	if err != nil {
		panic(err)
	}
	// Another caller changes the title after our read.
	if _, err := c.Update(ctx, original.ID, original.Hash, collection.Patch{Frontmatter: map[string]any{"title": "Edited elsewhere"}}); err != nil {
		panic(err)
	}
	body := "My body edit."
	_, err = c.Update(ctx, original.ID, original.Hash, collection.Patch{Body: &body})
	if !errors.Is(err, collection.ErrConflict) {
		panic(fmt.Sprintf("expected conflict, got %v", err))
	}
	current, err := c.Read(ctx, original.ID)
	if err != nil {
		panic(err)
	}
	// Reconcile with the current document. Reapply our edit only if the body is
	// unchanged; otherwise the caller must resolve both body edits first.
	if current.Body != original.Body {
		panic("body changed; resolve the conflicting edits before saving")
	}
	// The body-only patch preserves the other caller's title.
	updated, err := c.Update(ctx, current.ID, current.Hash, collection.Patch{Body: &body})
	if err != nil {
		panic(err) // A new concurrent edit can still cause another conflict.
	}
	fmt.Println(updated.Frontmatter["title"])
	fmt.Println(updated.Body)
}
Output:
Edited elsewhere
My body edit.

func (*Collection) Validate

func (c *Collection) Validate(frontmatter map[string]any) error

Validate checks the means envelope and data against the embedded schema. Frontmatter must contain only a valid id, a nonempty title, and a data object. JSON-compatible Go values are normalized without changing the map. It does not read or write documents; failures wrap ErrValidation.

func (*Collection) ValidateData

func (c *Collection) ValidateData(data map[string]any) error

ValidateData checks application data independently of the means-owned fields. Supply the application object itself, not a frontmatter envelope. Values are normalized like CreateOptions.Data; nil is not an object. It uses the loaded schema without reading or writing documents. Failures wrap ErrValidation.

func (*Collection) WithEmbeddingProgress

func (c *Collection) WithEmbeddingProgress(progress func(string)) *Collection

WithEmbeddingProgress returns a copy that reports embedding work to progress. The collection package stays silent unless a caller supplies this callback. Nil disables progress reporting. Concurrent operations can invoke the callback concurrently; the callback must synchronize its own shared state.

func (*Collection) WithEmbeddings

func (c *Collection) WithEmbeddings(cfg *EmbeddingConfig) *Collection

WithEmbeddings copies host settings without changing collection files. Nil disables embeddings. Settings are validated and defaulted when used. The original Collection is unchanged. Call EmbeddingConfig.WithDefaults first to check settings immediately. Embeddings returns the attached settings, which can still have zero-value defaults rather than their resolved values.

type CreateOptions

type CreateOptions struct {
	// Title is required and must contain non-whitespace text.
	Title string
	// Data is the application object checked against the loaded schema. Nil
	// means {}. JSON-compatible Go values, including int and []string, are
	// normalized without changing the input map. Use json.Number for exact
	// large integers or decimals that must not pass through float64.
	Data map[string]any
	// Body is a UTF-8 Markdown body, preserved exactly. Empty selects no body.
	Body string
}

CreateOptions supplies a document's title, application data, and Markdown body. Nil Data selects an empty object. Means generates the document ID.

type DateTimeFilter

type DateTimeFilter struct {
	// Field is a nonempty literal key under data. Dots are part of the key;
	// they do not select nested fields.
	Field string `json:"field"`
	// Op is "before", "after", "on_or_before", or "on_or_after". The first
	// two are exclusive; the on_or variants include equality.
	Op string `json:"op"`
	// Value is an RFC 3339 timestamp with a timezone and at most nine fractional
	// digits, for example "2026-11-03T09:00:00+01:00". Date-only values and leap
	// seconds are invalid. No schema annotation is required for the field.
	Value string `json:"value"`
}

DateTimeFilter compares a string field directly under frontmatter.data. Comparisons use instants, so different timezone offsets can denote equality. Invalid filter inputs fail the operation. A document with a missing, non-string, or invalid timestamp does not match. All supplied filters must match.

type DeleteResult

type DeleteResult struct {
	// ID is the stored ID of the removed document.
	ID string `json:"id"`
}

DeleteResult identifies the document that was permanently removed.

type Description

type Description struct {
	// Hash is lowercase hexadecimal SHA-256 of all MEANS.md bytes in the
	// snapshot. SetInstructions requires this hash, not a document's hash.
	Hash string `json:"hash"`
	// Title is the trimmed configuration title, or the directory name if blank.
	Title string `json:"title"`
	// Description is the trimmed configuration description, or empty if omitted.
	Description string `json:"description"`
	// Instructions is the exact Markdown body of MEANS.md, without frontmatter.
	Instructions string `json:"instructions"`
}

Description gives consumers the collection identity, exact Markdown guidance, and SHA-256 hash of the complete configuration snapshot.

type Diagnostic

type Diagnostic struct {
	// ID is empty when the file has no readable document ID. Cache warnings may
	// identify an orphaned vector whose document no longer exists.
	ID string `json:"id"`
	// Path is relative to the collection directory, including cache paths.
	Path string `json:"path"`
	// Error is a human-readable explanation, not a stable programmatic code.
	Error string `json:"error"`
}

Diagnostic identifies one problem with a stored document. Path is relative to the collection so files without a readable ID can still be located.

type DoctorResult

type DoctorResult struct {
	// Healthy is true when no document diagnostics were found. Warnings do not
	// affect it; fatal filesystem or cache-read failures return an error instead.
	Healthy bool `json:"healthy"`
	// Checked counts visible document files, including malformed files and
	// duplicate occurrences. Hidden paths, symlinks, and nested collections are
	// excluded, as is MEANS.md.
	Checked int `json:"checked"`
	// Diagnostics reports malformed envelopes, duplicate IDs, and data that
	// does not satisfy the loaded schema.
	Diagnostics []Diagnostic `json:"diagnostics"`
	// Warnings reports missing, stale, orphaned, corrupt, or incompatible
	// embedding caches when embeddings are enabled. Doctor does not repair them
	// or call the embedding provider; use Embed to refresh vectors.
	Warnings []Diagnostic `json:"warnings,omitempty"`
}

DoctorResult reports document health independently of embedding cache warnings. A completed check can return a nil error while Healthy is false.

type Document

type Document struct {
	// ID is the immutable stored ID, independent of the filename.
	ID string `json:"id"`
	// Hash is lowercase hexadecimal SHA-256 of the exact stored bytes. Supply
	// it with ID to Update, ReplaceMarkdown, or Delete.
	Hash string `json:"hash"`
	// Frontmatter contains means-owned id/title and an application data object.
	// Parsed numbers use json.Number; objects and arrays use map[string]any and
	// []any. Only data is checked against the collection schema.
	Frontmatter map[string]any `json:"frontmatter"`
	// Body is the exact Markdown body after the YAML frontmatter.
	Body string `json:"body"`
	// Markdown is the complete source, including frontmatter. JSON omits it.
	Markdown string `json:"-"`
	// contains filtered or unexported fields
}

Document is a complete stored document. Read, Create, Update, and ReplaceMarkdown return its exact source and hash. Changing this value does not change the stored file; use Update or ReplaceMarkdown to save changes.

type DocumentSummary

type DocumentSummary struct {
	// Body is nil unless bodies were requested. A non-nil empty string is an
	// empty body. Embed includes bodies in its result.
	Body *string `json:"body,omitempty"`
	// ID is the stored document ID, independent of its filename.
	ID string `json:"id"`
	// Frontmatter has the same id, title, and data representation as Document.
	Frontmatter map[string]any `json:"frontmatter"`
}

DocumentSummary is a list or embed result without a content hash. Read the document by ID before updating or deleting it.

type EmbedOptions

type EmbedOptions struct {
	// Force clears cached vectors before regenerating all valid visible
	// documents. This can incur fresh API charges. If rebuilding fails, only
	// batches completed in this run remain; a normal Embed call resumes them.
	Force bool
}

EmbedOptions controls an explicit embedding cache refresh.

type EmbeddingConfig

type EmbeddingConfig struct {
	// Provider is required: "openai" or "openrouter".
	Provider string `json:"provider"`
	// Model is text-embedding-3-small or text-embedding-3-large, with the openai/
	// prefix required for OpenRouter. Empty selects the provider's small model.
	Model string `json:"model"`
	// Dimensions is the vector size: 1–1536 for the small model, or 1–3072 for
	// the large model. Zero selects 512.
	Dimensions int `json:"dimensions"`
}

EmbeddingConfig opts the host into network-backed embedding maintenance. Attach it through Collection.WithEmbeddings. Creation and title/body updates can call the provider and fail before writing the document; data-only edits reuse unchanged valid vectors. Collection.Embed also backfills directly edited files.

Credentials come from OPENAI_API_KEY for provider "openai" and OPENROUTER_API_KEY for "openrouter". A nonempty MEANS_EMBEDDING_API_KEY overrides either. Keys never fall back across providers. Requests use https://api.openai.com/v1 or https://openrouter.ai/api/v1 by provider; a nonempty MEANS_EMBEDDING_BASE_URL overrides the base URL (before /embeddings). The override must be HTTP(S) without user credentials, a query, or a fragment. The host must load any .env files itself; network operations read the process environment when they run. These settings do not change MEANS.md or user config.

func (EmbeddingConfig) WithDefaults

func (cfg EmbeddingConfig) WithDefaults() (EmbeddingConfig, error)

WithDefaults returns validated settings without changing the receiver. Provider is required. Empty Model selects text-embedding-3-small (with the openai/ prefix for OpenRouter); zero Dimensions selects 512.

Example
package main

import (
	"fmt"

	"github.com/hmans/means/collection"
)

func main() {
	settings, err := (collection.EmbeddingConfig{Provider: "openrouter"}).WithDefaults()
	if err != nil {
		panic(err)
	}
	// This validates settings without network access. WithEmbeddings attaches
	// them to a collection; set OPENROUTER_API_KEY before requests need vectors.
	fmt.Println(settings.Model, settings.Dimensions)
}
Output:
openai/text-embedding-3-small 512

type ListOptions

type ListOptions struct {
	// Filter partially matches application data, using SearchOptions.Filter rules.
	Filter map[string]any
	// DateTime ANDs timestamp comparisons with Filter.
	DateTime []DateTimeFilter
	// Offset skips valid matches before Limit. It must not be negative.
	Offset int
	// Limit caps the page size. Zero returns all remaining matches; negative
	// values fail. Changes between calls can shift pages; there is no cursor.
	Limit int
	// WithBody includes exact bodies. False leaves DocumentSummary.Body nil.
	WithBody bool
}

ListOptions filters and pages valid documents in relative filename order. Its zero value returns every valid document without bodies. Filters apply before Offset and Limit; malformed and duplicate files never consume a slot.

type ListResult

type ListResult struct {
	// Documents contains valid documents in relative filename order.
	Documents []DocumentSummary `json:"documents"`
	// Diagnostics covers the whole collection, regardless of filters or paging.
	Diagnostics []Diagnostic `json:"diagnostics"`
	// HasMore reports valid matches after the requested page. It is false when
	// Limit is zero and for Embed results.
	HasMore bool `json:"has_more"`
}

ListResult separates valid documents from malformed or duplicate files. A nil error from List or Embed does not imply that Diagnostics is empty.

type Patch

type Patch struct {
	// Frontmatter may contain title and/or data, but never id or custom top-level
	// fields. Objects merge recursively, null deletes keys, and arrays replace.
	// Nil leaves metadata unchanged; removing required fields fails validation.
	// JSON-compatible Go values are normalized without changing the input map.
	Frontmatter map[string]any
	// Body replaces the complete UTF-8 Markdown body. Nil leaves it unchanged;
	// a pointer to an empty string clears it.
	Body *string
}

Patch merges supplied metadata recursively (null deletes, arrays replace). A nil Frontmatter or Body leaves that portion of the document unchanged.

type SchemaSetResult

type SchemaSetResult struct {
	// Installed is false when document diagnostics rejected the schema.
	// When true, the file was replaced; existing Collection snapshots are unchanged.
	Installed bool `json:"installed"`
	// DoctorResult checks documents against the proposed schema, including when
	// installation was refused. Force can install with Healthy false.
	*DoctorResult
}

SchemaSetResult reports the document check, including when installation is refused.

func SetSchema

func SetSchema(ctx context.Context, path string, schema []byte, force bool) (*SchemaSetResult, error)

SetSchema validates and installs a schema in an existing collection. The old schema may be invalid. Force bypasses document diagnostics only. Checks are optimistic: concurrent edits can race validation and the final replacement. Schema must be a self-contained JSON Schema object or boolean in JSON bytes; Draft 2020-12 is the default. Malformed YAML in MEANS.md cannot be repaired here. If document checks reject installation, both a non-nil result with diagnostics and ErrSchemaIncompatible are returned. Other failures return a nil result. Force never bypasses invalid schemas or filesystem failures. It does not migrate documents or prove compatibility for future data. Identity, views, workflow body bytes, and permissions are preserved; frontmatter can reformat. Call Load after installation to use the new schema in a Collection snapshot.

Example
package main

import (
	"context"
	"errors"
	"fmt"
	"os"

	"github.com/hmans/means/collection"
)

func main() {
	dir, err := os.MkdirTemp("", "means-example-*")
	if err != nil {
		panic(err)
	}
	defer os.RemoveAll(dir)
	c, err := collection.Init(dir, []byte(`true`))
	if err != nil {
		panic(err)
	}
	ctx := context.Background()
	if _, err := c.Create(ctx, collection.CreateOptions{Title: "Plan", Data: map[string]any{"status": "draft"}}); err != nil {
		panic(err)
	}
	result, err := collection.SetSchema(ctx, c.Path(), []byte(`{"required":["owner"]}`), false)
	if !errors.Is(err, collection.ErrSchemaIncompatible) {
		panic(fmt.Sprintf("expected schema rejection, got %v", err))
	}
	// Rejection returns diagnostics as well as an error, without changing MEANS.md.
	fmt.Printf("Schema rejected: %d document diagnostic\n", len(result.Diagnostics))

	compatible := []byte(`{"type":"object","properties":{"status":{"enum":["draft","ready"]}},"required":["status"]}`)
	result, err = collection.SetSchema(ctx, c.Path(), compatible, false)
	if err != nil {
		panic(err)
	}
	fmt.Println("Installed:", result.Installed)
	// Installation does not change c's snapshot. Reload before the next operation.
	c, err = collection.Load(c.Path())
	if err != nil {
		panic(err)
	}
	if err := c.ValidateData(map[string]any{"status": "draft"}); err != nil {
		panic(err)
	}
}
Output:
Schema rejected: 1 document diagnostic
Installed: true

type SearchHit

type SearchHit struct {
	// Body is nil unless WithBody was set. A non-nil empty string is an empty body.
	Body *string `json:"body,omitempty"`
	// ID is the stored document ID, independent of its filename.
	ID string `json:"id"`
	// Frontmatter contains id, title, and data. Numbers use json.Number.
	Frontmatter map[string]any `json:"frontmatter"`
	// Match is an excerpt for a full-text or literal query; otherwise nil.
	Match *SearchMatch `json:"match,omitempty"`
	// Score is cosine similarity for semantic search, from -1 to 1; otherwise
	// nil. Full-text ranking scores are not exposed.
	Score *float64 `json:"score,omitempty"`
}

SearchHit identifies one matching document without a content hash. Call Collection.Read with ID before updating or deleting the document.

type SearchMatch

type SearchMatch struct {
	// Field is "title" or "body".
	Field string `json:"field"`
	// Excerpt is nearby text, with whitespace collapsed and ellipses when cut.
	Excerpt string `json:"excerpt"`
}

SearchMatch contains a title or body excerpt for a text match. Data-only and semantic searches do not produce excerpts.

type SearchOptions

type SearchOptions struct {
	// DateTime compares timestamp strings under data; all comparisons must match.
	DateTime []DateTimeFilter

	// MinScore is an inclusive cosine threshold from -1 to 1. It requires
	// Semantic. Nil selects DefaultSemanticMinScore; a pointer to zero selects 0.
	MinScore *float64
	// WithBody includes exact Markdown bodies. False leaves SearchHit.Body nil.
	WithBody bool
	// Query searches title and body. By default, all lowercase Unicode tokens
	// must match; title matches rank higher. There is no query syntax, stemming,
	// or stop-word removal. Empty Query selects a data-only scan.
	Query string
	// Filter is a recursive partial match against frontmatter.data. Arrays match
	// completely, including objects inside arrays. Nil or empty means no filter.
	// JSON-compatible Go values are normalized without changing the input map.
	Filter map[string]any
	// Limit caps valid matches. Zero returns every match; negative values fail.
	Limit int
	// Literal selects a case-insensitive substring match in title or body,
	// ordered by filename. It cannot be combined with Semantic.
	Literal bool
	// Semantic ranks cached document vectors by cosine similarity. It requires
	// a nonblank Query and settings supplied through Collection.WithEmbeddings.
	// It can call the embedding provider for the query; missing or stale document
	// vectors are skipped. Use Collection.Embed to refresh those vectors.
	Semantic bool
	// contains filtered or unexported fields
}

SearchOptions selects a search mode and filters its results. The zero value lists every valid document in filename order. Filter and DateTime conditions are ANDed and apply before Limit in every mode.

type SearchResult

type SearchResult struct {
	// Documents contains matches in rank order, or filename order for scans.
	Documents []SearchHit `json:"documents"`
	// Diagnostics reports malformed documents and duplicate IDs across the
	// collection, independent of filters and Limit.
	Diagnostics []Diagnostic `json:"diagnostics"`
	// HasMore reports additional matches after filtering, score threshold, and
	// Limit. It is false for an unlimited search.
	HasMore bool `json:"has_more"`
}

SearchResult separates valid matches from document diagnostics. A nil error from Search does not imply that Diagnostics is empty.

type WatchEvent

type WatchEvent struct {
	// Err reports a watcher failure. Events can have been lost. The watcher
	// attempts to reconcile directory watches and continues until cancellation.
	Err error
}

WatchEvent invalidates a collection snapshot. Reload configuration and documents after each event, including events with an error.

Jump to

Keyboard shortcuts

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