loopflow 0.12.21

Run steps and flows with coding agents
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
//! W2-253 — Task PR operations must fail closed without durable authority.
//!
//! Task-owned publication, stacking, submit, and land must never degrade to
//! generic PR behavior when the shared Task registry is missing, inaccessible,
//! or schema-incompatible. These tests prove the observable contract: every
//! Task entry point refuses **before any push or `gh pr` mutation** with an
//! actionable authority error (zero remote mutation), ordinary non-Task PR
//! flows stay explicit, and valid authority still publishes and records the PR.

mod support;

use std::fs;
use std::process::{Command, Stdio};

use loopflow::ops::task::task_stack;
use loopflow::ops::{
    arm as land, create_or_update_pr, submit, LandOptions, NullProgress, PrOptions,
};
use loopflow_test_support::TestRepo;
use support::{register_task, EnvGuard};

fn land_options(create_pr: bool, pr_title: &str) -> LandOptions {
    LandOptions {
        strict: true,
        local: false,
        create_pr,
        complete: false,
        next_slug: None,
        worktree: None,
        commit_message: None,
        pr_title: Some(pr_title.to_string()),
        pr_body: Some("authority proof".to_string()),
        agent: None,
    }
}

fn noop_open_script() -> &'static str {
    "#!/bin/sh\nexit 0\n"
}

/// A `gh` that records every non-`--version` invocation to `log_path`. It
/// answers `pr list` with an empty list and `pr create` with a URL so a
/// successful publish can attach a PR; the refuse tests never reach those
/// branches and the log proves no PR mutation was issued.
fn gh_record_script(log_path: &str) -> String {
    format!(
        r#"#!/bin/sh
if [ "$1" = "--version" ]; then
  echo "gh version 1.0.0"
  exit 0
fi
echo "$@" >> "{log_path}"
if [ "$1 $2" = "pr list" ]; then
  echo '[]'
  exit 0
fi
if [ "$1 $2" = "pr create" ]; then
  echo 'https://example.com/pr/1'
  exit 0
fi
if [ "$1 $2" = "pr view" ]; then
  echo 'OPEN'
  exit 0
fi
exit 0
"#
    )
}

fn remote_branch_exists(repo: &TestRepo, name: &str) -> bool {
    Command::new("git")
        .arg("--git-dir")
        .arg(repo.bare_path())
        .args(["show-ref", "--verify", &format!("refs/heads/{name}")])
        .stderr(Stdio::null())
        .status()
        .map(|status| status.success())
        .unwrap_or(false)
}

/// Assert no GitHub PR mutation was issued. `--version` and `pr list` reads are
/// fine; creates, edits, readiness, merges, and closes are remote mutations.
fn assert_no_gh_pr_mutation(log_path: &std::path::Path) {
    let log = fs::read_to_string(log_path).unwrap_or_default();
    for mutation in ["pr create", "pr edit", "pr ready", "pr merge", "pr close"] {
        assert!(
            !log.contains(mutation),
            "no gh `{mutation}` mutation may be issued before authority refusal, got log:\n{log}"
        );
    }
}

/// RAII guard for an ambient env var so a test never leaks Run context
/// into a concurrently-running test, even on panic.
struct AmbientVarGuard {
    name: &'static str,
}
impl AmbientVarGuard {
    fn set(name: &'static str, value: &str) -> Self {
        std::env::set_var(name, value);
        Self { name }
    }
}
impl Drop for AmbientVarGuard {
    fn drop(&mut self) {
        std::env::remove_var(self.name);
    }
}

/// Make a registry file inaccessible so `open_store` cannot open it — the
/// `RegistryUnavailable::Incompatible` branch (which also covers
/// schema-incompatible and locked stores). Simulating a real registry that
/// became unreadable is more faithful than a garbage file, which SQLite may
/// recreate or recover from via WAL.
#[cfg(unix)]
fn make_registry_inaccessible(path: &std::path::Path) {
    use std::os::unix::fs::PermissionsExt;
    std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o000))
        .expect("make registry inaccessible");
}

