pocketshell 0.5.2__tar.gz → 0.5.3__tar.gz

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 (103) hide show
  1. {pocketshell-0.5.2 → pocketshell-0.5.3}/PKG-INFO +2 -2
  2. {pocketshell-0.5.2 → pocketshell-0.5.3}/pyproject.toml +29 -5
  3. {pocketshell-0.5.2 → pocketshell-0.5.3}/src/pocketshell/aplexer.py +28 -1
  4. pocketshell-0.5.3/src/pocketshell/memcap.py +259 -0
  5. {pocketshell-0.5.2 → pocketshell-0.5.3}/src/pocketshell/session_enum.py +224 -5
  6. {pocketshell-0.5.2 → pocketshell-0.5.3}/src/pocketshell/sessions.py +452 -29
  7. pocketshell-0.5.3/tests/fixtures/aplexer/snapshot-agent.json +83 -0
  8. pocketshell-0.5.3/tests/fixtures/aplexer/snapshot-crashed-start.json +25 -0
  9. pocketshell-0.5.3/tests/fixtures/aplexer/snapshot-liveness-mix.json +113 -0
  10. pocketshell-0.5.3/tests/fixtures/aplexer/snapshot-mid-create.json +25 -0
  11. pocketshell-0.5.3/tests/fixtures/aplexer/snapshot-post-kill-window.json +79 -0
  12. pocketshell-0.5.3/tests/test_agents_fixture_aplexer.py +714 -0
  13. {pocketshell-0.5.2 → pocketshell-0.5.3}/tests/test_aplexer_contract.py +168 -2
  14. {pocketshell-0.5.2 → pocketshell-0.5.3}/tests/test_aplexer_resolution.py +131 -4
  15. {pocketshell-0.5.2 → pocketshell-0.5.3}/tests/test_profiles.py +6 -0
  16. pocketshell-0.5.3/tests/test_session_enum_schema2.py +1226 -0
  17. {pocketshell-0.5.2 → pocketshell-0.5.3}/tests/test_sessions_attach.py +166 -0
  18. {pocketshell-0.5.2 → pocketshell-0.5.3}/tests/test_sessions_create_routing.py +449 -2
  19. pocketshell-0.5.3/tests/test_sessions_kill.py +748 -0
  20. pocketshell-0.5.3/tests/test_sessions_mem_cap.py +953 -0
  21. {pocketshell-0.5.2 → pocketshell-0.5.3}/tests/test_watch_ci.py +13 -1
  22. {pocketshell-0.5.2 → pocketshell-0.5.3}/uv.lock +8 -8
  23. pocketshell-0.5.2/tests/test_session_enum_schema2.py +0 -664
  24. pocketshell-0.5.2/tests/test_sessions_kill.py +0 -360
  25. {pocketshell-0.5.2 → pocketshell-0.5.3}/.gitignore +0 -0
  26. {pocketshell-0.5.2 → pocketshell-0.5.3}/README.md +0 -0
  27. {pocketshell-0.5.2 → pocketshell-0.5.3}/scheduler/README.md +0 -0
  28. {pocketshell-0.5.2 → pocketshell-0.5.3}/scheduler/pocketshell-usage-capture.service +0 -0
  29. {pocketshell-0.5.2 → pocketshell-0.5.3}/scheduler/pocketshell-usage-capture.timer +0 -0
  30. {pocketshell-0.5.2 → pocketshell-0.5.3}/scripts/sync-readme-exit-codes.py +0 -0
  31. {pocketshell-0.5.2 → pocketshell-0.5.3}/src/pocketshell/__init__.py +0 -0
  32. {pocketshell-0.5.2 → pocketshell-0.5.3}/src/pocketshell/__main__.py +0 -0
  33. {pocketshell-0.5.2 → pocketshell-0.5.3}/src/pocketshell/agent_card_push.py +0 -0
  34. {pocketshell-0.5.2 → pocketshell-0.5.3}/src/pocketshell/agent_log.py +0 -0
  35. {pocketshell-0.5.2 → pocketshell-0.5.3}/src/pocketshell/agents.py +0 -0
  36. {pocketshell-0.5.2 → pocketshell-0.5.3}/src/pocketshell/agents_kind.py +0 -0
  37. {pocketshell-0.5.2 → pocketshell-0.5.3}/src/pocketshell/cards.py +0 -0
  38. {pocketshell-0.5.2 → pocketshell-0.5.3}/src/pocketshell/cgroup_agents.py +0 -0
  39. {pocketshell-0.5.2 → pocketshell-0.5.3}/src/pocketshell/cli.py +0 -0
  40. {pocketshell-0.5.2 → pocketshell-0.5.3}/src/pocketshell/config.py +0 -0
  41. {pocketshell-0.5.2 → pocketshell-0.5.3}/src/pocketshell/daemon.py +0 -0
  42. {pocketshell-0.5.2 → pocketshell-0.5.3}/src/pocketshell/engines.py +0 -0
  43. {pocketshell-0.5.2 → pocketshell-0.5.3}/src/pocketshell/env.py +0 -0
  44. {pocketshell-0.5.2 → pocketshell-0.5.3}/src/pocketshell/github.py +0 -0
  45. {pocketshell-0.5.2 → pocketshell-0.5.3}/src/pocketshell/hooks.py +0 -0
  46. {pocketshell-0.5.2 → pocketshell-0.5.3}/src/pocketshell/jobs.py +0 -0
  47. {pocketshell-0.5.2 → pocketshell-0.5.3}/src/pocketshell/logs.py +0 -0
  48. {pocketshell-0.5.2 → pocketshell-0.5.3}/src/pocketshell/profiles.py +0 -0
  49. {pocketshell-0.5.2 → pocketshell-0.5.3}/src/pocketshell/prune_attachments.py +0 -0
  50. {pocketshell-0.5.2 → pocketshell-0.5.3}/src/pocketshell/push.py +0 -0
  51. {pocketshell-0.5.2 → pocketshell-0.5.3}/src/pocketshell/qr_share.py +0 -0
  52. {pocketshell-0.5.2 → pocketshell-0.5.3}/src/pocketshell/repos.py +0 -0
  53. {pocketshell-0.5.2 → pocketshell-0.5.3}/src/pocketshell/resume.py +0 -0
  54. {pocketshell-0.5.2 → pocketshell-0.5.3}/src/pocketshell/send.py +0 -0
  55. {pocketshell-0.5.2 → pocketshell-0.5.3}/src/pocketshell/serve.py +0 -0
  56. {pocketshell-0.5.2 → pocketshell-0.5.3}/src/pocketshell/tree.py +0 -0
  57. {pocketshell-0.5.2 → pocketshell-0.5.3}/src/pocketshell/usage.py +0 -0
  58. {pocketshell-0.5.2 → pocketshell-0.5.3}/src/pocketshell/usage_capture.py +0 -0
  59. {pocketshell-0.5.2 → pocketshell-0.5.3}/src/pocketshell/usage_reset.py +0 -0
  60. {pocketshell-0.5.2 → pocketshell-0.5.3}/tests/__init__.py +0 -0
  61. {pocketshell-0.5.2 → pocketshell-0.5.3}/tests/conftest.py +0 -0
  62. {pocketshell-0.5.2 → pocketshell-0.5.3}/tests/data/quse-0.0.11-usage.json +0 -0
  63. {pocketshell-0.5.2 → pocketshell-0.5.3}/tests/data/quse-0.0.13-usage.json +0 -0
  64. {pocketshell-0.5.2 → pocketshell-0.5.3}/tests/data/quse-0.0.15-usage.json +0 -0
  65. {pocketshell-0.5.2 → pocketshell-0.5.3}/tests/data/quse-0.0.15-usage.ndjson +0 -0
  66. {pocketshell-0.5.2 → pocketshell-0.5.3}/tests/data/quse-0.0.15-usage.provenance.txt +0 -0
  67. {pocketshell-0.5.2 → pocketshell-0.5.3}/tests/data/quse-0.0.9-usage.json +0 -0
  68. {pocketshell-0.5.2 → pocketshell-0.5.3}/tests/data/sshd_anchor/Dockerfile.from-unanchored-base +0 -0
  69. {pocketshell-0.5.2 → pocketshell-0.5.3}/tests/fixtures/aplexer/snapshot-reported-state.json +0 -0
  70. {pocketshell-0.5.2 → pocketshell-0.5.3}/tests/fixtures/aplexer/snapshot.json +0 -0
  71. {pocketshell-0.5.2 → pocketshell-0.5.3}/tests/test_agent_card_push.py +0 -0
  72. {pocketshell-0.5.2 → pocketshell-0.5.3}/tests/test_agent_log.py +0 -0
  73. {pocketshell-0.5.2 → pocketshell-0.5.3}/tests/test_agents.py +0 -0
  74. {pocketshell-0.5.2 → pocketshell-0.5.3}/tests/test_agents_kind.py +0 -0
  75. {pocketshell-0.5.2 → pocketshell-0.5.3}/tests/test_agents_kind_target.py +0 -0
  76. {pocketshell-0.5.2 → pocketshell-0.5.3}/tests/test_agents_source_target.py +0 -0
  77. {pocketshell-0.5.2 → pocketshell-0.5.3}/tests/test_cards.py +0 -0
  78. {pocketshell-0.5.2 → pocketshell-0.5.3}/tests/test_cards_push_notify.py +0 -0
  79. {pocketshell-0.5.2 → pocketshell-0.5.3}/tests/test_cgroup_agents.py +0 -0
  80. {pocketshell-0.5.2 → pocketshell-0.5.3}/tests/test_cli.py +0 -0
  81. {pocketshell-0.5.2 → pocketshell-0.5.3}/tests/test_daemon.py +0 -0
  82. {pocketshell-0.5.2 → pocketshell-0.5.3}/tests/test_daemon_fallback.py +0 -0
  83. {pocketshell-0.5.2 → pocketshell-0.5.3}/tests/test_engines.py +0 -0
  84. {pocketshell-0.5.2 → pocketshell-0.5.3}/tests/test_env.py +0 -0
  85. {pocketshell-0.5.2 → pocketshell-0.5.3}/tests/test_github.py +0 -0
  86. {pocketshell-0.5.2 → pocketshell-0.5.3}/tests/test_hooks.py +0 -0
  87. {pocketshell-0.5.2 → pocketshell-0.5.3}/tests/test_jobs.py +0 -0
  88. {pocketshell-0.5.2 → pocketshell-0.5.3}/tests/test_logs.py +0 -0
  89. {pocketshell-0.5.2 → pocketshell-0.5.3}/tests/test_prune_attachments.py +0 -0
  90. {pocketshell-0.5.2 → pocketshell-0.5.3}/tests/test_push.py +0 -0
  91. {pocketshell-0.5.2 → pocketshell-0.5.3}/tests/test_qr_share.py +0 -0
  92. {pocketshell-0.5.2 → pocketshell-0.5.3}/tests/test_repos.py +0 -0
  93. {pocketshell-0.5.2 → pocketshell-0.5.3}/tests/test_resume.py +0 -0
  94. {pocketshell-0.5.2 → pocketshell-0.5.3}/tests/test_send.py +0 -0
  95. {pocketshell-0.5.2 → pocketshell-0.5.3}/tests/test_serve.py +0 -0
  96. {pocketshell-0.5.2 → pocketshell-0.5.3}/tests/test_session_enum.py +0 -0
  97. {pocketshell-0.5.2 → pocketshell-0.5.3}/tests/test_sessions.py +0 -0
  98. {pocketshell-0.5.2 → pocketshell-0.5.3}/tests/test_ssh_fixture_penalties.py +0 -0
  99. {pocketshell-0.5.2 → pocketshell-0.5.3}/tests/test_tree.py +0 -0
  100. {pocketshell-0.5.2 → pocketshell-0.5.3}/tests/test_usage.py +0 -0
  101. {pocketshell-0.5.2 → pocketshell-0.5.3}/tests/test_usage_capture.py +0 -0
  102. {pocketshell-0.5.2 → pocketshell-0.5.3}/tests/test_usage_reset.py +0 -0
  103. {pocketshell-0.5.2 → pocketshell-0.5.3}/tests/test_watch_ci_cancelled.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: pocketshell
