Skip to content

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.

Add GET /api/v1/projects/:project_id/knowledge over Knowledge::Lookup

Guido Boyke01c98d5bcfe1
diff --git a/.github/workflows/guards.yml b/.github/workflows/guards.yml
index 84658dc..b71f3fe 100644
--- a/.github/workflows/guards.yml
+++ b/.github/workflows/guards.yml
@@ -273,6 +273,7 @@ jobs:
spec/requests/api/inbox_organisation_filter_spec.rb
spec/services/lalabase/tools/get_ticket_paging_spec.rb
spec/services/lalabase/tools/get_ticket_assistant_limits_spec.rb
+ spec/services/lalabase/tools/search_knowledge_spec.rb
spec/contracts/mcp_contract_spec.rb
spec/lib/tasks/mcp_contract_spec.rb
spec/lib/tasks/notifications_align_ticket_projects_spec.rb
@@ -299,6 +300,7 @@ jobs:
spec/requests/api/v1/people_spec.rb
spec/requests/api/people_parity_spec.rb
spec/requests/api/v1/post_comment_format_spec.rb
+ spec/requests/api/v1/knowledge_spec.rb
spec/models/codebase_import_mapping_spec.rb
spec/services/codebase_import/time_session_importer_spec.rb
spec/services/codebase_import/duplicate_prevention_spec.rb
@@ -334,6 +336,7 @@ jobs:
spec/services/people/directory_spec.rb
spec/services/people/contacts_spec.rb
spec/services/people/lookup_spec.rb
+ spec/services/knowledge/lookup_spec.rb
spec/requests/organisations/people_last_contact_spec.rb
spec/services/lalabase/tools/find_people_spec.rb
spec/services/lalabase/tools/get_person_spec.rb
diff --git a/CLAUDE.md b/CLAUDE.md
index 53b5325..ebd5d0a 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -856,6 +856,19 @@ reach, organisations AND projects, and only the rows the web time list shows the
its minutes, with `ticket: null`. Owner: `TimeSessions::OpenHours`; guard:
`spec/requests/api/v1/time_sessions_open_access_spec.rb`.
+`GET /api/v1/projects/:project_id/knowledge` (REST R2, 2026-10-29, API 1.6.0, capability
+`knowledge.search`) lists a project's notes and documents by title through `Knowledge::Lookup`,
+the read the MCP tool `search_knowledge` uses: the same rows, order (`updated_at` newest first,
+then id), fields (`type`, `id`, `title`, `updated_at`, `link`) and `total` for the same search.
+Rows only through the per-type policy scope: no title and no count of a type the reader may not
+read; a reader who may open the project but read no knowledge gets an empty list. Without `q`
+(or blank) REST lists every readable row; MCP keeps `q` required. `type` other than `note` or
+`document`, and `page`/`per_page` that are no whole number from 1 to the maximum (`per_page` at
+most 100, where MCP clamps) answer 422 `invalid_input`, checked before the project. The project
+gate is MCP's (token reach and `ProjectAccessService`): missing, malformed, beyond the reach,
+not openable (an archived project for a non-admin included) and foreign answer the same 404.
+Guards: `spec/requests/api/v1/knowledge_spec.rb`, `spec/services/knowledge/lookup_spec.rb`.
+
`GET /api/v1/organisations/:organisation_id/people` and `.../people/:id` (People S3b) read
the people directory through `People::Lookup`, the object the assistant's `find_people` /
`get_person` and their MCP twins read as well: one rights question (the people right, 403
diff --git a/app/controllers/api/v1/knowledge_controller.rb b/app/controllers/api/v1/knowledge_controller.rb
new file mode 100644
index 0000000..9e51226
--- /dev/null
+++ b/app/controllers/api/v1/knowledge_controller.rb
@@ -0,0 +1,59 @@
+# frozen_string_literal: true
+
+module Api
+ module V1
+ # The knowledge of one project (notes and documents) for a program such as the terminal
+ # client (REST R2), read through Knowledge::Lookup like the MCP tool search_knowledge
+ # (cli_rest_plan D5): the same rows, order, fields and total for the same search.
+ #
+ # * Without `q` REST lists every readable row, newest first, so a client can open the
+ # knowledge area without a search term. MCP keeps `q` required.
+ # * Paging: a page or per_page that is no whole number from 1 to the maximum is refused
+ # with 422, where MCP clamps: a program would get fewer rows than it asked for without
+ # being told. Absent or blank means the default. Checked before the project is looked up,
+ # so the 422 does not depend on whether the project exists.
+ # * The project gate is the one of MCP (Mcp::ToolCall#authorized_project): the token's reach
+ # and the owner's access to the project. A missing project, a malformed id, a project
+ # beyond the reach, one the owner cannot open and one of another organisation answer the
+ # same 404. A reader who may open the project but read no knowledge gets an empty list.
+ class KnowledgeController < BaseController
+ rescue_from Knowledge::Lookup::InvalidOption, with: :invalid_input
+
+ # GET /api/v1/projects/:project_id/knowledge?q=&type=&page=&per_page=
+ def index
+ options = Knowledge::Lookup.options(lookup_args, strict: true)
+ project = readable_project(params[:project_id])
+
+ ActsAsTenant.with_tenant(project.organisation) do
+ # The rows are policy-scoped inside Knowledge::Lookup, per type (Pundit.policy_scope!);
+ # a policy_scope here would be a second copy nothing reads.
+ skip_policy_scope
+ render json: Knowledge::Lookup.new(user: current_user, project: project).page(options).to_h
+ end
+ end
+
+ private
+
+ # Read raw, not through strong parameters: those would drop a list or a nested value and
+ # let a malformed request through as "no filter".
+ def lookup_args
+ %i[q type page per_page].index_with { |key| params[key] }
+ end
+
+ def readable_project(id)
+ project = ActsAsTenant.without_tenant { Project.find_by(id: id) } if id.present?
+ raise ActiveRecord::RecordNotFound unless project && current_token.accessible_project?(project)
+
+ ActsAsTenant.with_tenant(project.organisation) do
+ raise ActiveRecord::RecordNotFound unless AccessCheck::ProjectAccessService.can_access_project?(current_user, project)
+ end
+ project
+ end
+
+ def invalid_input(exception)
+ render_error(error: 'invalid_input', code: 'invalid_input', message: exception.message,
+ status: :unprocessable_content)
+ end
+ end
+ end
+end
diff --git a/app/services/CLAUDE.md b/app/services/CLAUDE.md
index 3339160..89aae8c 100644
--- a/app/services/CLAUDE.md
+++ b/app/services/CLAUDE.md
@@ -14,6 +14,15 @@ Ausgenommene Subtrees mit eigenem Vertrag: `actors/`, `lalabase/tools/`).
Einzel-`update!` ohne Side-Effects bleibt im Controller.
Verzeichnis-Übersicht (Auswahl):
+* `knowledge/` — `lookup.rb` (`Knowledge::Lookup`, REST R2, 29.10.2026) ist das EINE Lesen
+ des Wissens eines Projekts (Notizen, Dokumente) nach Titel, für das MCP-Werkzeug
+ `search_knowledge` und `GET /api/v1/projects/:project_id/knowledge`: Rechte je Typ über
+ `Pundit.policy_scope!` (kein Titel und keine Zählung eines Typs ohne Leserecht), Merge-Seite
+ über zwei Tabellen (`updated_at DESC, id ASC`, derselbe Tiebreak in SQL und Ruby), Gesamtzahl,
+ Serialisierung mit dem Link aus `Documentation::KnowledgeLink`. Ohne Suchwort listet es
+ alles Lesbare (nur REST nutzt das, MCP verlangt `q`). `.options(args, strict:)`: MCP liest
+ Unlesbares als Standard und klemmt `per_page`, REST (`strict: true`) lehnt ab
+ (`InvalidOption`, 422). Eine neue Such- oder Seitenregel gehört hierher, nicht in eine Hülle.
* `time_sessions/` — Lese-Objekte der Zeitdomäne. `viewing_scope.rb` ist der EINE Besitzer der
Regel „eigene oder alle Zeiten" (`:all`/`:own`/`:none` plus `#apply(relation)`), die
`ProjectPolicy#area_access?(:time_sessions)` nicht ausdrücken kann (`can_view_own ||
diff --git a/app/services/api/v1/capabilities.rb b/app/services/api/v1/capabilities.rb
index 2ab8cae..9edcd53 100644
--- a/app/services/api/v1/capabilities.rb
+++ b/app/services/api/v1/capabilities.rb
@@ -16,8 +16,9 @@ module Api
# Minor for an additive change (a new endpoint, field or capability), major
# never: an existing name, field or meaning does not change. 1.2.0 added
# the People API; 1.3.0 added the REST ticket view (R1); 1.4.0 adds
- # time_sessions.book (R6); 1.5.0 adds posts.plain (R3a).
- API_VERSION = '1.5.0'
+ # time_sessions.book (R6); 1.5.0 adds posts.plain (R3a); 1.6.0 adds
+ # knowledge.search (R2).
+ API_VERSION = '1.6.0'
# name => [verb, path as the router spells it]
ENDPOINTS = {
@@ -27,6 +28,7 @@ module Api
'people.show' => ['GET', '/api/v1/organisations/:organisation_id/people/:id'],
'projects.list' => ['GET', '/api/v1/projects'],
'projects.ticket_attribute_definitions' => ['GET', '/api/v1/projects/:id/ticket_attribute_definitions'],
+ 'knowledge.search' => ['GET', '/api/v1/projects/:project_id/knowledge'],
'tickets.list' => ['GET', '/api/v1/projects/:project_id/tickets'],
'tickets.create' => ['POST', '/api/v1/projects/:project_id/tickets'],
'tickets.by_number' => ['GET', '/api/v1/projects/:project_id/tickets/number/:number'],
diff --git a/app/services/lalabase/CLAUDE.md b/app/services/lalabase/CLAUDE.md
index 21ddfb1..1cbbb9d 100644
--- a/app/services/lalabase/CLAUDE.md
+++ b/app/services/lalabase/CLAUDE.md
@@ -99,6 +99,9 @@ Codebase-Verständnis.
`full_text`, `post_id`, Zitationen. `posts_per_page` über 50 klemmt MCP auf 50
(`over_max: :clamp`), REST lehnt mit 422 ab. Eine neue Seiten-Regel gehört in den Service,
nicht in eine der beiden Hüllen.
+ `search_knowledge` liest über `Knowledge::Lookup` (`app/services/knowledge/lookup.rb`,
+ REST R2), denselben Service wie `GET /api/v1/projects/:project_id/knowledge`. Im Werkzeug
+ bleiben `q` als Pflicht, die nachsichtigen Seiten-Optionen und die Zitationen.
Fehler eines Werkzeugs tragen eine Klasse: `Result.invalid_input(msg)` oder
`Result.refused(msg, reason:)`; ohne Code gilt `refused`, auch für ein abgelehntes Speichern
(Modellvalidierung, Actor-Fehler): das beweist keine falsche Eingabe. Spec je Fehlerstelle:
diff --git a/config/routes.rb b/config/routes.rb
index db5b134..b36b7ef 100644
--- a/config/routes.rb
+++ b/config/routes.rb
@@ -938,6 +938,8 @@ Rails.application.routes.draw do
get 'tickets/number/:number', to: 'tickets#by_number', as: :ticket_by_number, format: false,
constraints: { number: %r{[^/]+} }
get :ticket_attribute_definitions, on: :member
+ # REST R2: the project's notes and documents by title, read only.
+ resources :knowledge, only: %i[index], controller: 'knowledge'
end
resources :tickets, only: %i[show update] do
member do
diff --git a/spec/contracts/mcp_contract_recorder.rb b/spec/contracts/mcp_contract_recorder.rb
index 0b807e8..0981e92 100644
--- a/spec/contracts/mcp_contract_recorder.rb
+++ b/spec/contracts/mcp_contract_recorder.rb
@@ -546,7 +546,24 @@ module McpContract
'POST /api/v1/tickets/:ticket_id/time_sessions' => rest_booking_calls,
# REST R3a (cli_rest_plan R3 a), appended last: its comments land on the
# login ticket after every answer above, without advancing the clock.
- 'POST /api/v1/tickets/:ticket_id/posts' => rest_comment_calls
+ 'POST /api/v1/tickets/:ticket_id/posts' => rest_comment_calls,
+ # REST R2, appended last: reads only, over the deploy note of the website.
+ 'GET /api/v1/projects/:project_id/knowledge' => rest_knowledge_calls
+ }
+ end
+
+ def rest_knowledge_calls
+ # Spelled out, not a loop: each request from its own line (Prosopite).
+ path = "/api/v1/projects/#{id(:website)}/knowledge"
+ {
+ 'ok' => rest_get(:read, "#{path}?q=Deploy"),
+ 'empty' => rest_get(:read, "#{path}?q=Gibt%20es%20nicht"),
+ 'list' => rest_get(:read, path),
+ 'list_type' => rest_get(:read, "#{path}?type=note&per_page=5"),
+ 'invalid_input' => rest_get(:read, "#{path}?type=ticket"),
+ 'invalid_input_per_page' => rest_get(:read, "#{path}?per_page=101"),
+ 'not_found' => rest_get(:read, "/api/v1/projects/#{id(:foreign_project)}/knowledge"),
+ 'unauthorized' => rest_get(nil, path)
}
end
diff --git a/spec/fixtures/mcp_contract.json b/spec/fixtures/mcp_contract.json
index 1fd50c9..caefe50 100644
--- a/spec/fixtures/mcp_contract.json
+++ b/spec/fixtures/mcp_contract.json
@@ -1,9 +1,9 @@
{
"header": {
"regenerate": "RAILS_ENV=test bin/rails mcp:contract",
- "core_commit": "1a16f823f40cab62f11c3e5c929a6912bda0c95b",
+ "core_commit": "3b8b8c047d8706867945bae06e108b27b5dadffb",
"core_dirty": true,
- "contract_sha256": "80e07918e69c341f6079cc26d11f2144c73593178faa6cde0d6d616058c1f282"
+ "contract_sha256": "9f4ef33865437173595bdd3d8e21c1cb6dbb8f14a48af521817f0f9b53f5a51d"
},
"contract": {
"mcp": {
@@ -3654,10 +3654,11 @@
"all_projects": true
}
],
- "api_version": "1.5.0",
+ "api_version": "1.6.0",
"capabilities": [
"error_codes",
"idempotency",
+ "knowledge.search",
"me.show",
"notifications.archive",
"notifications.list",
@@ -3718,10 +3719,11 @@
"all_projects": true
}
],
- "api_version": "1.5.0",
+ "api_version": "1.6.0",
"capabilities": [
"error_codes",
"idempotency",
+ "knowledge.search",
"me.show",
"notifications.archive",
"notifications.list",
@@ -5792,6 +5794,154 @@
}
}
}
+ },
+ "GET /api/v1/projects/:project_id/knowledge": {
+ "ok": {
+ "token": "read",
+ "request": {
+ "path": "/api/v1/projects/00000000-0000-4000-8000-000000000031/knowledge?q=Deploy"
+ },
+ "response": {
+ "status": 200,
+ "body": {
+ "data": [
+ {
+ "type": "note",
+ "id": "00000000-0000-4000-8000-000000000061",
+ "title": "Deploy-Anleitung",
+ "updated_at": "2026-01-05T09:27:00Z",
+ "link": "lalabase://note/00000000-0000-4000-8000-000000000061"
+ }
+ ],
+ "meta": {
+ "page": 1,
+ "per_page": 10,
+ "total": 1
+ }
+ }
+ }
+ },
+ "empty": {
+ "token": "read",
+ "request": {
+ "path": "/api/v1/projects/00000000-0000-4000-8000-000000000031/knowledge?q=Gibt%20es%20nicht"
+ },
+ "response": {
+ "status": 200,
+ "body": {
+ "data": [],
+ "meta": {
+ "page": 1,
+ "per_page": 10,
+ "total": 0
+ }
+ }
+ }
+ },
+ "list": {
+ "token": "read",
+ "request": {
+ "path": "/api/v1/projects/00000000-0000-4000-8000-000000000031/knowledge"
+ },
+ "response": {
+ "status": 200,
+ "body": {
+ "data": [
+ {
+ "type": "note",
+ "id": "00000000-0000-4000-8000-000000000061",
+ "title": "Deploy-Anleitung",
+ "updated_at": "2026-01-05T09:27:00Z",
+ "link": "lalabase://note/00000000-0000-4000-8000-000000000061"
+ }
+ ],
+ "meta": {
+ "page": 1,
+ "per_page": 10,
+ "total": 1
+ }
+ }
+ }
+ },
+ "list_type": {
+ "token": "read",
+ "request": {
+ "path": "/api/v1/projects/00000000-0000-4000-8000-000000000031/knowledge?type=note&per_page=5"
+ },
+ "response": {
+ "status": 200,
+ "body": {
+ "data": [
+ {
+ "type": "note",
+ "id": "00000000-0000-4000-8000-000000000061",
+ "title": "Deploy-Anleitung",
+ "updated_at": "2026-01-05T09:27:00Z",
+ "link": "lalabase://note/00000000-0000-4000-8000-000000000061"
+ }
+ ],
+ "meta": {
+ "page": 1,
+ "per_page": 5,
+ "total": 1
+ }
+ }
+ }
+ },
+ "invalid_input": {
+ "token": "read",
+ "request": {
+ "path": "/api/v1/projects/00000000-0000-4000-8000-000000000031/knowledge?type=ticket"
+ },
+ "response": {
+ "status": 422,
+ "body": {
+ "error": "invalid_input",
+ "code": "invalid_input",
+ "message": "invalid type (expected \"note\" or \"document\")"
+ }
+ }
+ },
+ "invalid_input_per_page": {
+ "token": "read",
+ "request": {
+ "path": "/api/v1/projects/00000000-0000-4000-8000-000000000031/knowledge?per_page=101"
+ },
+ "response": {
+ "status": 422,
+ "body": {
+ "error": "invalid_input",
+ "code": "invalid_input",
+ "message": "per_page must be a whole number from 1 to 100"
+ }
+ }
+ },
+ "not_found": {
+ "token": "read",
+ "request": {
+ "path": "/api/v1/projects/00000000-0000-4000-8000-000000000034/knowledge"
+ },
+ "response": {
+ "status": 404,
+ "body": {
+ "error": "not_found",
+ "code": "not_found"
+ }
+ }
+ },
+ "unauthorized": {
+ "token": "invalid",
+ "request": {
+ "path": "/api/v1/projects/00000000-0000-4000-8000-000000000031/knowledge"
+ },
+ "response": {
+ "status": 401,
+ "body": {
+ "error": "unauthorized",
+ "code": "unauthorized"
+ }
+ }
+ }
}
}
}
diff --git a/spec/requests/api/v1/capabilities_spec.rb b/spec/requests/api/v1/capabilities_spec.rb
index 62a1818..a3c207f 100644
--- a/spec/requests/api/v1/capabilities_spec.rb
+++ b/spec/requests/api/v1/capabilities_spec.rb
@@ -33,7 +33,7 @@ RSpec.describe 'API V1 capabilities', :ci_guard, type: :request do
it 'names the API version and the capabilities beside the existing fields' do
data = me(token(read_only: false))
- expect(data['api_version']).to eq('1.5.0')
+ expect(data['api_version']).to eq('1.6.0')
expect(data['capabilities']).to eq(Api::V1::Capabilities.names)
expect(data.keys).to include('user', 'token', 'scoped_organisations')
end
@@ -47,7 +47,7 @@ RSpec.describe 'API V1 capabilities', :ci_guard, type: :request do
'me.show', 'organisations.list', 'projects.list', 'tickets.list', 'tickets.create', 'tickets.show',
'tickets.update', 'tickets.attachments', 'posts.create', 'time_sessions.create',
'notifications.list', 'notifications.mark_as_read', 'people.list', 'people.show', 'idempotency', 'error_codes',
- 'tickets.by_number', 'posts.show', 'tickets.paging', 'time_sessions.book', 'posts.plain'
+ 'tickets.by_number', 'posts.show', 'tickets.paging', 'time_sessions.book', 'posts.plain', 'knowledge.search'
)
end
diff --git a/spec/requests/api/v1/knowledge_spec.rb b/spec/requests/api/v1/knowledge_spec.rb
new file mode 100644
index 0000000..e815b75
--- /dev/null
+++ b/spec/requests/api/v1/knowledge_spec.rb
@@ -0,0 +1,278 @@
+# frozen_string_literal: true
+
+require 'rails_helper'
+
+# REST R2: GET /api/v1/projects/:project_id/knowledge, the knowledge of a project (notes and
+# documents) by title, through Knowledge::Lookup, the read the MCP tool search_knowledge uses.
+# With `q` REST answers what MCP answers; without it REST lists every readable row, newest first
+# (MCP keeps `q` required).
+#
+# Rights: rows only through the per-type policy scope, so a reader who may read notes only never
+# sees a document title, not even in `total`; a reader with access to the project but no
+# knowledge right gets an empty list. A missing project, a malformed id, a project beyond the
+# token's reach, one the reader cannot open and one of another organisation answer the same 404.
+RSpec.describe 'REST knowledge', :ci_guard, type: :request do
+ let(:organisation) { create(:organisation) }
+ let(:role) { create(:role, organisation: organisation) }
+ let(:project) { create(:project, organisation: organisation) }
+ let(:not_found_body) { { error: 'not_found', code: 'not_found' }.to_json }
+
+ def member(notes: 'read_only', documents: 'read_only', tickets: 'no_access', on: project)
+ Prosopite.pause do
+ ActsAsTenant.with_tenant(organisation) do
+ user = create(:user)
+ create(:membership, user: user, organisation: organisation, role: role, active: true)
+ if on
+ create(:project_permission, user: user, project: on, notes_access: notes, documents_access: documents,
+ tickets_access: tickets)
+ end
+ user
+ end
+ end
+ end
+
+ let(:reader) { member }
+
+ def note(title, at:)
+ Prosopite.pause do
+ ActsAsTenant.with_tenant(organisation) do
+ record = create(:note, project: project, organisation: organisation, title: title)
+ record.update_columns(updated_at: at)
+ record
+ end
+ end
+ end
+
+ def document(title, at:)
+ Prosopite.pause do
+ ActsAsTenant.with_tenant(organisation) do
+ 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)
+ doc
+ end
+ end
+ end
+
+ let!(:runbook) { note('Deploy runbook', at: 3.days.ago) }
+ let!(:checklist) { document('Deploy checklist', at: 2.days.ago) }
+ let!(:minutes) { note('Board minutes', at: 1.day.ago) }
+
+ after { ActsAsTenant.current_tenant = nil }
+
+ def token_for(user, **options)
+ Prosopite.pause do
+ create(:personal_access_token, user: user, organisations: [organisation], **options).token
+ end
+ end
+
+ def get_json(user, params = {}, token: nil, project_id: project.id, **query)
+ params = params.merge(query)
+ headers = { 'Authorization' => "Bearer #{token || token_for(user)}" }
+ get "/api/v1/projects/#{project_id}/knowledge", params: params, headers: headers
+ response.parsed_body
+ end
+
+ def mcp_answer(user, **args)
+ ActsAsTenant.with_tenant(organisation) do
+ context = Lalabase::Tools::Context.new(actor: user, organisation: organisation, project: project)
+ JSON.parse(Lalabase::Tools::SearchKnowledge.execute(args: args, context: context).content)
+ end
+ end
+
+ def expect_not_found
+ expect(response).to have_http_status(:not_found)
+ expect(response.body).to eq(not_found_body)
+ end
+
+ def expect_invalid_input(message)
+ expect(response).to have_http_status(:unprocessable_content)
+ expect(response.parsed_body).to include('error' => 'invalid_input', 'code' => 'invalid_input')
+ expect(response.parsed_body['message']).to match(message)
+ end
+
+ describe 'with q' do
+ it 'answers what MCP search_knowledge answers for the same reader and search' do
+ body = get_json(reader, q: 'deploy')
+
+ expect(response).to have_http_status(:ok)
+ expect(body).to eq(mcp_answer(reader, q: 'deploy'))
+ expect(body['data'].pluck('id')).to eq([checklist.id, runbook.id])
+ expect(body['data'].first).to eq(
+ 'type' => 'document', 'id' => checklist.id, 'title' => 'Deploy checklist',
+ 'updated_at' => checklist.reload.updated_at.iso8601, 'link' => "lalabase://document/#{checklist.id}"
+ )
+ expect(body['meta']).to eq('page' => 1, 'per_page' => 10, 'total' => 2)
+ end
+
+ it 'answers what MCP answers with a type, a page and a page size' do
+ body = get_json(reader, q: 'e', type: 'note', page: '2', per_page: '1')
+
+ expect(body).to eq(mcp_answer(reader, q: 'e', type: 'note', page: 2, per_page: 1))
+ expect(body['data'].pluck('id')).to eq([runbook.id])
+ expect(body['meta']).to eq('page' => 2, 'per_page' => 1, 'total' => 2)
+ end
+
+ it 'takes %, _ and \\ literally, as MCP does' do
+ note('50% done', at: 4.days.ago)
+
+ body = get_json(reader, q: '%')
+ expect(body['data'].pluck('title')).to eq(['50% done'])
+ expect(get_json(reader, q: '_')['data']).to eq([])
+ expect(get_json(reader, q: '\\')['data']).to eq([])
+ end
+ end
+
+ describe 'without q' do
+ it 'lists every readable note and document, newest first' do
+ body = get_json(reader)
+
+ expect(response).to have_http_status(:ok)
+ expect(body['data'].pluck('id')).to eq([minutes.id, checklist.id, runbook.id])
+ expect(body['meta']).to eq('page' => 1, 'per_page' => 10, 'total' => 3)
+ end
+
+ it 'takes a blank q as no q' do
+ expect(get_json(reader, q: ' ')['meta']['total']).to eq(3)
+ end
+
+ it 'pages across both types without repeating or losing a row of equal updated_at' do
+ at = 5.days.ago.change(usec: 0)
+ tied = [note('Tie 1', at: at), document('Tie 2', at: at), note('Tie 3', at: at)]
+ token = token_for(reader)
+
+ second = get_json(reader, { page: 2, per_page: 2 }, token: token)['data'].pluck('id')
+ third = get_json(reader, { page: 3, per_page: 2 }, token: token)['data'].pluck('id')
+
+ # Pages 1 holds minutes and the checklist; the runbook, then the three ties in id order.
+ expect(second + third).to eq([runbook.id] + tied.map(&:id).sort)
+ end
+ end
+
+ describe 'rights' do
+ it 'never shows a document title to a reader of notes only, not even in total' do
+ notes_only = member(documents: 'no_access')
+ token = token_for(notes_only)
+
+ listed = get_json(notes_only, {}, token: token)
+ searched = get_json(notes_only, { q: 'checklist' }, token: token)
+ documents = get_json(notes_only, { type: 'document' }, token: token)
+
+ expect(listed['data'].pluck('id')).to eq([minutes.id, runbook.id])
+ expect(listed['meta']['total']).to eq(2)
+ expect(searched).to eq('data' => [], 'meta' => { 'page' => 1, 'per_page' => 10, 'total' => 0 })
+ expect(documents['data']).to eq([])
+ expect(response.body).not_to include('Deploy checklist')
+ end
+
+ it 'never shows a note title to a reader of documents only' do
+ documents_only = member(notes: 'no_access')
+
+ body = get_json(documents_only)
+ expect(body['data'].pluck('id')).to eq([checklist.id])
+ expect(body['meta']['total']).to eq(1)
+ end
+
+ it 'answers an empty list to a reader with project access but no knowledge right' do
+ tickets_only = member(notes: 'no_access', documents: 'no_access', tickets: 'read_only')
+
+ body = get_json(tickets_only)
+ expect(response).to have_http_status(:ok)
+ expect(body).to eq('data' => [], 'meta' => { 'page' => 1, 'per_page' => 10, 'total' => 0 })
+ end
+
+ it 'answers to a read-only token' do
+ body = get_json(reader, {}, token: token_for(reader, read_only: true))
+ expect(response).to have_http_status(:ok)
+ expect(body['meta']['total']).to eq(3)
+ end
+ end
+
+ describe 'a project the reader may not read answers like a missing one' do
+ let(:admin) do
+ Prosopite.pause do
+ ActsAsTenant.with_tenant(organisation) do
+ user = create(:user)
+ create(:membership, user: user, organisation: organisation, role: create(:admin_role, organisation: organisation),
+ active: true)
+ user
+ end
+ end
+ end
+
+ it 'for a missing project' do
+ get_json(reader, project_id: SecureRandom.uuid)
+ expect_not_found
+ end
+
+ it 'for a malformed project id' do
+ get_json(reader, project_id: 'not-a-uuid')
+ expect_not_found
+ end
+
+ it 'for a project beyond the token reach, even for an account admin' do
+ elsewhere = Prosopite.pause { ActsAsTenant.with_tenant(organisation) { create(:project, organisation: organisation) } }
+ get_json(admin, {}, token: token_for(admin, project_scopes: { organisation => [elsewhere] }))
+ expect_not_found
+ end
+
+ it 'for a member without access to the project' do
+ outsider = member(on: nil)
+ get_json(outsider)
+ expect_not_found
+ end
+
+ it 'for an archived project the member cannot open any more' do
+ Prosopite.pause { ActsAsTenant.with_tenant(organisation) { project.update!(archived_at: Time.current) } }
+ get_json(reader)
+ expect_not_found
+ end
+
+ it 'for a member whose membership was deactivated' do
+ token = token_for(reader)
+ Prosopite.pause { Membership.unscoped.find_by!(user: reader, organisation: organisation).update!(active: false) }
+ get_json(reader, {}, token: token)
+ expect_not_found
+ end
+
+ it 'for a project of another organisation' do
+ foreign = Prosopite.pause do
+ org = create(:organisation)
+ ActsAsTenant.with_tenant(org) { create(:project, organisation: org) }
+ end
+ get_json(admin, project_id: foreign.id)
+ expect_not_found
+ end
+ end
+
+ describe 'invalid input' do
+ it 'refuses an unknown type' do
+ get_json(reader, type: 'ticket')
+ expect_invalid_input(/invalid type/)
+ end
+
+ it 'refuses a per_page above the maximum instead of clamping it' do
+ get_json(reader, per_page: (Knowledge::Lookup::MAX_PER_PAGE + 1).to_s)
+ expect_invalid_input(/per_page/)
+ end
+
+ it 'refuses a page or per_page that is no positive whole number' do
+ token = token_for(reader)
+ get_json(reader, { page: '0' }, token: token)
+ expect_invalid_input(/page/)
+ get_json(reader, { per_page: 'abc' }, token: token)
+ expect_invalid_input(/per_page/)
+ end
+
+ it 'refuses a q given as a list' do
+ get "/api/v1/projects/#{project.id}/knowledge?q[]=a", headers: { 'Authorization' => "Bearer #{token_for(reader)}" }
+ expect_invalid_input(/q/)
+ end
+
+ it 'checks the input before the project, so a missing project with bad input is still a 422' do
+ get_json(reader, { type: 'ticket' }, project_id: SecureRandom.uuid)
+ expect_invalid_input(/invalid type/)
+ end
+ end
+end