diff --git a/.beads/issues.jsonl b/.beads/issues.jsonl index b5bcdc1b3..3d0bdec09 100644 --- a/.beads/issues.jsonl +++ b/.beads/issues.jsonl @@ -2,7 +2,7 @@ {"_type":"issue","id":"archie-core-abg.18.26","title":"Verify: Built-in memory tool actions: add, replace, remove","acceptance_criteria":"Independent adversarial review by fresh agent. Verify: no dead code paths, no lint issues (golangci-lint run clean), tests pass (go test ./...), code is formatted (gofmt), no hardcoded values in tests. Review the implementation against the original acceptance criteria. Report findings or confirm clean.","status":"open","priority":0,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-07-25T14:12:46Z","created_by":"Sam Catlow","updated_at":"2026-07-25T14:12:46Z","dependencies":[{"issue_id":"archie-core-abg.18.26","depends_on_id":"archie-core-abg.18.13","type":"blocks","created_at":"2026-07-26T00:17:33Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-abg.18.26","depends_on_id":"archie-core-abg.18","type":"parent-child","created_at":"2026-07-26T00:12:46Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":1,"dependent_count":0,"comment_count":0} {"_type":"issue","id":"archie-core-abg.18.25","title":"Verify: Built-in memory tool: file-backed persistent memory","acceptance_criteria":"Independent adversarial review by fresh agent. Verify: no dead code paths, no lint issues (golangci-lint run clean), tests pass (go test ./...), code is formatted (gofmt), no hardcoded values in tests. Review the implementation against the original acceptance criteria. Report findings or confirm clean.","status":"open","priority":0,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-07-25T14:12:38Z","created_by":"Sam Catlow","updated_at":"2026-07-25T14:12:38Z","dependencies":[{"issue_id":"archie-core-abg.18.25","depends_on_id":"archie-core-abg.18.12","type":"blocks","created_at":"2026-07-26T00:19:09Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-abg.18.25","depends_on_id":"archie-core-abg.18","type":"parent-child","created_at":"2026-07-26T00:12:37Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":1,"dependent_count":0,"comment_count":0} {"_type":"issue","id":"archie-core-abg.18.24","title":"Verify: Tool schema normalization for memory providers","acceptance_criteria":"Independent adversarial review by fresh agent. Verify: no dead code paths, no lint issues (golangci-lint run clean), tests pass (go test ./...), code is formatted (gofmt), no hardcoded values in tests. Review the implementation against the original acceptance criteria. Report findings or confirm clean.","status":"open","priority":0,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-07-25T14:12:34Z","created_by":"Sam Catlow","updated_at":"2026-07-25T14:12:34Z","dependencies":[{"issue_id":"archie-core-abg.18.24","depends_on_id":"archie-core-abg.18.11","type":"blocks","created_at":"2026-07-26T00:19:11Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-abg.18.24","depends_on_id":"archie-core-abg.18","type":"parent-child","created_at":"2026-07-26T00:12:33Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":1,"dependent_count":0,"comment_count":0} -{"_type":"issue","id":"archie-core-abg.18.23","title":"Verify: StreamingContextScrubber","acceptance_criteria":"Independent adversarial review by fresh agent. Verify: no dead code paths, no lint issues (golangci-lint run clean), tests pass (go test ./...), code is formatted (gofmt), no hardcoded values in tests. Review the implementation against the original acceptance criteria. Report findings or confirm clean.","status":"open","priority":0,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-07-25T14:12:28Z","created_by":"Sam Catlow","updated_at":"2026-07-25T14:12:28Z","dependencies":[{"issue_id":"archie-core-abg.18.23","depends_on_id":"archie-core-abg.18","type":"parent-child","created_at":"2026-07-26T00:12:28Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-abg.18.23","depends_on_id":"archie-core-abg.18.10","type":"blocks","created_at":"2026-07-26T00:19:12Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":1,"dependent_count":0,"comment_count":0} +{"_type":"issue","id":"archie-core-abg.18.23","title":"Verify: StreamingContextScrubber","acceptance_criteria":"Independent adversarial review by fresh agent. Verify: no dead code paths, no lint issues (golangci-lint run clean), tests pass (go test ./...), code is formatted (gofmt), no hardcoded values in tests. Review the implementation against the original acceptance criteria. Report findings or confirm clean.","status":"in_progress","priority":0,"issue_type":"task","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-07-25T14:12:28Z","created_by":"Sam Catlow","updated_at":"2026-07-25T16:04:48Z","started_at":"2026-07-25T16:04:48Z","dependencies":[{"issue_id":"archie-core-abg.18.23","depends_on_id":"archie-core-abg.18","type":"parent-child","created_at":"2026-07-26T00:12:28Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-abg.18.23","depends_on_id":"archie-core-abg.18.10","type":"blocks","created_at":"2026-07-26T00:19:12Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":1,"dependent_count":0,"comment_count":0} {"_type":"issue","id":"archie-core-abg.18.22","title":"Verify: MemoryManager orchestrator","acceptance_criteria":"Independent adversarial review by fresh agent. Verify: no dead code paths, no lint issues (golangci-lint run clean), tests pass (go test ./...), code is formatted (gofmt), no hardcoded values in tests. Review the implementation against the original acceptance criteria. Report findings or confirm clean.","status":"open","priority":0,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-07-25T14:12:25Z","created_by":"Sam Catlow","updated_at":"2026-07-25T14:12:25Z","dependencies":[{"issue_id":"archie-core-abg.18.22","depends_on_id":"archie-core-abg.18","type":"parent-child","created_at":"2026-07-26T00:12:24Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-abg.18.22","depends_on_id":"archie-core-abg.18.6","type":"blocks","created_at":"2026-07-26T00:19:13Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":1,"dependent_count":0,"comment_count":0} {"_type":"issue","id":"archie-core-abg.18.21","title":"Verify: MemoryProvider backup paths support","acceptance_criteria":"Independent adversarial review by fresh agent. Verify: no dead code paths, no lint issues (golangci-lint run clean), tests pass (go test ./...), code is formatted (gofmt), no hardcoded values in tests. Review the implementation against the original acceptance criteria. Report findings or confirm clean.","status":"open","priority":0,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-07-25T14:12:21Z","created_by":"Sam Catlow","updated_at":"2026-07-25T14:12:21Z","dependencies":[{"issue_id":"archie-core-abg.18.21","depends_on_id":"archie-core-abg.18.5","type":"blocks","created_at":"2026-07-26T00:19:14Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-abg.18.21","depends_on_id":"archie-core-abg.18","type":"parent-child","created_at":"2026-07-26T00:12:21Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":1,"dependent_count":0,"comment_count":0} {"_type":"issue","id":"archie-core-abg.18.20","title":"Verify: MemoryProvider config helpers","acceptance_criteria":"Independent adversarial review by fresh agent. Verify: no dead code paths, no lint issues (golangci-lint run clean), tests pass (go test ./...), code is formatted (gofmt), no hardcoded values in tests. Review the implementation against the original acceptance criteria. Report findings or confirm clean.","status":"open","priority":0,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-07-25T14:12:18Z","created_by":"Sam Catlow","updated_at":"2026-07-25T14:12:18Z","dependencies":[{"issue_id":"archie-core-abg.18.20","depends_on_id":"archie-core-abg.18","type":"parent-child","created_at":"2026-07-26T00:12:17Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-abg.18.20","depends_on_id":"archie-core-abg.18.4","type":"blocks","created_at":"2026-07-26T00:19:17Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":1,"dependent_count":0,"comment_count":0} @@ -22,8 +22,8 @@ {"_type":"issue","id":"archie-core-abg.18.13","title":"Built-in memory tool actions: add, replace, remove","description":"Implement the three core memory tool actions: add (appends new content to a section), replace (replaces content using substring matching to find the target), remove (deletes content using substring matching). These act on the MEMORY.md/USER.md files.","acceptance_criteria":"Tool exposes three actions: add, replace, remove\nadd(target_section, content) appends to or creates a named section\nreplace(target_section, substring, replacement) finds first match of substring in section and replaces it\nremove(target_section, substring) removes the matching line/block from the section\nSubstring matching is exact, case-sensitive by default (configurable)\nActions return clear success/error messages including the affected section and character count\nTool validates section names (alphanumeric + spaces, max 64 chars)\nSize bounds are checked before any write (reject if would exceed max file size)","status":"open","priority":0,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-07-25T14:08:12Z","created_by":"Sam Catlow","updated_at":"2026-07-25T14:08:12Z","dependencies":[{"issue_id":"archie-core-abg.18.13","depends_on_id":"archie-core-abg.18","type":"parent-child","created_at":"2026-07-26T00:08:12Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":1,"comment_count":0} {"_type":"issue","id":"archie-core-abg.18.12","title":"Built-in memory tool: file-backed persistent memory","description":"Implement the built-in file-backed memory tool that persists to MEMORY.md and USER.md files. This replaces the current ephemeral memoryNotes system with durable on-disk storage that survives restarts and sessions.","acceptance_criteria":"Built-in provider lives in internal/memory/builtin package\nMEMORY.md stores persistent agent memory (facts, preferences, state across sessions)\nUSER.md stores user-provided context (background, instructions, preferences)\nBoth files are bounded (configurable max size, default 100KB per file)\nFiles are read at provider initialization and written on every mutation\nFile format is plain markdown with sections\nThread-safe reads and writes (sync.RWMutex)\nFiles live under the profile's memory directory (e.g., ~/.config/archie/profiles/{profile}/memory/)","status":"open","priority":0,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-07-25T14:08:03Z","created_by":"Sam Catlow","updated_at":"2026-07-25T14:08:03Z","dependencies":[{"issue_id":"archie-core-abg.18.12","depends_on_id":"archie-core-abg.18","type":"parent-child","created_at":"2026-07-26T00:08:03Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":1,"comment_count":0} {"_type":"issue","id":"archie-core-abg.17.16","title":"MCP client: stdio transport (subprocess management)","description":"Implement the MCP stdio transport: spawn and manage MCP server subprocesses, handle stdin/stdout JSON-RPC message framing, subprocess lifecycle (start/stop/restart), and auto-restart with exponential backoff. This is the foundational MCP transport that most local MCP servers use.","status":"in_progress","priority":0,"issue_type":"task","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-07-25T14:07:59Z","created_by":"Sam Catlow","updated_at":"2026-07-25T15:36:30Z","started_at":"2026-07-25T15:36:30Z","dependencies":[{"issue_id":"archie-core-abg.17.16","depends_on_id":"archie-core-abg.17","type":"parent-child","created_at":"2026-07-26T00:07:58Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":1,"comment_count":0} -{"_type":"issue","id":"archie-core-abg.18.11","title":"Tool schema normalization for memory providers","description":"Implement tool schema normalization that handles both bare tools (just Function definition) and wrapped OpenAI-style tool schemas from memory providers. Ensures all provider-exported tools are normalized to a consistent format before being merged into the agent's tool list.","acceptance_criteria":"Normalizer package detects whether a schema is bare (map with 'name' top-level) or wrapped (map with 'type':'function', 'function':{...})\nConverts both formats to a canonical internal representation\nHandles edge cases: missing required fields, extra unknown fields\nSchema normalization happens at registration time, not per-turn\nErrors on truly invalid schemas with clear messages\nRound-trips through JSON marshal/unmarshal","status":"open","priority":0,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-07-25T14:07:57Z","created_by":"Sam Catlow","updated_at":"2026-07-25T14:07:57Z","dependencies":[{"issue_id":"archie-core-abg.18.11","depends_on_id":"archie-core-abg.18","type":"parent-child","created_at":"2026-07-26T00:07:57Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":1,"comment_count":0} -{"_type":"issue","id":"archie-core-abg.18.10","title":"StreamingContextScrubber","description":"Implement a stateful StreamingContextScrubber that strips \u003cmemory-context\u003e...\u003c/memory-context\u003e fence spans from streaming text output. Must handle partial chunks that split across fence boundaries, maintain state between chunks, and only emit clean text downstream.","acceptance_criteria":"Scrubber is in internal/memory/scrubber package\nImplements an io.Writer or callback interface for processing streaming chunks\nStrips \u003cmemory-context\u003e ... \u003c/memory-context\u003e fences including the tags themselves\nHandles partial chunks where fence tags span chunk boundaries (maintains state)\nHandles missing closing tags (closes at end of stream)\nDoesn't interfere with non-memory-context content\nZero allocations in the hot path (reuses buffers)\nFully tested with edge cases: partial open/close, nested tags, empty content","status":"open","priority":0,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-07-25T14:07:53Z","created_by":"Sam Catlow","updated_at":"2026-07-25T14:07:53Z","dependencies":[{"issue_id":"archie-core-abg.18.10","depends_on_id":"archie-core-abg.18","type":"parent-child","created_at":"2026-07-26T00:07:52Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":1,"comment_count":0} +{"_type":"issue","id":"archie-core-abg.18.11","title":"Tool schema normalization for memory providers","description":"Implement tool schema normalization that handles both bare tools (just Function definition) and wrapped OpenAI-style tool schemas from memory providers. Ensures all provider-exported tools are normalized to a consistent format before being merged into the agent's tool list.","acceptance_criteria":"Normalizer package detects whether a schema is bare (map with 'name' top-level) or wrapped (map with 'type':'function', 'function':{...})\nConverts both formats to a canonical internal representation\nHandles edge cases: missing required fields, extra unknown fields\nSchema normalization happens at registration time, not per-turn\nErrors on truly invalid schemas with clear messages\nRound-trips through JSON marshal/unmarshal","status":"in_progress","priority":0,"issue_type":"task","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-07-25T14:07:57Z","created_by":"Sam Catlow","updated_at":"2026-07-25T16:06:41Z","started_at":"2026-07-25T16:06:41Z","dependencies":[{"issue_id":"archie-core-abg.18.11","depends_on_id":"archie-core-abg.18","type":"parent-child","created_at":"2026-07-26T00:07:57Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":1,"comment_count":0} +{"_type":"issue","id":"archie-core-abg.18.10","title":"StreamingContextScrubber","description":"Implement a stateful StreamingContextScrubber that strips \u003cmemory-context\u003e...\u003c/memory-context\u003e fence spans from streaming text output. Must handle partial chunks that split across fence boundaries, maintain state between chunks, and only emit clean text downstream.","acceptance_criteria":"Scrubber is in internal/memory/scrubber package\nImplements an io.Writer or callback interface for processing streaming chunks\nStrips \u003cmemory-context\u003e ... \u003c/memory-context\u003e fences including the tags themselves\nHandles partial chunks where fence tags span chunk boundaries (maintains state)\nHandles missing closing tags (closes at end of stream)\nDoesn't interfere with non-memory-context content\nZero allocations in the hot path (reuses buffers)\nFully tested with edge cases: partial open/close, nested tags, empty content","status":"in_progress","priority":0,"issue_type":"task","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-07-25T14:07:53Z","created_by":"Sam Catlow","updated_at":"2026-07-25T16:04:48Z","started_at":"2026-07-25T16:04:48Z","dependencies":[{"issue_id":"archie-core-abg.18.10","depends_on_id":"archie-core-abg.18","type":"parent-child","created_at":"2026-07-26T00:07:52Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":1,"comment_count":0} {"_type":"issue","id":"archie-core-abg.18.6","title":"MemoryManager orchestrator","description":"Implement MemoryManager that orchestrates the built-in memory provider plus at most one external provider. Key responsibilities: provider registration and lifecycle, tool schema merging from all active providers, runtime dispatch of tool calls to the correct provider, enforcement of the one-external-provider limit.","acceptance_criteria":"MemoryManager is in internal/memory/manager package\nConstructor accepts the built-in provider + optional external provider\nRegistering a second external provider returns an error\nget_tool_schemas() merges schemas from all active providers\nhandle_tool_call() routes calls to the owning provider\nProvides accessor methods for the current active provider(s)\nGracefully handles all provider being nil/empty","status":"closed","priority":0,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-07-25T14:07:33Z","created_by":"Sam Catlow","updated_at":"2026-07-25T15:23:33Z","closed_at":"2026-07-25T15:23:33Z","close_reason":"MemoryProvider interface + optional sub-interfaces + lifecycle hooks + config helpers + backup paths + MemoryManager orchestrator implemented test-first in internal/memory/. 29 tests pass.","dependencies":[{"issue_id":"archie-core-abg.18.6","depends_on_id":"archie-core-abg.18","type":"parent-child","created_at":"2026-07-26T00:07:33Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":1,"comment_count":0} {"_type":"issue","id":"archie-core-abg.18.5","title":"MemoryProvider backup paths support","description":"Add backup_paths() to MemoryProvider: returns a list of file paths outside HERMES_HOME that should be included in backups. External providers (e.g., SQLite, vector stores) may store data outside the main home directory, and this ensures backup completeness.","acceptance_criteria":"BackupProvider interface with backup_paths() returning []string\nReturned paths are absolute file or directory paths\nReturns empty slice for providers with no external data\nMemoryManager aggregates backup paths from all active providers\nPaths are included in any backup/restore workflow","status":"closed","priority":0,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-07-25T14:07:28Z","created_by":"Sam Catlow","updated_at":"2026-07-25T15:23:33Z","closed_at":"2026-07-25T15:23:33Z","close_reason":"MemoryProvider interface + optional sub-interfaces + lifecycle hooks + config helpers + backup paths + MemoryManager orchestrator implemented test-first in internal/memory/. 29 tests pass.","dependencies":[{"issue_id":"archie-core-abg.18.5","depends_on_id":"archie-core-abg.18","type":"parent-child","created_at":"2026-07-26T00:07:28Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":1,"comment_count":0} {"_type":"issue","id":"archie-core-abg.17.2","title":"Central tool registry singleton with Register() + discovery","description":"Implement a global tool registry singleton with a Register() method. Add file-system discovery that scans tools/*.go for registry.Register calls to auto-register tools at startup. This is the core infrastructure that all tool registration and lookup depends on.","status":"closed","priority":0,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-07-25T14:07:25Z","created_by":"Sam Catlow","updated_at":"2026-07-25T15:21:23Z","closed_at":"2026-07-25T15:21:23Z","close_reason":"Implemented Registry with Register, All, ByToolset, Available, Discover methods. Added registry.go with thread-safe singleton, AST-based file discovery for Register calls. 33 tests pass (toolentry + registry).","dependencies":[{"issue_id":"archie-core-abg.17.2","depends_on_id":"archie-core-abg.17","type":"parent-child","created_at":"2026-07-26T00:07:25Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":1,"comment_count":0} diff --git a/internal/memory/scrubber/scrubber.go b/internal/memory/scrubber/scrubber.go new file mode 100644 index 000000000..7f767d9dd --- /dev/null +++ b/internal/memory/scrubber/scrubber.go @@ -0,0 +1,319 @@ +// Package scrubber implements a stateful StreamingContextScrubber that +// strips ... 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. +package scrubber + +import ( + "bytes" + "fmt" + "io" + "strings" +) + +const ( + // openTag marks the start of a memory context block. + openTag = "" + // closeTag marks the end of a memory context block. + closeTag = "" + + // maxTagLen is the length of the longest tag we need to buffer for + // partial chunk boundary matching. + maxTagLen = len(closeTag) // 9 bytes +) + +// Scrubber strips ... 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 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 + + // 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.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 len(p), nil +} + +// processNormal handles input when we're outside a memory block (depth == 0). +// It looks for 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 tag. + tail := data[idx:] + if len(tail) >= len(openTag) { + // Enough data to check the full tag. + if string(tail[:len(openTag)]) == openTag { + // Found — 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 — 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 — write everything. + s.writeOutput(data) + return nil +} + +// processInMemory handles input when we're inside a memory block (depth > 0). +// It looks for 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 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 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. + s.bytesStripped += int64(idx + 1) + return data[idx+1:] + } + + // Not enough data to determine — partial tag at end of chunk. + 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. Nil writer is a no-op. +func (s *Scrubber) writeOutput(data []byte) { + if len(data) == 0 { + return + } + if s.w != nil { + // Write errors are rare on bytes.Buffer (the common case). When the + // underlying writer is a real connection, errors are surfaced on the + // next Write call. + _, _ = s.w.Write(data) + } +} + +// 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). +func (s *Scrubber) Flush() error { + // If we're still inside a memory block, close it implicitly. + // The content has already been stripped; we just need to reset depth. + if s.depth > 0 { + s.depth = 0 + } + + // Write any pending bytes — they weren't actually a tag. + if len(s.pending) > 0 { + s.writeOutput(s.pending) + s.pending = s.pending[:0] + } + + return nil +} + +// 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 + _, _ = s.Write([]byte(chunk)) + s.w = prev + 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 + _, _ = s.Write([]byte(input)) + _ = s.Flush() + s.w = prev + return s.buf.String() +} + +// BlocksStripped returns the number of 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 +// 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 blocks. +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) +) diff --git a/internal/memory/scrubber/scrubber_test.go b/internal/memory/scrubber/scrubber_test.go new file mode 100644 index 000000000..4d21126bd --- /dev/null +++ b/internal/memory/scrubber/scrubber_test.go @@ -0,0 +1,1069 @@ +package scrubber + +import ( + "bytes" + "fmt" + "io" + "strings" + "testing" +) + +// ── Basic functionality ───────────────────────────────────────────────── + +func TestScrubber_NoMemoryBlock(t *testing.T) { + s := New(nil) + result := s.ProcessString("Hello, world!") + if result != "Hello, world!" { + t.Errorf("got %q, want %q", result, "Hello, world!") + } + if s.BlocksStripped() != 0 { + t.Errorf("BlocksStripped = %d, want 0", s.BlocksStripped()) + } +} + +func TestScrubber_SingleMemoryBlock(t *testing.T) { + s := New(nil) + result := s.ProcessString("Before secret After") + if result != "Before After" { + t.Errorf("got %q, want %q", result, "Before After") + } + if s.BlocksStripped() != 1 { + t.Errorf("BlocksStripped = %d, want 1", s.BlocksStripped()) + } +} + +func TestScrubber_MultipleMemoryBlocks(t *testing.T) { + s := New(nil) + result := s.ProcessString("A x B y C") + if result != "A B C" { + t.Errorf("got %q, want %q", result, "A B C") + } + if s.BlocksStripped() != 2 { + t.Errorf("BlocksStripped = %d, want 2", s.BlocksStripped()) + } +} + +func TestScrubber_EmptyContent(t *testing.T) { + s := New(nil) + result := s.ProcessString("") + if result != "" { + t.Errorf("got %q, want %q", result, "") + } +} + +func TestScrubber_OnlyOpenTag(t *testing.T) { + // Missing close tag — block is implicitly closed at end of stream. + s := New(nil) + result := s.ProcessString("Before stuff") + if result != "Before " { + t.Errorf("got %q, want %q", result, "Before ") + } +} + +func TestScrubber_OnlyCloseTag(t *testing.T) { + // Stray close tag with no open — treated as literal text. + s := New(nil) + result := s.ProcessString("text more") + if result != "text more" { + t.Errorf("got %q, want %q", result, "text more") + } +} + +func TestScrubber_EmptyMemoryBlock(t *testing.T) { + s := New(nil) + result := s.ProcessString("beforeafter") + if result != "beforeafter" { + t.Errorf("got %q, want %q", result, "beforeafter") + } +} + +func TestScrubber_OnlyMemoryBlock(t *testing.T) { + s := New(nil) + result := s.ProcessString("everything") + if result != "" { + t.Errorf("got %q, want %q", result, "") + } +} + +// ── Nested tags ───────────────────────────────────────────────────────── + +func TestScrubber_NestedMemoryBlocks(t *testing.T) { + s := New(nil) + result := s.ProcessString("A outer inner back B") + if result != "A B" { + t.Errorf("got %q, want %q", result, "A B") + } + if s.BlocksStripped() != 2 { + t.Errorf("BlocksStripped = %d, want 2", s.BlocksStripped()) + } +} + +func TestScrubber_DeeplyNestedMemoryBlocks(t *testing.T) { + s := New(nil) + result := s.ProcessString("12321") + if result != "" { + t.Errorf("got %q, want %q", result, "") + } + if s.BlocksStripped() != 3 { + t.Errorf("BlocksStripped = %d, want 3", s.BlocksStripped()) + } +} + +func TestScrubber_UnbalancedNested_MoreOpens(t *testing.T) { + // More open tags than close tags — remaining blocks implicitly closed + // at end of stream. Everything after the first is stripped + // because the outer block never closes. + s := New(nil) + result := s.ProcessString("A outer inner B") + if result != "A " { + t.Errorf("got %q, want %q", result, "A ") + } +} + +func TestScrubber_UnbalancedNested_MoreCloses(t *testing.T) { + // Extra close tags are literal text. + s := New(nil) + result := s.ProcessString("ab") + if result != "b" { + t.Errorf("got %q, want %q", result, "b") + } +} + +// ── Partial chunk handling ────────────────────────────────────────────── + +func TestScrubber_PartialOpenTag_SplitAtAngle(t *testing.T) { + // Open tag split right after '<' + var buf bytes.Buffer + s := New(&buf) + + _, _ = s.Write([]byte("Hello <")) + _, _ = s.Write([]byte("memory>secret World")) + + if err := s.Flush(); err != nil { + t.Fatalf("Flush error: %v", err) + } + + result := buf.String() + if result != "Hello World" { + t.Errorf("got %q, want %q", result, "Hello World") + } +} + +func TestScrubber_PartialOpenTag_SplitMidTag(t *testing.T) { + tests := []struct { + name string + chunk1 string + chunk2 string + expected string + }{ + { + name: "split after secret Bye", + expected: "Hi Bye", + }, + { + name: "split after secret Bye", + expected: "Hi Bye", + }, + { + name: "split after secret Bye", + expected: "Hi Bye", + }, + { + name: "split after secret Bye", + expected: "Hi Bye", + }, + { + name: "split after secret Bye", + expected: "Hi Bye", + }, + { + name: "split after secret Bye", + expected: "Hi Bye", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + var buf bytes.Buffer + s := New(&buf) + + _, _ = s.Write([]byte(tt.chunk1)) + _, _ = s.Write([]byte(tt.chunk2)) + + if err := s.Flush(); err != nil { + t.Fatalf("Flush error: %v", err) + } + + if got := buf.String(); got != tt.expected { + t.Errorf("got %q, want %q", got, tt.expected) + } + }) + } +} + +func TestScrubber_PartialCloseTag_SplitMidTag(t *testing.T) { + tests := []struct { + name string + chunk1 string + chunk2 string + expected string + }{ + { + name: "close split after <", + chunk1: "AB secret <", + chunk2: "/memory> CD", + expected: "AB CD", + }, + { + name: "close split after secret CD", + expected: "AB CD", + }, + { + name: "close split after secret CD", + expected: "AB CD", + }, + { + name: "close split after secret CD", + expected: "AB CD", + }, + { + name: "close split after secret CD", + expected: "AB CD", + }, + { + name: "close split after secret CD", + expected: "AB CD", + }, + { + name: "close split after secret CD", + expected: "AB CD", + }, + { + name: "close split after secret CD", + expected: "AB CD", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + var buf bytes.Buffer + s := New(&buf) + + _, _ = s.Write([]byte(tt.chunk1)) + _, _ = s.Write([]byte(tt.chunk2)) + + if err := s.Flush(); err != nil { + t.Fatalf("Flush error: %v", err) + } + + if got := buf.String(); got != tt.expected { + t.Errorf("got %q, want %q", got, tt.expected) + } + }) + } +} + +func TestScrubber_PartialTag_NotActuallyATag(t *testing.T) { + // Text that looks like it could be a partial tag but isn't when the + // next chunk arrives. + tests := []struct { + name string + chunk1 string + chunk2 string + expected string + }{ + { + name: "literal < followed by x", + chunk1: "abc <", + chunk2: "x not a tag> def", + expected: "abc def", + }, + { + name: "literal def", + expected: "abc def", + }, + { + name: "literal def", + expected: "abc def", + }, + { + name: "partial in memory block not a close tag", + chunk1: "content more", + // "" is not "" — it doesn't close the block. + // Everything inside the memory block is stripped until the real + // is found (which closes the block). The " more" after + // the false close tag is also inside the memory block and is + // stripped. + expected: "", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + var buf bytes.Buffer + s := New(&buf) + + _, _ = s.Write([]byte(tt.chunk1)) + _, _ = s.Write([]byte(tt.chunk2)) + + if err := s.Flush(); err != nil { + t.Fatalf("Flush error: %v", err) + } + + if got := buf.String(); got != tt.expected { + t.Errorf("got %q, want %q", got, tt.expected) + } + }) + } +} + +func TestScrubber_LiteralAngleBrackets(t *testing.T) { + // Angle brackets that don't form memory tags should pass through. + s := New(nil) + result := s.ProcessString("if (x < 5 && y > 3) { doStuff(); }") + if result != "if (x < 5 && y > 3) { doStuff(); }" { + t.Errorf("got %q, want %q", result, "if (x < 5 && y > 3) { doStuff(); }") + } +} + +func TestScrubber_LiteralLtInMemoryBlock(t *testing.T) { + // '<' inside a memory block that's not part of a close tag — stripped. + s := New(nil) + result := s.ProcessString("before if (x < 5) { } after") + if result != "before after" { + t.Errorf("got %q, want %q", result, "before after") + } +} + +// ── Chunk boundary edge cases ────────────────────────────────────────── + +func TestScrubber_OpenTagAtExactChunkBoundary(t *testing.T) { + var buf bytes.Buffer + s := New(&buf) + + _, _ = s.Write([]byte("Hello ")) + _, _ = s.Write([]byte("secret")) + _, _ = s.Write([]byte(" World")) + + if err := s.Flush(); err != nil { + t.Fatalf("Flush error: %v", err) + } + + if got := buf.String(); got != "Hello World" { + t.Errorf("got %q, want %q", got, "Hello World") + } +} + +func TestScrubber_CloseTagAtExactChunkBoundary(t *testing.T) { + var buf bytes.Buffer + s := New(&buf) + + _, _ = s.Write([]byte("Hello secret")) + _, _ = s.Write([]byte(" World")) + + if err := s.Flush(); err != nil { + t.Fatalf("Flush error: %v", err) + } + + if got := buf.String(); got != "Hello World" { + t.Errorf("got %q, want %q", got, "Hello World") + } +} + +func TestScrubber_SingleByteChunks(t *testing.T) { + // Process input one byte at a time — stress test for state management. + input := "abcdefghi" + var buf bytes.Buffer + s := New(&buf) + + for i := 0; i < len(input); i++ { + _, _ = s.Write([]byte{input[i]}) + } + if err := s.Flush(); err != nil { + t.Fatalf("Flush error: %v", err) + } + + if got := buf.String(); got != "abcghi" { + t.Errorf("got %q, want %q", got, "abcghi") + } +} + +func TestScrubber_TwoByteChunks(t *testing.T) { + input := "abc" + var buf bytes.Buffer + s := New(&buf) + + for i := 0; i < len(input); i += 2 { + end := min(i+2, len(input)) + _, _ = s.Write([]byte(input[i:end])) + } + if err := s.Flush(); err != nil { + t.Fatalf("Flush error: %v", err) + } + + if got := buf.String(); got != "ac" { + t.Errorf("got %q, want %q", got, "ac") + } +} + +func TestScrubber_ChunkEndingWithOpenTagStart(t *testing.T) { + // Chunk ends exactly with "<" which might start a tag. + var buf bytes.Buffer + s := New(&buf) + + _, _ = s.Write([]byte("text <")) + _, _ = s.Write([]byte("notmemory> more")) + + if err := s.Flush(); err != nil { + t.Fatalf("Flush error: %v", err) + } + + if got := buf.String(); got != "text more" { + t.Errorf("got %q, want %q", got, "text more") + } +} + +// ── Streaming Write interface ────────────────────────────────────────── + +func TestScrubber_Write_ReturnsBytesConsumed(t *testing.T) { + var buf bytes.Buffer + s := New(&buf) + + input := []byte("hello") + n, err := s.Write(input) + if err != nil { + t.Fatalf("Write error: %v", err) + } + if n != len(input) { + t.Errorf("Write returned n=%d, want %d", n, len(input)) + } +} + +func TestScrubber_Write_EmptyChunk(t *testing.T) { + var buf bytes.Buffer + s := New(&buf) + + n, err := s.Write(nil) + if err != nil { + t.Fatalf("Write(nil) error: %v", err) + } + if n != 0 { + t.Errorf("Write(nil) returned n=%d, want 0", n) + } +} + +func TestScrubber_Flush_EmptyState(t *testing.T) { + var buf bytes.Buffer + s := New(&buf) + + // Flush with no writes should be a no-op. + if err := s.Flush(); err != nil { + t.Fatalf("Flush error: %v", err) + } + if buf.Len() != 0 { + t.Errorf("buf has %d bytes after empty flush, want 0", buf.Len()) + } +} + +func TestScrubber_Close(t *testing.T) { + var buf bytes.Buffer + s := New(&buf) + _, _ = s.Write([]byte("hello x B ", "y C"} + for _, ch := range chunks { + streamingResult.WriteString(s2.Process(ch)) + } + _ = s2.Flush() + streamingResult.WriteString(s2.Process("")) // drain any final output + + if streamingResult.String() != oneShot { + t.Errorf("streaming result %q != one-shot %q", streamingResult.String(), oneShot) + } +} + +func TestScrubber_Process_ReturnsOnlyNewOutput(t *testing.T) { + s := New(nil) + r1 := s.Process("hello secret world") + r3 := s.Process("") + + if r1 != "hello " { + t.Errorf("first Process = %q, want %q", r1, "hello ") + } + if r2 != " world" { + t.Errorf("second Process = %q, want %q", r2, " world") + } + if r3 != "" { + t.Errorf("third Process = %q, want %q", r3, "") + } +} + +func TestScrubber_ProcessString_CompleteInput(t *testing.T) { + s := New(nil) + + // ProcessString resets state, so we can reuse the same scrubber. + r1 := s.ProcessString("A x B") + r2 := s.ProcessString("C y D") + + if r1 != "A B" { + t.Errorf("first = %q, want %q", r1, "A B") + } + if r2 != "C D" { + t.Errorf("second = %q, want %q", r2, "C D") + } +} + +// ── Reset ────────────────────────────────────────────────────────────── + +func TestScrubber_Reset_MidStream(t *testing.T) { + var buf bytes.Buffer + s := New(&buf) + + _, _ = s.Write([]byte("A secret")) + if s.InMemoryBlock() == false { + t.Error("expected to be in memory block") + } + + // Reset both the scrubber and the output buffer to simulate a fresh start. + s.Reset() + buf.Reset() + + if s.InMemoryBlock() { + t.Error("after Reset, should not be in memory block") + } + if s.BlocksStripped() != 0 { + t.Errorf("BlocksStripped = %d after Reset, want 0", s.BlocksStripped()) + } + if s.Depth() != 0 { + t.Errorf("Depth = %d after Reset, want 0", s.Depth()) + } + + // After reset, should work like new. + _, _ = s.Write([]byte("clean gone text")) + _ = s.Flush() + + if got := buf.String(); got != "clean text" { + t.Errorf("after Reset: got %q, want %q", got, "clean text") + } +} + +// ── Stats tracking ──────────────────────────────────────────────────── + +func TestScrubber_Stats(t *testing.T) { + s := New(nil) + s.ProcessString("x abcdef y ghijk z") + + if s.BlocksStripped() != 2 { + t.Errorf("BlocksStripped = %d, want 2", s.BlocksStripped()) + } + // Tags: = 8, = 9 each → 17*2 = 34 + // Content: "abcdef" = 6, "ghijk" = 5 → 11 + // Total stripped: 34 + 11 = 45 + expectedBytes := int64(45) + if s.BytesStripped() != expectedBytes { + t.Errorf("BytesStripped = %d, want %d", s.BytesStripped(), expectedBytes) + } +} + +func TestScrubber_Stats_Reset(t *testing.T) { + s := New(nil) + s.ProcessString("a") + + if s.BlocksStripped() == 0 { + t.Fatal("expected blocks to be stripped") + } + + s.Reset() + + if s.BlocksStripped() != 0 { + t.Errorf("BlocksStripped = %d after Reset, want 0", s.BlocksStripped()) + } + if s.BytesStripped() != 0 { + t.Errorf("BytesStripped = %d after Reset, want 0", s.BytesStripped()) + } +} + +// ── InMemoryBlock / Depth ────────────────────────────────────────────── + +func TestScrubber_InMemoryBlock(t *testing.T) { + var buf bytes.Buffer + s := New(&buf) + + if s.InMemoryBlock() { + t.Error("InMemoryBlock should be false initially") + } + + _, _ = s.Write([]byte("before ")) + if !s.InMemoryBlock() { + t.Error("InMemoryBlock should be true after open tag") + } + + _, _ = s.Write([]byte("content after")) + if s.InMemoryBlock() { + t.Error("InMemoryBlock should be false after close tag") + } +} + +func TestScrubber_Depth(t *testing.T) { + var buf bytes.Buffer + s := New(&buf) + + if s.Depth() != 0 { + t.Errorf("Depth = %d initially, want 0", s.Depth()) + } + + _, _ = s.Write([]byte("")) + if s.Depth() != 1 { + t.Errorf("Depth = %d after first open, want 1", s.Depth()) + } + + _, _ = s.Write([]byte("")) + if s.Depth() != 2 { + t.Errorf("Depth = %d after second open, want 2", s.Depth()) + } + + _, _ = s.Write([]byte("")) + if s.Depth() != 1 { + t.Errorf("Depth = %d after first close, want 1", s.Depth()) + } + + _, _ = s.Write([]byte("")) + if s.Depth() != 0 { + t.Errorf("Depth = %d after second close, want 0", s.Depth()) + } +} + +// ── Nil writer ───────────────────────────────────────────────────────── + +func TestScrubber_NilWriter(t *testing.T) { + s := New(nil) + + input := []byte("some hidden text") + n, err := s.Write(input) + if err != nil { + t.Fatalf("Write error with nil writer: %v", err) + } + if n != len(input) { + t.Errorf("Write returned n=%d, want %d", n, len(input)) + } + + if err := s.Flush(); err != nil { + t.Fatalf("Flush error with nil writer: %v", err) + } +} + +// ── IO Writer integration ────────────────────────────────────────────── + +func TestScrubber_IOWriter_Chain(t *testing.T) { + // Verify Scrubber can be used as part of an io.Writer chain. + var buf bytes.Buffer + s := New(&buf) + + // Use io.WriteString which calls Write internally. + _, err := io.WriteString(s, "Hello hidden World") + if err != nil { + t.Fatalf("io.WriteString error: %v", err) + } + _ = s.Flush() + + if got := buf.String(); got != "Hello World" { + t.Errorf("got %q, want %q", got, "Hello World") + } +} + +// ── Complex scenarios ────────────────────────────────────────────────── + +func TestScrubber_MemoryBlockAcrossManyChunks(t *testing.T) { + // Simulates a memory block that spans many small chunks (as in + // real streaming LLM output). + content := "This is a very long memory block with lots of content " + + "that should be stripped. " + strings.Repeat("blah ", 200) + input := "visible_start" + content + "visible_end" + + var buf bytes.Buffer + s := New(&buf) + + // Chop into 3-byte chunks. + for i := 0; i < len(input); i += 3 { + end := min(i+3, len(input)) + _, _ = s.Write([]byte(input[i:end])) + } + _ = s.Flush() + + expected := "visible_startvisible_end" + if got := buf.String(); got != expected { + t.Errorf("got %q (len=%d), want %q (len=%d)", got, len(got), expected, len(expected)) + } +} + +func TestScrubber_ConsecutivePartialTags(t *testing.T) { + // Multiple partial tags in succession. + var buf bytes.Buffer + s := New(&buf) + + _, _ = s.Write([]byte("a <")) // partial + _, _ = s.Write([]byte("m")) // still partial + _, _ = s.Write([]byte("emory>")) // now it's complete! + _, _ = s.Write([]byte("hidden")) + _, _ = s.Write([]byte("")) // complete close + _, _ = s.Write([]byte("b")) + _ = s.Flush() + + if got := buf.String(); got != "a b" { + t.Errorf("got %q, want %q", got, "a b") + } +} + +func TestScrubber_MemoryLikeButNotExactly(t *testing.T) { + // Strings that look similar to memory tags but aren't. + tests := []struct { + name string + input string + want string + }{ + { + name: "memory without angle brackets", + input: "memory and /memory are not tags", + want: "memory and /memory are not tags", + }, + { + name: "angle bracket but wrong tag name", + input: "use
content
here", + want: "use
content
here", + }, + { + name: "unclosed angle bracket", + input: "the more text", + want: "text more text", + }, + { + name: "back-to-back memory blocks", + input: "AxyB", + want: "AB", + }, + { + name: "memory block at start", + input: "xB", + want: "B", + }, + { + name: "memory block at end", + input: "Ax", + want: "A", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + s := New(nil) + got := s.ProcessString(tt.input) + if got != tt.want { + t.Errorf("got %q, want %q", got, tt.want) + } + }) + } +} + +func TestScrubber_MalformedNested(t *testing.T) { + // Complex malformed nesting. + tests := []struct { + name string + input string + want string + }{ + { + name: "interleaved close tags", + input: "a
b", + want: "b", + }, + { + name: "open after close", + input: "b", + want: "", + }, + { + name: "deeply nested with missing close", + input: "ABCD", + want: "A", + }, + { + name: "partial nest resolution", + input: "ABCDE", + want: "AE", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + s := New(nil) + got := s.ProcessString(tt.input) + if got != tt.want { + t.Errorf("got %q, want %q", got, tt.want) + } + }) + } +} + +// ── UTF-8 / multibyte handling ───────────────────────────────────────── + +func TestScrubber_UnicodeContent(t *testing.T) { + s := New(nil) + result := s.ProcessString("BEFORE こんにちは世界 AFTER") + if result != "BEFORE AFTER" { + t.Errorf("got %q, want %q", result, "BEFORE AFTER") + } +} + +func TestScrubber_UnicodeOutsideMemoryBlock(t *testing.T) { + s := New(nil) + result := s.ProcessString("👋 hello secret 🌍 world") + if result != "👋 hello 🌍 world" { + t.Errorf("got %q, want %q", result, "👋 hello 🌍 world") + } +} + +func TestScrubber_UnicodeSplitAcrossChunks(t *testing.T) { + // Multi-byte UTF-8 character split across chunks after a partial tag. + var buf bytes.Buffer + s := New(&buf) + + // '世' is 3 bytes in UTF-8: E4 B8 96 + _, _ = s.Write([]byte("Hi ")) // completes the open tag + _, _ = s.Write([]byte("世界 Bye")) + + _ = s.Flush() + + if got := buf.String(); got != "Hi Bye" { + t.Errorf("got %q, want %q", got, "Hi Bye") + } +} + +// ── Benchmark-oriented correctness ───────────────────────────────────── + +func TestScrubber_LargeInput(t *testing.T) { + // Build a large input with many memory blocks. + var input strings.Builder + var expected strings.Builder + + input.WriteString("START ") + expected.WriteString("START ") + + for i := range 100 { + fmt.Fprintf(&input, " visible_%d ", i) + fmt.Fprintf(&expected, " visible_%d ", i) + + input.WriteString("") + fmt.Fprintf(&input, " hidden_block_%d ", i) + input.WriteString("") + } + + input.WriteString(" END") + expected.WriteString(" END") + + s := New(nil) + got := s.ProcessString(input.String()) + want := expected.String() + + if got != want { + if len(got) > 200 || len(want) > 200 { + t.Errorf("large output mismatch (got len=%d, want len=%d)", len(got), len(want)) + } else { + t.Errorf("got %q, want %q", got, want) + } + } +} + +// ── Regression: edge cases found during development ──────────────────── + +func TestScrubber_Regression_DoubleChevron(t *testing.T) { + // < should NOT be treated as because the first < is + // consumed as literal text, and then starts. + s := New(nil) + result := s.ProcessString("a <hidden b") + if result != "a < b" { + t.Errorf("got %q, want %q", result, "a < b") + } +} + +func TestScrubber_Regression_TagInTag(t *testing.T) { + // > — this is pathological but should not panic. + // The first 8 bytes "" (8th byte is '<', + // not '>'). So the leading '<' is emitted as literal text, "memory" + // passes through, then the second "" IS a valid open tag + // which strips everything until the matching . + s := New(nil) + result := s.ProcessString("x >test y") + // Output: "x <" (literal) + "memory" (text before second ) + " y" (after close) = "x test")) + + ds := s.DebugString() + if !strings.Contains(ds, "depth=1") { + t.Errorf("DebugString should contain depth=1: %s", ds) + } +} + +// ── Benchmarks ───────────────────────────────────────────────────────── + +func BenchmarkScrubber_NoMemoryBlock(b *testing.B) { + s := New(io.Discard) + input := []byte("This is normal text without any memory blocks at all.") + b.ResetTimer() + b.ReportAllocs() + for b.Loop() { + _, _ = s.Write(input) + } + _ = s.Flush() +} + +func BenchmarkScrubber_SingleMemoryBlock(b *testing.B) { + s := New(io.Discard) + input := []byte("Before hidden content here After") + b.ResetTimer() + b.ReportAllocs() + for b.Loop() { + s.Reset() + _, _ = s.Write(input) + _ = s.Flush() + } +} + +func BenchmarkScrubber_ManySmallChunks(b *testing.B) { + text := "This is a long text with some hidden content that should be stripped and more text here" + var chunks [][]byte + for i := 0; i < len(text); i += 3 { + end := min(i+3, len(text)) + chunks = append(chunks, []byte(text[i:end])) + } + + s := New(io.Discard) + b.ResetTimer() + b.ReportAllocs() + for b.Loop() { + s.Reset() + for _, ch := range chunks { + _, _ = s.Write(ch) + } + _ = s.Flush() + } +} + +func BenchmarkScrubber_ProcessString(b *testing.B) { + s := New(nil) + input := "Before hidden content here After" + b.ResetTimer() + b.ReportAllocs() + for b.Loop() { + s.ProcessString(input) + } +} + +func BenchmarkScrubber_LargeInputManyBlocks(b *testing.B) { + var input strings.Builder + for i := range 100 { + fmt.Fprintf(&input, "visible_%d ", i) + input.WriteString("") + fmt.Fprintf(&input, "hidden_%d ", i) + input.WriteString("") + } + data := []byte(input.String()) + + s := New(io.Discard) + b.ResetTimer() + b.ReportAllocs() + for b.Loop() { + s.Reset() + _, _ = s.Write(data) + _ = s.Flush() + } +} + +func BenchmarkScrubber_NestedBlocks(b *testing.B) { + s := New(io.Discard) + input := []byte("A B C DEFG") + b.ResetTimer() + b.ReportAllocs() + for b.Loop() { + s.Reset() + _, _ = s.Write(input) + _ = s.Flush() + } +}