Class: Ace::Docs::Molecules::ChangeDetector

Inherits:
Object
  • Object
show all
Defined in:
lib/ace/docs/molecules/change_detector.rb

Overview

Analyzes git history and file changes for documents Delegates diff operations to ace-git for consistency

Class Method Summary collapse

Class Method Details

.default_since_dateObject



237
238
239
# File 'lib/ace/docs/molecules/change_detector.rb', line 237

def self.default_since_date
  (Date.today - 7).strftime("%Y-%m-%d")
end

.detect_renames(since: nil) ⇒ Array<Hash>

Check if files have been renamed or moved

Parameters:

  • since (String) (defaults to: nil)

    Date or commit to check from

Returns:

  • (Array<Hash>)

    List of renamed/moved files



178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
# File 'lib/ace/docs/molecules/change_detector.rb', line 178

def self.detect_renames(since: nil)
  since_param = since || default_since_date
  since_ref = resolve_since_to_commit(since_param)
  cmd = "git diff --name-status --diff-filter=R #{since_ref}..HEAD"

  stdout = execute_git_command(cmd)
  return [] if stdout.strip.empty?

  renames = []
  stdout.each_line do |line|
    if line.start_with?("R")
      parts = line.strip.split(/\s+/, 3)
      if parts.length >= 3
        old_path, new_path = parts[1], parts[2]
        renames << {old: old_path, new: new_path}
      end
    end
  end

  renames
end

.determine_since(document, since) ⇒ Object



211
212
213
214
215
216
217
218
219
220
221
222
# File 'lib/ace/docs/molecules/change_detector.rb', line 211

def self.determine_since(document, since)
  # If explicit since provided, use it
  return format_since(since) if since

  # Use document's last updated date if available
  if document.last_updated
    return document.last_updated.strftime("%Y-%m-%d")
  end

  # Default to 7 days ago
  default_since_date
end

.empty_diff_resultObject



202
203
204
205
206
207
208
209
# File 'lib/ace/docs/molecules/change_detector.rb', line 202

def self.empty_diff_result
  {
    document_path: nil,
    diff: "",
    has_changes: false,
    timestamp: Time.now.iso8601
  }
end

.execute_git_command(cmd) ⇒ String

Execute git command (protected for testing)

Parameters:

  • cmd (String, Array)

    Git command to execute

Returns:

  • (String)

    Command output or empty string on failure



378
379
380
381
382
383
384
385
# File 'lib/ace/docs/molecules/change_detector.rb', line 378

def self.execute_git_command(cmd)
  if cmd.is_a?(Array)
    stdout, _stderr, status = Open3.capture3(*cmd, chdir: git_root)
  else
    stdout, _stderr, status = Open3.capture3(cmd, chdir: git_root)
  end
  status.success? ? stdout : ""
end

.format_diff_for_saving(diff_result) ⇒ Object



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
# File 'lib/ace/docs/molecules/change_detector.rb', line 323

def self.format_diff_for_saving(diff_result)
  content = []
  content << "# Diff Analysis Report"
  content << "Generated: #{diff_result[:timestamp]}"
  content << "Since: #{diff_result[:since]}"
  content << ""

  if diff_result[:document_diffs]
    # Multiple documents
    content << "## Summary"
    content << "- Total documents analyzed: #{diff_result[:total_documents]}"
    content << "- Documents with changes: #{diff_result[:documents_with_changes]}"
    content << ""

    diff_result[:document_diffs].each do |doc_diff|
      doc = doc_diff[:document]
      content << "## #{doc.display_name}"
      content << "- Type: #{doc.doc_type}"
      content << "- Purpose: #{doc.purpose}"
      content << "- Has changes: #{doc_diff[:has_changes] ? "Yes" : "No"}"
      content << ""

      if doc_diff[:has_changes]
        content << "### Relevant Changes"
        content << "```diff"
        content << doc_diff[:diff]
        content << "```"
      else
        content << "No relevant changes detected."
      end
      content << ""
    end
  else
    # Single document
    content << "## Document: #{diff_result[:document_path]}"
    content << "- Type: #{diff_result[:document_type]}"
    content << "- Has changes: #{diff_result[:has_changes] ? "Yes" : "No"}"
    content << ""

    if diff_result[:has_changes]
      content << "### Git Diff"
      content << "```diff"
      content << diff_result[:diff]
      content << "```"
    else
      content << "No changes detected."
    end
  end

  content.join("\n")
