pikuri-thunderbird 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -8,18 +8,17 @@ module Pikuri
8
8
  # (+cache.sqlite+ for cached network/CalDAV calendars, +local.sqlite+ for
9
9
  # local "storage" calendars). Event fields are *normalized columns*, not
10
10
  # opaque ICS, so basic reads are a plain +SELECT+ — no ICS parser for the
11
- # common case. The one exception is the guest list ({#attendees}), which
12
- # Thunderbird keeps as raw +ATTENDEE+/+ORGANIZER+ content lines.
11
+ # common case. The exceptions are the guest list ({#attendees}) and a
12
+ # series' recurrence ({Recurrence}), which Thunderbird keeps as raw
13
+ # content lines.
13
14
  #
14
15
  # cal = Calendar.new(calendar_dbs: profile.calendar_dbs, cache_dir: dir)
15
- # cal.available? # any calendar store on disk?
16
16
  # cal.event_count # 0 → nothing cached (prompt the user to enable Offline Support)
17
17
  # cal.search(query: 'standup', limit: 10)
18
18
  # cal.read(event_id: hit[:event_id])
19
19
  #
20
- # Like {Gloda}, every query runs against {DatabaseSnapshot} copies (opened
21
- # +?immutable=1+, so a WAL store reads as-of-last-checkpoint), refreshed
22
- # when the source generation moves.
20
+ # Like {Gloda}, every query runs against {DatabaseSnapshot} copies,
21
+ # refreshed when the source generation moves.
23
22
  #
24
23
  # == Time & all-day encoding
25
24
  #
@@ -32,6 +31,10 @@ module Pikuri
32
31
  # UTC {Time}s + the tz string + an +all_day+ flag; presentation (local
33
32
  # display, all-day date rendering) is the tool's job.
34
33
  #
34
+ # An all-day start is *floating*: its date's midnight labelled UTC, not an
35
+ # instant. So a date bound or "today", a machine-local instant, dates a
36
+ # timed event as is and an all-day one by its wall clock ({#floating}).
37
+ #
35
38
  # {#close} closes the snapshot connections.
36
39
  #
37
40
  # == Sharing
@@ -49,7 +52,8 @@ module Pikuri
49
52
 
50
53
  # @return [Integer] +HAS_RECURRENCE+ bit in +cal_events.flags+ — set on
51
54
  # the master row of any event with an RRULE/RDATE (Thunderbird's
52
- # +CAL_ITEM_FLAG+). Airtight for the master, same as {ALL_DAY_FLAG}.
55
+ # +CAL_ITEM_FLAG+, comm-central +calStorageHelpers.sys.mjs+). Airtight
56
+ # for the master, same as {ALL_DAY_FLAG}.
53
57
  RECURRENCE_FLAG = 16
54
58
 
55
59
  # @param calendar_dbs [Array<String>] existing calendar store paths
@@ -62,15 +66,9 @@ module Pikuri
62
66
  [src, DatabaseSnapshot.new(source: src, dir: File.join(cache_dir, File.basename(src, '.sqlite')))]
63
67
  end
64
68
  @conns = {}
65
- @generations = {}
66
69
  @lock = Mutex.new
67
70
  end
68
71
 
69
- # @return [Boolean] whether any calendar store exists on disk (the
70
- # calendar tools register regardless — see the empty-state guidance
71
- # in {Tools} — but this gates whether a snapshot is even attempted).
72
- def available? = !@sources.empty?
73
-
74
72
  # @return [Integer] total events cached to disk across all stores. Zero
75
73
  # means every calendar is memory-only (Offline Support off); the
76
74
  # tool turns that into a self-fixing observation.
@@ -95,11 +93,19 @@ module Pikuri
95
93
  # newest breaks ties. A single-word query has no adjacency to enforce, so
96
94
  # it stays pure substring recall.
97
95
  #
98
- # A recurring series is stored as a master row plus one row per modified
99
- # occurrence; Google additionally splits a "this-and-following" edit into
100
- # separate masters +UID_R<ical-datetime>@google.com+. {#base_uid} strips
101
- # that suffix and {#fold_series} collapses the whole lot to one hit, so a
102
- # weekly meeting surfaces once — not once per occurrence *or* per split.
96
+ # A recurring series is stored as a master row dated at its first
97
+ # occurrence, plus one row per modified occurrence. With a date range,
98
+ # {Recurrence} expands it and each occurrence in the range is a hit of
99
+ # its own, earliest first from an +after+:
100
+ #
101
+ # cal.search(query: '', limit: 15, after: monday, before: friday_night)
102
+ # # => standup Mon, standup Wed, planning Thu, standup Fri
103
+ #
104
+ # Without one, the series surfaces once, dated at its current occurrence
105
+ # (see {#current_of}), newest first. Google additionally splits a
106
+ # "this-and-following" edit into separate masters
107
+ # +UID_R<ical-datetime>@google.com+; {#base_uid} plus {#fold_series}
108
+ # collapse the whole lot to that one hit.
103
109
  #
