Compare commits

1 Commits

Author SHA1 Message Date
david 3b24e3b8be fix: make the snippet queue reviewable (#35)
build / image (push) Successful in 51s
build / test (push) Successful in 4m48s
Two causes, both fixed here.

Classification: trivialProbe bailed out on any newline, so multi-line
chores were never judged — 'cd X && sed -n 60,200p f' and 'git status &&
git log --oneline -3' all became technique candidates. Newlines are now
segment separators like ';', sed (without -i) and read-only git
subcommands count as inspections, and context flags (-A/-B/-C, git log -p,
--since, --graph, --all) keep a command because selecting history is
method, not a chore.

Over the live corpus the trivial verdicts go from 307 to 1,081 of 11,552
techniques, and the archaeology that matters (git log -p | grep -B 50)
still survives.

Retention: nothing ever aged a candidate out, so 16,149 of them sat in the
queue. knox snippets expire --days N rejects uncurated candidates older
than the window. It is reversible and never touches encoded rows: the code
did not change, the review window moved past it.
2026-11-04 21:20:24 -08:00
5 changed files with 224 additions and 8 deletions
+43
View File
@@ -4,6 +4,7 @@ import (
"encoding/json"
"fmt"
"strings"
"time"
"github.com/david/knox/internal/db"
"github.com/david/knox/internal/ingest"
@@ -32,6 +33,7 @@ Subcommands: extract, list, show, search, encode, reject, stats`,
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
@@ -333,6 +335,47 @@ func newSnippetsReopenCmd(kdb *db.KnoxDB) *cobra.Command {
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
+33
View File
@@ -3140,6 +3140,39 @@ func (k *KnoxDB) CountJunkCandidates() (int, error) {
return n, err
}
// ExpireSnippets rejects uncurated candidates discovered before the cutoff.
// This is retention, not judgement: the code did not change, the review window
// moved past it. Encoded and already-rejected rows are untouched, and the
// decision is reversible with knox snippets reopen.
func (k *KnoxDB) ExpireSnippets(cutoff time.Time, reason string) (int, error) {
if strings.TrimSpace(reason) == "" {
reason = "Expired: never curated within the retention window."
}
now := time.Now().UTC().Format(time.RFC3339)
res, err := k.db.Exec(
`UPDATE snippets SET status='rejected', reject_reason=?, reviewed_at=?
WHERE status='candidate' AND superseded_by=''
AND datetime(discovered_at) < datetime(?)`,
reason, now, cutoff.UTC().Format(time.RFC3339),
)
if err != nil {
return 0, fmt.Errorf("expire snippets: %w", err)
}
n, _ := res.RowsAffected()
return int(n), nil
}
// CountExpiredCandidates is the actionable expiry count for a cutoff.
func (k *KnoxDB) CountExpiredCandidates(cutoff time.Time) (int, error) {
var n int
err := k.db.QueryRow(
`SELECT COUNT(*) FROM snippets WHERE status='candidate' AND superseded_by=''
AND datetime(discovered_at) < datetime(?)`,
cutoff.UTC().Format(time.RFC3339),
).Scan(&n)
return n, err
}
// ReopenRejectedTechniques returns every rejected technique (bash-sourced) to the
// candidate queue — undoing the earlier junk sweep that discarded exploration
// and troubleshooting commands. Returns the number reopened.
+70
View File
@@ -830,3 +830,73 @@ func TestThreadIsDraft(t *testing.T) {
}
}
}
// Retention is not judgement: an old uncurated candidate is rejected so the
// review queue tracks recent work, while curated rows are never touched.
func TestExpireSnippets(t *testing.T) {
k := newTestDB(t)
add := func(fp, code string) {
t.Helper()
if _, err := k.UpsertSnippet(SnippetRecord{
Fingerprint: fp, Language: "go", Code: code, Title: fp, Tags: "[]",
SourceSession: "ses_1", Project: "demo", Tool: "write", Kind: "code",
}); err != nil {
t.Fatalf("upsert: %v", err)
}
}
setSeen := func(fp, when string) {
t.Helper()
if _, err := k.db.Exec(`UPDATE snippets SET discovered_at=? WHERE fingerprint=?`, when, fp); err != nil {
t.Fatalf("set discovered_at: %v", err)
}
}
old := "2026-01-01T00:00:00Z"
recent := time.Now().UTC().Format(time.RFC3339)
add("fp_old", "package demo\n\nfunc Old() {}\n")
add("fp_recent", "package demo\n\nfunc Recent() {}\n")
add("fp_encoded", "package demo\n\nfunc Encoded() {}\n")
setSeen("fp_old", old)
setSeen("fp_recent", recent)
setSeen("fp_encoded", old)
if _, err := k.db.Exec(`UPDATE snippets SET status='encoded' WHERE fingerprint='fp_encoded'`); err != nil {
t.Fatalf("encode: %v", err)
}
cutoff := time.Now().UTC().AddDate(0, 0, -30)
n, err := k.CountExpiredCandidates(cutoff)
if err != nil {
t.Fatalf("count: %v", err)
}
if n != 1 {
t.Fatalf("expirable=%d, want 1", n)
}
expired, err := k.ExpireSnippets(cutoff, "")
if err != nil {
t.Fatalf("expire: %v", err)
}
if expired != 1 {
t.Fatalf("expired=%d, want 1", expired)
}
status := func(fp string) (string, string) {
t.Helper()
var s, reason string
if err := k.db.QueryRow(`SELECT status, COALESCE(reject_reason,'') FROM snippets WHERE fingerprint=?`, fp).
Scan(&s, &reason); err != nil {
t.Fatalf("status %s: %v", fp, err)
}
return s, reason
}
if s, reason := status("fp_old"); s != "rejected" || !strings.Contains(reason, "retention") {
t.Fatalf("old candidate = %q / %q", s, reason)
}
if s, _ := status("fp_recent"); s != "candidate" {
t.Fatalf("recent candidate = %q, want candidate", s)
}
if s, _ := status("fp_encoded"); s != "encoded" {
t.Fatalf("encoded snippet = %q, want encoded", s)
}
}
+42 -8
View File
@@ -783,23 +783,39 @@ func trimQuotes(s string) string {
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.
// trivialProbe flags a technique command that is just a read of a file or
// system state (ls/cat/head/git log/…, or a non-recursive grep) with no
// diagnostic tooling. These carry no transferable method, so they are junk
// (hidden by default) while real work — an ssh probe, a dmesg/journalctl check,
// a recursive search, a test run — is kept.
//
// Every segment counts, including segments on their own line: a multi-line
// sequence of inspections is still an inspection. It used to bail out on any
// newline, which kept whole transcripts of `cd … && cat …` chores as candidates.
// Deliberately conservative: when in doubt, keep it.
func trivialProbe(cmd string) bool {
cmd = strings.TrimSpace(cmd)
if cmd == "" || strings.Contains(cmd, "\n") {
if cmd == "" {
return false
}
if strings.Contains(cmd, "$(") || strings.Contains(cmd, "`") {
return false // command substitution runs something
}
if selectsHistory(cmd) {
return false // context flags turn a read into an investigation
}
return trivialTokens(shellTokens(scrubRedirects(cmd)))
}
// historyFlagRe matches flags that make a read an *investigation*: grep context
// lines (-A/-B/-C), git log -p/--follow/--graph/--since. A `git log -p | grep
// -B 50` archaeology chain is transferable method, not a chore, so it is kept.
var historyFlagRe = regexp.MustCompile(`(^|\s)(-[ABC][0-9]*|-[pF]|--since|--until|--graph|--author|--follow|--all)(\s|$)`)
func selectsHistory(cmd string) bool {
return historyFlagRe.MatchString(cmd)
}
func scrubRedirects(s string) string {
return strings.NewReplacer(
"2>&1", "", "2>/dev/null", "", "&>/dev/null", "", ">/dev/null", "",
@@ -872,9 +888,26 @@ func trivialSSH(args []string) bool {
}
// trivialReader reports whether a single command is a read-only local inspection.
// grep/rg count only when non-recursive; docker/podman read subcommands count.
// grep/rg count only when non-recursive; docker/podman read subcommands count,
// and git counts only for subcommands that cannot mutate a repository.
func trivialReader(base string, args []string) bool {
switch base {
case "sed":
for _, tok := range args[1:] {
if strings.HasPrefix(tok, "-") && strings.Contains(tok, "i") {
return false // in-place edit
}
}
return true
case "git":
if len(args) >= 2 {
switch args[1] {
case "status", "log", "diff", "show", "rev-parse", "describe",
"blame", "shortlog", "ls-files", "grep", "cat-file", "reflog":
return true
}
}
return false
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",
@@ -952,9 +985,10 @@ func shellTokens(s string) []string {
} else {
toks = append(toks, "&")
}
case ';':
case ';', '\n':
flush()
toks = append(toks, ";")
case '\r':
case '>':
flush()
if i+1 < len(s) && s[i+1] == '>' {
+36
View File
@@ -166,3 +166,39 @@ func TestSnippetExtractorDoesNotDoubleCountV1AndV2(t *testing.T) {
t.Fatalf("projects = %v, want demo and old", seen)
}
}
// trivialProbe decides what a "technique" candidate is: an inspection chore
// (hidden) versus transferable method (kept). Multi-line commands used to be
// exempted wholesale, which kept every transcript of `cd … && cat …` chores.
func TestTrivialProbe(t *testing.T) {
cases := []struct {
name string
cmd string
want bool
}{
{"single read", "ls -la /tmp", true},
{"chained reads", "cd /repo && sed -n '60,200p' tools/deploy.py", true},
{"multi-line reads", "ls -la\nsed -n '1,20p' main.go\nwc -l main.go", true},
{"git chores", "git status --short && git log --oneline -3", true},
{"show file", "git show 1d244cf:engine/scroll.py | head -n 100", true},
{"pwd", "pwd && git rev-parse --show-toplevel", true},
{"test run", "go test ./... 2>&1 | tail -6", false},
{"archaeology", `git log --all -p --since="3 months ago" -- engine/app.py | grep -B 50 "class Camera"`, false},
{"context grep", `grep -A 5 "def main" engine/app.py`, false},
{"ssh diagnostic", "ssh host 'dmesg | grep dwc3'", false},
{"ssh read", "ssh host 'ls /usr/src'", true},
{"heredoc script", "python3 - <<'PY'\nprint(1)\nPY", false},
{"in-place edit", "sed -i 's/a/b/' main.go", false},
{"write", "git push origin main", false},
{"redirect", "cat > out.txt <<EOF\nx\nEOF", false},
{"substitution", "echo $(date)", false},
{"compose up", "docker compose up -d", false},
{"empty", "", false},
}
for _, c := range cases {
if got := trivialProbe(c.cmd); got != c.want {
t.Errorf("%s: trivialProbe(%q)=%v, want %v", c.name, c.cmd, got, c.want)
}
}
}