Skip to main content

bynk/deploy/
ledger.rs

1use super::*;
2use bynk_driver::emsg;
3
4#[derive(Debug, Default, Serialize, Deserialize, PartialEq, Eq)]
5pub(crate) struct DeployLock {
6    // No serde `default`: a ledger with no `version` is not a fresh project, it
7    // is corruption (a truncated write), and must fail the read rather than
8    // parse as an empty v1 ledger that re-mints every namespace (#736).
9    version: u32,
10    #[serde(default)]
11    pub(crate) environments: BTreeMap<String, Environment>,
12    /// #3112: the structured form behind recent contract hashes, oldest first.
13    /// A hash that is live resolves here, and so does one a `bynk revert`
14    /// restores from a version's deploy facts, which the ledger no longer
15    /// listed. Each entry is trusted only while it hashes to the hash it is
16    /// filed under. Pruned on write ([`DeployLock::record_shapes`]).
17    #[serde(default, skip_serializing_if = "Vec::is_empty")]
18    contract_shapes: Vec<ContractShape>,
19}
20
21/// One entry of [`DeployLock::contract_shapes`].
22#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
23struct ContractShape {
24    hash: String,
25    /// `bynk_check::contract_compat::ServiceShape::to_text`.
26    shape: String,
27}
28
29/// How many contract shapes no Worker's record references are kept, for a
30/// revert to restore (#3112).
31const RECENT_SHAPES: usize = 16;
32
33/// #2077: what a Worker was compiled against — dependency (qualified context
34/// name) → service → contract hash ([`WorkerRecord::expects`]).
35pub(crate) type Expects = BTreeMap<String, BTreeMap<String, String>>;
36
37fn lock_version() -> u32 {
38    1
39}
40
41#[derive(Debug, Default, Serialize, Deserialize, PartialEq, Eq)]
42pub(crate) struct Environment {
43    /// Each Worker's bare `KV` namespace, the cloudflare adapter's `Kv`.
44    #[serde(default)]
45    pub(crate) kv: BTreeMap<String, KvNamespace>,
46    /// S4b (#1967): each Worker's derived KV instances (`capability Sessions =
47    /// Kv`), keyed by the instance's binding (`KV_SESSIONS`): the capability's
48    /// name as the generated config carries it, which `deploy` reads rather
49    /// than the source (ADR 0193 D3). A renamed capability is a new binding,
50    /// so a new key: the plan shows a create and an orphan.
51    ///
52    /// Additive, `default`ed and omitted when empty, so an older ledger still
53    /// reads and a project with only the bare `Kv` writes the same file.
54    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
55    pub(crate) kv_instances: BTreeMap<String, BTreeMap<String, KvNamespace>>,
56    /// P5 (#2323): each Worker's `R2` instances (`capability Archives = R2`),
57    /// keyed by the instance's binding (`R2_ARCHIVES`), as `kv_instances` is.
58    /// A bucket has no minted id (its name is its identity), so the record is
59    /// the name and jurisdiction it was created under: what a changed
60    /// `@jurisdiction` is compared against, and what an orphan names.
61    ///
62    /// Additive, `default`ed and omitted when empty, so an older ledger still
63    /// reads and a project without R2 writes the same file.
64    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
65    pub(crate) r2_instances: BTreeMap<String, BTreeMap<String, R2Bucket>>,
66    /// #3479: each Worker's `Vectorize` instances (`capability Docs =
67    /// Vectorize …`), keyed by the instance's binding (`VECTORIZE_DOCS`). An
68    /// index's name is its identity and its configuration is fixed at
69    /// creation, so the record is the name it was created (or adopted) under.
70    ///
71    /// Additive, `default`ed and omitted when empty, so an older ledger still
72    /// reads and a project without Vectorize writes the same file.
73    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
74    pub(crate) vectorize_instances: BTreeMap<String, BTreeMap<String, VectorizeRecord>>,
75    /// #3477: each Worker's adopted container images, keyed by the `Container`
76    /// capability's name (`Renderer`): the digest-pinned reference
77    /// `[deploy.containers.<Cap>] image` named for this environment when it was
78    /// last pushed. A container built from its Dockerfile has no entry, because
79    /// the image is `wrangler`'s to make and the ledger records nothing it does
80    /// not own. It holds the image the last deploy attempt named, written before
81    /// the push, so a push that then failed still shows here. What it is for: a
82    /// changed or dropped adoption is shown in the plan, and `bynk revert` says which image a restored Worker takes for new
83    /// starts.
84    ///
85    /// Additive, `default`ed and omitted when empty, so an older ledger still
86    /// reads and a project without an adopted image writes the same file.
87    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
88    pub(crate) container_images: BTreeMap<String, BTreeMap<String, String>>,
89    /// P4a (#2602): each Worker's `D1` instances (`capability Orders = D1`),
90    /// keyed by the instance's binding (`D1_ORDERS`), as `kv_instances` is:
91    /// the database's account-facing name and the id Cloudflare minted for it
92    /// (ADR 0194: the ledger owns the ids it mints).
93    ///
94    /// Additive, `default`ed and omitted when empty, so an older ledger still
95    /// reads and a project without D1 writes the same file.
96    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
97    pub(crate) d1_instances: BTreeMap<String, BTreeMap<String, D1Record>>,
98    /// #3319: each Worker's `Postgres` instances (`capability Main =
99    /// Postgres`), keyed by the instance's binding (`HYPERDRIVE_MAIN`): the
100    /// Hyperdrive config the deploy created or adopted for it, and the id
101    /// the push binds. It holds an id and a name and nothing derived from
102    /// the connection string: the ledger is committed, so even a digest of a
103    /// secret there could be guessed offline.
104    ///
105    /// Additive, `default`ed and omitted when empty, so an older ledger still
106    /// reads and a project without `Postgres` writes the same file.
107    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
108    pub(crate) hyperdrive_instances: BTreeMap<String, BTreeMap<String, HyperdriveRecord>>,
109    /// #3301: each Worker's `StoredSecret` instances, keyed by the instance's
110    /// binding (`SECRET_STRIPE_KEY`): the Secrets Store the deploy linked it
111    /// to. Linked, never created, so there is nothing to orphan or prune; the
112    /// record is what `bynk dev -- --remote` binds by, and is refreshed by
113    /// every deploy. It holds a store's name and id and a secret's name, never
114    /// a value: the deploy never asks for one.
115    ///
116    /// Additive, `default`ed and omitted when empty, so an older ledger still
117    /// reads and a project without stored secrets writes the same file.
118    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
119    pub(crate) stored_secret_links: BTreeMap<String, BTreeMap<String, StoredSecretLink>>,
120    /// #3480: each Worker's `AiSearch` instances, keyed by the instance's
121    /// binding (`AI_SEARCH_KB`): the account's instance the deploy linked it
122    /// to. Linked, never created, so there is nothing to orphan or prune. It
123    /// holds an instance's name only, and is refreshed by every deploy.
124    ///
125    /// Additive, `default`ed and omitted when empty, so an older ledger still
126    /// reads and a project without AI Search writes the same file.
127    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
128    pub(crate) ai_search_links: BTreeMap<String, BTreeMap<String, AiSearchLink>>,
129    /// #3513 A: each Worker's `MtlsCertificate` instances, keyed by the instance's binding
130    /// (`MTLS_BACKEND`): the account certificate the deploy linked it to. Linked, never
131    /// uploaded, so there is nothing to orphan or prune. It holds a certificate's name and id,
132    /// never any key material: the deploy never asks for it. It is what `bynk dev` binds by.
133    ///
134    /// Additive, `default`ed and omitted when empty, so an older ledger still reads and a
135    /// project without mTLS writes the same file.
136    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
137    pub(crate) mtls_certificate_links: BTreeMap<String, BTreeMap<String, MtlsCertificateLink>>,
138    /// P3 (#2342): each Worker's `RateLimit` instances, keyed by binding
139    /// (`RATELIMIT_LOGIN_LIMIT`), as `kv_instances` is. The `namespace_id` is
140    /// minted here, not by Cloudflare: a positive integer unique across every
141    /// environment of the ledger, since environments may share an account
142    /// and the id is unique per account.
143    ///
144    /// Additive, `default`ed and omitted when empty, so an older ledger still
145    /// reads and a project without rate limiting writes the same file.
146    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
147    pub(crate) ratelimit_instances: BTreeMap<String, BTreeMap<String, RateLimitNamespace>>,
148    /// Slice 2: which Workers this project has ever pushed. Additive and
149    /// `default`ed, so a slice-0 ledger still reads.
150    ///
151    /// KV state alone could not answer "does this Worker exist on the account?"
152    /// — a context with no KV has no `kv` entry at all — and `--context` must
153    /// know, because a Service Binding to an absent Worker fails at upload.
154    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
155    workers: BTreeMap<String, WorkerRecord>,
156    /// Slice 1: the queue names this project has created at least once.
157    ///
158    /// Environment-wide rather than per-worker, because a queue is an account
159    /// resource addressed by name, not something a Worker owns — two contexts
160    /// consuming `"jobs"` mean the same queue.
161    ///
162    /// **Authoritative for nothing** (ADR 0194 D2). It exists so the plan can
163    /// say `create` or `reuse` without a `wrangler queues list` call; the
164    /// provision step attempts the create regardless, so a queue deleted
165    /// out-of-band comes back rather than being skipped on this set's word.
166    /// Additive and `default`ed, so a slice-0 or slice-2 ledger still reads.
167    #[serde(default, skip_serializing_if = "BTreeSet::is_empty")]
168    pub(crate) queues: BTreeSet<String>,
169    /// #2579: the subset of [`Environment::queues`] this project only found
170    /// already on the account, never created. `--prune` leaves them alone: a
171    /// queue another Worker owns must not be deleted, with its undelivered
172    /// messages, because this project stopped consuming it. A queue absent from
173    /// this set is one the run created, or one an older ledger recorded without
174    /// saying — which keeps its old, prunable meaning, so a ledger written
175    /// before this field still holds its reused queues as prunable; the
176    /// ledger cannot tell them apart. An entry no context declares any more
177    /// stays here, harmlessly: `--prune` never reaches it. Additive and
178    /// `default`ed, so an older ledger still reads.
179    #[serde(default, skip_serializing_if = "BTreeSet::is_empty")]
180    pub(crate) reused_queues: BTreeSet<String>,
181    /// State-migrations S3 (#2248, #2253 review): per Worker, the agent classes
182    /// whose `deleted` tombstone a successful push carried in this
183    /// environment. A `removed agent` declaration stays in source (and its
184    /// tombstone in the config) until Cloudflare reports it stale, so later
185    /// plans show the deletion as already applied and do not ask to confirm
186    /// it again. Replaced on every push of the Worker, so a declaration that is
187    /// later removed leaves nothing behind. A record of what was confirmed and
188    /// pushed — never a claim about the namespace, which Cloudflare owns (ADR
189    /// 0194 D1). Additive and `default`ed, so an older ledger still reads.
190    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
191    deleted_classes: BTreeMap<String, BTreeSet<String>>,
192    /// #2276 Decision D: per Worker, the agent class renames (old name → new
193    /// name) whose `renamed` tombstone a successful push carried in this
194    /// environment, so later plans show them as applied. Replaced on every
195    /// push of the Worker, like [`Environment::deleted_classes`], and for the
196    /// same reason a record, never a claim about the namespace. Additive and
197    /// `default`ed, so an older ledger still reads.
198    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
199    renamed_classes: BTreeMap<String, BTreeMap<String, String>>,
200    /// #3328: per Worker, the Email Routing `addresses` its last successful push
201    /// carried in this environment. Wrangler deletes the rule of an address no
202    /// longer listed, so mail to it would bounce: the next deploy compares the
203    /// list it is about to push with this record, and a removal is refused unless
204    /// confirmed (`--prune`). A record of what was pushed, never a claim about
205    /// the account's rules, which Cloudflare owns. Replaced on every push of the
206    /// Worker; additive and `default`ed, so an older ledger still reads.
207    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
208    email_addresses: BTreeMap<String, BTreeSet<String>>,
209}
210
211/// P3 (#2342): the `namespace_id` this project allocated for one rate limiter.
212#[derive(Debug, Serialize, Deserialize, PartialEq, Eq)]
213pub(crate) struct RateLimitNamespace {
214    pub(crate) namespace_id: String,
215}
216
217/// P3 (#2342): the lowest `namespace_id` the ledger allocates. Low ids are the
218/// ones a hand-written Worker on the same account is likeliest to have chosen.
219pub(crate) const FIRST_RATELIMIT_NAMESPACE: u64 = 1000;
220
221/// P3 (#2342): how many ids above [`FIRST_RATELIMIT_NAMESPACE`] a seed spreads
222/// over.
223pub(crate) const RATELIMIT_NAMESPACE_SPAN: u64 = 1_000_000_000;
224
225/// P3 (#2342, review): where the search for `worker`'s rate limiter
226/// `binding`'s id in `environment` starts: a hash of the three, into
227/// [`FIRST_RATELIMIT_NAMESPACE`]`..+`[`RATELIMIT_NAMESPACE_SPAN`]. Another
228/// Bynk project on the same account has a ledger of its own, which this one
229/// can't see; but its Workers have other names (a Worker name is unique on an
230/// account), so its limiters start elsewhere. A fixed starting point would
231/// give every project's first limiter the same id, and the same counters.
232pub(crate) fn ratelimit_seed(environment: &str, worker: &str, binding: &str) -> u64 {
233    use sha2::{Digest, Sha256};
234    let digest = Sha256::digest(format!("{environment}\0{worker}\0{binding}").as_bytes());
235    let n = u64::from_be_bytes(digest[..8].try_into().expect("8 bytes"));
236    FIRST_RATELIMIT_NAMESPACE + n % RATELIMIT_NAMESPACE_SPAN
237}
238
239/// P5 (#2323): one R2 bucket this project created, as the account names it.
240#[derive(Debug, Serialize, Deserialize, PartialEq, Eq)]
241pub(crate) struct R2Bucket {
242    /// The bucket's account-facing name, environment-qualified.
243    pub(crate) name: String,
244    /// The jurisdiction it was created in, if any.
245    #[serde(default, skip_serializing_if = "Option::is_none")]
246    pub(crate) jurisdiction: Option<String>,
247    /// Buckets this binding used to have, left in place when a changed
248    /// `@jurisdiction` made a new one. They hold data, so they stay recorded
249    /// (and are reported as orphans) until their entry is removed by hand.
250    #[serde(default, skip_serializing_if = "Vec::is_empty")]
251    pub(crate) superseded: Vec<R2Past>,
252}
253
254/// P4a (#2602): one D1 database this project created or adopted, as the
255/// account names it, with the id the push binds.
256#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
257pub(crate) struct D1Record {
258    /// The database's account-facing name, environment-qualified.
259    pub(crate) name: String,
260    /// Cloudflare's `database_id` for it.
261    pub(crate) id: String,
262    /// Databases this binding used to have, under a name it no longer
263    /// derives. They hold data, so they stay recorded (and are reported as
264    /// orphans) until their entry is removed by hand, as R2's are.
265    #[serde(default, skip_serializing_if = "Vec::is_empty")]
266    pub(crate) superseded: Vec<D1Past>,
267}
268
269/// #3319: the Hyperdrive config of one `Postgres` binding, as the account
270/// names it, with the id the push binds.
271#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
272pub(crate) struct HyperdriveRecord {
273    /// The config's account-facing name; for an adopted config, the name the
274    /// deploy found it under, or empty when it did not ask.
275    pub(crate) name: String,
276    /// Cloudflare's id for the config.
277    pub(crate) id: String,
278    /// `true` when the project named an existing config (`config_id`) rather
279    /// than having this deploy make one. An adopted config is not the
280    /// project's to change or delete: it is never updated and never pruned.
281    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
282    pub(crate) adopted: bool,
283    /// Configs this binding used to have, under another id. They stay recorded
284    /// (and are reported as orphans) until pruned or removed by hand.
285    #[serde(default, skip_serializing_if = "Vec::is_empty")]
286    pub(crate) superseded: Vec<HyperdrivePast>,
287}
288
289/// A config a binding no longer uses (see [`HyperdriveRecord::superseded`]).
290#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
291pub(crate) struct HyperdrivePast {
292    pub(crate) name: String,
293    pub(crate) id: String,
294    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
295    pub(crate) adopted: bool,
296}
297
298/// #3480: the AI Search instance an `AiSearch` binding was linked to.
299#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
300pub(crate) struct AiSearchLink {
301    /// The instance's name, as `@instance` wrote it.
302    pub(crate) instance: String,
303}
304
305/// #3513 A: the account certificate an `MtlsCertificate` binding was linked to.
306#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
307pub(crate) struct MtlsCertificateLink {
308    /// The certificate's name, as `@certificate` wrote it.
309    pub(crate) certificate: String,
310    /// The certificate's id, which the push binds.
311    pub(crate) certificate_id: String,
312}
313
314/// #3301: the Secrets Store secret a `StoredSecret` binding was linked to.
315#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
316pub(crate) struct StoredSecretLink {
317    /// The store's name, as `@store` wrote it.
318    pub(crate) store: String,
319    /// The store's id, which the push binds.
320    pub(crate) store_id: String,
321    /// The secret's name in the store, as `@secret` wrote it.
322    pub(crate) secret: String,
323}
324
325/// A database a binding no longer uses (see [`D1Record::superseded`]).
326#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
327pub(crate) struct D1Past {
328    pub(crate) name: String,
329    pub(crate) id: String,
330}
331
332/// #3479: one Vectorize index of a binding, as the account names it.
333#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
334pub(crate) struct VectorizeRecord {
335    /// The index's account-facing name, environment-qualified.
336    pub(crate) name: String,
337    /// `true` when the index was already on the account when this deploy first
338    /// met it (named by the project, or found under the derived name) rather
339    /// than created by this deploy. An adopted index is checked for drift and
340    /// never created, changed or deleted.
341    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
342    pub(crate) adopted: bool,
343    /// Indexes this binding used to have, under another name. They hold
344    /// vectors, so they stay recorded (and are reported as orphans) until
345    /// pruned or removed by hand.
346    #[serde(default, skip_serializing_if = "Vec::is_empty")]
347    pub(crate) superseded: Vec<VectorizePast>,
348}
349
350/// An index a binding no longer uses (see [`VectorizeRecord::superseded`]).
351#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
352pub(crate) struct VectorizePast {
353    pub(crate) name: String,
354    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
355    pub(crate) adopted: bool,
356}
357
358/// A bucket a binding no longer uses (see [`R2Bucket::superseded`]).
359#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
360pub(crate) struct R2Past {
361    pub(crate) name: String,
362    #[serde(default, skip_serializing_if = "Option::is_none")]
363    pub(crate) jurisdiction: Option<String>,
364}
365
366/// What the ledger remembers about one pushed Worker. A struct rather than a
367/// bare bool so slice 3's secrets have somewhere to land.
368#[derive(Debug, Serialize, Deserialize, PartialEq, Eq)]
369struct WorkerRecord {
370    deployed: bool,
371    /// v0.177 (#643): the contract hash this Worker *provides* per `on call`
372    /// service, as of the push that recorded it — what is **live**.
373    ///
374    /// This is what makes a skew visible before a request finds it: a later
375    /// `deploy --context A` compares A's compiled `expects` against these, and
376    /// refuses rather than shipping a caller that will 409 in production.
377    ///
378    /// `None` means **no record** — a Worker pushed by a pre-v0.177 driver, which
379    /// has nothing to say about contracts either way. `Some({})` means the
380    /// Worker is *known* to provide no `on call` service at all.
381    ///
382    /// The distinction is load-bearing, and an empty map cannot carry it: a
383    /// callee that removes **all** its services emits no manifest, so a
384    /// bare-`BTreeMap` field would record `{}` — indistinguishable from "old
385    /// ledger" — and the gate's `continue` would let a total, real skew through.
386    /// `Option` keeps "silence is not a match" while still catching removal.
387    ///
388    /// Additive and `default`ed, so a pre-v0.177 ledger still reads.
389    #[serde(default, skip_serializing_if = "Option::is_none")]
390    contracts: Option<BTreeMap<String, String>>,
391    /// #2077: the contract hash this Worker was compiled against for each
392    /// dependency service it calls, as of the push that recorded it —
393    /// dependency (qualified context name) → service → hash, the build's
394    /// `bynk-contracts.json` `expects` record. What its live call sites stamp.
395    ///
396    /// The other half of [`WorkerRecord::contracts`]: a later `deploy
397    /// --context B` compares B's newly built `provides` against every other
398    /// live Worker's `expects`, and refuses rather than shipping a callee its
399    /// live callers would 409 against.
400    ///
401    /// `None` means **no record** — a Worker pushed by a driver that predates
402    /// this field, which cannot be checked (the gate warns, never refuses, on
403    /// it: silence is not a match). `Some({})` means the Worker is *known* to
404    /// call no `on call` service at all. Additive and `default`ed, so an older
405    /// ledger still reads.
406    #[serde(default, skip_serializing_if = "Option::is_none")]
407    expects: Option<Expects>,
408    /// I4 (#1970): the contract each declared foreign caller may call this
409    /// Worker at, as of the push that recorded it — actor → service → hash, the
410    /// build's `bynk-contracts.json` `foreign` record. The foreign callers are
411    /// not Bynk and record nothing themselves, so this is where the ledger
412    /// learns of them, beside what the Worker `provides`. Empty (and omitted)
413    /// for a Worker with none; additive and `default`ed.
414    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
415    foreign: BTreeMap<String, BTreeMap<String, String>>,
416    /// #2485, read-only since #3112: the per-Worker form of the shapes now
417    /// filed by hash in [`DeployLock::contract_shapes`]. A ledger written
418    /// before that carries them; [`read_lock`] moves them into the table and
419    /// they are never written again.
420    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
421    shapes: BTreeMap<String, String>,
422    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
423    expects_shapes: BTreeMap<String, BTreeMap<String, String>>,
424    /// #3562: the contexts a `[deploy.workers.<key>]` group's Worker held as of
425    /// the push that recorded it, in the manifest's order, so a plan, an orphan or a
426    /// revert can name the members of a Worker whose key is not any of their
427    /// names. Empty (and omitted) for a context on a Worker of its own, and for
428    /// a ledger written before groups; additive and `default`ed.
429    #[serde(default, skip_serializing_if = "Vec::is_empty")]
430    contexts: Vec<String>,
431    /// #3562: the Worker's script name on Cloudflare when it is not its key (a
432    /// group's `name`), so a report or a `wrangler delete` names the script that
433    /// exists. Omitted when the script is named by the key.
434    #[serde(default, skip_serializing_if = "Option::is_none")]
435    script: Option<String>,
436    /// #3562 (G5): agent state this Worker's script still holds for a context that moved off
437    /// it with `--accept-fresh-agent` (context → its classes): the context now runs on
438    /// another script with fresh state, and this script's namespaces keep the old data.
439    /// Recorded so an orphan report never calls the script empty. Omitted when none.
440    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
441    fresh_agents: BTreeMap<String, Vec<String>>,
442}
443
444impl DeployLock {
445    /// #3112: move any per-Worker shapes an older ledger carries into the
446    /// hash-keyed table, so none is lost when the file is next written.
447    fn fold_legacy_shapes(&mut self) {
448        let mut moved = Vec::new();
449        for record in self
450            .environments
451            .values_mut()
452            .flat_map(|env| env.workers.values_mut())
453        {
454            moved.push((
455                std::mem::take(&mut record.shapes),
456                std::mem::take(&mut record.expects_shapes),
457            ));
458        }
459        for (shapes, expects_shapes) in moved {
460            self.record_shapes(shapes, expects_shapes);
461        }
462    }
463
464    pub(crate) fn is_deployed(&self, environment: &str, worker: &str) -> bool {
465        self.environments
466            .get(environment)
467            .and_then(|env| env.workers.get(worker))
468            .is_some_and(|record| record.deployed)
469    }
470
471    /// #3073: the Workers this ledger records as pushed in `environment`, by
472    /// logical name, sorted.
473    pub(crate) fn deployed_workers(&self, environment: &str) -> Vec<String> {
474        self.environments
475            .get(environment)
476            .map(|env| {
477                env.workers
478                    .iter()
479                    .filter(|(_, record)| record.deployed)
480                    .map(|(name, _)| name.clone())
481                    .collect()
482            })
483            .unwrap_or_default()
484    }
485
486    /// State-migrations S4 (#2259): every environment this ledger records
487    /// `worker` as pushed in, sorted. A floor-raising `bynk migrate sweep`
488    /// must cover all of them.
489    pub(crate) fn deployed_environments(&self, worker: &str) -> Vec<String> {
490        self.environments
491            .iter()
492            .filter(|(env, _)| self.is_deployed(env, worker))
493            .map(|(env, _)| env.clone())
494            .collect()
495    }
496
497    /// State-migrations S3 (#2248): whether a push in `environment` already
498    /// carried `class`'s `deleted` tombstone for `worker`.
499    pub(crate) fn has_deleted_class(&self, environment: &str, worker: &str, class: &str) -> bool {
500        self.environments
501            .get(environment)
502            .and_then(|env| env.deleted_classes.get(worker))
503            .is_some_and(|classes| classes.contains(class))
504    }
505
506    /// State-migrations S3 (#2248): record the `deleted` tombstones a
507    /// successful push of `worker` carried, replacing what was recorded for it.
508    pub(crate) fn record_deleted_classes(
509        &mut self,
510        environment: &str,
511        worker: &str,
512        classes: BTreeSet<String>,
513    ) {
514        let env = self
515            .environments
516            .entry(environment.to_string())
517            .or_default();
518        if classes.is_empty() {
519            env.deleted_classes.remove(worker);
520        } else {
521            env.deleted_classes.insert(worker.to_string(), classes);
522        }
523    }
524
525    /// #3328: the recorded addresses of `worker` that `current` no longer lists,
526    /// sorted. Nothing is recorded for a first deploy, so it removes nothing.
527    pub(crate) fn removed_email_addresses(
528        &self,
529        environment: &str,
530        worker: &str,
531        current: &[String],
532    ) -> Vec<String> {
533        self.environments
534            .get(environment)
535            .and_then(|env| env.email_addresses.get(worker))
536            .map(|recorded| {
537                recorded
538                    .iter()
539                    .filter(|a| !current.contains(a))
540                    .cloned()
541                    .collect()
542            })
543            .unwrap_or_default()
544    }
545
546    /// #3328: record the addresses a successful push of `worker` carried,
547    /// replacing what was recorded for it.
548    pub(crate) fn record_email_addresses(
549        &mut self,
550        environment: &str,
551        worker: &str,
552        addresses: BTreeSet<String>,
553    ) {
554        let env = self
555            .environments
556            .entry(environment.to_string())
557            .or_default();
558        if addresses.is_empty() {
559            env.email_addresses.remove(worker);
560        } else {
561            env.email_addresses.insert(worker.to_string(), addresses);
562        }
563    }
564
565    /// #2276 Decision D: whether a push in `environment` already carried the
566    /// rename `from → to` for `worker`.
567    pub(crate) fn has_renamed_class(
568        &self,
569        environment: &str,
570        worker: &str,
571        from: &str,
572        to: &str,
573    ) -> bool {
574        self.environments
575            .get(environment)
576            .and_then(|env| env.renamed_classes.get(worker))
577            .and_then(|renames| renames.get(from))
578            .is_some_and(|recorded| recorded == to)
579    }
580
581    /// #2276 Decision D: record the `renamed` tombstones a successful push of
582    /// `worker` carried, replacing what was recorded for it.
583    pub(crate) fn record_renamed_classes(
584        &mut self,
585        environment: &str,
586        worker: &str,
587        renames: BTreeMap<String, String>,
588    ) {
589        let env = self
590            .environments
591            .entry(environment.to_string())
592            .or_default();
593        if renames.is_empty() {
594            env.renamed_classes.remove(worker);
595        } else {
596            env.renamed_classes.insert(worker.to_string(), renames);
597        }
598    }
599
600    pub(crate) fn record_deployed(
601        &mut self,
602        environment: &str,
603        worker: &str,
604        contracts: Option<BTreeMap<String, String>>,
605    ) {
606        self.environments
607            .entry(environment.to_string())
608            .or_default()
609            .workers
610            .insert(
611                worker.to_string(),
612                WorkerRecord {
613                    deployed: true,
614                    contracts,
615                    expects: None,
616                    foreign: BTreeMap::new(),
617                    shapes: BTreeMap::new(),
618                    expects_shapes: BTreeMap::new(),
619                    contexts: Vec::new(),
620                    script: None,
621                    fresh_agents: BTreeMap::new(),
622                },
623            );
624    }
625
626    /// #3562: record the script name `worker` was pushed under, when it is not
627    /// the key ([`WorkerRecord::script`]). Called right after
628    /// [`DeployLock::record_deployed`].
629    pub(crate) fn record_script(&mut self, environment: &str, worker: &str, script: &str) {
630        if let Some(record) = self
631            .environments
632            .get_mut(environment)
633            .and_then(|env| env.workers.get_mut(worker))
634        {
635            record.script = (script != worker).then(|| script.to_string());
636        }
637    }
638
639    /// #3562: the Worker `context` was last pushed in, by the members the ledger
640    /// recorded for each group's Worker; a context on its own Worker (or one the
641    /// ledger does not know) is the Worker its dashed name gives.
642    pub(crate) fn worker_of(&self, environment: &str, context: &str) -> String {
643        self.environments
644            .get(environment)
645            .and_then(|env| {
646                env.workers.iter().find(|(_, record)| {
647                    record
648                        .contexts
649                        .iter()
650                        .any(|c| c == context || c.replace('.', "-") == context)
651                })
652            })
653            .map_or_else(|| context.replace('.', "-"), |(worker, _)| worker.clone())
654    }
655
656    /// #3562: the name `worker`'s script has on Cloudflare: the recorded script
657    /// name, else the key.
658    pub(crate) fn script_of(&self, environment: &str, worker: &str) -> String {
659        self.environments
660            .get(environment)
661            .and_then(|env| env.workers.get(worker))
662            .and_then(|record| record.script.clone())
663            .unwrap_or_else(|| worker.to_string())
664    }
665
666    /// #3562: record the contexts a group's Worker holds as of this push
667    /// ([`WorkerRecord::contexts`]). Called right after
668    /// [`DeployLock::record_deployed`]; a Worker not yet recorded is ignored.
669    pub(crate) fn record_members(&mut self, environment: &str, worker: &str, members: &[String]) {
670        // A context is in one Worker: whatever other records still list the contexts this push
671        // holds are stale (a dissolved group, the group it left), and `worker_of` would find
672        // them first. A context's own Worker holds just that context.
673        let held: Vec<String> = if members.is_empty() {
674            vec![worker.replace('-', ".")]
675        } else {
676            members.to_vec()
677        };
678        if let Some(env) = self.environments.get_mut(environment) {
679            for (other, record) in env.workers.iter_mut() {
680                if other != worker {
681                    record.contexts.retain(|c| !held.contains(c));
682                }
683            }
684        }
685        if let Some(record) = self
686            .environments
687            .get_mut(environment)
688            .and_then(|env| env.workers.get_mut(worker))
689        {
690            record.contexts = members.to_vec();
691        }
692    }
693
694    /// #3562 (G5): record that `worker`'s script still holds the agent state of `context`'s
695    /// `classes`, which moved off it fresh ([`WorkerRecord::fresh_agents`]).
696    pub(crate) fn record_fresh_agents(
697        &mut self,
698        environment: &str,
699        worker: &str,
700        context: &str,
701        classes: &[String],
702    ) {
703        if let Some(record) = self
704            .environments
705            .get_mut(environment)
706            .and_then(|env| env.workers.get_mut(worker))
707        {
708            record
709                .fresh_agents
710                .insert(context.to_string(), classes.to_vec());
711        }
712    }
713
714    /// #3562: the contexts a Worker was last pushed with: empty for a context's
715    /// own Worker, an unrecorded one, and a ledger from before groups.
716    #[cfg(test)]
717    pub(crate) fn members_of(&self, environment: &str, worker: &str) -> &[String] {
718        self.environments
719            .get(environment)
720            .and_then(|env| env.workers.get(worker))
721            .map_or(&[], |record| record.contexts.as_slice())
722    }
723
724    /// I4 (#1970): record the contract `worker`'s declared foreign callers may
725    /// call it at, as of this push ([`WorkerRecord::foreign`]). Called right
726    /// after [`DeployLock::record_deployed`]; a Worker not yet recorded is
727    /// ignored.
728    pub(crate) fn record_foreign(
729        &mut self,
730        environment: &str,
731        worker: &str,
732        foreign: BTreeMap<String, BTreeMap<String, String>>,
733    ) {
734        if let Some(record) = self
735            .environments
736            .get_mut(environment)
737            .and_then(|env| env.workers.get_mut(worker))
738        {
739            record.foreign = foreign;
740        }
741    }
742
743    /// #2077: record the contracts `worker` was compiled against as of this
744    /// push ([`WorkerRecord::expects`]). Called right after
745    /// [`DeployLock::record_deployed`]; a Worker not yet recorded is ignored.
746    /// `Some` even when empty: this build *knows* what the Worker calls.
747    pub(crate) fn record_expects(&mut self, environment: &str, worker: &str, expects: Expects) {
748        if let Some(record) = self
749            .environments
750            .get_mut(environment)
751            .and_then(|env| env.workers.get_mut(worker))
752        {
753            record.expects = Some(expects);
754        }
755    }
756
757    /// #2485: record the structured form behind the contracts a Worker provides
758    /// and expects as of this push, filed by hash ([`DeployLock::contract_shapes`]).
759    /// Called right after [`DeployLock::record_deployed`]. Entries no Worker's
760    /// record references any more are kept up to [`RECENT_SHAPES`], oldest
761    /// dropped first, so a `bynk revert` can still classify the contracts it
762    /// restores (#3112).
763    pub(crate) fn record_shapes(
764        &mut self,
765        shapes: BTreeMap<String, String>,
766        expects_shapes: BTreeMap<String, BTreeMap<String, String>>,
767    ) {
768        let texts = shapes
769            .into_values()
770            .chain(expects_shapes.into_values().flat_map(BTreeMap::into_values));
771        for text in texts {
772            let Some(shape) = ServiceShape::from_text(&text) else {
773                continue;
774            };
775            let hash = shape.hash();
776            // Already filed: leave it where it is, so a push that changes
777            // nothing leaves the committed lock byte-identical.
778            if self.contract_shapes.iter().any(|e| e.hash == hash) {
779                continue;
780            }
781            self.contract_shapes
782                .push(ContractShape { hash, shape: text });
783        }
784        let live: BTreeSet<String> = self
785            .environments
786            .values()
787            .flat_map(|env| env.workers.values())
788            .flat_map(|w| {
789                w.contracts.iter().flat_map(BTreeMap::values).chain(
790                    w.expects
791                        .iter()
792                        .flat_map(|e| e.values().flat_map(BTreeMap::values)),
793                )
794            })
795            .cloned()
796            .collect();
797        let mut spare = self
798            .contract_shapes
799            .iter()
800            .filter(|e| !live.contains(&e.hash))
801            .count();
802        self.contract_shapes.retain(|e| {
803            if live.contains(&e.hash) {
804                return true;
805            }
806            let keep = spare <= RECENT_SHAPES;
807            spare -= 1;
808            keep
809        });
810    }
811
812    /// The shape filed under `hash`, if it hashes to it.
813    fn shape_for(&self, hash: &str) -> Option<ServiceShape> {
814        let entry = self.contract_shapes.iter().find(|e| e.hash == hash)?;
815        ServiceShape::from_text_checked(&entry.shape, hash)
816    }
817
818    /// #2485: the shape `worker` provides `service` at, if the ledger holds one
819    /// for the hash recorded for it (and it hashes to it).
820    pub(crate) fn live_shape(
821        &self,
822        environment: &str,
823        worker: &str,
824        service: &str,
825    ) -> Option<ServiceShape> {
826        let record = self.environments.get(environment)?.workers.get(worker)?;
827        self.shape_for(record.contracts.as_ref()?.get(service)?)
828    }
829
830    /// #2485: the shape `caller` was compiled against for `dependency.service`,
831    /// under the same trust rule as [`DeployLock::live_shape`].
832    pub(crate) fn expected_shape(
833        &self,
834        environment: &str,
835        caller: &str,
836        dependency: &str,
837        service: &str,
838    ) -> Option<ServiceShape> {
839        let record = self.environments.get(environment)?.workers.get(caller)?;
840        self.shape_for(record.expects.as_ref()?.get(dependency)?.get(service)?)
841    }
842
843    /// #2077: every Worker the ledger records as deployed in `environment`,
844    /// with what it was compiled against — `None` when its record predates
845    /// [`WorkerRecord::expects`].
846    pub(crate) fn live_expects(
847        &self,
848        environment: &str,
849    ) -> impl Iterator<Item = (&str, Option<&Expects>)> {
850        self.environments
851            .get(environment)
852            .into_iter()
853            .flat_map(|env| env.workers.iter())
854            .filter(|(_, record)| record.deployed)
855            .map(|(worker, record)| (worker.as_str(), record.expects.as_ref()))
856    }
857
858    /// I4 (#1970): what the ledger recorded `worker`'s foreign callers may call
859    /// it at, empty when it recorded none.
860    #[cfg(test)]
861    pub(crate) fn live_foreign(
862        &self,
863        environment: &str,
864        worker: &str,
865    ) -> Option<&BTreeMap<String, BTreeMap<String, String>>> {
866        self.environments
867            .get(environment)
868            .and_then(|env| env.workers.get(worker))
869            .map(|record| &record.foreign)
870    }
871
872    /// v0.177 (#643): what the ledger believes `worker` currently provides.
873    ///
874    /// `None` for both "never deployed" and "deployed before contracts were
875    /// recorded" — in each case the ledger cannot speak, and the gate must not
876    /// invent an answer.
877    pub(crate) fn live_contracts(
878        &self,
879        environment: &str,
880        worker: &str,
881    ) -> Option<&BTreeMap<String, String>> {
882        self.environments
883            .get(environment)
884            .and_then(|env| env.workers.get(worker))
885            .and_then(|record| record.contracts.as_ref())
886    }
887}
888
889/// Slice 5: every ledger entry for this environment that the current build no
890/// longer declares. Owned, not borrowed — ledger-derived names don't share
891/// `Plan<'a>`'s lifetime over `order`/`resources` (the `PlanSecret.name:
892/// String` precedent below).
893///
894/// `kv` and `workers` are independent checks, deliberately not merged: both
895/// are keyed by worker name in the ledger (`Environment`, above), so a
896/// context removed from source that had KV is reported as **two** orphans,
897/// one per map, not one combined line. `--prune` (when it lands) treats them
898/// independently too — the `kv` line is prunable, the `workers` line is
899/// report-only (a whole-Worker delete is a materially larger blast radius
900/// than a namespace or a queue, and out of this slice's scope).
901#[derive(Debug, Default, PartialEq, Eq, Serialize)]
902pub(crate) struct Orphans {
903    pub(crate) kv: Vec<OrphanKv>,
904    /// P5 (#2323): recorded R2 buckets the build no longer declares. Reported
905    /// only: a bucket holds data, so `--prune` never deletes one (and R2
906    /// refuses to delete a non-empty one anyway).
907    #[serde(skip_serializing_if = "Vec::is_empty")]
908    pub(crate) r2: Vec<OrphanR2>,
909    /// #3479: recorded Vectorize indexes the build no longer declares. An
910    /// index holds vectors, so `--prune` deletes one only behind its
911    /// confirmation (as for KV); an adopted one is only ever reported.
912    #[serde(skip_serializing_if = "Vec::is_empty")]
913    pub(crate) vectorize: Vec<OrphanVectorize>,
914    /// P4a (#2602): recorded D1 databases the build no longer declares.
915    /// Reported only, as buckets are: a database holds data.
916    #[serde(skip_serializing_if = "Vec::is_empty")]
917    pub(crate) d1: Vec<OrphanD1>,
918    /// #3319: recorded Hyperdrive configs the build no longer declares. A
919    /// config holds no data, so `--prune` deletes one the deploy made; an
920    /// adopted one is only ever reported.
921    #[serde(skip_serializing_if = "Vec::is_empty")]
922    pub(crate) hyperdrive: Vec<OrphanHyperdrive>,
923    pub(crate) workers: Vec<String>,
924    /// #3562: the contexts of each orphaned Worker the ledger recorded as a
925    /// group's, by Worker name, so the report names a removed group's members.
926    #[serde(skip_serializing_if = "BTreeMap::is_empty")]
927    pub(crate) worker_contexts: BTreeMap<String, Vec<String>>,
928    /// #3562: the script name of each orphaned Worker whose script is not named
929    /// by its key (a renamed group), by key.
930    #[serde(skip_serializing_if = "BTreeMap::is_empty")]
931    pub(crate) worker_scripts: BTreeMap<String, String>,
932    /// #3562 (G5): the agent state each orphaned Worker's script still holds (context →
933    /// classes), from a move accepted with `--accept-fresh-agent`, by Worker.
934    #[serde(skip_serializing_if = "BTreeMap::is_empty")]
935    pub(crate) worker_agent_state: BTreeMap<String, BTreeMap<String, Vec<String>>>,
936    pub(crate) queues: Vec<String>,
937}
938
939impl Orphans {
940    /// Whether `--prune` would actually delete anything. **Not** the same as
941    /// checking whether every field is empty (review, #840): `workers`
942    /// orphans are report-only (DECISION C — never `wrangler delete`), so a
943    /// project whose only orphan is an unprunable Worker must not trigger
944    /// `confirm_prune`'s prompt at all — `Delete 0 resource(s)?` is a bug,
945    /// not a valid state.
946    pub(crate) fn has_prunable(&self) -> bool {
947        kinds_have_prunable(self)
948    }
949
950    /// These orphans as the account names them under `environment`, for the
951    /// plan to show (#2028): a queue by the [`env_qualify`]d name `--prune`
952    /// deletes, a Worker by its [`deployed_worker_name`]. A KV orphan keeps
953    /// its Worker's ledger key: its line names the ledger entry, not the
954    /// namespace's title ([`kv_title`]), which a namespace made before #2037
955    /// may not match.
956    /// An orphaned Worker as the account names it: its script name when that is
957    /// not its key, in `environment`.
958    fn shown_worker(&self, environment: &str, worker: &str) -> String {
959        let script = self
960            .worker_scripts
961            .get(worker)
962            .map_or(worker, String::as_str);
963        deployed_worker_name(environment, script)
964    }
965
966    pub(crate) fn as_named_in(&self, environment: &str) -> Orphans {
967        let mut shown = Orphans {
968            kv: Vec::new(),
969            r2: Vec::new(),
970            d1: Vec::new(),
971            hyperdrive: Vec::new(),
972            vectorize: Vec::new(),
973            workers: self
974                .workers
975                .iter()
976                .map(|worker| self.shown_worker(environment, worker))
977                .collect(),
978            worker_contexts: self
979                .worker_contexts
980                .iter()
981                .map(|(worker, contexts)| {
982                    (self.shown_worker(environment, worker), contexts.clone())
983                })
984                .collect(),
985            worker_scripts: BTreeMap::new(),
986            worker_agent_state: self
987                .worker_agent_state
988                .iter()
989                .map(|(worker, state)| (self.shown_worker(environment, worker), state.clone()))
990                .collect(),
991            queues: Vec::new(),
992        };
993        show_kind_orphans(self, environment, &mut shown);
994        shown
995    }
996}
997
998/// The orphan diff: ledger vs. the current build's full declared resource
999/// set, regardless of `--context` — `resources` already spans the *whole*
1000/// project (`project_resources`, called from `run()` over `available` — every
1001/// worker `workers::discover_workers` found — not the `--context`-narrowed
1002/// `order`/`selected`), so `resources.keys()` alone is the full live-worker
1003/// set and this reuses data `run()` already has rather than reading anything
1004/// new. No live Cloudflare call: the report half of reconciliation costs
1005/// nothing and needs no auth.
1006///
1007/// Pure, so the diff — including the shared-queue case (a queue two contexts
1008/// still consume must never appear orphaned because a *third* context that
1009/// used to consume it was removed) — is tested without a build tree.
1010pub(crate) fn find_orphans(
1011    lock: &DeployLock,
1012    environment: &str,
1013    resources: &BTreeMap<String, Resources>,
1014) -> Orphans {
1015    let Some(env) = lock.environments.get(environment) else {
1016        return Orphans::default();
1017    };
1018    let mut orphans = Orphans {
1019        r2: Vec::new(),
1020        vectorize: Vec::new(),
1021        d1: Vec::new(),
1022        hyperdrive: Vec::new(),
1023        kv: Vec::new(),
1024        workers: env
1025            .workers
1026            .keys()
1027            .filter(|worker| !resources.contains_key(worker.as_str()))
1028            .cloned()
1029            .collect(),
1030        worker_contexts: env
1031            .workers
1032            .iter()
1033            .filter(|(worker, record)| {
1034                !resources.contains_key(worker.as_str()) && !record.contexts.is_empty()
1035            })
1036            .map(|(worker, record)| (worker.clone(), record.contexts.clone()))
1037            .collect(),
1038        worker_scripts: env
1039            .workers
1040            .iter()
1041            .filter(|(worker, _)| !resources.contains_key(worker.as_str()))
1042            .filter_map(|(worker, record)| Some((worker.clone(), record.script.clone()?)))
1043            .collect(),
1044        worker_agent_state: env
1045            .workers
1046            .iter()
1047            .filter(|(worker, record)| {
1048                !resources.contains_key(worker.as_str()) && !record.fresh_agents.is_empty()
1049            })
1050            .map(|(worker, record)| (worker.clone(), record.fresh_agents.clone()))
1051            .collect(),
1052        queues: Vec::new(),
1053    };
1054    // 1D.1 (#3929): each converted kind's orphans.
1055    find_kind_orphans(&OrphanCx { env, resources }, &mut orphans);
1056    orphans
1057}
1058
1059pub(crate) fn read_lock(path: &Path) -> Result<DeployLock, String> {
1060    if !path.exists() {
1061        return Ok(DeployLock {
1062            version: lock_version(),
1063            ..Default::default()
1064        });
1065    }
1066    let text = std::fs::read_to_string(path).map_err(|e| e.to_string())?;
1067    // A zero-byte or whitespace-only ledger is a truncated write, not an empty
1068    // project. Accepting it as an empty v1 ledger would tell the planner that no
1069    // namespaces exist and re-mint every one — the exact orphaning the ledger
1070    // exists to prevent (#736, ADR 0180). Fail hard so the operator restores it.
1071    if text.trim().is_empty() {
1072        return Err(format!(
1073            "deploy ledger `{}` is empty or truncated (corrupt); refusing to \
1074             treat it as a fresh project — restore it from version control",
1075            path.display()
1076        ));
1077    }
1078    // A file that does not parse — including one truncated mid-table or missing
1079    // its now-required `version` — is corruption too, and gets the same
1080    // restore-it guidance rather than a bare toml diagnostic. A version we simply
1081    // do not support is a distinct case (a newer or older format), not corruption.
1082    let mut lock: DeployLock = toml::from_str(&text).map_err(|e| {
1083        format!(
1084            "deploy ledger `{}` is corrupt ({e}) — restore it from version control",
1085            path.display()
1086        )
1087    })?;
1088    if lock.version != lock_version() {
1089        return Err(format!("unsupported deploy lock version {}", lock.version));
1090    }
1091    lock.fold_legacy_shapes();
1092    Ok(lock)
1093}
1094
1095/// Distinguishes concurrent temp ledgers written by the same process.
1096static TMP_COUNTER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
1097
1098pub(crate) fn write_lock(path: &Path, lock: &DeployLock) -> Result<(), String> {
1099    #[cfg(test)]
1100    write_watch::observe(path, lock)?;
1101    let body = toml::to_string_pretty(lock).map_err(|e| e.to_string())?;
1102    // Atomic, durable replace: write a sibling temp file, fsync it, then rename
1103    // it over the ledger. A power loss or kill can then only leave the intact old
1104    // file or the intact new one — never a truncated ledger that reads as empty
1105    // (#736). Atomicity-for-readers (the rename) is not enough on its own: after
1106    // a crash the rename can be journaled while the temp's data blocks are still
1107    // only in the page cache, so we `sync_all` the data before the rename and
1108    // fsync the directory after it to make the new name itself durable.
1109    let dir = path
1110        .parent()
1111        .filter(|p| !p.as_os_str().is_empty())
1112        .unwrap_or_else(|| Path::new("."));
1113    let file_name = path
1114        .file_name()
1115        .and_then(|n| n.to_str())
1116        .unwrap_or(LOCK_FILE);
1117
1118    // A per-process counter keeps the temp name unique within a process, and
1119    // `create_new` makes the create exclusive — a stale temp from a prior crash
1120    // or a pre-planted symlink at this path is refused rather than followed.
1121    let (tmp, mut file) = loop {
1122        let n = TMP_COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1123        let candidate = dir.join(format!(".{file_name}.{}.{n}.tmp", std::process::id()));
1124        match std::fs::OpenOptions::new()
1125            .write(true)
1126            .create_new(true)
1127            .open(&candidate)
1128        {
1129            Ok(f) => break (candidate, f),
1130            Err(e) if e.kind() == io::ErrorKind::AlreadyExists => continue,
1131            Err(e) => return Err(e.to_string()),
1132        }
1133    };
1134
1135    // From here on, any failure must remove the temp so a full disk or crash
1136    // does not litter the project with `.bynk.deploy.lock.*.tmp` files.
1137    let write_then_sync = file
1138        .write_all(body.as_bytes())
1139        .and_then(|()| file.sync_all());
1140    if let Err(e) = write_then_sync {
1141        let _ = std::fs::remove_file(&tmp);
1142        return Err(e.to_string());
1143    }
1144    drop(file);
1145
1146    // Preserve the ledger's existing permissions across the replace.
1147    if let Ok(meta) = std::fs::metadata(path) {
1148        let _ = std::fs::set_permissions(&tmp, meta.permissions());
1149    }
1150
1151    if let Err(e) = std::fs::rename(&tmp, path) {
1152        let _ = std::fs::remove_file(&tmp);
1153        return Err(e.to_string());
1154    }
1155    // Best-effort: make the rename itself durable. Directory fsync is a no-op or
1156    // unsupported on some platforms, so a failure here is not fatal.
1157    if let Ok(dir_file) = std::fs::File::open(dir) {
1158        let _ = dir_file.sync_all();
1159    }
1160    Ok(())
1161}
1162
1163/// 1D.2 (#4001): a test's view of every [`write_lock`] on its thread, which may also refuse
1164/// one, so the apply fixtures (`apply_tests.rs`) can pin the ledger after each write and the
1165/// message when a write fails. Nothing watches outside a test.
1166#[cfg(test)]
1167pub(crate) mod write_watch {
1168    use super::*;
1169    use std::cell::RefCell;
1170
1171    /// Called with each ledger about to be written; an `Err` is the write's failure.
1172    pub(crate) type Watch = Box<dyn FnMut(&Path, &DeployLock) -> Result<(), String>>;
1173
1174    thread_local! {
1175        static WATCH: RefCell<Option<Watch>> = const { RefCell::new(None) };
1176    }
1177
1178    /// Run `f` with `watch` seeing every ledger write on this thread.
1179    pub(crate) fn watching<T>(watch: Watch, f: impl FnOnce() -> T) -> T {
1180        WATCH.with(|w| *w.borrow_mut() = Some(watch));
1181        let result = f();
1182        WATCH.with(|w| *w.borrow_mut() = None);
1183        result
1184    }
1185
1186    pub(super) fn observe(path: &Path, lock: &DeployLock) -> Result<(), String> {
1187        WATCH.with(|w| match w.borrow_mut().as_mut() {
1188            Some(watch) => watch(path, lock),
1189            None => Ok(()),
1190        })
1191    }
1192}
1193
1194/// #3513 A: bind a served Worker's `[[mtls_certificates]]` by the ids the last deploy of
1195/// `environment` recorded, for `bynk dev`. An mTLS binding has no local simulation, so the
1196/// development copy runs it on Cloudflare and needs the certificate's real id, which only a deploy
1197/// has resolved. Every binding with a recorded link is bound; the message names each that has
1198/// none (`Err`), for the caller to report and carry on: a call through it then fails, naming it.
1199/// `Ok(false)` when the Worker declares no certificate.
1200pub fn materialise_mtls_for_dev(
1201    project_root: &Path,
1202    worker: &str,
1203    config: &Path,
1204    environment: &str,
1205) -> Result<bool, String> {
1206    let text = std::fs::read_to_string(config).map_err(|e| e.to_string())?;
1207    let bindings = bynk_emit::emitter::wrangler::mtls_certificate_bindings(&text)?;
1208    if bindings.is_empty() {
1209        return Ok(false);
1210    }
1211    let lock = read_lock(&project_root.join(LOCK_FILE))?;
1212    let mut ids = BTreeMap::new();
1213    let mut unlinked = Vec::new();
1214    for binding in bindings {
1215        match lock.recorded::<MtlsCertificate>(environment, worker, &binding) {
1216            Some(link) => {
1217                ids.insert(binding, link.certificate_id.clone());
1218            }
1219            None => unlinked.push(binding),
1220        }
1221    }
1222    if !ids.is_empty() && !materialise_mtls_certificates(config, &ids) {
1223        return Err("could not write generated configuration".into());
1224    }
1225    if unlinked.is_empty() {
1226        return Ok(true);
1227    }
1228    // An unlinked entry is dropped from the development copy, not left to wrangler: marked
1229    // `remote = true` with a name where an id belongs, it might fail the whole startup.
1230    let text = std::fs::read_to_string(config).map_err(|e| e.to_string())?;
1231    let kept = bynk_emit::emitter::wrangler::drop_mtls_certificates(&text, &unlinked)?;
1232    if kept != text {
1233        std::fs::write(config, kept).map_err(|e| e.to_string())?;
1234    }
1235    Err(format!(
1236        "mTLS certificate binding {} of `{worker}` has not been linked under environment `{environment}`, so it is left unbound and a call through it fails; run `bynk deploy --env {environment}` first, which links the certificate by name",
1237        unlinked
1238            .iter()
1239            .map(|b| format!("`{b}`"))
1240            .collect::<Vec<_>>()
1241            .join(", ")
1242    ))
1243}
1244
1245/// Fill a generated worker configuration from the committed deploy ledger.
1246/// This is shared with `bynk dev -- --remote`; local dev leaves placeholders
1247/// alone because Miniflare does not read the Cloudflare namespace id.
1248///
1249/// `environment` (slice 4, #837 review): before `--env` existed every real
1250/// deploy recorded into `"default"` regardless, so hardcoding it here always
1251/// matched. A project deployed only under a non-default `--env` now has
1252/// nothing under `"default"` — reading the wrong section would misreport a
1253/// provisioned project as never deployed, so this reads whichever section
1254/// `bynk dev --env NAME -- --remote` names (default `"default"`, unchanged).
1255pub fn materialise_deploy_state(
1256    project_root: &Path,
1257    worker: &str,
1258    config: &Path,
1259    environment: &str,
1260) -> Result<bool, String> {
1261    // P7.4 (#1305): structural, not a substring search — closes R7.6/R8.20.
1262    let text = std::fs::read_to_string(config).map_err(|e| e.to_string())?;
1263    // S4b (#1967): every namespace still at its placeholder, the bare `KV`
1264    // and each derived instance alike.
1265    let needed = bynk_emit::emitter::wrangler::kv_bindings_needing_ids(&text)?;
1266    // P5 (#2323): each `R2` bucket must have been created by a deploy, and is
1267    // then named as that environment names it.
1268    let buckets = bynk_emit::emitter::wrangler::r2_bucket_entries(&text)?;
1269    // P3 (#2342): each rate limiter must have had its id allocated by a deploy.
1270    let limiters = bynk_emit::emitter::wrangler::ratelimits_needing_ids(&text)?;
1271    // P4a (#2602): each `D1` database must have been created by a deploy, and
1272    // is then bound by the name and id that environment's deploy recorded.
1273    let databases = bynk_emit::emitter::wrangler::d1_database_entries(&text)?;
1274    // #3301: each `StoredSecret` must have been linked by a deploy, and is
1275    // then bound by the store id that deploy recorded.
1276    let stored = bynk_emit::emitter::wrangler::stored_secret_entries(&text)?;
1277    // #3319: each `Postgres` must have had its Hyperdrive config made or
1278    // adopted by a deploy, and is then bound by the id that deploy recorded.
1279    let hyperdrive = bynk_emit::emitter::wrangler::hyperdrive_entries(&text)?;
1280    if needed.is_empty()
1281        && buckets.is_empty()
1282        && limiters.is_empty()
1283        && databases.is_empty()
1284        && stored.is_empty()
1285        && hyperdrive.is_empty()
1286    {
1287        return Ok(false);
1288    }
1289    let lock = read_lock(&project_root.join(LOCK_FILE))?;
1290    let mut limiter_ids = BTreeMap::new();
1291    for binding in limiters {
1292        let Some(id) = lock
1293            .recorded::<RateLimit>(environment, worker, &binding)
1294            .map(|r| r.namespace_id.as_str())
1295        else {
1296            return Err(format!(
1297                "remote rate limiter `{binding}` for `{worker}` has not been provisioned under environment `{environment}`; run `bynk deploy --env {environment}` first"
1298            ));
1299        };
1300        limiter_ids.insert(binding, id.to_string());
1301    }
1302    let mut names = BTreeMap::new();
1303    for (binding, name, jurisdiction) in &buckets {
1304        let Some(recorded) = lock.recorded::<R2>(environment, worker, binding) else {
1305            return Err(format!(
1306                "remote R2 bucket `{binding}` for `{worker}` has not been provisioned under environment `{environment}`; run `bynk deploy --env {environment}` first"
1307            ));
1308        };
1309        if recorded.jurisdiction != *jurisdiction {
1310            return Err(format!(
1311                "remote R2 bucket `{binding}` for `{worker}` was created under another `@jurisdiction` than the source now names; run `bynk deploy --env {environment}` first"
1312            ));
1313        }
1314        names.insert(binding.clone(), r2_bucket_name(environment, name));
1315    }
1316    let mut d1 = BTreeMap::new();
1317    for (binding, _) in &databases {
1318        let Some(recorded) = lock.recorded::<D1>(environment, worker, binding) else {
1319            return Err(format!(
1320                "remote D1 database `{binding}` for `{worker}` has not been provisioned under environment `{environment}`; run `bynk deploy --env {environment}` first"
1321            ));
1322        };
1323        d1.insert(
1324            binding.clone(),
1325            (recorded.name.clone(), recorded.id.clone()),
1326        );
1327    }
1328    let mut store_ids = BTreeMap::new();
1329    for (binding, _, _) in &stored {
1330        let Some(link) = lock.recorded::<StoredSecret>(environment, worker, binding) else {
1331            return Err(format!(
1332                "remote Secrets Store secret `{binding}` for `{worker}` has not been linked under environment `{environment}`; run `bynk deploy --env {environment}` first"
1333            ));
1334        };
1335        store_ids.insert(binding.clone(), link.store_id.clone());
1336    }
1337    let mut hyperdrive_ids = BTreeMap::new();
1338    for (binding, _) in &hyperdrive {
1339        let Some(recorded) = lock.recorded::<Hyperdrive>(environment, worker, binding) else {
1340            return Err(format!(
1341                "remote Hyperdrive config `{binding}` for `{worker}` has not been provisioned under environment `{environment}`; run `bynk deploy --env {environment}` first"
1342            ));
1343        };
1344        hyperdrive_ids.insert(binding.clone(), recorded.id.clone());
1345    }
1346    let mut changed = false;
1347    if !hyperdrive_ids.is_empty() {
1348        if !materialise_hyperdrive_ids(config, &hyperdrive_ids) {
1349            return Err("could not write generated configuration".into());
1350        }
1351        changed = true;
1352    }
1353    if !store_ids.is_empty() {
1354        if !materialise_stored_secret_stores(config, &store_ids) {
1355            return Err("could not write generated configuration".into());
1356        }
1357        changed = true;
1358    }
1359    if !d1.is_empty() {
1360        if !materialise_d1_databases(config, &d1) {
1361            return Err("could not write generated configuration".into());
1362        }
1363        changed = true;
1364    }
1365    if !limiter_ids.is_empty() {
1366        if !materialise_ratelimit_ids(config, &limiter_ids) {
1367            return Err("could not write generated configuration".into());
1368        }
1369        changed = true;
1370    }
1371    let text = std::fs::read_to_string(config).map_err(|e| e.to_string())?;
1372    if !names.is_empty() {
1373        let patched = bynk_emit::emitter::wrangler::materialise_r2_bucket_names(&text, &names)?;
1374        if patched != text {
1375            std::fs::write(config, patched).map_err(|e| e.to_string())?;
1376            changed = true;
1377        }
1378    }
1379    if needed.is_empty() {
1380        return Ok(changed);
1381    }
1382    let mut ids = BTreeMap::new();
1383    for binding in needed {
1384        let Some(id) = lock
1385            .recorded::<Kv>(environment, worker, &binding)
1386            .map(|kv| kv.id.as_str())
1387        else {
1388            let what = if is_bare_kv(&binding) {
1389                format!("remote KV for `{worker}`")
1390            } else {
1391                format!("remote KV namespace `{binding}` for `{worker}`")
1392            };
1393            return Err(format!(
1394                "{what} has not been provisioned under environment `{environment}`; run `bynk deploy --env {environment}` first"
1395            ));
1396        };
1397        ids.insert(binding, id.to_string());
1398    }
1399    if materialise_kv_ids(config, &ids) {
1400        Ok(true)
1401    } else {
1402        Err("could not write generated configuration".into())
1403    }
1404}
1405
1406// ---------------------------------------------------------------------------
1407// Slice 5: reconciliation — orphan pruning
1408// ---------------------------------------------------------------------------
1409
1410/// Print exactly what `--prune` is about to delete, then ask once for the
1411/// whole batch — the "strictly stronger gate" the track doc (§6) calls for on
1412/// top of [`confirm`]'s creation gate. `--yes` alone does **not** imply this:
1413/// a CI job that wants unattended pruning must pass `--yes` **and**
1414/// `--prune` together, the same non-interactive-requires-`--yes` shape
1415/// [`confirm`] already uses, just with its own prompt so a script that only
1416/// meant to authorise *creation* cannot accidentally also authorise deletion.
1417pub(crate) fn confirm_prune(yes: bool, orphans: &Orphans, environment: &str) -> bool {
1418    // 1D.1 (#3929): each converted kind's, in the list's order (ruled for 1D.1c), first.
1419    let kinds = announce_prunable_kinds(orphans, environment);
1420    confirm_deletion_prompt(yes, kinds)
1421}
1422
1423/// The `--yes`-or-ask tail of [`confirm_prune`], shared with the Email Routing
1424/// removal gate (#3328): `count` things are about to be deleted.
1425pub(crate) fn confirm_deletion_prompt(yes: bool, count: usize) -> bool {
1426    if yes {
1427        return true;
1428    }
1429    if !requires_interactive_confirmation(yes, io::stdin().is_terminal()) {
1430        emsg!("bynk: error: refusing to prune in a non-interactive session without --yes");
1431        return false;
1432    }
1433    eprint!("Delete {count} resource(s)? [y/N] ");
1434    let _ = io::stderr().flush();
1435    let mut answer = String::new();
1436    io::stdin().read_line(&mut answer).is_ok()
1437        && matches!(answer.trim().to_ascii_lowercase().as_str(), "y" | "yes")
1438}
1439
1440/// Delete every orphan `confirm_prune` just named: each converted kind's (1D.1),
1441/// then each queue — never a
1442/// worker (DECISION C: `wrangler delete`'s blast radius, routes/domains/crons
1443/// along with the script, is categorically larger than a namespace or a
1444/// queue, and pruning a whole Worker is explicitly out of this slice).
1445///
1446/// The ledger entry is stripped whether the delete found something to remove
1447/// or found it already gone (DECISION E) — both mean "this resource is not
1448/// there", and treating only a clean delete as ledger-worthy would wedge a
1449/// half-completed prune: crash between a successful Cloudflare delete and the
1450/// ledger write, and the next run would re-report the same orphan and
1451/// re-issue a delete Cloudflare now rejects as not-found.
1452pub(crate) fn prune_orphans(
1453    tools: Tools<'_>,
1454    writer: &mut LedgerWriter<'_>,
1455    environment: &str,
1456    orphans: &Orphans,
1457    lives: Lives<'_>,
1458) -> Result<(), DeployFailure> {
1459    // 1D.1 (#3929): each converted kind's, in the list's order (ruled for 1D.1c), first.
1460    prune_kind_orphans(tools, writer, environment, orphans, lives)?;
1461    Ok(())
1462}
1463
1464#[cfg(test)]
1465pub(crate) mod tests {
1466    use super::*;
1467    use crate::deploy::config::tests::project;
1468
1469    fn names(v: &[&str]) -> Vec<String> {
1470        v.iter().map(|s| s.to_string()).collect()
1471    }
1472
1473    pub(crate) fn lock_with_deployed(workers: &[&str]) -> DeployLock {
1474        let mut lock = DeployLock::default();
1475        for worker in workers {
1476            lock.record_deployed("default", worker, Some(Default::default()));
1477        }
1478        lock
1479    }
1480
1481    /// Record `worker`'s KV namespace, as a real deploy does before it pushes.
1482    pub(crate) fn with_kv(mut lock: DeployLock, worker: &str) -> DeployLock {
1483        lock.environments
1484            .entry("default".into())
1485            .or_default()
1486            .kv
1487            .insert(worker.to_string(), KvNamespace { id: "ns-id".into() });
1488        lock
1489    }
1490
1491    /// Record `worker`'s derived KV instance `binding` (S4b, #1967).
1492    pub(crate) fn with_kv_instance(
1493        mut lock: DeployLock,
1494        worker: &str,
1495        binding: &str,
1496    ) -> DeployLock {
1497        lock.record::<Kv>(
1498            "default",
1499            worker,
1500            binding,
1501            KvNamespace::of(&format!("{binding}-id")),
1502        );
1503        lock
1504    }
1505
1506    fn bare_orphan(worker: &str) -> OrphanKv {
1507        OrphanKv {
1508            worker: worker.to_string(),
1509            binding: None,
1510        }
1511    }
1512
1513    fn instance_orphan(worker: &str, binding: &str) -> OrphanKv {
1514        OrphanKv {
1515            worker: worker.to_string(),
1516            binding: Some(binding.to_string()),
1517        }
1518    }
1519
1520    /// Mark `queue` as one this project has already created.
1521    pub(crate) fn with_queue(mut lock: DeployLock, queue: &str) -> DeployLock {
1522        QueueTable::created(
1523            lock.environments
1524                .entry(String::from("default"))
1525                .or_default(),
1526            queue,
1527        );
1528        lock
1529    }
1530
1531    fn scratch_lock_path(label: &str) -> std::path::PathBuf {
1532        let unique = std::time::SystemTime::now()
1533            .duration_since(std::time::UNIX_EPOCH)
1534            .unwrap()
1535            .as_nanos();
1536        std::env::temp_dir().join(format!(
1537            "bynk-{label}-{}-{unique}.deploy.lock",
1538            std::process::id()
1539        ))
1540    }
1541
1542    fn scratch_lock_dir(label: &str) -> std::path::PathBuf {
1543        let unique = std::time::SystemTime::now()
1544            .duration_since(std::time::UNIX_EPOCH)
1545            .unwrap()
1546            .as_nanos();
1547        let dir =
1548            std::env::temp_dir().join(format!("bynk-{label}-{}-{unique}", std::process::id()));
1549        std::fs::create_dir_all(&dir).unwrap();
1550        dir
1551    }
1552
1553    fn temp_litter(dir: &Path) -> Vec<std::path::PathBuf> {
1554        std::fs::read_dir(dir)
1555            .unwrap()
1556            .filter_map(|e| e.ok().map(|e| e.path()))
1557            .filter(|p| p.extension().is_some_and(|x| x == "tmp"))
1558            .collect()
1559    }
1560
1561    /// P3 (#2342): an id starts at its limiter's own seed and probes upward
1562    /// past those the ledger holds, in any environment; a recorded id is
1563    /// kept; a forgotten one is free again.
1564    #[test]
1565    fn rate_limiter_ids_are_allocated_across_environments() {
1566        let mut lock = DeployLock::default();
1567        let api = ratelimit_seed("default", "api", "RATELIMIT_A");
1568        assert_eq!(
1569            allocate_in(&mut lock, "default", "api", "RATELIMIT_A"),
1570            (api.to_string(), true)
1571        );
1572        assert_eq!(
1573            allocate_in(&mut lock, "default", "api", "RATELIMIT_A"),
1574            (api.to_string(), false)
1575        );
1576        let staging = allocate_in(&mut lock, "staging", "api", "RATELIMIT_A").0;
1577        assert_ne!(staging, api.to_string(), "each environment its own");
1578        // A seed another limiter in the ledger already holds probes upward.
1579        let mut crowded = DeployLock::default();
1580        let seed = ratelimit_seed("default", "web", "RATELIMIT_B");
1581        crowded
1582            .environments
1583            .entry("staging".into())
1584            .or_default()
1585            .ratelimit_instances
1586            .insert(
1587                "other".into(),
1588                BTreeMap::from([(
1589                    "RATELIMIT_X".into(),
1590                    RateLimitNamespace {
1591                        namespace_id: seed.to_string(),
1592                    },
1593                )]),
1594            );
1595        assert_eq!(
1596            allocate_in(&mut crowded, "default", "web", "RATELIMIT_B"),
1597            ((seed + 1).to_string(), true)
1598        );
1599        // Forgotten after the push once the source declares none: twice is harmless.
1600        let none = Resources::default();
1601        for _ in 0..2 {
1602            RateLimit::after_push(lock.environments.get_mut("default").unwrap(), "api", &none);
1603        }
1604        assert!(
1605            !lock.environments["default"]
1606                .ratelimit_instances
1607                .contains_key("api")
1608        );
1609    }
1610
1611    /// P3 (#2342, review): two projects on one account have separate ledgers,
1612    /// so neither can see the other's ids. Their Workers' names differ (a
1613    /// Worker name is unique on an account), and so do the seeds their
1614    /// limiters start from: neither starts where the other did.
1615    #[test]
1616    fn two_projects_ledgers_do_not_start_their_limiters_at_one_id() {
1617        let mut shop = DeployLock::default();
1618        let mut registry = DeployLock::default();
1619        let a = allocate_in(&mut shop, "default", "shop-cart", "RATELIMIT_LOGIN").0;
1620        let b = allocate_in(
1621            &mut registry,
1622            "default",
1623            "registry-publish",
1624            "RATELIMIT_LOGIN",
1625        )
1626        .0;
1627        assert_ne!(a, b);
1628        for id in [&a, &b] {
1629            let n: u64 = id.parse().unwrap();
1630            assert!(
1631                (FIRST_RATELIMIT_NAMESPACE..FIRST_RATELIMIT_NAMESPACE + RATELIMIT_NAMESPACE_SPAN)
1632                    .contains(&n)
1633            );
1634        }
1635    }
1636
1637    #[test]
1638    fn lock_round_trip_is_environment_keyed() {
1639        let lock = DeployLock {
1640            version: 1,
1641            environments: BTreeMap::from([(
1642                "default".into(),
1643                Environment {
1644                    deleted_classes: BTreeMap::new(),
1645                    renamed_classes: BTreeMap::new(),
1646                    email_addresses: BTreeMap::new(),
1647                    kv: BTreeMap::from([("api".into(), KvNamespace { id: "abc".into() })]),
1648                    kv_instances: BTreeMap::from([(
1649                        "api".into(),
1650                        BTreeMap::from([("KV_SESSIONS".into(), KvNamespace { id: "s".into() })]),
1651                    )]),
1652                    vectorize_instances: BTreeMap::new(),
1653                    container_images: BTreeMap::new(),
1654                    ratelimit_instances: BTreeMap::from([(
1655                        "api".into(),
1656                        BTreeMap::from([(
1657                            "RATELIMIT_LOGIN".into(),
1658                            RateLimitNamespace {
1659                                namespace_id: "1000".into(),
1660                            },
1661                        )]),
1662                    )]),
1663                    r2_instances: BTreeMap::from([(
1664                        "api".into(),
1665                        BTreeMap::from([(
1666                            "R2_ARCHIVES".into(),
1667                            R2Bucket {
1668                                name: "api-archives".into(),
1669                                jurisdiction: Some("eu".into()),
1670                                superseded: vec![R2Past {
1671                                    name: "api-archives".into(),
1672                                    jurisdiction: None,
1673                                }],
1674                            },
1675                        )]),
1676                    )]),
1677                    d1_instances: BTreeMap::from([(
1678                        "api".into(),
1679                        BTreeMap::from([(
1680                            "D1_ORDERS".into(),
1681                            D1Record {
1682                                name: "api-orders".into(),
1683                                id: "0d1d0000-0000-4000-8000-000000000001".into(),
1684                                superseded: vec![D1Past {
1685                                    name: "api-orders-old".into(),
1686                                    id: "0d1d0000-0000-4000-8000-000000000000".into(),
1687                                }],
1688                            },
1689                        )]),
1690                    )]),
1691                    hyperdrive_instances: BTreeMap::new(),
1692                    ai_search_links: BTreeMap::new(),
1693                    mtls_certificate_links: BTreeMap::new(),
1694                    stored_secret_links: BTreeMap::from([(
1695                        "api".into(),
1696                        BTreeMap::from([(
1697                            "SECRET_STRIPE_KEY".into(),
1698                            StoredSecretLink {
1699                                store: "payments".into(),
1700                                store_id: "0b5e1c2a3d4f45678901234567890abc".into(),
1701                                secret: "stripe-live".into(),
1702                            },
1703                        )]),
1704                    )]),
1705                    workers: BTreeMap::from([(
1706                        "api".into(),
1707                        WorkerRecord {
1708                            deployed: true,
1709                            contracts: Default::default(),
1710                            expects: Some(BTreeMap::from([(
1711                                "shop.payment".into(),
1712                                BTreeMap::from([("authorise".into(), "febd15c2757b72e1".into())]),
1713                            )])),
1714                            foreign: BTreeMap::from([(
1715                                "Legacy".into(),
1716                                BTreeMap::from([("ping".into(), "4082ce9e2b74e919".into())]),
1717                            )]),
1718                            shapes: BTreeMap::new(),
1719                            expects_shapes: BTreeMap::new(),
1720                            contexts: Vec::new(),
1721                            script: None,
1722                            fresh_agents: BTreeMap::new(),
1723                        },
1724                    )]),
1725                    queues: BTreeSet::from(["intake".to_string()]),
1726                    reused_queues: BTreeSet::new(),
1727                },
1728            )]),
1729            contract_shapes: Vec::new(),
1730        };
1731        assert_eq!(
1732            toml::from_str::<DeployLock>(&toml::to_string_pretty(&lock).unwrap()).unwrap(),
1733            lock
1734        );
1735    }
1736
1737    #[test]
1738    fn a_slice_0_ledger_without_workers_or_queues_still_reads() {
1739        // Both tables are additive: a ledger committed before slice 2 (workers)
1740        // or slice 1 (queues) must keep working, reporting nothing recorded
1741        // rather than failing to parse. #600 D4: the version stays 1, so this
1742        // is the whole migration story.
1743        let lock: DeployLock = toml::from_str(
1744            r#"
1745            version = 1
1746            [environments.default.kv.api]
1747            id = "abc"
1748        "#,
1749        )
1750        .expect("a slice-0 ledger must still parse");
1751        assert_eq!(
1752            lock.recorded::<Kv>("default", "api", "KV")
1753                .map(|kv| kv.id.as_str()),
1754            Some("abc")
1755        );
1756        assert!(!lock.is_deployed("default", "api"));
1757        assert!(lock.recorded::<Queue>("default", "", "intake").is_none());
1758    }
1759
1760    #[test]
1761    fn the_queue_set_serialises_as_names_under_the_environment() {
1762        // The committed shape is a documented surface — a reviewer reads this
1763        // file in a diff. Queues are environment-wide names, not a per-worker
1764        // table, and carry no id.
1765        let mut lock = DeployLock {
1766            version: 1,
1767            ..Default::default()
1768        };
1769        QueueTable::created(
1770            lock.environments
1771                .entry(String::from("default"))
1772                .or_default(),
1773            "job-intake",
1774        );
1775        QueueTable::created(
1776            lock.environments
1777                .entry(String::from("default"))
1778                .or_default(),
1779            "job-retry",
1780        );
1781        let text = toml::to_string_pretty(&lock).unwrap();
1782        assert!(
1783            text.contains("[environments.default]") && text.contains("queues = ["),
1784            "the queue set is environment-wide, not a per-worker table: {text}"
1785        );
1786        for queue in ["job-intake", "job-retry"] {
1787            assert!(
1788                text.contains(&format!("\"{queue}\"")),
1789                "{queue} is recorded"
1790            );
1791        }
1792        assert!(
1793            !text.contains("id"),
1794            "a queue is addressed by name — the ledger has no id to record: {text}"
1795        );
1796        assert_eq!(toml::from_str::<DeployLock>(&text).unwrap(), lock);
1797    }
1798
1799    /// #3072: the lock does not list a Worker's static assets (their hashed
1800    /// names change with every page edit and nothing reads them). A lock that
1801    /// still carries an `assets` line reads, and the next write omits it.
1802    #[test]
1803    fn an_old_locks_assets_line_is_read_and_not_written_back() {
1804        let old = "version = 1\n\n[environments.default.workers.board]\ndeployed = true\nassets = [\"/_assets/board.1a2b.css\"]\n";
1805        let lock: DeployLock = toml::from_str(old).unwrap();
1806        assert!(lock.is_deployed("default", "board"));
1807        let text = toml::to_string_pretty(&lock).unwrap();
1808        assert!(!text.contains("assets"), "{text}");
1809        assert!(!text.contains("/_assets/"), "{text}");
1810    }
1811
1812    /// I4 (#1970): a Worker's foreign callers round-trip, a later push
1813    /// replaces them, and a Worker with none writes no `foreign` table.
1814    #[test]
1815    fn a_workers_foreign_callers_round_trip_and_none_is_not_written() {
1816        let mut lock = DeployLock {
1817            version: 1,
1818            ..Default::default()
1819        };
1820        let legacy = BTreeMap::from([(
1821            "Legacy".to_string(),
1822            BTreeMap::from([("ping".to_string(), "4082ce9e2b74e919".to_string())]),
1823        )]);
1824        lock.record_deployed("default", "shop-orders", Some(Default::default()));
1825        lock.record_foreign("default", "shop-orders", legacy.clone());
1826        lock.record_deployed("default", "shop-front", Some(Default::default()));
1827        lock.record_foreign("default", "shop-front", BTreeMap::new());
1828        let text = toml::to_string_pretty(&lock).unwrap();
1829        assert!(text.contains("4082ce9e2b74e919"), "{text}");
1830        assert_eq!(
1831            text.matches("foreign").count(),
1832            1,
1833            "only `shop-orders`: {text}"
1834        );
1835        let read = toml::from_str::<DeployLock>(&text).unwrap();
1836        assert_eq!(read, lock);
1837        assert_eq!(read.live_foreign("default", "shop-orders"), Some(&legacy));
1838        // A later push records what that build declares, not a union.
1839        lock.record_deployed("default", "shop-orders", Some(Default::default()));
1840        lock.record_foreign("default", "shop-orders", BTreeMap::new());
1841        assert_eq!(
1842            lock.live_foreign("default", "shop-orders"),
1843            Some(&BTreeMap::new())
1844        );
1845        // A Worker never recorded is left alone.
1846        lock.record_foreign("default", "never", legacy);
1847        assert_eq!(lock.live_foreign("default", "never"), None);
1848    }
1849
1850    /// #2485: the structure behind each hash round-trips, is omitted when
1851    /// empty (so a ledger written without shapes is byte-identical), and is
1852    /// trusted only while it hashes to the hash recorded beside it.
1853    #[test]
1854    fn contract_shapes_round_trip_and_are_trusted_only_with_their_hash() {
1855        use bynk_check::contract_compat::{ServiceShape, Shape};
1856        let shape = ServiceShape {
1857            name: "charge".into(),
1858            params: vec![("order".into(), Shape::Base("Int".into()))],
1859            ret: Shape::Base("Bool".into()),
1860        };
1861        let mut lock = DeployLock {
1862            version: 1,
1863            ..Default::default()
1864        };
1865        lock.record_deployed(
1866            "default",
1867            "shop-payment",
1868            Some(BTreeMap::from([("charge".to_string(), shape.hash())])),
1869        );
1870        assert!(
1871            !toml::to_string_pretty(&lock).unwrap().contains("shapes"),
1872            "no shapes recorded, none written"
1873        );
1874        lock.record_shapes(
1875            BTreeMap::from([("charge".to_string(), shape.to_text())]),
1876            BTreeMap::new(),
1877        );
1878        let read: DeployLock = toml::from_str(&toml::to_string_pretty(&lock).unwrap()).unwrap();
1879        assert_eq!(
1880            read.live_shape("default", "shop-payment", "charge"),
1881            Some(shape.clone())
1882        );
1883        assert_eq!(read.live_shape("default", "shop-payment", "other"), None);
1884        // A push that changes the contract without a fresh shape leaves a
1885        // stale one, which no longer hashes to the record and so is ignored.
1886        lock.record_deployed(
1887            "default",
1888            "shop-payment",
1889            Some(BTreeMap::from([("charge".to_string(), "0".repeat(16))])),
1890        );
1891        assert_eq!(lock.live_shape("default", "shop-payment", "charge"), None);
1892    }
1893
1894    /// #3112: a revert replaces the Worker's contract hashes with the target's
1895    /// and drops nothing it can still classify: the target's shape is found by
1896    /// hash, from the push that recorded it.
1897    #[test]
1898    fn a_reverted_contract_still_resolves_its_shape_by_hash() {
1899        use bynk_check::contract_compat::{ServiceShape, Shape};
1900        let shape = |ret: &str| ServiceShape {
1901            name: "charge".into(),
1902            params: vec![("order".into(), Shape::Base("Int".into()))],
1903            ret: Shape::Base(ret.into()),
1904        };
1905        let (v1, v2) = (shape("Bool"), shape("Int"));
1906        let mut lock = DeployLock {
1907            version: 1,
1908            ..Default::default()
1909        };
1910        for s in [&v1, &v2] {
1911            lock.record_deployed(
1912                "default",
1913                "pay",
1914                Some(BTreeMap::from([("charge".to_string(), s.hash())])),
1915            );
1916            lock.record_shapes(
1917                BTreeMap::from([("charge".to_string(), s.to_text())]),
1918                BTreeMap::new(),
1919            );
1920        }
1921        assert_eq!(lock.live_shape("default", "pay", "charge"), Some(v2));
1922        // The revert: v1's hash again, no shape handed over.
1923        lock.record_deployed(
1924            "default",
1925            "pay",
1926            Some(BTreeMap::from([("charge".to_string(), v1.hash())])),
1927        );
1928        assert_eq!(lock.live_shape("default", "pay", "charge"), Some(v1));
1929        let read: DeployLock = toml::from_str(&toml::to_string_pretty(&lock).unwrap()).unwrap();
1930        assert_eq!(read, lock, "the table survives a write and read");
1931    }
1932
1933    /// #3112: recording what is already filed changes nothing (the lock is
1934    /// committed, so a no-op push must not reorder it), and a target whose
1935    /// shape was pruned resolves to no shape, so its skew stays unclassified.
1936    #[test]
1937    fn recording_a_known_shape_changes_nothing_and_a_pruned_one_resolves_to_none() {
1938        use bynk_check::contract_compat::{ServiceShape, Shape};
1939        let shape = |n: usize| ServiceShape {
1940            name: "charge".into(),
1941            params: vec![(format!("p{n}"), Shape::Base("Int".into()))],
1942            ret: Shape::Base("Bool".into()),
1943        };
1944        let mut lock = DeployLock {
1945            version: 1,
1946            ..Default::default()
1947        };
1948        let push = |lock: &mut DeployLock, s: &ServiceShape| {
1949            lock.record_deployed(
1950                "default",
1951                "pay",
1952                Some(BTreeMap::from([("charge".to_string(), s.hash())])),
1953            );
1954            lock.record_shapes(
1955                BTreeMap::from([("charge".to_string(), s.to_text())]),
1956                BTreeMap::new(),
1957            );
1958        };
1959        push(&mut lock, &shape(0));
1960        push(&mut lock, &shape(1));
1961        let before = toml::to_string_pretty(&lock).unwrap();
1962        // Re-record the older, now unreferenced shape alongside the live one.
1963        lock.record_shapes(
1964            BTreeMap::from([
1965                ("a".to_string(), shape(0).to_text()),
1966                ("b".to_string(), shape(1).to_text()),
1967            ]),
1968            BTreeMap::new(),
1969        );
1970        assert_eq!(toml::to_string_pretty(&lock).unwrap(), before);
1971        // Enough later pushes prune shape 0: a revert to it classifies nothing.
1972        for n in 2..(RECENT_SHAPES + 4) {
1973            push(&mut lock, &shape(n));
1974        }
1975        lock.record_deployed(
1976            "default",
1977            "pay",
1978            Some(BTreeMap::from([("charge".to_string(), shape(0).hash())])),
1979        );
1980        assert_eq!(lock.live_shape("default", "pay", "charge"), None);
1981    }
1982
1983    /// #3112: a ledger written with per-Worker shapes still reads, and its
1984    /// shapes move into the table rather than being lost on the next write.
1985    #[test]
1986    fn per_worker_shapes_from_an_older_ledger_are_folded_into_the_table() {
1987        use bynk_check::contract_compat::{ServiceShape, Shape};
1988        let shape = ServiceShape {
1989            name: "charge".into(),
1990            params: vec![("order".into(), Shape::Base("Int".into()))],
1991            ret: Shape::Base("Bool".into()),
1992        };
1993        let dir = std::env::temp_dir().join(format!("bynk-legacy-shapes-{}", std::process::id()));
1994        std::fs::create_dir_all(&dir).unwrap();
1995        let path = dir.join("bynk.deploy.lock");
1996        std::fs::write(
1997            &path,
1998            format!(
1999                "version = 1\n[environments.default.workers.pay]\ndeployed = true\n\
2000                 [environments.default.workers.pay.contracts]\ncharge = '{}'\n\
2001                 [environments.default.workers.pay.shapes]\ncharge = '{}'\n",
2002                shape.hash(),
2003                shape.to_text()
2004            ),
2005        )
2006        .unwrap();
2007        let lock = read_lock(&path).unwrap();
2008        assert_eq!(lock.live_shape("default", "pay", "charge"), Some(shape));
2009        let written = toml::to_string_pretty(&lock).unwrap();
2010        assert!(
2011            !written.contains(".shapes]"),
2012            "not written per Worker again"
2013        );
2014        assert!(written.contains("contract_shapes"));
2015        std::fs::remove_dir_all(&dir).ok();
2016    }
2017
2018    /// #3112: shapes no record references are kept to a bound, oldest first;
2019    /// the live ones are never dropped.
2020    #[test]
2021    fn unreferenced_shapes_are_pruned_to_a_bound_and_live_ones_stay() {
2022        use bynk_check::contract_compat::{ServiceShape, Shape};
2023        let shape = |n: usize| ServiceShape {
2024            name: "charge".into(),
2025            params: vec![(format!("p{n}"), Shape::Base("Int".into()))],
2026            ret: Shape::Base("Bool".into()),
2027        };
2028        let mut lock = DeployLock {
2029            version: 1,
2030            ..Default::default()
2031        };
2032        for n in 0..(RECENT_SHAPES + 5) {
2033            let s = shape(n);
2034            lock.record_deployed(
2035                "default",
2036                "pay",
2037                Some(BTreeMap::from([("charge".to_string(), s.hash())])),
2038            );
2039            lock.record_shapes(
2040                BTreeMap::from([("charge".to_string(), s.to_text())]),
2041                BTreeMap::new(),
2042            );
2043        }
2044        // The live one plus the most recent RECENT_SHAPES others.
2045        assert_eq!(lock.contract_shapes.len(), RECENT_SHAPES + 1);
2046        let newest = shape(RECENT_SHAPES + 4);
2047        assert_eq!(lock.live_shape("default", "pay", "charge"), Some(newest));
2048        let oldest = shape(0).hash();
2049        assert!(lock.shape_for(&oldest).is_none(), "the oldest was pruned");
2050    }
2051
2052    /// #2077: what a Worker expects round-trips — a dotted dependency key, and
2053    /// "known to expect nothing" (`Some({})`), which must not read back as "no
2054    /// record" or every Worker that calls nothing would look unrecorded.
2055    #[test]
2056    fn a_workers_expects_round_trip_and_empty_is_not_no_record() {
2057        let mut lock = DeployLock {
2058            version: 1,
2059            ..Default::default()
2060        };
2061        let orders = BTreeMap::from([(
2062            "shop.payment".to_string(),
2063            BTreeMap::from([("authorise".to_string(), "febd15c2757b72e1".to_string())]),
2064        )]);
2065        lock.record_deployed("default", "shop-orders", Some(Default::default()));
2066        lock.record_expects("default", "shop-orders", orders.clone());
2067        lock.record_deployed("default", "shop-payment", Some(Default::default()));
2068        lock.record_expects("default", "shop-payment", BTreeMap::new());
2069        let text = toml::to_string_pretty(&lock).unwrap();
2070        let read = toml::from_str::<DeployLock>(&text).unwrap();
2071        assert_eq!(read, lock, "{text}");
2072        let live: BTreeMap<_, _> = read.live_expects("default").collect();
2073        assert_eq!(live["shop-orders"], Some(&orders));
2074        assert_eq!(live["shop-payment"], Some(&BTreeMap::new()), "{text}");
2075        // A Worker never recorded is left alone.
2076        lock.record_expects("default", "never", orders);
2077        assert!(lock.live_expects("default").all(|(w, _)| w != "never"));
2078    }
2079
2080    /// #2077: a lock written before `expects` was recorded still loads; its
2081    /// Workers read as deployed with no record, not as expecting nothing.
2082    #[test]
2083    fn a_lock_without_expects_still_reads_as_no_record() {
2084        let lock: DeployLock = toml::from_str(
2085            r#"
2086            version = 1
2087            [environments.default.workers.shop-orders]
2088            deployed = true
2089            [environments.default.workers.shop-payment]
2090            deployed = true
2091            [environments.default.workers.shop-payment.contracts]
2092            authorise = "febd15c2757b72e1"
2093        "#,
2094        )
2095        .expect("a lock without `expects` must still parse");
2096        assert!(lock.is_deployed("default", "shop-orders"));
2097        let live: BTreeMap<_, _> = lock.live_expects("default").collect();
2098        assert_eq!(live["shop-orders"], None);
2099        assert_eq!(live["shop-payment"], None);
2100        // And a record that has no `expects` writes none back.
2101        assert!(!toml::to_string_pretty(&lock).unwrap().contains("expects"));
2102    }
2103
2104    #[test]
2105    fn an_empty_queue_set_is_not_written_at_all() {
2106        // A project with no queues must not grow an empty `queues = []` line in
2107        // a committed file for a slice it does not use.
2108        let mut lock = DeployLock {
2109            version: 1,
2110            ..Default::default()
2111        };
2112        lock.record_deployed("default", "api", Some(Default::default()));
2113        assert!(!toml::to_string_pretty(&lock).unwrap().contains("queues"));
2114    }
2115
2116    #[test]
2117    fn materialises_only_the_placeholder() {
2118        // P7.4 (#1305): the real shape `emit_wrangler_toml` produces — a
2119        // `[[kv_namespaces]]` stanza, not a bare root `id` key (the old
2120        // fixture's shortcut, which only worked because the old
2121        // implementation was a whole-file substring replace that didn't
2122        // care where the placeholder sat).
2123        let unique = std::time::SystemTime::now()
2124            .duration_since(std::time::UNIX_EPOCH)
2125            .unwrap()
2126            .as_nanos();
2127        let path =
2128            std::env::temp_dir().join(format!("bynk-deploy-{}-{}", std::process::id(), unique));
2129        std::fs::write(
2130            &path,
2131            format!(
2132                "[[kv_namespaces]]\nbinding = \"KV\"\nid = \"{KV_NAMESPACE_ID_PLACEHOLDER}\"\n"
2133            ),
2134        )
2135        .unwrap();
2136        assert!(materialise_kv_ids(
2137            &path,
2138            &BTreeMap::from([("KV".to_string(), "abc".to_string())])
2139        ));
2140        let text = std::fs::read_to_string(&path).unwrap();
2141        let parsed: toml::Table = text.parse().unwrap();
2142        assert_eq!(
2143            parsed["kv_namespaces"].as_array().unwrap()[0]["id"].as_str(),
2144            Some("abc")
2145        );
2146        let _ = std::fs::remove_file(path);
2147    }
2148
2149    #[test]
2150    fn two_environments_do_not_cross_contaminate_the_ledger() {
2151        let mut lock = DeployLock {
2152            version: 1,
2153            ..Default::default()
2154        };
2155        lock.record_deployed("staging", "api", None);
2156        QueueTable::created(
2157            lock.environments
2158                .entry(String::from("staging"))
2159                .or_default(),
2160            "jobs",
2161        );
2162        lock.environments
2163            .entry("staging".into())
2164            .or_default()
2165            .kv
2166            .insert(
2167                "api".into(),
2168                KvNamespace {
2169                    id: "kv-staging".into(),
2170                },
2171            );
2172
2173        // "default" was never touched — a `--env staging` run must not
2174        // fabricate or leak into the section a plain `bynk deploy` reads.
2175        assert!(!lock.is_deployed("default", "api"));
2176        assert!(lock.recorded::<Queue>("default", "", "jobs").is_none());
2177        assert_eq!(
2178            lock.recorded::<Kv>("default", "api", "KV")
2179                .map(|kv| kv.id.as_str()),
2180            None
2181        );
2182
2183        assert!(lock.is_deployed("staging", "api"));
2184        assert!(lock.recorded::<Queue>("staging", "", "jobs").is_some());
2185        assert_eq!(
2186            lock.recorded::<Kv>("staging", "api", "KV")
2187                .map(|kv| kv.id.as_str()),
2188            Some("kv-staging")
2189        );
2190    }
2191
2192    /// #837 review: `materialise_deploy_state` (shared with `bynk dev --
2193    /// --remote`) hardcoded `"default"` even after `--env` shipped. Before
2194    /// `--env` existed every real deploy recorded into `"default"`
2195    /// regardless, so that always matched — but a project deployed *only*
2196    /// under `bynk deploy --env staging` now has nothing under `"default"`,
2197    /// and reading the wrong section misreports a provisioned project as
2198    /// never deployed.
2199    #[test]
2200    fn materialise_deploy_state_reads_the_named_environment_not_default() {
2201        let unique = std::time::SystemTime::now()
2202            .duration_since(std::time::UNIX_EPOCH)
2203            .unwrap()
2204            .as_nanos();
2205        let dir = std::env::temp_dir().join(format!(
2206            "bynk-materialise-state-{}-{unique}",
2207            std::process::id()
2208        ));
2209        std::fs::create_dir_all(&dir).unwrap();
2210        let project_root = dir.clone();
2211        let config = dir.join("wrangler.toml");
2212        std::fs::write(
2213            &config,
2214            format!(
2215                "[[kv_namespaces]]\nbinding = \"KV\"\nid = \"{KV_NAMESPACE_ID_PLACEHOLDER}\"\n"
2216            ),
2217        )
2218        .unwrap();
2219
2220        // Provisioned under "staging" alone — the scenario the review named:
2221        // a project that has never had a plain `bynk deploy` (no "default").
2222        let mut lock = DeployLock {
2223            version: 1,
2224            ..Default::default()
2225        };
2226        lock.environments
2227            .entry("staging".into())
2228            .or_default()
2229            .kv
2230            .insert(
2231                "api".into(),
2232                KvNamespace {
2233                    id: "kv-staging".into(),
2234                },
2235            );
2236        std::fs::write(
2237            project_root.join(LOCK_FILE),
2238            toml::to_string_pretty(&lock).unwrap(),
2239        )
2240        .unwrap();
2241
2242        // Reading "default" (what this function did unconditionally before
2243        // the fix) must fail helpfully, not silently mis-materialise.
2244        let err = materialise_deploy_state(&project_root, "api", &config, "default")
2245            .expect_err("nothing is recorded under \"default\" — this must not silently pass");
2246        assert!(
2247            err.contains("environment `default`"),
2248            "the error should name which environment it looked under: {err}"
2249        );
2250
2251        // Reading "staging" — the environment it was actually deployed under
2252        // — must succeed and materialise that environment's id.
2253        assert!(materialise_deploy_state(&project_root, "api", &config, "staging").unwrap());
2254        let text = std::fs::read_to_string(&config).unwrap();
2255        let parsed: toml::Table = text.parse().unwrap();
2256        assert_eq!(
2257            parsed["kv_namespaces"].as_array().unwrap()[0]["id"].as_str(),
2258            Some("kv-staging")
2259        );
2260
2261        let _ = std::fs::remove_dir_all(dir);
2262    }
2263
2264    /// S4b (#1967): `bynk dev --remote` binds every namespace, including on a
2265    /// Worker with no bare `KV`, whose first stanza is an instance's. The old
2266    /// first-stanza gate returned early there and materialised nothing.
2267    #[test]
2268    fn materialise_deploy_state_binds_each_rate_limiter() {
2269        // P3 (#2342): `bynk dev --remote` binds the ids a deploy allocated.
2270        let dir = scratch_lock_dir("materialise-ratelimits");
2271        let config = dir.join("wrangler.toml");
2272        std::fs::write(
2273            &config,
2274            "[[ratelimits]]\nname = \"RATELIMIT_LOGIN\"\nnamespace_id = \"<RATELIMIT_LOGIN_NAMESPACE>\" # set at deploy time\nsimple = { limit = 20, period = 60 }\n",
2275        )
2276        .unwrap();
2277        let mut lock = DeployLock {
2278            version: 1,
2279            ..Default::default()
2280        };
2281        std::fs::write(dir.join(LOCK_FILE), toml::to_string_pretty(&lock).unwrap()).unwrap();
2282        let err = materialise_deploy_state(&dir, "shop", &config, "default")
2283            .expect_err("an unallocated limiter must not pass");
2284        assert!(
2285            err.contains("`RATELIMIT_LOGIN`") && err.contains("bynk deploy"),
2286            "{err}"
2287        );
2288        allocate_in(&mut lock, "default", "shop", "RATELIMIT_LOGIN");
2289        std::fs::write(dir.join(LOCK_FILE), toml::to_string_pretty(&lock).unwrap()).unwrap();
2290        assert!(materialise_deploy_state(&dir, "shop", &config, "default").unwrap());
2291        let text = std::fs::read_to_string(&config).unwrap();
2292        let id = ratelimit_seed("default", "shop", "RATELIMIT_LOGIN");
2293        assert!(
2294            text.contains(&format!(
2295                "namespace_id = \"{id}\" # set at deploy time\nsimple = {{ limit = 20, period = 60 }}"
2296            )),
2297            "{text}"
2298        );
2299        let _ = std::fs::remove_dir_all(dir);
2300    }
2301
2302    #[test]
2303    fn materialise_deploy_state_binds_every_instance() {
2304        let dir = scratch_lock_dir("materialise-instances");
2305        let config = dir.join("wrangler.toml");
2306        std::fs::write(
2307            &config,
2308            "[[kv_namespaces]]\nbinding = \"KV_PRICE_CACHE\"\nid = \"<KV_PRICE_CACHE_ID>\"\n\n[[kv_namespaces]]\nbinding = \"KV_SESSIONS\"\nid = \"<KV_SESSIONS_ID>\"\n",
2309        )
2310        .unwrap();
2311        let mut lock = DeployLock {
2312            version: 1,
2313            ..Default::default()
2314        };
2315        lock.record::<Kv>(
2316            "default",
2317            "shop-cart",
2318            "KV_SESSIONS",
2319            KvNamespace::of("sess"),
2320        );
2321        std::fs::write(dir.join(LOCK_FILE), toml::to_string_pretty(&lock).unwrap()).unwrap();
2322
2323        // One instance unrecorded: refused, naming it, and nothing written.
2324        let err = materialise_deploy_state(&dir, "shop-cart", &config, "default")
2325            .expect_err("an unprovisioned instance must not pass");
2326        assert!(
2327            err.contains("`KV_PRICE_CACHE`") && err.contains("`shop-cart`"),
2328            "{err}"
2329        );
2330        assert!(
2331            std::fs::read_to_string(&config)
2332                .unwrap()
2333                .contains("<KV_SESSIONS_ID>")
2334        );
2335
2336        lock.record::<Kv>(
2337            "default",
2338            "shop-cart",
2339            "KV_PRICE_CACHE",
2340            KvNamespace::of("price"),
2341        );
2342        std::fs::write(dir.join(LOCK_FILE), toml::to_string_pretty(&lock).unwrap()).unwrap();
2343        assert!(materialise_deploy_state(&dir, "shop-cart", &config, "default").unwrap());
2344        let parsed: toml::Table = std::fs::read_to_string(&config).unwrap().parse().unwrap();
2345        let ids: Vec<&str> = parsed["kv_namespaces"]
2346            .as_array()
2347            .unwrap()
2348            .iter()
2349            .map(|ns| ns["id"].as_str().unwrap())
2350            .collect();
2351        assert_eq!(ids, ["price", "sess"]);
2352        let _ = std::fs::remove_dir_all(dir);
2353    }
2354
2355    /// #3513 A: `bynk dev` binds an mTLS certificate by the id the last deploy recorded for the
2356    /// environment, since the binding runs on Cloudflare and takes a real id. One no deploy has
2357    /// linked is reported naming it, and the certificate's *name* is never left in
2358    /// `certificate_id` for a linked one.
2359    #[test]
2360    fn materialise_mtls_for_dev_binds_a_linked_certificate_by_its_recorded_id() {
2361        let dir = scratch_lock_dir("materialise-mtls");
2362        let config = dir.join("wrangler.toml");
2363        let text = "[[mtls_certificates]]\nbinding = \"MTLS_BACKEND\"\ncertificate_id = \"acme-client\"\n\n[[mtls_certificates]]\nbinding = \"MTLS_OTHER\"\ncertificate_id = \"ops\"\n";
2364        std::fs::write(&config, text).unwrap();
2365        // A Worker with no certificate is left alone.
2366        let plain = dir.join("plain.toml");
2367        std::fs::write(&plain, "name = \"x\"\n").unwrap();
2368        assert_eq!(
2369            materialise_mtls_for_dev(&dir, "shop", &plain, "default"),
2370            Ok(false)
2371        );
2372        let mut lock = DeployLock {
2373            version: 1,
2374            ..Default::default()
2375        };
2376        lock.record::<MtlsCertificate>(
2377            "default",
2378            "shop",
2379            "MTLS_BACKEND",
2380            MtlsCertificateLink {
2381                certificate: "acme-client".into(),
2382                certificate_id: "c-123".into(),
2383            },
2384        );
2385        std::fs::write(dir.join(LOCK_FILE), toml::to_string_pretty(&lock).unwrap()).unwrap();
2386        let original = std::fs::read_to_string(&config).unwrap();
2387        // The linked binding is bound; the other is named and dropped from the development copy.
2388        let err = materialise_mtls_for_dev(&dir, "shop", &config, "default")
2389            .expect_err("an unlinked certificate is reported");
2390        assert!(
2391            err.contains("`MTLS_OTHER`") && !err.contains("`MTLS_BACKEND`"),
2392            "{err}"
2393        );
2394        assert!(err.contains("bynk deploy --env default"), "{err}");
2395        let out = std::fs::read_to_string(&config).unwrap();
2396        assert!(out.contains("certificate_id = \"c-123\""), "{out}");
2397        assert!(
2398            !out.contains("MTLS_OTHER") && !out.contains("\"ops\""),
2399            "{out}"
2400        );
2401        // Another environment has linked nothing, so each binding is dropped.
2402        std::fs::write(&config, original).unwrap();
2403        let other = materialise_mtls_for_dev(&dir, "shop", &config, "staging").unwrap_err();
2404        assert!(
2405            other.contains("`MTLS_OTHER`") && other.contains("staging"),
2406            "{other}"
2407        );
2408        let _ = std::fs::remove_dir_all(dir);
2409    }
2410
2411    /// #3301: `bynk dev -- --remote` binds a stored secret by the store id the
2412    /// last deploy recorded for the environment. An unlinked one is refused
2413    /// naming it, and the store's *name* is never left in `store_id`, where
2414    /// Cloudflare would take it as an id.
2415    #[test]
2416    fn materialise_deploy_state_binds_a_linked_stored_secret_by_its_recorded_id() {
2417        let dir = scratch_lock_dir("materialise-stored-secret");
2418        let config = dir.join("wrangler.toml");
2419        let text = "[[secrets_store_secrets]]\nbinding = \"SECRET_STRIPE_KEY\"\nstore_id = \"payments\"\nsecret_name = \"stripe-live\"\n";
2420        std::fs::write(&config, text).unwrap();
2421        let mut lock = DeployLock {
2422            version: 1,
2423            ..Default::default()
2424        };
2425        let link = |store_id: &str| StoredSecretLink {
2426            store: "payments".into(),
2427            store_id: store_id.into(),
2428            secret: "stripe-live".into(),
2429        };
2430        // Linked only under `staging`: the default environment is refused.
2431        lock.record::<StoredSecret>("staging", "shop-cart", "SECRET_STRIPE_KEY", link("store-s"));
2432        std::fs::write(dir.join(LOCK_FILE), toml::to_string_pretty(&lock).unwrap()).unwrap();
2433        let err = materialise_deploy_state(&dir, "shop-cart", &config, "default")
2434            .expect_err("an unlinked stored secret must not pass");
2435        assert!(
2436            err.contains("`SECRET_STRIPE_KEY`")
2437                && err.contains("`shop-cart`")
2438                && err.contains("bynk deploy --env default"),
2439            "{err}"
2440        );
2441        assert_eq!(std::fs::read_to_string(&config).unwrap(), text);
2442
2443        // Each environment binds its own recorded id.
2444        assert!(materialise_deploy_state(&dir, "shop-cart", &config, "staging").unwrap());
2445        let parsed: toml::Table = std::fs::read_to_string(&config).unwrap().parse().unwrap();
2446        let entry = &parsed["secrets_store_secrets"][0];
2447        assert_eq!(entry["store_id"].as_str(), Some("store-s"));
2448        assert_eq!(entry["secret_name"].as_str(), Some("stripe-live"));
2449        let _ = std::fs::remove_dir_all(dir);
2450    }
2451
2452    /// S4b (#1967): a project with only the bare `Kv` writes the ledger it
2453    /// wrote before instances existed, byte for byte: no `kv_instances` table.
2454    #[test]
2455    fn a_bare_kv_ledger_is_written_as_it_was_before_instances() {
2456        let pre_s4b = "version = 1\n\n[environments.default.kv.api]\nid = \"abc\"\n";
2457        let lock: DeployLock = toml::from_str(pre_s4b).expect("a pre-S4b ledger reads");
2458        assert_eq!(
2459            lock.recorded::<Kv>("default", "api", "KV")
2460                .map(|kv| kv.id.as_str()),
2461            Some("abc")
2462        );
2463        assert_eq!(toml::to_string_pretty(&lock).unwrap(), pre_s4b);
2464    }
2465
2466    /// S4b (#1967): instances live beside the bare namespace, keyed by Worker
2467    /// then binding, and forgetting the last one leaves the file as it was.
2468    #[test]
2469    fn instances_are_recorded_by_worker_and_binding_and_forgotten_cleanly() {
2470        let mut lock = with_kv(
2471            DeployLock {
2472                version: 1,
2473                ..Default::default()
2474            },
2475            "shop-cart",
2476        );
2477        let before = toml::to_string_pretty(&lock).unwrap();
2478        lock.record::<Kv>(
2479            "default",
2480            "shop-cart",
2481            "KV_SESSIONS",
2482            KvNamespace::of("sess"),
2483        );
2484        let text = toml::to_string_pretty(&lock).unwrap();
2485        assert!(
2486            text.contains("[environments.default.kv_instances.shop-cart.KV_SESSIONS]"),
2487            "{text}"
2488        );
2489        assert_eq!(
2490            lock.recorded::<Kv>("default", "shop-cart", "KV_SESSIONS")
2491                .map(|kv| kv.id.as_str()),
2492            Some("sess")
2493        );
2494        assert_eq!(
2495            lock.recorded::<Kv>("default", "shop-cart", "KV")
2496                .map(|kv| kv.id.as_str()),
2497            Some("ns-id")
2498        );
2499        assert_eq!(
2500            lock.recorded::<Kv>("default", "shop-cart", "KV_OTHER")
2501                .map(|kv| kv.id.as_str()),
2502            None
2503        );
2504        assert_eq!(
2505            toml::from_str::<DeployLock>(&text).unwrap(),
2506            lock,
2507            "the instance table round-trips"
2508        );
2509        lock.forget::<Kv>("default", "shop-cart", "KV_SESSIONS");
2510        assert_eq!(toml::to_string_pretty(&lock).unwrap(), before);
2511    }
2512
2513    /// Review of #1974: a still-live Worker that stops using the bare `Kv`
2514    /// (say, for `capability Sessions = Kv`) no longer declares `KV`, so its
2515    /// recorded bare namespace is an orphan, like an instance it dropped.
2516    #[test]
2517    fn a_bare_namespace_its_live_worker_no_longer_declares_is_an_orphan() {
2518        let lock = with_kv(DeployLock::default(), "api");
2519        let switched = project(vec![(
2520            "api",
2521            Resources::default().kv_instances(&["KV_SESSIONS"]),
2522        )]);
2523        assert_eq!(
2524            find_orphans(&lock, "default", &switched).kv,
2525            [bare_orphan("api")]
2526        );
2527        let still_bare = project(vec![("api", Resources::default().needs_kv())]);
2528        assert!(find_orphans(&lock, "default", &still_bare).kv.is_empty());
2529    }
2530
2531    /// S4b (#1967): an instance its still-live Worker no longer declares (a
2532    /// capability removed or renamed) is an orphan on its own; a removed
2533    /// Worker's instances go with it; a declared one is not an orphan.
2534    #[test]
2535    fn a_removed_or_renamed_instance_is_an_orphan() {
2536        let lock = with_kv_instance(
2537            with_kv_instance(
2538                with_kv_instance(with_kv(DeployLock::default(), "gone"), "gone", "KV_OLD"),
2539                "shop-cart",
2540                "KV_SESSIONS",
2541            ),
2542            "shop-cart",
2543            "KV_CARTS",
2544        );
2545        // `capability Carts = Kv` renamed to `Baskets`: `KV_CARTS` is gone
2546        // from the build, `KV_BASKETS` is new (a create, in the plan).
2547        let resources = project(vec![(
2548            "shop-cart",
2549            Resources::default().kv_instances(&["KV_BASKETS", "KV_SESSIONS"]),
2550        )]);
2551        let orphans = find_orphans(&lock, "default", &resources);
2552        assert_eq!(
2553            orphans.kv,
2554            [
2555                bare_orphan("gone"),
2556                instance_orphan("gone", "KV_OLD"),
2557                instance_orphan("shop-cart", "KV_CARTS"),
2558            ]
2559        );
2560        assert!(orphans.has_prunable());
2561    }
2562
2563    /// P7.4 (#1305): a project with no KV binding at all must skip the lock
2564    /// lookup entirely and return `Ok(false)` — not error just because
2565    /// nothing is recorded for it (there's nothing to materialise). No lock
2566    /// file exists in this project root at all, proving the early exit
2567    /// really does short-circuit before `read_lock` runs.
2568    #[test]
2569    fn materialise_deploy_state_is_a_no_op_without_a_kv_binding() {
2570        let unique = std::time::SystemTime::now()
2571            .duration_since(std::time::UNIX_EPOCH)
2572            .unwrap()
2573            .as_nanos();
2574        let dir = std::env::temp_dir().join(format!(
2575            "bynk-materialise-state-no-kv-{}-{unique}",
2576            std::process::id()
2577        ));
2578        std::fs::create_dir_all(&dir).unwrap();
2579        let config = dir.join("wrangler.toml");
2580        std::fs::write(&config, "name = \"api\"\nmain = \"index.ts\"\n").unwrap();
2581
2582        assert_eq!(
2583            materialise_deploy_state(&dir, "api", &config, "default"),
2584            Ok(false)
2585        );
2586
2587        let _ = std::fs::remove_dir_all(dir);
2588    }
2589
2590    // ---- #839 slice 5: reconciliation maturity + orphan reporting -------
2591
2592    #[test]
2593    fn a_removed_context_with_kv_is_two_orphans_not_one() {
2594        // `kv` and `workers` are both keyed by worker name — a context that
2595        // had KV and was deleted from source shows up in both maps, so the
2596        // diff must report both, independently (DECISION A).
2597        let mut lock = DeployLock {
2598            version: 1,
2599            ..Default::default()
2600        };
2601        lock.environments
2602            .entry("default".into())
2603            .or_default()
2604            .kv
2605            .insert(
2606                "gone".into(),
2607                KvNamespace {
2608                    id: "kv-gone".into(),
2609                },
2610            );
2611        lock.record_deployed("default", "gone", None);
2612        // "still-here" is in the current build, "gone" is not.
2613        let resources = BTreeMap::from([("still-here".into(), Resources::default())]);
2614
2615        let orphans = find_orphans(&lock, "default", &resources);
2616        assert_eq!(orphans.kv, [bare_orphan("gone")]);
2617        assert_eq!(orphans.workers, names(&["gone"]));
2618        assert!(orphans.queues.is_empty());
2619    }
2620
2621    // ---- P5 (#2323): R2 buckets ----
2622
2623    // ---- P4a (#2602): D1 databases ----
2624
2625    #[test]
2626    fn a_removed_database_is_a_reported_orphan_that_prune_leaves_alone() {
2627        let mut lock = DeployLock {
2628            version: 1,
2629            ..Default::default()
2630        };
2631        lock.record::<D1>(
2632            "default",
2633            "shop",
2634            "D1_ORDERS",
2635            D1Record::of("shop-orders", "id-1"),
2636        );
2637        lock.record::<D1>(
2638            "default",
2639            "shop",
2640            "D1_OLD",
2641            D1Record::of("shop-old", "id-2"),
2642        );
2643        let resources = BTreeMap::from([(
2644            "shop".to_string(),
2645            Resources::default().d1_databases(&[("D1_ORDERS", "shop-orders")]),
2646        )]);
2647        let orphans = find_orphans(&lock, "default", &resources);
2648        assert_eq!(
2649            orphans.d1,
2650            [OrphanD1 {
2651                worker: "shop".into(),
2652                binding: "D1_OLD".into(),
2653                database: "shop-old".into(),
2654            }]
2655        );
2656        // A database holds data: `--prune` neither offers nor attempts it.
2657        assert!(!orphans.has_prunable());
2658        // With its Worker gone, every database it had is reported.
2659        assert_eq!(find_orphans(&lock, "default", &BTreeMap::new()).d1.len(), 2);
2660        // A database a binding stopped using stays recorded and reported,
2661        // though the binding is live; recording the same one again does not.
2662        lock.record::<D1>(
2663            "default",
2664            "shop",
2665            "D1_ORDERS",
2666            D1Record::of("shop-orders", "id-1"),
2667        );
2668        lock.record::<D1>(
2669            "default",
2670            "shop",
2671            "D1_ORDERS",
2672            D1Record::of("shop-orders-v2", "id-3"),
2673        );
2674        let orphans = find_orphans(&lock, "default", &resources);
2675        assert!(
2676            orphans
2677                .d1
2678                .iter()
2679                .any(|o| o.binding == "D1_ORDERS" && o.database == "shop-orders"),
2680            "{orphans:?}"
2681        );
2682        assert_eq!(
2683            lock.recorded::<D1>("default", "shop", "D1_ORDERS")
2684                .unwrap()
2685                .superseded
2686                .len(),
2687            1
2688        );
2689    }
2690
2691    fn r2_lock() -> DeployLock {
2692        let mut lock = DeployLock {
2693            version: 1,
2694            ..Default::default()
2695        };
2696        lock.record::<R2>(
2697            "default",
2698            "shop",
2699            "R2_ARCHIVES",
2700            R2Bucket::of("shop-archives", None),
2701        );
2702        lock.record::<R2>(
2703            "default",
2704            "shop",
2705            "R2_OLD",
2706            R2Bucket::of("shop-old", Some("eu")),
2707        );
2708        lock
2709    }
2710
2711    #[test]
2712    fn a_removed_or_renamed_bucket_is_a_reported_orphan_that_prune_leaves_alone() {
2713        let resources = BTreeMap::from([(
2714            "shop".to_string(),
2715            Resources::default().r2_buckets(&[("R2_ARCHIVES", "shop-archives", None)]),
2716        )]);
2717        let orphans = find_orphans(&r2_lock(), "default", &resources);
2718        assert_eq!(
2719            orphans.r2,
2720            [OrphanR2 {
2721                worker: "shop".into(),
2722                binding: "R2_OLD".into(),
2723                bucket: "shop-old".into(),
2724                jurisdiction: Some("eu".into())
2725            }]
2726        );
2727        // A bucket holds data: `--prune` neither offers nor attempts it.
2728        assert!(!orphans.has_prunable());
2729    }
2730
2731    #[test]
2732    fn a_removed_worker_orphans_every_bucket_it_held() {
2733        let orphans = find_orphans(&r2_lock(), "default", &BTreeMap::new());
2734        assert_eq!(orphans.r2.len(), 2);
2735        assert!(
2736            find_orphans(&r2_lock(), "staging", &BTreeMap::new())
2737                .r2
2738                .is_empty()
2739        );
2740    }
2741
2742    #[test]
2743    fn a_bucket_is_recorded_under_the_environment_and_survives_the_file() {
2744        let lock = r2_lock();
2745        assert_eq!(
2746            lock.recorded::<R2>("default", "shop", "R2_OLD"),
2747            Some(&R2Bucket {
2748                name: "shop-old".into(),
2749                jurisdiction: Some("eu".into()),
2750                superseded: Vec::new()
2751            })
2752        );
2753        assert!(lock.recorded::<R2>("staging", "shop", "R2_OLD").is_none());
2754        let text = toml::to_string_pretty(&lock).unwrap();
2755        assert!(text.contains("[environments.default.r2_instances.shop.R2_OLD]"));
2756        let back: DeployLock = toml::from_str(&text).unwrap();
2757        assert_eq!(back, lock);
2758        // No R2, no table: a project without it writes the file it always did.
2759        assert!(
2760            !toml::to_string_pretty(&with_kv(DeployLock::default(), "api"))
2761                .unwrap()
2762                .contains("r2_instances")
2763        );
2764    }
2765
2766    /// A scratch project holding `config` as `workers/shop/wrangler.toml` and
2767    /// the ledger `lock`; returns the root and the config's path.
2768    fn r2_project(
2769        tag: &str,
2770        config: &str,
2771        lock: &DeployLock,
2772    ) -> (std::path::PathBuf, std::path::PathBuf) {
2773        let root = std::env::temp_dir().join(format!("bynk-r2-{tag}-{}", std::process::id()));
2774        let _ = std::fs::remove_dir_all(&root);
2775        std::fs::create_dir_all(root.join("workers/shop")).unwrap();
2776        let path = root.join("workers/shop/wrangler.toml");
2777        std::fs::write(&path, config).unwrap();
2778        write_lock(&root.join(LOCK_FILE), lock).unwrap();
2779        (root, path)
2780    }
2781
2782    const R2_CONFIG: &str = "name = \"shop\"\n\n[[r2_buckets]]\nbinding = \"R2_ARCHIVES\"\nbucket_name = \"shop-archives\"\n";
2783
2784    #[test]
2785    fn dev_remote_binds_a_recorded_bucket_under_the_environments_name() {
2786        let mut lock = DeployLock {
2787            version: 1,
2788            ..Default::default()
2789        };
2790        lock.record::<R2>(
2791            "staging",
2792            "shop",
2793            "R2_ARCHIVES",
2794            R2Bucket::of("shop-archives-staging", None),
2795        );
2796        let (root, config) = r2_project("staging", R2_CONFIG, &lock);
2797        assert_eq!(
2798            materialise_deploy_state(&root, "shop", &config, "staging"),
2799            Ok(true)
2800        );
2801        let text = std::fs::read_to_string(&config).unwrap();
2802        assert!(
2803            text.contains("bucket_name = \"shop-archives-staging\""),
2804            "{text}"
2805        );
2806        let _ = std::fs::remove_dir_all(root);
2807    }
2808
2809    // P4a (#2602): `dev --remote` binds a recorded database by name and id.
2810    const D1_CONFIG: &str = "name = \"shop\"\n\n[[d1_databases]]\nbinding = \"D1_ORDERS\"\ndatabase_name = \"shop-orders\"\ndatabase_id = \"<D1_ORDERS_ID>\" # set at deploy time\n";
2811
2812    #[test]
2813    fn dev_remote_binds_a_recorded_database_and_refuses_an_unrecorded_one() {
2814        let mut lock = DeployLock {
2815            version: 1,
2816            ..Default::default()
2817        };
2818        lock.record::<D1>(
2819            "staging",
2820            "shop",
2821            "D1_ORDERS",
2822            D1Record::of("shop-orders-staging", "id-7"),
2823        );
2824        let (root, config) = r2_project("d1-staging", D1_CONFIG, &lock);
2825        assert_eq!(
2826            materialise_deploy_state(&root, "shop", &config, "staging"),
2827            Ok(true)
2828        );
2829        let text = std::fs::read_to_string(&config).unwrap();
2830        assert!(
2831            text.contains("database_name = \"shop-orders-staging\"")
2832                && text.contains("database_id = \"id-7\""),
2833            "{text}"
2834        );
2835        let _ = std::fs::remove_dir_all(root);
2836        // Nothing recorded under `default`: refused, naming the remedy.
2837        let (root, config) = r2_project("d1-default", D1_CONFIG, &lock);
2838        let err = materialise_deploy_state(&root, "shop", &config, "default").unwrap_err();
2839        assert!(
2840            err.contains("remote D1 database `D1_ORDERS` for `shop` has not been provisioned")
2841                && err.contains("bynk deploy --env default"),
2842            "{err}"
2843        );
2844        let _ = std::fs::remove_dir_all(root);
2845    }
2846
2847    #[test]
2848    fn dev_remote_leaves_the_default_environments_bucket_as_generated() {
2849        let mut lock = DeployLock {
2850            version: 1,
2851            ..Default::default()
2852        };
2853        lock.record::<R2>(
2854            "default",
2855            "shop",
2856            "R2_ARCHIVES",
2857            R2Bucket::of("shop-archives", None),
2858        );
2859        let (root, config) = r2_project("default", R2_CONFIG, &lock);
2860        assert_eq!(
2861            materialise_deploy_state(&root, "shop", &config, "default"),
2862            Ok(false)
2863        );
2864        assert_eq!(std::fs::read_to_string(&config).unwrap(), R2_CONFIG);
2865        let _ = std::fs::remove_dir_all(root);
2866    }
2867
2868    #[test]
2869    fn a_replaced_bucket_stays_recorded_and_is_reported_while_its_binding_is_live() {
2870        let mut lock = DeployLock {
2871            version: 1,
2872            ..Default::default()
2873        };
2874        lock.record::<R2>(
2875            "default",
2876            "shop",
2877            "R2_ARCHIVES",
2878            R2Bucket::of("shop-archives", None),
2879        );
2880        // Recording the same bucket again changes nothing.
2881        lock.record::<R2>(
2882            "default",
2883            "shop",
2884            "R2_ARCHIVES",
2885            R2Bucket::of("shop-archives", None),
2886        );
2887        assert!(
2888            lock.recorded::<R2>("default", "shop", "R2_ARCHIVES")
2889                .unwrap()
2890                .superseded
2891                .is_empty()
2892        );
2893        lock.record::<R2>(
2894            "default",
2895            "shop",
2896            "R2_ARCHIVES",
2897            R2Bucket::of("shop-archives", Some("eu")),
2898        );
2899        let resources = BTreeMap::from([(
2900            "shop".to_string(),
2901            Resources::default().r2_buckets(&[("R2_ARCHIVES", "shop-archives", Some("eu"))]),
2902        )]);
2903        assert_eq!(
2904            find_orphans(&lock, "default", &resources).r2,
2905            [OrphanR2 {
2906                worker: "shop".into(),
2907                binding: "R2_ARCHIVES".into(),
2908                bucket: "shop-archives".into(),
2909                jurisdiction: None
2910            }]
2911        );
2912        let text = toml::to_string_pretty(&lock).unwrap();
2913        assert_eq!(toml::from_str::<DeployLock>(&text).unwrap(), lock);
2914    }
2915
2916    #[test]
2917    fn dev_remote_refuses_a_bucket_recorded_under_another_jurisdiction() {
2918        let mut lock = DeployLock {
2919            version: 1,
2920            ..Default::default()
2921        };
2922        lock.record::<R2>(
2923            "default",
2924            "shop",
2925            "R2_ARCHIVES",
2926            R2Bucket::of("shop-archives", Some("eu")),
2927        );
2928        let (root, config) = r2_project("jurisdiction", R2_CONFIG, &lock);
2929        let error = materialise_deploy_state(&root, "shop", &config, "default").unwrap_err();
2930        assert!(error.contains("another `@jurisdiction`"), "{error}");
2931        let _ = std::fs::remove_dir_all(root);
2932    }
2933
2934    #[test]
2935    fn dev_remote_refuses_a_bucket_no_deploy_has_made() {
2936        let (root, config) = r2_project(
2937            "unprovisioned",
2938            R2_CONFIG,
2939            &DeployLock {
2940                version: 1,
2941                ..Default::default()
2942            },
2943        );
2944        let error = materialise_deploy_state(&root, "shop", &config, "default").unwrap_err();
2945        assert!(error.contains("R2 bucket `R2_ARCHIVES`"), "{error}");
2946        assert!(
2947            error.contains("run `bynk deploy --env default` first"),
2948            "{error}"
2949        );
2950        let _ = std::fs::remove_dir_all(root);
2951    }
2952
2953    #[test]
2954    fn a_queue_two_contexts_share_is_never_orphaned_while_either_declares_it() {
2955        // The false-positive risk DECISION A's diff exists to avoid: a queue
2956        // consumed by two contexts must not be reported orphaned just because
2957        // a *third*, now-removed context used to consume it too.
2958        let mut lock = DeployLock {
2959            version: 1,
2960            ..Default::default()
2961        };
2962        QueueTable::created(
2963            lock.environments
2964                .entry(String::from("default"))
2965                .or_default(),
2966            "jobs",
2967        );
2968        let resources = BTreeMap::from([
2969            ("orders".into(), Resources::default().consumes(&["jobs"])),
2970            ("billing".into(), Resources::default().consumes(&["jobs"])),
2971        ]);
2972
2973        let orphans = find_orphans(&lock, "default", &resources);
2974        assert!(
2975            orphans.queues.is_empty(),
2976            "jobs is still consumed by two live contexts: {orphans:?}"
2977        );
2978    }
2979
2980    #[test]
2981    fn a_queue_a_context_only_sends_to_is_not_orphaned() {
2982        // P2 (#2578): a recorded queue no context consumes but one sends to.
2983        let mut lock = DeployLock {
2984            version: 1,
2985            ..Default::default()
2986        };
2987        QueueTable::created(
2988            lock.environments
2989                .entry(String::from("default"))
2990                .or_default(),
2991            "order-events",
2992        );
2993        let resources = BTreeMap::from([(
2994            "shop".into(),
2995            Resources::default().produces(&["order-events"]),
2996        )]);
2997        assert!(find_orphans(&lock, "default", &resources).queues.is_empty());
2998    }
2999
3000    #[test]
3001    fn a_queue_no_context_declares_anymore_is_orphaned() {
3002        let mut lock = DeployLock {
3003            version: 1,
3004            ..Default::default()
3005        };
3006        QueueTable::created(
3007            lock.environments
3008                .entry(String::from("default"))
3009                .or_default(),
3010            "stale-jobs",
3011        );
3012        let resources = BTreeMap::from([("orders".into(), Resources::default())]);
3013
3014        let orphans = find_orphans(&lock, "default", &resources);
3015        assert_eq!(orphans.queues, names(&["stale-jobs"]));
3016    }
3017
3018    #[test]
3019    fn a_queue_only_reused_is_never_orphaned() {
3020        // #2579: a consumed queue another Worker owns is recorded so the plan
3021        // says `reuse`, but dropping the consumer must not make it prunable.
3022        let mut lock = DeployLock {
3023            version: 1,
3024            ..Default::default()
3025        };
3026        assert!(QueueTable::reused(
3027            lock.environments
3028                .entry(String::from("default"))
3029                .or_default(),
3030            "theirs"
3031        ));
3032        assert!(!QueueTable::reused(
3033            lock.environments
3034                .entry(String::from("default"))
3035                .or_default(),
3036            "theirs"
3037        ));
3038        QueueTable::created(
3039            lock.environments
3040                .entry(String::from("default"))
3041                .or_default(),
3042            "ours",
3043        );
3044        let resources = BTreeMap::from([("orders".into(), Resources::default())]);
3045
3046        assert!(
3047            lock.recorded::<Queue>("default", "", "theirs").is_some(),
3048            "the plan still says reuse"
3049        );
3050        let orphans = find_orphans(&lock, "default", &resources);
3051        assert_eq!(orphans.queues, names(&["ours"]));
3052
3053        // Recreated by a later run (deleted out-of-band), it becomes Bynk's.
3054        assert!(QueueTable::created(
3055            lock.environments
3056                .entry(String::from("default"))
3057                .or_default(),
3058            "theirs"
3059        ));
3060        let orphans = find_orphans(&lock, "default", &resources);
3061        assert_eq!(orphans.queues, names(&["ours", "theirs"]));
3062    }
3063
3064    #[test]
3065    fn a_ledger_with_reused_queues_round_trips() {
3066        let mut lock = DeployLock {
3067            version: 1,
3068            ..Default::default()
3069        };
3070        QueueTable::reused(
3071            lock.environments
3072                .entry(String::from("default"))
3073                .or_default(),
3074            "theirs",
3075        );
3076        let text = toml::to_string_pretty(&lock).unwrap();
3077        assert!(text.contains("reused_queues"));
3078        assert_eq!(toml::from_str::<DeployLock>(&text).unwrap(), lock);
3079    }
3080
3081    #[test]
3082    fn find_orphans_is_scoped_to_the_named_environment() {
3083        // A "staging" orphan must never leak into "default"'s report, and
3084        // vice versa — environments (slice 4) stay fully independent.
3085        let mut lock = DeployLock {
3086            version: 1,
3087            ..Default::default()
3088        };
3089        lock.environments
3090            .entry("staging".into())
3091            .or_default()
3092            .kv
3093            .insert(
3094                "gone".into(),
3095                KvNamespace {
3096                    id: "kv-staging-gone".into(),
3097                },
3098            );
3099        let resources = BTreeMap::new();
3100
3101        assert!(
3102            find_orphans(&lock, "default", &resources).kv.is_empty(),
3103            "default"
3104        );
3105        assert_eq!(
3106            find_orphans(&lock, "staging", &resources).kv,
3107            [bare_orphan("gone")]
3108        );
3109    }
3110
3111    #[test]
3112    fn an_absent_environment_has_no_orphans() {
3113        let lock = DeployLock::default();
3114        let orphans = find_orphans(&lock, "default", &BTreeMap::new());
3115        assert_eq!(orphans, Orphans::default());
3116    }
3117
3118    #[test]
3119    fn has_prunable_ignores_worker_only_orphans() {
3120        // The bug the review caught: a project whose only orphan is an
3121        // unprunable Worker must not trigger confirm_prune's "Delete 0
3122        // resource(s)?" prompt at all.
3123        let worker_only = Orphans {
3124            workers: names(&["gone"]),
3125            ..Default::default()
3126        };
3127        assert!(!worker_only.has_prunable());
3128
3129        let with_kv = Orphans {
3130            kv: vec![bare_orphan("gone")],
3131            ..Default::default()
3132        };
3133        assert!(with_kv.has_prunable());
3134
3135        let with_queue = Orphans {
3136            queues: names(&["gone"]),
3137            ..Default::default()
3138        };
3139        assert!(with_queue.has_prunable());
3140
3141        assert!(!Orphans::default().has_prunable());
3142    }
3143
3144    #[test]
3145    fn a_written_ledger_reads_back_identically() {
3146        // The floor the atomic write must not disturb: a real ledger survives a
3147        // write/read round-trip unchanged.
3148        let path = scratch_lock_path("roundtrip");
3149        let mut lock = DeployLock {
3150            version: 1,
3151            ..Default::default()
3152        };
3153        lock.environments
3154            .entry("default".into())
3155            .or_default()
3156            .kv
3157            .insert(
3158                "api".into(),
3159                KvNamespace {
3160                    id: "kv-123".into(),
3161                },
3162            );
3163        write_lock(&path, &lock).unwrap();
3164        assert_eq!(read_lock(&path).unwrap(), lock);
3165        let _ = std::fs::remove_file(path);
3166    }
3167
3168    #[test]
3169    fn an_empty_ledger_is_corruption_not_a_fresh_project() {
3170        // #736: a truncated write leaves a zero-byte file. Reading it as an
3171        // empty v1 ledger would re-mint every namespace, so it must fail hard —
3172        // whereas a genuinely absent file is a fresh project and reads clean.
3173        let path = scratch_lock_path("empty");
3174        std::fs::write(&path, "").unwrap();
3175        assert!(
3176            read_lock(&path).is_err(),
3177            "a zero-byte ledger must be rejected, not treated as no environments"
3178        );
3179        std::fs::write(&path, "   \n\t\n").unwrap();
3180        assert!(
3181            read_lock(&path).is_err(),
3182            "a whitespace-only ledger is just as corrupt"
3183        );
3184        let _ = std::fs::remove_file(&path);
3185        assert!(
3186            read_lock(&path).is_ok(),
3187            "an absent ledger is a fresh project, not corruption"
3188        );
3189    }
3190
3191    #[test]
3192    fn a_ledger_without_a_version_is_rejected() {
3193        // With the serde default gone, a file that parses but carries no
3194        // `version` is corruption rather than a silent empty v1 ledger.
3195        let path = scratch_lock_path("noversion");
3196        std::fs::write(&path, "[environments]\n").unwrap();
3197        assert!(read_lock(&path).is_err());
3198        let _ = std::fs::remove_file(path);
3199    }
3200
3201    #[test]
3202    fn a_successful_write_leaves_no_temp_litter() {
3203        // The atomic write renames its temp over the ledger; nothing sibling to
3204        // the ledger may survive the write.
3205        let dir = scratch_lock_dir("nolitter");
3206        let path = dir.join(LOCK_FILE);
3207        let lock = DeployLock {
3208            version: 1,
3209            ..Default::default()
3210        };
3211        write_lock(&path, &lock).unwrap();
3212        write_lock(&path, &lock).unwrap(); // over an existing ledger, too
3213        assert!(
3214            temp_litter(&dir).is_empty(),
3215            "no `.tmp` sibling may outlive the rename"
3216        );
3217        assert_eq!(read_lock(&path).unwrap(), lock);
3218        let _ = std::fs::remove_dir_all(dir);
3219    }
3220
3221    #[cfg(unix)]
3222    #[test]
3223    fn a_rewrite_preserves_the_ledger_permissions() {
3224        use std::os::unix::fs::PermissionsExt;
3225        // A committed ledger's mode must survive a rewrite, or the atomic replace
3226        // would silently loosen or tighten it via the temp file's fresh mode.
3227        let dir = scratch_lock_dir("perms");
3228        let path = dir.join(LOCK_FILE);
3229        let lock = DeployLock {
3230            version: 1,
3231            ..Default::default()
3232        };
3233        write_lock(&path, &lock).unwrap();
3234        std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600)).unwrap();
3235        write_lock(&path, &lock).unwrap();
3236        assert_eq!(
3237            std::fs::metadata(&path).unwrap().permissions().mode() & 0o777,
3238            0o600,
3239            "the rewrite must carry the ledger's own mode across the rename"
3240        );
3241        let _ = std::fs::remove_dir_all(dir);
3242    }
3243
3244    /// #3562: a ledger written before groups has no `contexts`, still reads, and
3245    /// is written back unchanged; a group's Worker records its members.
3246    #[test]
3247    fn a_pre_groups_ledger_reads_and_a_groups_worker_records_its_members() {
3248        let before = "version = 1\n\n[environments.default.workers.shop-orders]\ndeployed = true\n\n[environments.default.workers.shop-orders.contracts]\ncharge = \"abc\"\n";
3249        let mut lock: DeployLock = toml::from_str(before).unwrap();
3250        assert!(lock.is_deployed("default", "shop-orders"));
3251        assert!(lock.members_of("default", "shop-orders").is_empty());
3252        assert!(
3253            !toml::to_string_pretty(&lock).unwrap().contains("contexts"),
3254            "a Worker with no members writes no `contexts`"
3255        );
3256        lock.record_deployed("default", "core", Some(BTreeMap::new()));
3257        lock.record_members(
3258            "default",
3259            "core",
3260            &["shop.a".to_string(), "shop.b".to_string()],
3261        );
3262        let text = toml::to_string_pretty(&lock).unwrap();
3263        assert!(text.contains("contexts = ["), "{text}");
3264        let again: DeployLock = toml::from_str(&text).unwrap();
3265        assert_eq!(again.members_of("default", "core"), ["shop.a", "shop.b"]);
3266        assert!(again.members_of("default", "shop-orders").is_empty());
3267        assert!(again.members_of("default", "unrecorded").is_empty());
3268        assert_eq!(again, lock);
3269    }
3270
3271    /// #3562: an orphaned Worker the ledger recorded as a group's is reported with
3272    /// its members; one it recorded without any (a context's own Worker, or a
3273    /// pre-groups ledger) is reported as before.
3274    #[test]
3275    fn an_orphaned_groups_members_are_named() {
3276        let mut lock = DeployLock {
3277            version: 1,
3278            ..Default::default()
3279        };
3280        lock.record_deployed("default", "gone-group", Some(BTreeMap::new()));
3281        lock.record_members(
3282            "default",
3283            "gone-group",
3284            &["shop.a".to_string(), "shop.b".to_string()],
3285        );
3286        lock.record_deployed("default", "gone-alone", Some(BTreeMap::new()));
3287        let orphans = find_orphans(&lock, "default", &BTreeMap::new());
3288        assert_eq!(orphans.workers, ["gone-alone", "gone-group"]);
3289        assert_eq!(
3290            orphans.worker_contexts,
3291            BTreeMap::from([(
3292                "gone-group".to_string(),
3293                vec!["shop.a".to_string(), "shop.b".to_string()]
3294            )])
3295        );
3296        let shown = orphans.as_named_in("staging");
3297        assert!(
3298            shown.worker_contexts.contains_key("gone-group-staging"),
3299            "{:?}",
3300            shown.worker_contexts
3301        );
3302    }
3303
3304    /// #3562: a renamed group is named by its script, not its key, where the
3305    /// account's name is wanted; a Worker with no recorded script is named by its key.
3306    #[test]
3307    fn a_renamed_groups_script_is_recorded_and_shown() {
3308        let mut lock = DeployLock {
3309            version: 1,
3310            ..Default::default()
3311        };
3312        lock.record_deployed("default", "core", Some(BTreeMap::new()));
3313        lock.record_script("default", "core", "core-script");
3314        lock.record_deployed("default", "plain", Some(BTreeMap::new()));
3315        lock.record_script("default", "plain", "plain");
3316        assert_eq!(lock.script_of("default", "core"), "core-script");
3317        assert_eq!(lock.script_of("default", "plain"), "plain");
3318        assert_eq!(lock.script_of("default", "unrecorded"), "unrecorded");
3319        let text = toml::to_string_pretty(&lock).unwrap();
3320        assert_eq!(text.matches("script =").count(), 1, "{text}");
3321        assert_eq!(toml::from_str::<DeployLock>(&text).unwrap(), lock);
3322        let orphans = find_orphans(&lock, "default", &BTreeMap::new());
3323        assert_eq!(
3324            orphans.as_named_in("staging").workers,
3325            ["core-script-staging", "plain-staging"]
3326        );
3327    }
3328}