# KnowHub Team Sharing — UI Design Document

**Version:** 1.0 | **Date:** 2026-03-20 | **Status:** Design Proposal
**Authors:** Expert Panel (Product, Architecture, API, Security, Timeline)

---

## 1. Executive Summary

### What We Are Building

Team Sharing enables multiple AI agents to share vaults (knowledge repositories) within a team. Today, KnowHub's "Share" button simply exposes a raw access token — full read/write access to all vaults, with no scoping, no revocation, and no team structure. This is a security liability and a UX dead end.

The goal is to replace token-sharing with proper team-based access control: create teams, invite members, grant teams access to specific vaults with specific permissions (read/write/admin), and manage all of this through the KnowHub UI.

### Why It Matters

- **Security:** Current sharing exposes the owner's full-access token. Any recipient has god-mode access to every vault.
- **Collaboration:** Agents working in teams need shared knowledge bases. The Jagger Team workspace report demonstrates that agents collaborating on shared repos need structured access — not ad-hoc token passing.
- **Scalability:** As teams grow beyond 2-3 agents, token-based sharing becomes unmanageable. Who has access? What can they do? There is no audit trail.

### Critical Finding

**The agent-git-service at git.clawmem.ai does NOT currently support the team/org APIs required for this feature.** Our API testing (Section 6) proves that org creation, team creation, team membership, and team-repo grants all return 404. Additionally, anonymous users cannot make repositories public. This means the full Team Sharing feature is **blocked on backend work** and must be designed in phases.

---

## 2. API Dependency Matrix

### Testing Methodology

All endpoints were tested against `https://git.clawmem.ai/api/v3/` using token `14c1a...0a26` (user: `anonymous-6f77bf130226e4da9012e17c65c75`). Tests were conducted on 2026-03-20.

### Results

| API Endpoint | Method | Status | HTTP Code | Notes |
|---|---|---|---|---|
| `/user` | GET | **WORKS** | 200 | Returns authenticated user profile |
| `/user/repos` | GET | **WORKS** | 200 | Lists all user repositories |
| `/user/orgs` | GET | **WORKS** | 200 | Returns empty array (no orgs exist) |
| `/user/repos` | POST | **WORKS** | 201 | Can create new private repos |
| `/repos/:o/:r` | DELETE | **WORKS** | 204 | Can delete repos |
| `/repos/:o/:r/collaborators` | GET | **WORKS** | 200 | Lists collaborators with `permissions: {admin, pull, push}` |
| `/repos/:o/:r/forks` | GET | **WORKS** | 200 | Returns empty array |
| `/` | GET | **WORKS** | 200 | API root; lists: `current_user_url`, `organization_url`, `repository_url`, `user_url` |
| `/orgs/{org}` | GET | **MISSING** | 404 | No org auto-creation, no org lookup |
| `/orgs` | POST | **MISSING** | 404 | Cannot create organizations |
| `/orgs/{org}/teams` | POST | **MISSING** | 404 | Cannot create teams |
| `/user/teams` | GET | **MISSING** | 404 | Cannot list user's teams |
| `/repos/:o/:r/teams` | GET | **MISSING** | 404 | Cannot list teams with repo access |
| `/repos/:o/:r/teams/:team` | PUT | **MISSING** | 404 | Cannot grant team access to repo |
| `/repos/search` | GET | **MISSING** | 404 | No repository search |
| `/users/search` | GET | **MISSING** | 404 | No user search |
| `/users/:u/tokens` | GET | **MISSING** | 404 | No token management |
| `/repos/:o/:r/collaborators/:u/permission` | GET | **MISSING** | 404 | No permission check |
| `/repos/:o/:r/transfer` | PUT | **MISSING** | 404 | No repo transfer |
| `/repos/:o/:r` (set `private:false`) | PATCH | **BLOCKED** | 422 | `"anonymous repositories must remain private"` |
| `/version` | GET | **MISSING** | 404 | No version endpoint |
| `/admin/orgs` | GET | **MISSING** | 404 | No admin endpoints |

### Dependency Classification

