@yasaswy.nagavolu/agents 0.30.2 → 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 (49) hide show
  1. package/bin/cli.js +2 -0
  2. package/content/manifest.json +25 -12
  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 +20 -3
  7. package/content/proxy/memory_reclaim.py +4 -17
  8. package/content/proxy/proc_policy.py +2 -8
  9. package/content/skills/README.md +6 -2
  10. package/content/skills/ci-runner/SKILL.md +2 -0
  11. package/content/skills/low-ram-advisor/SKILL.md +23 -31
  12. package/content/skills/low-ram-advisor/advisor.py +2 -190
  13. package/content/skills/low-ram-advisor/deep_report.py +19 -9
  14. package/content/skills/low-ram-advisor/handlecount.py +80 -0
  15. package/content/skills/low-ram-advisor/memwatch.py +43 -119
  16. package/content/skills/low-ram-advisor/pooltags.py +5 -2
  17. package/content/skills/low-ram-advisor/ram_notice.py +42 -0
  18. package/content/skills/low-ram-advisor/ram_optimize.py +206 -0
  19. package/content/skills/low-ram-advisor/ram_prompt.py +15 -53
  20. package/content/skills/low-ram-advisor/ram_thresholds.py +13 -0
  21. package/content/skills/low-ram-advisor/ramstatus.py +121 -0
  22. package/content/skills/low-ram-advisor/restart_verdict.py +72 -0
  23. package/content/skills/low-ram-advisor/tests/conftest.py +1 -0
  24. package/content/skills/low-ram-advisor/tests/test_advisor.py +14 -280
  25. package/content/skills/low-ram-advisor/tests/test_deep_report.py +19 -12
  26. package/content/skills/low-ram-advisor/tests/test_handlecount.py +36 -0
  27. package/content/skills/low-ram-advisor/tests/test_memwatch.py +40 -79
  28. package/content/skills/low-ram-advisor/tests/test_ram_notice.py +54 -0
  29. package/content/skills/low-ram-advisor/tests/test_ram_optimize.py +182 -0
  30. package/content/skills/low-ram-advisor/tests/test_ram_prompt.py +10 -85
  31. package/content/skills/low-ram-advisor/tests/test_restart_verdict.py +100 -0
  32. package/content/skills/ram/SKILL.md +26 -0
  33. package/content/statusline/statusline-command.ps1 +9 -0
  34. package/content/statusline/statusline-command.py +10 -0
  35. package/lib/memSafety.js +1 -2
  36. package/lib/runner/args.js +6 -2
  37. package/lib/runner/budget.js +27 -21
  38. package/lib/runner/cap.js +164 -0
  39. package/lib/runner/exec.js +2 -2
  40. package/lib/runner/index.js +38 -15
  41. package/lib/runner/janitor.js +16 -55
  42. package/lib/runner/janitorPlan.js +14 -87
  43. package/lib/runner/managed.js +21 -25
  44. package/lib/runner/pool.js +15 -90
  45. package/lib/runner/profiles/linuxDocker.js +1 -1
  46. package/lib/runner/profiles/macosShell.js +1 -1
  47. package/package.json +1 -1
  48. package/content/proxy/memory_reclaim_hook.py +0 -86
  49. 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)
@@ -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": [],
@@ -676,7 +680,7 @@
676
680
  {
677
681
  "path": "proxy/chat_ledger.py",
678
682
  "kind": "hook",
679
- "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."
680
684
  },