3
- Version: 0.5.2
3
+ Version: 0.5.3
4
4
  Summary: Unified server-side Python utility for the PocketShell Android client.
5
5
  Project-URL: Homepage, https://github.com/alexeygrigorev/pocketshell
6
6
  Project-URL: Issues, https://github.com/alexeygrigorev/pocketshell/issues
@@ -18,7 +18,7 @@ Classifier: Programming Language :: Python :: 3.13
18
18
  Classifier: Topic :: Software Development
19
19
  Classifier: Topic :: System :: Monitoring
20
20
  Requires-Python: >=3.11
21
- Requires-Dist: aplexer==0.1.3; sys_platform == 'linux'
21
+ Requires-Dist: aplexer==0.1.4; sys_platform == 'linux'
22
22
  Requires-Dist: click>=8.2.0
23
23
  Requires-Dist: google-auth>=2.0.0
24
24
  Requires-Dist: pyyaml>=6.0
@@ -14,7 +14,7 @@ name = "pocketshell"
14
14
  # scripts/check-pypi-version.sh enforces the stamped value matches the tag;
15
15
  # scripts/check-version-coupling.sh enforces the derivation itself is
16
16
  # single-sourced. See tools/pocketshell/README.md ("Version coupling").
17
- version = "0.5.2"
17
+ version = "0.5.3"
18
18
  description = "Unified server-side Python utility for the PocketShell Android client."
