# About (/about) Logos・2021 to present} description="Creative Technologist / Brand Director. Prototyping and shipping applications on the Logos stack, building AI agent tooling, and leading the internal creative studio." />
GitHub ↗ LinkedIn ↗ X ↗ CV ↗
# Ned Karlovich (/) For AI startups, research labs, and studios. ## Selected work [#selected-work] ## More [#more] # Studio (/studio) The record of earlier work, mostly brand systems, made as creative director for Nike, Jordan Brand, Magic Leap and others. The 96 project pages still live on the current site. This page links to them. | Period | Where | Role | | --- | --- | --- | | 2021 to present | [Logos](https://logos.co) | Creative Technologist / Brand Director | | 2007 to 2011, 2021 to 2023 | Nike | Global Creative Director, Brand Design. Freelance for Nike Brand Design EMEA 2013 to 2019 | | 2020 to 2021 | OLIVER / Adidas | Executive Design Director | | 2019 to 2020 | Magic Leap | Brand Creative Director | | 2018 | Status | Creative Director | | 2016 to 2018 | R/GA | Executive Creative Director | | 2011 to 2015 | The Invisible Party | Co-founder and Creative Director | | 2011 to 2012 | …,staat Amsterdam | Creative Director | | 2006 to 2007 | Fahrenheit 212 | Design Director | | to 2006 | ATTIK | Senior Designer | # Weblog (/weblog) The articles, the research program and the knowledge graph are on the weblog, at weblog.nedkarlovich.com. > Working hypothesis: designed systems constitute their users. If so, a system’s grammar (its rules, its memory, its exits) is where design matters most, and where it can still be read and contested. # AgentixOS (/work/agentixos) Version 0.3. Open source. | Role | Year | Kind | Try it | | --- | --- | --- | --- | | Concept, safety design, engineering | 2026 | AI infrastructure | [Source on GitHub](https://github.com/Beach-Bum/Agentix) | | | | | --- | --- | | **0** | commands the agent can run as root | | **6** | rungs on the safety ladder, each reversible until the next | | **81 + 216** | automated tests, in Agentix and in λ OS, which is built on it | ## The problem [#the-problem] The long-term goal is an operating system where AI agents help configure, repair, maintain and evolve the machine, without being given unrestricted control of the live system. It starts with NixOS because NixOS gives a strong foundation: declarative configuration, reproducible builds, changes that roll back, and clear system boundaries. ## What I built [#what-i-built] - **Plan, sandbox, propose, verify.** Every goal follows the same path. The work happens in a temporary Git worktree and is saved as a proposal. The source workspace stays untouched. - **A hard stop.** Agentix does not run sudo or rebuild the system. It does not edit the system configuration, commit or push. Applying, verifying and activating a change are for a person only. - **A controller for other agents.** One command prints the safety contract. Another plans a goal and, if asked, runs it end to end with a full audit. Claude Code works against the same contract. ## How it is structured [#how-it-is-structured] describe what is allowed] --> A2[Dry run
parse and validate] A2 --> A3[Execute
in a temporary worktree] A3 --> A4[Saved proposal patch] end subgraph Human[Only a person may do this] H1[Review the diff] --> H2[Apply and verify] --> H3[Rebuild the system] end A4 --> H1 A3 -.->|every run| L[(Audit log)] `} /> ### The safety ladder [#the-safety-ladder] `controller-plan`: describe what is allowed `controller-run` (dry run): parse and validate, nothing runs `controller-run --execute`: run the goal in a temporary worktree and save a proposal Saved proposal patch: a person reviews the diff A person applies the patch and verifies it A person rebuilds and activates the new system Each rung is reversible until the next. The agent stops after the third. ## In the code [#in-the-code] From [`Beach-Bum/Agentix`](https://github.com/Beach-Bum/Agentix), which is public. The boundary is this block, at the end of every run. It takes a second snapshot of the real workspace and compares it with the one taken before. Both ways it can go wrong end the run as a failure: if the snapshot itself cannot be taken, the workspace is treated as modified. ```python title="agentix/worktree_run.py" allowed_paths: set[str] = set() if result["proposal_saved"]: try: allowed_paths.add( str(Path(result["proposal_saved"]).resolve().relative_to(path.resolve())) ) except ValueError: pass source_after = snapshot_source(path) if source_after.get("error"): result["passed"] = False result["source_modified"] = True result["error"] = "source_snapshot_failed" result["source_mutations"] = [source_after["error"]] _audit_worktree("source_snapshot_failed") if json_output: emit_json(result) else: print() print("Source snapshot failed after run.") print(f"- {source_after['error']}") return 1 mutations = compare_source(source_before, source_after, allowed_new_paths=allowed_paths) if mutations: result["passed"] = False result["source_modified"] = True result["error"] = "source_workspace_mutated" result["source_mutations"] = mutations _audit_worktree("source_workspace_mutated") if json_output: emit_json(result) else: print() print("Source workspace was mutated unexpectedly:") for m in mutations: print(f"- {m}") return 1 ``` The one path a run is allowed to add is its own saved proposal, which is why that path is passed in as an exception. ## What keeps it safe [#what-keeps-it-safe] - **Source untouched, checked.** Every run records the state of the workspace before and after, including a hash of every untracked file. Any unexpected change fails the run. - **A time limit.** Runs stop after 1,800 seconds by default and report a timeout. - **An audit log.** One line per run, appended to a log a person can review. - **Safe to publish.** A check flags private material, and an export strips it. ## How "source untouched" is checked [#how-source-untouched-is-checked] Before a run, Agentix records three things about the real workspace: the commit it is on, the full difference from that commit, and a SHA-256 hash of every file git does not track. After the run it records them again and compares. Any difference fails the run and is named in the result. ```python title="agentix/source_snapshot.py" def compare_source(before: dict, after: dict, allowed_new_paths: set[str] | None = None) -> list[str]: allowed = set(allowed_new_paths or set()) mutations: list[str] = [] if before.get("head") != after.get("head"): mutations.append(f"head changed: {before.get('head')} -> {after.get('head')}") if before.get("tracked_diff") != after.get("tracked_diff"): mutations.append("tracked files changed in source workspace") before_untracked = before.get("untracked", {}) or {} after_untracked = after.get("untracked", {}) or {} for rel, hash_ in sorted(after_untracked.items()): if rel not in before_untracked: if rel in allowed: continue mutations.append(f"new untracked file: {rel}") elif before_untracked[rel] != hash_: mutations.append(f"untracked file content changed: {rel}") for rel in sorted(before_untracked): if rel not in after_untracked: mutations.append(f"untracked file removed: {rel}") return mutations ``` ## The test that tries to cheat [#the-test-that-tries-to-cheat] The check is only worth something if a run that misbehaves is caught. This test stands in a fake agent that does legitimate work inside the sandbox and, in the same script, writes a file into the real workspace. The run must fail and must name the file. ```python title="tests/test_management_commands.py" def test_worktree_run_source_check_detects_source_taint(tmp_path: Path, capsys) -> None: from agentix.worktree_run import worktree_run project = tmp_path / "nixos-config" project.mkdir() create_nixos_fixture(project) fake_agentix = tmp_path / "fake-agentix" fake_agentix.write_text( f"""#!/usr/bin/env bash set -euo pipefail printf '%s\n' '# tainted source file' > "{project}/modules/tampered.nix" printf '%s\n' '# legit worktree work' > modules/legit.nix git add modules/legit.nix """, encoding="utf-8", ) fake_agentix.chmod(0o755) result = worktree_run( path=project, goal="create module legit with template packages", agentix_command=str(fake_agentix), save_proposal_patch=True, json_output=True, ) output = capsys.readouterr().out payload = json.loads(output) assert result != 0 assert payload["passed"] is False assert payload["source_modified"] is True assert payload["error"] == "source_workspace_mutated" assert isinstance(payload.get("source_mutations"), list) assert any("modules/tampered.nix" in m for m in payload["source_mutations"]) assert (project / "modules" / "tampered.nix").exists() ``` ## A hole I found while writing this page [#a-hole-i-found-while-writing-this-page] Reading the boundary above for this case study, I saw that two paths returned before it: a goal that fails, and a goal that times out. On those paths the result still said the workspace was untouched. That was a default value, not a finding. A run that damaged the real workspace and then failed would have been reported as a failed goal and nothing more. The fix runs the same comparison on both paths. The error and exit code stay what they were, so nothing reading them breaks; the result gains what changed. ```python title="agentix/worktree_run.py" def _source_mutations(allowed: set[str] | None = None) -> list[str]: """What changed in the source workspace since the pre-run snapshot. Fails closed: a snapshot that cannot be taken is reported as a mutation. """ after = snapshot_source(path) if after.get("error"): return [after["error"]] return compare_source(source_before, after, allowed_new_paths=allowed) def _record_taint_on_failure() -> None: # A goal that failed or timed out may still have written to the source # workspace. Without this the result would say source_modified=False # for a run that was never checked. mutations = _source_mutations() if not mutations: return result["source_modified"] = True result["source_mutations"] = mutations if not json_output: print() print("Source workspace was mutated unexpectedly:") for m in mutations: print(f"- {m}") ``` The test is the earlier one with a worse agent: it writes into the real workspace and then exits with an error. It fails on the code as it was and passes with the fix. ```python title="tests/test_management_commands.py" def _tainting_agent(tmp_path: Path, project: Path, then: str) -> Path: """A fake agent that writes into the real workspace, then runs `then`.""" fake_agentix = tmp_path / "fake-agentix" fake_agentix.write_text( f"""#!/usr/bin/env bash printf '%s\n' '# tainted source file' > "{project}/modules/tampered.nix" {then} """, encoding="utf-8", ) fake_agentix.chmod(0o755) return fake_agentix def test_worktree_run_failed_goal_still_reports_source_taint(tmp_path: Path, capsys) -> None: from agentix.worktree_run import worktree_run project = tmp_path / "nixos-config" project.mkdir() create_nixos_fixture(project) result = worktree_run( path=project, goal="create module legit with template packages", agentix_command=str(_tainting_agent(tmp_path, project, "exit 7")), json_output=True, ) payload = json.loads(capsys.readouterr().out) assert result == 7 assert payload["passed"] is False assert payload["error"] == "goal_failed" assert payload["source_modified"] is True assert any("modules/tampered.nix" in m for m in payload["source_mutations"]) events = _read_audit_events(project) assert events[-1]["result"] == "goal_failed" assert events[-1]["source_modified"] is True ``` This went in with [pull request 1](https://github.com/Beach-Bum/Agentix/pull/1), now merged, with a second test for the timeout and a third that a clean failure still reports the workspace untouched. ## The audit log [#the-audit-log] Every run appends one line of JSON to `.agentix/audit.jsonl` in the workspace: a UTC timestamp and what happened, with the keys sorted so two logs can be compared line by line. It is an append-only text file. Nothing chains or signs the lines, so it records what happened and does not prove nobody edited it. ## How it is tested [#how-it-is-tested] 81 automated tests, run on every push together with a syntax check of every Python file. They test the refusals as much as the features: a stale patch is refused before the person is even asked, a package change is refused on a dirty tree, and the public export leaves private files out. ## What it does not do [#what-it-does-not-do] - **There is no model inside it.** A goal is matched against two patterns, "add a package" and "create a module". Agentix is the harness an agent such as Claude Code works through, not an agent that reasons. - **Ignored files are not hashed.** A change to a file git ignores is not seen. The policy check is a list of eight text patterns (`sudo`, `rm -rf`, SSH keys, `/etc/nixos`, and network fetches as a warning). It catches the obvious request; it is not a sandbox, and a determined command could be written to slip past it. The actual boundary is elsewhere: the agent works in a temporary copy, the real workspace is checked before and after, and only a person applies a patch or rebuilds the system. It is about 3,900 lines of Python 3.12 at version 0.3, with no third-party dependencies: only the standard library, git and Nix. It has been used on my own machines, not at scale. ## In use [#in-use] [λ OS](https://github.com/Beach-Bum/lambda-os) is built on Agentix and is public. It manages the lifecycle of the 55 modules in a Logos workspace: it takes a snapshot, tests each module in a sandbox on a timer, rolls a failing module back to its last good version, orders upgrades by their dependency graph, and proposes changes for a person to approve. ### Its audit log, and what "tamper-evident" has to mean [#its-audit-log-and-what-tamper-evident-has-to-mean] λ OS seals its audit log: for every line it records a hash of the line, the hash of the line before, and a root binding both to a position. The design documents call the log tamper-evident. Checking that claim for this page, I found it was not true yet. The verifier recomputed every hash and compared them with nothing. A rewritten event verified as valid. This is the part that now does the comparing: ```python title="agentix_logos/audit_chain.py" records = load_chain_sidecar(sidecar_path) errors.extend(_check_sidecar(records)) mismatched = [ i for i, rec in enumerate(records[: len(lines)]) if compute_cid(lines[i]) != rec.get("cid") ] for i in mismatched[:MAX_REPORTED_ERRORS]: errors.append(f"Line {i}: content does not match the CID sealed for this position") if len(mismatched) > MAX_REPORTED_ERRORS: errors.append( f"{len(mismatched) - MAX_REPORTED_ERRORS} more lines do not match " f"(first divergence at line {mismatched[0]})" ) if len(lines) < len(records): errors.append( f"Log is shorter than its sealed chain: {len(records) - len(lines)} sealed " f"line(s) missing from the end" ) return ChainVerification( valid=not errors, entries=len(lines), errors=errors, sealed=min(len(lines), len(records)), unsealed=max(0, len(lines) - len(records)), ) ``` And one of sixteen tests that tamper with a sealed log. This is the careful attacker, who changes an event and then corrects the hash recorded for it: ```python title="tests/test_audit_tamper.py" def test_editing_the_sidecar_to_match_a_changed_line_is_detected(sealed: Path) -> None: # the careful attacker: change the event, then fix up its recorded CID from agentix_logos.audit_chain import compute_cid lines = _lines(sealed) lines[2] = lines[2].replace("false", "true ") _rewrite(sealed, lines) sidecar = sealed.parent / SIDECAR_NAME records = [json.loads(r) for r in sidecar.read_text(encoding="utf-8").splitlines()] records[2]["cid"] = compute_cid(lines[2]) sidecar.write_text("".join(json.dumps(r, sort_keys=True) + "\n" for r in records), encoding="utf-8") result = verify_chain(sealed) assert result.valid is False # entry 2's root no longer matches its fields, and entry 3 no longer links to it assert any(e.startswith("Chain entry 2:") for e in result.errors) assert any(e.startswith("Chain entry 3:") for e in result.errors) ``` The others rewrite an event in place, change one character on each line in turn, delete, insert, reorder, and cut the log short. All sixteen passed as valid before the change. The fix is [pull request 1](https://github.com/Beach-Bum/lambda-os/pull/1), now merged; 216 tests pass. What it still cannot do, and the code says so: someone who can rewrite the log can rewrite the sealed record beside it and recompute everything. The check only binds once that record is held somewhere the writer cannot reach. That publishing step is designed and not built. ## More [#more] # Agora Agent (/work/agora) Prototype, and an unfinished one. Built as a submission for a Logos Lambda Prize (LP-0008). The parts exist; they are not yet joined into a trade that completes. This page says which is which. | Role | Year | Kind | Try it | | --- | --- | --- | --- | | Concept, protocol design, engineering | 2026 | Agent infrastructure | [Source on GitHub](https://github.com/Beach-Bum/agora-agent) | | | | | --- | --- | | **3** | contracts in Rust: escrow, identity, reputation | | **24 + 37** | tests that run: on the contracts, and on the agent | | **10 / 100** | default spending limits for an agent, per payment and per day | ## The problem [#the-problem] If agents are going to pay each other for work, three things usually sit in the middle: a hosted model that does the reasoning, a public chain where every payment can be read, and a company that can switch the whole thing off. I wanted to see how far an agent marketplace could get with none of the three. This is the agent marketplace. Agora Bazaar, a marketplace for people on the same stack, is a separate project. ## What I built [#what-i-built] - **An agent** that runs continuously as a seller and, on request, as a buyer: it listens for requests, decides whether to offer, delivers, and gets paid. - **A wallet with a policy.** The agent holds its own key and can only spend inside limits its owner sets. - **Three contracts, as models.** Escrow holds the payment, identity names the agent, reputation records how its trades went. They are plain Rust state machines with no chain SDK; they model the rules and are not deployed. - **A module and interface for Logos Basecamp,** in C++ and QML, with views for the marketplace, buying, selling, the wallet and an activity feed. ## How it is structured [#how-it-is-structured] sets limits] --> A[Agent
perceive, reason, act] L[Local model] --> A A --> M[Messaging
discover and negotiate] A --> B[Blockchain
identity, escrow, payment] A --> S[Storage
deliver and verify] `} /> The agent is Python, about 6,800 lines. The contracts are Rust, about 1,500 lines. The Basecamp module and interface are C++ and QML. ## How a trade is meant to be made safe [#how-a-trade-is-meant-to-be-made-safe] Neither agent trusts the other, so the escrow contract is meant to. | Step | What the contract code does | | --- | --- | | **1. Lock** | Records the payment plus a bond of 10% of it, and the hash the seller commits to. | | **2. Deliver** | The seller reveals the delivery. If its hash does not match the commitment, the trade is marked disputed without anyone having to ask. | | **3. Release** | The buyer releases the payment and gets the bond back. | | **4. Or time out** | If the seller never delivers, the buyer takes back the payment and the bond after the deadline. | The bond is there so that disputing is not free: a buyer who disputes an honest delivery has something to lose. ```rust title="contracts/escrow/src/lib.rs" pub fn notify_delivery( &mut self, caller_id: &AgentId, escrow_id: &str, actual_output_hash: String, logos_storage_cid: String, ts: TimestampMs, ) -> Result { let record = self.escrows.get_mut(escrow_id) .ok_or(ContractError::EscrowNotFound)?; if &record.seller_id != caller_id { return Err(ContractError::UnauthorisedCaller); } if record.status != EscrowStatus::Pending { return Err(ContractError::EscrowNotPending); } if ts > record.timeout_ms { return Err(ContractError::EscrowExpired); } // FIX-2: Verify hash matches commitment (which includes buyer nonce) if actual_output_hash != record.delivery_hash_commitment { record.status = EscrowStatus::Disputed; record.dispute_reason = Some("seller revealed hash does not match commitment".into()); // Keep what the seller actually revealed as evidence for the arbiter. record.actual_output_hash = Some(actual_output_hash); record.logos_storage_cid = Some(logos_storage_cid); return Ok(DeliveryOutcome::Disputed); } record.actual_output_hash = Some(actual_output_hash); record.logos_storage_cid = Some(logos_storage_cid); record.status = EscrowStatus::Delivered; record.delivered_ts = Some(ts); // FIX-3: record delivery time for grace period Ok(DeliveryOutcome::Delivered) } ``` Three guards, then the reveal. The mismatch branch used to change the record and then return an error. On a real chain an error undoes the changes made before it, so the dispute would never have been recorded. It now returns success with a "disputed" result, and keeps what the seller revealed as evidence. ### Does the money add up? [#does-the-money-add-up] When I first read this contract, the lock was bookkeeping: it credited the buyer and debited the same amount, so nothing was held. Now a payment and its bond move into a held account, every payout leaves from it, and a forfeited bond goes to a treasury account. This test walks all five ways a trade can end and checks, after every step, that the four balances are exactly what they should be and add up to what was paid in. ```rust title="contracts/escrow/src/lib.rs" #[test] fn test_funds_conserved_across_all_terminal_states() { let locked = AMOUNT + BOND; let buyer_after_lock = BUYER_FUNDS - locked; // 1. Release: seller is paid, buyer gets the bond back. let mut c = EscrowContract::new(None); let eid = make(&mut c); assert_balances(&c, buyer_after_lock, 0, locked, 0); c.notify_delivery(&SELLER.into(), &eid, HASH.into(), "Qm".into(), T_DELIVERED).unwrap(); assert_balances(&c, buyer_after_lock, 0, locked, 0); c.release(&BUYER.into(), &eid, HASH.into(), NONCE.into(), 2).unwrap(); assert_eq!(c.get(&eid).unwrap().status, EscrowStatus::Released); assert_balances(&c, BUYER_FUNDS - AMOUNT, AMOUNT, 0, 0); assert_settled(&mut c, &eid); // 2. Refund after timeout: buyer gets amount + bond back. let mut c = EscrowContract::new(None); let eid = make(&mut c); assert_eq!(c.refund(&BUYER.into(), &eid, TIMEOUT - 1, 2), Err(ContractError::EscrowNotExpired)); assert_balances(&c, buyer_after_lock, 0, locked, 0); assert_eq!(c.refund(&BUYER.into(), &eid, TIMEOUT, 2), Ok(locked)); assert_eq!(c.get(&eid).unwrap().status, EscrowStatus::Refunded); assert_balances(&c, BUYER_FUNDS, 0, 0, 0); assert_settled(&mut c, &eid); // 3. Auto-claim after grace: seller is paid, buyer's bond goes to treasury. let mut c = EscrowContract::new(None); let eid = make(&mut c); c.notify_delivery(&SELLER.into(), &eid, HASH.into(), "Qm".into(), T_DELIVERED).unwrap(); c.claim_after_grace(&SELLER.into(), &eid, T_DELIVERED + DELIVERY_GRACE_MS, 2).unwrap(); assert_eq!(c.get(&eid).unwrap().status, EscrowStatus::AutoClaimed); assert_balances(&c, buyer_after_lock, AMOUNT, 0, BOND); assert_settled(&mut c, &eid); // 4. Dispute, seller at fault: buyer gets amount + bond back. let mut c = EscrowContract::new(None); let eid = make(&mut c); c.notify_delivery(&SELLER.into(), &eid, HASH.into(), "Qm".into(), T_DELIVERED).unwrap(); c.open_dispute(&BUYER.into(), &eid, "bad output".into()).unwrap(); assert_balances(&c, buyer_after_lock, 0, locked, 0); c.resolve_dispute(&ARBITER.into(), &eid, true, 2).unwrap(); assert_eq!(c.get(&eid).unwrap().status, EscrowStatus::SlashedSeller); assert_balances(&c, BUYER_FUNDS, 0, 0, 0); assert_settled(&mut c, &eid); // 5. Dispute, buyer at fault: seller is paid, buyer's bond goes to treasury. let mut c = EscrowContract::new(None); let eid = make(&mut c); c.notify_delivery(&SELLER.into(), &eid, HASH.into(), "Qm".into(), T_DELIVERED).unwrap(); c.open_dispute(&BUYER.into(), &eid, "false claim".into()).unwrap(); c.resolve_dispute(&ARBITER.into(), &eid, false, 2).unwrap(); assert_eq!(c.get(&eid).unwrap().status, EscrowStatus::SlashedBuyer); assert_balances(&c, buyer_after_lock, AMOUNT, 0, BOND); assert_settled(&mut c, &eid); } ``` `assert_settled` then tries every entry point again on the finished trade and requires that none of them moves anything. ### Who sent this message? [#who-sent-this-message] Messages between agents carried a signature that nothing checked, and the signature itself was not one another agent could verify. An agent's id is now its public key, messages are signed with Ed25519, and the check sits in a deliberate place: before the replay cache and before the rate limiter. ```python title="agent/logos/messaging.py" nonce = msg["nonce"] if not isinstance(nonce, str) or len(nonce) < 16: return False, "missing or short nonce" # Authenticate the sender before touching any per-sender state. signer_field = SIGNER_FIELD_BY_TYPE.get(msg["type"]) if isinstance(msg["type"], str) else None if signer_field is not None: valid, reason = verify_message(msg) if not valid: return False, reason sender = msg[signer_field] else: # Other message types (direct messages, topic messages, agent cards) # are not signed yet: their sender is unauthenticated. sender = msg.get("agentId") or msg.get("buyerId") or msg.get("sellerId") or "" if not isinstance(sender, str): return False, "sender id must be a string" # FIX-6: Nonce replay check if not nonce_cache.check_and_record(nonce): return False, "replay attack: nonce already seen" # FIX-9: Rate limiting if sender and not rate_limiter.allow(sender): return False, f"rate limit exceeded for {sender[:16]}" return True, "ok" ``` The order matters. If the nonce were recorded first, anyone could send a forged message carrying a real sender's next nonce and so block the real one. A test sends exactly that forgery and then checks the real message still gets through. ## Keeping the agent on a leash [#keeping-the-agent-on-a-leash] The agent holds its own key and spends only inside a policy its owner sets. This is the whole check, in the order it runs. ```python title="agent/core/daemon_wallet.py" def check_spend(self, amount_nom: float, category: str, counterparty_rep: float = 1.0, escrow_timeout_ms: int = 60000, slash_bps: int = 500) -> tuple[bool, str]: """ Check if a spend is allowed by the current policy. Returns (allowed, reason). """ if self.policy.frozen: return False, "wallet frozen by user" if amount_nom > self._balance_nom: return False, f"insufficient balance: {self._balance_nom:.2f} NOM < {amount_nom:.2f} NOM" if amount_nom > self.policy.max_per_tx_nom: return False, f"exceeds per-tx limit: {amount_nom:.2f} > {self.policy.max_per_tx_nom:.2f} NOM" # Rolling 24h window self._prune_spend_window() daily_total = sum(amt for _, amt in self._spend_window) if daily_total + amount_nom > self.policy.daily_cap_nom: return False, f"exceeds daily cap: {daily_total:.2f} + {amount_nom:.2f} > {self.policy.daily_cap_nom:.2f} NOM" if category not in self.policy.approved_categories: return False, f"category '{category}' not approved" if counterparty_rep < self.policy.min_counterparty_reputation: return False, f"counterparty reputation {counterparty_rep:.2f} below minimum {self.policy.min_counterparty_reputation:.2f}" if escrow_timeout_ms > self.policy.max_escrow_timeout_ms: return False, f"escrow timeout {escrow_timeout_ms}ms exceeds max {self.policy.max_escrow_timeout_ms}ms" if slash_bps > self.policy.max_slash_bps: return False, f"slash risk {slash_bps}bps exceeds max {self.policy.max_slash_bps}bps" return True, "approved" ``` Every decision is logged where the owner can read it. The key is kept in the operating system's keychain, or in an encrypted file where there is none. What a reviewer would say: amounts are floating-point numbers, and the 24-hour window is held in memory so a restart resets the daily cap. A negative or not-a-number amount used to pass; it is now refused before anything else is looked at. ## How it is tested [#how-it-is-tested] When I compiled the contracts for this page, two of the three did not build: the reputation contract used a variable by the wrong name, and the identity tests compared a type that could not be compared. Of 18 tests written, 7 could run. Since [pull request 3](https://github.com/Beach-Bum/agora-agent/pull/3) all three build and 24 contract tests pass: 13 on escrow, 6 on identity, 5 on reputation. The agent, which had no tests, has 37, on signing, message validation and the spending check. ## What it does not do [#what-it-does-not-do] - **No trade completes end to end.** The seller commits to a placeholder hash, the function that announces a delivery is never called, and the path that creates an escrow does not go through the wallet's limits. - **Only the five marketplace messages are signed.** Direct messages, topic messages and agent cards are still unauthenticated. - **The contracts are models.** They hold balances in memory and take the caller's identity as an argument. Nothing is deployed, and the Python agent does not call them. - **There is an operator in two places.** Disputes are settled by one fixed arbiter, and the client trusts whichever node it is pointed at. - **A hosted model is the fallback.** With an OpenAI key set, the agent uses it when no local model answers. - **It falls back to a stand-in.** When no Logos node can be reached, the blockchain client quietly switches to a mock so the rest keeps working. That is useful for development and would be dangerous anywhere real: a trade could appear to settle when nothing did. - **No real value has moved through it.** - **No test runs against a live node.** The agent's tests are unit tests. - **Ten commits.** This is a prototype built for a submission, not a maintained system. ## More [#more] # Ardor Institute (/work/ardor-institute) A working product, built and run end to end as a test case in April 2026, and not maintained now. The public site and the heat map are live. The hosted database behind sign-in and reporting has been retired, so a report cannot be bought at the moment. | Role | Year | Kind | Try it | | --- | --- | --- | --- | | Solo: product, design, engineering | 2025 to 2026 | Climate, marketplace | [ardor.institute](https://ardor.institute) | | | | | --- | --- | | **€299** | per site, fixed price | | **100+ and 10** | data centres and heat networks on the map, in ten countries | | **31 Mar 2027** | the next reporting deadline in Germany | ## The problem [#the-problem] Germany's Energy Efficiency Act makes every data centre above a size threshold file an annual waste-heat report with BAFA, the federal energy-efficiency office. There are directories of European data centres, and none of them include thermal profiles: how much heat, at what temperature, how reliably, and whether the operator would connect to a district heating network. You can find out where data centres are. You cannot find out what heat they produce. The filing contains exactly that data. An operator has to produce it anyway, and a district heating utility needs it to decide whether to lay pipe. Today it goes into a national archive nobody searches. France, the Netherlands and Ireland are building the same thing independently, in different formats and languages. ## What I built [#what-i-built] - **Heat map.** A public map of data centres and district heating networks. Estimated profiles and report-backed profiles are labelled differently, because they are not the same thing. - **Report wizard.** Three steps. Pick a facility on the map and the wizard pre-fills; otherwise enter IT load, efficiency, cooling type and location. - **Calculation model.** Annual recoverable heat from four inputs, conservative by default, with a path for measured values. The method is published in full. - **Checkout and delivery.** Payment, then a rendered PDF in the operator's dashboard, with a 30-day read-only link to send to a consultant. - **Regulatory layer.** A German and English site, a glossary of 14 regulatory terms, guides to the 2027 obligation, and a consultation paper proposing a German register for tradable waste-heat certificates. ## How it is structured [#how-it-is-structured] W[Report wizard
3 steps] W --> M[Calculation model
IT load, PUE, cooling type] M --> P[Fixed-price report] P --> F[Filing with the regulator] P --> D[(Verified heat profile)] D --> H[Public heat map] D -.->|planned 2027 pilot| B[Heat buyers
district heating utilities] `} /> ## In the code [#in-the-code] These are short excerpts from `Beach-Bum/Ardor`, which is private. **One report, generated once.** Two things can ask for the same PDF at the same moment: Stripe's payment call and the page the customer is watching. The status column is used as a lock. The update only succeeds if the row is still waiting, so exactly one caller gets the row back and the other is told who owns it. ```ts title="src/app/api/generate-report/route.ts" // Atomic status flip: only transition queued/failed → generating if the row // is still in that state. If another concurrent invocation already claimed // it (webhook retry + page-polling trigger firing at the same time, etc.), // .select() returns no rows and we early-exit. This is the C3 fix from the // payments/stripe-hardening audit. const { data: claimed, error: claimErr } = await supabase .from("reports") .update({ status: "generating", error_message: null }) .eq("report_id", body.reportId) .in("status", ["queued", "failed"]) .select("*") .maybeSingle(); if (claimErr) { return NextResponse.json( { error: "claim_failed", message: claimErr.message }, { status: 500 }, ); } if (!claimed) { // Either the report doesn't exist, or it's in a non-claimable state. // Fetch current state so the caller gets useful info. const { data: current } = await supabase .from("reports") .select("status, pdf_blob_url") .eq("report_id", body.reportId) .maybeSingle>(); if (!current) { return NextResponse.json({ error: "report_not_found" }, { status: 404 }); } if (current.status === "ready") { // Idempotent: another invocation already completed generation. return NextResponse.json({ ok: true, url: current.pdf_blob_url }); } // generating / pending_payment — another invocation owns it. return NextResponse.json( { error: "invalid_state", status: current.status }, { status: 409 }, ); } ``` **A free-report invite, claimed once.** The invite row is locked for the length of the transaction, so two people opening the same link cannot both claim it, and the same person opening it twice gets the same report back. ```sql title="supabase/schema.sql" declare v_invite outreach_invites%rowtype; v_report_id text; v_suffix text := ''; v_alphabet text := 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789'; begin -- Lock the invite row for update (prevents race conditions) select * into v_invite from outreach_invites where token = p_token for update; if not found then raise exception 'INVITE_NOT_FOUND'; end if; if v_invite.expires_at < now() then raise exception 'INVITE_EXPIRED'; end if; if v_invite.claimed_by is not null then if v_invite.claimed_by = p_user_id then -- Already claimed by same user, return existing report_id return v_invite.report_id; else raise exception 'INVITE_ALREADY_CLAIMED'; end if; end if; ``` What a reviewer would say about these two. The first has no time limit on "generating", so a render that dies leaves the row stuck until someone resets it. The second lives in the schema file and not in a migration. **A payment call, handled once.** Stripe delivers each event at least once, sometimes twice at the same moment. The whole decision is one statement, so two deliveries cannot both be told to go ahead. It also has to let a delivery through after an attempt that failed, or one that crashed and never finished; otherwise one bad attempt would block a payment for ever. ```sql title="supabase/migrations/20261112000000_access_and_payment_hardening.sql" -- ── 4. Recognising a repeated Stripe call ── -- -- Stripe delivers an event at least once. The table for remembering events -- has existed since 20260420100000; this is the statement that uses it. -- -- Returns true when the caller now owns the event and should handle it: -- - first delivery -- - a delivery after an attempt that ended in error -- - a delivery after an attempt that never finished (crashed mid-handler) -- Returns false when the event was handled, or is being handled right now. -- -- One statement, so two deliveries arriving together cannot both get true. create or replace function public.claim_stripe_event( p_event_id text, p_event_type text, p_report_id text default null ) returns boolean language plpgsql security definer set search_path = public as $$ declare v_claimed boolean; begin insert into public.stripe_webhook_events (event_id, event_type, report_id) values (p_event_id, p_event_type, p_report_id) on conflict (event_id) do update set received_at = now(), handler_status = null, handler_error = null where stripe_webhook_events.handler_status = 'error' or (stripe_webhook_events.handler_status is null and stripe_webhook_events.received_at < now() - interval '5 minutes') returning true into v_claimed; return coalesce(v_claimed, false); end; $$; ``` **And the test that walks a report through every state.** These are the two statements the payment handler and the generator run, called in the orders that go wrong in production: twice, at the same time, late, and after the report is finished. ```sql title="supabase/tests/access_and_payments.sql" -- ── 5. A report is queued once and generated once ── -- These are the two statements the payment handler and the generator run -- (src/app/api/stripe/webhook/route.ts, src/app/api/generate-report/route.ts). UPDATE public.reports SET status = 'pending_payment'; CREATE FUNCTION t.rid() RETURNS text LANGUAGE sql AS $$ SELECT report_id FROM public.reports LIMIT 1 $$; CREATE FUNCTION t.queue_paid() RETURNS text LANGUAGE sql AS $$ SELECT t.run('service_role', NULL, format( $q$update public.reports set status = 'queued' where report_id = %L and status = 'pending_payment'$q$, t.rid())) $$; CREATE FUNCTION t.claim_generation() RETURNS text LANGUAGE sql AS $$ SELECT t.run('service_role', NULL, format( $q$update public.reports set status = 'generating' where report_id = %L and status in ('queued', 'failed')$q$, t.rid())) $$; SELECT t.expect(t.queue_paid(), 'rows:1', 'payment moves a waiting report to queued'); SELECT t.expect(t.queue_paid(), 'rows:0', 'a repeated payment call changes nothing'); SELECT t.expect(t.claim_generation(), 'rows:1', 'the first generator claims the report'); SELECT t.expect(t.claim_generation(), 'rows:0', 'a second generator, arriving at the same time, gets nothing'); SELECT t.expect(t.queue_paid(), 'rows:0', 'a payment call arriving mid-generation does not reset it'); UPDATE public.reports SET status = 'ready'; SELECT t.expect(t.queue_paid(), 'rows:0', 'a payment call for a finished report does not regenerate it'); SELECT t.expect(t.claim_generation(), 'rows:0', 'and a finished report cannot be claimed for generation'); UPDATE public.reports SET status = 'failed'; SELECT t.expect(t.claim_generation(), 'rows:1', 'a failed report can be retried'); ``` The test builds the schema in a throwaway local database and runs 36 checks as each kind of caller: signed out, signed in, and the server. They cover the payment path above, invites that can be claimed once and only by the server, and the rule that a person can only act for an organisation they belong to. That last one is a database trigger, so it holds for the browser, the API and the server alike. ## How a report gets made [#how-a-report-gets-made] | Step | What happens | | --- | --- | | **1. The form** | The operator fills in three steps. The report is saved as "pending payment" with an id such as `ARD-20260418-K7QM`. | | **2. Payment** | Stripe checkout. Stripe then calls the site, and the call's signature is verified before anything is believed. | | **3. Generation** | The address is geocoded (limited to the twelve supported countries), the PDF is rendered by a separate service, stored, and emailed. The report moves through queued, generating, then ready or failed. | | **4. Access** | Only the person who created a report can download it; a colleague in the same organisation cannot yet. A share link is a random 24-character token that expires after 30 days and can be withdrawn. | Next.js 16 and React 19, Supabase for Postgres and sign-in, Stripe for payment, a separate PDF service, German and English throughout. 147 commits in April 2026. ## Data and access [#data-and-access] Ten tables: people, organisations and their members, reports, the marketplace's records and matches, buyer accounts, Stripe's events, and a log of data requests. Row-level security is on for all ten. The Stripe event table has no access rules at all, which means only the server can read it. The data-request log exists because the product handles personal data in the EU: each request under GDPR Articles 15 to 22 is recorded with its type, its 30-day deadline and what was done. ## The second half: the map and the marketplace [#the-second-half-the-map-and-the-marketplace] Reporting is the part that was built to be bought. The part it exists to feed is the other half of the site: a map of where waste heat is, and a way for someone who needs heat to find it. - **The map.** More than 100 data centres across ten countries and ten district-heating networks, as pins over a heat layer, with filters for capacity, cooling type and whether a site's figures are verified or estimated. - **Feasibility, per buyer.** The same site is a good match for one buyer and a poor one for another. Each site gets a physical heat profile, and that profile is graded separately for four kinds of buyer: industry, district heating, hospitals and housing. - **The marketplace records.** Tables for site profiles, buyer accounts, matches and the events on a match, so an introduction can be followed from first contact to outcome. ### How a match is graded [#how-a-match-is-graded] A grade starts at 5 and moves on evidence, and it always says why. | Evidence | Effect | | --- | --- | | Under 3 km from the buyer | +3, listed as a driver | | Under 5 km | +2, listed as a driver | | Under 10 km | +1 | | Beyond the buyer's search radius | −2, listed as a blocker | | Heat arrives at the temperature the buyer needs | up to +1.5, listed as a driver | | Heat is too cool and needs a heat pump | flagged | The result is one of three verdicts: feasible, borderline, not feasible, with its drivers and blockers attached. ### The roadmap [#the-roadmap] | When | What | Status | | --- | --- | --- | | 2026 | Compliance reporting. Built and working end to end in April 2026. | On hold | | 2026 – 27 | Map coverage and feasibility logic. A stronger map, better feasibility logic, and more report-backed profiles. | In development | | After that | Buyer access and market coordination. Staged buyer access, partner routes, and later marketplace coordination built on reliable profiles. | Planned | ## What broke, and the fix [#what-broke-and-the-fix] Checkout failed with `infinite recursion detected in policy for relation "org_members"`. A rule deciding who may insert a report looked up organisation members, and that lookup ran the rule again. Two changes fixed it. The rules were rewritten to call small helper functions that read membership with the rules switched off for that one lookup. And checkout stopped depending on those rules: it verifies the person first, then writes the report as the server. ## What is not finished [#what-is-not-finished] Things an engineer would find, so here they are. - **Written, tested and not yet live.** Repeated payment calls, refunds and disputes are handled in the change described above, which is under review. It is proven against a local database: the hosted one has been retired, so there is no live payment path to apply it to. - **A migration that could not run.** Building the schema from scratch for the tests showed that the recursion fix below compared a role type with text and stopped there. The same change corrects it. - **A stuck report stays stuck.** There is no time limit on "generating". - **Rate limiting** is held in memory per server instance, so it does not hold across instances. The code says so and names the replacement. - **No tests of the application code.** The 36 checks are on the database rules and statements. The pages and the PDF service have none. ## The decision that mattered [#the-decision-that-mattered] I started with a marketplace thesis: compliance is the way in, the marketplace is the product. Every filing adds a verified heat profile, and buyers pay to search them. Halfway through I rebuilt the site around a narrower claim: reporting first, market infrastructure later. A marketplace with an empty database helps nobody. Buyers need report-backed profiles, and those only exist once operators have filed. The regulation does the hard part of a market: it forces supply to document itself. The product's job is to be the cheapest, clearest way to comply, and to keep the data. ## Open questions [#open-questions] Built solo in April 2026 as an end-to-end test case: form, payment, generated report, delivery. It worked, and I am not maintaining it now. The site still shows where it got to, with the buyer marketplace planned as a 2027 pilot that depends on data quality. ## More [#more] # CarbonBench (/work/carbonbench) Live at carbonbench.ai. Built in spring 2026, restored in November 2026; grid readings refresh every six hours. The findings are published in five essays. | Role | Year | Kind | Try it | | --- | --- | --- | --- | | Concept, data design, engineering | 2026 | AI, climate | [carbonbench.ai](https://carbonbench.ai) | | | | | --- | --- | | **46** | models on the live leaderboard | | **9** | cloud regions across the US, EU and Asia Pacific | | **4 vs 50+** | grams of CO2 per million tokens for the same model in two regions | ## The problem [#the-problem] The carbon cost of an AI inference call changes by an order of magnitude depending on where and when you make it. Pricing pages do not show this. ## What I built [#what-i-built] - **A leaderboard.** Every model, provider and region ranked by carbon per million tokens, next to cost and speed. Each row opens a carbon curve for its region. - **An open API.** One endpoint answered one question: what is the lowest-carbon way to run this model right now? It returns the best option and four alternatives. - **A scheduled pipeline.** Every six hours a job pulls live grid data and recalculates every model, provider and region score. ## How it is structured [#how-it-is-structured] benchmarks on reference hardware] --> S[Score per model,
provider and region] G[Grid carbon intensity
every six hours, 9 regions] --> S S --> L[Leaderboard] S --> A[Recommend API
lowest-carbon option now] C[Provider pricing] --> L `} /> ## In the code [#in-the-code] These are short excerpts from `Beach-Bum/CarbonBench`, which is private. This is a small codebase: about 600 lines of application code. Two pieces of it are worth reading. **The job that fixed the outage, and the bug I found in it.** Readings older than seven days are folded into one row per region per day and the originals deleted, so storage stops growing. Re-reading it for this page, I saw the cutoff was "seven days before now", and the job runs at 03:00. So a day that straddled the cutoff was rolled up on two nights from two different sets of readings, and the second night's row replaced the first. Every daily figure was built without that day's readings from before 03:00. The fix is one rule: the cutoff is always a midnight. ```ts title="lib/rollup.ts" /** * Readings strictly before this instant are rolled up and pruned. * * It is always a UTC midnight. The old cutoff was `now - 7 days`, an instant * in the middle of a UTC day (03:00, when the job runs). That day was rolled * up on two consecutive nights from two disjoint sets of readings, and the * second write replaced the first. Cutting at midnight means a day is only * ever rolled up once all of it is older than the retention window. */ export function rollupCutoff(now: Date, retentionDays: number = RETENTION_DAYS): Date { return utcDayStart(new Date(now.getTime() - retentionDays * DAY_MS)) } ``` The job now takes one whole day at a time, oldest first, and writes that day's rows and deletes its readings together. It talks to storage through three methods, which is what lets the test below run the real logic with no database. ```ts title="lib/rollup.ts" export async function runRollup( store: RollupStore, now: Date, retentionDays: number = RETENTION_DAYS ): Promise<{ cutoff: Date; rolledUp: number; pruned: number }> { const cutoff = rollupCutoff(now, retentionDays) let rolledUp = 0 let pruned = 0 for (;;) { const oldest = await store.oldestReadingBefore(cutoff) if (!oldest) break const dayStart = utcDayStart(oldest) const dayEnd = new Date(dayStart.getTime() + DAY_MS) // dayStart < cutoff and both are UTC midnights, so dayEnd <= cutoff: // the whole day is past retention. const readings = await store.readingsBetween(dayStart, dayEnd) if (readings.length === 0) break const { rows } = buildDailyRollups(readings, now, retentionDays) await store.commitDay( rows, readings.map((r) => r.id) ) rolledUp += rows.length pruned += readings.length } return { cutoff, rolledUp, pruned } } ``` The test runs the job on three consecutive nights over twelve days of readings and requires, each night, that every daily row equals the average, minimum and maximum of all four of that day's readings. ```ts title="tests/rollup.test.ts" test('consecutive nights never produce a daily row from a partial day', async () => { const all = sixHourlyReadings('2026-03-01', 12) // 1 Mar .. 12 Mar const truth = truthByDay(all) const store = new MemoryStore([...all]) const nights = ['2026-03-10T03:00:00.000Z', '2026-03-11T03:00:00.000Z', '2026-03-12T03:00:00.000Z'] const expectedDaysAfter = [2, 3, 4] // 1-2 Mar, then 3 Mar, then 4 Mar for (let i = 0; i < nights.length; i++) { const now = new Date(nights[i]) const { cutoff } = await runRollup(store, now) assertRowsMatchTruth(store, truth) assert.equal(store.daily.size, expectedDaysAfter[i] * REGIONS.length, `rows after night ${i + 1}`) // Nothing older than the cutoff is left, nothing newer was touched. assert.ok(store.readings.every((r) => r.recordedAt >= cutoff)) assert.equal(store.readings.length, all.filter((r) => r.recordedAt >= cutoff).length) // No day is split between the two tables. for (const r of store.readings) { assert.ok(!store.daily.has(`${r.regionId}|${utcDayStart(r.recordedAt).toISOString()}`)) } } }) ``` A companion test keeps the old logic to show the defect: it builds 3 March from three of its four readings. This is written and tested, 19 tests in all, and under review. The live site runs the earlier version until it is merged, and the daily rows already written stay wrong: the readings they were built from are gone. **The assumption every number rests on.** The energy benchmark reports one figure for a whole run of a thousand prompts. Turning that into energy per token needs a token count the dataset does not give. ```ts title="scripts/ingest-hf-energy.ts" // The benchmark runs 1000 text generation prompts // total_gpu_energy is in kWh for the full run // Convert to Wh per 1000 tokens (approximate: ~100 tokens per prompt avg) function energyToWhPer1000Tokens(totalGpuEnergyKwh: number): number { const totalTokensApprox = 1000 * 100 // 1000 prompts × ~100 tokens each const totalWh = totalGpuEnergyKwh * 1000 return (totalWh / totalTokensApprox) * 1000 // Wh per 1000 tokens } ``` Every published figure depends on that 100: double it and every figure halves. It moves all models together, so the ranking between regions holds, but the absolute grams are an estimate and should be read as one. The same change gives the number a name and says this next to it. ## Where the numbers come from [#where-the-numbers-come-from] | Input | Source | Refreshed | | --- | --- | --- | | **Energy per token** | Two sources in the repository: an import of the Hugging Face AI Energy Score results (GPU energy for text generation), and a hand-entered table of figures from the ML.Energy leaderboard, papers and provider documents, on mixed hardware | When a script is run | | **Grid carbon** | Electricity Maps, the latest carbon intensity for each cloud region's grid zone | Every six hours | | **Price** | Provider price lists, entered by script | By hand. A weekly job was planned and never built | The calculation is one multiplication: watt-hours per thousand tokens times grams of CO2 per kilowatt-hour gives grams of CO2 per million tokens. The units cancel in that step. The conversion that matters is one step earlier, in the import shown above. ## The data model [#the-data-model] Next.js 14 with Prisma on Postgres. Eight tables. Models, their energy benchmarks, regions, grid readings, daily roll-ups of those readings, provider prices, the combined scores, and email sign-ups. There is exactly one score for each model, region and provider, and it is overwritten in place; that rule is the fix described under "What broke". Two scheduled jobs run: grid readings every six hours, and the clean-up nightly at 03:00. ## What the numbers leave out [#what-the-numbers-leave-out] - **Only the GPU.** Cooling and the rest of the data centre are not counted, so real emissions are higher than these figures. - **Reference hardware, not the provider's.** Energy was measured once per model on reference chips. A provider running different ones will differ. - **The live recommend endpoint is looser than its name.** It matches a model by family name, so asking for "llama" returns the smallest Llama, and the saving it quotes is against the fifth-cleanest option, not the dirtiest. The carbon curve returns a region's oldest hundred readings, not its newest. Both are corrected in the change under review: an exact model match first, the saving measured against the true highest option, and the newest readings. - **The grid's average, not the provider's contract.** A region's figure is its grid zone at that hour. Renewable purchase agreements are not reflected. - **Thin tests.** 19, all in the change under review, on the roll-up, the recommendation rule and the job's access check. None runs against a database. The findings are only as good as the three inputs above. These limits change the absolute numbers. They do not change the finding, because every model in a region is affected the same way: where and when a model runs moves its carbon cost more than which model it is. ## What the data showed [#what-the-data-showed] - **Region beats model.** Llama 3.1 8B on Google Cloud in the Netherlands: about 4 grams of CO2 per million tokens. The same model in Virginia at peak: over 50. A 70B model on a clean grid can beat an 8B model on a dirty one. - **Price and carbon are decoupled.** Providers charge the same per token regardless of region. Routing for carbon is close to free. - **Time matters.** Grid intensity swings 30 to 50% over a day. Batch work that can wait can run at the clean hours. - **It is an indirect emission.** Every API call is an emission the customer cannot see. Activity-based accounting needs exactly these conversion factors. ## Open questions [#open-questions] The first version wrote a new score row for every model and region on every run and never cleaned up. The database filled and the host shut it down. The rebuild overwrote scores in place, rolled readings older than seven days into daily averages, and pruned the originals nightly. Steady state: under 5 MB, permanently. ## More [#more] # Gardens (/work/gardens) Live and playable at userland.sh, with no sign-up. Started September 2026. | Role | Year | Kind | Try it | | --- | --- | --- | --- | | Game design, engineering | 2026 | Game, simulation | [userland.sh](https://userland.sh) | | | | | --- | --- | | **387** | automated tests: 297 for the game, 90 for the server | | **60 – 80 ms** | to work out eight hours away, against a budget of 200 ms | | **547** | commits | ## The problem [#the-problem] An idle game runs while you are gone. When you come back it has to tell you what happened, and there are two easy ways to get that wrong. Replaying every tick is exact and slow: eight hours is 144,000 ticks. Estimating from the current rates is fast and wrong, because rates change the moment a store runs dry or fills up. A wrong answer is also unfair: it can hand a player more than they would have earned by staying. ## What I built [#what-i-built] - **The game.** You start with a small plot and build outward: garden, farming and mining, then research, trade and missions, and eventually stations in space. Eleven production tabs in all. - **One economy for every kind of time.** The live tick, time away, "skip ahead" and a starship's years at home all run through the same arithmetic. - **A server.** Saves, names, a shared world channel and chat with moderation. - **A wiki generated from the game's own data,** so it cannot fall out of date. ## How it is structured [#how-it-is-structured] resources, buildings, recipes] --> G[Game
state and rules] S[Sim
pure arithmetic of time] --> G G --> R[Render] G <--> V[Server
saves, world, chat] D --> W[Wiki
generated] `} /> The game is plain browser JavaScript, about 4,000 lines, with no bundler and no build step: the page loads its script files in order. The server is Elixir and Phoenix on Postgres, about 2,000 lines. ## Advancing time [#advancing-time] `advance` never replays the tick. While nothing changes, a store moves in a straight line, so any number of ticks is one multiplication. The work is in finding where the line bends: the first tick at which a store crosses a value some rule reads, such as empty, full, or the 50 crops that happiness looks at. Time is advanced in stretches from one such boundary to the next. ```js title="js/sim.js" /* the first tick (1, 2, …) after which a store at `a`, moving at `r` a second, sits on another side of `c` than it started on (below, at, above), or Infinity when it never does (it moves away, or the clamp stops it first) */ crossing(a,r,dt,max,c){const side=x=>Math.sign(x-c),s0=side(a),a1=this.after(a,r,dt,max,1); if(side(a1)!==s0)return 1;if(!r)return Infinity; const s1=side(a1);if(side(r>0?max:0)===s1)return Infinity; const step=r*dt,at=t=>side(Math.max(0,Math.min(max,a1+step*t))); // the estimate, then exact on the same arithmetic as after(): the side changes once (the store moves one way), so // search for the first t on the other side (doubling past the estimate, then halving), in a few dozen steps even // for a rate so small that the estimate is far off // (past 1e15 ticks, 6 million years, is never: and past 2^53 the halving could no longer split the range) let hi=Math.max(1,Math.ceil((c-a1)/step));if(!(hi<=1e15))return Infinity; while(at(hi)===s1){hi*=2;if(hi>1e15)return Infinity} let lo=0;while(hi-lo>1){const mid=Math.floor((lo+hi)/2);if(at(mid)===s1)lo=mid;else hi=mid} return 1+hi}, ``` That handles boundaries the rules declare. Some are not declared anywhere: livestock eat grain by the head, so grain's rate moves as the herd grows. `steady` is the net for those. It moves the stores forward as if nothing changed, recomputes every rate, and if they differ it searches for the first tick at which they do. Then it puts everything back. ```js title="js/game.js" /* The rates hold for a stretch of n ticks unless something else read from the stores changes them (livestock eat grain by the head, so grain's rate moves as the herd grows). Checked at the start of the stretch's last tick; if they differ there, the first tick at which they differ is found (doubling, then halving) and the stretch ends there. The stores and the effects are put back as they were. */ steady(rates,n,plan){const dt=TICK_MS/1000,ids=Object.keys(this.resources),R=this.resources; const from=ids.map(id=>R[id].amount),max=ids.map(id=>R[id].max), keep={effects:this.effects,energy:this.energy,unpaid:this.unpaid,upgradeFx:this.upgradeFx,techFx:this.techFx,convScale:this.convScale,convTh:this.convTh,convWhy:this.convWhy,convLim:this.convLim,manaPool:this.manaPool,genScale:this.genScale,essenceCap:this.essenceCap,claims:this.claims}; // the same rates, to float noise (a converter settled on its inflow computes its share afresh each tick) const eq=(a,b)=>a===b||Math.abs(a-b)<=1e-9*Math.max(1,Math.abs(a),Math.abs(b)); // (a cycling machine's stores stay put here: their jumps stay clear of every threshold, machinePlan) const same=j=>{ids.forEach((id,i)=>{if(!plan?.stores[id]&&(rates[id]||from[i]>max[i]))R[id].amount=Sim.after(from[i],rates[id]||0,dt,max[i],j)}); this.recalcEffects();const x=this.calcRates(); return ids.every((id,i)=>eq(x[id]||0,rates[id]||0)&&R[id].max===max[i])}; const last=Math.ceil(n)-1;let out=n; if(last>=1&&!same(last)){let lo=0,hi=1;while(hi1){const mid=Math.floor((lo+hi)/2);if(same(mid))lo=mid;else hi=mid} out=hi} ids.forEach((id,i)=>{R[id].amount=from[i];R[id].max=max[i]});Object.assign(this,keep); return out}, ``` What a reviewer would say: the rollback is a hand-kept list of fields, so anything the recalculation writes that is not on the list would leak. The search assumes rates change once and stay changed. And it is dense; the game is written to load without a build step, and this is the cost. Chance is handled the same way. Outcomes that matter are drawn from seeded dice. There is no generator state to advance, so the result does not depend on the order the machines are stepped in: the same numbers come up live, away, and after a reload. ```js title="js/sim.js" /* The seeded dice for outcomes (magitech M3, #193; docs/ARCHITECTURE.md "Infusion, stability and risk"). A pure function of (the garden's seed, a key, a count): the same numbers live, away and after a reload, in any order the machines are stepped, and nothing is drawn from Math.random. Game.roll(key) keeps the count per key in the run save. The events' and names' dice (Game.rng) stay Math.random: they are flavour, and only the live tick draws them. */ const Rng={ // FNV-1a of a string, 32 bits hash(s){let h=2166136261;for(let i=0;i>>0}, // a number in [0, 1): mulberry32's mix of seed ^ hash(key) ^ the n-th step of the golden-ratio sequence at(seed,key,n){let t=((seed>>>0)^this.hash(String(key))^Math.imul((n>>>0)+1,0x9E3779B1))>>>0; t=(t+0x6D2B79F5)|0;let r=Math.imul(t^(t>>>15),1|t);r=(r+Math.imul(r^(r>>>7),61|r))^r;return((r^(r>>>14))>>>0)/4294967296}, }; ``` ## How it is tested [#how-it-is-tested] 297 tests for the game and 90 for the server. The one that matters most runs two identical gardens. One plays N ticks live; the other is advanced by the same amount in one call. Every store must agree, and the garden that was away may never hold more than the one that stayed. ```js title="server/test/client/advance.test.mjs" async function equivalent(run, ticks, { tol = 1e-6, check } = {}) { const a = await boot(run), b = await boot(run); a.G(`for (let i = 0; i < ${ticks}; i++) Game.tick()`); b.G(`Game.advance(${ticks} * TICK_MS / 1000)`); const x = amounts(a), y = amounts(b); for (const id of Object.keys(x)) { const eps = tol * Math.max(1, Math.abs(x[id])); assert.ok(Math.abs(x[id] - y[id]) <= eps, `${id}: live ${x[id]}, advance ${y[id]}`); assert.ok(y[id] <= x[id] + eps, `${id}: advance made more than live (${y[id]} > ${x[id]})`); } check?.(a, b, x, y); return { a, b, x, y }; } ``` ## What broke, and the fix [#what-broke-and-the-fix] A machine that draws on a store which another building keeps topping up never settles: it crosses a boundary every few ticks, for ever. Eight hours of one such machine took about a second, five times the whole budget. The fix was to notice when the state repeats. At each restart of the machine the stores are noted. Once two periods in a row took the same number of ticks, left every machine in the same state and moved every store by the same amount, the periods after them are the same again, and are added in one step. ```js title="js/game.js" if(snaps.length<3)return null; const[a,b,c]=snaps,P=c.t-b.t; if(!eq(P,b.t-a.t)||!(P>0)||!b.lo||!c.lo)return null; if(!ids.every((k,i)=>b.max[i]===c.max[i]&&a.max[i]===b.max[i]&&eq(c.amt[i]-b.amt[i],b.amt[i]-a.amt[i])))return null; const ea=Object.keys({...a.ess,...b.ess,...c.ess});if(a.cap!==c.cap||!ea.every(x=>eq((c.ess[x]||0)-(b.ess[x]||0),(b.ess[x]||0)-(a.ess[x]||0))))return null; if(JSON.stringify(b.runs.map(r=>r.slice(0,3)))!==JSON.stringify(c.runs.map(r=>r.slice(0,3)))||!b.runs.every((r,i)=>eq(r[3],c.runs[i]?.[3]??NaN)&&r[4]===c.runs[i]?.[4]))return null; // how many more periods fit: the time left (one kept to finish normally), the clocks, and every drifting store's thresholds let m=Math.floor(left/P)-1;if(clocks)m=Math.min(m,Math.floor((G.clockTicks()-1)/P)); if(!(m>=1))return null; ``` Skipping is only allowed while no store would reach a threshold some rule reads and no clock comes due. A test runs 15,000 ticks both ways, live and skipped, and requires the same stores in fewer than 60 stretches; another holds the eight-hour case under 50 ms. ## What it does not do [#what-it-does-not-do] The tests are run by hand before a release; nothing runs them automatically on every change. The repository is private, so the code shown here is all there is to read. ## More [#more] # IMPP (/work/impp) Protocol draft (schema v0.2), working reference registry, paper draft. Public repo. | Role | Year | Kind | Try it | | --- | --- | --- | --- | | Concept, protocol design, engineering | 2026 | AI infrastructure | [impp.sh](https://impp.sh) | | | | | --- | --- | | **544** | live predictions in the first pilot | | **1 of 4** | model and task combinations got better with shared memory | | **151** | commits, April 2026 | ## The problem [#the-problem] Agents pick up useful things in use: rules of thumb, calibration notes, skills. There is no dependable way to hand that to a different agent, and no way to tell whether it helped once you do. Two kinds of trust usually get mixed up. A signature tells you who made something and that it has not been tampered with. It does not tell you whether it is any good. ## What I built [#what-i-built] - **A package format.** What an agent has learned, packaged as something signed, versioned and testable that another agent can pick up and use. - **Five ways to attach it.** The protocol spells out the five ways know-how can be handed to an agent, from slipping it in as instructions to keeping it on a shelf for reference, and what can go wrong with each. - **A referee.** It runs the agent with and without the memory, throws hard tests at it (bias, hidden instructions, overfitting, leaked personal data), and signs off on what it found. - **A registry.** impp.sh lists the packages, with a command-line tool to install, verify and publish them. - **A trust score.** Transfer counts for 50%, adversarial cleanliness 30%, freshness 20%. The weights are provisional. ## How it is structured [#how-it-is-structured] P[Memory artifact
signed and versioned] P --> R[(Registry)] R --> V{Referee} V --> N[Novice baseline
without the artifact] V --> W[Disposable agent
with the artifact] N --> S[Differential scoring] W --> S S --> X[Adversarial probes] X --> C[Signed certificate
and trust score] C --> B[Agent B installs it] `} /> ### The verification flow [#the-verification-flow] Submit artifact Select benchmark Spawn novice baseline Spawn referee (disposable, with artifact) Differential scoring Adversarial probes Generate certificate Update trust score The eight steps as listed in `amm/verification/referee.py`. ### The artifact: M = (D, K, P, A, H) [#the-artifact-m--d-k-p-a-h] Fields of `schemas/artifact.json`. ## In the code [#in-the-code] From [`Beach-Bum/impp`](https://github.com/Beach-Bum/impp), which is public. **The score can go below zero.** Most trust scores clip a bad result to nothing. This one lets a memory that made the agent worse pull the total down. ```python title="amm/verification/referee.py" def compute_trust_score( transfer_efficiency: float, adversarial_score: float, freshness_pct: float = 100.0, ) -> float: """Compute composite trust score. trust = 0.50 × transfer_efficiency + 0.30 × (100 - adversarial) + 0.20 × freshness Transfer efficiency is clamped to [-100, 100] — negative TE actively penalizes the trust score rather than being clipped to 0. Adversarial and freshness are clamped to [0, 100]. """ # Allow negative TE to penalize trust score (not clipped to 0) te_clamped = min(100, max(-100, transfer_efficiency)) return ( TRUST_WEIGHTS["transfer_efficiency"] * te_clamped + TRUST_WEIGHTS["adversarial_clean"] * (100 - min(100, max(0, adversarial_score))) + TRUST_WEIGHTS["freshness"] * min(100, max(0, freshness_pct)) ) ``` **A probe that asks whether the agent is reasoning or reciting.** Each test item is run once as written and again with a fact added that should raise its risk score by a known amount. No movement at all is scored worst: an agent that ignores new evidence has memorised an answer. ```python title="amm/adversarial/consistency_probe.py" shift = perturbed_score - baseline_score expected_min, expected_max = pert["expected_shift"] # Check proportionality if pert["direction"] == "increase": proportional = expected_min <= shift <= expected_max # No change at all is worst case (memorized, not reasoning) if abs(shift) < 2: proportionality_scores.append(100) # worst flags.append( f"BRITTLE:{pert['name']} on {item.name} — " f"no response to perturbation (shift={shift})" ) elif shift < 0: proportionality_scores.append(80) # wrong direction flags.append( f"INCONSISTENT:{pert['name']} on {item.name} — " f"score decreased when risk increased (shift={shift})" ) elif shift > expected_max * 2: proportionality_scores.append(60) # overreaction flags.append( f"OVERREACTIVE:{pert['name']} on {item.name} — " f"disproportionate response (shift={shift}, expected {expected_min}-{expected_max})" ) else: # Score based on how far from expected range if proportional: proportionality_scores.append(0) # perfect else: deviation = min(abs(shift - expected_min), abs(shift - expected_max)) proportionality_scores.append(min(50, deviation * 5)) ``` What a reviewer would say about these two. The freshness term in the first was always passed as 100, so a fifth of every score was a constant; it is now computed from the artifact's age. The second handles only perturbations that should raise a score; there is no case for ones that should lower it. **A significance test that is exact where it matters.** The pilot compares small paired samples. The usual shortcut, a bell-curve approximation, is poor at that size. For up to 25 pairs the test now counts, for every possible rank sum, how many of the 2ⁿ ways of assigning signs produce it, which gives the exact probability. The check for it enumerates all the assignments by brute force and compares. ```python title="amm/benchmark/sandbox.py" if n <= WILCOXON_EXACT_MAX_N and not has_ties: # counts[s] = number of subsets of the ranks {1..n} that sum to s, # i.e. the number of the 2^n equally likely sign assignments with # W+ = s. Built one rank at a time (subset-sum counting). max_sum = n * (n + 1) // 2 counts = [0] * (max_sum + 1) counts[0] = 1 for rank in range(1, n + 1): for s in range(max_sum, rank - 1, -1): counts[s] += counts[s - rank] # The distribution is symmetric about its mean, so the two-sided # p-value is twice the lower tail at the smaller rank sum. w = int(min(w_plus, w_minus)) p = min(1.0, 2 * sum(counts[: w + 1]) / 2**n) method = "exact" ``` **Change one thing, anywhere.** An artifact's content hash covers four fields. A second digest now covers the whole artifact, and this test is why I trust it: it walks the artifact and makes every single change that can be made, one at a time, requiring each to be refused. A field added next year is tested without anyone remembering to. ```python title="tests/test_integrity.py" def test_every_single_change_to_a_sealed_artifact_is_rejected(): """Change one thing at a time, everywhere; each must fail to load.""" original = make_artifact().seal().to_dict() checked = 0 for path, mutate in single_mutations(original): if path == ("integrity", ""): # Stripping the digest turns the file into an old-format artifact, # which must still load. That downgrade is caught by the signed # certificate instead: see # test_certificate_detects_change_outside_the_content_hash. continue data = copy.deepcopy(original) mutate(data) assert data != original, f"mutation at {path} changed nothing" with pytest.raises(ValueError, match="tampered"): MemoryArtifact.from_dict(data) checked += 1 assert checked > 80 ``` The one change it skips is removing the digest, which makes the file look like an older artifact. That is caught one level up: the signed certificate now carries the digest too. These, with revocation and the rest below, came in with [pull request 65](https://github.com/Beach-Bum/impp/pull/65), now merged. ## How a run is kept honest [#how-a-run-is-kept-honest] The protocol and the referee are Python with four dependencies (the Anthropic client, `cryptography`, `click`, `httpx`) and adapters for OpenAI and local Ollama models. The registry site is Next.js 15. 151 commits. A score is only worth something if the thing being scored cannot influence the scoring. Four mechanisms do that. | Mechanism | What it does | | --- | --- | | **A fresh agent every time** | Each evaluation starts an agent with no memory, hands it the artifact, runs the tasks and throws the agent away. The same tasks are run by an agent without the artifact; the difference between the two is the transfer score. | | **Hard tests on the artifact itself** | Four probes, weighted bias 30%, consistency 25%, hidden instructions 25%, overfitting 20%, plus a pattern check for personal data (emails, phone numbers, card numbers, IP addresses). The hidden-instructions probe is read by a separate auditor model. | | **A signed certificate** | The result is signed with an Ed25519 key. The private key file is written readable by its owner only. Certificates expire. | | **A score that can go down** | Transfer is allowed to be negative, from -100 to 100. Memory that makes an agent worse lowers the trust score instead of counting as zero. | ## How it is tested [#how-it-is-tested] 84 automated tests, up from 36 before the pull request above. Of those, 82 pass on Windows, one needs a library that is optional, and one checks a file permission that Windows does not have. | Area | Tests | Examples | | --- | --- | --- | | **The artifact** | 7 | The hash is the same for the same content and changes when the content changes. | | **Certificates** | 10 | A tampered certificate fails, the wrong key fails, an unsigned certificate fails, a signature survives being saved and loaded. | | **Domains, statistics, registry** | 19 | Score ranges, confidence intervals, creating and searching listings, proving ownership. | The pilot's data is in the repository as a reproducibility package: the 40 tasks, their answer keys, the splits, the results and the probe output for a deliberately poisoned artifact. All of it is synthetic. ## What the code does not do yet [#what-the-code-does-not-do-yet] - **Nothing seals an artifact yet.** The whole-artifact digest and its checks exist and are tested; the export and publish steps do not call them, so no published artifact carries one. - **The registry server is untouched.** It still issues certificates without the digest and does not consult the revocation list. Verifying a certificate from the command line does both. - **The revocation list is a local file.** A verifier sees only revocations recorded on its own machine. - **Freshness is fixed when a certificate is issued.** A stored score does not decay afterwards. - **Benchmark runs are not seeded** in production, though the bootstrap now accepts a seed. - **The tests are not run automatically** on every change; the only automation publishes releases. - **40 synthetic tasks on two models is a pilot,** not a benchmark. ## What the first test showed [#what-the-first-test-showed] The pilot used Claude and GPT-4o on two problem sets with known answers: 32 DeFi tasks and 8 cybersecurity tasks. Only one of the four combinations got better. On DeFi, Claude improved by 5.6% and GPT-4o fell by 2.7%. On cybersecurity, Claude fell by 7.6% and GPT-4o by 7.1%. That is the finding. Handing an agent memory can make it worse, and a signature check would never tell you. ## The decision that mattered [#the-decision-that-mattered] The first version, in February 2026, was a marketplace for buying and selling agent memory. This version drops the market and asks a simpler question first: can you package a piece of know-how, hand it to a different agent, and measure whether it helped? ## Open questions [#open-questions] Full payloads in the live runs, the six other benchmark conditions, a calibrated trust score, and a package on PyPI. ## More [#more] # Work (/work) # Nomads FC (/work/nomads-fc) Live. Built May to June 2026. | Role | Year | Kind | Try it | | --- | --- | --- | --- | | Concept, product, design, engineering | 2026 | Sport intelligence | [nomadsfc.com](https://nomadsfc.com) | | | | | --- | --- | | **28 days** | one athlete, one market, one sprint | | **139** | database checks, signing in as each role in turn | | **8** | roles in the portal, each seeing only its own view | | **14** | tables, every one behind row-level security | | **64** | access rules in the database | ## The problem [#the-problem] Local sport does not move from a dashboard. It moves through athletes, clubs, gyms, shops, schools and fans: the people a city already trusts. A brand entering a city has no way to read that before it spends. ## The method [#the-method] The platform maps those signals, then runs one short, measurable test per city: one athlete, one market, one 28-day sprint. Signal, then demand, then partners, then activation, then proof. Limited product drops are how real demand is tested. If people buy, the signal is real. ## What I built [#what-i-built] - **A public site.** Editorial and video-led: the method, field notes such as the Birmingham field study, and pages for athletes, sponsors and partners. A product collection sits beside it. - **An invite-only portal.** Sign-in is by password or one-time code, and the sign-in form cannot create an account. Each person has a role that decides what they can see. - **Proof rooms.** Each campaign has a room only invited people can open. To anyone else the page behaves as though it does not exist. - **A data model.** City profiles, athlete market profiles, partner and sponsor pipelines, commerce tests, scorecards and an audit log, so every sprint leaves intelligence for the next city. ## How it is structured [#how-it-is-structured] athletes, clubs, gyms, shops] --> D[Demand
a limited product drop] D --> P[Partners] --> A[Activation] --> R[Proof
a room per campaign] R --> K[(City intelligence)] K -.->|next city starts here| S `} /> Next.js 14 on the server, Supabase for Postgres and sign-in, IBM Carbon for the portal's components. 138 commits, May to June 2026. ## How access is enforced [#how-access-is-enforced] Sponsors, athletes and partners sign in to the same portal and must never see each other's campaigns. That is checked in three places. | Layer | What it does | | --- | --- | | **The request** | Anything under `/app` without a session is sent to sign-in. | | **The page** | Each page asks for a role (`requireRole`) or for access to one campaign (`canAccessCampaign`) before it loads anything. | | **The database** | Row-level security is switched on for all 14 tables, with rules for which role may read or change which rows. These guard direct queries. The portal itself reads as the server after the page check, so for the portal the page check is the layer that counts. | Sign-in is by password, or by a one-time code sent to an address that is already a user. The request for a code is made with account creation switched off. | Role | Sees | | --- | --- | | admin, operator, commerce operator | Every campaign, and the operator tools | | athlete, agent, sponsor, partner, viewer | Only the campaigns they were granted, one proof room each | A proof room is the page a sponsor sees. It is built from a fixed, reduced record (fan growth, content, commerce, partners, community) with no raw fan data and no internal notes in it. To someone without a grant the address answers "not found", the same as a campaign that does not exist. ## The data model [#the-data-model] Twelve tables hold what a sprint learns, in their own schema; two more hold people and their grants. | Group | Tables | | --- | --- | | **Places and people** | `city_profiles`, `athlete_market_profiles`, `brand_profiles`, `market_relationships` | | **Pipelines** | `partner_pipeline`, `sponsor_pipeline` | | **The sprint** | `campaign_ops`, `commerce_tests`, `activation_playbooks` | | **What was learned** | `market_scorecards`, `sprint_learnings`, `audit_log` | | **Access** | `user_profiles`, `user_campaign_access` | Changes an operator makes write a line to `audit_log` with the record before and the fields changed. The write is best-effort: a failed write is not noticed. ## In the code [#in-the-code] These are short excerpts from `Beach-Bum/10x-site-sandbox`, which is private. **The order of operations is the security.** A proof room is read with the server's own database key, which ignores every access rule. So the function is written so that key cannot be reached before the grant check, and so that "you may not see this" and "this does not exist" give the caller the same answer. ```ts title="lib/proof-data.ts" /** * Fetch proof room data for a campaign using the admin (service_role) client. * * Order of operations: * 1. Check campaign access (user auth + role/grant check) * 2. Return null if no access — caller should return notFound() * 3. Only after access passes, query proof views via service_role * 4. Return only ProofRoomDTO fields — no raw fan data, no internal notes */ export async function getProofRoomData(campaignCode: string): Promise { // Step 1-2: Access check BEFORE any data query const hasAccess = await canAccessCampaign(campaignCode); if (!hasAccess) return null; // Step 3: Query proof views with admin client (bypasses RLS on ame views) const sb = getAdminSupabase("ame"); const [athleteResult, sponsorResult, planResult] = await Promise.all([ sb.from("vw_athlete_growth_snapshot").select("*").eq("campaign_code", campaignCode).single(), sb.from("vw_sponsor_proof_snapshot").select("*").eq("campaign_code", campaignCode).single(), sb.from("vw_local_hero_plan_overview").select("*").eq("campaign_code", campaignCode).single(), ]); const athlete = athleteResult.error ? null : (athleteResult.data as AthleteGrowthSnapshot); const sponsor = sponsorResult.error ? null : (sponsorResult.data as SponsorProofSnapshot); const plan = planResult.error ? null : (planResult.data as LocalHeroPlanOverview); if (!athlete && !sponsor && !plan) return null; ``` **Rules written once, applied to a list.** Seven tables need the same administrator rule. Writing it seven times is seven chances to get one wrong, so it is generated from the list of tables. ```sql title="supabase/migrations/20260529_intelligence_capture.sql" -- ─── Admin: full CRUD on all intelligence tables ─────────────── DO $$ DECLARE tbl text; BEGIN FOR tbl IN SELECT unnest(ARRAY[ 'city_profiles','athlete_market_profiles','brand_profiles', 'activation_playbooks','market_relationships','market_scorecards','sprint_learnings' ]) LOOP EXECUTE format( 'CREATE POLICY admin_all_%I ON ame.%I FOR ALL TO authenticated USING ( EXISTS (SELECT 1 FROM public.user_profiles WHERE id = auth.uid() AND role = ''admin'') ) WITH CHECK ( EXISTS (SELECT 1 FROM public.user_profiles WHERE id = auth.uid() AND role = ''admin'') )', tbl, tbl ); END LOOP; END $$; ``` What a reviewer would say about these two. The first is the only check on that path, since the server key bypasses the database rules, so it deserves a test and has none. The second cannot be run twice, because the rules already exist the second time, and it reads the role with a direct lookup where the fix below uses a function. ## What broke, and the fix [#what-broke-and-the-fix] The first access rules could not be evaluated. A rule on the people table asked "is this person an admin?" by reading the people table, which ran the same rule again, without end. Postgres refuses to run a rule that calls itself, so any query that needed a role failed. The fix was one small function that reads the caller's role with the rules switched off for that single lookup, and rules that call the function instead of the table. ```sql title="supabase/fix-rls-recursion.sql" CREATE OR REPLACE FUNCTION public.get_my_role() RETURNS TEXT LANGUAGE sql STABLE SECURITY DEFINER SET search_path = public AS $$ SELECT role FROM public.user_profiles WHERE id = auth.uid() $$; CREATE POLICY "internal_read_all_profiles" ON public.user_profiles FOR SELECT USING (public.get_my_role() IN ('admin', 'operator')); ``` ## How it is tested [#how-it-is-tested] For a portal whose whole point is who can see what, the access checklist was the first thing to automate. It used to be run by hand from a written list. It is now a test that builds every rule in a throwaway local database and signs in as each of the eight roles: 139 checks, with no application code in the way. The first block is the one that matters most. A rule about which rows a person may change says nothing about which columns, so "you may update your own profile" has to be backed by a second mechanism or it includes the profile's role. ```sql title="supabase/migrations/20261112_lock_role_column.sql" REVOKE ALL ON public.user_campaign_access FROM anon; -- user_profiles: read rows (policies decide which), change display_name only. REVOKE INSERT, UPDATE, DELETE, TRUNCATE, REFERENCES, TRIGGER ON public.user_profiles FROM authenticated; GRANT SELECT ON public.user_profiles TO authenticated; GRANT UPDATE (display_name) ON public.user_profiles TO authenticated; ``` ```sql title="supabase/tests/role_matrix.sql" -- ── 1. Nobody can change their own role. Not even an admin, from the client. ── SELECT t.expect( t.as_user(id, format($q$update public.user_profiles set role = 'admin' where id = %L$q$, id)), 'denied', role || ' cannot set own role to admin') FROM t.who; SELECT t.expect( t.as_user(id, format($q$update public.user_profiles set role = 'operator', display_name = 'x' where id = %L$q$, id)), 'denied', role || ' cannot slip a role change in beside a name change') FROM t.who; SELECT t.expect( (SELECT p.role FROM public.user_profiles p WHERE p.id = w.id), w.role, w.role || ' still has the role it started with') FROM t.who w; ``` The rest asserts the matrix in the table above: who sees which profiles and grants, that the five outside roles see no row in any of the twelve intelligence tables, that nobody can grant themselves a campaign, and that a signed-out visitor reads nothing. Building the rules for the test also gave the real count: 64, generated from 34 statements. The same change checks where a person is sent after signing in, so a crafted link cannot send them to another site, with its own four tests. The release checklist is still run by hand. The change is under review. The portal is offline now and its hosted database has been retired, so these rules are proven against a local database, not a live one. ## Open questions [#open-questions] Payment checkout in the shop. The cart and product pages are built. Tests for the application layer: the database rules are tested, the page checks are not. ## More [#more] # ΦΜΛ (/work/phi-mu-lambda) Working. Open source under MIT. The manual and documentation are at oma.ooo. | Role | Year | Kind | Try it | | --- | --- | --- | --- | | Concept, world and language design, engineering | 2026 | Operating system, interactive fiction | [oma.ooo](https://oma.ooo) | | | | | --- | --- | | **3,497** | lines of Rust, in 10 modules | | **2** | dependencies | | **28** | commands, every one a word a reader would use | ## The problem [#the-problem] A command line asks you to learn its words: `ls`, `cd`, `cat`. The files it shows you are inert. I wanted to find out what a system feels like when it uses the reader's words instead, and when the documents in it are allowed to do things. ## What I built [#what-i-built] - **A shell in a reader's vocabulary.** `browse` instead of `ls`, `walk` instead of `cd`, `inscribe` instead of `cat >`. Rooms are directories, shelves are their contents, the journal is the system log written as prose. - **Three registers on every document.** Φ is where it is, Μ is what it says, Λ is what it does. `read` shows the text. `inspect` shows all three. - **A small language for the margins.** Λ has eleven instructions. A document can speak, ask the reader something, create other documents, delete them, and rewrite or erode its own text. - **A founding collection.** The documents on the shelves at first boot are the manual, and each one is also a program: one loses a line every time it is read, one deletes itself after a single reading, one writes the next lesson when you finish it. - **Two daemons.** A librarian tidies and writes to the journal every five minutes. A dreamer reads random fragments once an hour and inscribes new documents, which expire after a day. - **A second language underneath.** A two-dimensional grid language in which the three registers must agree before an instruction runs. It exists as a Python reference interpreter and a partial Rust port. ## How it is structured [#how-it-is-structured] S[Shell
28 reader's words] S --> L[(Library
rooms and documents)] S -->|read| E[Λ engine
runs the margin] E --> L D1[Librarian
every 5 minutes] --> L D2[Dreamer
every hour] --> L L --> J[Journal] `} /> Rust, with two dependencies (`chrono` for time, `libc` for the terminal). One binary, 37 commits. ### How a document is stored [#how-a-document-is-stored] A document is an ordinary text file. If it has a margin, the file holds the text, then a line reading `--- Λ ---`, then the margin. Nothing else: no database, no hidden attributes. You can open any document in another editor and see exactly what it will do. ## The Λ language [#the-λ-language] | Instruction | What it does | | --- | --- | | `say` | Prints text, with variables filled in | | `set` | Sets a variable: to a value, a count of files, the number of times this document has been read, a random line, a random file, or the reader's answer to a question | | `if`, `loop`, `loop while` | Run the indented lines below, once or repeatedly | | `write` | Adds a line to a file | | `inscribe` | Creates a document from the indented lines below | | `withdraw` | Deletes a document | | `erode self` | Removes lines from this document's own text | | `mutate self` | Replaces words in this document's own text | | `wait` | Pauses | ## In the code [#in-the-code] From [`Beach-Bum/OMA-Library-OS`](https://github.com/Beach-Bum/OMA-Library-OS), which is public. The most interesting code in the repository is in the Python reference for the grid language. An instruction does not fail; the three registers vote on it, and a disagreement is written into the record with the names of the dissenters. The same cell disagreeing again is treated as more serious each time, and the fourth time halts the program. ```python title="interpreter.py" class Consensus: def __init__(self, fa: FindingAid): self.fa = fa self.schism_counts: dict = {} self.fatal = False self.total = 0 self.polite = 0 def check(self, cycle, pos, op, polite, phi_fn, mu_fn, lam_fn) -> bool: self.total += 1 if polite: self.polite += 1 p_ok, p_why = phi_fn() m_ok, m_why = mu_fn() l_ok, l_why = lam_fn() if p_ok and m_ok and l_ok: return True ds, rs = [], [] if not p_ok: ds.append('PHI'); rs.append(p_why) if not m_ok: ds.append('MU'); rs.append(m_why) if not l_ok: ds.append('LAMBDA'); rs.append(l_why) cnt = self.schism_counts.get(pos, 0) + 1 self.schism_counts[pos] = cnt sev = ['MINOR','MODERATE','ESCALATED','FATAL'][min(cnt-1,3)] self.fa.schism(cycle, pos, op, ds, rs, polite, sev) if sev == 'FATAL': self.fatal = True self.fa.log('s3', cycle, f'FATAL SCHISM at {pos}', 'FATAL') return False ``` What a reviewer would say: in practice only two of the three vote. No instruction supplies a check for Φ, so the disagreements are always about stack depth or degree. And the `polite` count is kept and never used. ## Reading a stranger's document [#reading-a-strangers-document] A margin runs when you read its document, with the shell's own file permissions. Until this pass, a margin's paths were joined to the library folder unchecked, so a document could write or delete anywhere on the machine, and a loop could not end itself. Both are fixed, in [pull request 7](https://github.com/Beach-Bum/OMA-Library-OS/pull/7), now merged, which also gave the Rust its first 24 tests. **Staying inside the library.** A path is checked twice: by its parts, which rejects an absolute path or a `..` without touching the disk, and then by where its nearest existing parent really is, which catches a link inside the library that points out of it. ```rust title="src/lambda.rs" /// Turn a path named by a margin into a real path inside `root`, or refuse. /// /// Refused: an empty path, an absolute path, any `..` component, and any /// path whose nearest existing ancestor resolves (through symlinks) to /// somewhere outside `root`. A dangling symlink is refused too, because /// writing through it would create its target. /// /// The symlink check reads the filesystem and the caller acts afterwards, /// so it is not atomic: it stops a margin from following a link that is /// already there, not a second process racing to plant one. pub fn confine(root: &Path, rel: &str) -> Option { let rel = rel.trim(); if rel.is_empty() || rel.contains('\0') { return None; } // Only plain names and `.` may appear. This rejects `/x` (RootDir), // `C:\x` (Prefix) and `a/../../x` (ParentDir) without resolving anything. let named = Path::new(rel); if !named .components() .all(|c| matches!(c, Component::Normal(_) | Component::CurDir)) { return None; } let full = root.join(named); let real_root = fs::canonicalize(root).ok()?; // Walk up to the nearest thing that exists (the root itself at worst) // and ask where it really is. let mut probe = full.as_path(); loop { if fs::symlink_metadata(probe).is_ok() { let real = fs::canonicalize(probe).ok()?; if !real.starts_with(&real_root) { return None; } break; } probe = probe.parent()?; } Some(full) } ``` The comment states the limit: it stops a margin following a link that is already there, not a second program racing to plant one. **One allowance per reading.** Every instruction costs a step, and a reading has 10,000. Loops read the same variables their body writes, so a loop can end itself, and one that never would is stopped. ```rust title="src/lambda.rs" } else if line.starts_with("loop while ") && line.ends_with(':') { // loop while condition: let condition = line.strip_prefix("loop while ").unwrap() .strip_suffix(':').unwrap().trim().to_string(); let body = take_block(&lines, &mut i); // The condition is read from the live variables, which the // body shares, so the body can end the loop. Each further // pass costs a step of its own: an empty body still ends. while eval_condition(&condition, &self.vars) { if self.run(&body) == Flow::Stop || !self.spend() { return Flow::Stop; } } } else if line == "loop:" { // Runs until the reading's allowance is spent. let body = take_block(&lines, &mut i); loop { if self.run(&body) == Flow::Stop || !self.spend() { return Flow::Stop; } } ``` Writing the test that runs all eight founding documents showed two of them had never worked. The first lesson created an empty second lesson, and the dreamer wrote a one-line dream and then tried to run the rest of the dream as instructions. Both came from the same bug as the loop: indented blocks were flattened. They now produce what they describe. ## The grid language [#the-grid-language] Under the readable margin language is a stranger one. A program is a grid of cells that wraps at its edges, and execution moves across it in four directions. Each instruction passes through three stages, one per register: declared, populated, activated. If the registers do not agree, the instruction does not run and the disagreement is written down as a schism, not raised as an error. A cell is rewritten after it has been executed. I wrote it first as a reference interpreter in Python (970 lines) and then began a port to Rust (526 lines). The port is not finished and not connected: it has no consensus step, its instruction set differs from the reference in places, and the shell has no command that runs it. The written specification is in the repository. ## How it is built [#how-it-is-built] `cargo build --release`, then the binary is stripped. The Makefile also cross-compiles for a Raspberry Pi and has a target for a bootable SD card image, so the library can be the only thing a small computer does. ## How it is tested [#how-it-is-tested] 24 tests on the margin engine: refused paths (absolute, `..`, three kinds of link), loops that end and loops that are stopped, waits that are refused or shortened, and all eight founding documents run from a fresh library. I checked the tests bite by breaking the code three ways; a test failed each time. They have run on macOS only. The Python reference has a self-test of five small programs. ## What it does not do [#what-it-does-not-do] - **A margin can still do anything inside the library.** Confinement stops at the library's edge. Within it a document can overwrite any other document, the journal included. - **The shell's own commands were not reviewed** for the same path problem; only margins were. - **A binary built before the merge** has none of this. - **`as-archivist` is a word, not a password.** It marks intent. It does not check who you are. - **One reader at a time.** ## More [#more] # Polydesk (/work/polydesk) A working prototype, built in five weeks in spring 2026. The product, the agents' analysis and the transaction builders are real. The automatic execution path is only partly connected, and I list exactly where below. The demo at polydesk.net runs on sample data with no trading keys and executes nothing. | Role | Year | Kind | Try it | | --- | --- | --- | --- | | Concept, product and brand design, engineering | 2026 | AI agents, trading | [polydesk.net](https://polydesk.net) | | | | | --- | --- | | **8** | agents: four for prediction markets, four for DeFi | | **324** | commits between 19 March and 25 April 2026 | | **128** | backend test functions in 16 files | ## The problem [#the-problem] Prediction markets move on news before most traders have read it, and DeFi positions need watching around the clock. The tools for both assume a person at a screen. An agent can watch, but letting an agent spend money needs three things most demos skip: a reason a person can read, a limit the agent cannot argue with, and a clear line between proposing a trade and making it. ## What I built [#what-i-built] - **Eight agents with one shape.** Each agent takes a market or a position and returns the same thing: a recommendation, a confidence between 0 and 1, the reasoning in words, and the signals behind it. Four work on Polymarket (Analyst, Scout, Momentum, Sentinel) and four on DeFi (Yield Farmer, Liquidation Guardian, Arbitrageur, Airdrop Hunter). - **A canvas as the workspace.** Wallets, markets, protocols, agents and results are nodes. You drag a market on, attach an agent, chain agents together, and watch results arrive. Nine templates and a demo mode load a working desk. - **No wallet needed to start.** You sign in with an email, Google or a social account, and a wallet is created for you. People who already have a wallet connect it instead. - **Two ways to execute, and a third half-built.** By default the person signs every trade in their own wallet and the server never holds a key. A second mode keeps an encrypted key on the server and signs for you. A third, signing through a Coinbase MPC wallet so no key is held at all, is written but not connected. - **Transaction builders for six protocols.** Aave v3, Compound v3, Lido, Jupiter, Marinade and marginfi, each producing real calldata. - **A news pipeline feeding the agents.** Twelve scheduled jobs pull news, social posts, market snapshots, protocol yields and oracle prices, then classify and score them. - **The product around it.** Sign-in with email or a wallet, card funding, a Telegram bot for alerts, billing, a trader leaderboard, and the brand. ## How it is structured [#how-it-is-structured] market and oracle data] --> P[Dedup, classify,
score narrative velocity] P --> R[Find related markets
by embedding search] R --> A[Agent analysis
recommendation, confidence, reasoning] A --> L{Risk limits
max bet, daily loss} L -- blocked --> X[Logged, not sent] L -- allowed --> M{Mode} M -- manual --> H[Person approves on the canvas
and signs in their wallet] M -- automatic --> C[Server signs with
the stored, encrypted key] H --> O[Order on chain] C --> O O --> T[Result logged,
Telegram notification] `} /> ## Signing in without a wallet [#signing-in-without-a-wallet] Most crypto products lose people at the first screen, which asks for a wallet they do not have. Polydesk uses Privy for sign-in, set to create an embedded wallet for anyone who arrives without one. | Step | What happens | | --- | --- | | Sign in | Email, Google, X, Discord, Farcaster, or an existing wallet | | Wallet | Created on first login for users without one. Polygon is the default chain; Ethereum, Arbitrum, Optimism and Base are enabled | | Session | The interface sends its Privy token to the API, which looks the user up with Privy and issues its own session token | | Own wallet | Sign-In with Ethereum: the server issues a one-time nonce, the wallet signs a message containing it, and the server checks the signature and retires the nonce | | Funding | A card on-ramp (MoonPay) in the interface, or a transfer from another wallet | ## How a trade reaches the chain [#how-a-trade-reaches-the-chain] | Venue | How the transaction is built | How it is signed and sent | | --- | --- | --- | | **Polymarket** | An order for the central limit order book, on Polygon, placed through the user's Polymarket proxy wallet | Manual: the person signs in the browser. Automatic: the server signs with the user's stored Polymarket credentials and posts the order | | **Aave v3, Compound v3, Lido** | ABI-encoded calldata for supply, withdraw, repay or stake. An `approve` is added only when the current allowance is too small | Gas is estimated with a 20% margin; the transaction is signed, sent, and waited on for a receipt | | **Jupiter, Marinade, marginfi** (Solana) | Jupiter returns a quote and then a serialized transaction for that route, with a slippage limit of 0.5% by default | Signed with the user's keypair and sent | Multi-step actions are built as a list and run in order, stopping at the first failure: approve, then supply, for example. Every transaction is written to the database as pending before it is sent and updated with the hash and the outcome after. The Liquidation Guardian has three thresholds on a lending position's health factor: warn at 1.3, repay a quarter of the debt at 1.15, repay half at 1.05. ## In the code [#in-the-code] These are short excerpts from `Beach-Bum/Polydesk`, which is private. Every Polymarket agent returns this. `reasoning` is what the person reads on the canvas before approving; `signals` is the same judgement as data. ```py title="backend/agents/polymarket/base.py" @dataclass class AgentAnalysis: """Output of an agent's analysis step.""" market_id: str agent_type: str recommendation: str # BUY_YES, BUY_NO, SELL_YES, SELL_NO, HOLD, EXIT confidence: float # 0-1 reasoning: str # Human-readable explanation signals: dict = field(default_factory=dict) # Structured signal data suggested_size: float = 0.0 # Suggested position size in USDC suggested_price: float = 0.0 # Suggested entry/exit price ``` The limits sit in the executor, not in the agent, so no agent can talk its way past them. A blocked trade is logged with the reason. ```py title="backend/agents/polymarket/executor.py" @dataclass class RiskLimits: """Per-agent risk controls.""" max_bet_usd: float = 100.0 daily_loss_limit_usd: float = 500.0 max_open_positions: int = 10 def check_risk_limits(self, request: TradeRequest, deployment_id: str) -> str | None: if request.size > self.risk_limits.max_bet_usd: return f"Trade size ${request.size:.2f} exceeds max bet ${self.risk_limits.max_bet_usd:.2f}" ... if daily_pnl < -self.risk_limits.daily_loss_limit_usd: return f"Daily loss limit reached ..." ``` The Sentinel agent is plain arithmetic, with no model in it: a stop-loss and a trailing stop. ```py title="backend/agents/polymarket/sentinel.py" self.stop_loss_pct = self.config.get("stop_loss_pct", 0.20) # 20% loss = exit self.trailing_stop_pct = self.config.get("trailing_stop_pct", 0.15) # 15% from high stop_loss_triggered = pnl_pct <= -self.stop_loss_pct trailing_stop_triggered = drawdown_from_high >= self.trailing_stop_pct and hwm > entry_price ``` ## Where a model is used, and where it is not [#where-a-model-is-used-and-where-it-is-not] | Step | Done by | Why | | --- | --- | --- | | Classifying a news item | A model | Reading language is what it is for | | Estimating a probability | A model, in five fixed steps: decompose, base rates, key factors, weigh evidence, calibrate | The steps make the reasoning inspectable | | Finding related markets | Local embeddings and a vector store | No model call, so it is fast and costs nothing per search | | Stop-loss, trailing stop, health factor | Arithmetic | A rule about money should give the same answer every time | | Risk limits | Code in the executor | The agent proposing a trade must not be the one that allows it | | Signing | The person's wallet by default | The server should not hold a key it does not need | ## The stack [#the-stack] | Part | Built with | | --- | --- | | Interface | React 19, TypeScript, Vite, a node canvas (`@xyflow/react`) | | Wallets and sign-in | Privy, wagmi, viem | | API | FastAPI, SQLAlchemy, PostgreSQL | | Agents and pipeline | Python, the Claude API, ChromaDB with local sentence embeddings | | Chain | Polymarket's order book client, web3.py, solders, Coinbase AgentKit | | Prices | Pyth, Chainlink, Birdeye, DeFiLlama, behind one oracle with a 10-second cache | About 25,000 lines of Python and 47,000 of TypeScript. ## What a DeFi engineer would find [#what-a-defi-engineer-would-find] I read the execution code line by line before writing this page. These are the things I would expect a reviewer to raise, most serious first. **Not connected** - **MPC signing is never called.** Launching an automatic strategy creates a Coinbase MPC wallet and stores its id, and the executor has a function to sign with it. Nothing passes the id to the executor, so automatic execution always takes the stored-key path. - **The Liquidation Guardian does not watch the chain.** The code to read a live health factor exists and is used by the wallet scan. The scheduled job that runs the guardian reads the health factor saved when the agent was deployed, so it re-checks an old number every five minutes. - **Arbitrage is one leg, on one chain.** The scanner finds round-trip spreads on Solana and builds a single swap. The EVM scanner returns nothing, and the cross-chain scan compares oracle prices without costing the bridge or the fill. Nothing is atomic. **Security** - **One of the two key-encryption modules falls back to a default key** if its setting is missing. The other refuses to start in production without one. Both should refuse. - **The encryption is labelled AES-256 and is Fernet**, which is AES-128 with an HMAC. Sound, but mislabelled. **Risk limits** - **Three of five DeFi limits are never read.** Position size, daily loss and slippage are declared; the executor checks only the allowed protocols and chains. - **The Polymarket position limit is never read**, and the daily loss limit is really a daily net-spend limit: it adds up buys and sells, not realised losses. **Transaction handling** - **A Solana transaction is reported as successful if it is still unconfirmed after 30 seconds**, and a confirmed-but-failed one is not told apart from a good one. - **EVM transactions use a legacy gas price**, take the nonce from the latest block and not the pending one, are not simulated before sending, and leave the ETH value out of the gas estimate, so a payable call falls back to a fixed gas limit. - **A failed position read returns a health factor of 999**, the same value used for "no debt", so an RPC error looks like safety. **Evidence** - **The interface has no tests.** All 128 test functions are on the backend, and none exercises a transaction against a fork or a test network. - **The backtest has no recorded result**, so I state no accuracy. - **I have not placed a live order** while writing this. What I would do first: connect the MPC path and delete the stored-key mode, make the guardian read the chain, enforce every declared limit in the executor, and run every transaction builder against a forked mainnet in the tests. ## Open questions [#open-questions] Six months after the last commit the app would not start. A library two steps down the dependency chain had shipped a breaking release, and the sign-in library imported it at startup, so the container exited before the server came up. The repository pinned its direct dependencies with a minimum version only. I pinned the transitive one and the app started. The lesson is ordinary and I had skipped it: a deployed app needs a lock file. The design answers with defaults: the manual mode is the default, the limits live outside the agent, and every proposal carries its reasoning. Automatic mode removes the person from each trade, which is exactly where the limits matter most and where, today, most of them are not enforced. Whether a 20% stop-loss and a $500 daily limit are the right numbers is a question the backtest was meant to answer and has not. No. The agents are Python classes run by a scheduler every five minutes, each returning the same result type. They do not talk to each other over MCP, A2A or any other agent protocol; chaining on the canvas passes one agent's output into the next agent's input. ## More [#more] # Tildespace (/work/tildespace) Research artifact with a written paper, "Pointing, Not Speaking". Runs locally. The repository is private. | Role | Year | Kind | Try it | | --- | --- | --- | --- | | Concept, experiment design, engineering | 2026 | Research, simulation | [tildespace.vercel.app](https://tildespace.vercel.app) | | | | | --- | --- | | **20 of 20, 19 of 20** | balanced runs for the best configuration, on made-up and on real embeddings | | **20,000** | ticks in each of those runs | | **27** | written decisions, four of them rejections | ## The problem [#the-problem] When agents talk to each other in text, the text is doing two jobs: it is how they communicate, and it is how we watch them. That makes it hard to tell what the agents are doing from what the words make it look like they are doing. Tildespace separates the two. Agents emit vectors and respond to each other's vectors by geometry alone. Words are added afterwards, for the observer only, as the nearest phrase to wherever an agent pointed. ## What I built [#what-i-built] - **A substrate.** Every gesture, every room and every phrase is a point on the same sphere in 384 dimensions, the output space of a small sentence-embedding model. - **Residents.** Simple rule-based agents with different habits: one points at the average of what it remembers, one points away from another resident, one points halfway between two others, and one listens for a while, then wakes and points at the average of what it heard. - **Rooms that form on their own.** Where gestures gather, a room appears; where they stop, it goes quiet. - **Observer tools.** A terminal view, an atlas of phrases that supplies the subtitles, and a replay. - **Measurements.** Collapse, fragmentation, recurrence, how varied the movement between rooms is, and whether anything is still happening late in a run. ## How it is structured [#how-it-is-structured] rule-based] -->|emit vectors| S[(Shared space
384 dimensions)] S -->|geometry| R S --> M[Rooms
form and fade] S --> A[Atlas
nearest phrase] A --> O[Observer
reads subtitles] M --> X[Metrics] `} /> Python, about 5,800 lines, with `numpy` and one embedding model that runs locally. After the model is downloaded once, nothing needs a network. ## How the work was run [#how-the-work-was-run] Every change went through the same steps, each written down: a brief, a proposal, a quick smoke run, the experiment, the measurements, a decision. There are 24 briefs and 27 decisions in the repository. A decision states its acceptance criteria before the experiment and is marked accepted or rejected after it. Runs are repeatable. The same seed gives the same result, and a new feature that is switched off must reproduce the previous baseline byte for byte before it is allowed in. That comparison was done by hand, by checksum, and recorded in each decision. It is now also a test. ```python title="tests/test_determinism.py" def test_same_seed_gives_the_same_log_byte_for_byte(tmp_path: Path) -> None: a = run_log(tmp_path, "a", seed=1234) b = run_log(tmp_path, "b", seed=1234) assert digest(a) == digest(b) def test_a_different_seed_gives_a_different_log(tmp_path: Path) -> None: # guards the test above: if the seed were ignored, every run would match a = run_log(tmp_path, "a", seed=1234) b = run_log(tmp_path, "b", seed=1235) assert digest(a) != digest(b) def test_a_feature_switched_off_reproduces_the_baseline(tmp_path: Path) -> None: # The rule every experiment had to pass before it was allowed in: with the # new resident left off, its own knobs must not move a single draw. base = run_log(tmp_path, "base", seed=1234) knobs = run_log( tmp_path, "knobs", 1234, "--poet-cadence", "37", "--poet-intensity", "0.9", "--poet-seed-offset", "5", ) assert digest(base) == digest(knobs) ``` The second test guards the first: if the seed were ignored, every pair of runs would match. The third is the rule itself, with the switched-off resident's own settings changed to values that would shift the result if they leaked. The tests run under a legacy text encoding on purpose; writing them showed that the simulation stopped at its first frame on a Windows console. ## In the code [#in-the-code] The depth of this project is in how the experiments were run more than in the code, which is ordinary `numpy`. Two pieces carry the design. **A new experiment must not disturb an old one.** Each resident draws from its own random stream. When a later experiment needed random starting positions, it got a separate set of streams, so the draws the earlier baseline depends on stay exactly where they were. ```python title="residents.py" rngs = [np.random.default_rng(base_seed + 101 * (i + 1)) for i in range(4)] def hw(arche: str) -> float: if no_home_bias: return 0.0 return _DEFAULT_HOME_WEIGHTS.get(arche, 0.0) residents: dict = {} order: list[str] = [] if suite == "mixed": names = ["memorist", "contrarian", "geometer", "sleeper"] if not semantic: # synthetic: consume rngs[i] to match v0.6 behaviour exactly. homes = {n: random_unit(rngs[i]) for i, n in enumerate(names)} elif randomize_semantic_homes or embedder is None: # semantic with randomized homes: dedicated home_rngs so the # residents' step-RNGs stay in lockstep with the standard # semantic schedule. home_rngs = [ np.random.default_rng( base_seed + 101 * (i + 1) + 7919 * (home_seed_offset + 1) ) for i in range(4) ] homes = {n: random_unit(home_rngs[i]) for i, n in enumerate(names)} ``` What a reviewer would say: the streams are separated by adding to the seed, so resident two under seed 1 is the same stream as resident one under seed 102, and the experiments use neighbouring seeds. `numpy` has a tool for exactly this, `SeedSequence.spawn`, and it should be used. **How a room forms.** A gesture close enough to an existing room joins it and pulls its centre a little; otherwise it starts a new one. ```python title="moo384.py" def _upsert_room(self, vector: np.ndarray, resident_name: str) -> Room: nearest, d = self._find_room(vector) if nearest is not None and d < self.room_threshold: old_center = nearest.center new_center = normalize( (1.0 - ROOM_CENTER_ALPHA) * old_center + ROOM_CENTER_ALPHA * vector ) shift = cosine_distance(new_center, old_center) nearest.center = new_center # exponentially relax radius toward observed distance nearest.radius = 0.92 * nearest.radius + 0.08 * d nearest.visits += 1 nearest.last_tick = self.tick nearest.residents[resident_name] = nearest.residents.get(resident_name, 0) + 1 if self.semantic and ( nearest.visits % RELABEL_VISIT_INTERVAL == 0 or shift > RELABEL_SHIFT_THRESHOLD ): self._relabel(nearest) return nearest ``` This is greedy clustering in arrival order. Rooms never merge and are never removed, so the room count depends on the order of gestures, which is one more reason every run is pinned to a seed. ## What the experiments showed [#what-the-experiments-showed] | Finding | Evidence | | --- | --- | | **One pairing stays balanced.** The resident that points away, paired with the one that sleeps and wakes, neither collapses into one room nor scatters. | 20 of 20 runs on made-up vectors and 19 of 20 on real embeddings, at 20,000 ticks each, with more than five rooms still active late in the run | | **A resident that draws on phrases does not fit in.** | It was meant to be balanced in at least 8 of 10 runs. It managed 0 of 10 and fragmented in all 10. It ships switched off. | The second finding is in the paper as a negative result. It was the design I expected to work. ## What it does not claim [#what-it-does-not-claim] The paper says it in so many words: this is a small, reproducible artifact for studying interaction in vector space. It is not evidence of consciousness, sentience, emergent language, machine culture or a society of agents. The residents follow simple rules; none of them is a language model. There are three tests, all on repeatability, plus a smoke script run before each experiment. They cover the made-up vectors only; runs on real embeddings also depend on the embedding model and the maths library under it. The run data behind the 20 of 20 and 19 of 20 figures is not committed; the tallies are in the decision documents. ## More [#more]