104
110
  # @param query [String] substring over title + DESCRIPTION + LOCATION.
105
111
  # @param limit [Integer] max events.
@@ -107,19 +113,27 @@ module Pikuri
107
113
  # @param before [Time, nil] only events starting on/before this instant.
108
114
  # @param recurring [Boolean, nil] +true+ → only recurring events, +false+
109
115
  # → only single (non-recurring) events, +nil+ → both.
116
+ # @param now [Time] the clock {#current_of} reads.
110
117
  # @return [Array<Hash>] +[{event_id:, title:, start: Time, end: Time,
111
118
  # all_day: Boolean, recurring: Boolean, start_tz:, end_tz:, location:}, …]+
112
- def search(query:, limit:, after: nil, before: nil, recurring: nil)
119
+ def search(query:, limit:, after: nil, before: nil, recurring: nil, now: Time.now)
113
120
  words = query.to_s.scan(/[[:alnum:]]+/).map { |w| fold(w) }
121
+ ranged = !(after || before).nil?
122
+ today = local_midnight(now)
114
123
  # Only the fetch is guarded — the folding and ranking below run on
115
124
  # materialized rows and touch no connection.
116
125
  rows = @lock.synchronize do
117
126
  ensure_fresh
118
- @conns.values.flat_map { |db| search_db(db, words:, after:, before:) }
127
+ @conns.values.flat_map { |db| search_db(db, words:, after:, before:, today:) }
119
128
  end
120
- # Group on the *base* UID (see #base_uid), not the raw id, so Google's
121
- # this-and-following splits fold into one series instead of 20+ hits.
122
- series = rows.group_by { |h| base_uid(h[:event_id]) }.map { |_uid, group| fold_series(group) }
129
+ series =
130
+ if ranged
131
+ rows.map { |h| h.merge(recurring: h[:recurring] || h[:occurrence]).except(:occurrence) }
132
+ else
133
+ # Group on the *base* UID (see #base_uid), not the raw id, so Google's
134
+ # this-and-following splits fold into one series instead of 20+ hits.
135
+ rows.group_by { |h| base_uid(h[:event_id]) }.map { |_uid, group| fold_series(group, today) }
136
+ end
123
137
  # Phrase-first: once any event matches the words adjacently, drop the
124
138
  # OR-any-word matches — else a two-word query floods with events sharing
125
139
  # only a common word (e.g. "around") in a description. The OR set is the
@@ -130,31 +144,43 @@ module Pikuri
130
144
  # every occurrence "single" and leaked the whole series under
131
145
  # recurrence:single. Folding classifies the series as a whole first.
132
146
  series.select! { |h| h[:recurring] == recurring } unless recurring.nil?
133
- # Rank across stores by matched-word count, then recency. :score/:phrase
147
+ # Rank across stores by matched-word count, then date. :score/:phrase
134
148
  # are internal ranking keys (see #search_db), dropped from the shape.
135
- series.sort_by { |h| [-h[:score], -(h[:start]&.to_i || 0)] }
149
+ # From an +after+ the cap must cut the far end, not the days nearest it.
150
+ order = after ? 1 : -1
151
+ series.sort_by { |h| [-h[:score], order * (h[:start]&.to_i || 0)] }
136
152
  .first(limit).map { |h| h.except(:score, :phrase) }
137
153
  end
138
154
 
139
- # Full event detail for one event UID.
155
+ # Full event detail for one event UID; a recurring one is dated at its
156
+ # current occurrence (see {#current_of}).
140
157
  #
141
158
  # @param event_id [String] the {#search} handle (the event UID).
159
+ # @param now [Time] the clock {#current_of} reads.
142
160
  # @return [Hash, nil] the search shape plus +:description+, +:status+,
143
161
  # and +:attendees+ (see {#attendees}), or +nil+ if not found.
144
- def read(event_id:)
162
+ def read(event_id:, now: Time.now)
145
163
  @lock.synchronize do
146
164
  ensure_fresh
147
165
  @conns.each_value do |db|
148
166
  # A recurring UID has several rows (master + occurrence exceptions);
