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
//! Daemon-side implementation of the project-registry MCP tools
//! (WI-2 + WI-5, #1519 / #1517).
//!
//! Why: the MCP `StateBackend` (in `mcp_backend.rs`) must service project-registry
//! and NL-resolver tools, but inlining their bodies there would push that file
//! over the 500-SLOC production cap. This module holds the wrapping logic,
//! mirroring the `mcp_session.rs` / `mcp_console.rs` pattern.
//!
//! Four free async functions are exposed:
//! `project_list`, `project_register`, `project_get` (registry CRUD, WI-2) and
//! `project_resolve` (NL→project resolver, WI-5).
//! Each takes `&Arc<DaemonState>` plus parsed arguments and returns a JSON value
//! or a human-readable error string.
//!
//! Test: the dispatch-level tests in `crate::mcp::tests` exercise these
//! functions through the mock backend. `project_register`'s merge-with-
//! existing behaviour (#3025 review follow-up item 4) needs a REAL
//! `DaemonState`/`ProjectRegistry` (a mock cannot observe persistence), so
//! that is covered by this module's own inline `#[cfg(test)]` instead.
use std::sync::Arc;
use serde_json::{Value, json};
use crate::daemon::project_adoption::{RegisterProjectResponse, adopt_pre_existing_worktrees};
use crate::daemon::state::DaemonState;
use crate::project::record::Project;
use crate::project::resolver;
/// Return all registered projects as a JSON array.
///
/// Why: `project_list` gives the driver skill and operators a typed,
/// JSON-native inventory of known repos without scraping CLI text.
/// What: delegates to `DaemonState::project_registry` and serializes all
/// entries; an empty registry returns `{ "projects": [] }`.
/// Test: `dispatch_project_list_tool` in `crate::mcp::tests`.
pub async fn project_list(state: &Arc<DaemonState>) -> Result<Value, String> {
let registry = state.project_registry().await;
let projects = registry
.list()
.await
.map_err(|e| format!("project_list: registry error: {e}"))?;
let values = projects
.into_iter()
.map(|p| serde_json::to_value(p).map_err(|e| format!("project_list: serialize error: {e}")))
.collect::<Result<Vec<Value>, String>>()?;
let count = values.len();
Ok(json!({ "projects": values, "count": count }))
}
/// Register or update a project in the registry.
///
/// Why: `project_register` is the typed, JSON-native way to add a project
/// without editing `config.yaml` or restarting the daemon. `gh_user` (#2081)
/// lets an operator declare the project's preferred `gh` account so callers
/// can scope `gh` operations to it instead of relying on a per-session
/// reminder. `gh_account` (#3025) is the SEPARATE spawn-time pinning field:
/// when set, every session spawn/relaunch for this project resolves and
/// injects `GH_TOKEN`/`GH_USER` via
/// [`crate::core::gh_account::resolve_gh_account_env`].
/// What: builds a `Project` from the supplied fields (defaulting
/// `default_branch` to `"main"` when omitted); a `None` param for
/// `stack_hint`/`tags`/`description`/`gh_user`/`gh_account` PRESERVES the
/// current persisted value rather than clearing it (#3025 review follow-up
/// item 4 — mirrors [`crate::daemon::managed_routes::project_registry_routes::register_project_registry_route`](crate::daemon::managed_routes::register_project_registry_route)'s
/// identical fix; see that function's doc for the full rationale and the
/// deliberate `default_branch` exception). Calls `registry.register`, then runs
/// the SHARED [`adopt_pre_existing_worktrees`] (#7357 — the CLI transport runs
/// the same function, so neither can adopt what the other does not), and
/// returns the persisted record with that adoption report beside it as
/// [`RegisterProjectResponse`].
/// Test: `dispatch_project_register_tool` in `crate::mcp::tests`;
/// `project_register_backfills_pre_existing_worktrees`,
/// `project_register_backfill_is_idempotent`,
/// `parity_register_adopts_the_same_worktrees_across_transports`.
#[allow(clippy::too_many_arguments)]
pub async fn project_register(
state: &Arc<DaemonState>,
name: &str,
repo_url: &str,
default_branch: Option<&str>,
stack_hint: Option<&str>,
tags: Option<Vec<String>>,
description: Option<&str>,
gh_user: Option<&str>,
gh_account: Option<&str>,
) -> Result<Value, String> {
let registry = state.project_registry().await;
// #2184: `register` REPLACES the whole record and `project_register`'s
// params don't carry the github/commit-identity binding (operators set
// those via `config_write`'s per-project fields instead) — preserve any
// existing binding across a `project_register` call rather than silently
// wiping it.
let existing = registry.get(name).await.ok();
let project = Project {
name: name.to_string(),
repo_url: repo_url.to_string(),
default_branch: default_branch.unwrap_or("main").to_string(),
stack_hint: stack_hint
.map(str::to_string)
.or_else(|| existing.as_ref().and_then(|p| p.stack_hint.clone())),
tags: tags
.or_else(|| existing.as_ref().map(|p| p.tags.clone()))
.unwrap_or_default(),
description: description
.map(str::to_string)
.or_else(|| existing.as_ref().and_then(|p| p.description.clone())),
gh_user: gh_user
.map(str::to_string)
.or_else(|| existing.as_ref().and_then(|p| p.gh_user.clone())),
gh_account: gh_account
.map(str::to_string)
.or_else(|| existing.as_ref().and_then(|p| p.gh_account.clone())),
github: existing.as_ref().and_then(|p| p.github.clone()),
commit_name: existing.as_ref().and_then(|p| p.commit_name.clone()),
commit_email: existing.as_ref().and_then(|p| p.commit_email.clone()),
// #3455: no param for this tool (set via `tm projects config` /
// `config_write` instead) — preserve any existing value rather than
// silently resetting it back to worktree-ON.
worktree: existing.as_ref().and_then(|p| p.worktree),
};
registry
.register(project.clone())
.await
.map_err(|e| format!("project_register: registry error: {e}"))?;
// #7357: the SAME function the CLI transport calls, so the two surfaces
// cannot diverge on what registration adopts.
let adoption = adopt_pre_existing_worktrees(state, &project);
serde_json::to_value(RegisterProjectResponse { project, adoption }).map_err(|e| e.to_string())
}
/// Look up a single project by name.
///
/// Why: `project_get` is the typed point-lookup that lets a driver retrieve
/// a project's `repo_url` and `default_branch` without listing all projects.
/// What: calls `registry.get(name)` and serializes the result; returns a
/// descriptive error string when the name is not registered.
/// Test: `dispatch_project_get_tool` in `crate::mcp::tests`.
pub async fn project_get(state: &Arc<DaemonState>, name: &str) -> Result<Value, String> {
let registry = state.project_registry().await;
let project = registry
.get(name)
.await
.map_err(|e| format!("project `{name}` not found: {e}"))?;
serde_json::to_value(&project).map_err(|e| e.to_string())
}
/// Resolve a natural-language query to the best-matching registered project.
///
/// Why: `project_resolve` is the NL→repo entry point for all surfaces
/// (Telegram free-text, coordinator chat, driver skills) that need to route a
/// human-written query to a specific project without knowing its exact name or
/// URL. Centralising it here keeps routing logic in one testable place.
/// What: lists all registered projects, calls [`resolver::resolve_project`],
/// and serialises the result as:
/// ```json
/// {
/// "primary": {
/// "project": { "name": "…", "repo_url": "…", … },
/// "confidence": 0.95,
/// "reason": "url match"
/// },
/// "needs_disambiguation": false,
/// "matches": [
/// { "project": { … }, "confidence": 0.95, "reason": "url match" }
/// ]
/// }
/// ```
/// On no-match or empty registry `primary` is `null` and `error` explains
/// the failure.
/// Test: `dispatch_project_resolve_tool` in `crate::mcp::tests`.
pub async fn project_resolve(state: &Arc<DaemonState>, query: &str) -> Result<Value, String> {
let registry = state.project_registry().await;
let projects = registry
.list()
.await
.map_err(|e| format!("project_resolve: registry error: {e}"))?;
match resolver::resolve_project(query, &projects) {
Ok(resolution) => {
let primary_val = resolution.primary.as_ref().map(|m| {
json!({
"project": serde_json::to_value(&m.project)
.unwrap_or(Value::Null),
"confidence": m.confidence,
"reason": m.reason.label(),
})
});
let all_matches: Vec<Value> = resolution
.matches
.iter()
.map(|m| {
json!({
"project": serde_json::to_value(&m.project)
.unwrap_or(Value::Null),
"confidence": m.confidence,
"reason": m.reason.label(),
})
})
.collect();
Ok(json!({
"primary": primary_val,
"needs_disambiguation": resolution.needs_disambiguation(),
"matches": all_matches,
}))
}
Err(resolver::ResolverError::NoMatch { query: q }) => Ok(json!({
"primary": null,
"needs_disambiguation": false,
"matches": [],
"error": format!("no project matched query: {q:?}"),
})),
Err(resolver::ResolverError::EmptyRegistry) => Ok(json!({
"primary": null,
"needs_disambiguation": false,
"matches": [],
"error": "project registry is empty; register at least one project first",
})),
}
}
#[cfg(test)]
mod tests {
use super::*;
async fn isolated_state() -> Arc<DaemonState> {
let root = tempfile::tempdir().expect("tempdir").keep();
Arc::new(DaemonState::with_root_isolated_managed(root).await)
}
/// Why (#3025 review follow-up item 4): a `project_register` call that
/// omits `stack_hint`/`tags`/`description`/`gh_user` must PRESERVE the
/// currently-persisted values, not wipe them — the MCP-tool counterpart
/// of `register_preserves_unspecified_optional_fields_on_existing_project`
/// in `tests/project_registry_routes.rs`.
/// Test: itself.
#[tokio::test]
async fn project_register_preserves_unspecified_optional_fields() {
let state = isolated_state().await;
project_register(
&state,
"widget",
"https://github.com/acme/widget",
None,
Some("rust"),
Some(vec!["backend".to_string()]),
Some("the widget project"),
Some("bobmatnyc"),
None,
)
.await
.expect("initial register");
// Second call carries ONLY gh_account.
let result = project_register(
&state,
"widget",
"https://github.com/acme/widget",
None,
None,
None,
None,
None,
Some("bob-work"),
)
.await
.expect("gh_account-only re-register");
assert_eq!(result["gh_account"], "bob-work");
assert_eq!(result["stack_hint"], "rust");
assert_eq!(result["description"], "the widget project");
assert_eq!(result["gh_user"], "bobmatnyc");
assert_eq!(result["tags"][0], "backend");
}
/// Why: a value the SECOND call DOES supply must still override the
/// existing one — merge-with-existing must never become
/// merge-that-ignores-new-values.
/// Test: itself.
#[tokio::test]
async fn project_register_explicit_fields_still_override_existing() {
let state = isolated_state().await;
project_register(
&state,
"widget",
"https://github.com/acme/widget",
None,
Some("rust"),
None,
None,
None,
Some("bobmatnyc"),
)
.await
.expect("initial register");
let result = project_register(
&state,
"widget",
"https://github.com/acme/widget",
None,
Some("python"),
None,
None,
None,
Some("bob-work"),
)
.await
.expect("overriding re-register");
assert_eq!(result["stack_hint"], "python");
assert_eq!(result["gh_account"], "bob-work");
}
/// Register a project whose checkout ALREADY has worktrees, and both get a
/// record naming it (#7357).
///
/// Why: this is the reported bug end to end. Before the fix registration
/// wrote a `Project` record and nothing else, so every worktree already on
/// disk stayed invisible to `reconcile-worktrees`, the `--merged-prs` sweep
/// and `tm doctor` — all three read one scan that reaches a project only at
/// `<repos_root>/<owner>/<repo>`.
/// Test: itself.
#[tokio::test]
async fn project_register_backfills_pre_existing_worktrees() {
let fx = crate::session_manager::worktree_git_fixture::GitWorktreeFixture::new();
let a = fx.add_worktree("pre-one");
let b = fx.add_worktree("pre-two");
let state = isolated_state().await;
project_register(
&state,
"gnomish",
fx.repo.to_str().expect("utf8 checkout"),
None,
None,
None,
None,
None,
None,
)
.await
.expect("register");
let store = crate::project::AdoptionStore::load(&crate::project::registry_data_dir_under(
state.framework_root(),
));
let paths: Vec<&std::path::PathBuf> = store.entries().iter().map(|e| &e.path).collect();
for wt in [&a, &b] {
let canonical = std::fs::canonicalize(wt).expect("canonical worktree");
assert!(
paths.contains(&&canonical),
"{} must have an adoption record; got {paths:?}",
canonical.display()
);
}
assert!(store.entries().iter().all(|e| e.project == "gnomish"));
}
/// Re-registering an already-registered project adds no duplicate records.
/// Test: itself.
#[tokio::test]
async fn project_register_backfill_is_idempotent() {
let fx = crate::session_manager::worktree_git_fixture::GitWorktreeFixture::new();
fx.add_worktree("pre-one");
fx.add_worktree("pre-two");
let state = isolated_state().await;
let checkout = fx.repo.to_str().expect("utf8 checkout");
for _ in 0..2 {
project_register(
&state, "gnomish", checkout, None, None, None, None, None, None,
)
.await
.expect("register");
}
let store = crate::project::AdoptionStore::load(&crate::project::registry_data_dir_under(
state.framework_root(),
));
assert_eq!(store.entries().len(), 2, "two worktrees, two records");
}
/// The backfill is not a gate: a `repo_url` that is not a local repository
/// leaves registration succeeding and writes no records.
/// Test: itself.
#[tokio::test]
async fn project_register_succeeds_when_the_checkout_is_not_a_repository() {
let plain = tempfile::tempdir().expect("tempdir");
let state = isolated_state().await;
let result = project_register(
&state,
"plainly",
plain.path().to_str().expect("utf8 path"),
None,
None,
None,
None,
None,
None,
)
.await
.expect("register must still succeed");
assert_eq!(result["name"], "plainly");
let store = crate::project::AdoptionStore::load(&crate::project::registry_data_dir_under(
state.framework_root(),
));
assert!(store.entries().is_empty());
}
}