Skip to content
Merged
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
2 changes: 2 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ code, with short docstrings explaining why.
- `src/swellsense/extraction/`: structured extraction (boards, unit parsing)
- `src/swellsense/ingest/`: source registry, fetchers, raw document storage, ingest runs
- `src/swellsense/processing/`: cleaning, chunking, and the process run
- `src/swellsense/retrieval/`: vector search over stored chunks
- `src/swellsense/db/`: local Postgres connection and schema
- `src/swellsense/spots/`: spot profiles and the registry that loads them
- `src/swellsense/tides/`: LINZ Tauranga predictions and tide state at a time
Expand All @@ -77,6 +78,7 @@ code, with short docstrings explaining why.
- Apply lint and format fixes: `uv run ruff check --fix && uv run ruff format`
- Download sources: `uv run swellsense ingest` (or `--source ID` for one)
- Process raw pages: `uv run swellsense process` (reads `data/raw/`, embeds via the configured provider, upserts into local Postgres)
- Vector search (debug): `uv run swellsense search "QUESTION"` (optional `--k N`, default 5)
- Tauranga tides: `uv run swellsense tides` (or `--date YYYY-MM-DD`)
- Spot forecast: `uv run swellsense forecast SPOT` (or `--hours N`, default 12)
- Conditions check: `uv run swellsense check SPOT` (or `--hours N`, default 12); `uv run swellsense check --all` ranks every spot, with ties shown as ties; `--skill LEVEL` lists harder spots separately
Expand Down
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,8 @@ In `.env`, set `HTTP_USER_AGENT` to identify the project to source sites, for ex
| `uv run swellsense ingest` | Download all sources into `data/raw/` |
| `uv run swellsense ingest --source wikipedia` | Download a single source |
| `uv run swellsense process` | Clean, chunk and embed `data/raw/` into Postgres |
| `uv run swellsense search "what is a rip?"` | Vector search over embedded chunks (debug) |
| `uv run swellsense search "swell period" --k 10` | Return more nearest chunks |
| `uv run swellsense tides` | Print today's Tauranga highs and lows |
| `uv run swellsense tides --date 2026-01-15` | Print one day's Tauranga tides |
| `uv run swellsense forecast mount-main-beach` | Print 12 hours of swell and wind for a spot |
Expand Down
52 changes: 52 additions & 0 deletions src/swellsense/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
rank. ``--skill`` keeps harder spots in a separate list.
``db init`` creates the local Postgres schema (pgvector, documents, chunks).
``process`` cleans, chunks and embeds raw pages into Postgres.
``search`` runs vector retrieval over stored chunks for debugging.
"""

import argparse
Expand All @@ -33,6 +34,7 @@
from swellsense.ingest.store import load_all
from swellsense.llm.embeddings import embed
from swellsense.processing.run import PostgresChunkStore, ProcessReport, process
from swellsense.retrieval import retrieve
from swellsense.spots.models import Spot
from swellsense.spots.registry import get_spot, load_spots
from swellsense.tides.linz import (
Expand Down Expand Up @@ -65,6 +67,23 @@ def _main(argv: list[str] | None = None) -> int:
help="Clean, chunk and embed data/raw into Postgres",
)

search_parser = subparsers.add_parser(
"search",
help="Vector search over embedded chunks (debug)",
)
search_parser.add_argument(
"query",
nargs="+",
metavar="QUESTION",
help="Natural-language question",
)
search_parser.add_argument(
"--k",
type=int,
default=5,
help="How many chunks to return (default: 5)",
)

tides_parser = subparsers.add_parser(
"tides", help="Print Tauranga high and low waters for one day"
)
Expand Down Expand Up @@ -126,6 +145,8 @@ def _main(argv: list[str] | None = None) -> int:
return _ingest(args.source)
if args.command == "process":
return _process()
if args.command == "search":
return _search(" ".join(args.query), args.k)
if args.command == "tides":
return _tides(args.date)
if args.command == "forecast":
Expand All @@ -152,6 +173,37 @@ def _db_init() -> int:
return 0


def _search_preview(text: str, *, word_limit: int = 25) -> str:
words = text.split()
if len(words) <= word_limit:
return text
return " ".join(words[:word_limit]) + "..."


def _search(query: str, k: int) -> int:
try:
conn = connect()
try:
hits = retrieve(conn, query, k)
finally:
conn.close()
except (psycopg.Error, openai.APIError) as exc:
print(str(exc), file=sys.stderr)
return 1

if not hits:
print("No results.")
return 0

for rank, hit in enumerate(hits, start=1):
print(f"{rank}. {hit.distance:.3f}")
print(f"{hit.title} > {hit.section}")
print(hit.url)
print(_search_preview(hit.text))
print()
return 0


def _process() -> int:
try:
docs = load_all()
Expand Down
5 changes: 5 additions & 0 deletions src/swellsense/retrieval/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
"""Retrieval over the chunk store."""

from swellsense.retrieval.search import retrieve

__all__ = ["retrieve"]
37 changes: 37 additions & 0 deletions src/swellsense/retrieval/search.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
"""Vector retrieval over embedded knowledge chunks."""

from __future__ import annotations

from collections.abc import Callable
from typing import TYPE_CHECKING

from swellsense.db.chunks import ChunkHit, nearest
from swellsense.llm.embeddings import embed

if TYPE_CHECKING:
import psycopg


def retrieve(
conn: psycopg.Connection,
query: str,
k: int = 5,
*,
embed_fn: Callable[..., list[list[float]]] = embed,
search_fn: Callable[..., list[ChunkHit]] = nearest,
) -> list[ChunkHit]:
"""Return the k nearest public chunks for a natural-language query.

