newgit-core 0.2.0

Core domain model for newgit: branch instances, tracker lanes, and resource lifecycles
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
use std::process::Command;

use camino::{Utf8Path, Utf8PathBuf};
use newgit_core::branch::ResourceStatus;
use newgit_core::cleanup::ArchivedCheckpoints;
use newgit_core::config::WorkspaceSection;
use newgit_core::manager::{ActionOutcome, BranchManager};
use newgit_core::store::MetadataStore;
use newgit_core::supervisor::StopOutcome;
use newgit_core::tracker::Storage;
use newgit_core::{NewgitError, SourceSubstrate};

fn git(dir: &Utf8Path, args: &[&str]) {
    let output = Command::new("git")
        .arg("-C")
        .arg(dir.as_str())
        .args(args)
        .env("GIT_AUTHOR_NAME", "test")
        .env("GIT_AUTHOR_EMAIL", "test@example.com")
        .env("GIT_COMMITTER_NAME", "test")
        .env("GIT_COMMITTER_EMAIL", "test@example.com")
        .output()
        .expect("git runs");
    assert!(
        output.status.success(),
        "git {args:?} failed: {}",
        String::from_utf8_lossy(&output.stderr)
    );
}

fn setup(temp: &Utf8Path) -> MetadataStore {
    let repo = temp.join("store");
    std::fs::create_dir_all(&repo).expect("mkdir");
    git(&repo, &["init", "-q", "-b", "main"]);
    std::fs::write(repo.join("README.md"), "hello\n").expect("write");
    git(&repo, &["add", "."]);
    git(&repo, &["commit", "-q", "-m", "initial"]);

    let store = MetadataStore::init(&repo, "proj", SourceSubstrate::Git).expect("init");
    let mut config = store.load_config().expect("config");
    config.workspace = Some(WorkspaceSection {
        root: Some(temp.join("workspaces")),
        materializer: None,
    });
    store.write_config(&config).expect("write config");
    store
}

fn tempdir() -> (tempfile::TempDir, Utf8PathBuf) {
    let temp = tempfile::tempdir().expect("tempdir");
    let path = Utf8PathBuf::from_path_buf(temp.path().canonicalize().expect("canonicalize"))
        .expect("utf8 tempdir");
    (temp, path)
}

/// An executable script under the store's `.newgit/scripts/`.
fn write_script(path: &Utf8Path, body: &str) {
    std::fs::write(path, format!("#!/bin/sh\n{body}")).expect("write script");
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o755)).expect("chmod");
    }
}

fn write_resource(store: &MetadataStore, name: &str, contents: &str) {
    std::fs::write(
        store.paths().resources.join(format!("{name}.toml")),
        contents,
    )
    .expect("write resource");
}

const APP_RESOURCE: &str = r#"kind = "process"
ownership = "branch"
depends_on = ["prep"]

[ports]
app = { start = 3900, env = "PORT" }

[actions.start]
command = "sleep 30"
long_running = true

[actions.stop]
signal = "term"

[exports]
APP_URL = "http://127.0.0.1:{{ports.app}}/{{branch.slug}}"
"#;

const PREP_RESOURCE: &str = r#"kind = "command"
ownership = "workspace"

[actions.prepare]
command = "echo prepared-{{branch.slug}} > prepared.txt"
"#;

const BAD_PREP_RESOURCE: &str = r#"kind = "command"
ownership = "workspace"

[actions.prepare]
command = "echo bad-prep-ran > bad-prep.txt; exit 7"
"#;

const AFTER_BAD_RESOURCE: &str = r#"kind = "command"
ownership = "workspace"
depends_on = ["bad-prep"]

[actions.prepare]
command = "echo should-not-run > after-bad.txt"
"#;

const BLOCKED_PROCESS_RESOURCE: &str = r#"kind = "process"
ownership = "branch"
depends_on = ["bad-prep"]

[actions.start]
command = "sleep 30"
long_running = true

[actions.stop]
signal = "term"
"#;