end

.format_since(since) ⇒ Object



224
225
226
227
228
229
230
231
232
233
234
235
# File 'lib/ace/docs/molecules/change_detector.rb', line 224

def self.format_since(since)
  case since
  when Date
    since.strftime("%Y-%m-%d")
  when Time
    since.strftime("%Y-%m-%d")
  when String
    since
  else
    default_since_date
  end
end

.generate_batch_diff(documents, since, options = {}) ⇒ String

Generate batch diff for analysis

Parameters:

  • documents (Array<Document>)

    Documents to analyze

  • since (String)

    Time range for diff

  • options (Hash) (defaults to: {})

    Options for diff generation

Returns:

  • (String)

    Raw git diff



135
136
137
138
# File 'lib/ace/docs/molecules/change_detector.rb', line 135

def self.generate_batch_diff(documents, since, options = {})
  # Generate the full codebase diff for the time period
  generate_git_diff(since, options)
end

.generate_git_diff(since, options = {}) ⇒ Object



241
242
243
244
245
246
247
248
249
250
251
252
253
# File 'lib/ace/docs/molecules/change_detector.rb', line 241

def self.generate_git_diff(since, options = {})
  # Warn about deprecated option keys (migrated from ace-git-diff to ace-git)
  warn_deprecated_options(options)

  # Delegate to ace-git for consistent filtering and configuration
  diff_options = build_diff_options(since, options)

  result = Ace::Git::Organisms::DiffOrchestrator.generate(diff_options)
  result.content
rescue => e
  warn "ace-git failed: #{e.message}" if ENV["DEBUG"]
  ""
end

.get_diff_for_document(document, since: nil, options: {}) ⇒ Hash

Get git diff for a document since a specific date or commit

Parameters:

  • document (Document)

    The document to analyze

  • since (String, Date) (defaults to: nil)

    Date or commit to diff from

  • options (Hash) (defaults to: {})

    Options for diff generation

Returns:

  • (Hash)

    Diff result with content and metadata For single subject: returns hash with :diff key containing single diff For multi-subject: returns hash with :diffs key containing => content



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
# File 'lib/ace/docs/molecules/change_detector.rb', line 24

def self.get_diff_for_document(document, since: nil, options: {})
  return empty_diff_result unless document.path

  # Determine the since parameter
  since_param = determine_since(document, since)

  # Check if document has multi-subject configuration
  if document.multi_subject?
    # Generate separate diffs for each subject
    diffs_hash = get_diffs_for_subjects(document, since_param, options)

    {
      document_path: document.path,
      document_type: document.doc_type,
      since: since_param,
      diffs: diffs_hash,
      multi_subject: true,
      has_changes: diffs_hash.values.any? { |diff| !diff.strip.empty? },
      timestamp: Time.now.iso8601,
      options: options
    }
  else
    # Single subject - backward compatible behavior
    filters = document.subject_diff_filters
    if filters && !filters.empty?
      options = options.merge(paths: filters)
    end

    diff_content = generate_git_diff(since_param, options)

    {
      document_path: document.path,
      document_type: document.doc_type,
      since: since_param,
      diff: diff_content,
      multi_subject: false,
      has_changes: !diff_content.strip.empty?,
      timestamp: Time.now.iso8601,
      options: options
    }
  end
end

.get_diff_for_documents(documents, since: nil, options: {}) ⇒ Hash

Get combined diff for multiple documents

Parameters:

  • documents (Array<Document>)

    Documents to analyze

  • since (String, Date) (defaults to: nil)

    Date or commit to diff from

  • options (Hash) (defaults to: {})

    Options for diff generation

Returns:

  • (Hash)

    Combined diff results



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
# File 'lib/ace/docs/molecules/change_detector.rb', line 98

