Files
knox/internal/ingest/snippets.go
david 8d6d73b747 fix: read opencode sessions from session_v2/session_message (#7)
Fixes #6.

opencode 2.0.24 migrated its session store on 2026-11-01 21:01:20 UTC. `session`, `message` and `part` stopped being written; sessions now live in `session_v2` and messages in `session_message`. The ingest kept querying the abandoned tables, so every sweep after the migration logged `0 new` — no error, no new sessions indexed.

## Changes

- **`internal/ingest/opencode_db.go`**
  - Read sessions from `session_v2` (title is nullable there, the existing COALESCE + fallback still apply).
  - Rebuild transcripts from both message shapes: user turns at `$.text`, assistant turns from `$.content[]` filtered to `type='text'` (reasoning and tool parts are not indexed). Ordered by `seq`, then part index.
  - Count messages from `session_message` instead of parts.
  - Drop `<system-reminder>` text — reminders now arrive as `synthetic` messages and would eat the 4000-byte summary budget.
  - Ingester version is now `opencode-db/v2`.
- **`internal/watch/watch.go`** — an entry is no longer skipped on `created_at` alone. Resuming a session appends messages without touching the creation time, so the summary is compared too.
- **`internal/ingest/opencode_db_test.go`** — new test builds the v2 schema in a temp SQLite database and asserts user text and assistant text parts are indexed while reasoning, tool and reminder content is not.

## Validation

- `go build ./...`, `go test ./internal/ingest/ ./internal/db/ ./internal/watch/` pass.
- Rebuilt the binary and restarted `knox.service` against the live store:
  ```
  [knox] opencode.db: 1 new, 387 unchanged
  ```
  The new entry is the session that had been invisible since the migration (`Knox OpenCode session adapter compatibility check`, observation version `opencode-db/v2`), and `knox query "knox opencode session adapter compatibility"` finds it.
- 59 pre-migration sessions re-recorded because their stored transcripts contained reminder text that the new filter drops; summaries still carry the conversation.

## Notes

The first commit on this branch is a checkpoint of pre-existing uncommitted work that the adapter fix sits on top of; the fix itself is the second commit (`e07ae8a`).

Reviewed-on: #7
Co-authored-by: David Gwilliam <dhgwilliam@gmail.com>
Co-committed-by: David Gwilliam <dhgwilliam@gmail.com>
2026-11-02 01:16:50 +00:00

884 lines
22 KiB
Go

package ingest
import (
"database/sql"
"encoding/json"
"fmt"
"os"
"path/filepath"
"regexp"
"sort"
"strings"
_ "modernc.org/sqlite"
)
// SnippetExtractor mines opencode sessions for code that *demonstrably worked*.
//
// It is deliberately LLM-free and conservative: only tool calls that completed
// successfully become candidates, and a file that was later fully rewritten
// (a later `write` to the same path) marks its earlier snippets superseded —
// a dead end. Bash calls are mined (set KNOX_SNIPPET_BASH=0 to disable) because
// code is often written by hand there as a heredoc body; plain throwaway shell
// one-liners are dropped. Judgment about what is worth keeping is left to the
// agent that calls the MCP encode/reject tools.
//
// The output is candidate *raw material*; it is not curated until an agent
// encodes it. Identical code dedups by content hash, so the same snippet reused
// across sessions collapses to one row.
type SnippetExtractor struct {
Version string
Path string // defaults to ~/.local/share/opencode/opencode.db
IncludeBash bool
}
const (
snippetMinCode = 30
snippetMaxCode = 32000
snippetCodeCap = 200 // candidates kept per session
)
// SnippetCandidate is one extracted code snippet with its provenance.
type SnippetCandidate struct {
Fingerprint string
Language string
Code string
Title string
Description string
Tags string
SourceSession string
SourcePath string
SourceEntry string
Project string
Tool string
Model string
PatchHash string
Evidence string
SupersededBy string
Junk bool
Kind string
}
func NewSnippetExtractor() *SnippetExtractor {
return &SnippetExtractor{
Version: "snippet-extract/v1",
IncludeBash: os.Getenv("KNOX_SNIPPET_BASH") != "0",
}
}
type ocPart struct {
Session string
Message string
Model string
Time int64
Kind string // tool | patch | other
Tool string
Status string
Input string
Metadata string
Err string
PatchHash string
}
type toolInput struct {
FilePath string `json:"filePath"`
Content string `json:"content"`
NewString string `json:"newString"`
Command string `json:"command"`
Description string `json:"description"`
}
type toolMeta struct {
Exit *int `json:"exit"`
Output string `json:"output"`
Diagnostics map[string][]diagEntry `json:"diagnostics"`
}
type diagEntry struct {
Code string `json:"code"`
Message string `json:"message"`
}
// ExtractAll sweeps opencode.db and returns one candidate per successful,
// not-superseded code-producing tool call.
func (e *SnippetExtractor) ExtractAll() ([]SnippetCandidate, error) {
path := e.Path
if path == "" {
home, err := os.UserHomeDir()
if err != nil {
return nil, fmt.Errorf("home dir: %w", err)
}
path = filepath.Join(home, opencodeDBPath)
}
if _, err := os.Stat(path); err != nil {
return nil, fmt.Errorf("opencode db: %w", err)
}
db, err := sql.Open("sqlite", "file:"+path+"?mode=ro&_pragma=busy_timeout(5000)")
if err != nil {
return nil, fmt.Errorf("open opencode db: %w", err)
}
defer db.Close()
sessions, err := loadOCSessions(db)
if err != nil {
return nil, err
}
dirOf := make(map[string]string, len(sessions))
for _, s := range sessions {
dirOf[s.ID] = s.Directory
}
rows, err := db.Query(
`SELECT p.session_id,
COALESCE(p.message_id,''),
COALESCE(json_extract(m.data,'$.modelID'),''),
COALESCE(p.time_created,0),
COALESCE(json_extract(p.data,'$.type'),''),
COALESCE(json_extract(p.data,'$.tool'),''),
COALESCE(json_extract(p.data,'$.state.status'),''),
COALESCE(json_extract(p.data,'$.state.input'),''),
COALESCE(json_extract(p.data,'$.state.metadata'),''),
COALESCE(json_extract(p.data,'$.state.error'),''),
COALESCE(json_extract(p.data,'$.hash'),'')
FROM part p JOIN message m ON m.id = p.message_id
WHERE json_extract(p.data,'$.type') IN ('tool','patch')
ORDER BY p.session_id, p.time_created`)
if err != nil {
return nil, fmt.Errorf("query parts: %w", err)
}
defer rows.Close()
var (
out []SnippetCandidate
curSession string
events []ocPart
)
flush := func() {
if curSession == "" || len(events) == 0 {
return
}
out = append(out, e.processSession(curSession, dirOf[curSession], events)...)
events = events[:0]
}
for rows.Next() {
var p ocPart
if err := rows.Scan(&p.Session, &p.Message, &p.Model, &p.Time, &p.Kind,
&p.Tool, &p.Status, &p.Input, &p.Metadata, &p.Err, &p.PatchHash); err != nil {
return nil, err
}
if p.Session != curSession {
flush()
curSession = p.Session
}
events = append(events, p)
}
if err := rows.Err(); err != nil {
return nil, err
}
flush()
return dedupPrimaries(out), nil
}
func (e *SnippetExtractor) processSession(sessionID, directory string, events []ocPart) []SnippetCandidate {
project := ""
if directory != "" {
project = filepath.Base(directory)
}
entryFP := FingerprintWithMeta([]byte(sessionID), map[string]string{"source": "opencode-db"})
// Patch hashes are stamped onto the message they belong to.
patchHash := map[string]string{}
for _, ev := range events {
if ev.Kind == "patch" && ev.PatchHash != "" {
patchHash[ev.Message] = ev.PatchHash
}
}
type cand struct {
fp string
filePath string
idx int
isWrite bool
c SnippetCandidate
}
var cands []cand
for i, ev := range events {
if ev.Kind != "tool" || ev.Status != "completed" {
continue
}
if ev.Tool != "write" && ev.Tool != "edit" && ev.Tool != "bash" {
continue
}
if ev.Tool == "bash" && !e.IncludeBash {
continue
}
if len(cands) >= snippetCodeCap {
break
}
var in toolInput
if err := json.Unmarshal([]byte(ev.Input), &in); err != nil {
continue
}
var meta toolMeta
_ = json.Unmarshal([]byte(ev.Metadata), &meta)
var code, filePath, language, desc string
switch ev.Tool {
case "write":
code, filePath = in.Content, in.FilePath
case "edit":
code, filePath = in.NewString, in.FilePath
case "bash":
if meta.Exit == nil || *meta.Exit != 0 {
continue
}
// A bash call is often how code is written by hand: a heredoc body
// (`python3 - <<'PY' … PY`, `cat > x.py <<EOF`) is the real code.
bcode, blang, ok := extractBashSnippet(in.Command)
if !ok {
continue
}
code, language, desc = bcode, blang, in.Description
}
code = strings.TrimRight(code, "\n")
if len(code) < snippetMinCode || len(code) > snippetMaxCode {
continue
}
// Keep the raw code for the identity hash (so re-extraction is stable),
// but store a redacted copy and never index a leaked credential.
rawCode := code
code = Redact(code)
desc = Redact(desc)
if language == "" {
language = languageForPath(filePath)
}
if filePath == "" {
filePath = "(bash)"
}
evidence := map[string]any{
"tool": ev.Tool,
"status": "completed",
"bytes": len(code),
"lines": strings.Count(code, "\n") + 1,
"diagnostics": len(meta.Diagnostics),
"signal_version": e.Version,
}
if meta.Exit != nil {
evidence["exit"] = *meta.Exit
}
evJSON, _ := json.Marshal(evidence)
// bash calls are how exploration and troubleshooting happen: a diagnostic
// command is a *technique*, not junk, even when it's a one-liner tied to
// a specific host. Only code files get the import/stub junk verdict.
kind, junk := "code", classifyJunk(code, language)
if ev.Tool == "bash" {
kind, junk = "technique", trivialProbe(in.Command)
}
title := snippetTitle(ev.Tool, filePath)
if ev.Tool == "bash" {
switch {
case desc != "":
title = truncate(desc, 60)
case language != "" && language != "bash":
title = "script (" + language + ")"
default:
title = "shell command"
}
}
fp := Fingerprint([]byte(language + "\x00" + rawCode))
cands = append(cands, cand{
fp: fp,
filePath: filePath,
idx: i,
isWrite: ev.Tool == "write",
c: SnippetCandidate{
Fingerprint: fp,
Language: language,
Code: code,
Title: title,
Description: desc,
Tags: "[]",
SourceSession: sessionID,
SourcePath: filePath,
SourceEntry: entryFP,
Project: project,
Tool: ev.Tool,
Model: ev.Model,
PatchHash: patchHash[ev.Message],
Evidence: string(evJSON),
Junk: junk,
Kind: kind,
},
})
}
// Supersession: the last surviving full `write` to a file means every
// earlier candidate for that file (write or edit) may no longer be present.
lastWrite := map[string]int{} // filePath -> index of last write candidate
for _, c := range cands {
if c.isWrite {
if prev, ok := lastWrite[c.filePath]; !ok || c.idx > prev {
lastWrite[c.filePath] = c.idx
}
}
}
fpAtIdx := map[int]string{}
for _, c := range cands {
fpAtIdx[c.idx] = c.fp
}
out := make([]SnippetCandidate, 0, len(cands))
for _, c := range cands {
if lw, ok := lastWrite[c.filePath]; ok && c.idx < lw {
c.c.SupersededBy = fpAtIdx[lw]
}
out = append(out, c.c)
}
return out
}
// dedupPrimaries collapses identical fingerprints and clears the superseded
// marker for any fingerprint that also occurs as a primary elsewhere.
func dedupPrimaries(in []SnippetCandidate) []SnippetCandidate {
primary := map[string]bool{}
for _, c := range in {
if c.SupersededBy == "" {
primary[c.Fingerprint] = true
}
}
seen := map[string]bool{}
out := make([]SnippetCandidate, 0, len(in))
for _, c := range in {
if primary[c.Fingerprint] {
c.SupersededBy = ""
}
if seen[c.Fingerprint] {
continue
}
seen[c.Fingerprint] = true
out = append(out, c)
}
sort.Slice(out, func(i, j int) bool { return out[i].Fingerprint < out[j].Fingerprint })
return out
}
func snippetTitle(tool, filePath string) string {
base := filepath.Base(filePath)
switch tool {
case "bash":
return "command"
case "write":
return "new file: " + base
default:
return "edit " + base
}
}
func languageForPath(path string) string {
base := strings.ToLower(filepath.Base(path))
switch base {
case "dockerfile", "containerfile":
return "dockerfile"
case "makefile", "gnumakefile":
return "makefile"
case "cmakelists.txt":
return "cmake"
}
ext := strings.ToLower(filepath.Ext(path))
switch ext {
case ".go":
return "go"
case ".py":
return "python"
case ".js", ".mjs", ".cjs":
return "javascript"
case ".ts", ".mts", ".cts":
return "typescript"
case ".tsx":
return "tsx"
case ".jsx":
return "jsx"
case ".rs":
return "rust"
case ".c":
return "c"
case ".h":
return "c"
case ".cpp", ".cc", ".cxx", ".hpp", ".hh":
return "cpp"
case ".ino":
return "cpp"
case ".java":
return "java"
case ".rb":
return "ruby"
case ".erb":
return "erb"
case ".sh", ".bash", ".zsh", ".bashrc":
return "bash"
case ".fish":
return "fish"
case ".ps1":
return "powershell"
case ".sql":
return "sql"
case ".html", ".htm":
return "html"
case ".css":
return "css"
case ".scss", ".sass":
return "scss"
case ".json", ".jsonc":
return "json"
case ".yaml", ".yml":
return "yaml"
case ".toml":
return "toml"
case ".ini", ".cfg", ".conf":
return "ini"
case ".md", ".mdx":
return "markdown"
case ".nix":
return "nix"
case ".lua":
return "lua"
case ".tf", ".tfvars", ".hcl":
return "hcl"
case ".php":
return "php"
case ".cs":
return "csharp"
case ".swift":
return "swift"
case ".kt", ".kts":
return "kotlin"
case ".scala":
return "scala"
case ".pl", ".pm":
return "perl"
case ".r":
return "r"
case ".vue":
return "vue"
case ".svelte":
return "svelte"
case ".graphql", ".gql":
return "graphql"
case ".proto":
return "protobuf"
case ".xml":
return "xml"
case ".tex":
return "latex"
case ".rst":
return "rst"
case ".asm", ".s":
return "assembly"
case ".v", ".sv":
return "verilog"
case ".vhd", ".vhdl":
return "vhdl"
case ".gradle":
return "groovy"
case ".cmake":
return "cmake"
case ".bat", ".cmd":
return "batch"
case ".txt":
return "text"
default:
return ""
}
}
// classifyJunk flags low-reuse snippets: import/directive-only blocks,
// single-statement one-liners, and empty-body stubs. It is deliberately narrow —
// anything with real control flow or multiple statements is kept. The flag is a
// heuristic, not a verdict: the agent can still encode a junk row, and
// knox_snippet_reopen undoes a bulk rejection.
func classifyJunk(code, language string) bool {
lines := meaningfulLines(code)
if len(lines) == 0 {
return true
}
if allDirective(lines) {
return true
}
if len(lines) == 1 {
return len(code) < 160
}
if len(lines) <= 2 && isStub(lines) {
return true
}
return false
}
func meaningfulLines(code string) []string {
var out []string
for _, ln := range strings.Split(code, "\n") {
t := strings.TrimSpace(ln)
if t == "" || isCommentLine(t) {
continue
}
out = append(out, t)
}
return out
}
func isCommentLine(t string) bool {
for _, p := range []string{"//", "/*", "*/", "*", "<!--", "-->", "--"} {
if strings.HasPrefix(t, p) {
return true
}
}
return false
}
var directivePrefixes = []string{
"import ", "import\t", "from ", "require", "require_relative",
"use ", "using ", "package ", "option ", "#include", "#import",
"#pragma", "#!", "export ", "\"use strict\"", "'use strict'",
"//go:build", "// +build", "# frozen_string_literal", "module ",
"@import", "extern crate", "pub use", "mod ", "pub mod ",
}
func allDirective(lines []string) bool {
for _, ln := range lines {
if !isDirective(ln) {
return false
}
}
return true
}
func isDirective(ln string) bool {
l := strings.ToLower(ln)
for _, p := range directivePrefixes {
if strings.HasPrefix(l, p) {
return true
}
}
if strings.HasPrefix(l, "export ") && strings.Contains(l, " from ") {
return true
}
return false
}
func isStub(lines []string) bool {
joined := strings.TrimSpace(strings.Join(lines, " "))
if strings.HasSuffix(joined, "{}") || strings.HasSuffix(joined, "{ }") {
return true
}
switch strings.ToLower(strings.TrimSpace(lines[len(lines)-1])) {
case "pass", "...", "return", "return null", "return nil", "return none":
return true
}
return false
}
// ─── bash mining ─────────────────────────────────────────────
var (
heredocRe = regexp.MustCompile(`<<-?\s*['"]?([A-Za-z_][A-Za-z0-9_]*)`)
interpRe = regexp.MustCompile(`(?i)\b(python3|python|node|deno|bun|ruby|irb|perl|php|lua|fish|bash|zsh|sh|rscript)\b`)
redirRe = regexp.MustCompile(`>>?\s*([^\s;|&]+)`)
pythonCRe = regexp.MustCompile(`(?is)^\s*python3?\s+-c\s+(.*)$`)
)
// extractBashSnippet turns a completed bash command into code worth keeping:
// the body of a heredoc (the common way code is written by hand in a shell),
// the argument of `python -c`, or a genuine multi-line / control-flow shell
// script. Trivial one-liners return ok=false.
func extractBashSnippet(cmd string) (code, language string, ok bool) {
if body, lang, found := extractHeredoc(cmd); found {
if len(strings.TrimSpace(body)) >= snippetMinCode {
return strings.TrimRight(body, "\n"), lang, true
}
return "", "", false
}
if m := pythonCRe.FindStringSubmatch(cmd); m != nil {
if body := trimQuotes(m[1]); len(strings.TrimSpace(body)) >= snippetMinCode {
return strings.TrimRight(body, "\n"), "python", true
}
return "", "", false
}
if len(cmd) < snippetMinCode || (!strings.Contains(cmd, "\n") && !hasShellControl(cmd)) {
return "", "", false
}
return strings.TrimRight(cmd, "\n"), "bash", true
}
// extractHeredoc returns the body between a "<<WORD" marker and a line equal to
// WORD, plus the language inferred from the invoking interpreter or a `> file`
// redirection target.
func extractHeredoc(cmd string) (body, language string, ok bool) {
lines := strings.Split(cmd, "\n")
for i, ln := range lines {
m := heredocRe.FindStringSubmatch(ln)
if m == nil {
continue
}
marker := m[1]
for j := i + 1; j < len(lines); j++ {
if strings.TrimSpace(lines[j]) == marker {
return strings.Join(lines[i+1:j], "\n"), heredocLanguage(ln), true
}
}
return "", "", false // unterminated heredoc
}
return "", "", false
}
func heredocLanguage(opLine string) string {
if m := interpRe.FindStringSubmatch(opLine); m != nil {
return interpreterLanguage(strings.ToLower(m[1]))
}
if m := redirRe.FindStringSubmatch(opLine); m != nil {
if l := languageForPath(m[1]); l != "" {
return l
}
}
return ""
}
func interpreterLanguage(cmd string) string {
switch cmd {
case "python", "python3":
return "python"
case "node", "deno", "bun":
return "javascript"
case "ruby", "irb":
return "ruby"
case "perl":
return "perl"
case "php":
return "php"
case "lua":
return "lua"
case "fish":
return "fish"
case "bash", "sh", "zsh":
return "bash"
case "rscript":
return "r"
}
return ""
}
func hasShellControl(cmd string) bool {
return strings.ContainsAny(cmd, "|&;$(){}") ||
strings.Contains(cmd, " && ") || strings.Contains(cmd, " || ") ||
strings.Contains(cmd, "for ") || strings.Contains(cmd, "while ") || strings.Contains(cmd, "if ")
}
func trimQuotes(s string) string {
s = strings.TrimSpace(s)
if len(s) >= 2 {
if (s[0] == '"' && s[len(s)-1] == '"') || (s[0] == '\'' && s[len(s)-1] == '\'') {
return s[1 : len(s)-1]
}
}
return s
}
// trivialProbe flags a technique command that is just a one-shot read of a
// file or system state (ls/cat/head/…, or a non-recursive grep) with no
// pipeline, redirection, or diagnostic tooling. These carry no transferable
// method, so they are junk (hidden by default) while real diagnostics — an ssh
// probe, a dmesg/journalctl check, a recursive search, a test run — are kept.
// Deliberately conservative: when in doubt, keep it.
func trivialProbe(cmd string) bool {
cmd = strings.TrimSpace(cmd)
if cmd == "" || strings.Contains(cmd, "\n") {
return false
}
if strings.Contains(cmd, "$(") || strings.Contains(cmd, "`") {
return false // command substitution runs something
}
return trivialTokens(shellTokens(scrubRedirects(cmd)))
}
func scrubRedirects(s string) string {
return strings.NewReplacer(
"2>&1", "", "2>/dev/null", "", "&>/dev/null", "", ">/dev/null", "",
).Replace(s)
}
// trivialTokens reports whether every segment of a tokenized command is a
// read-only inspection. A write redirection or background job makes it real work.
func trivialTokens(toks []string) bool {
seg := make([]string, 0, len(toks))
for _, t := range toks {
switch t {
case "|", "||", "&&", ";", "&":
if !trivialWordSeq(seg) {
return false
}
seg = seg[:0]
case ">", ">>":
return false // writes a file
case "<":
// input redirection: harmless
default:
seg = append(seg, t)
}
}
return trivialWordSeq(seg)
}
func trivialWordSeq(seg []string) bool {
i := 0
for i < len(seg) && strings.Contains(seg[i], "=") && !strings.HasPrefix(seg[i], "-") {
i++ // skip leading VAR=value assignments
}
if i >= len(seg) {
return true
}
base := filepath.Base(seg[i])
if base == "ssh" {
return trivialSSH(seg[i+1:])
}
return trivialReader(base, seg[i:])
}
// trivialSSH classifies an ssh call by its remote command: `ssh host ls` and
// `ssh host 'docker ps'` are trivial reads, while `ssh host 'dmesg | grep dwc'`
// is a diagnostic method.
func trivialSSH(args []string) bool {
takesArg := map[string]bool{
"-i": true, "-o": true, "-p": true, "-l": true, "-b": true, "-c": true,
"-D": true, "-e": true, "-E": true, "-F": true, "-I": true, "-J": true,
"-L": true, "-m": true, "-O": true, "-Q": true, "-R": true, "-S": true,
"-W": true, "-w": true,
}
i := 0
for i < len(args) && strings.HasPrefix(args[i], "-") {
if takesArg[args[i]] {
i += 2
} else {
i++
}
}
if i >= len(args) {
return true // `ssh host` with no remote command
}
remote := strings.TrimSpace(strings.Join(args[i+1:], " "))
if remote == "" {
return true
}
return trivialTokens(shellTokens(scrubRedirects(remote)))
}
// trivialReader reports whether a single command is a read-only local inspection.
// grep/rg count only when non-recursive; docker/podman read subcommands count.
func trivialReader(base string, args []string) bool {
switch base {
case "ls", "cat", "head", "tail", "pwd", "which", "whoami", "echo", "printf",
"wc", "file", "stat", "du", "df", "readlink", "realpath", "env", "printenv",
"id", "true", "cd", "basename", "dirname", "sort", "uniq", "cut", "tr",
"nl", "column", "xxd", "strings", "cksum":
return true
case "grep", "rg", "egrep", "fgrep":
for _, tok := range args[1:] {
if strings.HasPrefix(tok, "--") {
if tok == "--recursive" || strings.HasPrefix(tok, "--include") || strings.HasPrefix(tok, "--exclude") {
return false
}
continue
}
if strings.HasPrefix(tok, "-") && strings.ContainsAny(tok, "rR") {
return false
}
}
return true
case "docker", "podman":
if len(args) >= 2 {
switch args[1] {
case "ps", "images", "inspect", "version", "info", "port", "history":
return true
}
}
return false
}
return false
}
// shellTokens splits a shell command into words and operator tokens. Quoted runs
// become one token (quotes stripped); operators |, ||, &&, ;, &, <, >, >> are
// emitted as their own tokens.
func shellTokens(s string) []string {
var toks []string
var cur strings.Builder
flush := func() {
if cur.Len() > 0 {
toks = append(toks, cur.String())
cur.Reset()
}
}
for i := 0; i < len(s); i++ {
switch s[i] {
case ' ', '\t':
flush()
case '\'':
i++
for i < len(s) && s[i] != '\'' {
cur.WriteByte(s[i])
i++
}
case '"':
i++
for i < len(s) && s[i] != '"' {
if s[i] == '\\' && i+1 < len(s) {
i++
}
cur.WriteByte(s[i])
i++
}
case '|':
flush()
if i+1 < len(s) && s[i+1] == '|' {
toks = append(toks, "||")
i++
} else {
toks = append(toks, "|")
}
case '&':
flush()
if i+1 < len(s) && s[i+1] == '&' {
toks = append(toks, "&&")
i++
} else {
toks = append(toks, "&")
}
case ';':
flush()
toks = append(toks, ";")
case '>':
flush()
if i+1 < len(s) && s[i+1] == '>' {
toks = append(toks, ">>")
i++
} else {
toks = append(toks, ">")
}
case '<':
flush()
toks = append(toks, "<")
default:
cur.WriteByte(s[i])
}
}
flush()
return toks
}