/// A Task entry point (ambient id set) whose registry file is gone must refuse
/// before any push or `gh pr` — the missing registry cannot be proven away, so
/// the PR must not degrade to generic behavior. `submit` is the gate.
#[test]
fn submit_refuses_when_registry_missing_before_any_push() {
    let home = tempfile::TempDir::new().expect("temp home");
    let repo = TestRepo::new();
    let base = repo.head_sha();

    let log_path = home.path().join("gh.log");
    let script = gh_record_script(log_path.to_string_lossy().as_ref());
    let _env = EnvGuard::with_lf_home(
        &[("gh", script.as_str()), ("open", noop_open_script())],
        home.path(),
    );

    let branch = "jack/authority-missing";
    repo.create_branch(branch);
    repo.create_file("task.txt", "task work\n");
    repo.stage_all();
    repo.commit("task commit");
    // Deliberately NOT pushed: the refusal must precede the first push.

    let _task = register_task(home.path(), repo.path(), branch, &base);

    // The registry vanishes. Ambient Run identity still marks this as an agent entry
    // point, so the missing registry is missing authority — not "no tasks here."
    std::fs::remove_file(home.path().join("loopflow.db")).expect("remove registry");
    let run_id = loopflow::durable::RunId::new();
    let _ambient = AmbientVarGuard::set(loopflow::durable::RUN_ID_ENV, run_id.as_str());

    let err = submit(
        repo.path(),
        &land_options(true, "authority missing"),
        &NullProgress,
    )
    .expect_err("missing registry must refuse before any push");
    let message = err.to_string();
    assert!(
        message.contains("authority refused"),
        "expected an authority refusal, got: {message}"
    );
    assert!(
        message.contains("missing"),
        "refusal must name the missing registry, got: {message}"
    );

    assert!(
        !remote_branch_exists(&repo, branch),
        "the branch must never reach the remote when authority is refused"
    );
    assert_no_gh_pr_mutation(&log_path);
}

/// A Task worktree whose registry exists but cannot be opened (inaccessible)
/// must refuse before any push or `gh pr`. No ambient id is set — this is the
/// human-in-a-Task-worktree shape — and the unreadable registry cannot be
/// inspected to prove otherwise, so publication refuses. The
/// `RegistryUnavailable::Incompatible` branch also covers schema-incompatible
/// and locked stores.
#[cfg(unix)]
#[test]
fn publish_refuses_when_registry_inaccessible_before_any_push() {
    let home = tempfile::TempDir::new().expect("temp home");
    let repo = TestRepo::new();
    let base = repo.head_sha();

    let log_path = home.path().join("gh.log");
    let script = gh_record_script(log_path.to_string_lossy().as_ref());
    let _env = EnvGuard::with_lf_home(
        &[("gh", script.as_str()), ("open", noop_open_script())],
        home.path(),
    );

    let branch = "jack/authority-inaccessible";
    repo.create_branch(branch);
    repo.create_file("task.txt", "task work\n");
    repo.stage_all();
    repo.commit("task commit");

    let _task = register_task(home.path(), repo.path(), branch, &base);

    // The registry exists with this Task but is now unreadable.
    make_registry_inaccessible(&home.path().join("loopflow.db"));

    let err = create_or_update_pr(
        repo.path(),
        &PrOptions {
            title: Some("inaccessible".to_string()),
            body: Some("authority proof".to_string()),
            agent: None,
        },
        &NullProgress,
    )
    .expect_err("inaccessible registry must refuse before any push");
    let message = err.to_string();
    assert!(
        message.contains("authority refused"),
        "expected an authority refusal, got: {message}"
    );
    assert!(
        message.contains("incompatible"),
        "refusal must name the inaccessible/incompatible registry, got: {message}"
    );

    assert!(
        !remote_branch_exists(&repo, branch),
        "the branch must never reach the remote when authority is refused"
    );
    assert_no_gh_pr_mutation(&log_path);
}

