1234567module cli89import json210import os11import time12import src.exchange13import src.fmt14import src.history15import src.storage1617pub fn cmd_doctor(raw []string) int {18 args := parse('doctor', raw, Options{19 values: ['backup']20 flags: ['json', 'yes', 'fast']21 }) or { return usage_error(err.msg()) }22 if args.positional.len > 0 {23 return usage_error('doctor takes no positional arguments')24 }25 store := open_store() or {26 report := DoctorJson{27 health: 'unhealthy'28 root: storage.find_root(os.getwd()) or { os.getwd() }29 problems: [err.msg()]30 checks: [DoctorCheck{'database open', 'fail', err.msg(), open_remedy(err.msg())}]31 scope: 'database could not be opened; further checks could not run'32 }33 if args.json() { emit_json(json2.encode(report)) } else { print_doctor(report, true) }34 return 135 }36 defer { store.close() }37 yes, fast := args.flag('yes'), args.flag('fast')38 39 backup_path := args.value_or_none('backup') or { '' }40 mut backup_error := ''41 if backup_path != '' {42 store.backup(backup_path) or { backup_error = err.msg() }43 }44 mut report := diagnose(store, fast)45 repairs := plan_repairs(store, report)46 report.repairs = repairs.map(it.action)47 mut repaired := []string{}48 mut repair_errors := []string{}49 mut attempted := false50 51 if repairs.len > 0 && backup_error == '' && (yes || (interactive() && !args.json())) {52 if !yes {53 print_doctor(report, false)54 println('')55 }56 for repair in repairs {57 if !yes {58 println(' repair: ${repair.action}')59 }60 if !(confirm(yes) or { false }) {61 continue62 }63 attempted = true64 repair.run() or {65 repair_errors << '${repair.action}: ${err.msg()}'66 if err is exchange.Partway {67 repaired << err.done68 }69 continue70 }71 repaired << repair.action72 }73 74 if attempted {75 report = diagnose(store, fast)76 report.repairs = plan_repairs(store, report).map(it.action)77 }78 }79 report.repaired = repaired80 report.repair_errors = repair_errors81 if yes {82 report.peek_folders_removed = sweep_peek_folders()83 }84 if backup_error != '' {85 report.check('backup', [backup_error])86 } else {87 report.backup = backup_path88 }89 report.health = if report.problems.len > 0 {90 'unhealthy'91 } else if report.warnings.len > 0 { 'warning' } else { 'healthy' }92 if args.json() {93 emit_json(json2.encode(report))94 } else if repairs.len == 0 || yes || attempted || backup_error != '' || !interactive() {95 print_doctor(report, true)96 }97 return if report.problems.len > 0 { 1 } else { 0 }98}99100101fn diagnose(store &storage.Store, fast bool) DoctorJson {102 mut report := DoctorJson{103 root: store.root104 database: os.join_path(store.root, storage.file_name)105 schema_version: storage.schema_version106 checked_at: time.now().unix()107 koh_version: version108 }109 working('checking database, objects and all stored history')110 store.db.exec('BEGIN') or {111 report.check('read transaction', [err.msg()])112 return report113 }114 report.check('SQLite integrity', store.integrity_check() or { [err.msg()] })115 if fast {116 117 118 report.checks << DoctorCheck{'object hashes and sizes', 'skipped', '--fast requested; object bytes not verified', ''}119 } else {120 report.object_check('object hashes and sizes', store.check_objects() or {121 [storage.ObjectProblem{'', err.msg()}]122 })123 }124 report.object_check('save object references', store.check_save_files() or {125 [storage.ObjectProblem{'', err.msg()}]126 })127 doctor_local(store, mut report) or { report.check('local metadata', [err.msg()]) }128 store.end() or { report.check('read transaction', [err.msg()]) }129 working('reading working files without cached hashes')130 doctor_working_tree(store, mut report) or { report.check('working tree', [err.msg()]) }131 doctor_build(store.root, mut report)132 report.size_bytes = os.file_size(report.database)133 report.wal_bytes = os.file_size('${report.database}-wal')134 doctor_remote_config(mut report)135 if fast {136 report.checks << DoctorCheck{'remote audit', 'skipped', '--fast requested; remote content not checked', ''}137 } else {138 working('auditing remote history and releases (read-only)')139 doctor_remote(store, mut report) or { report.check('remote audit', [err.msg()]) }140 }141 report.scope = 'repository data and configuration only; not application tests, backup recovery or remote write access'142 return report143}144145fn (mut report DoctorJson) check(name string, problems []string) {146 failed := problems.len > 0147 report.checks << DoctorCheck{name, if failed { 'fail' } else { 'pass' }, if failed {148 problems.join('; ')149 } else {150 'verified'151 }, if failed { remedy_for(name) } else { '' }}152 for problem in problems {153 if problem !in report.problems { report.problems << problem }154 }155}156157158fn (mut report DoctorJson) object_check(name string, problems []storage.ObjectProblem) {159 for problem in problems {160 if problem.hash != '' && problem.hash !in report.damaged_objects {161 report.damaged_objects << problem.hash162 }163 }164 report.check(name, problems.map(it.detail))165}166167168169fn remedy_for(check string) string {170 return match check {171 'SQLite integrity' {172 'koh doctor can rebuild the indexes; if damage remains, restore a copy made with koh doctor --backup, or rebuild from the remote with koh steal <repo> in an empty folder'173 }174 'object hashes and sizes', 'save object references' {175 'koh doctor restores verified copies from working files or the remote; with neither, that content is lost'176 }177 'history links and cycles' {178 'koh doctor fetches missing saves from the remote; a cycle needs a backup or the remote copy'179 }180 'saved paths and events' {181 'run the koh strip command shown for an unsafe path, or strip one side of a file/folder collision; koh doctor re-applies recorded strips; a bad event or unfinished strip note needs a backup or the remote copy'182 }183 'restore state' {184 'run koh revert; it keeps the current files in a checkpoint first'185 }186 'working tree safety' {187 'rename files whose names Koh cannot save, and move links that block a restore'188 }189 'ignore rules' {190 'make the ignore file readable'191 }192 'build configuration' {193 'fix koh.build; koh man build describes it'194 }195 'machine remote', 'machine remote configuration' {196 'run koh remote to set the remote and its credentials again'197 }198 'remote audit' {199 'check the network and the remote settings (koh remote), then run koh doctor again'200 }201 'remote history, events and objects' {202 'koh doctor uploads what this repo holds; anything else must be offered from a machine that has it'203 }204 'remote releases' {205 'publish that version again with koh offer --builds from the save it names'206 }207 'remote stability' {208 'another machine changed the remote during the audit; run koh doctor again'209 }210 'backup' {211 'choose a backup path that does not exist yet'212 }213 else {214 'run koh doctor again; if it repeats, restore a copy made with koh doctor --backup, or rebuild from the remote with koh steal <repo> in an empty folder'215 }216 }217}218219fn open_remedy(message string) string {220 return if message.contains('newer koh') {221 'run koh update'222 } else if message.contains('another koh command') || message.contains('locked') {223 'wait for the other koh command to finish, then run koh doctor again'224 } else if message.contains('koh init') {225 'run koh init here, or koh steal <repo> to fetch one'226 } else {227 'keep .koh as it is; restore a copy made with koh doctor --backup, or rebuild from the remote with koh steal <repo> in an empty folder'228 }229}230231232fn print_doctor(report DoctorJson, offer bool) {233 root := report.root.replace_once(os.home_dir(), '~')234 if report.problems.len > 0 {235 warn('${root} has ${fmt.plural(report.problems.len, 'problem')}')236 } else if report.warnings.len > 0 {237 ok('${root} is sound · ${fmt.plural(report.warnings.len, 'warning')}')238 } else {239 ok('${root} is healthy')240 }241 println('')242 if report.metadata_available {243 doctor_metadata(report)244 } else {245 println(' ${fmt.dim('repository metadata unavailable; see failed checks')}')246 }247 println('')248 passed := report.checks.filter(it.status == 'pass').map(it.name)249 if passed.len > 0 {250 ok('${fmt.plural(passed.len, 'check')} passed')251 for line in wrap_items(passed, 76) {252 println(' ${fmt.dim(line)}')253 }254 }255 for check in report.checks.filter(it.status != 'pass') {256 mark := match check.status {257 'fail' { fmt.red(fmt.glyph_fail) }258 'skipped' { fmt.dim('–') }259 else { fmt.amber('!') }260 }261 println(' ${mark} ${check.name} ${fmt.dim('· ${check.detail}')}')262 if check.remedy != '' {263 println(' fix: ${check.remedy}')264 }265 }266 for warning in report.warnings {267 warn(warning)268 }269 if report.peek_folders_removed > 0 {270 ok('removed ${report.peek_folders_removed} old peek folders')271 }272 if report.backup != '' { ok('backed up to ${report.backup}') }273 for action in report.repaired {274 ok('repaired: ${action}')275 }276 for failure in report.repair_errors {277 warn('repair failed: ${failure}')278 }279 if offer && report.repairs.len > 0 {280 println('')281 warn('koh doctor can repair ${fmt.plural(report.repairs.len, 'finding')}:')282 for action in report.repairs {283 println(' ${action}')284 }285 note('run koh doctor again to choose, or koh doctor --yes to run them all')286 }287 println('')288 note(report.scope)289}290291fn doctor_metadata(report DoctorJson) {292 if report.head.id != '' {293 doctor_row('head', '[${report.head.id}] ${fmt.safe_text(report.head.message.all_before('\n'))}')294 doctor_row('', fmt.dim([fmt.safe_text(report.head.agent), fmt.safe_text(report.head.session),295 fmt.stamp(report.head.created_at), fmt.plural(report.head_files, 'file')].filter(it != '').join(' · ')))296 } else {297 doctor_row('head', if report.saves == 0 { 'no saves yet' } else { report.head_id })298 }299 mut saves := ['${report.saves} saves', '${report.checkpoints} checkpoints']300 if report.off_line_saves > 0 { saves << '${report.off_line_saves} off line' }301 if report.events > 0 { saves << fmt.plural(report.events, 'event') }302 if report.flagged_saves > 0 { saves << '${report.flagged_saves} flagged' }303 doctor_row('history', saves.join(' · '))304 doctor_row('storage', '${fmt.human_bytes(i64(report.size_bytes))} + ${fmt.human_bytes(i64(report.wal_bytes))} WAL · schema ${report.schema_version}')305 doctor_row('', fmt.dim('${report.objects} objects · ${fmt.human_bytes(report.object_bytes)} → ${fmt.human_bytes(report.packed_bytes)} compressed · ${report.manifests} folder manifests'))306 changes := report.changes307 counts := ['${changes.added.len} added', '${changes.modified.len} modified',308 '${changes.removed.len} removed'].filter(!it.starts_with('0 '))309 mut tree := if counts.len == 0 { 'no changes' } else { counts.join(', ') }310 if report.cache_cleared {311 tree += fmt.dim(' · ${report.cached_files} cached hashes re-read')312 }313 doctor_row('tree', tree)314 if report.remote_target != '' {315 offer := if report.last_offered_head != '' {316 fmt.dim(' · last offer [${report.last_offered_head}]')317 } else {318 ''319 }320 doctor_row('remote', report.remote_target + offer)321 }322 if report.source != '' { doctor_row('source', '${report.source} (read-only)') }323 if report.project_version != '' {324 doctor_row('build', '${report.project_version} · ${report.build_platforms.join(', ')}')325 }326}327328fn doctor_row(label string, value string) {329 println(' ${fmt.dim('${label:-9}')}${value}')330}331332fn wrap_items(items []string, width int) []string {333 mut lines := []string{}334 mut line := ''335 for item in items {336 if line != '' && fmt.visible_width(line) + 3 + item.len > width {337 lines << line338 line = item339 } else {340 line = if line == '' { item } else { '${line} · ${item}' }341 }342 }343 if line != '' {344 lines << line345 }346 return lines347}348349fn shell_quote(text string) string {350 return "'${text.replace("'", "'\\''")}'"351}352353const peek_age = 86400354355fn sweep_peek_folders() int {356 mut removed := 0357 for name in os.ls(os.temp_dir()) or { return 0 } {358 path := os.join_path(os.temp_dir(), name)359 info := os.lstat(path) or { continue }360 if !name.starts_with(peek_prefix) || os.is_link(path) || !os.is_dir(path)361 || info.uid != u32(os.getuid()) || !peek_is_old(os.file_last_mod_unix(path), time.now().unix()) {362 continue363 }364 os.rmdir_all(path) or { continue }365 removed++366 }367 return removed368}369370// A recent peek may still be open in an editor.371fn peek_is_old(modified i64, now i64) bool {372 return modified < now - peek_age373}374375struct DoctorCheck {376 name string377 status string378 detail string379 remedy string380}381382struct DoctorJson {383mut:384 health string385 scope string386 metadata_available bool387 ignore_files map[string]int388 checks []DoctorCheck389 warnings []string390 problems []string391 root string392 database string393 schema_version int394 checked_at i64395 koh_version string396 head_id string397 head history.Save398 head_files int399 objects int400 saves int401 checkpoints int402 line_saves int403 off_line_saves int404 events int405 flagged_saves int406 head_flagged bool407 manifests i64408 size_bytes u64409 wal_bytes u64410 object_bytes i64411 packed_bytes i64412 unreferenced_objects i64413 restore_unfinished bool414 pending_strips []string415 changes Changes416 ignored_saved_files []string417 build_platforms []string418 project_version string419 source string420 remote_repo string421 remote_target string422 last_offered_head string423 remote_head string424 remote_objects int425 remote_saves int426 remote_releases int427 cached_files int428 cache_cleared bool429 peek_folders_removed int430 backup string431 repairs []string432 repaired []string433 repair_errors []string434 damaged_objects []string435 missing_saves []string436 strip_residue bool437 strip_residue_paths []string438 remote_strip_residue []string439 upload_unsettled bool440 remote_bad_objects []string441 remote_missing_saves []string442}