Merge branch 'crew/cluster3' into crew-integration

This commit is contained in:
sam committed 2026-09-15 10:33:15 +10:00
commit 04d690322a
7 files changed
+1 -1468

No files matched your search

-11
View File
@@ -11,7 +11,6 @@ package archied
import (
"context"
"crypto/subtle"
"encoding/json"
"fmt"
"net"
@@ -222,13 +221,3 @@ func stateStoreServerOpts(listen, token string, grants *staterpc.TaskGrants) (op
grpc.ChainStreamInterceptor(grants.StreamInterceptor(token)),
}, false, nil
}
// constantTimeTokenValidator returns a staterpc.TokenValidator that accepts
// exactly the configured token, compared in constant time so a timing side
// channel cannot leak how many bytes matched (the standalone server's
// equivalent of the earlier in-process interceptor's token check).
func constantTimeTokenValidator(token string) staterpc.TokenValidator {
return func(candidate string) bool {
return subtle.ConstantTimeCompare([]byte(token), []byte(candidate)) == 1
}
}
-13
View File
@@ -50,19 +50,6 @@ func TestStateStoreServerOptsMalformedListen(t *testing.T) {
}
}
func TestConstantTimeTokenValidator(t *testing.T) {
validate := constantTimeTokenValidator("correct-token")
if !validate("correct-token") {
t.Fatal("validator should accept the configured token")
}
if validate("wrong-token") {
t.Fatal("validator should reject a different token")
}
if validate("") {
t.Fatal("validator should reject an empty token")
}
}
// TestServeStateStoreServesContract verifies the standalone composition's
// serveStateStore + stateStoreDeps wiring actually serves the StateStore gRPC
// contract over a real loopback listener: the same service .4.2 serves
-36
View File
@@ -4,9 +4,7 @@ import (
"context"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/status"
)
// tokenMetadataKey is the gRPC metadata key the bearer token travels in.
@@ -14,40 +12,6 @@ import (
// lifecycle note.
const tokenMetadataKey = "state-store-token"
// TokenValidator reports whether token is a currently-issued, unexpired
// bearer token for the State Store's bridge-address listener topology. The
// caller (the daemon) owns the issued-token set; this package only enforces
// the check server-side and attaches the token client-side.
type TokenValidator func(token string) bool
// UnaryTokenInterceptor validates the bearer token carried in each unary
// call's metadata, returning codes.Unauthenticated on a missing, unknown, or
// expired token. Required on the bridge-address (agent-consumed) listener
// topology per §9; not used on the loopback-only, daemon-only topology.
func UnaryTokenInterceptor(validate TokenValidator) grpc.UnaryServerInterceptor {
return func(ctx context.Context, req any, _ *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (any, error) {
if err := checkToken(ctx, validate); err != nil {
return nil, err
}
return handler(ctx, req)
}
}
func checkToken(ctx context.Context, validate TokenValidator) error {
md, ok := metadata.FromIncomingContext(ctx)
if !ok {
return status.Error(codes.Unauthenticated, "missing state store token")
}
values := md.Get(tokenMetadataKey)
if len(values) == 0 || values[0] == "" {
return status.Error(codes.Unauthenticated, "missing state store token")
}
if !validate(values[0]) {
return status.Error(codes.Unauthenticated, "invalid state store token")
}
return nil
}
// UnaryClientTokenInterceptor attaches token to every outgoing call's
// metadata under tokenMetadataKey. One token covers a task's container
// lifetime (§9's per-incumbence lifecycle) so it does not need to be
@@ -263,50 +263,6 @@ func TestStateStoreConformance(t *testing.T) {
}
}
// TestTokenInterceptorRejectsMissingOrInvalidToken exercises the gRPC
// interceptor the bridge-address (agent-consumed) listener topology
// requires: missing or unrecognised tokens fail closed with
// codes.Unauthenticated, per §9's token lifecycle.
func TestTokenInterceptorRejectsMissingOrInvalidToken(t *testing.T) {
const validToken = "task-42-token"
validate := func(token string) bool { return token == validToken }
listener := bufconn.Listen(1 << 20)
local := store.OpenTest(t)
server := grpc.NewServer(grpc.UnaryInterceptor(UnaryTokenInterceptor(validate)))
RegisterServer(server, Deps{Tasks: local})
go func() { _ = server.Serve(listener) }()
t.Cleanup(func() { server.Stop(); _ = listener.Close() })
dial := func(t *testing.T, token string) contract {
t.Helper()
opts := []grpc.DialOption{
grpc.WithTransportCredentials(insecure.NewCredentials()),
grpc.WithContextDialer(func(ctx context.Context, _ string) (net.Conn, error) { return listener.DialContext(ctx) }),
}
if token != "" {
opts = append(opts, grpc.WithUnaryInterceptor(UnaryClientTokenInterceptor(token)))
}
conn, err := grpc.NewClient("passthrough:///state", opts...)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = conn.Close() })
return NewClient(conn)
}
ctx := t.Context()
if _, err := dial(t, "").StatusCounts(ctx); err == nil {
t.Fatal("missing token accepted")
}
if _, err := dial(t, "wrong-token").StatusCounts(ctx); err == nil {
t.Fatal("invalid token accepted")
}
if _, err := dial(t, validToken).StatusCounts(ctx); err != nil {
t.Fatalf("valid token rejected: %v", err)
}
}
// TestConfigSnapshotContract drives the published configuration projection
// through both the local store and the gRPC client. The document is opaque to
// this hop, so the test's whole claim is that it arrives unchanged: the UI
+1 -2
View File
@@ -144,8 +144,7 @@ func (p *Provider) Err() error { return p.dirErr }
// SystemPromptBlock implements memory.SystemPromptProvider. It returns a
// markdown-formatted block containing the frozen snapshot of MEMORY.md and
// USER.md content, wrapped in <memory>…</memory> fences so the scrubber can
// strip it from streaming output.
// USER.md content, wrapped in <memory>…</memory> fences.
//
// When the frozen snapshot is enabled (the default), the block is built from
// the snapshot captured at Initialize() time and does not change for the
-340
View File
@@ -1,340 +0,0 @@
// Package scrubber implements a stateful StreamingContextScrubber that
// strips <memory>...</memory> fence spans from streaming text output. It
// handles partial chunks that split across fence boundaries, maintains state
// between chunks, and only emits clean text downstream.
//
// The scrubber is designed for zero allocations in the hot path (normal text
// with no memory blocks). Buffers are pre-allocated and reused. An allocation
// occurs only when a tag spans a chunk boundary (the pending path), which is
// rare in practice.
package scrubber
import (
"bytes"
"fmt"
"io"
"strings"
)
const (
// openTag marks the start of a memory context block.
openTag = "<memory>"
// closeTag marks the end of a memory context block.
closeTag = "</memory>"
// maxTagLen is the length of the longest tag we need to buffer for
// partial chunk boundary matching.
maxTagLen = len(closeTag) // 9 bytes
)
// Scrubber strips <memory>...</memory> fence spans from streaming text
// output. It maintains state between Write calls to handle fence tags
// that span chunk boundaries.
//
// A Scrubber is safe for use by a single goroutine; it is not safe for
// concurrent use without external synchronization.
type Scrubber struct {
w io.Writer // underlying writer; nil means discard
depth int // nesting depth of <memory> blocks (0 = normal text)
// pending holds bytes from the end of the previous chunk that may be
// the start of a tag we're looking for. Backed by pbuf to avoid
// allocation when len(pending) <= maxTagLen.
pending []byte
pbuf [maxTagLen]byte
// buf is a reusable buffer for building output in Process.
buf bytes.Buffer
// writeErr stores the first write error from the underlying writer.
// Subsequent writes are skipped once an error is recorded.
writeErr error
// Stats counters.
blocksStripped int
bytesStripped int64
}
// New creates a new Scrubber that writes scrubbed output to w. If w is
// nil, scrubbed output is discarded (useful when the caller only needs
// to count stripped blocks or when using Process).
func New(w io.Writer) *Scrubber {
return &Scrubber{w: w}
}
// Reset resets the scrubber to its initial state so it can be reused.
// The underlying writer is preserved. Buffers are cleared without
// releasing backing arrays.
func (s *Scrubber) Reset() {
s.depth = 0
s.pending = s.pending[:0]
s.buf.Reset()
s.writeErr = nil
s.blocksStripped = 0
s.bytesStripped = 0
}
// Write processes a chunk of streaming text and writes the scrubbed output
// to the underlying writer. It returns the number of bytes consumed from p
// (always len(p) on success) and any write error from the underlying writer.
//
// Write is the primary streaming interface. It maintains internal state
// across calls to handle tags that span chunk boundaries.
func (s *Scrubber) Write(p []byte) (int, error) {
if len(p) == 0 {
return 0, nil
}
data := p
// Prepend any pending bytes from the previous chunk.
if len(s.pending) > 0 {
// We need to combine pending + new data. This allocates, but the
// pending path is rare (only when a tag is split across chunks).
combined := make([]byte, len(s.pending)+len(p))
copy(combined, s.pending)
copy(combined[len(s.pending):], p)
data = combined
s.pending = s.pending[:0]
}
for len(data) > 0 {
if s.depth > 0 {
data = s.processInMemory(data)
} else {
data = s.processNormal(data)
}
}
// Return any stored write error. The full input length is reported as
// consumed per the io.Writer contract: we always consume the entire
// input even if the underlying writer fails (the data has been
// processed; the error is about delivery, not consumption).
return len(p), s.writeErr
}
// processNormal handles input when we're outside a memory block (depth == 0).
// It looks for <memory> open tags and passes everything else through.
func (s *Scrubber) processNormal(data []byte) []byte {
// Fast path: no '<' at all means no possible tag.
idx := bytes.IndexByte(data, '<')
if idx < 0 {
s.writeOutput(data)
return nil
}
// Check if the '<' starts a <memory> tag.
tail := data[idx:]
if len(tail) >= len(openTag) {
// Enough data to check the full tag.
if string(tail[:len(openTag)]) == openTag {
// Found <memory> -- write everything before it, then enter memory block.
s.writeOutput(data[:idx])
s.depth++
s.blocksStripped++
s.bytesStripped += int64(len(openTag))
return tail[len(openTag):]
}
// Not <memory> -- write the '<' and continue after it.
s.writeOutput(data[:idx+1])
return data[idx+1:]
}
// Not enough data to determine -- partial tag at end of chunk.
// Hold the tail for the next Write call.
if isPrefixOfTag(tail, openTag) {
s.writeOutput(data[:idx])
s.pending = append(s.pbuf[:0], tail...)
return nil
}
// Not a prefix of <memory> -- write everything.
s.writeOutput(data)
return nil
}
// processInMemory handles input when we're inside a memory block (depth > 0).
// It looks for </memory> close tags and strips everything else.
func (s *Scrubber) processInMemory(data []byte) []byte {
// Fast path: no '<' means no possible close tag -- strip everything.
idx := bytes.IndexByte(data, '<')
if idx < 0 {
s.bytesStripped += int64(len(data))
return nil
}
tail := data[idx:]
// Check for nested <memory> open tags (increment depth).
if len(tail) >= len(openTag) && string(tail[:len(openTag)]) == openTag {
s.bytesStripped += int64(idx + len(openTag))
s.depth++
s.blocksStripped++
return tail[len(openTag):]
}
// Check for </memory> close tag.
if len(tail) >= len(closeTag) {
if string(tail[:len(closeTag)]) == closeTag {
s.bytesStripped += int64(idx + len(closeTag))
s.depth--
return tail[len(closeTag):]
}
// Not a close tag -- skip the '<' and continue stripping.
s.bytesStripped += int64(idx + 1)
return data[idx+1:]
}
// Not enough data to determine -- partial tag at end of chunk.
// Could be the start of </memory> (which would close the block) or
// <memory> (which would nest). Buffer it.
if isPrefixOfTag(tail, closeTag) || isPrefixOfTag(tail, openTag) {
s.bytesStripped += int64(idx)
s.pending = append(s.pbuf[:0], tail...)
return nil
}
// Not a prefix of any relevant tag -- strip everything.
s.bytesStripped += int64(len(data))
return nil
}
// writeOutput writes data to the underlying writer. If a previous write
// error has been recorded, writes are silently skipped. New write errors
// are stored for return from Write/Flush.
func (s *Scrubber) writeOutput(data []byte) {
if len(data) == 0 || s.w == nil || s.writeErr != nil {
return
}
_, err := s.w.Write(data)
if err != nil && s.writeErr == nil {
s.writeErr = err
}
}
// Flush writes any pending buffered bytes (from a partial tag match at the
// end of the previous chunk) to the underlying writer and resets the pending
// buffer. Call Flush at the end of the stream to ensure any partial tag that
// wasn't actually a tag is emitted.
//
// If the scrubber is inside a memory block when Flush is called, the block
// is implicitly closed (missing closing tag handling). Any pending bytes
// inside the block are stripped, not emitted.
func (s *Scrubber) Flush() error {
if s.depth > 0 {
// Inside an unclosed memory block. Pending bytes are content that
// was buffered as potential tag starts -- since no close tag arrives,
// they are memory-block content and should be stripped, not emitted.
s.bytesStripped += int64(len(s.pending))
s.pending = s.pending[:0]
s.depth = 0
} else if len(s.pending) > 0 {
// Outside a memory block -- pending bytes are literal text whose
// partial tag didn't resolve.
s.writeOutput(s.pending)
s.pending = s.pending[:0]
}
err := s.writeErr
s.writeErr = nil
return err
}
// Close is equivalent to Flush. It implements a subset of io.Closer for
// convenience when the scrubber is used in a pipeline.
func (s *Scrubber) Close() error {
return s.Flush()
}
// Process is a convenience method that scrubs a single chunk and returns
// the cleaned text. It maintains internal state across calls, so it can
// be used for streaming just like Write. The returned string is only the
// newly scrubbed output from this chunk -- not the full accumulated output.
//
// For zero-allocation streaming, prefer Write with a pre-allocated writer.
func (s *Scrubber) Process(chunk string) string {
s.buf.Reset()
prev := s.w
s.w = &s.buf
// Restore the original writer even if Write panics.
defer func() { s.w = prev }()
_, _ = s.Write([]byte(chunk))
if s.buf.Len() == 0 {
return ""
}
return s.buf.String()
}
// ProcessString is a convenience method that scrubs a complete string in
// one call. It resets the scrubber state first and flushes at the end,
// so it is suitable for one-shot use. For streaming use, call Write or
// Process repeatedly and call Flush at the end.
func (s *Scrubber) ProcessString(input string) string {
s.Reset()
s.buf.Reset()
prev := s.w
s.w = &s.buf
defer func() { s.w = prev }()
_, _ = s.Write([]byte(input))
_ = s.Flush()
return s.buf.String()
}
// BlocksStripped returns the number of <memory> blocks that have been
// stripped since the last Reset.
func (s *Scrubber) BlocksStripped() int {
return s.blocksStripped
}
// BytesStripped returns the total number of bytes stripped (including
// the fence tags themselves) since the last Reset.
func (s *Scrubber) BytesStripped() int64 {
return s.bytesStripped
}
// InMemoryBlock reports whether the scrubber is currently inside a
// <memory> block (i.e., an open tag has been seen but no matching
// close tag yet).
func (s *Scrubber) InMemoryBlock() bool {
return s.depth > 0
}
// Depth returns the current nesting depth of <memory> blocks.
// The depth is represented as an int; it is the caller's responsibility
// to ensure nesting does not exceed reasonable bounds.
func (s *Scrubber) Depth() int {
return s.depth
}
// ── Helpers ────────────────────────────────────────────────────────────
// isPrefixOfTag reports whether data is a prefix of tag -- i.e., data could
// be the start of tag if more bytes arrive later. Returns false if data is
// longer than tag.
func isPrefixOfTag(data []byte, tag string) bool {
if len(data) >= len(tag) {
return false
}
for i, b := range data {
if b != tag[i] {
return false
}
}
return len(data) > 0
}
// DebugString returns a human-readable representation of the scrubber's
// internal state. Useful for debugging tests.
func (s *Scrubber) DebugString() string {
var sb strings.Builder
fmt.Fprintf(&sb, "Scrubber{depth=%d", s.depth)
fmt.Fprintf(&sb, ", pending=%q", string(s.pending))
fmt.Fprintf(&sb, ", blocksStripped=%d", s.blocksStripped)
fmt.Fprintf(&sb, ", bytesStripped=%d}", s.bytesStripped)
return sb.String()
}
// Compile-time interface checks.
var (
_ io.Writer = (*Scrubber)(nil)
)
File diff suppressed because it is too large. Load diff