#[test]
fn spawn_allocates_stable_distinct_ports_and_runs_prepare() {
    let (_guard, temp) = tempdir();
    let store = setup(&temp);
    write_resource(&store, "app", APP_RESOURCE);
    write_resource(&store, "prep", PREP_RESOURCE);
    let repo = store.paths().project_root.clone();
    let manager = BranchManager::open(MetadataStore::at(repo)).expect("manager");

    let a = manager.spawn("feature-a", None).expect("spawn a");
    let b = manager.spawn("feature-b", None).expect("spawn b");

    let port_a = a.branch.resources["app"].resolved_ports["app"];
    let port_b = b.branch.resources["app"].resolved_ports["app"];
    assert!(port_a >= 3900);
    assert_ne!(port_a, port_b, "instances must not share a port");

    // Exports rendered with the allocated port and branch vars.
    assert_eq!(
        a.branch.resources["app"].resolved_exports["APP_URL"],
        format!("http://127.0.0.1:{port_a}/feature-a")
    );

    // Prepare ran in dependency order and left its artifact; status ready.
    assert_eq!(
        std::fs::read_to_string(a.branch.workspace_path.join("prepared.txt")).expect("read"),
        "prepared-feature-a\n"
    );
    assert_eq!(a.branch.resources["prep"].status, ResourceStatus::Ready);

    // Persisted: reloading the record shows the same port (determinism).
    let reloaded = manager.store().find_branch("feature-a").expect("reload");
    assert_eq!(reloaded.resources["app"].resolved_ports["app"], port_a);
}

#[test]
fn failed_prepare_blocks_dependents_but_keeps_instance_spawned() {
    let (_guard, temp) = tempdir();
    let store = setup(&temp);
    write_resource(&store, "bad-prep", BAD_PREP_RESOURCE);
    write_resource(&store, "after-bad", AFTER_BAD_RESOURCE);
    write_resource(&store, "blocked-app", BLOCKED_PROCESS_RESOURCE);
    let repo = store.paths().project_root.clone();
    let manager = BranchManager::open(MetadataStore::at(repo)).expect("manager");

    let spawned = manager.spawn("feature-a", None).expect("spawn");

    assert!(spawned.branch.workspace_path.is_dir());
    assert_eq!(
        spawned.branch.resources["bad-prep"].status,
        ResourceStatus::Failed
    );
    assert_eq!(
        spawned.branch.resources["after-bad"].status,
        ResourceStatus::Blocked
    );
    assert_eq!(
        spawned.branch.resources["blocked-app"].status,
        ResourceStatus::Blocked
    );
    assert!(
        spawned.branch.workspace_path.join("bad-prep.txt").is_file(),
        "the failing dependency should have run"
    );
    assert!(
        !spawned.branch.workspace_path.join("after-bad.txt").exists(),
        "blocked dependents should not run prepare"
    );

    let reports = manager.statuses().expect("statuses");
    let resources = &reports[0].resources;
    assert_eq!(
        resources
            .iter()
            .find(|r| r.name == "bad-prep")
            .expect("bad-prep")
            .state,
        "failed"
    );
    assert_eq!(
        resources
            .iter()
            .find(|r| r.name == "after-bad")
            .expect("after-bad")
            .state,
        "blocked"
    );
    assert_eq!(
        resources
            .iter()
            .find(|r| r.name == "blocked-app")
            .expect("blocked-app")
            .state,
        "blocked"
    );
    assert!(matches!(
        manager.run_action("feature-a", "after-bad.prepare"),
        Err(NewgitError::Unsupported(_))
    ));
    assert!(matches!(
        manager.run_action("feature-a", "blocked-app.start"),
        Err(NewgitError::Unsupported(_))
    ));
}

