Jakob WennbergandClaude Opus 4.7 6629964780 fix(mcp): unblock query_journal text search across line + entry descriptions (#605)
* fix(mcp): unblock query_journal text search across line+entry descriptions

`gnubok_query_journal` issued a single PostgREST `.or()` filter mixing a
base-table column (line_description on journal_entry_lines) with a column
on the embedded inner-joined resource (journal_entries.description).
PostgREST's flat comma OR syntax cannot span base and embedded resources
and returned 400 "failed to parse logic tree" on every free-text search,
so the agent could not look up history (e.g. "har vi bokfört Google
innan?") via the MCP tool.

Refactor: pull the common filter chain into a `buildBaseQuery()` helper
and issue two parallel `.ilike()` queries — one on `line_description`,
one on `journal_entries.description` — then merge by line id, re-sort,
and slice to `limit`. Same pattern as
`lib/invoices/duplicate-payment-candidates.ts`, with the same rationale
(LIKE-DSL injection risk + cross-embed unsupported).

Drops the obsolete comma-stripping pre-processing on the search term
(only needed because the value was being injected into PostgREST's OR
DSL); LIKE wildcard escaping (`%` and `_`) is preserved.

Adds four tests covering: merge across both legs, dedup of cross-leg
overlap, correct columns + escaped pattern sent to `.ilike`, and
LIKE-wildcard escape end-to-end. Existing amount-filter / accounts-cap /
truncation tests unchanged.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(mcp): query_journal PR review — honest truncation, wider leg, error sanitisation

Address PR #605 review (Greptile + compliance swarm).

- truncated math: previously dbMatched = byLine.count + byEntry.count
  inflated the counter every time a row matched both legs (e.g. an entry
  whose line description AND header description both contain "Google").
  total_lines was off by up to 2× and truncated was forced true even when
  every distinct match was already returned, sending the agent into
  unnecessary narrow-and-retry loops. dbMatched is now merged.size — the
  honest distinct-row count among what we fetched. A new legCapHit signal
  drives truncated when either leg's fetch window filled, so we never lie
  the other direction either.

- per-leg fetch widened to 2 × limit. Previously each leg was capped at
  `limit` independently, so when one column was much more selective than
  the other (e.g. 150 line matches vs 5 entry matches), the merge could
  drop globally-ranked rows from the chronologically newer tail. The
  final slice still caps at `limit`; the wider per-leg window just gives
  the merge a better tail to choose from.

- text input length cap (200 chars). Defence-in-depth against pathological
  inputs even though .ilike() parameterises the value (compliance A.8.28).

- error sanitisation in the text-search path. Raw PostgREST messages can
  surface internal schema details (table names, constraint names) to the
  caller. We now log details server-side via the existing module logger
  and throw a generic message (compliance V16).

- comma-stripping rationale documented inline so the next reviewer
  doesn't re-add it. The previous defence was needed because the value
  was injected into PostgREST's OR DSL where `,` is the separator; the
  parameterised .ilike() path treats `,` as a literal and stripping it
  would mangle real-comma searches (compliance V1.2.5).

Adds 4 regression tests: overlap-doesn't-falsely-truncate, leg-cap-hit
flags truncated, text>200 rejected, raw schema name never leaked. All
14 query_journal tests pass; 266/266 MCP suite green; build clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(mcp): query_journal PR review round 2 — schema guards, leg cap, audit log

Address compliance swarm findings on commit 3dfab46c.

- text input: add `maxLength: 200` to the JSON Schema so the limit is
  enforced at the boundary by the MCP runtime, not only inside execute().
  Inline guard kept as belt-and-suspenders (ASVS V2.2, ISO 27001 A.8.28).
- limit input: add `minimum: 1, maximum: 500` to the JSON Schema (matches
  the existing Math.min cap inside execute()) so the bound is visible to
  agents and enforced declaratively.
- legLimit hard cap: `Math.min(limit * 2, 500)`. Previously legLimit
  scaled with limit unbounded, so a maxed-out limit triggered 2×1000-row
  fetches. Cap is independent of the caller-supplied limit (ASVS V2.3).
- audit log: include `userId` alongside `companyId` in both log.warn
  payloads so failed-query events can be correlated to the actor for
  incident investigation (ASVS V16, SOC 2 CC7.2).
- new test: assert both parallel ilike legs in the text-search path issue
  `.eq('journal_entries.company_id', companyId)` — defence-in-depth
  against a future refactor accidentally dropping tenant scoping from
  one leg (SOC 2 CC6.1).

Not addressed (with rationale):

- ASVS V1.2.5 / SOC 2 CC7.2 "log.warn body contains raw PostgREST error
  text". The swedish-accounting-compliance reviewer explicitly cleared
  this on the same commit ("the schema-leak is plugged in both paths").
  The thrown error is generic; raw detail lives only in internal
  structured logs (Sentry, etc.) where it is needed for incident triage.
  Same pattern is used by 20+ other tools in this file; scrubbing only
  this one is inconsistent. Defer to a project-wide logger sanitiser.

- Swedish reviewer's "reversed mixed with posted in status=all": false
  positive — `status` IS surfaced per line in the response shape (see
  the lines.map projection in server.ts).

- Swedish reviewer's "debit XOR credit not enforced": insert-time
  concern, not a read-tool concern. Out of scope.

Tests: 15 query_journal cases (4 new this round); 267 MCP suite; build
clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-29 14:21:46 +02:00
2026-05-28 15:43:48 +02:00
2026-05-28 15:43:48 +02:00
2026-05-06 11:12:02 +02:00
2026-04-22 15:33:04 +02:00
2026-05-28 15:43:48 +02:00
2026-05-22 12:22:15 +02:00

gnubok

Open-source Swedish accounting software for sole traders (enskild firma) and limited companies (aktiebolag).

License: AGPL-3.0-or-later

What is gnubok?

gnubok implements double-entry bookkeeping compliant with Swedish accounting law (Bokforingslagen). It supports the BAS 2026 chart of accounts, handles VAT declarations (momsdeklaration), SIE import/export, and enforces 7-year document retention. Built for sole traders and limited companies operating in Sweden.

Features

  • Double-entry bookkeeping -- BAS 2026 chart of accounts, draft/commit workflow, sequential voucher numbering
  • Invoicing -- Create, send, and track invoices with mixed VAT rates and PDF generation
  • Bank reconciliation -- PSD2 bank connection via Enable Banking, 4-pass automatic matching
  • VAT declaration -- SKV 4700 form mapping, per-rate breakdown, EU/export handling
  • Tax reports -- NE-bilaga, INK2, SRU export for Skatteverket
  • Supplier invoices -- Registration, payment tracking, input VAT deduction
  • Document archive -- SHA-256 integrity, 7-year retention enforcement, full archive ZIP export
  • SIE import/export -- Standard Swedish accounting interchange format
  • Extension system -- Opt-in plugins for AI categorization, receipt OCR, email, calendar, and more

Self-Hosting

git clone https://github.com/erp-mafia/gnubok.git
cd gnubok
./setup.sh              # Prompts for Supabase credentials, generates .env
docker compose up -d

You need a Supabase project and must apply the database migrations before first use. See SELF-HOSTING.md for the full step-by-step guide, including Supabase setup, auth configuration, optional features (AI, email, push notifications), and troubleshooting.

Development Setup

Prerequisites: Node.js 20+, a Supabase project.

npm install
npm run dev       # Start dev server (auto-generates extension registry)
npm test          # Run tests
npm run build     # Production build
npm run lint      # ESLint

Tech Stack

  • Framework: Next.js 16 (App Router), React 19, TypeScript (strict)
  • Database: Supabase (PostgreSQL + Row Level Security + email/password auth + TOTP MFA)
  • Styling: Tailwind CSS 4 + shadcn/ui
  • Integrations: Enable Banking (PSD2), Anthropic SDK, LangChain, OpenAI, Resend, JSZip

Documentation

  • SELF-HOSTING.md -- Full self-hosting guide (Docker, Supabase setup, migrations, optional features)
  • CLAUDE.md -- Architecture, bookkeeping engine, database conventions, extension system
  • CONTRIBUTING.md -- Development workflow, code style, pull request process
  • SECURITY.md -- Vulnerability reporting policy

Contributing

Contributions are welcome. See CONTRIBUTING.md for the full guide.

All commits require a DCO sign-off (git commit -s).

License

AGPL-3.0-or-later with an extension exception: third-party extensions that interact solely through the documented Extension API may be licensed under any terms, including proprietary. See LICENSE for details and NOTICE for third-party attributions.

S
Description
Accounted — svensk bokföringsmotor (AGPL, BAS 2026, BFL-compliant, 150+ MCP tools). Finance-kapacitet brevet ERPNext. ADR-ENGAGEMENT-001-tillägg.
Readme AGPL-3.0
56 MiB
Languages
TypeScript 93%
PLpgSQL 5.8%
JavaScript 0.4%
HTML 0.3%
MDX 0.2%
Other 0.1%