@zabaca/zbc 0.11.0 → 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (74) hide show
  1. package/CHANGELOG.md +63 -0
  2. package/package.json +2 -1
  3. package/templates/apps/inbox/package.json +1 -1
  4. package/templates/apps/walgit/CONTEXT.md +135 -0
  5. package/templates/apps/walgit/Dockerfile +40 -18
  6. package/templates/apps/walgit/README.md +518 -55
  7. package/templates/apps/walgit/e2e/README.md +100 -6
  8. package/templates/apps/walgit/e2e/harness.ts +262 -1
  9. package/templates/apps/walgit/e2e/live.ts +588 -0
  10. package/templates/apps/walgit/e2e/scenarios.ts +367 -5
  11. package/templates/apps/walgit/e2e/suite.ts +5 -5
  12. package/templates/apps/walgit/examples/watch.ts +209 -0
  13. package/templates/apps/walgit/package.json +12 -3
  14. package/templates/apps/walgit/registry.json +6 -11
  15. package/templates/apps/walgit/shared/capabilities.ts +189 -0
  16. package/templates/apps/walgit/shared/container-env.ts +114 -0
  17. package/templates/apps/walgit/shared/credentials.ts +81 -0
  18. package/templates/apps/walgit/shared/events.ts +277 -0
  19. package/templates/apps/walgit/shared/landing.ts +1241 -0
  20. package/templates/apps/walgit/shared/llms.ts +463 -0
  21. package/templates/apps/walgit/shared/outbox.ts +266 -0
  22. package/templates/apps/walgit/shared/policy.ts +59 -0
  23. package/templates/apps/walgit/shared/protocol.ts +197 -0
  24. package/templates/apps/walgit/shared/provenance.ts +154 -0
  25. package/templates/apps/walgit/shared/ref-cache.ts +181 -0
  26. package/templates/apps/walgit/shared/telemetry.ts +219 -0
  27. package/templates/apps/walgit/src/announce-main.ts +37 -0
  28. package/templates/apps/walgit/src/announce.ts +98 -0
  29. package/templates/apps/walgit/src/append-only.ts +112 -0
  30. package/templates/apps/walgit/src/cache.ts +172 -0
  31. package/templates/apps/walgit/src/cli.ts +493 -0
  32. package/templates/apps/walgit/src/compact.ts +25 -23
  33. package/templates/apps/walgit/src/delete-repo.ts +237 -0
  34. package/templates/apps/walgit/src/expire.ts +248 -0
  35. package/templates/apps/walgit/src/gc.ts +8 -16
  36. package/templates/apps/walgit/src/git-backend.ts +29 -0
  37. package/templates/apps/walgit/src/git.ts +78 -0
  38. package/templates/apps/walgit/src/hook-main.ts +259 -17
  39. package/templates/apps/walgit/src/hooks.ts +4 -3
  40. package/templates/apps/walgit/src/http.ts +237 -45
  41. package/templates/apps/walgit/src/instructions.ts +240 -0
  42. package/templates/apps/walgit/src/keys.ts +126 -0
  43. package/templates/apps/walgit/src/limits.ts +158 -0
  44. package/templates/apps/walgit/src/materialize.bench.ts +10 -10
  45. package/templates/apps/walgit/src/materialize.ts +48 -40
  46. package/templates/apps/walgit/src/mkdir-lock.ts +66 -0
  47. package/templates/apps/walgit/src/orphans.ts +2 -5
  48. package/templates/apps/walgit/src/pending.ts +201 -0
  49. package/templates/apps/walgit/src/push-cert.ts +254 -0
  50. package/templates/apps/walgit/src/push.ts +233 -46
  51. package/templates/apps/walgit/src/reconcile.ts +5 -8
  52. package/templates/apps/walgit/src/repo.ts +22 -77
  53. package/templates/apps/walgit/src/server.ts +148 -26
  54. package/templates/apps/walgit/src/signers.ts +577 -0
  55. package/templates/apps/walgit/src/store-env.ts +5 -4
  56. package/templates/apps/walgit/src/store.ts +47 -24
  57. package/templates/apps/walgit/src/usage.ts +404 -0
  58. package/templates/apps/walgit/src/verify.ts +171 -0
  59. package/templates/apps/walgit/src/wal-index.ts +189 -11
  60. package/templates/apps/walgit/tsconfig.json +8 -2
  61. package/templates/apps/walgit/tsconfig.worker.json +24 -0
  62. package/templates/apps/walgit/worker/events-do.ts +259 -0
  63. package/templates/apps/walgit/worker/index.ts +572 -0
  64. package/templates/apps/walgit/wrangler.jsonc +95 -0
  65. package/templates/apps/warehouse/package.json +1 -1
  66. package/templates/infra/modules/cloudflare/index.ts +77 -6
  67. package/templates/infra/modules/cloudflare-access/index.ts +85 -14
  68. package/templates/infra/modules/fly/index.ts +150 -10
  69. package/templates/infra/modules/turso/index.ts +43 -3
  70. package/templates/infra/package.json +1 -1
  71. package/templates/apps/walgit/entrypoint.sh +0 -59
  72. package/templates/apps/walgit/fly.toml +0 -52
  73. package/templates/apps/walgit/src/ssh-shell.ts +0 -36
  74. package/templates/apps/walgit/sshd_config +0 -38