149
167
  # prefer the master (recurrence_id NULL sorts first) for a stable read.
150
- row = db.execute(<<~SQL, [event_id]).first
151
- SELECT id, title, event_start, event_end, event_start_tz, event_end_tz, flags, ical_status
168
+ rows = db.execute(<<~SQL, [event_id])
169
+ SELECT id, title, event_start, event_end, event_start_tz, event_end_tz, flags, cal_id, recurrence_id
152
170
  FROM cal_events WHERE id = ?
153
- ORDER BY (recurrence_id IS NOT NULL) LIMIT 1
171
+ ORDER BY (recurrence_id IS NOT NULL)
154
172
  SQL
155
- next unless row
173
+ next if rows.empty?
156
174
 
157
- return build_event(row).merge(properties(db, event_id), attendees: attendees(db, event_id))
175
+ master = build_event(rows.first)
176
+ if master[:recurring]
177
+ today = local_midnight(now)
178
+ cal_id = rows.first[7]
179
+ edited = rows.drop(1).select { |r| r[7] == cal_id }.map { |r| build_event(r) }
180
+ current = pick_current([current_of(master, cal_id, series_data(db, [cal_id, event_id]), today), *edited], today)
181
+ master = master.merge(start: current[:start], end: current[:end])
182
+ end
183
+ return master.merge(properties(db, event_id), attendees: attendees(db, event_id))
158
184
  end
159
185
  end
160
186
  nil
@@ -173,19 +199,19 @@ module Pikuri
173
199
 
174
200
  private
175
201
 
176
- # (Re)snapshot + reopen each store whose source generation moved.
202
+ # (Re)snapshot + reopen each store whose source generation moved. While
203
+ # Thunderbird is busy writing, the older copy keeps serving.
177
204
  #
178
205
  # @return [void]
206
+ # @raise [DatabaseSnapshot::TornError] Thunderbird is busy and a store
207
+ # has no copy yet.
179
208
  def ensure_fresh
180
209
  @snapshots.each do |src, snap|
181
- live = DatabaseSnapshot.change_counter(src)
182
- next if @conns[src] && @generations[src] && live == @generations[src]
183
-
184
- @conns[src]&.close
185
- snap.refresh
186
- @conns[src] = SQLite3::Database.new("file:#{snap.path}?immutable=1",
187
- flags: SQLite3::Constants::Open::READONLY | SQLite3::Constants::Open::URI)
188
- @generations[src] = snap.generation
210
+ next if @conns[src] && snap.current?
211
+ next unless snap.refresh || @conns[src].nil?
212
+
213
+ @conns.delete(src)&.close
214
+ @conns[src] = SQLite3::Database.new(snap.path, flags: SQLite3::Constants::Open::READONLY)
189
215
  end
190
216
  end
191
217
 
@@ -217,36 +243,31 @@ module Pikuri
217
243
  # such event exists".
218
244
  #
219
245
  # @param words [Array<String>] pre-folded query terms (empty ⇒ list all).
246
+ # @param today [Time] local midnight, for {#current_of}.
220
247
  # @return [Array<Hash>] hits carrying +:score+/+:phrase+ (for {#search})
221
248
  # and +:occurrence+ (for {#fold_series}); all dropped from the shape.
222
- def search_db(db, words:, after:, before:)
249
+ def search_db(db, words:, after:, before:, today:)
223
250
  filters = []
224
251
  binds = []
225
- # Date bounds are compared in the machine-local frame (the caller
226
- # parses a bare date to local midnight; parse_before extends it to
227
- # end-of-day). Correct for timed events in any zone. Caveat: all-day
228
- # events are stored as *floating* UTC-midnight, so in a far-*western*
229
- # zone (local midnight is hours ahead of UTC) an all-day event on day
230
- # D can fall just before a local-frame "day D" lower bound. Fine for
231
- # UTC/eastern zones; a fully correct fix needs per-event-type date
232
- # extraction (deferred — see ideas/thunderbird.md open questions).
233
- if after
234
- filters << 'event_start >= ?'
235
- binds << to_prtime(after)
236
- end
237
- if before
238
- filters << 'event_start <= ?'
239
- binds << to_prtime(before)
252
+ [[after, '>='], [before, '<=']].each do |bound, op|
253
+ next unless bound
254
+
255
+ filters << "event_start #{op} CASE WHEN flags & #{ALL_DAY_FLAG} != 0 THEN ? ELSE ? END"
256
+ binds.push(to_prtime(floating(bound)), to_prtime(bound))
240
257
  end