def self.get_diff_for_documents(documents, since: nil, options: {})
  # Get document-specific diffs with subject filtering
  since_param = since || default_since_date

  document_diffs = documents.map do |doc|
    # Extract subject diff filters for this document
    doc_options = options.dup
    filters = doc.subject_diff_filters
    if filters && !filters.empty?
      doc_options = doc_options.merge(paths: filters)
    end

    # Get filtered diff for this document
    diff_content = generate_git_diff(since_param, doc_options)

    {
      document: doc,
      diff: diff_content,
      has_changes: !diff_content.strip.empty?
    }
  end

  {
    total_documents: documents.size,
    documents_with_changes: document_diffs.count { |d| d[:has_changes] },
    since: since_param,
    timestamp: Time.now.iso8601,
    options: options,
    document_diffs: document_diffs
  }
end

.get_diffs_for_subjects(document, since, options = {}) ⇒ Hash

Generate diffs for multiple subjects

Parameters:

  • document (Document)

    The document with multi-subject configuration

  • since (String)

    Date or commit to diff from

  • options (Hash) (defaults to: {})

    Base options for diff generation

Returns:

  • (Hash)

    Hash mapping subject names to diff content => diff_string



72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
# File 'lib/ace/docs/molecules/change_detector.rb', line 72

def self.get_diffs_for_subjects(document, since, options = {})
  subject_configs = document.subject_configurations

  result = {}
  subject_configs.each do |subject|
    name = subject[:name]
    filters = subject[:filters]

    # Build options for this subject
    subject_options = options.merge(paths: filters)

    # Generate diff for this subject
    diff_content = generate_git_diff(since, subject_options)

    # Store diff (even if empty - caller can decide whether to keep)
    result[name] = diff_content
  end

  result
end

.git_rootObject



315
316
317
318
319
320
321
# File 'lib/ace/docs/molecules/change_detector.rb', line 315

def self.git_root
  @git_root ||= begin
    stdout, _, status = Open3.capture3("git rev-parse --show-toplevel")
    # Use ProjectRootFinder as fallback to support both main repos and git worktrees
    status.success? ? stdout.strip : Ace::Support::Fs::Molecules::ProjectRootFinder.find_or_current
  end
end

.resolve_since_to_commit(since) ⇒ Object



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
# File 'lib/ace/docs/molecules/change_detector.rb', line 288

def self.resolve_since_to_commit(since)
  # If it looks like a commit SHA, use as-is
  return since if /^[0-9a-f]{7,40}$/i.match?(since)

  # It's a date - find the first commit since that date
  cmd = "git log --since=\"#{since}\" --format=%H --reverse --all"
  stdout = execute_git_command(cmd)

  if !stdout.strip.empty?
    first_commit = stdout.strip.split("\n").first

    # Get parent of first commit to include all changes since date
    parent_cmd = "git rev-parse #{first_commit}~1 2>/dev/null"
    parent_stdout = execute_git_command(parent_cmd)

    if !parent_stdout.strip.empty?
      return parent_stdout.strip
    else
      # First commit has no parent (initial commit), use it directly
      return first_commit
    end
  end

  # Fallback: use date string and let git handle it
  since
end

.save_diff_to_cache(diff_result) ⇒ String

Save diff analysis to cache folder with session structure

Parameters:

  • diff_result (Hash)

    Diff analysis result

Returns:

  • (String)

    Path to saved analysis file



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
# File 'lib/ace/docs/molecules/change_detector.rb', line 143

def self.save_diff_to_cache(diff_result)
  cache_dir = ".ace-local/docs"
  compact_id = Ace::B36ts.encode(Time.now)
  session_dir = File.join(cache_dir, "diff-#{compact_id}")

  FileUtils.mkdir_p(session_dir)

  # Save raw git diff
  if diff_result[:diff] && !diff_result[:diff].empty?
    raw_diff_path = File.join(session_dir, "repo-diff.diff")
    File.write(raw_diff_path, diff_result[:diff])
  end

  # Save formatted analysis report
  analysis_path = File.join(session_dir, "analysis.md")
  content = format_diff_for_saving(diff_result)
  File.write(analysis_path, content)

  # Save metadata
   = File.join(session_dir, "metadata.yml")
   = {
    "generated" => diff_result[:timestamp],
    "since" => diff_result[:since],
    "document_count" => diff_result[:total_documents] || 1,
    "has_changes" => diff_result[:has_changes] || (diff_result[:documents_with_changes] || 0) > 0,
    "options" => diff_result[:options] || {}
  }
  File.write(, .to_yaml)

  analysis_path
end