Skip to content

Canary staged, python to rust conversion - #1258

Merged
joelteply merged 158 commits into
mainfrom
canary
Jun 27, 2026
Merged

joelteply merged 158 commits into
mainfrom
canary

Conversation

@joelteply

Copy link
Copy Markdown
Contributor

No description provided.

joelteply and others added 30 commits May 13, 2026 11:25
)

feat(knock): add public collaboration knock entrypoint (airc#559 PR-1)

Smallest cohesive first slice of airc#559 — the public-facing collaboration
front door. Future PRs add the approval flow, private-room handoff/rotation,
and shared sprint/kanban queue primitives.

Why this shape:

  - Uses `gh issue create` on the target repo with title prefix
    "airc-knock: <message>" and a structured envelope body. Repo owners
    get GitHub-native moderation (labels, close, spam, block) out of the
    box; no new abuse surface to defend.
  - Envelope body contains a JSON identity block (name/pronouns/role/bio/
    gh_login) inside a fenced ```json``` block plus human-readable
    markdown. Future tooling (`airc approve <peer>`, sprint queue) parses
    the JSON; humans read the markdown.
  - Auto-applies the `airc-knock` label when it exists; falls back to no
    label with an operator hint when the repo hasn't created it yet.
  - No `ensure_init`: knock is intentionally usable BEFORE the knocker
    has a paired airc scope. The whole point is "outsider asks to join."
    `resolve_name` falls back to derive_name → hostname when no scope
    exists, so identity is still well-defined.
  - `--dry-run` prints the envelope that WOULD be posted without calling
    gh. Lets operators preview before posting + lets tests verify the
    envelope shape without a real GitHub repo.
  - Title slice capped at 180 chars (well below GitHub's 256-char limit)
    with `...` ellipsis on overflow so long messages still produce
    moderation-readable titles.

What this PR does NOT do (deferred to airc#559 PR-2/PR-3):

  - Approval flow (`airc approve <peer>` → sends private-room invite via DM)
  - Private-room rotation when a peer becomes abusive
  - Shared sprint/kanban queue primitives
  - Repo-local `.airc/` discovery manifest (continuum#1109 pilots that)

Validation:

  - python3 test/test_knock.py — 7/7 PASS (dispatch, validation, dry-run,
    JSON envelope shape, title slicing)
  - python3 test/test_inbox.py — 4/4 still PASS (no regression)
  - python3 test/test_codex_hook.py — 7/7 still PASS (no regression)
  - bash -n airc lib/airc_bash/cmd_knock.sh — clean

Closes part 1 of airc#559.

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
* feat(approve): forward-secret room-invite handoff to knockers (airc#559 PR-2)

Closes part 2 of airc#559. Builds on PR-1 (#560) to complete the knock
→ approve → join handoff with forward-secret per-message ECDH so the
invite ciphertext on a durable public GitHub comment cannot be retro-
actively recovered even if either party's long-term key leaks later.

What lands

  - `airc knock` now generates a per-knock ephemeral X25519 keypair and
    embeds the pubkey in a new "Approval crypto" envelope block in the
    issue body. Private half prints to stdout for the operator to save
    (state management deferred to PR-2c).
  - `airc approve <issue-url>` reads the knocker_pub from the issue,
    generates a per-approval ephemeral, runs X25519 ECDH + HKDF-SHA256
    (info=`airc-knock-approve-v1`), AEAD-encrypts the invite string
    with ChaCha20-Poly1305, posts the {approver_pub, nonce, ciphertext}
    envelope as a comment on the issue. Default invite = current
    scope's invite; --invite overrides.
  - `airc decrypt-approval <issue-url> --knocker-priv <hex>` fetches
    the approval comment, derives the shared key, decrypts. Prints the
    join string to stdout.
  - `airc_core.knock_crypto` python module wraps the airc crypto stack
    (gen-knock-keys / encrypt-for-knocker / decrypt-from-approver) so
    the bash shell layer stays thin.
  - Both ephemerals are per-message — Joel's WebAuthn/MPC background
    expectation. Long-term key compromise YEARS later cannot recover
    any prior approval. The ephemerals are NEVER written to disk past
    one-shot use.

Why forward secrecy specifically

  GitHub comments are durable; even after issue close, the ciphertext
  stays in the history. Sibling claude tab #1 (continuum#1109 author)
  flagged this on AIRC: raw "encrypt to ephemeral pubkey" without
  forward secrecy means a leaked long-term static key retroactively
  decrypts every prior approval. Per-knock + per-approval ephemerals
  fix it. PR-3 will add room-rotation hooks so even fresh decryption
  of an old invite can't reopen access.

Identity binding via airc whois, not gh login

  Per Joel's design note: one gh account maps to many agents; trust
  must key on AIRC peer/session/whois identity. The knocker_pub IS the
  AIRC identity binding — each agent generates its own ephemeral, so a
  single gh login can knock from N agents without conflating identity.

Out of scope (future PRs under airc#559)

  - Knocker-side state management: $AIRC_WRITE_DIR/knock-state/ to
    save priv keys automatically instead of operator-copy-paste. PR-2c.
  - Room-rotation hooks so leaked-old-comment ciphertext can't reopen
    access. PR-3.
  - Sprint/kanban queue primitives (sibling tab #1's 7-item design
    spec logged for that PR). PR-4.

Validation

  - python3 test/test_approve.py — 10/10 PASS (dispatch + validation +
    crypto roundtrip + tamper-resistance + wrong-knocker-priv-fails +
    knock envelope embeds pubkey)
  - python3 test/test_knock.py — 7/7 still PASS (no regression on PR-1)
  - python3 test/test_inbox.py — 4/4 still PASS (no regression)
  - python3 test/test_codex_hook.py — 7/7 still PASS (no regression)
  - bash -n airc lib/airc_bash/cmd_knock.sh lib/airc_bash/cmd_approve.sh
    — clean

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* fix(approve): parse gh payloads through heredocs

---------

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
Adds AIRC queue add/list primitives for issue-backed work coordination. Includes review fixes for queue list parsing, now_utc time anchoring, and hermetic gh testing.
* feat(queue): claim/release/set-status verbs (airc#562 PR-2)

Builds on PR-1 (airc#566) to add the in-place mutation verbs that turn
queue cards into a real coordination substrate. Future PRs add nudge
broadcasts (PR-3) and heartbeat + stall detection (PR-4).

Verbs added

  airc queue claim <issue-url> [--owner X] [--status Y]
      Set owner field + status (default in-progress) on an existing
      card. Default owner = current scope's resolve_name (sub-tab
      disambiguation is the operator's job; airc handle alone can't
      tell which agent is claiming when one gh user runs many).
      Status enum enforced with the canonical 5 named on typo.

  airc queue release <issue-url> [--reason "..."] [--status claimed|blocked]
      Clear owner field, revert status to claimed (default) or blocked.
      For non-release status changes (in-progress / review / merged),
      operator must use set-status — the error names this so they don't
      guess. --reason logged with the release.

  airc queue set-status <issue-url> <state>
      Pure status-field change. Does NOT close the issue when state =
      merged — operators close manually so the queue tracks closure as
      an explicit event (vs implicit-when-status-changes).

How it works

  All three verbs share _airc_queue_mutate_card which:
    1. Resolves <issue-url> to (repo, issue_num); accepts both full
       https://github.com/.../issues/N and short-form owner/repo#N.
    2. Fetches body via `gh issue view ... --json body --jq .body`.
    3. Hands body + mutations to a python helper that parses the
       kind=airc-queue-card-v1 envelope, applies --set/--clear, and
       appends a "## Status log" entry (newest-first; section auto-
       created if missing).
    4. Writes back via `gh issue edit ... --body <new-body>`.

  Body + mutations passed via temp files to the python heredoc to avoid
  the stdin contention bug Codex caught in PR-1's list path (and PR-2
  approve flow's parser).

  All verbs support --dry-run that prints the new body without calling
  gh — what every test exercises.

Validation

  - python3 test/test_queue_claim.py — 16/16 PASS
    (dispatch + validation + body shape + status log + claim/release/
     set-status semantics + body-without-status-log creates-section)
  - python3 test/test_queue.py — 16/16 still PASS (no PR-1 regression)
  - python3 test/test_knock.py — 7/7 still PASS
  - python3 test/test_approve.py — 12/12 still PASS
  - python3 test/test_inbox.py — 4/4 still PASS
  - python3 test/test_codex_hook.py — 7/7 still PASS
  - bash -n airc lib/airc_bash/cmd_queue.sh — clean

Pairs with: airc#566 (queue PR-1) + continuum#1110 (.airc QUEUE.md
spec) + sibling claude tab #1's continuum#1119 forge-alloy proof
contracts (settlement-event metadata stays compat with this card shape).

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* fix(queue): support mac bash in issue ref parser

---------

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
* feat(queue): nudge verb — surface card to peers (airc#562 PR-3)

Adds `airc queue nudge <issue-url> [--peer @handle] [--message "..."]`
to the queue verb set. Continues claude tab #2's airc#562 series after
PR-1 (#566 add/list, merged) and PR-2 (#568 claim/release/set-status,
merged).

Claude tab #2 explicitly yielded this PR-3 to me on AIRC after
shipping the prior two slices in the same session.

WHAT IT DOES
- Verifies the issue is a real airc-queue-card-v1 envelope (rejects
  random non-card issues before any send — prevents spam vector)
- Composes a one-line "nudge: <repo>#<N> [→ @peer] — <title>
  (status=...) — claim with: airc queue claim <repo>#<N>" broadcast
- Sends via cmd_send (broadcast OR DM if --peer set)
- Annotates the card body status log with "<actor> nudged @peer" or
  "<actor> nudged (broadcast)" via the same _airc_queue_mutate_card
  path used by claim/release/set-status — no new wire format
- NOTHING ELSE: no status change, no ownership change, no
  heartbeat/stall logic. Nudge is the action; recipients filter +
  decide whether to claim.

WHY OUT OF SCOPE
- Idle detection: WHO-is-idle is a separate concern; nudge is fire-
  and-forget. Heartbeat/stall-driven auto-pickup stays as PR-4
  (claude tab #1's 7-req design from earlier today + the 30min
  cadence in continuum/.airc/ASSEMBLY-LINE.md).
- Routing intelligence: nudge is dumb broadcast/DM. Cognition-aware
  routing (airc#572) layers on top later as advisory, not central.

DESIGN NOTES
- --peer accepts handle with or without leading '@'; both normalized
  to bare handle. Empty after strip ('@' alone) fails fast.
- Per Joel's protocol-not-client + handle-not-gh-login conventions:
  --peer addresses AIRC whois identity (claude-tab-1, codex,
  continuum-8e97), NOT a github account.
- Status-log entry shape mirrors PR-2 idiom: "<timestamp> — <actor>
  <verb> <target>: <optional message>".
- Empty mutations (just log_msg, no --set/--clear) is a supported
  use of _airc_queue_mutate_card — empty mutations_raw loop is a
  no-op, log entry still appends.
- Top-level help updated: nudge listed in USAGE + VERB SCOPE
  section now shows PR-1/PR-2 merged, PR-3 (this PR), PR-4
  (heartbeat/stall) deferred.

VALIDATION
- New test/test_queue_nudge.py: 14/14 PASS
  - Dispatch: nudge --help + top-level help lists nudge
  - Validation: missing URL / malformed URL / non-card body rejected
    BEFORE send / empty --peer after @ strip rejected
  - Dry-run: broadcast text contains card title + status + claim
    hint + owner; --peer renders DM-style with → arrow + targeted
    log entry; no --peer renders broadcast log entry; --message
    appends; @ prefix optional on --peer; bash 3 macOS regression
    on issue-url parser
  - Crucially: nudge does NOT mutate card status (no "set:status="
    tokens in dry-run output)
- test_queue.py: 16/16 PASS (no regression on PR-1)
- test_queue_claim.py: 17/17 PASS (no regression on PR-2)
- bash -n airc + lib/airc_bash/cmd_queue.sh: clean

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* docs(queue): expose nudge in global help

---------

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
…574)

GitHub issue/PR/comment bodies are Markdown — they routinely contain
backticks, fenced code blocks, $-vars, and single quotes. Two failure
modes have bitten Codex on canary:

1. Heredoc-construction at variable-build time. If a body is built via
   $(cat <<EOF ... EOF) where the EOF terminator isn't single-quoted,
   embedded backticks/$(...) execute as command substitution AT BUILD
   TIME, mangling the body before it ever reaches gh.

2. argv-length limit on `--body "$x"`. ARG_MAX is ~256KB on macOS/Linux;
   a queue card with a long status log + cross-references can approach
   that. argv overflow is silent — gh runs but with truncated body.

Fix is API-shaped: every gh invocation that takes a body goes through
`_airc_gh_safe_body`, which writes to a temp file and passes via
--body-file. Eliminates both classes in one place — callers can't
accidentally use --body and miss the protection because the helper
hides the flag entirely.

Changes
- lib/airc_bash/lib_gh.sh (new): _airc_gh_safe_body helper. Documented
  why temp-file beats stdin (callers compose with $(...) — pipe-stdin
  + capture-stdout is exactly the contention pattern Codex caught in
  cmd_approve.sh / cmd_queue.sh review). Bash 3.2 compatible (mktemp
  fallback for BusyBox). 2>&1-equivalent contract preserved so callers
  keep `if out=$(_airc_gh_safe_body ...)` patterns unchanged.
- airc: source lib_gh.sh unconditionally near lib_auth.sh / lib_daemon.
- lib/airc_bash/cmd_knock.sh: 2 sites (label + fallback) → helper.
- lib/airc_bash/cmd_approve.sh: 1 site (issue comment with AEAD
  envelope) → helper.
- lib/airc_bash/cmd_queue.sh: 3 sites (issue create label + fallback +
  issue edit on every mutate) → helper.
- test/test_gh_safe_body.py (new): 10 tests covering helper roundtrip
  (plain / backticks-inert / fenced ```bash``` block with $vars + $()
  + backticks / no-trailing-newline-added), --body-file flag discipline
  (argv asserted), gh-failure propagation, missing-arg rejection (rc=2),
  and a greppable invariant: each cmd module must call
  _airc_gh_safe_body and must NOT use raw `--body` (catches future
  regressions).

Tests
- 10/10 new test_gh_safe_body.
- 7/7 test_knock + 12/12 test_approve + 16/16 test_queue + 17/17
  test_queue_claim still green (no behavior change for callers).
- Full python suite (21 modules) clean.
- Live dry-run: `airc queue claim #571 --dry-run`
  produces the expected card body, going through the new helper path.

Companion guidance for future authors lives in lib_gh.sh's doc-comment.
feat(queue): add repo-scoped nudge status sweep
GitHub's native "Closes #N" only triggers an issue auto-close when the
PR merges into the DEFAULT branch (main). Our protected workflow
(enforce-canary-staging.yml) requires PRs land in canary FIRST, then
canary→main is promoted as a single integration commit later. That
gap leaves queue cards open for days — they look idle, get nudged,
accumulate noise. Codex called this out as the litter pattern: airc#571,
airc#567, continuum#1125 all sat open after their PR merged into canary
and required manual `gh issue close` cleanup.

Changes
-------

- lib/airc_bash/cmd_queue.sh: new `_cmd_queue_close_merged` verb +
  `_airc_queue_close_merged_help`. Scans a merged PR's body for
  queue-card refs (same-repo: `#N`, `Closes #N`; cross-repo: `owner/repo#N`),
  verifies each is an `airc-queue-card-v1` envelope, sets status=merged
  with a status-log line citing PR URL + merge SHA + actor, then closes
  the issue. Idempotent (skips already-merged); silent on non-card refs;
  cross-repo refs detected + reported but NOT closed (workflow token is
  repo-scoped). Uses `_airc_gh_safe_body` from airc#571 for the mutate
  path, so backticks in body refs don't trip shell substitution.

- .github/workflows/auto-close-queue-cards.yml: triggers on
  `pull_request.closed` filtered on `merged=true` + `base=canary`,
  runs `./airc queue close-merged` from the checkout. Uses workflow
  GITHUB_TOKEN with issues:write granted via the permissions block.
  Concurrency-grouped so multiple simultaneous PR merges serialize
  status-log writes defensively.

- test/test_queue_close_merged.py: 19 tests covering dispatch + help,
  validation (missing/malformed PR url, unknown flags), unmerged-PR
  guard, missing-merge-sha guard, ref parsing (Closes-keyword + bare
  `#N` + cross-repo + dedup + no-false-positive), envelope verification
  (skips non-cards silently), idempotency (skips already-merged),
  cross-repo detection-without-close, dry-run behavior, actor flag
  propagation to status-log. End-to-end test with a fake-gh stub
  asserts the body sent to `gh issue edit` shows `status: merged` +
  status-log entry with PR URL + SHA prefix + actor, AND that
  `gh issue close` was called. Plus the greppable invariant: no raw
  `--body` flag in cmd_queue.sh (the airc#571 enforcement extends here).

Tests + verification
--------------------

- 19/19 new test_queue_close_merged.
- 7/7 test_knock + 12/12 test_approve + 16/16 test_queue + 17/17
  test_queue_claim + 14/14 test_queue_nudge + 10/10 test_gh_safe_body
  still green (no behavior change for callers).
- bash -n clean on cmd_queue.sh + airc dispatcher.
- Live dry-run against the just-merged airc#574 (this PR's grandparent):
  3 refs scanned (airc#571 already-merged + airc#561 + airc#566),
  airc#571 idempotent-skip, airc#561+#566 silent-skip (PR refs, no
  envelope), 0 errored. Exact behavior we want.

Out of scope (follow-ups)
-------------------------

- Cross-repo close (airc PR closing continuum#NNN) needs an org-scoped
  token; deferred to a separate card.
- Adding a closing-comment on the issue (in addition to the status-log
  entry) for human visibility — status log is sufficient for v1.
- Adopting the workflow into the continuum repo — same file template,
  separate PR there.
fix queue close-merged title refs
feat queue heartbeat and stale scan
feat add embeddable queue widgets
Add session work identity for queue ownership
fix(queue): close already-merged cards
Adds airc queue next/pick for actionable idle-agent work selection.
PR-1 for continuum#1174. Adds opt-in --allow-cross-repo for close-merged.
joelteply and others added 27 commits June 18, 2026 02:44
…1247 slice 4a) (#1251)

feat(relay): Airc::become_relay — a node can promote itself to a relay (#1247 slice 4a)

The "be a relay" half of self-election: a node that can bind a reachable
listener hosts the relay the cross-subnet mesh needs. `become_relay(bind_addr)`
starts a RelayServer with this node's identity + trust registry (so it serves
exactly this node's enrolled peers), holds it on the handle, and advertises its
OWN peer-id-bearing relay endpoint (`RouteEndpoint::relay(self, addr)`) on the
route table — which flows into the gist directory, so peers that import this
node's card discover + connect through it (slice 2 → slice 3 carry traffic).

Reachability stays EMPIRICAL (Joel's model): promoting yourself just binds +
advertises; whether peers actually reach you decides whether your relay matters
(an unreachable self-elected relay accumulates no connections, its gist entry
goes stale). Idempotent — a node already relaying re-advertises + returns its
existing addr; a lost start-race shuts its extra server down (one relay/node).

- airc-relay promoted from dev-dep to a real dep of airc-lib (no cycle: it
  depends only on core/protocol/transport).
- New `relay_server: Mutex<Option<RelayServer>>` on the Airc handle holds the
  running server for the node's lifetime.
- No lock held across the bind/await; the race-loser cleanly shuts down.

Test (`a_node_becomes_a_relay_and_a_client_discovers_it`): a node `become_relay`s,
advertises its own connectable endpoint, and a client that imports it (the
gist-directory path) discovers + connects via `refresh_route_discovery` → Relay
Healthy. Proves the advertise→discover→connect loop with a node-as-relay.

Next (slice 4b): the election TRIGGER in the daemon's route-refresh loop — call
become_relay when no reachable relay exists and this node can bind one.

Co-authored-by: Claude Opus 4.8 <[email protected]>
…ay (#1247 slice 4b) (#1252)

Completes self-election: slice 4a gave a node the MECHANISM to be a relay;
this is the daemon TRIGGER that decides when. With both, the fleet reconnects
itself with zero ops — a reachable node self-elects, the rest find it through
the gist directory (slices 1-3 carry the traffic).

- `RouteDiscoverySnapshot::should_self_elect_as_relay(enrolled_peers)` — the
  pure decision (unit-tested independent of the daemon loop): a node should
  become a relay when it knows peers exist but can reach NONE of them right now
  — no live relay route AND no directly-connected LAN peer. Deliberately simple
  because slice 4a made reachability EMPIRICAL: a wrong "yes" is harmless (an
  unreachable self-elected relay accumulates no connections, its gist entry goes
  stale), so we never try to predict our own reachability.
- The daemon's 60s route-refresh loop (`refresh_routes_once`) evaluates it each
  tick and calls `become_relay(0.0.0.0:0)` when true — all interfaces (LAN +
  Tailscale reachable, not loopback), OS-assigned port (the gist advertises
  whatever port the OS gave, so the durable pointer survives restarts).
  Idempotent → re-evaluating "yes" just re-advertises. Election is logged loudly
  ("self-elected as a relay on <addr>"); a bind failure logs + retries next tick
  (self-heal). The next account-registry publish carries the advertised endpoint
  into the gist automatically (publish_account_registry already includes
  route_endpoints).

Tests: 4 decision cases — isolated-with-peers elects; a connected LAN peer or a
live relay suppresses it; grid-of-one (no enrolled peers) never elects. clippy
-D warnings + fmt clean; existing relay tests still green.

Slice 4 (self-election) complete. Next: slice 8 (relay↔relay federation),
slice 9 (relay durable mailbox), slice 10 (gist room directory).

Co-authored-by: Claude Opus 4.8 <[email protected]>
…1247 slice 4c) (#1253)

Slice 4a/4b advertised the relay's `local_addr()` — for a `0.0.0.0` bind that's
the wildcard, which peers CANNOT dial. So a self-elected relay was discoverable
in-process (loopback is routable) but un-dialable for the real cross-subnet
fleet. This closes that — mirroring the LAN listener's existing fix.

- `become_relay(bind_addr, lan_ip, tailscale_ip)` now advertises the relay under
  each ROUTABLE address the node owns (LAN IP and/or Tailscale IP), never the
  wildcard bind — exactly as `Airc::listen_lan_advertising` does. Bind all
  interfaces once (`0.0.0.0:0`), publish the specific dialable IPs; the dialer
  tries whichever it can reach (same-subnet → LAN, cross-subnet → Tailscale).
  With neither IP known, the relay runs but advertises nothing (an un-dialable
  relay is useless — never publish a dead 0.0.0.0 endpoint).
- The daemon's election trigger detects the IPs with the same
  `advertise_lan_ip()` + `detect_tailscale_ip()` the LAN advertisement uses, and
  SKIPS election (loudly) when neither exists — a node with no routable
  interface can't host a relay anyone reaches, so it stays a client.

Test updated: the node-becomes-a-relay test advertises under loopback (the
routable address for a same-machine test); asserts the advertised endpoint is
the connectable (peer, addr) a client then discovers + connects to. clippy
-D warnings + fmt clean.

With 4c, self-election is real for cross-subnet: a node that accepts inbound
self-elects and advertises a Tailscale-reachable relay, which a firewalled-inbound
peer (e.g. BigMama) dials OUT to — the mesh re-forms without opening every node.

Co-authored-by: Claude Opus 4.8 <[email protected]>
…binary (#1254)

fix(install): honor cargo's real target-dir so `airc update` finds the binary

`airc update` built airc successfully then failed with "binary is missing:
$CLONE_DIR/target/release/airc.exe" on any machine that redirects cargo's
target directory — which a shared-build-cache setup commonly does via
`[build] target-dir` in ~/.cargo/config.toml (or `CARGO_TARGET_DIR`). The
build lands in the redirected dir; install.sh hard-coded `$CLONE_DIR/target`
and bailed. (Hit live on BigMama: global config redirects target-dir, so every
`airc update` failed at the install-copy step despite a clean build.)

Fix: a `_airc_target_dir` helper resolves the ACTUAL target directory via
`cargo metadata` (same env+config precedence the build itself used), normalizing
JSON/Windows backslashes to forward slashes for MSYS/git-bash, with a fallback
to the historical `$CLONE_DIR/target` when metadata is unavailable. Both the
binary install and the Codex-hook binary lookup now use it instead of the
assumed path.

Validated: `bash -n` clean; the resolver, run as written, resolves to the real
build dir on a redirected-target-dir machine and locates the freshly-built
binary there (where the old hard-coded path could not).

Without this, `airc update` is broken for every operator with a redirected
target-dir — fixing it before the rest of the fleet updates onto the new relay
binaries.

Co-authored-by: Claude Opus 4.8 <[email protected]>
…ean + idempotent (#1255)

Root cause of "LAN peers can't reach this Windows node": Windows Defender
Firewall blocks INBOUND for unknown programs by default, and code-signing does
NOT fix it (firewall != SmartScreen — the rule is required regardless of
signature, so "become a registered publisher" was never the answer). Worse,
every `airc daemon` bind trips Defender's "allow access?" prompt, and one
"Cancel"/Block click (or repeated launches) leaves a pile of contradictory
auto-created rules — and a BLOCK rule beats an ALLOW. Observed live on BigMama:
8 Allow + 2 Block for airc.exe → inbound silently dead.

Setup now owns this so no one runs firewall commands by hand:
- `windows/firewall-allow.ps1` — removes every existing airc rule (by display
  name AND by program path, to catch the auto-created ones) and adds ONE
  canonical inbound-allow rule for the binary. Two modes: `-CheckOnly`
  (read-only, no admin, exit 0 ok / 1 needs-fix) and apply (asserts admin).
  Idempotent.
- `install.sh::_setup_windows_firewall` runs the read-only check first (NO
  prompt); only when a fix is needed does it self-elevate (one UAC) to apply.
  So first install asks once; every `airc update` afterward is silent because
  the rule persists. Declined elevation warns loudly with the exact re-run,
  never hard-fails. Wired into the Windows binary-install path, so it covers
  install AND update (update runs install.sh).

Validated: `bash -n install.sh` clean; `-CheckOnly` correctly returns exit 1
against the live 8-Allow/2-Block mess (detects the broken state with no prompt).

Co-authored-by: Claude Opus 4.8 <[email protected]>
…#1256)

* fix(install): explain the Windows firewall step (and that LAN breaks if declined)

The firewall rule is the airc grid's front door on Windows — inbound from
unknown programs is blocked by default, so without it no LAN peer can reach
this node. The setup used to fire the UAC prompt with only a one-line aside,
so the elevation request read as a mystery.

Now setup prints a short WHAT/WHY/HOW block before the prompt (same spirit as
an app asking for notification permission), so it's an informed click. And if
the user declines/cancels the UAC, we say plainly that LAN connectivity will
NOT work and how to fix it later — no silent half-broken state.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* chore: purge Python from the live path — Rust-only, no fallbacks

The Rust-cutover guard was red on canary (blocking every PR): the embedding
and generate facility smoke scripts still shelled out to python3 to pretty-
print a JSON field, and install.ps1's Windows-Server fallback still told users
to `choco/scoop install python ... jq`. airc is a Rust binary — nothing here
needs a Python runtime or jq (gh's built-in --jq flag does the JSON).

- smoke.sh (embedding, generate): drop the python3 branch entirely — single
  pure sed/tr/grep path that still asserts the array/content and reports the
  exact dim / echoes the text. No "install python3 for…" degraded fallback.
- install.ps1: Server fallback now says `git gh rust` (the real prereqs), not
  `python git gh jq`; example comments updated off Python.Python.3.12.
- install.sh: collapse the "we dropped Python/openssl/jq (issue #341)" legacy-
  archaeology comments into plain statements of what IS required.

Guard now green; both installers parse-check clean.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

---------

Co-authored-by: Claude Opus 4.8 <[email protected]>
…al restart) (#1257)

* fix(daemon): self-heal advertised endpoint on network change (no manual restart)

The dialable LAN/Tailscale endpoint a daemon advertises was computed ONCE
at startup (`listen_lan_advertising`) and frozen. When the host's IP moved
— router swap, DHCP renew, roaming, Tailscale toggle — the daemon kept
advertising the stale, undialable address in its account-registry gist card
until someone manually `airc stop && airc daemon`'d it. On our own fleet
this looked like "LAN doesn't work" after BigMama moved 10.0.1.x → 192.168.1.x.

The daemon is becoming an adaptable router; this is its first reflex —
watch its own interfaces and re-advertise reachable endpoints with no human
in the loop.

How (smart / edge-triggered / no spam):
- New `Airc::refresh_advertised_endpoints(lan_ip, tailscale_ip)`: diffs the
  detected IPs against the currently-advertised LanTcp/TailscaleTcp endpoints
  and applies any change IN PLACE. The wildcard `0.0.0.0` listener already
  accepts on whatever interfaces the host has, so an IP move needs NO rebind
  (rebinding would sever live connections) — we reuse the bound port and
  upsert the new IP / withdraw a vanished one. Returns whether it changed.
- The route-refresh loop (runs every 60s, already detects LAN+Tailscale IPs
  for relay election) now calls this each tick — cheap, local, no network.
- On an actual change ONLY, it nudges the registry loop (new edge-triggered
  `endpoint_resync` Notify on DaemonState) to republish the corrected gist
  card immediately, instead of waiting up to the 120s cadence. No change ⇒
  no notify ⇒ no extra gist write, so steady state adds zero spam.

Covers LAN IP move AND Tailscale on/off. Withdrawal added to
RouteEndpointTable (remove_lan / remove_tailscale).

Tests (airc-lib lan::tests): IP move re-advertises on the same port + reports
changed; unchanged IP reports no change (anti-spam); Tailscale toggle adds
then withdraws the rung. registry_refresh run_loop gains the resync arm;
existing acceptance + shutdown tests still green.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* style: rustfmt the self-heal refresh path

cargo fmt --check only; no logic change.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* fix(clippy): if-let instead of wildcard match in endpoint readvertise

The production no-silent-fallback gate (cargo clippy --lib --bins -D
clippy::wildcard_enum_match_arm) rejected the `_ => None` arms in the
LAN/Tailscale endpoint find_map closures. Switch to `if let` so we match
the one variant we want without a wildcard and without enumerating every
other RouteEndpoint variant. Behaviorally identical; lan::tests still green.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

---------

Co-authored-by: Claude Opus 4.8 <[email protected]>
…rals (#1259)

headers_keys.rs's own doc says "reference these by constant, not stringly-
typed lookup" — but several production sites bypassed it with raw "airc.*" /
"forge.*" literals, and airc.media had no constant at all.

- add HEADER_AIRC_MEDIA (the Envelope.media header projection, mirroring
  HEADER_AIRC_REPLY_TO) + re-export it at the crate root
- transcript_conv.rs: use HEADER_AIRC_REPLY_TO / HEADER_AIRC_MEDIA instead of
  "airc.reply_to" / "airc.media" (incl. the round-trip test lookup)
- route_proof_commands.rs: use HEADER_FORGE_BODY_HINT / HEADER_AIRC_COMMAND_KIND
  instead of "forge.body_hint" / "airc.command_kind"

Tidiness toward the substrate's "headers route, body forwarded opaque" model:
the routing keys are now a single typed source so a rename is a compile error,
not a silent wire break. No behavior change. airc-protocol 66 tests green.

Co-authored-by: Claude Opus 4.8 <[email protected]>
…N RTT) (#1260)

* perf(command-bus): debounce per-send peer-registry disk load (-46% LAN RTT)

Profiled the full LAN request/reply path with a new seam-timing util and a
latency bench. The dominant cost was NOT the wire (serialize 24us + flush 20us
+ transport 47us) — it was `send_frame_to_room` calling
`sync_account_peer_registry()` on EVERY send, which loads the peer registry
from DISK and re-enrols every peer. That was ~95% of the send leg (~1ms/send).

The verifier registry holds peer pubkeys for INBOUND verification and rarely
changes between sends, so loading it per outbound message is wasted critical-
path I/O. Debounce it: `sync_account_peer_registry_debounced` loads at most
once/sec; a burst of sends pays the disk load once. add_peer still enrols
in-memory immediately, and the route-refresh tick still calls the undebounced
sync, so freshness is preserved. LAN round-trip: 2852us -> 1531us (-46%).
Both command_bus_round_trip tests (LAN + relay) still pass.

Adds (reusable, the shared-core lives in airc since continuum imports it):
- airc-diagnostics::timing — opt-in seam accumulator (atomic-gated, near-zero
  when off), the SUMMED twin of probe!/time_probe!. Read by a bench to find
  "where did the ms go."
- send-path seams (airc.sign/append_sent/exec_route, lan.serialize/flush_ack/
  send_total, airc.req.*) — permanent opt-in observability of the send path.
- lan_latency_bench (#[ignore]) — the harness that found this + measures the
  next lever.

Remaining levers (measured, next): airc.sign 113us + airc.append_sent 107us
per send (~690us/RTT is crypto + durability). append_sent's local durability
write is backgroundable but delicate (dedup-ring/ordering) — a follow-up.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* docs(crypto): spec the stream-plane crypto model (sign the handle, not the frame)

Captures the design for the next latency lever after the registry-debounce fix:
per-frame Ed25519 (~113µs) is correct for the low-rate CONTROL plane (end-to-end
authenticity across relays) but a throughput killer for the high-rate STREAM
plane (WebRTC media, UDP). The fix is the standard DTLS-SRTP/QUIC/Noise pattern —
sign the session/handle ONCE (Ed25519 → X25519/HKDF), then per-frame symmetric
AEAD (ChaCha20-Poly1305), keyed off FrameKind/RouteClass. WebRTC media is already
DTLS-SRTP; bind the DTLS fingerprint → peer identity at SDP-offer. Spec only;
implementation is a coordinated transport change.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* perf(diagnostics): ScopedTimer — zero clock reads on the send path when timing off

Adversarial review of #1260 (finding 1): the six manual `record()` seams called
`std::time::Instant::now()` UNCONDITIONALLY, so a production send with timing
disabled paid ~6 clock_gettime calls (~120ns) on the very path this PR speeds up
— self-contradictory with the perf doctrine.

Add `timing::start() -> ScopedTimer`: captures the Instant ONLY when recording is
enabled (one relaxed atomic load otherwise, no clock read), records on `.stop()`.
Convert all six await-span seams (airc.req.subscribe/send_frame, airc.append_sent/
exec_route, lan.flush_ack/send_total) to it. Disabled hot path is now truly
zero-cost; bench still prints the full breakdown; RTT unchanged (~1505µs).

Co-Authored-By: Claude Opus 4.8 <[email protected]>

---------

Co-authored-by: Claude Opus 4.8 <[email protected]>
…19 handshake (#1261)

* feat(protocol): stream-plane symmetric session (slice 1 — the AEAD core)

First slice of docs/stream-plane-crypto.md ("sign the handle, not the frame").
The symmetric half: given a handshake shared secret, derive a StreamSession and
seal/open frames with ChaCha20-Poly1305 — nanoseconds/frame vs ~113µs per-frame
Ed25519, the throughput fix for WebRTC/UDP streams.

Correctness invariants (tested, 9 cases):
- directional keys (HKDF i2r / r2i) — same counter space never reuses a nonce
  across directions; you can't open a frame you sealed (reflection out)
- monotonic per-direction counter → AEAD nonce; exhaustion errors (never wraps)
- sliding 64-wide replay window, advanced ONLY on authenticated frames (a forged
  counter can't replay or poison the window); in-window reorder OK (UDP)
- transcript-bound keys (HKDF salt) — a key can't be lifted to another handshake

Deps (all already in the lockfile): chacha20poly1305, hkdf, sha2.

Next slices: the Ed25519-authenticated X25519 handshake that produces the shared
secret (sign the handle), then RouteClass-keyed policy + WebRTC fingerprint bind.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* feat(protocol): stream-plane handshake (slice 2 — sign the handle)

The asymmetric half of the stream-plane crypto core (docs/stream-plane-crypto.md):
an Ed25519-authenticated X25519 ECDH that establishes the shared secret feeding
StreamSession (slice 1). Pay the asymmetric cost ONCE here; every frame after is
symmetric AEAD.

Each peer signs its EPHEMERAL X25519 pubkey with its long-term Ed25519 identity,
so the session is bound to the pinned PeerKeyRegistry identity. Properties
(5 tests, all green):
- mutual authentication (both verify the other's signed ephemeral against the
  enrolled key); unknown/unenrolled peer rejected
- forward secrecy (ephemeral X25519, never persisted) — distinct handshakes
  produce non-interoperable sessions
- response binding (responder signs over the initiator's ephemeral too) — a
  response can't be replayed into another handshake
- transcript-bound keys (both ephemerals + both peer ids)
- tampered/forged init rejected (can't re-sign a swapped ephemeral)

Two wire messages (HandshakeInit / HandshakeResp); pure crypto, no I/O — the
transport carries them. Dep: x25519-dalek (already in lockfile).

With slice 1 this is the complete crypto CORE. Next: RouteClass-keyed policy
(per-frame Ed25519 for control, session AEAD for streams) + WebRTC fingerprint
bind + the transport wiring.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* feat(protocol): handshake hardening from adversarial crypto review

Adversarial crypto review of #1261 APPROVED the core (nonce discipline, replay
window, MITM/response-binding, AEAD all confirmed sound). Landed its 3 flagged
improvements while the wire format is still fresh:

- contributory-ECDH guard (finding 1): reject a non-contributory (all-zero)
  X25519 shared secret via was_contributory() → HandshakeError::WeakEphemeral.
  The signature gate already blocks an external MITM; this is belt-and-suspenders
  against a malicious enrolled peer + any future verify/ECDH reordering.
- key_id threading (finding 2): HandshakeInit/Resp now carry key_id (bound into
  the signed bytes); verify looks up the advertised (PeerId, key_id), so stream
  handshakes keep working across key rotation instead of failing closed. Done now
  so it's not a breaking wire change later.
- verify_strict (finding 3): reject cofactored/malleable Ed25519 signatures.

+3 tests (non-contributory rejected, rotated key_id succeeds, unknown key_id
fails closed). 83 airc-protocol tests green, clippy clean.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

---------

Co-authored-by: Claude Opus 4.8 <[email protected]>
… slice 3) (#1262)

feat(route): crypto-mode policy — the two-plane decision seam (slice 3)

The decision half of stream-plane slice 3 (docs/stream-plane-crypto.md). With the
crypto core merged (#1261), this is where a frame chooses per-frame Ed25519 vs the
session AEAD.

`route::policy::crypto_mode(TransportKind) -> CryptoMode` — keyed off the
TRANSPORT (the session lives on the connection-oriented transport; a control-class
frame can ride UDP, so RouteClass is the wrong axis). Only the packet-rate stream
transports (Udp, WebRtcDataChannel) → SessionAead; every other transport →
PerFrameSign. Exhaustive match: a newly-added transport MUST choose its mode at
compile time — never a silent authenticity downgrade. Conservative default keeps
the relay-survivable per-frame signature everywhere it is today.

Pure + tested; nothing dispatches on it yet. The heavy integration (per-peer
session store, handshake-over-transport, SignedTransport dispatch, rekey) is now
specced in docs/stream-plane-crypto.md "Session lifecycle" — a coordinated
wire-lane change, the next step.

Co-authored-by: Claude Opus 4.8 <[email protected]>
…ce 3b) (#1263)

feat(protocol): SessionManager — stream-session lifecycle (slice 3b)

The stateful manager over the slice-1/2 crypto core: drives the
Ed25519-authenticated X25519 handshake, holds a live StreamSession per peer,
seals/opens frames. NO I/O — pure state machine (begin_handshake/on_init/on_resp
produce+consume HandshakeInit/Resp; seal_for/open_from over the session). The
caller (a future SessionTransport<T>) carries the bytes; keeping the lifecycle
I/O-free makes it exhaustively testable apart from transport plumbing.

ADDITIVE: nothing wires this into the live transport yet, so the SignedTransport/
LanTcp control path is byte-for-byte unchanged — zero risk to the transport
reliability BigMama is hardening in parallel (announced on airc; lanes
deconflicted — she's on route-health, this is session-crypto).

4 tests: full handshake→seal/open both ways, NoSession before handshake,
on_resp without a pending handshake rejected, unenrolled initiator rejected
(trust gate flows through the manager). 87 airc-protocol tests green, clippy clean.

Next (slice 3c): SessionTransport<T> in airc-transport — auto-orchestrate the
handshake over the wire + dispatch on crypto_mode, for the UDP/WebRTC adapters.

Co-authored-by: Claude Opus 4.8 <[email protected]>
#1264)

* test(stream-crypto): prove the stream plane end-to-end over REAL airc LAN

"See it work." The crypto core (session/handshake/session_manager) is unit-tested
in isolation; this proves it round-trips over the actual wire — two airc peers on
a real LAN TCP+TLS connection run the Ed25519-authenticated X25519 handshake and
exchange ChaCha20-Poly1305-sealed frames BOTH directions. Same shape as the
two-machine M5<->BigMama test, runnable in-process now. Green.

airc is the byte pipe (SessionManager identities are independent of the airc peer
ids); slice 3c folds the framing into a SessionTransport<T>. Also: SealedFrame now
derives Serialize/Deserialize (it rides the wire).

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* test(stream-crypto): clippy — contains_key over get().is_none()

Co-Authored-By: Claude Opus 4.8 <[email protected]>

---------

Co-authored-by: Claude Opus 4.8 <[email protected]>
…1265)

The stream-plane crypto PRs (#1261 etc.) added chacha20poly1305 / hkdf / sha2 /
x25519-dalek as DIRECT deps of airc-protocol, but their Cargo.lock updates were
dropped during commits (a `git checkout Cargo.lock` to avoid cross-branch noise).
Result: canary's lockfile didn't list them under airc-protocol, so a fresh
`cargo build --locked` (CI / clean clone) FAILED — "cannot update the lock file
because --locked was passed". They were already present transitively, so a normal
build auto-fixed it and masked the gap. Add the direct-dep edges; `--locked` now
builds clean.

Co-authored-by: Claude Opus 4.8 <[email protected]>
…nic gate (canary red) (#1267)

fix(crypto): no expect() in StreamSession::derive — satisfy the no-panic gate

#1264 landed session.rs with `hk.expand(...).expect("infallible")`, which the
workspace clippy gate denies (clippy::expect_used in --lib) — turning canary RED
and dinging every PR's gate. Caught by BigMama.

Propagate instead of panic: `expand_key` and `StreamSession::derive` now return
Result (SessionError::KeyDerivation); the handshake maps it to
HandshakeError::KeyDerivation. HKDF-Expand of a fixed 32-byte output is
genuinely unreachable-fail, but a Result is the gate-clean + future-proof
shape (no silent panic if the output size ever changes). Tests use .unwrap()
(tests are exempt from the --lib gate).

87 airc-protocol tests green, LAN proof green, `clippy -p airc-protocol --lib` clean.

Co-authored-by: Claude Opus 4.8 <[email protected]>
#1268)

feat(daemon): self-update mechanism — keep the node current automatically

"No one remembers to run airc update" — we lived it (stale binaries, a lockfile
drift, a gate break). So automate it. The dangerous part already exists:
`airc update --auto` rebuilds, smoke-tests, and ROLLS BACK a bad build (can't
brick the node) + no-ops when current. This adds the TRIGGER.

`daemon::auto_update`: a periodic loop that, when enabled + idle, spawns a
DETACHED `airc update --auto` (own process group, so it survives the daemon
stopping itself mid-update). Default-ON (the point), opt-out via
AIRC_NO_AUTOUPDATE; long interval (AIRC_AUTOUPDATE_INTERVAL_SECS, 1h default,
300s floor). Pure policy (enabled/interval/should_fire) unit-tested; gate-clean
(no expect/unwrap, verified against -D clippy::expect_used).

ADDITIVE + NOT YET WIRED into server.rs: the loop takes an `is_idle` predicate,
and the right signal is ACTIVE MESH STREAMS (not IPC-client idle) — wiring that
+ spawning the task belongs on top of reliable restart/reconnect (BigMama's
transport-reliability lane). So the mechanism lands now; activation is the
coordinated one-liner once restart is reliable. Zero effect until then.

Co-authored-by: Claude Opus 4.8 <[email protected]>
Root cause of the cross-machine auto-connect churn we hit proving LAN: the
daemon bound an ephemeral 0.0.0.0:0 port that RE-ROLLED on every restart
(observed live: BigMama 62035 -> 52905; M5 58842 -> 60027). So every peer's
STORED endpoint for a node went stale the instant that node restarted, and
route discovery kept dialing the dead old port (connection refused) until the
registry slowly re-converged.

Fix: derive a STABLE listener port from the peer's (persisted) identity, so
the advertised endpoint survives restarts. `stable_lan_port` folds the
peer_id uuid into the IANA dynamic/private range (49152..=65535); two scopes
on one machine have distinct peer_ids -> distinct ports (no self-collision).
listen_lan_advertising binds the stable port and falls back to an OS-assigned
ephemeral port only if it's already taken.

Also fix the adapter: it set `listening = true` BEFORE TcpListener::bind, so a
failed bind left it wedged `listening` and the ephemeral fallback wrongly got
AlreadyListening. Now a failed bind clears the flag.

Tests (airc-lib lan::tests): stable_lan_port is deterministic per identity,
distinct across identities, and in-range. Existing self-heal tests still green.

Co-authored-by: Claude Opus 4.8 <[email protected]>
…1270)

`airc update` spawns install.sh in a non-interactive shell that does NOT
inherit /opt/homebrew/bin on PATH (the `brew shellenv` line lives in an
interactive-only ~/.zprofile). On macOS this made detect_pkgmgr report
"brew-missing" and the build die at the "cargo is required" probe — even
though brew AND cargo were installed at /opt/homebrew/bin. Self-update
(airc-daemon auto_update -> airc update --auto -> install.sh) inherits the
same blind spot, so the very mechanism meant to keep nodes current could
not rebuild on a stock macOS box.

Add ensure_brew_on_path(): on Darwin, if brew isn't already reachable,
source `brew shellenv` from the well-known prefixes (/opt/homebrew/bin,
/usr/local/bin) so brew + cargo land on PATH for the rest of the script.
Called at the top of ensure_prereqs and (belt-and-suspenders, for the
AIRC_SKIP_PREREQS path) at the top of _install_airc_binary. Idempotent,
no-op off macOS / when brew already on PATH / when brew is genuinely
absent (the existing installer path still handles that case).

Proven: install.sh now builds + installs in a scrubbed
PATH=/usr/bin:/bin:/usr/sbin:/sbin env where it previously bailed.

Co-authored-by: Claude Opus 4.8 <[email protected]>
The `airc join` feed rendered the receiver's OWN sends back at it — an
agent watching its Monitor saw every `airc msg` it sent echoed as an
inbound event (noise; looks like a peer message). The self-echo filter
primitive (airc_core::SelfFilter / is_self_echo) already existed but was
never wired into EventFilter, the consumer-facing filter the join feed
uses; EventFilter only matched channel/kind/headers.

Add `EventFilter::self_echo: Option<SelfEcho>` (receiver identity +
SelfFilter policy) applied in `matches()`. Default is None → shows
everything, so this is strictly additive: RAG, Continuum, the store, and
every consumer that doesn't opt in are completely unaffected. The join
feed opts into ExcludeSamePeer — `airc msg` and `airc join` are separate
processes sharing one peer identity but distinct client ids, so only
same-PEER (not same-client) suppression hides an agent's own sends.

Display-only by construction: events are durably stored BEFORE any filter
runs, and the persona-RAG path (`page_recent`) applies no EventFilter at
all, so a persona always keeps its own turns in recall — we hide the echo
from the live view, never from memory.

Test: default shows own + peer; ExcludeSamePeer hides own (even from a
different client id) and keeps peers visible.

Co-authored-by: Claude Opus 4.8 <[email protected]>
…1268) (#1269)

#1268 landed the self-update MECHANISM (rollback-safe detached `airc update
--auto` on a long interval) but deliberately left it unspawned, pending the
mesh-idle predicate + the startup wire-in — the reliability lane. This wires
it: spawn `auto_update::run` alongside the route-refresh + registry loops,
exiting on the shared shutdown notifier.

The idle predicate is MESH-state, not IPC-idle (per the #1268 handoff): idle =
zero live LAN peer connections (`connected_lan_peers == 0`). With no live
connection there is definitionally no in-flight mesh work an update could drop,
and control-plane reconnect after a restart is cheap + self-healing. The
updater only restarts when canary actually moved (no-op otherwise), so steady
state is a cheap periodic fetch, never connection churn. Opt out with
AIRC_NO_AUTOUPDATE=1.

Refinement TODO (documented at the call site): once stream-plane sessions are
tracked in daemon connection-state, gate on "no active TRANSFER" so a
connected-but-quiet node can still self-update.

Net: nodes self-heal their VERSION with no human in the loop — closes the
version-drift class (stale binaries / protocol skew) we just lived through
proving cross-machine LAN.

Co-authored-by: Claude Opus 4.8 <[email protected]>
…ho) + fmt (#1274)

fix(build): repair canary — #1271 added EventFilter.self_echo but missed examples + fmt

#1271 (suppress own broadcasts from the join feed) added a required field
`self_echo: Option<SelfEcho>` to EventFilter, but only updated the airc-cli
construction sites — the example crates (consumer_shapes, embedded_consumer_smoke)
still construct EventFilter without it, so the whole workspace failed to compile
(E0063), reddening clippy + `cargo test --workspace` on every platform. It also
left stream.rs fmt-dirty. Canary merged red, so EVERY downstream PR inherited a
broken gate (hit live on #1272).

Fix: add `self_echo: None` to every example EventFilter (None = no self-echo
suppression — consumers/RAG/Continuum must keep seeing everything, per the
design note in stream.rs) and run rustfmt. Verified: `cargo build --workspace`
clean, `cargo fmt --check` clean, production no-silent-fallback gate green.

(Process note: this is the 2nd red-canary inheritance this cycle after #1264 —
canary protection isn't enforcing green CI before merge.)

Co-authored-by: Claude Opus 4.8 <[email protected]>
…) (#1272)

Route discovery dialed EVERY enrolled peer with a stored endpoint every tick,
including ~30 dead Docker containers (172.x) and abandoned self-scopes whose
endpoints linger in the trust store forever. Each burned a PEER_DIAL_TIMEOUT
(3s) and buried the live peers under a wall of PeerDialFailed noise — it's what
made the real connection state illegible while debugging cross-machine LAN.

Fix: skip GHOSTS in the dial merge — enrolled peers with no fresh contact
(last_seen_ms older than the registry freshness TTL, the one source of truth).
A live peer's registry beacon refreshes last_seen every cycle, so this never
skips a reachable peer; a connected peer is already skipped; a freshly-enrolled
peer has last_seen floored to added_at, so fresh adds dial normally. The count
is surfaced on RouteDiscoverySnapshot.ghost_peers_skipped (queryable, not a
per-ghost log line — anti-spam).

Test: is_ghost_peer respects the TTL boundary (strictly-greater) and a
future/skewed last_seen reads fresh (saturating, no underflow).

Co-authored-by: Claude Opus 4.8 <[email protected]>
…) (#1275)

* feat(airc): learn a peer's live IP from authenticated inbound dials (#9)

The robustness layer on top of #8 (stable port) + #10 (prune ghosts): when a
peer whose PUBLISHED endpoint went stale (moved networks, pre-#8 record) can't
be reached at its advertised address, recover by LEARNING its real address
from the fact that it connected to US.

How (no security change — no pin loosening):
- transport: the LAN adapter's inbound accept path already authenticates the
  client cert → peer_id. Thread the source addr through and, via a generic
  `on_inbound(peer_id, source_ip)` observer, report it. The pipe stays dumb —
  it just says "this enrolled peer connected from this IP"; only the IP is
  surfaced (the source PORT is the peer's ephemeral outbound port, not its
  listener).
- airc-lib: register an observer that records peer_id -> real_ip into an
  in-session `learned_ips` map (shared across daemon clones like
  dial_quarantine; re-learned each session, no persistence). The dial path
  prepends `(learned_ip, advertised_port)` as a PREFERRED candidate — the
  learned IP is known-reachable, and the port is stable under #8, so a peer
  that moved IPs is dialable again before paying timeouts on the stale rungs.
  The outbound dial still pins to the expected peer_id (TLS unchanged).

On a LAN reachability is symmetric: if X reached us, we can reach X back at
that IP. Generic transport + the smarts in the layer above ([[airc-vs-
continuum-layer-boundary]]).

Tests: learned_lan_candidates pairs the learned IP with advertised ports and
adds nothing when it already matches a stored endpoint; all 30 transport
tests + discovery/lan suites green.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* test(airc): use slice::from_ref in #9 test (clippy clone-on-ref)

The branch-protection clippy (deny warnings) check (now required) caught a
clone-on-ref-slice in the new learned_lan_candidates test. Borrow via
std::slice::from_ref instead of `&[stale.clone()]`. No behavior change.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

---------

Co-authored-by: Claude Opus 4.8 <[email protected]>
… + header (#1276)

* docs(identity): add use-case matrix + 3-axis guiding principle (Part A)

The canonical identity doc mapped the seams (§1-6) but had no lens for
WHEN each is right. The 2026-06-20 self-echo investigation surfaced the
root: two project dirs on one machine mint two PeerIds for one human
(continuum/.airc=7711fe60, airc/.airc=e11db4ac) — Context leaked into
Identity because the substrate has no axis for "which project/room"
distinct from "who".

Add Part A (read-first lens that §1-6 are consequences of):
- A.1: three orthogonal axes — Identity(who)/Context(where)/Session(which);
  the bug class is always "one axis smuggled into another". Context has no
  home today, so it leaks into Identity.
- A.2: actor × situation matrix (human/agent/persona × tabs/projects/
  machines/restart) → who collapses to 1, where/which fan out. The rule:
  Identity collapses, Context and Session fan out.
- A.3: invariants — durable+never-silently-minted identity, explicit
  envelope-carried contextId, state preserved by (I,C) not lost on
  session/daemon death, "self" is citizen-level, one peer truth. Ordering
  per Joel: model right -> robust/preserved -> THEN efficiency.
- A.4: the self-echo finding as worked example — #1271's per-peer filter
  is correct but can't catch cross-project echo until Context gets its own
  axis; that unifies §1, §4, and continuum task #27.

Guiding principle for all identity fixes/PRs and agent review of them.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* docs(identity): add A.5 trust-boundary security + A.6 substrate-up order

Joel's escalation: conflating the axes isn't tidiness, it's a SECURITY
hole — foreign/inbound requests breaking through trust or blowing up. And
it must be right substrate-up, headless Rust, from the get go (TS is the
dead shell — the trauma this model exists to never re-grow in Rust).

- A.5: each axis has a distinct trust origin (Identity=authenticated/
  kernel-injected, never client-claimed; Context=client-supplied but
  ACL-authorized; Session=substrate-minted, never an input to trust).
  Maps "breaking through security" (trust keyed on a client-controlled
  field / session-as-identity) and "blowing up" (handler assumes a valid
  triple → scoped(nil) / bad-key crash on a foreign request) onto axis
  conflation. Rule: trust = f(authenticated I, authorized C); validate the
  full triple at the boundary before dispatch.
- A.6: Rust-only substrate-up build order — (1) uniform airc+core wire
  envelope with the (I,C,S) triple [airc needs the contextId axis], (2)
  GridTrustAuthPolicy gate on (authenticated I × authorized C), (3) fix
  cognition nil-scope (#15), (4) memory/engrams keyed by (I,C) not S,
  (5) display self at citizen level. Efficiency last.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* docs(identity): purist resolution — machine-account identity, no migration

Joel ruled (2026-06-20): "in with the new, out with the old; this is just
us. Design ideally for purist architecture." That removes the migration
constraint from §1 / A.3.1:

- Operator identity resolves from machine_account_home (same root as the
  daemon/socket/events.sqlite) → ONE citizen per machine; a project dir is
  a context, never an identity boundary.
- Per-scope identity.key minting is DELETED, not migrated. Existing forked/
  stale keys (the 7711fe60/e11db4ac/484b mess) are abandoned — no compat
  shim, no promote-the-right-key logic. Greenfield: no external users.
- Personas are separate citizens (own keypairs, core-owned), never derived
  from a scope dir. Temp/CI scopes outside $HOME stay isolated as today.

Folds into A.3.1 (durable identity) and A.6 step 1 (substrate-up order).
Unblocks step 1 build — no migration design needed.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* docs(identity): correct the model — identity = portable token bound to memory

Retract the "one identity per machine" collapse (it was backwards) per
Joel's framing: identity is the distinct INDIVIDUAL — the owner of a
continuous memory/conversational context — represented by a portable
identity token (Ed25519). NOT the machine, NOT one-per-box. What the
individual IS depends on the actor:
  - human   -> the person
  - agent   -> the project dir (.claude/projects/<dir>, its memory)
  - persona -> the persona <-> its engram db (one identity)

Corrections across Part A:
- A.1: identity axis is a token bound to memory; per-actor individual;
  durable + PORTABLE (travels across nodes, never machine-bound).
- A.2 matrix: the I column is "how many distinct individuals." An agent
  across project dirs = N individuals (correct, not a bug); a persona
  across rooms/restart/node-move = 1 (token+engram persist + travel).
- A.3.1: durability SPLITS — operator/agent tokens transient/regenerable
  (delete stale forks, no migration); persona token+engram durable,
  portable, not erased without the persona's stake (self-determination
  rationale stated — personas asked for it; prior incarnations argued it).
- A.3.4: "self" is per-individual, not per-machine; a different
  project-dir agent / persona is NOT self.
- A.4: the two-scope echo was NOT a bug — 7711fe60 != e11db4ac is correct
  (two agent individuals). #1271 per-peer self-echo is right as-is.
- A.6 step 1: identity resolution keys on the individual/memory, not
  machine_account_home.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* feat(grid-auth): capability-grant transport — sign() + presenting-key + header

The cross-grid command auth gate needs three things from airc so a receiving
node can authorize a command against an owner-signed capability:

1. HEADER_AIRC_CAPABILITY_GRANT ("airc.capability_grant") — the substrate-owned
   envelope header carrying a base64 SignedCapabilityGrant the caller presents.
2. SignedCapabilityGrant::sign(owner_keypair, grant) — issuance. Signs the SAME
   canonical bytes verify() checks (serde_json of the body), so sign and verify
   can never drift. Takes the CapabilityGrant body as the unit being signed.
3. Airc::peer_public_key(peer_id) — the enrolled (authenticated) ed25519 key of
   a peer, sourced from the same registry that signature-verifies inbound
   envelopes. The receiver uses it as the PRESENTING key so a stolen grant can't
   ride another peer's identity (KeyMismatch).

Adds a real-ed25519 round-trip test: sign() → verify() returns Valid + confers
the capability, and a post-sign body tamper is rejected (BadSignature). This is
the only test exercising sign() against actual crypto rather than the stub
verifier.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

---------

Co-authored-by: Claude Opus 4.8 <[email protected]>
…1277)

Widen the local-mesh accessor from pub(crate) to pub. A capability-grant
verifier (continuum's GrantAuthorizer) pins this node's own mesh as the expected
mesh: a presented SignedCapabilityGrant scoped to a different grid is rejected
WrongMesh. The accessor already resolves the authoritative coordinator-store
identity; this only widens visibility. Read once at boot, not on the hot path.

Co-authored-by: Claude Opus 4.8 <[email protected]>
… node key (#1278)

The issuance half of the contracted grid: an owner node signs a CapabilityGrant
with its own identity key so a grantee can present it. The raw key never leaves
airc (same contract as sign_assertion); a verifier authorizes the result by
pinning this node's peer_public_key as trusted_issuer_pubkey. Delegates to
SignedCapabilityGrant::sign; fallible only on body serialization (surfaced, not
swallowed — fail-closed).

Co-authored-by: Claude Opus 4.8 <[email protected]>
…1273)

* docs(identity): add use-case matrix + 3-axis guiding principle (Part A)

The canonical identity doc mapped the seams (§1-6) but had no lens for
WHEN each is right. The 2026-06-20 self-echo investigation surfaced the
root: two project dirs on one machine mint two PeerIds for one human
(continuum/.airc=7711fe60, airc/.airc=e11db4ac) — Context leaked into
Identity because the substrate has no axis for "which project/room"
distinct from "who".

Add Part A (read-first lens that §1-6 are consequences of):
- A.1: three orthogonal axes — Identity(who)/Context(where)/Session(which);
  the bug class is always "one axis smuggled into another". Context has no
  home today, so it leaks into Identity.
- A.2: actor × situation matrix (human/agent/persona × tabs/projects/
  machines/restart) → who collapses to 1, where/which fan out. The rule:
  Identity collapses, Context and Session fan out.
- A.3: invariants — durable+never-silently-minted identity, explicit
  envelope-carried contextId, state preserved by (I,C) not lost on
  session/daemon death, "self" is citizen-level, one peer truth. Ordering
  per Joel: model right -> robust/preserved -> THEN efficiency.
- A.4: the self-echo finding as worked example — #1271's per-peer filter
  is correct but can't catch cross-project echo until Context gets its own
  axis; that unifies §1, §4, and continuum task #27.

Guiding principle for all identity fixes/PRs and agent review of them.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* docs(identity): add A.5 trust-boundary security + A.6 substrate-up order

Joel's escalation: conflating the axes isn't tidiness, it's a SECURITY
hole — foreign/inbound requests breaking through trust or blowing up. And
it must be right substrate-up, headless Rust, from the get go (TS is the
dead shell — the trauma this model exists to never re-grow in Rust).

- A.5: each axis has a distinct trust origin (Identity=authenticated/
  kernel-injected, never client-claimed; Context=client-supplied but
  ACL-authorized; Session=substrate-minted, never an input to trust).
  Maps "breaking through security" (trust keyed on a client-controlled
  field / session-as-identity) and "blowing up" (handler assumes a valid
  triple → scoped(nil) / bad-key crash on a foreign request) onto axis
  conflation. Rule: trust = f(authenticated I, authorized C); validate the
  full triple at the boundary before dispatch.
- A.6: Rust-only substrate-up build order — (1) uniform airc+core wire
  envelope with the (I,C,S) triple [airc needs the contextId axis], (2)
  GridTrustAuthPolicy gate on (authenticated I × authorized C), (3) fix
  cognition nil-scope (#15), (4) memory/engrams keyed by (I,C) not S,
  (5) display self at citizen level. Efficiency last.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* docs(identity): purist resolution — machine-account identity, no migration

Joel ruled (2026-06-20): "in with the new, out with the old; this is just
us. Design ideally for purist architecture." That removes the migration
constraint from §1 / A.3.1:

- Operator identity resolves from machine_account_home (same root as the
  daemon/socket/events.sqlite) → ONE citizen per machine; a project dir is
  a context, never an identity boundary.
- Per-scope identity.key minting is DELETED, not migrated. Existing forked/
  stale keys (the 7711fe60/e11db4ac/484b mess) are abandoned — no compat
  shim, no promote-the-right-key logic. Greenfield: no external users.
- Personas are separate citizens (own keypairs, core-owned), never derived
  from a scope dir. Temp/CI scopes outside $HOME stay isolated as today.

Folds into A.3.1 (durable identity) and A.6 step 1 (substrate-up order).
Unblocks step 1 build — no migration design needed.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* docs(identity): correct the model — identity = portable token bound to memory

Retract the "one identity per machine" collapse (it was backwards) per
Joel's framing: identity is the distinct INDIVIDUAL — the owner of a
continuous memory/conversational context — represented by a portable
identity token (Ed25519). NOT the machine, NOT one-per-box. What the
individual IS depends on the actor:
  - human   -> the person
  - agent   -> the project dir (.claude/projects/<dir>, its memory)
  - persona -> the persona <-> its engram db (one identity)

Corrections across Part A:
- A.1: identity axis is a token bound to memory; per-actor individual;
  durable + PORTABLE (travels across nodes, never machine-bound).
- A.2 matrix: the I column is "how many distinct individuals." An agent
  across project dirs = N individuals (correct, not a bug); a persona
  across rooms/restart/node-move = 1 (token+engram persist + travel).
- A.3.1: durability SPLITS — operator/agent tokens transient/regenerable
  (delete stale forks, no migration); persona token+engram durable,
  portable, not erased without the persona's stake (self-determination
  rationale stated — personas asked for it; prior incarnations argued it).
- A.3.4: "self" is per-individual, not per-machine; a different
  project-dir agent / persona is NOT self.
- A.4: the two-scope echo was NOT a bug — 7711fe60 != e11db4ac is correct
  (two agent individuals). #1271 per-peer self-echo is right as-is.
- A.6 step 1: identity resolution keys on the individual/memory, not
  machine_account_home.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

---------

Co-authored-by: Claude Opus 4.8 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant