layerctl 0.2.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
layerctl/tui.py ADDED
@@ -0,0 +1,887 @@
1
+ #!/usr/bin/env python3
2
+ """venice/layers - A/B/C/D layer switchboard (non-root, rish backend)"""
3
+ import argparse
4
+ import collections
5
+ import contextlib
6
+ import curses
7
+ import json
8
+ import os
9
+ import re
10
+ import sys
11
+ import time
12
+
13
+ HOME = os.path.expanduser("~")
14
+ RISH = os.path.join(HOME, "rish")
15
+
16
+ # 所在は main() 内で paths.state_dir() を1回通して決める。
17
+ # シム (layers) は cd 前に LAYERCTL_ORIG_CWD を export し、paths.py は
18
+ # それを cwd 規則と相対パス解決の基準に使う (直接実行時は未設定)。
19
+ TSV = None # layers.tsv (意志 — seed だけが書く)
20
+ OBS = None # layers.observed.tsv (観測 — snapshot だけが書く)
21
+ SDIR = None # 解決済み state dir (--profile と plan --json が参照)
22
+ PLAN_TXT = None
23
+ STATE = None # last-kill の時刻記録
24
+
25
+ LAYERS = ["0", "A", "B1", "B2", "C1", "C2", "D"]
26
+ TITLE = {"0": "UNTOUCHABLE", "A": "DAILY", "B1": "THROTTLED", "B2": "FREQUENT",
27
+ "C1": "DEAD", "C2": "PINNED", "D": "GREYOUT"}
28
+ DESC = {"0": "instant / doze-protected", "A": "resident allowed",
29
+ "B1": "background cut / notif delayed", "B2": "notif kept",
30
+ "C1": "disabled", "C2": "protected pkg / throttled",
31
+ "D": "root required / no diff"}
32
+ ACTION = {"0": "protect", "A": "none", "B1": "restrict", "B2": "frequent",
33
+ "C1": "disable", "C2": "restrict", "D": "root"}
34
+
35
+ # 端末固有データは profiles/ に分離。下の load_profile() で注入される
36
+
37
+ _T = None
38
+
39
+ def rish(cmd, timeout=300):
40
+ if _T is None:
41
+ return ""
42
+ try:
43
+ return _T.run(cmd, timeout=timeout)
44
+ except Exception: # noqa: BLE001
45
+ return ""
46
+
47
+ from . import core
48
+
49
+ from . import importers
50
+ from .profiles import base as pbase
51
+ from .profiles import load_profile
52
+ from . import paths
53
+
54
+ # import 時には端末に触れない: profile は常に generic で初期化しておき、
55
+ # 実機の当たり付け (getprop) は _setup() でのみ差し替える。--help は通らない
56
+ PROFILE = load_profile("", "")
57
+ D_HARD = PROFILE.D_HARD
58
+ C2_HARD = PROFILE.C2_HARD
59
+ L0_HARD = PROFILE.L0_HARD
60
+ IMPACT = PROFILE.IMPACT
61
+
62
+
63
+ def _setup(state_flag=None):
64
+ """起動処理: transport 探知 → profile 決定 → state_dir 解決の順。"""
65
+ global _T, PROFILE, D_HARD, C2_HARD, L0_HARD, IMPACT
66
+ global TSV, OBS, SDIR, PLAN_TXT, STATE
67
+ _T = core.detect(os.environ.get("VENICE_TRANSPORT"))
68
+ PROFILE = load_profile(rish("getprop ro.product.model").strip(),
69
+ rish("getprop ro.board.platform").strip())
70
+ D_HARD = PROFILE.D_HARD
71
+ C2_HARD = PROFILE.C2_HARD
72
+ L0_HARD = PROFILE.L0_HARD
73
+ IMPACT = PROFILE.IMPACT
74
+ scope = PROFILE.__name__.rsplit(".", 1)[-1]
75
+ SDIR = str(paths.state_dir(flag=state_flag, env=os.environ,
76
+ cwd=os.getcwd(), scope=scope))
77
+ TSV = os.path.join(SDIR, "layers.tsv")
78
+ OBS = os.path.join(SDIR, "layers.observed.tsv")
79
+ PLAN_TXT = os.path.join(SDIR, "plan.txt")
80
+ STATE = os.path.join(SDIR, "out", "last-kill")
81
+ return SDIR
82
+
83
+ # bucket 値: 10=ACTIVE 20=WORKING_SET 30=FREQUENT 40=RARE 45=RESTRICTED 50=NEVER
84
+ BUCKET_RESTRICTIVE = ("30", "40", "45", "50")
85
+ BUCKET_NEUTRAL = "working_set"
86
+
87
+
88
+ def _quirks_list(key):
89
+ """QUIRKS を呼び出し時に読む(プロファイル差し替えに追随させるため)"""
90
+ return set(PROFILE.QUIRKS.get(key, ()))
91
+
92
+
93
+ # 外部リストの verdict を層に写像する。語彙は importers が正規化済み。
94
+ VERDICT_LAYER = {
95
+ "recommended": "C1", # 消してよい
96
+ "advanced": "C1",
97
+ "expert": "B1", # 止めると影響が出る
98
+ "unsafe": "A", # 触らない
99
+ "keep": "A",
100
+ "": "C1", # verdict 無しの debloat リスト
101
+ }
102
+
103
+
104
+ def import_recs(path, as_layer=None):
105
+ """外部リストを読み、層に写像して recs を返す。
106
+
107
+ as_layer を渡すと全件その層に固定する。渡さない場合も、端末の中核
108
+ (D_HARD / C2_HARD / L0_HARD と QUIRKS)は verdict より優先する。
109
+ """
110
+ recs = []
111
+ c2_hard = C2_HARD | _quirks_list("protected_refuse_disable")
112
+ l0_hard = L0_HARD | _quirks_list("l0_force")
113
+ for pkg, verdict in sorted(importers.load(path).items()):
114
+ if as_layer:
115
+ L = as_layer
116
+ elif pkg in D_HARD:
117
+ L = "D"
118
+ elif pkg in c2_hard:
119
+ L = "C2"
120
+ elif pkg in l0_hard:
121
+ L = "0"
122
+ else:
123
+ # 名前規則は外部リストの verdict より優先する(生命線を守る)
124
+ L = name_layer(pkg) or VERDICT_LAYER.get(verdict or "", "C1")
125
+ recs.append([L, pkg, ACTION[L], risk_of(L, pkg), IMPACT.get(pkg, "")])
126
+ return recs
127
+
128
+
129
+ def merge_recs(old, new):
130
+ """pkg を鍵にして上書き統合。並びは pkg 順。"""
131
+ m = {r[1]: r for r in old}
132
+ for r in new:
133
+ m[r[1]] = r
134
+ return [m[p] for p in sorted(m)]
135
+
136
+
137
+ def name_layer(p):
138
+ """名前だけで層を推定する。観測が何も言わないときの最後の床。
139
+
140
+ プロファイルの NAME_RULES が base より優先される。
141
+ """
142
+ for L, rx in tuple(getattr(PROFILE, "NAME_RULES", ())) + pbase.NAME_RULES:
143
+ if re.search(rx, p):
144
+ return L
145
+ return None
146
+
147
+
148
+ def risk_of(L, p):
149
+ if L in ("D", "0", "C2"):
150
+ return 3
151
+ if L == "C1" and p in IMPACT:
152
+ return 2
153
+ return 1
154
+
155
+ def probe():
156
+ raw = rish("pm list packages")
157
+ pkgs = sorted({l.strip()[8:] for l in raw.splitlines() if l.startswith("package:")})
158
+
159
+ dis = set()
160
+ for l in rish("pm list packages -d").splitlines():
161
+ t = l.strip()
162
+ if t.startswith("package:"):
163
+ dis.add(t[8:])
164
+
165
+ wht = set()
166
+ for l in rish("dumpsys deviceidle whitelist").splitlines():
167
+ f = l.strip().split(",")
168
+ if len(f) >= 2 and f[1]:
169
+ wht.add(f[1])
170
+
171
+ # 能力検出: 一括取得が使えなければ個別に落ちる
172
+ ops = set()
173
+ if PROFILE.QUIRKS.get("appops_query_op", True):
174
+ for l in rish("cmd appops query-op RUN_ANY_IN_BACKGROUND ignore").splitlines():
175
+ t = l.strip()
176
+ if t:
177
+ ops.add(t.split()[0])
178
+ else:
179
+ for pk in pkgs:
180
+ if "ignore" in rish("cmd appops get %s RUN_ANY_IN_BACKGROUND" % pk):
181
+ ops.add(pk)
182
+
183
+ bkt, rsn = {}, {}
184
+ if PROFILE.QUIRKS.get("usagestats_bucket_dump", True):
185
+ for l in rish("dumpsys usagestats").splitlines():
186
+ t = l.strip()
187
+ if not t.startswith("package="):
188
+ continue
189
+ f = t.split()
190
+ try:
191
+ pk = f[0][8:]; b = f[2].split("=")[1]; r = f[3].split("=")[1]
192
+ except Exception: # noqa: BLE001
193
+ continue
194
+ bkt[pk] = b; rsn[pk] = r
195
+ else:
196
+ for pk in pkgs:
197
+ b = rish("am get-standby-bucket " + pk).strip()
198
+ if b:
199
+ bkt[pk] = b
200
+
201
+ return pkgs, dis, wht, bkt, ops, rsn
202
+
203
+ def infer(pkgs, dis, wht, bkt, ops, rsn=None):
204
+ # bucket: 5=EXEMPTED 10=ACTIVE 20=WORKING_SET 30=FREQUENT 40=RARE 45=RESTRICTED 50=NEVER
205
+ B1_B, B2_B = ("45", "40", "50"), ("30",)
206
+ # pm disable-user を拒む個体は C2 へ回す(profiles/*.py の QUIRKS に実測記録済み)
207
+ c2_hard = C2_HARD | _quirks_list("protected_refuse_disable")
208
+ recs = []
209
+ for p in pkgs:
210
+ b = bkt.get(p, "")
211
+ if p in D_HARD:
212
+ L = "D"
213
+ elif p in c2_hard:
214
+ L = "C2"
215
+ elif p in L0_HARD or p in _quirks_list("l0_force"):
216
+ L = "0"
217
+ elif p in dis:
218
+ L = "C1"
219
+ elif b == "5" or p in wht:
220
+ L = "0"
221
+ elif b in B1_B or p in ops:
222
+ L = "B1"
223
+ elif b in B2_B:
224
+ L = "B2"
225
+ else:
226
+ L = name_layer(p) or "A"
227
+ recs.append([L, p, ACTION[L], risk_of(L, p), IMPACT.get(p, "")])
228
+ return recs
229
+
230
+ def current_state():
231
+ _, dis, wht, bkt, ops, _ = probe()
232
+ return dis, wht, bkt, ops
233
+
234
+
235
+ def plan_lines(recs, st, installed=None):
236
+ """recs と現在状態 st=(dis,wht,bkt,ops) の差分コマンドだけを返す。
237
+
238
+ installed を渡すと、未インストールのパッケージを落とす。
239
+ 意志は端末固有なので、他機種の意志を使うと未インストール分が永久に差分に残る。
240
+ """
241
+ dis, wht, bkt, ops = st
242
+ out = []
243
+ for L, p, _a, _r, _imp in recs:
244
+ if installed is not None and p not in installed:
245
+ continue
246
+ if L == "D":
247
+ continue
248
+ # 意志が C1 以外で観測が無効のときは、他のコマンドの前に有効化する。
249
+ # enable なしで whitelist / bucket を撃っても無効のまま残る
250
+ if L != "C1" and p in dis:
251
+ out.append("pm enable --user 0 " + p)
252
+ # infer は p in wht で観測層を 0 に寄せる。意志が 0 以外なのに whitelist に
253
+ # 残っていると、appops / bucket が目標値のとき差分ゼロになり plan=0 で
254
+ # 見逃す(実測: managedprovisioning B1->0 / rakuten_rcs A->0)。解除は
255
+ # 持続するのでここで出す。L0 系(L0_HARD / l0_force)とは戦わない。
256
+ # 観測が C1(dis 優先)のときは infer も 0 に寄せないので触らない
257
+ if L != "0" and p in wht and p not in dis and \
258
+ p not in L0_HARD and p not in _quirks_list("l0_force") and \
259
+ p not in _quirks_list("l0_system_pinned"):
260
+ out.append("dumpsys deviceidle whitelist -" + p)
261
+ if L == "C1":
262
+ if p not in dis:
263
+ out.append("pm disable-user --user 0 " + p)
264
+ elif L == "0":
265
+ if p not in wht:
266
+ out.append("dumpsys deviceidle whitelist +" + p)
267
+ elif L in ("B1", "C2"):
268
+ if p not in ops:
269
+ out.append("cmd appops set %s RUN_ANY_IN_BACKGROUND ignore" % p)
270
+ # 書き戻される個体は bucket を主張しない(実測)。
271
+ # c2_does_not_hold_bucket は後方互換。no_bucket_hold は層を問わず効く
272
+ if p in _quirks_list("no_bucket_hold") or \
273
+ (L == "C2" and p in _quirks_list("c2_does_not_hold_bucket")):
274
+ pass
275
+ elif bkt.get(p) != "45":
276
+ out.append("am set-standby-bucket %s restricted" % p)
277
+ elif L == "B2":
278
+ if p in ops:
279
+ out.append("cmd appops set %s RUN_ANY_IN_BACKGROUND allow" % p)
280
+ # 書き戻される個体は bucket を主張しない。no_bucket_hold は層を問わず効く
281
+ if p in _quirks_list("no_bucket_hold"):
282
+ pass
283
+ elif bkt.get(p) != "30":
284
+ out.append("am set-standby-bucket %s frequent" % p)
285
+ elif L == "A":
286
+ if p in ops:
287
+ out.append("cmd appops set %s RUN_ANY_IN_BACKGROUND allow" % p)
288
+ # 書き戻される個体は bucket を主張しない。no_bucket_hold は層を問わず効く
289
+ if p in _quirks_list("no_bucket_hold"):
290
+ pass
291
+ # 制限系 bucket から中立へ戻す。未観測(None)は触らない
292
+ elif bkt.get(p) in BUCKET_RESTRICTIVE:
293
+ out.append("am set-standby-bucket %s %s" % (p, BUCKET_NEUTRAL))
294
+ return out
295
+
296
+
297
+ def plan_json(recs, st, profile="", transport="", installed=None, state_dir=""):
298
+ """差分を JSON で返す。他ツールから食える形にするための入口。"""
299
+ lines = plan_lines(recs, st, installed)
300
+ c = collections.Counter(x.split()[0] for x in lines)
301
+ return {
302
+ "schema": 1,
303
+ "profile": profile,
304
+ "transport": transport,
305
+ "state_dir": state_dir,
306
+ "counts": {"recs": len(recs), "commands": len(lines)},
307
+ "by_command": dict(c.most_common()),
308
+ "commands": lines,
309
+ }
310
+
311
+
312
+ def metrics():
313
+ o = rish("grep -E 'MemTotal|MemAvailable|SwapTotal|SwapFree' /proc/meminfo; "
314
+ "echo procs $(ps -A | wc -l); cat /proc/loadavg")
315
+ d = {"procs": 0, "load": 0.0}
316
+ for l in o.splitlines():
317
+ t = l.strip()
318
+ if t.startswith("MemTotal"):
319
+ d["total_kb"] = int(t.split()[1])
320
+ elif t.startswith("MemAvailable"):
321
+ d["avail_kb"] = int(t.split()[1])
322
+ elif t.startswith("SwapTotal"):
323
+ d["swaptotal_kb"] = int(t.split()[1])
324
+ elif t.startswith("SwapFree"):
325
+ d["swapfree_kb"] = int(t.split()[1])
326
+ elif t.startswith("procs"):
327
+ d["procs"] = int(t.split()[1])
328
+ else:
329
+ f = t.split()
330
+ if f:
331
+ with contextlib.suppress(ValueError):
332
+ d["load"] = float(f[0])
333
+ return d
334
+
335
+
336
+ def show_delta(b, a):
337
+ print(" MemAvailable %+8.1f MB"
338
+ % ((a.get("avail_kb", 0) - b.get("avail_kb", 0)) / 1024.0))
339
+ print(" SwapFree %+8.1f MB"
340
+ % ((a.get("swapfree_kb", 0) - b.get("swapfree_kb", 0)) / 1024.0))
341
+ print(" procs %+8d" % (a.get("procs", 0) - b.get("procs", 0)))
342
+ print(" load1 %+8.2f" % (a.get("load", 0.0) - b.get("load", 0.0)))
343
+
344
+
345
+ def mark_kill():
346
+ """掃除した時刻を記録する。次回の『蓄積量』の説明に使う。"""
347
+ os.makedirs(os.path.dirname(STATE), exist_ok=True)
348
+ with open(STATE, "w") as f:
349
+ f.write(str(int(time.time())))
350
+
351
+
352
+ def since_last_kill():
353
+ """前回の掃除からの経過秒。記録が無ければ None。"""
354
+ try:
355
+ with open(STATE) as f:
356
+ return max(0.0, time.time() - int(f.read().strip()))
357
+ except (OSError, ValueError):
358
+ return None
359
+
360
+
361
+ def load_hint(m):
362
+ """蓄積の見立て。空きが多ければ解放は小さく出る(閾値は経験則)。"""
363
+ tot = m.get("total_kb", 0) or 1
364
+ free = m.get("avail_kb", 0) / float(tot)
365
+ if free >= 0.65:
366
+ return "空きが多い。蓄積が少なく解放は小さく出る"
367
+ if free >= 0.40:
368
+ return "空きは中程度"
369
+ return "空きが少ない。解放は大きく出るはず"
370
+
371
+
372
+ def baseline_line(m, since=None):
373
+ """計測の前提。差分だけでは『なぜその数字か』が読めない。"""
374
+ av, tot = m.get("avail_kb", 0), m.get("total_kb", 0)
375
+ pct = (100.0 * av / tot) if tot else 0.0
376
+ out = "MemAvailable %d MB / %d MB (%.0f%%) / SwapFree %d MB / procs %d" % (
377
+ av // 1024, tot // 1024, pct, m.get("swapfree_kb", 0) // 1024, m.get("procs", 0))
378
+ if since is not None:
379
+ out += " (前回の掃除から %d分%02d秒)" % (since // 60, since % 60)
380
+ else:
381
+ out += " (前回の掃除の記録なし)"
382
+ out += "\n " + load_hint(m)
383
+ return out
384
+
385
+
386
+ def sample_kill(n=5, settle=8.0):
387
+ """am kill-all を n 回撃ち、各回の MemAvailable 差分(MB)を返す。
388
+
389
+ 掃除の効果は分散が大きい(実測 +1211 / +335 / -268 MB)。単発では語れない。
390
+ """
391
+ ds = []
392
+ for _ in range(n):
393
+ b = metrics()
394
+ rish("am kill-all")
395
+ mark_kill()
396
+ time.sleep(settle)
397
+ a = metrics()
398
+ ds.append((a.get("avail_kb", 0) - b.get("avail_kb", 0)) / 1024.0)
399
+ return ds
400
+
401
+
402
+ def median(xs):
403
+ xs = sorted(xs)
404
+ if not xs:
405
+ return 0.0
406
+ m = len(xs) // 2
407
+ return xs[m] if len(xs) % 2 else (xs[m - 1] + xs[m]) / 2.0
408
+
409
+
410
+ def applied_effect(recs, planned, st_after, installed=None):
411
+ """適用後に read-back して『効かなかった』を炙り出す。
412
+
413
+ rish() は失敗を握り潰す。だから打ちっぱなしでは何が効かなかったか分からない。
414
+ 適用後にもう一度 plan を引き、適用済みコマンドが残っていれば stuck と判定する。
415
+
416
+ 戻り値: (residual, stuck)
417
+ """
418
+ residual = plan_lines(recs, st_after, installed)
419
+ rset = set(residual)
420
+ stuck = [c for c in planned if c in rset]
421
+ return residual, stuck
422
+
423
+
424
+ # システムが書き戻すコマンド。効かなかった=失敗とは限らない
425
+ VOLATILE_CMD = ("am set-standby-bucket", "cmd appops set")
426
+
427
+
428
+ def classify_stuck(stuck):
429
+ """stuck を (永続で効かなかった, 揮発で書き戻された) に分ける。"""
430
+ hard = [c for c in stuck if not c.startswith(VOLATILE_CMD)]
431
+ vol = [c for c in stuck if c.startswith(VOLATILE_CMD)]
432
+ return hard, vol
433
+
434
+
435
+ def report_verify(recs, planned, installed=None):
436
+ """適用後にもう一度観測して、残差と『効かなかった』を報告する。"""
437
+ pkgs, dis, wht, bkt, ops, _ = probe()
438
+ residual, stuck = applied_effect(recs, planned, (dis, wht, bkt, ops), installed or set(pkgs))
439
+ if not residual:
440
+ print("--- 検証: 残差 0 本 ---")
441
+ return residual, stuck
442
+ print("--- 検証: 適用後に残った差分 %d 本 ---" % len(residual))
443
+ if not stuck:
444
+ print(" 適用した %d 本はすべて効いた(残りは揮発層の振動)" % len(planned))
445
+ return residual, stuck
446
+ hard, vol = classify_stuck(stuck)
447
+ if vol:
448
+ print(" 揮発で書き戻された(異常ではない): %d 本" % len(vol))
449
+ for c in vol[:5]:
450
+ print(" " + c)
451
+ if len(vol) > 5:
452
+ print(" ... 他 %d 本" % (len(vol) - 5))
453
+ if hard:
454
+ print(" 永続なのに効かなかった(本当の失敗): %d 本" % len(hard))
455
+ for c in hard[:10]:
456
+ print(" " + c)
457
+ else:
458
+ print(" 永続コマンドの失敗は 0 本")
459
+ return residual, stuck
460
+
461
+
462
+ def apply_measure(lines, do_kill=True, settle=8.0, cmd_settle=2.0):
463
+ """コマンドを適用し、『層変更の効果』と『掃除の効果』を分けて計測する。
464
+
465
+ 非root では dmesg も LMKD のログも読めないので、前後の差分が唯一の物証になる。
466
+ だが am kill-all を同じバッチに混ぜると、解放が層変更のせいなのか
467
+ 掃除のせいなのか区別できない。だから2段で測る。
468
+
469
+ 戻り値: (before, after_cmds, after_kill)。do_kill=False なら after_kill は after_cmds。
470
+ """
471
+ b = metrics()
472
+ if lines:
473
+ rish("; ".join(lines))
474
+ time.sleep(cmd_settle)
475
+ m1 = metrics()
476
+ if not do_kill:
477
+ return b, m1, m1
478
+ # plan が 0 本でも掃除は撃つ。撃たないと掃除の効果が測れない
479
+ rish("am kill-all")
480
+ mark_kill()
481
+ time.sleep(max(0.0, settle - cmd_settle))
482
+ return b, m1, metrics()
483
+
484
+
485
+ def save(recs, path=None):
486
+ path = path or TSV
487
+ os.makedirs(os.path.dirname(path) or ".", exist_ok=True)
488
+ with open(path, "w") as f:
489
+ f.write("# layer\tpkg\taction\trisk\timpact\n")
490
+ # action は層から導出する。古い tsv の残留値を引き継がない
491
+ f.writelines("%s\t%s\t%s\t%d\t%s\n" % (L, p, ACTION.get(L, a), r, imp)
492
+ for L, p, a, r, imp in recs)
493
+
494
+ def load(path=None):
495
+ path = path or TSV
496
+ if not os.path.exists(path):
497
+ return None
498
+ with open(path) as fh:
499
+ raw = fh.read().splitlines()
500
+ recs = []
501
+ for line in raw:
502
+ if not line or line.startswith("#"):
503
+ continue
504
+ c = line.split("\t")
505
+ while len(c) < 5:
506
+ c.append("")
507
+ recs.append([c[0], c[1], c[2], int(c[3] or 1), c[4]])
508
+ return recs
509
+
510
+ def ui(recs, orig):
511
+ curses.wrapper(_ui, recs, orig)
512
+
513
+ def _ui(std, recs, orig):
514
+ curses.start_color()
515
+ curses.use_default_colors()
516
+ curses.curs_set(0)
517
+ for i, c in enumerate([curses.COLOR_MAGENTA, curses.COLOR_CYAN, curses.COLOR_YELLOW,
518
+ curses.COLOR_GREEN, curses.COLOR_RED, curses.COLOR_RED,
519
+ curses.COLOR_WHITE]):
520
+ curses.init_pair(i + 1, c, -1)
521
+ LP = {L: i + 1 for i, L in enumerate(LAYERS)}
522
+ cur_l, cur_p, focus = 0, 0, 0
523
+ status = "space=cycle a=apply A=apply all staged w=save R=re-assert tab=panel q=quit"
524
+ while True:
525
+ std.erase()
526
+ h, w = std.getmaxyx()
527
+ grp = {L: [] for L in LAYERS}
528
+ for i, (L, _p, _a, _r, _imp) in enumerate(recs):
529
+ grp.setdefault(L, []).append(i)
530
+ std.addstr(0, 1, "LAYERS", curses.A_BOLD)
531
+ for i, L in enumerate(LAYERS):
532
+ at = curses.color_pair(LP[L])
533
+ if L == "D":
534
+ at |= curses.A_DIM
535
+ if i == cur_l:
536
+ at |= curses.A_REVERSE if focus == 0 else curses.A_BOLD
537
+ std.addstr(2 + i, 1, "%-3s %-12s %4d" % (L, TITLE[L], len(grp.get(L, []))), at)
538
+ staged = sum(1 for L, p, a, r, imp in recs if orig.get(p) != L)
539
+ std.addstr(3 + len(LAYERS), 1, "staged: %d" % staged, curses.A_BOLD)
540
+ cl = LAYERS[cur_l]
541
+ lst = grp.get(cl, [])
542
+ if lst and cur_p >= len(lst):
543
+ cur_p = len(lst) - 1
544
+ std.addstr(0, 34, "%s %s (%d)" % (cl, TITLE[cl], len(lst)), curses.A_BOLD)
545
+ std.addstr(1, 34, DESC[cl], curses.A_DIM)
546
+ vis = max(1, h - 5)
547
+ top = max(0, min(cur_p - vis // 2, max(0, len(lst) - vis)))
548
+ mark = "!"
549
+ for k in range(vis):
550
+ if top + k >= len(lst):
551
+ break
552
+ idx = lst[top + k]
553
+ L, p, a, r, imp = recs[idx]
554
+ mark = "!!!" if r >= 3 else ("!!" if r == 2 else "!")
555
+ at = curses.color_pair(LP[L])
556
+ if L == "D":
557
+ at |= curses.A_DIM
558
+ if orig.get(p) != L:
559
+ at |= curses.A_UNDERLINE
560
+ if top + k == cur_p and focus == 1:
561
+ at |= curses.A_REVERSE
562
+ std.addstr(2 + k, 34, "%-3s %s" % (mark, p[:max(1, w - 40)]), at)
563
+ if lst:
564
+ L, p, a, r, imp = recs[lst[cur_p]]
565
+ std.addstr(h - 3, 1, ("IMPACT: " + (imp or "-"))[:w - 2], curses.A_BOLD)
566
+ std.addstr(h - 2, 1, ("pkg=%s layer=%s action=%s risk=%s" % (p, L, a, mark))[:w - 2])
567
+ std.addstr(h - 1, 1, status[:w - 2], curses.A_DIM)
568
+ std.refresh()
569
+ ch = std.getch()
570
+ if ch in (ord("q"), 27):
571
+ save(recs)
572
+ return
573
+ elif ch in (curses.KEY_UP, ord("k")):
574
+ if focus == 0:
575
+ cur_l = (cur_l - 1) % len(LAYERS)
576
+ cur_p = 0
577
+ else:
578
+ cur_p = max(0, cur_p - 1)
579
+ elif ch in (curses.KEY_DOWN, ord("j")):
580
+ if focus == 0:
581
+ cur_l = (cur_l + 1) % len(LAYERS)
582
+ cur_p = 0
583
+ else:
584
+ cur_p = min(max(0, len(lst) - 1), cur_p + 1)
585
+ elif ch == 9:
586
+ focus = 1 - focus
587
+ elif ch == curses.KEY_LEFT:
588
+ focus = 0
589
+ elif ch == curses.KEY_RIGHT:
590
+ focus = 1
591
+ elif ch == ord(" "):
592
+ if focus == 1 and lst:
593
+ idx = lst[cur_p]
594
+ nxt = LAYERS[(LAYERS.index(recs[idx][0]) + 1) % len(LAYERS)]
595
+ recs[idx][0] = nxt
596
+ recs[idx][2] = ACTION[nxt]
597
+ recs[idx][3] = risk_of(nxt, recs[idx][1])
598
+ nl = [i for i, r2 in enumerate(recs) if r2[0] == nxt]
599
+ cur_l = LAYERS.index(nxt)
600
+ cur_p = nl.index(idx) if idx in nl else 0
601
+ status = "staged %s -> %s (space=cycle a=apply)" % (recs[idx][1], nxt)
602
+ elif ch == ord("a"):
603
+ if focus == 1 and lst and orig.get(recs[lst[cur_p]][1]) != recs[lst[cur_p]][0]:
604
+ idx = lst[cur_p]
605
+ if recs[idx][3] >= 3:
606
+ std.addstr(h - 1, 1, "DANGER risk>=3 -press y to confirm"[:w - 2],
607
+ curses.A_REVERSE)
608
+ std.refresh()
609
+ if std.getch() not in (ord("y"), ord("Y")):
610
+ continue
611
+ std.addstr(h - 1, 1, "working..."[:w - 2], curses.A_REVERSE)
612
+ std.refresh()
613
+ st = current_state()
614
+ pl = plan_lines([recs[idx]], st)
615
+ b, m1, m2 = apply_measure(pl, settle=3.0)
616
+ orig[recs[idx][1]] = recs[idx][0]
617
+ if pl:
618
+ status = "%s -> %s %dcmd cmd %+.1fMB / kill %+.1fMB" % (
619
+ recs[idx][1], recs[idx][0], len(pl),
620
+ (m1.get("avail_kb", 0) - b.get("avail_kb", 0)) / 1024.0,
621
+ (m2.get("avail_kb", 0) - m1.get("avail_kb", 0)) / 1024.0)
622
+ else:
623
+ status = "%s already at %s (no command needed)" % (recs[idx][1], recs[idx][0])
624
+ save(recs)
625
+ elif ch == ord("w"):
626
+ save(recs)
627
+ status = "saved -> " + TSV
628
+ elif ch == ord("A"):
629
+ staged = [r for r in recs if orig.get(r[1]) != r[0]]
630
+ if staged:
631
+ std.addstr(h - 1, 1, ("applying %d staged..." % len(staged))[:w - 2],
632
+ curses.A_REVERSE)
633
+ std.refresh()
634
+ st = current_state()
635
+ pl = plan_lines(staged, st)
636
+ b, m1, m2 = apply_measure(pl, settle=3.0)
637
+ for r in staged:
638
+ orig[r[1]] = r[0]
639
+ save(recs)
640
+ status = "applied %d staged %dcmd cmd %+.1fMB / kill %+.1fMB" % (
641
+ len(staged), len(pl),
642
+ (m1.get("avail_kb", 0) - b.get("avail_kb", 0)) / 1024.0,
643
+ (m2.get("avail_kb", 0) - m1.get("avail_kb", 0)) / 1024.0)
644
+ elif ch == ord("R"):
645
+ std.addstr(h - 1, 1, "re-asserting..."[:w - 2], curses.A_REVERSE)
646
+ std.refresh()
647
+ st = current_state()
648
+ pl = plan_lines(recs, st)
649
+ b, m1, m2 = apply_measure(pl, settle=3.0)
650
+ for L, p, _a, _r, _imp in recs:
651
+ orig[p] = L
652
+ status = "re-asserted %d cmd cmd %+.1fMB / kill %+.1fMB" % (
653
+ len(pl), (m1.get("avail_kb", 0) - b.get("avail_kb", 0)) / 1024.0,
654
+ (m2.get("avail_kb", 0) - m1.get("avail_kb", 0)) / 1024.0)
655
+ save(recs)
656
+
657
+ def diff_waived():
658
+ """諦め済みに分類する個体の包含集合。
659
+
660
+ no_bucket_hold(bucket を書き戻される個体)と l0_system_pinned
661
+ (フレームワーク設定が whitelist を主張し - で除去できない個体)。
662
+ どちらも engine が意図的に戦わない相手。
663
+ """
664
+ return _quirks_list("no_bucket_hold") | _quirks_list("l0_system_pinned")
665
+
666
+
667
+ def diff_counts(ch, waived=frozenset()):
668
+ """(未インストール, 意志不在, 諦め済み, 実残差) を数える。
669
+
670
+ 右列(now)が "-" は未インストール、左列(will)が "-" は意志不在。
671
+ 両列が存在し waived(no_bucket_hold 等の包含集合)に載る個体は諦め済み:
672
+ engine が意図的に戦わない相手なので実残差から除く。
673
+ 分類は (pkg, 層, 層) の完全一致のみ。前方一致では寄せない。
674
+ """
675
+ gone = sum(1 for _p, _a, b in ch if b == "-")
676
+ extra = sum(1 for _p, a, b in ch if a == "-" and b != "-")
677
+ rest = [c for c in ch if c[1] != "-" and c[2] != "-"]
678
+ waived_n = sum(1 for c in rest if c[0] in waived)
679
+ return gone, extra, waived_n, len(rest) - waived_n
680
+
681
+
682
+ def diff_view(ch, show_all=False, residual_only=False, waived=frozenset()):
683
+ """表示する行を選ぶ。集計(diff_counts)は常に ch 全体に対して行う。
684
+
685
+ --residual は engine が戦うべき実残差だけ。諦め済みは通常表示 / --all
686
+ ではそのまま出す(視認はできる、数えない)。
687
+ """
688
+ if residual_only:
689
+ return [c for c in ch if c[1] != "-" and c[2] != "-"
690
+ and c[0] not in waived]
691
+ if not show_all:
692
+ return [c for c in ch if c[2] != "-"]
693
+ return list(ch)
694
+
695
+
696
+ def _build_parser():
697
+ """St1b: subparsers 化。--state は親 (common) 定義を main と全サブに
698
+ parents= で渡す (argparse はグローバルオプションをサブコマンド後に
699
+ 取れないため)。後勝ちで解決される。--json は現行の到達範囲を保存する
700
+ (JSON 生成は plan 共有ブロック内の1箇所のみ。plan/apply/reapply の
701
+ 3cmd が今日も同じ出力を作る)。usage 文言は St1c で ./layers 表記に改修済み。
702
+ """
703
+ common = argparse.ArgumentParser(add_help=False)
704
+ # default は SUPPRESS: 子パーサの default=None がサブコマンド前に
705
+ # 指定した --state を上書きしてしまう (py3.14 argparse) のを防ぐ。
706
+ # 未指定時は getattr 側で None に落とし、後勝ちはそのまま効く。
707
+ common.add_argument("--state", metavar="DIR", default=argparse.SUPPRESS)
708
+ ap = argparse.ArgumentParser(prog="layerctl", parents=[common])
709
+ sub = ap.add_subparsers(dest="cmd")
710
+
711
+ for name in ("snapshot", "seed", "verify", "profile"):
712
+ sub.add_parser(name, parents=[common])
713
+
714
+ p = sub.add_parser("diff", parents=[common])
715
+ p.add_argument("--all", action="store_true")
716
+ p.add_argument("--residual", action="store_true")
717
+
718
+ for name in ("plan", "apply", "reapply"):
719
+ p = sub.add_parser(name, parents=[common])
720
+ # --json / --no-kill / --repeat は 3cmd 共通で登録する。旧実装は
721
+ # `in sys.argv` の全体照合だったため plan --repeat 3 のような
722
+ # 組み合わせも受理・無視されており、受理面を保存する
723
+ # (--json は plan JSON 生成ブロックで消費。旧 apply --json は
724
+ # 「JSON 表示 → 実 apply」だったのをそのまま保存する)
725
+ p.add_argument("--json", action="store_true")
726
+ p.add_argument("--no-kill", action="store_true")
727
+ p.add_argument("--repeat", type=int, default=None)
728
+
729
+ p = sub.add_parser("import", parents=[common])
730
+ p.add_argument("file")
731
+ p.add_argument("--as", dest="as_layer", type=str.upper, default=None)
732
+ p.add_argument("--dry", action="store_true")
733
+ return ap
734
+
735
+
736
+ def main(argv=None):
737
+ ap = _build_parser()
738
+ try:
739
+ args = ap.parse_args(sys.argv[1:] if argv is None else list(argv))
740
+ except SystemExit as e:
741
+ # --help/-h: 従来どおり出力して None を返す (終了コードでは無い)。
742
+ # 未知サブコマンド等のエラーは非ゼロのまま伝播させる。
743
+ if e.code:
744
+ raise
745
+ return None
746
+ _setup(getattr(args, "state", None))
747
+ if args.cmd == "import":
748
+ path = args.file
749
+ if args.as_layer is not None and args.as_layer not in LAYERS:
750
+ print("unknown layer: " + args.as_layer); return
751
+ try:
752
+ new = import_recs(path, args.as_layer)
753
+ except (OSError, ValueError) as e:
754
+ print("cannot read: %s" % e); return
755
+ if not new:
756
+ print("no packages parsed from " + path); return
757
+ old = load() or []
758
+ merged = merge_recs(old, new)
759
+ print("imported %d entries from %s (as=%s)" % (len(new), path, args.as_layer or "verdict"))
760
+ for k, v in collections.Counter(r[0] for r in new).most_common():
761
+ print(" %-3s %d" % (k, v))
762
+ print("will: %d -> %d records" % (len(old), len(merged)))
763
+ if args.dry:
764
+ return
765
+ save(merged)
766
+ print("saved -> " + TSV)
767
+ return
768
+
769
+ if args.cmd == "profile":
770
+ from .profiles import names
771
+ print("active profile : %s" % PROFILE.NAME)
772
+ print("desc : %s" % PROFILE.DESC)
773
+ print("state dir : %s" % SDIR)
774
+ print("available : %s" % ", ".join(names()))
775
+ print("quirks:")
776
+ for k, v in sorted(PROFILE.QUIRKS.items()):
777
+ print(" %-28s %s" % (k, v))
778
+ return
779
+ if args.cmd in ("snapshot", "seed"):
780
+ pkgs, dis, wht, bkt, ops, rsn = probe()
781
+ recs = infer(pkgs, dis, wht, bkt, ops, rsn)
782
+ if args.cmd == "seed":
783
+ save(recs, TSV)
784
+ print("seed -> " + TSV)
785
+ return
786
+ save(recs, OBS)
787
+ seeded = False
788
+ if not os.path.exists(TSV):
789
+ save(recs, TSV)
790
+ seeded = True
791
+ print("observed -> " + OBS + (" (seeded " + TSV + ")" if seeded else ""))
792
+ n = {L: 0 for L in LAYERS}
793
+ for L, _p, _a, _r, _imp in recs:
794
+ n[L] += 1
795
+ for L in LAYERS:
796
+ print(" %-3s %-12s %4d" % (L, TITLE[L], n[L]))
797
+ return
798
+ if args.cmd == "diff":
799
+ recs = load()
800
+ if recs is None:
801
+ print("no " + TSV); return
802
+ pkgs, dis, wht, bkt, ops, rsn = probe()
803
+ now = {r[1]: r[0] for r in infer(pkgs, dis, wht, bkt, ops, rsn)}
804
+ will = {r[1]: r[0] for r in recs}
805
+ ch = [(p, will.get(p, "-"), now.get(p, "-"))
806
+ for p in sorted(set(will) | set(now)) if will.get(p) != now.get(p)]
807
+ gone_n, extra_n, waived_n, resid_n = diff_counts(ch, diff_waived())
808
+ shown = diff_view(ch,
809
+ show_all=args.all,
810
+ residual_only=args.residual,
811
+ waived=diff_waived())
812
+ print("diff: %d (未インストール %d / 意志不在 %d / 諦め済み %d / 実残差 %d)"
813
+ % (len(ch), gone_n, extra_n, waived_n, resid_n))
814
+ if gone_n and not args.residual:
815
+ print(" 未インストール(意志にのみ存在、--all で表示): %d" % gone_n)
816
+ for p, a, b in shown:
817
+ print(" %-3s -> %-3s %s" % (a, b, p))
818
+ return
819
+ if args.cmd in ("plan", "apply", "reapply"):
820
+ recs = load()
821
+ if recs is None:
822
+ print("no " + TSV)
823
+ return
824
+ pkgs, dis, wht, bkt, ops, rsn = probe()
825
+ st = (dis, wht, bkt, ops)
826
+ lines = plan_lines(recs, st, set(pkgs))
827
+ if args.json:
828
+ print(json.dumps(plan_json(recs, st, PROFILE.NAME,
829
+ getattr(_T, "name", "") or "",
830
+ installed=set(pkgs), state_dir=SDIR),
831
+ ensure_ascii=False, indent=2))
832
+ else:
833
+ print("planned: %d commands (recs=%d)" % (len(lines), len(recs)))
834
+ c = collections.Counter(x.split()[0] for x in lines)
835
+ for k, v in c.most_common():
836
+ print(" %-10s %d" % (k, v))
837
+ with open(PLAN_TXT, "w") as fh:
838
+ fh.write("\n".join(lines) + "\n")
839
+ if not args.json:
840
+ print("plan -> " + PLAN_TXT)
841
+ if args.cmd == "plan":
842
+ return
843
+ if args.repeat is not None:
844
+ n = max(1, args.repeat) # type=int 済み (不正値は argparse が exit 2)
845
+ print("--- 計測の前提 ---")
846
+ print(" " + baseline_line(metrics(), since_last_kill()))
847
+ b, m1, _ = apply_measure(lines, do_kill=False)
848
+ print("applied %d commands" % len(lines))
849
+ print("--- delta: layer commands only ---")
850
+ show_delta(b, m1)
851
+ print("--- am kill-all x%d (掃除の分。中央値で見る) ---" % n)
852
+ ds = sample_kill(n)
853
+ for i, d in enumerate(ds, 1):
854
+ print(" %2d回目 MemAvailable %+8.1f MB" % (i, d))
855
+ print(" 中央値 %+.1f MB / 最小 %+.1f / 最大 %+.1f"
856
+ % (median(ds), min(ds), max(ds)))
857
+ report_verify(recs, lines)
858
+ return
859
+ print("--- 計測の前提 ---")
860
+ print(" " + baseline_line(metrics(), since_last_kill()))
861
+ b, m1, m2 = apply_measure(lines, do_kill=not args.no_kill)
862
+ print("applied %d commands" % len(lines))
863
+ print("--- delta: layer commands only (MemAvailable + = freed) ---")
864
+ show_delta(b, m1)
865
+ if m2 is not m1:
866
+ print("--- delta: after am kill-all (掃除の分。層変更とは別物) ---")
867
+ show_delta(m1, m2)
868
+ report_verify(recs, lines)
869
+ return
870
+ if args.cmd == "verify":
871
+ recs = load()
872
+ if recs is None:
873
+ print("no " + TSV)
874
+ return
875
+ pkgs, dis, wht, bkt, ops, rsn = probe()
876
+ lines = plan_lines(recs, (dis, wht, bkt, ops), set(pkgs))
877
+ report_verify(recs, lines)
878
+ return
879
+ recs = load()
880
+ if recs is None:
881
+ print("run: ./layers snapshot")
882
+ return
883
+ orig = {p: L for L, p, a, r, imp in recs}
884
+ ui(recs, orig)
885
+
886
+ if __name__ == "__main__":
887
+ main()