@yasaswy.nagavolu/agents 0.30.2 → 0.30.3
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.
- package/content/manifest.json +25 -1
- package/content/proxy/mem_sampler.py +8 -1
- package/content/proxy/memory_reclaim.py +3 -1
- package/content/skills/README.md +6 -2
- package/content/skills/low-ram-advisor/SKILL.md +13 -1
- package/content/skills/low-ram-advisor/deep_report.py +19 -9
- package/content/skills/low-ram-advisor/handlecount.py +80 -0
- package/content/skills/low-ram-advisor/memwatch.py +24 -4
- package/content/skills/low-ram-advisor/pooltags.py +5 -2
- package/content/skills/low-ram-advisor/ram_optimize.py +178 -0
- package/content/skills/low-ram-advisor/ram_prompt.py +46 -5
- package/content/skills/low-ram-advisor/ram_thresholds.py +13 -0
- package/content/skills/low-ram-advisor/ramstatus.py +121 -0
- package/content/skills/low-ram-advisor/restart_verdict.py +72 -0
- package/content/skills/low-ram-advisor/tests/test_deep_report.py +10 -3
- package/content/skills/low-ram-advisor/tests/test_handlecount.py +36 -0
- package/content/skills/low-ram-advisor/tests/test_ram_optimize.py +155 -0
- package/content/skills/low-ram-advisor/tests/test_restart_verdict.py +123 -0
- package/content/skills/ram/SKILL.md +26 -0
- package/lib/runner/exec.js +2 -2
- package/lib/runner/index.js +6 -1
- package/lib/runner/managed.js +1 -1
- package/lib/runner/pool.js +1 -1
- package/lib/runner/profiles/linuxDocker.js +1 -1
- package/lib/runner/profiles/macosShell.js +1 -1
- package/package.json +1 -1
package/content/manifest.json
CHANGED
|
@@ -234,6 +234,10 @@
|
|
|
234
234
|
{
|
|
235
235
|
"path": "skills/low-ram-advisor",
|
|
236
236
|
"kind": "skill"
|
|
237
|
+
},
|
|
238
|
+
{
|
|
239
|
+
"path": "skills/ram",
|
|
240
|
+
"kind": "skill"
|
|
237
241
|
}
|
|
238
242
|
],
|
|
239
243
|
"deps": [],
|
|
@@ -734,6 +738,11 @@
|
|
|
734
738
|
"kind": "skill",
|
|
735
739
|
"note": "Ranking logic imported by memory_reclaim.py; also its own bundle, safe to double-claim."
|
|
736
740
|
},
|
|
741
|
+
{
|
|
742
|
+
"path": "skills/ram",
|
|
743
|
+
"kind": "skill",
|
|
744
|
+
"note": "Thin /ram entry point over skills/low-ram-advisor/ram_optimize.py; also its own claim in low-ram-advisor, safe to double-claim."
|
|
745
|
+
},
|
|
737
746
|
{
|
|
738
747
|
"path": "proxy/memory_reclaim_hook.py",
|
|
739
748
|
"kind": "hook",
|
|
@@ -1261,7 +1270,12 @@
|
|
|
1261
1270
|
{
|
|
1262
1271
|
"path": "skills/low-ram-advisor",
|
|
1263
1272
|
"kind": "skill",
|
|
1264
|
-
"note": "memwatch.py, memprobe.py, pooltags.py and
|
|
1273
|
+
"note": "memwatch.py, memprobe.py, pooltags.py, autofree.py, restart_verdict.py, ram_thresholds.py and handlecount.py are loaded by file path from mem_sampler.py for the leak watch and WSL cache auto-free; also its own bundle and claimed by heavy-gate-runner and agent-orchestration, safe to double-claim."
|
|
1274
|
+
},
|
|
1275
|
+
{
|
|
1276
|
+
"path": "skills/ram",
|
|
1277
|
+
"kind": "skill",
|
|
1278
|
+
"note": "Thin /ram entry point over skills/low-ram-advisor/ram_optimize.py; also its own claim in low-ram-advisor, safe to double-claim."
|
|
1265
1279
|
},
|
|
1266
1280
|
{
|
|
1267
1281
|
"path": "proxy/proc_policy.py",
|
|
@@ -1582,6 +1596,11 @@
|
|
|
1582
1596
|
"path": "scripts",
|
|
1583
1597
|
"kind": "infra"
|
|
1584
1598
|
},
|
|
1599
|
+
{
|
|
1600
|
+
"path": "proxy/route_lock.py",
|
|
1601
|
+
"kind": "infra",
|
|
1602
|
+
"note": "Imported by scripts/backfill_armed_repos.py (route-lock state reader) - not wired to an event itself. Already deployed by other bundles too; safe to double-claim, install.js is idempotent per-file."
|
|
1603
|
+
},
|
|
1585
1604
|
{
|
|
1586
1605
|
"path": "proxy/agents_env.py",
|
|
1587
1606
|
"kind": "hook",
|
|
@@ -1995,6 +2014,11 @@
|
|
|
1995
2014
|
"kind": "hook",
|
|
1996
2015
|
"note": "Shared reader of models.json imported by the model-aware hooks."
|
|
1997
2016
|
},
|
|
2017
|
+
{
|
|
2018
|
+
"path": "proxy/project_resolver.py",
|
|
2019
|
+
"kind": "infra",
|
|
2020
|
+
"note": "Shared GitLab-project-slug resolver the hook imports (and its tests) - not wired to an event itself. Already deployed by other bundles too; safe to double-claim, install.js is idempotent per-file."
|
|
2021
|
+
},
|
|
1998
2022
|
{
|
|
1999
2023
|
"path": "hooks/conclusion-scribe",
|
|
2000
2024
|
"targetPath": "hooks",
|
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
Sample record: {kind:"sample", ts, available_mb, commit_gb, top10:[{name,pid,private_mb}], running_gate_ids}
|
|
9
9
|
plus, on Windows with the low-ram-advisor skill installed (each key independent; a failing probe is named in watch_errors):
|
|
10
10
|
commit_limit_gb; pool:{paged_gb,nonpaged_gb,top:[[tag,bytes,live]]}; vms:[{name,pid,private_mb,ws_mb}] for vmmem*, vmwp,
|
|
11
|
-
vmware-vmx and Memory Compression; mem:{standby_mb,modified_mb,free_mb,paged_mb,paged_resident_mb,nonpaged_mb}.
|
|
11
|
+
vmware-vmx and Memory Compression; mem:{standby_mb,modified_mb,free_mb,paged_mb,paged_resident_mb,nonpaged_mb}; token_handles (open token handles in all processes).
|
|
12
12
|
The loop also runs the leak watch (alerts file for chat) and the non-disruptive WSL cache auto-free from that skill.
|
|
13
13
|
Other writers (reaper_kill_hook.py) share the file through append_record(). Never raises out of the loop.
|
|
14
14
|
"""
|
|
@@ -448,6 +448,12 @@ def pool_section(memwatch, pooltags) -> dict:
|
|
|
448
448
|
return memwatch.pool_fields(tags, _watched)
|
|
449
449
|
|
|
450
450
|
|
|
451
|
+
def token_handle_total() -> int:
|
|
452
|
+
import handlecount
|
|
453
|
+
|
|
454
|
+
return handlecount.token_holders()["token_total"]
|
|
455
|
+
|
|
456
|
+
|
|
451
457
|
def watch_fields() -> dict:
|
|
452
458
|
"""Leak-watch and attribution fields for a sample; {} off Windows or without the skill. A failing probe drops only its own key
|
|
453
459
|
and is named in `watch_errors`."""
|
|
@@ -462,6 +468,7 @@ def watch_fields() -> dict:
|
|
|
462
468
|
("pool", lambda: pool_section(memwatch, pooltags)),
|
|
463
469
|
("vms", lambda: memprobe.vm_snapshot(memprobe.nt_processes())),
|
|
464
470
|
("mem", memprobe.memory_lists_mb),
|
|
471
|
+
("token_handles", token_handle_total),
|
|
465
472
|
):
|
|
466
473
|
try:
|
|
467
474
|
value = build()
|
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
|
|
4
4
|
memory_reclaim.py --trigger {gate_launch,subagent_dispatch,manual} [--session-id ID] [--apply | --dry-run]
|
|
5
5
|
[--spine-release]
|
|
6
|
+
memory_reclaim.py ... [--budget-mb N] override the budget for this run
|
|
6
7
|
memory_reclaim.py --preflight [--session-id ID] report only: RAM vs budget, decisions, top hogs
|
|
7
8
|
|
|
8
9
|
Dry-run is the default; only --apply stops anything. Candidates are alive ledger rows, descendants of
|
|
@@ -471,6 +472,7 @@ def build_parser() -> argparse.ArgumentParser:
|
|
|
471
472
|
ap.add_argument("--spine-release", action="store_true",
|
|
472
473
|
help="release idle spine-claimed Metro of recorded owners through spine.py stop-metro (default off; always on for orphan Metro)")
|
|
473
474
|
ap.add_argument("--preflight", action="store_true")
|
|
475
|
+
ap.add_argument("--budget-mb", type=float, help="treat this as the budget instead of memory_budget.json (the ram skill passes the machine total)")
|
|
474
476
|
return ap
|
|
475
477
|
|
|
476
478
|
|
|
@@ -484,7 +486,7 @@ def main(argv: list[str] | None = None) -> int:
|
|
|
484
486
|
print(render_preflight(preflight(session_id=args.session_id)))
|
|
485
487
|
else:
|
|
486
488
|
print(json.dumps(reclaim(args.trigger, session_id=args.session_id, dry_run=not args.apply,
|
|
487
|
-
spine_release=args.spine_release)))
|
|
489
|
+
spine_release=args.spine_release, budget=args.budget_mb)))
|
|
488
490
|
except SystemExit:
|
|
489
491
|
raise
|
|
490
492
|
except Exception as exc:
|
package/content/skills/README.md
CHANGED
|
@@ -10,7 +10,8 @@ Global Claude Code skills. Installed to `~/.claude/skills/` — each subdirector
|
|
|
10
10
|
| `graphic-novel-pipeline` | `/graphic-novel-pipeline` · "start a new graphic novel" · "plan the panels" · "generate the images" · "graphic novel status" | Skill |
|
|
11
11
|
| `heavy-gate-runner` | no slash command · "run the full test gate" · "start a heavy gate" · "gate status" · "cancel the gate" | Skill |
|
|
12
12
|
| `launch-litellm` | "start litellm" · "litellm is down" · "restart litellm" · "is litellm up" · any council/web-search/visual-check connection failure | Skill |
|
|
13
|
-
| `
|
|
13
|
+
| `ram` | `/ram` · "optimize RAM" · "clear RAM" · "free up memory" | Skill |
|
|
14
|
+
| `low-ram-advisor` | no slash command · started in code by any free-RAM check · "free up RAM" · "what can I close" · "what's my RAM" · "should I restart" | Skill |
|
|
14
15
|
| `android-emulator` | no slash command · "start an emulator" · "emulator on the GPU" | Skill |
|
|
15
16
|
| `make-space` | "make space" · "make-space" · "disk critically low" · "free up space" · "we are out of space" | Skill |
|
|
16
17
|
| `mattpocock-codebase-design` | `/codebase-design` · "design this module's interface" · "find a deepening opportunity" · "where should this seam go" | Skill |
|
|
@@ -40,7 +41,10 @@ Project-agnostic image generation behind one provider interface. Default provide
|
|
|
40
41
|
Local headless emulator launcher for the Windows host. `emulator_launch.py start --avd NAME` tries `-accel on -gpu host`, then the AVD's own mode; a mode that exits or never reaches `sys.boot_completed` is stopped and the next one runs on the same port. Modes the installed emulator build rejects in a user-supplied chain (36.4.9 drops `angle_indirect`) are skipped, and a `host` request that silently lands on a software renderer is reported as `downgraded`. The result carries the emulator log line and the guest GLES renderer as proof. CI and non-Windows hosts keep the AVD default. Override with env `ANDROID_EMULATOR_GPU_CHAIN`. Stdlib only; tests in `skills/android-emulator/tests`.
|
|
41
42
|
|
|
42
43
|
### low-ram-advisor
|
|
43
|
-
Non-blocking, suggest-only RAM triage, the memory analogue of `make-space`. Any free-RAM check runs `advisor.py start --source S --free-gb F --required-gb R`, which spawns a detached hidden analysis (`pythonw`, no window) and prints exactly one line, the report path, in under a second; the caller keeps working. Each calling session gets its own report (`~/.claude/logs/low-ram-advisor/latest-<key>.md` + `.json`, plus `state-<key>.json`; one shared raw `snapshot.json` per cooldown window) that groups Claude sessions, Metro/node, Gradle/Java, Maestro, emulator, browsers, WSL/Docker, local proxies and IDEs with owner, safe-to-stop (`yes` only for the caller's own dev processes; shared daemons and other live sessions never), RAM freed, rank and a graceful pwsh stop command. The cooldown (default 300 s) is per session, and an atomic lock prevents scan storms. Reports and state files older than 7 days (env `LOW_RAM_ADVISOR_RETENTION_DAYS`) are pruned best-effort by the detached child. The code has no kill/suspend path; tests assert it. Optional owner hints: `~/.claude/low-ram-advisor-hints.json`.
|
|
44
|
+
Non-blocking, suggest-only RAM triage, the memory analogue of `make-space`. Any free-RAM check runs `advisor.py start --source S --free-gb F --required-gb R`, which spawns a detached hidden analysis (`pythonw`, no window) and prints exactly one line, the report path, in under a second; the caller keeps working. Each calling session gets its own report (`~/.claude/logs/low-ram-advisor/latest-<key>.md` + `.json`, plus `state-<key>.json`; one shared raw `snapshot.json` per cooldown window) that groups Claude sessions, Metro/node, Gradle/Java, Maestro, emulator, browsers, WSL/Docker, local proxies and IDEs with owner, safe-to-stop (`yes` only for the caller's own dev processes; shared daemons and other live sessions never), RAM freed, rank and a graceful pwsh stop command. The cooldown (default 300 s) is per session, and an atomic lock prevents scan storms. Reports and state files older than 7 days (env `LOW_RAM_ADVISOR_RETENTION_DAYS`) are pruned best-effort by the detached child. The code has no kill/suspend path; tests assert it. Optional owner hints: `~/.claude/low-ram-advisor-hints.json`. `ramstatus.py` prints a 10-line live RAM summary and an OK / RESTART SOON / RESTART NOW verdict (token leak, kernel pools, commit; thresholds in `ram_thresholds.py`); chat questions like "what's my RAM" or "should I restart" run it, and the deep report and leak alerts carry the same verdict.
|
|
45
|
+
|
|
46
|
+
### ram
|
|
47
|
+
Thin `/ram` entry point over `low-ram-advisor/ram_optimize.py`. One run frees what is safe (idle ledger-proven processes, CI janitor when no job runs, WSL page cache), prints MB freed per action, then RAM left, top groups, Windows kernel pools, the token leak size and the OK / RESTART SOON / RESTART NOW verdict, and lists user-app closes as suggestions only. Plain phrases like "optimize RAM" or "free up memory" start it through the chat hook.
|
|
44
48
|
|
|
45
49
|
### make-space
|
|
46
50
|
One-call disk reclamation meant to run in a single background subagent so the calling chat only receives a compact JSON report. Thin layer over `disk-cleanup`: deletes only allowlisted regenerable data (package caches, gradle caches, recycle bin, Temp older than 1 day with `Temp\claude` excluded) behind a code-enforced path guard with a hard denylist and `.git` protection; judgment items and removable worktrees are reported, never deleted. `-DryRun` previews; `-RemoveWorktrees` removes only audit-clean worktrees after user approval.
|
|
@@ -33,6 +33,18 @@ Python: `advisor.start(source, free_gb, required_gb, session_id=None, cwd=None,
|
|
|
33
33
|
| Storm guard | Atomic lock file (`.lock`); a held lock never blocks, the loser prints the current report path |
|
|
34
34
|
| Internal | `run --out <file> ...` is the detached child; exit `0` report written, `1` analysis failed (error report written) |
|
|
35
35
|
|
|
36
|
+
## /ram (optimize), RAM status and restart verdict
|
|
37
|
+
|
|
38
|
+
`ram_optimize.py` (skill `ram`, `/ram` or plain "optimize RAM", "clear RAM", "free up memory") runs the safe frees (idle reclaimer, CI janitor, WSL cache drop), prints MB freed per action, then the status below. User apps are suggestions only. `--dry-run` previews.
|
|
39
|
+
|
|
40
|
+
`python <skills>/low-ram-advisor/ramstatus.py [--json]` answers "what's my RAM", "RAM status" and "should I restart" in about 0.5 s with ~10 lines: RAM used/free, commit, top groups (Claude sessions, browsers, WSL/Docker VM, apps, Windows kernel), kernel paged/nonpaged pool, token leak size, and one `VERDICT: OK | RESTART SOON | RESTART NOW - <reason>` line. In chat, `ram_prompt.py` injects this output on those questions; answer from it.
|
|
41
|
+
|
|
42
|
+
| Item | Behavior |
|
|
43
|
+
|---|---|
|
|
44
|
+
| Thresholds | One file: `ram_thresholds.py` (token tags 2/4 GiB, paged pool 6/10 GiB, nonpaged pool 3/5 GiB, commit 85/95%); rules in `restart_verdict.py` |
|
|
45
|
+
| Token leak wording | Windows kernel leak on process creation: the token of a process that spawns children survives its exit; no driver or app owns it; `handlecount.py` shows live tokens vs open token handles; a restart is the only fix |
|
|
46
|
+
| Same verdict everywhere | Deep report header (`verdict` key), token and kernel-pool alerts in `memwatch.py`, `ramstatus.py` |
|
|
47
|
+
|
|
36
48
|
## Deep report
|
|
37
49
|
|
|
38
50
|
On a RAM, memory or slowness question the chat hook (`proxy/chat_inbox_hook.py` via `ram_prompt.py`) starts it and adds one path to the context: read that report and answer from it; do not run one-off probes. `advisor.start` starts it too when a gate fires.
|
|
@@ -44,7 +56,7 @@ On a RAM, memory or slowness question the chat hook (`proxy/chat_inbox_hook.py`
|
|
|
44
56
|
| Ranked actions | Only rows freeing 100 MB or more, reboot rows, and rows needed to cover the shortfall; the rest is one line (count and total MB). WSL memory is one row (cache drop, `wsl --shutdown` in its note). Rows without a command are not listed |
|
|
45
57
|
| Process kinds | `advisor.component()`: `os` = image under `C:\Windows`, Microsoft-published app package (name `Microsoft.*` or Microsoft publisher id) without window, or a name in `SYSTEM_NAMES` (`no`). Service = "set to Manual/Disabled" with its service name. Windowed pids get `CloseMainWindow`; that row counts only them and their same-name children, and a remaining windowless service or helper is its own row. Third-party Store app without window = `ask`, "close it from its tray icon". Unreadable path (elevated or protected) = `ask`, no command, label says so. Other windowless processes get no command |
|
|
46
58
|
| Leak cleared | A pool tag at 1 GiB or more in sampler history and now at a quarter or less: finding with peak, current baseline and growth per hour since boot as the slope of the lowest reading per 30 min (a leak is the floor rising, not a peak; needs 3 buckets, else the average since boot), plus a "bursts up to X MB" note for large swings above the floor; "cleared by reboot" when uptime is under 1 day |
|
|
47
|
-
| Probes | `memprobe.py` (commit, pagefile, standby/modified/free, hard page reads/s, Memory Compression, VMs, GPU, `.wslconfig`, uptime, Docker runners) and `pooltags.py` (kernel pool tags, owner map, leak heuristic) |
|
|
59
|
+
| Probes | `handlecount.py` (open token handles), `memprobe.py` (commit, pagefile, standby/modified/free, hard page reads/s, Memory Compression, VMs, GPU, `.wslconfig`, uptime, Docker runners) and `pooltags.py` (kernel pool tags, owner map, leak heuristic) |
|
|
48
60
|
| Leak watch | `mem_sampler.py` adds `commit_limit_gb`, top pool tags plus `pool.watch` (Toke, SeAt, `Key ` and any tag that reached 1 GiB, always recorded even at 0), `vms` (vmmem*, vmwp, vmware-vmx, Memory Compression: private and working set) and `mem` (standby, modified, free, kernel paged pool virtual and resident, nonpaged) to each sample, and the deep report shows the largest changes of the last hour; `memwatch.py` writes `~/.claude/logs/mem-alerts.json` when a tag grows fast or commit headroom is below 10%; an alert reaches one chat per 24 h |
|
|
49
61
|
| Auto-free | `autofree.py` only: `timeout 20 sync; echo 3 > /proc/sys/vm/drop_caches` in one running WSL distro when RAM is below budget (cooldown 15 min, VM at least 1.5 GiB, log `~/.claude/logs/auto-free.jsonl`) and `autoMemoryReclaim=dropCache` in `.wslconfig` (`autofree.py wslconfig --apply`, no `memory=` cap). Everything else stays suggest-only |
|
|
50
62
|
|
|
@@ -25,6 +25,8 @@ import autofree # noqa: E402
|
|
|
25
25
|
import memprobe # noqa: E402
|
|
26
26
|
import memwatch # noqa: E402
|
|
27
27
|
import pooltags # noqa: E402
|
|
28
|
+
import ram_thresholds # noqa: E402,F401
|
|
29
|
+
import restart_verdict # noqa: E402
|
|
28
30
|
|
|
29
31
|
GIB = 1024 ** 3
|
|
30
32
|
MIB = 1024 ** 2
|
|
@@ -88,6 +90,12 @@ def load_history() -> list[dict]:
|
|
|
88
90
|
return out
|
|
89
91
|
|
|
90
92
|
|
|
93
|
+
def token_handle_total() -> int:
|
|
94
|
+
import handlecount
|
|
95
|
+
|
|
96
|
+
return handlecount.token_holders()["token_total"]
|
|
97
|
+
|
|
98
|
+
|
|
91
99
|
def collect(gap_s: int = 3) -> dict:
|
|
92
100
|
raw: dict = {"collected_at": datetime.now().astimezone().isoformat(timespec="seconds"), "collected_ts": time.time()}
|
|
93
101
|
raw["pool_a"] = safe(pooltags.sample)
|
|
@@ -100,6 +108,7 @@ def collect(gap_s: int = 3) -> dict:
|
|
|
100
108
|
raw["wsl_distros"] = safe(memprobe.wsl_distros)
|
|
101
109
|
raw["docker"] = safe(memprobe.docker_containers)
|
|
102
110
|
raw["history"] = safe(load_history)
|
|
111
|
+
raw["token_handles"] = safe(token_handle_total)
|
|
103
112
|
return raw
|
|
104
113
|
|
|
105
114
|
|
|
@@ -135,7 +144,6 @@ def pool_findings(raw: dict, perf: dict) -> list[dict]:
|
|
|
135
144
|
a, b = raw.get("pool_a"), raw.get("pool_b")
|
|
136
145
|
if not ok(b):
|
|
137
146
|
return []
|
|
138
|
-
handles = perf.get("handles", 0) if ok(perf) else 0
|
|
139
147
|
out, tokens = [], []
|
|
140
148
|
for s in pooltags.suspects(b, a if ok(a) else None):
|
|
141
149
|
if s["tag"] in pooltags.TOKEN_TAGS:
|
|
@@ -146,13 +154,10 @@ def pool_findings(raw: dict, perf: dict) -> list[dict]:
|
|
|
146
154
|
f"{'; '.join(s['reasons'])}. {s['owner']}.", "Find the owning driver; a reboot clears it."))
|
|
147
155
|
if tokens:
|
|
148
156
|
lead, family = tokens[0], sum(t["bytes"] for t in tokens)
|
|
149
|
-
|
|
150
|
-
if handles and lead["live"] > 10 * handles:
|
|
151
|
-
tail = (f" Live tokens ({lead['live']:,}) far exceed all open handles ({handles:,}), so no process handle holds them: "
|
|
152
|
-
f"suspect a driver or logon-session leak, not an app.")
|
|
157
|
+
token_handles = raw.get("token_handles") if isinstance(raw.get("token_handles"), int) else None
|
|
153
158
|
out.insert(0, finding("pool-token", "high", f"Access-token kernel leak: {', '.join(t['tag'] for t in tokens)} hold {family / GIB:.1f} GiB",
|
|
154
|
-
f"{lead['reasons'][0]}. {lead['
|
|
155
|
-
"
|
|
159
|
+
f"{lead['reasons'][0]}. {restart_verdict.token_sentence(family, lead['live'], token_handles)}",
|
|
160
|
+
"Restart Windows; stopping apps will not free it.", kind="reboot"))
|
|
156
161
|
return out
|
|
157
162
|
|
|
158
163
|
|
|
@@ -379,13 +384,17 @@ def analyze(raw: dict, trigger: dict, hints: dict | None = None) -> dict:
|
|
|
379
384
|
pool.update(paged_gb=gib(counters["pool_paged_bytes"]), nonpaged_gb=gib(counters["pool_nonpaged_bytes"]),
|
|
380
385
|
paged_resident_gb=gib(counters["pool_paged_resident_bytes"]))
|
|
381
386
|
fs = findings(raw, rows)
|
|
387
|
+
verdict = restart_verdict.assess({
|
|
388
|
+
"token_bytes": sum(t["bytes"] for t in (pooltags.top(b, len(b)) if ok(b) else []) if t["tag"] in pooltags.TOKEN_TAGS),
|
|
389
|
+
"paged_pool_bytes": counters.get("pool_paged_bytes"), "nonpaged_pool_bytes": counters.get("pool_nonpaged_bytes"),
|
|
390
|
+
"commit_pct": host.get("commit_pct"), "available_gb": avail / GIB, "total_gb": total / GIB})
|
|
382
391
|
shortfall_mb = max(0.0, (trigger.get("required_gb") or 0) - avail / GIB) * 1024
|
|
383
392
|
actions, actions_hidden = make_actions(fs, rows, shortfall_mb)
|
|
384
393
|
handle_holders = sorted(({"name": p["name"], "pid": p["pid"], "handles": p.get("handles", 0)} for p in procs),
|
|
385
394
|
key=lambda p: -p["handles"])[:TOP_HANDLES]
|
|
386
395
|
return {"schema_version": SCHEMA_VERSION, "kind": "deep", "mode": "suggest-only", "generated_at": raw["collected_at"],
|
|
387
396
|
"trigger": {k: trigger.get(k) for k in ("source", "session_id", "cwd")},
|
|
388
|
-
"headline": headline(host, pool), "host": host, "kernel_pool": pool, "handle_holders": handle_holders,
|
|
397
|
+
"headline": headline(host, pool), "verdict": verdict, "host": host, "kernel_pool": pool, "handle_holders": handle_holders,
|
|
389
398
|
"vms": memprobe.vm_snapshot(procs), "wsl": {"config": raw.get("wslconfig"), "distros": raw.get("wsl_distros")},
|
|
390
399
|
"gpu": counters.get("gpu", []), "last_auto_free": last_auto_free(),
|
|
391
400
|
"timeline": memwatch.timeline(raw["history"]) if ok(raw.get("history")) else None,
|
|
@@ -400,7 +409,8 @@ def cell(s: object) -> str:
|
|
|
400
409
|
def render_markdown(rep: dict) -> str:
|
|
401
410
|
h = rep["host"]
|
|
402
411
|
lines = ["# Deep RAM report", "", f"Generated {rep['generated_at']} - trigger `{rep['trigger'].get('source')}` - "
|
|
403
|
-
"suggest-only: nothing was stopped. Only a Linux page-cache drop runs by itself.", "", f"**{rep['headline']}**", ""
|
|
412
|
+
"suggest-only: nothing was stopped. Only a Linux page-cache drop runs by itself.", "", f"**{rep['headline']}**", "",
|
|
413
|
+
f"**Verdict: {rep['verdict']['label']}** - {rep['verdict']['advice']}.", ""]
|
|
404
414
|
lines += ["## Findings", ""]
|
|
405
415
|
lines += [f"- **{f['severity']}** {cell(f['title'])}. {cell(f['detail'])} {cell(f['action'])}".rstrip() for f in rep["findings"]] or ["- none"]
|
|
406
416
|
lines += ["", "## What to free (ranked)", "", "| Rank | What | Frees MB | Cumulative MB | Kind | Safe | Do this (pwsh) |", "|---|---|---|---|---|---|---|"]
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
"""Per-process kernel handle counts by object type (NtQuerySystemInformation class 64). Stdlib only, read-only, ~45 ms."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import os
|
|
5
|
+
import struct
|
|
6
|
+
import sys
|
|
7
|
+
|
|
8
|
+
ENTRY = struct.Struct("<QQQIHHII")
|
|
9
|
+
ENTRY_SIZE = 40
|
|
10
|
+
HEADER = 16
|
|
11
|
+
STATUS_INFO_LENGTH_MISMATCH = 0xC0000004
|
|
12
|
+
EXTENDED_HANDLE_CLASS = 64
|
|
13
|
+
TOKEN_QUERY = 0x8
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def parse(buf: bytes, type_index: int) -> dict[int, int]:
|
|
17
|
+
"""pid -> number of handles of one object type."""
|
|
18
|
+
count = struct.unpack_from("<Q", buf, 0)[0]
|
|
19
|
+
out: dict[int, int] = {}
|
|
20
|
+
for i in range(count):
|
|
21
|
+
off = HEADER + i * ENTRY_SIZE
|
|
22
|
+
if off + ENTRY_SIZE > len(buf):
|
|
23
|
+
break
|
|
24
|
+
_obj, pid, _hv, _acc, _bt, ti, _at, _rs = ENTRY.unpack_from(buf, off)
|
|
25
|
+
if ti == type_index:
|
|
26
|
+
out[pid] = out.get(pid, 0) + 1
|
|
27
|
+
return out
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def type_index_of(buf: bytes, pid: int, handle_value: int) -> int:
|
|
31
|
+
count = struct.unpack_from("<Q", buf, 0)[0]
|
|
32
|
+
for i in range(count):
|
|
33
|
+
_obj, p, hv, _acc, _bt, ti, _at, _rs = ENTRY.unpack_from(buf, HEADER + i * ENTRY_SIZE)
|
|
34
|
+
if p == pid and hv == handle_value:
|
|
35
|
+
return ti
|
|
36
|
+
raise LookupError("own handle not in the table")
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _table() -> bytes:
|
|
40
|
+
import ctypes
|
|
41
|
+
from ctypes import wintypes
|
|
42
|
+
|
|
43
|
+
nt = ctypes.WinDLL("ntdll")
|
|
44
|
+
nt.NtQuerySystemInformation.argtypes = [wintypes.ULONG, ctypes.c_void_p, wintypes.ULONG, ctypes.POINTER(wintypes.ULONG)]
|
|
45
|
+
nt.NtQuerySystemInformation.restype = ctypes.c_long
|
|
46
|
+
size = 16 << 20
|
|
47
|
+
for _ in range(8):
|
|
48
|
+
buf = ctypes.create_string_buffer(size)
|
|
49
|
+
ret = wintypes.ULONG()
|
|
50
|
+
status = nt.NtQuerySystemInformation(EXTENDED_HANDLE_CLASS, buf, size, ctypes.byref(ret)) & 0xFFFFFFFF
|
|
51
|
+
if status == STATUS_INFO_LENGTH_MISMATCH:
|
|
52
|
+
size = max(ret.value, size) + (8 << 20)
|
|
53
|
+
continue
|
|
54
|
+
if status != 0:
|
|
55
|
+
raise OSError(f"NtQuerySystemInformation status {status:#x}")
|
|
56
|
+
return buf.raw
|
|
57
|
+
raise OSError("handle table kept growing")
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def token_holders(top_n: int = 8) -> dict:
|
|
61
|
+
"""{"token_total": n, "top": [[pid, token_handles], ...]}. Raises OSError off Windows or when the query is refused."""
|
|
62
|
+
if sys.platform != "win32":
|
|
63
|
+
raise OSError("handle table needs Windows")
|
|
64
|
+
import ctypes
|
|
65
|
+
from ctypes import wintypes
|
|
66
|
+
|
|
67
|
+
adv, k32 = ctypes.WinDLL("advapi32"), ctypes.WinDLL("kernel32")
|
|
68
|
+
k32.GetCurrentProcess.restype = wintypes.HANDLE
|
|
69
|
+
adv.OpenProcessToken.argtypes = [wintypes.HANDLE, wintypes.DWORD, ctypes.POINTER(wintypes.HANDLE)]
|
|
70
|
+
k32.CloseHandle.argtypes = [wintypes.HANDLE]
|
|
71
|
+
probe = wintypes.HANDLE()
|
|
72
|
+
if not adv.OpenProcessToken(k32.GetCurrentProcess(), TOKEN_QUERY, ctypes.byref(probe)):
|
|
73
|
+
raise OSError("OpenProcessToken failed")
|
|
74
|
+
try:
|
|
75
|
+
buf = _table()
|
|
76
|
+
counts = parse(buf, type_index_of(buf, os.getpid(), probe.value))
|
|
77
|
+
finally:
|
|
78
|
+
k32.CloseHandle(probe)
|
|
79
|
+
ranked = sorted(counts.items(), key=lambda kv: kv[1], reverse=True)[:top_n]
|
|
80
|
+
return {"token_total": sum(counts.values()), "top": [[pid, n] for pid, n in ranked]}
|
|
@@ -7,6 +7,8 @@ import os
|
|
|
7
7
|
import time
|
|
8
8
|
|
|
9
9
|
import pooltags
|
|
10
|
+
import ram_thresholds as th
|
|
11
|
+
import restart_verdict
|
|
10
12
|
|
|
11
13
|
GIB = 1024 ** 3
|
|
12
14
|
MIB = 1024 ** 2
|
|
@@ -91,6 +93,16 @@ def _family_sizes(sample: dict) -> dict[str, tuple[int, int, str]]:
|
|
|
91
93
|
return {fam: (sizes[fam], lead[fam][1], lead[fam][2]) for fam in sizes}
|
|
92
94
|
|
|
93
95
|
|
|
96
|
+
def _verdict_sentence(fam: str, size: int, latest: dict, owner: str) -> str:
|
|
97
|
+
if fam != TOKEN_KEY:
|
|
98
|
+
return f"{owner}."
|
|
99
|
+
return restart_verdict.token_sentence(size, restart_verdict.token_leak(_pool(latest))[1], latest.get("token_handles"))
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def pool_sizes(sample: dict) -> dict[str, tuple[int, int]]:
|
|
103
|
+
return _pool(sample)
|
|
104
|
+
|
|
105
|
+
|
|
94
106
|
def _sustained(series: list[int]) -> bool:
|
|
95
107
|
if len(series) < GROWTH_MIN_POINTS:
|
|
96
108
|
return False
|
|
@@ -109,7 +121,8 @@ def evaluate_full(history: list[dict], now: float | None = None) -> tuple[list[d
|
|
|
109
121
|
headroom = (limit - used) / limit * 100
|
|
110
122
|
if headroom < HEADROOM_WARN_PCT:
|
|
111
123
|
alerts.append({"key": "commit_low", "severity": "high",
|
|
112
|
-
"text": f"Commit headroom is {headroom:.0f}% ({used:.1f} of {limit:.1f} GiB). New programs can fail to start."
|
|
124
|
+
"text": f"Commit headroom is {headroom:.0f}% ({used:.1f} of {limit:.1f} GiB). New programs can fail to start. "
|
|
125
|
+
"Close the biggest apps; restart Windows if it stays high."})
|
|
113
126
|
if _pool(latest):
|
|
114
127
|
domains.add("pool")
|
|
115
128
|
window = [s for s in history[:-1] if now - float(s.get("ts", now)) <= POOL_LOOKBACK_S and _pool(s)]
|
|
@@ -123,13 +136,20 @@ def evaluate_full(history: list[dict], now: float | None = None) -> tuple[list[d
|
|
|
123
136
|
series = [fs[fam][0] for fs in (_family_sizes(x) for x in window if float(x["ts"]) >= float(base_sample["ts"])) if fam in fs]
|
|
124
137
|
series.append(size)
|
|
125
138
|
grew = size - series[0] if _sustained(series) else 0
|
|
139
|
+
says = _verdict_sentence(fam, size, latest, owner)
|
|
126
140
|
if size >= POOL_MIN_BYTES and grew >= POOL_GROWTH_BYTES:
|
|
127
141
|
alerts.append({"key": f"pool:{fam}", "severity": "high",
|
|
128
142
|
"text": f"{label} grew {grew / MIB:.0f} MiB in {(now - float(base_sample['ts'])) / 60:.0f} min "
|
|
129
|
-
f"(now {size / GIB:.1f} GiB). {
|
|
143
|
+
f"(now {size / GIB:.1f} GiB). {says}"})
|
|
130
144
|
elif size >= POOL_LARGE_BYTES:
|
|
131
|
-
alerts.append({"key": f"pool:{fam}", "severity": "medium",
|
|
132
|
-
"text": f"{label} hold {size / GIB:.1f} GiB in {live:,} allocations. {
|
|
145
|
+
alerts.append({"key": f"pool:{fam}", "severity": "high" if fam == TOKEN_KEY and size >= th.TOKEN_NOW_BYTES else "medium",
|
|
146
|
+
"text": f"{label} hold {size / GIB:.1f} GiB in {live:,} allocations. {says}"})
|
|
147
|
+
mem = latest.get("mem") or {}
|
|
148
|
+
kernel = restart_verdict.assess({"paged_pool_bytes": float(mem.get("paged_mb") or 0) * MIB,
|
|
149
|
+
"nonpaged_pool_bytes": float(mem.get("nonpaged_mb") or 0) * MIB})
|
|
150
|
+
if kernel["level"] != "ok":
|
|
151
|
+
alerts.append({"key": "kernel_pool", "severity": "high" if kernel["level"] == "now" else "medium",
|
|
152
|
+
"text": f"{kernel['advice']}. Verdict: {kernel['label'].lower()}."})
|
|
133
153
|
return alerts, domains
|
|
134
154
|
|
|
135
155
|
|
|
@@ -18,10 +18,13 @@ LEAK_MIN_BYTES = 1 * GIB
|
|
|
18
18
|
LEAK_MIN_OUTSTANDING = 500_000
|
|
19
19
|
LEAK_GROWTH_BYTES = 64 * MIB
|
|
20
20
|
|
|
21
|
+
TOKEN_LEAK_NOTE = ("Windows kernel token leak: the token of a process that started child processes (bash.exe, sh.exe, node.exe) survives the "
|
|
22
|
+
"process exit. Almost no token has a handle, and no driver or app owns it. A restart is the only fix")
|
|
23
|
+
|
|
21
24
|
# Advisory owner hints; exact tags first, then 4-char-or-shorter prefixes.
|
|
22
25
|
TAG_OWNERS = {
|
|
23
|
-
"Toke":
|
|
24
|
-
"SeAt": "Token security attributes (nt!se); grows with
|
|
26
|
+
"Toke": TOKEN_LEAK_NOTE,
|
|
27
|
+
"SeAt": "Token security attributes (nt!se); grows with the token leak",
|
|
25
28
|
"SeTd": "Token security data (nt!se); grows with a token leak",
|
|
26
29
|
"SeDt": "Token security descriptors (nt!se); grows with a token leak",
|
|
27
30
|
"SeTl": "Token security lists (nt!se); grows with a token leak",
|
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""/ram: free what is safe to free, report MB freed per action, then report what is left with the restart verdict.
|
|
3
|
+
|
|
4
|
+
python ram_optimize.py [--dry-run] [--no-suggestions] [--json]
|
|
5
|
+
|
|
6
|
+
Actions (all existing safe mechanisms, graceful only): idle reclaimer (ledger-proven idle processes, memory_reclaim.py), CI janitor
|
|
7
|
+
(only when no CI job runs), WSL page-cache drop (autofree.py). User apps are only listed as suggestions with their graceful command.
|
|
8
|
+
Exits 0 always.
|
|
9
|
+
"""
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import html
|
|
13
|
+
import json
|
|
14
|
+
import os
|
|
15
|
+
import re
|
|
16
|
+
import shutil
|
|
17
|
+
import subprocess
|
|
18
|
+
import sys
|
|
19
|
+
import time
|
|
20
|
+
|
|
21
|
+
HERE = os.path.dirname(os.path.abspath(__file__))
|
|
22
|
+
if HERE not in sys.path:
|
|
23
|
+
sys.path.insert(0, HERE)
|
|
24
|
+
import autofree # noqa: E402
|
|
25
|
+
import memprobe # noqa: E402
|
|
26
|
+
import ramstatus # noqa: E402
|
|
27
|
+
import restart_verdict # noqa: E402
|
|
28
|
+
|
|
29
|
+
GIB = 1024 ** 3
|
|
30
|
+
MIB = 1024 ** 2
|
|
31
|
+
RECLAIM_TIMEOUT_S = 90
|
|
32
|
+
JANITOR_TIMEOUT_S = 120
|
|
33
|
+
SUGGESTIONS = 5
|
|
34
|
+
SETTLE_S = 2.0
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def proxy_dir() -> str:
|
|
38
|
+
return os.path.join(os.path.dirname(os.path.dirname(HERE)), "proxy")
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def available_mb() -> float:
|
|
42
|
+
return (memprobe.performance_info().get("physical_available") or 0) / MIB
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def total_mb() -> float:
|
|
46
|
+
return (memprobe.performance_info().get("physical_total") or 0) / MIB
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def step(name: str, freed_mb: float, detail: str, **extra) -> dict:
|
|
50
|
+
return {"name": name, "freed_mb": round(freed_mb), "detail": detail, **extra}
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def run_reclaim(dry_run: bool, runner=subprocess.run) -> dict:
|
|
54
|
+
"""Idle reclaimer with the budget raised to the machine total, so it stops every ledger-proven idle process instead of waiting for low RAM."""
|
|
55
|
+
script = os.path.join(proxy_dir(), "memory_reclaim.py")
|
|
56
|
+
if not os.path.isfile(script):
|
|
57
|
+
return step("Idle reclaimer", 0, "not installed")
|
|
58
|
+
cmd = [sys.executable, script, "--trigger", "manual", "--budget-mb", str(round(total_mb()))] + ([] if dry_run else ["--apply"])
|
|
59
|
+
try:
|
|
60
|
+
out = runner(cmd, capture_output=True, text=True, timeout=RECLAIM_TIMEOUT_S, creationflags=memprobe.no_window())
|
|
61
|
+
data = json.loads((out.stdout or "").strip().splitlines()[-1])
|
|
62
|
+
except Exception as exc:
|
|
63
|
+
return step("Idle reclaimer", 0, f"failed: {type(exc).__name__}")
|
|
64
|
+
stopped = int(data.get("stopped") or 0)
|
|
65
|
+
planned = [d for d in data.get("decisions") or [] if len(d) > 1 and d[1] == "stop"]
|
|
66
|
+
freed = max(0, data.get("available_after_mb", 0) - data.get("available_before_mb", 0))
|
|
67
|
+
if data.get("action") == "none":
|
|
68
|
+
return step("Idle reclaimer", 0, f"nothing to stop ({data.get('reason')})")
|
|
69
|
+
if dry_run:
|
|
70
|
+
return step("Idle reclaimer", 0, f"would stop {len(planned)} idle recorded process(es)")
|
|
71
|
+
return step("Idle reclaimer", freed if stopped else 0, f"stopped {stopped} idle recorded process(es), graceful only")
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
JANITOR_TASK = "ClaudeCiJanitor"
|
|
75
|
+
TASK_CLI = re.compile(r'"([^"]*node(?:\.exe)?)"\s+"([^"]*cli\.js)"', re.I)
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def task_command(runner=subprocess.run, exists=os.path.isfile) -> list[str] | None:
|
|
79
|
+
"""node + cli.js exactly as the ClaudeCiJanitor task runs them (the install record), when both files still exist."""
|
|
80
|
+
try:
|
|
81
|
+
out = runner(["schtasks", "/query", "/tn", JANITOR_TASK, "/xml"], capture_output=True, text=True, timeout=15,
|
|
82
|
+
creationflags=memprobe.no_window())
|
|
83
|
+
m = TASK_CLI.search(html.unescape(out.stdout or ""))
|
|
84
|
+
except Exception:
|
|
85
|
+
return None
|
|
86
|
+
return [m.group(1), m.group(2)] if m and exists(m.group(1)) and exists(m.group(2)) else None
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def janitor_command(runner=subprocess.run, which=shutil.which, exists=os.path.isfile) -> list[str] | None:
|
|
90
|
+
"""The janitor CLI: the ClaudeCiJanitor task's node + cli.js, else agents-cli on PATH, else cli.js next to this checkout."""
|
|
91
|
+
base = task_command(runner, exists)
|
|
92
|
+
if base:
|
|
93
|
+
return base + ["runner", "janitor"]
|
|
94
|
+
if which("agents-cli"):
|
|
95
|
+
return [which("agents-cli"), "runner", "janitor"]
|
|
96
|
+
cli = os.path.join(os.path.dirname(os.path.dirname(HERE)), "packages", "cli", "bin", "cli.js")
|
|
97
|
+
node = which("node")
|
|
98
|
+
return [node, cli, "runner", "janitor"] if node and exists(cli) else None
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def run_janitor(dry_run: bool, runner=subprocess.run) -> dict:
|
|
102
|
+
cmd = janitor_command()
|
|
103
|
+
if cmd is None:
|
|
104
|
+
return step("CI janitor", 0, "janitor CLI not found (no ClaudeCiJanitor task, no agents-cli on PATH), skipped")
|
|
105
|
+
try:
|
|
106
|
+
out = runner(cmd + (["--dry-run"] if dry_run else []), capture_output=True, text=True, timeout=JANITOR_TIMEOUT_S,
|
|
107
|
+
creationflags=memprobe.no_window())
|
|
108
|
+
except Exception as exc:
|
|
109
|
+
return step("CI janitor", 0, f"failed: {type(exc).__name__}")
|
|
110
|
+
lines = [ln.strip() for ln in (out.stdout or "").splitlines() if ln.strip()]
|
|
111
|
+
busy = next((ln for ln in lines if "job container" in ln and "running" in ln), "")
|
|
112
|
+
if busy:
|
|
113
|
+
return step("CI janitor", 0, "CI jobs are running, nothing touched")
|
|
114
|
+
return step("CI janitor", 0, f"{lines[-1] if lines else 'no output'} (frees disk, not RAM)")
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def run_wsl_drop(dry_run: bool) -> dict:
|
|
118
|
+
try:
|
|
119
|
+
r = autofree.maybe_drop("ram-skill", force=True, dry_run=dry_run)
|
|
120
|
+
except Exception as exc:
|
|
121
|
+
return step("WSL page-cache drop", 0, f"failed: {type(exc).__name__}")
|
|
122
|
+
if dry_run:
|
|
123
|
+
return step("WSL page-cache drop", 0, f"would drop in {r.get('distro') or 'no running distro'} (VM {r.get('vm_ws_mb')} MB)")
|
|
124
|
+
if not r.get("dropped"):
|
|
125
|
+
return step("WSL page-cache drop", 0, f"skipped: {r.get('skipped') or r.get('error') or 'not dropped'}")
|
|
126
|
+
freed = (r.get("vm_ws_before_mb") or 0) - (r.get("vm_ws_after_mb") or 0)
|
|
127
|
+
return step("WSL page-cache drop", max(0, freed), f"VM {r.get('vm_ws_before_mb')} to {r.get('vm_ws_after_mb')} MB in {r.get('distro')}")
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def suggestions() -> list[dict]:
|
|
131
|
+
"""Ranked user-app closes from the deep report analysis (never executed here)."""
|
|
132
|
+
import deep_report
|
|
133
|
+
|
|
134
|
+
raw = deep_report.collect(gap_s=2)
|
|
135
|
+
rep = deep_report.analyze(raw, {"source": "ram-skill", "session_id": None, "cwd": os.getcwd()})
|
|
136
|
+
return [{"what": a["what"], "mb": a["est_freed_mb"], "safe": a["safe_to_stop"], "command": a["command"]}
|
|
137
|
+
for a in rep["actions"] if a["command"] and a["kind"] not in ("reboot", "auto") and "autofree.py" not in a["command"]][:SUGGESTIONS]
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def render(report: dict) -> str:
|
|
141
|
+
lines = [f"RAM optimize{' (dry run, nothing changed)' if report['dry_run'] else ''}: available {report['before_gb']:.1f} GiB before"]
|
|
142
|
+
lines += [f" {s['name']}: {'freed ' + str(s['freed_mb']) + ' MB' if s['freed_mb'] else 'freed 0 MB'} - {s['detail']}" for s in report["steps"]]
|
|
143
|
+
lines.append(f"Available now: {report['after_gb']:.1f} GiB ({report['delta_mb']:+d} MB)")
|
|
144
|
+
lines += ["", report["status_text"]]
|
|
145
|
+
if report["suggestions"]:
|
|
146
|
+
lines += ["", "You decide (nothing below was closed):"]
|
|
147
|
+
lines += [f" {s['what']} (~{s['mb']} MB): {s['command']}" for s in report["suggestions"]]
|
|
148
|
+
return "\n".join(lines)
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def optimize(dry_run: bool = False, with_suggestions: bool = True) -> dict:
|
|
152
|
+
before = available_mb()
|
|
153
|
+
steps = [run_reclaim(dry_run), run_janitor(dry_run), run_wsl_drop(dry_run)]
|
|
154
|
+
if not dry_run:
|
|
155
|
+
time.sleep(SETTLE_S)
|
|
156
|
+
after = available_mb()
|
|
157
|
+
facts = ramstatus.collect()
|
|
158
|
+
verdict = restart_verdict.assess(facts)
|
|
159
|
+
try:
|
|
160
|
+
tips = suggestions() if with_suggestions else []
|
|
161
|
+
except Exception:
|
|
162
|
+
tips = []
|
|
163
|
+
return {"dry_run": dry_run, "before_gb": before / 1024, "after_gb": after / 1024, "delta_mb": round(after - before), "steps": steps,
|
|
164
|
+
"verdict": verdict, "suggestions": tips, "status_text": ramstatus.render(facts, verdict)}
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def main(argv: list[str] | None = None) -> int:
|
|
168
|
+
args = sys.argv[1:] if argv is None else argv
|
|
169
|
+
if sys.platform != "win32":
|
|
170
|
+
print("ram_optimize needs Windows")
|
|
171
|
+
return 0
|
|
172
|
+
report = optimize(dry_run="--dry-run" in args, with_suggestions="--no-suggestions" not in args)
|
|
173
|
+
print(json.dumps(report, indent=2) if "--json" in args else render(report))
|
|
174
|
+
return 0
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
if __name__ == "__main__":
|
|
178
|
+
sys.exit(main())
|