@@ -1,5 +1,5 @@
1
1
  /**
2
- * The seven scenarios from the walgit design, as executable specs.
2
+ * The scenarios from the walgit design, as executable specs.
3
3
  *
4
4
  * They are numbered and worded to match the design so a reader can hold the
5
5
  * document and this file side by side. Each one returns the observations it
@@ -8,7 +8,9 @@
8
8
  * weakened into tautologies without changing a single assertion.
9
9
  *
10
10
  * See docs/adr/0007-walgit-object-storage-holds-the-log.md in the zbc
11
- * repository for why these are the seven that matter.
11
+ * repository for why the first seven are the ones that matter; scenario 8 is
12
+ * the ref-event stream of docs/adr/0009, and scenario 9 the push provenance of
13
+ * docs/adr/0011.
12
14
  */
13
15
 
14
16
  import * as fs from 'node:fs'
@@ -18,9 +20,21 @@ import { compact } from '../src/compact'
18
20
  import { collectGarbage } from '../src/gc'
19
21
  import { materialize } from '../src/materialize'
20
22
  import { resolveRepo } from '../src/repo'
21
- import { loadIndex, type WalIndex } from '../src/wal-index'
23
+ import { loadIndex, type Provenance, type WalIndex } from '../src/wal-index'
24
+ import { fingerprintIn } from '../shared/provenance'
25
+ import { PROVENANCE_PATH } from '../shared/protocol'
22
26
  import { LATENCY_BASELINE, type LatencyCeiling } from './latency-baseline'
23
- import { clone, commit, git, gitOk, sleep, type Run } from './harness'
27
+ import {
28
+ EventsEndpoint,
29
+ TOKEN,
30
+ clone,
31
+ commit,
32
+ git,
33
+ gitOk,
34
+ sleep,
35
+ type Run,
36
+ type WalgitNode,
37
+ } from './harness'
24
38
 