241
258
  where = filters.empty? ? '1' : filters.join(' AND ')
259
+ # A master is dated at its first occurrence, so the range can't
260
+ # select it; #occurrences decides once it is expanded.
261
+ where = "(#{where}) OR (recurrence_id IS NULL AND flags & #{RECURRENCE_FLAG} != 0)" if after || before
242
262
 
243
263
  events = db.execute(<<~SQL, binds)
244
- SELECT id, title, event_start, event_end, event_start_tz, event_end_tz, flags, recurrence_id
264
+ SELECT id, title, event_start, event_end, event_start_tz, event_end_tz, flags, recurrence_id, cal_id
245
265
  FROM cal_events WHERE #{where}
246
266
  SQL
247
267
  text = searchable_text(db)
268
+ series = nil
248
269
 
249
- events.filter_map do |row|
270
+ events.flat_map do |row|
250
271
  loc, desc = text[row[0]]
251
272
  # recurrence_id is set only on a recurring series' occurrence rows
252
273
  # (NULL on a master or a single event); it's what marks the flood
@@ -254,14 +275,137 @@ module Pikuri
254
275
  # occurrence itself lacks the master's HAS_RECURRENCE flag.
255
276
  hit = build_event(row).merge(location: loc, occurrence: !row[7].nil? && row[7].to_i != 0)
256
277
  # Empty query → list everything (score 0, date-ordered by #search).
257
- next hit.merge(score: 0, phrase: false) if words.empty?
278
+ if words.empty?
279
+ hit = hit.merge(score: 0, phrase: false)
280
+ else
281
+ haystack = fold("#{row[1]} #{loc} #{desc}")
282
+ score = words.count { |w| haystack.include?(w) }
283
+ next [] if score.zero?
258
284
 
259
- haystack = fold("#{row[1]} #{loc} #{desc}")
260
- score = words.count { |w| haystack.include?(w) }
261
- next nil if score.zero?
285
+ hit = hit.merge(score: score, phrase: phrase_match?(haystack, words))
286
+ end
287
+ next [hit] unless hit[:recurring] && !hit[:occurrence]
262
288
 