#[test]
fn run_command_sees_layered_env() {
    let (_guard, temp) = tempdir();
    let store = setup(&temp);
    write_resource(&store, "app", APP_RESOURCE);
    write_resource(&store, "prep", PREP_RESOURCE);

    let repo = store.paths().project_root.clone();
    let manager = BranchManager::open(MetadataStore::at(repo)).expect("manager");
    let spawned = manager.spawn("feature-a", None).expect("spawn");
    let port = spawned.branch.resources["app"].resolved_ports["app"];

    let (code, _log) = manager
        .run_command(
            "feature-a",
            &[
                "sh".to_owned(),
                "-c".to_owned(),
                "echo \"$PORT|$APP_URL|$NEWGIT_BRANCH\" > env-probe.txt".to_owned(),
            ],
        )
        .expect("run");
    assert_eq!(code, 0);

    let probe =
        std::fs::read_to_string(spawned.branch.workspace_path.join("env-probe.txt")).expect("read");
    assert_eq!(
        probe.trim(),
        format!("{port}|http://127.0.0.1:{port}/feature-a|feature-a")
    );
}

#[test]
fn supervisor_starts_and_stops_long_running_actions() {
    let (_guard, temp) = tempdir();
    let store = setup(&temp);
    write_resource(&store, "app", APP_RESOURCE);
    write_resource(&store, "prep", PREP_RESOURCE);
    let repo = store.paths().project_root.clone();
    let manager = BranchManager::open(MetadataStore::at(repo)).expect("manager");
    manager.spawn("feature-a", None).expect("spawn");

    let ActionOutcome::Started { pid, .. } =
        manager.run_action("feature-a", "app.start").expect("start")
    else {
        panic!("expected Started");
    };
    assert!(pid > 0);

    // Double-start is refused.
    assert!(matches!(
        manager.run_action("feature-a", "app.start"),
        Err(NewgitError::AlreadyRunning { .. })
    ));

    // Status reflects the live process.
    let reports = manager.statuses().expect("statuses");
    let app_state = reports[0]
        .resources
        .iter()
        .find(|r| r.name == "app")
        .expect("app report");
    assert_eq!(app_state.state, "running");

    let ActionOutcome::Stopped(outcome) =
        manager.run_action("feature-a", "app.stop").expect("stop")
    else {
        panic!("expected Stopped");
    };
    assert_eq!(outcome, StopOutcome::Stopped(pid));

    let reports = manager.statuses().expect("statuses");
    let app_state = reports[0]
        .resources
        .iter()
        .find(|r| r.name == "app")
        .expect("app report");
    assert_eq!(app_state.state, "stopped");
}

#[test]
fn remove_stops_running_processes() {
    let (_guard, temp) = tempdir();
    let store = setup(&temp);
    write_resource(&store, "app", APP_RESOURCE);
    write_resource(&store, "prep", PREP_RESOURCE);
    let repo = store.paths().project_root.clone();
    let manager = BranchManager::open(MetadataStore::at(repo)).expect("manager");
    manager.spawn("feature-a", None).expect("spawn");

    let ActionOutcome::Started { pid, .. } =
        manager.run_action("feature-a", "app.start").expect("start")
    else {
        panic!("expected Started");
    };

    manager
        .remove("feature-a", &temp, ArchivedCheckpoints::Keep)
        .expect("remove");

    // The process group is gone.
    let alive = Command::new("kill")
        .args(["-0", "--", &format!("-{pid}")])
        .status()
        .expect("kill -0")
        .success();
    assert!(!alive, "process group survived remove");
}

#[test]
fn pnpm_template_creates_companion_store_and_loads() {
    let (_guard, temp) = tempdir();
    let store = setup(&temp);
    let repo = store.paths().project_root.clone();
    let manager = BranchManager::open(MetadataStore::at(repo.clone())).expect("manager");

    let outcome = manager.add_resource("deps", "pnpm").expect("add pnpm");
    assert!(outcome.path.is_file());
    assert_eq!(outcome.companions_created.len(), 1);
    assert!(
        outcome.companions_created[0]
            .as_str()
            .ends_with("pnpm-store.toml")
    );

    // Definitions load and the dependency resolves (no MissingDependency).
    let manager = BranchManager::open(MetadataStore::at(repo.clone())).expect("reopen");
    let names: Vec<&str> = manager
        .resource_definitions()
        .iter()
        .map(|d| d.name.as_str())
        .collect();
    assert!(names.contains(&"deps"));
    assert!(names.contains(&"pnpm-store"));

    // Re-adding under another name must not overwrite the existing companion.
    let again = manager.add_resource("deps2", "pnpm").expect("add again");
    assert!(again.companions_created.is_empty());
}

