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
16 changes: 16 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -135,3 +135,19 @@ Before proposing new work, list `openspec/changes/` (excluding `archive/`) to se
- **plannotator** — `submit_plan` is for action plans the user will execute, not for plans that themselves produce more plans.
- **bash** — PowerShell 7+ (`pwsh`) on Windows. Use the `workdir` parameter instead of `cd`; don't change directories inside a command.
- **Delegation** — default to orchestrating subagents; batch parallel investigations; chain sequential work when output feeds the next step.

---

## Agent skills

### Issue tracker

GitHub Issues at `https://github.com/expert-vision-software/gemiterm/issues`. Use `gh` CLI. OpenSpec change dirs use the `tskNN-` prefix to mirror GitHub issue numbers one-to-one. See `docs/agents/issue-tracker.md`.

### Triage labels

Default five-role vocabulary (`needs-triage`, `needs-info`, `ready-for-agent`, `ready-for-human`, `wontfix`). See `docs/agents/triage-labels.md`.

### Domain docs

Single-context layout. Read `CONTEXT.md` at the repo root before exploring the codebase, and any ADRs in `docs/adr/` that touch the area. The phantom-auth bug history is in `docs/phantom-bug-synthesis.md` (write-once ledger). See `docs/agents/domain.md`.
80 changes: 80 additions & 0 deletions CONTEXT.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
# Domain Glossary — GemiTerm

Stable terminology for the auth and conversation modules. No implementation details; see source and specs for those.

---

## Auth concepts

### Cookie jar
The persisted collection of authentication cookies for a single profile, stored at `%APPDATA%\gemiterm\profiles\<name>\cookies.json` (Windows) or `~/gemiterm/profiles/<name>/cookies.json` (POSIX). Contains the long-lived identity cookie (`__Secure-1PSID`), the short-lived session cookie (`__Secure-1PSIDTS`), and companion auth cookies (`SID`, `HSID`, `SSID`, `APISID`, `SAPISID`, `__Secure-3PSID`, `SIDCC`, etc.). All API operations ultimately read from this jar.

### Capture-integrity
The property that the cookie-capture path (login flow, silentRefresh) stores the COMPLETE jar the browser holds, not a filtered subset. Violated when the capture path trims to a "required cookies" predicate before persisting; the symptom is that `models()` succeeds but `listChats` returns empty, because `listChats` requires companion cookies that the trimmed jar lacks.

### Phantom-auth session
A session state where `models()` succeeds (the PSID is server-accepted) but `listChats` returns empty (companion cookies are absent or stale). The freshness model says "valid"; the API reality says "broken". Distinguished from a **dead session** (RotateCookies returns 401/403) and a **fresh session** (every probe passes).

### Session state
The named condition of a profile's server-accepted credentials. Enumerated values: `Fresh | Phantom | Dead | Stale | Declined`. Computed from the probe result (models), the rotation result (rotateCookies), and the listChats result. Currently an implicit state machine inside `ProfileAuthManager.ensureAuthenticated`; an explicit classifier is proposed (Candidate C).

### Companion cookies
Auth cookies set alongside `__Secure-1PSID` and `__Secure-1PSIDTS` during the Google login envelope: `SID`, `HSID`, `SSID`, `APISID`, `SAPISID`, `__Secure-3PSID`, `__Secure-3PSIDTS`, `SIDCC`, `NID`. Required by `listChats`; NOT required by `models()` or `readChat(cid)` (in practice). Their absence is the proximate cause of phantom-auth.

### PSID-only probe
A server-side validity check using `models()` which succeeds with only `__Secure-1PSID` present. Insufficient as the sole auth gate because it cannot detect phantom-auth. See **Probe cache** below.

### Probe cache
A per-process, TTL-bounded memoization of the most recent `models()` probe result per profile (default 150 000 ms, overridable via `GEMITERM_PROBE_TTL_MS`). Distinct from the on-disk freshness check, which is purely local. Does NOT cache the `listChats` result; the phantom check re-issues on every L1-decline path.

### Recovery ladder
The escalation sequence `ensureAuthenticated` follows when its probe says "stale" or its rotation says "declined": L1 `RotateCookies` POST → targeted L2 silent refresh (when phantom is detected) → throw `AuthenticationError` to surface to headed reauth. Each rung has different failure modes; the ladder is the policy that maps session state to action.

---

## Auth-flow control

### Cookie capture path
The sequence by which cookies enter the persisted jar: headed browser → `playwright-cli` probe → `CookieMonitor` callback → `AuthService.extractCookies` → `CookieStorageService.saveCookiesForProfile`. Trimming anywhere in this path is a capture-integrity bug.

### Cookie rotation
A POST to `https://accounts.google.com/RotateCookies` with the current `.google.com` cookie header, asking Google for a fresh `__Secure-1PSIDTS`. Returns 200 with refreshed Set-Cookies; 401/403 if the session is server-dead. Throttled per-process to 600 s.

