Update documentation to reflect current implementation status

- README.md: Complete rewrite with all implemented features
- Comprehensive command overview (auth, repo, issue, pr, knot, spindle)
- Installation instructions (source + AUR)
- Quick start guide with examples
- Configuration and environment variables
- Examples for issues, PRs, and CI/CD
- Development workflow section
- AGENTS.md: Updated from initial handoff to current status doc
- Implementation checklist (all features marked as complete except spindle run)
- Architecture patterns (ServiceAuth, repo creation, listing, PR merging)
- Working with tangled-core reference
- Next steps for contributors (focus on spindle run)
- Troubleshooting guide
- docs/getting-started.md: Expanded from stub to comprehensive tutorial
- Step-by-step installation guide
- First steps (auth, list, create, clone)
- Detailed examples for issues, PRs, and CI/CD
- Advanced topics (migration, output formats, quiet/verbose)
- Configuration and environment variables
- Troubleshooting section

Removed outdated "commands are stubs" messaging and added
accurate feature descriptions for all implemented functionality.

Changed files
+659 -399
docs
+188 -375
AGENTS.md
···
-
# Tangled CLI – Agent Handoff (Massive Context)
+
# Tangled CLI – Current Implementation Status
-
This document is a complete handoff for the next Codex instance working on the Tangled CLI (Rust). It explains what exists, what to build next, where to edit, how to call the APIs, how to persist sessions, how to print output, and how to validate success.
+
This document provides an overview of the Tangled CLI implementation status for AI agents or developers working on the project.
-
Primary focus for this session: implement authentication (auth login/status/logout) and repository listing (repo list).
+
## Implementation Status
-
--------------------------------------------------------------------------------
+
### ✅ Fully Implemented
-
## 0) TL;DR – Immediate Actions
+
#### Authentication (`auth`)
+
- `login` - Authenticate with AT Protocol using `com.atproto.server.createSession`
+
- `status` - Show current authentication status
+
- `logout` - Clear stored session from keyring
-
- Implement `auth login` using AT Protocol `com.atproto.server.createSession`.
-
- Prompt for handle/password if flags aren’t provided.
-
- POST to `/xrpc/com.atproto.server.createSession` at the configured PDS (default `https://bsky.social`).
-
- Persist `{accessJwt, refreshJwt, did, handle}` via `SessionManager` (keyring-backed).
-
- `auth status` reads keyring and prints handle + did; `auth logout` clears keyring.
+
#### Repositories (`repo`)
+
- `list` - List repositories using `com.atproto.repo.listRecords` with `collection=sh.tangled.repo`
+
- `create` - Create repositories with two-step flow:
+
1. Create PDS record via `com.atproto.repo.createRecord`
+
2. Initialize bare repo via `sh.tangled.repo.create` with ServiceAuth
+
- `clone` - Clone repositories using libgit2 with SSH agent support
+
- `info` - Display repository information including stats and languages
+
- `delete` - Delete repositories (both PDS record and knot repo)
+
- `star` / `unstar` - Star/unstar repositories via `sh.tangled.feed.star`
-
- Implement `repo list` using Tangled’s repo list method (tentative `sh.tangled.repo.list`).
-
- GET `/xrpc/sh.tangled.repo.list` with optional params: `user`, `knot`, `starred`.
-
- Include `Authorization: Bearer <accessJwt>` if required.
-
- Print results as table (default) or JSON (`--format json`).
+
#### Issues (`issue`)
+
- `list` - List issues via `com.atproto.repo.listRecords` with `collection=sh.tangled.repo.issue`
+
- `create` - Create issues via `com.atproto.repo.createRecord`
+
- `show` - Show issue details and comments
+
- `edit` - Edit issue title, body, or state
+
- `comment` - Add comments to issues
-
Keep edits minimal and scoped to these features.
+
#### Pull Requests (`pr`)
+
- `list` - List PRs via `com.atproto.repo.listRecords` with `collection=sh.tangled.repo.pull`
+
- `create` - Create PRs using `git format-patch` for patches
+
- `show` - Show PR details and diff
+
- `review` - Review PRs with approve/request-changes flags
+
- `merge` - Merge PRs via `sh.tangled.repo.merge` with ServiceAuth
-
--------------------------------------------------------------------------------
+
#### Knot Management (`knot`)
+
- `migrate` - Migrate repositories between knots
+
- Validates working tree is clean and pushed
+
- Creates new repo on target knot with source seeding
+
- Updates PDS record to point to new knot
-
## 1) Repository Map (Paths You Will Touch)
+
#### Spindle CI/CD (`spindle`)
+
- `config` - Enable/disable or configure spindle URL for a repository
+
- Updates the `spindle` field in `sh.tangled.repo` record
+
- `list` - List pipeline runs via `com.atproto.repo.listRecords` with `collection=sh.tangled.pipeline`
+
- `logs` - Stream workflow logs via WebSocket (`wss://spindle.tangled.sh/spindle/logs/{knot}/{rkey}/{name}`)
+
- `secret list` - List secrets via `sh.tangled.repo.listSecrets` with ServiceAuth
+
- `secret add` - Add secrets via `sh.tangled.repo.addSecret` with ServiceAuth
+
- `secret remove` - Remove secrets via `sh.tangled.repo.removeSecret` with ServiceAuth
-
- CLI (binary):
-
- `tangled/crates/tangled-cli/src/commands/auth.rs` → implement login/status/logout.
-
- `tangled/crates/tangled-cli/src/commands/repo.rs` → implement list.
-
- `tangled/crates/tangled-cli/src/cli.rs` → already contains arguments and subcommands; no structural changes needed.
-
- `tangled/crates/tangled-cli/src/main.rs` → no change.
+
### 🚧 Partially Implemented / Stubs
-
- Config + session:
-
- `tangled/crates/tangled-config/src/session.rs` → already provides `Session` + `SessionManager` (keyring).
-
- `tangled/crates/tangled-config/src/config.rs` → optional use for PDS/base URL (MVP can use CLI flags/env vars).
+
#### Spindle CI/CD (`spindle`)
+
- `run` - Manually trigger a workflow (stub)
+
- **TODO**: Parse `.tangled.yml` to determine workflows
+
- **TODO**: Create pipeline record and trigger spindle ingestion
+
- **TODO**: Support manual trigger inputs
-
- API client:
-
- `tangled/crates/tangled-api/src/client.rs` → add XRPC helpers and implement `login_with_password` and `list_repos`.
-
-
--------------------------------------------------------------------------------
-
-
## 2) Current State Snapshot
-
-
- Workspace is scaffolded and compiles after wiring dependencies (network needed to fetch crates):
-
- `tangled-cli`: clap CLI with subcommands; commands currently log stubs.
-
- `tangled-config`: TOML config loader/saver; keyring-backed session store.
-
- `tangled-api`: client struct with placeholder methods.
-
- `tangled-git`: stubs for future.
-
- Placeholder lexicons in `tangled/lexicons/sh.tangled/*` are not authoritative; use AT Protocol docs and inspect real endpoints later.
-
-
Goal: replace CLI stubs with real API calls for auth + repo list.
-
-
--------------------------------------------------------------------------------
-
-
## 3) Endpoints & Data Shapes
-
-
### 3.1 AT Protocol – Create Session
-
-
- Method: `com.atproto.server.createSession`
-
- HTTP: `POST /xrpc/com.atproto.server.createSession`
-
- Request JSON:
-
- `identifier: string` → user handle or email (e.g., `alice.bsky.social`).
-
- `password: string` → password or app password.
-
- Response JSON (subset used):
-
- `accessJwt: string`
-
- `refreshJwt: string`
-
- `did: string` (e.g., `did:plc:...`)
-
- `handle: string`
-
-
Persist to keyring using `SessionManager`.
-
-
### 3.2 Tangled – Repo List (tentative)
-
-
- Method: `sh.tangled.repo.list` (subject to change; wire in a constant to adjust easily).
-
- HTTP: `GET /xrpc/sh.tangled.repo.list?user=<..>&knot=<..>&starred=<true|false>`
-
- Auth: likely required; include `Authorization: Bearer <accessJwt>`.
-
- Response JSON (envelope):
-
- `{ "repos": [{ "name": string, "knot": string, "private": bool, ... }] }`
-
-
If method name or response shape differs, adapt the client code; keep CLI interface stable.
-
-
--------------------------------------------------------------------------------
-
-
## 4) Implementation Plan
-
-
### 4.1 Add XRPC helpers and methods in `tangled-api`
-
-
File: `tangled/crates/tangled-api/src/client.rs`
-
-
- Extend `TangledClient` with:
-
- `fn xrpc_url(&self, method: &str) -> String` → combines `base_url` + `/xrpc/` + `method`.
-
- `async fn post_json<TReq: Serialize, TRes: DeserializeOwned>(&self, method, req, bearer) -> Result<TRes>`.
-
- `async fn get_json<TRes: DeserializeOwned>(&self, method, params, bearer) -> Result<TRes>`.
-
- Include `Authorization: Bearer <token>` when `bearer` is provided.
-
-
- Implement:
-
- `pub async fn login_with_password(&self, handle: &str, password: &str, pds: &str) -> Result<Session>`
-
- POST to `com.atproto.server.createSession` at `self.base_url` (which should be the PDS base).
-
- Map response to `tangled_config::session::Session` and return it (caller will persist).
-
- `pub async fn list_repos(&self, user: Option<&str>, knot: Option<&str>, starred: bool, bearer: Option<&str>) -> Result<Vec<Repository>>`
-
- GET `sh.tangled.repo.list` with params present only if set.
-
- Return parsed `Vec<Repository>` from an envelope `{ repos: [...] }`.
-
-
Error handling: For non-2xx, read the response body, return `anyhow!("{status}: {body}")`.
+
## Architecture Overview
-
### 4.2 Wire CLI auth commands
+
### Workspace Structure
-
File: `tangled/crates/tangled-cli/src/commands/auth.rs`
+
- `crates/tangled-cli` - CLI binary with clap-based argument parsing
+
- `crates/tangled-config` - Configuration and keyring-backed session management
+
- `crates/tangled-api` - XRPC client wrapper for AT Protocol and Tangled APIs
+
- `crates/tangled-git` - Git operation helpers (currently unused)
-
- `login`:
-
- Determine PDS: use `--pds` arg if provided, else default `https://bsky.social` (later from config/env).
-
- Prompt for missing handle/password.
-
- `let client = tangled_api::TangledClient::new(&pds);`
-
- `let session = client.login_with_password(&handle, &password, &pds).await?;`
-
- `tangled_config::session::SessionManager::default().save(&session)?;`
-
- Print: `Logged in as '{handle}' ({did})`.
+
### Key Patterns
-
- `status`:
-
- Load `SessionManager::default().load()?`.
-
- If Some: print `Logged in as '{handle}' ({did})`.
-
- Else: print `Not logged in. Run: tangled auth login`.
+
#### ServiceAuth Flow
+
Many Tangled API operations require ServiceAuth tokens:
+
1. Obtain token via `com.atproto.server.getServiceAuth` from PDS
+
- `aud` parameter must be `did:web:<target-host>`
+
- `exp` parameter should be Unix timestamp + 600 seconds
+
2. Use token as `Authorization: Bearer <serviceAuth>` for Tangled API calls
-
- `logout`:
-
- `SessionManager::default().clear()?`.
-
- Print `Logged out` if something was cleared; otherwise `No session found` is acceptable.
+
#### Repository Creation Flow
+
Two-step process:
+
1. **PDS**: Create `sh.tangled.repo` record via `com.atproto.repo.createRecord`
+
2. **Tangled API**: Initialize bare repo via `sh.tangled.repo.create` with ServiceAuth
-
### 4.3 Wire CLI repo list
+
#### Repository Listing
+
Done entirely via PDS (not Tangled API):
+
1. Resolve handle → DID if needed via `com.atproto.identity.resolveHandle`
+
2. List records via `com.atproto.repo.listRecords` with `collection=sh.tangled.repo`
+
3. Filter client-side (e.g., by knot)
-
File: `tangled/crates/tangled-cli/src/commands/repo.rs`
+
#### Pull Request Merging
+
1. Fetch PR record to get patch and target branch
+
2. Obtain ServiceAuth token
+
3. Call `sh.tangled.repo.merge` with `{did, name, patch, branch, commitMessage, commitBody}`
-
- Load session; if absent, print `Please login first: tangled auth login` and exit 1 (or 0 with friendly message; choose one and be consistent).
-
- Build a client for Tangled API base (for now, default to `https://tangled.org` or allow `TANGLED_API_BASE` env var to override):
-
- `let base = std::env::var("TANGLED_API_BASE").unwrap_or_else(|_| "https://tangled.org".into());`
-
- `let client = tangled_api::TangledClient::new(base);`
-
- Call `client.list_repos(args.user.as_deref(), args.knot.as_deref(), args.starred, Some(session.access_jwt.as_str())).await?`.
-
- Print:
-
- If `Cli.format == OutputFormat::Json`: `serde_json::to_string_pretty(&repos)`.
-
- Else: simple columns `NAME KNOT PRIVATE` using `println!` formatting for now.
+
### Base URLs and Defaults
-
--------------------------------------------------------------------------------
+
- **PDS Base** (auth + record operations): Default `https://bsky.social`, stored in session
+
- **Tangled API Base** (server operations): Default `https://tngl.sh`, can override via `TANGLED_API_BASE`
+
- **Spindle Base** (CI/CD): Default `wss://spindle.tangled.sh` for WebSocket logs, can override via `TANGLED_SPINDLE_BASE`
-
## 5) Code Snippets (Copy/Paste Friendly)
+
### Session Management
-
### 5.1 In `tangled-api/src/client.rs`
+
Sessions are stored in the system keyring:
+
- Linux: GNOME Keyring / KWallet via Secret Service API
+
- macOS: macOS Keychain
+
- Windows: Windows Credential Manager
+
Session includes:
```rust
-
use anyhow::{anyhow, bail, Result};
-
use serde::{de::DeserializeOwned, Deserialize, Serialize};
-
use tangled_config::session::Session;
-
-
#[derive(Clone, Debug)]
-
pub struct TangledClient { pub(crate) base_url: String }
-
-
impl TangledClient {
-
pub fn new(base_url: impl Into<String>) -> Self { Self { base_url: base_url.into() } }
-
pub fn default() -> Self { Self::new("https://tangled.org") }
-
-
fn xrpc_url(&self, method: &str) -> String {
-
format!("{}/xrpc/{}", self.base_url.trim_end_matches('/'), method)
-
}
-
-
async fn post_json<TReq: Serialize, TRes: DeserializeOwned>(
-
&self,
-
method: &str,
-
req: &TReq,
-
bearer: Option<&str>,
-
) -> Result<TRes> {
-
let url = self.xrpc_url(method);
-
let client = reqwest::Client::new();
-
let mut reqb = client.post(url).header(reqwest::header::CONTENT_TYPE, "application/json");
-
if let Some(token) = bearer { reqb = reqb.header(reqwest::header::AUTHORIZATION, format!("Bearer {}", token)); }
-
let res = reqb.json(req).send().await?;
-
let status = res.status();
-
if !status.is_success() {
-
let body = res.text().await.unwrap_or_default();
-
return Err(anyhow!("{}: {}", status, body));
-
}
-
Ok(res.json::<TRes>().await?)
-
}
-
-
async fn get_json<TRes: DeserializeOwned>(
-
&self,
-
method: &str,
-
params: &[(&str, String)],
-
bearer: Option<&str>,
-
) -> Result<TRes> {
-
let url = self.xrpc_url(method);
-
let client = reqwest::Client::new();
-
let mut reqb = client.get(url).query(&params);
-
if let Some(token) = bearer { reqb = reqb.header(reqwest::header::AUTHORIZATION, format!("Bearer {}", token)); }
-
let res = reqb.send().await?;
-
let status = res.status();
-
if !status.is_success() {
-
let body = res.text().await.unwrap_or_default();
-
return Err(anyhow!("{}: {}", status, body));
-
}
-
Ok(res.json::<TRes>().await?)
-
}
-
-
pub async fn login_with_password(&self, handle: &str, password: &str, _pds: &str) -> Result<Session> {
-
#[derive(Serialize)]
-
struct Req<'a> { #[serde(rename = "identifier")] identifier: &'a str, #[serde(rename = "password")] password: &'a str }
-
#[derive(Deserialize)]
-
struct Res { #[serde(rename = "accessJwt")] access_jwt: String, #[serde(rename = "refreshJwt")] refresh_jwt: String, did: String, handle: String }
-
let body = Req { identifier: handle, password };
-
let res: Res = self.post_json("com.atproto.server.createSession", &body, None).await?;
-
Ok(Session { access_jwt: res.access_jwt, refresh_jwt: res.refresh_jwt, did: res.did, handle: res.handle, ..Default::default() })
-
}
-
-
pub async fn list_repos(&self, user: Option<&str>, knot: Option<&str>, starred: bool, bearer: Option<&str>) -> Result<Vec<Repository>> {
-
#[derive(Deserialize)]
-
struct Envelope { repos: Vec<Repository> }
-
let mut q = vec![];
-
if let Some(u) = user { q.push(("user", u.to_string())); }
-
if let Some(k) = knot { q.push(("knot", k.to_string())); }
-
if starred { q.push(("starred", true.to_string())); }
-
let env: Envelope = self.get_json("sh.tangled.repo.list", &q, bearer).await?;
-
Ok(env.repos)
-
}
+
struct Session {
+
access_jwt: String,
+
refresh_jwt: String,
+
did: String,
+
handle: String,
+
pds: Option<String>, // PDS base URL
}
-
-
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
-
pub struct Repository { pub did: Option<String>, pub rkey: Option<String>, pub name: String, pub knot: Option<String>, pub description: Option<String>, pub private: bool }
```
-
### 5.2 In `tangled-cli/src/commands/auth.rs`
+
## Working with tangled-core
-
```rust
-
use anyhow::Result;
-
use dialoguer::{Input, Password};
-
use tangled_config::session::SessionManager;
-
use crate::cli::{AuthCommand, AuthLoginArgs, Cli};
+
The `../tangled-core` repository contains the server implementation and lexicon definitions.
-
pub async fn run(_cli: &Cli, cmd: AuthCommand) -> Result<()> {
-
match cmd {
-
AuthCommand::Login(args) => login(args).await,
-
AuthCommand::Status => status().await,
-
AuthCommand::Logout => logout().await,
-
}
-
}
+
### Key Files to Check
-
async fn login(mut args: AuthLoginArgs) -> Result<()> {
-
let handle: String = match args.handle.take() { Some(h) => h, None => Input::new().with_prompt("Handle").interact_text()? };
-
let password: String = match args.password.take() { Some(p) => p, None => Password::new().with_prompt("Password").interact()? };
-
let pds = args.pds.unwrap_or_else(|| "https://bsky.social".to_string());
-
let client = tangled_api::TangledClient::new(&pds);
-
let mut session = match client.login_with_password(&handle, &password, &pds).await {
-
Ok(sess) => sess,
-
Err(e) => {
-
println!("\x1b[93mIf you're on your own PDS, make sure to pass the --pds flag\x1b[0m");
-
return Err(e);
-
}
-
};
-
SessionManager::default().save(&session)?;
-
println!("Logged in as '{}' ({})", session.handle, session.did);
-
Ok(())
-
}
+
- **Lexicons**: `../tangled-core/lexicons/**/*.json`
+
- Defines XRPC method schemas (NSIDs, parameters, responses)
+
- Example: `sh.tangled.repo.create`, `sh.tangled.repo.merge`
-
async fn status() -> Result<()> {
-
let mgr = SessionManager::default();
-
match mgr.load()? {
-
Some(s) => println!("Logged in as '{}' ({})", s.handle, s.did),
-
None => println!("Not logged in. Run: tangled auth login"),
-
}
-
Ok(())
-
}
+
- **XRPC Routes**: `../tangled-core/knotserver/xrpc/xrpc.go`
+
- Shows which endpoints require ServiceAuth
+
- Maps NSIDs to handler functions
-
async fn logout() -> Result<()> {
-
let mgr = SessionManager::default();
-
if mgr.load()?.is_some() { mgr.clear()?; println!("Logged out"); } else { println!("No session found"); }
-
Ok(())
-
}
-
```
+
- **API Handlers**: `../tangled-core/knotserver/xrpc/*.go`
+
- Implementation details for server-side operations
+
- Example: `create_repo.go`, `merge.go`
-
### 5.3 In `tangled-cli/src/commands/repo.rs`
+
### Useful Search Commands
-
```rust
-
use anyhow::{anyhow, Result};
-
use tangled_config::session::SessionManager;
-
use crate::cli::{Cli, RepoCommand, RepoListArgs};
+
```bash
+
# Find a specific NSID
+
rg -n "sh\.tangled\.repo\.create" ../tangled-core
-
pub async fn run(_cli: &Cli, cmd: RepoCommand) -> Result<()> {
-
match cmd { RepoCommand::List(args) => list(args).await, _ => Ok(println!("not implemented")) }
-
}
+
# List all lexicons
+
ls ../tangled-core/lexicons/repo
-
async fn list(args: RepoListArgs) -> Result<()> {
-
let mgr = SessionManager::default();
-
let session = mgr.load()?.ok_or_else(|| anyhow!("Please login first: tangled auth login"))?;
-
let base = std::env::var("TANGLED_API_BASE").unwrap_or_else(|_| "https://tangled.org".into());
-
let client = tangled_api::TangledClient::new(base);
-
let repos = client.list_repos(args.user.as_deref(), args.knot.as_deref(), args.starred, Some(session.access_jwt.as_str())).await?;
-
// Simple output: table or JSON to be improved later
-
println!("NAME\tKNOT\tPRIVATE");
-
for r in repos { println!("{}\t{}\t{}", r.name, r.knot.unwrap_or_default(), r.private); }
-
Ok(())
-
}
+
# Check ServiceAuth usage
+
rg -n "ServiceAuth|VerifyServiceAuth" ../tangled-core
```
-
--------------------------------------------------------------------------------
+
## Next Steps for Contributors
-
## 6) Configuration, Env Vars, and Security
+
### Priority: Implement `spindle run`
-
- PDS base (auth): default `https://bsky.social`. Accept CLI flag `--pds`; later read from config.
-
- Tangled API base (repo list): default `https://tangled.org`; allow override via `TANGLED_API_BASE` env var.
-
- Do not log passwords or tokens.
-
- Store tokens only in keyring (already implemented).
+
The only remaining stub is `spindle run` for manually triggering workflows. Implementation plan:
-
--------------------------------------------------------------------------------
+
1. **Parse `.tangled.yml`** in the current repository to extract workflow definitions
+
- Look for workflow names, triggers, and manual trigger inputs
-
## 7) Testing Plan (MVP)
+
2. **Create pipeline record** on PDS via `com.atproto.repo.createRecord`:
+
```rust
+
collection: "sh.tangled.pipeline"
+
record: {
+
triggerMetadata: {
+
kind: "manual",
+
repo: { knot, did, repo, defaultBranch },
+
manual: { inputs: [...] }
+
},
+
workflows: [{ name, engine, clone, raw }]
+
}
+
```
-
- Client unit tests with `mockito` for `createSession` and `repo list` endpoints; simulate expected JSON.
-
- CLI smoke tests optional for this pass. If added, use `assert_cmd` to check printed output strings.
-
- Avoid live network calls in tests.
+
3. **Notify spindle** (if needed) or let the ingester pick up the new record
-
--------------------------------------------------------------------------------
+
4. **Support workflow selection** when multiple workflows exist:
+
- `--workflow <name>` flag to select specific workflow
+
- Default to first workflow if not specified
-
## 8) Acceptance Criteria
+
5. **Support manual inputs** (if workflow defines them):
+
- Prompt for input values or accept via flags
-
- `tangled auth login`:
-
- Prompts or uses flags; successful call saves session and prints `Logged in as ...`.
-
- On failure, shows HTTP status and error message, plus helpful hint about --pds flag for users on their own PDS.
-
- `tangled auth status`:
-
- Shows handle + did if session exists; otherwise says not logged in.
-
- `tangled auth logout`:
-
- Clears keyring; prints confirmation.
-
- `tangled repo list`:
-
- Performs authenticated GET and prints a list (even if empty) without panicking.
-
- JSON output possible later; table output acceptable for now.
+
### Code Quality Tasks
-
--------------------------------------------------------------------------------
+
- Add more comprehensive error messages for common failure cases
+
- Improve table formatting for list commands (consider using `tabled` crate features)
+
- Add shell completion generation (bash, zsh, fish)
+
- Add more unit tests with `mockito` for API client methods
+
- Add integration tests with `assert_cmd` for CLI commands
-
## 9) Troubleshooting Notes
-
-
- Keyring errors on Linux may indicate no secret service running; suggest enabling GNOME Keyring or KWallet.
-
- If `repo list` returns 404, the method name or base URL may be wrong; adjust `sh.tangled.repo.list` or `TANGLED_API_BASE`.
-
- If 401, session may be missing/expired; run `auth login` again.
-
-
--------------------------------------------------------------------------------
-
-
## 10) Non‑Goals for This Pass
+
### Documentation Tasks
-
- Refresh token flow, device code, OAuth.
-
- PRs, issues, knots, spindle implementation.
-
- Advanced formatting, paging, completions.
-
-
--------------------------------------------------------------------------------
+
- Add man pages for all commands
+
- Create video tutorials for common workflows
+
- Add troubleshooting guide for common issues
-
## 11) Future Follow‑ups
-
-
- Refresh flow (`com.atproto.server.refreshSession`) and retry once on 401.
-
- Persist base URLs and profiles in config; add `tangled config` commands.
-
- Proper table/json formatting and shell completions.
-
-
--------------------------------------------------------------------------------
-
-
## 12) Quick Operator Commands
-
-
- Build CLI: `cargo build -p tangled-cli`
-
- Help: `cargo run -p tangled-cli -- --help`
-
- Login: `cargo run -p tangled-cli -- auth login --handle <handle>`
-
- Status: `cargo run -p tangled-cli -- auth status`
-
- Repo list: `TANGLED_API_BASE=https://tangled.org cargo run -p tangled-cli -- repo list --user <handle>`
-
-
--------------------------------------------------------------------------------
+
## Development Workflow
-
End of handoff. Implement auth login and repo list as described, keeping changes focused and testable.
+
### Building
+
```sh
+
cargo build # Debug build
+
cargo build --release # Release build
+
```
-
--------------------------------------------------------------------------------
+
### Running
-
## 13) Tangled Core (../tangled-core) – Practical Notes
+
```sh
+
cargo run -p tangled-cli -- <command>
+
```
-
This workspace often needs to peek at the Tangled monorepo to confirm XRPC endpoints and shapes. Here are concise tips and findings that informed this CLI implementation.
+
### Testing
-
### Where To Look
+
```sh
+
cargo test # Run all tests
+
cargo test -- --nocapture # Show println output
+
```
-
- Lexicons (authoritative NSIDs and shapes): `../tangled-core/lexicons/**`
-
- Repo create: `../tangled-core/lexicons/repo/create.json` → `sh.tangled.repo.create`
-
- Repo record schema: `../tangled-core/lexicons/repo/repo.json` → `sh.tangled.repo`
-
- Misc repo queries (tree, log, tags, etc.) under `../tangled-core/lexicons/repo/`
-
- Note: there is no `sh.tangled.repo.list` lexicon in the core right now; listing is done via ATproto records.
-
- Knotserver XRPC routes (what requires auth vs open): `../tangled-core/knotserver/xrpc/xrpc.go`
-
- Mutating repo ops (e.g., `sh.tangled.repo.create`) are behind ServiceAuth middleware.
-
- Read-only repo queries (tree, log, etc.) are open.
-
- Create repo handler (server-side flow): `../tangled-core/knotserver/xrpc/create_repo.go`
-
- Validates ServiceAuth; expects rkey for the `sh.tangled.repo` record that already exists on the user's PDS.
-
- ServiceAuth middleware (how Bearer is validated): `../tangled-core/xrpc/serviceauth/service_auth.go`
-
- Validates a ServiceAuth token with Audience = `did:web:<knot-or-service-host>`.
-
- Appview client for ServiceAuth: `../tangled-core/appview/xrpcclient/xrpc.go` (method: `ServerGetServiceAuth`).
+
### Code Quality
-
### How To Search Quickly (rg examples)
+
```sh
+
cargo fmt # Format code
+
cargo clippy # Run linter
+
cargo clippy -- -W clippy::all # Strict linting
+
```
-
- Find a specific NSID across the repo:
-
- `rg -n "sh\.tangled\.repo\.create" ../tangled-core`
-
- See which endpoints are routed and whether they’re behind ServiceAuth:
-
- `rg -n "chi\..*Get\(|chi\..*Post\(" ../tangled-core/knotserver/xrpc`
-
- Then open `xrpc.go` and respective handlers.
-
- Discover ServiceAuth usage and audience DID:
-
- `rg -n "ServerGetServiceAuth|VerifyServiceAuth|serviceauth" ../tangled-core`
-
- List lexicons by area:
-
- `ls ../tangled-core/lexicons/repo` or `rg -n "\bid\": \"sh\.tangled\..*\"" ../tangled-core/lexicons`
+
## Troubleshooting Common Issues
-
### Repo Listing (client-side pattern)
+
### Keyring Errors on Linux
-
- There is no `sh.tangled.repo.list` in core. To list a user’s repos:
-
1) Resolve handle → DID if needed via PDS: `GET com.atproto.identity.resolveHandle`.
-
2) List records from the user’s PDS: `GET com.atproto.repo.listRecords` with `collection=sh.tangled.repo`.
-
3) Filter client-side (e.g., by `knot`). “Starred” filtering is not currently defined in core.
+
Ensure a secret service is running:
+
```sh
+
systemctl --user enable --now gnome-keyring-daemon
+
```
-
### Repo Creation (two-step flow)
+
### Invalid Token Errors
-
- Step 1 (PDS): create the `sh.tangled.repo` record in the user’s repo:
-
- `POST com.atproto.repo.createRecord` with `{ repo: <did>, collection: "sh.tangled.repo", record: { name, knot, description?, createdAt } }`.
-
- Extract `rkey` from the returned `uri` (`at://<did>/<collection>/<rkey>`).
-
- Step 2 (Tangled API base): call the server to initialize the bare repo on the knot:
-
- Obtain ServiceAuth: `GET com.atproto.server.getServiceAuth` from PDS with `aud=did:web:<tngl.sh or target-host>`.
-
- `POST sh.tangled.repo.create` on the Tangled API base with `{ rkey, defaultBranch?, source? }` and `Authorization: Bearer <serviceAuth>`.
-
- Server validates token via `xrpc/serviceauth`, confirms actor permissions, and creates the git repo.
+
- For record operations: Use PDS client, not Tangled API client
+
- For server operations: Ensure ServiceAuth audience DID matches target host
-
### Base URLs, DIDs, and Defaults
+
### Repository Not Found
-
- Tangled API base (server): default is `https://tngl.sh`. Do not use the marketing/landing site.
-
- PDS base (auth + record ops): default `https://bsky.social` unless a different PDS was chosen on login.
-
- ServiceAuth audience DID is `did:web:<host>` where `<host>` is the Tangled API base hostname.
-
- CLI stores the PDS URL in the session to keep the CLI stateful.
+
- Verify repo exists: `tangled repo info owner/name`
+
- Check you're using the correct owner (handle or DID)
+
- Ensure you have access permissions
-
### Common Errors and Fixes
+
### WebSocket Connection Failures
-
- `InvalidToken` when listing repos: listing should use the PDS (`com.atproto.repo.listRecords`), not the Tangled API base.
-
- 404 on `repo.create`: verify ServiceAuth audience matches the target host and that the rkey exists on the PDS.
-
- Keychain issues on Linux: ensure a Secret Service (e.g., GNOME Keyring or KWallet) is running.
+
- Check spindle base URL is correct (default: `wss://spindle.tangled.sh`)
+
- Verify the job_id format: `knot:rkey:name`
+
- Ensure the workflow has actually run and has logs
-
### Implementation Pointers (CLI)
+
## Additional Resources
-
- Auth
-
- `com.atproto.server.createSession` against the PDS, save `{accessJwt, refreshJwt, did, handle, pds}` in keyring.
-
- List repos
-
- Use session.handle by default; resolve to DID, then `com.atproto.repo.listRecords` on PDS.
-
- Create repo
-
- Build the PDS record first; then ServiceAuth → `sh.tangled.repo.create` on `tngl.sh`.
+
- Main README: `README.md` - User-facing documentation
+
- Getting Started Guide: `docs/getting-started.md` - Tutorial for new users
+
- Lexicons: `../tangled-core/lexicons/` - XRPC method definitions
+
- Server Implementation: `../tangled-core/knotserver/` - Server-side code
-
### Testing Hints
+
---
-
- Avoid live calls; use `mockito` to stub both PDS and Tangled API base endpoints.
-
- Unit test decoding with minimal JSON envelopes: record lists, createRecord `uri`, and repo.create (empty body or simple ack).
+
Last updated: 2025-10-14
+168 -17
README.md
···
-
# Tangled CLI (Rust)
+
# Tangled CLI
A Rust CLI for Tangled, a decentralized git collaboration platform built on the AT Protocol.
-
Status: project scaffold with CLI, config, API and git crates. Commands are stubs pending endpoint wiring.
+
## Features
+
+
Tangled CLI is a fully functional tool for managing repositories, issues, pull requests, and CI/CD workflows on the Tangled platform.
+
+
### Implemented Commands
+
+
- **Authentication** (`auth`)
+
- `login` - Authenticate with AT Protocol credentials
+
- `status` - Show current authentication status
+
- `logout` - Clear stored session
+
+
- **Repositories** (`repo`)
+
- `list` - List your repositories or another user's repos
+
- `create` - Create a new repository on a knot
+
- `clone` - Clone a repository to your local machine
+
- `info` - Show detailed repository information
+
- `delete` - Delete a repository
+
- `star` / `unstar` - Star or unstar repositories
+
+
- **Issues** (`issue`)
+
- `list` - List issues for a repository
+
- `create` - Create a new issue
+
- `show` - Show issue details and comments
+
- `edit` - Edit issue title, body, or state
+
- `comment` - Add a comment to an issue
+
+
- **Pull Requests** (`pr`)
+
- `list` - List pull requests for a repository
+
- `create` - Create a pull request from a branch
+
- `show` - Show pull request details and diff
+
- `review` - Review a pull request (approve/request changes)
+
- `merge` - Merge a pull request
+
+
- **Knot Management** (`knot`)
+
- `migrate` - Migrate a repository to another knot
+
+
- **CI/CD with Spindle** (`spindle`)
+
- `config` - Enable/disable or configure spindle for a repository
+
- `list` - List pipeline runs for a repository
+
- `logs` - Stream logs from a workflow execution
+
- `secret` - Manage secrets for CI/CD workflows
+
- `list` - List secrets for a repository
+
- `add` - Add or update a secret
+
- `remove` - Remove a secret
+
- `run` - Manually trigger a workflow (not yet implemented)
-
## Workspace
+
## Installation
-
- `crates/tangled-cli`: CLI binary (clap-based)
-
- `crates/tangled-config`: Config + session management
-
- `crates/tangled-api`: XRPC client wrapper (stubs)
-
- `crates/tangled-git`: Git helpers (stubs)
-
- `lexicons/sh.tangled`: Placeholder lexicons
+
### Build from Source
-
## Quick start
+
Requires Rust toolchain (1.70+) and network access to fetch dependencies.
```sh
-
cargo run -p tangled-cli -- --help
+
cargo build --release
```
-
### Install from AUR (community maintained)
+
The binary will be available at `target/release/tangled-cli`.
+
+
### Install from AUR (Arch Linux)
+
+
Community-maintained package:
```sh
yay -S tangled-cli-git
```
-
Building requires network to fetch crates.
+
## Quick Start
+
+
1. **Login to Tangled**:
+
```sh
+
tangled auth login --handle your.handle.bsky.social
+
```
+
+
2. **List your repositories**:
+
```sh
+
tangled repo list
+
```
+
+
3. **Create a new repository**:
+
```sh
+
tangled repo create myproject --description "My cool project"
+
```
+
+
4. **Clone a repository**:
+
```sh
+
tangled repo clone username/reponame
+
```
+
+
## Workspace Structure
+
+
- `crates/tangled-cli` - CLI binary with clap-based argument parsing
+
- `crates/tangled-config` - Configuration and session management (keyring-backed)
+
- `crates/tangled-api` - XRPC client wrapper for AT Protocol and Tangled APIs
+
- `crates/tangled-git` - Git operation helpers
+
+
## Configuration
+
+
The CLI stores session credentials securely in your system keyring and configuration in:
+
- Linux: `~/.config/tangled/config.toml`
+
- macOS: `~/Library/Application Support/tangled/config.toml`
+
- Windows: `%APPDATA%\tangled\config.toml`
+
+
### Environment Variables
+
+
- `TANGLED_PDS_BASE` - Override the PDS base URL (default: `https://bsky.social`)
+
- `TANGLED_API_BASE` - Override the Tangled API base URL (default: `https://tngl.sh`)
+
- `TANGLED_SPINDLE_BASE` - Override the Spindle base URL (default: `wss://spindle.tangled.sh`)
-
## Next steps
+
## Examples
+
+
### Working with Issues
-
- Implement `com.atproto.server.createSession` for auth
-
- Wire repo list/create endpoints under `sh.tangled.*`
-
- Persist sessions via keyring and load in CLI
-
- Add output formatting (table/json)
+
```sh
+
# Create an issue
+
tangled issue create --repo myrepo --title "Bug: Fix login" --body "Description here"
+
+
# List issues
+
tangled issue list --repo myrepo
+
+
# Comment on an issue
+
tangled issue comment <issue-id> --body "I'll fix this"
+
```
+
+
### Working with Pull Requests
+
+
```sh
+
# Create a PR from a branch
+
tangled pr create --repo myrepo --base main --head feature-branch --title "Add new feature"
+
+
# Review a PR
+
tangled pr review <pr-id> --approve --comment "LGTM!"
+
+
# Merge a PR
+
tangled pr merge <pr-id>
+
```
+
### CI/CD with Spindle
+
+
```sh
+
# Enable spindle for your repo
+
tangled spindle config --repo myrepo --enable
+
+
# List pipeline runs
+
tangled spindle list --repo myrepo
+
+
# Stream logs from a workflow
+
tangled spindle logs knot:rkey:workflow-name --follow
+
+
# Manage secrets
+
tangled spindle secret add --repo myrepo --key API_KEY --value "secret-value"
+
tangled spindle secret list --repo myrepo
+
```
+
+
## Development
+
+
Run tests:
+
```sh
+
cargo test
+
```
+
+
Run with debug output:
+
```sh
+
cargo run -p tangled-cli -- --verbose <command>
+
```
+
+
Format code:
+
```sh
+
cargo fmt
+
```
+
+
Check for issues:
+
```sh
+
cargo clippy
+
```
+
+
## Contributing
+
+
Contributions are welcome! Please feel free to submit issues or pull requests.
+
+
## License
+
+
MIT OR Apache-2.0
+303 -7
docs/getting-started.md
···
-
# Getting Started
+
# Getting Started with Tangled CLI
+
+
This guide will help you get up and running with the Tangled CLI.
+
+
## Installation
+
+
### Prerequisites
+
+
- Rust toolchain 1.70 or later
+
- Git
+
- A Bluesky/AT Protocol account
+
+
### Build from Source
+
+
1. Clone the repository:
+
```sh
+
git clone https://tangled.org/tangled/tangled-cli
+
cd tangled-cli
+
```
+
+
2. Build the project:
+
```sh
+
cargo build --release
+
```
+
+
3. The binary will be available at `target/release/tangled-cli`. Optionally, add it to your PATH or create an alias:
+
```sh
+
alias tangled='./target/release/tangled-cli'
+
```
+
+
### Install from AUR (Arch Linux)
+
+
If you're on Arch Linux, you can install from the AUR:
+
+
```sh
+
yay -S tangled-cli-git
+
```
+
+
## First Steps
+
+
### 1. Authenticate
+
+
Login with your AT Protocol credentials (your Bluesky account):
+
+
```sh
+
tangled auth login
+
```
+
+
You'll be prompted for your handle (e.g., `alice.bsky.social`) and password. If you're using a custom PDS, specify it with the `--pds` flag:
+
+
```sh
+
tangled auth login --pds https://your-pds.example.com
+
```
+
+
Your credentials are stored securely in your system keyring.
+
+
### 2. Check Your Status
+
+
Verify you're logged in:
+
+
```sh
+
tangled auth status
+
```
+
+
### 3. List Your Repositories
+
+
See all your repositories:
+
+
```sh
+
tangled repo list
+
```
+
+
Or view someone else's public repositories:
+
+
```sh
+
tangled repo list --user alice.bsky.social
+
```
+
+
### 4. Create a Repository
+
+
Create a new repository on Tangled:
+
+
```sh
+
tangled repo create my-project --description "My awesome project"
+
```
+
+
By default, repositories are created on the default knot (`tngl.sh`). You can specify a different knot:
+
+
```sh
+
tangled repo create my-project --knot knot1.tangled.sh
+
```
+
+
### 5. Clone a Repository
+
+
Clone a repository to start working on it:
+
+
```sh
+
tangled repo clone alice/my-project
+
```
+
+
This uses SSH by default. For HTTPS:
+
+
```sh
+
tangled repo clone alice/my-project --https
+
```
+
+
## Working with Issues
+
+
### Create an Issue
+
+
```sh
+
tangled issue create --repo my-project --title "Add new feature" --body "We should add feature X"
+
```
+
+
### List Issues
+
+
```sh
+
tangled issue list --repo my-project
+
```
-
This project is a scaffold of a Tangled CLI in Rust. The commands are present as stubs and will be wired to XRPC endpoints iteratively.
+
### View Issue Details
-
## Build
+
```sh
+
tangled issue show <issue-id>
+
```
-
Requires Rust toolchain and network access to fetch dependencies.
+
### Comment on an Issue
+
```sh
+
tangled issue comment <issue-id> --body "I'm working on this!"
```
-
cargo build
+
+
## Working with Pull Requests
+
+
### Create a Pull Request
+
+
```sh
+
tangled pr create --repo my-project --base main --head feature-branch --title "Add feature X"
```
-
## Run
+
The CLI will use `git format-patch` to create a patch from your branch.
+
### List Pull Requests
+
+
```sh
+
tangled pr list --repo my-project
```
-
cargo run -p tangled-cli -- --help
+
+
### Review a Pull Request
+
+
```sh
+
tangled pr review <pr-id> --approve --comment "Looks good!"
```
+
Or request changes:
+
+
```sh
+
tangled pr review <pr-id> --request-changes --comment "Please fix the tests"
+
```
+
+
### Merge a Pull Request
+
+
```sh
+
tangled pr merge <pr-id>
+
```
+
+
## CI/CD with Spindle
+
+
Spindle is Tangled's integrated CI/CD system.
+
+
### Enable Spindle for Your Repository
+
+
```sh
+
tangled spindle config --repo my-project --enable
+
```
+
+
Or use a custom spindle URL:
+
+
```sh
+
tangled spindle config --repo my-project --url https://my-spindle.example.com
+
```
+
+
### View Pipeline Runs
+
+
```sh
+
tangled spindle list --repo my-project
+
```
+
+
### Stream Workflow Logs
+
+
```sh
+
tangled spindle logs knot:rkey:workflow-name
+
```
+
+
Add `--follow` to tail the logs in real-time.
+
+
### Manage Secrets
+
+
Add secrets for your CI/CD workflows:
+
+
```sh
+
tangled spindle secret add --repo my-project --key API_KEY --value "my-secret-value"
+
```
+
+
List secrets:
+
+
```sh
+
tangled spindle secret list --repo my-project
+
```
+
+
Remove a secret:
+
+
```sh
+
tangled spindle secret remove --repo my-project --key API_KEY
+
```
+
+
## Advanced Topics
+
+
### Repository Migration
+
+
Move a repository to a different knot:
+
+
```sh
+
tangled knot migrate --repo my-project --to knot2.tangled.sh
+
```
+
+
This command must be run from within the repository's working directory, and your working tree must be clean and pushed.
+
+
### Output Formats
+
+
Most commands support JSON output:
+
+
```sh
+
tangled repo list --format json
+
```
+
+
### Quiet and Verbose Modes
+
+
Reduce output:
+
+
```sh
+
tangled --quiet repo list
+
```
+
+
Increase verbosity for debugging:
+
+
```sh
+
tangled --verbose repo list
+
```
+
+
## Configuration
+
+
The CLI stores configuration in:
+
- Linux: `~/.config/tangled/config.toml`
+
- macOS: `~/Library/Application Support/tangled/config.toml`
+
- Windows: `%APPDATA%\tangled\config.toml`
+
+
Session credentials are stored securely in your system keyring (GNOME Keyring, KWallet, macOS Keychain, or Windows Credential Manager).
+
+
### Environment Variables
+
+
- `TANGLED_PDS_BASE` - Override the default PDS (default: `https://bsky.social`)
+
- `TANGLED_API_BASE` - Override the Tangled API base (default: `https://tngl.sh`)
+
- `TANGLED_SPINDLE_BASE` - Override the Spindle base (default: `wss://spindle.tangled.sh`)
+
+
## Troubleshooting
+
+
### Keyring Issues on Linux
+
+
If you see keyring errors on Linux, ensure you have a secret service running:
+
+
```sh
+
# For GNOME
+
systemctl --user enable --now gnome-keyring-daemon
+
+
# For KDE
+
# KWallet should start automatically with Plasma
+
```
+
+
### Authentication Failures
+
+
If authentication fails with your custom PDS:
+
+
```sh
+
tangled auth login --pds https://your-pds.example.com
+
```
+
+
Make sure the PDS URL is correct and accessible.
+
+
### "Repository not found" Errors
+
+
Verify the repository exists and you have access:
+
+
```sh
+
tangled repo info owner/reponame
+
```
+
+
## Getting Help
+
+
For command-specific help, use the `--help` flag:
+
+
```sh
+
tangled --help
+
tangled repo --help
+
tangled repo create --help
+
```
+
+
## Next Steps
+
+
- Explore all available commands with `tangled --help`
+
- Set up CI/CD workflows with `.tangled.yml` in your repository
+
- Check out the main README for more examples and advanced usage
+
+
Happy collaborating! 🧶