Files
knox/internal/cmd/snippet_shared.go
T
david 8d6d73b747 fix: read opencode sessions from session_v2/session_message (#7)
Fixes #6.

opencode 2.0.24 migrated its session store on 2026-11-01 21:01:20 UTC. `session`, `message` and `part` stopped being written; sessions now live in `session_v2` and messages in `session_message`. The ingest kept querying the abandoned tables, so every sweep after the migration logged `0 new` — no error, no new sessions indexed.

## Changes

- **`internal/ingest/opencode_db.go`**
  - Read sessions from `session_v2` (title is nullable there, the existing COALESCE + fallback still apply).
  - Rebuild transcripts from both message shapes: user turns at `$.text`, assistant turns from `$.content[]` filtered to `type='text'` (reasoning and tool parts are not indexed). Ordered by `seq`, then part index.
  - Count messages from `session_message` instead of parts.
  - Drop `<system-reminder>` text — reminders now arrive as `synthetic` messages and would eat the 4000-byte summary budget.
  - Ingester version is now `opencode-db/v2`.
- **`internal/watch/watch.go`** — an entry is no longer skipped on `created_at` alone. Resuming a session appends messages without touching the creation time, so the summary is compared too.
- **`internal/ingest/opencode_db_test.go`** — new test builds the v2 schema in a temp SQLite database and asserts user text and assistant text parts are indexed while reasoning, tool and reminder content is not.

## Validation

- `go build ./...`, `go test ./internal/ingest/ ./internal/db/ ./internal/watch/` pass.
- Rebuilt the binary and restarted `knox.service` against the live store:
  ```
  [knox] opencode.db: 1 new, 387 unchanged
  ```
  The new entry is the session that had been invisible since the migration (`Knox OpenCode session adapter compatibility check`, observation version `opencode-db/v2`), and `knox query "knox opencode session adapter compatibility"` finds it.
- 59 pre-migration sessions re-recorded because their stored transcripts contained reminder text that the new filter drops; summaries still carry the conversation.

## Notes

The first commit on this branch is a checkpoint of pre-existing uncommitted work that the adapter fix sits on top of; the fix itself is the second commit (`e07ae8a`).

Reviewed-on: #7
Co-authored-by: David Gwilliam <dhgwilliam@gmail.com>
Co-committed-by: David Gwilliam <dhgwilliam@gmail.com>
2026-11-02 01:16:50 +00:00

147 lines
4.2 KiB
Go

package cmd
import (
"fmt"
"path/filepath"
"strings"
"time"
"github.com/david/knox/internal/db"
"github.com/david/knox/internal/skillsrepo"
)
// snippetEncodeArgs carries an agent's curation decision for one snippet.
type snippetEncodeArgs struct {
Fingerprint string
Title string
Description string
Tags string
Language string
Skill string // skill name, or "auto" to derive from the title
Overwrite bool
}
// encodeSnippet is the single curation path shared by the CLI and the MCP tool.
// It optionally materializes the snippet as a ~/.skills SKILL.md (the second
// sink), then marks the snippet encoded in the index.
func encodeSnippet(kdb *db.KnoxDB, a snippetEncodeArgs) (string, error) {
s, err := kdb.SnippetByFingerprint(a.Fingerprint)
if err != nil {
return "", err
}
if s == nil {
return "", fmt.Errorf("no snippet matching %q", a.Fingerprint)
}
if s.Status == "rejected" {
return "", fmt.Errorf("snippet %s is rejected; un-reject it before encoding", shortFP(s.Fingerprint))
}
title := firstNonEmpty(a.Title, s.Title)
description := firstNonEmpty(a.Description, s.Description)
if description == "" {
description = title
}
skillName := ""
skillPath := ""
if strings.TrimSpace(a.Skill) != "" {
name := a.Skill
if name == "auto" {
name = title
}
md := snippetSkillMarkdown(s, name, title, description, a.Tags)
skillPath, err = skillsrepo.WriteSkill(name, md, a.Overwrite)
if err != nil {
return "", err
}
skillName = filepath.Base(filepath.Dir(skillPath))
}
ok, err := kdb.EncodeSnippet(a.Fingerprint, a.Title, a.Description, a.Tags, a.Language, skillName)
if err != nil {
return "", err
}
if !ok {
return "", fmt.Errorf("snippet %s not encoded (not found or already rejected)", shortFP(s.Fingerprint))
}
var b strings.Builder
fmt.Fprintf(&b, "Encoded snippet %s (%s, %s)", shortFP(s.Fingerprint), firstNonEmpty(s.Language, "text"), s.Tool)
if skillPath != "" {
fmt.Fprintf(&b, "\nWrote skill: %s", skillPath)
}
return b.String(), nil
}
// snippetSkillMarkdown renders a SKILL.md for an encoded snippet, matching the
// frontmatter shape the skills MCP and knox's skills ingester expect.
func snippetSkillMarkdown(s *db.Snippet, name, title, description, tags string) string {
slug := skillsrepo.Slugify(name)
allTags := strings.TrimSpace(tags)
if s.Project != "" {
allTags = strings.TrimSpace(allTags + " scope:project:" + s.Project)
}
allTags = strings.TrimSpace(allTags + " scope:machine:specific")
fence := "```"
if strings.Contains(s.Code, "```") {
fence = "````"
}
lang := s.Language
if lang == "" {
lang = "text"
}
var b strings.Builder
b.WriteString("---\n")
fmt.Fprintf(&b, "name: %s\n", slug)
fmt.Fprintf(&b, "description: %s\n", oneLine(description, 400))
b.WriteString("compatibility: opencode\n")
b.WriteString("metadata:\n")
fmt.Fprintf(&b, " tags: %q\n", allTags)
fmt.Fprintf(&b, " created_at: %q\n", time.Now().UTC().Format(time.RFC3339))
b.WriteString(" source_type: \"knox-snippet\"\n")
fmt.Fprintf(&b, " kind: %q\n", kindOr(s.Kind))
fmt.Fprintf(&b, " source_session: %q\n", s.SourceSession)
fmt.Fprintf(&b, " source_path: %q\n", s.SourcePath)
fmt.Fprintf(&b, " snippet_fingerprint: %q\n", s.Fingerprint)
b.WriteString("---\n\n")
technique := kindOr(s.Kind) == "technique"
fmt.Fprintf(&b, "# %s\n\n", title)
if description != "" {
fmt.Fprintf(&b, "%s\n\n", description)
}
heading := "## Snippet"
if technique {
heading = "## Recipe"
}
fmt.Fprintf(&b, "%s\n\n", heading)
fmt.Fprintf(&b, "%s%s\n%s\n%s\n", fence, lang, s.Code, fence)
b.WriteString("\n## Provenance\n\n")
fmt.Fprintf(&b, "- Extracted from an opencode session where the %s tool completed successfully.\n", s.Tool)
if s.SourcePath != "" && s.SourcePath != "(bash)" {
fmt.Fprintf(&b, "- File: `%s`\n", s.SourcePath)
}
if s.SourceSession != "" {
fmt.Fprintf(&b, "- Session: `%s`\n", s.SourceSession)
}
fmt.Fprintf(&b, "- Evidence: `%s`\n", s.Evidence)
return b.String()
}
func firstNonEmpty(vals ...string) string {
for _, v := range vals {
if strings.TrimSpace(v) != "" {
return strings.TrimSpace(v)
}
}
return ""
}
func oneLine(s string, n int) string {
s = strings.Join(strings.Fields(s), " ")
return truncateStr(s, n)
}