#!/bin/bash # THIS MAC'S ROW OF THE MACHINES TOOL, kept fresh — dev tooling, never app code. # # bash scripts/dev/machine-row.sh # sample this Mac and write its row # bash scripts/dev/machine-row.sh --dry-run # print the row and the floor, write nothing # # The owner's real database holds a "Machines" tool (table `machine`), one row # per Mac: its chip, memory and disk free, load, the coding sessions running, # macOS, the installed CottonDB version, and WHAT IT CAN DO FOR A RELEASE # (`capabilities`: builder, signer). Every Mac may build and sign (owner, # 12 Oct 2026), so whoever places a cut reads these rows and picks a signer # with room, never "the" build Mac. # # THE READINGS ARE THE SYSTEM'S. No app is asked: `sysctl` (chip, cores, # memory, macOS), `vm_stat` (free memory is free + inactive + speculative # pages, as `crates/cotton-session-host/src/machine.rs` counts it, because an # inactive page is the kernel's to hand over the moment somebody asks), `df` # on the home volume, `sysctl vm.loadavg`, and `security find-identity` for # whether this Mac holds a Developer ID Application identity (signer). # Each is called by name, from launchd's PATH, so a test can stand in for it. # `builder` is not this Mac's to say: it is the declared row, read off the # owner's `list_devices`. # # WRITTEN AS THE TABLE'S PRODUCER. The `machine` table names one token as its # producer (`producer.token_id`), and only that token fills its read-only # columns (`apps/business/src/mcp/tools/records/values.ts` `authored`). That # token — scopes read, write, machines — is minted once by the owner and set as # the producer by `machine-row-install.sh --mint` on one Mac, and copied to each # Mac as ~/.cotton-agent/machine-producer-token (0600). It is read inside # python and sent in a header: never in argv, never printed, never in an error. # The endpoint is `COTTON_MCP_URL`, else the personal object's /mcp. # # THIS MAC'S KEEP-FREE FLOOR, published from the same disk reading to # ~/.cottondb/disk-policy.json — {keepFreeBytes, sampledAt (seconds), volumeId # (`stat -f %d` of the home volume)} — which the build guard # (scripts/lib/mac_disk_policy.py, installed by install-mac-build-policy.py) # and claims-sweep.sh read and refuse once it is three periods (540 s) old. The # rule is the one the old CottonDB app published by # (crates/cotton-core/src/device/disk.rs `keep_free_bytes`): 15% of the # volume, or the Mac's own setting in ~/.cotton-agent/keep-free-bytes (whole # bytes), never below 10% of the volume. It is written before anything is asked # of the network, so a refused or unreachable row still leaves a fresh floor; a # setting that is not a whole number publishes nothing and says why. # # Installed per Mac as a launchd agent every five minutes by # its installer, which copies THIS file to # ~/.cotton-agent/machine-row.sh so the agent never depends on a worktree. set -euo pipefail name="$(scutil --get LocalHostName 2>/dev/null || hostname -s)" name="$(printf '%s' "$name" | tr '[:upper:]' '[:lower:]')" NAME="$name" \ SESSIONS="$( (pgrep -x claude || true) | wc -l | tr -d ' ')" \ APP_PATH="${COTTON_APP:-/Applications/CottonDB.app}" \ DRY_RUN="${1:-}" \ exec /usr/bin/python3 - <<'PY' import datetime, json, os, plistlib, subprocess, sys, tempfile, time, urllib.request env = os.environ try: with open(os.path.join(env["APP_PATH"], "Contents/Info.plist"), "rb") as file: app_info = plistlib.load(file) except (OSError, ValueError, plistlib.InvalidFileException): app_info = {} installed_at = None try: with open(os.path.expanduser("~/.cotton-agent/mac-install.json")) as file: installed = json.load(file) if (os.path.realpath(installed["app"]) == os.path.realpath(env["APP_PATH"]) and installed["version"] == app_info.get("CFBundleShortVersionString") and installed["build"] == str(app_info.get("CFBundleVersion"))): instant = datetime.datetime.fromisoformat(installed["installed_at"].replace("Z", "+00:00")) if instant.tzinfo is not None: installed_at = installed["installed_at"] except (OSError, ValueError, KeyError, TypeError, AttributeError): pass # No verified install stamp: never substitute the sampling time. GIB = 1024 ** 3 def ask(*argv, timeout=20): """What a system command printed, or None when it could not say.""" try: said = subprocess.run(list(argv), capture_output=True, text=True, timeout=timeout) except (OSError, subprocess.SubprocessError): return None return said.stdout if said.returncode == 0 else None def sysctl(key): value = (ask("sysctl", "-n", key) or "").strip() return value or None def free_pages(text): # Free + inactive + speculative, `parse_vm_stat_free_pages`'s count. pages = {} for line in (text or "").splitlines(): label, _, value = line.partition(":") value = value.strip().rstrip(".") if value.isdigit(): pages[label.strip()] = int(value) if "Pages free" not in pages: return None return pages["Pages free"] + pages.get("Pages inactive", 0) + pages.get("Pages speculative", 0) def disk(): # Free is what a non-root process may still write (df's "Available"). # Bytes: the size of the home volume and what is free on it. lines = (ask("df", "-k", os.path.expanduser("~")) or "").splitlines() try: fields = lines[1].split() return int(fields[1]) * 1024, int(fields[3]) * 1024 except (IndexError, ValueError): return None, None def share(total, percent): return -(-total * percent // 100) def keep_free(total): # crates/cotton-core/src/device/disk.rs `keep_free_bytes`: 15% of the # volume, or the setting, never below 10%. path = os.path.expanduser("~/.cotton-agent/keep-free-bytes") try: with open(path) as file: said = file.read().strip() except FileNotFoundError: return share(total, 15) if not said.isdigit(): raise ValueError(f"{path} is not a whole number of bytes") return max(int(said), share(total, 10)) def publish_floor(total, dry_run): # A floor that cannot be taken is not published: the last one ages and the # build guard refuses, naming this script. home = os.path.expanduser("~") target = os.path.join(home, ".cottondb", "disk-policy.json") try: policy = {"keepFreeBytes": keep_free(total), "sampledAt": int(time.time()), "volumeId": int((ask("stat", "-f", "%d", home) or "").strip())} except (OSError, ValueError) as error: print(f"machine-row: no keep-free floor published ({error})", file=sys.stderr) return if dry_run: print(f"machine-row: would publish {json.dumps(policy)} to {target}", file=sys.stderr) return os.makedirs(os.path.dirname(target), exist_ok=True) handle, partial = tempfile.mkstemp(dir=os.path.dirname(target), prefix=".disk-policy.") with os.fdopen(handle, "w") as file: json.dump(policy, file, separators=(",", ":")) os.chmod(partial, 0o644) os.replace(partial, target) def load(): # "{ 1.23 1.10 0.98 }" words = (sysctl("vm.loadavg") or "").strip("{} ").split() return float(words[0]) if words else None def signs(): listing = ask("security", "find-identity", "-v", "-p", "codesigning") or "" return "Developer ID Application:" in listing memsize = int(sysctl("hw.memsize") or 0) page = int(sysctl("hw.pagesize") or 0) free = free_pages(ask("vm_stat")) disk_total_bytes, disk_free_bytes = disk() if disk_total_bytes: publish_floor(disk_total_bytes, env.get("DRY_RUN") == "--dry-run") disk_total_raw = None if disk_total_bytes is None else disk_total_bytes / GIB disk_free_raw = None if disk_free_bytes is None else disk_free_bytes / GIB load_raw = load() if not memsize or not page or free is None or disk_total_raw is None or load_raw is None: # A reading the system would not give is a row NOT written — the last one ages and says so. sys.exit("machine-row: this Mac did not answer memory, disk or load") sample = { "chip": sysctl("machdep.cpu.brand_string"), "cpu_count": int(sysctl("hw.ncpu") or 0) or None, "mem_total_gb": memsize / GIB, "mem_free_pct": max(0, min(100, round(free * page / memsize * 100))), "disk_total_gb": disk_total_raw, "disk_free_gb": disk_free_raw, "load1": load_raw, "os_version": sysctl("kern.osproductversion"), } def model_name(): # What this Mac is, as About This Mac says it ("Mac mini", "MacBook Pro"): # the card draws its picture by it. Unknown is null, never a guess. try: said = subprocess.run(["system_profiler", "-json", "SPHardwareDataType"], capture_output=True, text=True, timeout=20) return (json.loads(said.stdout).get("SPHardwareDataType") or [{}])[0].get("machine_name") or None except Exception: return None def whole(key): value = sample.get(key) return None if value is None else round(value) mem_total = whole("mem_total_gb") mem_free = None if mem_total is None or sample.get("mem_free_pct") is None else round(sample["mem_total_gb"] * sample["mem_free_pct"] / 100) disk_total, disk_free = whole("disk_total_gb"), whole("disk_free_gb") load_1 = round(float(sample["load1"]), 2) cpus = int(sample["cpu_count"] or 0) can_sign = signs() row = { "name": env["NAME"], "chip": sample.get("chip"), "model": model_name(), "cpu_count": cpus, "mem_total_gb": mem_total, "mem_free_gb": mem_free, "mem_used_gb": None if mem_free is None else mem_total - mem_free, "memory": f"{mem_free} of {mem_total} GB free", "disk_total_gb": disk_total, "disk_free_gb": disk_free, "disk_used_gb": None if disk_free is None or disk_total is None else disk_total - disk_free, "disk": f"{disk_free} of {disk_total} GB free", "load_1": load_1, "load": f"{load_1:g} on {cpus} cores", "sessions": int(env["SESSIONS"] or 0), "os_version": "macOS " + sample["os_version"] if sample.get("os_version") else None, "app_version": app_info.get("CFBundleShortVersionString") or None, "installed_at": installed_at, # An instant, so the phone says "5 min ago" (the column is read `ago`); a # serving Mac older than the rule that admits one answers "a date written # YYYY-MM-DD", and then the day is written instead. "sampled_at": datetime.datetime.now(datetime.timezone.utc).isoformat(timespec="seconds").replace("+00:00", "Z"), } def capabilities(builder): # Null, not "", for a Mac that is neither: an empty text is a value somebody reads. return ", ".join(word for word, held in (("builder", builder), ("signer", can_sign)) if held) or None if env.get("DRY_RUN") == "--dry-run": # Nothing is asked of the serving Mac on a dry run, so `builder` is not known. row["capabilities"] = capabilities(False) print(json.dumps(row, indent=2)) sys.exit(0) def credentials(): endpoint = env.get("COTTON_MCP_URL") or "https://cottondb.com/mcp" with open(os.path.expanduser("~/.cotton-agent/machine-producer-token")) as file: return endpoint, file.read().strip() try: endpoint, token = credentials() except Exception: sys.exit("machine-row: no producer token at ~/.cotton-agent/machine-producer-token — machine-row-install.sh puts it there") class Refused(Exception): pass def call(tool, arguments): body = json.dumps({"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": {"name": tool, "arguments": arguments}}).encode() request = urllib.request.Request(endpoint, data=body, method="POST", headers={ "authorization": "Bearer " + token, "content-type": "application/json", "accept": "application/json, text/event-stream", "user-agent": "cotton-machine-row/1"}) try: with urllib.request.urlopen(request, timeout=30) as answer: rpc = json.load(answer) except Exception as error: sys.exit(f"machine-row: {tool} did not answer ({type(error).__name__}: {getattr(error, 'code', '')})") if rpc.get("error"): sys.exit(f"machine-row: {tool}: {rpc['error'].get('message', 'RPC error')}") result = rpc.get("result") or {} text = ((result.get("content") or [{}])[0]).get("text", "") if result.get("isError"): raise Refused(f"machine-row: {tool}: {text[:200]}") return json.loads(text) def write(tool, arguments): try: return call(tool, arguments) except Refused as refusal: if "YYYY-MM-DD" not in str(refusal): sys.exit(str(refusal)) for key in ("patch", "data"): if key in arguments: arguments[key]["sampled_at"] = datetime.date.today().isoformat() return call(tool, arguments) # WHETHER THIS MAC IS A BUILDER, off its own entry in the serving Mac's # `list_devices` (the newest approval of this name that is not revoked). A # serving Mac older than `capabilities` names none, and then this row says # only what the helper knows and the log says why. try: devices = call("list_devices", {"includeRevoked": False}).get("devices") or [] except Refused as refusal: sys.exit(str(refusal)) mine = [device for device in devices if (device.get("name") or "").lower() == row["name"]] declared = mine[0].get("capabilities") if mine else None if declared is None: print(f"machine-row: the serving Mac does not say whether {row['name']} is a builder yet (no `capabilities` in list_devices) — the row says signer only") row["capabilities"] = capabilities("builder" in (declared or [])) try: found = call("list_records", {"table": "machine", "where": {"name": row["name"]}, "limit": 1}) except Refused as refusal: sys.exit(str(refusal)) records = found.get("records") or [] stamp = datetime.datetime.now().astimezone().isoformat(timespec="seconds") # EVERY WRITE NAMES ITS DATABASE (the writedoor, 14 Oct 2026). The row already # has one home and the read that found it says which (`databaseId`, stamped on # an answer read across more than one database); the first row is made in the # owner's personal database, where the Machines tool lives. A write with no # database was refused by 0.29.55 every five minutes into this agent's own log # and nowhere else, and every Machines row stopped at 06:02-06:06Z. home = found.get("databaseId") or "personal" if records: write("update_record", {"table": "machine", "id": records[0]["id"], "patch": row, "database": home}) print(f"{stamp} machine-row: updated {row['name']} ({row['memory']}, {row['disk']}, load {row['load_1']}, {row['sessions']} sessions, can: {row['capabilities'] or 'nothing for a release'})") else: row["notes"] = "Written every five minutes by scripts/dev/machine-row.sh on this Mac." write("create_record", {"table": "machine", "data": row, "database": "personal"}) print(f"{stamp} machine-row: created {row['name']}") PY