Module: Textus::Doctor

Defined in:
lib/textus/doctor.rb

Overview

Health check for a Textus store. Returns a JSON-friendly Hash envelope with an ‘issues` array and a summary. Each issue is a Hash with `code`, `level`, `subject`, `message`, and optionally `fix`.

Constant Summary collapse

LEVELS =

rubocop:disable Metrics/ModuleLength – 9 built-in checks + extension dispatch

%w[error warning info].freeze
DOCTOR_CHECK_TIMEOUT_SECONDS =
2
ALL_CHECKS =
%w[
  manifest_files schemas templates extensions illegal_keys
  sentinels audit_log unowned_schema_fields schema_violations
].freeze

Class Method Summary collapse

Class Method Details

.check_audit_log(store) ⇒ Object



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
# File 'lib/textus/doctor.rb', line 211

def check_audit_log(store)
  out = []
  path = File.join(store.root, "audit.log")
  return out unless File.exist?(path)

  File.foreach(path).with_index(1) do |line, lineno| # rubocop:disable Metrics/BlockLength
    stripped = line.chomp
    next if stripped.empty?

    if stripped.start_with?("{")
      begin
        JSON.parse(stripped)
      rescue JSON::ParserError => e
        out << {
          "code" => "audit.parse_error",
          "level" => "warning",
          "subject" => "#{path}:#{lineno}",
          "message" => "audit log line #{lineno} is invalid JSON: #{e.message}",
          "fix" => "inspect #{path} at line #{lineno} and remove the corrupted row",
        }
      end
    else
      # Legacy TSV: minimum 6 fields. Removed in 0.6.
      fields = stripped.split("\t")
      next if fields.length >= 6

      out << {
        "code" => "audit.parse_error",
        "level" => "warning",
        "subject" => "#{path}:#{lineno}",
        "message" => "audit log line #{lineno} has #{fields.length} fields " \
                     "(expected >=6 for legacy TSV; consider migrating to NDJSON)",
        "fix" => "inspect #{path} at line #{lineno} and remove the corrupted row",
      }
    end
  end
  out
end

.check_extensions(store) ⇒ Object



114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
# File 'lib/textus/doctor.rb', line 114

def check_extensions(store)
  out = []
  dir = File.join(store.root, "extensions")
  return out unless File.directory?(dir)

  Dir.glob(File.join(dir, "*.rb")).sort.each do |f| # rubocop:disable Lint/RedundantDirGlobSort
    registry = ExtensionRegistry.new
    Textus.with_registry(registry) do
      load(f)
    end
  rescue StandardError, ScriptError => e
    out << {
      "code" => "extension.load_failed",
      "level" => "error",
      "subject" => File.basename(f),
      "message" => "#{e.class}: #{e.message}",
      "fix" => "open #{f} and fix the syntax/load error",
    }
  end
  out
end

.check_illegal_keys(store) ⇒ Object



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
# File 'lib/textus/doctor.rb', line 136

def check_illegal_keys(store)
  out = []
  store.manifest.entries.each do |entry|
    next unless entry.nested

    base = File.join(store.root, "zones", entry.path)
    next unless File.directory?(base)

    walk_nested(base) do |abs_path, is_dir|
      basename = File.basename(abs_path)
      stem = is_dir ? basename : basename.sub(/#{Regexp.escape(File.extname(basename))}\z/, "")
      next if stem.match?(Manifest::KEY_SEGMENT)

      proposed = Textus::MigrateKeys.normalize(stem)
      out << {
        "code" => "key.illegal",
        "level" => "error",
        "subject" => abs_path,
        "path" => abs_path,
        "proposed_key" => proposed,
        "message" => "illegal key segment '#{stem}' at #{abs_path}",
        "fix" => "run 'textus migrate-keys --dry-run' then '--write' to rename to '#{proposed}'",
      }
    end
  end
  out
end

.check_manifest_files(store) ⇒ Object

— Checks ———————————————————–



56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
# File 'lib/textus/doctor.rb', line 56

def check_manifest_files(store)
  out = []
  store.manifest.entries.each do |entry|
    next if entry.nested

    path = leaf_path_for(store, entry)
    next if File.exist?(path)

    out << {
      "code" => "manifest.missing_file",
      "level" => "info",
      "subject" => entry.key,
      "message" => "declared entry has no file on disk at #{path}",
      "fix" => "create the entry with 'textus put #{entry.key} --stdin --as=<role>' " \
               "(or leave empty if not yet authored)",
    }
  end
  out
end

.check_schema_violations(store) ⇒ Object



277
278
279
280
281
282
283
284
285
286
287
288
289
290
# File 'lib/textus/doctor.rb', line 277

def check_schema_violations(store)
  res = store.validate_all
  res["violations"].map do |v|
    fix = v["expected"] &&
          "field '#{v["field"]}' should be written by '#{v["expected"]}' (last writer: #{v["last_writer"]})"
    {
      "code" => v["code"],
      "level" => "error",
      "subject" => v["key"],
      "message" => v["message"] || "#{v["code"]} on #{v["key"]}",
      "fix" => fix,
    }.compact
  end
end

.check_schemas(store) ⇒ Object



76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
# File 'lib/textus/doctor.rb', line 76

def check_schemas(store)
  out = []
  store.manifest.entries.each do |entry|
    next if entry.schema.nil?

    sp = File.join(store.root, "schemas", "#{entry.schema}.yaml")
    next if File.exist?(sp)

    out << {
      "code" => "schema.missing",
      "level" => "error",
      "subject" => entry.key,
      "message" => "schema '#{entry.schema}' not found at #{sp}",
      "fix" => "create the schema file or run 'textus schema-init #{entry.schema} --from=<key>'",
    }
  end
  out
end

.check_sentinels(store) ⇒ Object



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
# File 'lib/textus/doctor.rb', line 164

def check_sentinels(store)
  out = []
  dir = File.join(store.root, "sentinels")
  return out unless File.directory?(dir)

  Dir.glob(File.join(dir, "**", "*.textus-managed.json")).each do |sp| # rubocop:disable Metrics/BlockLength
    begin
      data = JSON.parse(File.read(sp))
    rescue JSON::ParserError => e
      out << {
        "code" => "sentinel.parse_error",
        "level" => "warning",
        "subject" => sp,
        "message" => "sentinel is not valid JSON: #{e.message}",
        "fix" => "delete #{sp} and re-run 'textus build' to regenerate",
      }
      next
    end

    target = data["target"]
    recorded_sha = data["sha256"]

    if target.nil? || !File.exist?(target)
      out << {
        "code" => "sentinel.orphan",
        "level" => "warning",
        "subject" => sp,
        "message" => "sentinel target #{target.inspect} no longer exists",
        "fix" => "delete #{sp} (the published file is gone) or restore the target",
      }
      next
    end

    current_sha = Digest::SHA256.hexdigest(File.binread(target))
    next if recorded_sha.nil? || current_sha == recorded_sha

    out << {
      "code" => "sentinel.drift",
      "level" => "warning",
      "subject" => target,
      "message" => "published file at #{target} was modified out-of-band",
      "fix" => "re-run 'textus build' to overwrite, or copy the manual edit back into the store source",
    }
  end
  out
end

.check_templates(store) ⇒ Object



95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
# File 'lib/textus/doctor.rb', line 95

def check_templates(store)
  out = []
  store.manifest.entries.each do |entry|
    next if entry.template.nil?

    tp = File.join(store.root, "templates", entry.template)
    next if File.exist?(tp)

    out << {
      "code" => "template.missing",
      "level" => "error",
      "subject" => entry.key,
      "message" => "template '#{entry.template}' not found at #{tp}",
      "fix" => "create the file at #{tp} or update the entry's template: field",
    }
  end
  out
end

.check_unowned_schema_fields(store) ⇒ Object



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
# File 'lib/textus/doctor.rb', line 250

def check_unowned_schema_fields(store)
  out = []
  dir = File.join(store.root, "schemas")
  return out unless File.directory?(dir)

  Dir.glob(File.join(dir, "*.yaml")).sort.each do |sp| # rubocop:disable Lint/RedundantDirGlobSort
    schema = begin
      Schema.load(sp)
    rescue StandardError
      next
    end
    unowned = schema.fields.each_with_object([]) do |(name, spec), acc|
      acc << name if spec.is_a?(Hash) && spec["maintained_by"].nil?
    end
    next if unowned.empty?

    out << {
      "code" => "schema.unowned_fields",
      "level" => "info",
      "subject" => schema.name || File.basename(sp, ".yaml"),
      "message" => "schema has fields without maintained_by: #{unowned.join(", ")}",
      "fix" => "add 'maintained_by: <role>' to each field in #{sp} (optional but recommended)",
    }
  end
  out
end

.fail_issue(name, code:, message:, fix:) ⇒ Object



319
320
321
322
323
324
325
326
327
# File 'lib/textus/doctor.rb', line 319

def fail_issue(name, code:, message:, fix:)
  {
    "code" => code,
    "level" => "error",
    "subject" => name.to_s,
    "message" => message,
    "fix" => fix,
  }
end

.leaf_path_for(store, entry) ⇒ Object

— Helpers ———————————————————-



331
332
333
334
335
336
337
338
# File 'lib/textus/doctor.rb', line 331

def leaf_path_for(store, entry)
  primary_ext = Entry.for_format(entry.format).extensions.first
  if File.extname(entry.path) == ""
    File.join(store.root, "zones", entry.path + primary_ext)
  else
    File.join(store.root, "zones", entry.path)
  end
end

.run(store, checks: nil) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/textus/doctor.rb', line 19

def run(store, checks: nil)
  selected = checks ? Array(checks).map(&:to_s) : ALL_CHECKS
  unknown = selected - ALL_CHECKS
  unless unknown.empty?
    raise UsageError.new(
      "unknown doctor check: #{unknown.first}. Valid checks: #{ALL_CHECKS.join(", ")}",
    )
  end

  issues = run_builtin_checks(store, selected)
  issues.concat(run_registered_checks(store)) # extensions always run

  summary = LEVELS.to_h { |l| [l, issues.count { |i| i["level"] == l }] }
  {
    "protocol" => Textus::PROTOCOL,
    "ok" => summary["error"].zero?,
    "issues" => issues,
    "summary" => summary,
  }
end

.run_builtin_checks(store, selected) ⇒ Object



40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/textus/doctor.rb', line 40

def run_builtin_checks(store, selected)
  issues = []
  issues.concat(check_manifest_files(store))        if selected.include?("manifest_files")
  issues.concat(check_schemas(store))               if selected.include?("schemas")
  issues.concat(check_templates(store))             if selected.include?("templates")
  issues.concat(check_extensions(store))            if selected.include?("extensions")
  issues.concat(check_illegal_keys(store))          if selected.include?("illegal_keys")
  issues.concat(check_sentinels(store))             if selected.include?("sentinels")
  issues.concat(check_audit_log(store))             if selected.include?("audit_log")
  issues.concat(check_unowned_schema_fields(store)) if selected.include?("unowned_schema_fields")
  issues.concat(check_schema_violations(store))     if selected.include?("schema_violations")
  issues
end

.run_registered_checks(store) ⇒ Object



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
# File 'lib/textus/doctor.rb', line 292

def run_registered_checks(store)
  out = []
  view = StoreView.new(store)
  store.registry.doctor_check_names.each do |name|
    callable = store.registry.doctor_check(name)
    begin
      result = Timeout.timeout(DOCTOR_CHECK_TIMEOUT_SECONDS) { callable.call(store: view) }
      if result.is_a?(Array)
        out.concat(result.map { |h| h.transform_keys(&:to_s) })
      else
        out << fail_issue(name, code: "doctor_check.bad_return",
                                message: "doctor_check '#{name}' returned #{result.class} (expected Array)",
                                fix: "return an array of issue hashes from the doctor_check block")
      end
    rescue Timeout::Error
      out << fail_issue(name, code: "doctor_check.timeout",
                              message: "doctor_check '#{name}' exceeded #{DOCTOR_CHECK_TIMEOUT_SECONDS}s",
                              fix: "shorten the check or split it into smaller checks")
    rescue StandardError => e
      out << fail_issue(name, code: "doctor_check.failed",
                              message: "#{e.class}: #{e.message}",
                              fix: "fix the doctor_check block in .textus/extensions/")
    end
  end
  out
end

.walk_nested(root, &block) ⇒ Object



340
341
342
343
344
345
346
347
348
349
350
# File 'lib/textus/doctor.rb', line 340

def walk_nested(root, &block)
  Dir.each_child(root) do |name|
    abs = File.join(root, name)
    if File.directory?(abs)
      walk_nested(abs, &block)
      yield abs, true
    else
      yield abs, false
    end
  end
end