/// `land` arms auto-merge — a GitHub mutation. An inaccessible registry must
/// refuse before that first push, proving the land path fails closed too.
#[cfg(unix)]
#[test]
fn land_refuses_when_registry_inaccessible_before_any_push() {
    let home = tempfile::TempDir::new().expect("temp home");
    let repo = TestRepo::new();
    let base = repo.head_sha();

    let log_path = home.path().join("gh.log");
    let script = gh_record_script(log_path.to_string_lossy().as_ref());
    let _env = EnvGuard::with_lf_home(
        &[("gh", script.as_str()), ("open", noop_open_script())],
        home.path(),
    );

    let branch = "jack/authority-inaccessible-land";
    repo.create_branch(branch);
    repo.create_file("task.txt", "task work\n");
    repo.stage_all();
    repo.commit("task commit");

    let _task = register_task(home.path(), repo.path(), branch, &base);

    make_registry_inaccessible(&home.path().join("loopflow.db"));

    let err = land(
        repo.path(),
        &land_options(true, "inaccessible land"),
        &NullProgress,
    )
    .expect_err("inaccessible registry must refuse before any push");
    let message = err.to_string();
    assert!(
        message.contains("authority refused"),
        "expected an authority refusal, got: {message}"
    );

    assert!(
        !remote_branch_exists(&repo, branch),
        "the branch must never reach the remote when authority is refused"
    );
    assert_no_gh_pr_mutation(&log_path);
}

/// Stacking resolution (`task_stack`) shares the authority gate. An
/// inaccessible registry must refuse rather than return `None` and let a
/// stacked rebase silently collapse to generic.
#[cfg(unix)]
#[test]
fn task_stack_refuses_when_registry_inaccessible() {
    let home = tempfile::TempDir::new().expect("temp home");
    let repo = TestRepo::new();
    let base = repo.head_sha();

    let _env = EnvGuard::with_lf_home(&[("open", noop_open_script())], home.path());

    let branch = "jack/authority-stack";
    repo.create_branch(branch);
    repo.create_file("task.txt", "task work\n");
    repo.stage_all();
    repo.commit("task commit");

    let _task = register_task(home.path(), repo.path(), branch, &base);

    make_registry_inaccessible(&home.path().join("loopflow.db"));

    let err = task_stack(repo.path()).expect_err("inaccessible registry must refuse stacking");
    let message = err.to_string();
    assert!(
        message.contains("authority refused"),
        "expected an authority refusal, got: {message}"
    );
}

/// A registry file that is present but not a valid database (schema-incompatible
/// / corrupt) must refuse before any push or `gh pr`. The WAL sidecars are
/// removed first so SQLite cannot recover the prior valid state from them and
/// `open_store` hits "file is not a database" — the same
/// `RegistryUnavailable::Incompatible` branch as an inaccessible store.
#[test]
fn publish_refuses_when_registry_schema_incompatible_before_any_push() {
    let home = tempfile::TempDir::new().expect("temp home");
    let repo = TestRepo::new();
    let base = repo.head_sha();

    let log_path = home.path().join("gh.log");
    let script = gh_record_script(log_path.to_string_lossy().as_ref());
    let _env = EnvGuard::with_lf_home(
        &[("gh", script.as_str()), ("open", noop_open_script())],
        home.path(),
    );

    let branch = "jack/authority-schema-incompatible";
    repo.create_branch(branch);
    repo.create_file("task.txt", "task work\n");
    repo.stage_all();
    repo.commit("task commit");

    let _task = register_task(home.path(), repo.path(), branch, &base);

    let db = home.path().join("loopflow.db");
    // Drop the WAL sidecars so SQLite cannot recover a valid database from them
    // after the main file is corrupted.
    for sidecar in ["loopflow.db-wal", "loopflow.db-shm"] {
        let _ = std::fs::remove_file(home.path().join(sidecar));
    }
    std::fs::write(&db, b"not a sqlite database").expect("corrupt the registry");

    let err = create_or_update_pr(
        repo.path(),
        &PrOptions {
            title: Some("schema-incompatible".to_string()),
            body: Some("authority proof".to_string()),
            agent: None,
        },
        &NullProgress,
    )
    .expect_err("schema-incompatible registry must refuse before any push");
    let message = err.to_string();
    assert!(
        message.contains("authority refused"),
        "expected an authority refusal, got: {message}"
    );
    assert!(
        message.contains("incompatible"),
        "refusal must name the incompatible registry, got: {message}"
    );

    assert!(
        !remote_branch_exists(&repo, branch),
        "the branch must never reach the remote when authority is refused"
    );
    assert_no_gh_pr_mutation(&log_path);
}

