Compare commits
2 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 3b24e3b8be | |||
| 87eb47ca3c |
+1
-1
@@ -340,7 +340,7 @@ func NewMCPServer(kdb *db.KnoxDB) *mcp.Server {
|
||||
}
|
||||
selected := make([]db.Thread, 0, len(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)
|
||||
}
|
||||
if len(selected) >= limit {
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -390,7 +390,7 @@ a better title and motivation. Apply changes with ` + "`knox thread update <id>`
|
||||
}
|
||||
var shown int
|
||||
for _, t := range threads {
|
||||
if !isAutoThreaded(t) {
|
||||
if !t.IsDraft() {
|
||||
continue
|
||||
}
|
||||
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 {
|
||||
var title, motivation, priority, tags string
|
||||
cmd := &cobra.Command{
|
||||
|
||||
@@ -1602,6 +1602,17 @@ type Thread struct {
|
||||
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
|
||||
// considered stalled (derived, reversible — not a stored state).
|
||||
const stallAfterDays = 14
|
||||
@@ -3129,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.
|
||||
|
||||
@@ -805,3 +805,98 @@ func TestUpdateThreadClearsAutoThreadMarker(t *testing.T) {
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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] == '>' {
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user