handoff-mcp-server 0.15.1 → 0.17.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.
@@ -7,6 +7,7 @@ pub mod check_criterion;
7
7
  pub mod config;
8
8
  pub mod config_crud;
9
9
  pub mod dashboard;
10
+ pub mod fork_session;
10
11
  pub mod get_session;
11
12
  pub mod get_task;
12
13
  pub mod import_context;
@@ -16,6 +17,7 @@ pub mod list_tasks;
16
17
  pub mod load_context;
17
18
  pub mod log_time;
18
19
  pub mod memory;
20
+ pub mod merge_sessions;
19
21
  pub mod metrics;
20
22
  pub mod milestones;
21
23
  pub mod refer;
@@ -80,6 +82,8 @@ pub fn handle_tool_call(name: &str, arguments: &Value) -> JsonRpcResponse {
80
82
  "handoff_memory_query" => memory::handle_query(arguments),
81
83
  "handoff_memory_delete" => memory::handle_delete(arguments),
82
84
  "handoff_memory_cleanup" => memory::handle_cleanup(arguments),
85
+ "handoff_fork_session" => fork_session::handle(arguments),
86
+ "handoff_merge_sessions" => merge_sessions::handle(arguments),
83
87
  "handoff_timer_start" => timer::handle_start(arguments),
84
88
  "handoff_timer_stop" => timer::handle_stop(arguments),
85
89
  "handoff_timer_get_time" => timer::handle_get_time(arguments),
@@ -79,6 +79,8 @@ pub fn handle(arguments: &Value) -> Result<String> {
79
79
  let git_state = capture_git_state(&project_dir)?;
80
80
  let now = Utc::now().to_rfc3339();
81
81
 
82
+ let target_session_id = arguments.get("session_id").and_then(|v| v.as_str());
83
+
82
84
  let handoff_updates = SessionData {
83
85
  version: 2,
84
86
  id: None,
@@ -94,6 +96,16 @@ pub fn handle(arguments: &Value) -> Result<String> {
94
96
  references: extract_array(arguments, "references"),
95
97
  context_pointers: extract_array(arguments, "context_pointers"),
96
98
  environment: arguments.get("environment").cloned(),
99
+ timeline: arguments
100
+ .get("timeline")
101
+ .and_then(|v| v.as_str())
102
+ .map(String::from),
103
+ label: arguments
104
+ .get("label")
105
+ .and_then(|v| v.as_str())
106
+ .map(String::from),
107
+ parent_session_id: None,
108
+ related_task_ids: extract_string_array(arguments, "related_task_ids"),
97
109
  };
98
110
 
99
111
  let (total_closed, path, session_id) = if let Some(id) = close_id {
@@ -103,16 +115,19 @@ pub fn handle(arguments: &Value) -> Result<String> {
103
115
  (0, None, None)
104
116
  } else {
105
117
  let active = read_active_sessions(&sessions_dir)?;
106
- if active.len() > 1 {
107
- let active_ids: Vec<String> = active.iter().filter_map(|s| s.id.clone()).collect();
108
- anyhow::bail!(
109
- "Multiple active sessions found ({}).\n\
110
- Use close_session_id or pause_session_id to specify which to \
111
- close/pause before saving context.",
112
- active_ids.join(", ")
113
- );
114
- }
115
- if let Some(active_session) = active.first() {
118
+ let target = if let Some(tid) = target_session_id {
119
+ active.iter().find(|s| {
120
+ s.id.as_deref()
121
+ .is_some_and(|id| id == tid || id.starts_with(tid) || tid.starts_with(id))
122
+ })
123
+ } else if active.len() == 1 {
124
+ active.first()
125
+ } else if active.len() > 1 {
126
+ active.iter().last()
127
+ } else {
128
+ None
129
+ };
130
+ if let Some(active_session) = target {
116
131
  let sid = active_session.id.clone().unwrap_or_default();
117
132
  if keep_active {
118
133
  let updated_path = update_active_session(&sessions_dir, &sid, &handoff_updates)?;
@@ -126,6 +141,11 @@ pub fn handle(arguments: &Value) -> Result<String> {
126
141
  Some(sid),
127
142
  )
128
143
  }
144
+ } else if target_session_id.is_some() {
145
+ anyhow::bail!(
146
+ "session_id '{}' not found among active sessions",
147
+ target_session_id.unwrap_or("")
148
+ );
129
149
  } else {
130
150
  let new_id = generate_session_id();
131
151
  let mut data = handoff_updates.clone();
@@ -10,21 +10,28 @@ pub fn handle(arguments: &Value) -> Result<String> {
10
10
  let handoff = ensure_handoff_exists(&project_dir)?;
11
11
  let sessions_dir = handoff.join("sessions");
12
12
 
13
+ let target_session_id = arguments.get("session_id").and_then(|v| v.as_str());
14
+
13
15
  let active = read_active_sessions(&sessions_dir)?;
14
16
  if active.is_empty() {
15
17
  anyhow::bail!(
16
18
  "No active session. Call save_context with session_status='active' to create one first."
17
19
  );
18
20
  }
19
- if active.len() > 1 {
20
- let ids: Vec<String> = active.iter().filter_map(|s| s.id.clone()).collect();
21
- anyhow::bail!(
22
- "Multiple active sessions ({}). Use save_context to resolve.",
23
- ids.join(", ")
24
- );
25
- }
26
21
 
27
- let session = &active[0];
22
+ let session = if let Some(tid) = target_session_id {
23
+ active
24
+ .iter()
25
+ .find(|s| {
26
+ s.id.as_deref()
27
+ .is_some_and(|id| id == tid || id.starts_with(tid) || tid.starts_with(id))
28
+ })
29
+ .ok_or_else(|| anyhow::anyhow!("session_id '{tid}' not found among active sessions"))?
30
+ } else if active.len() == 1 {
31
+ &active[0]
32
+ } else {
33
+ active.last().unwrap()
34
+ };
28
35
  let sid = session.id.as_deref().unwrap_or("");
29
36
 
30
37
  let checklist_index = arguments
@@ -247,6 +247,15 @@ fn handle_update(
247
247
  }
248
248
  if let Some(notes) = task_val.get("notes").and_then(|v| v.as_str()) {
249
249
  data.notes = Some(notes.to_string());
250
+ } else if let Some(append) = task_val.get("notes_append").and_then(|v| v.as_str()) {
251
+ let timestamp = Utc::now().format("%Y-%m-%dT%H:%M:%S");
252
+ let block = format!("--- {timestamp}\n{append}");
253
+ match &mut data.notes {
254
+ Some(existing) if !existing.is_empty() => {
255
+ existing.push_str(&format!("\n\n{block}"));
256
+ }
257
+ _ => data.notes = Some(block),
258
+ }
250
259
  }
251
260
  if let Some(priority) = task_val.get("priority").and_then(|v| v.as_str()) {
252
261
  validate_priority(Some(priority))?;
package/src/mcp/tools.rs CHANGED
@@ -168,6 +168,23 @@ pub fn all_tool_definitions() -> Vec<ToolDefinition> {
168
168
  "environment": {
169
169
  "type": "object",
170
170
  "description": "Free-form environment state"
171
+ },
172
+ "session_id": {
173
+ "type": "string",
174
+ "description": "Target active session ID. When multiple active sessions exist, specifies which to update/close. If omitted, uses the latest active session. Lower priority than close_session_id / pause_session_id."
175
+ },
176
+ "timeline": {
177
+ "type": "string",
178
+ "description": "Session timeline/group label (e.g. 'feature-x', 'hotfix-y')."
179
+ },
180
+ "label": {
181
+ "type": "string",
182
+ "description": "Short human-readable session label for switching UI (e.g. 'WT2作業', 'API設計')."
183
+ },
184
+ "related_task_ids": {
185
+ "type": "array",
186
+ "description": "Task IDs this session is primarily working on.",
187
+ "items": { "type": "string" }
171
188
  }
172
189
  },
173
190
  "required": ["summary"]
@@ -272,6 +289,7 @@ pub fn all_tool_definitions() -> Vec<ToolDefinition> {
272
289
  "enum": ["todo", "in_progress", "review", "done", "blocked", "skipped"]
273
290
  },
274
291
  "notes": { "type": "string" },
292
+ "notes_append": { "type": "string", "description": "Append text to existing notes with a timestamp heading. If both notes and notes_append are provided, notes (replace) takes precedence." },
275
293
  "priority": {
276
294
  "type": "string",
277
295
  "enum": ["low", "medium", "high"]
@@ -695,6 +713,10 @@ pub fn all_tool_definitions() -> Vec<ToolDefinition> {
695
713
  "type": "string",
696
714
  "description": "Project directory path. Defaults to current working directory."
697
715
  },
716
+ "session_id": {
717
+ "type": "string",
718
+ "description": "Target active session ID. When multiple active sessions exist, specifies which to update. If omitted and multiple exist, uses the latest."
719
+ },
698
720
  "checklist_index": {
699
721
  "type": "integer",
700
722
  "description": "0-based index of a checklist item to toggle."
@@ -798,9 +820,17 @@ pub fn all_tool_definitions() -> Vec<ToolDefinition> {
798
820
  "enum": ["open", "active", "paused", "closed"],
799
821
  "description": "Filter sessions by status."
800
822
  },
823
+ "timeline": {
824
+ "type": "string",
825
+ "description": "Filter sessions by timeline label."
826
+ },
801
827
  "limit": {
802
828
  "type": "integer",
803
829
  "description": "Max sessions to return (default 20)."
830
+ },
831
+ "include_children": {
832
+ "type": "boolean",
833
+ "description": "If true, include a 'children' array on each session showing its forked child sessions."
804
834
  }
805
835
  }
806
836
  }),
@@ -838,6 +868,8 @@ pub fn all_tool_definitions() -> Vec<ToolDefinition> {
838
868
  "status": { "type": "string", "enum": ["todo", "in_progress", "review", "done", "blocked", "skipped"] },
839
869
  "priority": { "type": "string", "enum": ["low", "medium", "high"] },
840
870
  "assignee": { "type": "string" },
871
+ "notes": { "type": "string", "description": "Replace task notes." },
872
+ "notes_append": { "type": "string", "description": "Append text to existing notes with a timestamp heading. If both notes and notes_append are provided, notes (replace) takes precedence." },
841
873
  "schedule": {
842
874
  "type": "object",
843
875
  "properties": {
@@ -1082,6 +1114,74 @@ pub fn all_tool_definitions() -> Vec<ToolDefinition> {
1082
1114
  }
1083
1115
  }),
1084
1116
  },
1117
+ // ---- Session fork/merge tools ----
1118
+ ToolDefinition {
1119
+ name: "handoff_fork_session".to_string(),
1120
+ description: "Fork a new session from an existing one. Inherits decisions, context_pointers, references, and handoff_notes by default. The forked session becomes active with parent_session_id set.".to_string(),
1121
+ input_schema: json!({
1122
+ "type": "object",
1123
+ "properties": {
1124
+ "project_dir": {
1125
+ "type": "string",
1126
+ "description": "Project directory path. Defaults to current working directory."
1127
+ },
1128
+ "source_session_id": {
1129
+ "type": "string",
1130
+ "description": "Session ID to fork from (active, paused, or closed)."
1131
+ },
1132
+ "summary": {
1133
+ "type": "string",
1134
+ "description": "Summary for the new forked session."
1135
+ },
1136
+ "label": {
1137
+ "type": "string",
1138
+ "description": "Short human-readable label for the forked session."
1139
+ },
1140
+ "timeline": {
1141
+ "type": "string",
1142
+ "description": "Timeline label. Defaults to the source session's timeline."
1143
+ },
1144
+ "inherit": {
1145
+ "type": "array",
1146
+ "description": "Fields to inherit from the source. Default: [\"decisions\", \"context_pointers\", \"references\", \"handoff_notes\", \"environment\"]. Available: decisions, context_pointers, references, handoff_notes, environment, blockers, checklist.",
1147
+ "items": { "type": "string" }
1148
+ },
1149
+ "related_task_ids": {
1150
+ "type": "array",
1151
+ "description": "Task IDs the forked session will work on.",
1152
+ "items": { "type": "string" }
1153
+ }
1154
+ },
1155
+ "required": ["source_session_id", "summary"]
1156
+ }),
1157
+ },
1158
+ ToolDefinition {
1159
+ name: "handoff_merge_sessions".to_string(),
1160
+ description: "Merge multiple sessions into one. Combines decisions, notes, references, and context_pointers. Detects duplicate decisions as conflicts. Source sessions (except the target) are closed by default.".to_string(),
1161
+ input_schema: json!({
1162
+ "type": "object",
1163
+ "properties": {
1164
+ "project_dir": {
1165
+ "type": "string",
1166
+ "description": "Project directory path. Defaults to current working directory."
1167
+ },
1168
+ "source_session_ids": {
1169
+ "type": "array",
1170
+ "description": "Session IDs to merge (must include at least 2).",
1171
+ "items": { "type": "string" }
1172
+ },
1173
+ "target_session_id": {
1174
+ "type": "string",
1175
+ "description": "Which source session becomes the merge target (must be one of source_session_ids)."
1176
+ },
1177
+ "close_sources": {
1178
+ "type": "boolean",
1179
+ "description": "Close non-target source sessions after merge. Default: true."
1180
+ }
1181
+ },
1182
+ "required": ["source_session_ids", "target_session_id"]
1183
+ }),
1184
+ },
1085
1185
  // ---- Timer coordination tools ----
1086
1186
  ToolDefinition {
1087
1187
  name: "handoff_timer_start".to_string(),
@@ -90,6 +90,9 @@ pub struct SettingsConfig {
90
90
  /// Idle timeout in minutes for MCP fallback timer. Default 10.
91
91
  #[serde(default = "default_timer_idle_timeout_minutes")]
92
92
  pub timer_idle_timeout_minutes: u64,
93
+ /// Allow multiple active sessions simultaneously. Default false (single-active).
94
+ #[serde(default)]
95
+ pub multi_session: bool,
93
96
  #[serde(default)]
94
97
  pub custom_fields: HashMap<String, toml::Value>,
95
98
  }
@@ -295,6 +298,7 @@ impl Default for SettingsConfig {
295
298
  timer_provider: default_timer_provider(),
296
299
  timer_authority_ttl_secs: default_timer_authority_ttl_secs(),
297
300
  timer_idle_timeout_minutes: default_timer_idle_timeout_minutes(),
301
+ multi_session: false,
298
302
  custom_fields: HashMap::new(),
299
303
  }
300
304
  }
@@ -311,6 +315,10 @@ impl Default for DashboardConfig {
311
315
 
312
316
  impl Config {
313
317
  pub fn new(name: &str, description: &str) -> Self {
318
+ let settings = SettingsConfig {
319
+ multi_session: true,
320
+ ..SettingsConfig::default()
321
+ };
314
322
  Self {
315
323
  project: ProjectConfig {
316
324
  name: name.to_string(),
@@ -320,7 +328,7 @@ impl Config {
320
328
  Some(description.to_string())
321
329
  },
322
330
  },
323
- settings: SettingsConfig::default(),
331
+ settings,
324
332
  dashboard: DashboardConfig::default(),
325
333
  started_at: None,
326
334
  schedule_mode: None,
@@ -32,6 +32,14 @@ pub struct SessionData {
32
32
  pub context_pointers: Vec<Value>,
33
33
  #[serde(default, skip_serializing_if = "Option::is_none")]
34
34
  pub environment: Option<Value>,
35
+ #[serde(default, skip_serializing_if = "Option::is_none")]
36
+ pub timeline: Option<String>,
37
+ #[serde(default, skip_serializing_if = "Option::is_none")]
38
+ pub label: Option<String>,
39
+ #[serde(default, skip_serializing_if = "Option::is_none")]
40
+ pub parent_session_id: Option<String>,
41
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
42
+ pub related_task_ids: Vec<String>,
35
43
  }
36
44
 
37
45
  pub fn generate_session_id() -> String {
@@ -169,13 +177,12 @@ pub fn read_active_sessions(sessions_dir: &Path) -> Result<Vec<SessionData>> {
169
177
  read_sessions_by_status(sessions_dir, "active")
170
178
  }
171
179
 
172
- /// Append `decision` (a decision object: {decision, reason?, confidence?}) to the
173
- /// `decisions` list of every active session file. Returns the number of sessions
174
- /// updated. Used by tools like auto_schedule to record applied changes so the
175
- /// audit trail lives with the session, not just the tool response.
180
+ /// Append `decision` to active session(s). When `target_session_id` is Some,
181
+ /// only the matching session is updated; otherwise all active sessions are updated.
176
182
  pub fn append_decision_to_active_sessions(
177
183
  sessions_dir: &Path,
178
184
  decision: serde_json::Value,
185
+ target_session_id: Option<&str>,
179
186
  ) -> Result<usize> {
180
187
  let suffix = ".active.json";
181
188
  if !sessions_dir.exists() {
@@ -194,6 +201,14 @@ pub fn append_decision_to_active_sessions(
194
201
  .with_context(|| format!("Failed to read session: {}", path.display()))?;
195
202
  let mut data: SessionData = serde_json::from_str(&content)
196
203
  .with_context(|| format!("Failed to parse session: {}", path.display()))?;
204
+
205
+ if let Some(tid) = target_session_id {
206
+ let file_id = data.id.as_deref().unwrap_or("");
207
+ if !ids_match(file_id, tid) {
208
+ continue;
209
+ }
210
+ }
211
+
197
212
  data.decisions.push(decision.clone());
198
213
  let updated = serde_json::to_string_pretty(&data).context("Failed to serialize session")?;
199
214
  crate::storage::atomic_write(&path, updated.as_bytes())
@@ -369,6 +384,15 @@ fn apply_session_updates(data: &mut SessionData, updates: &SessionData) {
369
384
  if updates.environment.is_some() {
370
385
  data.environment = updates.environment.clone();
371
386
  }
387
+ if updates.timeline.is_some() {
388
+ data.timeline = updates.timeline.clone();
389
+ }
390
+ if updates.label.is_some() {
391
+ data.label = updates.label.clone();
392
+ }
393
+ if !updates.related_task_ids.is_empty() {
394
+ data.related_task_ids = updates.related_task_ids.clone();
395
+ }
372
396
  }
373
397
 
374
398
  fn find_and_update_active_session(
@@ -467,6 +491,277 @@ pub fn update_active_session(
467
491
  find_and_update_active_session(sessions_dir, session_id, updates, None)
468
492
  }
469
493
 
494
+ pub fn read_session_by_id(sessions_dir: &Path, session_id: &str) -> Result<Option<SessionData>> {
495
+ if !sessions_dir.exists() {
496
+ return Ok(None);
497
+ }
498
+
499
+ let mut matches: Vec<(SessionData, String)> = Vec::new();
500
+
501
+ for entry in std::fs::read_dir(sessions_dir)? {
502
+ let entry = entry?;
503
+ let name = entry.file_name().to_string_lossy().to_string();
504
+ if !name.ends_with(".json") {
505
+ continue;
506
+ }
507
+ let content = std::fs::read_to_string(entry.path())
508
+ .with_context(|| format!("Failed to read session: {}", entry.path().display()))?;
509
+ let data: SessionData = serde_json::from_str(&content)
510
+ .with_context(|| format!("Failed to parse session: {}", entry.path().display()))?;
511
+
512
+ let file_id = data.id.as_deref().unwrap_or("");
513
+ let resolved_id = if file_id.is_empty() {
514
+ synthesize_id_from_filename(&name)
515
+ } else {
516
+ file_id.to_string()
517
+ };
518
+
519
+ if ids_match(&resolved_id, session_id) {
520
+ matches.push((data, resolved_id));
521
+ }
522
+ }
523
+
524
+ if matches.len() > 1 {
525
+ let candidates: Vec<&str> = matches.iter().map(|(_, id)| id.as_str()).collect();
526
+ anyhow::bail!(
527
+ "Ambiguous session_id '{}': matched {} sessions ({}). Provide a more specific ID.",
528
+ session_id,
529
+ matches.len(),
530
+ candidates.join(", ")
531
+ );
532
+ }
533
+
534
+ Ok(matches.into_iter().next().map(|(data, _)| data))
535
+ }
536
+
537
+ pub fn fork_session(
538
+ sessions_dir: &Path,
539
+ source: &SessionData,
540
+ summary: &str,
541
+ label: Option<&str>,
542
+ timeline: Option<&str>,
543
+ related_task_ids: Vec<String>,
544
+ inherit: &[&str],
545
+ ) -> Result<SessionData> {
546
+ let source_id = source
547
+ .id
548
+ .as_deref()
549
+ .ok_or_else(|| anyhow::anyhow!("Source session has no ID"))?;
550
+
551
+ let mut forked = SessionData {
552
+ version: source.version,
553
+ id: Some(generate_session_id()),
554
+ ended_at: None,
555
+ summary: summary.to_string(),
556
+ branch: None,
557
+ commit: None,
558
+ dirty_files: Vec::new(),
559
+ decisions: Vec::new(),
560
+ blockers: Vec::new(),
561
+ checklist: Vec::new(),
562
+ handoff_notes: Vec::new(),
563
+ references: Vec::new(),
564
+ context_pointers: Vec::new(),
565
+ environment: None,
566
+ timeline: timeline
567
+ .map(String::from)
568
+ .or_else(|| source.timeline.clone()),
569
+ label: label.map(String::from),
570
+ parent_session_id: Some(source_id.to_string()),
571
+ related_task_ids,
572
+ };
573
+
574
+ for field in inherit {
575
+ match *field {
576
+ "decisions" => forked.decisions = source.decisions.clone(),
577
+ "context_pointers" => forked.context_pointers = source.context_pointers.clone(),
578
+ "references" => forked.references = source.references.clone(),
579
+ "handoff_notes" => forked.handoff_notes = source.handoff_notes.clone(),
580
+ "environment" => forked.environment = source.environment.clone(),
581
+ "blockers" => forked.blockers = source.blockers.clone(),
582
+ "checklist" => forked.checklist = source.checklist.clone(),
583
+ _ => {}
584
+ }
585
+ }
586
+
587
+ write_session_with_status(sessions_dir, &forked, "active")?;
588
+ Ok(forked)
589
+ }
590
+
591
+ pub fn merge_sessions(
592
+ sessions_dir: &Path,
593
+ source_ids: &[&str],
594
+ target_id: &str,
595
+ close_sources: bool,
596
+ ) -> Result<MergeResult> {
597
+ let mut sources: Vec<SessionData> = Vec::new();
598
+ for sid in source_ids {
599
+ let session = read_session_by_id(sessions_dir, sid)?
600
+ .ok_or_else(|| anyhow::anyhow!("Source session not found: {sid}"))?;
601
+ sources.push(session);
602
+ }
603
+
604
+ let mut target = read_session_by_id(sessions_dir, target_id)?
605
+ .ok_or_else(|| anyhow::anyhow!("Target session not found: {target_id}"))?;
606
+
607
+ let target_actual_id = target.id.clone().unwrap_or_default();
608
+
609
+ let mut merged_decisions = 0usize;
610
+ let mut merged_notes = 0usize;
611
+ let mut merged_references = 0usize;
612
+ let mut merged_context_pointers = 0usize;
613
+ let mut conflicts = Vec::new();
614
+ let mut closed_sessions = Vec::new();
615
+
616
+ for source in &sources {
617
+ let source_actual_id = source.id.as_deref().unwrap_or("");
618
+ if source_actual_id == target_actual_id {
619
+ continue;
620
+ }
621
+
622
+ for d in &source.decisions {
623
+ let decision_text = d.get("decision").and_then(|v| v.as_str()).unwrap_or("");
624
+ let already_exists = target.decisions.iter().any(|td| {
625
+ td.get("decision").and_then(|v| v.as_str()).unwrap_or("") == decision_text
626
+ });
627
+ if already_exists {
628
+ conflicts.push(MergeConflict {
629
+ conflict_type: "decision_conflict".to_string(),
630
+ description: format!("Duplicate decision: {decision_text}"),
631
+ session_a: target_actual_id.clone(),
632
+ session_b: source_actual_id.to_string(),
633
+ });
634
+ } else {
635
+ target.decisions.push(d.clone());
636
+ merged_decisions += 1;
637
+ }
638
+ }
639
+
640
+ for n in &source.handoff_notes {
641
+ target.handoff_notes.push(n.clone());
642
+ merged_notes += 1;
643
+ }
644
+
645
+ for r in &source.references {
646
+ let label = r.get("label").and_then(|v| v.as_str()).unwrap_or("");
647
+ let already_exists = target
648
+ .references
649
+ .iter()
650
+ .any(|tr| tr.get("label").and_then(|v| v.as_str()).unwrap_or("") == label);
651
+ if !already_exists {
652
+ target.references.push(r.clone());
653
+ merged_references += 1;
654
+ }
655
+ }
656
+
657
+ for cp in &source.context_pointers {
658
+ let path = cp.get("path").and_then(|v| v.as_str()).unwrap_or("");
659
+ let already_exists = target
660
+ .context_pointers
661
+ .iter()
662
+ .any(|tcp| tcp.get("path").and_then(|v| v.as_str()).unwrap_or("") == path);
663
+ if !already_exists {
664
+ target.context_pointers.push(cp.clone());
665
+ merged_context_pointers += 1;
666
+ }
667
+ }
668
+
669
+ for task_id in &source.related_task_ids {
670
+ if !target.related_task_ids.contains(task_id) {
671
+ target.related_task_ids.push(task_id.clone());
672
+ }
673
+ }
674
+
675
+ if close_sources {
676
+ if let Some(path) = close_session_by_id(sessions_dir, source_actual_id)? {
677
+ let _ = path;
678
+ closed_sessions.push(source_actual_id.to_string());
679
+ }
680
+ }
681
+ }
682
+
683
+ update_session_in_place(sessions_dir, &target_actual_id, &target)?;
684
+
685
+ Ok(MergeResult {
686
+ merged_session_id: target_actual_id,
687
+ merged_decisions,
688
+ merged_notes,
689
+ merged_references,
690
+ merged_context_pointers,
691
+ conflicts,
692
+ closed_sessions,
693
+ })
694
+ }
695
+
696
+ fn update_session_in_place(
697
+ sessions_dir: &Path,
698
+ session_id: &str,
699
+ updated: &SessionData,
700
+ ) -> Result<()> {
701
+ if !sessions_dir.exists() {
702
+ anyhow::bail!("Sessions directory not found");
703
+ }
704
+
705
+ let mut matches: Vec<(PathBuf, String)> = Vec::new();
706
+
707
+ for entry in std::fs::read_dir(sessions_dir)? {
708
+ let entry = entry?;
709
+ let name = entry.file_name().to_string_lossy().to_string();
710
+ if !name.ends_with(".json") {
711
+ continue;
712
+ }
713
+ let content = std::fs::read_to_string(entry.path())?;
714
+ let data: SessionData = serde_json::from_str(&content)?;
715
+ let file_id = data.id.as_deref().unwrap_or("");
716
+ let resolved_id = if file_id.is_empty() {
717
+ synthesize_id_from_filename(&name)
718
+ } else {
719
+ file_id.to_string()
720
+ };
721
+ if ids_match(&resolved_id, session_id) {
722
+ matches.push((entry.path(), resolved_id));
723
+ }
724
+ }
725
+
726
+ if matches.len() > 1 {
727
+ let candidates: Vec<&str> = matches.iter().map(|(_, id)| id.as_str()).collect();
728
+ anyhow::bail!(
729
+ "Ambiguous session_id '{}': matched {} sessions ({}). Provide a more specific ID.",
730
+ session_id,
731
+ matches.len(),
732
+ candidates.join(", ")
733
+ );
734
+ }
735
+
736
+ if let Some((path, _)) = matches.into_iter().next() {
737
+ let serialized =
738
+ serde_json::to_string_pretty(updated).context("Failed to serialize session")?;
739
+ crate::storage::atomic_write(path, serialized.as_bytes())?;
740
+ return Ok(());
741
+ }
742
+
743
+ anyhow::bail!("Session not found for in-place update: {session_id}")
744
+ }
745
+
746
+ #[derive(Debug)]
747
+ pub struct MergeConflict {
748
+ pub conflict_type: String,
749
+ pub description: String,
750
+ pub session_a: String,
751
+ pub session_b: String,
752
+ }
753
+
754
+ #[derive(Debug)]
755
+ pub struct MergeResult {
756
+ pub merged_session_id: String,
757
+ pub merged_decisions: usize,
758
+ pub merged_notes: usize,
759
+ pub merged_references: usize,
760
+ pub merged_context_pointers: usize,
761
+ pub conflicts: Vec<MergeConflict>,
762
+ pub closed_sessions: Vec<String>,
763
+ }
764
+
470
765
  pub fn enforce_history_limit(sessions_dir: &Path, limit: u32) -> Result<u32> {
471
766
  if !sessions_dir.exists() {
472
767
  return Ok(0);