From eb1689cb9d1be0452b8d4236cb8c15e4d94a1d3d Mon Sep 17 00:00:00 2001 From: Vishnu J Date: Sat, 26 Sep 2026 18:51:37 -0700 Subject: [PATCH] fix(timeparsing): add min minutes unit to compact duration parser (#6609) (#6629) * fix(timeparsing): add unambiguous "min" minute unit to compact durations --defer/--due use the compact duration parser, whose smallest unit was one hour. "+30m" silently parsed as 30 months (rc 0, no warning), so a row meant to return in half an hour became ready again years later, while "+30min" was rejected outright. Add "min" as a new minute spelling alongside h/d/w/m/y. Bare "m" keeps meaning months, so existing callers are unchanged; redefining or refusing bare "m" is a semantics change left for maintainer sign-off. Fixes #6609 Co-Authored-By: Claude Sonnet 5 * fix(query): resolve the "min" minutes unit as "N ago" in bd query The widened compact-duration grammar reached the `bd query` plane through the evaluator's ungated fallback arm: `isDurationSuffix` classifies a single rune, so `30min` lexed as TokenIdent, skipped `parseDurationAgo`, and resolved through `ParseRelativeTime` as 30 minutes in the *future* -- the opposite direction from `created > 30m` (30 months ago) and from the command's own documented contract at cmd/bd/query.go:66. Recognize multi-rune duration suffixes in `readNumberOrDuration` so `30min` lexes as TokenDuration and resolves to 30 minutes ago. Plural, uppercase, and identifier-continuation spellings (`30mins`, `30MIN`, `30min-window`) keep their existing identifier classification. Maintainer review fixups for PR #6629, review iteration 1: - pin the query-plane semantics with EvaluateAt tests against a fixed now - make the months assertion in TestParseTimeFlag_MinutesVsMonths two-sided, so it can no longer stay green if "m" regressed to years - mention +30min in the ParseRelativeTime error examples Maintainer review fixups for PR #6629, review iteration 2 (non-gating): - bind the query lexer's unit set to the shared timeparsing grammar with a cross-package test. ParseCompactDuration is the oracle, so a unit added to that grammar but missed in durationWords/isDurationSuffix now fails loudly instead of silently resolving as a future offset -- the class this fixup previously closed only for "min". Verified by adding "sec" to the shared pattern alone: the test discovers and fails it with no test edit. - pin that a duration token on a non-time field (label=1min) is still filtered as a literal string, since parseTimeValue is the only consumer of ValueType. - list min/m/y in the bd query duration help, so "m" reads as months right next to "min". The generated CLI docs are release-pinned (docs/cli-docs.pin v1.2.2, built from the tag rather than the working tree), so they are deliberately not regenerated here; ./scripts/generate-cli-docs.sh --check reports them fresh. Co-Authored-By: Claude Opus 5 --------- Co-authored-by: Claude Sonnet 5 Co-authored-by: Julian Knutsen --- cmd/bd/list_test.go | 24 ++++ cmd/bd/query.go | 4 +- internal/query/lexer.go | 45 +++++++ internal/query/query_test.go | 166 ++++++++++++++++++++++++++ internal/timeparsing/duration_test.go | 34 ++++++ internal/timeparsing/parser.go | 16 ++- 6 files changed, 282 insertions(+), 7 deletions(-) diff --git a/cmd/bd/list_test.go b/cmd/bd/list_test.go index 0e022abac..2aa3dcd64 100644 --- a/cmd/bd/list_test.go +++ b/cmd/bd/list_test.go @@ -1322,6 +1322,7 @@ func TestParseTimeFlag(t *testing.T) { {"Compact days", "+1d", false}, {"Compact weeks", "+2w", false}, {"Compact negative", "-3d", false}, + {"Compact minutes", "+30min", false}, // Natural language (GH#820) {"Natural tomorrow", "tomorrow", false}, {"Natural next monday", "next monday", false}, @@ -1340,6 +1341,29 @@ func TestParseTimeFlag(t *testing.T) { } } +// TestParseTimeFlag_MinutesVsMonths guards GH#6609: "min" is minutes, bare "m" stays months. +func TestParseTimeFlag_MinutesVsMonths(t *testing.T) { + t.Parallel() + minutes, err := parseTimeFlag("+30min") + if err != nil { + t.Fatalf("parseTimeFlag(+30min) error: %v", err) + } + if d := time.Until(minutes); d < 29*time.Minute || d > 31*time.Minute { + t.Errorf("+30min resolved %v from now, want ~30m", d) + } + months, err := parseTimeFlag("+30m") + if err != nil { + t.Fatalf("parseTimeFlag(+30m) error: %v", err) + } + // Bound the months arm on both sides against a computed expectation: a + // one-sided "more than a year out" check stays green if "m" regressed to + // years or decades, which is the exact discrimination this test exists for. + wantMonths := time.Now().AddDate(0, 30, 0) + if d := months.Sub(wantMonths); d < -time.Minute || d > time.Minute { + t.Errorf("+30m resolved %v, want ~%v (30 months out)", months, wantMonths) + } +} + // TestListTimeBasedFilters tests the time-based scheduling filters (GH#820) func TestListTimeBasedFilters(t *testing.T) { t.Parallel() diff --git a/cmd/bd/query.go b/cmd/bd/query.go index 7151ba257..7bfc3313f 100644 --- a/cmd/bd/query.go +++ b/cmd/bd/query.go @@ -63,7 +63,9 @@ Supported fields: mol_type Molecule type (swarm, patrol, work) Date values: - Relative durations: 7d (7 days ago), 24h (24 hours ago), 2w (2 weeks ago) + Relative durations: 30min (30 minutes ago), 24h (24 hours ago), + 7d (7 days ago), 2w (2 weeks ago), + 6m (6 months ago), 1y (1 year ago) Absolute dates: 2025-01-15, 2025-01-15T10:00:00Z Natural language: tomorrow, "next monday", "in 3 days" diff --git a/internal/query/lexer.go b/internal/query/lexer.go index f6f92d333..fb5540b42 100644 --- a/internal/query/lexer.go +++ b/internal/query/lexer.go @@ -271,6 +271,19 @@ func (l *Lexer) readNumberOrDuration(startPos int) (Token, error) { return Token{Type: TokenDuration, Value: sb.String(), Pos: startPos}, nil } + // Multi-rune duration suffixes ("min") cannot be recognized above: + // isDurationSuffix classifies a single rune, and the stands-alone guard + // bails on the letters that follow it. Left as an identifier, "30min" + // would skip the evaluator's TokenDuration arm and resolve through + // timeparsing.ParseRelativeTime as a *future* offset — the opposite + // direction from the "N ago" contract 7d, 24h and 30m all honor. + if r != 0 { + if word, ok := l.acceptDurationWord(); ok { + sb.WriteString(word) + return Token{Type: TokenDuration, Value: sb.String(), Pos: startPos}, nil + } + } + // Identifier-continuation fallback: an unsigned digit-led run that // butts against more identifier characters is an identifier, not a // number. Restart the lex at the original position and read it as an @@ -358,3 +371,35 @@ func isDurationSuffix(r rune) bool { return false } } + +// durationWords are the multi-rune duration suffixes of the shared +// compact-duration grammar (internal/timeparsing). "min" is spelled out there +// precisely because "m" means months, so the query plane has to match the whole +// word to classify it as a duration. Lowercase only, matching that grammar. +var durationWords = []string{"min"} + +// acceptDurationWord reports whether the input spells a multi-rune duration +// suffix, starting at the rune the caller most recently read with next() and +// standing alone. On a match it consumes the suffix and returns it; otherwise +// the lexer position is left untouched. +func (l *Lexer) acceptDurationWord() (string, bool) { + if l.width == 0 { + return "", false + } + start := l.pos - l.width + for _, word := range durationWords { + if !strings.HasPrefix(l.input[start:], word) { + continue + } + end := start + len(word) + // More identifier characters follow ("30mins", "30minutes", + // "30min-sla"), so this is an identifier, not a duration. + if end < len(l.input) && isIdentChar(rune(l.input[end])) { + continue + } + l.pos = end + l.width = 1 + return word, true + } + return "", false +} diff --git a/internal/query/query_test.go b/internal/query/query_test.go index d8223f62f..94b3c8660 100644 --- a/internal/query/query_test.go +++ b/internal/query/query_test.go @@ -5,6 +5,7 @@ import ( "time" "github.com/steveyegge/beads/internal/storage" + "github.com/steveyegge/beads/internal/timeparsing" "github.com/steveyegge/beads/internal/types" ) @@ -146,6 +147,36 @@ func TestLexer(t *testing.T) { expected: []TokenType{TokenIdent, TokenGreater, TokenDuration, TokenAnd, TokenIdent, TokenEquals, TokenIdent, TokenEOF}, values: []string{"updated", ">", "30d", "AND", "status", "=", "open", ""}, }, + { + name: "multi-rune minutes suffix is a duration", + input: "updated>30min", + expected: []TokenType{TokenIdent, TokenGreater, TokenDuration, TokenEOF}, + values: []string{"updated", ">", "30min", ""}, + }, + { + name: "multi-rune minutes suffix in a compound expression", + input: "updated>30min AND status=open", + expected: []TokenType{TokenIdent, TokenGreater, TokenDuration, TokenAnd, TokenIdent, TokenEquals, TokenIdent, TokenEOF}, + values: []string{"updated", ">", "30min", "AND", "status", "=", "open", ""}, + }, + { + name: "plural minutes spelling stays an identifier", + input: "label=30mins", + expected: []TokenType{TokenIdent, TokenEquals, TokenIdent, TokenEOF}, + values: []string{"label", "=", "30mins", ""}, + }, + { + name: "minutes suffix continuing into an identifier stays an identifier", + input: "label=30min-window", + expected: []TokenType{TokenIdent, TokenEquals, TokenIdent, TokenEOF}, + values: []string{"label", "=", "30min-window", ""}, + }, + { + name: "uppercase minutes spelling stays an identifier", + input: "label=30MIN", + expected: []TokenType{TokenIdent, TokenEquals, TokenIdent, TokenEOF}, + values: []string{"label", "=", "30MIN", ""}, + }, } for _, tt := range tests { @@ -681,6 +712,141 @@ func TestDurationParsing(t *testing.T) { } } +// TestQueryMinutesUnitResolvesAgo pins the query-plane semantics of the "min" +// minutes unit in the shared compact-duration grammar: like every other duration +// token here it resolves to N *ago*, per the documented contract in +// `bd query --help` ("7d (7 days ago)"). The fixed now makes the exact instant +// assertable, so classifying "30min" as an identifier again — which routes it to +// the future-relative ParseRelativeTime fallback — fails this test. +func TestQueryMinutesUnitResolvesAgo(t *testing.T) { + now := time.Date(2025, 2, 4, 12, 0, 0, 0, time.UTC) + + tests := []struct { + name string + query string + want time.Time + bound func(*types.IssueFilter) *time.Time + }{ + { + name: "created>30min is 30 minutes ago", + query: "created>30min", + want: now.Add(-30 * time.Minute), + bound: func(f *types.IssueFilter) *time.Time { return f.CreatedAfter }, + }, + { + name: "updated<90min is 90 minutes ago", + query: "updated<90min", + want: now.Add(-90 * time.Minute), + bound: func(f *types.IssueFilter) *time.Time { return f.UpdatedBefore }, + }, + { + name: "bare m still means months, not minutes", + query: "created>30m", + want: now.AddDate(0, -30, 0), + bound: func(f *types.IssueFilter) *time.Time { return f.CreatedAfter }, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + result, err := EvaluateAt(tt.query, now) + if err != nil { + t.Fatalf("EvaluateAt(%q) error = %v", tt.query, err) + } + got := tt.bound(&result.Filter) + if got == nil { + t.Fatalf("EvaluateAt(%q) left the time bound unset, filter=%+v", tt.query, result.Filter) + } + if !got.Equal(tt.want) { + t.Errorf("EvaluateAt(%q) = %s, want %s", tt.query, got.Format(time.RFC3339), tt.want.Format(time.RFC3339)) + } + }) + } +} + +// TestCompactDurationGrammarReachesQueryPlane binds this package's duration +// grammar to the shared one in internal/timeparsing, which owns it. The lexer +// keeps a second copy of the unit set — isDurationSuffix for single runes, +// durationWords for whole words — and nothing outside this test holds the two +// in sync. A unit added to the shared grammar but missed here lexes as +// TokenIdent, skips the evaluator's TokenDuration arm, and resolves through +// ParseRelativeTime as a *future* offset: the "30min meant 30 minutes from now" +// inversion this PR fixed, reproduced silently for the next unit. +// +// The shared pattern is unexported, so ParseCompactDuration is the oracle: +// whatever suffix it accepts must lex as a duration here. Candidates are +// exhaustive over lowercase ASCII up to three runes, so plausible future +// spellings ("sec", "hr", "mo", "yr") are covered alongside today's six. +// +// Only this direction is asserted. The reverse — everything the lexer accepts +// being valid in the shared grammar — is already false at base: isDurationSuffix +// also takes "H D W M Y", which the case-sensitive pattern rejects, so +// "created>30M" lexes as a duration and then fails in ParseCompactDuration. +// That asymmetry predates this PR and is not what this test is for. +func TestCompactDurationGrammarReachesQueryPlane(t *testing.T) { + now := time.Date(2025, 2, 4, 12, 0, 0, 0, time.UTC) + + const letters = "abcdefghijklmnopqrstuvwxyz" + var candidates []string + for _, a := range letters { + candidates = append(candidates, string(a)) + for _, b := range letters { + candidates = append(candidates, string(a)+string(b)) + for _, c := range letters { + candidates = append(candidates, string(a)+string(b)+string(c)) + } + } + } + + var accepted []string + isAccepted := make(map[string]bool) + for _, unit := range candidates { + if _, err := timeparsing.ParseCompactDuration("1"+unit, now); err != nil { + continue + } + accepted = append(accepted, unit) + isAccepted[unit] = true + } + + // Guard the oracle itself: if ParseCompactDuration stopped accepting the + // units the grammar documents, every assertion below would pass vacuously. + for _, unit := range []string{"min", "h", "d", "w", "m", "y"} { + if !isAccepted[unit] { + t.Fatalf("oracle lost unit %q: timeparsing no longer accepts %q", unit, "1"+unit) + } + } + + for _, unit := range accepted { + t.Run(unit, func(t *testing.T) { + value := "1" + unit + + tokens, err := NewLexer("updated>" + value).Tokenize() + if err != nil { + t.Fatalf("Tokenize(updated>%s) error = %v", value, err) + } + if len(tokens) < 3 { + t.Fatalf("Tokenize(updated>%s) produced %d tokens, want at least 3", value, len(tokens)) + } + if tokens[2].Type != TokenDuration || tokens[2].Value != value { + t.Errorf("timeparsing accepts %q but the query lexer typed it %v(%q), want %v(%q); "+ + "add the unit to durationWords/isDurationSuffix or it resolves as a future offset", + value, tokens[2].Type, tokens[2].Value, TokenDuration, value) + } + + // Widening the duration grammar must not change non-time fields: + // parseTimeValue is the only consumer of ValueType, so a duration + // token on label= is still filtered as the literal string. + result, err := EvaluateAt("label="+value, now) + if err != nil { + t.Fatalf("EvaluateAt(label=%s) error = %v", value, err) + } + if len(result.Filter.Labels) != 1 || result.Filter.Labels[0] != value { + t.Errorf("EvaluateAt(label=%s) Labels = %v, want [%q]", value, result.Filter.Labels, value) + } + }) + } +} + func TestEvaluatorMetadataQueries(t *testing.T) { now := time.Date(2025, 2, 4, 12, 0, 0, 0, time.UTC) diff --git a/internal/timeparsing/duration_test.go b/internal/timeparsing/duration_test.go index e6cead242..34e7ff059 100644 --- a/internal/timeparsing/duration_test.go +++ b/internal/timeparsing/duration_test.go @@ -42,6 +42,28 @@ func TestParseCompactDuration(t *testing.T) { want: time.Date(2026, 6, 15, 12, 0, 0, 0, time.UTC), }, + // "min" is the unambiguous minute unit; bare "m" stays months (GH #6609) + { + name: "+30min adds 30 minutes", + input: "+30min", + want: time.Date(2025, 6, 15, 12, 30, 0, 0, time.UTC), + }, + { + name: "-15min subtracts 15 minutes", + input: "-15min", + want: time.Date(2025, 6, 15, 11, 45, 0, 0, time.UTC), + }, + { + name: "90min without sign adds 90 minutes", + input: "90min", + want: time.Date(2025, 6, 15, 13, 30, 0, 0, time.UTC), + }, + { + name: "+30m still adds 30 months", + input: "+30m", + want: time.Date(2027, 12, 15, 12, 0, 0, 0, time.UTC), + }, + // Valid negative durations (past) { name: "-1d subtracts 1 day", @@ -99,6 +121,16 @@ func TestParseCompactDuration(t *testing.T) { input: "++1d", wantErr: true, }, + { + name: "30mins (plural) is invalid", + input: "+30mins", + wantErr: true, + }, + { + name: "30minutes is invalid", + input: "+30minutes", + wantErr: true, + }, { name: "1x (unknown unit) is invalid", input: "1x", @@ -161,6 +193,8 @@ func TestIsCompactDuration(t *testing.T) { {"3m", true}, {"1y", true}, {"+24h", true}, + {"+30min", true}, + {"+30mins", false}, {"", false}, {"tomorrow", false}, {"2025-01-15", false}, diff --git a/internal/timeparsing/parser.go b/internal/timeparsing/parser.go index feced0b38..8d495385c 100644 --- a/internal/timeparsing/parser.go +++ b/internal/timeparsing/parser.go @@ -17,22 +17,24 @@ import ( "github.com/olebedev/when/rules/en" ) -// compactDurationRe matches compact duration patterns: [+-]?(\d+)([hdwmy]) -// Examples: +6h, -1d, +2w, 3m, 1y -var compactDurationRe = regexp.MustCompile(`^([+-]?)(\d+)([hdwmy])$`) +// compactDurationRe matches compact duration patterns: [+-]?(\d+)(min|[hdwmy]) +// Examples: +6h, -1d, +2w, 3m, 1y, +30min +var compactDurationRe = regexp.MustCompile(`^([+-]?)(\d+)(min|[hdwmy])$`) // ParseCompactDuration parses compact duration syntax and returns the resulting time. // -// Format: [+-]?(\d+)([hdwmy]) +// Format: [+-]?(\d+)(min|[hdwmy]) // // Units: +// - min = minutes // - h = hours // - d = days // - w = weeks -// - m = months +// - m = months (NOT minutes; use "min" for minutes) // - y = years // // Examples: +// - "+30min" -> now + 30 minutes // - "+6h" -> now + 6 hours // - "-1d" -> now - 1 day // - "+2w" -> now + 2 weeks @@ -67,6 +69,8 @@ func ParseCompactDuration(s string, now time.Time) (time.Time, error) { // applyDuration applies the given amount and unit to the base time. func applyDuration(base time.Time, amount int, unit string) time.Time { switch unit { + case "min": + return base.Add(time.Duration(amount) * time.Minute) case "h": return base.Add(time.Duration(amount) * time.Hour) case "d": @@ -179,5 +183,5 @@ func ParseRelativeTime(s string, now time.Time) (time.Time, error) { return t.UTC(), nil } - return time.Time{}, fmt.Errorf("cannot parse time expression: %q (examples: +6h, tomorrow, 2025-01-15)", s) + return time.Time{}, fmt.Errorf("cannot parse time expression: %q (examples: +30min, +6h, tomorrow, 2025-01-15)", s) }