Self-hosted project management for devs and their clients: tickets, time tracking, docs and meetings, with an AI assistant that cites its sources. AGPL-3.0.
Ruby agplai-assistantdockerdsgvogdprhotwireissue-trackerjira-alternativeknowledge-basellmmcp-servermeeting-notesopen-sourceproject-managementredmine-alternativeruby-on-railsself-hostedticketingtime-tracking
Extract the knowledge lookup of search_knowledge into Knowledge::Lookup
Guido Boyke3b8b8c047d87
diff --git a/app/services/knowledge/lookup.rb b/app/services/knowledge/lookup.rbnew file mode 100644index 0000000..4cc8a56--- /dev/null+++ b/app/services/knowledge/lookup.rb@@ -0,0 +1,169 @@+# frozen_string_literal: true++# The knowledge of a project (notes and documents) by title, one rule for two surfaces+# (cli_rest_plan D5): the MCP tool search_knowledge and GET /api/v1/projects/:project_id/knowledge+# read the same rows through this object. Each surface keeps its own envelope: the tool adds+# citations and requires a search term, REST also lists without one.+#+# Security (project mode, D7): every row comes through Pundit.policy_scope!, per type, in the+# project context. A reader without read access to a type gets no row of that type and no count+# of it, never a foreign title. The per-type search arm (incl. the document -> current_version+# title join) is Knowledge::TypeRegistry's, the link Documentation::KnowledgeLink's.+#+# Title only, not content: a lookup is for finding an object to link, and searching bodies+# would surface content the link never reveals. We do NOT reuse KnowledgeSearchQuery: it gates+# by whole-type accessible keys rather than per-record policy_scope, and its UNION/pagy/+# smart-folder machinery is far heavier than a title lookup needs.+#+# Entry point: options+module Knowledge+ class Lookup+ # Cap shared with the ticket list and the HTTP API, so both agent-facing surfaces bound a+ # page the same way.+ MAX_PER_PAGE = Tickets::Filter::MAX_PER_PAGE+ DEFAULT_PER_PAGE = 10+ # Bounds LIMIT page * per_page of each arm (the reasoning of Tickets::Reading::MAX_PAGE).+ MAX_PAGE = 100_000+ SEARCH_MODE = 'title_only'+ WHOLE_NUMBER = /\A[0-9]+\z/++ Options = Struct.new(:query, :type, :page, :per_page, keyword_init: true)+ class InvalidOption < ArgumentError; end++ # One page of hits: the records (documents with their current version loaded), the page+ # asked for and the count of every readable hit.+ Result = Struct.new(:records, :page, :per_page, :total, keyword_init: true) do+ def to_h+ { data: records.map { |record| Lookup.serialize(record) },+ meta: { page: page, per_page: per_page, total: total } }+ end+ end++ # Reads the options of a lookup. An unknown type is refused on both surfaces. Page and+ # per_page differ by surface: MCP has always read garbage as the default and clamped a+ # large per_page (`strict: false`); REST refuses what it cannot read (`strict: true`),+ # where absent or blank still means the default.+ #+ # @param args [Hash] symbol keys q, type, page, per_page+ # @raise [InvalidOption] with a message naming the argument+ def self.options(args, strict: false)+ Options.new(+ query: text_arg(args[:q], 'q', strict),+ type: type_arg(args[:type], strict),+ page: strict ? strict_number(args[:page], 'page', 1, MAX_PAGE) : [args[:page].to_i, 1].max,+ per_page: strict ? strict_number(args[:per_page], 'per_page', DEFAULT_PER_PAGE, MAX_PER_PAGE) : clamp_per_page(args[:per_page])+ )+ end++ # Note#title is a column; Document#title delegates to its current_version: both respond to+ # #title, so serialization needs no per-type branch. The link is the shared contract+ # (KnowledgeLink), so it round-trips through the resolver.+ def self.serialize(record)+ {+ type: Documentation::KnowledgeLink.key_for(record),+ id: record.id,+ title: record.title,+ updated_at: record.updated_at&.iso8601,+ link: Documentation::KnowledgeLink.build(record)+ }+ end++ def initialize(user:, project:)+ @user = user+ @project = project+ end++ # @param options [Options] blank query = every readable row+ # @return [Result]+ def page(options)+ Result.new(records: page_records(options), page: options.page, per_page: options.per_page,+ total: total(options))+ end++ def self.text_arg(value, name, strict)+ raise InvalidOption, "#{name} must be text" if strict && !value.nil? && !value.is_a?(String)++ value.to_s.strip+ end+ private_class_method :text_arg++ # Validated against the LINK contract's types: what can actually be output as a+ # lalabase:// link.+ def self.type_arg(value, strict)+ type = text_arg(value, 'type', strict)+ return type if type.empty? || Documentation::KnowledgeLink.type_keys.include?(type)++ raise InvalidOption, 'invalid type (expected "note" or "document")'+ end+ private_class_method :type_arg++ def self.strict_number(value, name, default, max)+ return default if value.nil? || value == ''++ text = value.is_a?(Integer) ? value.to_s : value+ valid = text.is_a?(String) && text.match?(WHOLE_NUMBER) && text.to_i.between?(1, max)+ raise InvalidOption, "#{name} must be a whole number from 1 to #{max}" unless valid++ text.to_i+ end+ private_class_method :strict_number++ def self.clamp_per_page(raw)+ value = raw.to_i+ return DEFAULT_PER_PAGE if value <= 0++ [value, MAX_PER_PAGE].min+ end+ private_class_method :clamp_per_page++ private++ def type_keys(options)+ options.type.present? ? [options.type] : Documentation::KnowledgeLink.type_keys+ end++ # One policy-scoped relation per knowledge type, title-filtered when there is a query.+ def arm(key, query)+ entry = Knowledge::TypeRegistry.fetch(key)+ scope = Pundit.policy_scope!(@user, entry[:base_scope].call(@project))+ return scope if query.empty?++ entry[:search_scope].call(scope, "%#{ActiveRecord::Base.sanitize_sql_like(query)}%", SEARCH_MODE)+ end++ # Merge-paginate the arms newest-first. Each arm is fetched with LIMIT = page * per_page,+ # all a correct offset merge can ever need, since the k-th global row sits at position <= k+ # inside one arm. The merged list is then sliced to the requested page.+ #+ # Ordering is `updated_at DESC, id ASC`, qualified through the arm's own arel_table: the+ # document arm joins document_versions, which ALSO has updated_at, and the id tiebreak+ # MATCHES the Ruby merge below, so rows with an identical updated_at are cut by the LIMIT+ # in the order the merge expects; without it a tie across a page boundary could drop or+ # repeat a row.+ def page_records(options)+ limit = options.page * options.per_page+ records = type_keys(options).flat_map do |key|+ scope = arm(key, options.query)+ table = scope.arel_table+ scope.reorder(table[:updated_at].desc, table[:id].asc).limit(limit).to_a+ end+ page_records = records.sort_by { |record| [-record.updated_at.to_f, record.id] }+ .slice((options.page - 1) * options.per_page, options.per_page) || []+ preload_titles(page_records)+ page_records+ end++ def total(options)+ type_keys(options).sum { |key| arm(key, options.query).count }+ end++ # A Document's title lives on its current_version; serialize would otherwise load it once+ # per row (N+1). Preloaded for the final page only. Notes carry a title column.+ def preload_titles(records)+ documents = records.grep(Document)+ return if documents.empty?++ ActiveRecord::Associations::Preloader.new(records: documents, associations: :current_version).call+ end+ end+enddiff --git a/app/services/lalabase/tools/search_knowledge.rb b/app/services/lalabase/tools/search_knowledge.rbindex d7bd3d2..142cb52 100644--- a/app/services/lalabase/tools/search_knowledge.rb+++ b/app/services/lalabase/tools/search_knowledge.rb@@ -10,33 +10,19 @@ module Lalabase# an in-app link + a Reference row. The link string is produced by the SAME builder# the resolver parses (Documentation::KnowledgeLink), so authoring can't drift.#- # Security (project-mode, D7): results come exclusively through Pundit.policy_scope!,- # per type, in the project context. A PAT user without notes/documents READ access- # gets an empty list for that type — never a foreign title. This is the SAME gate the- # chat's double-gate relies on; leaking titles here (the MCP side-door) would be the- # exact hole it exists to close. Read-only tool → runs with a read-only PAT.- #- # Reuse (not duplication): the per-type search arm (incl. the document→current_version- # title join) comes from Knowledge::TypeRegistry, and the link from KnowledgeLink —- # this tool only wraps each arm in policy_scope, paginates, and shapes the JSON. We do- # NOT reuse KnowledgeSearchQuery: it gates by whole-type accessible keys rather than- # per-record policy_scope, and its UNION/pagy/smart-folder/ad-hoc machinery is far- # heavier than a title lookup needs.+ # The rows come from Knowledge::Lookup, the one read GET /api/v1/projects/:project_id/knowledge+ # uses too (cli_rest_plan D5): per-type Pundit.policy_scope!, the merge page, the total and+ # the serialization live there. This tool keeps what is MCP's own: `q` is required, page and+ # per_page are read leniently (garbage = default, a large per_page is clamped), and the+ # citations. Read-only tool → runs with a read-only PAT.class SearchKnowledge < Base- # Cap shared with the ticket list + HTTP API so the two agent-facing surfaces- # bound page size the same way.- MAX_PER_PAGE = Tickets::Filter::MAX_PER_PAGE- DEFAULT_PER_PAGE = 10+ MAX_PER_PAGE = Knowledge::Lookup::MAX_PER_PAGE+ DEFAULT_PER_PAGE = Knowledge::Lookup::DEFAULT_PER_PAGE# Same reasoning as ListTickets::MAX_CITATIONS: the gate needs one citation per area,# a full page of source chips under a lookup answer helps nobody.MAX_CITATIONS = 5- # Title-only search (not content): the agent is looking for a specific object to- # link, the mentions picker (the closest existing precedent) is title-only too, and- # searching bodies would surface — and thus expose — content the link never reveals.- SEARCH_MODE = 'title_only'-# Reads context.actor for its Pundit scoping — declared so the Runner's# fail-closed bar refuses the call when no user is in the context.def self.requires_actor?@@ -74,23 +60,18 @@ module Lalabasereturn Result.new(error: 'project context missing') if context.project.nil?args = symbolized(args)- query = args[:q].to_s.strip- return Result.invalid_input('q is required') if query.empty?+ return Result.invalid_input('q is required') if args[:q].to_s.strip.empty?- type = args[:type].to_s.strip- return Result.invalid_input('invalid type (expected "note" or "document")') if invalid_type?(type)-- page = [args[:page].to_i, 1].max- per_page = clamp_per_page(args[:per_page])+ begin+ options = Knowledge::Lookup.options(args)+ rescue Knowledge::Lookup::InvalidOption => e+ return Result.invalid_input(e.message)+ end- records = page_of(context, query, type, page, per_page)- # Braces required: json_result takes the payload positionally plus a- # `citations:` keyword, so a bare hash would be parsed as keyword args.+ found = Knowledge::Lookup.new(user: context.actor, project: context.project).page(options)+ records = found.recordsjson_result(- {- data: records.map { |record| serialize(record) },- meta: { page: page, per_page: per_page, total: total(context, query, type) }- },+ found.to_h,# Titles of notes and documents are content, and the answer's rights gate runs on# the citations' `area` (Chatpost#gated_streaming?, MessageComponent#redacted?),# not on the asker. Without them an answer built from this tool would be@@ -101,75 +82,6 @@ module Lalabase)end- # A non-blank type that is not a link-able knowledge type. Validated against the- # LINK contract's types (what can actually be output as a lalabase:// link).- def self.invalid_type?(type)- type.present? && !Documentation::KnowledgeLink.type_keys.include?(type)- end- private_class_method :invalid_type?-- def self.type_keys_for(type)- type.present? ? [type] : Documentation::KnowledgeLink.type_keys- end- private_class_method :type_keys_for-- # One policy-scoped, title-filtered relation per knowledge type. base_scope +- # search_scope are Knowledge::TypeRegistry's (so the document title join lives in- # one place); policy_scope! is the access gate wrapped around it.- def self.arm(context, key, query)- entry = Knowledge::TypeRegistry.fetch(key)- scope = Pundit.policy_scope!(context.actor, entry[:base_scope].call(context.project))- entry[:search_scope].call(scope, like_term(query), SEARCH_MODE)- end- private_class_method :arm-- # Merge-paginate the arms newest-first. Each arm is fetched with LIMIT = page *- # per_page — all a correct offset-merge can ever need, since the k-th global item- # sits at position ≤ k inside one arm. (LIMIT is an UPPER bound: with fewer matches- # Postgres returns fewer rows, so a large page over a small result set is cheap, not- # a memory blow-up.) The merged list is then sliced to the requested page.- #- # Ordering is `updated_at DESC, id ASC`, table-qualified via the arm's own arel_table:- # * qualified — the document arm joins document_versions, which ALSO has updated_at,- # so a bare ORDER BY would be ambiguous; arel_table qualifies to the arm's table- # and is injection-proof (no string built);- # * the id tiebreak MATCHES the Ruby merge sort below, so rows with an identical- # updated_at are cut by the LIMIT in the same order the merge expects — without it,- # pagination could drop or repeat a row at a tie that straddles a page boundary.- def self.page_of(context, query, type, page, per_page)- limit = page * per_page- records = type_keys_for(type).flat_map do |key|- scope = arm(context, key, query)- table = scope.arel_table- scope.reorder(table[:updated_at].desc, table[:id].asc).limit(limit).to_a- end- page_records = records.sort_by { |record| [-record.updated_at.to_f, record.id] }- .slice((page - 1) * per_page, per_page) || []- preload_titles(page_records)- page_records- end- private_class_method :page_of-- # A Document's title lives on its current_version; serialize would otherwise lazy-load- # it once per row (N+1). Preload it for the final page only (already sliced to per_page)- # — the registry arm uses a raw string join, so a Preloader run is cleaner and safer- # here than folding includes into that query. Notes carry a title column: nothing to do.- def self.preload_titles(records)- documents = records.select { |record| record.is_a?(Document) }- return if documents.empty?-- ActiveRecord::Associations::Preloader.new(records: documents, associations: :current_version).call- end- private_class_method :preload_titles-- def self.total(context, query, type)- type_keys_for(type).sum { |key| arm(context, key, query).count }- end- private_class_method :total-- # Note#title is a column; Document#title delegates to its current_version — both- # respond to #title, so serialization needs no per-type branch. The link string is- # the shared contract (KnowledgeLink), guaranteeing a round-trip with the resolver.# Note → note citation, Document → its current version (Citations.document reads the# title off the version). nil for anything else, the caller compacts.#@@ -186,30 +98,6 @@ module Lalabaseendendprivate_class_method :citation_for-- def self.serialize(record)- {- type: Documentation::KnowledgeLink.key_for(record),- id: record.id,- title: record.title,- updated_at: record.updated_at&.iso8601,- link: Documentation::KnowledgeLink.build(record)- }- end- private_class_method :serialize-- def self.like_term(query)- "%#{ActiveRecord::Base.sanitize_sql_like(query)}%"- end- private_class_method :like_term-- def self.clamp_per_page(raw)- value = raw.to_i- return DEFAULT_PER_PAGE if value <= 0-- [value, MAX_PER_PAGE].min- end- private_class_method :clamp_per_pageendendenddiff --git a/spec/services/knowledge/lookup_spec.rb b/spec/services/knowledge/lookup_spec.rbnew file mode 100644index 0000000..7ab2b50--- /dev/null+++ b/spec/services/knowledge/lookup_spec.rb@@ -0,0 +1,259 @@+# frozen_string_literal: true++require 'rails_helper'++# What: Knowledge::Lookup, the one read of a project's knowledge (notes and documents)+# by title, shared by the MCP tool search_knowledge and GET /api/v1/projects/:id/knowledge.+# Type: Service spec.+# Why: Both surfaces must list the same rows for the same reader: per-type policy scoping+# (no title of a type the reader may not read, not even in `total`), one order+# (updated_at DESC, id ASC) and a merge over two tables that neither repeats nor loses a+# row at a page boundary. The options differ by surface on purpose: MCP has always+# clamped, REST refuses what it cannot read.+RSpec.describe Knowledge::Lookup, :ci_guard do+ include ActiveSupport::Testing::TimeHelpers++ let(:organisation) { create(:organisation) }+ let(:project) { create(:project, organisation: organisation) }+ let(:role) { create(:role, organisation: organisation, is_default: true) }++ let(:reader) do+ user = create(:user)+ ActsAsTenant.with_tenant(organisation) do+ create(:membership, user: user, organisation: organisation, role: role, active: true)+ end+ user+ end++ let(:lookup) { described_class.new(user: reader, project: project) }++ before { ActsAsTenant.current_tenant = organisation }+ after { ActsAsTenant.current_tenant = nil }++ def grant(**areas)+ create(:project_permission, { user: reader, project: project }.merge(areas))+ end++ def note(title, at: nil)+ record = create(:note, project: project, organisation: organisation, title: title)+ record.update_columns(updated_at: at) if at+ record+ end++ def document(title, at: nil)+ doc = create(:document, project: project, organisation: organisation)+ version = create(:document_version, document: doc, organisation: organisation, title: title)+ doc.update!(current_version: version)+ doc.update_columns(updated_at: at) if at+ doc+ end++ def options(**args)+ described_class.options(args)+ end++ def titles(result)+ result.records.map(&:title)+ end++ describe '.options' do+ context 'lenient (MCP)' do+ it 'reads garbage page and per_page as the defaults and clamps a large per_page' do+ opts = described_class.options({ q: ' Alpha ', page: 'x', per_page: '0' })+ expect(opts).to have_attributes(query: 'Alpha', type: '', page: 1, per_page: described_class::DEFAULT_PER_PAGE)++ expect(described_class.options({ per_page: 10_000 }).per_page).to eq(described_class::MAX_PER_PAGE)+ expect(described_class.options({ page: -3 }).page).to eq(1)+ end++ it 'refuses an unknown type with the MCP wording' do+ expect { described_class.options({ type: 'ticket' }) }+ .to raise_error(described_class::InvalidOption, 'invalid type (expected "note" or "document")')+ end+ end++ context 'strict (REST)' do+ def strict(**args)+ described_class.options(args, strict: true)+ end++ it 'takes absent and blank page and per_page as the defaults' do+ expect(strict).to have_attributes(page: 1, per_page: described_class::DEFAULT_PER_PAGE, query: '', type: '')+ expect(strict(page: '', per_page: '')).to have_attributes(page: 1, per_page: described_class::DEFAULT_PER_PAGE)+ end++ it 'reads whole numbers given as text' do+ expect(strict(page: '2', per_page: '25')).to have_attributes(page: 2, per_page: 25)+ end++ it 'refuses a per_page above the maximum instead of clamping it' do+ expect { strict(per_page: (described_class::MAX_PER_PAGE + 1).to_s) }+ .to raise_error(described_class::InvalidOption, /per_page/)+ expect(strict(per_page: described_class::MAX_PER_PAGE.to_s).per_page).to eq(described_class::MAX_PER_PAGE)+ end++ it 'refuses page and per_page that are not positive whole numbers' do+ ['0', '-1', 'abc', '1.5', ' 2'].each do |value|+ expect { strict(page: value) }.to raise_error(described_class::InvalidOption, /page/), "page #{value.inspect}"+ expect { strict(per_page: value) }.to raise_error(described_class::InvalidOption, /per_page/),+ "per_page #{value.inspect}"+ end+ end++ it 'refuses a page beyond MAX_PAGE' do+ expect { strict(page: (described_class::MAX_PAGE + 1).to_s) }.to raise_error(described_class::InvalidOption, /page/)+ end++ it 'refuses a list or a nested value' do+ expect { strict(page: ['1']) }.to raise_error(described_class::InvalidOption, /page/)+ expect { strict(q: ['a']) }.to raise_error(described_class::InvalidOption, /q/)+ expect { strict(type: { 'a' => 'note' }) }.to raise_error(described_class::InvalidOption, /type/)+ end+ end+ end++ describe '#page' do+ context 'with read access to both types' do+ before { grant(notes_access: 'read_only', documents_access: 'read_only') }++ it 'without a query lists every note and document, newest first' do+ note('Old note', at: 3.days.ago)+ document('Middle document', at: 2.days.ago)+ note('New note', at: 1.day.ago)++ result = lookup.page(options)++ expect(titles(result)).to eq(['New note', 'Middle document', 'Old note'])+ expect(result.total).to eq(3)+ end++ it 'with a query matches titles only, case-insensitively' do+ note('Deploy runbook')+ document('deploy checklist')+ note('Something else')++ expect(titles(lookup.page(options(q: 'DEPLOY')))).to contain_exactly('Deploy runbook', 'deploy checklist')+ end++ it 'filters by type' do+ note('Shared')+ document('Shared')++ expect(lookup.page(options(q: 'Shared', type: 'document')).records.map(&:class)).to eq([Document])+ expect(lookup.page(options(type: 'note')).records.map(&:class)).to eq([Note])+ expect(lookup.page(options(type: 'note')).total).to eq(1)+ end++ it 'takes %, _ and \\ in the query literally' do+ note('Cost a%b')+ note('axxb')+ note('snake_case')+ note('snakeXcase')+ note('back\\slash')+ note('backslash')++ expect(titles(lookup.page(options(q: 'a%b')))).to eq(['Cost a%b'])+ expect(titles(lookup.page(options(q: 'snake_case')))).to eq(['snake_case'])+ expect(titles(lookup.page(options(q: 'back\\slash')))).to eq(['back\\slash'])+ end++ # Five rows share one updated_at and straddle the page boundary of a merge over two+ # tables. Walking the pages must hand out every row exactly once, in id order.+ it 'neither repeats nor loses a row at a page boundary with equal updated_at' do+ at = 1.day.ago.change(usec: 0)+ # Setup only: five records from one line read as an N+1 to Prosopite.+ rows = Prosopite.pause do+ [note('t1', at: at), document('t2', at: at), note('t3', at: at), document('t4', at: at), note('t5', at: at)]+ end++ first = lookup.page(options(page: 1, per_page: 2))+ second = lookup.page(options(page: 2, per_page: 2))+ third = lookup.page(options(page: 3, per_page: 2))++ expect((first.records + second.records + third.records).map(&:id)).to eq(rows.map(&:id).sort)+ expect(third.total).to eq(5)+ end++ it 'returns an empty page beyond the last one, with the full total' do+ note('Only')++ result = lookup.page(options(page: 4, per_page: 2))+ expect(result.records).to eq([])+ expect(result.total).to eq(1)+ end++ it 'serializes a hit with the knowledge link' do+ hit = note('Alpha')++ expect(described_class.serialize(hit)).to eq(+ type: 'note', id: hit.id, title: 'Alpha', updated_at: hit.updated_at.iso8601,+ link: "lalabase://note/#{hit.id}"+ )+ end++ it 'answers in data and meta' do+ note('Alpha')+ result = lookup.page(options(per_page: 5))++ expect(result.to_h).to eq(+ data: result.records.map { |record| described_class.serialize(record) },+ meta: { page: 1, per_page: 5, total: 1 }+ )+ end+ end++ context 'with read access to notes only' do+ before { grant(notes_access: 'read_only', documents_access: 'no_access') }++ it 'never lists a document, neither as a hit nor in total, with or without a query' do+ note('Plan A')+ document('Plan B secret')++ listed = lookup.page(options)+ searched = lookup.page(options(q: 'Plan'))+ documents_only = lookup.page(options(type: 'document'))+ secret = lookup.page(options(q: 'secret'))++ expect([titles(listed), listed.total]).to eq([['Plan A'], 1])+ expect([titles(searched), searched.total]).to eq([['Plan A'], 1])+ expect([documents_only.records, documents_only.total]).to eq([[], 0])+ expect([secret.records, secret.total]).to eq([[], 0])+ end+ end++ context 'with read access to documents only' do+ before { grant(notes_access: 'no_access', documents_access: 'read_only') }++ it 'never lists a note' do+ note('Hidden note')+ document('Visible document')++ result = lookup.page(options)+ expect(titles(result)).to eq(['Visible document'])+ expect(result.total).to eq(1)+ end+ end++ context 'without any knowledge right' do+ before { grant(notes_access: 'no_access', documents_access: 'no_access') }++ it 'answers an empty list, not an error' do+ note('Hidden')+ document('Hidden too')++ result = lookup.page(options)+ expect(result.records).to eq([])+ expect(result.total).to eq(0)+ end+ end++ it 'never lists knowledge of another project of the same organisation' do+ grant(notes_access: 'read_only', documents_access: 'read_only')+ other = create(:project, organisation: organisation)+ create(:project_permission, user: reader, project: other, notes_access: 'read_only')+ create(:note, project: other, organisation: organisation, title: 'Elsewhere')++ expect(lookup.page(options).records).to eq([])+ end+ end+end