rigops 0.13.0__py3-none-any.whl

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.
Files changed (86) hide show
  1. rigops/__init__.py +3 -0
  2. rigops/__main__.py +7 -0
  3. rigops/authprobe.py +106 -0
  4. rigops/backlog.py +107 -0
  5. rigops/cause.py +151 -0
  6. rigops/cli/__init__.py +66 -0
  7. rigops/cli/authprobe.py +47 -0
  8. rigops/cli/backlog.py +93 -0
  9. rigops/cli/config.py +61 -0
  10. rigops/cli/doctor.py +666 -0
  11. rigops/cli/eit.py +225 -0
  12. rigops/cli/eval.py +370 -0
  13. rigops/cli/hook.py +7 -0
  14. rigops/cli/janitor.py +88 -0
  15. rigops/cli/jobs.py +122 -0
  16. rigops/cli/ledger.py +350 -0
  17. rigops/cli/mine.py +7 -0
  18. rigops/cli/reap.py +110 -0
  19. rigops/cli/tax.py +238 -0
  20. rigops/cli/version.py +12 -0
  21. rigops/config.py +83 -0
  22. rigops/config_spec.py +336 -0
  23. rigops/core/__init__.py +224 -0
  24. rigops/corpus.py +44 -0
  25. rigops/cost.py +37 -0
  26. rigops/detector.py +91 -0
  27. rigops/doctor/__init__.py +81 -0
  28. rigops/doctor/check_agents.py +85 -0
  29. rigops/doctor/check_budget.py +110 -0
  30. rigops/doctor/check_jobs.py +30 -0
  31. rigops/doctor/check_levers.py +328 -0
  32. rigops/doctor/check_mcp.py +104 -0
  33. rigops/doctor/check_memory.py +92 -0
  34. rigops/doctor/check_pointers.py +358 -0
  35. rigops/doctor/ids.py +32 -0
  36. rigops/doctor/pointer_grammar.py +147 -0
  37. rigops/errors.py +5 -0
  38. rigops/eval/__init__.py +35 -0
  39. rigops/eval/cases.py +188 -0
  40. rigops/eval/checks.py +117 -0
  41. rigops/eval/client.py +190 -0
  42. rigops/eval/diff.py +108 -0
  43. rigops/eval/score.py +90 -0
  44. rigops/fmt.py +62 -0
  45. rigops/frontmatter.py +36 -0
  46. rigops/guard_state.py +69 -0
  47. rigops/hook.py +245 -0
  48. rigops/janitor.py +384 -0
  49. rigops/jobs.py +203 -0
  50. rigops/judge.py +364 -0
  51. rigops/launchd.py +194 -0
  52. rigops/ledger_row.py +88 -0
  53. rigops/levers.py +397 -0
  54. rigops/mine.py +195 -0
  55. rigops/mine_group.py +111 -0
  56. rigops/mine_redact.py +192 -0
  57. rigops/modelmix.py +36 -0
  58. rigops/notify.py +114 -0
  59. rigops/procgroup.py +37 -0
  60. rigops/reap.py +917 -0
  61. rigops/reap_guards.py +70 -0
  62. rigops/reap_owned.py +44 -0
  63. rigops/reap_procs.py +382 -0
  64. rigops/reap_report.py +78 -0
  65. rigops/reap_selftest.py +94 -0
  66. rigops/rebuilds.py +163 -0
  67. rigops/redaction-patterns.public.txt +40 -0
  68. rigops/registry.py +137 -0
  69. rigops/sources/__init__.py +19 -0
  70. rigops/sources/ccusage.py +44 -0
  71. rigops/sources/command.py +50 -0
  72. rigops/starts.py +247 -0
  73. rigops/state.py +159 -0
  74. rigops/templates/cron/crontab.example +21 -0
  75. rigops/templates/launchd/doctor.plist.in +44 -0
  76. rigops/templates/launchd/janitor.plist.in +50 -0
  77. rigops/templates/launchd/ledger.plist.in +48 -0
  78. rigops/templates/launchd/reap.plist.in +48 -0
  79. rigops/transcripts.py +369 -0
  80. rigops/watermarks.py +116 -0
  81. rigops-0.13.0.dist-info/METADATA +300 -0
  82. rigops-0.13.0.dist-info/RECORD +86 -0
  83. rigops-0.13.0.dist-info/WHEEL +5 -0
  84. rigops-0.13.0.dist-info/entry_points.txt +2 -0
  85. rigops-0.13.0.dist-info/licenses/LICENSE +21 -0
  86. rigops-0.13.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,30 @@
