♻️ Quality: lsp, rzbstart, saved, sbxinit and store without smells (6 → 0)
- lsp.Diagnostics with session.published (sync, then wait) - rzbstart.lists with modelIDs - saved.Write with create - sbxinit: the flags as sbxArgs and parseFlags; printWritable - store: search_match.go (entries, snippets, word matching) Checked: go test, and old vs new binary on 6 mm sbxinit runs (-h, an argument, --yes twice, a .mm agent with --name, answers with --workspace) and /save (saved, existing, no name, an answer out of range): identical output and files (but the sessions' random ids). internal/ is now without smells. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
d5a92e9 parent: f062af9 modified
internal/lsp/change.go +13 -7 | @@ -34,19 +34,25 @@ func (c *Client) Diagnostics(ctx context.Context, path string) (string, error) { | ||
| 34 | 34 | } |
| 35 | 35 | // The request failed: wait for a publication as below. |
| 36 | 36 | } |
| 37 | - // The sequence is read BEFORE the sync: the publication the sync | |
| 38 | - // triggers may arrive before this function gets to look. | |
| 39 | - before := s.publications(u) | |
| 40 | - if _, err := s.sync(ctx, path); err != nil { | |
| 41 | - return "", err | |
| 42 | - } | |
| 43 | - fresh, err := s.waitPublication(ctx, u, before, c.diagWait) | |
| 37 | + fresh, err := s.published(ctx, path, u, c.diagWait) | |
| 44 | 38 | if err != nil { |
| 45 | 39 | return "", err |
| 46 | 40 | } |
| 47 | 41 | return c.renderDiagnostics(s, u, fresh), nil |
| 48 | 42 | } |
| 49 | 43 | |
| 44 | +// published syncs the file and waits for the publication the sync | |
| 45 | +// triggers; fresh is false when none came in time. The sequence is read | |
| 46 | +// BEFORE the sync: the publication may arrive before this function gets to | |
| 47 | +// look. | |
| 48 | +func (s *session) published(ctx context.Context, path string, u uri.URI, wait time.Duration) (bool, error) { | |
| 49 | + before := s.publications(u) | |
| 50 | + if _, err := s.sync(ctx, path); err != nil { | |
| 51 | + return false, err | |
| 52 | + } | |
| 53 | + return s.waitPublication(ctx, u, before, wait) | |
| 54 | +} | |
| 55 | + | |
| 50 | 56 | // pullsDiagnostics reports whether the server answers textDocument/diagnostic |
| 51 | 57 | // (LSP 3.17 "pull" diagnostics). Some servers only do that: TypeScript 7's |
| 52 | 58 | // `tsc --lsp --stdio` never publishes, so waiting for a publication always |
| @@ -34,19 +34,25 @@ func (c *Client) Diagnostics(ctx context.Context, path string) (string, error) { | |||
| 34 | } | 34 | } |
| 35 | // The request failed: wait for a publication as below. | 35 | // The request failed: wait for a publication as below. |
| 36 | } | 36 | } |
| 37 | - // The sequence is read BEFORE the sync: the publication the sync | 37 | + fresh, err := s.published(ctx, path, u, c.diagWait) |
| 38 | - // triggers may arrive before this function gets to look. | ||
| 39 | - before := s.publications(u) | ||
| 40 | - if _, err := s.sync(ctx, path); err != nil { | ||
| 41 | - return "", err | ||
| 42 | - } | ||
| 43 | - fresh, err := s.waitPublication(ctx, u, before, c.diagWait) | ||
| 44 | if err != nil { | 38 | if err != nil { |
| 45 | return "", err | 39 | return "", err |
| 46 | } | 40 | } |
| 47 | return c.renderDiagnostics(s, u, fresh), nil | 41 | return c.renderDiagnostics(s, u, fresh), nil |
| 48 | } | 42 | } |
| 49 | 43 | ||
| 44 | +// published syncs the file and waits for the publication the sync | ||
| 45 | +// triggers; fresh is false when none came in time. The sequence is read | ||
| 46 | +// BEFORE the sync: the publication may arrive before this function gets to | ||
| 47 | +// look. | ||
| 48 | +func (s *session) published(ctx context.Context, path string, u uri.URI, wait time.Duration) (bool, error) { | ||
| 49 | + before := s.publications(u) | ||
| 50 | + if _, err := s.sync(ctx, path); err != nil { | ||
| 51 | + return false, err | ||
| 52 | + } | ||
| 53 | + return s.waitPublication(ctx, u, before, wait) | ||
| 54 | +} | ||
| 55 | + | ||
| 50 | // pullsDiagnostics reports whether the server answers textDocument/diagnostic | 56 | // pullsDiagnostics reports whether the server answers textDocument/diagnostic |
| 51 | // (LSP 3.17 "pull" diagnostics). Some servers only do that: TypeScript 7's | 57 | // (LSP 3.17 "pull" diagnostics). Some servers only do that: TypeScript 7's |
| 52 | // `tsc --lsp --stdio` never publishes, so waiting for a publication always | 58 | // `tsc --lsp --stdio` never publishes, so waiting for a publication always |
modified
internal/rzbstart/rzbstart.go +14 -8 | @@ -32,6 +32,7 @@ import ( | ||
| 32 | 32 | "os" |
| 33 | 33 | "os/exec" |
| 34 | 34 | "runtime" |
| 35 | + "slices" | |
| 35 | 36 | "strconv" |
| 36 | 37 | "strings" |
| 37 | 38 | "time" |
| @@ -203,20 +204,26 @@ func pull(ctx context.Context, o Options, so serverstart.Options) error { | ||
| 203 | 204 | |
| 204 | 205 | // lists reports whether GET <base>/v1/models names o.Model. |
| 205 | 206 | func lists(ctx context.Context, base string, o Options) (bool, error) { |
| 207 | + ids, err := modelIDs(ctx, base, o) | |
| 208 | + return slices.Contains(ids, o.Model), err | |
| 209 | +} | |
| 210 | + | |
| 211 | +// modelIDs is the ids GET <base>/v1/models lists. | |
| 212 | +func modelIDs(ctx context.Context, base string, o Options) ([]string, error) { | |
| 206 | 213 | req, err := http.NewRequestWithContext(ctx, http.MethodGet, base+"/v1/models", nil) |
| 207 | 214 | if err != nil { |
| 208 | - return false, err | |
| 215 | + return nil, err | |
| 209 | 216 | } |
| 210 | 217 | if o.APIKey != "" { |
| 211 | 218 | req.Header.Set("Authorization", "Bearer "+o.APIKey) |
| 212 | 219 | } |
| 213 | 220 | resp, err := http.DefaultClient.Do(req) |
| 214 | 221 | if err != nil { |
| 215 | - return false, err | |
| 222 | + return nil, err | |
| 216 | 223 | } |
| 217 | 224 | defer func() { _ = resp.Body.Close() }() |
| 218 | 225 | if resp.StatusCode != http.StatusOK { |
| 219 | - return false, fmt.Errorf("rzb: GET /v1/models answered %d (is RZB_API_KEY the server's key?)", resp.StatusCode) | |
| 226 | + return nil, fmt.Errorf("rzb: GET /v1/models answered %d (is RZB_API_KEY the server's key?)", resp.StatusCode) | |
| 220 | 227 | } |
| 221 | 228 | var list struct { |
| 222 | 229 | Data []struct { |
| @@ -224,12 +231,11 @@ func lists(ctx context.Context, base string, o Options) (bool, error) { | ||
| 224 | 231 | } `json:"data"` |
| 225 | 232 | } |
| 226 | 233 | if err := json.NewDecoder(resp.Body).Decode(&list); err != nil { |
| 227 | - return false, fmt.Errorf("GET /v1/models: %w", err) | |
| 234 | + return nil, fmt.Errorf("GET /v1/models: %w", err) | |
| 228 | 235 | } |
| 236 | + ids := make([]string, 0, len(list.Data)) | |
| 229 | 237 | for _, m := range list.Data { |
| 230 | - if m.ID == o.Model { | |
| 231 | - return true, nil | |
| 232 | - } | |
| 238 | + ids = append(ids, m.ID) | |
| 233 | 239 | } |
| 234 | - return false, nil | |
| 240 | + return ids, nil | |
| 235 | 241 | } |
| @@ -32,6 +32,7 @@ import ( | |||
| 32 | "os" | 32 | "os" |
| 33 | "os/exec" | 33 | "os/exec" |
| 34 | "runtime" | 34 | "runtime" |
| 35 | + "slices" | ||
| 35 | "strconv" | 36 | "strconv" |
| 36 | "strings" | 37 | "strings" |
| 37 | "time" | 38 | "time" |
| @@ -203,20 +204,26 @@ func pull(ctx context.Context, o Options, so serverstart.Options) error { | |||
| 203 | 204 | ||
| 204 | // lists reports whether GET <base>/v1/models names o.Model. | 205 | // lists reports whether GET <base>/v1/models names o.Model. |
| 205 | func lists(ctx context.Context, base string, o Options) (bool, error) { | 206 | func lists(ctx context.Context, base string, o Options) (bool, error) { |
| 207 | + ids, err := modelIDs(ctx, base, o) | ||
| 208 | + return slices.Contains(ids, o.Model), err | ||
| 209 | +} | ||
| 210 | + | ||
| 211 | +// modelIDs is the ids GET <base>/v1/models lists. | ||
| 212 | +func modelIDs(ctx context.Context, base string, o Options) ([]string, error) { | ||
| 206 | req, err := http.NewRequestWithContext(ctx, http.MethodGet, base+"/v1/models", nil) | 213 | req, err := http.NewRequestWithContext(ctx, http.MethodGet, base+"/v1/models", nil) |
| 207 | if err != nil { | 214 | if err != nil { |
| 208 | - return false, err | 215 | + return nil, err |
| 209 | } | 216 | } |
| 210 | if o.APIKey != "" { | 217 | if o.APIKey != "" { |
| 211 | req.Header.Set("Authorization", "Bearer "+o.APIKey) | 218 | req.Header.Set("Authorization", "Bearer "+o.APIKey) |
| 212 | } | 219 | } |
| 213 | resp, err := http.DefaultClient.Do(req) | 220 | resp, err := http.DefaultClient.Do(req) |
| 214 | if err != nil { | 221 | if err != nil { |
| 215 | - return false, err | 222 | + return nil, err |
| 216 | } | 223 | } |
| 217 | defer func() { _ = resp.Body.Close() }() | 224 | defer func() { _ = resp.Body.Close() }() |
| 218 | if resp.StatusCode != http.StatusOK { | 225 | if resp.StatusCode != http.StatusOK { |
| 219 | - return false, fmt.Errorf("rzb: GET /v1/models answered %d (is RZB_API_KEY the server's key?)", resp.StatusCode) | 226 | + return nil, fmt.Errorf("rzb: GET /v1/models answered %d (is RZB_API_KEY the server's key?)", resp.StatusCode) |
| 220 | } | 227 | } |
| 221 | var list struct { | 228 | var list struct { |
| 222 | Data []struct { | 229 | Data []struct { |
| @@ -224,12 +231,11 @@ func lists(ctx context.Context, base string, o Options) (bool, error) { | |||
| 224 | } `json:"data"` | 231 | } `json:"data"` |
| 225 | } | 232 | } |
| 226 | if err := json.NewDecoder(resp.Body).Decode(&list); err != nil { | 233 | if err := json.NewDecoder(resp.Body).Decode(&list); err != nil { |
| 227 | - return false, fmt.Errorf("GET /v1/models: %w", err) | 234 | + return nil, fmt.Errorf("GET /v1/models: %w", err) |
| 228 | } | 235 | } |
| 236 | + ids := make([]string, 0, len(list.Data)) | ||
| 229 | for _, m := range list.Data { | 237 | for _, m := range list.Data { |
| 230 | - if m.ID == o.Model { | 238 | + ids = append(ids, m.ID) |
| 231 | - return true, nil | ||
| 232 | - } | ||
| 233 | } | 239 | } |
| 234 | - return false, nil | 240 | + return ids, nil |
| 235 | } | 241 | } |
modified
internal/saved/saved.go +8 -3 | @@ -31,10 +31,10 @@ var ErrExists = errors.New("the file already exists") | ||
| 31 | 31 | // n, err := saved.Write("notes/nushell.md", answer) |
| 32 | 32 | // // n: bytes written; errors.Is(err, saved.ErrExists) when it was there |
| 33 | 33 | func Write(path, text string) (int, error) { |
| 34 | - if strings.TrimSpace(path) == "" { | |
| 34 | + switch { | |
| 35 | + case strings.TrimSpace(path) == "": | |
| 35 | 36 | return 0, errors.New("no file name given") |
| 36 | - } | |
| 37 | - if strings.TrimSpace(text) == "" { | |
| 37 | + case strings.TrimSpace(text) == "": | |
| 38 | 38 | return 0, errors.New("the answer is empty: nothing to save") |
| 39 | 39 | } |
| 40 | 40 | if !strings.HasSuffix(text, "\n") { |
| @@ -45,6 +45,11 @@ func Write(path, text string) (int, error) { | ||
| 45 | 45 | return 0, err |
| 46 | 46 | } |
| 47 | 47 | } |
| 48 | + return create(path, text) | |
| 49 | +} | |
| 50 | + | |
| 51 | +// create writes a new file — never an existing one (ErrExists). | |
| 52 | +func create(path, text string) (int, error) { | |
| 48 | 53 | f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o644) |
| 49 | 54 | if errors.Is(err, os.ErrExist) { |
| 50 | 55 | return 0, fmt.Errorf("%s: %w", path, ErrExists) |
| @@ -31,10 +31,10 @@ var ErrExists = errors.New("the file already exists") | |||
| 31 | // n, err := saved.Write("notes/nushell.md", answer) | 31 | // n, err := saved.Write("notes/nushell.md", answer) |
| 32 | // // n: bytes written; errors.Is(err, saved.ErrExists) when it was there | 32 | // // n: bytes written; errors.Is(err, saved.ErrExists) when it was there |
| 33 | func Write(path, text string) (int, error) { | 33 | func Write(path, text string) (int, error) { |
| 34 | - if strings.TrimSpace(path) == "" { | 34 | + switch { |
| 35 | + case strings.TrimSpace(path) == "": | ||
| 35 | return 0, errors.New("no file name given") | 36 | return 0, errors.New("no file name given") |
| 36 | - } | 37 | + case strings.TrimSpace(text) == "": |
| 37 | - if strings.TrimSpace(text) == "" { | ||
| 38 | return 0, errors.New("the answer is empty: nothing to save") | 38 | return 0, errors.New("the answer is empty: nothing to save") |
| 39 | } | 39 | } |
| 40 | if !strings.HasSuffix(text, "\n") { | 40 | if !strings.HasSuffix(text, "\n") { |
| @@ -45,6 +45,11 @@ func Write(path, text string) (int, error) { | |||
| 45 | return 0, err | 45 | return 0, err |
| 46 | } | 46 | } |
| 47 | } | 47 | } |
| 48 | + return create(path, text) | ||
| 49 | +} | ||
| 50 | + | ||
| 51 | +// create writes a new file — never an existing one (ErrExists). | ||
| 52 | +func create(path, text string) (int, error) { | ||
| 48 | f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o644) | 53 | f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o644) |
| 49 | if errors.Is(err, os.ErrExist) { | 54 | if errors.Is(err, os.ErrExist) { |
| 50 | return 0, fmt.Errorf("%s: %w", path, ErrExists) | 55 | return 0, fmt.Errorf("%s: %w", path, ErrExists) |
modified
internal/sbxinit/sbxinit.go +46 -24 | @@ -146,32 +146,47 @@ func (p place) resolve(path string) string { | ||
| 146 | 146 | return filepath.Join(p.dir, path) |
| 147 | 147 | } |
| 148 | 148 | |
| 149 | -func run(args []string, stdin io.Reader, stdout io.Writer, latest func() (string, error), at place) int { | |
| 149 | +// sbxArgs are mm sbxinit's flags; explicit says -agent was given. | |
| 150 | +type sbxArgs struct { | |
| 151 | + name, agentFile, workspace string | |
| 152 | + yes, explicit bool | |
| 153 | +} | |
| 154 | + | |
| 155 | +// parseFlags reads the flags. ok is false when run must stop with code: 0 | |
| 156 | +// for -h, 2 for an unknown flag or an argument. | |
| 157 | +func parseFlags(args []string, stdout io.Writer) (a sbxArgs, code int, ok bool) { | |
| 150 | 158 | fs := flag.NewFlagSet("mm sbxinit", flag.ContinueOnError) |
| 151 | 159 | fs.SetOutput(stdout) |
| 152 | - name := fs.String("name", "", "the agent's name; the sandbox is <name>-sbx (default: acp.name in the agent file, else mm)") | |
| 153 | - agentFile := fs.String("agent", "agent.yaml", "the agent file to name the sandbox after (default: agent.yaml, then .mm/agent.yaml)") | |
| 154 | - workspace := fs.String("workspace", ".", "the folder the sandbox mounts, relative to the current directory or absolute") | |
| 155 | - yes := fs.Bool("yes", false, "ask nothing: an existing file stops everything, nothing is overwritten") | |
| 160 | + fs.StringVar(&a.name, "name", "", "the agent's name; the sandbox is <name>-sbx (default: acp.name in the agent file, else mm)") | |
| 161 | + fs.StringVar(&a.agentFile, "agent", "agent.yaml", "the agent file to name the sandbox after (default: agent.yaml, then .mm/agent.yaml)") | |
| 162 | + fs.StringVar(&a.workspace, "workspace", ".", "the folder the sandbox mounts, relative to the current directory or absolute") | |
| 163 | + fs.BoolVar(&a.yes, "yes", false, "ask nothing: an existing file stops everything, nothing is overwritten") | |
| 156 | 164 | if err := fs.Parse(args); err != nil { |
| 157 | 165 | if errors.Is(err, flag.ErrHelp) { |
| 158 | - return 0 | |
| 166 | + return a, 0, false | |
| 159 | 167 | } |
| 160 | - return 2 | |
| 168 | + return a, 2, false | |
| 161 | 169 | } |
| 162 | 170 | if fs.NArg() > 0 { |
| 163 | 171 | fmt.Fprintf(stdout, "⚠️ mm sbxinit takes no argument, got %q\n", fs.Arg(0)) |
| 164 | - return 2 | |
| 172 | + return a, 2, false | |
| 173 | + } | |
| 174 | + fs.Visit(func(f *flag.Flag) { a.explicit = a.explicit || f.Name == "agent" }) | |
| 175 | + return a, 0, true | |
| 176 | +} | |
| 177 | + | |
| 178 | +func run(args []string, stdin io.Reader, stdout io.Writer, latest func() (string, error), at place) int { | |
| 179 | + a, code, ok := parseFlags(args, stdout) | |
| 180 | + if !ok { | |
| 181 | + return code | |
| 165 | 182 | } |
| 166 | - absolute, err := filepath.Abs(at.resolve(*workspace)) | |
| 183 | + absolute, err := filepath.Abs(at.resolve(a.workspace)) | |
| 167 | 184 | if err != nil { |
| 168 | 185 | fmt.Fprintln(stdout, "⚠️ "+err.Error()) |
| 169 | 186 | return 1 |
| 170 | 187 | } |
| 171 | 188 | |
| 172 | - explicit := false | |
| 173 | - fs.Visit(func(f *flag.Flag) { explicit = explicit || f.Name == "agent" }) | |
| 174 | - agentPath := scaffold.FindAgentFile(*agentFile, absolute, explicit, at.resolve) | |
| 189 | + agentPath := scaffold.FindAgentFile(a.agentFile, absolute, a.explicit, at.resolve) | |
| 175 | 190 | mmFolder := mmFolderOf(agentPath, absolute) |
| 176 | 191 | if mmFolder != nil { |
| 177 | 192 | // The paths of a .mm project's file are relative to the folder of |
| @@ -181,34 +196,41 @@ func run(args []string, stdin io.Reader, stdout io.Writer, latest func() (string | ||
| 181 | 196 | mmFolder.Base, _ = os.Getwd() |
| 182 | 197 | } |
| 183 | 198 | } |
| 184 | - chosen := *name | |
| 199 | + chosen := a.name | |
| 185 | 200 | if chosen == "" { |
| 186 | 201 | chosen = scaffold.AgentName(agentPath, stdout) |
| 187 | 202 | } |
| 188 | 203 | sandbox := scaffold.Name(chosen) + "-sbx" |
| 189 | 204 | files := []scaffold.File{{Path: at.resolve("sbxenv.yaml"), Replace: at.overwrite, Text: Render(sandbox, kitTag(latest, stdout), absolute, mmFolder)}} |
| 190 | - wrote, err := scaffold.Write(files, stdin, stdout, *yes) | |
| 205 | + wrote, err := scaffold.Write(files, stdin, stdout, a.yes) | |
| 191 | 206 | if err != nil { |
| 192 | 207 | fmt.Fprintln(stdout, "⚠️ "+err.Error()) |
| 193 | 208 | return 1 |
| 194 | 209 | } |
| 195 | 210 | if wrote { |
| 196 | 211 | warnAboutWorkspace(stdout, absolute, agentPath) |
| 197 | - if mmFolder != nil { | |
| 198 | - fmt.Fprintf(stdout, "\nThe agent is %s: .mm/ is mounted read-only, writable again:", agentPath) | |
| 199 | - if len(mmFolder.Writable) == 0 { | |
| 200 | - fmt.Fprint(stdout, " nothing (no sessions, no trace)") | |
| 201 | - } | |
| 202 | - for _, w := range mmFolder.Writable { | |
| 203 | - fmt.Fprintf(stdout, " %s (%s)", mmFolder.Rel(w.Path), w.Key) | |
| 204 | - } | |
| 205 | - fmt.Fprintln(stdout) | |
| 206 | - } | |
| 212 | + printWritable(stdout, agentPath, mmFolder) | |
| 207 | 213 | fmt.Fprintf(stdout, "\nCreate the sandbox %[1]s:\n sbx env create --force\n\nRun the sandbox %[1]s:\n sbx env run --force\n\nRemove it:\n sbx env rm --force\n", sandbox) |
| 208 | 214 | } |
| 209 | 215 | return 0 |
| 210 | 216 | } |
| 211 | 217 | |
| 218 | +// printWritable says, for a .mm project, what stays writable in the | |
| 219 | +// read-only .mm/ mount. | |
| 220 | +func printWritable(stdout io.Writer, agentPath string, mmFolder *scaffold.MMFolder) { | |
| 221 | + if mmFolder == nil { | |
| 222 | + return | |
| 223 | + } | |
| 224 | + fmt.Fprintf(stdout, "\nThe agent is %s: .mm/ is mounted read-only, writable again:", agentPath) | |
| 225 | + if len(mmFolder.Writable) == 0 { | |
| 226 | + fmt.Fprint(stdout, " nothing (no sessions, no trace)") | |
| 227 | + } | |
| 228 | + for _, w := range mmFolder.Writable { | |
| 229 | + fmt.Fprintf(stdout, " %s (%s)", mmFolder.Rel(w.Path), w.Key) | |
| 230 | + } | |
| 231 | + fmt.Fprintln(stdout) | |
| 232 | +} | |
| 233 | + | |
| 212 | 234 | // kitTag is the latest version, or "latest" with the reason when it cannot be read. |
| 213 | 235 | func kitTag(latest func() (string, error), stdout io.Writer) string { |
| 214 | 236 | version, err := latest() |
| @@ -146,32 +146,47 @@ func (p place) resolve(path string) string { | |||
| 146 | return filepath.Join(p.dir, path) | 146 | return filepath.Join(p.dir, path) |
| 147 | } | 147 | } |
| 148 | 148 | ||
| 149 | -func run(args []string, stdin io.Reader, stdout io.Writer, latest func() (string, error), at place) int { | 149 | +// sbxArgs are mm sbxinit's flags; explicit says -agent was given. |
| 150 | +type sbxArgs struct { | ||
| 151 | + name, agentFile, workspace string | ||
| 152 | + yes, explicit bool | ||
| 153 | +} | ||
| 154 | + | ||
| 155 | +// parseFlags reads the flags. ok is false when run must stop with code: 0 | ||
| 156 | +// for -h, 2 for an unknown flag or an argument. | ||
| 157 | +func parseFlags(args []string, stdout io.Writer) (a sbxArgs, code int, ok bool) { | ||
| 150 | fs := flag.NewFlagSet("mm sbxinit", flag.ContinueOnError) | 158 | fs := flag.NewFlagSet("mm sbxinit", flag.ContinueOnError) |
| 151 | fs.SetOutput(stdout) | 159 | fs.SetOutput(stdout) |
| 152 | - name := fs.String("name", "", "the agent's name; the sandbox is <name>-sbx (default: acp.name in the agent file, else mm)") | 160 | + fs.StringVar(&a.name, "name", "", "the agent's name; the sandbox is <name>-sbx (default: acp.name in the agent file, else mm)") |
| 153 | - agentFile := fs.String("agent", "agent.yaml", "the agent file to name the sandbox after (default: agent.yaml, then .mm/agent.yaml)") | 161 | + fs.StringVar(&a.agentFile, "agent", "agent.yaml", "the agent file to name the sandbox after (default: agent.yaml, then .mm/agent.yaml)") |
| 154 | - workspace := fs.String("workspace", ".", "the folder the sandbox mounts, relative to the current directory or absolute") | 162 | + fs.StringVar(&a.workspace, "workspace", ".", "the folder the sandbox mounts, relative to the current directory or absolute") |
| 155 | - yes := fs.Bool("yes", false, "ask nothing: an existing file stops everything, nothing is overwritten") | 163 | + fs.BoolVar(&a.yes, "yes", false, "ask nothing: an existing file stops everything, nothing is overwritten") |
| 156 | if err := fs.Parse(args); err != nil { | 164 | if err := fs.Parse(args); err != nil { |
| 157 | if errors.Is(err, flag.ErrHelp) { | 165 | if errors.Is(err, flag.ErrHelp) { |
| 158 | - return 0 | 166 | + return a, 0, false |
| 159 | } | 167 | } |
| 160 | - return 2 | 168 | + return a, 2, false |
| 161 | } | 169 | } |
| 162 | if fs.NArg() > 0 { | 170 | if fs.NArg() > 0 { |
| 163 | fmt.Fprintf(stdout, "⚠️ mm sbxinit takes no argument, got %q\n", fs.Arg(0)) | 171 | fmt.Fprintf(stdout, "⚠️ mm sbxinit takes no argument, got %q\n", fs.Arg(0)) |
| 164 | - return 2 | 172 | + return a, 2, false |
| 173 | + } | ||
| 174 | + fs.Visit(func(f *flag.Flag) { a.explicit = a.explicit || f.Name == "agent" }) | ||
| 175 | + return a, 0, true | ||
| 176 | +} | ||
| 177 | + | ||
| 178 | +func run(args []string, stdin io.Reader, stdout io.Writer, latest func() (string, error), at place) int { | ||
| 179 | + a, code, ok := parseFlags(args, stdout) | ||
| 180 | + if !ok { | ||
| 181 | + return code | ||
| 165 | } | 182 | } |
| 166 | - absolute, err := filepath.Abs(at.resolve(*workspace)) | 183 | + absolute, err := filepath.Abs(at.resolve(a.workspace)) |
| 167 | if err != nil { | 184 | if err != nil { |
| 168 | fmt.Fprintln(stdout, "⚠️ "+err.Error()) | 185 | fmt.Fprintln(stdout, "⚠️ "+err.Error()) |
| 169 | return 1 | 186 | return 1 |
| 170 | } | 187 | } |
| 171 | 188 | ||
| 172 | - explicit := false | 189 | + agentPath := scaffold.FindAgentFile(a.agentFile, absolute, a.explicit, at.resolve) |
| 173 | - fs.Visit(func(f *flag.Flag) { explicit = explicit || f.Name == "agent" }) | ||
| 174 | - agentPath := scaffold.FindAgentFile(*agentFile, absolute, explicit, at.resolve) | ||
| 175 | mmFolder := mmFolderOf(agentPath, absolute) | 190 | mmFolder := mmFolderOf(agentPath, absolute) |
| 176 | if mmFolder != nil { | 191 | if mmFolder != nil { |
| 177 | // The paths of a .mm project's file are relative to the folder of | 192 | // The paths of a .mm project's file are relative to the folder of |
| @@ -181,34 +196,41 @@ func run(args []string, stdin io.Reader, stdout io.Writer, latest func() (string | |||
| 181 | mmFolder.Base, _ = os.Getwd() | 196 | mmFolder.Base, _ = os.Getwd() |
| 182 | } | 197 | } |
| 183 | } | 198 | } |
| 184 | - chosen := *name | 199 | + chosen := a.name |
| 185 | if chosen == "" { | 200 | if chosen == "" { |
| 186 | chosen = scaffold.AgentName(agentPath, stdout) | 201 | chosen = scaffold.AgentName(agentPath, stdout) |
| 187 | } | 202 | } |
| 188 | sandbox := scaffold.Name(chosen) + "-sbx" | 203 | sandbox := scaffold.Name(chosen) + "-sbx" |
| 189 | files := []scaffold.File{{Path: at.resolve("sbxenv.yaml"), Replace: at.overwrite, Text: Render(sandbox, kitTag(latest, stdout), absolute, mmFolder)}} | 204 | files := []scaffold.File{{Path: at.resolve("sbxenv.yaml"), Replace: at.overwrite, Text: Render(sandbox, kitTag(latest, stdout), absolute, mmFolder)}} |
| 190 | - wrote, err := scaffold.Write(files, stdin, stdout, *yes) | 205 | + wrote, err := scaffold.Write(files, stdin, stdout, a.yes) |
| 191 | if err != nil { | 206 | if err != nil { |
| 192 | fmt.Fprintln(stdout, "⚠️ "+err.Error()) | 207 | fmt.Fprintln(stdout, "⚠️ "+err.Error()) |
| 193 | return 1 | 208 | return 1 |
| 194 | } | 209 | } |
| 195 | if wrote { | 210 | if wrote { |
| 196 | warnAboutWorkspace(stdout, absolute, agentPath) | 211 | warnAboutWorkspace(stdout, absolute, agentPath) |
| 197 | - if mmFolder != nil { | 212 | + printWritable(stdout, agentPath, mmFolder) |
| 198 | - fmt.Fprintf(stdout, "\nThe agent is %s: .mm/ is mounted read-only, writable again:", agentPath) | ||
| 199 | - if len(mmFolder.Writable) == 0 { | ||
| 200 | - fmt.Fprint(stdout, " nothing (no sessions, no trace)") | ||
| 201 | - } | ||
| 202 | - for _, w := range mmFolder.Writable { | ||
| 203 | - fmt.Fprintf(stdout, " %s (%s)", mmFolder.Rel(w.Path), w.Key) | ||
| 204 | - } | ||
| 205 | - fmt.Fprintln(stdout) | ||
| 206 | - } | ||
| 207 | fmt.Fprintf(stdout, "\nCreate the sandbox %[1]s:\n sbx env create --force\n\nRun the sandbox %[1]s:\n sbx env run --force\n\nRemove it:\n sbx env rm --force\n", sandbox) | 213 | fmt.Fprintf(stdout, "\nCreate the sandbox %[1]s:\n sbx env create --force\n\nRun the sandbox %[1]s:\n sbx env run --force\n\nRemove it:\n sbx env rm --force\n", sandbox) |
| 208 | } | 214 | } |
| 209 | return 0 | 215 | return 0 |
| 210 | } | 216 | } |
| 211 | 217 | ||
| 218 | +// printWritable says, for a .mm project, what stays writable in the | ||
| 219 | +// read-only .mm/ mount. | ||
| 220 | +func printWritable(stdout io.Writer, agentPath string, mmFolder *scaffold.MMFolder) { | ||
| 221 | + if mmFolder == nil { | ||
| 222 | + return | ||
| 223 | + } | ||
| 224 | + fmt.Fprintf(stdout, "\nThe agent is %s: .mm/ is mounted read-only, writable again:", agentPath) | ||
| 225 | + if len(mmFolder.Writable) == 0 { | ||
| 226 | + fmt.Fprint(stdout, " nothing (no sessions, no trace)") | ||
| 227 | + } | ||
| 228 | + for _, w := range mmFolder.Writable { | ||
| 229 | + fmt.Fprintf(stdout, " %s (%s)", mmFolder.Rel(w.Path), w.Key) | ||
| 230 | + } | ||
| 231 | + fmt.Fprintln(stdout) | ||
| 232 | +} | ||
| 233 | + | ||
| 212 | // kitTag is the latest version, or "latest" with the reason when it cannot be read. | 234 | // kitTag is the latest version, or "latest" with the reason when it cannot be read. |
| 213 | func kitTag(latest func() (string, error), stdout io.Writer) string { | 235 | func kitTag(latest func() (string, error), stdout io.Writer) string { |
| 214 | version, err := latest() | 236 | version, err := latest() |
modified
internal/store/search.go +0 -139 | @@ -8,7 +8,6 @@ import ( | ||
| 8 | 8 | "time" |
| 9 | 9 | "unicode/utf8" |
| 10 | 10 | |
| 11 | - "mm/internal/compact" | |
| 12 | 11 | "mm/internal/textfold" |
| 13 | 12 | |
| 14 | 13 | "github.com/firebase/genkit/go/ai" |
| @@ -187,141 +186,3 @@ func knownTexts(msgs []*ai.Message) map[string]bool { | ||
| 187 | 186 | } |
| 188 | 187 | return seen |
| 189 | 188 | } |
| 190 | - | |
| 191 | -// entry is one searchable message of a session, with its turn. | |
| 192 | -type entry struct { | |
| 193 | - role, text string | |
| 194 | - turn int | |
| 195 | - final bool // the answer its turn ended on | |
| 196 | -} | |
| 197 | - | |
| 198 | -// entries lists the searchable messages of a session, numbered by question, | |
| 199 | -// each turn's last answer marked final. | |
| 200 | -func entries(msgs []*ai.Message) []entry { | |
| 201 | - var out []entry | |
| 202 | - turn := 0 | |
| 203 | - for _, m := range msgs { | |
| 204 | - role, text, ok := searchable(m) | |
| 205 | - if !ok { | |
| 206 | - continue | |
| 207 | - } | |
| 208 | - if role == "question" { | |
| 209 | - turn++ | |
| 210 | - } | |
| 211 | - out = append(out, entry{role: role, text: text, turn: max(turn, 1)}) | |
| 212 | - } | |
| 213 | - for i := range out { | |
| 214 | - next := i + 1 | |
| 215 | - out[i].final = out[i].role == "answer" && (next == len(out) || out[next].role != "answer") | |
| 216 | - } | |
| 217 | - return out | |
| 218 | -} | |
| 219 | - | |
| 220 | -// searchSession is the hits of one session. A question that matches comes | |
| 221 | -// with its turn's final answer (Hit.Answer), which is then not a hit of its | |
| 222 | -// own; a message seen already (the conversation in progress) is skipped. | |
| 223 | -func searchSession(sess *Session, words []string, seen map[string]bool) []Hit { | |
| 224 | - var hits []Hit | |
| 225 | - list := entries(sess.Messages) | |
| 226 | - answered := map[int]bool{} // entries folded into their question's hit | |
| 227 | - for i, e := range list { | |
| 228 | - if answered[i] || seen[e.role+"\x00"+e.text] { | |
| 229 | - continue | |
| 230 | - } | |
| 231 | - score, first, last := matchWords(e.text, words) | |
| 232 | - if score == 0 { | |
| 233 | - continue | |
| 234 | - } | |
| 235 | - hit := Hit{Session: sess.ID, At: sess.UpdatedAt, Turn: e.turn, Role: e.role, Snippet: snippet(e.text, first, last), Score: score} | |
| 236 | - if e.role == "question" { | |
| 237 | - if j := finalAnswer(list, i); j >= 0 { | |
| 238 | - answered[j] = true | |
| 239 | - hit.Answer = answerSnippet(list[j].text, words) | |
| 240 | - hit.Score, _, _ = matchWords(e.text+"\n"+list[j].text, words) | |
| 241 | - } | |
| 242 | - } | |
| 243 | - hits = append(hits, hit) | |
| 244 | - } | |
| 245 | - return hits | |
| 246 | -} | |
| 247 | - | |
| 248 | -// finalAnswer is the index of the answer the turn of question i ended on, | |
| 249 | -// -1 when it has none (the turn failed, or the session stops there). | |
| 250 | -func finalAnswer(list []entry, i int) int { | |
| 251 | - for j := i + 1; j < len(list) && list[j].role != "question"; j++ { | |
| 252 | - if list[j].final { | |
| 253 | - return j | |
| 254 | - } | |
| 255 | - } | |
| 256 | - return -1 | |
| 257 | -} | |
| 258 | - | |
| 259 | -// answerSnippet is what a question's hit shows of its answer: the text | |
| 260 | -// around the words when it holds some, its beginning otherwise. | |
| 261 | -func answerSnippet(text string, words []string) string { | |
| 262 | - score, first, last := matchWords(text, words) | |
| 263 | - if score == 0 { | |
| 264 | - first, last = 0, 0 | |
| 265 | - } | |
| 266 | - return snippet(text, first, last) | |
| 267 | -} | |
| 268 | - | |
| 269 | -// searchable is the role and text of a message worth searching, and whether | |
| 270 | -// it is one: a question as the user typed it (see question), an answer's | |
| 271 | -// text, a /compact summary's notes — without the wrapper line mm puts before | |
| 272 | -// them, and never the fixed acknowledgement that follows them. | |
| 273 | -func searchable(m *ai.Message) (role, text string, ok bool) { | |
| 274 | - switch { | |
| 275 | - case m == nil: | |
| 276 | - return "", "", false | |
| 277 | - case compact.InSummaryPair(m): | |
| 278 | - text = strings.TrimSpace(compact.SummaryNotes(m)) | |
| 279 | - return "summary", text, compact.IsSummary(m) && text != "" | |
| 280 | - case m.Role == ai.RoleUser: | |
| 281 | - text, ok = question(m) | |
| 282 | - return "question", text, ok | |
| 283 | - case m.Role == ai.RoleModel: | |
| 284 | - text = strings.TrimSpace(m.Text()) | |
| 285 | - return "answer", text, text != "" | |
| 286 | - } | |
| 287 | - return "", "", false | |
| 288 | -} | |
| 289 | - | |
| 290 | -// matchWords counts the words text holds and returns, in runes, where the | |
| 291 | -// earliest one found starts and where the latest one found ends. | |
| 292 | -func matchWords(text string, words []string) (score, first, last int) { | |
| 293 | - folded := textfold.Fold(text) | |
| 294 | - first = -1 | |
| 295 | - for _, w := range words { | |
| 296 | - i := strings.Index(folded, w) | |
| 297 | - if i < 0 { | |
| 298 | - continue | |
| 299 | - } | |
| 300 | - score++ | |
| 301 | - start := utf8.RuneCountInString(folded[:i]) | |
| 302 | - if first < 0 || start < first { | |
| 303 | - first = start | |
| 304 | - } | |
| 305 | - end := utf8.RuneCountInString(folded[:strings.LastIndex(folded, w)]) + utf8.RuneCountInString(w) | |
| 306 | - last = max(last, end) | |
| 307 | - } | |
| 308 | - return score, first, last | |
| 309 | -} | |
| 310 | - | |
| 311 | -// snippet is the text from rune first to rune last with some context (see | |
| 312 | -// snippetMax), whitespace collapsed to single spaces. textfold.Fold keeps one rune | |
| 313 | -// per rune, so a position in the folded text is the same position in the | |
| 314 | -// original. | |
| 315 | -func snippet(text string, first, last int) string { | |
| 316 | - runes := []rune(text) | |
| 317 | - from := max(first-snippetBefore, 0) | |
| 318 | - to := min(max(first+snippetAfter, last+snippetBefore), from+snippetMax, len(runes)) | |
| 319 | - out := strings.Join(strings.Fields(string(runes[from:to])), " ") | |
| 320 | - if from > 0 { | |
| 321 | - out = "…" + out | |
| 322 | - } | |
| 323 | - if to < len(runes) { | |
| 324 | - out += "…" | |
| 325 | - } | |
| 326 | - return out | |
| 327 | -} | |
| @@ -8,7 +8,6 @@ import ( | |||
| 8 | "time" | 8 | "time" |
| 9 | "unicode/utf8" | 9 | "unicode/utf8" |
| 10 | 10 | ||
| 11 | - "mm/internal/compact" | ||
| 12 | "mm/internal/textfold" | 11 | "mm/internal/textfold" |
| 13 | 12 | ||
| 14 | "github.com/firebase/genkit/go/ai" | 13 | "github.com/firebase/genkit/go/ai" |
| @@ -187,141 +186,3 @@ func knownTexts(msgs []*ai.Message) map[string]bool { | |||
| 187 | } | 186 | } |
| 188 | return seen | 187 | return seen |
| 189 | } | 188 | } |
| 190 | - | ||
| 191 | -// entry is one searchable message of a session, with its turn. | ||
| 192 | -type entry struct { | ||
| 193 | - role, text string | ||
| 194 | - turn int | ||
| 195 | - final bool // the answer its turn ended on | ||
| 196 | -} | ||
| 197 | - | ||
| 198 | -// entries lists the searchable messages of a session, numbered by question, | ||
| 199 | -// each turn's last answer marked final. | ||
| 200 | -func entries(msgs []*ai.Message) []entry { | ||
| 201 | - var out []entry | ||
| 202 | - turn := 0 | ||
| 203 | - for _, m := range msgs { | ||
| 204 | - role, text, ok := searchable(m) | ||
| 205 | - if !ok { | ||
| 206 | - continue | ||
| 207 | - } | ||
| 208 | - if role == "question" { | ||
| 209 | - turn++ | ||
| 210 | - } | ||
| 211 | - out = append(out, entry{role: role, text: text, turn: max(turn, 1)}) | ||
| 212 | - } | ||
| 213 | - for i := range out { | ||
| 214 | - next := i + 1 | ||
| 215 | - out[i].final = out[i].role == "answer" && (next == len(out) || out[next].role != "answer") | ||
| 216 | - } | ||
| 217 | - return out | ||
| 218 | -} | ||
| 219 | - | ||
| 220 | -// searchSession is the hits of one session. A question that matches comes | ||
| 221 | -// with its turn's final answer (Hit.Answer), which is then not a hit of its | ||
| 222 | -// own; a message seen already (the conversation in progress) is skipped. | ||
| 223 | -func searchSession(sess *Session, words []string, seen map[string]bool) []Hit { | ||
| 224 | - var hits []Hit | ||
| 225 | - list := entries(sess.Messages) | ||
| 226 | - answered := map[int]bool{} // entries folded into their question's hit | ||
| 227 | - for i, e := range list { | ||
| 228 | - if answered[i] || seen[e.role+"\x00"+e.text] { | ||
| 229 | - continue | ||
| 230 | - } | ||
| 231 | - score, first, last := matchWords(e.text, words) | ||
| 232 | - if score == 0 { | ||
| 233 | - continue | ||
| 234 | - } | ||
| 235 | - hit := Hit{Session: sess.ID, At: sess.UpdatedAt, Turn: e.turn, Role: e.role, Snippet: snippet(e.text, first, last), Score: score} | ||
| 236 | - if e.role == "question" { | ||
| 237 | - if j := finalAnswer(list, i); j >= 0 { | ||
| 238 | - answered[j] = true | ||
| 239 | - hit.Answer = answerSnippet(list[j].text, words) | ||
| 240 | - hit.Score, _, _ = matchWords(e.text+"\n"+list[j].text, words) | ||
| 241 | - } | ||
| 242 | - } | ||
| 243 | - hits = append(hits, hit) | ||
| 244 | - } | ||
| 245 | - return hits | ||
| 246 | -} | ||
| 247 | - | ||
| 248 | -// finalAnswer is the index of the answer the turn of question i ended on, | ||
| 249 | -// -1 when it has none (the turn failed, or the session stops there). | ||
| 250 | -func finalAnswer(list []entry, i int) int { | ||
| 251 | - for j := i + 1; j < len(list) && list[j].role != "question"; j++ { | ||
| 252 | - if list[j].final { | ||
| 253 | - return j | ||
| 254 | - } | ||
| 255 | - } | ||
| 256 | - return -1 | ||
| 257 | -} | ||
| 258 | - | ||
| 259 | -// answerSnippet is what a question's hit shows of its answer: the text | ||
| 260 | -// around the words when it holds some, its beginning otherwise. | ||
| 261 | -func answerSnippet(text string, words []string) string { | ||
| 262 | - score, first, last := matchWords(text, words) | ||
| 263 | - if score == 0 { | ||
| 264 | - first, last = 0, 0 | ||
| 265 | - } | ||
| 266 | - return snippet(text, first, last) | ||
| 267 | -} | ||
| 268 | - | ||
| 269 | -// searchable is the role and text of a message worth searching, and whether | ||
| 270 | -// it is one: a question as the user typed it (see question), an answer's | ||
| 271 | -// text, a /compact summary's notes — without the wrapper line mm puts before | ||
| 272 | -// them, and never the fixed acknowledgement that follows them. | ||
| 273 | -func searchable(m *ai.Message) (role, text string, ok bool) { | ||
| 274 | - switch { | ||
| 275 | - case m == nil: | ||
| 276 | - return "", "", false | ||
| 277 | - case compact.InSummaryPair(m): | ||
| 278 | - text = strings.TrimSpace(compact.SummaryNotes(m)) | ||
| 279 | - return "summary", text, compact.IsSummary(m) && text != "" | ||
| 280 | - case m.Role == ai.RoleUser: | ||
| 281 | - text, ok = question(m) | ||
| 282 | - return "question", text, ok | ||
| 283 | - case m.Role == ai.RoleModel: | ||
| 284 | - text = strings.TrimSpace(m.Text()) | ||
| 285 | - return "answer", text, text != "" | ||
| 286 | - } | ||
| 287 | - return "", "", false | ||
| 288 | -} | ||
| 289 | - | ||
| 290 | -// matchWords counts the words text holds and returns, in runes, where the | ||
| 291 | -// earliest one found starts and where the latest one found ends. | ||
| 292 | -func matchWords(text string, words []string) (score, first, last int) { | ||
| 293 | - folded := textfold.Fold(text) | ||
| 294 | - first = -1 | ||
| 295 | - for _, w := range words { | ||
| 296 | - i := strings.Index(folded, w) | ||
| 297 | - if i < 0 { | ||
| 298 | - continue | ||
| 299 | - } | ||
| 300 | - score++ | ||
| 301 | - start := utf8.RuneCountInString(folded[:i]) | ||
| 302 | - if first < 0 || start < first { | ||
| 303 | - first = start | ||
| 304 | - } | ||
| 305 | - end := utf8.RuneCountInString(folded[:strings.LastIndex(folded, w)]) + utf8.RuneCountInString(w) | ||
| 306 | - last = max(last, end) | ||
| 307 | - } | ||
| 308 | - return score, first, last | ||
| 309 | -} | ||
| 310 | - | ||
| 311 | -// snippet is the text from rune first to rune last with some context (see | ||
| 312 | -// snippetMax), whitespace collapsed to single spaces. textfold.Fold keeps one rune | ||
| 313 | -// per rune, so a position in the folded text is the same position in the | ||
| 314 | -// original. | ||
| 315 | -func snippet(text string, first, last int) string { | ||
| 316 | - runes := []rune(text) | ||
| 317 | - from := max(first-snippetBefore, 0) | ||
| 318 | - to := min(max(first+snippetAfter, last+snippetBefore), from+snippetMax, len(runes)) | ||
| 319 | - out := strings.Join(strings.Fields(string(runes[from:to])), " ") | ||
| 320 | - if from > 0 { | ||
| 321 | - out = "…" + out | ||
| 322 | - } | ||
| 323 | - if to < len(runes) { | ||
| 324 | - out += "…" | ||
| 325 | - } | ||
| 326 | - return out | ||
| 327 | -} | ||
added
internal/store/search_match.go +149 -0 | new file mode 100644 | ||
| @@ -0,0 +1,149 @@ | ||
| 1 | +package store | |
| 2 | + | |
| 3 | +import ( | |
| 4 | + "strings" | |
| 5 | + "unicode/utf8" | |
| 6 | + | |
| 7 | + "mm/internal/compact" | |
| 8 | + "mm/internal/textfold" | |
| 9 | + | |
| 10 | + "github.com/firebase/genkit/go/ai" | |
| 11 | +) | |
| 12 | + | |
| 13 | +// entry is one searchable message of a session, with its turn. | |
| 14 | +type entry struct { | |
| 15 | + role, text string | |
| 16 | + turn int | |
| 17 | + final bool // the answer its turn ended on | |
| 18 | +} | |
| 19 | + | |
| 20 | +// entries lists the searchable messages of a session, numbered by question, | |
| 21 | +// each turn's last answer marked final. | |
| 22 | +func entries(msgs []*ai.Message) []entry { | |
| 23 | + var out []entry | |
| 24 | + turn := 0 | |
| 25 | + for _, m := range msgs { | |
| 26 | + role, text, ok := searchable(m) | |
| 27 | + if !ok { | |
| 28 | + continue | |
| 29 | + } | |
| 30 | + if role == "question" { | |
| 31 | + turn++ | |
| 32 | + } | |
| 33 | + out = append(out, entry{role: role, text: text, turn: max(turn, 1)}) | |
| 34 | + } | |
| 35 | + for i := range out { | |
| 36 | + next := i + 1 | |
| 37 | + out[i].final = out[i].role == "answer" && (next == len(out) || out[next].role != "answer") | |
| 38 | + } | |
| 39 | + return out | |
| 40 | +} | |
| 41 | + | |
| 42 | +// searchSession is the hits of one session. A question that matches comes | |
| 43 | +// with its turn's final answer (Hit.Answer), which is then not a hit of its | |
| 44 | +// own; a message seen already (the conversation in progress) is skipped. | |
| 45 | +func searchSession(sess *Session, words []string, seen map[string]bool) []Hit { | |
| 46 | + var hits []Hit | |
| 47 | + list := entries(sess.Messages) | |
| 48 | + answered := map[int]bool{} // entries folded into their question's hit | |
| 49 | + for i, e := range list { | |
| 50 | + if answered[i] || seen[e.role+"\x00"+e.text] { | |
| 51 | + continue | |
| 52 | + } | |
| 53 | + score, first, last := matchWords(e.text, words) | |
| 54 | + if score == 0 { | |
| 55 | + continue | |
| 56 | + } | |
| 57 | + hit := Hit{Session: sess.ID, At: sess.UpdatedAt, Turn: e.turn, Role: e.role, Snippet: snippet(e.text, first, last), Score: score} | |
| 58 | + if e.role == "question" { | |
| 59 | + if j := finalAnswer(list, i); j >= 0 { | |
| 60 | + answered[j] = true | |
| 61 | + hit.Answer = answerSnippet(list[j].text, words) | |
| 62 | + hit.Score, _, _ = matchWords(e.text+"\n"+list[j].text, words) | |
| 63 | + } | |
| 64 | + } | |
| 65 | + hits = append(hits, hit) | |
| 66 | + } | |
| 67 | + return hits | |
| 68 | +} | |
| 69 | + | |
| 70 | +// finalAnswer is the index of the answer the turn of question i ended on, | |
| 71 | +// -1 when it has none (the turn failed, or the session stops there). | |
| 72 | +func finalAnswer(list []entry, i int) int { | |
| 73 | + for j := i + 1; j < len(list) && list[j].role != "question"; j++ { | |
| 74 | + if list[j].final { | |
| 75 | + return j | |
| 76 | + } | |
| 77 | + } | |
| 78 | + return -1 | |
| 79 | +} | |
| 80 | + | |
| 81 | +// answerSnippet is what a question's hit shows of its answer: the text | |
| 82 | +// around the words when it holds some, its beginning otherwise. | |
| 83 | +func answerSnippet(text string, words []string) string { | |
| 84 | + score, first, last := matchWords(text, words) | |
| 85 | + if score == 0 { | |
| 86 | + first, last = 0, 0 | |
| 87 | + } | |
| 88 | + return snippet(text, first, last) | |
| 89 | +} | |
| 90 | + | |
| 91 | +// searchable is the role and text of a message worth searching, and whether | |
| 92 | +// it is one: a question as the user typed it (see question), an answer's | |
| 93 | +// text, a /compact summary's notes — without the wrapper line mm puts before | |
| 94 | +// them, and never the fixed acknowledgement that follows them. | |
| 95 | +func searchable(m *ai.Message) (role, text string, ok bool) { | |
| 96 | + switch { | |
| 97 | + case m == nil: | |
| 98 | + return "", "", false | |
| 99 | + case compact.InSummaryPair(m): | |
| 100 | + text = strings.TrimSpace(compact.SummaryNotes(m)) | |
| 101 | + return "summary", text, compact.IsSummary(m) && text != "" | |
| 102 | + case m.Role == ai.RoleUser: | |
| 103 | + text, ok = question(m) | |
| 104 | + return "question", text, ok | |
| 105 | + case m.Role == ai.RoleModel: | |
| 106 | + text = strings.TrimSpace(m.Text()) | |
| 107 | + return "answer", text, text != "" | |
| 108 | + } | |
| 109 | + return "", "", false | |
| 110 | +} | |
| 111 | + | |
| 112 | +// matchWords counts the words text holds and returns, in runes, where the | |
| 113 | +// earliest one found starts and where the latest one found ends. | |
| 114 | +func matchWords(text string, words []string) (score, first, last int) { | |
| 115 | + folded := textfold.Fold(text) | |
| 116 | + first = -1 | |
| 117 | + for _, w := range words { | |
| 118 | + i := strings.Index(folded, w) | |
| 119 | + if i < 0 { | |
| 120 | + continue | |
| 121 | + } | |
| 122 | + score++ | |
| 123 | + start := utf8.RuneCountInString(folded[:i]) | |
| 124 | + if first < 0 || start < first { | |
| 125 | + first = start | |
| 126 | + } | |
| 127 | + end := utf8.RuneCountInString(folded[:strings.LastIndex(folded, w)]) + utf8.RuneCountInString(w) | |
| 128 | + last = max(last, end) | |
| 129 | + } | |
| 130 | + return score, first, last | |
| 131 | +} | |
| 132 | + | |
| 133 | +// snippet is the text from rune first to rune last with some context (see | |
| 134 | +// snippetMax), whitespace collapsed to single spaces. textfold.Fold keeps one rune | |
| 135 | +// per rune, so a position in the folded text is the same position in the | |
| 136 | +// original. | |
| 137 | +func snippet(text string, first, last int) string { | |
| 138 | + runes := []rune(text) | |
| 139 | + from := max(first-snippetBefore, 0) | |
| 140 | + to := min(max(first+snippetAfter, last+snippetBefore), from+snippetMax, len(runes)) | |
| 141 | + out := strings.Join(strings.Fields(string(runes[from:to])), " ") | |
| 142 | + if from > 0 { | |
| 143 | + out = "…" + out | |
| 144 | + } | |
| 145 | + if to < len(runes) { | |
| 146 | + out += "…" | |
| 147 | + } | |
| 148 | + return out | |
| 149 | +} | |
| new file mode 100644 | |||
| @@ -0,0 +1,149 @@ | |||
| 1 | +package store | ||
| 2 | + | ||
| 3 | +import ( | ||
| 4 | + "strings" | ||
| 5 | + "unicode/utf8" | ||
| 6 | + | ||
| 7 | + "mm/internal/compact" | ||
| 8 | + "mm/internal/textfold" | ||
| 9 | + | ||
| 10 | + "github.com/firebase/genkit/go/ai" | ||
| 11 | +) | ||
| 12 | + | ||
| 13 | +// entry is one searchable message of a session, with its turn. | ||
| 14 | +type entry struct { | ||
| 15 | + role, text string | ||
| 16 | + turn int | ||
| 17 | + final bool // the answer its turn ended on | ||
| 18 | +} | ||
| 19 | + | ||
| 20 | +// entries lists the searchable messages of a session, numbered by question, | ||
| 21 | +// each turn's last answer marked final. | ||
| 22 | +func entries(msgs []*ai.Message) []entry { | ||
| 23 | + var out []entry | ||
| 24 | + turn := 0 | ||
| 25 | + for _, m := range msgs { | ||
| 26 | + role, text, ok := searchable(m) | ||
| 27 | + if !ok { | ||
| 28 | + continue | ||
| 29 | + } | ||
| 30 | + if role == "question" { | ||
| 31 | + turn++ | ||
| 32 | + } | ||
| 33 | + out = append(out, entry{role: role, text: text, turn: max(turn, 1)}) | ||
| 34 | + } | ||
| 35 | + for i := range out { | ||
| 36 | + next := i + 1 | ||
| 37 | + out[i].final = out[i].role == "answer" && (next == len(out) || out[next].role != "answer") | ||
| 38 | + } | ||
| 39 | + return out | ||
| 40 | +} | ||
| 41 | + | ||
| 42 | +// searchSession is the hits of one session. A question that matches comes | ||
| 43 | +// with its turn's final answer (Hit.Answer), which is then not a hit of its | ||
| 44 | +// own; a message seen already (the conversation in progress) is skipped. | ||
| 45 | +func searchSession(sess *Session, words []string, seen map[string]bool) []Hit { | ||
| 46 | + var hits []Hit | ||
| 47 | + list := entries(sess.Messages) | ||
| 48 | + answered := map[int]bool{} // entries folded into their question's hit | ||
| 49 | + for i, e := range list { | ||
| 50 | + if answered[i] || seen[e.role+"\x00"+e.text] { | ||
| 51 | + continue | ||
| 52 | + } | ||
| 53 | + score, first, last := matchWords(e.text, words) | ||
| 54 | + if score == 0 { | ||
| 55 | + continue | ||
| 56 | + } | ||
| 57 | + hit := Hit{Session: sess.ID, At: sess.UpdatedAt, Turn: e.turn, Role: e.role, Snippet: snippet(e.text, first, last), Score: score} | ||
| 58 | + if e.role == "question" { | ||
| 59 | + if j := finalAnswer(list, i); j >= 0 { | ||
| 60 | + answered[j] = true | ||
| 61 | + hit.Answer = answerSnippet(list[j].text, words) | ||
| 62 | + hit.Score, _, _ = matchWords(e.text+"\n"+list[j].text, words) | ||
| 63 | + } | ||
| 64 | + } | ||
| 65 | + hits = append(hits, hit) | ||
| 66 | + } | ||
| 67 | + return hits | ||
| 68 | +} | ||
| 69 | + | ||
| 70 | +// finalAnswer is the index of the answer the turn of question i ended on, | ||
| 71 | +// -1 when it has none (the turn failed, or the session stops there). | ||
| 72 | +func finalAnswer(list []entry, i int) int { | ||
| 73 | + for j := i + 1; j < len(list) && list[j].role != "question"; j++ { | ||
| 74 | + if list[j].final { | ||
| 75 | + return j | ||
| 76 | + } | ||
| 77 | + } | ||
| 78 | + return -1 | ||
| 79 | +} | ||
| 80 | + | ||
| 81 | +// answerSnippet is what a question's hit shows of its answer: the text | ||
| 82 | +// around the words when it holds some, its beginning otherwise. | ||
| 83 | +func answerSnippet(text string, words []string) string { | ||
| 84 | + score, first, last := matchWords(text, words) | ||
| 85 | + if score == 0 { | ||
| 86 | + first, last = 0, 0 | ||
| 87 | + } | ||
| 88 | + return snippet(text, first, last) | ||
| 89 | +} | ||
| 90 | + | ||
| 91 | +// searchable is the role and text of a message worth searching, and whether | ||
| 92 | +// it is one: a question as the user typed it (see question), an answer's | ||
| 93 | +// text, a /compact summary's notes — without the wrapper line mm puts before | ||
| 94 | +// them, and never the fixed acknowledgement that follows them. | ||
| 95 | +func searchable(m *ai.Message) (role, text string, ok bool) { | ||
| 96 | + switch { | ||
| 97 | + case m == nil: | ||
| 98 | + return "", "", false | ||
| 99 | + case compact.InSummaryPair(m): | ||
| 100 | + text = strings.TrimSpace(compact.SummaryNotes(m)) | ||
| 101 | + return "summary", text, compact.IsSummary(m) && text != "" | ||
| 102 | + case m.Role == ai.RoleUser: | ||
| 103 | + text, ok = question(m) | ||
| 104 | + return "question", text, ok | ||
| 105 | + case m.Role == ai.RoleModel: | ||
| 106 | + text = strings.TrimSpace(m.Text()) | ||
| 107 | + return "answer", text, text != "" | ||
| 108 | + } | ||
| 109 | + return "", "", false | ||
| 110 | +} | ||
| 111 | + | ||
| 112 | +// matchWords counts the words text holds and returns, in runes, where the | ||
| 113 | +// earliest one found starts and where the latest one found ends. | ||
| 114 | +func matchWords(text string, words []string) (score, first, last int) { | ||
| 115 | + folded := textfold.Fold(text) | ||
| 116 | + first = -1 | ||
| 117 | + for _, w := range words { | ||
| 118 | + i := strings.Index(folded, w) | ||
| 119 | + if i < 0 { | ||
| 120 | + continue | ||
| 121 | + } | ||
| 122 | + score++ | ||
| 123 | + start := utf8.RuneCountInString(folded[:i]) | ||
| 124 | + if first < 0 || start < first { | ||
| 125 | + first = start | ||
| 126 | + } | ||
| 127 | + end := utf8.RuneCountInString(folded[:strings.LastIndex(folded, w)]) + utf8.RuneCountInString(w) | ||
| 128 | + last = max(last, end) | ||
| 129 | + } | ||
| 130 | + return score, first, last | ||
| 131 | +} | ||
| 132 | + | ||
| 133 | +// snippet is the text from rune first to rune last with some context (see | ||
| 134 | +// snippetMax), whitespace collapsed to single spaces. textfold.Fold keeps one rune | ||
| 135 | +// per rune, so a position in the folded text is the same position in the | ||
| 136 | +// original. | ||
| 137 | +func snippet(text string, first, last int) string { | ||
| 138 | + runes := []rune(text) | ||
| 139 | + from := max(first-snippetBefore, 0) | ||
| 140 | + to := min(max(first+snippetAfter, last+snippetBefore), from+snippetMax, len(runes)) | ||
| 141 | + out := strings.Join(strings.Fields(string(runes[from:to])), " ") | ||
| 142 | + if from > 0 { | ||
| 143 | + out = "…" + out | ||
| 144 | + } | ||
| 145 | + if to < len(runes) { | ||
| 146 | + out += "…" | ||
| 147 | + } | ||
| 148 | + return out | ||
| 149 | +} | ||