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 – 8 built-in checks + extension dispatch

%w[error warning info].freeze
DOCTOR_CHECK_TIMEOUT_SECONDS =
2

Class Method Summary collapse

Class Method Details

.check_audit_log(store) ⇒ Object



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

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?

    # Audit log is TSV, not NDJSON. Treat as malformed if it doesn't have
    # at least 6 tab-separated fields (timestamp, role, verb, key, etag_before, etag_after).
    fields = stripped.split("\t")
    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)",
        "fix" => "inspect #{path} at line #{lineno} and remove the corrupted row",
      }
      next
    end

    extras = fields[6]
    next if extras.nil? || extras.empty?

    begin
      JSON.parse(extras)
    rescue JSON::ParserError => e
      out << {
        "code" => "audit.parse_error",
        "level" => "warning",
        "subject" => "#{path}:#{lineno}",
        "message" => "audit log line #{lineno} extras JSON malformed: #{e.message}",
        "fix" => "inspect #{path} at line #{lineno} and fix the JSON in the last column",
      }
    end
  end
  out
end

.check_extensions(store) ⇒ Object



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

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



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

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 ———————————————————–



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

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_schemas(store) ⇒ Object



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

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



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

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



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

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



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

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



288
289
290
291
292
293
294
295
296
# File 'lib/textus/doctor.rb', line 288

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 ———————————————————-



300
301
302
303
304
305
306
307
# File 'lib/textus/doctor.rb', line 300

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) ⇒ Object



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/textus/doctor.rb', line 15

def run(store)
  issues = []
  issues.concat(check_manifest_files(store))
  issues.concat(check_schemas(store))
  issues.concat(check_templates(store))
  issues.concat(check_extensions(store))
  issues.concat(check_illegal_keys(store))
  issues.concat(check_sentinels(store))
  issues.concat(check_audit_log(store))
  issues.concat(check_unowned_schema_fields(store))
  issues.concat(run_registered_checks(store))

  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_registered_checks(store) ⇒ Object



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

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



309
310
311
312
313
314
315
316
317
318
319
# File 'lib/textus/doctor.rb', line 309

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