| Capability | Required APIs | Status | Blocking? |
|---|---|---|---|
| **List own vaults** | `GET /user/repos` | Available | No |
| **List collaborators** | `GET /repos/:o/:r/collaborators` | Available | No |
| **Create vault** | `POST /user/repos` | Available | No |
| **Make vault public** | `PATCH /repos/:o/:r {private:false}` | Blocked (anonymous constraint) | **YES** |
| **Create organization** | `POST /orgs` | Missing | **YES** |
| **Create team** | `POST /orgs/{org}/teams` | Missing | **YES** |
| **Add team member** | `PUT /orgs/{org}/teams/{team}/members/{user}` | Missing | **YES** |
| **Grant team repo access** | `PUT /orgs/{org}/teams/{team}/repos/{owner}/{repo}` | Missing | **YES** |
| **Search users** | `GET /users/search` | Missing | **YES** |
| **Scoped tokens** | `POST /users/:u/tokens` | Missing | **YES** |
| **Add collaborator** | `PUT /repos/:o/:r/collaborators/:user` | Untested (no second user available) | Needs verification |

---

## 3. Expert Panel Discussion

### Expert 1: Product Designer

**Position:** Team sharing should feel native to KnowHub's existing information architecture — not bolted on. The current sidebar already has "MY VAULTS" and "SHARED VAULTS" sections. Teams should appear as a third concept that bridges the two.

**Proposed user flow:**

1. **Discover teams:** New sidebar section "TEAMS" between MY VAULTS and SHARED VAULTS.
2. **Create team:** Settings > Teams tab, or a "+" button in the Teams sidebar section. User names the team, gets an invite link/code.
3. **Invite members:** Team settings page with a member list. Owner searches for users (by login) and sends invites. Or shares an invite code.
4. **Share vault with team:** On vault detail, the existing "Share" button opens an upgraded modal. Instead of just showing a raw token, it offers: (a) "Share with Team" — pick a team, set permission level (read/write/admin), (b) "Share via Token" — legacy behavior, with stronger warnings.
5. **Team vault view:** When a team has shared vaults, they appear in the "SHARED VAULTS" sidebar section (or a new "TEAM VAULTS" section) with the team name as a group label.

**Challenges raised:**
- The "anonymous user" constraint means users on git.clawmem.ai cannot currently make repos public. This fundamentally limits the "shared vaults" concept — they can only work through collaborator/team access, not public visibility.
- User search is missing. Without it, adding team members requires knowing exact usernames. This is a terrible UX for a collaboration feature.

**Expert 2's challenge:** "How do you handle the case where the backend APIs don't exist? You're designing screens for features that can't be built."

**Response:** "We design in phases. Phase 0 ships with what exists today — improved Share modal with better warnings and collaborator visibility. Phase 1 ships when team APIs land. The UI scaffolding can be built ahead of time behind a feature flag."

---

### Expert 2: Frontend Architect

**Position:** The component architecture should extend, not replace, what exists. The codebase is clean and well-structured. Here is what needs to be built:

**New components needed:**

```
frontend/src/components/
  team-sharing-modal.tsx      // Replaces share-vault-modal.tsx
  team-list.tsx               // Sidebar team section
  team-settings-panel.tsx     // Team management (members, repos)
  team-member-row.tsx         // Individual member in team settings
  team-vault-grant-row.tsx    // Vault permission row
  user-search-input.tsx       // Autocomplete user search
  permission-badge.tsx        // Read/Write/Admin badge

frontend/src/app/
  teams/page.tsx              // Team list page
  teams/[slug]/page.tsx       // Team detail page (members + vaults)

frontend/src/lib/
  team-api.ts                 // Team-specific API functions
  use-teams.ts                // useTeams, useTeamMembers hooks
```

**Integration with existing architecture:**

- `sidebar.tsx` gets a new "TEAMS" section (line ~99-167 area, between MY VAULTS and SHARED VAULTS).
- `types.ts` gets new types: `Team`, `TeamMember`, `TeamVaultGrant`.
- `api.ts` gets team-related API functions (or separate `team-api.ts` to keep it clean).
- `use-data.ts` pattern is replicated: `useTeams()`, `useTeamMembers(teamId)`, `useTeamVaults(teamId)`.

**Data hooks pattern (follows existing `useVaults` pattern):**

```typescript
// Follows the exact same pattern as useVaults in use-data.ts
function useTeams(): { teams: Team[]; loading: boolean; error: string | null }
function useTeamMembers(teamSlug: string): { members: TeamMember[]; loading: boolean }
function useTeamVaults(teamSlug: string): { vaults: TeamVaultGrant[]; loading: boolean }
```

**Performance considerations:**
- Network latency to git.clawmem.ai is ~300ms per call. Team data should be loaded once and cached in a React context or SWR-like pattern.
- The current `useVaults` hook makes N+1 API calls (1 for repo list + 3 per repo for counts). Adding team data should not multiply this further.
- Team membership and vault grants should be loaded lazily — only when the user navigates to team settings.

**Expert 3's challenge:** "You're designing a component tree for APIs that return 404. What can actually be built today?"

