Files
knox/internal/cmd/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

429 lines
13 KiB
Go

package cmd
import (
"encoding/json"
"fmt"
"strings"
"github.com/david/knox/internal/db"
"github.com/david/knox/internal/ingest"
"github.com/spf13/cobra"
)
func NewSnippetsCmd(kdb *db.KnoxDB) *cobra.Command {
cmd := &cobra.Command{
Use: "snippets",
Short: "Extract and curate reusable code snippets from sessions",
Long: `Snippets are code lifted from opencode sessions that demonstrably worked.
Extraction is deterministic and LLM-free (the daemon also does this on a tick):
only tool calls that completed successfully become candidates, and a file that
was later fully rewritten marks its earlier snippets superseded (a dead end).
Curation is agent-driven: review candidates and encode the good ones (optionally
as a ~/.skills entry), or reject the rest so they are not proposed again.
Subcommands: extract, list, show, search, encode, reject, stats`,
}
cmd.AddCommand(newSnippetsExtractCmd(kdb))
cmd.AddCommand(newSnippetsListCmd(kdb))
cmd.AddCommand(newSnippetsShowCmd(kdb))
cmd.AddCommand(newSnippetsSearchCmd(kdb))
cmd.AddCommand(newSnippetsEncodeCmd(kdb))
cmd.AddCommand(newSnippetsRejectCmd(kdb))
cmd.AddCommand(newSnippetsReopenCmd(kdb))
cmd.AddCommand(newSnippetsPruneCmd(kdb))
cmd.AddCommand(newSnippetsRedactCmd(kdb))
cmd.AddCommand(newSnippetsStatsCmd(kdb))
return cmd
}
func newSnippetsExtractCmd(kdb *db.KnoxDB) *cobra.Command {
var dryRun bool
cmd := &cobra.Command{
Use: "extract",
Short: "Sweep opencode sessions for worked code candidates (heuristic, no LLM)",
RunE: func(c *cobra.Command, args []string) error {
cands, err := ingest.NewSnippetExtractor().ExtractAll()
if err != nil {
return err
}
if dryRun {
for _, c := range cands {
fmt.Printf("%s [%s] %-24s %4d B %s\n",
c.Fingerprint[:8], langOrText(c.Language), truncateStr(c.SourcePath, 24), len(c.Code), c.Title)
}
fmt.Printf("\n%d candidates (dry run, nothing written)\n", len(cands))
return nil
}
recs := make([]db.SnippetRecord, 0, len(cands))
for _, c := range cands {
recs = append(recs, db.SnippetRecord{
Fingerprint: c.Fingerprint,
Language: c.Language,
Code: c.Code,
Title: c.Title,
Description: c.Description,
Tags: c.Tags,
SourceSession: c.SourceSession,
SourcePath: c.SourcePath,
SourceEntry: c.SourceEntry,
Project: c.Project,
Tool: c.Tool,
Model: c.Model,
PatchHash: c.PatchHash,
Evidence: c.Evidence,
SupersededBy: c.SupersededBy,
Junk: c.Junk,
Kind: c.Kind,
})
}
newCount, err := kdb.UpsertSnippets(recs)
if err != nil {
return err
}
fmt.Printf("\nSnippet extract: %d candidates, %d new\n", len(cands), newCount)
return nil
},
}
cmd.Flags().BoolVar(&dryRun, "dry-run", false, "Preview candidates without writing")
return cmd
}
func newSnippetsListCmd(kdb *db.KnoxDB) *cobra.Command {
var status, language, project, tool, config, junk, kind string
var described bool
var minBytes, limit int
cmd := &cobra.Command{
Use: "list",
Short: "List snippets (default: candidates awaiting curation)",
RunE: func(c *cobra.Command, args []string) error {
var (
items []db.Snippet
err error
)
switch {
case status == "all":
items, err = kdb.ListSnippets("", limit)
case status == "" || status == "candidate" || language != "" || project != "" || tool != "" || minBytes > 0 || junk != "" || kind != "" || described:
items, err = kdb.SnippetCandidates(db.SnippetFilter{
Limit: limit,
Language: language,
Project: project,
Tool: tool,
MinBytes: minBytes,
Config: config,
Junk: junk,
Kind: kind,
Described: described,
})
default:
items, err = kdb.ListSnippets(status, limit)
}
if err != nil {
return err
}
if len(items) == 0 {
fmt.Println("No snippets. Run `knox snippets extract` or wait for the daemon tick.")
return nil
}
fmt.Printf("%-8s %-10s %-9s %-24s %s\n", "FP", "LANG", "STATUS", "SOURCE", "TITLE")
fmt.Println(strings.Repeat("-", 78))
for _, s := range items {
flag := ""
if s.SupersededBy != "" {
flag = " (superseded)"
}
if isConfigLang(s.Language) {
flag += " (config)"
}
if s.Junk {
flag += " (junk)"
}
if kindOr(s.Kind) == "technique" {
flag += " (technique)"
}
fmt.Printf("%-8s %-10s %-9s %-24s %s%s\n",
s.Fingerprint[:8], langOrText(s.Language), s.Status,
truncateStr(s.SourcePath, 24), truncateStr(s.Title, 30), flag)
}
return nil
},
}
cmd.Flags().StringVarP(&status, "status", "s", "", "Filter: candidate, encoded, rejected, all (default: candidates)")
cmd.Flags().StringVarP(&language, "language", "l", "", "Filter by language")
cmd.Flags().StringVar(&project, "project", "", "Filter by project")
cmd.Flags().StringVar(&tool, "tool", "", "Filter by tool: edit, write, bash")
cmd.Flags().IntVar(&minBytes, "min-bytes", 0, "Minimum code size in bytes")
cmd.Flags().StringVar(&config, "config", "hide", "Config/doc handling: hide, demote, only")
cmd.Flags().StringVar(&junk, "junk", "hide", "Junk (imports/stubs) handling: hide, demote, only")
cmd.Flags().StringVar(&kind, "kind", "", "Filter by kind: code, technique")
cmd.Flags().BoolVar(&described, "described", false, "Only snippets with a non-empty description (intent)")
cmd.Flags().IntVarP(&limit, "limit", "n", 50, "Max results")
return cmd
}
func newSnippetsShowCmd(kdb *db.KnoxDB) *cobra.Command {
return &cobra.Command{
Use: "show <fingerprint>",
Short: "Show a snippet's code, provenance, and worked evidence",
Args: cobra.ExactArgs(1),
RunE: func(c *cobra.Command, args []string) error {
s, err := kdb.SnippetByFingerprint(args[0])
if err != nil {
return err
}
if s == nil {
return fmt.Errorf("no snippet matching %q", args[0])
}
fmt.Printf("fingerprint: %s\n", s.Fingerprint)
fmt.Printf("title: %s\n", s.Title)
fmt.Printf("language: %s\n", langOrText(s.Language))
fmt.Printf("status: %s\n", s.Status)
fmt.Printf("kind: %s\n", kindOr(s.Kind))
fmt.Printf("tool: %s\n", s.Tool)
if s.Project != "" {
fmt.Printf("project: %s\n", s.Project)
}
if s.SourcePath != "" {
fmt.Printf("source: %s\n", s.SourcePath)
}
if s.SourceSession != "" {
fmt.Printf("session: %s\n", s.SourceSession)
}
if s.SupersededBy != "" {
fmt.Printf("superseded: %s\n", s.SupersededBy[:8])
}
if s.SkillName != "" {
fmt.Printf("skill: %s\n", s.SkillName)
}
if s.RejectReason != "" {
fmt.Printf("rejected: %s\n", s.RejectReason)
}
if s.Description != "" {
fmt.Printf("description: %s\n", s.Description)
}
if s.Junk {
fmt.Printf("junk: yes (imports/directives/single-line/empty-body stub)\n")
}
fmt.Printf("evidence: %s\n", s.Evidence)
fmt.Printf("\n%s\n", s.Code)
return nil
},
}
}
func newSnippetsSearchCmd(kdb *db.KnoxDB) *cobra.Command {
var limit int
cmd := &cobra.Command{
Use: "search <query>",
Short: "Full-text search over all snippets",
Args: cobra.MinimumNArgs(1),
RunE: func(c *cobra.Command, args []string) error {
query := strings.Join(args, " ")
items, err := kdb.SearchSnippets(query, limit)
if err != nil {
return err
}
if len(items) == 0 {
fmt.Printf("No snippets matching %q\n", query)
return nil
}
for _, s := range items {
fmt.Printf("%-8s %-10s %-9s %-24s %s\n",
s.Fingerprint[:8], langOrText(s.Language), s.Status,
truncateStr(s.SourcePath, 24), truncateStr(s.Title, 40))
}
return nil
},
}
cmd.Flags().IntVarP(&limit, "limit", "n", 20, "Max results")
return cmd
}
func newSnippetsEncodeCmd(kdb *db.KnoxDB) *cobra.Command {
var title, description, tags, language, skill string
var overwrite bool
cmd := &cobra.Command{
Use: "encode <fingerprint>",
Short: "Mark a snippet as curated knowledge (optionally write a ~/.skills entry)",
Args: cobra.ExactArgs(1),
RunE: func(c *cobra.Command, args []string) error {
msg, err := encodeSnippet(kdb, snippetEncodeArgs{
Fingerprint: args[0],
Title: title,
Description: description,
Tags: tags,
Language: language,
Skill: skill,
Overwrite: overwrite,
})
if err != nil {
return err
}
fmt.Println(msg)
return nil
},
}
cmd.Flags().StringVarP(&title, "title", "t", "", "Title (defaults to the extracted title)")
cmd.Flags().StringVarP(&description, "description", "d", "", "What it does / when to use it")
cmd.Flags().StringVar(&tags, "tags", "", "Space-separated tags")
cmd.Flags().StringVarP(&language, "language", "l", "", "Language override")
cmd.Flags().StringVar(&skill, "skill", "", "Write a ~/.skills entry with this name ('auto' derives from the title)")
cmd.Flags().BoolVar(&overwrite, "overwrite", false, "Overwrite an existing skill of the same name")
return cmd
}
func newSnippetsRejectCmd(kdb *db.KnoxDB) *cobra.Command {
var reason string
cmd := &cobra.Command{
Use: "reject <fingerprint> [fingerprint...]",
Short: "Record dead ends so they are not proposed again",
Args: cobra.MinimumNArgs(1),
RunE: func(c *cobra.Command, args []string) error {
n := 0
for _, fp := range args {
ok, err := kdb.RejectSnippet(fp, reason)
if err != nil {
return err
}
if ok {
n++
}
}
fmt.Printf("Rejected %d/%d snippet(s)\n", n, len(args))
return nil
},
}
cmd.Flags().StringVar(&reason, "reason", "", "Why it was rejected (kept for the record)")
return cmd
}
func newSnippetsReopenCmd(kdb *db.KnoxDB) *cobra.Command {
var techniques bool
cmd := &cobra.Command{
Use: "reopen [fingerprint...]",
Short: "Undo a reject/encode decision, returning snippets to the candidate queue",
RunE: func(c *cobra.Command, args []string) error {
if techniques {
n, err := kdb.ReopenRejectedTechniques()
if err != nil {
return err
}
fmt.Printf("Reopened %d rejected technique(s)\n", n)
return nil
}
if len(args) == 0 {
return fmt.Errorf("provide fingerprints, or --techniques to reopen all rejected bash techniques")
}
n := 0
for _, fp := range args {
ok, err := kdb.ReopenSnippet(fp)
if err != nil {
return err
}
if ok {
n++
}
}
fmt.Printf("Reopened %d/%d snippet(s)\n", n, len(args))
return nil
},
}
cmd.Flags().BoolVar(&techniques, "techniques", false, "Reopen all rejected bash-sourced techniques")
return cmd
}
func newSnippetsPruneCmd(kdb *db.KnoxDB) *cobra.Command {
var dryRun bool
var reason string
cmd := &cobra.Command{
Use: "prune",
Short: "Bulk-reject candidates the extractor classified as junk (imports/directives/single-line/stubs)",
Long: `Rejects every candidate flagged junk by the heuristic classifier. This is a
convenience over knox_snippet_reject for the obvious noise; it is reversible with
` + "`knox snippets reopen`" + ` (pass the fingerprints you want back).`,
RunE: func(c *cobra.Command, args []string) error {
if dryRun {
n, err := kdb.CountJunkCandidates()
if err != nil {
return err
}
fmt.Printf("Would reject %d junk candidate(s).\n", n)
return nil
}
n, err := kdb.RejectJunkSnippets(reason)
if err != nil {
return err
}
fmt.Printf("Rejected %d junk candidate(s).\n", n)
return nil
},
}
cmd.Flags().BoolVar(&dryRun, "dry-run", false, "Report the count without rejecting")
cmd.Flags().StringVar(&reason, "reason", "", "Rejection reason")
return cmd
}
func newSnippetsRedactCmd(kdb *db.KnoxDB) *cobra.Command {
var dryRun bool
cmd := &cobra.Command{
Use: "redact",
Short: "Scrub secrets (DB URLs, TOKEN=/PASSWORD=, cloud keys, JWTs) from stored snippets",
Long: "Applies the same redaction the extractor uses to already-stored snippets, masking credentials indexed before redaction existed.",
RunE: func(c *cobra.Command, args []string) error {
n, err := kdb.RedactSnippets(ingest.Redact, dryRun)
if err != nil {
return err
}
if dryRun {
fmt.Printf("Would redact %d snippet(s).\n", n)
} else {
fmt.Printf("Redacted %d snippet(s).\n", n)
}
return nil
},
}
cmd.Flags().BoolVar(&dryRun, "dry-run", false, "Report the count without writing")
return cmd
}
func newSnippetsStatsCmd(kdb *db.KnoxDB) *cobra.Command {
return &cobra.Command{
Use: "stats",
Short: "Show snippet counts by status and language",
RunE: func(c *cobra.Command, args []string) error {
stats, err := kdb.SnippetStats()
if err != nil {
return err
}
b, _ := json.MarshalIndent(stats, "", " ")
fmt.Println(string(b))
return nil
},
}
}
func langOrText(l string) string {
if l == "" {
return "text"
}
return l
}
func kindOr(k string) string {
if k == "" {
return "code"
}
return k
}
// isConfigLang mirrors db.configLangExpr: config/doc languages that demote
// below real code in the candidate queue.
func isConfigLang(l string) bool {
switch l {
case "json", "yaml", "toml", "markdown", "lua":
return true
}
return false
}