chore: checkpoint uncommitted work before session store fix

Pre-existing work-in-progress in the tree: karakeep, snippets,
skills-health and redaction ingesters, the opencode.db session sweep,
gossip and metrics changes. Checkpointed as-is so the adapter fix in the
next commit stays reviewable on its own.
This commit is contained in:
2026-11-01 13:33:36 -08:00
parent bb852faa27
commit 0b8ac34aee
43 changed files with 6771 additions and 419 deletions
+291
View File
@@ -2,6 +2,9 @@ package cmd
import (
"fmt"
"io"
"os"
"sort"
"strconv"
"strings"
@@ -33,6 +36,294 @@ Subcommands: create, list, link, link-entry, relate, golden, prune, rescan, clos
cmd.AddCommand(newThreadGoldenCmd(kdb))
cmd.AddCommand(newThreadPruneCmd(kdb))
cmd.AddCommand(newThreadRescanCmd(kdb))
cmd.AddCommand(newThreadDenyCmd(kdb))
cmd.AddCommand(newThreadGroomCmd(kdb))
cmd.AddCommand(newThreadRetainCmd(kdb))
cmd.AddCommand(newThreadMergeCmd(kdb))
cmd.AddCommand(newThreadTextCmd(kdb))
cmd.AddCommand(newThreadSummarizeCmd(kdb))
cmd.AddCommand(newThreadLinkNewCmd(kdb))
cmd.AddCommand(newThreadFocusCmd(kdb))
return cmd
}
// newThreadFocusCmd ranks threads by the normalized, source-balanced model.
func newThreadFocusCmd(kdb *db.KnoxDB) *cobra.Command {
var window int
cmd := &cobra.Command{
Use: "focus",
Short: "Rank threads by normalized source-balanced activity (the 'current focus' model)",
RunE: func(c *cobra.Command, args []string) error {
focus, err := kdb.ThreadFocus(window)
if err != nil {
return err
}
if len(focus) == 0 {
fmt.Println("No activity in window.")
return nil
}
for i, f := range focus {
fmt.Printf("%2d. #%-3d score=%.2f z=%+.2f work=%-4d total=%-4d %s\n",
i+1, f.ID, f.Score, f.ZScore, f.WorkRecent, f.Total, f.Title)
fmt.Printf(" %s\n", formatContrib(f))
}
return nil
},
}
cmd.Flags().IntVar(&window, "window", 14, "Window in days")
return cmd
}
// formatContrib renders per-source contributions (count and clipped z).
func formatContrib(f db.ThreadFocus) string {
type kv struct {
src string
z float64
n int
}
items := make([]kv, 0, len(f.Sources))
for s, n := range f.Sources {
items = append(items, kv{s, f.Contrib[s], n})
}
sort.Slice(items, func(i, j int) bool {
if items[i].z != items[j].z {
return items[i].z > items[j].z
}
return items[i].src < items[j].src
})
parts := make([]string, 0, len(items))
for _, it := range items {
parts = append(parts, fmt.Sprintf("%s=%d(z%.2f)", it.src, it.n, it.z))
}
return strings.Join(parts, " ")
}
// newThreadLinkNewCmd links newly-arrived observations to existing threads.
func newThreadLinkNewCmd(kdb *db.KnoxDB) *cobra.Command {
return &cobra.Command{
Use: "link-new",
Short: "Link newly-arrived observations to existing threads (bounded incremental pass)",
RunE: func(c *cobra.Command, args []string) error {
n, err := kdb.AutoLinkNewObservations()
if err != nil {
return err
}
fmt.Printf("Linked %d new observation(s) to threads\n", n)
return nil
},
}
}
// newThreadMergeCmd folds one thread into another.
func newThreadMergeCmd(kdb *db.KnoxDB) *cobra.Command {
return &cobra.Command{
Use: "merge <into-id> <from-id>",
Short: "Merge thread <from> into <into> (moves observations; resolves from)",
Args: cobra.ExactArgs(2),
RunE: func(c *cobra.Command, args []string) error {
into, _ := strconv.ParseInt(args[0], 10, 64)
from, _ := strconv.ParseInt(args[1], 10, 64)
if into == 0 || from == 0 {
return fmt.Errorf("thread ids must be numeric")
}
if err := kdb.MergeThreads(into, from); err != nil {
return err
}
fmt.Printf("Merged thread #%d into #%d\n", from, into)
return nil
},
}
}
// newThreadTextCmd prints a bounded digest of a thread's linked content.
func newThreadTextCmd(kdb *db.KnoxDB) *cobra.Command {
var maxBytes int
cmd := &cobra.Command{
Use: "text <thread-id>",
Short: "Print a bounded digest of a thread's linked content (for summarizing)",
Args: cobra.ExactArgs(1),
RunE: func(c *cobra.Command, args []string) error {
id, _ := strconv.ParseInt(args[0], 10, 64)
if id == 0 {
return fmt.Errorf("thread-id must be numeric")
}
text, err := kdb.ThreadText(id, maxBytes)
if err != nil {
return err
}
fmt.Print(text)
return nil
},
}
cmd.Flags().IntVar(&maxBytes, "max-bytes", 16000, "Max digest size in bytes")
return cmd
}
// newThreadSummarizeCmd stores an agent-written thread summary (from args or stdin).
func newThreadSummarizeCmd(kdb *db.KnoxDB) *cobra.Command {
cmd := &cobra.Command{
Use: "summarize <thread-id> [summary text...]",
Short: "Store a thread summary (sets summarized_at) from args or stdin",
Args: cobra.MinimumNArgs(1),
RunE: func(c *cobra.Command, args []string) error {
id, _ := strconv.ParseInt(args[0], 10, 64)
if id == 0 {
return fmt.Errorf("thread-id must be numeric")
}
summary := strings.Join(args[1:], " ")
if strings.TrimSpace(summary) == "" {
in, _ := io.ReadAll(os.Stdin)
summary = strings.TrimSpace(string(in))
}
if summary == "" {
return fmt.Errorf("no summary provided")
}
if err := kdb.SetThreadSummary(id, summary); err != nil {
return err
}
fmt.Printf("Summary stored for thread #%d\n", id)
return nil
},
}
return cmd
}
// newThreadRetainCmd allowlists a thread so the denylist never flags/resolves it.
func newThreadRetainCmd(kdb *db.KnoxDB) *cobra.Command {
var off bool
cmd := &cobra.Command{
Use: "retain <thread-id>",
Short: "Allowlist a thread so the denylist never flags or resolves it",
Args: cobra.ExactArgs(1),
RunE: func(c *cobra.Command, args []string) error {
id, _ := strconv.ParseInt(args[0], 10, 64)
if id == 0 {
return fmt.Errorf("thread-id must be numeric")
}
if err := kdb.SetThreadRetained(id, !off); err != nil {
return err
}
state := "retained"
if off {
state = "unretained"
}
fmt.Printf("Thread #%d %s\n", id, state)
return nil
},
}
cmd.Flags().BoolVar(&off, "off", false, "Remove the allowlist flag")
return cmd
}
// newThreadGroomCmd prints the value/coherence/denylist assessment for each
// active thread, and optionally runs the denylist pass.
func newThreadGroomCmd(kdb *db.KnoxDB) *cobra.Command {
var deny, lowSignalOnly bool
cmd := &cobra.Command{
Use: "groom",
Short: "Assess thread value/coherence vs the denylist, with suggested titles",
RunE: func(c *cobra.Command, args []string) error {
if deny {
removed, closed, err := kdb.DenyThreadNoise(false)
if err != nil {
return err
}
fmt.Printf("Denylist pass: removed %d links, resolved %d threads.\n\n", removed, len(closed))
}
assessments, err := kdb.GroomThreads(30)
if err != nil {
return err
}
counts := map[string]int{}
for _, a := range assessments {
counts[a.Verdict]++
if lowSignalOnly && a.Verdict != "low-signal" && a.Verdict != "deny" {
continue
}
anchor := "no"
if a.WorkAnchored {
anchor = "yes"
}
denyNote := ""
if a.Denied {
denyNote = " deny=" + a.DenyMatch
}
if a.Retained {
denyNote += " RETAINED"
}
if a.ResummaryDue {
denyNote += " [resummary-due]"
}
fmt.Printf("#%d [%s] linked=%d anchor=%s browser=%.0f%%%s\n", a.ID, a.Verdict, a.Linked, anchor, a.BrowserFrac*100, denyNote)
fmt.Printf(" title: %s\n", a.Title)
if a.SuggestedTitle != "" && a.SuggestedTitle != a.Title {
fmt.Printf(" suggest: %s\n", a.SuggestedTitle)
}
if a.Summary != "" {
fmt.Printf(" summary: %s\n", a.Summary)
}
}
due := 0
for _, a := range assessments {
if a.ResummaryDue {
due++
}
}
fmt.Printf("\nThreads: %d (high-snr=%d ok=%d low-signal=%d deny=%d); resummary-due=%d\n",
len(assessments), counts["high-snr"], counts["ok"], counts["low-signal"], counts["deny"], due)
if merges, err := kdb.MergeSuggestions(3, 0.7); err == nil && len(merges) > 0 {
fmt.Println("\nMerge suggestions (overlapping observation sets):")
for _, m := range merges {
fmt.Printf(" #%d %q + #%d %q — shared=%d (a-only=%d, b-only=%d)\n",
m.A, m.ATitle, m.B, m.BTitle, m.Shared, m.AOnly, m.BOnly)
}
}
return nil
},
}
cmd.Flags().BoolVar(&deny, "deny", false, "Also run the denylist pass first")
cmd.Flags().BoolVar(&lowSignalOnly, "low-signal-only", false, "Only show low-signal/deny threads")
return cmd
}
// newThreadDenyCmd refocuses threads against the shared browser denylist:
// it drops denylisted webapp browsing links and resolves denylisted-topic
// threads that have no work-source anchor.
func newThreadDenyCmd(kdb *db.KnoxDB) *cobra.Command {
var dryRun bool
cmd := &cobra.Command{
Use: "deny",
Short: "Drop denylisted webapp browsing from threads and resolve noise-only threads",
RunE: func(c *cobra.Command, args []string) error {
removed, closed, err := kdb.DenyThreadNoise(dryRun)
if err != nil {
return err
}
verb := "Removed"
if dryRun {
verb = "Would remove"
}
fmt.Printf("%s %d denylisted observation links from threads\n", verb, removed)
if len(closed) == 0 {
fmt.Println("No denylisted-topic threads to resolve.")
return nil
}
for _, id := range closed {
t, _ := kdb.GetThread(id)
label := ""
if t != nil {
label = t.Title
}
if dryRun {
fmt.Printf("Would resolve thread #%d (%s)\n", id, label)
} else {
fmt.Printf("Resolved thread #%d (%s)\n", id, label)
}
}
return nil
},
}
cmd.Flags().BoolVar(&dryRun, "dry-run", false, "Report without writing")
return cmd
}