diff --git a/CHANGELOG.md b/CHANGELOG.md index 8ea2a48..73e06c8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,22 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [Unreleased] + +### Added +- `hn front --feed` reads the `top`, `new`, `best`, `ask`, `show` and `job` lists. +- `hn read` flags `-n`, `--replies`, `--depth` and `--max-chars`, and comment IDs + in its output. `hn read COMMENT_ID` opens a collapsed thread. + +### Changed +- `hn read` caps its output by default, and says what it leaves out. `--expand` + shows everything. + +### Fixed +- `hn front` lists stories in site rank order. Algolia's `front_page` tag has + the right stories in another order. +- `hn read` lists comments in site rank order, not oldest first. + ## [0.3.0] — 2026-11-05 ### Added diff --git a/README.md b/README.md index 75e4e91..c85b245 100644 --- a/README.md +++ b/README.md @@ -41,8 +41,8 @@ $ hn front -n 3 3. [145pts 53c] The death of microservices @mfiguiere 6h ago https://example.com/microservices -$ hn read 43163011 --json | jq '.comments | length' -963 +$ hn read 43163011 --json | jq '.children | length' +412 ``` Run `hn --help` for the full command tree. @@ -100,13 +100,22 @@ hn search "github.com/voska" --url # Next page of results hn search "WASM" --page 1 -# Current front page +# Current front page, in site rank order hn front -# Read a story with comments (3 levels deep) +# Other feeds: new, best, ask, show, job +hn front --feed show -n 10 + +# Read a story with its top comments hn read 43163011 -# Read with all comments expanded +# Open a collapsed thread by comment ID +hn read 43163150 + +# Fewer comments, shorter +hn read 43163011 -n 5 --replies 1 --max-chars 300 + +# Read every comment in full hn read 43163011 --expand # User profile @@ -126,7 +135,7 @@ npx skills add -g voska/hn-cli ## API -Uses the [HN Algolia API](https://hn.algolia.com/api/v1/) for search and threads, and the [official Firebase API](https://github.com/HackerNews/API) for user profiles. Both are free and public, with no authentication or API keys required. +Uses the [HN Algolia API](https://hn.algolia.com/api/v1/) for search and threads, and the [official Firebase API](https://github.com/HackerNews/API) for site ranking and user profiles. Both are free and public, with no authentication or API keys required. ## Output Modes @@ -140,8 +149,8 @@ Uses the [HN Algolia API](https://hn.algolia.com/api/v1/) for search and threads | Command | Alias | Description | |---------|-------|-------------| | `search [query]` | `s` | Search stories or comments | -| `front` | `f` | Current front page stories | -| `read ` | `r` | Story with threaded comments | +| `front` | `f` | Stories in site rank order, from any feed | +| `read ` | `r` | Story or comment with its top comments | | `user ` | `u` | User profile and karma | | `status` | | API health check with latency | | `version` | | Version, commit, build date | diff --git a/internal/api/client.go b/internal/api/client.go index c0ed91d..a8e548f 100644 --- a/internal/api/client.go +++ b/internal/api/client.go @@ -8,8 +8,10 @@ import ( "net/http" "net/url" "regexp" + "sort" "strconv" "strings" + "sync" "time" ) @@ -20,6 +22,23 @@ const ( FirebaseURL = "https://hacker-news.firebaseio.com/v0" ) +const ( + // feedChunk is how many story IDs fit in one Algolia tag filter. + feedChunk = 100 + // maxConcurrent caps parallel Firebase requests. + maxConcurrent = 10 +) + +// feedLists maps feed names to Firebase story lists. +var feedLists = map[string]string{ + "top": "topstories", + "new": "newstories", + "best": "beststories", + "ask": "askstories", + "show": "showstories", + "job": "jobstories", +} + var ( // ErrNotFound means the requested item or user does not exist. ErrNotFound = errors.New("not found") @@ -120,6 +139,33 @@ type User struct { Karma int `json:"karma"` } +// firebaseItem is an item from the Firebase API. +type firebaseItem struct { + ID int `json:"id"` + By string `json:"by"` + Title string `json:"title"` + URL string `json:"url"` + Score int `json:"score"` + Descendants int `json:"descendants"` + Time int64 `json:"time"` + Dead bool `json:"dead"` + Deleted bool `json:"deleted"` + Kids []int `json:"kids"` +} + +func (f firebaseItem) hit() Hit { + return Hit{ + ObjectID: strconv.Itoa(f.ID), + Title: f.Title, + URL: f.URL, + Author: f.By, + Points: f.Score, + NumComments: f.Descendants, + CreatedAt: time.Unix(f.Time, 0).UTC().Format(time.RFC3339), + CreatedAtI: f.Time, + } +} + // SearchOptions configures a search request. type SearchOptions struct { Query string @@ -184,6 +230,177 @@ func (c *Client) Search(opts SearchOptions) (*SearchResult, error) { return &result, nil } +// FeedNames returns the valid feed names, sorted. +func FeedNames() []string { + names := make([]string, 0, len(feedLists)) + for name := range feedLists { + names = append(names, name) + } + sort.Strings(names) + return names +} + +// Feed returns the first n stories of a feed in site rank order. The order +// comes from Firebase and the details from Algolia, with single Firebase +// lookups for what Algolia lacks: job posts and stories not indexed yet. +func (c *Client) Feed(feed string, n int) (*SearchResult, error) { + list, ok := feedLists[feed] + if !ok { + return nil, fmt.Errorf("unknown feed %q (use %s)", feed, strings.Join(FeedNames(), ", ")) + } + + var ids []int + if err := c.getJSON(fmt.Sprintf("%s/%s.json", c.firebaseURL, list), &ids); err != nil { + return nil, fmt.Errorf("feed %s: %w", feed, err) + } + if n > 0 && n < len(ids) { + ids = ids[:n] + } + + found := make(map[string]Hit, len(ids)) + for start := 0; start < len(ids); start += feedChunk { + chunk := ids[start:min(start+feedChunk, len(ids))] + tags := make([]string, len(chunk)) + for i, id := range chunk { + tags[i] = fmt.Sprintf("story_%d", id) + } + result, err := c.Search(SearchOptions{ + Tags: "(story,job),(" + strings.Join(tags, ",") + ")", + NumResults: len(chunk), + }) + if err != nil { + return nil, err + } + for _, hit := range result.Hits { + found[hit.ObjectID] = hit + } + } + + if err := c.fillMissing(ids, found); err != nil { + return nil, err + } + + hits := make([]Hit, 0, len(ids)) + for _, id := range ids { + if hit, ok := found[strconv.Itoa(id)]; ok { + hits = append(hits, hit) + } + } + return &SearchResult{Hits: hits, NbHits: len(hits), HitsPerPage: len(ids)}, nil +} + +// fillMissing adds to found the ids it lacks, looked up on Firebase. Dead and +// deleted items stay out. +func (c *Client) fillMissing(ids []int, found map[string]Hit) error { + var missing []int + for _, id := range ids { + if _, ok := found[strconv.Itoa(id)]; !ok { + missing = append(missing, id) + } + } + + var ( + wg sync.WaitGroup + mu sync.Mutex + firstErr error + slots = make(chan struct{}, maxConcurrent) + ) + for _, id := range missing { + wg.Add(1) + slots <- struct{}{} + go func() { + defer wg.Done() + defer func() { <-slots }() + + fb, err := c.firebaseItem(id) + mu.Lock() + defer mu.Unlock() + switch { + case err != nil: + if firstErr == nil { + firstErr = err + } + case fb != nil && !fb.Dead && !fb.Deleted: + found[strconv.Itoa(id)] = fb.hit() + } + }() + } + wg.Wait() + return firstErr +} + +// firebaseItem fetches one item from the Firebase API. It returns nil when the +// item does not exist. +func (c *Client) firebaseItem(id int) (*firebaseItem, error) { + var fb *firebaseItem + if err := c.getJSON(fmt.Sprintf("%s/item/%d.json", c.firebaseURL, id), &fb); err != nil { + return nil, fmt.Errorf("item %d: %w", id, err) + } + return fb, nil +} + +// RankComments sorts item's comments into site rank order, and the replies of +// the first n comments too. Algolia returns comments oldest first, and only +// Firebase knows the ranking. Deeper replies stay oldest first. +func (c *Client) RankComments(item *Item, n int) error { + if err := c.rankChildren(item); err != nil { + return err + } + + children := item.Children + if n <= 0 { + return nil + } + if n < len(children) { + children = children[:n] + } + + var ( + wg sync.WaitGroup + slots = make(chan struct{}, maxConcurrent) + ) + for i := range children { + if len(children[i].Children) < 2 { + continue + } + wg.Add(1) + slots <- struct{}{} + go func() { + defer wg.Done() + defer func() { <-slots }() + // Replies are only reordered, so a failed lookup costs nothing. + _ = c.rankChildren(&children[i]) + }() + } + wg.Wait() + return nil +} + +func (c *Client) rankChildren(item *Item) error { + fb, err := c.firebaseItem(item.ID) + if err != nil { + return err + } + if fb == nil { + return fmt.Errorf("item %d: %w", item.ID, ErrNotFound) + } + + rank := make(map[int]int, len(fb.Kids)) + for i, id := range fb.Kids { + rank[id] = i + } + position := func(id int) int { + if r, ok := rank[id]; ok { + return r + } + return len(fb.Kids) + } + sort.SliceStable(item.Children, func(i, j int) bool { + return position(item.Children[i].ID) < position(item.Children[j].ID) + }) + return nil +} + // GetItem fetches a single item (story/comment) with its children. func (c *Client) GetItem(id string) (*Item, error) { var item Item diff --git a/internal/api/client_test.go b/internal/api/client_test.go index 34abca3..07dc979 100644 --- a/internal/api/client_test.go +++ b/internal/api/client_test.go @@ -5,6 +5,7 @@ import ( "errors" "net/http" "net/http/httptest" + "slices" "testing" "time" ) @@ -217,6 +218,96 @@ func TestClientErrorIsNotRetryable(t *testing.T) { } } +func TestFeed(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.URL.Path { + case "/topstories.json": + w.Write([]byte("[30,10,20,40,50]")) + case "/search": + if got := r.URL.Query().Get("tags"); got != "(story,job),(story_30,story_10,story_20,story_40)" { + t.Errorf("tags = %q", got) + } + json.NewEncoder(w).Encode(SearchResult{Hits: []Hit{ + {ObjectID: "10", Title: "ten"}, + {ObjectID: "30", Title: "thirty"}, + }}) + case "/item/20.json": + w.Write([]byte(`{"id":20,"type":"job","title":"twenty","by":"yc","score":1,"time":1700000000}`)) + case "/item/40.json": + w.Write([]byte(`{"id":40,"dead":true,"title":"forty"}`)) + default: + t.Errorf("unexpected request %s", r.URL.Path) + } + })) + defer srv.Close() + + c := testClient(srv) + result, err := c.Feed("top", 4) + if err != nil { + t.Fatalf("Feed() error: %v", err) + } + + var titles []string + for _, hit := range result.Hits { + titles = append(titles, hit.Title) + } + if want := []string{"thirty", "ten", "twenty"}; !slices.Equal(titles, want) { + t.Errorf("titles = %v, want %v", titles, want) + } + if result.Hits[2].CreatedAt != "2023-11-14T22:13:20Z" { + t.Errorf("CreatedAt = %q", result.Hits[2].CreatedAt) + } +} + +func TestFeedUnknown(t *testing.T) { + c := NewClient("", http.DefaultClient) + if _, err := c.Feed("nope", 1); err == nil { + t.Error("expected error for unknown feed") + } +} + +func TestRankComments(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.URL.Path { + case "/item/1.json": + w.Write([]byte(`{"id":1,"kids":[4,2]}`)) + case "/item/4.json": + w.Write([]byte(`{"id":4,"kids":[6,5]}`)) + default: + t.Errorf("unexpected request %s", r.URL.Path) + } + })) + defer srv.Close() + + item := &Item{ID: 1, Children: []Item{ + {ID: 2, Children: []Item{{ID: 8}, {ID: 7}}}, + {ID: 3}, + {ID: 4, Children: []Item{{ID: 5}, {ID: 6}}}, + }} + + c := testClient(srv) + if err := c.RankComments(item, 1); err != nil { + t.Fatalf("RankComments() error: %v", err) + } + + ids := func(items []Item) []int { + var out []int + for _, it := range items { + out = append(out, it.ID) + } + return out + } + if got, want := ids(item.Children), []int{4, 2, 3}; !slices.Equal(got, want) { + t.Errorf("comments = %v, want %v", got, want) + } + if got, want := ids(item.Children[0].Children), []int{6, 5}; !slices.Equal(got, want) { + t.Errorf("ranked replies = %v, want %v", got, want) + } + if got, want := ids(item.Children[1].Children), []int{8, 7}; !slices.Equal(got, want) { + t.Errorf("replies past n = %v, want %v", got, want) + } +} + func TestCleanHTML(t *testing.T) { tests := []struct { name string diff --git a/internal/cmd/root.go b/internal/cmd/root.go index 075de19..0e55689 100644 --- a/internal/cmd/root.go +++ b/internal/cmd/root.go @@ -176,17 +176,17 @@ func init() { // --- front --- -var frontNum int +var ( + frontNum int + frontFeed string +) var frontCmd = &cobra.Command{ Use: "front", Aliases: []string{"f"}, - Short: "Current front page stories", + Short: "Stories in site rank order", RunE: func(cmd *cobra.Command, args []string) error { - result, err := client().Search(api.SearchOptions{ - Tags: "front_page", - NumResults: frontNum, - }) + result, err := client().Feed(frontFeed, frontNum) if err != nil { return err } @@ -198,40 +198,66 @@ var frontCmd = &cobra.Command{ if jsonOutput { return output.JSON(result) } - output.FormatFrontPage(os.Stdout, result) + output.FormatFeed(os.Stdout, result, frontFeed) return nil }, } func init() { frontCmd.Flags().IntVarP(&frontNum, "num", "n", 30, "Number of stories") + frontCmd.Flags().StringVar(&frontFeed, "feed", "top", "Feed: "+strings.Join(api.FeedNames(), ", ")) } // --- read --- -var readExpand bool +var ( + readNum int + readReplies int + readDepth int + readMaxChars int + readExpand bool +) var readCmd = &cobra.Command{ Use: "read ID", Aliases: []string{"r"}, - Short: "Read a story with comments", - Args: cobra.ExactArgs(1), + Short: "Read a story or comment with its top comments", + Long: `Read a story or comment with its comments in site rank order. The output is +capped to fit an agent's context, and names what it leaves out. Comment IDs +open a collapsed thread: hn read COMMENT_ID. + +--json returns the whole tree and ignores the caps. Only top-level comments +and the direct replies of the first -n comments are in rank order.`, + Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { item, err := client().GetItem(args[0]) if err != nil { return err } + opts := output.ReadOptions{Num: readNum, Replies: readReplies, Depth: readDepth, MaxChars: readMaxChars} + if readExpand { + opts = output.ReadOptions{Replies: -1, Depth: -1} + } + + if err := client().RankComments(item, opts.Num); err != nil { + fmt.Fprintf(os.Stderr, "warning: comments are oldest first: %v\n", err) + } + if jsonOutput { return output.JSON(item) } - output.FormatItem(os.Stdout, item, readExpand) + output.FormatItem(os.Stdout, item, opts) return nil }, } func init() { - readCmd.Flags().BoolVar(&readExpand, "expand", false, "Show all comments expanded") + readCmd.Flags().IntVarP(&readNum, "num", "n", 20, "Top comments to show, 0 for all") + readCmd.Flags().IntVar(&readReplies, "replies", 3, "Replies to show per comment") + readCmd.Flags().IntVar(&readDepth, "depth", 1, "Levels of replies to show") + readCmd.Flags().IntVar(&readMaxChars, "max-chars", 800, "Characters per comment, 0 for no cap") + readCmd.Flags().BoolVar(&readExpand, "expand", false, "Show every comment in full") } // --- user --- diff --git a/internal/output/format.go b/internal/output/format.go index 499a2ce..601f324 100644 --- a/internal/output/format.go +++ b/internal/output/format.go @@ -39,10 +39,7 @@ func formatStory(w io.Writer, n int, hit api.Hit) { func formatComment(w io.Writer, n int, hit api.Hit) { ago := timeAgo(hit.CreatedAt) - text := api.CleanHTML(hit.CommentText) - if len(text) > 200 { - text = text[:200] + "..." - } + text := truncate(api.CleanHTML(hit.CommentText), 200) text = strings.ReplaceAll(text, "\n", " ") storyTitle := hit.StoryTitle @@ -54,28 +51,42 @@ func formatComment(w io.Writer, n int, hit api.Hit) { fmt.Fprintf(w, " HN: https://news.ycombinator.com/item?id=%s\n", hit.ObjectID) } -// FormatFrontPage prints front page stories in compact plaintext. -func FormatFrontPage(w io.Writer, result *api.SearchResult) { +// FormatFeed prints a story feed in compact plaintext. +func FormatFeed(w io.Writer, result *api.SearchResult, feed string) { if len(result.Hits) == 0 { - fmt.Fprintln(w, "No stories on front page.") + fmt.Fprintln(w, "No stories.") return } - fmt.Fprintf(w, "Front page (%d stories):\n", len(result.Hits)) + title := "Front page" + if feed != "top" { + title = "Feed " + feed + } + fmt.Fprintf(w, "%s (%d stories):\n", title, len(result.Hits)) for i, hit := range result.Hits { formatStory(w, i+1, hit) } } -// FormatItem prints a story with its comments. -func FormatItem(w io.Writer, item *api.Item, expand bool) { +// ReadOptions caps the comments FormatItem prints. +type ReadOptions struct { + Num int // top comments, 0 for all + Replies int // replies per comment, negative for all + Depth int // levels of replies, negative for all + MaxChars int // characters per comment, 0 for no cap +} + +// FormatItem prints a story or comment with its comments. +func FormatItem(w io.Writer, item *api.Item, opts ReadOptions) { pts := 0 if item.Points != nil { pts = *item.Points } ago := timeAgo(item.CreatedAt) - fmt.Fprintf(w, "%s\n", item.Title) + if item.Title != "" { + fmt.Fprintf(w, "%s\n", item.Title) + } fmt.Fprintf(w, "@%s %dpts %s\n", item.Author, pts, ago) if item.URL != "" { fmt.Fprintf(w, "%s\n", item.URL) @@ -93,11 +104,11 @@ func FormatItem(w io.Writer, item *api.Item, expand bool) { } fmt.Fprintf(w, "\n--- %d comments ---\n", commentCount) - if expand { - printComments(w, item.Children, 0, -1) - } else { - printComments(w, item.Children, 0, 3) + limit := opts.Num + if limit <= 0 { + limit = -1 } + printComments(w, item.Children, 0, limit, opts) } // FormatUser prints user profile in compact plaintext. @@ -116,34 +127,48 @@ func JSON(v any) error { return enc.Encode(v) } -func printComments(w io.Writer, children []api.Item, depth int, maxDepth int) { - if maxDepth >= 0 && depth > maxDepth { - return - } - +func printComments(w io.Writer, children []api.Item, depth, limit int, opts ReadOptions) { indent := strings.Repeat(" ", depth) - for _, c := range children { + + shown := 0 + for i, c := range children { if c.Author == "" && c.Text == "" { continue } + if limit >= 0 && shown == limit { + noun := "replies" + if depth == 0 { + noun = "comments" + } + fmt.Fprintf(w, "%s[%d more %s]\n", indent, countComments(children[i:]), noun) + return + } + shown++ + ago := timeAgo(c.CreatedAt) - fmt.Fprintf(w, "%s@%s %s\n", indent, c.Author, ago) - text := api.CleanHTML(c.Text) + fmt.Fprintf(w, "%s@%s %s #%d\n", indent, c.Author, ago, c.ID) + text := truncate(api.CleanHTML(c.Text), opts.MaxChars) for _, line := range strings.Split(text, "\n") { fmt.Fprintf(w, "%s %s\n", indent, line) } - if len(c.Children) > 0 { - if maxDepth >= 0 && depth+1 > maxDepth { - collapsed := countComments(c.Children) - if collapsed > 0 { - fmt.Fprintf(w, "%s [%d more replies]\n", indent, collapsed) - } - } else { - printComments(w, c.Children, depth+1, maxDepth) + if opts.Depth >= 0 && depth >= opts.Depth { + if collapsed := countComments(c.Children); collapsed > 0 { + fmt.Fprintf(w, "%s [%d more replies]\n", indent, collapsed) } + continue } + printComments(w, c.Children, depth+1, opts.Replies, opts) + } +} + +// truncate caps s at maxChars characters and says how many it dropped. +func truncate(s string, maxChars int) string { + runes := []rune(s) + if maxChars <= 0 || len(runes) <= maxChars { + return s } + return fmt.Sprintf("%s... [+%d chars]", string(runes[:maxChars]), len(runes)-maxChars) } func countComments(children []api.Item) int { diff --git a/internal/output/format_test.go b/internal/output/format_test.go index 4b1a8e2..39a46e3 100644 --- a/internal/output/format_test.go +++ b/internal/output/format_test.go @@ -48,6 +48,79 @@ func TestFormatSearchResults(t *testing.T) { } } +func TestFormatItemCaps(t *testing.T) { + story := &api.Item{ + ID: 1, + Title: "Story", + Author: "pg", + Children: []api.Item{ + {ID: 2, Author: "a", Text: "first", Children: []api.Item{ + {ID: 3, Author: "b", Text: "reply one", Children: []api.Item{{ID: 4, Author: "c", Text: "deep"}}}, + {ID: 5, Author: "d", Text: "reply two"}, + {ID: 6, Author: "e", Text: "reply three"}, + }}, + {ID: 7, Author: "f", Text: strings.Repeat("é", 20)}, + {ID: 8, Author: "g", Text: "hidden", Children: []api.Item{{ID: 9, Author: "h", Text: "hidden too"}}}, + }, + } + + var buf strings.Builder + FormatItem(&buf, story, ReadOptions{Num: 2, Replies: 1, Depth: 1, MaxChars: 10}) + out := buf.String() + + for _, want := range []string{ + "--- 8 comments ---", + "@a ", + "#2\n", + "reply one", + "[1 more replies]", + "[2 more replies]", + strings.Repeat("é", 10) + "... [+10 chars]", + "[2 more comments]", + } { + if !strings.Contains(out, want) { + t.Errorf("expected %q in output:\n%s", want, out) + } + } + for _, unwanted := range []string{"deep", "reply two", "hidden"} { + if strings.Contains(out, unwanted) { + t.Errorf("did not expect %q in output:\n%s", unwanted, out) + } + } +} + +func TestFormatItemExpanded(t *testing.T) { + story := &api.Item{ID: 1, Title: "Story", Children: []api.Item{ + {ID: 2, Author: "a", Text: "one", Children: []api.Item{ + {ID: 3, Author: "b", Text: "two", Children: []api.Item{{ID: 4, Author: "c", Text: "three"}}}, + }}, + }} + + var buf strings.Builder + FormatItem(&buf, story, ReadOptions{Replies: -1, Depth: -1}) + out := buf.String() + + if !strings.Contains(out, "three") || strings.Contains(out, "more") { + t.Errorf("expected the full thread, got:\n%s", out) + } +} + +func TestFormatFeed(t *testing.T) { + result := &api.SearchResult{Hits: []api.Hit{{ObjectID: "1", Title: "Launch"}}} + + var buf strings.Builder + FormatFeed(&buf, result, "top") + if !strings.Contains(buf.String(), "Front page (1 stories):") { + t.Errorf("unexpected header: %q", buf.String()) + } + + buf.Reset() + FormatFeed(&buf, result, "show") + if !strings.Contains(buf.String(), "Feed show (1 stories):") { + t.Errorf("unexpected header: %q", buf.String()) + } +} + func TestFormatUser(t *testing.T) { user := &api.User{ Username: "pg", diff --git a/skills/hn/SKILL.md b/skills/hn/SKILL.md index e7f2365..f2f37ec 100644 --- a/skills/hn/SKILL.md +++ b/skills/hn/SKILL.md @@ -28,11 +28,15 @@ hn search "example.com" --url # Match story URLs only hn search "query" --page 1 # Next page, starting at 0 hn search --tag show_hn --sort date # The query is optional -hn front # Current front page stories +hn front # Front page in site rank order hn front -n 10 # Fewer results +hn front --feed show # top, new, best, ask, show or job -hn read ID # Read story + top comments -hn read ID --expand # All comments expanded +hn read ID # Story + top comments, capped +hn read ID -n 5 --replies 1 # Fewer comments +hn read ID --max-chars 300 # Shorter comments +hn read COMMENT_ID # Open a collapsed thread +hn read ID --expand # Every comment in full hn user USERNAME # User profile and karma @@ -47,7 +51,9 @@ Aliases: `hn s` = `hn search`, `hn f` = `hn front`, `hn r` = `hn read`, `hn u` = 1. Search or browse front page: `hn search "topic" -n 5` or `hn front` 2. Note the item ID from the HN URL in results 3. Read the full story + comments: `hn read ID` -4. Expand all comments if needed: `hn read ID --expand` +4. Open a thread with `hn read COMMENT_ID`, using the `#ID` on any comment +5. Use `--expand` only when you need the whole thread: a big one costs tens of + thousands of tokens ## Output Format @@ -65,8 +71,10 @@ to files -- never use `--json` in LLM context. ### Read output -Full story title, metadata, URL, body text, and threaded comments with author -and timestamps. Top 3 levels by default, `--expand` for all. +Full story title, metadata, URL, body text, and comments in site rank order +with author, timestamp and `#ID`. By default 20 comments, 3 replies each, one +level of replies and 800 characters per comment. Cuts show as `[N more replies]`, +`[N more comments]` and `[+N chars]`. ### User output