Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/auto-install-app.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@bradygaster/squad-cli': minor
---

Auto-open browser for GitHub App installation after manifest creation, with polling fallback
5 changes: 5 additions & 0 deletions .changeset/canonicalize-resolve-token.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@bradygaster/squad-cli': patch
---

Canonicalize `resolve-token.mjs`: single source at `packages/squad-cli/scripts/resolve-token.source.mjs`, new `sync:resolve-token` generator propagates to the four template copies, and a CI guard fails PRs if the copies drift. Internal refactor — no runtime behavior change.
6 changes: 6 additions & 0 deletions .changeset/env-var-credentials.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
'@bradygaster/squad-sdk': minor
'@bradygaster/squad-cli': minor
---

Support environment variable credentials for CI/CD workflows. `resolveToken()` now checks `SQUAD_{ROLE}_APP_ID`, `SQUAD_{ROLE}_PRIVATE_KEY`, and `SQUAD_{ROLE}_INSTALLATION_ID` before reading from filesystem. Added `squad identity export` subcommand to output `gh secret set` commands.
5 changes: 5 additions & 0 deletions .changeset/exec-with-role-token.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@bradygaster/squad-sdk': minor
---

Add `execWithRoleToken` and `withRoleToken` utilities for running shell commands or async functions under a role's GitHub App installation token, with graceful fallback and guaranteed GH_TOKEN restoration.
6 changes: 6 additions & 0 deletions .changeset/gitignore-identity-secrets.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
'@bradygaster/squad-sdk': patch
'@bradygaster/squad-cli': patch
---

Auto-ignore identity secrets on `squad init` and `squad upgrade`. `.squad/identity/keys/` (GitHub App private PEMs), `.squad/identity/apps/` (per-role installation metadata), `.squad/identity/config.json`, and per-role token caches matching `.squad-*-token` / `.squad-*-token.json` (e.g. `.squad-hermes-token` holding `ghs_*` installation tokens) are now appended to `.gitignore` so they cannot be accidentally committed.
Copy link

Copilot AI Apr 18, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The release note in this changeset claims init/upgrade will auto-append ignores for identity secrets (apps/, config.json, token caches, etc.), but this PR only adds .squad/identity/keys/ to the repo root .gitignore and does not update the init/upgrade gitignore enforcement lists (e.g. ensureGitignore()’s GITIGNORE_ENTRIES). Please either implement the described auto-ignore behavior or adjust this changeset text to match what actually ships.

Suggested change
Auto-ignore identity secrets on `squad init` and `squad upgrade`. `.squad/identity/keys/` (GitHub App private PEMs), `.squad/identity/apps/` (per-role installation metadata), `.squad/identity/config.json`, and per-role token caches matching `.squad-*-token` / `.squad-*-token.json` (e.g. `.squad-hermes-token` holding `ghs_*` installation tokens) are now appended to `.gitignore` so they cannot be accidentally committed.
Add `.squad/identity/keys/` to the repository root `.gitignore` so GitHub App private PEMs are less likely to be accidentally committed.

Copilot uses AI. Check for mistakes.
14 changes: 14 additions & 0 deletions .changeset/identity-consistency-fix.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
---
'@bradygaster/squad-cli': patch
'@bradygaster/squad-sdk': patch
---

fix(identity): cover all gh write commands and map reviewer roles to lead tier

- Template GIT IDENTITY block now uses session-level `export GH_TOKEN` pattern
so every `gh` write command (review, comment, merge, edit, issue comment)
uses the bot identity instead of falling through to the authenticated user.
- Added `code review`, `reviewer`, `watchdog` patterns to role-slug resolution
so compound roles like "Code Reviewer & Watchdog" route to the lead tier.
- Fixes the inconsistency seen on kickstart PRs #986/#989/#990 where reviewer
agents posted as the user instead of their bot identity.
6 changes: 6 additions & 0 deletions .changeset/identity-dedup-key-age.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
"@bradygaster/squad-sdk": minor
"@bradygaster/squad-cli": patch
---

Identity hardening: concurrent-fetch dedup (H-12), key-age warnings in `identity doctor`/`status` (H-14), and a sync cache-only resolver `resolveTokenSync` for hot paths (H-09).
23 changes: 23 additions & 0 deletions .changeset/identity-doctor-explain.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
---
"@bradygaster/squad-cli": minor
---

Add `squad identity doctor` and `squad identity explain` subcommands (H-10, H-11).