/// Valid authority: a healthy registry with a Task that owns this
/// worktree publishes, pushes, and durably records the PR — the publication
/// request and GitHub attachment prove the Task path ran, not a generic PR.
#[test]
fn valid_authority_publishes_and_records_the_pr() {
    let home = tempfile::TempDir::new().expect("temp home");
    let repo = TestRepo::new();
    let base = repo.head_sha();

    let log_path = home.path().join("gh.log");
    let script = gh_record_script(log_path.to_string_lossy().as_ref());
    let _env = EnvGuard::with_lf_home(
        &[("gh", script.as_str()), ("open", noop_open_script())],
        home.path(),
    );

    let branch = "jack/authority-valid";
    repo.create_branch(branch);
    repo.create_file("task.txt", "task work\n");
    repo.stage_all();
    repo.commit("task commit");
    repo.push_new_branch(branch);

    let task = register_task(home.path(), repo.path(), branch, &base);

    create_or_update_pr(
        repo.path(),
        &PrOptions {
            title: Some("valid authority".to_string()),
            body: Some("authority proof".to_string()),
            agent: None,
        },
        &NullProgress,
    )
    .expect("valid authority publishes");

    assert!(
        remote_branch_exists(&repo, branch),
        "the Task branch must be pushed under valid authority"
    );

    // The Task path ran end to end: the publication request was recorded and the
    // GitHub PR was attached, so this did not degrade to a generic PR.
    let runtime = tokio::runtime::Runtime::new().expect("read task runtime");
    let pr = runtime
        .block_on(task.store.active_task_pr(&task.task.id))
        .expect("read active PR")
        .expect("active PR");
    assert!(
        pr.publication.is_some(),
        "publication must be recorded under valid authority, not degraded to generic"
    );
    assert!(
        pr.publication.as_ref().unwrap().merge.is_none(),
        "publication alone must not request a merge"
    );
    let github = pr
        .github()
        .expect("GitHub PR must be attached under valid authority");
    assert_eq!(github.number, 1, "the published PR number must be attached");
}

/// Ordinary non-Task PR flows remain explicit: a healthy registry that
/// registers a task for a *different* worktree must not capture this checkout.
/// The publish proceeds as a normal PR (the Task bookkeeping is an explicit
/// no-op), proving the fail-closed gate does not over-block ordinary PRs.
#[test]
fn ordinary_pr_publishes_when_worktree_is_not_a_task_worktree() {
    let home = tempfile::TempDir::new().expect("temp home");
    let repo = TestRepo::new();
    let base = repo.head_sha();

    let log_path = home.path().join("gh.log");
    let script = gh_record_script(log_path.to_string_lossy().as_ref());
    let _env = EnvGuard::with_lf_home(
        &[("gh", script.as_str()), ("open", noop_open_script())],
        home.path(),
    );

    // A healthy registry exists, but its one Task claims a different
    // worktree — this checkout is provably not a Task worktree.
    let elsewhere = tempfile::TempDir::new().expect("unrelated worktree");
    let _unrelated = register_task(home.path(), elsewhere.path(), "jack/elsewhere", &base);

    let branch = "jack/ordinary-pr";
    repo.create_branch(branch);
    repo.create_file("task.txt", "ordinary work\n");
    repo.stage_all();
    repo.commit("ordinary commit");
    repo.push_new_branch(branch);

    create_or_update_pr(
        repo.path(),
        &PrOptions {
            title: Some("ordinary non-Task PR".to_string()),
            body: Some("not a task".to_string()),
            agent: None,
        },
        &NullProgress,
    )
    .expect("ordinary non-Task PR publishes");

    assert!(
        remote_branch_exists(&repo, branch),
        "an ordinary non-Task PR must still push and publish"
    );
}

