@yasaswy.nagavolu/agents 0.30.3 → 0.31.0

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 (38) hide show
  1. package/bin/cli.js +2 -0
  2. package/content/manifest.json +2 -13
  3. package/content/proxy/README.md +1 -2
  4. package/content/proxy/chat_inbox_hook.py +10 -24
  5. package/content/proxy/chat_ledger.py +1 -32
  6. package/content/proxy/mem_sampler.py +12 -2
  7. package/content/proxy/memory_reclaim.py +1 -16
  8. package/content/proxy/proc_policy.py +2 -8
  9. package/content/skills/README.md +1 -1
  10. package/content/skills/ci-runner/SKILL.md +2 -0
  11. package/content/skills/low-ram-advisor/SKILL.md +17 -37
  12. package/content/skills/low-ram-advisor/advisor.py +2 -190
  13. package/content/skills/low-ram-advisor/memwatch.py +19 -115
  14. package/content/skills/low-ram-advisor/ram_notice.py +42 -0
  15. package/content/skills/low-ram-advisor/ram_optimize.py +29 -1
  16. package/content/skills/low-ram-advisor/ram_prompt.py +4 -83
  17. package/content/skills/low-ram-advisor/tests/conftest.py +1 -0
  18. package/content/skills/low-ram-advisor/tests/test_advisor.py +14 -280
  19. package/content/skills/low-ram-advisor/tests/test_deep_report.py +9 -9
  20. package/content/skills/low-ram-advisor/tests/test_memwatch.py +40 -79
  21. package/content/skills/low-ram-advisor/tests/test_ram_notice.py +54 -0
  22. package/content/skills/low-ram-advisor/tests/test_ram_optimize.py +37 -10
  23. package/content/skills/low-ram-advisor/tests/test_ram_prompt.py +10 -85
  24. package/content/skills/low-ram-advisor/tests/test_restart_verdict.py +0 -23
  25. package/content/statusline/statusline-command.ps1 +9 -0
  26. package/content/statusline/statusline-command.py +10 -0
  27. package/lib/memSafety.js +1 -2
  28. package/lib/runner/args.js +6 -2
  29. package/lib/runner/budget.js +27 -21
  30. package/lib/runner/cap.js +164 -0
  31. package/lib/runner/index.js +32 -14
  32. package/lib/runner/janitor.js +16 -55
  33. package/lib/runner/janitorPlan.js +14 -87
  34. package/lib/runner/managed.js +20 -24
  35. package/lib/runner/pool.js +14 -89
  36. package/package.json +1 -1
  37. package/content/proxy/memory_reclaim_hook.py +0 -86
  38. package/content/skills/low-ram-advisor/tests/test_advisor_deep.py +0 -45
package/bin/cli.js CHANGED
@@ -184,6 +184,8 @@ Flags for runner:
184
184
  runner attach | detach --project-id <id> Enable/disable the saved runners on a project (--no-cloud on
185
185
  attach also turns off cloud runners for it)
186
186
  runner pool --pool-file <spec> [--apply] Merge runners into one capped pool (dry run without --apply; refuses while a job runs)
187
+ runner cap <class> <size> Change a class memory cap now (for example: runner cap release 12g); no restart, running jobs keep the old cap
188
+ runner concurrent <n> | pause | resume Change the job slots, or stop and start taking jobs (running jobs finish)
187
189
  runner janitor [--dry-run] [--watch] Remove finished job containers, per-job volumes and unused images; --watch cleans after every job
188
190
  runner init-project [--profile node|python|docker|macos|blank] [--write] [--attach --project-id <id>]
189
191
  Write a .gitlab-ci.yml that uses the shared templates (dry run unless --write)
