csf

package
v0.1.3 Latest Latest
Warning

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

Go to latest
Published: Oct 1, 2026 License: Apache-2.0 Imports: 77 Imported by: 0

README

One Go runtime. Agent work, typed tools, shared knowledge, observable experiments.

Developer preview. The first release makes no stability or compatibility promise.

Try the library · Workbench · Agent-native onboarding · Proofs · Add your code · Agent instructions · Examples · Terms · Citation


1. Introduction

CSF — The Cerebrospinal Fluid — is the library and runtime at the centre of this repository: one Go process that composes agent sessions, typed tools, knowledge and experiment evidence around a brain and a spine. The repository front page is the overview; this page is the library's own technical guide.

CSF's first release, 0.1.0, is a developer preview. It makes no stability or compatibility promise beyond what this page states. This is a breaking integration baseline. Pin a reviewed snapshot and use the examples shipped with it. The public Go import is github.com/candacelabs/csf/csf; this release does not introduce a /v2 module or claim backward compatibility for earlier experimental CSF interfaces.

Work Knowledge Evidence
Sessions, worktrees, schedules, and a shared Workbench Typed tools, ingestion, and configured search Traces, experiment results, and retained receipts

The brain proposes. The spine executes admitted behavior. CSF supplies the contracts and coordination that let each experiment inform the next decision.

2. Why Go: no IPC inside LITHE's CPU 0 (Housekeeping)

Figure 2 from Lim and Clites (2026) [1], arXiv:2603.07442. © the authors. Architecture inspiration: CSF coordinates the work, knowledge, and evidence around the brain and spine.

LITHE (Lim and Clites, 2026) names CPU 0 (Housekeeping) (LITHE §III-B) and treats inter-process communication (IPC) as an architectural concern (LITHE §III-C). CSF applies that framing to the coordination work inside the housekeeping layer: tools, sessions, schedules, knowledge and observation.

CSF prevents the avoidable IPC problem within this layer by composing those capabilities in one Go process. Services are Go libraries selected with functional options. They exchange typed values through function calls and coordinate concurrent work with goroutines and channels. An internal handoff needs no socket, wire serialization or separate service daemon. Go's concurrency primitives let waiting on tools, storage and model calls coexist in the same runtime; contexts and explicit ownership give each operation a cancellation and cleanup path. The consumer example shows that composition.

PostgreSQL, OpenSearch, Langfuse and external model or simulator processes keep their protocol boundaries. LITHE's Brain–Spine shared-memory IPC remains a separate integration boundary. The CPU 0 mapping describes CSF's role; CPU affinity and isolation require deployment configuration.

The repository front page draws this as a CPU 0 mapping diagram, with the same boundaries.

3. Agent-native onboarding

CSF is intended to be agent-native. Alongside human-readable READMEs, it exposes an MCP server. The goal is a self-changeable MCP surface that an agent can learn, configure and extend for the consumer repository.

The intended first instruction to your agent is “Learn about CSF.” The LearnAboutCSF operation explains the pinned version's capabilities and extension points and submits the embedded guidance plus selected consumer files to the configured knowledge capability. Its first call needs no arguments. Set CSF_CONSUMER_ROOT to authorize a checkout, then select relative source paths in batches of up to 64. The response carries durable ingestion receipts with revisions and content hashes; queued receipts become searchable when the existing projection workers finish. Repeating the call is idempotent and retrieves matching indexed sources. Without knowledge configuration, the tool still explains CSF and reports that indexing is unavailable. See the configuration contract; library hosts use WithOnboarding for the same source authorization.

Copilot CLI history is an explicit opt-in source. Set CSF_COPILOT_HISTORY_SOURCE to a native history directory that the host is authorized to read; startup copies that directory into a disposable SDK home, and the live source is never opened by onboarding. Select at most 16 session IDs with copilot_session_ids in LearnAboutCSF. An empty first call does not read history. When the source is configured, the same MCP server exposes ListCopilotHistorySessions; list IDs there, then pass selected IDs to onboarding. Library hosts can call the bridge's typed ListHistorySessions method directly. Each retained document is a decoded SDK snapshot containing metadata and events. Its receipt is queued until projection workers index it, and only then can retrieval return it. The SDK transport fixture verifies resume, typed event reads and disconnect. Native acceptance with Copilot CLI 1.0.85 and SDK 1.0.11 also reads a persisted synthetic conversation without changing its source or making another model request. Real PostgreSQL/OpenSearch acceptance verifies retained history reaches the lexical search index. User history is not part of those fixtures. It guides the agent through this workflow:

  1. Inspect the consumer repository and identify tooling CSF can take over.
  2. Adopt CSF through its Bazel dependency, required environment settings and optional capabilities, keeping consumer integration code minimal.
  3. Extend that same MCP server with the consumer's own tools: define their contracts, implement their behavior and expose them alongside CSF's tools.
  4. Discover and call the resulting tools, run the consumer's checks and retain evidence that the integration works.

The aim is broad, mostly implicit dependence on CSF: it handles more underneath the consumer, and improvements arrive through CSF upgrades with minimal changes to consumer code. The agent can continue adapting its integration and adding tools as the repository's needs change.

Current status: the MCP server, agent configuration tools, typed consumer registration (WithMCPTool[In, Out]) and the onboarding operation exist. Consumer registration uses the pinned MCP SDK to derive and validate schemas, and rejects name collisions with CSF operations. The host still owns listener startup, authentication, repository authorization and consumer checks.

4. Proofs, not just hardware

LITHE bounds a model-written controller with hardware: its user-space real-time design "lacks the formal mathematical guarantees of a verified real-time operating system" (LITHE §V-A), and where control theory is unvalidated, "safety must be enforced via strict hardware-level limits on torque and velocity" (LITHE §V-C). CSF's direction is the complementary guarantee: a typed, bounded controller language whose compiled code is proved to compute what its source says, so a model chooses among checked options instead of emitting arbitrary code.

examples/proof/BrainSpine.lean models the arithmetic slice of brainspine.proto and machine-checks four theorems about that bounded model:

Theorem Guarantee
compile_correct For every expression, inputs and existing stack, the compiled instructions push exactly the evaluated value and preserve the stack.
evaluate_bounds Every expression evaluates within the numeric saturation bound.
compiled_actuator_correct Compiled code run from an empty stack, then through the actuator clamp, agrees exactly with the clamped source evaluator.
compiled_actuator_bounds Every compiled expression produces an actuator value in [-1000, 1000].

bash csf/examples/proof/check.sh runs the pinned Lean release with --trust=0 and admits only Lean's standard propext, Classical.choice and Quot.sound axioms. What is not proved: agreement between the Lean model and the canonical wire semantics (a reviewed translation boundary), equivalence of the native Go and Rust evaluators (conformance tests only), and csfc itself — its Lean verifier is a stub that returns notImplemented. The actuator clamp proves a numeric range only; timing, stability, collision avoidance, safe controller switching and physical safety remain outside every theorem.

5. System diagrams

These diagrams are generated, not hand-maintained. The shared architecture model also produces the human dictionary; its syntax is specified in EBNF. The OCaml documentation compiler checks identifiers, references and the declared graph before rendering. Separate architecture checks inspect selected Go ownership/process boundaries. These checks establish their stated source constraints, not runtime timing or physical safety.

Solid connections are existing components or configurable integrations. Dotted connections are planned. An integration shown here still needs its dependencies and configuration; it is not automatically running when you import CSF.