#[test]
fn unknown_action_and_bad_spec_error_cleanly() {
    let (_guard, temp) = tempdir();
    let store = setup(&temp);
    write_resource(&store, "app", APP_RESOURCE);
    write_resource(&store, "prep", PREP_RESOURCE);
    let repo = store.paths().project_root.clone();
    let manager = BranchManager::open(MetadataStore::at(repo)).expect("manager");
    manager.spawn("feature-a", None).expect("spawn");

    assert!(matches!(
        manager.run_action("feature-a", "app.dance"),
        Err(NewgitError::UnknownAction { .. })
    ));
    assert!(matches!(
        manager.run_action("feature-a", "nope.start"),
        Err(NewgitError::UnknownResource(_))
    ));
    assert!(matches!(
        manager.run_action("feature-a", "no-dot"),
        Err(NewgitError::Unsupported(_))
    ));
}

/// Every shipped template has to survive the trip through the parser and the
/// dependency graph, or `newgit resource add` hands the user a project that
/// will not open. This is the "model a normal web app without writing TOML
/// from scratch" claim, checked.
#[test]
fn every_template_loads_after_being_added() {
    let (_guard, temp) = tempdir();
    let store = setup(&temp);
    let repo = store.paths().project_root.clone();

    for template in newgit_core::templates::RESOURCE_TEMPLATES {
        let manager = BranchManager::open(MetadataStore::at(repo.clone())).expect("reopen");
        manager
            .add_resource(template.name, template.name)
            .unwrap_or_else(|error| panic!("add `{}`: {error}", template.name));
    }

    // One project holding all of them still opens: definitions parse, every
    // `depends_on` resolves, and no two lanes claim the same path.
    let manager = BranchManager::open(MetadataStore::at(repo)).expect("open with all templates");
    let names: Vec<&str> = manager
        .resource_definitions()
        .iter()
        .map(|definition| definition.name.as_str())
        .collect();
    for template in newgit_core::templates::RESOURCE_TEMPLATES {
        assert!(
            names.contains(&template.name),
            "{} is missing",
            template.name
        );
    }
}

#[test]
fn the_command_snapshot_template_brings_its_deposit_lane() {
    let (_guard, temp) = tempdir();
    let store = setup(&temp);
    let repo = store.paths().project_root.clone();
    let manager = BranchManager::open(MetadataStore::at(repo.clone())).expect("manager");

    let outcome = manager
        .add_resource("postgres-db", "command-snapshot")
        .expect("add");
    assert_eq!(outcome.trackers_created.len(), 1);
    assert!(
        outcome.trackers_created[0]
            .as_str()
            .ends_with("db-snapshots.toml"),
        "a template that deposits must create the lane it deposits into"
    );

    // The lane exists as a deposit-only tracker: no owned workspace paths.
    let manager = BranchManager::open(MetadataStore::at(repo)).expect("reopen");
    let lane = manager
        .tracker_definitions()
        .iter()
        .find(|definition| definition.name == "db-snapshots")
        .expect("db-snapshots defined");
    assert!(lane.paths.is_empty());
    assert_eq!(lane.audience, "project-devs");

    // Adding a second database resource reuses the existing lane.
    let again = manager
        .add_resource("other-db", "command-snapshot")
        .expect("add again");
    assert!(again.trackers_created.is_empty());
}

