* refactor(timeparsing): export IsCompactDuration The query lexer keeps its own copy of the compact-duration unit set, and that copy has drifted from the grammar: it accepts the uppercase units H D W M Y, which ParseCompactDuration rejects. Export the classifier so the lexer can ask timeparsing instead of keeping a copy, and pin that it agrees with ParseCompactDuration on every row, uppercase spellings included. AC: AC-1 Agent-Signature: claude-code-claude-opus-5-5-unknown-reasoning on behalf of Julian Knutsen Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(query): classify durations with timeparsing.IsCompactDuration The query lexer kept its own copy of the compact-duration unit set: isDurationSuffix for single runes and durationWords for "min". The copy had drifted. It accepted H D W M Y, which the case-sensitive grammar rejects, so "created>30M" reached the evaluator as a duration and failed with the internal error `not a compact duration: "-30M"`, quoting a value the user never typed. Classify the whole digit-led lexeme with timeparsing.IsCompactDuration and delete the copy (isDurationSuffix, durationWords, acceptDurationWord). Uppercase units now lex as identifiers and fail as an unparseable time; every lowercase input lexes as before. A unit added to compactDurationRe now reaches the lexer with no edit here: with "sec" added to the regex alone, TestCompactDurationGrammarReachesQueryPlane fails on the old lexer and passes on this one. Retire that test's text naming the deleted copy. AC: AC-2 Agent-Signature: claude-code-claude-opus-5-5-unknown-reasoning on behalf of Julian Knutsen Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * test(query): pin that uppercase duration units lex as identifiers "updated>30M", "updated>30H" and "label=30D" lex the value as one TokenIdent with the text as typed; "updated>30m" and "updated>+30d" still lex as TokenDuration. On the base lexer the three uppercase rows fail (typed DURATION). AC: AC-3 Agent-Signature: claude-code-claude-opus-5-5-unknown-reasoning on behalf of Julian Knutsen Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * test(query): pin the error for an uppercase duration unit created>, updated<, closed>= and started<= compared to 30M, 30D, 30W, 30Y, 30H or 1H, alone or in "... OR status=open", fail with `cannot parse time expression: "<value as typed>"`, never with the internal `not a compact duration` error and never quoting the negated "-<value>". 30MIN and 30Min, which always took this path, are the controls. On the base lexer 30 of the 40 subtests fail; the 10 controls pass. AC: AC-4 Agent-Signature: claude-code-claude-opus-5-5-unknown-reasoning on behalf of Julian Knutsen Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * test(query): bind the lexer's duration grammar to timeparsing both ways TestCompactDurationGrammarReachesQueryPlane asserted only that every suffix ParseCompactDuration accepts lexes as a duration. Assert the reverse too: a suffix it rejects must not lex as TokenDuration, or the evaluator fails on it with ParseCompactDuration's internal error about a negated value. Widen the candidates to every one- and two-letter ASCII suffix in either case, every three-letter lowercase one, and every case spelling of an accepted three-letter unit. On the base lexer the reverse sweep fails on exactly [D H M W Y]. A mutant that case-folds before classifying fails it on those plus the seven other spellings of "min". AC: AC-5 Agent-Signature: claude-code-claude-opus-5-5-unknown-reasoning on behalf of Julian Knutsen Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * test(query): pin that a signed uppercase unit stops at the parser "created>+30M" and "created>-30M" fail Parse and EvaluateAt with `unexpected token "M" at position 11 (expected end of query)`, as "created>+30x" already does: a signed digit run has no identifier fallback, so "+30" is a number and "M" a stray token. On the base lexer both parsed as a duration and failed in the evaluator with `not a compact duration: "-30M"` and `"--30M"`; the +30x control passes on both. AC: AC-6 Agent-Signature: claude-code-claude-opus-5-5-unknown-reasoning on behalf of Julian Knutsen Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * test(query): pin the values rejecting uppercase units leaves alone At a fixed now, created>+30d is still 30 days ago, updated>5pm still 17:00 that day, and label=30M / title=30M still filter the literal "30M". TestQueryMinutesUnitResolvesAgo already pins created>30m (30 months ago) and created>30min (30 minutes ago). These rows pass on the base lexer as well, which is the point; a lexer mutant that stops typing signed lexemes as durations fails the +30d row. AC: AC-7 Agent-Signature: claude-code-claude-opus-5-5-unknown-reasoning on behalf of Julian Knutsen Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Eddie the Engineer <julianknutsen@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
192 lines
6 KiB
Go
192 lines
6 KiB
Go
// Package timeparsing provides layered time parsing for relative date/time expressions.
|
|
//
|
|
// The parsing follows a layered architecture (ADR-001):
|
|
// 1. Compact duration (+6h, -1d, +2w)
|
|
// 2. Natural language (tomorrow, next monday)
|
|
// 3. Absolute timestamp (RFC3339, date-only)
|
|
package timeparsing
|
|
|
|
import (
|
|
"fmt"
|
|
"regexp"
|
|
"strconv"
|
|
"time"
|
|
|
|
"github.com/olebedev/when"
|
|
"github.com/olebedev/when/rules/common"
|
|
"github.com/olebedev/when/rules/en"
|
|
)
|
|
|
|
// 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+)(min|[hdwmy])
|
|
//
|
|
// Units:
|
|
// - min = minutes
|
|
// - h = hours
|
|
// - d = days
|
|
// - w = weeks
|
|
// - 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
|
|
// - "3m" -> now + 3 months (no sign = positive)
|
|
// - "1y" -> now + 1 year
|
|
//
|
|
// Returns error if input doesn't match the compact duration pattern.
|
|
func ParseCompactDuration(s string, now time.Time) (time.Time, error) {
|
|
matches := compactDurationRe.FindStringSubmatch(s)
|
|
if matches == nil {
|
|
return time.Time{}, fmt.Errorf("not a compact duration: %q", s)
|
|
}
|
|
|
|
sign := matches[1]
|
|
amountStr := matches[2]
|
|
unit := matches[3]
|
|
|
|
amount, err := strconv.Atoi(amountStr)
|
|
if err != nil {
|
|
// Should not happen given regex ensures digits, but handle gracefully
|
|
return time.Time{}, fmt.Errorf("invalid duration amount: %q", amountStr)
|
|
}
|
|
|
|
// Apply sign (default positive)
|
|
if sign == "-" {
|
|
amount = -amount
|
|
}
|
|
|
|
return applyDuration(now, amount, unit), nil
|
|
}
|
|
|
|
// 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":
|
|
return base.AddDate(0, 0, amount)
|
|
case "w":
|
|
return base.AddDate(0, 0, amount*7)
|
|
case "m":
|
|
return base.AddDate(0, amount, 0)
|
|
case "y":
|
|
return base.AddDate(amount, 0, 0)
|
|
default:
|
|
// Should not happen given regex, but return base unchanged
|
|
return base
|
|
}
|
|
}
|
|
|
|
// IsCompactDuration reports whether s is in the compact duration syntax that
|
|
// ParseCompactDuration parses; only an amount too large for an int matches it
|
|
// and still fails to parse. Callers that classify a compact duration without
|
|
// parsing it (the query lexer) use this instead of keeping their own copy of
|
|
// the unit set, so a unit added to compactDurationRe reaches them with no edit
|
|
// of theirs.
|
|
func IsCompactDuration(s string) bool {
|
|
return compactDurationRe.MatchString(s)
|
|
}
|
|
|
|
// nlpParser is the singleton natural language parser (olebedev/when).
|
|
// Initialized lazily on first use.
|
|
var nlpParser *when.Parser
|
|
|
|
// getNLPParser returns the singleton NLP parser, initializing it if needed.
|
|
func getNLPParser() *when.Parser {
|
|
if nlpParser == nil {
|
|
nlpParser = when.New(nil)
|
|
nlpParser.Add(en.All...)
|
|
nlpParser.Add(common.All...)
|
|
}
|
|
return nlpParser
|
|
}
|
|
|
|
// parseNaturalLanguage parses natural language time expressions using olebedev/when.
|
|
//
|
|
// Examples:
|
|
// - "tomorrow" -> tomorrow at current time
|
|
// - "next monday" -> next Monday at current time
|
|
// - "next monday at 9am" -> next Monday at 9:00
|
|
// - "in 3 days" -> now + 3 days
|
|
// - "3 days ago" -> now - 3 days
|
|
//
|
|
// Known Issues (olebedev/when):
|
|
// - Month name "September" may not parse correctly in some contexts.
|
|
// Workaround: Use date format "2025-09-15" instead of "September 15" or "Sep 15".
|
|
// This is a known issue in the olebedev/when library.
|
|
//
|
|
// Returns error if input cannot be parsed as natural language.
|
|
func parseNaturalLanguage(s string, now time.Time) (time.Time, error) {
|
|
parser := getNLPParser()
|
|
result, err := parser.Parse(s, now)
|
|
if err != nil {
|
|
return time.Time{}, fmt.Errorf("NLP parse error: %w", err)
|
|
}
|
|
if result == nil {
|
|
return time.Time{}, fmt.Errorf("not a natural language time expression: %q", s)
|
|
}
|
|
return result.Time, nil
|
|
}
|
|
|
|
// dateOnlyRe matches date-only format YYYY-MM-DD to avoid NLP misinterpretation.
|
|
var dateOnlyRe = regexp.MustCompile(`^\d{4}-\d{2}-\d{2}$`)
|
|
|
|
// ParseRelativeTime parses a time expression using the layered architecture (ADR-001).
|
|
//
|
|
// Parsing order:
|
|
// 1. Compact duration (+6h, -1d, +2w)
|
|
// 2. Absolute formats (date-only, RFC3339) - checked before NLP to avoid misinterpretation
|
|
// 3. Natural language (tomorrow, next monday)
|
|
//
|
|
// Timezone-less inputs are interpreted in now's location. Returns the parsed
|
|
// time in UTC or an error if no layer could parse the input.
|
|
func ParseRelativeTime(s string, now time.Time) (time.Time, error) {
|
|
location := now.Location()
|
|
|
|
// Layer 1: Compact duration
|
|
if t, err := ParseCompactDuration(s, now); err == nil {
|
|
return t.UTC(), nil
|
|
}
|
|
|
|
// Layer 2: Absolute formats (must be checked before NLP to avoid misinterpretation)
|
|
// NLP parser can incorrectly parse "2025-02-01" as a time, so we check date formats first.
|
|
|
|
// Try date-only format (YYYY-MM-DD)
|
|
if dateOnlyRe.MatchString(s) {
|
|
if t, err := time.ParseInLocation("2006-01-02", s, location); err == nil {
|
|
return t.UTC(), nil
|
|
}
|
|
}
|
|
|
|
// Try RFC3339 format (2025-01-15T10:00:00Z)
|
|
if t, err := time.Parse(time.RFC3339, s); err == nil {
|
|
return t.UTC(), nil
|
|
}
|
|
|
|
// Try ISO 8601 datetime without timezone (2025-01-15T10:00:00)
|
|
if t, err := time.ParseInLocation("2006-01-02T15:04:05", s, location); err == nil {
|
|
return t.UTC(), nil
|
|
}
|
|
|
|
// Try datetime with space (2025-01-15 10:00:00)
|
|
if t, err := time.ParseInLocation("2006-01-02 15:04:05", s, location); err == nil {
|
|
return t.UTC(), nil
|
|
}
|
|
|
|
// Layer 3: Natural language (after absolute formats to avoid misinterpretation)
|
|
if t, err := parseNaturalLanguage(s, now); err == nil {
|
|
return t.UTC(), nil
|
|
}
|
|
|
|
return time.Time{}, fmt.Errorf("cannot parse time expression: %q (examples: +30min, +6h, tomorrow, 2025-01-15)", s)
|
|
}
|