1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
//! NL-to-project resolver and session↔project binding (WI-5, #1517).
//!
//! Why: operators work across multiple repos and should not have to remember
//! exact URLs or project names; free-text queries (names, URLs, keywords,
//! ticket IDs) must route automatically to the right registered project so
//! the session manager can spawn or connect sessions without manual lookup.
//! What: exports [`resolve_project`], [`resolve_session_project`], and
//! [`fleet_by_project`] — the three primitives of the NL→project layer:
//! (1) map a free-text query to a ranked [`ProjectResolution`]; (2) bind a
//! live [`SessionRecord`] to its [`Project`]; (3) group active sessions by
//! project into a [`ProjectFleet`] vector for fleet-management UX.
//! Test: unit tests live in the sibling `tests` module (`resolver/tests.rs`),
//! covering exact-name, URL, keyword, multi-candidate disambiguation, clamping,
//! no-match, tie-breaking, and confidence-capping scenarios.
use Error;
use Project;
use crateSessionRecord;
// ---------------------------------------------------------------------------
// Public thresholds (spec §4.2 / §5.3, with #1532 clarifications)
// ---------------------------------------------------------------------------
/// Minimum raw keyword score required for a candidate to enter `matches`.
///
/// Why: a single incidental tag hit should not produce a match; 0.3 is exactly
/// one tag-word hit which gives operators a reasonable floor without noise.
/// Per #1532 item 2 this is the *collection* floor, distinct from the
/// disambiguation floor.
/// What: used in the keyword-scoring pass to filter candidates before sorting.
/// Test: `resolver_keyword_threshold_filters_low_score`.
pub const KEYWORD_COLLECTION_FLOOR: f32 = 0.3;
/// Confidence threshold above which multiple candidates trigger disambiguation.
///
/// Why: if more than one candidate scores above this level the caller cannot
/// automatically pick a winner and must surface a disambiguation picker (e.g.
/// in the Telegram bot). Per #1532 item 2 this is the *presentation* floor,
/// separate from the collection floor.
/// What: callers inspect `ProjectResolution::needs_disambiguation()` which uses
/// this constant.
/// Test: `resolver_multi_candidate_disambiguation`, `resolver_single_above_floor`.
pub const DISAMBIGUATION_FLOOR: f32 = 0.6;
// ---------------------------------------------------------------------------
// Error type
// ---------------------------------------------------------------------------
/// Errors that the NL-to-project resolver can produce.
///
/// Why: structured errors let callers distinguish "no project matched at all"
/// from "the query itself was unusable", enabling different UX responses
/// (disambiguation picker vs. bad-input message).
/// What: three variants cover the no-match case, the empty-registry guard,
/// and future extension points.
/// Test: `resolver_no_match_returns_error`, `resolver_empty_registry`.
// ---------------------------------------------------------------------------
// Resolution reason
// ---------------------------------------------------------------------------
/// Why a particular project was chosen by the resolver.
///
/// Why: surfacing the reason lets UIs (Telegram bot, TUI) show operators a
/// brief explanation ("matched by name", "matched URL keyword") and build
/// trust in the routing decision.
/// What: one variant per matching strategy, ordered by precedence.
/// Test: `resolver_exact_name_reason`, `resolver_url_reason`,
/// `resolver_keyword_reason`.
// ---------------------------------------------------------------------------
// Match and resolution types
// ---------------------------------------------------------------------------
/// A single candidate project returned by the resolver.
///
/// Why: callers (Telegram, TUI, MCP tools) need not just the project but also
/// the confidence score and matching reason to present meaningful disambiguation
/// options and audit trails.
/// What: wraps a [`Project`] clone with a clamped `[0.0, 1.0]` confidence
/// score and the [`ResolutionReason`] that explains the match.
/// Test: `resolver_confidence_clamped_to_one`, `resolver_exact_name_confidence`.
/// Resolver output: an ordered list of candidates plus the primary pick.
///
/// Why: returning all candidates enables disambiguation UIs to show a picker
/// while still providing a `primary` shortcut for the common single-match case.
/// What: `matches` is sorted by descending confidence; `primary` is the
/// highest-confidence match. Per #1532 item 3 `primary` is `Option<ProjectMatch>`
/// and is `None` only when the resolver would have returned `NoMatch` — in
/// practice, a `ProjectResolution` is only constructed when ≥1 match exists.
/// Test: `resolver_resolution_primary_is_highest_confidence`,
/// `resolver_multi_candidate_disambiguation`.
// ---------------------------------------------------------------------------
// Fleet view
// ---------------------------------------------------------------------------
/// A project and the subset of sessions currently serving it.
///
/// Why: the Telegram `/fleet` command and the TUI both need a per-project
/// grouped view of live sessions; computing it here keeps the rendering layer
/// thin and testable.
/// What: wraps a [`Project`] clone with all [`SessionRecord`]s whose
/// `repo_url` matches the project's `repo_url`.
/// Test: `resolver_fleet_by_project_basic`, `resolver_fleet_empty_sessions`.
// ---------------------------------------------------------------------------
// Core resolver functions
// ---------------------------------------------------------------------------
/// Map a free-text query to the best-matching registered project.
///
/// Why: the central entry point for NL→repo routing; all caller surfaces
/// (Telegram free-text, coordinator chat endpoint, MCP `resolve_project` tool)
/// delegate to this function so matching logic is consolidated and testable.
///
/// What: applies three strategies in precedence order — (1) exact name match
/// (confidence 1.0, case-insensitive equality against `Project::name`);
/// (2) URL match (confidence 0.95, extracts repo fragment and matches against
/// `Project::repo_url`); (3) keyword match (confidence clamped to `[0.0, 1.0]`,
/// scores each query word against `name` (+0.4), `description` (+0.2), and
/// `tags` (+0.3); candidates above `KEYWORD_COLLECTION_FLOOR` enter the result
/// set).
///
/// Returns `Err(EmptyRegistry)` when no projects are registered, `Err(NoMatch)`
/// when no candidate reached any floor, or `Ok(ProjectResolution)` with
/// `matches` sorted by descending confidence.
///
/// Test: `resolver_exact_name`, `resolver_url_match`, `resolver_keyword_match`,
/// `resolver_multi_candidate_disambiguation`, `resolver_no_match_returns_error`.
/// Bind a live session to its registered project by `repo_url`.
///
/// Why: `SessionRecord` carries `repo_url` but not a project name reference;
/// this function performs the lookup so fleet grouping and focused-session
/// routing do not need to replicate the matching logic.
/// What: returns the first project whose `repo_url` (case-insensitive) equals
/// the session's `repo_url`. Per #1532 item 5, when the same `repo_url` is
/// registered under multiple project names the first match in `projects` order
/// is returned — callers that need determinism should ensure `repo_url`
/// uniqueness in the registry.
/// Test: `resolver_session_project_binding`, `resolver_session_no_repo`,
/// `resolver_session_url_tie_break`.
/// Group a slice of session records by their bound project.
///
/// Why: the Telegram `/fleet` command and the SM TUI both need a
/// project-grouped view of active sessions; computing it once here keeps
/// the rendering layer thin.
/// What: for each registered project collects sessions whose `repo_url`
/// matches; projects with no sessions are included with an empty `sessions`
/// vec so callers can still display the full registry. Session records with
/// no `repo_url` (or whose URL matches no project) are silently omitted from
/// the fleet view.
/// Test: `resolver_fleet_by_project_basic`, `resolver_fleet_empty_sessions`,
/// `resolver_fleet_no_repo_sessions_omitted`.
// ---------------------------------------------------------------------------
// Private helpers
// ---------------------------------------------------------------------------
/// Returns `true` if the query looks like a URL or URL fragment.
///
/// Why: URL-matching must not be triggered for short keyword queries;
/// requiring "://" or a leading "github.com/" prefix keeps false-positives low.
/// What: checks for "://" (standard URL scheme) or "github.com/" prefix after
/// stripping whitespace.
/// Test: covered via URL-match resolver tests.
/// Extract a `owner/repo` or bare `repo` fragment from a URL string.
///
/// Why: matching a full URL against `repo_url` is fragile (http vs https,
/// trailing `.git`, port numbers); extracting the repo fragment and doing a
/// substring match is more robust.
/// What: splits on "/" and takes the last two non-empty segments (e.g.
/// `owner/repo`); strips a trailing ".git" if present.
/// Test: covered via `resolver_url_match` tests.
/// Returns `true` if the query looks like a ticket identifier.
///
/// Why: ticket IDs (`PROJ-123`, `#456`) should be flagged so the resolver
/// can attach a `TicketKeyword` reason even though full ticket-tracker
/// integration is deferred to Phase 2.
/// What: matches patterns like `ABC-123` or `#123`.
/// Test: `resolver_ticket_keyword_reason`.
/// Extract the alphabetic project-code prefix from a ticket-ID string.
///
/// Why: ticket IDs like `"PROJ-123"` or `"#456"` should score against the
/// project-code fragment (`"proj"`, `"#"` stripped) rather than the full
/// token so that projects tagged or named with that code get matched.
/// What: for PROJ-NNN form, returns everything before the dash (lowercased);
/// for `#NNN` form, returns the string `"#"` (minimal; callers that want
/// GitHub-issue routing should integrate the issue tracker in Phase 2).
/// Test: covered by `resolver_ticket_keyword_reason`.
/// Accumulate a keyword relevance score for `project` given the query `words`.
///
/// Why: the score drives ranking; per §5.3 each word contributes per-field
/// weights, and per #1532 item 1 the total must be clamped by the caller.
///
/// What: returns the raw (potentially > 1.0) sum; the caller clamps to
/// `[0.0, 1.0]`. Per-word weights: name hit +0.4, description hit +0.2,
/// exact tag match +0.3.
///
/// Note on description-only matches: a query word that matches only the
/// description scores 0.2, which is below `KEYWORD_COLLECTION_FLOOR` (0.3).
/// Description-only hits therefore never surface as a result on their own —
/// they only contribute to the final score when a name or tag hit also fires.
/// This is intentional (Phase 1 scope); raise the description weight or lower
/// the collection floor in a future phase if description-only routing is needed.
///
/// Test: `resolver_keyword_score_accumulates`, `resolver_keyword_clamped`.
/// Normalise a repository URL for fuzzy equality comparison.
///
/// Why: two URLs for the same repo may differ by trailing ".git" or trailing
/// slash; normalising before comparison avoids false non-matches.
/// What: strips a trailing "/" then a trailing ".git" suffix.
/// Test: covered via `resolve_session_project` tests.