%% Generated from csf/compiler/language/architecture.csf; do not edit.
%% Documentation model only; status labels do not establish runtime verification.
flowchart TB
  classDef csf_existing fill:#0F766E,stroke:#115E59,stroke-width:2px,color:#FFFFFF;
  classDef csf_planned fill:#FEF3C7,stroke:#B45309,stroke-width:2px,color:#78350F;
  n_human["Human or agent client (existing)"]:::csf_existing
  n_brain["Models and agents (existing)"]:::csf_existing
  n_contracts["Shared typed contracts (existing)"]:::csf_existing
  n_stores["PostgreSQL and artifact storage (existing)"]:::csf_existing
  n_jobs["Simulator and AWS Batch adapters (existing)"]:::csf_existing
  n_views["Prometheus#44; Grafana and Langfuse (existing)"]:::csf_existing
  n_experiments["Training results and optional MLflow (existing)"]:::csf_existing
  n_vendor["Consumer Copilot backend (existing)"]:::csf_existing
  n_spine["Consumer C#43;#43; control loop (planned)"]:::csf_planned
  n_hardware["Consumer sensors and actuators (planned)"]:::csf_planned
  subgraph g_host["CSF#58; one Go application process"]
    n_bench["Workbench (existing)"]:::csf_existing
    n_api["Generated HTTP#44; CLI and MCP operations (existing)"]:::csf_existing
    n_knowledge["Knowledge and retrieval (existing)"]:::csf_existing
    n_compiler["Bounded controller compiler (existing)"]:::csf_existing
    n_workers["Configured worker goroutines (existing)"]:::csf_existing
    n_inspect["Inspection (existing)"]:::csf_existing
    n_widgets["Widget SDK and gotth#45;live (existing)"]:::csf_existing
  end
  style g_host fill:#EEF2FF,stroke:#4338CA,stroke-width:2px,color:#1E1B4B
  n_human --> n_bench
  n_brain --> n_api
  n_contracts --> n_api
  n_bench --> n_api
  n_bench --> n_vendor
  n_api --> n_knowledge
  n_api --> n_compiler
  n_api --> n_workers
  n_api --> n_inspect
  n_knowledge --> n_stores
  n_workers --> n_jobs
  n_jobs --> n_stores
  n_inspect --> n_views
  n_brain --> n_experiments
  n_widgets -->|"keyed Kanban cards"| n_bench
  n_compiler -.->|"planned external adapter"| n_spine
  n_spine -.-> n_hardware
  linkStyle 0 stroke:#0F766E,stroke-width:2px
  linkStyle 1 stroke:#0F766E,stroke-width:2px
  linkStyle 2 stroke:#0F766E,stroke-width:2px
  linkStyle 3 stroke:#0F766E,stroke-width:2px
  linkStyle 4 stroke:#0F766E,stroke-width:2px
  linkStyle 5 stroke:#0F766E,stroke-width:2px
  linkStyle 6 stroke:#0F766E,stroke-width:2px
  linkStyle 7 stroke:#0F766E,stroke-width:2px
  linkStyle 8 stroke:#0F766E,stroke-width:2px
  linkStyle 9 stroke:#0F766E,stroke-width:2px
  linkStyle 10 stroke:#0F766E,stroke-width:2px
  linkStyle 11 stroke:#0F766E,stroke-width:2px
  linkStyle 12 stroke:#0F766E,stroke-width:2px
  linkStyle 13 stroke:#0F766E,stroke-width:2px
  linkStyle 14 stroke:#0F766E,stroke-width:2px
  linkStyle 15 stroke:#B45309,stroke-width:2px,stroke-dasharray:5 5
  linkStyle 16 stroke:#B45309,stroke-width:2px,stroke-dasharray:5 5
%% Generated from csf/compiler/language/architecture.csf; do not edit.
%% Documentation model only; status labels do not establish runtime verification.
flowchart LR
  classDef csf_existing fill:#0F766E,stroke:#115E59,stroke-width:2px,color:#FFFFFF;
  classDef csf_planned fill:#FEF3C7,stroke:#B45309,stroke-width:2px,color:#78350F;
  n_observe["Observe (existing)"]:::csf_existing
  n_retrieve["Retrieve (existing)"]:::csf_existing
  n_choose["Choose (planned)"]:::csf_planned
  n_check["Check (existing)"]:::csf_existing
  n_execute["Execute (existing)"]:::csf_existing
  n_evaluate["Evaluate (existing)"]:::csf_existing
  n_save_evidence["Save evidence (existing)"]:::csf_existing
  n_improve["Improve (planned)"]:::csf_planned
  n_select_controller["Select a controller between episodes (existing)"]:::csf_existing
  n_observe -.-> n_retrieve
  n_retrieve -.-> n_choose
  n_choose -.-> n_check
  n_check --> n_execute
  n_execute --> n_evaluate
  n_evaluate --> n_save_evidence
  n_evaluate --> n_select_controller
  n_select_controller -.->|"next agent iteration"| n_choose
  n_save_evidence -.-> n_improve
  n_improve -.->|"next iteration"| n_observe
  linkStyle 0 stroke:#B45309,stroke-width:2px,stroke-dasharray:5 5
  linkStyle 1 stroke:#B45309,stroke-width:2px,stroke-dasharray:5 5
  linkStyle 2 stroke:#B45309,stroke-width:2px,stroke-dasharray:5 5
  linkStyle 3 stroke:#0F766E,stroke-width:2px
  linkStyle 4 stroke:#0F766E,stroke-width:2px
  linkStyle 5 stroke:#0F766E,stroke-width:2px
  linkStyle 6 stroke:#0F766E,stroke-width:2px
  linkStyle 7 stroke:#B45309,stroke-width:2px,stroke-dasharray:5 5
  linkStyle 8 stroke:#B45309,stroke-width:2px,stroke-dasharray:5 5
  linkStyle 9 stroke:#B45309,stroke-width:2px,stroke-dasharray:5 5
%% Generated from csf/compiler/language/architecture.csf; do not edit.
%% Documentation model only; status labels do not establish runtime verification.
flowchart LR
  classDef csf_existing fill:#0F766E,stroke:#115E59,stroke-width:2px,color:#FFFFFF;
  classDef csf_planned fill:#FEF3C7,stroke:#B45309,stroke-width:2px,color:#78350F;
  n_submit["SubmitSimulation (existing)"]:::csf_existing
  n_admitted["Recorded simulation job (existing)"]:::csf_existing
  n_start_job["Start configured local profile (existing)"]:::csf_existing
  n_local_job["Simulator container (existing)"]:::csf_existing
  n_poll_job["Read simulator status#44; progress and logs (existing)"]:::csf_existing
  n_observations["Saved simulation observations (existing)"]:::csf_existing
  n_inspect_job["InspectSimulation (existing)"]:::csf_existing
  n_submit --> n_admitted
  n_admitted --> n_start_job
  n_start_job --> n_local_job
  n_local_job -->|"simulation steps and outputs"| n_poll_job
  n_poll_job --> n_observations
  n_poll_job -->|"continue while running"| n_local_job
  n_inspect_job -->|"read state and artifact references"| n_observations
  linkStyle 0 stroke:#0F766E,stroke-width:2px
  linkStyle 1 stroke:#0F766E,stroke-width:2px
  linkStyle 2 stroke:#0F766E,stroke-width:2px
  linkStyle 3 stroke:#0F766E,stroke-width:2px
  linkStyle 4 stroke:#0F766E,stroke-width:2px
  linkStyle 5 stroke:#0F766E,stroke-width:2px
  linkStyle 6 stroke:#0F766E,stroke-width:2px