### Silent refresh (L2)
A headless-browser session that captures a fresh PSIDTS via the cookie-capture path without user interaction. Two modes: `full` (replaces jar via merge) and `targeted` (updates only PSIDTS-family cookies). The targeted mode exists because the full mode was found to corrupt the login's aligned cookie envelope.

---

## Conversation concepts

### Conversation threading
The property that a `sendMessage(cid)` call extends an existing conversation rather than starting a new one. Requires the SDK's positional metadata array `[cid, rid, rcid, null, null, null, null, null, null, ctx]` to carry `rid` and `rcid` from the conversation's last model turn. See [AGENTS.md](../AGENTS.md) for the session-metadata history.

### Chat metadata
A small per-conversation record `{ rid, rcid, ctx }` stored at `%APPDATA%\gemiterm\profiles\<name>\chat-metadata.json`. The `rid`/`rcid` slots are required for threading; `ctx` is a context-token slot used by some Gemini operations. Currently the metadata array layout leaks across 5 call sites — see Candidate B.

### Profile
A named collection of (cookies, chat metadata, conversation history) under a single Google login. Multiple profiles may coexist (`gemiterm auth -e <name>`); `getDefaultProfileName()` returns the active one.

---

## Test-layer concepts

### Regression net
A characterization-test layer that pins behaviour at the integration boundary (the seam where callers meet services), so internal restructuring cannot silently reintroduce known regressions. Distinct from per-method unit tests (which pin implementation) and from mediator-mocked CLI integration tests (which pin argv dispatch). Phase 0 of the auth-path architecture review is the regression net for the auth + chat modules.

### Cookie-aware fake
A test double at the `GeminiClientService` seam whose responses depend on the on-disk cookie jar's contents — specifically, `listChats` returns chats iff the jar carries the companions `listChats` requires. Replaces a ~1 h server-degradation wait with an instant local repro. Pattern established in `tests/services/cookie-jar-repro.test.ts` (commit `efab987`).

### Capture-trim bug
The historical defect (closed by commit `6bc51f6`) where `CookieMonitor` filtered the browser jar to `REQUIRED_COOKIES` before invoking the persistence callback, causing downstream `saveCookiesForProfile` to overwrite a full 39-cookie jar with a 4-cookie subset. The regression-net test for capture-integrity must assert the post-capture jar contains companions.

---

## See also

- `docs/phantom-bug-synthesis.md` — full investigation history; the authoritative source for "what the bug actually was"
- `openspec/specs/auth/spec.md` — committed requirements; the canonical specification
- `openspec/specs/phantom-auth-detection/spec.md` — capability spec for the probe contract
- `openspec/specs/silent-refresh-tightening/spec.md` — capability spec for silentRefresh
- `openspec/changes/archive/2026-08-07-cookie-jar-integrity/` — archived change; the capture-fix provenance
48 changes: 48 additions & 0 deletions docs/agents/domain.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
# Domain Docs

How the engineering skills should consume this repo's domain documentation when exploring the codebase.

## Before exploring, read these

- **`CONTEXT.md`** at the repo root, or
- **`CONTEXT-MAP.md`** at the repo root if it exists — it points at one `CONTEXT.md` per context. Read each one relevant to the topic.
- **`docs/adr/`** — read ADRs that touch the area you're about to work in. In multi-context repos, also check `src/<context>/docs/adr/` for context-scoped decisions.

If any of these files don't exist, **proceed silently**. Don't flag their absence; don't suggest creating them upfront. The `/domain-modeling` skill (reached via `/grill-with-docs` and `/improve-codebase-architecture`) creates them lazily when terms or decisions actually get resolved.

## File structure

Single-context repo (this repo):

```
/
├── CONTEXT.md
├── docs/
│ ├── adr/
│ ├── agents/
│ │ ├── issue-tracker.md
│ │ ├── domain.md
│ │ └── triage-labels.md
│ └── phantom-bug-synthesis.md ← write-once ledger of phantom-auth attempts
└── src/
```

## Use the glossary's vocabulary

When your output names a domain concept (in an issue title, a refactor proposal, a hypothesis, a test name), use the term as defined in `CONTEXT.md`. Don't drift to synonyms the glossary explicitly avoids.

If the concept you need isn't in the glossary yet, that's a signal — either you're inventing language the project doesn't use (reconsider) or there's a real gap (note it for `/domain-modeling`).

## Flag ADR conflicts

If your output contradicts an existing ADR, surface it explicitly rather than silently overriding:

> _Contradicts ADR-0007 (event-sourced orders) — but worth reopening because…_

## Bug-history convention

`docs/phantom-bug-synthesis.md` is a **write-once ledger** of every attempt to deal with the phantom-auth bug. New entries are appended when:
- A bug, symptom, or finding is reported AFTER a supposed fix was implemented and failed
- A new attempt (fix or refactor) is made

Past entries are not edited; only appended to. The doc preserves the full history of attempts, including which fixes worked and which regressed.
55 changes: 55 additions & 0 deletions docs/agents/issue-tracker.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
# Issue tracker: GitHub

Issues and specs for this repo live as GitHub issues. Use the `gh` CLI for all operations.

## Conventions

