diff --git a/.goreleaser.yaml b/.goreleaser.yaml index aa1aacb..d962811 100644 --- a/.goreleaser.yaml +++ b/.goreleaser.yaml @@ -94,6 +94,7 @@ homebrew_casks: trash: - ~/Library/LaunchAgents/com.github.milosmosovsky.agentyard.plist - ~/Library/Caches/agentyard + - ~/Library/Application Support/agentyard/summary - ~/Library/Logs/agentyard.log caveats: | Start agentyard in the background (asks before changing anything): diff --git a/CHANGELOG.md b/CHANGELOG.md index bc15481..ac53aad 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,33 @@ All notable changes are documented here. The format follows ## [Unreleased] +### Added + +- **Session summaries, off by default.** A Summary page says where each Claude Code and Codex session + got to, what it is waiting on you for or blocked on, and what comes next. A summary runs every + morning (07:00 by default, after wake if the Mac was asleep) and **Summarize** runs one for the last + 24 hours. Work is grouped by repository (worktrees count as their repository), then topic, then + session, newest first, with how long ago each session was touched, its branch and PR, sub-agents and + Copy resume. Topics carry over with how long they have been open, stay visible 7 days after their + last activity and leave after 14. Every run is saved, failed ones included, and reopens from a dated + picker; a failed run shows the previous good summary under its error. +- One provider writes the summaries, Claude (`haiku`) or Codex (`gpt-6-luna`), through your own CLI + login, and it never switches to the other. Each run sends clipped transcript excerpts to that + provider's company. The CLI runs in an empty folder with its tools, MCP servers and session + persistence off, the prompt on stdin, and its answer is checked against a schema. Nothing runs and + no model is called while summaries are off. State is kept private in + `~/Library/Application Support/agentyard/summary`. +- `agentyard install` asks once whether to turn summaries on, naming the company that would receive + excerpts; `--yes` keeps the previous choice or leaves them off. New flags: `--summary + off|auto|claude|codex`, `--summary-at HH:MM` and `--summary-model` on `install`, and `-summary`, + `-summary-at` and `-summary-model` on `serve`. +- MCP tools `list_summaries` and `get_summary` (read saved runs, no model call) and `summarize` (starts + a last-24-hours run and sends excerpts to your provider). +- `POST /api/summary` starts a run and answers this Mac only; a browser request needs the page token + and its own `Origin`. `GET /api/summary/status` and the Summary page follow the Sessions tab's + rule (this Mac, unless `--sessions-lan`). +- `brew uninstall --zap` also removes the saved summaries. + ## [0.10.0] - 2026-10-12 ### Added diff --git a/README.md b/README.md index 9e2599d..58aa64b 100644 --- a/README.md +++ b/README.md @@ -278,6 +278,33 @@ Agent icons identify Claude Code and Codex. Use the agent icons for quick filter > contain tokens and customer data, so other devices see a notice instead. See > [Privacy and security](#privacy-and-security). +### Summary + + + + The Summary page: a repository, its topics, and for each session where it got to, what it waits on, what comes next, its branch and PR, and Copy resume. + + +What each session got to, so you can start the day without rereading transcripts. A summary runs +every morning (07:00 by default, and right after your Mac wakes if it was asleep then), and +**Summarize** runs one for the last 24 hours whenever you want it. It is off until you turn it on. + +Work is grouped by repository (a worktree counts as its repository), then by topic, then by session, +with the newest work first and how long ago each session was touched. For each session: + +- where it got to, what it is waiting on you for or blocked on, and what comes next; +- its branch and PR, any sub-agents with a line each, and **Copy resume**. + +Topics carry over from one summary to the next and say how long they have been open ("open since +Mon, Nov 2 · 4 days"). A topic with no activity stays visible for 7 days and leaves the list after +14. Every run is saved, including failed ones, and you can reopen any of the last 30 from the dated +picker. A failed run keeps showing the previous good summary beneath its error. + +One provider writes the summaries, the one you choose: your own Claude Code or Codex CLI, with its +login. It never switches to the other. Each run sends excerpts of your transcripts to that provider; +see [Privacy and security](#privacy-and-security). Turn it on with +[`agentyard install`](#run-in-the-background). + ### On your phone With [LAN mode](#on-your-local-network) on, the same page works on a phone: tables become cards, and @@ -462,9 +489,19 @@ $ agentyard uninstall # stop it and remove the LaunchAgent `uninstall` asks `Remove the background agent? [y/N]`, then tells you what it left behind: the cache in `~/Library/Caches/agentyard` and the log. +`install` asks one more thing the first time: whether to summarize your sessions each morning. The +question names the provider it found (Claude, then Codex) and the company that would receive +excerpts of your transcripts, Anthropic or OpenAI, through your own CLI login. The default is no. +Later installs keep your answer, and `--yes` keeps the previous choice or leaves summaries off. To +decide without being asked, pass `--summary off|auto|claude|codex`; `auto` picks `claude` if it is on +your PATH, else `codex`. The agent's `PATH` includes the folders of `gh`, `git`, `claude` and `codex`, +since launchd does not read your shell profile. Summaries, their saved runs and their notes live in +`~/Library/Application Support/agentyard/summary`; `agentyard uninstall` leaves them, and +`brew uninstall --zap agentyard` removes them. + Removing a Homebrew install? Stop the agent first, or launchd keeps trying to start a binary that is gone: `agentyard uninstall && brew uninstall agentyard`. `brew uninstall --zap agentyard` also -removes the agent, the cache and the log. +removes the agent, the cache, the saved summaries and the log. ## Let your AI clean up @@ -496,6 +533,9 @@ anything. | `merge_train` | Ranked open PRs, one next step, all lane counts, local validation and linked worktrees. Optional exact `repo` (`owner/name`) and `lane`; `stale_days` defaults to 14 and `limit` to 50 (maximum 500). Counts cover the repository scope before lane filtering and limiting. | | `get_pr` | A PR's train step and local evidence, plus its description and changed files via the agent. Requires `repo` and `number`; returns the snapshot with an unavailable-detail notice when offline. | | `remove_worktrees` | Removes the given worktrees if they are still reclaimable; `dry_run` reports what would go. | +| `list_summaries` | Saved [summary](#summary) runs, newest first, failures included: time, window, scheduled or on demand, provider and counts. Reads local files; calls no model. `limit` defaults to 14. | +| `get_summary` | The latest successful summary, or the run at an `at` timestamp from `list_summaries`, optionally for one `project`: progress, next steps, what each session waits on, resume commands and sub-agents. Calls no model. | +| `summarize` | Starts (or joins) a summary of the last 24 hours through the background agent and waits for it. It sends transcript excerpts to your chosen provider, and only works when summaries are on. | | `sync_worktrees` | Asks the background agent to rescan now, refresh PRs and their local validation, and waits for it, up to a few minutes. | An MCP server keeps running the code it started with, so after `brew upgrade` the AI may be talking @@ -504,6 +544,10 @@ elsewhere, or the background agent reports another version, every tool result ca and `remove_worktrees` refuses (dry runs too): older code may lack checks the installed version has. Reconnect it (`/mcp` in Claude Code) or start a new session. +`list_summaries` and `get_summary` read the saved runs directly, so they work without the background +agent. `summarize` is the only summary tool that sends anything off this Mac, and the AI client sees +a clear message instead if summaries are off. + Start a PR session with `merge_train`, then use `get_pr` to read each candidate. Both tools are read-only. They read `/api/prs.json`, falling back to the saved `prs.json` snapshot, and report the source and age. `agentyard mcp -demo` includes every merge train lane and synthetic PR details. @@ -605,6 +649,9 @@ Flags take one dash or two (`-root` and `--root` are the same). | `--name NAME` | `agentyard` | with `--lan`: the `.local` name to publish | | `--port N` | `4777`, or `80` with `--lan` | port to listen on | | `--sessions-lan` | off | with `--lan`: show the Sessions tab to other devices too | +| `--summary off\|auto\|claude\|codex` | the previous install's, else ask once (no on `--yes` or without a terminal) | who writes the daily summary; `off` runs and sends nothing | +| `--summary-at HH:MM` | `07:00`, or the previous install's | local time of the daily summary | +| `--summary-model MODEL` | `haiku` for Claude, `gpt-6-luna` for Codex | model passed to the provider's CLI | | `--yes` | | don't ask; install with these settings | | `--dry-run` | | show the checks, the plan and the plist; change nothing | @@ -628,7 +675,10 @@ manager. | `-size-ttl D` | `30m` | how long a measured worktree size is reused | | `-claude-dir DIR` | `~/.claude` | Claude Code config folder (holds `projects/` and live `sessions/`) | | `-codex-dir DIR` | `~/.codex` | Codex home folder (holds `sessions/`) | -| `-sessions-lan` | off | serve the Sessions tab to other devices too | +| `-sessions-lan` | off | serve the Sessions and Summary tabs to other devices too | +| `-summary` | `off` | summary provider: `off`, `auto`, `claude` or `codex` | +| `-summary-at HH:MM` | `07:00` | local time of the daily summary | +| `-summary-model MODEL` | `haiku` for Claude, `gpt-6-luna` for Codex | model passed to the provider's CLI | | `-once` | | scan once, print the worktree JSON to stdout and exit | #### `agentyard mcp` @@ -646,11 +696,14 @@ manager. The page's data is also served as JSON: `/api.json` (worktrees), `/api/prs.json` (pull requests), `/api/pr-history.json` (cached 30-day opened/merged PR history), -`/api/pr-detail?repo=OWNER/REPO&number=123` (description and changed files for a tracked PR), and -`/api/status` (version, last scan times, whether a sync is running). PR details include up to the first +`/api/pr-detail?repo=OWNER/REPO&number=123` (description and changed files for a tracked PR), +`/api/status` (version, last scan times, whether a sync is running) and `/api/summary/status` (whether +summaries are on, the provider, whether a run is going, its progress and the last error; this Mac only, +like the Sessions tab). PR details include up to the first 100 changed files and the total changed-file count. -`POST /api/remove` is the one write. It is meant for the page, not for scripts: it needs the token +`POST /api/remove` removes worktrees (and `POST /api/summary` starts a summary run, see +[Privacy and security](#privacy-and-security)). `POST /api/remove` is meant for the page, not for scripts: it needs the token the page embeds for viewers on this Mac, and the dashboard's own `Origin`. ``` @@ -680,6 +733,19 @@ agentyard is a local tool with no login and no telemetry. It talks to GitHub thr branch names, PR titles and repository names. Don't use LAN mode on shared or public Wi-Fi. - **Sessions stay on this Mac.** Other devices see a notice and no session ids, unless you opt in with `--sessions-lan`. +- **Summaries send transcript excerpts to one provider, only when you turn them on.** With + `--summary` off (the default) nothing runs and no model is called. With it on, each run sends clipped + excerpts of the Claude Code and Codex sessions active in the window (their titles, first prompts and + latest messages) to the provider you chose, Anthropic for `claude` or OpenAI for `codex`, through your + own CLI login. Transcripts can contain secrets, so decide that before you opt in. agentyard starts the + CLI in an empty folder with every tool, MCP server and session record switched off. Claude runs with + `--safe-mode --strict-mcp-config --tools "" --no-session-persistence`. Codex runs in a read-only + sandbox with `--ephemeral`, `--ignore-user-config`, web search disabled and every default-on tool + feature turned off. The prompt travels on stdin, not in the process list, and answers are checked + against a fixed schema before they are saved. Saved runs, notes and topics live in + `~/Library/Application Support/agentyard/summary` (folder `0700`, files `0600`). The Summary page + follows the Sessions tab's rule: this Mac only, unless `--sessions-lan`. Only this Mac can start a + run, and a browser must send the page's token and its own `Origin`. - **Sync** refuses cross-origin requests, so another web page cannot trigger scans. - **Removal is this Mac's alone.** The dashboard is no longer read-only: `POST /api/remove` removes worktrees, through the same re-checked removal as `agentyard mcp`. It answers only a client on this diff --git a/SECURITY.md b/SECURITY.md index dd132f6..c9169ee 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -3,7 +3,8 @@ ## Threat model agentyard is a local developer tool. It reads your git worktrees, the GitHub CLI's view of your pull -requests, and your Claude Code and Codex transcripts, and serves them over HTTP. +requests, and your Claude Code and Codex transcripts, and serves them over HTTP. If you turn on +summaries, it also sends excerpts of those transcripts to Anthropic or OpenAI. - **The page has no login.** Anyone who can reach the listening address sees branch names, PR titles and repository names. By default it listens on `127.0.0.1:4777`, reachable only from this machine. @@ -49,6 +50,37 @@ with `--lan`. Session ids are validated and shell-quoted in the copied resume co (`.env` and the like) are deleted with it and listed in every result. Branches are never deleted. `agentyard mcp` reads its listings from the agent at the address it is given, the installed agent's by default; the decision to remove always comes from its own local scan, never from that data. +- **Summaries send transcript excerpts to a model provider (opt-in).** With summaries off, the default, + nothing is read for them and no model is called. With `-summary` on, each run sends clipped excerpts + of the Claude Code and Codex sessions active in the window (title or first prompt, the latest + messages, a first prompt and last reply for automated sessions) to the one provider chosen, through + that provider's CLI and your login there. It never falls back to the other. Excerpts can hold secrets + from tool output and text written by someone else (a web page or issue an agent read), so assume the + provider sees both. `install` asks before turning this on and names the company that receives them; + `--yes` keeps the previous choice or leaves it off. +- **Prompt injection is contained by denying tools, not by trusting the model.** The prompt says to + treat excerpts as data, but the protection is that the CLI can do nothing with an instruction. It runs + in an empty folder with the prompt on stdin. Claude gets `--safe-mode --strict-mcp-config --tools "" + --no-session-persistence`. Codex gets a read-only sandbox, `--ephemeral`, `--ignore-user-config`, + `--ignore-rules`, web search disabled and every feature that adds a tool turned off (the list is read + from the installed `codex`, so tool families added later are off too). Each call times out after two + minutes. The answer must match a closed JSON schema, or the batch fails and its sessions show as not + summarized. The page renders every field as escaped text; the model's output is never HTML, a command + or a link. The one command the page offers, Copy resume, is built from the session id and folder + agentyard read, not from model text. +- **Starting a summary is guarded like removal.** `POST /api/summary` is refused unless the client is + this Mac itself (never another LAN device, even with `-sessions-lan`). A request that carries an + `Origin` header, which is every browser request, must name the dashboard's own host and carry the + `X-Agentyard-Token` the page embeds for this Mac. A request with no `Origin` header from this Mac is + the path for `agentyard mcp` and command-line tools, which are the user's own processes. It takes no + parameters (the window is always the last 24 hours), starts nothing while a run is going, and + answers `409` when summaries are off. `GET /summary` and `GET /api/summary/status` follow the + Sessions tab's rule: this Mac only unless `-sessions-lan`, and other devices see a notice. Under + `-sessions-lan` a device can read the summary but not start a run. +- **Summary state is private.** Saved runs, cached notes, topics and the schedule live in + `~/Library/Application Support/agentyard/summary`, in a `0700` folder with `0600` files. They hold + model-written text derived from your transcripts, which can repeat what the transcripts contained. + `brew uninstall --zap agentyard` deletes them; `agentyard uninstall` does not. - **Credentials.** It uses the GitHub CLI's existing login and stores no tokens; the LaunchAgent never carries `GH_TOKEN` or `GITHUB_TOKEN`. Caches in `~/Library/Caches/agentyard/` hold repository, PR and session metadata, not credentials. diff --git a/cli.go b/cli.go index 61cc548..2c70314 100644 --- a/cli.go +++ b/cli.go @@ -243,7 +243,7 @@ func agentJSON(method, listen, path string, timeout time.Duration, limit int64, } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { - return fmt.Errorf("%s", resp.Status) + return &agentHTTPError{Code: resp.StatusCode, Status: resp.Status} } b, err := io.ReadAll(io.LimitReader(resp.Body, limit)) if err != nil { diff --git a/demo.go b/demo.go index 535f2de..8cfd75d 100644 --- a/demo.go +++ b/demo.go @@ -13,6 +13,7 @@ import ( "fmt" "net" "net/http" + "os" "os/signal" "path/filepath" "strings" @@ -81,7 +82,19 @@ func newDemo(now time.Time) (*scanner, *prTracker, *sessionIndex, *demoWorld) { sessions, messages := demoSessions(now) x.show(sessions) - return s, t, x, &demoWorld{messages: messages} + demo := &demoWorld{messages: messages, summaries: &summarizer{enabled: true, provider: "demo", now: time.Now}} + for _, at := range []time.Time{now.Add(-20 * time.Minute), now.Add(-24 * time.Hour)} { + run := demoSummary(at, sessions, messages, snap, t.snap.Load()) + if len(demo.summaryRuns) > 0 { + topic := run.Projects[0].Topics[0] + note := topic.Sessions[0].Note + note.State, note.Progress, note.Next = summaryInProgress, "Reproduced the token refresh flake; reviewing lock ownership.", "Move the token write inside the critical section." + topic.Status = note.Progress + } + demo.summaryRuns = append(demo.summaryRuns, run) + } + demo.summaries.latest.Store(demo.summaryRuns[0]) + return s, t, x, demo } // ---------------------------------------------------------------- helpers @@ -520,3 +533,157 @@ func demoSessions(now time.Time) ([]*Session, map[string][]Message) { } return sessions, messages } + +// ---------------------------------------------------------------- summaries + +func demoSummary(at time.Time, sessions []*Session, messages map[string][]Message, wt *Snapshot, prs *PRSnapshot) *summarySnapshot { + snap := &summarySnapshot{At: at, Window: summaryWindow{Start: at.Add(-24 * time.Hour), End: at}, Provider: "demo"} + projects := map[string]*summarySnapshotProject{} + for _, session := range sessions { + project := "Other" + for _, repo := range wt.Repos { + if repo.Path == session.Cwd { + project = repo.Slug + } + for _, worktree := range repo.Worktrees { + if worktree.Path == session.Cwd { + project = repo.Slug + } + } + } + if projects[project] == nil { + projects[project] = &summarySnapshotProject{Project: project} + snap.Projects = append(snap.Projects, projects[project]) + } + fixture, known := demoSummaryNotes[session.Label()] + if !known { + fixture = demoSummaryNote{Topic: session.Label(), State: summaryInProgress, Next: "Pick up where the session stopped."} + for _, message := range messages[session.Tool+"/"+session.ID] { + if message.Role == "assistant" { + fixture.Progress = message.Text + } + } + } + note := &summaryNote{State: fixture.State, Progress: fixture.Progress, Next: fixture.Next} + if fixture.WaitsOn != "" { + note.WaitsOn = &fixture.WaitsOn + } + entry := &summarySession{Session: session, Automated: session.Kind == "scheduled" || session.Kind == "exec"} + view := snapshotSummarySession(entry, note, wt, prs) + if session.Title == "Fix token refresh race in auth middleware" { + view.Subagents = []*summarySnapshotSession{{Tool: "codex", Title: "Race-test review", Progress: "Checked lock ownership and verified the regression tests."}} + } + if session.Title == "Deflake webhook retry test" { + view.Note, view.NotSummarized = nil, true + projects[project].Unsorted = append(projects[project].Unsorted, view) + continue + } + var topic *summarySnapshotTopic + for _, existing := range projects[project].Topics { + if existing.Name == fixture.Topic { + topic = existing + } + } + if topic == nil { + status := demoSummaryTopics[fixture.Topic] + if status == "" { + status = note.Progress + } + topic = &summarySnapshotTopic{ + summaryTopic: summaryTopic{ID: session.ID, Name: fixture.Topic, Status: status, FirstSeen: at.Add(-3 * 24 * time.Hour), LastActive: session.Modified}, + CarriedOver: session.Started.Before(at.Add(-24 * time.Hour)), OpenDays: 3, + IdleDays: max(0, int(at.Sub(session.Modified).Hours()/24)), + } + projects[project].Topics = append(projects[project].Topics, topic) + } + topic.Sessions = append(topic.Sessions, view) + if session.Modified.After(topic.LastActive) { + topic.LastActive = session.Modified + topic.IdleDays = max(0, int(at.Sub(session.Modified).Hours()/24)) + } + } + sortSummaryProjects(snap.Projects) + return snap +} + +type demoSummaryNote struct{ Topic, State, Progress, Next, WaitsOn string } + +var demoSummaryNotes = map[string]demoSummaryNote{ + "Fix token refresh race in auth middleware": {"Auth reliability", summaryDone, "Fixed the token refresh race; 50 race-test runs passed and PR #482 is in the merge queue.", "Check the merge queue result.", ""}, + "Deflake webhook retry test": {"Auth reliability", summaryInProgress, "", "", ""}, + "Migrate payments to the v2 ledger": {"Payments ledger v2", summaryInProgress, "Dual writes are on behind ledger.dual_write; the backfill job turns them off at the high-water mark.", "Add the down migration for 0042 so migrations-lint passes.", ""}, + "Investigate p99 latency on /search": {"Search latency", summaryWaitingOnYou, "Wrote a concurrent index on (tenant_id, created_at DESC) as migration 0043; nothing applied yet.", "Apply the migration with make migrate once it is scheduled.", "Choose when to apply the index migration."}, + "Scheduled: nightly-dependency-audit": {"Dependency hygiene", summaryDone, "Two advisories: golang.org/x/net needs v0.33.0; github.com/jackc/pgx/v5 is fine.", "Bump golang.org/x/net to v0.33.0.", ""}, + "Split the shipping step out of checkout": {"Checkout redesign", summaryInProgress, "Shipping fields now live in their own step; main moved the payment fields meanwhile.", "Rebase on main and resolve the conflict in CheckoutForm.tsx.", ""}, + "Saved carts: address review comments": {"Checkout redesign", summaryInProgress, "Cart merge moved to POST /api/cart/merge, called once from the sign-in callback.", "Answer the last review thread on merge timing.", ""}, + "Dark mode design tokens": {"Dark mode", summaryInProgress, "Two commits on claude/dark-mode-tokens, not pushed yet.", "Check focus-ring contrast on the sidebar links, then push.", ""}, + "Upgrade Terraform to 1.9 and fix deprecations": {"Terraform 1.9", summaryDone, "Plan is clean on staging after fixing three deprecated arguments.", "Review the production plan before applying.", ""}, + "Rotate KMS keys runbook": {"Key rotation", summaryBlocked, "Runbook drafted through step 4.", "Finish the runbook once staging grants exist.", "Staging grants need to be recreated before rotation."}, + "HTTP/2 server push": {"HTTP/2", summaryInProgress, "Push promises are sent for linked assets; the h2spec push suite passes.", "Decide whether push stays behind an option.", ""}, + "Write the streaming guide": {"Docs", summaryInProgress, "First draft covers chunked responses and backpressure.", "Add the cancellation example.", ""}, +} + +var demoSummaryTopics = map[string]string{ + "Auth reliability": "Token race fixed and queued; the webhook retry test is still flaky.", + "Payments ledger v2": "Dual writes running; one down migration left before review.", + "Search latency": "Index migration ready; waiting on you to schedule it.", + "Dependency hygiene": "One dependency bump to make.", + "Checkout redesign": "Shipping step split out and saved carts in review; both need a rebase.", + "Dark mode": "Tokens done locally; contrast check before pushing.", + "Terraform 1.9": "Staging is clean; production plan to review.", + "Key rotation": "Blocked on staging grants.", + "HTTP/2": "Server push works; one API decision left.", + "Docs": "Streaming guide drafted.", +} + +// Demo runs publish in memory; they never enter the provider pipeline or read state. +func (d *demoWorld) startSummary() string { + s := d.summaries + s.mu.Lock() + defer s.mu.Unlock() + if s.runStatus.Running { + return "running" + } + at := s.now() + s.runStatus = summaryRunStatus{Running: true, Started: at} + s.done = make(chan struct{}) + go func() { + time.Sleep(500 * time.Millisecond) + s.mu.Lock() + defer s.mu.Unlock() + previous := s.latest.Load() + snap := *previous + snap.At, snap.Window = at, summaryWindow{Start: at.Add(-24 * time.Hour), End: at} + d.summaryRuns = append([]*summarySnapshot{&snap}, d.summaryRuns...) + s.latest.Store(&snap) + s.runStatus.Running = false + for _, project := range snap.Projects { + for _, session := range project.sessions() { + s.runStatus.Sessions++ + if !session.NotSummarized { + s.runStatus.Summarized++ + } + } + } + close(s.done) + }() + return "started" +} + +func (d *demoWorld) summaryHistory() ([]*summaryHistoryRun, func(time.Time) (*summarySnapshot, error)) { + d.summaries.mu.Lock() + runs := append([]*summarySnapshot{}, d.summaryRuns...) + d.summaries.mu.Unlock() + history := make([]*summaryHistoryRun, 0, len(runs)) + for _, run := range runs { + history = append(history, &summaryHistoryRun{At: run.At, Error: run.Error}) + } + return history, func(at time.Time) (*summarySnapshot, error) { + for _, run := range runs { + if run.At.Equal(at) { + return run, nil + } + } + return nil, os.ErrNotExist + } +} diff --git a/docs/screenshots/phone-summary.png b/docs/screenshots/phone-summary.png new file mode 100644 index 0000000..fdc399f Binary files /dev/null and b/docs/screenshots/phone-summary.png differ diff --git a/docs/screenshots/summary-dark.png b/docs/screenshots/summary-dark.png new file mode 100644 index 0000000..aa27e00 Binary files /dev/null and b/docs/screenshots/summary-dark.png differ diff --git a/docs/screenshots/summary-light.png b/docs/screenshots/summary-light.png new file mode 100644 index 0000000..076267c Binary files /dev/null and b/docs/screenshots/summary-light.png differ diff --git a/install.go b/install.go index b7990f2..a7dc4ab 100644 --- a/install.go +++ b/install.go @@ -35,15 +35,18 @@ func launchDomain() string { // installConfig is everything the LaunchAgent is made of. type installConfig struct { - Exe string // the binary launchd runs - Root string - Listen string - Name string // mDNS name; "" = not published - ClaudeDir string - CodexDir string - SessionsLAN bool - Path string // PATH for launchd, which otherwise starts with a bare one - Log string + Exe string // the binary launchd runs + Root string + Listen string + Name string // mDNS name; "" = not published + ClaudeDir string + CodexDir string + SessionsLAN bool + Summary string + SummaryAt string + SummaryModel string + Path string // PATH for launchd, which otherwise starts with a bare one + Log string // Where gh keeps its login, when moved from the default; passed through // because launchd does not read shell profiles. Never a token. @@ -79,9 +82,16 @@ func (c installConfig) sessionsLabel() string { return "this Mac only" } +func (c installConfig) summaryLabel() string { + if summaryOff(c.Summary) { + return "off" + } + return c.Summary + " at " + c.SummaryAt +} + // args is the LaunchAgent's ProgramArguments. func (c installConfig) args() []string { - return []string{c.Exe, "serve", + args := []string{c.Exe, "serve", "-root", c.Root, "-listen", c.Listen, "-mdns", c.Name, @@ -89,6 +99,10 @@ func (c installConfig) args() []string { "-codex-dir", c.CodexDir, "-sessions-lan=" + strconv.FormatBool(c.SessionsLAN), } + if c.Summary != "" { + args = append(args, "-summary", c.Summary, "-summary-at", c.SummaryAt, "-summary-model", c.SummaryModel) + } + return args } // configFromArgs reads back what args wrote; ok is false for anything else. @@ -116,6 +130,12 @@ func configFromArgs(args []string) (c installConfig, ok bool) { c.CodexDir = val case "sessions-lan": c.SessionsLAN = !hasVal || val == "true" + case "summary": + c.Summary = val + case "summary-at": + c.SummaryAt = val + case "summary-model": + c.SummaryModel = val } } return c, c.Listen != "" @@ -359,7 +379,7 @@ func expandHome(p string) string { return p } -// launchPath is PATH for launchd: wherever gh and git live, then the system dirs. +// launchPath is PATH for launchd: wherever its tools live, then the system dirs. func launchPath(tools ...string) string { var dirs []string for _, t := range tools { @@ -529,13 +549,58 @@ func resolveSessionsLAN(flag, flagSet bool, prev installConfig, hadPrev, lan boo return v && lan } +// resolveSummary keeps the previous choice or asks once, naming the provider +// before the user agrees to send transcript excerpts to it. +func resolveSummary(choice string, flagSet bool, prev installConfig, hadPrev, interactive bool) (string, error) { + if !flagSet { + switch { + case hadPrev && prev.Summary != "": // an install from before summaries has no choice yet + choice = prev.Summary + case interactive: + p, err := newSummaryProvider("auto", "", "") + if err != nil { + return "off", nil + } + name, company := "Claude", "Anthropic" + if p.name == "codex" { + name, company = "Codex", "OpenAI" + } + ok, err := ask("Summarize your sessions each morning with " + name + "? Each summary sends excerpts of your Claude Code and Codex transcripts to " + company + " through your " + p.name + " CLI.") + if err != nil { + return "", err + } + fmt.Println() + if ok { + return p.name, nil + } + return "off", nil + } + } + if summaryOff(choice) { + return "off", nil + } + switch choice { + case "claude", "codex": + return choice, nil + default: + p, err := newSummaryProvider(choice, "", "") + if err != nil { + return "", err + } + return p.name, nil + } +} + func runInstall(args []string) error { - fs := newFlags("install", "install [--root DIR] [--lan] [--name agentyard] [--port N] [--sessions-lan] [--yes] [--dry-run]") + fs := newFlags("install", "install [--root DIR] [--lan] [--name agentyard] [--port N] [--sessions-lan] [--summary off|auto|claude|codex] [--summary-at HH:MM] [--summary-model MODEL] [--yes] [--dry-run]") root := fs.String("root", "", "folder holding your repositories (default: the previous install's, else the first of ~/Projects, ~/code, ~/src, … that exists)") lan := fs.Bool("lan", false, "serve on your local network as http://.local on port 80 (--lan=false turns it off again)") name := fs.String("name", "agentyard", "with --lan: the http://.local name to publish") port := fs.Int("port", 0, "port to listen on (default 4777, or 80 with --lan)") sessionsLAN := fs.Bool("sessions-lan", false, "with --lan: show the Sessions tab to other devices too (transcripts can hold secrets)") + summary := fs.String("summary", "off", "summary provider: off, auto, claude or codex (default: the previous install's, else ask once)") + summaryAt := fs.String("summary-at", "07:00", "daily summary time (local HH:MM; keeps the previous install's if set)") + summaryModel := fs.String("summary-model", "", "summary model (default: the previous install's, else the provider's cheapest)") yes := fs.Bool("yes", false, "don't ask; install with these settings") dry := fs.Bool("dry-run", false, "show the checks, the plan and the plist; change nothing") if err := parse(fs, args); err != nil { @@ -576,10 +641,12 @@ func runInstall(args []string) error { Root: detectRoot(), ClaudeDir: envOr("CLAUDE_CONFIG_DIR", filepath.Join(home, ".claude")), CodexDir: envOr("CODEX_HOME", filepath.Join(home, ".codex")), - Path: launchPath("gh", "git"), + Path: launchPath("gh", "git", "claude", "codex"), GHConfigDir: os.Getenv("GH_CONFIG_DIR"), XDGConfigHome: os.Getenv("XDG_CONFIG_HOME"), Log: logPath(), + SummaryAt: *summaryAt, + SummaryModel: *summaryModel, } if hadPrev { c.Root = prev.Root @@ -592,6 +659,23 @@ func runInstall(args []string) error { if !set["name"] && prev.Name != "" { *name = prev.Name } + if !set["summary-at"] && prev.SummaryAt != "" { + c.SummaryAt = prev.SummaryAt + } + if !set["summary-model"] { + c.SummaryModel = prev.SummaryModel + } + } + // serve would exit on a bad time, and launchd would restart it forever. + if _, _, err := parseSummaryAt(c.SummaryAt); err != nil { + return err + } + c.Summary, err = resolveSummary(*summary, set["summary"], prev, hadPrev, interactive) + if err != nil { + return err + } + if !set["summary-model"] && c.Summary != prev.Summary { + c.SummaryModel = "" } if set["root"] { c.Root = expandHome(*root) @@ -624,6 +708,7 @@ func runInstall(args []string) error { {"root", tilde(c.Root)}, {"network", c.networkLabel()}, {"sessions", c.sessionsLabel()}, + {"summary", c.summaryLabel()}, {"url", c.URL()}, }) fmt.Println() diff --git a/install_test.go b/install_test.go index c9ed1d5..b55476c 100644 --- a/install_test.go +++ b/install_test.go @@ -6,6 +6,9 @@ import ( "io" "net/http" "os" + "path/filepath" + "runtime" + "slices" "strings" "testing" ) @@ -154,6 +157,177 @@ func TestResolveSessionsLAN(t *testing.T) { } } +// Dry runs exercise flag parsing, previous settings, plan rows and the plist +// without touching launchd or invoking either summary CLI. +func TestInstallSummaryDryRun(t *testing.T) { + if runtime.GOOS != "darwin" { + t.Skip("LaunchAgent install is macOS only") + } + for _, tc := range []struct { + name, previous, provider, at, model string + args []string + }{ + {"explicit", "", "codex", "06:30", "custom & small", []string{"--summary", "codex", "--summary-at", "06:30", "--summary-model", "custom & small"}}, + {"switch provider uses its default", "codex", "claude", "06:30", "", []string{"--summary", "claude"}}, + {"switch provider explicit model", "codex", "claude", "06:30", "chosen-model", []string{"--summary", "claude", "--summary-model", "chosen-model"}}, + {"reinstall --yes", "codex", "codex", "06:30", "saved-model", []string{"--yes"}}, + {"first install without terminal", "", "off", "07:00", "", nil}, + {"older install stays off", "legacy", "off", "07:00", "", []string{"--yes"}}, + {"auto resolves to Codex", "", "codex", "07:00", "", []string{"--summary", "auto"}}, + {"explicit overrides previous", "codex", "off", "08:15", "", []string{"--summary", "off", "--summary-at", "08:15", "--summary-model="}}, + } { + t.Run(tc.name, func(t *testing.T) { + oldHome, oldUID, oldStdin := home, geteuid, os.Stdin + home, geteuid = t.TempDir(), func() int { return 501 } + t.Cleanup(func() { home, geteuid, os.Stdin = oldHome, oldUID, oldStdin }) + input, err := os.Open(os.DevNull) + if err != nil { + t.Fatal(err) + } + defer input.Close() + os.Stdin = input + bin, claudeBin, codexBin := t.TempDir(), t.TempDir(), t.TempDir() + t.Setenv("PATH", bin+":"+claudeBin+":"+codexBin) + fakeSummaryCLI(t, bin, "git", "exit 0") + fakeSummaryCLI(t, bin, "gh", "exit 0") + record := filepath.Join(t.TempDir(), "called") + t.Setenv("SUMMARY_RECORD", record) + fakeSummaryCLI(t, codexBin, "codex", `printf called > "$SUMMARY_RECORD"; exit 1`) + if tc.name != "auto resolves to Codex" { + fakeSummaryCLI(t, claudeBin, "claude", `printf called > "$SUMMARY_RECORD"; exit 1`) + } + if tc.previous != "" { + c := testConfig() + c.Listen, c.Name = "127.0.0.1:4777", "" + plist := renderPlist(c) + if tc.previous != "legacy" { + plist = strings.Replace(plist, " ", " -summarycodex\n -summary-at06:30\n -summary-modelsaved-model\n ", 1) + } + if err := os.MkdirAll(filepath.Dir(plistPath()), 0700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(plistPath(), []byte(plist), 0600); err != nil { + t.Fatal(err) + } + } + args := append([]string{"--dry-run", "--lan=false", "--port", "1", "--root", t.TempDir()}, tc.args...) + var installErr error + out := installOutput(t, func() { installErr = runInstall(args) }) + // go test's executable is a temporary go-build binary; dry-run still + // prints the full plan and plist before reporting that preflight check. + if installErr != nil && !strings.Contains(installErr.Error(), "check(s) failed") { + t.Fatalf("dry-run: %v\n%s", installErr, out) + } + start := strings.Index(out, "= len(got) || got[i+1] != want { + t.Errorf("%s = %q, want %q", flag, got, want) + } + } + label := tc.provider + if label != "off" { + label += " at " + tc.at + } + if !strings.Contains(out, "summary "+label) { + t.Errorf("plan lacks summary setting %q:\n%s", label, out) + } + dirs := []string{bin, codexBin} + if tc.name != "auto resolves to Codex" { + dirs = append(dirs, claudeBin) + } + for _, dir := range dirs { + if !strings.Contains(out[start:], dir) { + t.Errorf("plist PATH lacks %s", dir) + } + } + if _, err := os.Stat(record); !os.IsNotExist(err) { + t.Fatalf("summary CLI was invoked: %v", err) + } + }) + } +} + +func installOutput(t *testing.T, f func()) string { + t.Helper() + out, err := os.CreateTemp(t.TempDir(), "stdout") + if err != nil { + t.Fatal(err) + } + defer out.Close() + old := os.Stdout + os.Stdout = out + defer func() { os.Stdout = old }() + f() + if _, err := out.Seek(0, io.SeekStart); err != nil { + t.Fatal(err) + } + b, err := io.ReadAll(out) + if err != nil { + t.Fatal(err) + } + return string(b) +} + +func TestResolveSummary(t *testing.T) { + for _, tc := range []struct { + name, previous, answer, want string + bins []string + hadPrev, interactive bool + prompt string + }{ + {"Claude first", "", "y\n", "claude", []string{"claude", "codex"}, false, true, "Summarize your sessions each morning with Claude? Each summary sends excerpts of your Claude Code and Codex transcripts to Anthropic through your claude CLI. [y/N] "}, + {"Codex only", "", "yes\n", "codex", []string{"codex"}, false, true, "Summarize your sessions each morning with Codex? Each summary sends excerpts of your Claude Code and Codex transcripts to OpenAI through your codex CLI. [y/N] "}, + {"decline", "", "n\n", "off", []string{"claude"}, false, true, "[y/N] "}, + {"default no", "", "\n", "off", []string{"codex"}, false, true, "[y/N] "}, + {"no CLI", "", "", "off", nil, false, true, ""}, + {"previous choice", "codex", "", "codex", []string{"claude", "codex"}, true, true, ""}, + {"previous off", "off", "", "off", []string{"claude"}, true, true, ""}, + {"older install asks once", "", "y\n", "claude", []string{"claude"}, true, true, "[y/N] "}, + {"older install without a terminal", "", "", "off", []string{"claude"}, true, false, ""}, + {"no terminal or --yes", "", "", "off", []string{"claude"}, false, false, ""}, + } { + t.Run(tc.name, func(t *testing.T) { + bin := t.TempDir() + t.Setenv("PATH", bin) + for _, name := range tc.bins { + fakeSummaryCLI(t, bin, name, "exit 1") + } + old := stdin + stdin = bufio.NewReader(strings.NewReader(tc.answer)) + defer func() { stdin = old }() + var got string + var err error + out := installOutput(t, func() { + got, err = resolveSummary("off", false, installConfig{Summary: tc.previous}, tc.hadPrev, tc.interactive) + }) + if err != nil || got != tc.want { + t.Fatalf("summary = %q, %v; want %q", got, err, tc.want) + } + if tc.prompt == "" && out != "" || tc.prompt != "" && !strings.Contains(out, tc.prompt) { + t.Errorf("prompt = %q, want %q", out, tc.prompt) + } + c := testConfig() + c.Summary, c.SummaryAt, c.SummaryModel = got, "07:00", "custom & small" + args, err := plistArgs([]byte(renderPlist(c))) + if err != nil { + t.Fatal(err) + } + back, ok := configFromArgs(args) + if !ok || back.Summary != tc.want || back.SummaryAt != c.SummaryAt || back.SummaryModel != c.SummaryModel { + t.Errorf("summary plist round trip: %+v", back) + } + }) + } +} + func TestServeRejectsStrayArguments(t *testing.T) { serveFlags.SetOutput(io.Discard) defer serveFlags.SetOutput(nil) @@ -161,3 +335,21 @@ func TestServeRejectsStrayArguments(t *testing.T) { t.Fatalf("serve extra -once: %v, want a usage error", err) } } + +func TestInstallRejectsBadSummaryTime(t *testing.T) { + if runtime.GOOS != "darwin" { + t.Skip("LaunchAgent install is macOS only") + } + oldHome, oldUID := home, geteuid + home, geteuid = t.TempDir(), func() int { return 501 } + t.Cleanup(func() { home, geteuid = oldHome, oldUID }) + for _, at := range []string{"7:00", "25:00", "07:00:00", ""} { + var err error + installOutput(t, func() { + err = runInstall([]string{"--dry-run", "--yes", "--lan=false", "--port", "1", "--root", t.TempDir(), "--summary-at", at}) + }) + if err == nil || !strings.Contains(err.Error(), "summary-at") { + t.Errorf("--summary-at %q: %v", at, err) + } + } +} diff --git a/main.go b/main.go index fb4d80e..2cc9034 100644 --- a/main.go +++ b/main.go @@ -41,15 +41,18 @@ import ( // Serve flags live on their own FlagSet so every subcommand can parse its own; // the pointers keep their defaults when nothing is parsed (tests, demo). var ( - home, _ = os.UserHomeDir() - serveFlags = flag.NewFlagSet("serve", flag.ContinueOnError) - flagRoot = serveFlags.String("root", filepath.Join(home, "Projects"), "folder to search for repositories") - flagDepth = serveFlags.Int("depth", 5, "max folder depth below -root to look for repositories") - flagListen = serveFlags.String("listen", defaultListen, "HTTP listen address (\":80\" serves the whole LAN)") - flagInterval = serveFlags.Duration("interval", 5*time.Minute, "rescan interval") - flagSizeTTL = serveFlags.Duration("size-ttl", 30*time.Minute, "how long a measured worktree size is reused") - flagMDNS = serveFlags.String("mdns", "", "publish as http://.local over mDNS (empty: off; ignored on loopback)") - flagOnce = serveFlags.Bool("once", false, "scan once, print the worktree JSON to stdout and exit") + home, _ = os.UserHomeDir() + serveFlags = flag.NewFlagSet("serve", flag.ContinueOnError) + flagRoot = serveFlags.String("root", filepath.Join(home, "Projects"), "folder to search for repositories") + flagDepth = serveFlags.Int("depth", 5, "max folder depth below -root to look for repositories") + flagListen = serveFlags.String("listen", defaultListen, "HTTP listen address (\":80\" serves the whole LAN)") + flagInterval = serveFlags.Duration("interval", 5*time.Minute, "rescan interval") + flagSizeTTL = serveFlags.Duration("size-ttl", 30*time.Minute, "how long a measured worktree size is reused") + flagMDNS = serveFlags.String("mdns", "", "publish as http://.local over mDNS (empty: off; ignored on loopback)") + flagOnce = serveFlags.Bool("once", false, "scan once, print the worktree JSON to stdout and exit") + flagSummary = serveFlags.String("summary", "off", "summary provider: off, auto, claude or codex") + flagSummaryAt = serveFlags.String("summary-at", "07:00", "daily summary time (local HH:MM)") + flagSummaryModel = serveFlags.String("summary-model", "", "summary model (default: haiku for Claude, gpt-6-luna for Codex)") ) const ( @@ -207,6 +210,16 @@ func runIsolated(timeout time.Duration, dir string, env []string, name string, a return execute(timeout, dir, base, env, "", name, args...) } +// commandError preserves the deadline and final stderr line for provider callers. +type commandError struct { + Err error + LastLine string + message string +} + +func (e *commandError) Error() string { return e.message } +func (e *commandError) Unwrap() error { return e.Err } + func execute(timeout time.Duration, dir string, base, env []string, input, name string, args ...string) (string, error) { ctx, cancel := context.WithTimeout(context.Background(), timeout) defer cancel() @@ -229,13 +242,21 @@ func execute(timeout time.Duration, dir string, base, env []string, input, name // The last line, unless git said fatal:/error: earlier; its hint lines // ("use 'remove -f -f'") are not the reason. lines := strings.Split(strings.TrimSpace(stderr.String()), "\n") - msg := lines[len(lines)-1] + last := lines[len(lines)-1] + msg := last for _, l := range lines { if strings.HasPrefix(l, "fatal: ") || strings.HasPrefix(l, "error: ") { msg = l } } - return out.String(), fmt.Errorf("%s %s: %w %s", name, args[0], err, msg) + if ctx.Err() != nil { + err = ctx.Err() + } + first := "" + if len(args) > 0 { + first = args[0] + } + return out.String(), &commandError{Err: err, LastLine: last, message: fmt.Sprintf("%s %s: %v %s", name, first, err, msg)} } return out.String(), nil } @@ -1224,17 +1245,19 @@ func ago(t time.Time) string { var pageHTML string var page = template.Must(template.New("page").Funcs(template.FuncMap{ - "size": kbSize, - "bytes": byteSize, - "ago": ago, - "tilde": tilde, - "anchorOf": func(r *Repo) string { return anchor(r.Path) }, - "base": filepath.Base, - "seq": func(n int) []int { return make([]int, n) }, - "join": strings.Join, - "org": func(repo string) string { o, _, _ := strings.Cut(repo, "/"); return o }, - "repoShort": func(repo string) string { _, r, _ := strings.Cut(repo, "/"); return r }, - "fsize": func(n int64) string { return byteSize(uint64(max(n, 0))) }, + "summarySessionStatus": summarySessionStatus, + "summaryProjectVisible": summaryProjectVisible, + "size": kbSize, + "bytes": byteSize, + "ago": ago, + "tilde": tilde, + "anchorOf": func(r *Repo) string { return anchor(r.Path) }, + "base": filepath.Base, + "seq": func(n int) []int { return make([]int, n) }, + "join": strings.Join, + "org": func(repo string) string { o, _, _ := strings.Cut(repo, "/"); return o }, + "repoShort": func(repo string) string { _, r, _ := strings.Cut(repo, "/"); return r }, + "fsize": func(n int64) string { return byteSize(uint64(max(n, 0))) }, "countKind": func(list []*Session, kind string) (n int) { for _, x := range list { if x.Kind == kind { @@ -1430,11 +1453,55 @@ func (y *syncer) start() string { // demoWorld switches serve to synthetic data: nothing on disk is read, the // Sessions tab is open to any viewer and Sync does nothing. See demo.go. type demoWorld struct { - messages map[string][]Message // keyed by tool + "/" + session id + messages map[string][]Message // keyed by tool + "/" + session id + summaries *summarizer + summaryRuns []*summarySnapshot +} + +// summaryPickerRuns is how many saved runs the Summary page loads and offers. +const summaryPickerRuns = 30 + +type summaryPageView struct { + Enabled bool + Status summaryRunStatus + Run, Snapshot *summarySnapshot + History []*summaryHistoryRun + Past bool + Error string +} + +func summarySessionStatus(s *summarySnapshotSession) summarySessionState { + if !s.NotSummarized && s.Note != nil { + for _, state := range summarySessionStates { + if state.State == s.Note.State { + return state + } + } + } + return summarySessionState{Label: "Not summarized", Tone: "tone-muted"} +} + +func summaryProjectVisible(p *summarySnapshotProject) bool { + if len(p.Unsorted) > 0 { + return true + } + for _, topic := range p.Topics { + if !topic.Hidden { + return true + } + } + return false } // serve builds every route of the dashboard. demo is nil in production. -func serve(s *scanner, t *prTracker, x *sessionIndex, demo *demoWorld) http.Handler { +func serve(s *scanner, t *prTracker, x *sessionIndex, demo *demoWorld, sources ...*summarizer) http.Handler { + var summaries *summarizer + if len(sources) > 0 { + summaries = sources[0] + } + if demo != nil { + summaries = demo.summaries + } t.worktrees = func() *Snapshot { return s.snap.Load() } y := &syncer{s: s, t: t, x: x, demo: demo != nil} removeToken := newRemoveToken() @@ -1462,6 +1529,7 @@ func serve(s *scanner, t *prTracker, x *sessionIndex, demo *demoWorld) http.Hand // call POST /api/remove with RemoveToken. In demo mode removal is simulated. CanRemove bool RemoveToken string + Summary summaryPageView } newView := func(tab string, r *http.Request) view { v := view{Tab: tab, RefreshSec: int(flagInterval.Seconds()), WT: s.snap.Load(), PR: t.snap.Load(), Local: canSeeSessions(r), @@ -1494,6 +1562,119 @@ func serve(s *scanner, t *prTracker, x *sessionIndex, demo *demoWorld) http.Hand } render(w, "sessions", newView("sessions", r)) }) + mux.HandleFunc("GET /summary", func(w http.ResponseWriter, r *http.Request) { + v := newView("summary", r) + if v.Local && summaries != nil && summaries.enabled { + v.Summary = summaryPageView{Enabled: true, Status: summaries.status(), Snapshot: summaries.latest.Load()} + var runs []*summaryHistoryRun + load := summaries.load + if demo != nil { + runs, load = demo.summaryHistory() + } else { + stamps, err := summaries.history() + if err != nil { + log.Printf("summary history: %v", err) + } + for _, at := range stamps[:min(len(stamps), summaryPickerRuns)] { + run, err := summaries.loadHistoryRun(at) + if err != nil { + log.Printf("summary history: %v", err) + continue + } + runs = append(runs, run) + } + } + v.Summary.History = runs + v.Summary.Run = v.Summary.Snapshot + if value := r.URL.Query().Get("at"); value != "" { + at, err := time.Parse(time.RFC3339Nano, value) + if err != nil { + http.Error(w, "invalid summary timestamp", http.StatusBadRequest) + return + } + var chosen *summarySnapshot + for _, run := range runs { + if run.At.Equal(at) { + chosen, err = load(run.At) + if err != nil { + log.Printf("summary history: %v", err) + } + break + } + } + if chosen == nil { + http.NotFound(w, r) + return + } + v.Summary.Run, v.Summary.Snapshot, v.Summary.Past = chosen, chosen, true + if chosen.Error != "" { + v.Summary.Snapshot = nil + stamps := make([]time.Time, 0, len(runs)) + byTime := make(map[time.Time]*summaryHistoryRun, len(runs)) + for _, run := range runs { + stamps = append(stamps, run.At) + byTime[run.At] = run + } + previous, _ := latestSuccessfulSummaryRun(stamps, chosen.At, func(at time.Time) (*summaryHistoryRun, error) { + return byTime[at], nil + }) + if previous != nil { + v.Summary.Snapshot, err = load(previous.At) + if err != nil { + log.Printf("summary history: %v", err) + } + } + } + } + v.Summary.Error = v.Summary.Status.LastError + if v.Summary.Past { + v.Summary.Error = v.Summary.Run.Error + } + } + render(w, "summary", v) + }) + mux.HandleFunc("POST /api/summary", func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + if !localMutationAllowed(w, r, removeToken, "summaries can only be started from the Mac that runs agentyard", true) { + return + } + state := "off" + if summaries != nil { + if demo != nil { + state = demo.startSummary() + } else { + state = summaries.start(summaryWindow{}) + } + } + if state == "off" { + w.WriteHeader(http.StatusConflict) + json.NewEncoder(w).Encode(map[string]string{"state": "off", "error": "summaries are off; run agentyard install to turn them on"}) + return + } + json.NewEncoder(w).Encode(map[string]string{"state": state}) + }) + mux.HandleFunc("GET /api/summary/status", func(w http.ResponseWriter, r *http.Request) { + if !canSeeSessions(r) { + http.Error(w, "sessions are only viewable on the Mac that runs this", http.StatusForbidden) + return + } + var status summaryRunStatus + enabled, provider := false, "" + var started, latest *time.Time + if summaries != nil { + enabled, provider, status = summaries.enabled, summaries.provider, summaries.status() + if !status.Started.IsZero() { + started = &status.Started + } + if snap := summaries.latest.Load(); snap != nil { + latest = &snap.At + } + } + w.Header().Set("Content-Type", "application/json") + w.Header().Set("Cache-Control", "no-store") + json.NewEncoder(w).Encode(summaryStatus{Enabled: enabled, Provider: provider, Running: status.Running, + Started: started, Sessions: status.Sessions, Summarized: status.Summarized, LastError: status.LastError, Latest: latest}) + }) mux.HandleFunc("GET /sessions/view", func(w http.ResponseWriter, r *http.Request) { if !canSeeSessions(r) { http.Error(w, "sessions are only viewable on the Mac that runs this", http.StatusForbidden) @@ -1582,18 +1763,38 @@ func cachePath(name string) string { } func saveCache(name string, v any) { - p := cachePath(name) - os.MkdirAll(filepath.Dir(p), 0o700) + if err := writeJSONFile(cachePath(name), v); err != nil { + log.Printf("cache %s: %v", name, err) + } +} + +// writeJSONFile replaces path atomically, readable only by this user, so a +// crash mid-write never leaves half a file for the next start to load. +func writeJSONFile(path string, v any) error { b, err := json.Marshal(v) - if err == nil { - err = os.WriteFile(p+".tmp", b, 0o600) + if err != nil { + return err } - if err == nil { - err = os.Rename(p+".tmp", p) + if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil { + return err } + f, err := os.CreateTemp(filepath.Dir(path), filepath.Base(path)+"-*.tmp") if err != nil { - log.Printf("cache %s: %v", name, err) + return err + } + defer os.Remove(f.Name()) + if _, err := f.Write(b); err != nil { + f.Close() + return err } + if err := f.Sync(); err != nil { // a power loss must not leave an empty file + f.Close() + return err + } + if err := f.Close(); err != nil { + return err + } + return os.Rename(f.Name(), path) } func loadCache(name string, v any) bool { @@ -1632,6 +1833,13 @@ func runServe(args []string) error { return json.NewEncoder(os.Stdout).Encode(s.scan()) } + summaries, err := newSummarizer(*flagSummary, *flagSummaryModel, *flagSummaryAt, "", time.Now) + if err != nil { + return err + } + summaries.worktrees = func() *Snapshot { return s.snap.Load() } + summaries.prs = func() *PRSnapshot { return t.snap.Load() } + ctx, cancel := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM) defer cancel() @@ -1639,7 +1847,7 @@ func runServe(args []string) error { if err != nil { return err } - srv := &http.Server{Handler: serve(s, t, x, nil), ReadHeaderTimeout: 10 * time.Second} + srv := &http.Server{Handler: serve(s, t, x, nil, summaries), ReadHeaderTimeout: 10 * time.Second} go func() { if err := srv.Serve(ln); err != nil && !errors.Is(err, http.ErrServerClosed) { log.Fatal(err) @@ -1654,11 +1862,11 @@ func runServe(args []string) error { go advertise(ctx, mdns, ln.Addr().(*net.TCPAddr).Port) } - every := func(fn func(), fresh time.Time) { - if time.Since(fresh) > *flagInterval { // a recent cache is good enough for the first tick + every := func(interval time.Duration, fn func(), fresh time.Time) { + if time.Since(fresh) > interval { // a recent cache is good enough for the first tick fn() } - tick := time.NewTicker(*flagInterval) + tick := time.NewTicker(interval) defer tick.Stop() for { select { @@ -1669,13 +1877,16 @@ func runServe(args []string) error { } } } - go every(func() { s.scan() }, cachedWT.At) + go every(*flagInterval, func() { s.scan() }, cachedWT.At) prFresh := cachedPR.At if cachedHistory.At.Before(prFresh) { prFresh = cachedHistory.At } - go every(t.refresh, prFresh) - go every(func() { x.refresh(0) }, time.Time{}) + go every(*flagInterval, t.refresh, prFresh) + go every(*flagInterval, func() { x.refresh(0) }, time.Time{}) + if summaries.enabled { + go every(time.Minute, summaries.tick, time.Time{}) + } <-ctx.Done() shutdown, done := context.WithTimeout(context.Background(), 3*time.Second) diff --git a/main_test.go b/main_test.go index 2bb1cc6..d4cfa54 100644 --- a/main_test.go +++ b/main_test.go @@ -70,6 +70,7 @@ func TestDemoPages(t *testing.T) { pages := map[string][]string{ "/": {"claude/fix-auth-race", "codex/migrate-payments-ledger", "Fix token refresh race in auth middleware", "worktree remove"}, "/prs": {"Migrate payments to the v2 ledger", "test (postgres-16)", "acme-labs/tinyhttp", "ada/dotfiles", "tkowalski"}, + "/summary": {"Fix token refresh race in auth middleware", "In progress", "Waiting on you", "Blocked", "Done", "Unsorted sessions", "Other"}, "/sessions": {"Fix token refresh race in auth middleware", "claude --resume", "codex resume", "Scheduled: nightly-dependency-audit"}, "/api.json": {`"verdict":"merged"`, `"verdict":"prunable"`, `"verdict":"unmerged"`, `"verdict":"open"`, `"verdict":"keep"`}, "/api/prs.json": {`"state":"In merge queue"`, `"state":"Draft"`, `"state":"Conflicts"`}, @@ -620,7 +621,7 @@ func TestPageRemoveControls(t *testing.T) { t.Fatal("demo lacks a reclaimable worktree") } const never = "Commands are copied, never run here." - controls := []string{`id="remove-panel"`, `