1
+ """A scheduled launchd job whose program is gone or broken never runs, and says nothing.
2
+
3
+ An interpreter upgrade or a removed install leaves the plist in place with a
4
+ path that no longer works; `launchd` then fails the job on every tick. Only
5
+ macOS schedules with launchd, so elsewhere the check reports nothing.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import sys
11
+
12
+ from rigops import core
13
+
14
+ AREA = "rigops"
15
+ CHECK = "jobs"
16
+
17
+
18
+ def run(cfg):
19
+ if sys.platform != "darwin":
20
+ return []
21
+ return [
22
+ core.Finding(
23
+ check=CHECK, area=AREA, key=f"program:{path.name}",
24
+ symptom=f"scheduled job {path.stem} cannot run its program: {problem}",
25
+ evidence=str(path),
26
+ fix="rigops jobs install --apply",
27
+ extra={"paths": [str(path)]},
28
+ )
29
+ for path, problem in core.job_problems()
30
+ ]
@@ -0,0 +1,328 @@
1
+ """Lever regressions read from the ledger the weekly job already writes.
2
+
3
+ Every finding here is a warning. A ledger row aggregates last week's sessions,
4
+ so a regressed lever is a trend to act on rather than a defect in whatever is
5
+ being committed, and a commit gate that tripped on it would be switched off the
6
+ first time it got in the way.
7
+
8
+ Rules live under ``doctor.levers.rules``, one per ledger column:
9
+
10
+ - ``max``: the latest row must not exceed it (a lever whose right value is zero).
11
+ - ``min``: the latest row must not fall below it (a floor).
12
+ - ``rise_pct`` / ``drop_pct``: the latest row must not move further than this, in
13
+ the worse direction, from the median of the weekly rows before it.
14
+
15
+ Built-in rules (``DEFAULT_RULES``) watch the core cost columns without any
16
+ config; a user rule replaces the built-in one for its lever, ``null`` turns a
17
+ lever off, and ``doctor.levers.defaults: false`` drops the built-ins. A
18
+ ``{group}`` in a rule key stands for every ``ledger.watch_projects`` group.
19
+
20
+ ``rigops ledger note "<why>" --accept <lever>`` records a deliberate change: rows
21
+ on or before that note's date are not judged for that lever, and a band restarts
22
+ its baseline at the accepted row.
23
+ """
24
+
25
+ from __future__ import annotations
26
+
27
+ import json
28
+ import statistics
29
+ from datetime import date, timedelta
30
+
31
+ from rigops import core
32
+
33
+ AREA = "metrics"
34
+ CHECK = "levers"
35
+
36
+ # Ledger rows aggregate the seven days before their date; rows closer together
37
+ # share sessions and would count one week twice.
38
+ WINDOW_DAYS = 7
39
+ BASELINE_ROWS = 4
40
+ MIN_BASELINE_ROWS = 2
41
+ DEFAULT_MAX_AGE_DAYS = 10
42
+ RULE_KEYS = ("max", "min", "rise_pct", "drop_pct")
43
+ GROUP = "{group}"
44
+
45
+ # Tolerances sit just above the widest swing across a real ledger's flat weeks, so a
46
+ # built-in fires on a step change, not on weekly noise.
47
+ DEFAULT_RULES = {
48
+ "turn1_p50": {"rise_pct": 30},
49
+ "turn1_{group}": {"rise_pct": 30},
50
+ "turn1_{group}_p50": {"rise_pct": 30},
51
+ "eit_per_turn": {"rise_pct": 20},
52
+ "cache_hit_pct": {"drop_pct": 3},
53
+ "fixed_tax_b": {"rise_pct": 10},
54
+ "start_tool_chars": {"rise_pct": 10},
55
+ "rebuild_eit_pct": {"rise_pct": 30},
56
+ "main_default_model_pct": {"min": 50},
57
+ "corrections": {"rise_pct": 150},
58
+ "tool_err_per_100": {"rise_pct": 50},
59
+ }
60
+
61
+ HINTS = (
62
+ ("turn1_", "`rigops tax --starts` shows what session starts load, per surface and tool group"),
63
+ ("start_tool", "`rigops tax --starts` shows which tool groups session starts load"),
64
+ ("fixed_tax_b", "`rigops tax` lists the always-loaded files by size"),
65
+ ("eit_per_turn", "`rigops eit --by session` shows which sessions carry the cost"),
66
+ ("cache_hit_pct", "`rigops eit --by session` shows which sessions lost cache reuse"),
67
+ ("rebuild_", "`rigops eit --rebuilds` classes each cache rebuild by cause"),
68
+ ("main_default_model", "a session's own model pick overrides the settings default; "
69
+ "`rigops eit --by model` splits EIT per model"),
70
+ ("corrections", "`rigops ledger diff` pairs the jump with the interventions around it"),
71
+ ("tool_err_per_100", "`rigops ledger diff` pairs the jump with the interventions around it"),
72
+ )
73
+
74
+
75
+ def _number(value) -> bool:
76
+ return isinstance(value, (int, float)) and not isinstance(value, bool)
77
+
78
+
79
+ def _show(value) -> str:
80
+ return f"{round(value, 1):g}" if isinstance(value, float) else str(value)
81
+
82
+
83
+ def _warning(key, symptom, evidence, fix, ledger) -> core.Finding:
84
+ return core.Finding(
85
+ check=CHECK, area=AREA, key=key, symptom=symptom, evidence=evidence, fix=fix,
86
+ severity="warn", extra={"paths": [str(ledger)]},
87
+ )
88
+
89
+
90
+ def _dated(row) -> bool:
91
+ try:
92
+ date.fromisoformat(row["date"])
93
+ except (ValueError, TypeError, KeyError):
94
+ return False
95
+ return True
96
+
97
+
98
+ def read_rows(path):
99
+ """(rows, skipped, problem): dated rows, how many were skipped, or why there are none."""
100
+ if not path.exists():
101
+ return None, 0, "does not exist"
102
+ try:
103
+ rows, skipped = core.read_rows(path, _dated)
104
+ except core.RigopsError as exc:
105
+ return None, 0, f"cannot be read ({exc})"
106
+ return rows, skipped, None
107
+
108
+
109
+ def weekly(rows) -> list:
110
+ """Rows a full window apart, picked from the newest back, returned oldest first."""
111
+ kept = []
112
+ for row in sorted(rows, key=lambda r: r["date"], reverse=True):
113
+ if not kept or date.fromisoformat(row["date"]) <= (
114
+ date.fromisoformat(kept[-1]["date"]) - timedelta(days=WINDOW_DAYS)
115
+ ):
116
+ kept.append(row)
117
+ return kept[::-1]
118
+
119
+
120
+ def accepted_through(notes, lever):
121
+ dates = [
122
+ n["date"] for n in notes
123
+ if isinstance(n, dict) and isinstance(n.get("date"), str)
124
+ and isinstance(n.get("accept"), list) and lever in n["accept"]
125
+ ]
126
+ return max(dates) if dates else None
127
+
128
+
129
+ def _malformed(rule) -> bool:
130
+ return (
131
+ not isinstance(rule, dict) or not rule
132
+ or any(k not in RULE_KEYS or not _number(v) for k, v in rule.items())
133
+ )
134
+
135
+
136
+ def _expand(rules, groups) -> dict:
137
+ out = {}
138
+ for key, rule in rules.items():
139
+ if GROUP in key:
140
+ out.update({key.replace(GROUP, g): rule for g in groups})
141
+ else:
142
+ out[key] = rule
143
+ return out
144
+
145
+
146
+ def effective_rules(cfg) -> tuple[dict, set]:
147
+ """(rules, built-in lever names): built-ins overlaid by the user's rules, nulls dropped."""
148
+ user = core.cfg_get(cfg, "doctor.levers.rules") or {}
149
+ if not isinstance(user, dict):
150
+ user = {}
151
+ groups = sorted(core.cfg_get(cfg, "ledger.watch_projects") or {})
152
+ use_defaults = core.cfg_get(cfg, "doctor.levers.defaults", True) is not False
153
+ builtin = _expand(DEFAULT_RULES, groups) if use_defaults else {}
154
+ configured = {
155
+ **_expand({k: v for k, v in user.items() if GROUP in k}, groups),
156
+ **{k: v for k, v in user.items() if GROUP not in k},
157
+ }
158
+ merged = {**builtin, **configured}
159
+ rules = {k: v for k, v in merged.items() if v is not None}
160
+ return rules, set(builtin) - set(configured)
161
+
162
+
163
+ def _fix(lever) -> str:
164
+ accept = f'`rigops ledger note "<why>" --accept {lever}`'
165
+ for prefix, hint in HINTS:
166
+ if lever.startswith(prefix):
167
+ return f"{hint}; if the change is deliberate, record it with {accept}"
168
+ return f"find what moved it, or record a deliberate change with {accept}"
169
+
170
+
171
+ def _judge_lever(lever, rule, series, accepted, ledger) -> list:
172
+ latest = series[-1]
173
+ value = latest.get(lever)
174
+ if accepted and latest["date"] <= accepted:
175
+ return []
176
+ if not _number(value):
177
+ return [_warning(
178
+ f"{lever}:value",
179
+ f"{lever} is {value!r} on the {latest['date']} ledger row, not a number, so its "
180
+ "rule is not judged",
181
+ f"{core.short(ledger)} row {latest['date']}",
182
+ "check what wrote the column, or turn the rule off", ledger,
183
+ )]
184
+ fix = _fix(lever)
185
+ found = []
186
+ if "max" in rule and value > rule["max"]:
187
+ found.append(_warning(
188
+ f"{lever}:max",
189
+ f"{lever} is {_show(value)} on the {latest['date']} ledger row, above its limit of "
190
+ f"{_show(rule['max'])}",
191
+ f"{core.short(ledger)} row {latest['date']}", fix, ledger,
192
+ ))
193
+ if "min" in rule and value < rule["min"]:
194
+ found.append(_warning(
195
+ f"{lever}:min",
196
+ f"{lever} is {_show(value)} on the {latest['date']} ledger row, below its floor of "
197
+ f"{_show(rule['min'])}",
198
+ f"{core.short(ledger)} row {latest['date']}", fix, ledger,
199
+ ))
200
+ earlier = series[:-1]
201
+ if accepted:
202
+ anchor = [r["date"] for r in earlier if r["date"] <= accepted]
203
+ if anchor:
204
+ earlier = [r for r in earlier if r["date"] >= anchor[-1]]
205
+ history = [r for r in earlier if _number(r.get(lever))][-BASELINE_ROWS:]
206
+ if len(history) < MIN_BASELINE_ROWS:
207
+ return found
208
+ baseline = statistics.median(r[lever] for r in history)
209
+ if baseline == 0:
210
+ return found
211
+ change = (value - baseline) / abs(baseline) * 100
212
+ for kind, worse, verb in (("rise_pct", change, "rose"), ("drop_pct", -change, "fell")):
213
+ if kind in rule and worse > rule[kind]:
214
+ found.append(_warning(
215
+ f"{lever}:{kind}",
216
+ f"{lever} {verb} {abs(change):.0f}% to {_show(value)} on the {latest['date']} "
217
+ f"ledger row, past its {_show(rule[kind])}% tolerance",
218
+ f"baseline median {_show(baseline)} over weekly rows "
219
+ f"{history[0]['date']}..{history[-1]['date']}",
220
+ fix, ledger,
221
+ ))
222
+ return found
223
+
224
+
225
+ def _row_health(row, ledger) -> list:
226
+ where = f"{core.short(ledger)} row {row['date']}"
227
+ found = []
228
+ lost = core.unparsed_lines(row)
229
+ if lost:
230
+ found.append(_warning(
231
+ "parse", f"{core.unparsed_text(*lost)} on the {row['date']} ledger row",
232
+ where, "check the transcript format or the harness version; the row may undercount",
233
+ ledger,
234
+ ))
235
+ if row.get("window_empty") is True:
236
+ found.append(_warning(
237
+ "no-turns", f"the {row['date']} ledger row has no turns in its window", where,
238
+ "check `transcripts_dir` and that sessions ran that week", ledger,
239
+ ))
240
+ return found
241
+
242
+
243
+ def judge(rows, notes, rules, today, ledger, max_age_days=DEFAULT_MAX_AGE_DAYS,
244
+ builtin=frozenset()) -> list:
245
+ """Judge the newest weekly row; ``builtin`` levers stay quiet about their own setup."""
246
+ configured = set(rules) - set(builtin)
247
+ if not rows:
248
+ if not configured:
249
+ return []
250
+ return [_warning(
251
+ "empty", "the ledger has no rows, so no lever is judged",
252
+ core.short(ledger), "run `rigops ledger` or remove doctor.levers.rules", ledger,
253
+ )]
254
+ series = weekly(rows)
255
+ latest = series[-1]
256
+ found = []
257
+ age = (today - date.fromisoformat(latest["date"])).days
258
+ if configured and age > max_age_days:
259
+ found.append(_warning(
260
+ "stale",
261
+ f"the newest ledger row is {age} days old, past the {max_age_days}-day limit",
262
+ f"{core.short(ledger)} row {latest['date']}",
263
+ "check the job that runs `rigops ledger`; lever findings still describe that row",
264
+ ledger,
265
+ ))
266
+ found.extend(_row_health(latest, ledger))
267
+ for lever, rule in sorted(rules.items()):
268
+ if _malformed(rule):
269
+ found.append(_warning(
270
+ f"{lever}:rule", f"doctor.levers.rules.{lever} is not a usable rule",
271
+ json.dumps(rule), f"give it one or more of {', '.join(RULE_KEYS)} as numbers",
272
+ ledger,
273
+ ))
274
+ elif lever not in latest:
275
+ if lever in builtin:
276
+ continue
277
+ found.append(_warning(
278
+ f"{lever}:column", f"the ledger has no `{lever}` column, so that rule never fires",
279
+ f"{core.short(ledger)} row {latest['date']}",
280
+ "fix the lever name in doctor.levers.rules", ledger,
281
+ ))
282
+ else:
283
+ found.extend(_judge_lever(lever, rule, series, accepted_through(notes, lever), ledger))
284
+ return found
285
+
286
+
287
+ def run(cfg, today=None):
288
+ user = core.cfg_get(cfg, "doctor.levers.rules") or {}
289
+ state = core.state_dir()
290
+ ledger = state / "ledger.jsonl"
291
+ if not isinstance(user, dict):
292
+ return [_warning(
293
+ "rules", "doctor.levers.rules is not an object", json.dumps(user),
294
+ "map each ledger column to its rule", ledger,
295
+ )]
296
+ rules, builtin = effective_rules(cfg)
297
+ if not rules:
298
+ return []
299
+ rows, skipped, problem = read_rows(ledger)
300
+ if problem == "does not exist" and not set(rules) - builtin:
301
+ return []
302
+ if problem:
303
+ return [_warning(
304
+ "unreadable", f"the ledger {problem}, so no lever is judged", core.short(ledger),
305
+ "run `rigops ledger`, or repair the named line", ledger,
306
+ )]
307
+ found = []
308
+ if skipped:
309
+ found.append(_warning(
310
+ "skipped", f"{skipped} ledger row(s) skipped as unreadable or newer than this rigops",
311
+ core.short(ledger), "repair the rows or upgrade rigops", ledger,
312
+ ))
313
+ notes, notes_skipped, notes_problem = read_rows(state / "interventions.jsonl")
314
+ if notes_problem and notes_problem != "does not exist":
315
+ found.append(_warning(
316
+ "notes", f"the intervention notes {notes_problem}, so no acceptance is honoured",
317
+ core.short(state / "interventions.jsonl"), "repair the named line", ledger,
318
+ ))
319
+ if notes_skipped:
320
+ found.append(_warning(
321
+ "notes-skipped", f"{notes_skipped} intervention note(s) skipped as unreadable",
322
+ core.short(state / "interventions.jsonl"), "repair the rows", ledger,
323
+ ))
324
+ max_age = core.cfg_get(cfg, "doctor.levers.max_age_days", DEFAULT_MAX_AGE_DAYS)
325
+ if not _number(max_age):
326
+ max_age = DEFAULT_MAX_AGE_DAYS
327
+ found.extend(judge(rows, notes or [], rules, today or date.today(), ledger, max_age, builtin))
328
+ return found
@@ -0,0 +1,104 @@
1
+ """A stdio MCP server spawns one process per live session, and the desktop app
2
+ keeps idle sessions alive: eighteen copies of one server measured at 1.5 GB on
3
+ this host. Every registry a session can resolve a server from is checked.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import json
9
+ from pathlib import Path
10
+
11
+ from rigops import core
12
+
13
+ AREA = "rigops"
14
+ CHECK = "mcp"
15
+
16
+ FIX = (
17
+ "use an http MCP or a skill script; a stdio server spawns one process per "
18
+ "live session (or add it to doctor.mcp.stdio_allow)"
19
+ )
20
+
21
+
22
+ def _json(path, default):
23
+ try:
24
+ return json.loads(core.read_text(path))
25
+ except (OSError, ValueError):
26
+ return default
27
+
28
+
29
+ def _is_stdio(server):
30
+ if not isinstance(server, dict):
31
+ return False
32
+ server_type = server.get("type")
33
+ if server_type == "stdio":
34
+ return True
35
+ return server_type is None and bool(server.get("command"))
36
+
37
+
38
+ def _claude_json_servers():
39
+ path = core.HOME / ".claude.json"
40
+ data = _json(path, {})
41
+ label = core.short(path)
42
+ out = [
43
+ (name, server, f"{label} (user)")
44
+ for name, server in (data.get("mcpServers", {}) or {}).items()
45
+ ]
46
+ for project_path, project in (data.get("projects", {}) or {}).items():
47
+ for name, server in ((project or {}).get("mcpServers", {}) or {}).items():
48
+ out.append((name, server, f"{label} (project {project_path})"))
49
+ return out
50
+
51
+
52
+ def _file_servers(path):
53
+ servers = _json(path, {}).get("mcpServers", {}) or {}
54
+ return [(name, server, core.short(path)) for name, server in servers.items()]
55
+
56
+
57
+ def _plugin_servers():
58
+ settings = _json(core.CLAUDE_DIR / "settings.json", {})
59
+ enabled = [key for key, on in (settings.get("enabledPlugins", {}) or {}).items() if on is True]
60
+ if not enabled:
61
+ return []
62
+ installed = _json(core.CLAUDE_DIR / "plugins" / "installed_plugins.json", {}).get("plugins", {})
63
+ out = []
64
+ for key in enabled:
65
+ install_paths = {
66
+ entry.get("installPath") for entry in installed.get(key, []) or []
67
+ if entry.get("installPath")
68
+ }
69
+ for install_path in install_paths:
70
+ base = Path(install_path)
71
+ manifest_path = base / ".mcp.json"
72
+ manifest = _json(manifest_path, {})
73
+ for name, server in (manifest.get("mcpServers", {}) or {}).items():
74
+ out.append((name, server, f"plugin {key} ({core.short(manifest_path)})"))
75
+ plugin_json_path = base / ".claude-plugin" / "plugin.json"
76
+ if plugin_json_path.is_file():
77
+ plugin_json = _json(plugin_json_path, {})
78
+ inline = plugin_json.get("mcpServers")
79
+ if isinstance(inline, dict):
80
+ for name, server in inline.items():
81
+ out.append((name, server, f"plugin {key} ({core.short(plugin_json_path)})"))
82
+ return out
83
+
84
+
85
+ def run(cfg):
86
+ allow = {name.lower() for name in core.cfg_get(cfg, "doctor.mcp.stdio_allow", [])}
87
+ findings = []
88
+ sources = (
89
+ _claude_json_servers()
90
+ + _file_servers(core.CLAUDE_DIR / "settings.json")
91
+ + _file_servers(core.CLAUDE_DIR / ".mcp.json")
92
+ + _plugin_servers()
93
+ )
94
+ for name, server, where in sources:
95
+ if not _is_stdio(server) or name.lower() in allow:
96
+ continue
97
+ command = server.get("command", "")
98
+ findings.append(core.Finding(
99
+ check=CHECK, area=AREA, key=f"stdio:{name}",
100
+ symptom=f"stdio MCP server `{name}` is defined in {where}",
101
+ evidence=Path(str(command)).name,
102
+ fix=FIX,
103
+ ))
104
+ return findings
@@ -0,0 +1,92 @@
1
+ """A memory store's index must match the notes beside it, and stay loadable.
2
+
3
+ The index is read into every session, so a pointer to a note that is gone wastes
4
+ a line and misleads, a note the index does not name is never recalled, and an
5
+ index past the load limit is silently cut. Findings are warnings: they are
6
+ reported, never fail the run and never page.
7
+
8
+ A ``[[name]]`` link with no note behind it is not checked. It marks something
9
+ worth writing later, so it is allowed by convention.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import re
15
+ from pathlib import Path
16
+
17
+ from rigops import core
18
+
19
+ from .check_pointers import finding_key, source_files
20
+ from .pointer_grammar import MEMORY_NOTE_RE
21
+
22
+ AREA = "docs"
23
+ CHECK = "memory"
24
+
25
+ INDEX = "MEMORY.md"
26
+ DEFAULT_MAX_LINES = 150
27
+ DEFAULT_MAX_BYTES = 20000
28
+ DEFAULT_SOURCES = ["~/.claude/projects/*/memory/*.md"]
29
+
30
+ _POINTER_RE = re.compile(r"\]\(([^)\s#]+\.md)(?:#[^)\s]*)?\)")
31
+
32
+
33
+ def _warn(kind, value, where, fix, symptom):
34
+ return core.Finding(
35
+ check=CHECK, area=AREA, key=finding_key(kind, value, where), symptom=symptom,
36
+ evidence=where, fix=fix, severity="warn",
37
+ )
38
+
39
+
40
+ def _cap(cfg, key, default):
41
+ value = core.cfg_get(cfg, f"doctor.memory.{key}", None)
42
+ return default if value is None else value
43
+
44
+
45
+ def _store_findings(mem, max_lines, max_bytes):
46
+ out = []
47
+ label = core.short(mem / INDEX)
48
+ text = core.read_text(mem / INDEX)
49
+ linked = set()
50
+ for match in _POINTER_RE.finditer(text):
51
+ target = match.group(1)
52
+ if "://" in target:
53
+ continue
54
+ linked.add(Path(target).name)
55
+ if not (mem / target).is_file():
56
+ out.append(_warn(
57
+ "pointer", target, label,
58
+ "repoint the index entry at a note that exists or drop it",
59
+ f"index pointer `{target}` has no note",
60
+ ))
61
+ for note in sorted(mem.glob("*.md")):
62
+ if note.name != INDEX and note.name not in linked:
63
+ out.append(_warn(
64
+ "unindexed", note.name, label,
65
+ "add a one-line index entry or retire the note",
66
+ f"note `{note.name}` is missing from the index",
67
+ ))
68
+ lines, size = len(text.splitlines()), len(text.encode("utf-8"))
69
+ if lines > max_lines or size > max_bytes:
70
+ out.append(_warn(
71
+ "index-size", label, label,
72
+ "fold index lines together or retire stale notes",
73
+ f"index is {lines} lines and {size} bytes (caps {max_lines} and {max_bytes})",
74
+ ))
75
+ return out
76
+
77
+
78
+ def run(cfg):
79
+ configured = core.cfg_get(cfg, "doctor.memory.sources", None)
80
+ paths, _ = source_files(DEFAULT_SOURCES if configured is None else configured)
81
+ max_lines = _cap(cfg, "index_max_lines", DEFAULT_MAX_LINES)
82
+ max_bytes = _cap(cfg, "index_max_bytes", DEFAULT_MAX_BYTES)
83
+ stores = sorted({p.parent for p in paths if MEMORY_NOTE_RE.search(str(p))})
84
+ out = []
85
+ for mem in stores:
86
+ if (mem / INDEX).is_file():
87
+ try:
88
+ out.extend(_store_findings(mem, max_lines, max_bytes))
89
+ except OSError:
90
+ continue
91
+ return out
92
+