263
- hit.merge(score: score, phrase: phrase_match?(haystack, words))
289
+ series ||= series_data(db)
290
+ after || before ? occurrences(hit, row[8], series, after:, before:) : [current_of(hit, row[8], series, today)]
291
+ end
292
+ end
293
+
294
+ # A master's hit repeated once per occurrence in the range, each with
295
+ # its own start and end. A series {Recurrence} won't expand keeps its
296
+ # one stored row, as long as that falls in the range.
297
+ #
298
+ # @param hit [Hash] the master's hit (see {#search_db}).
299
+ # @param cal_id [String]
300
+ # @param series [Array(Hash, Hash)] from {#series_data}.
301
+ # @return [Array<Hash>]
302
+ def occurrences(hit, cal_id, series, after:, before:)
303
+ return [] unless hit[:start]
304
+
305
+ after = frame(hit, after)
306
+ before = frame(hit, before)
307
+ recurrence(hit, cal_id, series).starts(after:, before:).map { |start| starting_at(hit, start) }
308
+ rescue Recurrence::Unexpandable => e
309
+ LOGGER.warn("not expanding recurring event #{hit[:event_id]}: #{e.message}")
310
+ stored = hit[:start].between?(after || hit[:start], before || hit[:start])
311
+ stored ? [hit] : []
312
+ end
313
+
314
+ # A master's hit dated at the series' current occurrence: the first on
315
+ # or after +today+, else the last before it, so an ended series shows
316
+ # when it last met.
317
+ #
318
+ # current_of(standup, 'c1', series, Time.local(2026, 11, 17))
319
+ # # => standup's hit with start: 2026-11-18 07:00 UTC — Wednesday's
320
+ #
321
+ # It keeps its stored first date when nothing falls within
322
+ # {Recurrence::MAX_SPAN} either side, or the series won't expand.
323
+ #
324
+ # @param hit [Hash] the master's hit (see {#search_db}).
325
+ # @param cal_id [String]
326
+ # @param series [Array(Hash, Hash)] from {#series_data}.
327
+ # @param today [Time] local midnight.
328
+ # @return [Hash]
329
+ def current_of(hit, cal_id, series, today)
330
+ return hit unless hit[:start]
331
+
332
+ today = frame(hit, today)
333
+ rec = recurrence(hit, cal_id, series)
334
+ start = rec.starts(after: today, before: nil).first || rec.starts(after: nil, before: today - 1).last
335
+ start ? starting_at(hit, start) : hit
336
+ rescue Recurrence::Unexpandable => e
337
+ LOGGER.warn("not expanding recurring event #{hit[:event_id]}: #{e.message}")
338
+ hit
339
+ end
340
+
341
+ # @param hits [Array<Hash>] dated hits of one series.
342
+ # @param today [Time] local midnight.
343
+ # @return [Hash] the earliest on or after +today+, else the latest.
344
+ def pick_current(hits, today)
345
+ upcoming = hits.select { |h| h[:start] && h[:start] >= frame(h, today) }
346
+ upcoming.empty? ? hits.max_by { |h| h[:start]&.to_i || 0 } : upcoming.min_by { |h| h[:start] }
347
+ end
348
+
349
+ # @return [Recurrence] the series of a master's hit.
350
+ # @raise [Recurrence::Unexpandable]
351
+ def recurrence(hit, cal_id, series)
352
+ lines, overridden = series.map { |by_key| by_key.fetch([cal_id, hit[:event_id]], nil) }
353
+ Recurrence.new(start: hit[:start], tz: hit[:start_tz], lines: lines || [], overridden: overridden || Set.new)
354
+ end
355
+
356
+ # @return [Hash] +hit+ moved to +start+, keeping its duration.
357
+ def starting_at(hit, start)
358
+ duration = hit[:end] - hit[:start] if hit[:end]
359
+ hit.merge(start: start, end: duration && (start + duration))
360
+ end
361
+
362
+ # +time+'s local wall clock labelled UTC, the frame an all-day event is
363
+ # stored in:
364
+ #
365
+ # floating(Time.local(2026, 6, 1)) # => 2026-06-01 00:00:00 UTC, in any zone
366
+ #
367
+ # @param time [Time] a machine-local instant: a bound, or today's midnight.
368
+ # @return [Time]
369
+ def floating(time)
370
+ local = time.getlocal
371
+ Time.utc(local.year, local.month, local.day, local.hour, local.min, local.sec)
372
+ end
373
+
374
+ # @param hit [Hash] a dated hit.
375
+ # @param time [Time, nil]
376
+ # @return [Time, nil] +time+ to compare +hit+'s start with: {#floating}
377
+ # for an all-day hit, else unchanged.
378
+ def frame(hit, time) = hit[:all_day] && time ? floating(time) : time
379
+
380
+ # @param now [Time]
381
+ # @return [Time] the start of +now+'s day, machine-local.
382
+ def local_midnight(now)
383
+ local = now.getlocal
384
+ Time.local(local.year, local.month, local.day)
385
+ end
386
+
387
+ # One flat scan each of the recurrence lines and of the edited
388
+ # occurrences' original starts, keyed by +[cal_id, uid]+ — a UID alone
389
+ # can repeat across calendars.
390
+ #
391
+ # @param only [Array(String, String), nil] one +[cal_id, uid]+ to read
392
+ # instead of all.
393
+ # @return [Array(Hash{Array(String, String) => Array<String>},
394
+ # Hash{Array(String, String) => Set<Integer>})] the +icalString+ lines,
395
+ # and the +recurrence_id+s in epoch seconds.
396
+ def series_data(db, only = nil)
397
+ binds = only || []
398
+ lines = {}
399
+ db.execute("SELECT cal_id, item_id, icalString FROM cal_recurrence#{' WHERE cal_id = ? AND item_id = ?' if only}",
400
+ binds) do |cal_id, uid, ical|
401
+ (lines[[cal_id, uid]] ||= []) << ical
402
+ end
403
+ overridden = {}
404
+ db.execute("SELECT cal_id, id, recurrence_id FROM cal_events WHERE recurrence_id IS NOT NULL#{' AND cal_id = ? AND id = ?' if only}",
405
+ binds) do |cal_id, uid, rid|
406
+ (overridden[[cal_id, uid]] ||= Set.new) << (rid / 1_000_000)
264
407
  end
408
+ [lines, overridden]
265
409
  end
266
410
 
267
411
  # Whether the query's words appear *adjacently* in +folded_haystack+
@@ -299,15 +443,17 @@ module Pikuri
299
443
  # hit, so a weekly meeting surfaces once instead of once per occurrence or
300
444
  # split. The series counts as recurring if any row is a master
301
445
  # (HAS_RECURRENCE) or an occurrence (recurrence_id set), a phrase hit if