19
19
  readme = "README.md"
20
20
  requires-python = ">=3.11"
@@ -98,6 +98,28 @@ dependencies = [
98
98
  # so the pinned wheel is the ONLY aplexer this CLI can run. Bumping the
99
99
  # pin is a deliberate, reviewed change.
100
100
  #
101
+ # 0.1.4 is required for the session tree to say WHICH agent is running.
102
+ # Through 0.1.3 a snapshot row's only agent-ish field was `engine`, and
103
+ # `engine` cannot answer that question: every session PocketShell creates
104
+ # is `engine: "shell"` with the agent launched by hand inside it, so a
105
+ # tree full of claude/codex/opencode sessions is indistinguishable from a
106
+ # tree full of bare shells. 0.1.4 derives an `agent` field at QUERY time
107
+ # by walking the workload's descendant process tree (`workload_pid` plus
108
+ # `/proc/<pid>/task/*/children`, the same walk containment already uses)
109
+ # and classifying each `comm`/`cmdline` by whole-word command token —
110
+ # aplexer ca56fa5, spec.md section 18. It is present on every
111
+ # `a list --json` / `a snapshot` row (`null` when nothing recognisable is
112
+ # running) and never persisted, so it cannot go stale.
113
+ #
114
+ # `session_enum._aplexer_rows` reads that key straight onto
115
+ # `LiveSession.agent` and schema 2 emits it on every row. Against 0.1.3
116
+ # the key is simply absent and every row reports `agent: null` — the
117
+ # listing still works, it just cannot name an agent, which is the whole
118
+ # point of the bump. tests/test_aplexer_contract.py pins the behaviour
119
+ # against the bundled binary: a real session running a process named
120
+ # `claude` reports `agent == "claude"`, and `null` again once it exits.
121
+ # Verified red on published 0.1.3 (no `agent` key at all), green on 0.1.4.
122
+ #
101
123
  # 0.1.3 is required for a USER-VISIBLE session-tree defect, not for
102
124
  # version hygiene (aplexer#2 / aplexer#3). Through 0.1.2, aplexer's
103
125
  # `list_records` treated a session directory containing no `session.json`
@@ -162,12 +184,12 @@ dependencies = [
162
184
  # fails loud (there is no PATH fallback — D22) while tmux, the default
163
185
  # backend, keeps working.
164
186
  #
165
- # Install-surface note (unchanged in 0.1.3): as of 0.1.2 the wheels moved
187
+ # Install-surface note (unchanged in 0.1.4): as of 0.1.2 the wheels moved
166
188
  # from manylinux_2_17 to manylinux_2_28, raising the minimum glibc from
167
189
  # 2.17 to 2.28. Linux hosts older than that (CentOS 7, Ubuntu 18.04) can
168
190
  # no longer install pocketshell at all now that aplexer is a hard
169
191
  # dependency. Flagged, not solved here — see docs/aplexer-integration.md.
170
- "aplexer==0.1.3; sys_platform == 'linux'",
192
+ "aplexer==0.1.4; sys_platform == 'linux'",
171
193
  ]
172
194
 
173
195
  [project.scripts]
@@ -230,8 +252,10 @@ required-version = "==0.10.11"
230
252
  # rather than a stale cutoff, so this value moves in lock-step with every new
231
253
  # pin — and the `uv.lock` options cutoff must be moved to match. Now past
232
254
  # aplexer 0.1.3's 2026-09-06T00:32:09Z PyPI upload (its `aplexer-client`
233
- # runtime dep landed at 00:32:04Z) for the session-tree regression fix above.
234
- exclude-newer = "2026-09-06T01:00:00Z"
255
+ # runtime dep landed at 00:32:04Z) for the session-tree regression fix above,
256
+ # and now past aplexer 0.1.4's 2026-09-06T16:14:52Z PyPI upload (its
257
+ # `aplexer-client` runtime dep landed at 16:14:48Z) for the `agent` field.
258
+ exclude-newer = "2026-09-06T17:00:00Z"
235
259
 
236
260
  [tool.pytest.ini_options]
237
261
  testpaths = ["tests"]
@@ -43,6 +43,16 @@ dirs (e.g. ``~/bin/a``) was invisible, and the error said "not installed".
43
43
  ``worker_executable`` resolves it next to ``current_exe``, else bare
44
44
  ``aplexer`` on PATH). The pinned wheel always ships both into the same dir, so