6. The architecture for self-improving autonomy

The direction is a system that can inspect a result, propose a change, evaluate it against a fixed baseline, and retain the evidence for its next decision. Improvement is something to measure, not a consequence of adding an agent loop.

LITHE [1] separates best-effort reasoning, real-time control, transport, and housekeeping. Its CPU 0: Housekeeping box makes CSF's intended position concrete: coordinate tools, records, worker lifetimes and experiments around the brain and spine. That is our architectural mapping; CSF does not currently implement LITHE's loader, CPU isolation, or real-time controller hot swap.

Figure 1 from Lim and Clites (2026) [1], arXiv:2603.07442. © the authors.

Figures 2 and 1 are linked from the authors' paper, not copied. They illustrate LITHE, not measured CSF hardware behavior. Their authors retain ownership; CSF's source license does not relicense these externally hosted figures.

7. Try the library

Use Go 1.26. The smallest example needs no database, GPU, model account, or extra service process. From the public repository root:

go run ./examples/csf-theme --listen 127.0.0.1:8089 --theme-dir ./examples/csf-theme

That mounts the generated HTTP API and MCP at http://127.0.0.1:8089/mcp. It is an integration example, not the complete Workbench UI. Its essential implementation is:

service, err := csf.New(csf.WithWorkbenchThemeDirectory(themeDirectory))
if err != nil {
    return err
}
router := httpserver.NewEngine("consumer")
service.Register(router)
router.Any("/mcp", gin.WrapH(service.MCPHandler()))
return httpserver.Serve(ctx, httpserver.NewStreamingServer(address, router))

The service registers its generated HTTP routes and provides the MCP handler; the caller owns the HTTP server, listener and cancellation. Place your CSS in workbench-theme.css inside the configured directory; ReloadWorkbenchTheme reloads that fixed file through the same generated API. A missing file restores the built-in appearance. No arbitrary file path is accepted from a tool caller.

For your own repository, start with the complete consumer example and extension guide. The example adds a custom Go endpoint beside CSF, uses its generated client, discovers MCP tools, reloads a theme, and tests shutdown. The archive acceptance script creates a fresh Git repository, vendors dependencies, then tests/builds with networking disabled.

bash examples/csf-consumer/test-archive.sh /path/to/csf-snapshot.tar.gz /tmp/csf-consumer-check

For Bazel consumers, use the public repository's archive instructions and depend on @csf//csf. Building that library does not start a host or database.

8. Run the Workbench

For native deployment, the optional dependency package builds selected PostgreSQL, OpenSearch, and Langfuse dependencies as independent systemd services. Langfuse uses ClickHouse and Redis; AWS S3 is its default object store. A credential or bucket-access failure offers an explicit MinIO opt-in that describes the local service, ports, and storage.

The supplied composition combines the CSF API, MCP, inspection, Workbench and configured workers in one Go application process. Application means a process-owning runnable composition; service means its owned lifecycle component. Widgets exist inside gotth-live, CSF's web layer. A widget is not a separate application.

Build the host and the Workbench browser assets from the public repository root:

go build -trimpath -o out/csf ./app/csf/cmd
npm --prefix services/copilot-adapter/ui ci
npm --prefix services/copilot-adapter/ui run build

The runtime image recipe packages the same host and UI with Git LFS and the pinned Copilot CLI. From the public repository root:

docker build -f app/csf/Dockerfile -t csf:local .
bash app/csf/test-image.sh csf:local

The image runs as the node user and contains /app/candace-runtime and /app/workbench-ui. Its acceptance check exercises a local Git LFS worktree checkout and HTTP startup without provider credentials. Mount the private configuration, repository and writable worktree directory when configuring a Workbench deployment; the image does not provide a database or credentials.

The full Workbench uses your PostgreSQL database and a configured Copilot backend. Create a private JSON file with {"url":"postgres://..."} and configure an existing repository and worktree directory. Keep credentials out of Git.

./out/csf serve \
  --listen 127.0.0.1:14111 --origin http://127.0.0.1:14111 \
  --workbench-database-config /absolute/private/workbench-db.json \
  --workbench-repository /absolute/consumer-repository \
  --workbench-worktrees /absolute/consumer-worktrees \
  --workbench-ui ./services/copilot-adapter/ui/dist \
  --workbench-theme-dir /absolute/theme-directory

Open http://127.0.0.1:14111/ui/. The MCP endpoint is http://127.0.0.1:14111/mcp. The Workbench composition accepts a caller-supplied database and backend, and has an explicit Close. The Copilot bridge is a deliberate external backend boundary; it does not turn the model execution loop into an embedded Go implementation.

For your own composition, follow the runnable CSF host and Workbench lifecycle. After constructing the Workbench with its database, bridge, repository and worktree directory, call Register(router) and start the HTTP/MCP listener before calling Restore(ctx): restored sessions may connect to that MCP endpoint. Workbench API routes return 503 until restoration succeeds. Then run Adapter.RunSchedules(ctx) under the host's cancellation context. On shutdown, call Close(ctx) with a bounded context before closing the bridge and database.

Discover capabilities from MCP tools/list rather than copying operation names into a second schema. The optional JSON CLI uses the same generated contract:

printf '%s\n' '{}' | ./out/csf call --endpoint http://127.0.0.1:14111 GetSnapshot

9. Examples and boundaries

Component Example and implementation What the consumer supplies
Mounting and custom Go Consumer, source: mount CSF and add /consumer/snapshot HTTP lifecycle and intended access policy
Theme configuration Theme, source: csf.WithWorkbenchThemeDirectory(directory) The fixed workbench-theme.css file
Agent assignment Agent example, source: typed profile and session assignment A compatible backend; complete context management remains future work
Knowledge Ingestion, source: python3 .../daily_papers.py fetch --date YYYY-MM-DD --out /new/snapshot Source documents; persistence and a model for semantic search
CPU controller search Driving experiment, source: uv run --locked python train.py --runtime /path/to/csf --output /new/run Python environment and fixed evaluation seeds; this is numerical search, not neural training
CARLA / Isaac Sim Workers, source: SubmitSimulation then InspectSimulation Vendor images, GPU, configured execution/artifact policy
AWS Batch Configuration, job example: choose SIMULATION_EXECUTOR_AWS_BATCH Account, roles, queue, job definitions, budget and S3; real AWS acceptance remains pending
Formal arithmetic model Lean proof, source: bash csf/examples/proof/check.sh Pinned Lean download; theorem covers its bounded model, not the Go runtime or robot safety
Independent interpreter Rust conformance, source: cargo test --locked --manifest-path csf/examples/rust/Cargo.toml Rust toolchain; finite conformance tests are not language equivalence proofs

Neural training, ROS recording, perception, cross-simulator equivalence, and physical robot safety remain consumer work. See the simulator integration contract for required interfaces and evidence. A configured tool is not evidence that a job ran.

10. Contracts and release evidence

csfc is CSF's architecture compiler, with its own pinned OCaml build and executable under bin/. Its Lean verifier currently provides a compiling stub that returns notImplemented; it does not certify compiler output.

The architecture model generates the diagrams and human dictionary, using the declared grammar. The documentation compiler checks identifiers, references, and the graph; separate architecture checks inspect selected Go ownership/process boundaries. These establish source constraints, not runtime timing or physical safety.