- **Create an issue**: `gh issue create --title "..." --body "..."`. Use a heredoc for multi-line bodies.
- **Read an issue**: `gh issue view <number> --comments`, filtering comments by `jq` and also fetching labels.
- **List issues**: `gh issue list --state open --json number,title,body,labels,comments --jq '[.[] | {number, title, body, labels: [.labels[].name], comments: [.comments[].body]}]'` with appropriate `--label` and `--state` filters.
- **Comment on an issue**: `gh issue comment <number> --body "..."`
- **Apply / remove labels**: `gh issue edit <number> --add-label "..."` / `--remove-label "..."`
- **Close**: `gh issue close <number> --comment "..."`

Infer the repo from `git remote -v` — `gh` does this automatically when run inside a clone.

## Pull requests as a triage surface

**PRs as a request surface: no.** _(Set to `yes` if this repo treats external PRs as feature requests; `/triage` reads this flag.)_

When set to `yes`, PRs run through the same labels and states as issues, using the `gh pr` equivalents:

- **Read a PR**: `gh pr view <number> --comments` and `gh pr diff <number>` for the diff.
- **List external PRs for triage**: `gh pr list --state open --json number,title,body,labels,author,authorAssociation,comments` then keep only `authorAssociation` of `CONTRIBUTOR`, `FIRST_TIME_CONTRIBUTOR`, or `NONE` (drop `OWNER`/`MEMBER`/`COLLABORATOR`).
- **Comment / label / close**: `gh pr comment`, `gh pr edit --add-label`/`--remove-label`, `gh pr close`.

GitHub shares one number space across issues and PRs, so a bare `#42` may be either — resolve with `gh pr view 42` and fall back to `gh issue view 42`.

## When a skill says "publish to the issue tracker"

Create a GitHub issue.

## When a skill says "fetch the relevant ticket"

Run `gh issue view <number> --comments`.

## Ticket-id prefix convention

OpenSpec changes use `tskNN-<short-kebab-name>` to mirror GitHub issue numbers one-to-one. Examples:

- `tsk12-phantom-bug-refactor-clock`
- `tsk01-phase0-regression-net-char`
- `tsk02-phase0-factory-coverage`

The `tskNN` prefix is the GitHub issue number. If the tracker number differs (e.g. issue #42 is the canonical id), use `tsk42-` instead. The OpenSpec change dir name is `openspec/changes/tsk<NN>-<name>/`.

## Wayfinding operations

Used by `/wayfinder`. The **map** is a single issue with **child** issues as tickets.

- **Map**: a single issue labelled `wayfinder:map`, holding the Notes / Decisions-so-far / Fog body. `gh issue create --label wayfinder:map`.
- **Child ticket**: an issue linked to the map as a GitHub sub-issue (`gh api` on the sub-issues endpoint). Where sub-issues aren't enabled, add the child to a task list in the map body and put `Part of #<map>` at the top of the child body. Labels: `wayfinder:<type>` (`research`/`prototype`/`grilling`/`task`). Once claimed, the ticket is assigned to the driving dev.
- **Blocking**: GitHub's **native issue dependencies** — the canonical, UI-visible representation. Add an edge with `gh api --method POST repos/<owner>/<repo>/issues/<child>/dependencies/blocked_by -F issue_id=<blocker-db-id>`, where `<blocker-db-id>` is the blocker's numeric **database id** (`gh api repos/<owner>/<repo>/issues/<n> --jq .id`, _not_ the `#number` or `node_id`). GitHub reports `issue_dependencies_summary.blocked_by` (open blockers only — the live gate). Where dependencies aren't available, fall back to a `Blocked by: #<n>, #<n>` line at the top of the child body. A ticket is unblocked when every blocker is closed.
- **Frontier query**: list the map's open children (`gh issue list --state open`, scoped to the map's sub-issues / task list), drop any with an open blocker (`issue_dependencies_summary.blocked_by > 0`, or an open issue in the `Blocked by` line) or an assignee; first in map order wins.
- **Claim**: `gh issue edit <n> --add-assignee @me` — the session's first write.
- **Resolve**: `gh issue comment <n> --body "<answer>"`, then `gh issue close <n>`, then append a context pointer (gist + link) to the map's Decisions-so-far.
15 changes: 15 additions & 0 deletions docs/agents/triage-labels.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
# Triage Labels

The skills speak in terms of five canonical triage roles. This file maps those roles to the actual label strings used in this repo's issue tracker.

| Label in mattpocock/skills | Label in our tracker | Meaning |
| -------------------------- | -------------------- | ---------------------------------------- |
| `needs-triage` | `needs-triage` | Maintainer needs to evaluate this issue |
| `needs-info` | `needs-info` | Waiting on reporter for more information |
| `ready-for-agent` | `ready-for-agent` | Fully specified, ready for an AFK agent |
| `ready-for-human` | `ready-for-human` | Requires human implementation |
| `wontfix` | `wontfix` | Will not be actioned |

When a skill mentions a role (e.g. "apply the AFK-ready triage label"), use the corresponding label string from this table.

Edit the right-hand column to match whatever vocabulary you actually use.
Loading
Loading