302
- # any row matched the phrase; the earliest in-range row represents it (its
303
- # real id stays the read handle), and the group's best word-count is its
304
- # score.
446
+ # any row matched the phrase; the current row represents it (see
447
+ # {#pick_current}; its real id stays the read handle), and the group's
448
+ # best word-count is its score.
305
449
  #
306
- # @param group [Array<Hash>] rows sharing a {#base_uid} (from {#search_db}).
450
+ # @param group [Array<Hash>] rows sharing a {#base_uid} (from {#search_db}),
451
+ # masters already at their {#current_of} dates.
452
+ # @param today [Time] local midnight.
307
453
  # @return [Hash] one merged hit (search shape + +:score+ + +:phrase+).
308
- def fold_series(group)
454
+ def fold_series(group, today)
309
455
  recurring = group.any? { |h| h[:recurring] || h[:occurrence] }
310
- rep = group.min_by { |h| h[:start]&.to_i || 0 }
456
+ rep = pick_current(group, today)
311
457
  rep.merge(recurring: recurring, score: group.map { |h| h[:score] }.max,
312
458
  phrase: group.any? { |h| h[:phrase] }).except(:occurrence)
313
459
  end
@@ -5,7 +5,7 @@ require 'securerandom'
5
5
 
6
6
  module Pikuri
7
7
  module Thunderbird
8
- # The +thunderbird_calendar_create+ tool — the v2 outbound calendar leg, and
8
+ # The +thunderbird_calendar_create+ tool — the outbound calendar leg, and
9
9
  # (like {MailCompose}) an egress leg that never commits anything itself. It
10
10
  # builds an +.ics+ ({IcsEvent}), stages it where a possibly-snap-confined
11
11
  # Thunderbird can read it ({Profile#outbox_dir}), and launches Thunderbird on
@@ -22,12 +22,12 @@ module Pikuri
22
22
  # local calendar never leaves the machine; importing into a CalDAV calendar
23
23
  # syncs out — and it's the human, in Thunderbird's wizard, who chooses.
24
24
  #
25
- # == Deferred: attendees
25
+ # == No attendees, on purpose
26
26
  #
27
- # No +attendees+ parameter — an imported +ATTENDEE+ line *might* trigger
28
- # CalDAV meeting invites, which would be an autonomous send; that's unverified
29
- # (see +ideas/thunderbird.md+), so the whole capability waits rather than risk
30
- # it. A self-authored event with no attendees can't invite anyone.
27
+ # The event carries no +ATTENDEE+, so importing it invites nobody: with
28
+ # guests, an auto-scheduling CalDAV server mails them on the import's PUT,
29
+ # or on the human's first save in Thunderbird's event dialog even when
30
+ # marked +SCHEDULE-AGENT=CLIENT+. Why not, measured: +D_no_calendar_attendees+.
31
31
  #
32
32
  # Sharing: +P_one_agent+ — it holds a {Profile} and writes an +.ics+ per
33
33
  # call. As {MailCompose}, the binding constraint is the human at the import
@@ -55,13 +55,11 @@ module Pikuri
55
55
 
56
56
  # @param profile [Profile] the discovered profile — supplies the confined
57
57
  # staging dir ({Profile#outbox_dir}).
58
- # @param thunderbird_bin [String] the Thunderbird executable (PATH name or
59
- # absolute path) for the hand-off.
60
58
  # @param launcher [Launcher, nil] test seam; +nil+ builds a real {Launcher}.
61
59
  # @return [CalendarCreate]
62
- def initialize(profile:, thunderbird_bin: 'thunderbird', launcher: nil)
60
+ def initialize(profile:, launcher: nil)
63
61
  @profile = profile
64
- @launcher = launcher || Launcher.new(thunderbird_bin: thunderbird_bin)
62
+ @launcher = launcher || Launcher.new
65
63
  super(
66
64
  name: 'thunderbird_calendar_create',
67
65
  description: DESCRIPTION,
@@ -87,19 +85,22 @@ module Pikuri
87
85
  # A bad date comes back as +"Error: …"+; so does a hand-off that can't
88
86
  # reach Thunderbird.
89
87
  #
90
- # @return [String] the observation.
88
+ # @return [Pikuri::Tool::Result] the checklist (+"Handed to Thunderbird"+
89
+ # — the wizard, not pikuri, imports it), or
90
+ # {Pikuri::Tool::Result.error}.
91
91
  def create(title:, start:, finish:, all_day:, location:, description:)
92
- start_t = DateHelpers.parse_time(start) or return 'Error: a start date/time is required.'
92
+ start_t = DateHelpers.parse_time(start) or
93
+ return Pikuri::Tool::Result.error('a start date/time is required.')
93
94
  finish_t = DateHelpers.parse_time(finish)
94
95
 
95
96
  ics = IcsEvent.build(title:, start: start_t, finish: finish_t, all_day:,
96
97
  location:, description:)
97
98
  @launcher.launch(stage(ics))
98
- CHECKLIST
99
+ Pikuri::Tool::Result.new(content: CHECKLIST, summary: 'Handed to Thunderbird')
99
100
  rescue ArgumentError => e
100
- "Error: bad date (#{e.message})."
101
+ Pikuri::Tool::Result.error("bad date (#{e.message}).")
101
102
  rescue Launcher::Error => e
102
- "Error: #{e.message}"
103
+ Pikuri::Tool::Result.error("#{e.message}")
103
104
  end
104
105
 
105
106
  private
@@ -46,21 +46,26 @@ module Pikuri
46
46
  )