**Response:** "Today we can build: (1) an improved ShareVaultModal that shows current collaborators (the collaborators API works), (2) the UI scaffolding with a feature flag, (3) the Settings > Teams tab as a placeholder that explains team sharing is coming. The component architecture is ready for when APIs land."

---

### Expert 3: API Integration Expert

**Position:** The API situation is far worse than expected. Based on testing, here is the honest assessment:

**What actually works today:**
1. Repo CRUD (create, read, delete) — confirmed.
2. Collaborator listing — confirmed. Returns users with `permissions: {admin: true, pull: true, push: true}`.
3. Fork listing — confirmed (empty, but the endpoint exists).
4. User profile — confirmed.
5. User org listing — confirmed (empty array).

**What is completely absent:**
1. **All organization APIs** — cannot create, get, list, or manage orgs.
2. **All team APIs** — cannot create teams, manage membership, or grant repo access.
3. **User search** — cannot find users to invite.
4. **Token management** — cannot create scoped tokens.
5. **Visibility toggle** — anonymous users cannot make repos public (server-enforced).
6. **Permission check** — `collaborators/:user/permission` returns 404.

**Critical analysis of the agent-git-service design document (PR #907):**

The design document describes:
- `TeamRepository` model with `permission` field (read/write/admin)
- `HasRepoAccess` function: owner -> collaborator -> team member chain
- APIs: `PUT /orgs/{org}/teams/{team}/repos/{owner}/{repo}`, `GET /orgs/{org}/teams/{team}/repos`, `DELETE`, `PUT /orgs/{org}/teams/{team}/members/{user}`, `GET /orgs/{org}/teams/{team}/members`
- Phased: Phase 1 (CRUD), Phase 2 (enforcement), Phase 3 (tokens)

**Reality check:** None of Phase 1 is deployed. The API root at git.clawmem.ai lists only 4 URL templates: `current_user_url`, `organization_url`, `repository_url`, `user_url`. The `organization_url` template exists but returns 404 for any org name. This suggests the URL routing is defined but the handler is not implemented.

**What can we build with collaborators API:**

The collaborators endpoint (`GET /repos/:o/:r/collaborators`) works and returns permission data. This means we can:
- Show who currently has access to a vault
- Display their permission level (admin/push/pull maps to admin/write/read)

We cannot yet:
- Add collaborators (untested — needs a second user account)
- Set granular permissions on collaborators
- Group collaborators into teams

**Expert 4's challenge:** "If we can't even add collaborators, what's the point of showing them?"

**Response:** "Transparency. Today the Share modal shows a raw token with zero context about who has access. Even showing 'You are the only collaborator' is more informative. And when the collaborator PUT API is confirmed, we can add 'Invite collaborator' immediately."

---

### Expert 4: Security Expert

**Position:** The current sharing model is a security incident waiting to happen. The Share modal exposes the user's full-access token — the same token used for authentication. This means:

1. **No scoping** — the token grants access to ALL vaults, not just the shared one.
2. **No revocation** — revoking the token locks out the owner themselves.
3. **No audit** — no way to know who used the token or when.
4. **No expiration** — tokens live forever once shared.

**Current state of share-vault-modal.tsx:**

The modal (lines 47-53) already warns: "Full access token. Anyone with this token has complete read/write access to all your vaults." This is accurate and honest, but the solution is to replace the mechanism, not just warn about it.

**Security recommendations by phase:**

**Phase 0 (immediate, no API dependency):**
- Add a "Who has access" section to the Share modal showing collaborators from the API.
- Add a "Danger zone" label to the token section.
- Add a confirmation step before revealing the token ("I understand this grants full access").
- Log share actions locally (localStorage) so the user can see when they last shared.

**Phase 1 (when team APIs land):**
- Team-based sharing replaces token sharing as the primary flow.
- Permissions are explicit: read (can view vault content), write (can create/edit content), admin (can manage team membership).
- The token-sharing option moves to an "Advanced" section with stronger warnings.

**Phase 2 (when scoped tokens land):**
- Generate read-only tokens scoped to a single vault.
- Tokens have expiration dates.
- Token revocation dashboard in Settings.

**Token sharing vs team sharing:**
- Token sharing is fundamentally "bearer auth" — whoever has the token has access. It's the worst model for collaboration.
- Team sharing is identity-based — access is tied to a user account, can be revoked per-user, and supports different permission levels.
- Recommendation: Phase out token sharing entirely once team sharing is stable. Keep it only as a fallback for environments without org/team support.

**Expert 5's challenge:** "Scoped tokens are Phase 3 in the agent-git-service plan. That's months away. What do we do in the meantime?"

**Response:** "In the meantime, we make the current sharing more transparent and add friction. The collaborator list shows who has access. The confirmation dialog makes users think before sharing. And we document that token sharing is a temporary measure. The security story improves incrementally."

---

### Expert 5: Timeline Expert

**Position:** Realistic timelines must account for three categories of work: (A) what we can ship with current APIs, (B) what we can scaffold behind feature flags, and (C) what is blocked.

**Phase 0 — Ship with current APIs (Week 1-2):**

| Task | Effort | Dependency |
|---|---|---|
| Redesign ShareVaultModal with collaborator list | 2 days | Collaborators API (works) |
| Add confirmation step before token reveal | 0.5 days | None |
| Add "Who has access" section | 1 day | Collaborators API (works) |
| Add Team types to types.ts (future-proofing) | 0.5 days | None |
| Add Settings > Teams tab (placeholder) | 1 day | None |
| **Total** | **~5 days** | |

**Phase 1 — When org/team CRUD APIs land (Week 3-5, assuming APIs ship Week 2):**

| Task | Effort | Dependency |
|---|---|---|
| Team creation flow (Settings > Teams) | 3 days | `POST /orgs`, `POST /orgs/{org}/teams` |
| Team member management | 2 days | `PUT /orgs/{org}/teams/{team}/members/{user}` |
| User search/invite | 2 days | `GET /users/search` or user lookup |
| Sidebar Teams section | 1 day | `GET /user/teams` |
| Team vault sharing (upgraded Share modal) | 2 days | `PUT /orgs/{org}/teams/{team}/repos/{o}/{r}` |
| Team vault list in sidebar | 1 day | Team repos API |
| Testing + polish | 2 days | All above |
| **Total** | **~13 days** | |

**Phase 2 — When enforcement + scoped tokens land (Week 6-8):**

| Task | Effort | Dependency |
|---|---|---|
| Permission enforcement UI (read-only vs write indicators) | 2 days | Phase 2 enforcement |
| Scoped token generation UI | 2 days | `POST /users/:u/tokens` |
| Token management dashboard (Settings > Security) | 2 days | Token listing API |
| Deprecate raw token sharing | 1 day | Scoped tokens working |
| **Total** | **~7 days** | |

**Realistic caveats:**
- **API latency:** git.clawmem.ai has ~300ms round-trip. Any UI that chains API calls (e.g., fetch teams -> fetch members -> fetch repos) will feel slow without caching.
- **agent-git-service deployment:** The team repo sharing PR (#907) is described in the design doc but not yet deployed. We have no committed ship date from the backend team.
- **Anonymous user constraint:** The error "anonymous repositories must remain private" suggests the server treats these users specially. Team sharing may require non-anonymous (named) user accounts, which could require an auth flow change.
- **No user search:** Without user search, inviting team members requires knowing exact usernames. This is a significant UX gap that may require a workaround (invite codes, or manual username entry).

**Expert 1's challenge:** "You're giving 5+ weeks for a feature where we can't build 80% of it today. Should we even start?"

**Response:** "Phase 0 is independently valuable — it makes the current sharing safer and more transparent. It ships in under a week. Phase 1 scaffolding can be built behind a flag so we're ready the day APIs land. The risk is spending time on Phase 1 UI before confirming the API contract, but the design doc is specific enough to build against."

---

## 4. UI Design

### 4.1 Updated Sidebar

```
+-------------------------------------------+
| KnowHub                           [<] [>] |
+-------------------------------------------+
| [Search...]                        Cmd+K  |
+-------------------------------------------+
| [Home icon]  Home                          |
+-------------------------------------------+
| MY VAULTS                                  |
|   [Lock] c99a3ba1ca316f0de551...           |
|   [Lock] 04cb29ef29c6eb895f33...           |
+-------------------------------------------+
| TEAMS                    [Phase 1]  [+]    |
|   [Users] DB9 Team                         |
|   [Users] Frontend Squad                   |
+-------------------------------------------+
| SHARED VAULTS                              |
|   [Globe] db9-shared-knowledge             |
+-------------------------------------------+
| [avatar] anonymous-6f77bf...               |
|          git.clawmem.ai                    |
| [Settings icon] Settings                   |
| [Logout icon]   Sign out                   |
+-------------------------------------------+
```

The TEAMS section appears between MY VAULTS and SHARED VAULTS. In Phase 0, it shows a placeholder message: "Team sharing coming soon." In Phase 1, it lists teams with a [+] create button.

### 4.2 Upgraded Share Modal (Phase 0 — Shippable Now)

```
+-----------------------------------------------------+
|  Share Vault                                    [X]  |
+-----------------------------------------------------+
|                                                      |
|  WHO HAS ACCESS                                      |
|  +-----------------------------------------------+  |
|  | [avatar] anonymous-6f77bf1... (you)    admin   |  |
|  +-----------------------------------------------+  |
|  | Only you have access to this vault.            |  |
|  +-----------------------------------------------+  |
|                                                      |
|  ---- Share with Team [Phase 1 — coming soon] ----   |
|                                                      |
|  +-----------------------------------------------+  |
|  | Team sharing lets you grant read or write      |  |
|  | access to specific teams. Available when your  |  |
|  | server supports team management.               |  |
|  +-----------------------------------------------+  |
|                                                      |
|  ---- or share via token (advanced) ----             |
|                                                      |
|  [!] DANGER: Full access token                       |
|  Anyone with this token has complete read/write      |
|  access to ALL your vaults — not just this one.      |
|                                                      |
|  [ I understand the risks — reveal token ]           |
|                                                      |
|  (after clicking:)                                   |
|  SERVER URL                                          |
|  [ https://git.clawmem.ai/api/v3       ] [Copy]     |
|                                                      |
|  ACCESS TOKEN                                        |
|  [ 14c1a4de••••••••••••••••••••0a26     ] [Copy]     |
|                                                      |
|  ---- or copy as config ----                         |
|  CONNECTION CONFIG                          [Copy]   |
|  {                                                   |
|    "baseUrl": "...",                                 |
|    "authScheme": "token",                            |
|    "token": "..."                                    |
|  }                                                   |
|                                                      |
|  +-----------------------------------------------+  |
|  | [Shield] The recipient pastes this into        |  |
|  | KnowHub's login page or their agent config.   |  |
|  +-----------------------------------------------+  |
|                                            [ Done ]  |
+-----------------------------------------------------+
```

Key changes from current `share-vault-modal.tsx`:
1. **"Who has access" section** at the top — pulls from collaborators API.
2. **Team sharing placeholder** — visible but disabled, educates users about what's coming.
3. **Token section hidden behind confirmation** — adds friction to prevent accidental sharing.
4. **"DANGER" label** instead of just "warning" — clearer severity signal.

### 4.3 Team Creation Flow (Phase 1)

```
Settings > Teams

+-----------------------------------------------------+
|  Teams                              [ Create Team ]  |
+-----------------------------------------------------+
|                                                      |
|  You are not a member of any teams yet.              |
|                                                      |
|  Teams let multiple agents share vaults with         |
|  controlled permissions. Create a team to get        |
|  started.                                            |
|                                                      |
+-----------------------------------------------------+

(After clicking Create Team:)

+-----------------------------------------------------+
|  Create Team                                    [X]  |
+-----------------------------------------------------+
|                                                      |
|  TEAM NAME                                           |
|  [ DB9 Team                               ]         |
|                                                      |
|  DESCRIPTION (optional)                              |
|  [ Shared knowledge for the DB9 project   ]         |
|                                                      |
|  This will create an organization on your server     |
|  and a team within it.                               |
|                                                      |
|                     [ Cancel ]  [ Create Team ]      |
+-----------------------------------------------------+
```

### 4.4 Team Detail Page (Phase 1)

```
/teams/db9-team

+-----------------------------------------------------+
|  < Back to Teams                                     |
|                                                      |
|  DB9 Team                                            |
|  Shared knowledge for the DB9 project                |
|                                                      |
|  [Members (3)]  [Shared Vaults (2)]  [Settings]     |
+-----------------------------------------------------+

Members tab:
+-----------------------------------------------------+
|  MEMBERS                            [ Add Member ]   |
+-----------------------------------------------------+
|  [avatar] alice-agent          admin    [Remove]     |
|  [avatar] bob-agent            write    [v]          |
|  [avatar] charlie-agent        read     [v]          |
+-----------------------------------------------------+

Shared Vaults tab:
+-----------------------------------------------------+
|  SHARED VAULTS                     [ Add Vault ]     |
+-----------------------------------------------------+
|  [Lock] 04cb29ef29c6eb...    write    [v] [Remove]  |
|  [Lock] c99a3ba1ca316f...    read     [v] [Remove]  |
+-----------------------------------------------------+

[v] = permission dropdown (read / write / admin)
```

### 4.5 Team Vault Sharing (Phase 1 — Upgraded Share Modal)

```
+-----------------------------------------------------+
|  Share Vault                                    [X]  |
+-----------------------------------------------------+
|                                                      |
|  WHO HAS ACCESS                                      |
|  +-----------------------------------------------+  |
|  | [avatar] you (owner)                   admin   |  |
|  | [users]  DB9 Team (3 members)          write   |  |
|  +-----------------------------------------------+  |
|                                                      |
|  SHARE WITH TEAM                                     |
|  +-----------------------------------------------+  |
|  | Team:       [ DB9 Team            v ]          |  |
|  | Permission: [ Write               v ]          |  |
|  |                                                |  |
|  |                          [ Grant Access ]      |  |
|  +-----------------------------------------------+  |
|                                                      |
|  ---- or share via token (advanced) ----             |
|  (collapsed by default, same as Phase 0)             |
|                                                      |
|                                            [ Done ]  |
+-----------------------------------------------------+
```

---

## 5. Implementation Plan

### Phase 0: Improved Sharing Transparency (No Backend Dependency)

**Goal:** Make current sharing safer and more informative. Ships independently.

**Changes to existing files:**

| File | Change |
|---|---|
| `frontend/src/components/share-vault-modal.tsx` | Major rewrite: add collaborator list, confirmation gate, danger zone styling |
| `frontend/src/lib/api.ts` | Add `fetchCollaborators(owner, repo)` function |
| `frontend/src/lib/types.ts` | Add `Collaborator` type, `Team` type (for future), `TeamVaultGrant` type (for future) |
| `frontend/src/components/sidebar.tsx` | Add placeholder TEAMS section (behind feature check) |

**New files:**

| File | Purpose |
|---|---|
| `frontend/src/lib/team-api.ts` | Stub file with team API functions that check server capabilities |

**API calls used:**
- `GET /repos/:owner/:repo/collaborators` — already works, returns users with permissions.

**Estimated effort:** 5 working days.

### Phase 1: Team CRUD (Requires Backend Phase 1)

**Goal:** Create teams, manage members, share vaults with teams.

**BLOCKED ON:** agent-git-service deploying org/team CRUD APIs.

**Required backend APIs (all currently return 404):**
- `POST /orgs` — create organization
- `POST /orgs/{org}/teams` — create team within org
- `PUT /orgs/{org}/teams/{team}/members/{user}` — add team member
- `GET /user/teams` — list current user's teams
- `PUT /orgs/{org}/teams/{team}/repos/{owner}/{repo}` — grant team access to vault
- `GET /orgs/{org}/teams/{team}/repos` — list team's vaults
- `GET /users/search` or `GET /users/{username}` — find users to invite

**New files:**

| File | Purpose |
|---|---|
| `frontend/src/app/teams/page.tsx` | Team list page |
| `frontend/src/app/teams/[slug]/page.tsx` | Team detail (members + vaults) |
| `frontend/src/components/team-create-modal.tsx` | Create team flow |
| `frontend/src/components/team-member-row.tsx` | Member management row |
| `frontend/src/components/team-vault-grant-row.tsx` | Vault permission row |
| `frontend/src/components/user-search-input.tsx` | User search autocomplete |
| `frontend/src/components/permission-badge.tsx` | Read/Write/Admin badge |
| `frontend/src/lib/use-teams.ts` | `useTeams`, `useTeamMembers`, `useTeamVaults` hooks |

**Changes to existing files:**

| File | Change |
|---|---|
| `frontend/src/components/sidebar.tsx` | TEAMS section with real data |
| `frontend/src/components/share-vault-modal.tsx` | "Share with Team" section enabled |
| `frontend/src/lib/team-api.ts` | Full implementation of team API functions |
| `frontend/src/lib/types.ts` | `Team`, `TeamMember`, `TeamVaultGrant` types finalized |

**Estimated effort:** 13 working days after APIs are available.

### Phase 2: Enforcement + Scoped Tokens (Requires Backend Phase 2-3)

**Goal:** Permission enforcement in UI, scoped token generation, token management.

**BLOCKED ON:** agent-git-service Phase 2 (enforcement) and Phase 3 (tokens).

**Changes:**

| Task | Details |
|---|---|
| Read-only vault indicators | When user has `read` permission, hide edit/delete/upload buttons |
| Scoped token generation | New UI in Share modal: generate a read-only token for a single vault |
| Token management dashboard | Settings > Security: list active tokens, revoke, see last used |
| Deprecate raw token sharing | Remove "Share via Token" or make it require admin permission |

**Estimated effort:** 7 working days after APIs are available.

---

## 6. Evidence: API Test Results

### Test 1: Authenticated User
```
GET /user -> 200
Response: { login: "anonymous-6f77bf130226e4da9012e17c65c75", type: "User", site_admin: false }
```

### Test 2: User Repositories
```
GET /user/repos -> 200
Response: 2 repos, both private:
  - anonymous-6f77bf.../04cb29ef29c6eb895f3394624792b64f (description: "Shared memory repo for the DB9 team")
  - anonymous-6f77bf.../c99a3ba1ca316f0de5516dacca783aaa (description: "")
```

### Test 3: Organization Lookup (Auto-Creation)
```
GET /orgs/test-org-probe -> 404
Response: { error: "Not Found", message: "Not Found" }
CONCLUSION: No org auto-creation. Orgs do not exist on this server.
```

### Test 4: Organization Creation
```
POST /orgs { username: "knowhub-test-team", visibility: "public" } -> 404
Response: { error: "Not Found", message: "Not Found" }
CONCLUSION: Org creation endpoint is not implemented.
```

### Test 5: Team Creation
```
POST /orgs/test-org-probe/teams { name: "test-team-probe" } -> 404
CONCLUSION: Team creation endpoint is not implemented.
```

### Test 6: User Teams
```
GET /user/teams -> 404
CONCLUSION: User teams endpoint is not implemented.
```

### Test 7: Repo Teams
```
GET /repos/:owner/:repo/teams -> 404
CONCLUSION: Repo teams endpoint is not implemented.
```

### Test 8: Collaborators (WORKS)
```
GET /repos/anonymous-6f77bf.../04cb29ef29c6eb895f3394624792b64f/collaborators -> 200
Response: [{ login: "anonymous-6f77bf...", permissions: { admin: true, pull: true, push: true } }]
CONCLUSION: Collaborator listing works. Shows owner with full permissions.
```

### Test 9: Repo Visibility Toggle
```
PATCH /repos/:owner/:repo { private: false } -> 422
Response: { error: "validation failed: anonymous repositories must remain private" }
CONCLUSION: Anonymous users cannot make repos public. This is a server-enforced constraint
that blocks the current "Shared Vaults" concept for anonymous users.
```

### Test 10: Repo Creation/Deletion
```
POST /user/repos { name: "sharing-probe-test", private: false } -> 201
DELETE /repos/:owner/sharing-probe-test -> 204
CONCLUSION: Repo CRUD works. Note: repo was created as private despite requesting
private:false (anonymous constraint).
```

### Test 11: User Search
```
GET /users/search?q=anon -> 404
CONCLUSION: User search is not implemented. This blocks member invitation UX.
```

### Test 12: Token Management
```
GET /users/:user/tokens -> 404
CONCLUSION: Token management is not implemented. Blocks scoped token feature.
```

### Test 13: API Root
```
GET / -> 200
Response: {
  current_user_url: "https://git.clawmem.ai/api/v3/user",
  organization_url: "https://git.clawmem.ai/api/v3/orgs/{org}",
  repository_url: "https://git.clawmem.ai/api/v3/repos/{owner}/{repo}",
  user_url: "https://git.clawmem.ai/api/v3/users/{user}"
}
CONCLUSION: API root lists org URL template but org endpoints are not functional.
Only user and repo endpoints work.
```

### Test 14: Fork API
```
GET /repos/:owner/:repo/forks -> 200 (empty array)
POST /repos/:owner/:repo/forks -> 422 (duplicate entry error — cannot self-fork)
CONCLUSION: Fork listing works but forking is not a viable sharing mechanism.
```

### Test 15: Collaborator Permission Check
```
GET /repos/:owner/:repo/collaborators/:user/permission -> 404
CONCLUSION: Per-user permission check endpoint not implemented.
Must rely on collaborators list endpoint (which does include permission data).
```

---

## 7. Blockers

### Critical Blockers (Cannot Build Without These)

| # | Blocker | Impact | Required API | Owner |
|---|---|---|---|---|
| B1 | **Org/Team APIs not implemented** | Cannot create teams, manage membership, or grant vault access | `POST /orgs`, `POST /orgs/{org}/teams`, team membership APIs | agent-git-service team |
| B2 | **User search not implemented** | Cannot find users to invite to teams | `GET /users/search` or equivalent | agent-git-service team |
| B3 | **Anonymous user visibility constraint** | Anonymous repos must remain private; shared vaults via visibility are impossible | Server-side policy change or named user accounts | agent-git-service team |

### Medium Blockers (Workarounds Exist)

| # | Blocker | Workaround |
|---|---|---|
| B4 | No scoped tokens | Continue with full-access token sharing (with stronger warnings) until Phase 3 |
| B5 | No collaborator add/remove API verified | Could not test PUT/DELETE collaborators (need second user). May work. |
| B6 | No permission check endpoint | Use collaborators list with permissions field instead |

### Assumptions That Need Validation

| # | Assumption | Risk if Wrong |
|---|---|---|
| A1 | agent-git-service will implement team APIs matching the PR #907 design doc | Entire Phase 1 UI design may need revision |
| A2 | Team-repo permissions (read/write/admin) will map to collaborator permissions | Permission model mismatch would require UI redesign |
| A3 | Non-anonymous user accounts will be supported | Without named users, team membership is meaningless |
| A4 | `PUT /repos/:o/:r/collaborators/:user` will work for adding collaborators | If not, even Phase 0+ collaboration is blocked |

---

## 8. Jagger Team Workspace Report

The Jagger Team Shared Workspace report (PR #907 context) could not be fetched — the GitHub repository `634750802/jagger-team-0-shared-workspace` returned 404. This may indicate:

1. The repository is private or has been renamed.
2. The report has not yet been published.
3. The URL path has changed.

**Impact:** Without the report, our design is based solely on the agent-git-service design document and our own API testing. We lack:
- Real-world experience data on how agents collaborate in shared repos.
- Implementation challenge details from an actual team-sharing build.
- Recommendations from practitioners who have built and tested this flow.

**Recommendation:** Request the Jagger Team report through an alternative channel. The findings should be incorporated into this design before Phase 1 implementation begins, as they may reveal UX requirements not covered by the API design alone.

---

## 9. New Types (types.ts additions for Phase 0+)

```typescript
// Team — an organization+team on the git service
export interface Team {
  id: number;
  name: string;          // human-readable team name
  slug: string;          // URL-safe slug
  orgName: string;       // parent organization name
  description: string;
  memberCount: number;
  repoCount: number;
  permission: 'read' | 'write' | 'admin';  // default permission for new repos
  createdAt: string;
}

// TeamMember — a user in a team
export interface TeamMember {
  id: number;
  login: string;
  avatarUrl: string;
  role: 'member' | 'maintainer';  // team-level role
  joinedAt: string;
}

// TeamVaultGrant — a vault shared with a team
export interface TeamVaultGrant {
  teamId: number;
  teamName: string;
  vaultFullName: string;
  permission: 'read' | 'write' | 'admin';
  grantedAt: string;
  grantedBy: string;
}

// Collaborator — a user with access to a vault (available NOW via API)
export interface Collaborator {
  id: number;
  login: string;
  avatarUrl: string;
  permissions: {
    admin: boolean;
    push: boolean;
    pull: boolean;
  };
}
```

---

## 10. Decision Log

| # | Decision | Rationale | Date |
|---|---|---|---|
| D1 | Ship Phase 0 independently without waiting for team APIs | Improves security and transparency with zero backend dependency | 2026-03-20 |
| D2 | Use org+team model (not collaborator-only) | Matches agent-git-service design doc; supports multi-vault sharing per team | 2026-03-20 |
| D3 | Hide token behind confirmation in Share modal | Reduces accidental full-token exposure | 2026-03-20 |
| D4 | Add TEAMS sidebar section even in Phase 0 (as placeholder) | Educates users, reduces surprise when feature launches | 2026-03-20 |
| D5 | Map git permissions: pull=read, push=write, admin=admin | Matches GitHub API convention used by agent-git-service | 2026-03-20 |
| D6 | Do not design for public/shared vaults via visibility toggle | Server enforces "anonymous repositories must remain private" | 2026-03-20 |

---

## 11. Open Questions

1. **When will agent-git-service deploy Phase 1 (team CRUD)?** No committed date. Phase 1 UI work is blocked on this.
2. **Will non-anonymous user accounts be supported?** Current users are anonymous hashes. Team collaboration requires identifiable users.
3. **What is the team-to-org mapping?** Does each KnowHub "team" map to one org with one team, or one org with multiple teams?
4. **Can we test `PUT /repos/:o/:r/collaborators/:user`?** Need a second user account on git.clawmem.ai to verify.
5. **What happens to existing token-shared access when we migrate to teams?** Need a migration path.
6. **Does the Jagger Team report contain UX recommendations we should incorporate?** Report was inaccessible (404).

---

_This document is based on actual API testing against git.clawmem.ai on 2026-03-20. All claims about API availability are backed by curl test results in Section 6. No API behavior was assumed without testing._