#[test]
fn captures_publish_a_handle_into_the_binding_and_the_command_env() {
    let (_guard, temp) = tempdir();
    let store = setup(&temp);
    // KEY=VALUE lines, the other accepted capture shape.
    write_resource(
        &store,
        "preview",
        r#"kind = "external"
ownership = "external"

[actions.prepare]
command = "echo PREVIEW_URL=https://pv9.example"
captures = ["PREVIEW_URL"]
"#,
    );
    let repo = store.paths().project_root.clone();
    let manager = BranchManager::open(MetadataStore::at(repo)).expect("manager");

    let spawned = manager.spawn("feature-a", None).expect("spawn");
    assert_eq!(
        spawned.branch.resources["preview"].resolved_exports["PREVIEW_URL"],
        "https://pv9.example"
    );

    // Persisted on the binding record, and layered into the command env.
    let reloaded = manager.store().find_branch("feature-a").expect("reload");
    assert_eq!(
        reloaded.resources["preview"].resolved_exports["PREVIEW_URL"],
        "https://pv9.example"
    );
    let env = manager.assemble_env(&reloaded).expect("env");
    assert!(env.contains(&("PREVIEW_URL".to_owned(), "https://pv9.example".to_owned())));
}

/// A resource that names a tracker before the tracker exists used to break
/// `BranchManager::open`, so every command failed — including the ones that
/// create the missing name. Definition-building commands must stay reachable.
#[test]
fn an_unresolved_dependency_does_not_block_the_commands_that_fix_it() {
    let (_guard, temp) = tempdir();
    let store = setup(&temp);
    let repo = store.paths().project_root.clone();

    write_resource(
        &store,
        "db",
        r#"kind = "command"
ownership = "branch"
depends_on = ["runtime-env"]

[actions.prepare]
command = "true"
"#,
    );

    let manager = BranchManager::open(MetadataStore::at(repo.clone())).expect("open still works");
    assert_eq!(
        manager.graph_problems(),
        &[newgit_core::resource::GraphProblem::MissingDependency {
            resource: "db".to_owned(),
            dependency: "runtime-env".to_owned(),
        }]
    );

    // Graph-acting commands refuse, and say which name is missing.
    assert!(matches!(
        manager.spawn("blocked", None),
        Err(NewgitError::MissingDependency { .. })
    ));

    // Definition-building commands run, and creating the tracker resolves it.
    manager
        .create_tracker("runtime-env", "user", Storage::Local, false)
        .expect("create tracker against an incomplete graph");
    manager
        .track_paths("runtime-env", &[Utf8PathBuf::from("packages/db/.env")])
        .expect("track paths against an incomplete graph");

    let manager = BranchManager::open(MetadataStore::at(repo)).expect("reopen");
    assert!(manager.graph_problems().is_empty());
    manager.spawn("unblocked", None).expect("spawn now works");
}

/// A cycle is reported the same way: `open` succeeds, graph-acting commands
/// refuse. Otherwise a typo in `depends_on` bricks the project.
#[test]
fn a_dependency_cycle_is_reported_rather_than_raised_at_open() {
    let (_guard, temp) = tempdir();
    let store = setup(&temp);
    let repo = store.paths().project_root.clone();

    for (name, dependency) in [("a", "b"), ("b", "a")] {
        write_resource(
            &store,
            name,
            &format!(
                r#"kind = "command"
ownership = "branch"
depends_on = ["{dependency}"]

[actions.prepare]
command = "true"
"#
            ),
        );
    }

    let manager = BranchManager::open(MetadataStore::at(repo)).expect("open still works");
    assert!(matches!(
        manager.graph_problems(),
        [newgit_core::resource::GraphProblem::Cycle(_)]
    ));
    assert!(matches!(
        manager.spawn("blocked", None),
        Err(NewgitError::DependencyCycle(_))
    ));
    // Listing definitions is how you find the cycle, so it must not refuse.
    assert_eq!(manager.resource_definitions().len(), 2);
}

