WIP: A simple cli for daily tangled use cases and AI integration. This is for my personal use right now, but happy if others get mileage from it! :)
1# Tangled CLI: Architecture & Implementation Plan
2
3## Project Overview
4
5**Goal:** Create a context-aware CLI for tangled.org that bridges the gap between the AT Protocol (XRPC) and standard Git.
6
7**Philosophy:** Follow the **GitHub CLI (gh)** standard: act as a wrapper that creates a seamless experience where the API and local Git repo feel like one unified tool.
8
9## Prior Art Analysis: GitHub CLI (gh) vs. Tangled CLI
10
11| Feature | GitHub CLI (gh) Approach | Tangled CLI Strategy |
12| :------------- | :--------------------------------------------------- | :------------------------------------------------------------------------------------------------------------------------- |
13| **Context** | Infers repo from .git/config remote URL. | **Must-Have:** Parse .git/config to resolve did:plc:... from the remote URL. |
14| **Auth** | Stores oauth token; acts as a git-credential-helper. | **Plan:** Store AT Proto session; inject auth headers into git operations if possible, or manage SSH keys via API. |
15| **Output** | TTY \= Tables. Pipe \= Text. \--json \= Structured. | **Plan:** Use is-interactive check. Default to "Human Mode". Force "Machine Mode" via flags. |
16| **Filtering** | \--json name,url (filters fields). | **Plan:** Support basic \--json flag first. Add field filtering (--json "cloneUrl,did") to save LLM context window tokens. |
17| **Extensions** | Allows custom subcommands. | _Out of Scope for V1._ |
18
19## High-Level Architecture (Refined)
20
21The CLI acts as a "Context Engine" before it even hits the API.
22`graph TD`
23`User[User / LLM] -->|Command| CLI`
24
25 `subgraph "Context Engine"`
26 `Git[Local .git/config] -->|Read Remote| Resolver[Context Resolver]`
27 `Resolver -->|Inferred DID| Payload`
28 `end`
29
30 `subgraph "Execution"`
31 `Payload -->|XRPC Request| API[Tangled AppView]`
32 `Payload -->|Git Command| Shell[Git Shell]`
33 `end`
34
35 `API --> Output`
36 `Shell --> Output`
37
38## Tech Stack (TypeScript)
39
40| Component | Library | Purpose |
41| :---------------- | :---------------------- | :--------------------------------------------------------------------------------------------- |
42| **Framework** | **commander** | CLI routing and command parsing (e.g., `tangled repo create`). |
43| **API Client** | **@atproto/api** | Official AT Protocol XRPC client, session management, and record operations. |
44| **Lexicon Tools** | **@atproto/lexicon** | Schema validation for custom Tangled.org lexicons (e.g., `sh.tangled.publicKey`). |
45| **Git Context** | **git-url-parse** | Parses remote URLs to extract the Tangled DID/NSID from `.git/config`. |
46| **Git Ops** | **simple-git** | Wraps local git operations safely. |
47| **Validation** | **zod** | Input validation and schema generation for LLMs. |
48| **Interactivity** | **@inquirer/prompts** | Modern, user-friendly prompts for interactive flows. |
49| **Formatting** | **cli-table3** | Pretty tables for "Human Mode" output (following gh CLI patterns). |
50| **OS Keychain** | **@napi-rs/keyring** | Cross-platform secure storage for AT Protocol session tokens (macOS, Windows, Linux). |
51| **TypeScript** | **tsx** | Fast TypeScript execution for development and testing. |
52
53## Agent Integration (The "LLM Friendly" Layer)
54
55To make this tool accessible to Claude Code/Gemini, we adopt gh's best patterns:
56
57### Rule 1: Context is King
58
59LLMs often hallucinate repo IDs.
60
61- **Design:** If the user/LLM runs tangled issue list inside a folder, **do not** ask for the repo DID. Infer it.
62- **Fallback:** Only error if no git remote is found.
63
64### Rule 2: Precision JSON (--json \<fields\>)
65
66LLMs have token limits. Returning a 50KB repo object is wasteful.
67
68- **Feature:** tangled repo view \--json name,cloneUrl,description
69- **Implementation:** Use lodash/pick to filter the API response before printing to stdout.
70
71### Rule 3: Fail Fast, Fail Loud
72
73LLMs can't read error messages buried in HTML or long stack traces. Provide a `--no-input` flag that forces the CLI to error if it can't resolve context or if required flags are missing.
74
75### Rule 4: Flexible Input for Issue Bodies
76
77Following `gh`'s pattern, `tangled issue create` will support various ways to provide the issue body, making it LLM-friendly and flexible for scripting. It will accept:
78
79- `--body "Text"` or `-b "Text"` for a direct string.
80- `--body-file ./file.md` or `-F ./file.md` to read from a file.
81- `--body-file -` or `-F -` to read from standard input (stdin).
82
83### Summary of Improvements
84
85- **Context Inference:** This is the "killer feature" of gh that we are copying. It makes the tool usable for humans and safer for LLMs (less typing = fewer errors).
86- **Filtered JSON:** Saves tokens for LLM context windows.
87- **Git Config Integration:** Treats the local .git folder as a database of configuration, reducing the need for environment variables or complex flags.
88- **Flexible Issue Body Input:** Improves usability for both humans and LLMs by allowing diverse input methods for issue descriptions.
89
90## Examples Tangled CLI Usage
91
92```bash
93tangled auth login (opens a browser for auth)
94tangled repo create my-new-repo
95cd my-new-repo
96tangled issue create "Bug: Something is broken" --body "Detailed description of the bug here."
97echo "Another bug description from stdin." | tangled issue create "Bug: From stdin" --body-file -
98tangled issue list --json "id,title"
99tangled pr create --base main --head my-feature --title "Add new feature" --body-file ./pr_description.md
100tangled pr view 123
101tangled pr comment 123 --body "Looks good, small change needed."
102```
103
104## Basic Commands
105
106Basic commands include auth, key management, repo creation, issue management, and pull request management.
107
108`tangled auth login`
109
110- Logs in the user, ideally through a web browser flow for security.
111 `tangled auth logout`
112- Logs out the user, clearing the session.
113 `tangled ssh-key add <public-key-path>`
114- Uploads the provided public SSH key to the user's tangled.org account via the API.
115 `tangled ssh-key verify`
116- Verifies that the user's SSH key is correctly set up and can authenticate with tangled.org. Returns the associated DID and handle if successful.
117 `tangled repo create <repo-name>`
118- Creates a new repository under the user's account.
119 `tangled repo view [--json <fields>]`
120- Displays details about the current repository. If `--json` is provided, outputs only the specified fields in JSON format.
121 `tangled issue create "<title>" [--body "<body>" | --body-file <file> | -F -]`
122- Creates a new issue in the current repository with the given title and optional body, which can be provided via flag, file, or stdin.
123 `tangled pr create --base <base-branch> --head <head-branch> --title <title> [--body <body> | --body-file <file> | -F -]`
124- Creates a new pull request in the current repository from a head branch to a base branch.
125 `tangled pr list [--json <fields>]`
126- Lists pull requests for the current repository.
127 `tangled pr view <id> [--json <fields>]`
128- Displays detailed information about a specific pull request, including comments.
129 `tangled pr comment <id> [--body <body> | --body-file <file> | -F -]`
130- Adds a comment to a pull request.
131 `tangled pr review <id> --comment <comment> [--approve | --request-changes]`
132- Submits a review for a pull request, with optional approval or request for changes.
133
134## Design Decisions & Outstanding Issues
135
136This section documents key design decisions and tracks outstanding architectural questions.
137
138### (Resolved) SSH Key Management (`gh` Compatibility)
139
140- **Original Question:** How does `gh` manage SSH keys, and can we follow that pattern?
141- **Resolution:** Analysis shows that `gh` does _not_ manage private keys. It facilitates uploading the user's _public_ key to their GitHub account. The local SSH agent handles the private key.
142- **Our Approach:** The `tangled ssh-key add` command follows this exact pattern. It provides a user-friendly way to upload a public key to `tangled.org`. This resolves the core of this issue, as it is compatible with external key managers like 1Password's SSH agent.
143
144### (Decided) Secure Session Storage
145
146- **Original Question:** How should we securely store the AT Proto session token?
147- **Resolution:** Storing sensitive tokens in plaintext files is not secure.
148- **Our Approach:** The CLI will use the operating system's native keychain for secure storage (e.g., macOS Keychain, Windows Credential Manager, or Secret Service on Linux). A library like `keytar` will be used to abstract the platform differences.
149
150### (Decided) Configuration Resolution Order
151
152- **Original Question:** How should settings be resolved from different sources?
153- **Resolution:** A clear precedence order is necessary.
154- **Our Approach:** The CLI will resolve settings in the following order of precedence (highest first):
155 1. Command-line flags (e.g., `--repo-did ...`)
156 2. Environment variables (e.g., `TANGLED_REPO_DID=...`)
157 3. Project-specific config file (e.g., `.tangled/config.yml` in the current directory)
158 4. Global user config file (e.g., `~/.config/tangled/config.yml`)
159
160### (Decided for V1) Authentication Flow: App Passwords (PDS)
161
162- **Original Question:** Can we allow auth through a web browser?
163- **Resolution:** For the initial version, the CLI will use **App Passwords** for authentication. This is the standard and simplest method for third-party AT Protocol clients and aligns with existing practices.
164- **`tangled auth login` Flow:** When running `tangled auth login`, the CLI will prompt the user for their **PDS handle** (e.g., `@mark.bsky.social`) and an **App Password**.
165- **Generating an App Password:** Users typically generate App Passwords from their PDS's settings (e.g., in the official Bluesky app under "Settings -> App Passwords", or on their self-hosted PDS web interface). The CLI **does not** generate app passwords.
166- **Session Management:** The session established is with the user's PDS, and this authenticated session is then used to interact with `tangled.org`'s App View/Service.
167- **OAuth Support:** Implementing a web-based OAuth flow (similar to `gh`'s approach) is more complex and not a standard part of the AT Protocol client authentication flow. This approach is deferred for future consideration.
168
169## Future Expansion Opportunities
170
171The analysis of the `tangled.org` API revealed a rich set of features that are not yet part of the initial CLI plan but represent significant opportunities for future expansion. These include:
172
173- **CI/CD Pipelines:** Commands to view pipeline status and manage CI/CD jobs.
174- **Repository Secrets:** A dedicated command set for managing CI/CD secrets within a repository (`tangled repo secret ...`).
175- **Advanced Git Operations:** Commands to interact with the commit log, diffs, branches, and tags directly via the API, augmenting local `git` commands.
176- **Social & Feed Interactions:** Commands for starring repositories, reacting to feed items, and managing the user's social graph (following/unfollowing).
177- **Label Management:** Commands to create, apply, and remove labels from issues and pull requests.
178- **Collaboration:** Commands to manage repository collaborators.
179- **Fork Management:** Commands for forking repositories and managing the sync status of forks.
180- **Reactions**: Commands to add and remove reactions on issues, pull requests, and comments.
181- **Commenting on Issues**: Commands to add comments to issues.
182
183## Task Management
184
185We're bootstrapping task tracking with TODO.md, but will migrate all tasks into Tangled issues and dog food the product as soon as we have basic issue creation and listing working.
186
187## Development
188
189### Prerequisites
190
191- Node.js 22.0.0 or higher (latest LTS)
192- npm (comes with Node.js)
193
194### Installation
195
196Clone the repository and install dependencies:
197
198```bash
199npm install
200```
201
202### Available Scripts
203
204- `npm run dev` - Run the CLI in development mode (with hot reload via tsx)
205- `npm run build` - Build TypeScript to JavaScript (output to `dist/`)
206- `npm test` - Run tests once
207- `npm run test:watch` - Run tests in watch mode
208- `npm run test:coverage` - Run tests with coverage report
209- `npm run lint` - Check code with Biome linter
210- `npm run lint:fix` - Auto-fix linting issues
211- `npm run format` - Format code with Biome
212- `npm run typecheck` - Type check without building
213
214### Running Locally
215
216```bash
217# Run the CLI in development mode
218npm run dev -- --version
219npm run dev -- --help
220
221# Build and run the production version
222npm run build
223node dist/index.js --version
224
225# Install globally for local testing
226npm link
227tangled --version
228tangled --help
229npm unlink -g tangled-cli # Unlink when done
230```
231
232### Project Structure
233
234```
235tangled-cli/
236├── src/
237│ ├── index.ts # Main CLI entry point
238│ ├── commands/ # Command implementations
239│ ├── lib/ # Core business logic
240│ └── utils/ # Helper functions
241├── tests/ # Test files
242├── dist/ # Build output (gitignored)
243└── package.json # Package configuration
244```
245
246### Coding Guidelines
247
248**IMPORTANT: These guidelines must be followed for all code contributions.**
249
250#### Validation Functions Location
251
252**ALL validation logic belongs in `src/utils/validation.ts`**
253
254- Use Zod schemas for all input validation
255- Boolean validation helpers (e.g., `isValidHandle()`, `isValidTangledDid()`) go in `validation.ts`
256- Never define validation functions in other files - import from `validation.ts`
257- Validation functions should return `true/false` or use Zod's `safeParse()` pattern
258
259Example:
260```typescript
261// ✅ CORRECT: validation.ts
262export function isValidHandle(handle: string): boolean {
263 return handleSchema.safeParse(handle).success;
264}
265
266// ❌ WRONG: Don't define validators in other files
267// git.ts should import isValidHandle, not define it
268```
269
270#### Test Coverage Requirements
271
272**ALL code must have comprehensive test coverage**
273
274- Every new feature requires tests in the corresponding `tests/` directory
275- Commands must have test files (e.g., `src/commands/foo.ts` → `tests/commands/foo.test.ts`)
276- Utilities must have test files (e.g., `src/utils/bar.ts` → `tests/utils/bar.test.ts`)
277- Tests should cover:
278 - Success cases (happy path)
279 - Error cases (validation failures, network errors, etc.)
280 - Edge cases (empty input, boundary values, etc.)
281- Aim for high test coverage - tests are not optional
282
283Example test structure:
284```typescript
285describe('MyFeature', () => {
286 describe('successfulOperation', () => {
287 it('should handle valid input', async () => { /* ... */ });
288 it('should handle edge case', async () => { /* ... */ });
289 });
290
291 describe('errorHandling', () => {
292 it('should reject invalid input', async () => { /* ... */ });
293 it('should handle network errors', async () => { /* ... */ });
294 });
295});
296```
297
298#### Pull Request Checklist
299
300Before submitting code, verify:
301- [ ] All validation functions are in `validation.ts`
302- [ ] Comprehensive tests are written and passing
303- [ ] TypeScript compilation passes (`npm run typecheck`)
304- [ ] Linting passes (`npm run lint`)
305- [ ] All tests pass (`npm test`)
306
307### Technology Stack
308
309- **TypeScript 5.7.2** - Latest stable with strict mode enabled
310- **Node.js 22+** - Latest LTS target
311- **ES2023** - Latest stable ECMAScript target
312- **Biome** - Fast linter and formatter (replaces ESLint + Prettier)
313- **Vitest** - Fast unit test framework
314- **Commander.js** - CLI framework
315- **tsx** - Fast TypeScript execution for development