/// Ordinary non-Task PR flows remain explicit when no registry exists at all:
/// a machine with no registry file has no tasks, so a plain PR publishes.
#[test]
fn ordinary_pr_publishes_when_no_registry_exists() {
    let home = tempfile::TempDir::new().expect("temp home");
    let repo = TestRepo::new();

    let log_path = home.path().join("gh.log");
    let script = gh_record_script(log_path.to_string_lossy().as_ref());
    let _env = EnvGuard::with_lf_home(
        &[("gh", script.as_str()), ("open", noop_open_script())],
        home.path(),
    );
    // No register_task, no ambient id, no registry file.

    let branch = "jack/ordinary-no-registry";
    repo.create_branch(branch);
    repo.create_file("task.txt", "ordinary work\n");
    repo.stage_all();
    repo.commit("ordinary commit");
    repo.push_new_branch(branch);

    create_or_update_pr(
        repo.path(),
        &PrOptions {
            title: Some("ordinary PR no registry".to_string()),
            body: Some("not a task".to_string()),
            agent: None,
        },
        &NullProgress,
    )
    .expect("ordinary non-Task PR publishes without any registry");

    assert!(
        remote_branch_exists(&repo, branch),
        "an ordinary non-Task PR must still push and publish with no registry"
    );
}

/// Delivery commands act on Task Work directly. They do not require or infer a
/// controller decision, so a person can submit a Task created with `prepare`
/// or take over a Task whose controller is absent.
#[test]
fn managed_task_submit_assigns_for_human_review() {
    let home = tempfile::TempDir::new().expect("temp home");
    let repo = TestRepo::new();
    let base = repo.head_sha();

    let log_path = home.path().join("gh.log");
    let script = gh_record_script(log_path.to_string_lossy().as_ref());
    let _env = EnvGuard::with_lf_home(
        &[("gh", script.as_str()), ("open", noop_open_script())],
        home.path(),
    );

    let branch = "jack/managed-submit";
    repo.create_branch(branch);
    repo.create_file("task.txt", "task work\n");
    repo.stage_all();
    repo.commit("task commit");
    // Deliberately not pushed: submit owns integration and publication.

    let _task = register_task(home.path(), repo.path(), branch, &base);

    submit(
        repo.path(),
        &land_options(true, "managed submit"),
        &NullProgress,
    )
    .expect("managed Task submits for human review");

    assert!(
        remote_branch_exists(&repo, branch),
        "submit must publish the Task branch"
    );
    let log = fs::read_to_string(&log_path).unwrap_or_default();
    assert!(
        log.contains("pr ready") && log.contains("pr edit --add-assignee @me"),
        "submit must prepare the Task PR for a human merge, got log:\n{log}"
    );
    assert!(
        !log.contains("pr merge"),
        "submit must not arm or merge the Task PR, got log:\n{log}"
    );
}

#[test]
fn ordinary_submit_still_assigns_for_review() {
    let home = tempfile::TempDir::new().expect("temp home");
    let repo = TestRepo::new();
    let base = repo.head_sha();

    let log_path = home.path().join("gh.log");
    let script = gh_record_script(log_path.to_string_lossy().as_ref());
    let _env = EnvGuard::with_lf_home(
        &[("gh", script.as_str()), ("open", noop_open_script())],
        home.path(),
    );

    // A healthy registry exists, but its one Task claims a different worktree —
    // this checkout is provably not a Task worktree, so submit is unaffected.
    let elsewhere = tempfile::TempDir::new().expect("unrelated worktree");
    let _unrelated = register_task(home.path(), elsewhere.path(), "jack/elsewhere", &base);

    let branch = "jack/ordinary-submit";
    repo.create_branch(branch);
    repo.create_file("task.txt", "ordinary work\n");
    repo.stage_all();
    repo.commit("ordinary commit");
    repo.push_new_branch(branch);

    submit(
        repo.path(),
        &land_options(true, "ordinary submit"),
        &NullProgress,
    )
    .expect("ordinary non-Task submit still assigns for review");

    let log = fs::read_to_string(&log_path).unwrap_or_default();
    assert!(
        log.contains("pr edit --add-assignee @me"),
        "ordinary submit must assign the PR for a human merge, got log:\n{log}"
    );
    assert!(
        !log.contains("merge --auto"),
        "submit must never arm auto-merge, got log:\n{log}"
    );
}