* feat(memory): four-scope contract with CRUD and revisions
Seam for memory unification slice 2 (docs/prds/memory-engine-unification.md
§1, §2, §7): internal/domain/memory is now a scope-addressed CRUD contract.
- Scope{Kind,Agent,User} with the four ratified kinds, Validate rejecting a
component present where it is not required, and a length-prefixed Key so
opaque channel-native ids cannot collide.
- Subject{AgentID,UserID} with Scopes()/WritableScopes(): global is never
writable, and an absent user id removes every scope requiring one.
- Store becomes Create/Get/Query/List/Update/Forget/Revisions over
NewRecord/RecordUpdate/Record/Revision, with ErrNotFound/ErrStaleRevision.
Observation, Identity and Metadata are deleted.
- The content scanner moves into the family (internal/domain/memory) so every
engine applies it in Create and Update; internal/memory re-exports the types
until slice 5 deletes it.
- The markdown store moves to internal/infrastructure/memory/builtin, its
correct home per organisation.md.
WIP: internal/infrastructure/memory and internal/infrastructure/sessioncurator
are converted in the lanes that follow this commit.
* feat(memory): builtin engine CRUD, retained revisions and the curator's agent-user write
Slice 2 implementation (docs/prds/memory-engine-unification.md §1, §2, §6,
§7), on top of the contract seam in the previous commit.
- internal/infrastructure/memory: per-scope markdown heads with a JSON
provenance marker, per-scope HISTORY.md retaining superseded and deleted
states, Update superseding before replacing the live block, ErrStaleRevision
via RecordUpdate.Expected, idempotent Forget, and the family scanner applied
in Create and Update. Scope directories are hex(sha256(Scope.Key())).
- internal/infrastructure/sessioncurator: the participant is derived from the
session's user-role senders; exactly one writes agent-user scope, zero or
several write nothing and return ActionSkipped naming the count.
- docs/architecture: the settled decision recorded in migration-decisions §5
(superseding the 2026-09-02 marker entry) and agent-system.md pointing at it.
Draft: to be squashed and reviewed before publication.
* test(curator): conform the registry's fake memory engine to the CRUD contract
The fake still implemented the pre-CRUD Store surface (Write taking an
Observation, List/Forget keyed by a bare string), so the package's test
binary no longer compiles: fakeMemoryEngine is missing Create, Get, Update
and Revisions, and domainmemory.Observation no longer exists. That took
`go fix ./...`, `go vet ./...` and `go test ./...` down with it, which is
what `task check` runs first.
Missed by the same commit that updated internal/infrastructure/sessioncurator's
own fake to the new interface. Repaired on the fake, not by loosening the
interface: the fake is the only thing out of date.
* fix(sessioncurator): refuse to attribute a session with unidentified user messages
sessionParticipant skipped user-role messages with an empty SenderID and
counted only the identified ones, so a session holding one identified sender
plus any number of unidentified user messages yielded that sender as the
single participant. Those messages are still part of the excerpt the
extraction model reads, so facts derived from content of unknown provenance
were written into the identified sender's agent-user scope: user A's memory
can end up crediting content that may belong to someone else. It is exactly
the case the function's own doc comment claims to handle, which it only
caught when no message at all was identified.
An unidentified user message now makes the session unattributable outright,
beside any number of identified senders, and the skip action's reason names
the count instead of reporting a sender count that no longer explains the
skip. Assistant-role messages are unaffected: they carry the bot, so they
still cannot manufacture a participant.
Fixed in sessionParticipant rather than at the write, because it is the
single producer of the attribution decision: it now returns the participant
or the reason there is none, so the caller cannot print a reason that
disagrees with what it decided. The fail-closed path (nothing written, one
ActionSkipped) and the extraction flow are unchanged.
* fix(memory): carry record content through the block format intact
builtin.Store's format ends a block at a blank line and starts a section at a
"## " line, but storeContent only trimmed the content and rejected an empty
one. Content holding either delimiter was accepted, written, and answered back
to the caller in full -- then read back truncated at the delimiter by Get,
List, or a process restart, with the remainder unaddressable and no error
anywhere along the path.
Fixed at the producer, in the render/parse pair that owns the block format:
renderBlock escapes the two delimiter shapes (an empty line becomes a single
backslash, a line already starting with a backslash or "## " gains one) and
parseBlocks undoes it on the way back, so a record's content survives the
write whole. Rejecting the content instead would have made an ordinary
multi-paragraph note or a quoted heading unrepresentable; escaping every line
would have changed the on-disk shape of every record. Only the lines that need
it are escaped, so a one-paragraph record is byte-identical to what the
unfixed engine wrote and the document stays hand-editable.
Reachable from both producers: the chat tool's note and the curator's
model-extracted fact are free text, and neither is constrained to one
paragraph.
Tests: TestBuiltinEngineRenderedBlockRoundTripsContent asserts
parseBlocks(renderBlock(c)) == c for eleven content shapes, and
TestBuiltinEngineContentSurvivesTheWriteAndAReopen carries the same shapes
through Create, Get, and a second engine reading the file a restart would.
* fix(memory): compare Update's expected revision against the file, not the cache
Update read the record to compare against out of findBlock(stores.live, ...)
-- the engine's cached copy of the scope document -- and checked Expected
against that copy. This engine caches one document per scope and rewrites it
whole, so a second engine over the same scope file (archied and the gateway,
or a restart) holds a copy taken when it last read the file: its view of the
record's revision is superseded, Expected matches the revision it remembers,
ErrStaleRevision never fires, and the rewrite that follows writes that stale
copy back over the file -- discarding the other writer's update and every
record written since the copy was loaded. The field existed and could not
fire.
Reload the scope document before anything is decided from it, so the check
answers about the revision actually on disk and the rewrite starts from the
current document. That is the smaller of the two fixes the PRD leaves open
("Not determined": a reload-before-mutate or an advisory lock); no locking
scheme, no retry loop, and no change to the read paths.
Still unsolved, and deliberately: the whole-document rewrite is
last-writer-wins between the reload and the write, so two engines writing one
scope concurrently can still lose one of the two writes, and HISTORY.md is
rewritten from the cached copy the same way.
Tests: TestBuiltinEngineSecondEngineCannotReuseAStaleRevision asserts the
second engine gets ErrStaleRevision and the first writer's state survives;
TestBuiltinEngineUpdateDoesNotEraseRecordsItHasNotLoaded asserts the record
written after the second engine loaded is still there after its update.
* fix(memory): emit the scanner's warning instead of dropping it
scanContent returned nil for every result that was not ThreatBlock, so a
ThreatWarn result -- documented in the scanner as "allow the write but emit a
warning", and what every sensitive-data match produces (API keys, passwords,
tokens, private keys) -- was stored with no audit signal anywhere. The
comment justified the silence by pointing at Bind, but Bind's argument is
about Registrar.Events: internal/events declares no memory kind and the
composition binds no memory event sink, so an invented kind would look wired
and not be. A scanner warning is a diagnostic rather than an event, and there
was nothing else to carry it: the registrar had no logger.
Bind now takes Registrar.Log, optional and mirroring the curator family's
Registrar for the same reason, scanContent emits the warn-level result
through it before the write is allowed, and bootstrap passes the daemon's
logger so the line reaches archied's configured sinks instead of only the
process default. The write is still allowed: only the silence changed.
Tests: TestBuiltinEngineScanWarnsWithoutRefusingTheWrite runs Create and
Update over warn, clean and block content, asserting the write lands either
way, that a warn-level scan result logs exactly one warning carrying the
scanner's own message, that clean content logs none, and that a refused
block-level match logs none.
* test(memory): carry every content shape through Update and Revisions
Update replaces the block it read out of the document by that text, and
retains the superseded state in HISTORY.md, so an escaped block has to be
found, superseded and retained exactly like an unescaped one. Covered here
rather than left to the Create path: without the escaping, every shape in
this table came back truncated after an update, including the plain
one-paragraph record whose replacement holds a blank line.
The test asserts values only: the updated record as a second engine reads it
off disk, and the superseded content as Revisions returns it.
* style(memory): apply the linter's gofumpt form to the Update revision error
golangci-lint's bundled gofumpt wants the closing paren of that wrapped
fmt.Errorf on its own line; the standalone gofumpt binary the fmt task uses
(0.7.0, a different version) leaves it as it was. The text is unchanged from
before the engine fixes in this branch, so this is pre-existing drift inside a
function these commits already touch -- taken so the file is clean under both
formatters rather than only one.
501 lines
15 KiB
Go
501 lines
15 KiB
Go
// Package builtin implements the built-in, file-backed MemoryProvider. It
|
|
// persists agent memory to MEMORY.md and USER.md as plain markdown, using
|
|
// "## " headers to delimit named sections. Content within a section is
|
|
// organized into blank-line-separated blocks; add/replace/remove act on
|
|
// those blocks and on substrings within them.
|
|
package builtin
|
|
|
|
import (
|
|
"fmt"
|
|
"os"
|
|
"path/filepath"
|
|
"regexp"
|
|
"strings"
|
|
"sync"
|
|
)
|
|
|
|
// defaultMaxFileBytes is the default per-file size bound (100KB).
|
|
const defaultMaxFileBytes = 100 * 1024
|
|
|
|
// sectionNamePattern restricts section names to alphanumerics and spaces,
|
|
// matching the tool's input-validation contract.
|
|
var sectionNamePattern = regexp.MustCompile(`^[A-Za-z0-9 ]{1,64}$`)
|
|
|
|
// ValidateSectionName reports an error if name is empty, too long, or
|
|
// contains characters outside [A-Za-z0-9 ].
|
|
func ValidateSectionName(name string) error {
|
|
if !sectionNamePattern.MatchString(name) {
|
|
return fmt.Errorf("builtin: invalid section name %q: must be 1-64 alphanumeric/space characters", name)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// section is a named markdown block within a store file. blocks holds the
|
|
// section's content split into blank-line-separated paragraphs.
|
|
type section struct {
|
|
name string
|
|
blocks []string
|
|
}
|
|
|
|
// clone returns a deep copy of the section so callers can mutate a
|
|
// candidate version without touching the committed state.
|
|
func (s *section) clone() *section {
|
|
blocks := make([]string, len(s.blocks))
|
|
copy(blocks, s.blocks)
|
|
return §ion{name: s.name, blocks: blocks}
|
|
}
|
|
|
|
// Store is a thread-safe, size-bounded, file-backed markdown document. It
|
|
// reads its full content at construction and rewrites the whole file on
|
|
// every mutation.
|
|
type Store struct {
|
|
mu sync.RWMutex
|
|
path string
|
|
maxBytes int
|
|
|
|
preamble string
|
|
sections []*section
|
|
}
|
|
|
|
// NewStore loads path if it exists (creating an empty in-memory document
|
|
// otherwise) and returns a Store bounded to maxBytes. maxBytes <= 0 uses
|
|
// defaultMaxFileBytes.
|
|
func NewStore(path string, maxBytes int) (*Store, error) {
|
|
if maxBytes <= 0 {
|
|
maxBytes = defaultMaxFileBytes
|
|
}
|
|
s := &Store{path: path, maxBytes: maxBytes}
|
|
|
|
data, err := os.ReadFile(path)
|
|
if err != nil {
|
|
if os.IsNotExist(err) {
|
|
return s, nil
|
|
}
|
|
return nil, fmt.Errorf("builtin: reading %s: %w", path, err)
|
|
}
|
|
s.preamble, s.sections = parseSections(string(data))
|
|
return s, nil
|
|
}
|
|
|
|
// emptyStore returns a Store bound to path with no content, for a file that
|
|
// could not be read. Reads answer as empty and a later write still attempts
|
|
// the file, so a directory that becomes usable repairs itself.
|
|
func emptyStore(path string, maxBytes int) *Store {
|
|
if maxBytes <= 0 {
|
|
maxBytes = defaultMaxFileBytes
|
|
}
|
|
return &Store{path: path, maxBytes: maxBytes}
|
|
}
|
|
|
|
// Reload re-reads the backing file from disk, replacing all in-memory
|
|
// state. A missing file resets the store to empty rather than erroring.
|
|
func (s *Store) Reload() error {
|
|
data, err := os.ReadFile(s.path)
|
|
if err != nil {
|
|
if os.IsNotExist(err) {
|
|
s.mu.Lock()
|
|
s.preamble, s.sections = "", nil
|
|
s.mu.Unlock()
|
|
return nil
|
|
}
|
|
return fmt.Errorf("builtin: reading %s: %w", s.path, err)
|
|
}
|
|
|
|
preamble, sections := parseSections(string(data))
|
|
s.mu.Lock()
|
|
s.preamble, s.sections = preamble, sections
|
|
s.mu.Unlock()
|
|
return nil
|
|
}
|
|
|
|
// Path returns the file path backing this store.
|
|
func (s *Store) Path() string {
|
|
return s.path
|
|
}
|
|
|
|
// MaxBytes returns the configured size bound for this store.
|
|
func (s *Store) MaxBytes() int {
|
|
return s.maxBytes
|
|
}
|
|
|
|
// Render returns the current serialized document. Safe for concurrent use.
|
|
func (s *Store) Render() string {
|
|
s.mu.RLock()
|
|
defer s.mu.RUnlock()
|
|
return renderSections(s.preamble, s.sections)
|
|
}
|
|
|
|
// Size returns the current serialized document length in bytes.
|
|
func (s *Store) Size() int {
|
|
s.mu.RLock()
|
|
defer s.mu.RUnlock()
|
|
return len(renderSections(s.preamble, s.sections))
|
|
}
|
|
|
|
// AddResult describes the outcome of a successful Add.
|
|
type AddResult struct {
|
|
Section string
|
|
CharsAdded int
|
|
SectionChars int
|
|
FileBytes int
|
|
Created bool // true if the section did not exist before this call
|
|
}
|
|
|
|
// Add appends content as a new block in the named section, creating the
|
|
// section if it does not already exist. The write is rejected -- with no
|
|
// change to in-memory state or disk -- if the resulting file would exceed
|
|
// the store's size bound.
|
|
func (s *Store) Add(sectionName, content string) (AddResult, error) {
|
|
if err := ValidateSectionName(sectionName); err != nil {
|
|
return AddResult{}, err
|
|
}
|
|
content = strings.TrimSpace(content)
|
|
if content == "" {
|
|
return AddResult{}, fmt.Errorf("builtin: content must not be empty")
|
|
}
|
|
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
|
|
candidate := cloneSections(s.sections)
|
|
sec, created := findOrCreateSection(&candidate, sectionName)
|
|
sec.blocks = append(sec.blocks, content)
|
|
|
|
rendered := renderSections(s.preamble, candidate)
|
|
if len(rendered) > s.maxBytes {
|
|
return AddResult{}, fmt.Errorf("builtin: add to section %q would exceed max file size (%d > %d bytes)", sectionName, len(rendered), s.maxBytes)
|
|
}
|
|
if err := writeFileAtomic(s.path, rendered); err != nil {
|
|
return AddResult{}, err
|
|
}
|
|
|
|
s.sections = candidate
|
|
return AddResult{
|
|
Section: sectionName,
|
|
CharsAdded: len(content),
|
|
SectionChars: sectionChars(sec),
|
|
FileBytes: len(rendered),
|
|
Created: created,
|
|
}, nil
|
|
}
|
|
|
|
// ReplaceResult describes the outcome of a successful Replace.
|
|
type ReplaceResult struct {
|
|
Section string
|
|
CharsRemoved int
|
|
CharsAdded int
|
|
SectionChars int
|
|
FileBytes int
|
|
}
|
|
|
|
// Replace finds the first occurrence of substring within the named
|
|
// section's content and replaces it with replacement. It returns an error
|
|
// if the section does not exist, if substring is not found, or if the
|
|
// result would exceed the store's size bound.
|
|
func (s *Store) Replace(sectionName, substring, replacement string, caseSensitive bool) (ReplaceResult, error) {
|
|
if err := ValidateSectionName(sectionName); err != nil {
|
|
return ReplaceResult{}, err
|
|
}
|
|
if substring == "" {
|
|
return ReplaceResult{}, fmt.Errorf("builtin: substring must not be empty")
|
|
}
|
|
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
|
|
candidate := cloneSections(s.sections)
|
|
sec := findSection(candidate, sectionName)
|
|
if sec == nil {
|
|
return ReplaceResult{}, fmt.Errorf("builtin: section %q not found", sectionName)
|
|
}
|
|
|
|
blockIdx, pos, matchLen := findInBlocks(sec.blocks, substring, caseSensitive)
|
|
if blockIdx < 0 {
|
|
return ReplaceResult{}, fmt.Errorf("builtin: substring %q not found in section %q", substring, sectionName)
|
|
}
|
|
|
|
block := sec.blocks[blockIdx]
|
|
sec.blocks[blockIdx] = block[:pos] + replacement + block[pos+matchLen:]
|
|
|
|
rendered := renderSections(s.preamble, candidate)
|
|
if len(rendered) > s.maxBytes {
|
|
return ReplaceResult{}, fmt.Errorf("builtin: replace in section %q would exceed max file size (%d > %d bytes)", sectionName, len(rendered), s.maxBytes)
|
|
}
|
|
if err := writeFileAtomic(s.path, rendered); err != nil {
|
|
return ReplaceResult{}, err
|
|
}
|
|
|
|
s.sections = candidate
|
|
return ReplaceResult{
|
|
Section: sectionName,
|
|
CharsRemoved: matchLen,
|
|
CharsAdded: len(replacement),
|
|
SectionChars: sectionChars(sec),
|
|
FileBytes: len(rendered),
|
|
}, nil
|
|
}
|
|
|
|
// RemoveResult describes the outcome of a successful Remove.
|
|
type RemoveResult struct {
|
|
Section string
|
|
CharsRemoved int
|
|
SectionChars int
|
|
FileBytes int
|
|
}
|
|
|
|
// Remove deletes the first block within the named section whose text
|
|
// contains substring. It returns an error if the section does not exist
|
|
// or if no block matches.
|
|
func (s *Store) Remove(sectionName, substring string, caseSensitive bool) (RemoveResult, error) {
|
|
if err := ValidateSectionName(sectionName); err != nil {
|
|
return RemoveResult{}, err
|
|
}
|
|
if substring == "" {
|
|
return RemoveResult{}, fmt.Errorf("builtin: substring must not be empty")
|
|
}
|
|
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
|
|
candidate := cloneSections(s.sections)
|
|
sec := findSection(candidate, sectionName)
|
|
if sec == nil {
|
|
return RemoveResult{}, fmt.Errorf("builtin: section %q not found", sectionName)
|
|
}
|
|
|
|
blockIdx, _, _ := findInBlocks(sec.blocks, substring, caseSensitive)
|
|
if blockIdx < 0 {
|
|
return RemoveResult{}, fmt.Errorf("builtin: substring %q not found in section %q", substring, sectionName)
|
|
}
|
|
|
|
removed := sec.blocks[blockIdx]
|
|
sec.blocks = append(sec.blocks[:blockIdx], sec.blocks[blockIdx+1:]...)
|
|
|
|
rendered := renderSections(s.preamble, candidate)
|
|
// Removal only ever shrinks the file, but a bound check is kept for
|
|
// consistency with Add/Replace and to guard against pathological
|
|
// preamble/header growth from re-serialization.
|
|
if len(rendered) > s.maxBytes {
|
|
return RemoveResult{}, fmt.Errorf("builtin: remove from section %q would exceed max file size (%d > %d bytes)", sectionName, len(rendered), s.maxBytes)
|
|
}
|
|
if err := writeFileAtomic(s.path, rendered); err != nil {
|
|
return RemoveResult{}, err
|
|
}
|
|
|
|
s.sections = candidate
|
|
return RemoveResult{
|
|
Section: sectionName,
|
|
CharsRemoved: len(removed),
|
|
SectionChars: sectionChars(sec),
|
|
FileBytes: len(rendered),
|
|
}, nil
|
|
}
|
|
|
|
// ── Parsing & rendering ────────────────────────────────────────────────
|
|
|
|
// sectionHeaderPrefix is the markdown header marker that delimits sections.
|
|
const sectionHeaderPrefix = "## "
|
|
|
|
// parseSections splits document content into a preamble (any content before
|
|
// the first section header) and an ordered list of sections. Each section's
|
|
// body is split into blocks on blank lines.
|
|
func parseSections(content string) (preamble string, sections []*section) {
|
|
lines := strings.Split(content, "\n")
|
|
|
|
var preambleLines []string
|
|
var cur *section
|
|
var bodyLines []string
|
|
|
|
flush := func() {
|
|
if cur != nil {
|
|
cur.blocks = splitBlocks(bodyLines)
|
|
sections = append(sections, cur)
|
|
}
|
|
bodyLines = nil
|
|
}
|
|
|
|
for _, line := range lines {
|
|
if strings.HasPrefix(line, sectionHeaderPrefix) {
|
|
flush()
|
|
name := strings.TrimSpace(strings.TrimPrefix(line, sectionHeaderPrefix))
|
|
cur = §ion{name: name}
|
|
continue
|
|
}
|
|
if cur == nil {
|
|
preambleLines = append(preambleLines, line)
|
|
} else {
|
|
bodyLines = append(bodyLines, line)
|
|
}
|
|
}
|
|
flush()
|
|
|
|
preamble = strings.TrimRight(strings.Join(preambleLines, "\n"), "\n \t")
|
|
return preamble, sections
|
|
}
|
|
|
|
// splitBlocks groups lines into blank-line-separated blocks, trimming
|
|
// leading/trailing blank lines and skipping empty blocks.
|
|
func splitBlocks(lines []string) []string {
|
|
var blocks []string
|
|
var cur []string
|
|
|
|
flush := func() {
|
|
if len(cur) > 0 {
|
|
blocks = append(blocks, strings.TrimRight(strings.Join(cur, "\n"), "\n"))
|
|
cur = nil
|
|
}
|
|
}
|
|
|
|
for _, line := range lines {
|
|
if strings.TrimSpace(line) == "" {
|
|
flush()
|
|
continue
|
|
}
|
|
cur = append(cur, line)
|
|
}
|
|
flush()
|
|
return blocks
|
|
}
|
|
|
|
// renderSections serializes a preamble and ordered sections back into the
|
|
// on-disk markdown format.
|
|
func renderSections(preamble string, sections []*section) string {
|
|
var sb strings.Builder
|
|
if preamble != "" {
|
|
sb.WriteString(preamble)
|
|
if len(sections) > 0 {
|
|
sb.WriteString("\n\n")
|
|
} else {
|
|
sb.WriteString("\n")
|
|
}
|
|
}
|
|
for i, sec := range sections {
|
|
if i > 0 {
|
|
sb.WriteString("\n")
|
|
}
|
|
sb.WriteString(sectionHeaderPrefix)
|
|
sb.WriteString(sec.name)
|
|
sb.WriteString("\n")
|
|
if len(sec.blocks) > 0 {
|
|
sb.WriteString("\n")
|
|
for j, block := range sec.blocks {
|
|
if j > 0 {
|
|
sb.WriteString("\n\n")
|
|
}
|
|
sb.WriteString(block)
|
|
}
|
|
sb.WriteString("\n")
|
|
}
|
|
}
|
|
return sb.String()
|
|
}
|
|
|
|
// sectionChars returns the serialized character count of a single section's
|
|
// body (blocks only, joined as they would appear on disk).
|
|
func sectionChars(sec *section) int {
|
|
return len(strings.Join(sec.blocks, "\n\n"))
|
|
}
|
|
|
|
// cloneSections returns a deep copy of a section slice.
|
|
func cloneSections(sections []*section) []*section {
|
|
out := make([]*section, len(sections))
|
|
for i, sec := range sections {
|
|
out[i] = sec.clone()
|
|
}
|
|
return out
|
|
}
|
|
|
|
// findSection returns the section with the given name, or nil.
|
|
func findSection(sections []*section, name string) *section {
|
|
for _, sec := range sections {
|
|
if sec.name == name {
|
|
return sec
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// findOrCreateSection returns the named section from *sections, appending a
|
|
// new empty section (and reporting created=true) if none exists.
|
|
func findOrCreateSection(sections *[]*section, name string) (sec *section, created bool) {
|
|
if sec := findSection(*sections, name); sec != nil {
|
|
return sec, false
|
|
}
|
|
sec = §ion{name: name}
|
|
*sections = append(*sections, sec)
|
|
return sec, true
|
|
}
|
|
|
|
// findInBlocks searches blocks in order for the first occurrence of
|
|
// substring, returning the block index, the byte offset within that block,
|
|
// and the byte length of the match. Returns (-1, -1, 0) if not found.
|
|
func findInBlocks(blocks []string, substring string, caseSensitive bool) (blockIdx, pos, matchLen int) {
|
|
for i, block := range blocks {
|
|
if caseSensitive {
|
|
if idx := strings.Index(block, substring); idx >= 0 {
|
|
return i, idx, len(substring)
|
|
}
|
|
continue
|
|
}
|
|
if idx, l := indexFold(block, substring); idx >= 0 {
|
|
return i, idx, l
|
|
}
|
|
}
|
|
return -1, -1, 0
|
|
}
|
|
|
|
// indexFold finds the first byte index in haystack where a substring of the
|
|
// same rune length as needle case-insensitively equals needle, using
|
|
// strings.EqualFold for comparison. Returns (-1, 0) if not found.
|
|
func indexFold(haystack, needle string) (int, int) {
|
|
needleRunes := len([]rune(needle))
|
|
runes := []rune(haystack)
|
|
for i := range runes {
|
|
if i+needleRunes > len(runes) {
|
|
break
|
|
}
|
|
candidate := string(runes[i : i+needleRunes])
|
|
if strings.EqualFold(candidate, needle) {
|
|
// Translate the rune index back to a byte offset.
|
|
byteOffset := len(string(runes[:i]))
|
|
return byteOffset, len(candidate)
|
|
}
|
|
}
|
|
return -1, 0
|
|
}
|
|
|
|
// writeFileAtomic writes content to path by writing to a temp file in the
|
|
// same directory and renaming it into place, so a crash mid-write cannot
|
|
// leave a truncated file behind.
|
|
func writeFileAtomic(path, content string) error {
|
|
dir := filepath.Dir(path)
|
|
if err := os.MkdirAll(dir, 0o755); err != nil {
|
|
return fmt.Errorf("builtin: creating directory %s: %w", dir, err)
|
|
}
|
|
|
|
tmp, err := os.CreateTemp(dir, ".tmp-*")
|
|
if err != nil {
|
|
return fmt.Errorf("builtin: creating temp file in %s: %w", dir, err)
|
|
}
|
|
tmpPath := tmp.Name()
|
|
|
|
if _, err := tmp.WriteString(content); err != nil {
|
|
_ = tmp.Close()
|
|
_ = os.Remove(tmpPath)
|
|
return fmt.Errorf("builtin: writing %s: %w", path, err)
|
|
}
|
|
if err := tmp.Close(); err != nil {
|
|
_ = os.Remove(tmpPath)
|
|
return fmt.Errorf("builtin: closing %s: %w", path, err)
|
|
}
|
|
if err := os.Chmod(tmpPath, 0o644); err != nil {
|
|
_ = os.Remove(tmpPath)
|
|
return fmt.Errorf("builtin: setting permissions on %s: %w", path, err)
|
|
}
|
|
if err := os.Rename(tmpPath, path); err != nil {
|
|
_ = os.Remove(tmpPath)
|
|
return fmt.Errorf("builtin: renaming into %s: %w", path, err)
|
|
}
|
|
return nil
|
|
}
|