package cmd import ( "encoding/json" "fmt" "strings" "time" "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(newSnippetsExpireCmd(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 ", 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 ", 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 ", 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...]", 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 newSnippetsExpireCmd(kdb *db.KnoxDB) *cobra.Command { var days int var dryRun bool var reason string cmd := &cobra.Command{ Use: "expire", Short: "Reject uncurated candidates older than a retention window", Long: `Retention, not judgement: candidates that were never curated within the window are rejected so the review queue stays the size of recent work. The code did not change — the window moved past it. Encoded snippets are never touched, and the decision is reversible with ` + "`knox snippets reopen`" + ` (or scope=techniques for every rejected technique at once).`, RunE: func(c *cobra.Command, args []string) error { if days <= 0 { return fmt.Errorf("--days must be a positive number of days") } cutoff := time.Now().UTC().AddDate(0, 0, -days) if dryRun { n, err := kdb.CountExpiredCandidates(cutoff) if err != nil { return err } fmt.Printf("Would expire %d candidate(s) discovered before %s.\n", n, cutoff.Format(time.RFC3339)) return nil } n, err := kdb.ExpireSnippets(cutoff, reason) if err != nil { return err } fmt.Printf("Expired %d candidate(s) discovered before %s.\n", n, cutoff.Format(time.RFC3339)) return nil }, } cmd.Flags().IntVar(&days, "days", 0, "Retention window in days (candidates older than this are rejected)") cmd.Flags().BoolVar(&dryRun, "dry-run", false, "Report the count without rejecting") cmd.Flags().StringVar(&reason, "reason", "", "Rejection reason") 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 }