**`squad identity doctor`** — runs a 9-step live health check for each configured identity role:
config.json presence, app registration files, PEM key existence, PEM permissions (mode 0o600,
Unix/WSL only), PEM crypto validation via `createPrivateKey()`, `.gitignore` coverage, JWT
signing, live installation token fetch, and expected scope verification. Supports `--role <slug>`
to target one role, `--no-network` to skip network steps (offline mode), `--json` for structured
CI output. Exits 1 if any check fails.

**`squad identity explain <role>`** — traces the full token resolution path for a role without
side effects: input key + alias resolution, env var presence (values masked), filesystem file
inventory, token cache state, and the expected resolution source (`env / filesystem / mock /
none`). Use `--live` to actually fetch the token and confirm end-to-end. Always exits 0.

Also adds `peekTokenCache` and `getInstallationPermissions` to the SDK's identity module to
support inspection of cache state and permission verification.

Reference: [H-10](../../docs/proposals/identity-hardening-roadmap-2026-04-20.md#h-10) ·
[H-11](../../docs/proposals/identity-hardening-roadmap-2026-04-20.md#h-11)
17 changes: 17 additions & 0 deletions .changeset/identity-hardening.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
---
"@bradygaster/squad-sdk": minor
"@bradygaster/squad-cli": minor
---

feat(identity): hardening + kickstart sync quick wins

- **Structured error reporting** (`TokenResolveError`): typed `kind` field (`not-configured` | `runtime`) with human message
- **Fetch timeout** (H-01): `AbortController` + `Promise.race` 10-second cap on installation token requests
- **PEM validation** (H-02): `createPrivateKey()` validates key before signing; rejects with descriptive error
- **Partial env detection** (H-03): logs loud error when only 1-2 of 3 required env vars are set
- **Mock hook** (H-07): `SQUAD_IDENTITY_MOCK=1` bypasses real credentials; `SQUAD_IDENTITY_MOCK_TOKEN` sets custom token value
- **Role aliases**: `resolveRoleSlug()` maps shorthand aliases (`core`, `ui`, `qa`, `ops`, `writer`, `sec`, `ml`, `note`) to canonical role slugs
- **Scribe role**: `'scribe'` added to `RoleSlug` union; `ALL_ROLES` constant exported from SDK
- **ESM dual-mode guard**: `isCliInvocation` IIFE prevents CLI side-effects when `resolve-token.mjs` is imported as a module
- **`resolveTokenWithDiagnostics()`**: full diagnostic result type; `clearTokenCache()` for test isolation
- **Cache key fix**: token cache keyed by `${projectRoot}:${roleKey}` to prevent cross-test pollution
5 changes: 5 additions & 0 deletions .changeset/identity-import-multi-repo.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@bradygaster/squad-cli': minor
---

Add `--import` flag to `squad identity create` for multi-repo identity reuse. When a GitHub App already exists from another repo, `--import /path/to/source-repo` copies credentials and triggers installation on the current repo. Also improves error handling when app name is already taken, suggesting the `--import` flag.
10 changes: 10 additions & 0 deletions .changeset/identity-module.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
---
'@bradygaster/squad-sdk': minor
'@bradygaster/squad-cli': minor
---

Add identity module for GitHub App-based agent identity

New SDK module (`identity/`) with role slug resolution, credential storage,
and comment/commit attribution formatting. New CLI command `squad identity status`
shows configured identity tier, app registrations, and key status.
11 changes: 11 additions & 0 deletions .changeset/identity-retry-resilience.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
---
'@bradygaster/squad-sdk': minor
'@bradygaster/squad-cli': patch
---

**H-03: Retry with exponential backoff** — `resolveTokenWithDiagnostics` and `resolveToken` now accept an optional `retryPolicy` parameter. When provided, transient failures (network errors, 5xx, 429 with `Retry-After` support) are retried with configurable exponential backoff and ±20% jitter. Non-retryable errors (4xx except 429, `AbortError`/timeout, `not-configured`) propagate immediately. Adds `GitHubApiError`, `RetryExhaustedError` and `RetryPolicy` to the SDK public API. `TokenResolveError` gains a `retriesExhausted: boolean` field.

**PR #22 nit fixes:**
- N-1: `getInstallationPermissions` now makes a single `GET /installation` call (removed the redundant preflight to `/installation/repositories`).
- N-2: `getInstallationPermissions` uses a dedicated `AbortController` per fetch (was sharing one across two sequential calls).
- N-3: `squad identity doctor` mode-0o600 check now detects WSL drvfs paths (mode reported as `0o777`) and skips the assertion with a `⚠ skipped (drvfs)` detail instead of false-failing.
5 changes: 5 additions & 0 deletions .changeset/identity-rotate-command.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@bradygaster/squad-cli': minor
---

Add `squad identity rotate --role <role>` command for key rotation. Opens GitHub App settings for manual key regeneration, and supports `--import path/to/key.pem` to import a new PEM file and clear the token cache.
6 changes: 6 additions & 0 deletions .changeset/identity-token-lifecycle.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
'@bradygaster/squad-sdk': minor
'@bradygaster/squad-cli': minor
---

Add token lifecycle (JWT generation, installation token exchange, caching) and `squad identity create` command for GitHub App Manifest flow
8 changes: 8 additions & 0 deletions .changeset/identity-token-precedence-docs.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
---
"@bradygaster/squad-cli": patch
---

Docs: document GITHUB_TOKEN vs GH_TOKEN precedence (H-13) and remove unused test import

- Add `docs/identity/token-precedence.md` explaining how Squad agents choose between GITHUB_TOKEN and GH_TOKEN environment variables, with decision tables and troubleshooting
- Remove unused `withRetry` import from `test/identity/retry.test.ts` (PR #23 review nit)
5 changes: 5 additions & 0 deletions .changeset/team-aware-identity-create.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@bradygaster/squad-cli': minor
---

`squad identity create` is now team-aware: when run with no flags and `.squad/team.md` exists, it auto-detects roles from the team roster, deduplicates them, and creates GitHub Apps only for the team's actual roles.
5 changes: 5 additions & 0 deletions .changeset/wire-gh-token-spawn.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@bradygaster/squad-cli': minor
---

Wire GH_TOKEN injection into agent spawn logic. When an agent is spawned, its role is mapped to a canonical identity slug via `resolveRoleSlug()`, and `resolveToken()` is called to obtain an installation token. If a token is found, `process.env.GH_TOKEN` is set before creating the session so that `gh` CLI calls automatically use the bot identity. The token is always restored/cleaned up in a `finally` block. Identity failures are gracefully ignored — spawn works exactly as before when no identity is configured.
60 changes: 60 additions & 0 deletions .copilot/skills/injectable-random/SKILL.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
# Skill: Injectable Randomness for Deterministic Tests

**Owner:** EECOM
**Date:** 2026-04-21
**Status:** Active

---

## Problem

Code that uses `Math.random()` is hard to test deterministically. Jitter, random IDs, shuffle operations, and retry delays all suffer from this. Tests either ignore randomness (asserting only bounds) or use `vi.spyOn(Math, 'random')` — which is fragile and affects all code running in the test.

## Pattern

Expose a `random?: () => number` seam in any interface that drives randomness:

```typescript
interface RetryPolicy {
random?: () => number; // defaults to Math.random
}
```

In implementation, destructure with a default:

```typescript
const { random = Math.random } = policy;
const jitter = base * 0.2 * (2 * random() - 1);
```

In tests, inject a fixed value:

```typescript
// No jitter — exact base delay
retryPolicy: { random: () => 0.5 }

// Min delay (−20% jitter)
retryPolicy: { random: () => 0 }

// Max delay (+20% jitter)
retryPolicy: { random: () => 1 }
```

## When to use

- Retry backoff jitter
- Random ID / slug generation in code under test
- Any shuffle or sampling that must produce predictable output in tests

## When NOT to use

- Cryptographic randomness — never make `crypto.randomBytes` injectable; use real entropy
- Simple unit tests that only check success/failure (not delay values) — bound assertions suffice

## Alternative: spy on Math.random

`vi.spyOn(Math, 'random').mockReturnValue(0.5)` works but has two downsides:
1. Affects ALL code calling `Math.random` in that test, not just your function.
2. Requires `vi.restoreAllMocks()` discipline to avoid cross-test leakage.

The injectable seam is scoped — it only affects the function you're testing.
49 changes: 49 additions & 0 deletions .github/agents/squad.agent.md
Original file line number Diff line number Diff line change
Expand Up @@ -340,6 +340,10 @@ prompt: |
**WORKTREE:** Working in `{WORKTREE_PATH}`. All operations relative to this path. Do NOT switch branches.
{% endif %}

{only if identity configured:}
GIT IDENTITY: Commit as `{app_slug}[bot]`. Push with token: `TOKEN=$(node {team_root}/.squad/scripts/resolve-token.mjs '{role_slug}'); if [ -n "$TOKEN" ]; then git push https://x-access-token:${TOKEN}@github.com/{owner}/{repo}.git {branch}; else git push; fi`. PR: `if [ -n "$TOKEN" ]; then GH_TOKEN=$TOKEN gh pr create --repo {owner}/{repo} ...; else gh pr create ...; fi`. PR body: `🤖 [{app_slug}](https://github.com/apps/{app_slug})`.
{end identity block}

Comment thread
sabbour marked this conversation as resolved.
TASK: {specific task description}
TARGET FILE(S): {exact file path(s)}

Expand Down Expand Up @@ -694,6 +698,30 @@ The coordinator passes a **spawn manifest** (who ran, why, what mode, outcome) t

Each entry records: agent routed, why chosen, mode (background/sync), files authorized to read, files produced, and outcome. See `.squad/templates/orchestration-log.md` for the field format.

### Pre-Spawn: Identity Resolution

When spawning an agent that may do git operations (commit, push, PR), resolve the identity context:

1. **Check identity config:** Does `.squad/identity/config.json` exist?
- **No** → omit the identity block entirely. Agents use default auth.
- **Yes** → read the config to get the tier and app registrations.
Comment thread
sabbour marked this conversation as resolved.

2. **Resolve the role slug:** Map the agent's role to an identity role slug using `resolveRoleSlug()` semantics:
- Lead/Architect → `lead`
- Backend/Core Dev → `backend` (falls back to `lead` if no backend app)
- Frontend → `frontend` (falls back to `lead`)
- Tester → `tester` (falls back to `lead`)
- For `shared` tier: all agents use the single shared app
- For `per-role` tier: try role-specific app first, fall back to `lead`

3. **Get the app slug:** From the identity config, look up the app registration for the resolved role slug. The `appSlug` is the GitHub App's URL slug (e.g., `sabbour-squad-lead`).

4. **Get the repo owner/name:** From the git remote origin URL, parse `{owner}/{repo}`.

5. **Include the identity block** in the spawn prompt with the resolved values.

**If any step fails, omit the identity block silently.** Identity is always graceful — never block a spawn because identity resolution failed.

### Pre-Spawn: Worktree Setup

When spawning an agent for issue-based work (user request references an issue number, or agent is working on a GitHub issue):
Expand Down Expand Up @@ -811,6 +839,27 @@ prompt: |
MCP TOOLS: {service}: ✅ ({tools}) | ❌. Fall back to CLI when unavailable.
{end MCP block}

{only if .squad/identity/config.json exists — omit entirely if no identity configured:}
## GIT IDENTITY — Bot Authentication
This project uses GitHub App identity for git operations. When pushing code or creating PRs, authenticate as the bot.

**Resolve token at runtime:**
```bash
TOKEN=$(node {team_root}/.squad/scripts/resolve-token.mjs '{role_slug}')
```
If token resolution fails (no identity configured), fall back to default git auth — do NOT block on identity.

**Git commit identity:**
- `git -c user.name="{app_slug}[bot]" -c user.email="{app_slug}[bot]@users.noreply.github.com" commit ...`

**Push:** `if [ -n "$TOKEN" ]; then git push https://x-access-token:${TOKEN}@github.com/{owner}/{repo}.git {branch}; else git push; fi`
**PR create:** `if [ -n "$TOKEN" ]; then GH_TOKEN=$TOKEN gh pr create --repo {owner}/{repo} ...; else gh pr create ...; fi`
**PR body must include:** `🤖 Created by [{app_slug}](https://github.com/apps/{app_slug})`

**Never log or echo the token value.**
**Parallel safety:** Each agent resolves exactly one token. If you need multiple tokens in one shell block (e.g., batch operations), use newline-separated statements — NOT `&&` chains — before backgrounding with `&`. Bash variable scoping causes `&&`-chained assignments to lose values in child subshells.
{end identity block}

**Requested by:** {current user name}

INPUT ARTIFACTS: {list exact file paths to review/modify}
Expand Down
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,9 @@ docs/src/content/docs/reference/api/

# Docs test screenshots (local verification only)
docs/tests/screenshots/
# Squad: private keys must never be committed
.squad/identity/keys/

# Squad: SubSquad activation file (local to this machine)
.squad-workstream
.squad/.first-run
Expand Down
Loading
Loading