feat: StreamingContextScrubber for memory-context fence stripping (18.10)
Stateful io.Writer that strips <memory>...</memory> fences from streaming output, handling partial chunks split across tag boundaries, nested tags, and missing closing tags.
This commit is contained in:
1 parent
f0c2a3eda5
commit
886591f674
3 files changed
+1391
-3
No files matched your search
+3
-3
@@ -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}
|
||||
|
||||
@@ -0,0 +1,319 @@
|
||||
// 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.
|
||||
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
|
||||
|
||||
// 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 <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.
|
||||
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 <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.
|
||||
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
Reference in new issue
Block a user