Compare commits

2 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
david 87eb47ca3c fix: keep merged and resolved threads out of the draft queue (#33) (#34)
build / test (push) Successful in 3m9s
build / image (push) Successful in 17s
Co-authored-by: David Gwilliam <dhgwilliam@gmail.com>
Co-committed-by: David Gwilliam <dhgwilliam@gmail.com>
2026-11-05 04:38:02 +00:00
7 changed files with 262 additions and 17 deletions
+1 -1
View File
@@ -340,7 +340,7 @@ func NewMCPServer(kdb *db.KnoxDB) *mcp.Server {
} }
selected := make([]db.Thread, 0, len(threads)) selected := make([]db.Thread, 0, len(threads))
for _, t := range threads { for _, t := range threads {
if strings.Contains(t.Provenance, "auto_thread") || strings.HasPrefix(t.Motivation, "Auto-detected") { if t.IsDraft() {
selected = append(selected, t) selected = append(selected, t)
} }
if len(selected) >= limit { if len(selected) >= limit {
+43
View File
@@ -4,6 +4,7 @@ import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"strings" "strings"
"time"
"github.com/david/knox/internal/db" "github.com/david/knox/internal/db"
"github.com/david/knox/internal/ingest" "github.com/david/knox/internal/ingest"
@@ -32,6 +33,7 @@ Subcommands: extract, list, show, search, encode, reject, stats`,
cmd.AddCommand(newSnippetsRejectCmd(kdb)) cmd.AddCommand(newSnippetsRejectCmd(kdb))
cmd.AddCommand(newSnippetsReopenCmd(kdb)) cmd.AddCommand(newSnippetsReopenCmd(kdb))
cmd.AddCommand(newSnippetsPruneCmd(kdb)) cmd.AddCommand(newSnippetsPruneCmd(kdb))
cmd.AddCommand(newSnippetsExpireCmd(kdb))
cmd.AddCommand(newSnippetsRedactCmd(kdb)) cmd.AddCommand(newSnippetsRedactCmd(kdb))
cmd.AddCommand(newSnippetsStatsCmd(kdb)) cmd.AddCommand(newSnippetsStatsCmd(kdb))
return cmd return cmd
@@ -333,6 +335,47 @@ func newSnippetsReopenCmd(kdb *db.KnoxDB) *cobra.Command {
return cmd 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 { func newSnippetsPruneCmd(kdb *db.KnoxDB) *cobra.Command {
var dryRun bool var dryRun bool
var reason string var reason string
+1 -8
View File
@@ -390,7 +390,7 @@ a better title and motivation. Apply changes with ` + "`knox thread update <id>`
} }
var shown int var shown int
for _, t := range threads { for _, t := range threads {
if !isAutoThreaded(t) { if !t.IsDraft() {
continue continue
} }
obs, _ := kdb.ThreadObservations(t.ID) obs, _ := kdb.ThreadObservations(t.ID)
@@ -419,13 +419,6 @@ a better title and motivation. Apply changes with ` + "`knox thread update <id>`
} }
} }
func isAutoThreaded(t db.Thread) bool {
if strings.Contains(t.Provenance, "auto_thread") {
return true
}
return strings.HasPrefix(t.Motivation, "Auto-detected")
}
func newThreadUpdateCmd(kdb *db.KnoxDB) *cobra.Command { func newThreadUpdateCmd(kdb *db.KnoxDB) *cobra.Command {
var title, motivation, priority, tags string var title, motivation, priority, tags string
cmd := &cobra.Command{ cmd := &cobra.Command{
+44
View File
@@ -1602,6 +1602,17 @@ type Thread struct {
LastActivity string // newest linked observation's signal time (created_at) LastActivity string // newest linked observation's signal time (created_at)
} }
// IsDraft reports whether a thread still carries the heuristic auto-threader's
// editorial copy and is worth offering for polish. Merged clusters are resolved
// and left with no observations, so they are excluded: there is nothing to
// rewrite and the queue could never drain.
func (t Thread) IsDraft() bool {
if t.Status == "resolved" || t.EntryCount == 0 {
return false
}
return strings.Contains(t.Provenance, "auto_thread") || strings.HasPrefix(t.Motivation, "Auto-detected")
}
// stallAfterDays is how long a thread may go without activity before it is // stallAfterDays is how long a thread may go without activity before it is
// considered stalled (derived, reversible — not a stored state). // considered stalled (derived, reversible — not a stored state).
const stallAfterDays = 14 const stallAfterDays = 14
@@ -3129,6 +3140,39 @@ func (k *KnoxDB) CountJunkCandidates() (int, error) {
return n, err 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 // ReopenRejectedTechniques returns every rejected technique (bash-sourced) to the
// candidate queue — undoing the earlier junk sweep that discarded exploration // candidate queue — undoing the earlier junk sweep that discarded exploration
// and troubleshooting commands. Returns the number reopened. // and troubleshooting commands. Returns the number reopened.
+95
View File
@@ -805,3 +805,98 @@ func TestUpdateThreadClearsAutoThreadMarker(t *testing.T) {
t.Fatalf("unrelated provenance was rewritten: %s", got.Provenance) t.Fatalf("unrelated provenance was rewritten: %s", got.Provenance)
} }
} }
// The draft queue is "auto-threaded clusters still worth polishing". A merged
// cluster is resolved and empty, so it must not come back as a candidate.
func TestThreadIsDraft(t *testing.T) {
cases := []struct {
name string
t Thread
draft bool
}{
{"marker", Thread{Status: "active", EntryCount: 12, Provenance: `{"trigger":"auto_thread"}`}, true},
{"prefix", Thread{Status: "stalled", EntryCount: 3, Motivation: "Auto-detected cluster of 4"}, true},
{"groomed", Thread{Status: "active", EntryCount: 12,
Provenance: `{"groomed":true,"cluster":"plant"}`, Motivation: "Plant watering"}, false},
{"merged", Thread{Status: "resolved", EntryCount: 0, Provenance: `{"trigger":"auto_thread"}`}, false},
{"resolved with work", Thread{Status: "resolved", EntryCount: 9, Provenance: `{"trigger":"auto_thread"}`}, false},
{"empty cluster", Thread{Status: "active", EntryCount: 0, Motivation: "Auto-detected cluster"}, false},
{"manual", Thread{Status: "active", EntryCount: 4,
Provenance: `{"trigger":"display-watch"}`, Motivation: "By hand"}, false},
}
for _, c := range cases {
if got := c.t.IsDraft(); got != c.draft {
t.Errorf("%s: IsDraft()=%v, want %v", c.name, got, c.draft)
}
}
}
// 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 return s
} }
// trivialProbe flags a technique command that is just a one-shot read of a // trivialProbe flags a technique command that is just a read of a file or
// file or system state (ls/cat/head/…, or a non-recursive grep) with no // system state (ls/cat/head/git log/…, or a non-recursive grep) with no
// pipeline, redirection, or diagnostic tooling. These carry no transferable // diagnostic tooling. These carry no transferable method, so they are junk
// method, so they are junk (hidden by default) while real diagnostics — an ssh // (hidden by default) while real work — an ssh probe, a dmesg/journalctl check,
// probe, a dmesg/journalctl check, a recursive search, a test run — are kept. // 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. // Deliberately conservative: when in doubt, keep it.
func trivialProbe(cmd string) bool { func trivialProbe(cmd string) bool {
cmd = strings.TrimSpace(cmd) cmd = strings.TrimSpace(cmd)
if cmd == "" || strings.Contains(cmd, "\n") { if cmd == "" {
return false return false
} }
if strings.Contains(cmd, "$(") || strings.Contains(cmd, "`") { if strings.Contains(cmd, "$(") || strings.Contains(cmd, "`") {
return false // command substitution runs something return false // command substitution runs something
} }
if selectsHistory(cmd) {
return false // context flags turn a read into an investigation
}
return trivialTokens(shellTokens(scrubRedirects(cmd))) 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 { func scrubRedirects(s string) string {
return strings.NewReplacer( return strings.NewReplacer(
"2>&1", "", "2>/dev/null", "", "&>/dev/null", "", ">/dev/null", "", "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. // 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 { func trivialReader(base string, args []string) bool {
switch base { 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", case "ls", "cat", "head", "tail", "pwd", "which", "whoami", "echo", "printf",
"wc", "file", "stat", "du", "df", "readlink", "realpath", "env", "printenv", "wc", "file", "stat", "du", "df", "readlink", "realpath", "env", "printenv",
"id", "true", "cd", "basename", "dirname", "sort", "uniq", "cut", "tr", "id", "true", "cd", "basename", "dirname", "sort", "uniq", "cut", "tr",
@@ -952,9 +985,10 @@ func shellTokens(s string) []string {
} else { } else {
toks = append(toks, "&") toks = append(toks, "&")
} }
case ';': case ';', '\n':
flush() flush()
toks = append(toks, ";") toks = append(toks, ";")
case '\r':
case '>': case '>':
flush() flush()
if i+1 < len(s) && s[i+1] == '>' { 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) 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)
}
}
}