brainspine.proto and the annotated API own the wire messages and operations. Generated Go, Python, OpenAPI, HTTP, CLI and MCP projections share those sources. Upstream generators keep their own filenames; Candace-generated output uses _cgen where it does not conflict with the upstream convention.

bash proto/generate.sh check
bash csf/tools/codegen/generate.sh check
go test ./csf/... ./services/copilot-adapter/... ./examples/csf-consumer

The public repository snapshot carries .candace-export.json; its downloadable source archive carries .candace-source.json with the source revision and tree. The public publisher proposes each snapshot in a ready PR against main. After that PR is merged, the publisher verifies the approved tree before tagging it and attaching its reproducible archive. An open snapshot PR is a release candidate, not a published release tag. Keep archive hashes, source revision, test receipts and any deployment receipt separate. Generated-code and generated-documentation percentages are separate measurements; neither is a proof coverage score.

11. Citation

[1] He Kai Lim and Tyler R. Clites. LITHE: Bridging Best-Effort Python and Real-Time C++ for Hot-Swapping Robotic Control Laws on Commodity Linux. arXiv:2603.07442 [cs.RO], 2026. Submitted to IROS 2026. https://doi.org/10.48550/arXiv.2603.07442

@misc{lim2026lithe,
  title         = {{LITHE}: Bridging Best-Effort {Python} and Real-Time {C++} for Hot-Swapping Robotic Control Laws on Commodity {Linux}},
  author        = {Lim, He Kai and Clites, Tyler R.},
  year          = {2026},
  eprint        = {2603.07442},
  archivePrefix = {arXiv},
  primaryClass  = {cs.RO},
  doi           = {10.48550/arXiv.2603.07442},
  url           = {https://arxiv.org/abs/2603.07442},
  note          = {Submitted to IROS 2026}
}

CSF's architecture is inspired by LITHE [1]. To cite CSF itself, name the exact release tag you used:

@software{csf2026,
  title   = {CSF — The Cerebrospinal Fluid},
  author  = {{Candace Labs}},
  version = {0.1.0},
  year    = {2026},
  url     = {https://github.com/candacelabs/csf}
}

The LITHE paper and its figures are distributed under arXiv's non-exclusive distribution license, not a Creative Commons license. © the authors; this repository's license does not cover them, and no figure file is copied into it.

License

Apache License 2.0. See LICENSE.

Documentation

Overview

Code generated by Candacegen (csf/compiler/api_codegen). DO NOT EDIT.

Package csf composes the research controller compiler and runtime in one Go process. It makes no hard-real-time or physical-safety guarantee.

Code generated by Candacegen from the pinned OpenSearch SDK using ifacemaker; DO NOT EDIT.

Index

Constants

View Source
const (
	// AgentMCPAuthorizationHeader carries a session-bound credential for an agent MCP request.
	AgentMCPAuthorizationHeader = "Authorization"
	// AgentMCPAgentIDHeader identifies the agent making an authenticated MCP request.
	AgentMCPAgentIDHeader = "X-CSF-Agent-ID"
	// AgentMCPSessionIDHeader identifies the agent session making an authenticated MCP request.
	AgentMCPSessionIDHeader = "X-CSF-Session-ID"
)
View Source
const (
	SchemaVersion    = 1
	Scale            = int64(1000)
	ValueLimit       = int64(1000000000)
	CoefficientLimit = int64(1000000)
	FeatureLimit     = int64(10000)
	FeatureCount     = 4
	MaxInstructions  = 128
	MaxDepth         = 16
	MaxAgeTicks      = uint64(3)
)
View Source
const (
	SnapshotPath = "/api/snapshot"
	CompilePath  = "/api/compile"
)
View Source
const (
	ChangeCreated  = "created"
	ChangeModified = "modified"
	ChangeDeleted  = "deleted"
)
View Source
const (
	WatchRegistryID = "brainspine.source-checks.v1"
)
View Source
const WorkbenchThemeFileName = "workbench-theme.css"

WorkbenchThemeFileName is the only stylesheet the theme capability reads.

Variables

View Source
var (
	ErrInvalidRequest                = errors.New("invalid request")
	ErrUnauthorized                  = errors.New("agent identity is required")
	ErrNotFound                      = errors.New("not found")
	ErrConflict                      = errors.New("revision conflict")
	ErrAgentConfigurationUnavailable = errors.New("agent configuration capability unavailable")
	ErrMCPToolConflict               = errors.New("MCP tool name already registered")
	ErrInvalidMCPTool                = errors.New("invalid MCP tool registration")
)

Input, identity and revision errors are stable transport classifications. Backend and encoding failures remain server errors at the HTTP boundary.

View Source
var ErrEmailUnavailable = errors.New("operator email is not configured")

Functions

func CLIOperations

func CLIOperations() []string

func CheckSourceSnapshot

func CheckSourceSnapshot(ctx context.Context, request CheckRequest) (*pb.CommandReceipt, error)

CheckSourceSnapshot returns a generated receipt for the bounded registry. Command identifies an in-process invocation, never a shell execution.

func Compile

func Compile(controller *brainspinev1.Controller) (*brainspinev1.Program, error)

Compile rejects unsupported expressions before creating a bounded program. Deterministic protobuf is used only for this map-free, unknown-field-free versioned contract. This is not a universal canonical protobuf encoding.

func Evaluate

func Evaluate(program *brainspinev1.Program, features []int64) (*brainspinev1.Action, error)

Evaluate interprets the compiled program with bounded integer arithmetic. Multiplication cannot overflow int64: |stack value| <= 1e9 and |gain| <= 1e6.

func ImportantSourcePaths

func ImportantSourcePaths() []string

ImportantSourcePaths is a fresh explicit allowlist, never a recursive scan.

func PrepareAgentAssignment

func PrepareAgentAssignment(recipe *pb.AgentAssignmentRecipe) (*pb.AgentAssignmentPlan, error)

PrepareAgentAssignment freezes a recipe into an independently owned plan. Retry keys depend on assignment identity, not content: editing an already submitted recipe must conflict with Workbench's existing idempotency receipt.

func SubmitAgentAssignmentHTTP

func SubmitAgentAssignmentHTTP(ctx context.Context, client *api.ClientWithResponses, endpoint string, plan *pb.AgentAssignmentPlan) (*pb.AgentAssignmentReceipt, error)

SubmitAgentAssignmentHTTP is a consumer-side example of executing a plan through the existing generated Workbench client. Hosts composing in process can pass NewAgentWorkbenchRequests directly to their adapter instead. A partial receipt is returned if session creation succeeds but prompt acceptance is unconfirmed. Retry the original plan to recover its identities.

Types

type AgentMCPAuthenticator

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

AgentMCPAuthenticator signs and verifies identity-bound session credentials for CSF's protected streamable MCP route. Its signing key stays with the host.

func NewAgentMCPAuthenticator

func NewAgentMCPAuthenticator(key []byte) (*AgentMCPAuthenticator, error)

NewAgentMCPAuthenticator creates an authenticator from one caller-owned signing key. Credentials remain valid for their identity tuple until key rotation.

func (*AgentMCPAuthenticator) AgentMCPHeaders

func (authenticator *AgentMCPAuthenticator) AgentMCPHeaders(agentID string, sessionID string) (http.Header, error)

AgentMCPHeaders returns the complete bearer and identity headers for one validated agent session without disclosing the signing key. It is intended for the trusted local in-process bridge, not for untrusted callers to mint identities.

type AgentWorkbenchRequests

type AgentWorkbenchRequests struct {
	Session api.CreateSessionJSONRequestBody
	Prompt  api.SubmitPromptJSONRequestBody
}

AgentWorkbenchRequests uses the Workbench's generated request types. This translation is the sole boundary between CSF recipes and its current backend.

func NewAgentWorkbenchRequests

func NewAgentWorkbenchRequests(plan *pb.AgentAssignmentPlan) (*AgentWorkbenchRequests, error)

NewAgentWorkbenchRequests verifies a prepared plan before translating it. The same keys safely replay session creation and prompt acceptance; retries never claim that a backend completed work whose result was not observed.

type Artifacts

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

Artifacts retains bytes under their SHA256. Writes never replace a blob.

func NewArtifacts

func NewArtifacts(directory string) (*Artifacts, error)

func (*Artifacts) Close

func (artifacts *Artifacts) Close() error

func (*Artifacts) Get

func (artifacts *Artifacts) Get(hash string) ([]byte, error)

func (*Artifacts) Put

func (artifacts *Artifacts) Put(content []byte) (string, string, error)

type Change

type Change struct{ Path, Kind string }

type CheckRequest

type CheckRequest struct {
	Changes []Change
	Files   []SourceFile
}

type Client

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

Client uses generated method signatures with protobuf's JSON codec.

func NewClient

func NewClient(endpoint string, transport IHTTPDoer) (*Client, error)

func (*Client) CallOperation

func (client *Client) CallOperation(ctx context.Context, operation string, input []byte) ([]byte, error)

func (*Client) CancelSimulation

func (client *Client) CancelSimulation(ctx context.Context, request *contract0.CancelSimulationRequest) (*contract0.CancelSimulationResponse, error)

func (*Client) Compile

func (client *Client) Compile(ctx context.Context, request *contract0.CompileRequest) (*contract0.CompileResponse, error)

func (*Client) GetDocument

func (client *Client) GetDocument(ctx context.Context, request *contract0.GetDocumentRequest) (*contract0.GetDocumentResponse, error)

func (*Client) GetGraph

func (client *Client) GetGraph(ctx context.Context, request *contract0.GetGraphRequest) (*contract0.GetGraphResponse, error)

func (*Client) GetSnapshot

func (client *Client) GetSnapshot(ctx context.Context, request *contract0.GetSnapshotRequest) (*contract0.GetSnapshotResponse, error)

func (*Client) GetWorkbenchTheme

func (*Client) IngestDocument

func (client *Client) IngestDocument(ctx context.Context, request *contract0.IngestDocumentRequest) (*contract0.IngestDocumentResponse, error)

func (*Client) InspectSimulation

func (*Client) LearnAboutCSF

func (client *Client) LearnAboutCSF(ctx context.Context, request *contract0.LearnAboutCSFRequest) (*contract0.LearnAboutCSFResponse, error)

func (*Client) ListSimulations

func (client *Client) ListSimulations(ctx context.Context, request *contract0.ListSimulationsRequest) (*contract0.ListSimulationsResponse, error)

func (*Client) PutEdge

func (client *Client) PutEdge(ctx context.Context, request *contract0.PutEdgeRequest) (*contract0.PutEdgeResponse, error)

func (*Client) PutNode

func (client *Client) PutNode(ctx context.Context, request *contract0.PutNodeRequest) (*contract0.PutNodeResponse, error)

func (*Client) ReadSimulationLogs

func (*Client) ReloadWorkbenchTheme

func (*Client) Search

func (client *Client) Search(ctx context.Context, request *contract0.SearchRequest) (*contract0.SearchResponse, error)

func (*Client) SendEmail

func (client *Client) SendEmail(ctx context.Context, request *contract1.SendEmailRequest) (*contract1.SendEmailResponse, error)

func (*Client) SubmitSimulation

func (client *Client) SubmitSimulation(ctx context.Context, request *contract0.SubmitSimulationRequest) (*contract0.SubmitSimulationResponse, error)

type CopilotHistoryReader

type CopilotHistoryReader func(ctx context.Context, sessionID string) (copilotbridge.HistorySnapshot, error)

CopilotHistoryReader reads one explicitly selected native Copilot session. The bridge owns SDK lifecycle, source isolation and typed event decoding.

type Dashboard

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

Dashboard observes one run's append-only artifact. It never owns the runtime.

func NewDashboard

func NewDashboard(eventPath string) *Dashboard

func (*Dashboard) Register

func (dashboard *Dashboard) Register(router gin.IRouter)

Register mounts the basic metric view; Service owns its generated APIs.

func (*Dashboard) Snapshot

func (dashboard *Dashboard) Snapshot() *brainspinev1.Snapshot

type EmailProvenance

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

EmailProvenance observes host-owned metadata at send time. It reads only the explicitly configured observer file, never a Docker socket or other sessions.

func NewEmailProvenance

func NewEmailProvenance(configuration *emailv1.EmailHostConfiguration, now func() time.Time) *EmailProvenance

func (*EmailProvenance) Snapshot

type FarmAgent

type FarmAgent struct {
	Name, Role, State, Task, Note, ObservedAt, SessionID, Worktree, TicketURL string
	Model, StartedAt, FinishedAt, Duration, DurationLabel                     string
	Tokens                                                                    *api.UsageObservation
	PremiumRequests                                                           *float64
}

These are the board's presentation inputs, not a second domain contract. Runtime/program/knowledge contracts remain in their generated protobufs.

type FarmAgentSource

type FarmAgentSource func(now time.Time) ([]FarmAgent, error)

FarmAgentSource supplies observed workers without owning another durable store.

type FarmCheck

type FarmCheck struct{ ID, Title, Status, Evidence string }

type FarmCheckpoint

type FarmCheckpoint struct {
	Title                string
	Items                []FarmCheck
	Done, Total, Percent int
}

type FarmDashboard

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

FarmDashboard mounts into an existing process. Observe owns publication and priority writes; sessions only consume immutable published views.

func NewFarmDashboard

func NewFarmDashboard(origins []string, options ...FarmOption) (*FarmDashboard, error)

func (*FarmDashboard) ActiveConnections

func (dashboard *FarmDashboard) ActiveConnections() int

ActiveConnections counts live board WebSockets, including connection cleanup. Workbench chat streams and terminal sockets have different owners and are excluded.

func (*FarmDashboard) Close

func (dashboard *FarmDashboard) Close(ctx context.Context) error

func (*FarmDashboard) Observe

func (dashboard *FarmDashboard) Observe(ctx context.Context)

Observe runs under the caller's process context; it owns no listener.

func (*FarmDashboard) Register

func (dashboard *FarmDashboard) Register(router gin.IRouter)

func (*FarmDashboard) RenderFarm

func (dashboard *FarmDashboard) RenderFarm() ([]byte, error)

RenderFarm is useful for deterministic page inspection without opening a listener.

func (*FarmDashboard) Snapshot

func (dashboard *FarmDashboard) Snapshot() FarmView

Snapshot returns the latest immutable view for sibling in-process mounts.

type FarmEvent

type FarmEvent struct{ At, Agent, Message, Evidence, Kind string }
type FarmLink struct{ Name, URL string }

type FarmOption

type FarmOption func(dashboard *FarmDashboard)

func WithFarmAgentSource

func WithFarmAgentSource(source FarmAgentSource) FarmOption

func WithFarmWorkPath

func WithFarmWorkPath(path string) FarmOption

type FarmScore

type FarmScore struct{ Label, Value, Scope string }

type FarmTask

type FarmTask struct{ ID, Title, Status, Detail, TicketURL string }

type FarmView

type FarmView struct {
	BrowserConnections                                                               int
	Title, Phase, UpdatedAt, Now, Uptime, Elapsed, StartedAt, Branch, TicketURL      string
	RuntimeCount, Goroutines, GoMaxProcs, HeapMiB, Containers, WorktreeCount         int
	ContainersObservedAt, WorktreesObservedAt, SourceError, AgentSourceError, Notice string
	Agents                                                                           []FarmAgent
	Tasks                                                                            []FarmTask
	Feed                                                                             []FarmEvent
	Scores                                                                           []FarmScore
	Operations                                                                       []HumanOperation
	DashboardLinks                                                                   []FarmLink
	Checkpoint                                                                       FarmCheckpoint
}

type HumanOperation

type HumanOperation struct{ Name, Description string }

func HumanOperations

func HumanOperations() []HumanOperation

type IAgentConfigurationStore

type IAgentConfigurationStore interface {
	GetAgentConfiguration(ctx context.Context, agentID string) (*pb.AgentConfiguration, error)
	PutAgentConfiguration(ctx context.Context, agentID string, expectedRevision uint32, configuration *pb.AgentConfigurationInput) (*pb.AgentConfiguration, error)
}

IAgentConfigurationStore retains one revisioned external-tool configuration per authenticated agent. It stores opaque secret references, never values.

type IBatch

type IBatch interface {
	SubmitJob(ctx context.Context, input *batch.SubmitJobInput, options ...func(options *batch.Options)) (*batch.SubmitJobOutput, error)
	DescribeJobs(ctx context.Context, input *batch.DescribeJobsInput, options ...func(options *batch.Options)) (*batch.DescribeJobsOutput, error)
	TerminateJob(ctx context.Context, input *batch.TerminateJobInput, options ...func(options *batch.Options)) (*batch.TerminateJobOutput, error)
}

IBatch is the consumer seam over the upstream generated AWS SDK.

type IDockerSimulations

IDockerSimulations consumes the upstream Docker Engine SDK, not a second orchestrator process. The application owns the socket and client lifetime.

type IEmailSender

type IEmailSender interface {
	Send(ctx context.Context, message *emailv1.EmailMessage) (*emailv1.EmailReceipt, error)
}

IEmailSender is the shared capability, not an SMTP implementation.

type IHTTPDoer

type IHTTPDoer interface {
	Do(request *http.Request) (*http.Response, error)
}

IHTTPDoer is the only network behavior the generated client consumes.

type IKnowledgeIndex

type IKnowledgeIndex interface {
	Index(ctx context.Context, document *pb.SourceDocument, text string) error
	Search(ctx context.Context, request *pb.SearchRequest) (*pb.SearchResult, error)
}

IKnowledgeIndex is a rebuildable projection, never the evidence authority.

type IKnowledgeStore

type IKnowledgeStore interface {
	PutDocument(ctx context.Context, document *pb.SourceDocument) (*pb.SourceDocument, error)
	GetDocument(ctx context.Context, request *pb.DocumentRequest) (*pb.SourceDocument, error)
	PutNode(ctx context.Context, node *pb.KnowledgeNode) (*pb.KnowledgeNode, error)
	PutEdge(ctx context.Context, edge *pb.KnowledgeEdge) (*pb.KnowledgeEdge, error)
	GetGraph(ctx context.Context, request *pb.GraphRequest) (*pb.GraphSnapshot, error)
	ClaimProjection(ctx context.Context) (*pb.ProjectionTask, error)
	CompleteProjection(ctx context.Context, task *pb.ProjectionTask) error
	FailProjection(ctx context.Context, task *pb.ProjectionTask, problem string) error
	GetProjection(ctx context.Context, request *pb.DocumentRequest) (*pb.ProjectionTask, error)
	CountProjections(ctx context.Context) ([]*pb.ProjectionCount, error)
}

IKnowledgeStore owns durable source identities and immutable symbolic facts.

type IOpenSearchClient

type IOpenSearchClient interface {
	Index(ctx context.Context, req opensearchapi.IndexReq) (*opensearchapi.IndexResp, error)
	Search(ctx context.Context, req *opensearchapi.SearchReq) (*opensearchapi.SearchResp, error)
}

IOpenSearchClient is the shared generated Index/Search contract.

type ISimulationLogs

type ISimulationLogs interface {
	GetLogEvents(ctx context.Context, input *cloudwatchlogs.GetLogEventsInput, options ...func(options *cloudwatchlogs.Options)) (*cloudwatchlogs.GetLogEventsOutput, error)
}

ISimulationLogs reads the job's CloudWatch stream without an inbound worker listener.

type ISimulationTraces

type ISimulationTraces interface {
	Start(ctx context.Context) error
	Stop(ctx context.Context) error
	UploadTraces(ctx context.Context, spans []*tracepb.ResourceSpans) error
}

type Inspection

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

Inspection mounts observations in the caller's router and registry. It owns no listener or background task. Receipts remain the event ledger; their retained counts are gauges because retention can remove records.

func NewInspection

func NewInspection(options ...InspectionOption) *Inspection

func (*Inspection) Collect

func (inspection *Inspection) Collect(output chan<- prometheus.Metric)

func (*Inspection) Describe

func (inspection *Inspection) Describe(output chan<- *prometheus.Desc)

func (*Inspection) Register

func (inspection *Inspection) Register(router gin.IRouter)

type InspectionOption

type InspectionOption func(inspection *Inspection)

func WithInspectionBrowserConnections

func WithInspectionBrowserConnections(source func() int) InspectionOption

WithInspectionBrowserConnections samples the live board's connection registry. Without a source the series is absent, rather than reporting a measured zero.

func WithInspectionProjectionWorkers

func WithInspectionProjectionWorkers(workers *ProjectionWorkers) InspectionOption

func WithInspectionReceipts

func WithInspectionReceipts(path string) InspectionOption

func WithInspectionRegistry

func WithInspectionRegistry(registry *prometheus.Registry) InspectionOption

WithInspectionRegistry shares the host's registry with optional capabilities. The host owns this registry and must not register Go/process collectors twice.

func WithInspectionSimulations

func WithInspectionSimulations(simulations *Simulations) InspectionOption

func WithInspectionSnapshot

func WithInspectionSnapshot(snapshot func() FarmView) InspectionOption

func WithInspectionTelemetry

func WithInspectionTelemetry(source func(ctx context.Context) (api.TelemetrySnapshot, error)) InspectionOption

type LocalSimulations

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

LocalSimulations is an optional capability of the shared host. It never owns a listener or a goroutine; Simulations.Work drives its bounded reconciliation.

func NewLocalSimulations

func NewLocalSimulations(docker IDockerSimulations, config *pb.LocalSimulationConfig) (*LocalSimulations, error)

type OnboardingConfig

type OnboardingConfig struct {
	CSFRoot          string
	CSFRevision      string
	ConsumerRoot     string
	ConsumerRevision string
	// CopilotHistoryReader is opt-in and reads from the bridge's disposable
	// native snapshot for explicitly selected session IDs.
	CopilotHistoryReader CopilotHistoryReader
}

OnboardingConfig is supplied by the host. ConsumerRoot is an explicitly authorized checkout; callers select relative paths within it. Empty CSFRoot uses the documentation embedded in this exact build. Omitted revisions use each document's content hash, so uncommitted edits retain distinct identities.

type OpenSearch

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

OpenSearch projects canonical documents using a configured ML Commons model. Empty model configuration means lexical search, explicitly labelled as such.

func ConnectOpenSearch

func ConnectOpenSearch(endpoint string, index string, model string, transport IHTTPDoer) (*OpenSearch, error)

ConnectOpenSearch owns a configured upstream SDK client until Close.

func NewOpenSearch

func NewOpenSearch(index string, model string, client IOpenSearchClient) (*OpenSearch, error)

NewOpenSearch composes the document projection with generated SDK contracts. The caller owns the supplied clients and their lifecycle.

func (*OpenSearch) Close

func (search *OpenSearch) Close() error

Close releases SDK background resources without closing the caller's HTTP client.

func (*OpenSearch) Index

func (search *OpenSearch) Index(ctx context.Context, document *pb.SourceDocument, text string) error

func (*OpenSearch) IndexSimulationSource

func (search *OpenSearch) IndexSimulationSource(ctx context.Context, index string, source *pb.SimulationTraceSource) (string, error)

IndexSimulationSource uses the same generated SDK client as knowledge search. Source records retain original event/trajectory text, not only rendered spans.

func (*OpenSearch) Search

func (search *OpenSearch) Search(ctx context.Context, request *pb.SearchRequest) (*pb.SearchResult, error)

func (*OpenSearch) SimulationSource

func (search *OpenSearch) SimulationSource(ctx context.Context, index string, runID string) (*pb.SimulationLogRecord, error)

type Option

type Option func(service *Service)

func WithAgentConfigurations

func WithAgentConfigurations(store IAgentConfigurationStore) Option

func WithDashboard

func WithDashboard(dashboard *Dashboard) Option

func WithEmail

func WithEmail(sender IEmailSender) Option

func WithKnowledge

func WithKnowledge(store IKnowledgeStore, index IKnowledgeIndex, artifacts *Artifacts) Option

func WithMCPTool

func WithMCPTool[In, Out any](tool mcp.Tool, handler mcp.ToolHandlerFor[In, Out]) Option

WithMCPTool adds one typed consumer-owned tool to the same MCP server as CSF's generated operations. The MCP SDK derives and validates the input and output schemas from In and Out; CSF only supplies registration ordering and collision checks.

func WithOnboarding

func WithOnboarding(config OnboardingConfig) Option

func WithSimulations

func WithSimulations(simulations *Simulations) Option

func WithWorkbenchThemeDirectory

func WithWorkbenchThemeDirectory(directory string) Option

WithWorkbenchThemeDirectory selects where the host reads workbench-theme.css. Missing or empty files use the default theme. Agents edit the file, then call ReloadWorkbenchTheme; they cannot choose a file path through an operation.

type Postgres

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

Postgres owns the relational projection of retained source and experiment data.

func NewPostgres

func NewPostgres(pool *pgxpool.Pool) (*Postgres, error)

func (*Postgres) ClaimProjection

func (store *Postgres) ClaimProjection(ctx context.Context) (*pb.ProjectionTask, error)

func (*Postgres) CompleteProjection

func (store *Postgres) CompleteProjection(ctx context.Context, task *pb.ProjectionTask) error

func (*Postgres) CountProjections

func (store *Postgres) CountProjections(ctx context.Context) ([]*pb.ProjectionCount, error)

func (*Postgres) FailProjection

func (store *Postgres) FailProjection(ctx context.Context, task *pb.ProjectionTask, problem string) error

func (*Postgres) GetAgentConfiguration

func (store *Postgres) GetAgentConfiguration(ctx context.Context, agentID string) (*pb.AgentConfiguration, error)

func (*Postgres) GetDocument

func (store *Postgres) GetDocument(ctx context.Context, request *pb.DocumentRequest) (*pb.SourceDocument, error)

func (*Postgres) GetGraph

func (store *Postgres) GetGraph(ctx context.Context, request *pb.GraphRequest) (*pb.GraphSnapshot, error)

func (*Postgres) GetProjection

func (store *Postgres) GetProjection(ctx context.Context, request *pb.DocumentRequest) (*pb.ProjectionTask, error)

func (*Postgres) Initialize

func (store *Postgres) Initialize(ctx context.Context) error

Initialize bootstraps an empty, explicitly selected database, then applies additive migrations. Each phase commits atomically. Existing installations fail bootstrap rather than silently adopting a schema.

func (*Postgres) Migrate

func (store *Postgres) Migrate(ctx context.Context) error

Migrate uses the shared migration ledger for additive, transactional upgrades.

func (*Postgres) PutAgentConfiguration

func (store *Postgres) PutAgentConfiguration(ctx context.Context, agentID string, expectedRevision uint32, configuration *pb.AgentConfigurationInput) (*pb.AgentConfiguration, error)

func (*Postgres) PutDocument

func (store *Postgres) PutDocument(ctx context.Context, document *pb.SourceDocument) (*pb.SourceDocument, error)

func (*Postgres) PutEdge

func (store *Postgres) PutEdge(ctx context.Context, edge *pb.KnowledgeEdge) (*pb.KnowledgeEdge, error)

func (*Postgres) PutNode

func (store *Postgres) PutNode(ctx context.Context, node *pb.KnowledgeNode) (*pb.KnowledgeNode, error)

type ProjectionWorkers

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

ProjectionWorkers runs bounded, at-least-once projection work in its caller's process. PostgreSQL owns claims and retries; wakeups are only a latency hint.

func (*ProjectionWorkers) Active

func (workers *ProjectionWorkers) Active() int64

func (*ProjectionWorkers) Close

func (workers *ProjectionWorkers) Close()

func (*ProjectionWorkers) Configured

func (workers *ProjectionWorkers) Configured() int

func (*ProjectionWorkers) Counts

func (workers *ProjectionWorkers) Counts(ctx context.Context) ([]*pb.ProjectionCount, error)

type Runtime

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

Runtime has one owner. Compose it directly into a Go loop, or use the JSONL test adapter. No goroutine, socket, container or service registry is required.

func NewRuntime

func NewRuntime() *Runtime

func (*Runtime) Activate

func (runtime *Runtime) Activate(controller *brainspinev1.Controller, epoch uint64) (*brainspinev1.Program, error)

Activate is an episode-boundary operation in this prototype. It compiles the candidate completely before replacing the active immutable program.

func (*Runtime) Handle

func (runtime *Runtime) Handle(request *brainspinev1.RuntimeRequest) *brainspinev1.RuntimeResponse

func (*Runtime) Reset

func (runtime *Runtime) Reset(epoch uint64) error

Reset starts a new test episode while preserving the admitted controller.

func (*Runtime) Step

func (runtime *Runtime) Step(observation *brainspinev1.Observation, nowTick uint64) *brainspinev1.Action

Step rejects stale, replayed and wrong-epoch observations. Braking is a simulation fallback policy, not a theorem about a physical vehicle.

type Service

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

Service composes CSF capabilities and their generated HTTP/MCP operations. It opens no listener and owns no process.

func New

func New(options ...Option) (*Service, error)

func (*Service) AgentMCPHandler

func (service *Service) AgentMCPHandler(authenticator *AgentMCPAuthenticator) http.Handler

AgentMCPHandler returns a streamable MCP HTTP handler that checks the bearer credential against both identity headers before exposing CSF's private request identity.

func (*Service) CancelSimulation

func (service *Service) CancelSimulation(ctx context.Context, request *pb.CancelSimulationRequest) (*pb.CancelSimulationResponse, error)

func (*Service) Compile

func (service *Service) Compile(ctx context.Context, request *pb.CompileRequest) (*pb.CompileResponse, error)

func (*Service) GetDocument

func (service *Service) GetDocument(ctx context.Context, request *pb.GetDocumentRequest) (*pb.GetDocumentResponse, error)

func (*Service) GetGraph

func (service *Service) GetGraph(ctx context.Context, request *pb.GetGraphRequest) (*pb.GetGraphResponse, error)

func (*Service) GetOwnAgentConfiguration

func (service *Service) GetOwnAgentConfiguration(ctx context.Context, _ *pb.GetOwnAgentConfigurationRequest) (*pb.GetOwnAgentConfigurationResponse, error)

GetOwnAgentConfiguration returns the configuration selected by the signed transport identity. Callers cannot choose an agent ID through this API.

func (*Service) GetSnapshot

func (service *Service) GetSnapshot(ctx context.Context, request *pb.GetSnapshotRequest) (*pb.GetSnapshotResponse, error)

func (*Service) GetWorkbenchTheme

func (service *Service) GetWorkbenchTheme(ctx context.Context, request *pb.GetWorkbenchThemeRequest) (*pb.GetWorkbenchThemeResponse, error)

func (*Service) IngestDocument

func (service *Service) IngestDocument(ctx context.Context, request *pb.IngestDocumentRequest) (*pb.IngestDocumentResponse, error)

func (*Service) InspectSimulation

func (service *Service) InspectSimulation(ctx context.Context, request *pb.InspectSimulationRequest) (*pb.InspectSimulationResponse, error)

func (*Service) LearnAboutCSF

func (service *Service) LearnAboutCSF(ctx context.Context, request *pb.LearnAboutCSFRequest) (*pb.LearnAboutCSFResponse, error)

func (*Service) ListSimulations

func (service *Service) ListSimulations(ctx context.Context, request *pb.ListSimulationsRequest) (*pb.ListSimulationsResponse, error)

func (*Service) MCPHandler

func (service *Service) MCPHandler() *mcp.StreamableHTTPHandler

MCPHandler supports legacy clients and per-request protocol metadata. Durable knowledge belongs to the service stores, so the HTTP transport is stateless.

func (*Service) PrepareAgentAssignment

func (service *Service) PrepareAgentAssignment(ctx context.Context, request *pb.PrepareAgentAssignmentRequest) (*pb.PrepareAgentAssignmentResponse, error)

PrepareAgentAssignment prepares data only. The caller decides when to submit it; this capability allocates no session, worker, process or persistent state.

func (*Service) PutEdge

func (service *Service) PutEdge(ctx context.Context, request *pb.PutEdgeRequest) (*pb.PutEdgeResponse, error)

func (*Service) PutNode

func (service *Service) PutNode(ctx context.Context, request *pb.PutNodeRequest) (*pb.PutNodeResponse, error)

func (*Service) ReadSimulationLogs

func (service *Service) ReadSimulationLogs(ctx context.Context, request *pb.ReadSimulationLogsRequest) (*pb.ReadSimulationLogsResponse, error)

func (*Service) RebuildSimulationTrace

func (service *Service) RebuildSimulationTrace(ctx context.Context, request *pb.RebuildSimulationTraceRequest) (*pb.RebuildSimulationTraceResponse, error)

RebuildSimulationTrace derives versioned spans from OpenSearch alone. The durable delivery ledger prevents repeating an accepted or ambiguous export.

func (*Service) RecordSimulationEvents

func (service *Service) RecordSimulationEvents(ctx context.Context, request *pb.RecordSimulationEventsRequest) (*pb.RecordSimulationEventsResponse, error)

func (*Service) Register

func (service *Service) Register(router gin.IRouter)

func (*Service) ReloadWorkbenchTheme

func (service *Service) ReloadWorkbenchTheme(ctx context.Context, request *pb.ReloadWorkbenchThemeRequest) (*pb.ReloadWorkbenchThemeResponse, error)

func (*Service) Search

func (service *Service) Search(ctx context.Context, request *pb.SearchRequest) (*pb.SearchResponse, error)

func (*Service) SendEmail

func (service *Service) SendEmail(ctx context.Context, request *emailv1.SendEmailRequest) (*emailv1.SendEmailResponse, error)

SendEmail accepts content only, and never accepts a caller-selected recipient or claimed provenance. Legacy unauthenticated HTTP/MCP routes fail closed.

func (*Service) ServeStdioMCP

func (service *Service) ServeStdioMCP(ctx context.Context) error

ServeStdioMCP serves the same generated tools over the caller process's standard input and output. The application still owns the process lifetime and cancellation context.

func (*Service) StartProjectionWorkers

func (service *Service) StartProjectionWorkers(ctx context.Context) (*ProjectionWorkers, error)

StartProjectionWorkers starts one pool for this service. The caller closes it before closing the store, artifacts or shared OpenSearch client.

func (*Service) SubmitSimulation

func (service *Service) SubmitSimulation(ctx context.Context, request *pb.SubmitSimulationRequest) (*pb.SubmitSimulationResponse, error)

func (*Service) UpdateOwnAgentConfiguration

func (service *Service) UpdateOwnAgentConfiguration(ctx context.Context, request *pb.UpdateOwnAgentConfigurationRequest) (*pb.UpdateOwnAgentConfigurationResponse, error)

UpdateOwnAgentConfiguration replaces only the signed caller's references. expected_revision is a compare-and-swap precondition owned by the store.

type SimulationOption

type SimulationOption func(simulations *Simulations)

func WithLocalSimulations

func WithLocalSimulations(local *LocalSimulations) SimulationOption

func WithSimulationLogSearch

func WithSimulationLogSearch(search *OpenSearch) SimulationOption

func WithSimulationTraces

func WithSimulationTraces(client ISimulationTraces) SimulationOption

type Simulations

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

Simulations owns job admission and observation; the application owns its worker lifetime.

func NewSimulations

func NewSimulations(store *Postgres, artifacts *Artifacts, config *pb.SimulationConfig, provider IBatch, logs ISimulationLogs, options ...SimulationOption) (*Simulations, error)

func (*Simulations) Tick

func (simulations *Simulations) Tick(ctx context.Context) error

Tick is the bounded worker iteration used by integration checks and Work.

func (*Simulations) Work

func (simulations *Simulations) Work(ctx context.Context) error

Work runs one bounded queue consumer in the caller's Go runtime. SubmitJob has no idempotency token: an uncertain result is retained, never blindly retried.

type SourceCheck

type SourceCheck func(ctx context.Context, request CheckRequest) error

type SourceFile

type SourceFile struct {
	Path    string
	Content []byte
	Missing bool
	Problem string
}

These are in-process snapshots, not wire DTOs. Each check sees the exact bytes whose digest caused notification, including explicit missing files.

type SourceWatch

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

func NewSourceWatch

func NewSourceWatch(root string, paths []string, interval time.Duration, check SourceCheck) (*SourceWatch, error)

NewSourceWatch accepts only explicit relative files, bounded in count and size. Checks must honor ctx; a callback owns no additional watcher goroutine.

func (*SourceWatch) Start

func (watch *SourceWatch) Start(ctx context.Context) (<-chan WatchResult, error)

Start captures the baseline before returning. One goroutine owns observation, checks and coalescing. A slow consumer applies backpressure, cancellably.

type WatchResult

type WatchResult struct {
	Changes []Change
	Err     error
}

Directories

Path Synopsis
internal
mocks
Package csfmocks is a generated GoMock package.
Package csfmocks is a generated GoMock package.

Jump to

Keyboard shortcuts

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