25
39
  export interface Scenario {
26
40
  n: number
@@ -415,7 +429,7 @@ const restoreLatency: Scenario = {
415
429
  const sizes = opts.quick ? [1, 10] : [1, 10, 50]
416
430
  const runs = opts.quick ? 5 : 11
417
431
  const notes: string[] = [
418
- 'measures WAL replay ONLY — machine wake (~1.35s on Fly, milestone-0 spike) is excluded, ' +
432
+ 'measures WAL replay ONLY — container cold start (median 1.77s, Containers spike) is excluded, ' +
419
433
  'because blending the two makes a regression unattributable',
420
434
  ]
421
435
  const breaches: string[] = []
@@ -516,6 +530,352 @@ function loadCeilings(): Record<string, LatencyCeiling> {
516
530
  return JSON.parse(fs.readFileSync(override, 'utf8')) as Record<string, LatencyCeiling>
517
531
  }
518
532
 
533
+ // ── 8. Ref events ───────────────────────────────────────────────────────────
534
+
535
+ /**
536
+ * How long a push that must announce NOTHING is given to prove it.
537
+ *
538
+ * A negative is only as strong as the wait behind it: assert immediately and
539
+ * the scenario passes because the announcement had not arrived yet. This is an
540
+ * announcement over loopback from a hook that has already exited, so a second
541
+ * is orders of magnitude more than it needs.
542
+ */
543
+ const SILENCE_WINDOW_MS = 1_000
544
+
545
+ const refEvents: Scenario = {
546
+ n: 8,
547
+ name: 'Ref events — a subscriber sees a real push, and never sees one that lost',
548
+ async run(run) {
549
+ const repoId = run.repoId('events')
550
+ const endpoint = new EventsEndpoint()
551
+ await endpoint.start()
552
+ try {
553
+ // Both nodes announce to the same endpoint, which is what makes the
554
+ // third check possible: the loser of a compare-and-swap has somewhere to
555
+ // announce to, and still announces nothing.
556
+ const eventsEnv = {
557
+ WALGIT_EVENTS_URL: endpoint.url,
558
+ WALGIT_EVENTS_TOKEN: endpoint.token,
559
+ }
560
+ const a = await run.node('events-a', eventsEnv)
561
+ const b = await run.node('events-b', eventsEnv)
562
+ endpoint.refsFrom(a)
563
+
564
+ const work = await clone(run, a, repoId, 'work')
565
+ const seed = await commit(work, 'seed\n')
566
+ assert(
567
+ (await git(work, 'push', 'origin', 'HEAD:refs/heads/main')).status === 0,
568
+ 'the seed push failed',
569
+ )
570
+
571
+ // Subscribed AFTER the seed push, so the handshake has something to be
572
+ // right about: a subscriber that connects to a repository already in
573
+ // motion must be told where it stands before any event fires.
574
+ const subscriber = await endpoint.subscribe([{ repo: repoId }])
575
+ const handshakeMain = subscriber.handshake?.refs.find((r) => r.ref === 'refs/heads/main')
576
+ assert(
577
+ handshakeMain?.sha === seed,
578
+ `handshake said ${handshakeMain?.sha ?? 'nothing'} for main, expected ${seed}`,
579
+ )
580
+
581
+ // 1. A real push, over a real socket.
582
+ const pushed = await commit(work, 'pushed\n')
583
+ assert(
584
+ (await git(work, 'push', 'origin', 'HEAD:refs/heads/main')).status === 0,
585
+ 'the push under observation failed',
586
+ )
587
+ const advanced = await subscriber.next((e) => e.ref === 'refs/heads/main' && e.sha === pushed)
588
+
589
+ // 2. A ref-only push. `git push` sends no pack at all here — the objects
590
+ // are already on the server — so a hook path that only fires when
591
+ // something was uploaded would pass every other check and fail this one.
592
+ const beforeRelease = subscriber.events.length
593
+ assert(
594
+ (await git(work, 'push', 'origin', 'refs/heads/main:refs/heads/release')).status === 0,
595
+ 'the ref-only push failed',
596
+ )
597
+ const release = await subscriber.next(
598
+ (e) => e.ref === 'refs/heads/release' && e.sha === pushed,
599
+ )
600
+ assert(
601
+ subscriber.events.length > beforeRelease,
602
+ 'the ref-only push arrived as no new message',
603
+ )
604
+
605
+ // 3. The loser announces nothing. Two clones from two different nodes,
606
+ // as in scenario 3, so the race is resolved by the store's
607
+ // compare-and-swap rather than by one machine's lock — and the push that
608
+ // loses it never reaches `post-receive`, which is the ordering the
609
+ // announcement's correctness rests on (src/announce.ts).
610
+ const left = await clone(run, a, repoId, 'left')
611
+ const right = await clone(run, b, repoId, 'right')
612
+ const leftOid = await commit(left, 'left\n')
613
+ const rightOid = await commit(right, 'right\n')
614
+ const [pushLeft, pushRight] = await Promise.all([
615
+ git(left, 'push', 'origin', 'HEAD:refs/heads/main'),
616
+ git(right, 'push', 'origin', 'HEAD:refs/heads/main'),
617
+ ])
618
+ const winners = [pushLeft, pushRight].filter((r) => r.status === 0)
619
+ assert(
620
+ winners.length === 1,
621
+ `expected exactly one winner, got ${winners.length}\nleft:\n${pushLeft.out}\nright:\n${pushRight.out}`,
622
+ )
623
+ const winnerOid = pushLeft.status === 0 ? leftOid : rightOid
624
+ const loserOid = pushLeft.status === 0 ? rightOid : leftOid
625
+
626
+ await subscriber.next((e) => e.ref === 'refs/heads/main' && e.sha === winnerOid)
627
+ await sleep(SILENCE_WINDOW_MS)
628
+ // Asserted against what the endpoint was TOLD, not against what the
629
+ // socket received: an announcement the fan-out happened to drop would
630
+ // otherwise read as a push that never announced.
631
+ assert(
632
+ !endpoint.announced.some((e) => e.sha === loserOid),
633
+ `the loser ${loserOid.slice(0, 8)} was announced`,
634
+ )
635
+ assert(
636
+ !subscriber.events.some((e) => e.sha === loserOid),
637
+ `the loser ${loserOid.slice(0, 8)} reached the subscriber`,
638
+ )
639
+
640
+ const { index } = await loadIndex(run.store, repoId)
641
+ assert(
642
+ index.refs['refs/heads/main'] === winnerOid,
643
+ 'the log does not name the push the subscriber was told about',
644
+ )
645
+
646
+ return [
647
+ `handshake reported main at ${seed.slice(0, 8)} from the Index before any event`,
648
+ `push ${pushed.slice(0, 8)} reached the subscriber as ${advanced.ref} over a real socket`,
649
+ `ref-only push (no pack) reached it as ${release.ref} at ${release.sha?.slice(0, 8)}`,
650
+ `the compare-and-swap loser ${loserOid.slice(0, 8)} announced nothing in ` +
651
+ `${SILENCE_WINDOW_MS}ms; the winner ${winnerOid.slice(0, 8)} arrived`,
652
+ 'NOTE: the sockets are held by a Bun server, not a Durable Object — the ' +
653
+ 'decisions are shared/events.ts and shared/outbox.ts either way',
654
+ ]
655
+ } finally {
656
+ endpoint.stop()
657
+ }
658
+ },
659
+ }
660
+
661
+ // ── 9. Push provenance ──────────────────────────────────────────────────────
662
+
663
+ /**
664
+ * The one place the provenance chain is checked without a double anywhere in
665
+ * it (docs/adr/0011).
666
+ *
667
+ * Every seam below is stubbed somewhere in the unit suite, and each stub is
668
+ * reasonable on its own — but the design was nearly built on git's own
669
+ * verification verdict, which reports `GIT_PUSH_CERT_STATUS=N` and no signer at
670
+ * all for an SSH signature. A fake verifier would have reported success against
671
+ * that mistake for as long as anyone cared to look. So here the key is real and
672
+ * generated by this scenario, the certificate is minted by `git push
673
+ * --signed=yes` against a server that advertised the capability, the signature
674
+ * is verified by the real `ssh-keygen`, and the answer is read back over HTTP
675
+ * from the endpoint a client would use — then compared against `ssh-keygen -lf`
676
+ * on the public half of the key, which is the only fingerprint in the run that
677
+ * walgit had no hand in producing.
678
+ */
679
+
680
+ /** The seed this scenario's node advertises nonces from. Local, and disposable. */
681
+ const CERT_NONCE_SEED = 'walgit-e2e-push-cert-seed'
682
+
683
+ /** `ssh-keygen`, run for its output. Never throws; the caller asserts. */
684
+ async function sshKeygen(...args: string[]): Promise<{ status: number; out: string }> {
685
+ const child = Bun.spawn(['ssh-keygen', ...args], { stdout: 'pipe', stderr: 'pipe' })
686
+ const [out, err, status] = await Promise.all([
687
+ new Response(child.stdout).text(),
688
+ new Response(child.stderr).text(),
689
+ child.exited,
690
+ ])
691
+ return { status, out: `${out}${err}` }
692
+ }
693
+
694
+ /**
695
+ * How many objects the entries after `seqBefore` carry, straight out of the
696
+ * pack header (`PACK`, version, object count — bytes 8..12, big-endian).
697
+ *
698
+ * Zero when nothing was transferred, which is the case a ref-only push has to
699
+ * be checked against. Reading the header beats counting WAL entries because a
700
+ * signed ref-only push uploads an empty pack where an unsigned one uploads
701
+ * nothing, and both mean the same thing.
702
+ */
703
+ async function packObjectCount(run: Run, index: WalIndex, seqBefore: number): Promise<number> {
704
+ let objects = 0
705
+ for (const entry of index.entries.filter((e) => e.seq > seqBefore)) {
706
+ const stored = await run.store.get(entry.key)
707
+ assert(stored !== null, `the log names ${entry.key}, which the store does not have`)
708
+ const head = stored.body
709
+ assert(new TextDecoder().decode(head.subarray(0, 4)) === 'PACK', `${entry.key} is not a pack`)
710
+ objects += new DataView(head.buffer, head.byteOffset, head.byteLength).getUint32(8)
711
+ }
712
+ return objects
713
+ }
714
+
715
+ /** `{ 'refs/heads/main': { signer, ts } }`, read over HTTP as a client would. */
716
+ async function readProvenance(
717
+ node: WalgitNode,
718
+ repoId: string,
719
+ ): Promise<Record<string, Provenance>> {
720
+ const res = await fetch(
721
+ `http://127.0.0.1:${node.port}${PROVENANCE_PATH}?repo=${encodeURIComponent(repoId)}`,
722
+ { headers: { authorization: `Bearer ${TOKEN}` } },
723
+ )
724
+ assert(res.status === 200, `provenance read answered ${res.status}, expected 200`)
725
+ const body = (await res.json()) as { repo: string; provenance: Record<string, Provenance> }
726
+ assert(body.repo === repoId, `provenance read named ${body.repo}, expected ${repoId}`)
727
+ return body.provenance
728
+ }
729
+
730
+ const pushProvenance: Scenario = {
731
+ n: 9,
732
+ name: 'Push provenance — a real signed push names its key, and an unsigned one names nobody',
733
+ async run(run) {
734
+ const repoId = run.repoId('provenance')
735
+ // The seed IS the capability: with it set, `git-receive-pack` advertises
736
+ // `push-cert`; without it the client's own git refuses `--signed=yes`
737
+ // before a byte reaches the network. So a signed push that exits 0 below
738
+ // is itself evidence the server offered the capability.
739
+ const node = await run.node('provenance', { WALGIT_PUSH_CERT_SEED: CERT_NONCE_SEED })
740
+
741
+ // Generated here, used here, and gone at the end — walgit has no key
742
+ // registry (that is the point of `check-novalidate`), so nothing outside
743
+ // this scenario ever needs to have heard of it.
744
+ const keyDir = run.dir('signing-key')
745
+ const keyPath = path.join(keyDir, 'id_ed25519')
746
+ try {
747
+ const generated = await sshKeygen(
748
+ '-q',
749
+ '-t',
750
+ 'ed25519',
751
+ '-N',
752
+ '',
753
+ '-C',
754
+ 'walgit-e2e',
755
+ '-f',
756
+ keyPath,
757
+ )
758
+ assert(generated.status === 0, `ssh-keygen could not generate a key:\n${generated.out}`)
759
+
760
+ // The expected answer, from the tool rather than from walgit. `-lf` on
761
+ // the PUBLIC half: if the two disagree, the recorded Signer is not this
762
+ // key, whatever else verified.
763
+ const listed = await sshKeygen('-lf', `${keyPath}.pub`)
764
+ assert(listed.status === 0, `ssh-keygen -lf failed:\n${listed.out}`)
765
+ const expected = fingerprintIn(listed.out)
766
+ assert(expected !== null, `ssh-keygen -lf named no fingerprint:\n${listed.out}`)
767
+
768
+ const work = await clone(run, node, repoId, 'signer')
769
+ // Local config only — the ambient `~/.gitconfig` is already stripped by
770
+ // the harness, so this is the whole of what makes the client sign.
771
+ await gitOk(work, 'config', 'gpg.format', 'ssh')
772
+ await gitOk(work, 'config', 'user.signingkey', keyPath)
773
+
774
+ // 1. A real signed push, minted and verified end to end.
775
+ const signed = await commit(work, 'signed\n')
776
+ const pushSigned = await git(work, 'push', '--signed=yes', 'origin', 'HEAD:refs/heads/main')
777
+ assert(pushSigned.status === 0, `the signed push failed:\n${pushSigned.out}`)
778
+
779
+ const afterSigned = await readProvenance(node, repoId)
780
+ const main = afterSigned['refs/heads/main']
781
+ assert(main !== undefined, 'the signed push recorded no Signer for refs/heads/main')
782
+ assert(
783
+ main.signer === expected,
784
+ `recorded ${main.signer}, but ssh-keygen -lf says ${expected}`,
785
+ )
786
+ assert(
787
+ !Number.isNaN(Date.parse(main.ts)),
788
+ `the recorded timestamp ${main.ts} is not an instant`,
789
+ )
790
+
791
+ // 2. A signed push whose refs move without new objects: a second branch
792
+ // pointed at the commit the server already has. The provenance path must
793
+ // not be hung off the upload — everything above would pass if it were.
794
+ const seqBefore = (await loadIndex(run.store, repoId)).index.seq
795
+ const pushRefOnly = await git(
796
+ work,
797
+ 'push',
798
+ '--signed=yes',
799
+ 'origin',
800
+ 'refs/heads/main:refs/heads/release',
801
+ )
802
+ assert(pushRefOnly.status === 0, `the ref-only signed push failed:\n${pushRefOnly.out}`)
803
+
804
+ const afterRefOnly = await loadIndex(run.store, repoId)
805
+ assert(
806
+ afterRefOnly.index.refs['refs/heads/release'] === signed,
807
+ 'the ref-only push did not move refs/heads/release',
808
+ )
809
+ // "No new objects" is asserted about the objects, not about whether a
810
+ // pack arrived: a signed push sends an EMPTY pack where an unsigned one
811
+ // sends none at all (scenario 8's ref-only push appends no WAL entry;
812
+ // this one appends a 32-byte header-and-trailer). Both are the same
813
+ // fact — nothing was transferred — so the check reads the pack's own
814
+ // object count rather than counting WAL entries.
815
+ const objectsPushed = await packObjectCount(run, afterRefOnly.index, seqBefore)
816
+ assert(
817
+ objectsPushed === 0,
818
+ `the ref-only push transferred ${objectsPushed} object(s); it was not ref-only`,
819
+ )
820
+
821
+ const release = (await readProvenance(node, repoId))['refs/heads/release']
822
+ assert(release !== undefined, 'the ref-only signed push recorded no Signer')
823
+ assert(
824
+ release.signer === expected,
825
+ `the ref-only push recorded ${release.signer}, expected ${expected}`,
826
+ )
827
+
828
+ // 3. The negative, on the same repository and the same clone: an
829
+ // ordinary push lands, and records nothing — neither a Signer of its
830
+ // own, nor any change to the two already recorded.
831
+ const unsigned = await commit(work, 'unsigned\n')
832
+ const pushUnsigned = await git(work, 'push', 'origin', 'HEAD:refs/heads/plain')
833
+ assert(pushUnsigned.status === 0, `the unsigned push failed:\n${pushUnsigned.out}`)
834
+
835
+ const final = await readProvenance(node, repoId)
836
+ const { index } = await loadIndex(run.store, repoId)
837
+ assert(
838
+ index.refs['refs/heads/plain'] === unsigned,
839
+ 'the unsigned push did not land — the negative below would be vacuous',
840
+ )
841
+ assert(
842
+ final['refs/heads/plain'] === undefined,
843
+ `the unsigned push recorded ${final['refs/heads/plain']?.signer}`,
844
+ )
845
+ assert(
846
+ Object.keys(final).sort().join(',') === 'refs/heads/main,refs/heads/release',
847
+ `provenance names ${Object.keys(final).sort().join(', ')} after the unsigned push`,
848
+ )
849
+ assert(
850
+ final['refs/heads/main']?.ts === main.ts,
851
+ 'the unsigned push disturbed the Signer of a ref it never touched',
852
+ )
853
+
854
+ // Gone the moment it stops being needed, and observed to be gone rather
855
+ // than assumed: a suite that leaves a private key in a scratch directory
856
+ // has taught every reader that this is how one signs a push.
857
+ fs.rmSync(keyDir, { recursive: true, force: true })
858
+ assert(!fs.existsSync(keyPath), 'the signing key outlived the scenario')
859
+
860
+ return [
861
+ `signed push ${signed.slice(0, 8)} recorded ${expected}, which is ` +
862
+ 'ssh-keygen -lf on the public half of a key generated by this scenario',
863
+ `the ref-only signed push recorded ${release.signer.slice(0, 14)}… for ` +
864
+ 'refs/heads/release, transferring 0 objects',
865
+ `the unsigned push landed as ${unsigned.slice(0, 8)} on refs/heads/plain and ` +
866
+ `recorded nothing; provenance still names exactly ${Object.keys(final).length} refs`,
867
+ 'read back over HTTP from ' +
868
+ `${PROVENANCE_PATH}?repo=…, behind the same credential a clone needs`,
869
+ 'the ed25519 key was generated by this scenario and removed with it',
870
+ ]
871
+ } finally {
872
+ // The same removal again, for the paths that never reached it: an
873
+ // assertion above throwing must not be how a key survives.
874
+ fs.rmSync(keyDir, { recursive: true, force: true })
875
+ }
876
+ },
877
+ }
878
+
519
879
  export const SCENARIOS: Scenario[] = [
520
880
  durability,
521
881
  noPhantomAcks,
@@ -524,4 +884,6 @@ export const SCENARIOS: Scenario[] = [
524
884
  compactionSafety,
525
885
  idleRoundTrip,
526
886
  restoreLatency,
887
+ refEvents,
888
+ pushProvenance,
527
889
  ]
@@ -1,8 +1,8 @@
1
1
  #!/usr/bin/env bun
2
2
  /**
3
- * The seven-scenario verification suite.
3
+ * The verification suite.
4
4
  *
5
- * bun run e2e/suite.ts # all seven, against a local FileStore
5
+ * bun run e2e/suite.ts # every scenario, against a local FileStore
6
6
  * bun run e2e/suite.ts --quick # smaller fixtures, disclosed in the output
7
7
  * bun run e2e/suite.ts --only 2,7 # a subset, disclosed in the output
8
8
  *
@@ -48,7 +48,7 @@ interface Outcome {
48
48
  const run: RunType = new Run()
49
49
 
50
50
  // Cleanup on the way out by every route, including the ones that skip `finally`.
51
- // A run that leaks its prefix costs storage; a run that leaks a Fly app costs
51
+ // A run that leaks its prefix costs storage; a run that leaks a deployed app costs
52
52
  // two dollars a month forever.
53
53
  let cleaned = false
54
54
  const cleanup = async () => {
@@ -85,7 +85,7 @@ const outcomes: Outcome[] = []
85
85
  try {
86
86
  for (const scenario of selected) {
87
87
  const startedAt = performance.now()
88
- process.stdout.write(`[${scenario.n}/7] ${scenario.name}\n`)
88
+ process.stdout.write(`[${scenario.n}/${SCENARIOS.length}] ${scenario.name}\n`)
89
89
  try {
90
90
  const notes = await scenario.run(run, { quick })
91
91
  const ms = Math.round(performance.now() - startedAt)
@@ -126,7 +126,7 @@ if (process.env.WALGIT_E2E_JSON) {
126
126
  }
127
127
 
128
128
  // 1 = something is broken. 2 = nothing broke but the suite ran less than the
129
- // full seven, which must not be readable as a clean sweep by a script either.
129
+ // full set, which must not be readable as a clean sweep by a script either.
130
130
  if (failed.length > 0) process.exit(1)
131
131
  if (selected.length < SCENARIOS.length) {
132
132
  console.log('PARTIAL RUN — exiting 2 so this cannot be mistaken for a full pass.')
@@ -0,0 +1,209 @@
1
+ #!/usr/bin/env bun
2
+ /**
3
+ * Keep local clones current without ever asking whether they are.
4
+ *
5
+ * This is the whole client. There is no SDK to install and nothing here is
6
+ * imported from walgit — it is one WebSocket and one `git fetch`, written out
7
+ * so that an agent can read it, understand the protocol from it, and paste a
8
+ * changed version rather than depend on this file.
9
+ *
10
+ * bun watch.ts my-thing=/path/to/clone other-repo=/path/to/other
11
+ *
12
+ * Run it in the background and forget it: `nohup bun watch.ts … &`, a tmux
13
+ * pane, or whatever your harness uses for long-lived processes. It holds one
14
+ * socket for every repository named, because the subscription is a list.
15
+ *
16
+ * WHAT IT DOES ON AN EVENT, and what it deliberately does not: `git fetch`,
17
+ * which advances `origin/<ref>` and touches nothing else — and then it says
18
+ * whether what arrived collides with the work in progress here, which is the
19
+ * question the fetch was really being run to answer. Your branch, your
20
+ * working tree and any work in progress are left alone — a watcher that moved
21
+ * branches under a working agent would be a menace. "Current" here means
22
+ * `origin/main` is fresh without anyone having asked for it; merging or
23
+ * rebasing stays a decision its owner makes.
24
+ *
25
+ * WHAT IT DOES NOT NEED, which is the point: no cursor, no state file, no
26
+ * keepalive, no config. Events are latest state, so a reconnect's handshake IS
27
+ * the recovery — a client that was offline for an hour is correct one round
28
+ * trip after it comes back, with nothing remembered in between.
29
+ *
30
+ * Measured against agentgit: an event lands under a second after the push, the
31
+ * fetch it triggers takes about another, and a socket idle for six minutes
32
+ * receives the next push without a keepalive of any kind.
33
+ */
34
+
35
+ /** `repo=dir` pairs, and optionally `--ref refs/heads/whatever` (repeatable). */
36
+ function parseArgs(argv: readonly string[]): {
37
+ targets: Map<string, string>
38
+ refs: string[]
39
+ } {
40
+ const targets = new Map<string, string>()
41
+ const refs: string[] = []
42
+ for (let i = 0; i < argv.length; i += 1) {
43
+ const arg = argv[i] as string
44
+ if (arg === '--ref') {
45
+ const value = argv[i + 1]
46
+ if (!value) throw new Error('--ref needs a ref name')
47
+ refs.push(value)
48
+ i += 1
49
+ continue
50
+ }
51
+ const split = arg.indexOf('=')
52
+ if (split < 1) throw new Error(`expected repo=dir, got ${JSON.stringify(arg)}`)
53
+ targets.set(arg.slice(0, split), arg.slice(split + 1))
54
+ }
55
+ if (targets.size === 0) {
56
+ throw new Error('usage: bun watch.ts <repo>=<dir> [<repo>=<dir> …] [--ref refs/heads/main]')
57
+ }
58
+ // Watching `refs/heads/main` unless told otherwise, rather than the whole
59
+ // repository: fetching on every tag and every side branch is noise for the
60
+ // one question this answers. Pass `--ref` more than once for more refs.
61
+ return { targets, refs: refs.length > 0 ? refs : ['refs/heads/main'] }
62
+ }
63
+
64
+ const { targets, refs } = parseArgs(process.argv.slice(2))
65
+ const host = process.env.WALGIT_HOST ?? 'agentgit.zabaca.com'
66
+ // Only needed where the instance requires a credential; a public one takes none.
67
+ const token = process.env.WALGIT_TOKEN ?? ''
68
+
69
+ const log = (...parts: unknown[]) => console.log(new Date().toISOString(), ...parts)
70
+
71
+ /** Fetch the ref that moved, and say whether the clone now agrees with the event. */
72
+ function fetchRef(repo: string, ref: string, sha: string | null): void {
73
+ const dir = targets.get(repo)
74
+ if (!dir) return
75
+ if (sha === null) {
76
+ // A deleted ref is not a reason to fetch: nothing new exists to download,
77
+ // and pruning somebody's ref out from under a working clone is a decision
78
+ // for its owner, not for a watcher.
79
+ log(`${repo} ${ref} deleted upstream; leaving ${dir} alone`)
80
+ return
81
+ }
82
+ const short = ref.replace(/^refs\/heads\//, '')
83
+ const result = Bun.spawnSync(['git', '-C', dir, 'fetch', '--quiet', 'origin', short])
84
+ if (result.exitCode !== 0) {
85
+ log(`${repo} ${short}: fetch failed (${result.exitCode})`, result.stderr.toString().trim())
86
+ return
87
+ }
88
+ const local = Bun.spawnSync(['git', '-C', dir, 'rev-parse', `origin/${short}`])
89
+ .stdout.toString()
90
+ .trim()
91
+ log(`${repo} ${short}: origin/${short} is ${local.slice(0, 8)}`, local === sha ? '' : '(behind)')
92
+
93
+ // Reported when it CHANGES, not on every event. A collision that is still
94
+ // there is still true, but an agent told the same thing on every unrelated
95
+ // push learns to ignore the channel — and this one is only worth having if
96
+ // it is believed.
97
+ const key = `${repo} ${short}`
98
+ const clash = conflicts(dir, short).join(', ')
99
+ const before = standing.get(key) ?? ''
100
+ if (clash !== before) {
101
+ standing.set(key, clash)
102
+ if (clash) log(`${key}: COLLIDES with your work in ${clash}`)
103
+ else if (before) log(`${key}: no longer collides with your work`)
104
+ }
105
+ }
106
+
107
+ /** The collision each watched ref last reported, so repeats stay quiet. */
108
+ const standing = new Map<string, string>()
109
+
110
+ /**
111
+ * Which files the ref that just moved would collide with, here, right now.
112
+ *
113
+ * This is the whole reason an event beats a timer: not that the fetch happens
114
+ * sooner, but that the agent can be told the thing it actually needs to know —
115
+ * *the branch you are working on just moved underneath you, in these files* —
116
+ * at the moment it becomes true rather than an hour later at push time.
117
+ *
118
+ * `git stash create` is what makes that possible. `merge-tree` compares
119
+ * COMMITS, so an agent mid-task — edits in the working tree, nothing committed
120
+ * — is invisible to it, which is precisely the case worth warning about.
121
+ * `stash create` writes a throwaway commit of the working tree and index
122
+ * without touching the working tree, the refs or the stash list, and merging
123
+ * THAT reports what the agent is really holding. The commit is unreferenced and
124
+ * is collected on its own.
125
+ *
126
+ * Verified against git 2.50.1:
127
+ *
128
+ * exit 0 clean — including a clone that is merely behind, where the merge
129
+ * is a fast-forward and there is nothing to collide with
130
+ * exit 1 conflict; stdout is the tree oid, then one path per line
131
+ * exit 128 git could not answer (unrelated histories, and similar)
132
+ *
133
+ * The last case is reported as nothing at all rather than as a conflict: an
134
+ * agent sent to reconcile a collision that does not exist has been given work,
135
+ * not information.
136
+ */
137
+ function conflicts(dir: string, short: string): string[] {
138
+ // Empty when the tree is clean, and `HEAD` is then the honest comparison.
139
+ const wip = Bun.spawnSync(['git', '-C', dir, 'stash', 'create']).stdout.toString().trim()
140
+ const merge = Bun.spawnSync([
141
+ 'git',
142
+ '-C',
143
+ dir,
144
+ 'merge-tree',
145
+ '--write-tree',
146
+ '--name-only',
147
+ wip || 'HEAD',
148
+ `origin/${short}`,
149
+ ])
150
+ if (merge.exitCode !== 1) return []
151
+ // Line one is the tree the merge produced; the paths follow, then a blank
152
+ // line and git's own prose, which is for people rather than for this.
153
+ const [, ...rest] = merge.stdout.toString().split('\n')
154
+ const paths: string[] = []
155
+ for (const line of rest) {
156
+ if (line.trim() === '') break
157
+ paths.push(line.trim())
158
+ }
159
+ return paths
160
+ }
161
+
162
+ let attempt = 0
163
+
164
+ function connect(): void {
165
+ const ws = new WebSocket(
166
+ `wss://${host}/_walgit/events`,
167
+ token ? { headers: { authorization: `Bearer ${token}` } } : undefined,
168
+ )
169
+
170
+ ws.onopen = () => {
171
+ attempt = 0
172
+ ws.send(JSON.stringify({ watch: [...targets.keys()].map((repo) => ({ repo, refs })) }))
173
+ }
174
+
175
+ ws.onmessage = (event) => {
176
+ const message = JSON.parse(String(event.data))
177
+ // A refusal names what it refused — an unknown repository, a watch list
178
+ // over the cap — and is worth reading rather than retrying blindly.
179
+ if (message.error) return log('refused:', message.error)
180
+ if (message.ok) {
181
+ // The handshake: current state for everything watched, before any event
182
+ // can fire. Fetching it here is what makes a freshly started watcher
183
+ // correct rather than merely subscribed.
184
+ log(`watching ${targets.size} repo(s); catching up`)
185
+ for (const state of message.refs) fetchRef(state.repo, state.ref, state.sha)
186
+ return
187
+ }
188
+ fetchRef(message.repo, message.ref, message.sha)
189
+ }
190
+
191
+ // Reconnect with a backoff, and nothing else: whatever moved while the socket
192
+ // was down is in the next handshake, so there is nothing to replay and
193
+ // nothing to remember.
194
+ ws.onclose = (event) => {
195
+ const wait = Math.min(30_000, 500 * 2 ** attempt)
196
+ attempt += 1
197
+ log(`disconnected (${event.code}); reconnecting in ${wait}ms`)
198
+ setTimeout(connect, wait)
199
+ }
200
+
201
+ ws.onerror = () => {
202
+ // Reported, not acted on: a close always follows, and reconnecting from
203
+ // both would open two sockets.
204
+ log('socket error')
205
+ }
206
+ }
207
+
208
+ log(`${host}: watching ${[...targets.keys()].join(', ')} for ${refs.join(', ')}`)
209
+ connect()