/// A resource definition is read from the store, but anything it shelled out
/// to was read from the workspace — so iterating on a `prepare` script meant
/// committing every attempt or copying it into the workspace by hand.
/// `{{scripts}}` puts both halves of a definition under one rule.
#[test]
fn a_scripts_command_picks_up_edits_without_a_commit() {
    let (_guard, temp) = tempdir();
    let store = setup(&temp);
    let repo = store.paths().project_root.clone();
    let script = store.paths().scripts.join("prepare.sh");

    write_resource(
        &store,
        "db",
        r#"kind = "command"
ownership = "workspace"

[actions.prepare]
command = "{{scripts}}/prepare.sh {{branch.slug}}"
"#,
    );
    write_script(&script, "echo first-$1 > prepared.txt\n");

    // Never committed: the script is not in the source history the workspace
    // clone is made from.
    let manager = BranchManager::open(MetadataStore::at(repo.clone())).expect("manager");
    let spawned = manager.spawn("feature-a", None).expect("spawn");
    let workspace = spawned.branch.workspace_path.clone();
    assert_eq!(
        spawned.branch.resources["db"].status,
        ResourceStatus::Ready,
        "prepare should find the script in the store"
    );
    assert_eq!(
        std::fs::read_to_string(workspace.join("prepared.txt")).expect("read"),
        "first-feature-a\n"
    );
    assert!(
        !workspace.join(".newgit/scripts/prepare.sh").exists(),
        "the script runs from the store, it is not copied into the workspace"
    );

    // The loop the issue described: edit in place, re-run, no commit, no copy.
    write_script(&script, "echo second-$1 > prepared.txt\n");
    let outcome = manager
        .run_action("feature-a", "db.prepare")
        .expect("re-run prepare");
    assert!(matches!(outcome, ActionOutcome::Ran { code: 0, .. }));
    assert_eq!(
        std::fs::read_to_string(workspace.join("prepared.txt")).expect("read"),
        "second-feature-a\n",
        "the edited script should run, not the one from spawn time"
    );
}

/// A declared capture that never appears in stdout used to pass in total
/// silence: exit 0, `prepare: ok`, resource `ready`, and an empty handle
/// nobody noticed until an API call 401'd. The usual cause is the command's
/// own noise on stdout, which `captures` reserves for newgit.
#[test]
fn a_declared_capture_that_never_appears_is_reported() {
    let (_guard, temp) = tempdir();
    let store = setup(&temp);
    // Emits one of the two declared names, with progress noise around it —
    // exactly the shape that bit in the field.
    write_resource(
        &store,
        "db",
        r#"kind = "external"
ownership = "external"

[actions.prepare]
command = "echo 'Starting containers...'; echo ANON_KEY=abc; echo 'done.'"
captures = ["ANON_KEY", "SERVICE_ROLE_KEY"]
"#,
    );
    let repo = store.paths().project_root.clone();
    let manager = BranchManager::open(MetadataStore::at(repo)).expect("manager");

    let spawned = manager.spawn("feature-a", None).expect("spawn");
    let resource = spawned
        .resources
        .iter()
        .find(|r| r.name == "db")
        .expect("db bound");

    // What did arrive still arrives, and the action still succeeded.
    assert_eq!(
        spawned.branch.resources["db"].resolved_exports["ANON_KEY"],
        "abc"
    );
    assert_eq!(spawned.branch.resources["db"].status, ResourceStatus::Ready);

    // What did not arrive is named, once, with the log to look in.
    assert_eq!(resource.missing_captures.len(), 1);
    let warning = &resource.missing_captures[0];
    assert!(warning.contains("SERVICE_ROLE_KEY"), "names the capture");
    assert!(!warning.contains("ANON_KEY"), "not the one that arrived");
    assert!(warning.contains("db.prepare"), "points at the log");

    // And on a later `newgit action`, not just at spawn.
    let outcome = manager
        .run_action("feature-a", "db.prepare")
        .expect("re-run");
    let ActionOutcome::Ran {
        missing_captures, ..
    } = outcome
    else {
        panic!("expected a one-shot run");
    };
    assert_eq!(missing_captures.len(), 1);
    assert!(missing_captures[0].contains("SERVICE_ROLE_KEY"));
}