This repository has no description
1---
2title: Tangled docs
3author: The Tangled Contributors
4date: 21 Sun, Dec 2025
5abstract: |
6 Tangled is a decentralized code hosting and collaboration
7 platform. Every component of Tangled is open-source and
8 self-hostable. [tangled.org](https://tangled.org) also
9 provides hosting and CI services that are free to use.
10
11 There are several models for decentralized code
12 collaboration platforms, ranging from ActivityPub’s
13 (Forgejo) federated model, to Radicle’s entirely P2P model.
14 Our approach attempts to be the best of both worlds by
15 adopting the AT Protocol—a protocol for building decentralized
16 social applications with a central identity
17
18 Our approach to this is the idea of “knots”. Knots are
19 lightweight, headless servers that enable users to host Git
20 repositories with ease. Knots are designed for either single
21 or multi-tenant use which is perfect for self-hosting on a
22 Raspberry Pi at home, or larger “community” servers. By
23 default, Tangled provides managed knots where you can host
24 your repositories for free.
25
26 The appview at tangled.org acts as a consolidated "view"
27 into the whole network, allowing users to access, clone and
28 contribute to repositories hosted across different knots
29 seamlessly.
30---
31
32# Quick start guide
33
34## Login or sign up
35
36You can [login](https://tangled.org) by using your AT Protocol
37account. If you are unclear on what that means, simply head
38to the [signup](https://tangled.org/signup) page and create
39an account. By doing so, you will be choosing Tangled as
40your account provider (you will be granted a handle of the
41form `user.tngl.sh`).
42
43In the AT Protocol network, users are free to choose their account
44provider (known as a "Personal Data Service", or PDS), and
45login to applications that support AT accounts.
46
47You can think of it as "one account for all of the atmosphere"!
48
49If you already have an AT account (you may have one if you
50signed up to Bluesky, for example), you can login with the
51same handle on Tangled (so just use `user.bsky.social` on
52the login page).
53
54## Add an SSH key
55
56Once you are logged in, you can start creating repositories
57and pushing code. Tangled supports pushing git repositories
58over SSH.
59
60First, you'll need to generate an SSH key if you don't
61already have one:
62
63```bash
64ssh-keygen -t ed25519 -C "foo@bar.com"
65```
66
67When prompted, save the key to the default location
68(`~/.ssh/id_ed25519`) and optionally set a passphrase.
69
70Copy your public key to your clipboard:
71
72```bash
73# on X11
74cat ~/.ssh/id_ed25519.pub | xclip -sel c
75
76# on wayland
77cat ~/.ssh/id_ed25519.pub | wl-copy
78
79# on macos
80cat ~/.ssh/id_ed25519.pub | pbcopy
81```
82
83Now, navigate to 'Settings' -> 'Keys' and hit 'Add Key',
84paste your public key, give it a descriptive name, and hit
85save.
86
87## Create a repository
88
89Once your SSH key is added, create your first repository:
90
911. Hit the green `+` icon on the topbar, and select
92 repository
932. Enter a repository name
943. Add a description
954. Choose a knotserver to host this repository on
965. Hit create
97
98Knots are self-hostable, lightweight Git servers that can
99host your repository. Unlike traditional code forges, your
100code can live on any server. Read the [Knots](TODO) section
101for more.
102
103## Configure SSH
104
105To ensure Git uses the correct SSH key and connects smoothly
106to Tangled, add this configuration to your `~/.ssh/config`
107file:
108
109```
110Host tangled.org
111 Hostname tangled.org
112 User git
113 IdentityFile ~/.ssh/id_ed25519
114 AddressFamily inet
115```
116
117This tells SSH to use your specific key when connecting to
118Tangled and prevents authentication issues if you have
119multiple SSH keys.
120
121Note that this configuration only works for knotservers that
122are hosted by tangled.org. If you use a custom knot, refer
123to the [Knots](TODO) section.
124
125## Push your first repository
126
127Initialize a new Git repository:
128
129```bash
130mkdir my-project
131cd my-project
132
133git init
134echo "# My Project" > README.md
135```
136
137Add some content and push!
138
139```bash
140git add README.md
141git commit -m "Initial commit"
142git remote add origin git@tangled.org:user.tngl.sh/my-project
143git push -u origin main
144```
145
146That's it! Your code is now hosted on Tangled.
147
148## Migrating an existing repository
149
150Moving your repositories from GitHub, GitLab, Bitbucket, or
151any other Git forge to Tangled is straightforward. You'll
152simply change your repository's remote URL. At the moment,
153Tangled does not have any tooling to migrate data such as
154GitHub issues or pull requests.
155
156First, create a new repository on tangled.org as described
157in the [Quick Start Guide](#create-a-repository).
158
159Navigate to your existing local repository:
160
161```bash
162cd /path/to/your/existing/repo
163```
164
165You can inspect your existing Git remote like so:
166
167```bash
168git remote -v
169```
170
171You'll see something like:
172
173```bash
174origin git@github.com:username/my-project.git (fetch)
175origin git@github.com:username/my-project.git (push)
176```
177
178Update the remote URL to point to tangled:
179
180```bash
181git remote set-url origin git@tangled.org:user.tngl.sh/my-project
182```
183
184Verify the change:
185
186```bash
187git remote -v
188```
189
190You should now see:
191
192```bash
193origin git@tangled.org:user.tngl.sh/my-project (fetch)
194origin git@tangled.org:user.tngl.sh/my-project (push)
195```
196
197Push all your branches and tags to Tangled:
198
199```bash
200git push -u origin --all
201git push -u origin --tags
202```
203
204Your repository is now migrated to Tangled! All commit
205history, branches, and tags have been preserved.
206
207## Mirroring a repository to Tangled
208
209If you want to maintain your repository on multiple forges
210simultaneously, for example, keeping your primary repository
211on GitHub while mirroring to Tangled for backup or
212redundancy, you can do so by adding [multiple remotes](https://git-scm.com/docs/git-push#_remotes).
213
214You can configure your local repository to push to both
215Tangled and, say, GitHub. You may already have the following
216setup:
217
218```bash
219$ git remote -v
220origin git@github.com:username/my-project.git (fetch)
221origin git@github.com:username/my-project.git (push)
222```
223
224Now add Tangled as an additional push URL to the same
225remote:
226
227```bash
228git remote set-url --add --push origin git@tangled.org:user.tngl.sh/my-project
229```
230
231You also need to re-add the original URL as a push
232destination (Git will now use the original URL to fetch only):
233
234```bash
235git remote set-url --add --push origin git@github.com:username/my-project.git
236```
237
238Verify your configuration:
239
240```bash
241$ git remote -v
242origin git@github.com:username/my-project.git (fetch)
243origin git@tangled.org:user.tngl.sh/my-project (push)
244origin git@github.com:username/my-project.git (push)
245```
246
247Notice that there's one fetch URL (the primary remote) and
248two push URLs. Now, whenever you push, Git will
249automatically push to both remotes:
250
251```bash
252git push origin main
253```
254
255This single command pushes your `main` branch to both GitHub
256and Tangled simultaneously.
257
258To push all branches and tags:
259
260```bash
261git push origin --all
262git push origin --tags
263```
264
265If you prefer more control over which remote you push to,
266you can maintain separate remotes:
267
268```bash
269git remote add github git@github.com:username/my-project.git
270git remote add tangled git@tangled.org:user.tngl.sh/my-project
271```
272
273Then push to each explicitly:
274
275```bash
276git push github main
277git push tangled main
278```
279
280# Hosting websites on Tangled
281
282You can serve static websites directly from your git repositories on
283Tangled. If you've used GitHub Pages or Codeberg Pages, this should feel
284familiar.
285
286## Overview
287
288Every user gets a sites domain. If you signed up through Tangled's own
289PDS (`tngl.sh`), your sites domain is automatically
290`<your-handle>.tngl.sh` no setup needed. Otherwise, you can claim a
291`<subdomain>.tngl.io` domain from your settings.
292
293You can serve multiple sites per domain:
294
295- One **index site** served at the root of your domain (e.g.
296 `alice.tngl.sh`)
297- Any number of **sub-path sites** served under the repository name
298 (e.g. `alice.tngl.sh/my-project`)
299
300## Claiming a domain
301
302If you don't have a `tngl.sh` handle, you need to claim a domain before
303publishing sites:
304
3051. Go to **Settings → Sites**
3062. Enter a subdomain (e.g. `alice` to claim `alice.tngl.io`)
3073. Click **claim**
308
309You can only hold one domain at a time. Releasing a domain puts it in a
31030-day cooldown before anyone else can claim it.
311
312## Configuring a site for a repository
313
3141. Navigate to your repository
3152. Go to **Settings → Sites**
3163. Choose a **branch** to deploy from
3174. Set the **deploy directory** — the path within the repository
318 containing your `index.html`. Use `/` for the root, or a subdirectory
319 like `/docs` or `/public`
3205. Choose the **site type**:
321 - **Index site** — served at the root of your domain (e.g.
322 `alice.tngl.sh`)
323 - **Sub-path site** — served under the repository name (e.g.
324 `alice.tngl.sh/my-project`)
3256. Click **save**
326
327The site will be deployed automatically. You can see the status of your
328previous deploys in the **Recent Deploys** section at the bottom of the
329page.
330
331Sites are redeployed automatically on every push to the configured
332branch.
333
334## Custom domains
335
336Tangled currently doesn't support custom domains for sites. This will be
337added in a future update.
338
339## Deploy directory
340
341The deploy directory is the path within your repository that Tangled
342serves as the site root. It must contain an `index.html`.
343
344| Deploy directory | Result |
345|---|---|
346| `/` | Serves the repository root |
347| `/docs` | Serves the `docs/` subdirectory |
348| `/public` | Serves the `public/` subdirectory |
349
350Directories are served with automatic `index.html` resolution -- a
351request to `/about` will serve `/about/index.html` if it exists.
352
353## Site types
354
355| Type | URL |
356|---|---|
357| Index site | `alice.tngl.sh` |
358| Sub-path site | `alice.tngl.sh/my-project` |
359
360Only one repository can be the index site for a given domain at a time.
361If another repository already holds the index site, you will see a
362notice in the settings and only the sub-path option will be available.
363
364## Deploy triggers
365
366A deployment is triggered automatically when:
367
368- You push to the configured branch
369- You change the site configuration (branch, deploy directory, or site
370 type)
371
372## Disabling a site
373
374To stop serving a site, go to **Settings → Sites** in your repository
375and click **Disable**. This removes the site configuration and stops
376serving the site. The deployed files are also deleted from storage.
377
378Releasing your domain from **Settings → Sites** at the account level
379will disable all sites associated with it and delete their files.
380
381
382# Knot self-hosting guide
383
384So you want to run your own knot server? Great! Here are a few prerequisites:
385
3861. A server of some kind (a VPS, a Raspberry Pi, etc.). Preferably running a Linux distribution of some kind.
3872. A (sub)domain name. People generally use `knot.example.com`.
3883. A valid SSL certificate for your domain.
389
390## NixOS
391
392Refer to the [knot
393module](https://tangled.org/tangled.org/core/blob/master/nix/modules/knot.nix)
394for a full list of options. Sample configurations:
395
396- [The test VM](https://tangled.org/tangled.org/core/blob/master/nix/vm.nix#L85)
397- [@pyrox.dev/nix](https://tangled.org/pyrox.dev/nix/blob/c2b644c214d278af12523618de952ee2eab1af3d/hosts/marvin/services/tangled.nix#L15-26)
398
399## Docker
400
401Refer to
402[@tangled.org/knot-docker](https://tangled.org/@tangled.org/knot-docker).
403Note that this is community maintained.
404
405## Manual setup
406
407First, clone this repository:
408
409```
410git clone https://tangled.org/@tangled.org/core
411```
412
413Then, build the `knot` CLI. This is the knot administration
414and operation tool. For the purpose of this guide, we're
415only concerned with these subcommands:
416
417- `knot server`: the main knot server process, typically
418 run as a supervised service
419- `knot guard`: handles role-based access control for git
420 over SSH (you'll never have to run this yourself)
421- `knot keys`: fetches SSH keys associated with your knot;
422 we'll use this to generate the SSH
423 `AuthorizedKeysCommand`
424
425```
426cd core
427export CGO_ENABLED=1
428go build -o knot ./cmd/knot
429```
430
431Next, move the `knot` binary to a location owned by `root` --
432`/usr/local/bin/` is a good choice. Make sure the binary itself is also owned by `root`:
433
434```
435sudo mv knot /usr/local/bin/knot
436sudo chown root:root /usr/local/bin/knot
437```
438
439This is necessary because SSH `AuthorizedKeysCommand` requires [really
440specific permissions](https://stackoverflow.com/a/27638306). The
441`AuthorizedKeysCommand` specifies a command that is run by `sshd` to
442retrieve a user's public SSH keys dynamically for authentication. Let's
443set that up.
444
445```
446sudo tee /etc/ssh/sshd_config.d/authorized_keys_command.conf <<EOF
447Match User git
448 AuthorizedKeysCommand /usr/local/bin/knot keys -o authorized-keys
449 AuthorizedKeysCommandUser nobody
450EOF
451```
452
453Then, reload `sshd`:
454
455```
456sudo systemctl reload ssh
457```
458
459Next, create the `git` user. We'll use the `git` user's home directory
460to store repositories:
461
462```
463sudo adduser git
464```
465
466Create `/home/git/.knot.env` with the following, updating the values as
467necessary. The `KNOT_SERVER_OWNER` should be set to your
468DID, you can find your DID in the [Settings](https://tangled.sh/settings) page.
469
470```
471KNOT_REPO_SCAN_PATH=/home/git
472KNOT_SERVER_HOSTNAME=knot.example.com
473APPVIEW_ENDPOINT=https://tangled.org
474KNOT_SERVER_OWNER=did:plc:foobar
475KNOT_SERVER_INTERNAL_LISTEN_ADDR=127.0.0.1:5444
476KNOT_SERVER_LISTEN_ADDR=127.0.0.1:5555
477```
478
479If you run a Linux distribution that uses systemd, you can
480use the provided service file to run the server. Copy
481[`knotserver.service`](https://tangled.org/tangled.org/core/blob/master/systemd/knotserver.service)
482to `/etc/systemd/system/`. Then, run:
483
484```
485systemctl enable knotserver
486systemctl start knotserver
487```
488
489The last step is to configure a reverse proxy like Nginx or Caddy to front your
490knot. Here's an example configuration for Nginx:
491
492```
493server {
494 listen 80;
495 listen [::]:80;
496 server_name knot.example.com;
497
498 location / {
499 proxy_pass http://localhost:5555;
500 proxy_set_header Host $host;
501 proxy_set_header X-Real-IP $remote_addr;
502 proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
503 proxy_set_header X-Forwarded-Proto $scheme;
504 }
505
506 # wss endpoint for git events
507 location /events {
508 proxy_set_header X-Forwarded-For $remote_addr;
509 proxy_set_header Host $http_host;
510 proxy_set_header Upgrade websocket;
511 proxy_set_header Connection Upgrade;
512 proxy_pass http://localhost:5555;
513 }
514 # additional config for SSL/TLS go here.
515}
516
517```
518
519Remember to use Let's Encrypt or similar to procure a certificate for your
520knot domain.
521
522You should now have a running knot server! You can finalize
523your registration by hitting the `verify` button on the
524[/settings/knots](https://tangled.org/settings/knots) page. This simply creates
525a record on your PDS to announce the existence of the knot.
526
527### Custom paths
528
529(This section applies to manual setup only. Docker users should edit the mounts
530in `docker-compose.yml` instead.)
531
532Right now, the database and repositories of your knot lives in `/home/git`. You
533can move these paths if you'd like to store them in another folder. Be careful
534when adjusting these paths:
535
536- Stop your knot when moving data (e.g. `systemctl stop knotserver`) to prevent
537 any possible side effects. Remember to restart it once you're done.
538- Make backups before moving in case something goes wrong.
539- Make sure the `git` user can read and write from the new paths.
540
541#### Database
542
543As an example, let's say the current database is at `/home/git/knotserver.db`,
544and we want to move it to `/home/git/database/knotserver.db`.
545
546Copy the current database to the new location. Make sure to copy the `.db-shm`
547and `.db-wal` files if they exist.
548
549```
550mkdir /home/git/database
551cp /home/git/knotserver.db* /home/git/database
552```
553
554In the environment (e.g. `/home/git/.knot.env`), set `KNOT_SERVER_DB_PATH` to
555the new file path (_not_ the directory):
556
557```
558KNOT_SERVER_DB_PATH=/home/git/database/knotserver.db
559```
560
561#### Repositories
562
563As an example, let's say the repositories are currently in `/home/git`, and we
564want to move them into `/home/git/repositories`.
565
566Create the new folder, then move the existing repositories (if there are any):
567
568```
569mkdir /home/git/repositories
570# move all DIDs into the new folder; these will vary for you!
571mv /home/git/did:plc:wshs7t2adsemcrrd4snkeqli /home/git/repositories
572```
573
574In the environment (e.g. `/home/git/.knot.env`), update `KNOT_REPO_SCAN_PATH`
575to the new directory:
576
577```
578KNOT_REPO_SCAN_PATH=/home/git/repositories
579```
580
581Similarly, update your `sshd` `AuthorizedKeysCommand` to use the updated
582repository path:
583
584```
585sudo tee /etc/ssh/sshd_config.d/authorized_keys_command.conf <<EOF
586Match User git
587 AuthorizedKeysCommand /usr/local/bin/knot keys -o authorized-keys -git-dir /home/git/repositories
588 AuthorizedKeysCommandUser nobody
589EOF
590```
591
592Make sure to restart your SSH server!
593
594#### MOTD (message of the day)
595
596To configure the MOTD used ("Welcome to this knot!" by default), edit the
597`/home/git/motd` file:
598
599```
600printf "Hi from this knot!\n" > /home/git/motd
601```
602
603Note that you should add a newline at the end if setting a non-empty message
604since the knot won't do this for you.
605
606## Secure Mode
607
608Secure Mode isolates each `git` subprocess to the repository it is
609operating on, using two mechanisms:
610
611- **Linux Landlock** restricts the filesystem paths the subprocess
612 can access -- it can only read/write its own repository and the
613 system directories it needs to run.
614- **UID isolation** runs each subprocess as a virtual UID assigned
615 to the repository owner, so that repositories belonging to
616 different owners are isolated from each other at the OS level
617 even if Landlock were somehow bypassed.
618
619Secure Mode requires:
620
621- Linux kernel >= 5.19 (Landlock V2). This is the minimum needed
622 for `git push` to work, because receive-pack's quarantine
623 migration uses cross-directory rename which requires the
624 Landlock `REFER` access right (added in V2). Kernels 5.13-5.18
625 support Landlock V1 and clones will work, but pushes will fail
626 with cross-device link errors. On kernels without any Landlock
627 support (< 5.13), the sandbox call is a no-op: UID isolation
628 still applies but no filesystem restriction is enforced.
629- `CAP_SETUID`, `CAP_SETGID`, and `CAP_CHOWN` available to the
630 knot process. The NixOS module grants these automatically; for
631 manual setups see the `setcap` step below.
632
633### NixOS
634
635Add `server.secureMode = true;` to your knot module configuration:
636
637```nix
638services.tangled.knot = {
639 server.secureMode = true;
640 # ... other options
641};
642```
643
644The NixOS module handles everything else automatically:
645
646- Grants the required capabilities to the knot service via
647 `AmbientCapabilities` in the systemd unit.
648- Installs a capability-bearing wrapper at
649 `/run/wrappers/bin/knot` via `security.wrappers`, so that
650 SSH-invoked git operations (pushes) also run under the correct
651 UID without requiring the service to run as root.
652- Runs `knot migrate-isolation` at service start to chown
653 existing repositories to their virtual UIDs.
654
655### Manual setup
656
657**Step 1.** Grant the required capabilities to the knot binary.
658This allows the knot process to switch to virtual UIDs at runtime
659without running as root. You will need to repeat this step
660whenever the binary is updated.
661
662```
663sudo setcap cap_setuid,cap_setgid,cap_chown+eip /usr/local/bin/knot
664```
665
666**Step 2.** Run the migration tool to assign virtual UIDs to all
667existing repositories and set their filesystem permissions. This
668must be run as root:
669
670```
671sudo knot migrate-isolation \
672 --git-dir /home/git \
673 --db /home/git/knotserver.db \
674 --internal-api 127.0.0.1:5444
675```
676
677You can re-run this at any time with `--force` to reapply
678permissions (e.g. after a manual repair or after updating the
679binary).
680
681**Step 2a.** Ensure the home directory is traversable by
682non-group users. Git subprocesses run as virtual UIDs that are
683not in the git group, and they need to resolve
684`$HOME/.config/git/config` to load the global config:
685
686```
687sudo chmod o+x /home/git
688```
689
690This adds only the execute bit, not read -- the virtual UIDs can
691traverse to known paths but cannot list directory contents.
692
693**Step 3.** Enable Secure Mode in your environment file:
694
695```
696KNOT_SERVER_SECURE_MODE=true
697```
698
699Or pass it as a flag:
700
701```
702knot server --secure-mode
703```
704
705**Step 4.** Regenerate the `AuthorizedKeysCommand` with the
706`-secure-mode` flag. This causes `knot keys` to emit guard
707command lines that include `-secure-mode`, so SSH pushes also
708get UID isolation:
709
710```
711sudo tee /etc/ssh/sshd_config.d/authorized_keys_command.conf <<EOF
712Match User git
713 AuthorizedKeysCommand /usr/local/bin/knot keys \
714 -o authorized-keys -secure-mode
715 AuthorizedKeysCommandUser nobody
716EOF
717```
718
719Reload `sshd` after making this change.
720
721> **Note:** the server will refuse to start in Secure Mode if any
722> repositories have not yet been isolation-migrated. Re-run
723> `migrate-isolation` if you see this error.
724
725## Troubleshooting
726
727If you run your own knot, you may run into some of these
728common issues. You can always join the
729[IRC](https://web.libera.chat/#tangled) or
730[Discord](https://chat.tangled.org/) if this section does
731not help.
732
733### Unable to push
734
735If you are unable to push to your knot or repository:
736
7371. First, ensure that you have added your SSH public key to
738 your account
7392. Check to see that your knot has synced the key by running
740 `knot keys`
7413. Check to see if git is supplying the correct private key
742 when pushing: `GIT_SSH_COMMAND="ssh -v" git push ...`
7434. Check to see if `sshd` on the knot is rejecting the push
744 for some reason: `journalctl -xeu ssh` (or `sshd`,
745 depending on your machine). These logs are unavailable if
746 using docker.
7475. Check to see if the knot itself is rejecting the push,
748 depending on your setup, the logs might be in one of the
749 following paths:
750 - `/tmp/knotguard.log`
751 - `/home/git/log`
752 - `/home/git/guard.log`
753
754# Spindles
755
756## Pipelines
757
758Spindle workflows allow you to write CI/CD pipelines in a
759simple format. They're located in the `.tangled/workflows`
760directory at the root of your repository, and are defined
761using YAML.
762
763A workflow has a set of common fields that apply no matter
764which engine you pick:
765
766- [Trigger](#trigger): A **required** field that defines
767 when a workflow should be triggered.
768- [Engine](#engine): A **required** field that defines which
769 engine a workflow should run on.
770- [Clone options](#clone-options): An **optional** field
771 that defines how the repository should be cloned.
772- [Environment](#environment): An **optional** field that
773 allows you to define environment variables.
774- [Steps](#steps): An **optional** field that allows you to
775 define what steps should run in the workflow.
776
777On top of these, each engine has its own options for things
778like dependencies and images. See [Engines](#engines) for
779the per-engine fields.
780
781### Trigger
782
783The first thing to add to a workflow is the trigger, which
784defines when a workflow runs. This is defined using a `when`
785field, which takes in a list of conditions. Each condition
786has the following fields:
787
788- `event`: This is a **required** field that defines when
789 your workflow should run. It's a list that can take one or
790 more of the following values:
791 - `push`: The workflow should run every time a commit is
792 pushed to the repository.
793 - `pull_request`: The workflow should run every time a
794 pull request is made or updated.
795 - `manual`: The workflow can be triggered manually.
796- `branch`: Defines which branches the workflow should run
797 for. If used with the `push` event, commits to the
798 branch(es) listed here will trigger the workflow. If used
799 with the `pull_request` event, updates to pull requests
800 targeting the branch(es) listed here will trigger the
801 workflow. This field has no effect with the `manual`
802 event. Supports glob patterns using `*` and `**` (e.g.,
803 `main`, `develop`, `release-*`). Either `branch` or `tag`
804 (or both) must be specified for `push` events.
805- `tag`: Defines which tags the workflow should run for.
806 Only used with the `push` event - when tags matching the
807 pattern(s) listed here are pushed, the workflow will
808 trigger. This field has no effect with `pull_request` or
809 `manual` events. Supports glob patterns using `*` and `**`
810 (e.g., `v*`, `v1.*`, `release-**`). Either `branch` or
811 `tag` (or both) must be specified for `push` events.
812
813For example, if you'd like to define a workflow that runs
814when commits are pushed to the `main` and `develop`
815branches, or when pull requests that target the `main`
816branch are updated, or manually, you can do so with:
817
818```yaml
819when:
820 - event: ["push", "manual"]
821 branch: ["main", "develop"]
822 - event: ["pull_request"]
823 branch: ["main"]
824```
825
826You can also trigger workflows on tag pushes. For instance,
827to run a deployment workflow when tags matching `v*` are
828pushed:
829
830```yaml
831when:
832 - event: ["push"]
833 tag: ["v*"]
834```
835
836You can even combine branch and tag patterns in a single
837constraint (the workflow triggers if either matches):
838
839```yaml
840when:
841 - event: ["push"]
842 branch: ["main", "release-*"]
843 tag: ["v*", "stable"]
844```
845
846To skip CI for a push, pass a Git push option:
847
848```sh
849git push -o skip-ci
850```
851
852`ci-skip` is also accepted.
853
854### Engine
855
856Next is the engine on which the workflow should run, defined
857using the **required** `engine` field. The currently
858supported engines are:
859
860- `nixery`: This uses an instance of
861 [Nixery](https://nixery.dev) to run steps, which allows
862 you to add [dependencies](#dependencies) from
863 Nixpkgs (https://github.com/NixOS/nixpkgs). You can
864 search for packages on https://search.nixos.org, and
865 there's a pretty good chance the package(s) you're looking
866 for will be there.
867 See [Nixery engine](#nixery-engine).
868- `microvm`: Runs the whole workflow inside its own
869 microVM. Has configuration features for NixOS images
870 that will let you enable services, do Docker-in-VM, etc.
871 See [microVM engine](#microvm-engine).
872
873Example:
874
875```yaml
876engine: "nixery"
877```
878
879Each engine also adds its own workflow fields (dependencies,
880images, services, and so on). These are documented under
881[Engines](#engines).
882
883### Clone options
884
885When a workflow starts, the first step is to clone the
886repository. You can customize this behavior using the
887**optional** `clone` field. It has the following fields:
888
889- `skip`: Setting this to `true` will skip cloning the
890 repository. This can be useful if your workflow is doing
891 something that doesn't require anything from the
892 repository itself. This is `false` by default.
893- `depth`: This sets the number of commits, or the "clone
894 depth", to fetch from the repository. For example, if you
895 set this to 2, the last 2 commits will be fetched. By
896 default, the depth is set to 1, meaning only the most
897 recent commit will be fetched, which is the commit that
898 triggered the workflow.
899- `submodules`: If you use Git submodules
900 (https://git-scm.com/book/en/v2/Git-Tools-Submodules)
901 in your repository, setting this field to `true` will
902 recursively fetch all submodules. This is `false` by
903 default.
904
905The default settings are:
906
907```yaml
908clone:
909 skip: false
910 depth: 1
911 submodules: false
912```
913
914### Environment
915
916The `environment` field allows you define environment
917variables that will be available throughout the entire
918workflow. **Do not put secrets here, these environment
919variables are visible to anyone viewing the repository. You
920can add secrets for pipelines in your repository's
921settings.**
922
923Example:
924
925```yaml
926environment:
927 GOOS: "linux"
928 GOARCH: "arm64"
929 NODE_ENV: "production"
930 MY_ENV_VAR: "MY_ENV_VALUE"
931```
932
933By default, the following environment variables are set:
934
935- `CI` - Always set to `true` to indicate a CI environment
936- `TANGLED_PIPELINE_ID` - The AT URI of the current pipeline
937- `TANGLED_PIPELINE_KIND` - One of `push`, `pull_request` or
938 `manual`
939- `TANGLED_REPO_KNOT` - The repository's knot hostname
940- `TANGLED_REPO_DID` - The DID of the repository owner
941- `TANGLED_REPO_NAME` - The name of the repository
942- `TANGLED_REPO_DEFAULT_BRANCH` - The default branch of the
943 repository
944- `TANGLED_REPO_URL` - The full URL to the repository
945
946These variables are only available when the pipeline is
947triggered by a push:
948
949- `TANGLED_REF` - The full git reference (e.g.,
950 `refs/heads/main` or `refs/tags/v1.0.0`)
951- `TANGLED_REF_NAME` - The short name of the reference
952 (e.g., `main` or `v1.0.0`)
953- `TANGLED_REF_TYPE` - The type of reference, either
954 `branch` or `tag`
955- `TANGLED_SHA` - The commit SHA that triggered the pipeline
956- `TANGLED_COMMIT_SHA` - Alias for `TANGLED_SHA`
957
958These variables are only available when the pipeline is
959triggered by a pull request:
960
961- `TANGLED_PR_SOURCE_BRANCH` - The source branch of the pull
962 request
963- `TANGLED_PR_TARGET_BRANCH` - The target branch of the pull
964 request
965- `TANGLED_PR_SOURCE_SHA` - The commit SHA of the source
966 branch
967
968### Steps
969
970The `steps` field allows you to define what steps should run
971in the workflow. It's a list of step objects, each with the
972following fields:
973
974- `name`: This field allows you to give your step a name.
975 This name is visible in your workflow runs, and is used to
976 describe what the step is doing.
977- `command`: This field allows you to define a command to
978 run in that step. The step is run in a Bash shell, and the
979 logs from the command will be visible in the pipelines
980 page on the Tangled website. Any dependencies you added in
981 your engine's section (see [Engines](#engines)) will be
982 available to use here.
983- `environment`: Similar to the global
984 [environment](#environment) config, this **optional**
985 field is a key-value map that allows you to set
986 environment variables for the step. **Do not put secrets
987 here, these environment variables are visible to anyone
988 viewing the repository. You can add secrets for pipelines
989 in your repository's settings.**
990
991Example:
992
993```yaml
994steps:
995 - name: "Build backend"
996 command: "go build"
997 environment:
998 GOOS: "darwin"
999 GOARCH: "arm64"
1000 - name: "Build frontend"
1001 command: "npm run build"
1002 environment:
1003 NODE_ENV: "production"
1004```
1005
1006## Engines
1007
1008The common fields above apply to every workflow. Each engine
1009then adds its own fields on top. Pick an engine with the
1010[`engine`](#engine) field and use the matching section below.
1011
1012### Nixery engine
1013
1014#### Dependencies
1015
1016When you're running a workflow you'll usually need additional
1017dependencies. The `dependencies` field lets you define which
1018dependencies to get, and from where. It's a key-value map,
1019with the key being the registry to fetch dependencies from,
1020and the value being the list of dependencies to fetch.
1021
1022The registry URL syntax can be found [on the nix
1023manual](https://nix.dev/manual/nix/2.18/command-ref/new-cli/nix3-registry-add).
1024
1025Say you want to fetch Node.js and Go from `nixpkgs`, and a
1026package called `my_pkg` you've made from your own registry
1027at your repository at
1028`https://tangled.org/@example.com/my_pkg`. You can define
1029those dependencies like so:
1030
1031```yaml
1032dependencies:
1033 # nixpkgs
1034 nixpkgs:
1035 - nodejs
1036 - go
1037 # unstable
1038 nixpkgs/nixpkgs-unstable:
1039 - bun
1040 # custom registry
1041 git+https://tangled.org/@example.com/my_pkg:
1042 - my_pkg
1043```
1044
1045Now these dependencies are available to use in your
1046workflow!
1047
1048#### Complete nixery workflow
1049
1050```yaml
1051# .tangled/workflows/build.yml
1052
1053when:
1054 - event: ["push", "manual"]
1055 branch: ["main", "develop"]
1056 - event: ["pull_request"]
1057 branch: ["main"]
1058
1059engine: "nixery"
1060
1061# using the default values
1062clone:
1063 skip: false
1064 depth: 1
1065 submodules: false
1066
1067dependencies:
1068 # nixpkgs
1069 nixpkgs:
1070 - nodejs
1071 - go
1072 # custom registry
1073 git+https://tangled.org/@example.com/my_pkg:
1074 - my_pkg
1075
1076environment:
1077 GOOS: "linux"
1078 GOARCH: "arm64"
1079 NODE_ENV: "production"
1080 MY_ENV_VAR: "MY_ENV_VALUE"
1081
1082steps:
1083 - name: "Build backend"
1084 command: "go build"
1085 environment:
1086 GOOS: "darwin"
1087 GOARCH: "arm64"
1088 - name: "Build frontend"
1089 command: "npm run build"
1090 environment:
1091 NODE_ENV: "production"
1092```
1093
1094If you want another example of a workflow, you can look at
1095the one [Tangled uses to build the
1096project](https://tangled.org/@tangled.org/core/blob/master/.tangled/workflows/build.yml).
1097
1098### microVM engine
1099
1100#### Image
1101
1102A workflow picks the image to boot with the top-level `image`
1103field:
1104
1105```yaml
1106engine: microvm
1107image: nixos
1108```
1109
1110There are two flavours of images:
1111
1112- **NixOS images** (e.g. `nixos`): the whole guest is built
1113 with Nix, so you can configure it from the workflow file
1114 itself. The `dependencies`, `services`, `virtualisation`,
1115 `registry` and `caches` fields below are all understood
1116 here, and the guest builds and activates that configuration
1117 before any of your steps run.
1118- **Non-NixOS images** (e.g. `alpine`): there's no NixOS to
1119 configure, so the workflow-level config fields above have
1120 no effect. You still get a full machine to run steps in.
1121
1122The available image names depend on what the spindle operator
1123has installed. `nixos` and `alpine` are examples. If `image`
1124is omitted, the spindle's configured default image is used.
1125
1126#### Dependencies
1127
1128On the microVM engine, `dependencies` is a flat list of
1129packages that are made available to every step. This field
1130only applies to **NixOS images**; for other images you can
1131use the package manager included in a step.
1132
1133The guest builds a [`nix develop`](https://nix.dev/manual/nix/2.18/command-ref/new-cli/nix3-develop)-style
1134devshell from your dependencies and uses it for each step,
1135so you can, for example, add `pkg-config` and `openssl` and
1136have the `openssl-sys` crate while compiling a Rust project
1137just work.
1138
1139A bare name like `go` is looked up in nixpkgs. You can also
1140point at any flake with the `flakeref#attr` syntax, so
1141`github:nixos/nixpkgs#hello` pulls `hello` straight out of
1142that flake.
1143
1144```yaml
1145dependencies:
1146 - go
1147 - github:nixos/nixpkgs#hello
1148```
1149
1150#### Registry
1151
1152The `registry` field remaps flake references, the same way
1153`nix registry` does. This lets you pin or alias the flakes
1154used by `dependencies`.
1155
1156For example, pin `nixpkgs` to `nixos-unstable` so that the
1157bare `go` above resolves from unstable, and alias your own
1158flake so you can use `myflake#tool` in `dependencies`:
1159
1160```yaml
1161registry:
1162 nixpkgs: github:nixos/nixpkgs/nixos-unstable
1163 myflake: github:me/x
1164```
1165
1166#### Caches
1167
1168The `caches` field is a map of Nix binary cache URL to its
1169trusted public key. These are fed into the spindle's read
1170proxy, so the guest can substitute prebuilt paths from them
1171instead of building everything from scratch.
1172
1173```yaml
1174caches:
1175 https://nix-community.cachix.org: "nix-community.cachix.org-1:mB9FSh9qf2dCimDSUo8Zy7bkq5CX+/rkCWyvRCYg3Fs="
1176```
1177
1178#### Services and virtualisation
1179
1180The `services` and `virtualisation` fields are passed straight
1181through to NixOS. Anything you could write under
1182`services.*` or `virtualisation.*` in a NixOS configuration,
1183you can write here, and it's brought up before any of your
1184steps run.
1185
1186As a convenience, `true` works as shorthand for
1187`.enable = true` anywhere an `enable` option exists (e.g.
1188`virtualisation.docker: true`).
1189
1190```yaml
1191services:
1192 postgresql:
1193 enable: true
1194 ensureDatabases: ["spindle-workflow"]
1195 ensureUsers:
1196 - name: spindle-workflow
1197 ensureDBOwnership: true
1198
1199virtualisation:
1200 docker: true
1201```
1202
1203#### Recipes
1204
1205##### Lint, test and build a Node project
1206
1207```yaml
1208when:
1209 - event: ["push", "pull_request"]
1210 branch: ["main"]
1211
1212engine: microvm
1213image: nixos
1214
1215dependencies:
1216 - pnpm
1217
1218steps:
1219 - name: "Install dependencies"
1220 command: pnpm install --frozen-lockfile
1221 - name: "Lint and test"
1222 command: |
1223 pnpm run lint
1224 pnpm test
1225 - name: "Build"
1226 command: pnpm run build
1227```
1228
1229##### Check formatting
1230
1231```yaml
1232when:
1233 - event: ["push", "pull_request"]
1234 branch: ["main"]
1235
1236engine: microvm
1237image: alpine # slimmer image for checking the formatting
1238
1239steps:
1240 - name: "Install go"
1241 command: apk add go
1242 - name: "Check formatting"
1243 command: test -z $(gofmt -l .)
1244```
1245
1246##### Build a Rust project that links OpenSSL
1247
1248```yaml
1249when:
1250 - event: ["push", "pull_request"]
1251 branch: ["main"]
1252
1253engine: microvm
1254image: nixos
1255
1256dependencies:
1257 - gcc
1258 - cargo
1259 - rustc
1260 - clippy
1261 - rustfmt
1262 - pkg-config # exports PKG_CONFIG_PATH for the libraries below
1263 - openssl # the C library + headers openssl-sys links against
1264
1265steps:
1266 - name: "Check formatting"
1267 command: cargo fmt --check
1268 - name: "Clippy"
1269 command: cargo clippy --all-targets -- -D warnings
1270 - name: "Test"
1271 command: cargo test --all
1272 - name: "Release build"
1273 command: cargo build --release
1274```
1275
1276##### Run migrations and integration tests against PostgreSQL
1277
1278```yaml
1279when:
1280 - event: ["push", "pull_request"]
1281 branch: ["main"]
1282
1283engine: microvm
1284image: nixos
1285
1286environment:
1287 DATABASE_URL: "postgresql:///spindle-workflow?host=/run/postgresql"
1288
1289dependencies:
1290 - gcc
1291 - cargo
1292 - rustc
1293 - pkg-config
1294 - openssl
1295 - sqlx-cli
1296
1297services:
1298 postgresql:
1299 enable: true
1300 # has to be same name as the user for peer auth to work automatically
1301 ensureDatabases: ["spindle-workflow"]
1302 ensureUsers:
1303 - name: spindle-workflow
1304 ensureDBOwnership: true
1305
1306steps:
1307 - name: "Run migrations"
1308 command: sqlx migrate run
1309 - name: "Integration tests"
1310 command: cargo test --all
1311```
1312
1313##### Build and push a Docker image on tag
1314
1315```yaml
1316when:
1317 - event: ["push"]
1318 tag: ["v*"]
1319
1320engine: microvm
1321image: nixos
1322
1323virtualisation:
1324 docker: true
1325
1326steps:
1327 - name: "Build and push to ghcr.io"
1328 command: |
1329 set -euo pipefail
1330
1331 echo "$REGISTRY_TOKEN" | docker login ghcr.io -u "$REGISTRY_USER" --password-stdin
1332 image="ghcr.io/$REGISTRY_USER/myapp:$TANGLED_REF_NAME"
1333
1334 docker build -t "$image" -t "ghcr.io/$REGISTRY_USER/myapp:latest" .
1335 docker push "$image"
1336 docker push "ghcr.io/$REGISTRY_USER/myapp:latest"
1337```
1338
1339##### Deploy to Cloudflare Workers on tag
1340
1341```yaml
1342# .tangled/workflows/deploy.yml
1343when:
1344 - event: ["push"]
1345 tag: ["v*"]
1346
1347engine: microvm
1348image: nixos
1349
1350dependencies:
1351 - pnpm
1352
1353steps:
1354 - name: "Install dependencies"
1355 command: pnpm install --frozen-lockfile
1356 - name: "Deploy worker"
1357 # `wrangler` picks up `CLOUDFLARE_API_TOKEN` from the env.
1358 # set it under **Settings → Secrets**.
1359 command: pnpm exec wrangler deploy
1360```
1361
1362##### Publish a release artifact
1363
1364```yaml
1365when:
1366 - event: ["push"]
1367 tag: ["v*"] # trigger on versions
1368
1369engine: microvm
1370image: nixos
1371
1372dependencies:
1373 - go
1374
1375steps:
1376 - name: "Build release binary"
1377 command: |
1378 mkdir -p dist
1379 CGO_ENABLED=0 go build -trimpath -ldflags "-s -w" -o dist/myapp ./cmd/myapp
1380
1381 - name: "Publish artifact record"
1382 command: |
1383 set -euo pipefail
1384 # change this if you're not on `tngl.sh`
1385 PDS="https://tngl.sh"
1386 # also update this to your handle or did
1387 ATP_IDENTIFIER="user.tngl.sh"
1388 ARTIFACT_PATH="dist/myapp"
1389 ARTIFACT_NAME="myapp"
1390
1391 # set `ATP_APP_PASSWORD` under **Settings → Secrets**
1392 session=$(curl -fsS -X POST "$PDS/xrpc/com.atproto.server.createSession" \
1393 -H "Content-Type: application/json" \
1394 -d "{\"identifier\":\"$ATP_IDENTIFIER\",\"password\":\"$ATP_APP_PASSWORD\"}")
1395 jwt=$(echo "$session" | jq -r .accessJwt)
1396 did=$(echo "$session" | jq -r .did)
1397
1398 # upload the binary as a blob
1399 blob=$(curl -fsS -X POST "$PDS/xrpc/com.atproto.repo.uploadBlob" \
1400 -H "Authorization: Bearer $jwt" \
1401 -H "Content-Type: application/octet-stream" \
1402 --data-binary @"$ARTIFACT_PATH")
1403
1404 # note that this requires an annotated tag (`git tag -a v1.0.0 -m ...`)
1405 tag_hash=$(git rev-parse "$TANGLED_REF_NAME^{tag}")
1406 tag_bytes=$(printf '%s' "$tag_hash" | xxd -r -p | base64 | tr -d '=')
1407
1408 # the sh.tangled.repo.artifact record for your artifact
1409 record=$(jq -n \
1410 --arg did "$did" \
1411 --arg tag "$tag_bytes" \
1412 --arg name "$ARTIFACT_NAME" \
1413 --arg repo "$TANGLED_REPO_URL" \
1414 --arg created "$(date -Iseconds)" \
1415 --argjson blob "$(echo "$blob" | jq .blob)" '{
1416 repo: $did,
1417 collection: "sh.tangled.repo.artifact",
1418 validate: false,
1419 record: {
1420 "$type": "sh.tangled.repo.artifact",
1421 tag: {"$bytes": $tag},
1422 name: $name,
1423 repo: $repo,
1424 artifact: $blob,
1425 createdAt: $created
1426 }
1427 }')
1428
1429 # create the record on the PDS
1430 curl -fsS -X POST "$PDS/xrpc/com.atproto.repo.createRecord" \
1431 -H "Authorization: Bearer $jwt" \
1432 -H "Content-Type: application/json" \
1433 -d "$record"
1434```
1435
1436## Self-hosting guide
1437
1438### Prerequisites
1439
1440- Go
1441- For the **nixery** engine: Docker (or Podman with Docker
1442 compatibility enabled).
1443- For the **microVM** engine: a Linux host with KVM, plus the
1444 microVM host dependencies described in [Running microVM
1445 workflows](#running-microvm-workflows).
1446
1447### Configuration
1448
1449Spindle is configured using environment variables. The following environment variables are available:
1450
1451- `SPINDLE_SERVER_LISTEN_ADDR`: The address the server listens on (default: `"0.0.0.0:6555"`).
1452- `SPINDLE_SERVER_DB_PATH`: The path to the SQLite database file (default: `"spindle.db"`).
1453- `SPINDLE_SERVER_HOSTNAME`: The hostname of the server (required).
1454- `SPINDLE_SERVER_ADMIN_PASSWORD`: The password for the `/admin` endpoints used by `spindle admin allow|block` to manage members. When unset, the `/admin` endpoints are not mounted at all (default: `""`).
1455- `SPINDLE_SERVER_JETSTREAM_ENDPOINT`: The endpoint of the Jetstream server (default: `"wss://jetstream1.us-west.bsky.network/subscribe"`).
1456- `SPINDLE_SERVER_DEV`: A boolean indicating whether the server is running in development mode (default: `false`).
1457- `SPINDLE_SERVER_INVITE_ONLY`: A boolean indicating whether only members of this spindle may register repos. When `false`, the spindle accepts repos from anyone on the network (default: `true`).
1458- `SPINDLE_SERVER_LOG_DIR`: The directory to store workflow logs (default: `"/var/log/spindle"`).
1459- `SPINDLE_SERVER_DOCKER_SOCKET`: Path to Docker socket to expose to invoked Spindle containers (default: `""`).
1460- `SPINDLE_NIXERY_PIPELINES_NIXERY`: The Nixery URL (default: `"nixery.tangled.sh"`).
1461- `SPINDLE_NIXERY_PIPELINES_WORKFLOW_TIMEOUT`: The default workflow timeout (default: `"5m"`).
1462
1463For the microVM engine, the following are also available
1464(prefix `SPINDLE_MICROVM_PIPELINES_`):
1465
1466- `SPINDLE_MICROVM_PIPELINES_IMAGE_DIR`: Directory containing
1467 microVM images (**required** to use the engine). See
1468 [Running microVM workflows](#running-microvm-workflows).
1469- `SPINDLE_MICROVM_PIPELINES_DEFAULT_IMAGE`: Image used when a
1470 workflow doesn't set `image` (default: `"nixos-x86_64"`).
1471- `SPINDLE_MICROVM_PIPELINES_OVERLAY_DIR`: Where per-workflow
1472 temporary disks are created (default: the system temp dir).
1473- `SPINDLE_MICROVM_PIPELINES_ENABLE_KVM`: Use KVM hardware
1474 acceleration (default: `true`). Without KVM, guests fall
1475 back to slow software emulation.
1476- `SPINDLE_MICROVM_PIPELINES_WORKFLOW_TIMEOUT`: Default
1477 workflow timeout (default: `"5m"`).
1478
1479Optional resource limits (a value of `0` disables that
1480limit). The limits cap usage across all running microVM
1481workflows:
1482
1483- `SPINDLE_MICROVM_PIPELINES_MAX_TOTAL_MEMORY_MIB`
1484- `SPINDLE_MICROVM_PIPELINES_MAX_TOTAL_VCPUS`
1485- `SPINDLE_MICROVM_PIPELINES_MAX_TOTAL_DISK_MIB`
1486
1487Optional cgroup enforcement:
1488
1489- `SPINDLE_MICROVM_PIPELINES_ENABLE_CGROUPS`: Place each
1490 workflow's QEMU and slirp4netns in a per-workflow cgroup=
1491 (default: `false`).
1492- `SPINDLE_MICROVM_PIPELINES_CGROUP_PARENT`: Parent cgroup;
1493 `self` resolves the spindle service's own cgroup (default:
1494 `"self"`).
1495- `SPINDLE_MICROVM_PIPELINES_CGROUP_PIDS_MAX`: Max processes
1496 per workflow cgroup (default: `4096`).
1497- `SPINDLE_MICROVM_PIPELINES_CGROUP_SWAP_MAX_MIB`: Max swap
1498 per workflow cgroup (default: `0`, no swap).
1499- `SPINDLE_MICROVM_PIPELINES_CGROUP_SUPERVISOR_MEMORY_MIN_MIB`:
1500 Memory protected for spindle itself so it isn't OOM-killed
1501 before the workflows (default: `512`).
1502
1503To push paths built inside microVMs back to a shared Nix
1504cache (and read from it), configure the cache (prefix
1505`SPINDLE_NIX_CACHE_`):
1506
1507- `SPINDLE_NIX_CACHE_READ_URLS`: Comma-separated binary cache
1508 URLs the guest reads from.
1509- `SPINDLE_NIX_CACHE_TRUSTED_PUBLIC_KEYS`: Comma-separated
1510 trusted public keys for those caches.
1511- `SPINDLE_NIX_CACHE_UPLOAD_URL`: Cache URL that paths built
1512 in the guest are uploaded to.
1513
1514### Running spindle
1515
15161. **Set the environment variables.** For example:
1517
1518 ```shell
1519 export SPINDLE_SERVER_HOSTNAME="your-hostname"
1520 ```
1521
15222. **Build the Spindle binary.**
1523
1524 ```shell
1525 cd core
1526 go mod download
1527 go build -o cmd/spindle/spindle cmd/spindle/main.go
1528 ```
1529
15303. **Create the log directory.**
1531
1532 ```shell
1533 sudo mkdir -p /var/log/spindle
1534 sudo chown $USER:$USER -R /var/log/spindle
1535 ```
1536
15374. **Run the Spindle binary.**
1538
1539 ```shell
1540 ./cmd/spindle/spindle
1541 ```
1542
1543Spindle will now start, connect to the Jetstream server, and begin processing pipelines.
1544
1545Spindles are not registered with the appview. To point a repository at
1546yours, type its hostname into the spindle field under the repository's
1547pipeline settings (or when creating or forking a repo); recently used
1548spindles are offered as suggestions. The spindle picks the repo up from
1549the network and runs its pipelines if its owner is a member.
1550
1551### Managing members
1552
1553An invite-only spindle (the default, see `SPINDLE_SERVER_INVITE_ONLY`) only
1554accepts repos whose owner is a member. Members are managed over the `/admin`
1555endpoints, which authenticate with `SPINDLE_SERVER_ADMIN_PASSWORD`:
1556
1557```shell
1558export SPINDLE_SERVER_ADMIN_PASSWORD="your-admin-password"
1559spindle admin --url http://localhost:6555 allow did:plc:examplemember
1560spindle admin --url http://localhost:6555 block did:plc:examplemember
1561```
1562
1563Blocking keeps the DID on record and denies it, so a blocked DID stays blocked
1564until you allow it again.
1565
1566If `SPINDLE_SERVER_ADMIN_PASSWORD` is unset the spindle still starts, but the
1567`/admin` endpoints are not mounted (they return 404) and `spindle admin` cannot
1568be used, so set it if you run an invite-only spindle.
1569
1570### Running microVM workflows
1571
1572The microVM engine needs a few extra things on the host, and
1573it needs images to boot.
1574
1575#### Host dependencies
1576
1577microVM workflows depend on a handful of host tools and
1578devices. spindle checks for the ones an image needs right
1579before it launches, so a missing dependency surfaces as a
1580clear error. You'll need:
1581
1582- `qemu`: the runner. The QEMU binary for the image's arch
1583 must be present (e.g. `qemu-system-x86_64`).
1584- `mkfs.ext4` (from `e2fsprogs`): to format the per-workflow
1585 writable volumes.
1586- [`slirp4netns`](https://github.com/rootless-containers/slirp4netns#install),
1587 `ip` (from `iproute2`), `mount` and `unshare` (from `util-linux`):
1588 used to sandbox guest networking.
1589- `/dev/kvm`: for hardware acceleration (unless you disable
1590 KVM with `SPINDLE_MICROVM_PIPELINES_ENABLE_KVM=false`).
1591- `/dev/vhost-vsock`: used by QEMU to enable guest-to-host vsock
1592 communication.
1593- `/dev/vsock`: used by spindle on the host to listen on vsock ports
1594 and accept guest agent connections.
1595- `/dev/net/tun`: required by `slirp4netns` to set up tap devices
1596 for sandboxed guest networking.
1597
1598On NixOS, the [spindle
1599module](https://tangled.org/tangled.org/core/blob/master/nix/modules/spindle.nix)
1600puts `qemu`, `e2fsprogs`, `slirp4netns`, `iproute2` and
1601`util-linux` on the service's `PATH` for you.
1602
1603#### Container virtualization
1604
1605Running `spindle` inside a container (e.g., Docker, Podman, or LXD) requires passing host device nodes into the container and granting the runtime additional privileges. Because spindle uses nested namespaces (`unshare`) and helper tools (`slirp4netns`), the container configuration will require:
1606
1607- `/dev/vsock`, `/dev/vhost-vsock`, `/dev/kvm`, and `/dev/net/tun` mapped from the host.
1608- `NET_ADMIN` and `SYS_ADMIN` capabilities to manage network namespaces and mounts inside the container.
1609- Relaxed seccomp filters (e.g., `seccomp=unconfined`) and SELinux/AppArmor containment if they restrict namespace creation or device access.
1610
1611#### Building images
1612
1613Images are built with Nix. The flake exposes packages for the
1614two stock images (use the `-tarball` prefixed ones for a gzipped
1615tarball you can copy to another host):
1616
1617```shell
1618# a NixOS image
1619nix build .#spindle-nixos-image
1620# an Alpine image
1621nix build .#spindle-alpine-image
1622```
1623
1624#### Installing images
1625
1626Spindle looks for images in
1627`SPINDLE_MICROVM_PIPELINES_IMAGE_DIR`. An image is resolved by
1628the name a workflow puts in its `image` field, matched
1629literally against what's on disk:
1630
16311. a directory `<name>/` containing a `spec.json` (next to the
1632 kernel/initrd/store-disk), or
16332. a flat `<name>.json` self-contained spec.
1634
1635Resolution depends only on the name and what's on disk, never
1636on the host doing the resolving, so the same workflow resolves
1637to the same image on every spindle. If you keep multiple
1638arches side by side, you can name them `<name>-<arch>` (e.g.
1639`nixos-x86_64`, `alpine-aarch64`); the suffix is just part of
1640the name. To make a name like `nixos` work if you are hosting
1641multiple arches, you can use symlinks.
1642
1643On NixOS, you'll most likely want to use `systemd.tmpfiles.rules`
1644to set these up declaratively.
1645
1646## Architecture
1647
1648Spindle is a small CI runner service. Here's a high-level overview of how it operates:
1649
1650- Listens for [`sh.tangled.spindle.member`](/lexicons/spindle/member.json) and
1651 [`sh.tangled.repo`](/lexicons/repo.json) records on the Jetstream.
1652- When a new repo record comes through (typically when you add a spindle to a
1653 repo from the settings), spindle then resolves the underlying knot and
1654 subscribes to repo events (see:
1655 [`sh.tangled.pipeline`](/lexicons/pipeline.json)).
1656- The spindle engine then handles execution of the pipeline, with results and
1657 logs beamed on the spindle event stream over WebSocket
1658
1659### The engines
1660
1661Spindle has two execution backends, picked per-workflow with
1662the [`engine`](#engine) field:
1663
1664- **nixery**: executes each step in a fresh Docker container
1665 (Podman works too, if Docker compatibility is enabled so
1666 that `/run/docker.sock` is created), with state persisted
1667 across steps within the `/tangled/workspace` directory. The
1668 base image for the container is constructed on the fly using
1669 [Nixery](https://nixery.dev), which is/rhandy for caching
1670 layers for frequently used packages.
1671- **microvm**: runs the whole workflow inside its own
1672 microVM, supporting different images, with extra
1673 configuration for NixOS images (e.g. services in workflow file)
1674 See the [engine
1675 README](https://tangled.org/tangled.org/core/blob/master/spindle/engines/microvm/README.md)
1676 for the architecture in depth.
1677
1678The pipeline manifest is [specified here](https://docs.tangled.org/spindles.html#pipelines).
1679
1680## Secrets with openbao
1681
1682This document covers setting up spindle to use OpenBao for secrets
1683management via OpenBao Proxy instead of the default SQLite backend.
1684
1685### Overview
1686
1687Spindle now uses OpenBao Proxy for secrets management. The proxy handles
1688authentication automatically using AppRole credentials, while spindle
1689connects to the local proxy instead of directly to the OpenBao server.
1690
1691This approach provides better security, automatic token renewal, and
1692simplified application code.
1693
1694### Installation
1695
1696Install OpenBao from Nixpkgs:
1697
1698```bash
1699nix shell nixpkgs#openbao # for a local server
1700```
1701
1702### Setup
1703
1704The setup process can is documented for both local development and production.
1705
1706#### Local development
1707
1708Start OpenBao in dev mode:
1709
1710```bash
1711bao server -dev -dev-root-token-id="root" -dev-listen-address=127.0.0.1:8201
1712```
1713
1714This starts OpenBao on `http://localhost:8201` with a root token.
1715
1716Set up environment for bao CLI:
1717
1718```bash
1719export BAO_ADDR=http://localhost:8200
1720export BAO_TOKEN=root
1721```
1722
1723#### Production
1724
1725You would typically use a systemd service with a
1726configuration file. Refer to
1727[@tangled.org/infra](https://tangled.org/@tangled.org/infra)
1728for how this can be achieved using Nix.
1729
1730Then, initialize the bao server:
1731
1732```bash
1733bao operator init -key-shares=1 -key-threshold=1
1734```
1735
1736This will print out an unseal key and a root key. Save them
1737somewhere (like a password manager). Then unseal the vault
1738to begin setting it up:
1739
1740```bash
1741bao operator unseal <unseal_key>
1742```
1743
1744All steps below remain the same across both dev and
1745production setups.
1746
1747#### Configure openbao server
1748
1749Create the spindle KV mount:
1750
1751```bash
1752bao secrets enable -path=spindle -version=2 kv
1753```
1754
1755Set up AppRole authentication and policy:
1756
1757Create a policy file `spindle-policy.hcl`:
1758
1759```hcl
1760# Full access to spindle KV v2 data
1761path "spindle/data/*" {
1762 capabilities = ["create", "read", "update", "delete"]
1763}
1764
1765# Access to metadata for listing and management
1766path "spindle/metadata/*" {
1767 capabilities = ["list", "read", "delete", "update"]
1768}
1769
1770# Allow listing at root level
1771path "spindle/" {
1772 capabilities = ["list"]
1773}
1774
1775# Required for connection testing and health checks
1776path "auth/token/lookup-self" {
1777 capabilities = ["read"]
1778}
1779```
1780
1781Apply the policy and create an AppRole:
1782
1783```bash
1784bao policy write spindle-policy spindle-policy.hcl
1785bao auth enable approle
1786bao write auth/approle/role/spindle \
1787 token_policies="spindle-policy" \
1788 token_ttl=1h \
1789 token_max_ttl=4h \
1790 bind_secret_id=true \
1791 secret_id_ttl=0 \
1792 secret_id_num_uses=0
1793```
1794
1795Get the credentials:
1796
1797```bash
1798# Get role ID (static)
1799ROLE_ID=$(bao read -field=role_id auth/approle/role/spindle/role-id)
1800
1801# Generate secret ID
1802SECRET_ID=$(bao write -f -field=secret_id auth/approle/role/spindle/secret-id)
1803
1804echo "Role ID: $ROLE_ID"
1805echo "Secret ID: $SECRET_ID"
1806```
1807
1808#### Create proxy configuration
1809
1810Create the credential files:
1811
1812```bash
1813# Create directory for OpenBao files
1814mkdir -p /tmp/openbao
1815
1816# Save credentials
1817echo "$ROLE_ID" > /tmp/openbao/role-id
1818echo "$SECRET_ID" > /tmp/openbao/secret-id
1819chmod 600 /tmp/openbao/role-id /tmp/openbao/secret-id
1820```
1821
1822Create a proxy configuration file `/tmp/openbao/proxy.hcl`:
1823
1824```hcl
1825# OpenBao server connection
1826vault {
1827 address = "http://localhost:8200"
1828}
1829
1830# Auto-Auth using AppRole
1831auto_auth {
1832 method "approle" {
1833 mount_path = "auth/approle"
1834 config = {
1835 role_id_file_path = "/tmp/openbao/role-id"
1836 secret_id_file_path = "/tmp/openbao/secret-id"
1837 }
1838 }
1839
1840 # Optional: write token to file for debugging
1841 sink "file" {
1842 config = {
1843 path = "/tmp/openbao/token"
1844 mode = 0640
1845 }
1846 }
1847}
1848
1849# Proxy listener for spindle
1850listener "tcp" {
1851 address = "127.0.0.1:8201"
1852 tls_disable = true
1853}
1854
1855# Enable API proxy with auto-auth token
1856api_proxy {
1857 use_auto_auth_token = true
1858}
1859
1860# Enable response caching
1861cache {
1862 use_auto_auth_token = true
1863}
1864
1865# Logging
1866log_level = "info"
1867```
1868
1869#### Start the proxy
1870
1871Start OpenBao Proxy:
1872
1873```bash
1874bao proxy -config=/tmp/openbao/proxy.hcl
1875```
1876
1877The proxy will authenticate with OpenBao and start listening on
1878`127.0.0.1:8201`.
1879
1880#### Configure spindle
1881
1882Set these environment variables for spindle:
1883
1884```bash
1885export SPINDLE_SERVER_SECRETS_PROVIDER=openbao
1886export SPINDLE_SERVER_SECRETS_OPENBAO_PROXY_ADDR=http://127.0.0.1:8201
1887export SPINDLE_SERVER_SECRETS_OPENBAO_MOUNT=spindle
1888```
1889
1890On startup, spindle will now connect to the local proxy,
1891which handles all authentication automatically.
1892
1893### Production setup for proxy
1894
1895For production, you'll want to run the proxy as a service:
1896
1897Place your production configuration in
1898`/etc/openbao/proxy.hcl` with proper TLS settings for the
1899vault connection.
1900
1901### Verifying setup
1902
1903Test the proxy directly:
1904
1905```bash
1906# Check proxy health
1907curl -H "X-Vault-Request: true" http://127.0.0.1:8201/v1/sys/health
1908
1909# Test token lookup through proxy
1910curl -H "X-Vault-Request: true" http://127.0.0.1:8201/v1/auth/token/lookup-self
1911```
1912
1913Test OpenBao operations through the server:
1914
1915```bash
1916# List all secrets
1917bao kv list spindle/
1918
1919# Add a test secret via the spindle API, then check it exists
1920bao kv list spindle/repos/
1921
1922# Get a specific secret
1923bao kv get spindle/repos/your_repo_path/SECRET_NAME
1924```
1925
1926### How it works
1927
1928- Spindle connects to OpenBao Proxy on localhost (typically
1929 port 8200 or 8201)
1930- The proxy authenticates with OpenBao using AppRole
1931 credentials
1932- All spindle requests go through the proxy, which injects
1933 authentication tokens
1934- Secrets are stored at
1935 `spindle/repos/{sanitized_repo_path}/{secret_key}`
1936- Repository paths like `did:plc:alice/myrepo` become
1937 `did_plc_alice_myrepo`
1938- The proxy handles all token renewal automatically
1939- Spindle no longer manages tokens or authentication
1940 directly
1941
1942### Troubleshooting
1943
1944**Connection refused**: Check that the OpenBao Proxy is
1945running and listening on the configured address.
1946
1947**403 errors**: Verify the AppRole credentials are correct
1948and the policy has the necessary permissions.
1949
1950**404 route errors**: The spindle KV mount probably doesn't
1951exist—run the mount creation step again.
1952
1953**Proxy authentication failures**: Check the proxy logs and
1954verify the role-id and secret-id files are readable and
1955contain valid credentials.
1956
1957**Secret not found after writing**: This can indicate policy
1958permission issues. Verify the policy includes both
1959`spindle/data/*` and `spindle/metadata/*` paths with
1960appropriate capabilities.
1961
1962Check proxy logs:
1963
1964```bash
1965# If running as systemd service
1966journalctl -u openbao-proxy -f
1967
1968# If running directly, check the console output
1969```
1970
1971Test AppRole authentication manually:
1972
1973```bash
1974bao write auth/approle/login \
1975 role_id="$(cat /tmp/openbao/role-id)" \
1976 secret_id="$(cat /tmp/openbao/secret-id)"
1977```
1978
1979# Webhooks
1980
1981Webhooks allow you to receive HTTP POST notifications when events occur in your repositories. This enables you to integrate Tangled with external services, trigger CI/CD pipelines, send notifications, or automate workflows.
1982
1983## Overview
1984
1985Webhooks send HTTP POST requests to URLs you configure whenever specific events happen. Currently, Tangled supports push, repository rename, and pull request events, with more event types coming soon.
1986
1987## Configuring webhooks
1988
1989To set up a webhook for your repository:
1990
19911. Navigate to your repository
19922. Go to **Settings → Hooks**
19933. Click **new webhook**
19944. Configure your webhook:
1995 - **Payload URL**: The endpoint that will receive the webhook POST requests
1996 - **Secret**: An optional secret key for verifying webhook authenticity (leave blank to send unsigned webhooks)
1997 - **Events**: Select which events trigger the webhook
1998 - **Active**: Toggle whether the webhook is enabled
1999
2000## Webhook payload
2001
2002### Push
2003
2004When a push event occurs, Tangled sends a POST request with a JSON payload of the format:
2005
2006```json
2007{
2008 "after": "7b320e5cbee2734071e4310c1d9ae401d8f6cab5",
2009 "before": "c04ddf64eddc90e4e2a9846ba3b43e67a0e2865e",
2010 "pusher": {
2011 "did": "did:plc:hwevmowznbiukdf6uk5dwrrq"
2012 },
2013 "ref": "refs/heads/main",
2014 "repository": {
2015 "clone_url": "https://tangled.org/did:plc:hwevmowznbiukdf6uk5dwrrq/some-repo",
2016 "created_at": "2025-09-15T08:57:23Z",
2017 "description": "an example repository",
2018 "fork": false,
2019 "full_name": "did:plc:hwevmowznbiukdf6uk5dwrrq/some-repo",
2020 "html_url": "https://tangled.org/did:plc:hwevmowznbiukdf6uk5dwrrq/some-repo",
2021 "name": "some-repo",
2022 "open_issues_count": 5,
2023 "owner": {
2024 "did": "did:plc:hwevmowznbiukdf6uk5dwrrq"
2025 },
2026 "ssh_url": "ssh://git@tangled.org/did:plc:hwevmowznbiukdf6uk5dwrrq/some-repo",
2027 "stars_count": 1,
2028 "updated_at": "2025-09-15T08:57:23Z"
2029 }
2030}
2031```
2032
2033### Pull request
2034
2035Pull request events are sent as separate event types, so you can subscribe to
2036exactly the transitions you care about:
2037
2038- `pull_request:created` — a pull request was opened
2039- `pull_request:resubmitted` — a new round (revision) was pushed to a pull request
2040- `pull_request:merged` — a pull request was merged
2041- `pull_request:closed` — a pull request was closed
2042- `pull_request:reopened` — a closed pull request was reopened
2043
2044All pull request events share the same payload format:
2045
2046```json
2047{
2048 "action": "created",
2049 "pull_request": {
2050 "number": 4,
2051 "title": "add dark mode",
2052 "body": "implements dark mode as discussed in #2",
2053 "state": "open",
2054 "target_branch": "main",
2055 "source": {
2056 "branch": "dark-mode",
2057 "sha": "7b320e5cbee2734071e4310c1d9ae401d8f6cab5"
2058 },
2059 "round_number": 0,
2060 "owner": {
2061 "did": "did:plc:hwevmowznbiukdf6uk5dwrrq"
2062 },
2063 "html_url": "https://tangled.org/did:plc:hwevmowznbiukdf6uk5dwrrq/some-repo/pulls/4",
2064 "patch_url": "https://tangled.org/did:plc:hwevmowznbiukdf6uk5dwrrq/some-repo/pulls/4/round/0.patch",
2065 "created_at": "2025-09-15T08:57:23Z"
2066 },
2067 "repository": { ... },
2068 "sender": {
2069 "did": "did:plc:hwevmowznbiukdf6uk5dwrrq"
2070 }
2071}
2072```
2073
2074Notes:
2075
2076- `action` mirrors the event type suffix (`created`, `resubmitted`, `merged`, `closed`, `reopened`).
2077- `repository` has the same format as in the push payload.
2078- The patch itself is not embedded in the payload (patches can be large); fetch it from `patch_url` instead. `round_number` identifies the latest round, and `patch_url` always points at that round's patch.
2079- `source` is only present for branch-based and fork-based pull requests; it is omitted for patch-based pulls. For fork-based pulls, `source.repo` contains the DID of the source repository.
2080- `sender` is the user who performed the action.
2081
2082## HTTP headers
2083
2084Each webhook request includes the following headers:
2085
2086- `Content-Type: application/json`
2087- `User-Agent: Tangled-Hook/<short-sha>` — User agent with short SHA of the commit (push events); `Tangled-Hook/pull_request` for pull request events
2088- `X-Tangled-Event: push` — The full event type (e.g. `push`, `pull_request:merged`)
2089- `X-Tangled-Hook-ID: <webhook-id>` — The webhook ID
2090- `X-Tangled-Delivery: <uuid>` — Unique delivery ID
2091- `X-Tangled-Signature-256: sha256=<hmac>` — HMAC-SHA256 signature (if secret configured)
2092
2093## Verifying webhook signatures
2094
2095If you configured a secret, you should verify the webhook signature to ensure requests are authentic. For example, in Go:
2096
2097```go
2098package main
2099
2100import (
2101 "crypto/hmac"
2102 "crypto/sha256"
2103 "encoding/hex"
2104 "io"
2105 "net/http"
2106 "strings"
2107)
2108
2109func verifySignature(payload []byte, signatureHeader, secret string) bool {
2110 // Remove 'sha256=' prefix from signature header
2111 signature := strings.TrimPrefix(signatureHeader, "sha256=")
2112
2113 // Compute expected signature
2114 mac := hmac.New(sha256.New, []byte(secret))
2115 mac.Write(payload)
2116 expected := hex.EncodeToString(mac.Sum(nil))
2117
2118 // Use constant-time comparison to prevent timing attacks
2119 return hmac.Equal([]byte(signature), []byte(expected))
2120}
2121
2122func webhookHandler(w http.ResponseWriter, r *http.Request) {
2123 // Read the request body
2124 payload, err := io.ReadAll(r.Body)
2125 if err != nil {
2126 http.Error(w, "Bad request", http.StatusBadRequest)
2127 return
2128 }
2129
2130 // Get signature from header
2131 signatureHeader := r.Header.Get("X-Tangled-Signature-256")
2132
2133 // Verify signature
2134 if signatureHeader != "" && verifySignature(payload, signatureHeader, yourSecret) {
2135 // Webhook is authentic, process it
2136 processWebhook(payload)
2137 w.WriteHeader(http.StatusOK)
2138 } else {
2139 http.Error(w, "Invalid signature", http.StatusUnauthorized)
2140 }
2141}
2142```
2143
2144## Delivery retries
2145
2146Webhooks are automatically retried on failure:
2147
2148- **3 total attempts** (1 initial + 2 retries)
2149- **Exponential backoff** starting at 1 second, max 10 seconds
2150- **Retried on**:
2151 - Network errors
2152 - HTTP 5xx server errors
2153- **Not retried on**:
2154 - HTTP 4xx client errors (bad request, unauthorized, etc.)
2155
2156### Timeouts
2157
2158Webhook requests timeout after 30 seconds. If your endpoint needs more time:
2159
21601. Respond with 200 OK immediately
21612. Process the webhook asynchronously in the background
2162
2163## Example integrations
2164
2165### Discord notifications
2166
2167```javascript
2168app.post("/webhook", (req, res) => {
2169 const payload = req.body;
2170
2171 fetch("https://discord.com/api/webhooks/...", {
2172 method: "POST",
2173 headers: { "Content-Type": "application/json" },
2174 body: JSON.stringify({
2175 content: `New push to ${payload.repository.full_name}`,
2176 embeds: [
2177 {
2178 title: `${payload.pusher.did} pushed to ${payload.ref}`,
2179 url: payload.repository.html_url,
2180 color: 0x00ff00,
2181 },
2182 ],
2183 }),
2184 });
2185
2186 res.status(200).send("OK");
2187});
2188```
2189
2190# Migrating knots and spindles
2191
2192Sometimes, non-backwards compatible changes are made to the
2193knot/spindle XRPC APIs. If you host a knot or a spindle, you
2194will need to follow this guide to upgrade. Typically, this
2195only requires you to deploy the newest version.
2196
2197This document is laid out in reverse-chronological order.
2198Newer migration guides are listed first, and older guides
2199are further down the page.
2200
2201## Upgrading to v1.16.0-alpha
2202
2203Starting with v1.16.0-alpha, spindles own CI pipeline data
2204directly. The appview no longer stores pipeline runs or follows
2205spindle event streams for pipeline history. Instead, it asks the
2206configured spindle for pipeline lists, single pipeline details,
2207workflow logs, retries, and cancellations over XRPC.
2208
2209This means that existing pipeline logs / runs won't appear after
2210you upgrade. Existing pipeline history from the appview cannot be
2211automatically migrated. If you want to migrate your data, you can
2212reach out to us and we will send you an SQL file that'll add the data
2213into your spindle.
2214
2215- Upgrade to the latest tag (v1.16.0 or above)
2216- Head to the [spindle
2217 dashboard](https://tangled.org/settings/spindles) and hit the
2218 "retry" button to verify your spindle
2219
2220## Upgrading to v1.15.0-alpha
2221
2222With v1.15.0-alpha, a knot itself owns its members and
2223per-repo collaborators directly. Previously this data was sourced from
2224PDS records (`sh.tangled.knot.member` and `sh.tangled.repo.collaborator`)
2225that the appview and the knot both read off the firehose.
2226The knot is now the source of truth and serves them over XRPC instead:
2227
2228- `sh.tangled.knot.addMember`, `sh.tangled.knot.removeMember`, `sh.tangled.knot.listMembers`
2229- `sh.tangled.repo.addCollaborator`, `sh.tangled.repo.removeCollaborator`, `sh.tangled.repo.listCollaborators`
2230
2231Until your knot is upgraded, the appview keeps reading its
2232members and collaborators from the old firehose-sourced records.
2233Upgrade to move your knot onto knot-owned access control.
2234
2235- Upgrade to the latest tag (v1.15.0 or above)
2236- Head to the [knot dashboard](https://tangled.org/settings/knots) and
2237 hit the "retry" button to verify your knot
2238
2239## Upgrading to v1.14.0-alpha
2240
2241Starting with v1.14.0-alpha, the fully knot uses the repoDID as its
2242canonical handle for repositories. This unlocks repository
2243renames from the appview UI and changes the wire format for
2244the following lexicons (`sh.tangled.repo.pull`, `sh.tangled.repo.collaborator`,
2245`sh.tangled.repo.issue`, `sh.tangled.git.refUpdate`).
2246
2247Knots that have not been upgraded may silently drop new push
2248events, pull requests, issues, and collaborator invites for
2249repositories they host until upgraded. So upgrade please!!!
2250
2251- Upgrade to the latest tag (v1.14.0 or above)
2252- Head to the [knot dashboard](https://tangled.org/settings/knots) and
2253 hit the "retry" button to verify your knot
2254
2255## Upgrading to v1.13.0-alpha
2256
2257Starting with v1.13.0-alpha, every repository on a knot is
2258assigned a DID. This makes repositories stable across
2259renames and transfers.
2260
2261When you upgrade your knot to this version, the server will
2262automatically mint DIDs for all existing repositories on
2263startup. This is a one-time process and you may see
2264additional log output during the first boot as DIDs are
2265assigned.
2266
2267- Upgrade to the latest tag (v1.13.0 or above)
2268- Head to the [knot dashboard](https://tangled.org/settings/knots) and
2269 hit the "retry" button to verify your knot
2270
2271## Upgrading from v1.8.x
2272
2273After v1.8.2, the HTTP API for knots and spindles has been
2274deprecated and replaced with XRPC. Repositories on outdated
2275knots will not be viewable from the appview. Upgrading is
2276straightforward however.
2277
2278For knots:
2279
2280- Upgrade to the latest tag (v1.9.0 or above)
2281- Head to the [knot dashboard](https://tangled.org/settings/knots) and
2282 hit the "retry" button to verify your knot
2283
2284For spindles:
2285
2286- Upgrade to the latest tag (v1.9.0 or above)
2287- Head to the [spindle
2288 dashboard](https://tangled.org/settings/spindles) and hit the
2289 "retry" button to verify your spindle
2290
2291## Upgrading from v1.7.x
2292
2293After v1.7.0, knot secrets have been deprecated. You no
2294longer need a secret from the appview to run a knot. All
2295authorized commands to knots are managed via [Inter-Service
2296Authentication](https://atproto.com/specs/xrpc#inter-service-authentication-jwt).
2297Knots will be read-only until upgraded.
2298
2299Upgrading is quite easy, in essence:
2300
2301- `KNOT_SERVER_SECRET` is no more, you can remove this
2302 environment variable entirely
2303- `KNOT_SERVER_OWNER` is now required on boot, set this to
2304 your DID. You can find your DID in the
2305 [settings](https://tangled.org/settings) page.
2306- Restart your knot once you have replaced the environment
2307 variable
2308- Head to the [knot dashboard](https://tangled.org/settings/knots) and
2309 hit the "retry" button to verify your knot. This simply
2310 writes a `sh.tangled.knot` record to your PDS.
2311
2312If you use the nix module, simply bump the flake to the
2313latest revision, and change your config block like so:
2314
2315```diff
2316 services.tangled.knot = {
2317 enable = true;
2318 server = {
2319- secretFile = /path/to/secret;
2320+ owner = "did:plc:foo";
2321 };
2322 };
2323```
2324
2325# Bobbin
2326
2327Bobbin is an API appview for Tangled records. It serves XRPC
2328endpoints for `sh.tangled.*`, with it you can get repos,
2329issues, pulls, comments, follows, stars, labels, pipelines,
2330and profiles. It is read-only, there is no auth, since that
2331should all be handled direct-to-PDS and knot respectively.
2332
2333**Bobbin has no permanent storage**.
2334
2335It is only a glorified edge index, in the graph theory
2336sense. Additionally it has a record cache, re-filled on
2337demand. All other data that Bobbin serves comes live from
2338PDSes & knots.
2339
2340## What Bobbin needs
2341
2342The way that Bobbin is able to pull off being
2343so stateless is by moving state upstream.
2344Primarily it depends on an instance of
2345[Hydrant](https://tangled.org/did:plc:6v3ul2ptnqctyxwkz5ti4amn)
2346, which is the service that gives an event stream
2347for Bobbin to quickly backfill from on every restart.
2348Backfilling ought to take less than a couple of minutes
2349maximum. If the upstream instance of Hydrant fails
2350while Bobbin is live, its list/count endpoints stop
2351advancing and report a stale cursor. Single-lookups
2352will continue working, due to the second dependency:
2353[Slingshot](https://tangled.org/did:plc:c7mc2fn47ihdihul4vjwsuy3/tree/main/slingshot).
2354Slingshot fetches individual records & resolves identities.
2355If the upstream instance of Slingshot fails, single-lookups
2356will fail with a `502` error. There are some aggregation
2357endpoints that use Slingshot for hydrating, which will also
2358fail.
2359
2360A soft dependency that ought to exist for Bobbin to operate
2361correctly is simply the plethora of knots that are out
2362there, that Bobbin talks to directly for git data and, for
2363knots at v1.15+, members & collaborators.
2364
2365## Building Bobbin
2366
2367Bobbin is under [Tangled's core monorepo, under bobbin/](https://tangled.org/did:plc:j5hmlfdrwkvtxm7cjmu7j2is/tree/master/bobbin).
2368Here's an easy local debug-build:
2369
2370```sh
2371cargo build -p bobbin
2372```
2373
2374Bobbin loves being in a container. When using
2375`bobbin/containerfiles/bobbin.Containerfile`, it runs `cargo
2376build --release --bin bobbin --package bobbin` within a
2377little Debian runtime, exposing port 8090.
2378
2379## Configuration
2380
2381The best way to configure Bobbin is via a toml config file.
2382There's an `example.toml` in [Bobbin's subdir](https://tangled.org/did:plc:j5hmlfdrwkvtxm7cjmu7j2is/blob/master/bobbin/example.toml).
2383Every value is overridable by a `BOBBIN_*` env var.
2384The load order is env, then `--config <path>`, then
2385`/etc/bobbin/config.toml`, then built-in defaults.
2386
2387Load and check a config without starting the server:
2388
2389```sh
2390bobbin --config config.toml validate
2391```
2392
2393Minimal config is the two upstream URLs. The hydrant URL
2394takes `ws://` or `wss://`. An `http://` or `https://`
2395URL is rewritten to the matching websocket scheme at
2396connection-time.
2397
2398```toml
2399[server]
2400binds = ["127.0.0.1:8090"]
2401
2402# Loopback-only & can leave empty to disable debug introspection.
2403debug_bind = "127.0.0.1:8091"
2404
2405[hydrant]
2406url = "https://hydrant.example.com"
2407
2408[slingshot]
2409url = "https://slingshot.example.com"
2410```
2411
2412> 🦪 Lewis
2413>
2414> At time of writing, we (Tangled) don't host public
2415> instances of Hydrant or Slingshot. You will have to
2416> find public instances or spin these up yourself! :P
2417
2418Take a gander in the project's example.toml for an
2419exhaustive list of things to configure.
2420
2421You will discover fun things such as a configurable adaptive
2422loop that watches the cgroup memory limit & throttles heavy
2423requests under pressure. It only works if it detects a
2424cgroup limit is present. The config for that is in the
2425`[backpressure]` block of the config template.
2426
2427## Running Bobbin
2428
2429Start the server using a config toml:
2430
2431```bash
2432bobbin --config config.toml
2433```
2434Bobbin wakes up in a cold sweat and immediately gets to
2435work:
24361. It binds its listeners, connects to the Hydrant stream
2437 in the background.
24382. It serves requests from the first
2439 moment it's alive, even before the Hydrant stream connects
2440 or finishes catching up. Having a cold Hydrant itself
2441 costs only latency and approximate counts.
2442
2443## The API
2444
2445**Single lookups** take a record's AT-URI.
2446
2447- `getRepo` takes the repo URI:
2448
2449```sh
2450curl "$BOBBIN/xrpc/sh.tangled.repo.getRepo?repo=at://did:plc:boltless/sh.tangled.repo/squid"
2451```
2452```json
2453{
2454 "uri": "at://did:plc:boltless/sh.tangled.repo/squid",
2455 "cid": "bafyrei...",
2456 "value": { "$type": "sh.tangled.repo", "knot": "knot1.tangled.sh", "description": "...", "createdAt": "..." }
2457}
2458```
2459
2460- `getProfile` takes the full profile record URI, so a bare
2461 handle or DID will not resolve:
2462
2463```sh
2464curl "$BOBBIN/xrpc/sh.tangled.actor.getProfile?actor=at://did:plc:boltless/sh.tangled.actor.profile/self"
2465```
2466
2467- If Slingshot cannot serve the record, the response is `502`:
2468
2469```json
2470{ "error": "UpstreamFailed", "message": "upstream unavailable: ..." }
2471```
2472
2473**Aggregation** endpoints come in `list*` and `count*` pairs,
2474each with a `*By` sibling, and require a `subject` query param.
2475
2476- `listRepos` and `countRepos` key on the owner DID:
2477
2478```sh
2479curl "$BOBBIN/xrpc/sh.tangled.repo.countRepos?subject=did:plc:boltless"
2480```
2481```json
2482{ "count": 7, "distinctAuthors": 1 }
2483```
2484
2485```sh
2486curl "$BOBBIN/xrpc/sh.tangled.repo.listRepos?subject=did:plc:boltless&limit=3"
2487```
2488```json
2489{ "items": [ { "uri": "at://did:plc:boltless/sh.tangled.repo/squid", "cid": "bafyrei...", "value": { } } ], "cursor": null }
2490```
2491
2492- Bobbin validates the subject per collection. Here a repo URI
2493 is passed where a bare DID is required, so the call returns a
2494 `400`:
2495
2496```sh
2497curl "$BOBBIN/xrpc/sh.tangled.graph.listFollows?subject=at://did:plc:boltless/sh.tangled.repo/squid"
2498```
2499```json
2500{ "error": "InvalidRequest", "message": "invalid request: subject must be a bare did, got at-uri with collection sh.tangled.repo" }
2501```
2502
2503**Search** is a single endpoint over an in-mem full-text
2504index:
2505
2506```sh
2507curl "$BOBBIN/xrpc/sh.tangled.search.query?q=tangled&limit=2"
2508```
2509```json
2510{ "hits": [ { "uri": "at://...", "cid": "...", "nsid": "sh.tangled.repo", "score": 27.1, "value": { } } ], "cursor": null }
2511```
2512
2513**Git data** such as blob, tree, diff, log, and archive proxies
2514straight to the repo's knot, streamed back without caching.
2515
2516## Coverage and warm-up
2517
2518- While the edge index is catching up from Hydrant,
2519 the aggregation count is a lower bound & may still climb.
2520- One endpoint reports how far along the backfill it is:
2521
2522```sh
2523curl "$BOBBIN/xrpc/sh.tangled.bobbin.getCoverage"
2524```
2525
2526While warming up:
2527
2528```json
2529{ "ready": false, "eventsProcessed": 45588, "lastCursor": 51658 }
2530```
2531
2532Once caught up, Bobbin flips to ready:
2533
2534```json
2535{ "ready": true, "eventsProcessed": 106085, "lastCursor": 116527 }
2536```
2537
2538If starting up Hydrant for the first time, Hydrant itself
2539will take a decent while (a couple of hours) to backfill
2540from PDSes. Hydrant stores its backfill on disk. Bobbin
2541restart reaches `ready` in minutes by replaying event from
2542an already-populated Hydrant. If your Hydrant is new, expect
2543Bobbin to backfill in that same couple of hours that Hydrant
2544takes.
2545
2546## Loose ends and not-gonna-impl
2547
2548- **No coverage signal for per-knot rosters yet.**
2549 Coverage tracks the hydrant stream only. A v1.15 knot
2550 that is unreachable serves a stale or empty member set
2551 with nothing to flag it.
2552- **Knot eventstream fan-out isn't pooled.**
2553 Bobbin opens one websocket per v1.15
2554 knot on top of the hydrant subscription. A network with
2555 thousands of knots wants pooling or a shared subscription.
2556- **No sequential issue or PR numbers.** bobbin returns rkeys,
2557 not `#42` style ids like the web appview. A client
2558 deriving a display number does it from creation order. But
2559 why bother? rkeys are the IDs.
2560
2561# Hacking on Tangled
2562
2563We highly recommend [installing
2564Nix](https://nixos.org/download/) (the package manager)
2565before working on the codebase. The Nix flake provides a lot
2566of helpers to get started and most importantly, builds and
2567dev shells are entirely deterministic.
2568
2569To set up your dev environment:
2570
2571```bash
2572nix develop
2573```
2574
2575Non-Nix users can look at the `devShell` attribute in the
2576`flake.nix` file to determine necessary dependencies.
2577
2578## Running the appview
2579
2580The appview requires Redis and OAuth JWKs. Start these
2581first, before launching the appview itself.
2582
2583```bash
2584# OAuth JWKs should already be set up by the Nix devshell:
2585echo $TANGLED_OAUTH_CLIENT_SECRET
2586z42ty4RT1ovnTopY8B8ekz9NuziF2CuMkZ7rbRFpAR9jBqMc
2587
2588echo $TANGLED_OAUTH_CLIENT_KID
25891761667908
2590
2591# if not, you can set it up yourself:
2592goat key generate -t P-256
2593Key Type: P-256 / secp256r1 / ES256 private key
2594Secret Key (Multibase Syntax): save this securely (eg, add to password manager)
2595 z42tuPDKRfM2mz2Kv953ARen2jmrPA8S9LX9tRq4RVcUMwwL
2596Public Key (DID Key Syntax): share or publish this (eg, in DID document)
2597 did:key:zDnaeUBxtG6Xuv3ATJE4GaWeyXM3jyamJsZw3bSPpxx4bNXDR
2598
2599# the secret key from above
2600export TANGLED_OAUTH_CLIENT_SECRET="z42tuP..."
2601
2602# Run Redis in a new shell to store OAuth sessions
2603redis-server
2604```
2605
2606The Nix flake exposes a few `app` attributes (run `nix
2607flake show` to see a full list of what the flake provides),
2608one of the apps runs the appview with the `air`
2609live-reloader:
2610
2611```bash
2612TANGLED_DEV=true nix run .#watch-appview
2613
2614# TANGLED_DB_PATH might be of interest to point to
2615# different sqlite DBs
2616
2617# in a separate shell, you can live-reload tailwind
2618nix run .#watch-tailwind
2619```
2620
2621## Running knots and spindles
2622
2623An end-to-end knot setup requires setting up a machine with
2624`sshd`, `AuthorizedKeysCommand`, and a Git user, which is
2625quite cumbersome. So the Nix flake provides a
2626`nixosConfiguration` to do so.
2627
2628<details>
2629 <summary><strong>macOS users will have to set up a Nix Builder first</strong></summary>
2630
2631In order to build Tangled's dev VM on macOS, you will
2632first need to set up a Linux Nix builder. The recommended
2633way to do so is to run a [`darwin.linux-builder`
2634VM](https://nixos.org/manual/nixpkgs/unstable/#sec-darwin-builder)
2635and to register it in `nix.conf` as a builder for Linux
2636with the same architecture as your Mac (`linux-aarch64` if
2637you are using Apple Silicon).
2638
2639If you're on nix-darwin, you can simply add
2640
2641```
2642nix.linux-builder.enable = true;
2643```
2644
2645to your host's `configuration.nix`.
2646
2647Alternatively, you can use any other method to set up a
2648Linux machine with Nix installed that you can `sudo ssh`
2649into (in other words, root user on your Mac has to be able
2650to ssh into the Linux machine without entering a password)
2651and that has the same architecture as your Mac. See
2652[remote builder
2653instructions](https://nix.dev/manual/nix/2.28/advanced-topics/distributed-builds.html#requirements)
2654for how to register such a builder in `nix.conf`.
2655
2656> WARNING: If you'd like to use
2657> [`nixos-lima`](https://github.com/nixos-lima/nixos-lima) or
2658> [Orbstack](https://orbstack.dev/), note that setting them up so that `sudo
2659ssh` works can be tricky. It seems to be [possible with
2660> Orbstack](https://github.com/orgs/orbstack/discussions/1669).
2661
2662</details>
2663
2664To begin, grab your DID from http://localhost:3000/settings.
2665Then, set `TANGLED_VM_KNOT_OWNER` to your DID. You can now start a
2666lightweight NixOS VM like so:
2667
2668```bash
2669nix run --impure .#vm
2670
2671# type `poweroff` at the shell to exit the VM
2672```
2673
2674This starts a knot on port 6444, a spindle on port 6555
2675with `ssh` exposed on port 2222.
2676
2677Once the services are running, head to
2678http://localhost:3000/settings/knots and hit "Verify". It should
2679verify the ownership of the services instantly if everything
2680went smoothly.
2681
2682You can push repositories to this VM with this ssh config
2683block on your main machine:
2684
2685```bash
2686Host nixos-shell
2687 Hostname localhost
2688 Port 2222
2689 User git
2690 IdentityFile ~/.ssh/my_tangled_key
2691```
2692
2693Set up a remote called `local-dev` on a git repo:
2694
2695```bash
2696git remote add local-dev git@nixos-shell:user/repo
2697git push local-dev main
2698```
2699
2700The above VM should already be running a spindle on
2701`localhost:6555`. Spindles aren't registered with the appview:
2702type `localhost:6555` into the spindle field on a repository's
2703pipeline settings (or when creating the repo) and it will run
2704that repo's CI jobs, as long as the spindle allows you as a
2705member (see [Managing members](#managing-members), or run it
2706with `SPINDLE_SERVER_INVITE_ONLY=false`).
2707
2708Of interest when debugging spindles:
2709
2710```
2711# Service logs from journald:
2712journalctl -xeu spindle
2713
2714# CI job logs from disk:
2715ls /var/log/spindle
2716
2717# Debugging spindle database:
2718sqlite3 /var/lib/spindle/spindle.db
2719
2720# litecli has a nicer REPL interface:
2721litecli /var/lib/spindle/spindle.db
2722```
2723
2724If for any reason you wish to disable either one of the
2725services in the VM, modify [nix/vm.nix](/nix/vm.nix) and set
2726`services.tangled.spindle.enable` (or
2727`services.tangled.knot.enable`) to `false`.
2728
2729# Contribution guide
2730
2731## Commit guidelines
2732
2733We follow a commit style similar to the Go project. Please keep commits:
2734
2735- **atomic**: each commit should represent one logical change
2736- **descriptive**: the commit message should clearly describe what the
2737 change does and why it's needed
2738
2739### Message format
2740
2741```
2742<service/top-level directory>/<affected package/directory>: <short summary of change>
2743
2744Optional longer description can go here, if necessary. Explain what the
2745change does and why, especially if not obvious. Reference relevant
2746issues or PRs when applicable. These can be links for now since we don't
2747auto-link issues/PRs yet.
2748```
2749
2750Here are some examples:
2751
2752```
2753appview/state: fix token expiry check in middleware
2754
2755The previous check did not account for clock drift, leading to premature
2756token invalidation.
2757```
2758
2759```
2760knotserver/git/service: improve error checking in upload-pack
2761```
2762
2763### General notes
2764
2765- PRs get merged "as-is" (fast-forward)—like applying a patch-series
2766 using `git am`. At present, there is no squashing—so please author
2767 your commits as they would appear on `master`, following the above
2768 guidelines.
2769- If there is a lot of nesting, for example "appview:
2770 pages/templates/repo/fragments: ...", these can be truncated down to
2771 just "appview: repo/fragments: ...". If the change affects a lot of
2772 subdirectories, you may abbreviate to just the top-level names, e.g.
2773 "appview: ..." or "knotserver: ...".
2774- Keep commits lowercased with no trailing period.
2775- Use the imperative mood in the summary line (e.g., "fix bug" not
2776 "fixed bug" or "fixes bug").
2777- Try to keep the summary line under 72 characters, but we aren't too
2778 fussed about this.
2779- Follow the same formatting for PR titles if filled manually.
2780- Don't include unrelated changes in the same commit.
2781- Avoid noisy commit messages like "wip" or "final fix"—rewrite history
2782 before submitting if necessary.
2783
2784## Code formatting
2785
2786We use a variety of tools to format our code, and multiplex them with
2787[`treefmt`](https://treefmt.com). All you need to do to format your changes
2788is run `nix run .#fmt` (or just `treefmt` if you're in the devshell).
2789
2790## Proposals for bigger changes
2791
2792Small fixes like typos, minor bugs, or trivial refactors can be
2793submitted directly as PRs.
2794
2795For larger changes—especially those introducing new features, significant
2796refactoring, or altering system behavior—please open a proposal first. This
2797helps us evaluate the scope, design, and potential impact before implementation.
2798
2799Create a new issue titled:
2800
2801```
2802proposal: <affected scope>: <summary of change>
2803```
2804
2805In the description, explain:
2806
2807- What the change is
2808- Why it's needed
2809- How you plan to implement it (roughly)
2810- Any open questions or tradeoffs
2811
2812We'll use the issue thread to discuss and refine the idea before moving
2813forward.
2814
2815## Developer Certificate of Origin (DCO)
2816
2817We require all contributors to certify that they have the right to
2818submit the code they're contributing. To do this, we follow the
2819[Developer Certificate of Origin
2820(DCO)](https://developercertificate.org/).
2821
2822By signing your commits, you're stating that the contribution is your
2823own work, or that you have the right to submit it under the project's
2824license. This helps us keep things clean and legally sound.
2825
2826To sign your commit, just add the `-s` flag when committing:
2827
2828```sh
2829git commit -s -m "your commit message"
2830```
2831
2832This appends a line like:
2833
2834```
2835Signed-off-by: Your Name <your.email@example.com>
2836```
2837
2838We won't merge commits if they aren't signed off. If you forget, you can
2839amend the last commit like this:
2840
2841```sh
2842git commit --amend -s
2843```
2844
2845If you're submitting a PR with multiple commits, make sure each one is
2846signed.
2847
2848For [jj](https://jj-vcs.github.io/jj/latest/) users, you can run the following command
2849to make it sign off commits in the tangled repo:
2850
2851```shell
2852# Safety check, should say "No matching config key..."
2853jj config list templates.commit_trailers
2854# The command below may need to be adjusted if the command above returned something.
2855jj config set --repo templates.commit_trailers "format_signed_off_by_trailer(self)"
2856```
2857
2858Refer to the [jujutsu
2859documentation](https://jj-vcs.github.io/jj/latest/config/#commit-trailers)
2860for more information.
2861
2862# Troubleshooting guide
2863
2864## Login issues
2865
2866Owing to the distributed nature of OAuth on AT Protocol, you
2867may run into issues with logging in. If you run a
2868self-hosted PDS:
2869
2870- You may need to ensure that your PDS is timesynced using
2871 NTP:
2872 - Enable the `ntpd` service
2873 - Run `ntpd -qg` to synchronize your clock
2874- You may need to increase the default request timeout:
2875 `NODE_OPTIONS="--network-family-autoselection-attempt-timeout=500"`
2876
2877## Empty punchcard
2878
2879For Tangled to register commits that you make across the
2880network, you need to setup one of following:
2881
2882- The committer email should be a verified email associated
2883 to your account. You can add and verify emails on the
2884 settings page.
2885- Or, the committer email should be set to your account's
2886 DID: `git config user.email "did:plc:foobar"`. You can find
2887 your account's DID on the settings page
2888
2889## Commit is not marked as verified
2890
2891Tangled only supports SSH commit signatures. Ensure the SSH public key you use
2892for signing is uploaded to Tangled.
2893
2894To sign commits using an SSH key with git:
2895
2896```
2897git config --global gpg.format ssh
2898git config --global user.signingkey ~/.ssh/tangled-key
2899```
2900
2901To sign commits using an SSH key with jj, add this to your
2902config:
2903
2904```
2905[signing]
2906behavior = "own"
2907backend = "ssh"
2908key = "~/.ssh/tangled-key"
2909```
2910
2911## Self-hosted knot issues
2912
2913If you need help troubleshooting a self-hosted knot, check
2914out the [knot troubleshooting
2915guide](/knot-self-hosting-guide.html#troubleshooting).