45
45
  :class:`AplexerResolution` reports the worker it found next to ``a``.
46
+
47
+ A BUNDLED ``a`` with no sibling worker is therefore a packaging-integrity
48
+ failure, not a usable resolution (issue #2553): accepting it would let the
49
+ pinned CLI start an UNPINNED worker off ``PATH`` — the same separate-install
50
+ hazard #2543 removed, one level down. Such a candidate is skipped with a
51
+ ``tried`` entry saying why, so the caller's existing "could not resolve `a`;
52
+ tried …" message explains it instead of a low-level worker-startup error.
53
+ ``APLEXER_BIN`` is deliberately exempt: it is the one explicit override ("run
54
+ exactly this binary"), the reinstall advice does not apply to it, and it is
55
+ the seam the test suite's stub ``a`` uses.
46
56
  """
47
57
 
48
58
  from __future__ import annotations
@@ -136,6 +146,8 @@ def resolve_a(env: Optional[Mapping[str, str]] = None) -> AplexerResolution:
136
146
  so a separately-installed ``a`` can never be load-bearing. Never raises —
137
147
  an unresolvable ``a`` comes back as a report whose ``path`` is ``None``
138
148
  and whose ``tried`` lists every candidate, for the caller's error message.
149
+ A bundled ``a`` missing its sibling ``aplexer`` worker counts as
150
+ unresolvable (#2553), for the reason the module docstring gives.
139
151
  """
140
152
  source = env_map(env)
141
153
  tried: list[str] = []
@@ -153,10 +165,25 @@ def resolve_a(env: Optional[Mapping[str, str]] = None) -> AplexerResolution:
153
165
  for bin_dir in _bundled_bin_dirs():
154
166
  candidate = bin_dir / "a"
155
167
  if candidate.exists():
168
+ worker = _sibling_worker(str(candidate))
169
+ if worker is None:
170
+ # HALF-INSTALLED BUNDLE (#2553). `a` alone is not usable:
171
+ # `aplexer/src/lib.rs::worker_executable` resolves the worker
172
+ # next to `current_exe` and, failing that, runs a BARE
173
+ # `aplexer` off PATH — so returning this `a` would either
174
+ # start an unpinned worker (the separate-install hazard #2543
175
+ # removed, one level down) or die with a low-level startup
176
+ # error. Treated exactly like an absent `a`: keep looking, and
177
+ # if nothing answers, fail loud with this candidate named.
178
+ tried.append(
179
+ f"{candidate} (bundled, found; sibling `aplexer` worker "
180
+ "missing — half-installed)"
181
+ )
182
+ continue
156
183
  return AplexerResolution(
157
184
  path=str(candidate),
158
185
  source="bundled",
159
- worker=_sibling_worker(str(candidate)),
186
+ worker=worker,
160
187
  tried=tuple([*tried, f"{candidate} (bundled, found)"]),
161
188
  )
162
189
  tried.append(f"{candidate} (bundled, missing)")
@@ -0,0 +1,259 @@
1
+ """Per-session memory cap resolution for `pocketshell sessions create` (#2562).
2
+
3
+ Every session PocketShell starts must be memory-capped. The reason is written
4
+ into `sessions.py` and predates this module: a runaway session that can eat
5
+ the whole box triggers "the OOM-kill cascade that wiped the agent team", and
6
+ the box is the maintainer's only dev machine, usually reached from a phone
7
+ where recovering from that cascade is worst.
8
+
9
+ Where the number lives
10
+ ----------------------
11
+
12
+ In the repo's ``cgroups.toml``, and nowhere else. This module is a READER of
13
+ that file, never a second copy of the value:
14
+
15
+ .. code-block:: toml
16
+
17
+ # <repo>/cgroups.toml
18
+ mem = "30G"
19
+
20
+ Resolution order for a session whose workspace is ``W`` (first match wins):
21
+
22
+ 1. an explicit ``--mem`` on the command line (``--mem none`` = uncapped, see
23
+ below);
24
+ 2. ``W/cgroups.toml``'s top-level ``mem``;
25
+ 3. ``W/pyproject.toml``'s ``[tool.tmuxctl] mem`` (Python projects state it
26
+ there instead of a dedicated file);
27
+ 4. the same two files at ``W``'s git root;
28
+ 5. :data:`DEFAULT_MEM` — the documented fallback, never "no cap".
29
+
30
+ That is deliberately the same shape ``tmuxctl.robust.read_project_value`` /
31
+ ``resolve_mem`` use for the tmux arm, so a workspace resolves to the SAME
32
+ ceiling whichever backend a session lands on. ``tests/test_sessions_mem_cap``
33
+ pins that agreement against the real tmuxctl.
34
+
35
+ Why a pocketshell-owned reader instead of ``from tmuxctl.robust import
36
+ resolve_mem`` (the decision #2562 asks to record)
37
+ -------------------------------------------------------------------------
38
+
39
+ tmuxctl is being removed (#2561). Importing its resolver would make the
40
+ aplexer arm — the arm that OUTLIVES tmux — depend on the dependency that
41
+ removal deletes, so the cap would silently vanish again at deletion time,
42
+ which is exactly the failure this issue exists to close. The per-project
43
+ CONFIG FILE, not tmuxctl's code, is the contract: `cgroups.toml` stays where
44
+ it is and keeps its format (an explicit non-goal of #2562), and this module
45
+ becomes its sole reader once the tmux arm goes. tmuxctl's env layer
46
+ (``ROBUST_TMUX_MEM``) and its ``~/.config/tmuxctl/cgroups.toml`` user-config
47
+ layer are deliberately NOT reproduced: both are tmuxctl-namespaced knobs that
48
+ die with it, and a session cap is not something an inherited environment
49
+ variable should be able to change.
50
+
51
+ Failing loud
52
+ ------------
53
+
54
+ A cap that cannot be resolved is an ERROR, not a shrug: a malformed
55
+ ``cgroups.toml`` or an unparseable size raises :class:`MemCapError` and the
56
+ create is refused before anything is started. Silently running uncapped is the
57
+ bug (#2562), and silently substituting the fallback for a file the project
58
+ clearly meant to be authoritative would hide it just as well.
59
+
60
+ The single, explicit escape hatch is ``--mem none`` at the CALL SITE. It
61
+ exists because a cap is unenforceable on a host with no delegated cgroup-v2
62
+ user scope (an unprivileged container, e.g. the Docker `agents` fixture),
63
+ where aplexer itself fails closed with "systemd did not delegate the memory
64
+ controller". A committed config file can NOT request it: ``mem = "none"`` in
65
+ ``cgroups.toml`` is an error, so an uncapped session always has a human-typed
66
+ flag behind it.
67
+ """
68
+
69
+ from __future__ import annotations
70
+
71
+ import re
72
+ import subprocess
73
+ import tomllib
74
+ from pathlib import Path
75
+ from typing import Optional
76
+
77
+ #: Filename holding a project's cap for non-Python projects (PocketShell's own).
78
+ PROJECT_CONFIG_NAME = "cgroups.toml"
79
+
80
+ #: Python projects state the same value under ``[tool.tmuxctl] mem``.
81
+ PYPROJECT_NAME = "pyproject.toml"
82
+
83
+ #: The documented fallback for a workspace whose project declares no cap.
84
+ #: Same value tmuxctl falls back to (``robust.DEFAULT_MEM``), so the two arms
85
+ #: agree on a capless workspace. A cap that is merely a default is still a cap.
86
+ DEFAULT_MEM = "12G"
87
+
88
+ #: The one spelling that means "run this session uncapped". Accepted ONLY from
89
+ #: an explicit ``--mem``, never from a project file.
90
+ UNCAPPED = "none"
91
+
92
+ #: Anything smaller than this is a typo, not a policy (``mem = "30"`` meaning
93
+ #: 30 GiB would otherwise resolve to 30 BYTES). Refused loudly: aplexer would
94
+ #: fail closed on it anyway, with a much less obvious message.
95
+ MIN_MEM_BYTES = 64 * 1024**2
96
+
97
+ _SIZE_UNITS = {
98
+ "B": 1,
99
+ "K": 1024,
100
+ "KB": 1024,
101
+ "KIB": 1024,
102
+ "M": 1024**2,
103
+ "MB": 1024**2,
104
+ "MIB": 1024**2,
105
+ "G": 1024**3,
106
+ "GB": 1024**3,
107
+ "GIB": 1024**3,
108
+ "T": 1024**4,
109
+ "TB": 1024**4,
110
+ "TIB": 1024**4,
111
+ }
112
+
113
+ _SIZE_RE = re.compile(r"\s*([0-9]+(?:\.[0-9]+)?)\s*([a-zA-Z]*)\s*\Z")
114
+
115
+ #: `git rev-parse` on a workspace is a local, sub-millisecond call; a hung git
116
+ #: must not hang a create started from the phone.
117
+ _GIT_TIMEOUT_S = 5.0
118
+
119
+
120
+ class MemCapError(RuntimeError):
121
+ """The session's memory cap could not be resolved — refuse the create."""
122
+
123
+
124
+ def parse_size(value: str, *, source: str) -> int:
125
+ """Parse a human size (``30G``, ``512M``, ``1.5G``, ``1048576``) to bytes.
126
+
127
+ Accepts exactly what ``tmuxctl.robust.parse_size`` accepts, so the same
128
+ project file resolves identically on both arms — and is a strict superset
129
+ of what aplexer's ``parse_byte_size`` takes (it has no fractional form).
130
+ That is why callers hand aplexer the resulting BYTE COUNT rather than the
131
+ raw string: a value tmuxctl honours can then never be rejected, or worse
132
+ reinterpreted, one layer down.
133
+
134
+ ``source`` names where the value came from, for the error message.
135
+ """
136
+ text = str(value).strip()
137
+ if not text:
138
+ raise MemCapError(f"{source}: empty memory cap")
139
+ match = _SIZE_RE.fullmatch(text)
140
+ if match is None:
141
+ raise MemCapError(f"{source}: {value!r} is not a memory size (e.g. 30G)")
142
+ unit = (match.group(2) or "B").upper()
143
+ if unit not in _SIZE_UNITS:
144
+ raise MemCapError(f"{source}: unknown memory-size unit in {value!r}")
145
+ size = int(float(match.group(1)) * _SIZE_UNITS[unit])
146
+ if size < MIN_MEM_BYTES:
147
+ raise MemCapError(
148
+ f"{source}: memory cap {value!r} resolves to {size} bytes, below the "
149
+ f"{MIN_MEM_BYTES}-byte floor — did you mean {text}G?"
150
+ )
151
+ return size
152
+
153
+
154
+ def is_uncapped(flag: Optional[str]) -> bool:
155
+ """Whether an explicit ``--mem`` value asks for NO cap at all."""
156
+ return bool(flag) and flag.strip().lower() == UNCAPPED
157
+
158
+
159
+ def _read_project_config(path: Path) -> Optional[str]:
160
+ """``mem`` from a dedicated ``cgroups.toml``.
161
+
162
+ A file that exists but cannot be parsed raises: ``cgroups.toml`` has
163
+ exactly one job, so an unreadable one means the project's cap is unknown,
164
+ and guessing is how the cap gets lost silently.
165
+ """
166
+ if not path.is_file():
167
+ return None
168
+ try:
169
+ document = tomllib.loads(path.read_text(encoding="utf-8"))
170
+ except (OSError, UnicodeDecodeError, tomllib.TOMLDecodeError) as exc:
171
+ raise MemCapError(f"{path}: cannot be read as TOML: {exc}") from exc
172
+ value = document.get("mem")
173
+ return None if value is None else str(value)
174
+
175
+
176
+ def _read_pyproject(path: Path) -> Optional[str]:
177
+ """``[tool.tmuxctl] mem`` from a ``pyproject.toml``.
178
+
179
+ Unlike ``cgroups.toml`` this file is NOT primarily a cap declaration, so a
180
+ malformed one is skipped rather than fatal (tmuxctl does the same): the
181
+ resolution simply continues, and the fallback still caps the session.
182
+ """
183
+ if not path.is_file():
184
+ return None
185
+ try:
186
+ document = tomllib.loads(path.read_text(encoding="utf-8"))
187
+ except (OSError, UnicodeDecodeError, tomllib.TOMLDecodeError):
188
+ return None
189
+ tool = document.get("tool")
190
+ section = tool.get("tmuxctl") if isinstance(tool, dict) else None
191
+ value = section.get("mem") if isinstance(section, dict) else None
192
+ return None if value is None else str(value)
193
+
194
+
195
+ def _git_root(start: Path) -> Optional[Path]:
196
+ try:
197
+ completed = subprocess.run(
198
+ ["git", "-C", str(start), "rev-parse", "--show-toplevel"],
199
+ capture_output=True,
200
+ text=True,
201
+ check=False,
202
+ timeout=_GIT_TIMEOUT_S,
203
+ )
204
+ except (OSError, subprocess.TimeoutExpired):
205
+ return None
206
+ if completed.returncode != 0:
207
+ return None
208
+ top = completed.stdout.strip()
209
+ return Path(top) if top else None
210
+
211
+
212
+ def read_project_mem(workspace: Path) -> Optional[tuple[str, Path]]:
213
+ """The project cap for ``workspace`` as ``(raw value, file it came from)``.
214
+
215
+ Checks the workspace directory first, then its git root — the same order
216
+ (and the same two file shapes) tmuxctl uses, so a session started deep in
217
+ a repo still gets the repo's committed cap.
218
+ """
219
+ try:
220
+ base = workspace.resolve()
221
+ except OSError: # pragma: no cover - resolve() is strict=False here
222
+ base = workspace
223
+ directories = [base]
224
+ root = _git_root(base)
225
+ if root is not None and root != base:
226
+ directories.append(root)
227
+ for directory in directories:
228
+ for reader, name in (
229
+ (_read_project_config, PROJECT_CONFIG_NAME),
230
+ (_read_pyproject, PYPROJECT_NAME),
231
+ ):
232
+ path = directory / name
233
+ value = reader(path)
234
+ if value is not None:
235
+ return value, path
236
+ return None
237
+
238
+
239
+ def resolve_session_mem_bytes(*, flag: Optional[str], workspace: str) -> Optional[int]:
240
+ """The cap, in bytes, for a session created in ``workspace``.
241
+
242
+ ``None`` means "explicitly uncapped" and can ONLY come from ``--mem none``.
243
+ Every other outcome is a positive byte count or a :class:`MemCapError`;
244
+ there is no path that returns "no cap" by accident.
245
+ """
246
+ if flag is not None and flag.strip():
247
+ if is_uncapped(flag):
248
+ return None
249
+ return parse_size(flag, source="--mem")
250
+ found = read_project_mem(Path(workspace))
251
+ if found is None:
252
+ return parse_size(DEFAULT_MEM, source="the built-in default cap")
253
+ raw, path = found
254
+ if is_uncapped(raw):
255
+ raise MemCapError(
256
+ f"{path}: mem = {raw!r} is not allowed in a project file — an "
257
+ "uncapped session must be asked for explicitly with `--mem none`"
258
+ )
259
+ return parse_size(raw, source=str(path))