@crvouga/homelab 0.23.9 → 0.23.11

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.
@@ -0,0 +1,9 @@
1
+ # Managed by personal converge. BASH_ENV runs before a noninteractive Bash
2
+ # command. Re-exec its original arguments in a separately bounded tool scope.
3
+ # The helper clears BASH_ENV only for that job: nested shells stay in its cap.
4
+ if [[ -r /proc/$$/cmdline ]]; then
5
+ mapfile -d '' -t homelab_shell_argv < /proc/$$/cmdline
6
+ exec /usr/bin/python3 -I -B /usr/local/lib/personal-fleet-agent-tool/agent-tool.py "${homelab_shell_argv[@]:1}"
7
+ fi
8
+ printf '%s\n' 'AGENT_TOOL_REFUSED: cannot identify shell command for memory isolation.' >&2
9
+ exit 75
@@ -0,0 +1,113 @@
1
+ #!/usr/bin/python3
2
+ """Admit one shell tool into its own bounded scope; never cap the shared provider."""
3
+ import fcntl
4
+ import json
5
+ import os
6
+ import signal
7
+ from pathlib import Path
8
+ import subprocess
9
+ import sys
10
+ import time
11
+ import uuid
12
+
13
+
14
+ def available(root, proc):
15
+ info = dict(line.split(':', 1) for line in (proc / 'meminfo').read_text().splitlines())
16
+ headroom = int(info['MemAvailable'].split()[0]) * 1024
17
+ # Include every ancestor, not just the aggregate agent budget.
18
+ group = root
19
+ while group != Path('/sys/fs') and group != group.parent:
20
+ maximum = group / 'memory.max'
21
+ if maximum.exists():
22
+ value = maximum.read_text().strip()
23
+ if value != 'max':
24
+ headroom = min(headroom, int(value) - int((group / 'memory.current').read_text()))
25
+ group = group.parent
26
+ return max(0, headroom)
27
+
28
+
29
+ def limits(policy, capacity):
30
+ mib = 1024 * 1024
31
+ # Small supported workers need a smaller envelope, not a permanent refusal
32
+ # because one default tool budget exceeds the whole agent slice.
33
+ reserve = min(policy['reserveMiB'] * mib, capacity // 4)
34
+ provider = min(policy.get('providerReserveMiB', 1024) * mib, capacity // 4)
35
+ return min(policy['memoryMiB'] * mib, capacity - reserve - provider), reserve
36
+
37
+
38
+ def reserved(root, budget):
39
+ # Empty scopes are no longer running. Reservations are the unused part of
40
+ # each live tool's hard cap, so simultaneous launches cannot overcommit.
41
+ total = 0
42
+ for group in root.glob('homelab-tool-*.scope'):
43
+ try:
44
+ if 'populated 1' in (group / 'cgroup.events').read_text():
45
+ maximum = (group / 'memory.max').read_text().strip()
46
+ cap = int(maximum) if maximum != 'max' else budget
47
+ total += max(0, cap - int((group / 'memory.current').read_text()))
48
+ except FileNotFoundError:
49
+ pass
50
+ return total
51
+
52
+
53
+ def main():
54
+ policy = json.loads(Path(__file__).with_name('agent-tool-policy.json').read_text())
55
+ runtime = Path(os.environ['XDG_RUNTIME_DIR'])
56
+ own = (Path('/proc/self/cgroup').read_text().strip().split('0::', 1)[1])
57
+ prefix = own.split('/app-t3code-agents.slice/', 1)
58
+ if len(prefix) != 2:
59
+ sys.stderr.write('AGENT_TOOL_REFUSED: shell tool is outside the managed agent budget; run homelab converge.\n')
60
+ return 75
61
+ root = Path('/sys/fs/cgroup' + prefix[0] + '/app-t3code-agents.slice')
62
+ maximum = (root / 'memory.max').read_text().strip()
63
+ if maximum == 'max':
64
+ raise ValueError('agent slice is not bounded')
65
+ budget, reserve = limits(policy, int(maximum))
66
+ # Scope creation and the admission check form one worker-wide critical
67
+ # section. Kernel hard caps enforce every granted reservation afterwards.
68
+ with (runtime / 'homelab-tool-admission.lock').open('a') as lock:
69
+ fcntl.flock(lock, fcntl.LOCK_EX)
70
+ if available(root, Path('/proc')) - reserved(root, budget) < budget + reserve:
71
+ sys.stderr.write('AGENT_TOOL_REFUSED: insufficient unreserved memory for a bounded shell job. Finish other jobs or move work to another worker, then retry.\n')
72
+ return 75
73
+ unit = 'homelab-tool-' + uuid.uuid4().hex + '.scope'
74
+ env = dict(os.environ)
75
+ env.pop('BASH_ENV', None)
76
+ child = subprocess.Popen([
77
+ '/usr/bin/systemd-run', '--user', '--scope', '--quiet', '--collect',
78
+ '--slice=app-t3code-agents.slice', '--unit=' + unit,
79
+ '--property=MemoryMax=' + str(budget),
80
+ '--property=MemorySwapMax=' + str(policy['swapMiB']) + 'M',
81
+ '--property=OOMPolicy=stop', '--property=IOAccounting=yes',
82
+ '--property=TimeoutStopSec=10s',
83
+ '--', '/bin/bash', *sys.argv[1:]], env=env)
84
+ def cancel(signum, _frame):
85
+ subprocess.run(['/usr/bin/systemctl', '--user', 'stop', unit], check=False)
86
+ child.wait()
87
+ sys.exit(128 + signum)
88
+ signal.signal(signal.SIGTERM, cancel)
89
+ signal.signal(signal.SIGINT, cancel)
90
+ deadline = time.monotonic() + 10
91
+ while child.poll() is None:
92
+ try:
93
+ if 'populated 1' in (root / unit / 'cgroup.events').read_text():
94
+ break
95
+ except FileNotFoundError:
96
+ pass
97
+ if time.monotonic() >= deadline:
98
+ # Do not release admission while an unobserved job may start.
99
+ subprocess.run(['/usr/bin/systemctl', '--user', 'stop', unit], check=False)
100
+ child.terminate()
101
+ child.wait()
102
+ sys.stderr.write('AGENT_TOOL_REFUSED: tool scope startup was not observed.\n')
103
+ return 75
104
+ time.sleep(0.02)
105
+ return child.wait()
106
+
107
+
108
+ if __name__ == '__main__':
109
+ try:
110
+ sys.exit(main())
111
+ except (OSError, ValueError, KeyError):
112
+ sys.stderr.write('AGENT_TOOL_REFUSED: memory admission could not be measured; run homelab converge.\n')
113
+ sys.exit(75)
@@ -776,29 +776,71 @@ def expire_entries(directory, hours, busy, now, dry_run):
776
776
  return freed
777
777
 
778
778
 
779
- def footprint(paths):
780
- """What the files under paths hold: their bytes, the bytes of the ones
781
- that have more than one link, and their share of the disk, where a file
782
- with N links is charged a 1/N share to each of them. Nothing is
783
- remembered per file: a node may hold millions."""
779
+ # Inventory is optional. Keep the deadline well below the service timeout.
780
+ INVENTORY_SECONDS = 60
781
+ INVENTORY_IO_FULL_PERCENT = 20
782
+
783
+
784
+ class InventoryDeferred(Exception):
785
+ pass
786
+
787
+
788
+ def inventory_checkpoint(proc):
789
+ deadline = time.monotonic() + INVENTORY_SECONDS
790
+ next_sample = 0
791
+
792
+ def check():
793
+ nonlocal next_sample
794
+ now = time.monotonic()
795
+ if now >= deadline:
796
+ raise InventoryDeferred('deadline')
797
+ if proc is None or now < next_sample:
798
+ return
799
+ next_sample = now + 1
800
+ try:
801
+ for line in (Path(proc) / 'pressure/io').read_text().splitlines():
802
+ if line.startswith('full '):
803
+ fields = dict(field.split('=', 1) for field in line.split()[1:])
804
+ if float(fields['avg10']) >= INVENTORY_IO_FULL_PERCENT:
805
+ raise InventoryDeferred('io-pressure')
806
+ break
807
+ except (OSError, ValueError, KeyError):
808
+ pass # The monotonic budget also applies without PSI.
809
+
810
+ return check
811
+
812
+
813
+ def footprint(paths, check):
814
+ """Measure allocated blocks, charging each hardlink its share."""
784
815
  total = linked = charged = 0
816
+
817
+ def files(path):
818
+ check()
819
+ try:
820
+ with os.scandir(path) as entries:
821
+ for entry in entries:
822
+ check()
823
+ try:
824
+ metadata = entry.stat(follow_symlinks=False)
825
+ except FileNotFoundError:
826
+ continue
827
+ if stat.S_ISDIR(metadata.st_mode):
828
+ yield from files(entry.path)
829
+ elif stat.S_ISREG(metadata.st_mode):
830
+ yield metadata
831
+ except FileNotFoundError:
832
+ return # A build may remove a path during inventory.
833
+
785
834
  for top in paths:
835
+ check()
786
836
  if not is_real_dir(top):
787
837
  continue
788
- for current, dirs, files in os.walk(top):
789
- dirs[:] = [d for d in dirs if not os.path.islink(os.path.join(current, d))]
790
- for name in files:
791
- try:
792
- st = os.lstat(os.path.join(current, name))
793
- except OSError:
794
- continue
795
- if not stat.S_ISREG(st.st_mode):
796
- continue
797
- size = st.st_blocks * 512
798
- total += size
799
- charged += size / max(1, st.st_nlink)
800
- if st.st_nlink > 1:
801
- linked += size
838
+ for st in files(top):
839
+ size = st.st_blocks * 512
840
+ total += size
841
+ charged += size / max(1, st.st_nlink)
842
+ if st.st_nlink > 1:
843
+ linked += size
802
844
  return total, linked, int(charged)
803
845
 
804
846
 
@@ -806,7 +848,7 @@ def footprint(paths):
806
848
  LINKED_STORES = ('pnpm', 'bun')
807
849
 
808
850
 
809
- def measure(home, worktree_roots):
851
+ def measure(home, worktree_roots, check):
810
852
  """What the worktrees, the package stores and the tool installs take on
811
853
  disk, the share of the worktrees' and stores' bytes that is hardlinked,
812
854
  and whether every store is on the filesystem of every worktree root:
@@ -814,12 +856,13 @@ def measure(home, worktree_roots):
814
856
  worktrees = [os.path.join(home, root) for root in worktree_roots]
815
857
  stores = [os.path.join(home, STORES[name][0]) for name in LINKED_STORES]
816
858
  tools = [os.path.join(home, '.local', 'share', 'mise', 'installs')]
817
- worktree_total, worktree_linked, worktree_bytes = footprint(worktrees)
818
- store_total, store_linked, store_bytes = footprint(stores)
819
- _, _, tool_bytes = footprint(tools)
859
+ worktree_total, worktree_linked, worktree_bytes = footprint(worktrees, check)
860
+ store_total, store_linked, store_bytes = footprint(stores, check)
861
+ _, _, tool_bytes = footprint(tools, check)
820
862
  total = worktree_total + store_total
821
863
  devices = {}
822
864
  for path in worktrees + stores:
865
+ check()
823
866
  try:
824
867
  devices[path] = os.stat(path).st_dev
825
868
  except OSError:
@@ -849,6 +892,28 @@ def write_report(path, report):
849
892
  os.replace(temporary, path)
850
893
 
851
894
 
895
+ def report_collection(path, outcome, home, roots, proc):
896
+ started = int(time.time())
897
+ inventory = {'status': 'pending', 'started': started}
898
+ write_report(path, {**outcome, 'inventory': inventory})
899
+ check = inventory_checkpoint(proc)
900
+ measured = {}
901
+ try:
902
+ check()
903
+ measured = measure(home, roots, check)
904
+ check()
905
+ except InventoryDeferred as error:
906
+ inventory.update(status='deferred', reason=str(error))
907
+ measured = {}
908
+ except OSError:
909
+ inventory.update(status='deferred', reason='unavailable')
910
+ measured = {}
911
+ else:
912
+ inventory.update(status='complete')
913
+ inventory['finished'] = int(time.time())
914
+ write_report(path, {**outcome, **measured, 'inventory': inventory})
915
+
916
+
852
917
  def pair(text, kind):
853
918
  name, _, value = text.rpartition('=')
854
919
  if not name:
@@ -1413,7 +1478,7 @@ def main(argv):
1413
1478
  free_mib={p: v // MIB for p, v in after.items()})
1414
1479
  if args.report and not args.dry_run:
1415
1480
  final_used = max(used_percent(p) for p in paths) if target else None
1416
- write_report(os.path.join(home, args.report), {
1481
+ report_collection(os.path.join(home, args.report), {
1417
1482
  'version': 1,
1418
1483
  'operationFailures': OPERATION_FAILURES,
1419
1484
  'finished': int(time.time()),
@@ -1424,8 +1489,7 @@ def main(argv):
1424
1489
  'pnpmStores': generations,
1425
1490
  **({'targetUsedPercent': target, 'usedPercentBefore': initial_used,
1426
1491
  'usedPercentAfter': final_used, 'targetReached': final_used <= target} if target else {}),
1427
- **measure(home, args.worktree_root),
1428
- })
1492
+ }, home, args.worktree_root, None if args.lsof else args.proc)
1429
1493
 
1430
1494
 
1431
1495
  if __name__ == '__main__':
@@ -274,7 +274,13 @@
274
274
  "diskGcScript": "/usr/local/lib/personal-fleet-disk-gc.py",
275
275
  "diskGcMemoryMaxMiB": 2048,
276
276
  "diskGcGitTempHours": 1,
277
- "diskGcFetchMaxMiB": 256
277
+ "diskGcFetchMaxMiB": 256,
278
+ "agentTool": {
279
+ "memoryMiB": 4096,
280
+ "reserveMiB": 2048,
281
+ "swapMiB": 512,
282
+ "providerReserveMiB": 1024
283
+ }
278
284
  },
279
285
  "clock": {
280
286
  "warnOffsetSeconds": 2,
@@ -44,7 +44,10 @@ def io_delta(previous, current):
44
44
 
45
45
 
46
46
  def workloads(args):
47
- yield from args.agent_tree.rglob('t3code-*.scope')
47
+ # Never kill a shared Codex provider to shed one shell tool.
48
+ yield from (group for group in args.agent_tree.rglob('t3code-*.scope')
49
+ if not group.name.startswith('t3code-codex-'))
50
+ yield from args.agent_tree.glob('homelab-tool-*.scope')
48
51
  # The drop-ins place new transient units in the shared slice. Jobs that
49
52
  # predate the policy can still be direct children of app.slice.
50
53
  for tree in (args.agent_tree, args.app_tree):
@@ -166,7 +166,7 @@
166
166
  mode: '0644'
167
167
  content: |
168
168
  # Managed by personal converge. Applies to every t3code-*.scope T3 starts for an agent.
169
- # OOMPolicy=continue: the kernel kills the largest process in the agent; the agent itself keeps running.
169
+ # OOMPolicy=continue permits surviving processes to continue; it cannot protect the provider itself.
170
170
  # IOAccounting=yes: the pressure guard needs each agent's io.stat to tell a writer from a reader it blocks.
171
171
  [Scope]
172
172
  MemoryMax={{ resourceSafety.agentMemoryMax }}
@@ -174,6 +174,48 @@
174
174
  OOMPolicy=continue
175
175
  IOAccounting=yes
176
176
  register: agent_policy
177
+ # Codex app-server serves many threads. Its shell tools are separately admitted
178
+ # and capped; protecting the provider does not remove the aggregate hard cap.
179
+ - name: Create shared-provider and tool policy directories
180
+ ansible.builtin.file:
181
+ path: '{{ item }}'
182
+ state: directory
183
+ owner: root
184
+ group: root
185
+ mode: '0755'
186
+ loop:
187
+ - /etc/systemd/user/t3code-codex-.scope.d
188
+ - /usr/local/lib/personal-fleet-agent-tool
189
+ - name: Declare the shared Codex provider reserve
190
+ ansible.builtin.copy:
191
+ dest: /etc/systemd/user/t3code-codex-.scope.d/60-personal-fleet.conf
192
+ owner: root
193
+ group: root
194
+ mode: '0644'
195
+ content: |
196
+ # Managed by personal converge. A shared provider is not one shell tool.
197
+ [Scope]
198
+ MemoryMax=infinity
199
+ MemorySwapMax=infinity
200
+ MemoryMin={{ resourceSafety.agentTool.providerReserveMiB }}M
201
+ MemoryLow={{ resourceSafety.agentTool.providerReserveMiB }}M
202
+ OOMPolicy=continue
203
+ register: shared_provider_policy
204
+ - name: Install bounded shell tool admission
205
+ ansible.builtin.copy:
206
+ src: '{{ playbook_dir }}/{{ item }}'
207
+ dest: '/usr/local/lib/personal-fleet-agent-tool/{{ item }}'
208
+ owner: root
209
+ group: root
210
+ mode: '0644'
211
+ loop: [agent-tool.py, agent-tool.bash]
212
+ - name: Declare shell tool admission budgets
213
+ ansible.builtin.copy:
214
+ dest: /usr/local/lib/personal-fleet-agent-tool/agent-tool-policy.json
215
+ owner: root
216
+ group: root
217
+ mode: '0644'
218
+ content: '{{ resourceSafety.agentTool | to_nice_json }}'
177
219
  - name: Charge automatically named systemd-run jobs to the shared agent budget
178
220
  ansible.builtin.copy:
179
221
  dest: '/etc/systemd/user/run-.{{ item | lower }}.d/60-personal-fleet.conf'
@@ -241,7 +283,7 @@
241
283
  path: '{{ item.path }}'
242
284
  state: absent
243
285
  loop: '{{ agent_override_files.files }}'
244
- when: item.path is match('^.*/app-t3code-agents(?:-[^/]*)?\.slice\.d/50-[^/]+\.conf$')
286
+ when: item.path is match('^.*/(?:app-t3code-agents(?:-[^/]*)?\\.slice|t3code-codex-[^/]+\\.scope)\\.d/50-[^/]+\\.conf$')
245
287
  register: agent_overrides
246
288
  - name: Restore declared pressure policy over worker user-service overrides
247
289
  ansible.builtin.file:
@@ -261,7 +303,7 @@
261
303
  ansible.builtin.systemd_service:
262
304
  scope: user
263
305
  daemon_reload: true
264
- when: agent_policy.changed or transient_limits.changed or agent_slices.changed or agent_overrides.changed
306
+ when: agent_policy.changed or shared_provider_policy.changed or transient_limits.changed or agent_slices.changed or agent_overrides.changed
265
307
  failed_when: false
266
308
  - name: Run systemd-oomd
267
309
  ansible.builtin.systemd_service:
package/docs/runbooks.md CHANGED
@@ -14,7 +14,7 @@ It reads a code by where it stands, never by the word it ends with. The CLI
14
14
  proxy documents the codes of its own commands in
15
15
  [its README](../cliproxy/README.md); the ones converge reports are here.
16
16
 
17
- There are 509 codes; 111 need a person.
17
+ There are 510 codes; 111 need a person.
18
18
 
19
19
  ## Bootstrap of a new or returning worker
20
20
 
@@ -104,6 +104,7 @@ There are 509 codes; 111 need a person.
104
104
  - `DISK_GC_TIMER_MISSING`: the disk GC timer is missing, stopped or disabled.
105
105
  - `DISK_GC_MEMORY_POLICY_STALE`: the effective collector memory limit differs from the bounded Git-maintenance budget in the Ubuntu policy. Run `homelab converge` and inspect service drop-ins if it remains different; the old 512 MiB limit cannot complete representative large-repository maintenance.
106
106
  - `DISK_GC_RUN_STALE`: the disk GC failed or its timer has not fired for two hours.
107
+ - `DISK_GC_INVENTORY_STALE`: cleanup reported its result, but footprint inventory has been pending for over a minute. Inspect the collector service and storage I/O pressure. The reported reclaimed space and cleanup failure count remain available.
107
108
  - `DISK_GC_NOT_REPORTED`: the disk GC has left no report (`resourceSafety.diskGcReport` in `ansible/ubuntu/policy.json`) since converge installed it, so `ubuntu:disk-gc` is skipped. It reports after its next run, within the hour; one that never does fails `DISK_GC_RUN_STALE`.
108
109
  - `PACKAGE_STORE_OTHER_FILESYSTEM`: a package store (`~/.local/share/pnpm/store`, `~/.bun/install/cache`) is on another filesystem than the agent worktrees (`~/.t3/worktrees`), so every install copies its packages instead of linking them, and the disk fills faster. `ubuntu:disk-gc` and `manager:disk-gc` warn. Put the store and the worktrees on one filesystem, or unset an override of `pnpm_config_store_dir` or `BUN_INSTALL_CACHE_DIR`. **Needs a person.**
109
110
  - `SERVICE_NOT_ENABLED`: service not enabled.
@@ -616,3 +616,48 @@ item in the volatile session keyring at startup. Its encrypted login keyring
616
616
  can stay locked. The desktop service shares the existing primary display.
617
617
  The manager checks pre-authentication negotiation and the certificate.
618
618
  A client login is needed to confirm authenticated control.
619
+
620
+ ### Shared Codex providers and shell tool memory
621
+
622
+ A Codex app-server can serve many T3 threads. Its scope therefore has no
623
+ single-tool hard cap; the combined agent slice still has its hard memory and
624
+ swap limits. A 1 GiB provider reserve protects its working memory. The pressure
625
+ guard never kills that shared scope to relieve CPU or I/O pressure.
626
+
627
+ On Ubuntu, managed Codex launchers set `shell_environment_policy.set.BASH_ENV`
628
+ to the fleet's tracked Bash startup hook. Each noninteractive Bash tool command
629
+ is re-executed in a `homelab-tool-*.scope` under the combined agent slice, with
630
+ its own memory cap of up to 4 GiB, 512 MiB swap cap and `OOMPolicy=stop`. Nested shells
631
+ stay in that tool's cap. An oversized tool fails without killing the provider.
632
+ The hook preserves shell arguments, stdin/stdout and exit status. Cancellation
633
+ stops its tool scope. The managed Python helper and budget are installed by
634
+ Ansible, not generated by a launcher.
635
+
636
+ Before creating a tool scope, a worker-wide lock serializes admission. The
637
+ helper checks host available memory and every ancestor cgroup's remaining
638
+ hard-limit headroom, subtracts unused reservations for already admitted tools,
639
+ and requires a further reserve of up to 2 GiB. On small workers, the
640
+ reserve and provider allowance each use at most a quarter of the agent slice,
641
+ and the tool cap shrinks to fit the remaining half. It refuses excess demand with
642
+ `AGENT_TOOL_REFUSED` and exit 75; finish jobs or move work to another worker
643
+ before retrying. It fails closed when it cannot measure admission. This is a
644
+ bounded supported workload envelope, not a guarantee for unlimited work.
645
+
646
+ `homelab converge --no-restart-busy` defers a T3 restart until idle, subject
647
+ to the existing 24 hour recovery deadline. Use it when running a rollout from
648
+ a T3 session. The flag survives worker-to-manager hand-off.
649
+
650
+ Convergence removes stale Codex scope property overrides and reloads the user
651
+ manager without restarting providers. Existing provider processes load the new
652
+ shell policy on their next launch; drain their turns before recycling a shared
653
+ provider. Do not restart T3 while relying on an agent inside it. Confirm a new
654
+ shell command's `/proc/self/cgroup` names a `homelab-tool-*.scope` before resuming
655
+ heavy work. The isolation covers Bash shell tools; explicit alternative shells,
656
+ non-shell native operations and manually detached named services are outside
657
+ that hook. Keep those separately bounded. `worker:pressure-events` reports
658
+ kernel shared-provider OOM kills as well as pressure guard and oomd activity.
659
+
660
+ Run `HOMELAB_TEST_SYSTEMD=1 python3 -B -m unittest discover -s
661
+ ansible/ubuntu/tests -p test_agent_tool.py` on a Linux development worker for a
662
+ small disposable-scope check of arguments, exit status, runaway containment and
663
+ provider survival. No production unit is stopped by that check.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@crvouga/homelab",
3
- "version": "0.23.9",
3
+ "version": "0.23.11",
4
4
  "description": "Keeps a set of development machines in sync: one manager and many workers",
5
5
  "license": "MIT",
6
6
  "repository": "github:crvouga/homelab",
@@ -74,5 +74,5 @@
74
74
  "engines": {
75
75
  "node": ">=22"
76
76
  },
77
- "gitHead": "ed315929ad238df76bc689c727cae62d93db282f"
77
+ "gitHead": "9be01ec43800a7b1ab2a4e0de570807c8ceefcc1"
78
78
  }
@@ -1,4 +1,5 @@
1
1
  import { join } from 'node:path';
2
+ import { existsSync } from 'node:fs';
2
3
  import { mkdirSync } from 'node:fs';
3
4
  import { AgentConfigurationError } from './errors';
4
5
  import { registry, type Selection } from './registry';
@@ -74,6 +75,7 @@ async function spawnAgent(
74
75
  : selection.tool;
75
76
  const command = [
76
77
  executable,
78
+ ...codexToolIsolation(selection.tool),
77
79
  ...pinned,
78
80
  ...launchArgs(selection, directory, args, env),
79
81
  ];
@@ -344,3 +346,16 @@ function configureGatewayEnvironment(
344
346
  env[`ANTHROPIC_DEFAULT_${family}_MODEL`] = selection.model;
345
347
  }
346
348
  }
349
+
350
+ /** Bash commands from a Linux Codex provider enter worker-wide admitted scopes.
351
+ * Install policy before enabling it; other platforms retain their native shell. */
352
+ export function codexToolIsolation(
353
+ tool: string,
354
+ platform: string = process.platform,
355
+ installed: (path: string) => boolean = existsSync
356
+ ): string[] {
357
+ const hook = '/usr/local/lib/personal-fleet-agent-tool/agent-tool.bash';
358
+ return tool === 'codex' && platform === 'linux' && installed(hook)
359
+ ? ['-c', `shell_environment_policy.set.BASH_ENV=${JSON.stringify(hook)}`]
360
+ : [];
361
+ }
@@ -368,7 +368,9 @@ export function forwardedFlags(
368
368
  for (const [option, flag] of Object.entries(HAND_OFF)) {
369
369
  if (typeof flag !== 'string') continue;
370
370
  const value: unknown = options[option as keyof FleetSyncOptions];
371
- if (value === true) flags.push(flag);
371
+ if (option === 'restartBusy' && value === false)
372
+ flags.push('--no-restart-busy');
373
+ else if (value === true) flags.push(flag);
372
374
  else if (typeof value === 'string' && value) flags.push(flag, value);
373
375
  else if (Array.isArray(value))
374
376
  for (const entry of value) flags.push(flag, String(entry));
@@ -1,4 +1,5 @@
1
1
  import { record } from '../config';
2
+ import policy from '../../ansible/ubuntu/policy.json';
2
3
  import { join } from 'node:path';
3
4
  import type { Standing } from '../state/sync';
4
5
  import type { Runner } from '../types';
@@ -95,14 +96,24 @@ export function toolChanges(
95
96
  }));
96
97
  }
97
98
 
98
- export function restarts(tools: ToolChange[], files: string[]): Restart[] {
99
+ export function restarts(
100
+ tools: ToolChange[],
101
+ files: string[],
102
+ restartBusy = true
103
+ ): Restart[] {
99
104
  const found: Restart[] = [];
100
- const when = 'at once, ending running agent turns.';
105
+ const when = restartBusy
106
+ ? 'at once, ending running agent turns.'
107
+ : `when idle, or after the ${policy.t3RestartMaxDeferralHours} hour recovery deadline.`;
108
+ const deferred = restartBusy
109
+ ? {}
110
+ : { deadlineHours: policy.t3RestartMaxDeferralHours };
101
111
  if (tools.some((change) => change.tool === 't3'))
102
112
  found.push({
103
113
  service: 't3',
104
114
  reason: `T3 is upgraded on every worker and restarted ${when}`,
105
- endsRunningTurns: true,
115
+ endsRunningTurns: restartBusy,
116
+ ...deferred,
106
117
  });
107
118
  else if (
108
119
  files.some((file) =>
@@ -112,7 +123,8 @@ export function restarts(tools: ToolChange[], files: string[]): Restart[] {
112
123
  found.push({
113
124
  service: 't3',
114
125
  reason: `The managed T3 policy may change: a T3 that has not loaded it is restarted ${when}`,
115
- endsRunningTurns: true,
126
+ endsRunningTurns: restartBusy,
127
+ ...deferred,
116
128
  });
117
129
  const agents = tools.filter((change) => AGENT_TOOLS.includes(change.tool));
118
130
  if (agents.length)
@@ -145,6 +157,7 @@ export async function syncPlan(
145
157
  nodes: string[];
146
158
  sources: string[];
147
159
  desktopPreferences?: boolean;
160
+ restartBusy?: boolean;
148
161
  /** The fleet configuration last applied (from the fleet state), when
149
162
  * there is one, and the one this sync applies. */
150
163
  definitions?: { applied: unknown; selected: unknown };
@@ -175,7 +188,9 @@ export async function syncPlan(
175
188
  revision: { from: input.from, to: input.to },
176
189
  known: changes !== null,
177
190
  tools: changes?.tools ?? [],
178
- restarts: changes ? restarts(changes.tools, changes.files) : [],
191
+ restarts: changes
192
+ ? restarts(changes.tools, changes.files, input.restartBusy)
193
+ : [],
179
194
  nodes: input.nodes.map((node) => ({
180
195
  node,
181
196
  from: input.from,
@@ -260,7 +260,9 @@ function requested(
260
260
  options: FleetSyncOptions
261
261
  ): Pick<BootstrapPayload, 'restartBusy' | 'allowMiseDowngrade'> {
262
262
  return {
263
- ...(options.restartBusy ? { restartBusy: true } : {}),
263
+ ...(options.restartBusy === undefined
264
+ ? {}
265
+ : { restartBusy: options.restartBusy }),
264
266
  ...(allowsMiseDowngrade(options, options.revision)
265
267
  ? { allowMiseDowngrade: true }
266
268
  : {}),
@@ -649,6 +649,9 @@ async function preview(
649
649
  .map((node) => node.node)
650
650
  .filter((node): node is string => typeof node === 'string'),
651
651
  sources: planSources(settings.workspace, context.root),
652
+ ...(options.restartBusy === undefined
653
+ ? {}
654
+ : { restartBusy: options.restartBusy }),
652
655
  desktopPreferences: (canonicalDefinition.ides ?? ['t3']).includes('t3'),
653
656
  definitions: {
654
657
  applied: appliedDefinition(),
@@ -237,6 +237,10 @@ function registerSync({ program, defaults, complete }: Registration) {
237
237
  '--restart-busy',
238
238
  'Restart a worker T3 for a new release or policy even while agent turns run, which ends them (the default)'
239
239
  )
240
+ .option(
241
+ '--no-restart-busy',
242
+ 'Defer a worker T3 restart until idle, subject to the existing recovery deadline'
243
+ )
240
244
  .option(
241
245
  '--allow-unmerged',
242
246
  'Converge to a revision that is not on the default branch of the source repository; without it such a revision is refused before anything changes'
@@ -12,15 +12,22 @@ export interface DiskGcReport {
12
12
  disposable: boolean;
13
13
  reclaimedMiB: number;
14
14
  categoriesMiB: Record<string, number>;
15
+ inventory: Inventory;
16
+ }
17
+
18
+ interface Footprint {
15
19
  worktreesMiB: number;
16
20
  storesMiB: number;
17
21
  toolsMiB: number;
18
22
  hardlinkedPercent: number;
19
- /** Whether every package store is on the filesystem of the worktrees;
20
- * null when there is no store or no worktree root yet. */
21
23
  sameFilesystem: boolean | null;
22
24
  }
23
25
 
26
+ type Inventory =
27
+ | { status: 'pending'; started: number }
28
+ | { status: 'deferred' }
29
+ | { status: 'complete'; footprint: Footprint };
30
+
24
31
  const number = (value: unknown): value is number =>
25
32
  typeof value === 'number' && Number.isFinite(value) && value >= 0;
26
33
 
@@ -49,27 +56,12 @@ export async function readDiskGcReport(
49
56
  }
50
57
  if (typeof value !== 'object' || value === null || value['version'] !== 1)
51
58
  return null;
52
- const categories =
53
- typeof value['categoriesMiB'] === 'object' &&
54
- value['categoriesMiB'] !== null
55
- ? Object.fromEntries(
56
- Object.entries(value['categoriesMiB'] as Record<string, unknown>)
57
- .filter(([name, mib]) => /^[a-z_]{1,32}$/.test(name) && number(mib))
58
- .map(([name, mib]) => [name, mib as number])
59
- )
60
- : {};
61
- const fields = [
62
- 'finished',
63
- 'reclaimedMiB',
64
- 'worktreesMiB',
65
- 'storesMiB',
66
- 'toolsMiB',
67
- 'hardlinkedPercent',
68
- ] as const;
69
- if (!fields.every((field) => number(value[field]))) return null;
70
- const same = value['sameFilesystem'];
59
+ const finished = value['finished'];
60
+ const reclaimedMiB = value['reclaimedMiB'];
61
+ const inventory = readInventory(value);
62
+ if (!number(finished) || !number(reclaimedMiB) || !inventory) return null;
71
63
  return {
72
- finished: value['finished'] as number,
64
+ finished,
73
65
  ...operationFailures(value),
74
66
  ...(number(value['usedPercentAfter']) && number(value['targetUsedPercent'])
75
67
  ? {
@@ -78,13 +70,63 @@ export async function readDiskGcReport(
78
70
  }
79
71
  : {}),
80
72
  disposable: value['disposable'] === true,
81
- reclaimedMiB: value['reclaimedMiB'] as number,
82
- categoriesMiB: categories,
83
- worktreesMiB: value['worktreesMiB'] as number,
84
- storesMiB: value['storesMiB'] as number,
85
- toolsMiB: value['toolsMiB'] as number,
86
- hardlinkedPercent: value['hardlinkedPercent'] as number,
87
- sameFilesystem: typeof same === 'boolean' ? same : null,
73
+ reclaimedMiB,
74
+ categoriesMiB: readCategories(value),
75
+ inventory,
76
+ };
77
+ }
78
+
79
+ function readCategories(
80
+ value: Record<string, unknown>
81
+ ): Record<string, number> {
82
+ return typeof value['categoriesMiB'] === 'object' &&
83
+ value['categoriesMiB'] !== null
84
+ ? Object.fromEntries(
85
+ Object.entries(value['categoriesMiB'] as Record<string, unknown>)
86
+ .filter(([name, mib]) => /^[a-z_]{1,32}$/.test(name) && number(mib))
87
+ .map(([name, mib]) => [name, mib as number])
88
+ )
89
+ : {};
90
+ }
91
+
92
+ function readInventory(value: Record<string, unknown>): Inventory | null {
93
+ const metadata = value['inventory'];
94
+ if (metadata !== undefined) {
95
+ if (!metadata || typeof metadata !== 'object') return null;
96
+ const { status, started } = metadata as Record<string, unknown>;
97
+ if (status === 'pending' && number(started)) return { status, started };
98
+ if (status === 'deferred') return { status };
99
+ if (status !== 'complete') return null;
100
+ }
101
+ return readFootprint(value);
102
+ }
103
+
104
+ function readFootprint(value: Record<string, unknown>): Inventory | null {
105
+ // Reports predating the inventory phase already include a full footprint.
106
+ const {
107
+ worktreesMiB,
108
+ storesMiB,
109
+ toolsMiB,
110
+ hardlinkedPercent,
111
+ sameFilesystem,
112
+ } = value;
113
+ if (
114
+ !number(worktreesMiB) ||
115
+ !number(storesMiB) ||
116
+ !number(toolsMiB) ||
117
+ !number(hardlinkedPercent)
118
+ )
119
+ return null;
120
+ return {
121
+ status: 'complete',
122
+ footprint: {
123
+ worktreesMiB,
124
+ storesMiB,
125
+ toolsMiB,
126
+ hardlinkedPercent,
127
+ sameFilesystem:
128
+ typeof sameFilesystem === 'boolean' ? sameFilesystem : null,
129
+ },
88
130
  };
89
131
  }
90
132
 
@@ -100,10 +142,26 @@ export function describeDiskGc(report: DiskGcReport, now: number): string {
100
142
  .join(', ');
101
143
  return [
102
144
  `The disk GC${report.disposable ? ' (disposable storage)' : ''} last ran ${minutes} min ago and reclaimed ${report.reclaimedMiB} MiB${categories ? ` (${categories})` : ''}`,
103
- `worktrees hold ${gib(report.worktreesMiB)}, package stores ${gib(report.storesMiB)}, tool installs ${gib(report.toolsMiB)}; ${report.hardlinkedPercent}% of the worktrees' and stores' bytes are hardlinked.`,
145
+ describeInventory(report.inventory, now),
104
146
  ].join('; ');
105
147
  }
106
148
 
149
+ function inventoryOverdue(inventory: Inventory, now: number): boolean {
150
+ return inventory.status === 'pending' && now - inventory.started > 60;
151
+ }
152
+
153
+ function describeInventory(inventory: Inventory, now: number): string {
154
+ if (inventory.status === 'pending')
155
+ return inventoryOverdue(inventory, now)
156
+ ? 'DISK_GC_INVENTORY_STALE: footprint inventory is overdue.'
157
+ : 'footprint inventory is in progress.';
158
+ if (inventory.status === 'deferred')
159
+ return 'footprint inventory was deferred.';
160
+ const { worktreesMiB, storesMiB, toolsMiB, hardlinkedPercent } =
161
+ inventory.footprint;
162
+ return `worktrees hold ${gib(worktreesMiB)}, package stores ${gib(storesMiB)}, tool installs ${gib(toolsMiB)}; ${hardlinkedPercent}% of the worktrees' and stores' bytes are hardlinked.`;
163
+ }
164
+
107
165
  export const STORE_FILESYSTEM_REMEDY =
108
166
  'Hardlinks cannot cross filesystems, so every install copies its packages instead of linking them from the shared store. Keep the package stores (~/.local/share/pnpm/store, ~/.bun/install/cache) on the filesystem of the agent worktrees (~/.t3/worktrees): move whichever is mounted elsewhere, or unset an override of pnpm_config_store_dir or BUN_INSTALL_CACHE_DIR.';
109
167
 
@@ -115,6 +173,9 @@ export function diskGcReportCheck(
115
173
  now: number
116
174
  ): Check {
117
175
  const summary = describeDiskGc(report, now);
176
+ const otherFilesystem =
177
+ report.inventory.status === 'complete' &&
178
+ report.inventory.footprint.sameFilesystem === false;
118
179
  if (report.operationFailures)
119
180
  return {
120
181
  id,
@@ -137,12 +198,20 @@ export function diskGcReportCheck(
137
198
  remedy: {
138
199
  action:
139
200
  'Inspect the remaining protected data and the GC service result. Add disk capacity if live data exceeds the target.' +
140
- (report.sameFilesystem === false
141
- ? ' ' + STORE_FILESYSTEM_REMEDY
142
- : ''),
201
+ (otherFilesystem ? ' ' + STORE_FILESYSTEM_REMEDY : ''),
202
+ },
203
+ };
204
+ if (inventoryOverdue(report.inventory, now))
205
+ return {
206
+ id,
207
+ status: 'warn',
208
+ summary,
209
+ remedy: {
210
+ action:
211
+ 'Inspect the collector service and storage I/O pressure. Cleanup reported its outcome before inventory began.',
143
212
  },
144
213
  };
145
- return report.sameFilesystem === false
214
+ return otherFilesystem
146
215
  ? {
147
216
  id,
148
217
  status: 'warn',
@@ -128,13 +128,44 @@ const memoryReserved: Probe = async (run) => {
128
128
  : ['AGENT_PRESSURE_KILL_ENABLED', PRESSURE_POLICY_REMEDY];
129
129
  };
130
130
 
131
- const agentsBounded: Probe = async (run) =>
132
- (await run(['test', '-f', AGENT_DROP_IN])).ok
133
- ? undefined
134
- : [
131
+ const agentsBounded: Probe = async (run) => {
132
+ for (const path of [
133
+ AGENT_DROP_IN,
134
+ '/etc/systemd/user/t3code-codex-.scope.d/60-personal-fleet.conf',
135
+ '/usr/local/lib/personal-fleet-agent-tool/agent-tool.bash',
136
+ '/usr/local/lib/personal-fleet-agent-tool/agent-tool.py',
137
+ '/usr/local/lib/personal-fleet-agent-tool/agent-tool-policy.json',
138
+ ]) {
139
+ if (!(await run(['test', '-f', path])).ok)
140
+ return [
135
141
  'AGENT_MEMORY_LIMIT_MISSING',
136
- 'T3 agent scopes have no per-agent memory limit. Reapply converge; new agents pick it up without restarts.',
142
+ 'Run homelab converge to install shared-provider protection and shell tool memory admission.',
137
143
  ];
144
+ }
145
+ const scopes = await run([
146
+ 'systemctl',
147
+ '--user',
148
+ 'show',
149
+ 't3code-codex-*.scope',
150
+ '--property=MemoryMax,MemoryMin',
151
+ ]);
152
+ const fields = scopes.stdout.trim().split('\n').filter(Boolean);
153
+ if (
154
+ !scopes.ok ||
155
+ fields.some(
156
+ (line) =>
157
+ (line.startsWith('MemoryMax=') && line !== 'MemoryMax=infinity') ||
158
+ (line.startsWith('MemoryMin=') &&
159
+ Number(line.slice('MemoryMin='.length)) <
160
+ policy.resourceSafety.agentTool.providerReserveMiB * MIB)
161
+ )
162
+ )
163
+ return [
164
+ 'AGENT_LIMIT_OVERRIDDEN',
165
+ 'Run homelab converge to migrate existing shared Codex scopes and remove stale property overrides. Verify a fresh Bash command enters a homelab-tool scope before heavy work.',
166
+ ];
167
+ return undefined;
168
+ };
138
169
 
139
170
  const agentSliceBounded: Probe = async (run) => {
140
171
  const [slice, memory] = await Promise.all([
@@ -485,6 +516,28 @@ async function oomdAgentKills(run: Runner): Promise<number | undefined> {
485
516
  return oomdReadable ? oomdKills : undefined;
486
517
  }
487
518
 
519
+ async function kernelProviderKills(run: Runner): Promise<number | undefined> {
520
+ const kernel = await run([
521
+ 'sudo',
522
+ '-n',
523
+ 'journalctl',
524
+ '--quiet',
525
+ '--dmesg',
526
+ '--since=24 hours ago',
527
+ '--output=cat',
528
+ '--grep=oom-kill:',
529
+ ]);
530
+ const kernelReadable =
531
+ kernel.ok || (kernel.reason === 'exit' && !kernel.stderr.trim());
532
+ return kernelReadable
533
+ ? kernel.stdout
534
+ .split('\n')
535
+ .filter(
536
+ (line) => /task=codex,/.test(line) && /app-t3code-agents/.test(line)
537
+ ).length
538
+ : undefined;
539
+ }
540
+
488
541
  export async function pressureEvents(run: Runner): Promise<Check> {
489
542
  const id = 'worker:pressure-events';
490
543
  const events = await run([
@@ -505,6 +558,7 @@ export async function pressureEvents(run: Runner): Promise<Check> {
505
558
  status: 'warn',
506
559
  summary: 'Recent pressure guard activity could not be read.',
507
560
  };
561
+ const providerKills = await kernelProviderKills(run);
508
562
  const oomdKills = await oomdAgentKills(run);
509
563
  const { stops, dryRuns, unclassified } = pressureCounts(events.stdout);
510
564
  const count = stops.cpu + stops.io + stops.memory + stops.unknown;
@@ -513,16 +567,16 @@ export async function pressureEvents(run: Runner): Promise<Check> {
513
567
  '-e',
514
568
  '/run/personal-fleet-pressure-guard/active',
515
569
  ]);
516
- const warn = Boolean(
517
- count || unclassified || active.ok || oomdKills || oomdKills === undefined
518
- );
570
+ const warn =
571
+ [count, unclassified, active.ok, oomdKills, providerKills].some(Boolean) ||
572
+ [oomdKills, providerKills].includes(undefined);
519
573
  const pressure = active.ok
520
574
  ? 'The guard currently reports sustained pressure.'
521
575
  : 'The sustained-pressure marker is absent.';
522
576
  return {
523
577
  id,
524
578
  status: warn ? 'warn' : 'pass',
525
- summary: `In the last 24 hours the pressure guard stopped ${count} workloads (CPU: ${stops.cpu}, I/O: ${stops.io}, memory: ${stops.memory}, unknown cause: ${stops.unknown}). Dry runs: ${dryRuns}. Unclassified historical records: ${unclassified}. ${pressure} systemd-oomd agent kills: ${oomdKills ?? 'unavailable'}.`,
579
+ summary: `In the last 24 hours the pressure guard stopped ${count} workloads (CPU: ${stops.cpu}, I/O: ${stops.io}, memory: ${stops.memory}, unknown cause: ${stops.unknown}). Dry runs: ${dryRuns}. Unclassified historical records: ${unclassified}. ${pressure} systemd-oomd agent kills: ${oomdKills ?? 'unavailable'}. Kernel shared-provider OOM kills: ${providerKills ?? 'unavailable'}.`,
526
580
  ...(warn
527
581
  ? {
528
582
  remedy: {