47
47
  end
48
48
 
49
- # @return [String] formatted event or +"Error: …"+.
49
+ # @return [Pikuri::Tool::Result] the formatted event (+"Read 1 event"+),
50
+ # or {Pikuri::Tool::Result.error}.
50
51
  def self.run_read(backend:, event_id:)
51
52
  ev = backend.read(event_id:)
52
- return "Error: no event found with id #{event_id.inspect}." unless ev
53
+ return Pikuri::Tool::Result.error("no event found with id #{event_id.inspect}.") unless ev
53
54
 
54
55
  desc = ev[:description].to_s.strip
55
- [
56
+ detail = [
56
57
  "Title: #{ev[:title]}",
57
58
  "When: #{DateHelpers.when_label(ev)}",
59
+ *('Repeats: yes' if ev[:recurring]),
58
60
  "Where: #{ev[:location].to_s.strip.empty? ? '(none)' : ev[:location].strip}",
59
61
  "Status: #{ev[:status] || '(none)'}",
60
62
  *attendee_lines(ev[:attendees]),
61
63
  '',
62
64
  desc.empty? ? '(no description)' : desc
63
65
  ].join("\n")
66
+ Pikuri::Tool::Result.new(content: detail, summary: 'Read 1 event')
67
+ rescue DatabaseSnapshot::TornError => e
68
+ Pikuri::Tool::Result.error(e.message)
64
69
  end
65
70
 
66
71
  # The +Organizer:+ + +Attendees:+ block, or +[]+ when the event has no
@@ -10,7 +10,7 @@ module Pikuri
10
10
  # mirroring {MailSearch}: tighten it to AND and the model — primed by the
11
11
  # forgiving mail search — reads the sparser hits as "no such event".
12
12
  #
13
- # == Empty-corpus guidance (Q6)
13
+ # == Empty-corpus guidance
14
14
  #
15
15
  # Thunderbird keeps a CalDAV calendar's events *in memory only* unless
16
16
  # "Offline Support" is enabled, so a calendar can look full in the UI yet
@@ -70,14 +70,15 @@ module Pikuri
70
70
 
71
71
  # @param recurrence [String, nil] +"recurring"+, +"single"+, or +nil+ for
72
72
  # both (mapped to the backend's tri-state +recurring:+ flag).
73
- # @return [String]
73
+ # @return [Pikuri::Tool::Result] the events (+"Found 8 events"+), or
74
+ # {Pikuri::Tool::Result.error}.
74
75
  def self.run_search(backend:, query:, after:, before:, recurrence: nil, limit:)
75
76
  # Refuse a match-everything call: with no query and no date bound this
76
77
  # would dump every cached event. "What's on my calendar" should name a
77
78
  # span — steer the model to add after/before (e.g. this week). A lone
78
79
  # recurrence filter is still too broad to stand in for a span.
79
80
  if [query, after, before].all? { |v| v.to_s.strip.empty? }
80
- return 'Error: give a query and/or a date range (after/before) to search for'
81
+ return Pikuri::Tool::Result.error('give a query and/or a date range (after/before) to search for')
81
82
  end
82
83
 
83
84
  limit = limit.to_i.clamp(1, MAX_LIMIT)
@@ -88,13 +89,21 @@ module Pikuri
88
89
  # full page as the whole calendar.
89
90
  hits = backend.search(query:, limit: limit + 1, recurring:,
90
91
  after: DateHelpers.parse_after(after), before: DateHelpers.parse_before(before))
91
- return offline_or_no_match(backend, query) if hits.empty?
92
+ if hits.empty?
93
+ return Pikuri::Tool::Result.new(content: offline_or_no_match(backend, query),
94
+ summary: 'Found 0 events')
95
+ end
92
96
 
93
97
  has_more = hits.size > limit
94
98
  hits = hits.first(limit)
95
- [header(shown: hits.size, has_more:), *hits.map { |h| render(h) }].join("\n\n")
99
+ Pikuri::Tool::Result.new(
100
+ content: [header(shown: hits.size, has_more:), *hits.map { |h| render(h) }].join("\n\n"),
101
+ summary: "Found #{Pikuri::Tool.pluralize(hits.size, 'event')}#{'+' if has_more}"
102
+ )
96
103
  rescue ArgumentError => e
97
- "Error: bad date filter (#{e.message})."
104
+ Pikuri::Tool::Result.error("bad date filter (#{e.message}).")
105
+ rescue DatabaseSnapshot::TornError => e
106
+ Pikuri::Tool::Result.error(e.message)
98
107
  end
99
108
 
100
109
  # The leading line: affirm completeness when every event fit ("all
@@ -132,7 +141,7 @@ module Pikuri
132
141
  loc = event[:location].to_s.strip
133
142
  tail = +''
134
143
  tail << " | where: #{loc}" unless loc.empty?
135
- tail << ' | recurring' if event[:recurring]
144
+ tail << ' | repeats: yes' if event[:recurring]
136
145
  <<~EV.chomp
137
146
  #{event[:title].to_s.strip.empty? ? '(untitled)' : event[:title].strip}
138
147
  when: #{DateHelpers.when_label(event)}#{tail}
@@ -23,9 +23,9 @@ module Pikuri
23
23
  # must be ASCII-only and non-punycode (an +xn--+ domain is a pre-encoded
24
24
  # homoglyph that would otherwise pass {Pikuri::Sanitizer}'s mixed-script
25
25
  # check as pure ASCII).
26
- # * *Soft warn* — the correspondence-graph novelty check: a recipient domain
27
- # the user has never exchanged mail with (per {Gloda::Contacts#domains_seen}) stays
28
- # in the draft but earns a loud note urging out-of-band verification. A
26
+ # * *Soft warn* — the novelty check: a recipient domain the user has never
27
+ # sent mail to (per {Gloda::Contacts#domains_sent_to}) stays in the draft
28
+ # but earns a loud note urging out-of-band verification. A
29
29
  # hard reject here would fire on every genuinely-new correspondent. A body
30
30
  # carrying an *encoded-looking blob* (a long base64, hex or base32 run —
31
31
  # see {#body_blob_note}) likewise stays but earns a located note.
@@ -171,10 +171,10 @@ module Pikuri
171
171
  Pikuri::Sanitizer.sanitize(addr).warnings.empty?
172
172
  end
173
173
 
174
- # Append the correspondence-graph novelty warning for any recipient domain
175
- # the user has no prior mail with. Best-effort: degrades to a "couldn't
176
- # check" note when the backend is absent or its identity schema differs
177
- # from the probed shape (the schema is unverified across TB versions).
174
+ # Append the novelty warning for any recipient domain the user has never
175
+ # sent mail to. Best-effort: degrades to a "couldn't check" note when the
176
+ # backend is absent, no Sent mail is indexed, or the schema differs from
177
+ # the probed shape (it is unverified across TB versions).
178
178
  #
179
179
  # @return [void]
180
180
  def novelty_note(addrs, notes)
@@ -187,14 +187,19 @@ module Pikuri
187
187
  return
188
188
  end
189
189
 
190
- seen = @backend.domains_seen(domains)
191
- novel = domains - seen
190
+ sent_to = @backend.domains_sent_to(domains)
191
+ unless sent_to
192
+ notes << "Couldn't check whether you've mailed these recipients before " \
193
+ '(no sent mail is indexed) — double-check the address is correct.'
194
+ return
195
+ end
196
+ novel = domains - sent_to
192
197
  return if novel.empty?
193
198
 
194
- notes << "You have no prior mail with #{novel.join(', ')}. If you expected a " \
199
+ notes << "You have never sent mail to #{novel.join(', ')}. If you expected a " \
195
200
  'familiar contact, watch for a look-alike domain and verify out of ' \
196
201
  'band (not by replying to a suspect message).'
197
- rescue SQLite3::SQLException => e
202
+ rescue SQLite3::SQLException, DatabaseSnapshot::TornError => e
198
203
  LOGGER.warn("recipient-novelty check unavailable: #{e.message}")
199
204
  notes << "Couldn't check whether you've mailed these recipients before — " \
200
205
  'double-check the address is correct.'