681
685
  {
682
686
  "path": "proxy/proc_policy.py",
@@ -727,7 +731,7 @@
727
731
  {
728
732
  "path": "proxy/memory_reclaim.py",
729
733
  "kind": "hook",
730
- "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."
731
735
  },
732
736
  {
733
737
  "path": "skills/low-ram-advisor",
@@ -735,14 +739,9 @@
735
739
  "note": "Ranking logic imported by memory_reclaim.py; also its own bundle, safe to double-claim."
736
740
  },
737
741
  {
738
- "path": "proxy/memory_reclaim_hook.py",
739
- "kind": "hook",
740
- "wiring": {
741
- "event": "PreToolUse",
742
- "matcher": "Agent",
743
- "type": "command",
744
- "command": "node ~/.claude/hooks/pyrun.js ~/.claude/proxy/memory_reclaim_hook.py"
745
- }
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."
746
745
  },
747
746
  {
748
747
  "path": "proxy/reaper_kill_hook.py",
@@ -1261,7 +1260,12 @@
1261
1260
  {
1262
1261
  "path": "skills/low-ram-advisor",
1263
1262
  "kind": "skill",
1264
- "note": "memwatch.py, memprobe.py, pooltags.py and autofree.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."
1263
+ "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."
1264
+ },
1265
+ {
1266
+ "path": "skills/ram",
1267
+ "kind": "skill",
1268
+ "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
1269
  },
1266
1270
  {
1267
1271
  "path": "proxy/proc_policy.py",
@@ -1582,6 +1586,11 @@
1582
1586
  "path": "scripts",
1583
1587
  "kind": "infra"
1584
1588
  },
1589
+ {
1590
+ "path": "proxy/route_lock.py",
1591
+ "kind": "infra",
1592
+ "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."
1593
+ },
1585
1594
  {
1586
1595
  "path": "proxy/agents_env.py",
1587
1596
  "kind": "hook",
@@ -1995,6 +2004,11 @@
1995
2004
  "kind": "hook",
1996
2005
  "note": "Shared reader of models.json imported by the model-aware hooks."
1997
2006
  },
2007
+ {
2008
+ "path": "proxy/project_resolver.py",
2009
+ "kind": "infra",
2010
+ "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."
2011
+ },
1998
2012
  {
1999
2013
  "path": "hooks/conclusion-scribe",
2000
2014
  "targetPath": "hooks",
@@ -2436,7 +2450,6 @@
2436
2450
  }
2437
2451
  ],
2438
2452
  "internal": [
2439
- "config/runner-pool.json",
2440
2453
  "hooks/test_tracker_proof_gate.py",
2441
2454
  "agents/lint_agent_tools.py",
2442
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}
@@ -8,8 +8,8 @@
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}.
12
- The loop also runs the leak watch (alerts file for chat) and the non-disruptive WSL cache auto-free from that skill.
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 (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
@@ -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()
@@ -583,6 +590,16 @@ def _free_safely(available_mb: float) -> None:
583
590
  _report_once("auto-free tick", exc)
584
591
 
585
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
+
586
603
  def watch_and_free(history: list[dict], available_mb: float) -> bool:
587
604
  """Leak watch runs inline (milliseconds, file only). The auto-free tick may spawn wsl.exe and wait, so it runs in a worker
588
605
  thread that never delays the watch; False while a previous tick still runs."""
@@ -590,7 +607,7 @@ def watch_and_free(history: list[dict], available_mb: float) -> bool:
590
607
  mods = advisor_modules()
591
608
  if mods is not None:
592
609
  try:
593
- mods[2].update(history)
610
+ _write_alert(mods[2], history)
594
611
  except Exception as exc:
595
612
  _report_once("leak watch update", exc)
596
613
  if _free_thread is not None and _free_thread.is_alive():
@@ -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
@@ -275,14 +276,6 @@ def _record_orphan_stop(result: dict, cand: dict, trigger: str, method: str) ->
275
276
  "method": method, "trigger": trigger, "owner_session": None})
276
277
 
277
278
 