@@ -680,7 +680,7 @@
680
680
  {
681
681
  "path": "proxy/chat_ledger.py",
682
682
  "kind": "hook",
683
- "note": "Chat ledger, heartbeat, ownership proof and owner inbox library (record_launch, heartbeat, owner_of, is_idle, notify_owner, audit) imported by bg_process_registry.py and chat_inbox_hook.py — not wired to an event itself."
683
+ "note": "Chat ledger, heartbeat and ownership proof library (record_launch, heartbeat, owner_of, is_idle, audit) imported by bg_process_registry.py and chat_inbox_hook.py — not wired to an event itself."
684
684
  },
685
685
  {
686
686
  "path": "proxy/proc_policy.py",
@@ -731,7 +731,7 @@
731
731
  {
732
732
  "path": "proxy/memory_reclaim.py",
733
733
  "kind": "hook",
734
- "note": "Background memory reclaimer: below budget it stops idle recorded processes (dry-run by default), notifies owners, logs reclaim_run; --preflight reports only. Started by memory_reclaim_hook.py — not wired to an event itself."
734
+ "note": "Background memory reclaimer: below budget it stops idle recorded processes (dry-run by default), logs reclaim_run; --preflight reports only. Started by heavy_gate_runner.py at gate start and by the /ram skill — not wired to an event itself."
735
735
  },
736
736
  {
737
737
  "path": "skills/low-ram-advisor",
@@ -743,16 +743,6 @@
743
743
  "kind": "skill",
744
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
745
  },
746
- {
747
- "path": "proxy/memory_reclaim_hook.py",
748
- "kind": "hook",
749
- "wiring": {
750
- "event": "PreToolUse",
751
- "matcher": "Agent",
752
- "type": "command",
753
- "command": "node ~/.claude/hooks/pyrun.js ~/.claude/proxy/memory_reclaim_hook.py"
754
- }
755
- },
756
746
  {
757
747
  "path": "proxy/reaper_kill_hook.py",
758
748
  "kind": "hook",
@@ -2460,7 +2450,6 @@
2460
2450
  }
2461
2451
  ],
