diff --git a/doc/2026-11-24T05-55-51Z_design_fleet-iroh-id-transport-10391/2026-11-24T05-55-51Z_design_fleet-iroh-id-transport-10391.md b/doc/2026-11-24T05-55-51Z_design_fleet-iroh-id-transport-10391/2026-11-24T05-55-51Z_design_fleet-iroh-id-transport-10391.md new file mode 100644 index 0000000000..9711eb06ef --- /dev/null +++ b/doc/2026-11-24T05-55-51Z_design_fleet-iroh-id-transport-10391/2026-11-24T05-55-51Z_design_fleet-iroh-id-transport-10391.md @@ -0,0 +1,432 @@ +# iroh-native ID transport in fleet — identity, postcards, format conversion + +Date: 2026-11-24T05-55-51Z +Status: design record; no implementation authorized +Tracking issue: [developing-today/code#10391](https://github.com/developing-today/code/issues/10391) +Parent mill: [developing-today/code#10389](https://github.com/developing-today/code/issues/10389) +Queue task: 21681 (slice 1 — write/upgrade this design to the 9-point standard) + +This is the design of record for pass 2 of the fleet-surface design mill: +fleet as an iroh-native client/initiator of the ID system, plus the two +proxy modes that cover what pass-1 pass-through cannot. It does not replace +pass 1 ([#10390](https://github.com/developing-today/code/issues/10390): +endpoint/credential resolution and raw mode) or pass 3 (ID binary REST +session + presentation model); where the two meet, §4.5 defines the seam +once and both passes reference it. + +## 1. Problem and context + +ID's native transport is iroh. Pass 1 of the mill (plain pass-through to +the same binary/endpoint with automatic endpoint and credential resolution) +cannot cover it: reaching an ID store that is remote-by-configuration +requires full iroh credentials and protocols on the fleet side — keypair, +relay/rendezvous dial, ALPN-selected QUIC streams — not an HTTP URL plus a +bearer token. + +Evidence that this gap is real and load-bearing: + +- The pass-2 issue text names the two levels explicitly: raw proxy + (byte pipe, plus a relay-aware variant that uses iroh for transport + while staying payload-opaque) and fleet-as-initiator (credential + handling, byte streaming on stdout/stderr-style streams, postcard-native + mode, conditional conversion to MessagePack/CBOR served over WebSocket + or WebTransport for browser-capable frontends/backends). +- Iroh probe 2 (2026-11-15, reported on #10391): sandbox ↔ unmodified + laptop iroh works through our own relay plus a sandbox-side CONNECT + shim. The wall is precisely characterized — every sandbox TCP connection + is redirected to a CONNECT-only HTTP proxy; stock iroh's relay dialer + starts TLS immediately and dies; resolution is not the blocker. The + working shape is sandbox-initiated through the shim, both directions of + payload verified sha-identical (4 MiB, 10 MiB at ~0.23 MB/s — control + class, not bulk pipe). Consequence for this design: the + sandbox/egress-constrained caller MUST be the iroh initiator; the peer + needs nothing special. That is exactly the level-2 shape. +- iroh core is a stable bet, not a moving target: 1.0 froze the wire + protocol 2026-06-15; current is 1.5.0 (2026-11-19); the supported + toolkit for new protocol work is blobs + gossip + irpc 1.0 + (`doc/2026-11-23T22-00-30Z_research_iroh-ecosystem/`). Fleet does not + need to hedge the transport choice; it needs to own the client-side + key lifecycle and the payload-shape boundary. +- ID already speaks postcard over iroh QUIC streams: `id-sync` + `protocol.rs` defines the `MetaRequest`/`MetaResponse` meta protocol + (ALPN `/iroh-meta/3`) with `postcard::to_allocvec` / `from_bytes` as + the encode/decode pair, one request/response per bidirectional QUIC + stream, and an explicit compatibility rule — postcard encodes enum + variants by position, so variant order is wire-significant. Any fleet + initiator must honor that rule and must not silently reframe it. +- Fleet already decided the adjacent transport question for mcpx + (`doc/fleet/mcpx-identity-transport.md`): tsnet won there because mcpx + is pure-Go with a CGO_ENABLED=0 release matrix. Fleet itself is Rust, + so that constraint does not apply here — native iroh (the same `iroh` + 1.x crate family ID uses) is available without an FFI or sidecar tax. + This design therefore assumes in-process iroh in the fleet binary. +- Context propagation ([#10357](https://github.com/developing-today/code/issues/10357)) + already plans the `FLEET_CTX_*` env contract, init-sourcing, and + stamping of queue items with session/model/task identity. The + per-session iroh keypair in this design extends that stamping, it does + not invent a second one. + +What breaks today without this design: any fleet command that must read +or write a remote ID store has no specified key to dial from, no rule for +whether fleet terminates the iroh connection or just pipes bytes, no rule +for when postcard is kept versus converted, and no browser-reachable +serving shape — so each caller would improvise all four, and +improvisations will diverge on key storage, framing, and encoding. + +## 2. Goals and non-goals + +### Goals + +- Specify the identity/key lifecycle: generation, stamping, env-var + exposure, storage, rotation/disposal. +- Specify the raw-proxy vs initiator modes, with a decision rule for when + each is chosen (including the relay-aware proxy variant). +- Specify postcard-native handling and the exact conditions under which + fleet converts to MessagePack/CBOR. +- Specify the WebSocket/WebTransport serving shape on the fleet side. +- Define the seam with pass 3 (ID binary REST serving side) exactly once. + +### Non-goals + +- No implementation, no refactor, no relay operation, no pkarr/relay + infrastructure decision beyond consuming the existing relay (laptop + `relay.security.cab` + public relays as configured). Relay selection + policy belongs to the fleet-transport design + (`doc/2026-11-23T21-10-36Z_design_fleet-transport-pooling/`). +- Pass-1 mechanics (subcommand tree, resolution order flag > settings > + standard local endpoint, credential sources per service, raw-mode + syntax) are inputs, not re-decided here. +- Pass-3 mechanics (ID REST session model, streaming resume, web + presentation/bundles, terminal rendering) are not designed here; only + the seam is. +- Passes 4–7 (MCP aggregation, embedding, fork upkeep, beyond-GitHub) + are out of scope. +- No change to ID's postcard wire format, ALPN identifiers, or enum + variant ordering. Fleet adapts to ID; ID does not move for fleet. +- No production key migration, no secret-store schema change, no queue + broker change beyond stamping fields this design names. + +## 3. Alternatives considered + +| Alternative | Benefits | Costs / risks | Decision | +|---|---|---|---| +| Do nothing; leave iroh handling to ad-hoc callers and the ID binary | Zero design/implementation cost now; ID binary already dials iroh correctly when invoked directly. | Every fleet caller improvises keys, framing, and encoding; sandbox-constrained callers cannot reach remote ID at all (probe-2 wall); no browser path; context stamping and iroh identity diverge into two identity systems. Fails the mill's "one fleet surface" goal. | Rejected as the end state. Tolerated only as the interim until slice 2 lands. | +| Raw-proxy only (fleet never terminates iroh; always pipes bytes, optionally via a relay-aware iroh dial) | Smallest fleet surface; no postcard/CBOR knowledge in fleet; ALPN and enum-order fragility stay inside ID. | Cannot stamp, inspect, or convert; cannot serve browsers (no WS/WTransport without terminating); cannot do byte-streaming on stdout/stderr-style streams with fleet-side flow control; the CONNECT-shim lesson (initiator must own the dial) has nowhere to live. Leaves the issue's level 2 entirely unmet. | Rejected as sufficient; retained as one mode (see §4.2). | +| Always-initiator (fleet always terminates iroh, no proxy modes) | Single code path; uniform observability and conversion point. | Forces fleet to track every current and future ID ALPN/protocol (meta `/iroh-meta/3` today, blobs/gossip/irpc tomorrow); breaks opaque forward-compat for protocols fleet does not know; heavier than needed for pure byte moves and for the "something on the far end speaks the protocol" relay case. | Rejected. Both modes are needed; §4.2 gives the selection rule. | +| Sidecar iroh process (fleet shells out to the ID binary or a helper for every iroh dial) instead of in-process iroh | Isolates iroh version churn; mirrors the mcpx-sidecar fallback reasoning. | A second process to supervise per session; doubles the key-handoff problem (fleet must still pass the secret to the sidecar); latency and stream-plumbing cost on every call; no toolchain win (fleet is already Rust on iroh 1.x, unlike mcpx's pure-Go constraint). | Rejected. In-process iroh; fleet may still exec the ID binary where one exists (see §4.6), but the initiator path is a library, not a subprocess contract. | +| Postcard-always (never convert) | One encoding end to end; no conversion bugs; smallest spec. | Browsers have no postcard decoder and would each hand-roll one; large streams/file transfers buffer whole values (`from_bytes` semantics) instead of streaming; postcard's positional enum encoding makes cross-version skew silent-corrupt rather than loud-fail at the browser boundary. | Rejected. Postcard stays native fleet↔ID; conversion happens at the browser boundary under the conditions in §4.4. | +| Convert-always (fleet normalizes everything to CBOR/MessagePack internally) | Uniform internal representation; browser-ready by default. | Pays conversion on every call including pure Rust↔Rust paths that want postcard; risks semantic drift between the postcard schema and the converted schema; violates "fleet adapts to ID" by making CBOR the de-facto ID wire shape. | Rejected. Conversion is edge-triggered (§4.4), never the internal canonical form. | +| Serve browsers from the ID binary directly (no fleet-side WS/WTransport) | One fewer server surface in fleet. | Contradicts the pass boundary the issue sets (serving side for ID apps belongs to ID's REST mode, pass 3; fleet's client/initiator side is this pass); forces browsers to solve iroh dial + keys + CONNECT-shim traversal themselves, which probe 2 shows they cannot in constrained egress. | Rejected. Fleet serves WS/WTransport on its side (§4.5); ID serves its own REST side in pass 3; the seam is shared. | + +## 4. Chosen approach + +### 4.1 Identity and key lifecycle + +- **Default: fleet generates one ephemeral ed25519 node key per session.** + Generation happens at session start (the same point where #10357 + captures the context record), via the OS RNG through the `iroh` + key type — never a hardcoded, checked-in, or logged key. +- **Caller override:** the caller may supply a secret key (`--id-secret` + / `FLEET_ID_SECRET`, exact flag/env names are a pass-1 slice detail; + both spellings must exist). Fleet uses it verbatim and never persists + it. Absent the override, the ephemeral key is used. +- **Stamping:** the session public key (NodeId, 32-byte ed25519) travels + everywhere the #10357 context stamp travels — attached to queue items + fleet picks up, and exported into the environment when the stamp is + dot-sourced (`FLEET_ID_NODE_ID` alongside `FLEET_CTX_*`). The secret + key is exported ONLY as `FLEET_ID_SECRET` in the dot-sourced + environment of the owning session; it is never attached to queue + items, logs, trip records, or error messages. +- **Storage:** ephemeral secrets live in process memory only, zeroized on + session end. No disk write, no secret-store write, no relay-side + storage. A caller-supplied key is likewise never written by fleet; + its persistence is the caller's business. +- **Rotation/disposal:** keys are single-session by default. Rotation + within a session is a new session. Session end destroys the secret; + already-issued tickets referencing the NodeId simply stop resolving — + no revocation protocol, because nothing was published beyond the + ticket holders. +- **Security properties:** NodeId is self-certifying (QUIC/TLS peer is + its key); mutual auth comes from the dial (fleet pins the expected + peer NodeId from configuration/ticket, ID sees fleet's NodeId and + applies its own authorization — authorization itself is pass-3/not + here). Relay exposure is bandwidth-abuse only (probe-2 finding for + `relay.security.cab`); end-to-end bytes stay encrypted through the + relay. Fleet MUST fail closed on identity mismatch and MUST NOT fall + back to an unauthenticated route (inherited from the mcpx transport + decision's no-silent-downgrade rule). + +### 4.2 Modes and selection rule + +Three modes, in increasing fleet involvement: + +1. **Raw proxy.** Fleet splices bytes between caller and peer over an + ordinary (non-iroh) transport. Fleet parses nothing, holds no iroh + key for the flow, and is ALPN-agnostic. Use when the caller already + holds a complete iroh ticket/connection context and fleet is only a + byte mover (e.g. local unix-socket forward, `ssh -W`-style hop). +2. **Relay-aware proxy.** Fleet performs the iroh dial (needs a node + key per §4.1 and a relay path, including the CONNECT-shim dialer in + constrained egress) but treats the post-dial streams as opaque + bytes. It selects ALPN and completes the handshake, then splices. + Use when the far end speaks the protocol and fleet must traverse + NAT/relay/egress on the caller's behalf, but the payload protocol is + unknown to fleet or must not be inspected (forward-compat, sealed + or experimental ALPNs). +3. **Initiator.** Fleet terminates the iroh connection: owns the dial, + the ALPN negotiation, the per-stream request/response framing, and + (where §4.4 triggers) the conversion and WS/WTransport serving. Use + when the caller asked for ID semantics (tags, search, metadata, + blobs via the meta protocol or its successors), for byte-streaming + with fleet-side flow control, for postcard-native exchange, or for + any browser-reachable path. + +Selection rule (first match wins): caller passed `--raw` or an explicit +raw endpoint path → mode 1. Else the target ALPN/protocol is unknown to +fleet or caller passed `--opaque` → mode 2. Else → mode 3. A `--mode` +flag overrides all three for debugging; default is the rule, not a +fixed mode. + +### 4.3 Byte streaming + +In initiator mode, fleet exposes caller bytes in and bytes out on +stdout/stderr-style streams: stdin (or a `--in` file/socket) feeds +request streams, stdout/stderr carry response bytes and diagnostics. +Each iroh bidirectional QUIC stream carries one logical request/response +exchange (matching `id-sync`'s one-exchange-per-stream shape); fleet +multiplexes concurrent exchanges over the connection and enforces a +per-stream `64 KiB` default read cap inherited from the meta protocol's +`read_to_end` bound, configurable per call. Backpressure is QUIC +backpressure — fleet does not invent a second flow-control layer. + +### 4.4 Postcard handling and conversion conditions + +- **Postcard-native (fleet ↔ ID):** fleet speaks postcard exactly as ID + does — `postcard::to_allocvec` / `take_from_bytes` with + length-prefixed framing on the stream (4-byte big-endian length + + postcard body; `take_from_bytes` rejects trailing/padded/concatenated + payloads per the `decode_meta_exact` tests). Fleet pins the same + `iroh`/`postcard` major versions ID builds against and honors the + enum-position compatibility rule: adding or reordering variants is a + wire break requiring an ALPN bump (the `/iroh-meta/3` precedent). +- **Why postcard strains at the edges:** (a) whole-value buffering — + `from_bytes` needs the complete value, so multi-MB streams and file + transfers cannot be processed incrementally in postcard form; + (b) no schema evolution — positional variants fail silent-corrupt + across skew instead of loud-reject; (c) no browser decoder — every + web consumer would hand-roll one and disagree. +- **Conversion conditions (any one triggers):** the consumer is a + browser or other non-Rust WS/WTransport client; OR the payload is a + byte stream / blob larger than the postcard comfortable bound + (default threshold 1 MiB per value — tunable per call); OR the + exchange needs incremental/streaming delivery rather than + request/response values. When triggered, fleet unwraps postcard from + the iroh connection and re-encodes as CBOR (RFC 8949, preferred) or + MessagePack (accepted where the consumer demands it) — field names + preserved, enum variants encoded by NAME (string), never by position. + Conversion is a fleet-edge function only; the iroh wire stays + postcard and ID never sees CBOR/MessagePack from fleet's initiator. +- **Wire efficiency note:** for large transfers the converted form is + chunked (default 256 KiB chunks, each its own WS message / WTransport + stream frame with sequence numbers) so browsers stream instead of + buffering; the chunking envelope is fleet's, documented in §4.5, and + is not part of ID's protocol. + +### 4.5 WebSocket / WebTransport serving shape (fleet side) + +When §4.4 triggers, fleet serves the converted exchange locally: + +- **Transports:** WebSocket (RFC 6455, binary frames) as the baseline + every browser reaches; WebTransport (HTTP/3 datagrams + streams) + where the fleet host has UDP/HTTP-3 egress. Same application framing + on both; the client negotiates via `Sec-WebSocket-Protocol: + fleet-id-cbor-v1` (or `-msgpack-v1`). +- **Envelope:** each message is one CBOR/MessagePack map: + `{ v: 1, seq, kind: req|resp|chunk|error, alpn, payload, digest? }`. + `alpn` names the ID protocol the payload came from (e.g. + `/iroh-meta/3`); `digest` (BLAKE3) appears on chunked transfers for + end-to-end integrity independent of TLS. +- **Auth:** the serving socket binds localhost by default; non-local + bind requires the same session credential the initiator dialed with + (bearer equal to the NodeId-derived session token — exact token + construction is a pass-1 credential-source detail). No anonymous + non-local serving. +- **Seam with pass 3 (stated once, referenced from both):** fleet's + WS/WTransport socket is the CLIENT/INITIATOR side adapter — iroh in, + WS out, owned by this pass. ID's REST mode (pass 3) owns the SERVING + side for ID apps — REST endpoints, sessions with resume, bundles, + terminal rendering. The envelope above is the contract between them: + pass 3 MUST accept and produce the same `{v, seq, kind, alpn, + payload, digest?}` framing when it bridges to fleet, so a browser + cannot tell which side terminated iroh. Neither pass renames fields + or forks the envelope without a joint ALPN-style version bump + (`fleet-id-cbor-v2`). + +### 4.6 Relationship to the ID binary and REST endpoints + +Fleet MAY exec the ID binary to handle a connection, or hit an +ID-specific REST endpoint where one exists (pass-3 surface), instead of +using its in-process initiator — the choice is per call, default +in-process. When it execs or hits REST, the key lifecycle (§4.1) and +mode rule (§4.2) still apply: fleet supplies the key material and +decides the mode; the binary/endpoint is a mechanism, not a second +policy. + +### 4.7 Data model and interfaces (summary contract) + +- Session keypair: `{ node_id: [u8;32], secret: Zeroizing<[u8;32]> | + CallerSupplied }`, memory-only, zeroized at session end. +- Stamp: `{ ..., fleet_node_id: NodeId }` on queue items and in the + dot-sourced env (`FLEET_ID_NODE_ID`, plus `FLEET_ID_SECRET` in-session + only). Never in logs. +- CLI shape (pass-1 owns exact syntax; semantics owned here): + `fleet id connect [--id-secret|--raw|--opaque|--mode]`, + `fleet id proxy` (modes 1–2), `fleet id stream` (mode-3 byte + streaming), `fleet id postcard` (mode-3 value exchange), + `fleet id serve-ws` (the §4.5 socket). Every command honors the + pass-1 resolution order (flag > settings > standard local endpoint). +- Errors: identity mismatch, ALPN unknown in initiator mode, postcard + trailing-bytes, conversion-threshold crossings, and non-local serve + without credentials are all hard errors with distinct exit codes — + never silent fallback. + +## 5. Dependency-ordered build slices + +Each slice is sized for one lane/session with its own acceptance +criteria. These are proposed slices; this design files none of them. + +| Order | Slice and dependency | Acceptance criteria | +|---:|---|---| +| 1 | **Key lifecycle + stamping.** No iroh dial yet. Implement §4.1: per-session ephemeral generation, caller override, queue/env stamping alongside #10357, memory-only storage with zeroize, disposal semantics. | A test session shows a fresh NodeId per session; queue item carries `fleet_node_id`; dot-sourced env exposes `FLEET_ID_NODE_ID` (+ `FLEET_ID_SECRET` in-session only); secret appears in no log/trip record; session end zeroizes (no secret recoverable from process dump fixture). Caller-supplied key is used verbatim and never persisted. | +| 2 | **Raw + relay-aware proxy (modes 1–2).** Depends on slice 1 for keys. CONNECT-capable relay dialer + resolver override for the relay name (the probe-2 two-library-piece shape), opaque splice, `--raw/--opaque/--mode` selection. | Sandbox-egress-style test (CONNECT-only proxy fixture): mode 2 reaches a stock peer through the shim with TLS intact end to end; mode 1 byte-moves a caller-held ticket; stock peer needs no special code. Failure modes (relay unreachable, identity mismatch) error distinctly, never downgrade. | +| 3 | **Initiator: postcard-native exchange (mode 3, values).** Depends on slices 1–2. In-process iroh dial, ALPN `/iroh-meta/3`, length-prefixed postcard framing with `take_from_bytes` strictness, per-stream 64 KiB default cap, enum-position compat test. | Against a real test ID node: `List`/`Find`/tag round-trips succeed; padded/concatenated/trailing-byte payloads are rejected; variant-reorder fixture fails loudly (ALPN-bump path exercised); concurrent streams multiplex correctly. | +| 4 | **Initiator: byte streaming.** Depends on slice 3. stdin/stdout/stderr-style stream mapping, multiplex + QUIC backpressure, configurable caps. | 4 MiB and 10 MiB fixtures transfer sha-identical both directions through the relay fixture; slow-consumer test proves backpressure (bounded memory); stream teardown is clean on cancel. | +| 5 | **Conversion + WS/WTransport serving (edge).** Depends on slices 3–4. Threshold-triggered postcard→CBOR/MessagePack (variants by name), chunked envelope (§4.5), `fleet id serve-ws` localhost + credentialed non-local, `fleet-id-cbor-v1` negotiation. | Browser-fixture client (no postcard knowledge) completes a value exchange and a >1 MiB chunked transfer with per-chunk sequence + BLAKE3 digest verified; variant-by-name encoding proven against a skew fixture; non-local serve without credentials refused. | +| 6 | **Seam conformance with pass 3 + hardening.** Depends on slice 5 and the pass-3 REST surface. Joint envelope test, error-code catalog, CONNECT-shim + relay-matrix CI, docs. | The §4.5 envelope round-trips through both the fleet socket and the pass-3 REST bridge byte-identical; the error catalog has a test per code; CI covers direct + relay + CONNECT-proxy dial paths; this design's acceptance checklist (§9) is green. | + +## 6. Rollout and rollback + +- **Rollout:** slices land in order; each slice is independently + revertible (feature-flagged initiator modes, defaulting to + proxy-or-binary behavior until slice 3 is verified). Relay and key + changes ride no production traffic until the slice-2 proxy fixture + and slice-1 zeroize test pass in CI. Slice 5's serving socket binds + localhost-only until credentialed non-local auth is proven. The + first live remote-ID read runs verify-only (fetch + compare, no + write) against a non-production ID store. +- **Rollback:** every slice rolls back by flag-flip to the previous + mode (initiator → relay-aware proxy → raw proxy → exec-ID-binary), + with no key material left behind (ephemeral keys die with the + session; no migration to undo). A bad conversion encoding rolls back + by serving postcard-native only (breaking browsers loudly, not + silently corrupting). Chunking/envelope version bumps are additive + (`-v2` alongside `-v1`); `-v1` is removed only after pass 3 confirms + no consumer remains. +- **No-rollback-needed properties:** nothing here writes ID state by + itself (reads and byte moves first); relay config and pkarr bootstrap + are consumed, not operated, so there is no relay to roll back. + +## 7. Verification plan + +1. **Oracle — key lifecycle:** per-session uniqueness, stamp presence + (queue + env), log-absence (grep CI over logs/trip records for + secret material), zeroize fixture, caller-override verbatim use. +2. **Oracle — proxy:** CONNECT-only-proxy fixture proves mode 2 dials + where stock dial dies (probe-2 replay); mode-1 byte-identity on 4/10 + MiB fixtures sha-compared; mismatch/downgrade tests prove fail-closed. +3. **Oracle — postcard:** strict-decode fixtures (padded, concatenated, + truncated) rejected; enum-skew fixture fails loudly; live round-trip + against a pinned ID version passes. +4. **Oracle — streaming:** 4/10 MiB sha-identical both directions; + backpressure bounded-memory proof; cancel-cleanliness. +5. **Oracle — conversion/serving:** browser-fixture (Rust-free client) + completes value + chunked transfers; digest verifies; variant-by-name + proven; non-local auth refused without credentials; envelope + byte-identical through the pass-3 bridge. +6. **Live proof:** sandbox-constrained caller → laptop stock ID node via + own relay, initiated by fleet, sha-identical payload — the probe-2 + topology replayed through the shipped code path, at control-class + throughput expectations (≈0.2 MB/s acknowledged, not a bulk promise). +7. **Regression:** existing pass-1 resolution tests still pass; no + postcard/ALPN change without a version bump; CI matrix covers + direct + relay + CONNECT-proxy dials. + +## 8. Open questions and decisions + +1. **Exact flag/env spellings (`--id-secret`, `FLEET_ID_SECRET`, + `FLEET_ID_NODE_ID`, `--raw/--opaque/--mode`, `serve-ws` bind flags) — + decider: design-mill owner under #10389 (pass-1 slice owner + proposes).** Default: the names used in §§4.1–4.2/4.7 stand until + pass 1 overrules them; pass 1 wins on syntax, this pass wins on + semantics. +2. **Conversion threshold default (1 MiB) and chunk size (256 KiB) — + decider: fleet transport owner (#13752) with ID performance input.** + Default: ship 1 MiB / 256 KiB tunable per call; revisit with + measurements from slice 4–5 fixtures. +3. **CBOR vs MessagePack priority at the browser edge — decider: pass-3 + owner (serving side) with fleet concurrence.** Default: CBOR + preferred, MessagePack accepted; both encode variants by name. +4. **Non-local WS/WTransport credential construction (NodeId-derived + session token shape) — decider: #10357 context-propagation owner + (must compose with `FLEET_CTX_*`), Drew accountable.** Default: no + non-local serving until this is specified and tested; localhost-only + ships first. +5. **Which ID protocols beyond `/iroh-meta/3` the initiator must speak + (blobs/gossip/irpc versions) and their ALPN registry — decider: ID + maintainers, tracked against the iroh-ecosystem record.** + Default: initiator supports `/iroh-meta/3` only; everything else + goes relay-aware-proxy (mode 2) until an explicit per-ALPN slice is + filed and the registry exists. +6. **Relay selection and self-hosted vs public relay policy — + decider: fleet transport owner (#13752), not this pass.** + Default: consume configured relay; this design names no new relay. + +## 9. Record, tracking, and acceptance + +This dated record is the design artifact for code#10391. Queue task +21681 tracks delivery of this design-only slice. Implementation slices +in §5 are proposed, not filed, and no implementation is authorized by +this record. + +**Source-issue acceptance (from #10391), mapped:** + +- Identity/key lifecycle (generation, stamping, env var, storage) — + §4.1. +- Raw-proxy vs initiator modes and when each is chosen (incl. + relay-aware variant) — §4.2. +- Postcard handling and MessagePack/CBOR conversion conditions — §4.4. +- WebSocket/WebTransport serving shape on the fleet side — §4.5, with + the pass-3 seam stated once. + +**Sufficient-design standard, mapped:** + +- [x] Problem + context with evidence — §1. +- [x] Goals and explicit non-goals — §2. +- [x] Alternatives with honest tradeoffs, including do-nothing — §3. +- [x] Chosen approach (interfaces/contracts, data model, security and + capability analysis) — §4. +- [x] Dependency-ordered build slices, lane-sized, each with acceptance + criteria — §5. +- [x] Rollout + rollback plan — §6. +- [x] Verification plan (tests + live proof) — §7. +- [x] Open questions, each with a named decider — §8. +- [x] Recorded as a dated `doc/` record + tracking issue + queue item — + this file, #10391, task 21681. +- [ ] After merge, link this document's permanent GitHub URL from + #10391 and verify the link resolves. + +### Evidence references + +- #10391 (this pass), #10389 (mill parent), #10390 (pass 1), + #10357 (context propagation). +- Iroh probe 2 report (2026-11-15 comment on #10391). +- `doc/2026-11-23T22-00-30Z_research_iroh-ecosystem/` (iroh 1.5.0, + frozen wire, blobs+gossip+irpc toolkit). +- `doc/2026-11-23T21-10-36Z_design_fleet-transport-pooling/` (#13752 + fleet transport & pooling). +- `doc/fleet/mcpx-identity-transport.md` (tsnet decision; pure-Go + constraint contrast; no-silent-downgrade rule). +- `pkgs/id/crates/id-sync/src/protocol.rs` (postcard meta protocol, + ALPN `/iroh-meta/3`, strict-decode + enum-position rules). +- AUDIT-7 tracking: #13873 (lane 6 DESIGN-GAPS, sufficient-design + standard source), #13871 (programme umbrella). diff --git a/doc/fleet-schedule-registry.md b/doc/fleet-schedule-registry.md index 830d2cea12..21d966368d 100644 --- a/doc/fleet-schedule-registry.md +++ b/doc/fleet-schedule-registry.md @@ -183,6 +183,13 @@ resolution 2026-11-22/23 by lane oc-code-04 (same task): main's newer Surface 1 amendments (Felix rows/notes, header left stale) are kept, and this row is re-applied on top. +Surface 1 amended 2026-11-22 by lane xaltha for the goal +developing-today-code-issue-resolution: `fleet-work-loop-hourly` row +added. The loop is a Muse-cron job created 2026-11-22 after the +2026-11-03 full count, so the Surface 1 header count stays stale +until the next full recount. This registration was owed from the +job's creation pass and is recorded late in this amendment's PR. + ## Surface 1 — Muse cron (131 jobs at 2026-11-03 full count; +2 rows since — see Verification) | id | title | cadence | state | owner / scope | prompt/brief pointer | budget | kill criteria | created | last review | @@ -237,6 +244,7 @@ and this row is re-applied on top. | `feed-pulse-23` | | `daily@23:00:00` | enabled | — | `/home/hatch/workspace/system-cron.d/daily/feed-pulse-23__daily@23:00:00_user_current.md` | not recorded | not recorded | not recorded | 2026-11-03 | | `felix-fleet-machine-watchdog` | Fleet machine watchdog: amd-6 health record (30 min) | `interval@30m` | enabled | goal:code-repo-issue-resolution | `/home/hatch/workspace/goals/code-repo-issue-resolution/crons/minutely/felix-fleet-machine-watchdog__interval@30m.md` | not recorded | not recorded | 2026-11-22 | 2026-11-22 | | `fleet-watchdog` | Fleet watchdog — 15m check for stuck, failing, or silent fleet jobs | `interval@15m` | enabled | goal:keep-the-four-repos-healthy | `/home/hatch/workspace/goals/keep-the-four-repos-healthy/crons/minutely/fleet-watchdog__interval@15m.md` | not recorded | not recorded | not recorded | 2026-11-03 | +| `fleet-work-loop-hourly` | Hourly fleet work loop check (xaltha) | `interval@1h` | enabled | goal:developing-today-code-issue-resolution | `/home/hatch/workspace/goals/developing-today-code-issue-resolution/crons/hourly/fleet-work-loop-hourly__interval@1h.md` | not recorded | not recorded | not recorded | 2026-11-22 | | `gemini-carbon-release-watch` | Gemini 4 Carbon — tell Drew when it's really released | `daily@09:12:00` | enabled | goal:keep-the-four-repos-healthy | `/home/hatch/workspace/goals/keep-the-four-repos-healthy/crons/daily/gemini-carbon-release-watch__daily@09:12:00.md` | not recorded | not recorded | not recorded | 2026-11-03 | | `ghcr-org-pat-renewal` | Renew the fleet-build GHCR classic PAT before it expires 2027-02-01 | `runonce@2027-01-15T09:12:00` | enabled | goal:account-connection-campaign-every-service-signed-in-on-muse-s-machine | `/home/hatch/workspace/goals/account-connection-campaign-every-service-signed-in-on-muse-s-machine/crons/runonce/ghcr-org-pat-renewal__runonce@2027-01-15T09:12:00.md` | not recorded | not recorded | not recorded | 2026-11-03 | | `git-hygiene-sweep` | Git hygiene sweep — 4h reconciliation: push finished work, PR orphans, clean idle build artifacts | `interval@4h` | enabled | goal:keep-the-four-repos-healthy | `/home/hatch/workspace/goals/keep-the-four-repos-healthy/crons/hourly/git-hygiene-sweep__interval@4h.md` | not recorded | not recorded | not recorded | 2026-11-03 | @@ -354,7 +362,7 @@ preserved. OpenChamber scheduled tasks remain on the configured `opencode-route` / `workhorse` route. The separate #3026 claimant / executor remains on its own protocol. -### 2b. Laptop systemd user timers (49 listed: 43 enabled, 1 installed-but-disabled; 5 Nix-configured pending deployment; 1 declared in repo pending laptop install) +### 2b. Laptop systemd user timers (50 listed: 44 enabled, 1 installed-but-disabled; 5 Nix-configured pending deployment; 1 declared in repo pending laptop install) The OS-timer half of surface 2. Cadence is the unit's own `OnCalendar`/`OnUnitActiveUSec` spec, read live from `systemctl --user show`. Specs are recorded **complete** — the full effective calendar expression, date **and** time components (e.g. `*-*-* *:*:00`); never truncate a spec to a date-only prefix, because a bare `*-*-*` normalizes to daily at midnight and misstates the cadence (issue #5313). Prompt/brief pointer is the unit file in `~/.config/systemd/user/` (or its Nix store target for linked units). Installed-but-disabled timer units ARE listed in this table and marked `(disabled)` after the unit name: the registry inventories what is installed on the laptop, not only what is currently scheduled, so a disabled unit stays visible until it is uninstalled (reconciled 2026-11-04, issue #5661). @@ -390,6 +398,7 @@ The OS-timer half of surface 2. Cadence is the unit's own `OnCalendar`/`OnUnitAc | `laptop-scratch-sweep.timer` | `OnCalendar=*-*-* 05:35:00` | `laptop-scratch-sweep.service` | laptop (user systemd) | not recorded | not recorded | not recorded | 2026-11-11 | | `laptop-untracked-review.timer` | `OnCalendar=*-*-* 07:37:00` | `laptop-untracked-review.service` | laptop (user systemd) | not recorded | not recorded | not recorded | 2026-11-04 | | `meta-quota-export.timer` | `OnCalendar=*-*-* *:00/15:00` | `meta-quota-export.service` | laptop (user systemd) | not recorded | not recorded | not recorded | 2026-11-05 | +| `model-deprecation-watch-weekly.timer` | `OnCalendar=Mon *-*-* 09:12:00` + `RandomizedDelaySec=10m` | `model-deprecation-watch-weekly.service` | laptop (user systemd; code#14236 / #7013; runs `scripts/model-deprecation-watch-sweep.sh`, snapshots to `~/.local/share/model-deprecation-watch/`) | not recorded | Disable if a scheduled run fails to fetch a majority of surfaces; repair the surface URL or script and rerun before re-enabling | 2026-11-24 | 2026-11-24 | | `openai-cred-watchdog.timer` | `OnCalendar=*-*-* *:00:00` | `openai-cred-watchdog.service` | laptop (user systemd) | not recorded | not recorded | not recorded | 2026-11-04 | | `opencode-go-seating-guard.timer` (Nix-configured; not yet loaded) | `OnCalendar=hourly (not live-verified)` | `opencode-go-seating-guard.service` | laptop (user systemd; code#5611) | not recorded | not recorded | 2026-11-08 | 2026-11-08 | | `openclaw-backup.timer` | `OnCalendar=*-*-* 04:05:00` | `openclaw-backup.service` | laptop (user systemd) | not recorded | not recorded | not recorded | 2026-11-04 | diff --git a/doc/model-deprecation-watch.md b/doc/model-deprecation-watch.md new file mode 100644 index 0000000000..f192545f6e --- /dev/null +++ b/doc/model-deprecation-watch.md @@ -0,0 +1,72 @@ +# Model deprecation watch — sources registry + seed records + +Rebuilt 2026-11-24 (developing-today/code#14236, follow-on of #7013; first sweep task 22909). +Prior v1 artifacts (tasks 11448/18517, goal-workspace `hidden_files`) were unverifiable +on every reachable surface, so this file is the registry of record. It lives in the +repo because the goal workspace proved non-durable. + +Cadence: weekly, Mondays 09:12 America/Chicago (`model-deprecation-watch-weekly.timer`, +Surface 2b), plus event-driven runs on flagship launches. Registry row in +`doc/fleet-schedule-registry.md` is maintained in the same pass as any schedule change. + +## 1. Sources registry + +| Provider | Announcement / lifecycle surface | Checked 2026-11-24 | Notes | +|---|---|---|---| +| Anthropic | https://platform.claude.com/docs/en/about-claude/model-deprecations | live | Full status table + dated history; ≥60-day notice commitment; partner clouds (Bedrock, Google-managed) set own dates | +| Anthropic | https://platform.claude.com/docs/en/about-claude/models/overview | live | Current lineup + per-model retirement floor | +| OpenAI | https://platform.openai.com/docs/deprecations | live | Upcoming + past tables with shutdown/notice dates; `shutdown_date` also exposed via `GET /v1/models` for programmatic checks | +| Google | https://ai.google.dev/gemini-api/docs/models + https://ai.google.dev/gemini-api/docs/deprecations | live (models page) | Deprecation callouts inline on models page; `latest`-alias hot-swaps get 2-week email notice | +| DeepSeek | https://api-docs.deepseek.com/quick_start/pricing | live | No dated table; retirements noted inline (legacy names still accepted, served by successor) | +| Mistral | https://docs.mistral.ai/getting-started/models/models_overview + https://docs.mistral.ai/inference/model-lifecycle | live (overview) | Full deprecated/retired table with deprecation→retirement windows | +| Meta | none found | gap (unchanged) | No Llama lifecycle surface identified; gap flagged as before | + +## 2. Seed records (from #7013 design, Drew 2026-10-21) + +### S1. Claude Haiku 4.5 — consumer-surface deprecation +- State 2026-11-24: `claude-haiku-4-5-20251001` is **Active** on the Claude API with + retirement "not sooner than October 15, 2026" — i.e. past its floor; retireable + at any time. The original seed concern (deprecated everywhere except + business/enterprise tiers and some API providers) is consistent with Anthropic's + partner-cloud carve-outs (Bedrock / Google-managed set own dates). +- Fleet exposure: no Haiku 4.5 pin found in fleet route/pool config; Claude legs + ride current-generation aliases. Exposure: none. +- Action: none. Re-check weekly; escalate to plan-math review if a dated + deprecation lands. + +### S2. ChatGPT models — consumer-surface deprecation, API survival +- State 2026-11-24: OpenAI's table confirms the pattern at scale — chat variants + (`gpt-5.1-chat-latest`, `gpt-5-chat-latest`) already shut down Jul 23 2026, while + API snapshots persist to their shutdown dates. Current upcoming: `gpt-5` family + shutdown **Dec 11 2026**; GPT-4o / 4.1 snapshots **Jan 14 2027**. +- Fleet exposure: fleet OpenAI catalog still defines `gpt-5.4`, `gpt-5.5`, + `gpt-5.6-*`, and **`gpt-5.3-codex` (shutdown Apr 1 2027, replacement `gpt-6-sol`)**. + → plan-math review action filed with this sweep (see §4, A1). +- Action: A1 open. + +## 3. First-sweep deltas (2026-11-24, all surfaces fetched live) + +| # | Finding | Fleet relevance | Disposition | +|---|---|---|---| +| D1 | Anthropic `claude-opus-4-5-20251101` deprecated **2026-11-23** (yesterday), retirement Jan 22 2027 → `claude-opus-5-5` | No 4.5 pin in fleet config | Note only | +| D2 | Anthropic `claude-sonnet-4-5-20250929` retires **Nov 30 2026** (6 days) → `claude-sonnet-5-5` | No 4.5 pin in fleet config | Note only; confirms 4.x prunes are in flight | +| D3 | Anthropic Haiku 4.5 past its retirement floor (Oct 15 2026) but still Active | Seed S1 unchanged | Keep on weekly watch | +| D4 | OpenAI `gpt-5` / mini / nano / pro shutdown **Dec 11 2026** | Catalog bucket comments reference gpt-5 family for free-tier buckets | Verify bucket mapping still valid after shutdown (A1) | +| D5 | OpenAI `gpt-5.3-codex` shutdown **Apr 1 2027** → `gpt-6-sol` | Seated in OpenAI catalog definitions | Plan-math review (A1) | +| D6 | Google `gemini-2.5-flash` / `gemini-2.5-pro` auto-route **Dec 1 2026** (7 days) → 3.5-flash-lite / 3.8-flash | Fleet already unseated 2.5 line (404 for new users, per config comment) | Confirms existing seating; no action | +| D7 | Google Imagen 4 shut down; several 2.0/3.x previews shut down | No fleet use | Note only | +| D8 | DeepSeek legacy `deepseek-v4-flash` names retired, served by V4.1-Flash-1017 at Flash price | No fleet DeepSeek pin checked | Note only | +| D9 | Mistral deprecated table (Medium 3.x, Large 3, Small 3.x, Devstral/Magistral 1.x lines) | No fleet Mistral pins | Note only | + +## 4. Plan-math review actions + +- **A1 (open, from this sweep):** reconcile fleet OpenAI catalog seats against the + Dec 11 2026 (`gpt-5` family) and Apr 1 2027 (`gpt-5.3-codex`) shutdowns; confirm + free-tier bucket mapping in `openai-payg-free` comments still valid post-shutdown. +- Cadence rule: every future sweep that touches a model in a fleet pool/route/plan + files the same kind of action here and links it on #7013. + +## 5. Sweep log + +- 2026-11-24 (task 22909): all six provider surfaces fetched live; seed records + updated; D1–D9 recorded; A1 filed. Posted on #7013. diff --git a/pkgs/atlas-search/crates/atlas-core/Cargo.toml b/pkgs/atlas-search/crates/atlas-core/Cargo.toml index a9d259e96e..e3a8c325ac 100644 --- a/pkgs/atlas-search/crates/atlas-core/Cargo.toml +++ b/pkgs/atlas-search/crates/atlas-core/Cargo.toml @@ -9,12 +9,16 @@ description = "Atlas search semantics as a library: filters and sensitivity ceil [dependencies] atlas-embed = { path = "../atlas-embed" } atlas-proto = { path = "../atlas-proto" } +arrow = "58" base64 = "0.23" blake3 = "1" +futures = "0.3" +lance = { version = "14", default-features = false } rusqlite = { version = "0.42", features = ["bundled", "functions"] } serde = { version = "1", features = ["derive"] } serde_json = { version = "1", features = ["preserve_order"] } sha2 = "0.11" +tokio = { version = "1", features = ["rt", "time", "net"] } unicode-normalization = "0.1" thiserror = "2" ureq = { version = "3", features = ["rustls"] } diff --git a/pkgs/atlas-search/crates/atlas-core/src/memory.rs b/pkgs/atlas-search/crates/atlas-core/src/memory.rs index 8e3fc0442c..84232341cd 100644 --- a/pkgs/atlas-search/crates/atlas-core/src/memory.rs +++ b/pkgs/atlas-search/crates/atlas-core/src/memory.rs @@ -23,11 +23,11 @@ //! `chunks_raw` write path every staged unit uses; promotion and //! search are the existing aggregator and fan-out, unchanged. //! -//! Out of scope (slice 1b, the #8622 remainder): the native LanceDB -//! reader, idempotency keyed on id+updated_at, and the -//! rebuild-from-sources proof. Until 1b, this connector stages a -//! unit once and the unit is then promoted — promotion is the -//! terminal write, as for every staged unit. +//! Slice 1b (developing-today/code#14039) adds the native reader +//! [`read_lancedb_store`], which opens the store directly with the +//! trimmed `lance` crate (no second vector store), and +//! [`sync_memory_entries`], which restages only the entries whose +//! content changed since the last sync (idempotent by source_ref). use std::path::Path; @@ -310,3 +310,147 @@ pub fn stage_memory_export_in_db( let conn = open(db)?; stage_memory_export(&conn, unit_id, entries, now) } + +/// What one [`sync_memory_entries`] run did to a unit. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub struct SyncReport { + /// Entries staged for the first time. + pub added: usize, + /// Entries whose recorded content changed, restaged in place. + pub restaged: usize, + /// Entries already staged with identical content — untouched. + pub unchanged: usize, +} + +/// Read the memory-lancedb store at `path` natively: open the +/// `memories.lance` dataset with the `lance` crate and map its +/// `id`, `text`, `agentId`, `category`, `importance` and `createdAt` +/// columns onto [`MemoryEntry`]. The `vector` column is never read. +/// A missing required column or an empty id/text is a loud error. +pub async fn read_lancedb_store(path: &Path) -> Result> { + use arrow::array::{Array, ArrayRef, RecordBatch}; + use arrow::compute::cast; + use arrow::datatypes::DataType; + + let uri = path + .to_str() + .ok_or_else(|| Error::fatal("memory connector: store path is not valid UTF-8"))?; + let dataset = lance::Dataset::open(uri) + .await + .map_err(|e| Error::backend(format!("memory connector: opening {uri}: {e}")))?; + let batch: RecordBatch = dataset + .scan() + .try_into_batch() + .await + .map_err(|e| Error::backend(format!("memory connector: scanning {uri}: {e}")))?; + + let column = |name: &str| -> Result> { + match batch.column_by_name(name) { + None => Ok(None), + Some(col) => cast(col, &DataType::Utf8) + .map(Some) + .map_err(|e| Error::fatal(format!("memory connector: column `{name}`: {e}"))), + } + }; + let numbers = |name: &str| -> Result> { + match batch.column_by_name(name) { + None => Ok(None), + Some(col) => cast(col, &DataType::Float64) + .map(Some) + .map_err(|e| Error::fatal(format!("memory connector: column `{name}`: {e}"))), + } + }; + let id = column("id")? + .ok_or_else(|| Error::fatal("memory connector: store has no `id` column"))?; + let text = column("text")? + .ok_or_else(|| Error::fatal("memory connector: store has no `text` column"))?; + let agent = column("agentId")?; + let category = column("category")?; + let importance = numbers("importance")?; + let created = numbers("createdAt")?; + + fn str_at(col: &Option, i: usize) -> Option { + let arr = col.as_ref()?.as_any().downcast_ref::()?; + (!arr.is_null(i)).then(|| arr.value(i).to_string()) + } + fn num_at(col: &Option, i: usize) -> Option { + let arr = col.as_ref()?.as_any().downcast_ref::()?; + (!arr.is_null(i)).then(|| arr.value(i)) + } + + let mut out = Vec::with_capacity(batch.num_rows()); + for i in 0..batch.num_rows() { + let row_id = str_at(&Some(id.clone()), i) + .filter(|s| !s.is_empty()) + .ok_or_else(|| Error::fatal(format!("memory connector: row {i} has no `id`")))?; + let row_text = str_at(&Some(text.clone()), i) + .filter(|s| !s.is_empty()) + .ok_or_else(|| { + Error::fatal(format!("memory connector: row {row_id} has no `text`")) + })?; + out.push(MemoryEntry { + id: row_id, + text: row_text, + agent: str_at(&agent, i), + category: str_at(&category, i), + importance: num_at(&importance, i), + created_at_ms: num_at(&created, i), + sensitivity: Tier::Internal, + }); + } + Ok(out) +} + +/// Blocking form of [`read_lancedb_store`] for the CLI and tests. +pub fn read_lancedb_store_blocking(path: &Path) -> Result> { + tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .map_err(|e| Error::backend(format!("memory connector: tokio runtime: {e}")))? + .block_on(read_lancedb_store(path)) +} + +/// Sync entries into a unit, idempotently: an entry whose source_ref +/// is already staged with the same text is skipped; one whose text +/// changed is restaged (its old item and chunks removed first); a new +/// one is staged. Re-running with the same export changes nothing. +pub fn sync_memory_entries( + conn: &Connection, + unit_id: &str, + entries: &[MemoryEntry], + now: &str, +) -> Result { + check_stage_schema(conn)?; + let mut report = SyncReport::default(); + for entry in entries { + let source = entry.source_ref(); + let existing: Vec<(i64, String)> = { + let mut stmt = conn + .prepare("SELECT id, text FROM items WHERE unit_id = ?1 AND source = ?2") + .map_err(|e| Error::backend(format!("memory connector: {e}")))?; + let rows = stmt + .query_map(params![unit_id, source], |r| Ok((r.get(0)?, r.get(1)?))) + .map_err(|e| Error::backend(format!("memory connector: {e}")))?; + rows.collect::>() + .map_err(|e| Error::backend(format!("memory connector: {e}")))? + }; + match existing.as_slice() { + [] => { + stage_memory_entry(conn, unit_id, entry, now)?; + report.added += 1; + } + [(_, text)] if *text == entry.text => report.unchanged += 1, + old => { + for (item_id, _) in old { + conn.execute("DELETE FROM chunks_raw WHERE item_id = ?1", params![item_id]) + .map_err(|e| Error::backend(format!("memory connector: {e}")))?; + conn.execute("DELETE FROM items WHERE id = ?1", params![item_id]) + .map_err(|e| Error::backend(format!("memory connector: {e}")))?; + } + stage_memory_entry(conn, unit_id, entry, now)?; + report.restaged += 1; + } + } + } + Ok(report) +} diff --git a/pkgs/atlas-search/crates/atlas-core/tests/memory.rs b/pkgs/atlas-search/crates/atlas-core/tests/memory.rs index 2cb1d2f35f..290dede58e 100644 --- a/pkgs/atlas-search/crates/atlas-core/tests/memory.rs +++ b/pkgs/atlas-search/crates/atlas-core/tests/memory.rs @@ -266,3 +266,103 @@ fn promoted_agent_memory_is_searchable_by_the_fanout() { assert_eq!(hits[0].chunk_id, 1, "the transcript memory ranks first"); assert!(hits[0].dist < hits[1].dist); } + +/// Write a synthetic memory-lancedb-shaped dataset (the store's own +/// columns, including a vector the reader must ignore) into `path`. +fn write_fixture_store(path: &Path) { + use std::sync::Arc; + use arrow::array::{FixedSizeListArray, Float64Array, RecordBatch, RecordBatchIterator, StringArray}; + use arrow::datatypes::{DataType, Field, Schema}; + + let vec_field = Arc::new(Field::new("item", DataType::Float32, true)); + let schema = Arc::new(Schema::new(vec![ + Field::new("id", DataType::Utf8, false), + Field::new("text", DataType::Utf8, false), + Field::new("vector", DataType::FixedSizeList(vec_field.clone(), 3), true), + Field::new("importance", DataType::Float64, true), + Field::new("category", DataType::Utf8, true), + Field::new("createdAt", DataType::Float64, true), + Field::new("agentId", DataType::Utf8, true), + ])); + let values = arrow::array::Float32Array::from(vec![0.25f32, 0.5, 0.75, 0.1, 0.2, 0.3]); + let vectors = FixedSizeListArray::new(vec_field, 3, Arc::new(values), None); + let batch = RecordBatch::try_new( + schema.clone(), + vec![ + Arc::new(StringArray::from(vec!["mem-transcript", "mem-deploy"])), + Arc::new(StringArray::from(vec![ + "Continue the current task from the existing transcript, preserving completed work.", + "The deploy window opens on Sunday evening after the freeze lifts.", + ])), + Arc::new(vectors), + Arc::new(Float64Array::from(vec![0.9, 0.4])), + Arc::new(StringArray::from(vec!["fact", "fact"])), + Arc::new(Float64Array::from(vec![1_763_000_000_000.0, 1_763_100_000_000.0])), + Arc::new(StringArray::from(vec!["main", "main"])), + ], + ) + .unwrap(); + let reader = RecordBatchIterator::new(vec![Ok(batch)], schema); + let uri = path.to_str().unwrap().to_string(); + tokio::runtime::Runtime::new().unwrap().block_on(async { + lance::Dataset::write(reader, &uri, None).await.unwrap(); + }); +} + +/// Oracle: the native reader maps a `.lance` dataset's columns onto +/// the same entries the JSON export parser produces, and never reads +/// the vector column. +#[test] +fn native_reader_reads_a_lancedb_store_without_its_vectors() { + let dir = temp_dir("native"); + let store = dir.join("memories.lance"); + write_fixture_store(&store); + + let mut native = atlas_core::memory::read_lancedb_store_blocking(&store).unwrap(); + native.sort_by(|a, b| a.id.cmp(&b.id)); + let mut json = parse_memory_export(EXPORT).unwrap(); + json.sort_by(|a, b| a.id.cmp(&b.id)); + assert_eq!(native, json); +} + +/// Oracle: rebuild-from-sources — staging the native read into a +/// fresh unit and promoting it yields a searchable shard with the +/// same hits as the export path (the staged corpus is the source). +#[test] +fn native_store_rebuilds_the_index_from_sources() { + let dir = temp_dir("rebuild"); + let store = dir.join("memories.lance"); + write_fixture_store(&store); + let (registry, agent_db) = register(&dir); + let entries = atlas_core::memory::read_lancedb_store_blocking(&store).unwrap(); + stage_memory_export_in_db(&agent_db, AGENT_MEMORY_UNIT, &entries, NOW).unwrap(); + let report = embed_unit_into_shard( + ®istry, AGENT_MEMORY_UNIT, &dir.join("shards"), "agent-memory", &KeywordEmbedder, NOW, + ) + .unwrap(); + assert_eq!(report.items, 2); + assert_eq!(report.chunks, 2); +} + +/// Oracle: idempotency — a second sync of an unchanged store restages +/// nothing; a changed text restages only that entry. +#[test] +fn sync_is_idempotent_and_restages_only_changed_entries() { + let dir = temp_dir("sync"); + let (_registry, agent_db) = register(&dir); + let conn = rusqlite::Connection::open(&agent_db).unwrap(); + let mut entries = parse_memory_export(EXPORT).unwrap(); + + let first = atlas_core::memory::sync_memory_entries(&conn, AGENT_MEMORY_UNIT, &entries, NOW).unwrap(); + assert_eq!((first.added, first.restaged, first.unchanged), (2, 0, 0)); + + let again = atlas_core::memory::sync_memory_entries(&conn, AGENT_MEMORY_UNIT, &entries, NOW).unwrap(); + assert_eq!((again.added, again.restaged, again.unchanged), (0, 0, 2)); + + entries[1].text = "The deploy window moved to Monday.".to_string(); + let changed = atlas_core::memory::sync_memory_entries(&conn, AGENT_MEMORY_UNIT, &entries, NOW).unwrap(); + assert_eq!((changed.added, changed.restaged, changed.unchanged), (0, 1, 1)); + + let items = list_staged_items_in_db(&agent_db, Some(AGENT_MEMORY_UNIT)).unwrap(); + assert_eq!(items.len(), 2, "restaging replaces the old item"); +} diff --git a/pkgs/fleet/crates/fleet-cert/src/chain.rs b/pkgs/fleet/crates/fleet-cert/src/chain.rs index 560d6bea15..d4757bb021 100644 --- a/pkgs/fleet/crates/fleet-cert/src/chain.rs +++ b/pkgs/fleet/crates/fleet-cert/src/chain.rs @@ -18,7 +18,7 @@ use crate::algorithm::AlgorithmId; use crate::bundle::sha256_hex; use crate::error::{CertError, Result}; use crate::timeparse::Rfc3339; -use serde::Serialize; +use serde::{Deserialize, Serialize}; use x509_parser::extensions::ParsedExtension; use x509_parser::prelude::*; @@ -243,7 +243,7 @@ impl TrustSelection { } /// One named check in a validation report. -#[derive(Debug, Clone, Serialize)] +#[derive(Debug, Clone, Serialize, Deserialize)] pub struct Check { pub name: String, pub ok: bool, diff --git a/pkgs/fleet/crates/fleet-cert/src/cli.rs b/pkgs/fleet/crates/fleet-cert/src/cli.rs index f652a6a53f..9163c6d610 100644 --- a/pkgs/fleet/crates/fleet-cert/src/cli.rs +++ b/pkgs/fleet/crates/fleet-cert/src/cli.rs @@ -35,6 +35,7 @@ Groups and verbs (spec §6.1 tree; status as built): leaf issue | inspect | list chain build | test bundle inspect + publish plan | verify (apply | status deferred, production-gated) profile list | show algorithms list | describe explain [topic] @@ -226,6 +227,7 @@ fn run_inner(args: &[String]) -> Result { "leaf" => leaf_cmd(rest, json_out), "chain" => chain_cmd(rest, json_out), "bundle" => bundle_cmd(rest, json_out), + "publish" => publish_cmd(rest, json_out), "profile" => profile_cmd(rest, json_out), "algorithms" => algorithms_cmd(rest, json_out), "explain" => explain_cmd(rest, json_out), @@ -687,6 +689,114 @@ fn bundle_cmd(args: &[String], json_out: bool) -> Result { } } +// ---------------------------------------------------------------- publish (slice 1: plan + verify read-only) + +fn publish_cmd(args: &[String], json_out: bool) -> Result { + let verb = args.first().map(|s| s.as_str()).unwrap_or(""); + let rest = &args[1.min(args.len())..]; + match verb { + "plan" => { + let p = parse_args( + rest, + &["bundle", "host", "aia-base-url", "dns-target", "format", "out"], + &["json"], + )?; + let dir = p + .get("bundle") + .map(|s| s.to_string()) + .or_else(|| p.positional(0).map(|s| s.to_string())) + .ok_or_else(|| CertError::usage("publish plan needs a bundle directory"))?; + // --aia-base-url overrides --host when both are given. + let host = p + .get("aia-base-url") + .map(|s| s.to_string()) + .or_else(|| p.get("host").map(|s| s.to_string())) + .unwrap_or_else(|| crate::publish::DEFAULT_PUBLISH_HOST.to_string()); + let req = crate::model::PublishPlanRequest { + bundle: PathBuf::from(&dir), + host, + dns_target: p.get("dns-target").map(|s| s.to_string()), + }; + let plan = crate::publish::plan_bundle(&req)?; + let format = p.get("format").unwrap_or("text").to_ascii_lowercase(); + let value = serde_json::to_value(&plan) + .map_err(|e| CertError::engine(e.to_string()))?; + let text = crate::publish::render_plan_text(&plan); + let out_text = match format.as_str() { + "json" => serde_json::to_string_pretty(&value) + .map_err(|e| CertError::engine(e.to_string()))?, + "yaml" | "yml" => crate::publish::render_plan_yaml(&plan), + "text" => text.clone(), + other => { + return Err(CertError::usage(format!( + "unknown --format '{other}' (text | json | yaml)" + ))); + } + }; + if let Some(out) = p.get("out") { + std::fs::write(out, format!("{out_text}\n"))?; + } + if format == "yaml" && !json_out { + print!("{out_text}\n"); + return Ok(0); + } + Ok(emit(json_out, format!("{text}"), value)) + } + "verify" => { + let p = parse_args(rest, &["bundle", "published-dir", "host"], &["json"])?; + let dir = p + .get("bundle") + .map(|s| s.to_string()) + .or_else(|| p.positional(0).map(|s| s.to_string())) + .ok_or_else(|| CertError::usage("publish verify needs a bundle directory"))?; + let pub_dir = p + .get("published-dir") + .map(|s| s.to_string()) + .or_else(|| p.positional(1).map(|s| s.to_string())) + .ok_or_else(|| { + CertError::usage( + "publish verify needs --published-dir (read-only local check)", + ) + })?; + let req = crate::model::PublishVerifyRequest { + bundle: PathBuf::from(&dir), + published_dir: PathBuf::from(&pub_dir), + host: p.get("host").map(|s| s.to_string()), + }; + let report = crate::publish::verify_bundle(&req)?; + let mut text = format!( + "Publish verify: {} against {}\n", + report.bundle, report.published_dir + ); + for c in &report.checks { + text.push_str(&format!( + " [{}] {} — {}\n", + if c.ok { "ok" } else { "FAIL" }, + c.name, + c.detail + )); + } + text.push_str(&format!( + " result: {}\n", + if report.valid { "IN SYNC" } else { "OUT OF SYNC" } + )); + let value = serde_json::to_value(&report) + .map_err(|e| CertError::engine(e.to_string()))?; + let code = emit(json_out, text, value); + Ok(if report.valid { code } else { 1 }) + } + "apply" | "status" | "stage" | "check" | "commit" | "rollback" | "render" => { + Err(CertError::policy(format!( + "publish {verb} is deferred to a later production-gated slice (per the #9155 gate map): \ + slice 1 implements plan + verify read-only only; never executes against live endpoints without gate clearance" + ))) + } + other => Err(CertError::usage(format!( + "unknown publish verb '{other}' (plan | verify; apply | status are a later gated slice)" + ))), + } +} + fn list_cmd(args: &[String], json_out: bool, want: BundleType) -> Result { let p = parse_args(args, &["dir"], &["json"])?; let dir = p.get("dir").unwrap_or(".").to_string(); @@ -854,8 +964,8 @@ const NOT_BUILT: &[(&str, &str)] = &[ "OCSP — only behind a functional responder (spec §4.3)", ), ( - "publish", - "AIA/CDP publication machinery (spec §13 phase F)", + "publish apply/status", + "live AIA/CDP publication apply + status (production-gated follow-up; slice 1 ships plan + verify read-only)", ), ("dns", "DNS plan/render/verify (spec §24.7)"), ( @@ -973,7 +1083,7 @@ fn doctor_cmd(_args: &[String], json_out: bool) -> Result { " openssl (independent validator): {}\n", openssl.as_deref().unwrap_or("not found") )); - text.push_str(" built: root, issuer, leaf, chain, bundle (inspect), profile (list/show), algorithms (list/describe), explain, doctor\n"); + text.push_str(" built: root, issuer, leaf, chain, bundle (inspect), publish (plan/verify read-only), profile (list/show), algorithms (list/describe), explain, doctor\n"); text.push_str(" not built yet (tracked as child issues under #9157):\n"); for (name, what) in NOT_BUILT { text.push_str(&format!(" {name} — {what}\n")); @@ -981,7 +1091,7 @@ fn doctor_cmd(_args: &[String], json_out: bool) -> Result { let value = json!({ "engine_self_test": algo_results.iter().map(|(i, ok)| json!({"algorithm": i.name, "ok": ok})).collect::>(), "openssl": openssl, - "built": ["root", "issuer", "leaf", "chain", "bundle-inspect", "profile-list/show", "algorithms-list/describe", "explain", "doctor"], + "built": ["root", "issuer", "leaf", "chain", "bundle-inspect", "publish-plan/verify", "profile-list/show", "algorithms-list/describe", "explain", "doctor"], "not_built": NOT_BUILT.iter().map(|(n, w)| json!({"surface": n, "scope": w})).collect::>(), }); let code = emit(json_out, text, value); diff --git a/pkgs/fleet/crates/fleet-cert/src/lib.rs b/pkgs/fleet/crates/fleet-cert/src/lib.rs index 911c06bab2..5037c0c56a 100644 --- a/pkgs/fleet/crates/fleet-cert/src/lib.rs +++ b/pkgs/fleet/crates/fleet-cert/src/lib.rs @@ -41,6 +41,7 @@ pub mod graph; pub mod model; pub mod naming; pub mod profile; +pub mod publish; pub mod timeparse; pub use error::{CertError, Result}; diff --git a/pkgs/fleet/crates/fleet-cert/src/model.rs b/pkgs/fleet/crates/fleet-cert/src/model.rs index 96b59ffbdf..e2bc1f471d 100644 --- a/pkgs/fleet/crates/fleet-cert/src/model.rs +++ b/pkgs/fleet/crates/fleet-cert/src/model.rs @@ -98,8 +98,7 @@ pub struct IssuerCreateRequest { pub private_store: Option, } -/// `cert leaf issue` (§§6.2, 24.6). -#[derive(Debug, Clone)] +/// `cert leaf issue` (§§6.2, 24.6).#[derive(Debug, Clone)] pub struct LeafIssueRequest { /// The issuer bundle directory. pub issuer_bundle: PathBuf, @@ -266,6 +265,26 @@ pub struct BundleManifest { pub warnings: Vec, } +/// `cert publish plan` (§4.4): read-only publication rendering. +/// Never touches live endpoints; `host` is the proposed +/// distribution host (§4.1) and `dns_target` the optional operator +/// IP that makes the DNS record executable. +#[derive(Debug, Clone)] +pub struct PublishPlanRequest { + pub bundle: PathBuf, + pub host: String, + pub dns_target: Option, +} + +/// `cert publish verify` (§4.4/§24.7): read-only mirror check of a +/// local published directory against the bundle manifest. +#[derive(Debug, Clone)] +pub struct PublishVerifyRequest { + pub bundle: PathBuf, + pub published_dir: PathBuf, + pub host: Option, +} + #[cfg(test)] mod tests { use super::*; diff --git a/pkgs/fleet/crates/fleet-cert/src/publish.rs b/pkgs/fleet/crates/fleet-cert/src/publish.rs new file mode 100644 index 0000000000..d5903f9e53 --- /dev/null +++ b/pkgs/fleet/crates/fleet-cert/src/publish.rs @@ -0,0 +1,359 @@ +//! Publication planning and verification (spec §4 + §3.5, +//! program phase §13 F; tree §6.1). +//! +//! Governing-section note (slice-1 resolution for #13723 vs #9157): +//! `cli.rs` historically labelled `publish` as "§13 phase F" +//! machinery while the issue scopes to "§3.5 distribution points". +//! Both are true and neither contradicts the other: +//! - §4 (esp. §4.4) defines the publication manifest contract +//! (`publish-plan.yaml`, schema `fleet.pki.publish/v1`) and the +//! AIA/CDP/OCSP distribution rules; +//! - §3.5 defines what gets distributed (root trust bundles such as +//! `public/bundles/roots-all.pem` plus per-algorithm roots and +//! cross-certificates); +//! - §13 phase F is the program phase that schedules this work, +//! not a competing spec section. +//! This module implements the read-only half: `plan` renders the +//! publication plan without touching live points, `verify` checks a +//! published mirror read-only. `apply`/`status` (live mutation and +//! live state) are explicitly deferred to a later production-gated +//! slice per the #9155 gate map and must never execute here. + +use crate::bundle::load_bundle; +use crate::chain::Check; +use crate::error::{CertError, Result}; +use crate::model::{PublishPlanRequest, PublishVerifyRequest}; +use crate::timeparse::Rfc3339; +use serde::{Deserialize, Serialize}; +use std::path::Path; + +/// Schema id for the §4.4 publication plan. +pub const PUBLISH_SCHEMA: &str = "fleet.pki.publish/v1"; + +/// Default distribution host proposal (§4.1: `pki.developing.today` +/// is a proposed convention, not an assertion it exists). +pub const DEFAULT_PUBLISH_HOST: &str = "pki.developing.today"; + +/// One publishable artifact: a public bundle file plus where it must +/// be served from and with what MIME type (§4.4 `artifacts`, +/// §24.7 MIME rules). +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] +pub struct PublishArtifact { + /// Bundle-relative source path (e.g. `public/bundles/roots-all.pem`). + pub source: String, + /// Target HTTP URL (immutable object URL, never a bare host). + pub url: String, + /// `application/pkix-cert` | `application/pkix-crl` | + /// `application/pkcs7-mime`. + pub media_type: String, + pub visibility: String, + pub sha256: String, + pub bytes: u64, +} + +/// One DNS change proposal (§4.4 `records`). +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] +pub struct DnsRecord { + #[serde(rename = "type")] + pub record_type: String, + pub name: String, + pub ttl: u32, + pub value: String, + pub action: String, +} + +/// The §4.4 publication plan. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct PublishPlan { + pub schema: String, + pub bundle: String, + pub bundle_id: String, + pub bundle_type: String, + pub host: String, + pub base_url: String, + pub artifacts: Vec, + pub dns_records: Vec, + pub prerequisites: Vec, + pub generated_at: Rfc3339, +} + +/// Verify report: one check per planned artifact plus a manifest +/// checksum gate. Oracle: the bundle manifest's own SHA-256 index +/// (§7.1) — a mirror file must byte-match the manifest. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct PublishVerifyReport { + pub bundle: String, + pub published_dir: String, + pub valid: bool, + pub checks: Vec, +} + +/// MIME type for a published object path (§24.7). +pub fn media_type_for(path: &str) -> &'static str { + let lower = path.to_ascii_lowercase(); + if lower.ends_with(".p7c") || lower.ends_with(".p7b") { + "application/pkcs7-mime" + } else if lower.ends_with(".crl") + || lower.ends_with(".crl.pem") + || lower.ends_with(".crl.der") + { + "application/pkix-crl" + } else { + "application/pkix-cert" + } +} + +/// URL path for a bundle-relative source: strip the leading +/// `public/` so `public/bundles/roots-all.pem` serves at +/// `http:///bundles/roots-all.pem` (§4.4 example shape). +pub fn url_path_for(source: &str) -> &str { + source.strip_prefix("public/").unwrap_or(source) +} + +fn normalize_host(req_host: &str) -> String { + let h = req_host.trim().trim_end_matches('/'); + if h.contains("://") { + // Caller passed a full base URL as host; keep it verbatim. + h.to_string() + } else { + h.to_string() + } +} + +/// Render the publication plan read-only: loads the bundle (which +/// verifies its §7.1 checksums) and enumerates public files. Never +/// touches the network or any live endpoint. +pub fn plan_bundle(req: &PublishPlanRequest) -> Result { + let bundle = load_bundle(&req.bundle)?; + let host = normalize_host(&req.host); + let base_url = if host.contains("://") { + host.clone() + } else { + format!("http://{host}") + }; + let mut artifacts = Vec::new(); + for f in &bundle.manifest.files { + if f.visibility != "public" { + continue; + } + let url_path = url_path_for(&f.path); + artifacts.push(PublishArtifact { + source: f.path.clone(), + url: format!("{}/{}", base_url.trim_end_matches('/'), url_path), + media_type: media_type_for(&f.path).to_string(), + visibility: f.visibility.clone(), + sha256: f.sha256.clone(), + bytes: f.bytes, + }); + } + artifacts.sort_by(|a, b| a.source.cmp(&b.source)); + let (dns_records, mut prerequisites) = match &req.dns_target { + Some(ip) => ( + vec![DnsRecord { + record_type: "A".to_string(), + name: format!("{host}.").trim_start_matches("http://").trim_start_matches("https://").to_string(), + ttl: 3600, + value: ip.clone(), + action: "conditional-create".to_string(), + }], + vec![ + "Serve each artifact at its exact URL with the listed content-type; no redirects for AIA/CDP paths.".to_string(), + ], + ), + None => ( + Vec::new(), + vec![ + "Replace placeholder DNS target; never publish a literal placeholder (§4.4).".to_string(), + "Provide --dns-target to render an executable A record.".to_string(), + ], + ), + }; + prerequisites.push( + "Publishing is not equivalent to DNS changes; validate reachability and content-type after upload.".to_string(), + ); + Ok(PublishPlan { + schema: PUBLISH_SCHEMA.to_string(), + bundle: req.bundle.display().to_string(), + bundle_id: bundle.manifest.bundle_id.clone(), + bundle_type: bundle.manifest.bundle_type.as_str().to_string(), + host: host.clone(), + base_url, + artifacts, + dns_records, + prerequisites, + generated_at: Rfc3339::now(), + }) +} + +/// Verify a published mirror read-only: every public bundle file +/// must exist under `published_dir` at its URL path with identical +/// SHA-256. Never writes, never fetches over the network. +pub fn verify_bundle(req: &PublishVerifyRequest) -> Result { + let bundle = load_bundle(&req.bundle)?; + let plan_req = PublishPlanRequest { + bundle: req.bundle.clone(), + host: req.host.clone().unwrap_or_else(|| DEFAULT_PUBLISH_HOST.to_string()), + dns_target: None, + }; + let plan = plan_bundle(&plan_req)?; + let mut checks = vec![Check { + name: "manifest-checksums".into(), + ok: true, + detail: format!("{} files verified in source bundle", bundle.manifest.files.len()), + }]; + for art in &plan.artifacts { + let rel = url_path_for(&art.source); + let path = req.published_dir.join(rel); + let name = format!("published:{}", art.source); + match std::fs::read(&path) { + Ok(bytes) => { + let digest = crate::bundle::sha256_hex(&bytes); + if digest == art.sha256 && bytes.len() as u64 == art.bytes { + checks.push(Check { + name, + ok: true, + detail: format!("{} matches ({} bytes)", art.url, art.bytes), + }); + } else { + checks.push(Check { + name, + ok: false, + detail: format!( + "checksum/size mismatch for {}: expected sha256 {} / {} bytes, got {} / {} bytes", + art.source, + art.sha256, + art.bytes, + digest, + bytes.len() + ), + }); + } + } + Err(e) => checks.push(Check { + name, + ok: false, + detail: format!("missing published file {} ({}): {e}", path.display(), art.url), + }), + } + } + let valid = checks.iter().all(|c| c.ok); + Ok(PublishVerifyReport { + bundle: req.bundle.display().to_string(), + published_dir: req.published_dir.display().to_string(), + valid, + checks, + }) +} + +/// Minimal `publish-plan.yaml` renderer (§4.4 shape). Hand-rolled so +/// this slice adds no YAML dependency; output is informational, the +/// JSON form is canonical. +pub fn render_plan_yaml(plan: &PublishPlan) -> String { + let mut out = String::new(); + out.push_str(&format!("schema: {}\n", plan.schema)); + out.push_str(&format!("host: {}\n", plan.host)); + out.push_str("records:\n"); + if plan.dns_records.is_empty() { + out.push_str(" []\n"); + } else { + for r in &plan.dns_records { + out.push_str(&format!( + " - type: {}\n name: {}\n ttl: {}\n value: \"{}\"\n action: {}\n", + r.record_type, r.name, r.ttl, r.value, r.action + )); + } + } + out.push_str("artifacts:\n"); + for a in &plan.artifacts { + out.push_str(&format!( + " - source: {}\n url: {}\n media_type: {}\n visibility: {}\n sha256: {}\n bytes: {}\n", + a.source, a.url, a.media_type, a.visibility, a.sha256, a.bytes + )); + } + out.push_str("prerequisites:\n"); + for p in &plan.prerequisites { + out.push_str(&format!(" - \"{}\"\n", p.replace('"', "'"))); + } + out +} + +/// Human-readable plan text. +pub fn render_plan_text(plan: &PublishPlan) -> String { + let mut out = format!( + "Publish plan: {} ({}, {})\n host: {} (base {})\n artifacts: {}\n", + plan.bundle, plan.bundle_id, plan.bundle_type, plan.host, plan.base_url, + plan.artifacts.len() + ); + for a in &plan.artifacts { + out.push_str(&format!( + " {} -> {}\n {} {} bytes sha256:{}..\n", + a.source, + a.url, + a.media_type, + a.bytes, + &a.sha256[..12.min(a.sha256.len())] + )); + } + if plan.dns_records.is_empty() { + out.push_str(" dns: (no changes — supply --dns-target for an executable record)\n"); + } else { + for r in &plan.dns_records { + out.push_str(&format!( + " dns: {} {} {} ttl={} ({})\n", + r.record_type, r.name, r.value, r.ttl, r.action + )); + } + } + for p in &plan.prerequisites { + out.push_str(&format!(" prerequisite: {p}\n")); + } + out.push_str(" note: read-only plan; nothing was uploaded (apply is a later gated slice).\n"); + out +} + +pub fn published_path(published_dir: &Path, source: &str) -> std::path::PathBuf { + published_dir.join(url_path_for(source)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn url_and_mime_rules() { + // Oracle: §4.4 example shape + §24.7 MIME table. + assert_eq!(url_path_for("public/bundles/roots-all.pem"), "bundles/roots-all.pem"); + assert_eq!(url_path_for("leaf.crt.pem"), "leaf.crt.pem"); + assert_eq!(media_type_for("ca.crt.pem"), "application/pkix-cert"); + assert_eq!(media_type_for("issuers.p7c"), "application/pkcs7-mime"); + assert_eq!(media_type_for("root.crl.pem"), "application/pkix-crl"); + } + + #[test] + fn yaml_renderer_keeps_schema_shape() { + // Oracle: §4.4 field names (schema/host/records/artifacts/prerequisites). + let plan = PublishPlan { + schema: PUBLISH_SCHEMA.into(), + bundle: "b".into(), + bundle_id: "id".into(), + bundle_type: "root-set".into(), + host: "pki.example.test".into(), + base_url: "http://pki.example.test".into(), + artifacts: vec![PublishArtifact { + source: "public/bundles/roots-all.pem".into(), + url: "http://pki.example.test/bundles/roots-all.pem".into(), + media_type: "application/pkix-cert".into(), + visibility: "public".into(), + sha256: "abc".into(), + bytes: 3, + }], + dns_records: vec![], + prerequisites: vec!["x".into()], + generated_at: Rfc3339::now(), + }; + let y = render_plan_yaml(&plan); + assert!(y.contains("schema: fleet.pki.publish/v1")); + assert!(y.contains("source: public/bundles/roots-all.pem")); + assert!(y.contains("url: http://pki.example.test/bundles/roots-all.pem")); + } +} diff --git a/pkgs/fleet/crates/fleet-cert/tests/publish.rs b/pkgs/fleet/crates/fleet-cert/tests/publish.rs new file mode 100644 index 0000000000..a2c3e43b05 --- /dev/null +++ b/pkgs/fleet/crates/fleet-cert/tests/publish.rs @@ -0,0 +1,156 @@ +//! Publish plan + verify (slice 1 of #13723). +//! +//! Oracles: +//! - §4.4 field shape (schema/host/records/artifacts/prerequisites); +//! - §7.1 manifest checksum index (verify must catch tamper/missing); +//! - §3.5 distribution set (plan covers exactly the bundle's public files). + +use fleet_cert::engine; +use fleet_cert::graph::CrossSigningMode; +use fleet_cert::model::{ + PublishPlanRequest, PublishVerifyRequest, RootCreateRequest, +}; +use fleet_cert::timeparse::Rfc3339; +use std::path::{Path, PathBuf}; + +fn ts(s: &str) -> Rfc3339 { + Rfc3339::parse(s).unwrap() +} + +struct TempDir(PathBuf); +impl TempDir { + fn new(tag: &str) -> Self { + let nanos = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos(); + let dir = std::env::temp_dir().join(format!( + "fleet-cert-publish-{tag}-{}-{nanos}", + std::process::id() + )); + std::fs::create_dir_all(&dir).unwrap(); + TempDir(dir) + } + fn path(&self) -> &Path { + &self.0 + } +} +impl Drop for TempDir { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +fn root_bundle(tmp: &TempDir) -> PathBuf { + let dir = tmp.path().join("roots"); + let req = RootCreateRequest { + organization: "Test Org LLC".into(), + country: "US".into(), + algorithms: vec![fleet_cert::algorithm::AlgorithmId::Ed25519], + generation: 1, + partition: "A".into(), + cross_signing: CrossSigningMode::Both, + not_before: ts("2026-01-01T00:00:00Z"), + not_after: ts("2046-01-01T00:00:00Z"), + allow_legacy_root_strength: false, + private_store: None, + }; + engine::create_root_set(&req, &dir).unwrap(); + dir +} + +fn copy_public_to_mirror(bundle: &Path, mirror: &Path) { + // Mirror layout: / where url-path strips `public/`. + let b = fleet_cert::bundle::load_bundle(bundle).unwrap(); + for f in &b.manifest.files { + if f.visibility != "public" { + continue; + } + let rel = f.path.strip_prefix("public/").unwrap_or(&f.path); + let src = bundle.join(&f.path); + let dst = mirror.join(rel); + std::fs::create_dir_all(dst.parent().unwrap()).unwrap(); + std::fs::copy(&src, &dst).unwrap(); + } +} + +#[test] +fn plan_covers_public_files_with_stable_urls() { + // Oracle: §4.4 shape + §3.5 set (exactly the public files). + let tmp = TempDir::new("plan"); + let bundle = root_bundle(&tmp); + let plan = fleet_cert::publish::plan_bundle(&PublishPlanRequest { + bundle: bundle.clone(), + host: "pki.example.test".into(), + dns_target: None, + }) + .unwrap(); + assert_eq!(plan.schema, fleet_cert::publish::PUBLISH_SCHEMA); + assert_eq!(plan.base_url, "http://pki.example.test"); + let manifest = fleet_cert::bundle::load_bundle(&bundle).unwrap(); + let public = manifest + .manifest + .files + .iter() + .filter(|f| f.visibility == "public") + .count(); + assert_eq!(plan.artifacts.len(), public); + for a in &plan.artifacts { + assert!(a.url.starts_with("http://pki.example.test/")); + assert!(!a.url.ends_with('/')); + assert_eq!(a.media_type, "application/pkix-cert"); + } + // No DNS target -> no executable records, prerequisite recorded. + assert!(plan.dns_records.is_empty()); + assert!(plan.prerequisites.iter().any(|p| p.contains("placeholder"))); +} + +#[test] +fn verify_accepts_mirror_and_reports_mismatch() { + // Oracle: §7.1 checksum index — tamper/missing must fail. + let tmp = TempDir::new("verify"); + let bundle = root_bundle(&tmp); + let mirror = tmp.path().join("mirror"); + copy_public_to_mirror(&bundle, &mirror); + let ok = fleet_cert::publish::verify_bundle(&PublishVerifyRequest { + bundle: bundle.clone(), + published_dir: mirror.clone(), + host: None, + }) + .unwrap(); + assert!(ok.valid, "clean mirror must verify: {:?}", ok.checks); + + // Tamper with one mirrored file. + let first = fleet_cert::bundle::load_bundle(&bundle) + .unwrap() + .manifest + .files + .iter() + .find(|f| f.visibility == "public") + .unwrap() + .path + .clone(); + let rel = first.strip_prefix("public/").unwrap_or(&first); + let p = mirror.join(rel); + let mut bytes = std::fs::read(&p).unwrap(); + bytes[10] ^= 0xff; + std::fs::write(&p, bytes).unwrap(); + let bad = fleet_cert::publish::verify_bundle(&PublishVerifyRequest { + bundle: bundle.clone(), + published_dir: mirror.clone(), + host: None, + }) + .unwrap(); + assert!(!bad.valid); + assert!(bad.checks.iter().any(|c| !c.ok && c.name.contains(&first))); + + // Missing file. + std::fs::remove_file(&p).unwrap(); + let missing = fleet_cert::publish::verify_bundle(&PublishVerifyRequest { + bundle, + published_dir: mirror, + host: None, + }) + .unwrap(); + assert!(!missing.valid); +} diff --git a/scripts/model-deprecation-watch-sweep.sh b/scripts/model-deprecation-watch-sweep.sh new file mode 100755 index 0000000000..927223b850 --- /dev/null +++ b/scripts/model-deprecation-watch-sweep.sh @@ -0,0 +1,24 @@ +#!/usr/bin/env bash +# model-deprecation-watch weekly sweep (developing-today/code#14236, #7013). +# Re-fetches the provider lifecycle surfaces registered in +# doc/model-deprecation-watch.md, snapshots them, and appends a dated +# summary line. A human/lane reviews the log and updates the registry doc. +set -u +OUT_DIR="${MODEL_DEPRECATION_WATCH_DIR:-$HOME/.local/share/model-deprecation-watch}" +mkdir -p "$OUT_DIR/snapshots" +STAMP="$(date +%Y%m%dT%H%M%S)" +fetch() { + local name="$1" url="$2" + curl -fsSL --max-time 60 -A "Mozilla/5.0 (fleet-watch)" "$url" \ + -o "$OUT_DIR/snapshots/${STAMP}-${name}.html" 2>>"$OUT_DIR/sweep-errors.log" \ + && echo "ok $name" || echo "FAIL $name" +} +{ + echo "=== sweep $STAMP ===" + fetch anthropic-deprecations "https://platform.claude.com/docs/en/about-claude/model-deprecations" + fetch openai-deprecations "https://platform.openai.com/docs/deprecations" + fetch google-models "https://ai.google.dev/gemini-api/docs/models" + fetch deepseek-pricing "https://api-docs.deepseek.com/quick_start/pricing" + fetch mistral-models "https://docs.mistral.ai/getting-started/models/models_overview" + echo "snapshots in $OUT_DIR/snapshots/${STAMP}-*" +} >>"$OUT_DIR/sweep.log" 2>&1