Vector search only for now; keyword search, hybrid fusion and a relevance
gate arrive in later roadmap slices.
"""
if k < 1:
msg = f"k must be at least 1, got {k}"
raise ValueError(msg)

stripped = query.strip()
if not stripped:
return []

vector = embed_fn([stripped], "query")[0]
return search_fn(conn, vector, k, public_only=True)
95 changes: 95 additions & 0 deletions tests/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import pytest

from swellsense.cli import main
from swellsense.db.chunks import ChunkHit
from swellsense.forecast.models import AUCKLAND, HourlyConditions, SpotForecast
from swellsense.forecast.openmeteo import OPEN_METEO_ATTRIBUTION
from swellsense.ingest.run import RunReport, SourceReport
Expand Down Expand Up @@ -99,6 +100,100 @@ def fail():
assert capsys.readouterr().err.strip() == "connection refused"


def _search_hit(
*,
title: str = "Surfing",
section: str = "Rips",
url: str = "https://example.test/surfing",
text: str = "Short chunk text.",
distance: float = 0.4567,
) -> ChunkHit:
return ChunkHit(
id="doc#0",
document_id="doc",
index=0,
section=section,
text=text,
title=title,
url=url,
license="CC BY-SA 4.0",
attribution="Wiki",
usage="open",
distance=distance,
)


def test_search_prints_hits_and_exits_0(capsys, monkeypatch):
long_text = " ".join(f"w{i}" for i in range(30))
hits = [
_search_hit(distance=0.4567, text=long_text),
_search_hit(
title="Swell",
section="Period",
url="https://example.test/swell",
text="Only five words here total",
distance=1.0,
),
]

monkeypatch.setattr("swellsense.cli.connect", lambda: _FakeConn())
monkeypatch.setattr("swellsense.cli.retrieve", lambda conn, query, k: hits)

with pytest.raises(SystemExit) as caught:
main(["search", "rip", "currents", "--k", "2"])

assert caught.value.code == 0
out = capsys.readouterr().out
assert out.startswith("1. 0.457\nSurfing > Rips\nhttps://example.test/surfing\n")
preview = " ".join(f"w{i}" for i in range(25)) + "..."
assert preview in out
assert (
"2. 1.000\n"
"Swell > Period\n"
"https://example.test/swell\n"
"Only five words here total\n"
) in out


def test_search_no_results_exits_0(capsys, monkeypatch):
monkeypatch.setattr("swellsense.cli.connect", lambda: _FakeConn())
monkeypatch.setattr("swellsense.cli.retrieve", lambda conn, query, k: [])

with pytest.raises(SystemExit) as caught:
main(["search", "nothing"])

assert caught.value.code == 0
assert capsys.readouterr().out == "No results.\n"


def test_search_postgres_unreachable_exits_1(capsys, monkeypatch):
def fail():
raise psycopg.OperationalError("connection refused")

monkeypatch.setattr("swellsense.cli.connect", fail)

with pytest.raises(SystemExit) as caught:
main(["search", "swell"])

assert caught.value.code == 1
assert capsys.readouterr().err.strip() == "connection refused"


def test_search_ollama_unreachable_exits_1(capsys, monkeypatch):
def fail_retrieve(*args, **kwargs):
del args, kwargs
raise openai.APIConnectionError(message="connection failed", request=None)

monkeypatch.setattr("swellsense.cli.connect", lambda: _FakeConn())
monkeypatch.setattr("swellsense.cli.retrieve", fail_retrieve)

with pytest.raises(SystemExit) as caught:
main(["search", "swell"])

assert caught.value.code == 1
assert capsys.readouterr().err.strip() == "connection failed"


def test_process_ollama_unreachable_exits_1(capsys, monkeypatch):
conn = _FakeConn()

Expand Down
75 changes: 75 additions & 0 deletions tests/test_retrieval.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
"""Unit tests for vector retrieval (no network, no database)."""

from __future__ import annotations

import pytest

from swellsense.db.chunks import ChunkHit
from swellsense.retrieval.search import retrieve


def _hit(index: int, *, text: str = "body") -> ChunkHit:
return ChunkHit(
id=f"doc#{index}",
document_id="doc",
index=index,
section="Intro",
text=text,
title="Surfing",
url="https://example.test/surfing",
license="CC BY-SA 4.0",
attribution="Wiki",
usage="open",
distance=0.1 * index,
)


def test_empty_or_whitespace_query_skips_embed_and_search():
calls: list[str] = []

def embed_fn(texts, kind):
calls.append("embed")
return [[0.0]]

def search_fn(conn, vector, k, public_only):
calls.append("search")
return []

conn = object()
assert retrieve(conn, "", embed_fn=embed_fn, search_fn=search_fn) == []
assert retrieve(conn, " \t\n", embed_fn=embed_fn, search_fn=search_fn) == []
assert calls == []


def test_passes_query_kind_k_and_public_only():
seen: dict[str, object] = {}

def embed_fn(texts, kind):
seen["texts"] = texts
seen["kind"] = kind
return [[1.0, 2.0]]

def search_fn(conn, vector, k, public_only):
seen["conn"] = conn
seen["vector"] = vector
seen["k"] = k
seen["public_only"] = public_only
return [_hit(0), _hit(1)]

conn = object()
hits = retrieve(
conn, " rip currents ", k=3, embed_fn=embed_fn, search_fn=search_fn
)

assert seen["texts"] == ["rip currents"]
assert seen["kind"] == "query"
assert seen["conn"] is conn
assert seen["vector"] == [1.0, 2.0]
assert seen["k"] == 3
assert seen["public_only"] is True
assert [h.index for h in hits] == [0, 1]


def test_k_zero_raises():
with pytest.raises(ValueError, match="k must be at least 1"):
retrieve(object(), "swell", k=0)
Loading