2462
2452
  "internal": [
2463
- "config/runner-pool.json",
2464
2453
  "hooks/test_tracker_proof_gate.py",
2465
2454
  "agents/lint_agent_tools.py",
2466
2455
  "agents/test_lint_agent_tools.py",
@@ -217,8 +217,7 @@ Installed by the `agent-orchestration` bundle (my-agents#57). Rules, install, co
217
217
  | `mem_sampler.py` | Library and `--loop`/`--once` sampler; one record per minute to `~/.claude/logs/mem-samples.jsonl` |
218
218
  | `register_mem_sampler.ps1` | Registers the hidden logon task `ClaudeMemSampler` (`-WhatIf`, `-Unregister`, `-TaskName`); run by `agents-cli install/update/sampler` |
219
219
  | `memory_reclaim.py` | Reclaimer CLI (`--trigger`, `--apply`, `--preflight`); dry-run by default |
220
- | `memory_reclaim_hook.py` | `PreToolUse` matcher `Agent`: starts the reclaimer when RAM is below budget |
221
- | `chat_inbox_hook.py` | `UserPromptSubmit`, `PreToolUse` and `SessionEnd`: session heartbeat (turn flag cleared at `SessionEnd`) and owner inbox delivery; on `UserPromptSubmit` also starts the deep RAM report on a RAM question and shows leak-watch alerts (low-ram-advisor skill) |
220
+ | `chat_inbox_hook.py` | `UserPromptSubmit`, `PreToolUse` and `SessionEnd`: session heartbeat (turn flag cleared at `SessionEnd`); on `UserPromptSubmit` adds the /ram instruction only when the user asked to free RAM (low-ram-advisor skill); no alert, note or RAM answer reaches a chat |
222
221
  | `reaper_kill_hook.py` | `UserPromptSubmit`: records Claude Code low-memory task kills |
223
222
 
224
223
  ---
@@ -1,13 +1,12 @@
1
1
  #!/usr/bin/env python3
2
- """chat_inbox_hook.py — UserPromptSubmit, PreToolUse and SessionEnd hook: per-session heartbeat, owner inbox delivery, turn flag cleared at SessionEnd.
2
+ """chat_inbox_hook.py — UserPromptSubmit, PreToolUse and SessionEnd hook: per-session heartbeat and turn flag.
3
3
 
4
4
  - UserPromptSubmit: marks the turn running, records which Claude process hosts the session.
5
5
  - PreToolUse: refreshes last_activity (throttled) so a working chat is never judged idle.
6
- - UserPromptSubmit also starts the deep RAM report (low-ram-advisor skill) on a RAM/memory/slowness question or an unseen
7
- leak-watch alert and adds its path to the context.
8
6
  - SessionEnd: marks the turn not running so a closed chat never holds its processes as "turn running".
9
- - Prompt and tool events: pending notes in ~/.claude/logs/chat_inbox/<session_id>.jsonl (e.g. "your idle dev server was
10
- stopped to free memory") are shown once as additionalContext on the chat's next turn or tool call.
7
+ - UserPromptSubmit adds RAM text to the context only when the user asked about RAM or asked to free it (ram_prompt.context_for:
8
+ the short ramstatus summary, or the /ram instruction). Alerts, leak watch and reclaimer results never reach the chat; they go to
9
+ the one-line statusline alert (skills/low-ram-advisor/ram_notice.py) and to logs.
11
10
 
12
11
  Fail-open: any malformed input or internal error exits 0 with no output.
13
12
 
@@ -28,14 +27,8 @@ import chat_ledger as ledger
28
27
  TOUCH_INTERVAL_SECONDS = 10
29
28
 
30
29
 
31
- def _render(notes: list[dict]) -> str:
32
- lines = [f"[chat-inbox] {len(notes)} note(s) for this chat:"]
33
- lines += [f"- {n.get('text', '')}" for n in notes]
34
- return "\n".join(lines)
35
-
36
-
37
- def _ram_context(payload: dict, session_id: str) -> str:
38
- """Deep RAM report trigger from the sibling low-ram-advisor skill; "" when the skill is absent or nothing applies."""
30
+ def _asked_ram_context(payload: dict) -> str:
31
+ """RAM text for a prompt where the user asked about RAM; "" for every other prompt or when the skill is absent."""
39
32
  skill = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "skills", "low-ram-advisor")
40
33
  if not os.path.isfile(os.path.join(skill, "ram_prompt.py")):
41
34
  return ""
@@ -44,7 +37,7 @@ def _ram_context(payload: dict, session_id: str) -> str:
44
37
  sys.path.insert(0, skill)
45
38
  import ram_prompt
46
39
 
47
- return ram_prompt.context_for(str(payload.get("prompt") or ""), session_id, payload.get("cwd"))
40
+ return ram_prompt.context_for(str(payload.get("prompt") or ""))
48
41
  except Exception:
49
42
  return ""
50
43
 
@@ -74,17 +67,10 @@ def _safe_main() -> int:
74
67
  ledger.heartbeat(session_id, turn_running=True, cwd=payload.get("cwd"), claude=ledger.current_claude(), now=now)
75
68
  elif stale or not prior.get("turn_running"):
76
69
  ledger.heartbeat(session_id, turn_running=True, cwd=payload.get("cwd"), now=now)
77
- parts = []
78
- if ledger.has_notes(session_id):
79
- notes = ledger.consume_notes(session_id)
80
- if notes:
81
- parts.append(_render(notes))
82
70
  if event == "UserPromptSubmit":
83
- ram = _ram_context(payload, session_id)
84
- if ram:
85
- parts.append(ram)
86
- if parts:
87
- print(json.dumps({"hookSpecificOutput": {"hookEventName": event, "additionalContext": "\n".join(parts)}}))
71
+ asked = _asked_ram_context(payload)
72
+ if asked:
73
+ print(json.dumps({"hookSpecificOutput": {"hookEventName": event, "additionalContext": asked}}))
88
74
  except Exception as exc:
89
75
  print(f"[chat_inbox_hook] error: {exc}", file=sys.stderr)
90
76
  return 0
@@ -1,4 +1,4 @@
1
- """chat_ledger: record_launch, heartbeat, owner_of, is_idle, notify_owner, audit -- ownership proof and heartbeat state for per-chat process cleanup (my-agents#57)."""
1
+ """chat_ledger: record_launch, heartbeat, owner_of, is_idle, audit -- ownership proof and heartbeat state for per-chat process cleanup (my-agents#57)."""
2
2
  from __future__ import annotations
3
3
 
4
4
  import hashlib
@@ -743,37 +743,6 @@ def _tree_cpu(procs: ProcTable, members: list[int]) -> float:
743
743
  return sum((procs.get(p) or {}).get("cpu", 0.0) for p in members)
744
744
 
745
745
 
746
- def notify_owner(session_id: str, text: str, **meta: Any) -> None:
747
- if not session_id:
748
- return
749
- _append_line(_path("chat_inbox", f"{_safe(session_id)}.jsonl"), {"ts": time.time(), "text": text, **meta})
750
-
751
-
752
- def consume_notes(session_id: str) -> list[dict]:
753
- src = _path("chat_inbox", f"{_safe(session_id)}.jsonl")
754
- if not os.path.exists(src):
755
- return []
756
- taken = f"{src}.{os.getpid()}.{threading.get_ident()}.taken"
757
- with _Locked(src):
758
- try:
759
- os.replace(src, taken)
760
- except OSError:
761
- return []
762
- try:
763
- return _read_lines(taken)
764
- except ProofUnreadable:
765
- return []
766
- finally:
767
- try:
768
- os.unlink(taken)
769
- except OSError:
770
- pass
771
-
772
-
773
- def has_notes(session_id: str) -> bool:
774
- return os.path.exists(_path("chat_inbox", f"{_safe(session_id)}.jsonl"))
775
-
776
-
777
746
  def audit(pid: int, name: str, owner_session: str | None, decision: str, reason: str, **extra: Any) -> dict:
778
747
  rec = {"ts": time.time(), "pid": pid, "name": name, "owner_session": owner_session,
779
748
  "decision": decision, "reason": reason, **extra}
@@ -9,7 +9,7 @@ Sample record: {kind:"sample", ts, available_mb, commit_gb, top10:[{name,pid,pri
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
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
- The loop also runs the leak watch (alerts file for chat) and the non-disruptive WSL cache auto-free from that skill.
12
+ The loop also runs the leak watch (one statusline alert line via ram_notice.py) 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
  """
15
15
  from __future__ import annotations
@@ -590,6 +590,16 @@ def _free_safely(available_mb: float) -> None:
590
590
  _report_once("auto-free tick", exc)
591
591
 
592
592
 
593
+ def _write_alert(memwatch, history: list[dict]) -> None:
594
+ import ram_notice
595
+
596
+ text = memwatch.restart_alert(history)
597
+ if text:
598
+ ram_notice.write_alert(text)
599
+ else:
600
+ ram_notice.clear_alert("RAM:")
601
+
602
+
593
603
  def watch_and_free(history: list[dict], available_mb: float) -> bool:
594
604
  """Leak watch runs inline (milliseconds, file only). The auto-free tick may spawn wsl.exe and wait, so it runs in a worker
595
605
  thread that never delays the watch; False while a previous tick still runs."""
@@ -597,7 +607,7 @@ def watch_and_free(history: list[dict], available_mb: float) -> bool:
597
607
  mods = advisor_modules()
598
608
  if mods is not None:
599
609
  try:
600
- mods[2].update(history)
610
+ _write_alert(mods[2], history)
601
611
  except Exception as exc:
602
612
  _report_once("leak watch update", exc)
603
613
  if _free_thread is not None and _free_thread.is_alive():
@@ -276,14 +276,6 @@ def _record_orphan_stop(result: dict, cand: dict, trigger: str, method: str) ->
276
276
  "method": method, "trigger": trigger, "owner_session": None})
277
277
 
278
278
 
279
- def _idle_minutes(ledger, pid: int, ctime: float, now: float) -> int:
280
- state = ledger._read_json(ledger._path("chat_cpu_state.json")) or {}
281
- rec = state.get(f"{pid}_{int(ctime * 1000)}")
282
- since = rec.get("since") if isinstance(rec, dict) else None
283
- floor = int(ledger.IDLE_SECONDS // 60)
284
- return max(floor, int((now - since) // 60)) if since else floor
285
-
286
-
287
279
  def reclaim(trigger: str, *, session_id: str | None = None, dry_run: bool = True, spine_release: bool = False,
288
280
  now: float | None = None, read_available=None, budget: float | None = None) -> dict:
289
281
  t_start = time.monotonic()
@@ -327,11 +319,6 @@ def _reclaim_locked(summary: dict, before: float, budget: float, *, session_id,
327
319
  _record(summary, results, releases, t_start)
328
320
  return summary
329
321
 
330
- def note(d: dict) -> str:
331
- minutes = _idle_minutes(ledger, d["pid"], d["create_time"], now)
332
- return (f"Memory was low: stopped idle {d['name']} (pid {d['pid']}) after {minutes} min idle. "
333
- "Start it again if you still need it.")
334
-
335
322
  avail = before
336
323
  for cand in cands:
337
324
  if avail >= budget or time.monotonic() > deadline:
@@ -340,7 +327,7 @@ def _reclaim_locked(summary: dict, before: float, budget: float, *, session_id,
340
327
  results.append({"pid": cand["pid"], "decision": "keep", "reason": why, "result": "kept"})
341
328
  continue
342
329
  r = proc_policy.run_cleanup([(cand["pid"], cand["create_time"])], invoker_session=None, scope="idle",
343
- spine_check=guard, dry_run=dry_run, reason=trigger, now=now, note=note)[0]
330
+ spine_check=guard, dry_run=dry_run, reason=trigger, now=now)[0]
344
331
  results.append(r)
345
332
  if r["decision"] == "stop":
346
333
  if r.get("rule") and not dry_run and r.get("result") in ("stopped_gracefully", "stopped_forced"):
@@ -370,8 +357,6 @@ def _reclaim_locked(summary: dict, before: float, budget: float, *, session_id,
370
357
  _record_orphan_stop(r, cand, trigger, outcome["method"])
371
358
  time.sleep(SETTLE_S)
372
359
  avail = read_available()
373
- if r["owner_session"] and ledger.session_alive(r["owner_session"]) is not False:
374
- ledger.notify_owner(r["owner_session"], note(r), pid=cand["pid"], name=r["name"])
375
360
  releases.append(entry)
376
361
  if not dry_run:
377
362
  avail = read_available()
@@ -394,7 +394,7 @@ def stop_proven(pid: int, create_time: float, *, force: bool) -> str:
394
394
  def run_cleanup(candidates: list[tuple[int, float | None]], *, invoker_session: str | None, scope: str,
395
395
  spine_check: Callable[[int, str | None], bool], dry_run: bool = True,
396
396
  reason: str = "", now: float | None = None,
397
- note: Callable[[dict], str] | None = None, force: bool | None = None) -> list[dict]:
397
+ force: bool | None = None) -> list[dict]:
398
398
  """Decide, audit (one line per pid) and, unless dry_run, stop. Decision fields are identical for dry and real runs.
399
399
  Force-stop is allowed only for the idle scope unless the caller passes force explicitly."""
400
400
  now = now if now is not None else time.time()
@@ -409,22 +409,16 @@ def run_cleanup(candidates: list[tuple[int, float | None]], *, invoker_session:
409
409
  d = {"pid": pid, "create_time": ctime, "name": "", "owner_session": None, "proof": "unreadable",
410
410
  "class": None, "decision": "keep", "reason": f"proof_unreadable:{type(exc).__name__}"}
411
411
  result = "dry_run" if dry_run else "kept"
412
- notified = False
413
412
  if d["decision"] == "stop" and not dry_run:
414
413
  result = stop_proven(d["pid"], d["create_time"], force=force)
415
414
  if result not in ("stop_failed", "kept_running"):
416
415
  live = procs.get(d["pid"])
417
416
  if live:
418
417
  _cooldown_mark(_victim_key(live["cmdline"], d["owner_session"]), now)
419
- owner_alive = ledger.session_alive(d["owner_session"], procs)
420
- notified = bool(d["owner_session"]) and d["owner_session"] != invoker_session and owner_alive is not False
421
- if notified:
422
- text = note(d) if note else f"Process {d['name']} (pid {d['pid']}) was idle and stopped to free memory ({reason or scope})."
423
- ledger.notify_owner(d["owner_session"], text, pid=d["pid"], name=d["name"])
424
418
  extra = {"rule": d["rule"]} if d.get("rule") else {}
425
419
  ledger.audit(d["pid"], d["name"], d["owner_session"], d["decision"], d["reason"],
426
420
  proof=d["proof"], cls=d["class"], scope=scope, invoker=invoker_session,
427
- dry_run=dry_run, result=result, trigger=reason, owner_notified=notified, **extra)
421
+ dry_run=dry_run, result=result, trigger=reason, **extra)
428
422
  results.append({**d, "result": result})
429
423
  return results
430
424
 
@@ -41,7 +41,7 @@ Project-agnostic image generation behind one provider interface. Default provide
41
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`.
42
42
 
43
43
  ### low-ram-advisor
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.
44
+ Suggest-only RAM triage, the memory analogue of `make-space`, run on demand. `deep_report.py start` writes a report of commit, pagefile, kernel pool leaks, WSL/Docker VM, GPU and CI findings; `advisor.py` is the ranking library that groups Claude sessions, Metro/node, Gradle/Java, Maestro, emulator, browsers, WSL/Docker, local proxies and IDEs with owner, safe-to-stop, RAM freed and a graceful pwsh stop command. The code has no kill/suspend path; tests assert it. `ramstatus.py` prints a 10-line live RAM summary and an OK / RESTART SOON / RESTART NOW verdict (thresholds in `ram_thresholds.py`); run it on demand. Alerts never enter a chat: the sampler writes a `soon` or `now` verdict to the one-line statusline file `~/.claude/state/ram-alert.txt` through `ram_notice.py`.
45
45
 
46
46
  ### ram
47
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.
@@ -26,6 +26,8 @@ CLI = `npx @yasaswy.nagavolu/agents`. Always start with `CLI runner status`.
26
26
  | Any command exits 1 | `CLI runner doctor`, then follow its fix hints |
27
27
  | CI memory piles up, Docker disk is full, or runners need caps | `CLI runner pool --pool-file <spec>` (plan), then `--apply` when no job runs |
28
28
  | Clean finished jobs now | `CLI runner janitor [--dry-run]` |
29
+ | Change a class memory cap | `CLI runner cap <class> <size>` (for example `runner cap release 12g`) |
30
+ | CI eats RAM now | `CLI runner pause` (running jobs finish), `runner resume`, or `runner concurrent <n>` |
29
31
 
30
32
  Exit codes: 0 ok, 1 a step failed (read the failed step), 2 usage error (fix the flags).
31
33
 
@@ -1,43 +1,19 @@
1
1
  ---
2
2
  name: low-ram-advisor
3
- description: Background, suggest-only RAM triage plus a deep RAM report. Any free-RAM check calls `start` in code when RAM is low; it detaches, returns one report path in under 1 second and never blocks or stops the caller's work. The report groups memory hogs (Claude sessions, Metro/node, Gradle, Maestro, emulator, browsers, WSL/Docker, local proxies, IDEs) with owner, safe-to-stop, RAM freed, rank and a graceful pwsh stop command. The deep report adds commit and pagefile, kernel pool leaks, WSL/Docker VM, GPU and CI runner findings, and starts by itself on a RAM, memory or slowness question in chat. Use when free RAM is below what a task needs, or the user asks what can be closed to free RAM or why the PC is slow.
3
+ description: Suggest-only RAM triage on demand: ranked report of memory hogs (Claude sessions, Metro/node, Gradle, Maestro, emulator, browsers, WSL/Docker, local proxies, IDEs) with owner, safe-to-stop, RAM freed and a graceful pwsh stop command, plus a deep RAM report (commit and pagefile, kernel pool leaks, WSL/Docker VM, GPU, CI runner findings). Alerts never go into working chats: a restart-soon verdict or a CI cap event writes one line to the statusline. Use when the user asks what can be closed to free RAM, why the PC is slow, or whether to restart.
4
4
  ---
5
5
 
6
6
  # low-ram-advisor
7
7
 
8
8
  Low RAM is a prompt to offer options, never a reason to wait or fail.
9
9
  The advisor only reads process state and writes reports. It has no path that stops, signals or suspends a process. The separate background reclaimer may stop idle, ledger-proven processes of any chat: [`docs/memory-safety.md`](../../docs/memory-safety.md).
10
- All mechanics live in `advisor.py` (stdlib; uses `psutil` when installed). Deep report, leak watch and auto-free: [Deep report](#deep-report).
11
-
12
- ## Trigger contract
13
-
14
- | Rule | Detail |
15
- |---|---|
16
- | Who calls | Any code that checks free RAM (gates, preflights, spine); call it whenever free < required |
17
- | Caller behavior | Print or relay the path, then continue the work in parallel; never wait, never exit non-zero because of RAM |
18
- | Chat context | The one printed path is all the chat sees; read the report only if the user asks |
19
-
20
- ## Entrypoint
21
-
22
- `python <skills>/low-ram-advisor/advisor.py start --source <who> --free-gb <F> --required-gb <R> [--session-id <id>] [--cwd <dir>] [--cooldown-sec N]`
23
-
24
- Python: `advisor.start(source, free_gb, required_gb, session_id=None, cwd=None, cooldown_sec=None) -> Path`
25
-
26
- | Item | Behavior |
27
- |---|---|
28
- | stdout | Exactly one line: absolute path of the markdown report |
29
- | Exit code | `0` always, including bad or missing args, bad env, spawn or disk errors (a best-effort path is still printed). A spawn failure is written into the report and clears the cooldown |
30
- | Speed | Returns in under 1 second; analysis runs in a detached hidden child (`pythonw`, no window, no focus) |
31
- | Cooldown | Per calling session (key: session id, else normalised cwd). Repeat starts by the same session within the window (default 300 s, env `LOW_RAM_ADVISOR_COOLDOWN_SEC`, bad value falls back to default) print the same path and spawn nothing |
32
- | Snapshot cache | The raw process snapshot (`snapshot.json`) is shared machine-wide for the cooldown window; ownership and safe-to-stop are computed per caller, so sessions never see each other's report |
33
- | Storm guard | Atomic lock file (`.lock`); a held lock never blocks, the loser prints the current report path |
34
- | Internal | `run --out <file> ...` is the detached child; exit `0` report written, `1` analysis failed (error report written) |
10
+ `advisor.py` is the ranking library (stdlib; uses `psutil` when installed): `deep_report.py`, `ramstatus.py` and `memory_reclaim.py --preflight` import it. It has no start, spawn, cooldown or lock path. Deep report, leak watch and auto-free: [Deep report](#deep-report).
35
11
 
36
12
  ## /ram (optimize), RAM status and restart verdict
37
13
 
38
14
  `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
15
 
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.
16
+ `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 only a /ram request adds context (the skill instruction); questions, alerts and notes add nothing (see [Alerts](#alerts)). Ask for the status by running `ramstatus.py`.
41
17
 
42
18
  | Item | Behavior |
43
19
  |---|---|
@@ -47,7 +23,7 @@ Python: `advisor.start(source, free_gb, required_gb, session_id=None, cwd=None,
47
23
 
48
24
  ## Deep report
49
25
 
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.
26
+ Started on demand only (nothing spawns it automatically): run the entrypoint below, then read `latest-deep.md`.
51
27
 
52
28
  | Item | Behavior |
53
29
  |---|---|
@@ -57,19 +33,12 @@ On a RAM, memory or slowness question the chat hook (`proxy/chat_inbox_hook.py`
57
33
  | 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 |
58
34
  | 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 |
59
35
  | 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) |
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 |
36
+ | 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. Every sampler tick `memwatch.restart_alert` picks the worst `soon` or `now` finding (token leak, kernel pool, commit headroom below 10%); the sampler writes it as the statusline alert, or clears its own `RAM:` line when none remains. Normal pool growth is a deep-report finding only |
61
37
  | 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 |
62
38
 
63
39
  ## Output (`~/.claude/logs/low-ram-advisor/`, override with env `LOW_RAM_ADVISOR_DIR`)
64
40
 
65
- | File | Content |
66
- |---|---|
67
- | `<timestamp>.md` / `.json` | One report; the `.md` shows "analysis running" until the child finishes (seconds) |
68
- | `latest-<key>.md` / `.json` | Copy of that session's newest finished report |
69
- | `state-<key>.json` | Per-session cooldown marker (start time and report path) |
70
- | `snapshot.json` | Shared raw process snapshot |
71
-
72
- Retention: after writing a report the detached child prunes, best-effort (errors ignored), `<timestamp>`, `state-*` and `latest-*` files untouched for 7 days (env `LOW_RAM_ADVISOR_RETENTION_DAYS`, bad value falls back to 7). It never deletes the current caller's files or any file modified within the cooldown window.
41
+ `deep-<ts>.md` / `.json` and `latest-deep.md` / `.json` (deep report), `snapshot.json` (raw process snapshot). Report files are pruned by the deep report run (env `LOW_RAM_ADVISOR_RETENTION_DAYS`, default 7).
73
42
 
74
43
  JSON keys: `schema_version`, `mode` (`suggest-only`), `generated_at`, `trigger`, `host {total_gb, free_gb, shortfall_gb}`, `covers_shortfall_at_rank`, `rows[]`.
75
44
  Row keys: `rank`, `group`, `label`, `pids`, `count`, `ram_mb`, `owner`, `safe_to_stop`, `est_freed_mb`, `cumulative_freed_mb`, `stop_command`.
@@ -93,3 +62,14 @@ First matching hint wins; an invalid regex is skipped; `yes` is ignored and OS/C
93
62
  ## Tests
94
63
 
95
64
  `python -m pytest skills/low-ram-advisor/tests -q`
65
+
66
+ ## Alerts
67
+
68
+ One channel for every RAM, leak, memory or CI-cleanup alert: the file `~/.claude/state/ram-alert.txt` (env `RAM_ALERT_PATH`), written only by `ram_notice.py`. The statusline shows it on the pill line (hidden when older than 24 h); it costs no chat tokens. `proxy/tests/test_ram_notice_contract.py` enforces the contract.
69
+
70
+ | Rule | Detail |
71
+ |---|---|
72
+ | Shape | One line, at most 15 words, overwritten by the newest writer, deleted when clear; tables and newlines are flattened |
73
+ | Write / clear | `import ram_notice` (from `~/.claude/skills/low-ram-advisor/`), `ram_notice.write_alert("RAM: restart Windows soon.")`, `ram_notice.clear_alert("RAM:")` (with a prefix it deletes only its own line). The CI janitor and cap events write the same file from JS (`packages/cli/lib/runner/cap.js`) |
74
+ | Writers | Sampler tick (`RAM:` restart verdict at `soon` or above); CI janitor and cap events (`CI:`) |
75
+ | Never in a chat | No hook writes alerts, notes, leak-watch or reclaimer results into a chat. Only a /ram request adds context for that one prompt (`ram_prompt.context_for`) |