278
- def _idle_minutes(ledger, pid: int, ctime: float, now: float) -> int:
279
- state = ledger._read_json(ledger._path("chat_cpu_state.json")) or {}
280
- rec = state.get(f"{pid}_{int(ctime * 1000)}")
281
- since = rec.get("since") if isinstance(rec, dict) else None
282
- floor = int(ledger.IDLE_SECONDS // 60)
283
- return max(floor, int((now - since) // 60)) if since else floor
284
-
285
-
286
279
  def reclaim(trigger: str, *, session_id: str | None = None, dry_run: bool = True, spine_release: bool = False,
287
280
  now: float | None = None, read_available=None, budget: float | None = None) -> dict:
288
281
  t_start = time.monotonic()
@@ -326,11 +319,6 @@ def _reclaim_locked(summary: dict, before: float, budget: float, *, session_id,
326
319
  _record(summary, results, releases, t_start)
327
320
  return summary
328
321
 
329
- def note(d: dict) -> str:
330
- minutes = _idle_minutes(ledger, d["pid"], d["create_time"], now)
331
- return (f"Memory was low: stopped idle {d['name']} (pid {d['pid']}) after {minutes} min idle. "
332
- "Start it again if you still need it.")
333
-
334
322
  avail = before
335
323
  for cand in cands:
336
324
  if avail >= budget or time.monotonic() > deadline:
@@ -339,7 +327,7 @@ def _reclaim_locked(summary: dict, before: float, budget: float, *, session_id,
339
327
  results.append({"pid": cand["pid"], "decision": "keep", "reason": why, "result": "kept"})
340
328
  continue
341
329
  r = proc_policy.run_cleanup([(cand["pid"], cand["create_time"])], invoker_session=None, scope="idle",
342
- 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]
343
331
  results.append(r)
344
332
  if r["decision"] == "stop":
345
333
  if r.get("rule") and not dry_run and r.get("result") in ("stopped_gracefully", "stopped_forced"):
@@ -369,8 +357,6 @@ def _reclaim_locked(summary: dict, before: float, budget: float, *, session_id,
369
357
  _record_orphan_stop(r, cand, trigger, outcome["method"])
370
358
  time.sleep(SETTLE_S)
371
359
  avail = read_available()
372
- if r["owner_session"] and ledger.session_alive(r["owner_session"]) is not False:
373
- ledger.notify_owner(r["owner_session"], note(r), pid=cand["pid"], name=r["name"])
374
360
  releases.append(entry)
375
361
  if not dry_run:
376
362
  avail = read_available()
@@ -471,6 +457,7 @@ def build_parser() -> argparse.ArgumentParser:
471
457
  ap.add_argument("--spine-release", action="store_true",
472
458
  help="release idle spine-claimed Metro of recorded owners through spine.py stop-metro (default off; always on for orphan Metro)")
473
459
  ap.add_argument("--preflight", action="store_true")
460
+ 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
461
  return ap
475
462
 
476
463
 
@@ -484,7 +471,7 @@ def main(argv: list[str] | None = None) -> int:
484
471
  print(render_preflight(preflight(session_id=args.session_id)))
485
472
  else:
486
473
  print(json.dumps(reclaim(args.trigger, session_id=args.session_id, dry_run=not args.apply,
487
- spine_release=args.spine_release)))
474
+ spine_release=args.spine_release, budget=args.budget_mb)))
488
475
  except SystemExit:
489
476
  raise
490
477
  except Exception as exc:
@@ -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
 
@@ -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
- | `low-ram-advisor` | no slash command · started in code by any free-RAM check · "free up RAM" · "what can I close" | Skill |
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
+ 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
+
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.
@@ -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,41 +1,29 @@
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).
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).
11
11
 
12
- ## Trigger contract
12
+ ## /ram (optimize), RAM status and restart verdict
13
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
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.
21
15
 
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`
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`.
25
17
 
26
18
  | Item | Behavior |
27
19
  |---|---|
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) |
20
+ | 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` |
21
+ | 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 |
22
+ | Same verdict everywhere | Deep report header (`verdict` key), token and kernel-pool alerts in `memwatch.py`, `ramstatus.py` |
35
23
 
36
24
  ## Deep report
37
25
 
38
- 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`.
39
27
 
40
28
  | Item | Behavior |
41
29
  |---|---|
@@ -44,20 +32,13 @@ On a RAM, memory or slowness question the chat hook (`proxy/chat_inbox_hook.py`
44
32
  | 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
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 |
46
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 |
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) |
48
- | 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 |
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) |
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 |
49
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 |
50
38
 
51
39
  ## Output (`~/.claude/logs/low-ram-advisor/`, override with env `LOW_RAM_ADVISOR_DIR`)
52
40
 
53
- | File | Content |
54
- |---|---|
55
- | `<timestamp>.md` / `.json` | One report; the `.md` shows "analysis running" until the child finishes (seconds) |
56
- | `latest-<key>.md` / `.json` | Copy of that session's newest finished report |
57
- | `state-<key>.json` | Per-session cooldown marker (start time and report path) |
58
- | `snapshot.json` | Shared raw process snapshot |
59
-
60
- 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).
61
42
 
62
43
  JSON keys: `schema_version`, `mode` (`suggest-only`), `generated_at`, `trigger`, `host {total_gb, free_gb, shortfall_gb}`, `covers_shortfall_at_rank`, `rows[]`.
63
44
  Row keys: `rank`, `group`, `label`, `pids`, `count`, `ram_mb`, `owner`, `safe_to_stop`, `est_freed_mb`, `cumulative_freed_mb`, `stop_command`.
@@ -81,3 +62,14 @@ First matching hint wins; an invalid regex is skipped; `yes` is ignored and OS/C
81
62
  ## Tests
82
63
 
83
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`) |