diff --git a/AGENTS.md b/AGENTS.md index 0c1c0e3..9eacbc3 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -9,8 +9,9 @@ tests. The approved scope is the [Support Desk enhancement plan](https://github. - Contracts and core own collection policy, immutable article revisions, validation/evidence bindings, approval, publication, and retirement. - KB-01 owns pure domain work. KB-02 adds declared persistence and authorized - application services. Retrieval/search, API/MCP, and live host interfaces - remain later tasks; do not create their packages early. + application services. KB-03 extends the application with bounded retrieval, + authoritative confirmation, and repair; it adds no package. API/MCP and live + host interfaces remain later tasks; do not create their packages early. - Never implement a database, authorization role model, identity/session/token system, audit log, request limiter, or durable scheduler here. Compose the corresponding Pegma package in the owning later task. @@ -34,6 +35,11 @@ tests. The approved scope is the [Support Desk enhancement plan](https://github. not provide a global policy fence; current reads must reject stale authority. - Replay rechecks current operation/resource permission and returns a bounded historical acknowledgement, not raw content or restored publication authority. +- Retrieval projections are derived hints. Count physical work before filtering; + request paths use keyed reads, never a corpus scan. Confirm current publication, + applicability, and effective portal/bot audience before exposing any title, + count, content, or citation. Whole source serialization uses the trusted local + token counter; do not truncate article procedures into partial steps. - Base packages require no Support Desk, GitHub, model, framework, HTTP, or provider SDK. Evidence is data; never execute code or fetch submitted URLs. - Constrain content and links; host renderers must disable executable content @@ -63,3 +69,5 @@ explicit file ownership boundary; do not revert another worker's edits. For KB-02, read [declared collections](docs/COLLECTIONS.md) before changing durable operations and [host composition](docs/HOST_COMPOSITION.md) before changing authorization, verifier, replay, or DTO boundaries. +For KB-03, read [retrieval](docs/RETRIEVAL.md) and the declared projection +layout before changing query work, citations, or repair. diff --git a/README.md b/README.md index ba10a9c..d1c6f41 100644 --- a/README.md +++ b/README.md @@ -6,17 +6,17 @@ Knowledge Base owns collection policy, immutable article revisions, validation, and exact publication approval. It requires no GitHub connection or AI provider. > Development status: KB-01 provides contracts and pure domain transitions; -> KB-02 adds authorized application/persistence source. Its implementation and -> repository gates determine completion. All three packages are unpublished. -> Retrieval/search, API/MCP, and live customer/staff interfaces remain later -> tasks. This repository is not yet an operational hosted KB or a production -> dependency. +> KB-02 adds authorized application/persistence source, and KB-03 extends that +> application with bounded retrieval and repair. Implementation and repository +> gates determine completion. All three packages are unpublished. API/MCP and +> live customer/staff interfaces remain later tasks. This repository is not yet +> an operational hosted KB or a production dependency. -| Package | Scope | -| --------------------------------------------------------------------- | -------------------------------------------------------------------------------------- | -| [`@pegma/knowledge-base-contracts`](packages/contracts/README.md) | Collection, article, evidence, and approval vocabulary | -| [`@pegma/knowledge-base-core`](packages/core/README.md) | Pure validation and lifecycle transitions | -| [`@pegma/knowledge-base-application`](packages/application/README.md) | Authorized services, bounded declared persistence, private DTOs, and exact publication | +| Package | Scope | +| --------------------------------------------------------------------- | --------------------------------------------------------------------------------------- | +| [`@pegma/knowledge-base-contracts`](packages/contracts/README.md) | Collection, article, evidence, and approval vocabulary | +| [`@pegma/knowledge-base-core`](packages/core/README.md) | Pure validation and lifecycle transitions | +| [`@pegma/knowledge-base-application`](packages/application/README.md) | Authorized services, bounded persistence/retrieval, private DTOs, and exact publication | Collections default to private and independently specify portal and bot-answer audiences. Articles inherit collection policy. Staff approval binds the exact @@ -42,6 +42,13 @@ Read [declared collections](docs/COLLECTIONS.md) and [host composition](docs/HOST_COMPOSITION.md) for the layout, limits, verifier contract, and safe read boundaries. +KB-03 adds deterministic lexical retrieval over a bounded, repairable +projection. Hints are confirmed against current authoritative publication, +audience, applicability, and source eligibility before disclosure. Portal and +bot-answer uses have separate safe citations; bot-only knowledge does not +grant an article browse capability. Read [retrieval](docs/RETRIEVAL.md) for +physical work/source budgets, whole-article token accounting, and repair. + Develop on Node 22 or 24 with pnpm 10.34.5: ```sh diff --git a/docs/COLLECTIONS.md b/docs/COLLECTIONS.md index c3cbb18..758d509 100644 --- a/docs/COLLECTIONS.md +++ b/docs/COLLECTIONS.md @@ -1,15 +1,17 @@ -# KB-02 declared collections and durable layout +# Declared collections and durable layout ## Design status -This layout was written before durable operations and synchronized with the -storage/application seam agreement. KB-02 source work remains subject to the -owning implementation tests and repository gate; this document alone does not -mark the task complete. The declared collection is `knowledge-base.records.v1`. +The authoritative layout was written before KB-02 durable operations. The +KB-03 retrieval layout below was recorded before its durable operations and +synchronized with the implementation seam agreement. Source work +remains subject to owning implementation tests and repository gates; this +document alone does not mark a task complete. The authoritative collection is +`knowledge-base.records.v1`. The approved scope is the [implementation plan](https://github.com/pegma-dev/support-desk/blob/main/docs/KNOWLEDGE_AI_PLAN.md) -and its P-00 capacity/privacy requirements. No KB-03 search projection, MCP -endpoint, real-host acceptance, or production readiness is established here. +and its P-00 capacity/privacy requirements. MCP, real-host acceptance, and +production readiness remain later gates. ## Partition and authority rules @@ -176,6 +178,72 @@ exact retained immutable versions, not the new mutable draft's material. Invalid rows or an unavailable dependency produce a visible failure. There is no best-effort acceptance through Spine's event bus. Projection/search repair -is KB-03 work and cannot authorize a read or hide a failed authoritative +cannot authorize a read or hide a failed authoritative mutation. Host blob uploads are separate from record transactions and need pending references plus orphan cleanup in the owning integration. + +## KB-03 retrieval projection layout + +The derived collection is `knowledge-base.retrieval.v1`. This layout was +recorded before its operations and synchronized with source. The host-supplied +Store is isolated per KB +instance, as in KB-02. There is no tenant/instance-ID option or shared tenant +control plane. Cross-instance isolation depends on supplying separate stores. + +| Partition family | Row families | Meaning | +| ---------------------------- | ----------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------- | +| Singleton `directory` | `head` | Bounded collection discovery hints | +| `catalog:` | `head` | Bounded article discovery hints for one collection | +| `article:` | `head` | Bounded projection progress/status for one article | +| `scope:` | `head`, `manifest:`, `posting:`, `page::<0..15>` | Quota ledger, per-article term/progress manifest, posting head, and bounded posting pages | + +Article/catalog ID hashes and normalized-term hashes use +`SHA256(canonicalJson(value))`. Scope hashes cover canonical JSON of the object +`{ collectionId, policyVersion, use }`, where use is `portal` or `bot`. +Candidate entries contain article revision/content hash plus observed +application/source generations and a binding hash. Queries match the immutable +published revision/hash and current collection/policy; the hint's older +generations or full binding hash neither grant authority nor hide an unchanged +retained publication after a new draft. Current authority comes from the +publication checker. Hints contain no titles, +article bodies, raw source text, or URLs; lexical terms are hashed. These are +lookup/integrity bindings, not encryption or access capabilities. Current +authoritative confirmation still gates every exposed result. + +Request retrieval uses only keyed directory/catalog/posting reads and bounded +article confirmation. It never lists or scans a projection partition. Only +maintenance scans bounded physical pages of `knowledge-base.records.v1`, +counting all rows before filtering and returning an opaque backend cursor. + +Projection rows use native flat chunk properties with the same independent +row/string limits as the authoritative collection. Scope partitions admit at +most 8,192 physical rows and 16 MiB of encoded-record JSON estimates; batches +are bounded to 100 actions and a 3 MiB transaction estimate. A transaction +counts encoded native rows (or encoded delete keys) plus 256 bytes per action; +retained partition bytes count encoded rows without that action allowance. +These byte estimates +remain distinct from native UTF-16 property/entity bounds and backend wire +framing. Lower host limits still apply. + +Each scope batch handles at most two terms: even two full sixteen-page +postings require at most 36 physical mutations including manifest and scope +head. Three bounded CAS attempts protect the scope ledger, which subtracts +old rows/bytes and adds replacements and the new head. Scope CAS protects a +batch, not a whole corpus or all partitions. Partial batches and +directory/catalog/article-status changes are +resumable derived work. Maintain generation-fenced target manifests and +conditional cleanup, with visible pending/blocked status on failure. Do not +report indexing complete until new targets and obsolete-scope cleanup have +converged. Retirement/revocation remains effective through authoritative read +checks while projection repair catches up. See [retrieval](RETRIEVAL.md) for +query bounds, audience-safe citations, and repair/acceptance requirements. + +Cleanup reclaims obsolete term/page rows while retaining small manifest and +catalog generation floors so delayed work cannot recreate older projections. +The directory retains at most 64 collection IDs. A collection catalog retains +at most 256 article identities and 32 historical policy/use epochs; a scope +retains at most 256 article floors. An article plan admits at most 32 +known/pending scopes while cleanup converges. These are finite admission +budgets, not unbounded lifetime history. When retained floors/epochs exhaust +capacity, report blocked capacity work; no safe floor/epoch compaction is +implemented or implied. diff --git a/docs/HOST_COMPOSITION.md b/docs/HOST_COMPOSITION.md index d6bf7f3..b4b858d 100644 --- a/docs/HOST_COMPOSITION.md +++ b/docs/HOST_COMPOSITION.md @@ -1,13 +1,13 @@ -# KB-02 host composition +# Application and retrieval host composition ## Status and ownership -This documents the agreed KB-02 source API and host boundary. Implementation +This documents the agreed KB-02/KB-03 source API and host boundary. Implementation and repository gates determine task completion; this document does not assert that either real host is ready. The unpublished application composes contracts/core with host-supplied Storage Core and Authorization Core. It is -not an HTTP server, an identity system, a search service, or an operational -MCP endpoint. See [declared collections](COLLECTIONS.md) for the required +not an HTTP server, an identity system, or an operational MCP endpoint. +See [declared collections](COLLECTIONS.md) for the required layout, CAS, admission, and replay design. The host owns identity verification, scoped local-agent credentials, current @@ -52,7 +52,8 @@ the effective customer's answer audience. ## Authoring, evidence, and exact review Compose `createKnowledgeBaseApplication` once with `store` and `clock`, and -optional `limits`, `evidenceVerifier`, and `privateSources`. The full +optional `limits`, `evidenceVerifier`, `privateSources`, and nested `retrieval` +settings. The full [application types](../packages/application/src/types.ts) define the command, result, verifier, and DTO contracts. Keep mutation commands distinct from trusted contexts: the host supplies actor identity, @@ -76,8 +77,8 @@ untrusted command body as proof of authority. Names in this table are members of the contracts package's `knowledgePermissions`; they are permission identifiers, not roles. Resource and proof checks remain additional requirements. `getPublishedArticle` is a -portal read, not bot-only retrieval. No KB-03 search/bot-retrieval surface is -provided by these methods. +portal read, not bot-only retrieval. The separate retrieval methods below +enforce their own effective-customer use and audience. `getValidationRequirements` returns the current article-kind checks, validation-policy reference, governance generation, and expected staging @@ -171,8 +172,77 @@ remain live gates. Retirement or current policy revocation defeats old pointers. separate collection/profile transaction cannot atomically fence all article partitions: current checks make stale state unusable on subsequent reads; the implementation must not promise cross-partition atomic revocation. -KB-03 retrieval/search adds its own bounded candidate and final-authority -checks; a KB-02 keyed read is not that search implementation. +Retrieval/search adds bounded candidate and final-authority checks; a keyed +`getPublishedArticle` call is not a search operation. + +## Retrieval and trusted local ports + +The application extends the same composition with `retrieval.limits`, +`retrieval.candidateAdapter`, and `retrieval.tokenCounter`. Limits may only +reduce fixed component ceilings; unknown, nonpositive, or excessive values +are rejected. Defaults use keyed Storage Core projection reads. No request +path may scan or mutate a corpus. See [retrieval](RETRIEVAL.md) for the exact +[public retrieval types](../packages/application/src/retrieval-types.ts), +physical work limits, lexical behavior, and repair design. + +| Methods | Required current authority | +| -------------------------------------------------------------------- | ------------------------------------------------------------------------ | +| `listPortalCollections`, `searchPublishedArticles` | `articleRead` and the relevant portal audience | +| `retrieveAnswerSources`, `confirmAnswerSources` | Effective customer's `articleRead`, `botRead`, and relevant bot audience | +| `repairArticleIndex`, `repairRetrievalPage`, `getArticleIndexStatus` | `indexManage`; staff-only DTOs | + +Resolve bot calls from the effective customer, not an unrestricted service or +staff principal. Portal permission alone does not authorize bot use, and bot +permission does not grant portal browsing. Search and bot applicability are +exact tuples; an absent build/locale is not a wildcard. Safe no-result DTOs +contain no candidate totals or unconfirmed text. + +`SourceTokenCounter.count(serializedSources)` is a trusted synchronous local +port required for counted bot payloads. Count the complete deterministic +source serialization, not just article bodies. `AnswerSourcesResult` returns +that `serializedSources` and `sourceTokens`. Retrieval fits the largest ranked +prefix of whole sources within aggregate byte/token limits, requiring a +positive safe-integer count for nonempty sources. Reconfirmation is exact and +all-or-nothing, without prefix fitting. The owning support integration +separately budgets the full prompt and output. Do not send customer text to an +external tokenizer merely to count it. + +A host `KnowledgeCandidateAdapter` supplies source-free hints and truthful +bounded work accounting, including empty pages and discarded rows. Reported +work is checked before hints are consumed; the library cannot meter hidden +remote-provider work. Candidate IDs, ranking, and counts never authorize +content. Current publication, policy, source eligibility, and applicability +are independently confirmed by the shared checker. +The application preserves first-seen adapter order for bounded preselection; +host adapters supply stable ordering across pages and may return +approved body/synonym matches with zero local metadata overlap. Confirmed +metadata scores rank results, with adapter order breaking ties; the default +Store lexical path retains ordinal ID ties. Hosts evaluate adapter relevance +and own provider data controls. + +Citations contain a safe label and optional `portalArticle` ID/revision, never +a URL. That browse reference exists only when the same customer independently +passes portal authority. Resolve it into the host's safe article route; never +resolve a private provenance reference into a customer citation. Exact answer +source references are observation fences, not leases. Reconfirm under fresh +effective-customer access before later answer use, then enforce the Support +Desk ticket/turn fence before reply commit. + +Schedule bounded `repairRetrievalPage` cycles with its opaque cursor and +staff-visible progress. `getArticleIndexStatus` reports pending/ready/blocked +and `indexed`; a ready withdrawal has `indexed: false`. Projection admission +or partial failure must remain visible. Repair convergence is separate from +live authoritative revocation; do not imply a cross-partition transaction. +Page scans are also bounded by the shared batch allowance (at most 32 physical +rows by default), with one registration/advancement per unique collection or +article. Current collection hints also make empty collections discoverable; +directory IDs do not grant access to their labels. Persist the actual +backend cursor and repeat complete cycles; a single pass may leave pending +work. Authoritative jobs remain hints rather than being acknowledged or +deleted by repair. +Unexpected configuration, adapter, or storage errors in staff maintenance +fail visibly rather than becoming a customer `no_result`; documented admission +and source-hold status paths remain in force. ## Replay, failure, and host operation @@ -218,9 +288,9 @@ and byte accounting definition. Hosts remain responsible for authorized evidence downloads, retention/deletion, backup/recovery, blob orphan cleanup, safe Markdown/plain-text rendering, -rate limits, and later worker wakeups/checkpoints. Signed-in web/API integration +rate limits, and worker scheduling/checkpoints. Signed-in web/API integration and a supervised deployment require their own task evidence. Passing local -application tests does not establish KB-03 retrieval, MCP authentication, +application tests does not establish MCP authentication, provider ZDR configuration, either real host, or production readiness. Built in the open by RetireGolden, LLC. diff --git a/docs/RELEASING.md b/docs/RELEASING.md index 99b393b..7456022 100644 --- a/docs/RELEASING.md +++ b/docs/RELEASING.md @@ -4,9 +4,9 @@ `@pegma/knowledge-base-contracts`, `@pegma/knowledge-base-core`, and `@pegma/knowledge-base-application` are prepared at synchronized source version -`0.1.0`. All three package names are unpublished. KB-01/KB-02 establish domain -and authorized application source plus packaging checks; their repository -gates determine task completion. They do not publish, create tags/releases, +`0.1.0`. All three package names are unpublished. KB-01 through KB-03 establish +domain, authorized application, and bounded retrieval source plus packaging +checks; their repository gates determine task completion. They do not publish, create tags/releases, configure credentials, or enable a publish workflow. Hosts must wait for an exact public registry release. Git branches, copied @@ -70,7 +70,7 @@ release procedure, not proof that external publisher settings exist. - [ ] Confirm package-name ownership and organization publishing permissions. - [ ] Complete KB-05's advertised package/adapter and dual-store release - criteria. KB-02 memory/Azurite evidence does not establish the later D1 + criteria. KB-02/KB-03 memory/Azurite evidence does not establish the later D1 consumer fixture, MCP client flow, or either host's production readiness. Do not publish empty packages. - [ ] Merge reviewed release source and exact version/pin changes to protected diff --git a/docs/RETRIEVAL.md b/docs/RETRIEVAL.md new file mode 100644 index 0000000..5e38adb --- /dev/null +++ b/docs/RETRIEVAL.md @@ -0,0 +1,243 @@ +# KB-03 bounded retrieval + +## Design status + +This design was recorded before durable retrieval operations and synchronized +with the agreed public types and projection layout. Implementation tests and +repository gates remain required. +KB-03 extends the existing application package; it creates no new package, +database, model integration, or authentication system. All packages remain +unpublished at source version `0.1.0`. Source tests and repository gates, not +this document, determine completion. API/MCP, real-host acceptance, and +production activation remain later tasks. + +Read [declared collections](COLLECTIONS.md) for the authoritative record +layout and [host composition](HOST_COMPOSITION.md) for trusted access, +evidence, source eligibility, and safe DTO boundaries. + +## Projection and authority + +The index is a maintained, repairable set of derived candidate hints over +approved article revisions. A host instance and collection scope every hint; +policy/use and exact revision bindings scope its use. It is not another +authoritative KB. A search entry never grants publication, audience access, +product applicability, or authority to a title, snippet, count, or citation. + +Request paths use keyed reads only. The lexical index uses approved titles, +summaries, and tags, not article bodies or private material. Normalization +folds accents/case, extracts Unicode letter/number terms, and removes common +question words. Approved tags supply explicit aliases; the default path has +no model query expansion. Confirmed metadata scores a title match at 12, tag match at +8, and summary match at 3 per query term. Semantic retrieval is not required +by this task. See [COLLECTIONS.md](COLLECTIONS.md) for physical row families. + +Default Store preselection considers at most eight candidates (or a lower +configured bound) by matching-term count, then ordinal article ID. Confirmed +positive lexical matches sort by score descending, then ordinal article ID. +With an optional adapter, preselection preserves first-seen response order +across pages. The host supplies stable relevance ordering; it may match +approved body text or synonyms with zero local +metadata overlap; after confirmation, metadata score ranks those candidates +and adapter order breaks equal-score ties. Both paths rank a bounded candidate +window, without an exhaustive corpus-wide best-match claim. + +Every article candidate must pass the shared authoritative publication checker before +any customer/model material is returned. The checker uses the exact current +published revision, its retained review/proofs/source snapshot, current +collection and validation authority, current source eligibility, and the +requested product applicability. It does not use the new draft's metadata. +Retained proof freshness is checked at the stored approval time; proof +availability, revocation, governance, and source eligibility remain live. +A hint must match the immutable approved revision/hash and current +collection/policy. Its observed application/source generations and full +binding hash do not establish authority. A new draft can make those hint +fields old while leaving the retained approved revision unchanged; that +publication remains searchable after full current confirmation. Output +reference fences come from the checker, not the hint. +Collection discovery labels likewise come from the current authorized +collection, never a directory hint. + +Portal and bot-answer audiences are independent. The host supplies the +effective customer's authority; a broad service context cannot widen it. +Drafts, evidence, private source references, review metadata, internal notes, +and storage metadata never enter retrieval DTOs. Unauthorized hints are not +exposed through titles, snippets, total counts, or diagnostic errors either. + +## Application surface + +The existing `createKnowledgeBaseApplication` composition accepts optional +`retrieval` settings: downward-only `limits`, a host `candidateAdapter`, and a +trusted local `tokenCounter`. The +[retrieval types](../packages/application/src/retrieval-types.ts) define these +ports and the following methods; there is no new package or HTTP endpoint. + +| Method | Authority and result boundary | +| -------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------- | +| `listPortalCollections` | `articleRead` plus each current portal audience; safe collection ID/label only | +| `searchPublishedArticles` | `articleRead`, current portal audience, and exact requested applicability; confirmed publication metadata/snippet | +| `retrieveAnswerSources` | Effective customer's `articleRead`, `botRead`, and current bot audience; whole approved source payloads | +| `confirmAnswerSources` | Same bot authority and exact current reference/applicability check before downstream use | +| `repairArticleIndex`, `repairRetrievalPage`, `getArticleIndexStatus` | `indexManage`; staff-only maintenance/status DTOs | + +Customer retrieval results have `outcome: "results" | "no_result"` and no candidate totals. +Search snippets are the confirmed approved summary, never posting text or +truncated procedure steps. +Applicability is an exact tuple, including absent build/locale; absence does +not request a fallback or wildcard. Existing `getPublishedArticle` remains a +portal keyed read and retains its original input contract. +Invalid query/scope/limit input throws `TypeError`. Access failures, +stale/unavailable authority, malformed adapter accounting, exhausted read +budgets, and missing/invalid token counters produce the content-free +`no_result` shape rather than exposing private candidate diagnostics. + +The optional `KnowledgeCandidateAdapter` returns source-free hints and bounded +`CandidateWork`. The host adapter must truthfully report keyed reads, +physical rows, posting entries, and pages, including empty pages, misses, +duplicates, malformed, and filtered rows. The application validates and counts +reported work before consuming hints; it cannot meter an external provider's +unreported internal work. An adapter's ranking, hint, or count grants no +authority. Hosts own adapter relevance evaluation and provider data controls. + +## Fixed ceilings + +These are component work/admission ceilings, not measured production capacity +or retrieval-quality certification. Hosts may configure lower values only. +Each independent bound still applies when another bound has remaining space. + +| Scope | Ceiling | +| --------------------- | ------------------------------------------------------------------------------------------------ | +| Directory | 64 collections per instance | +| Catalog | 256 articles per collection | +| Terms | 256 indexed terms per article | +| Posting | 16 entries per page; 16 pages per term | +| Projection partition | 8,192 physical rows and 16 MiB encoded-record estimate | +| Query | 256 UTF-16 code units and 8 distinct normalized terms | +| Bot query scope | 4 collections | +| Request index work | 128 keyed index reads and 2,048 posting entries | +| Request article work | 64 head probes and 8 full authoritative confirmations | +| Returned sources | 5 whole articles and 64 KiB of content | +| Model source budget | 8,192 tokens in the complete serialized source set | +| Request physical work | 768 total physical keyed reads | +| Maintenance scan | Configured row ceiling 100; actual page also bounded by requested limit and shared batch ceiling | +| Maintenance batches | 32 shared per maintenance call; at most 32 physical scan rows with defaults | + +Count physical work before filtering and deduplication. A query cannot bypass +work limits by retrieving many unauthorized, duplicate, or stale entries. +Request handlers never scan the corpus to fill a result count. Bounded +no-result and admission outcomes must remain explicit. Invalid input is not +silently truncated into a different query. + +The host's trusted local token counter measures the complete serialization +that will be supplied as sources, including citation labels and metadata. +It must not send text to a model or external token service merely to count it. +`retrieveAnswerSources` selects the largest top-ranked prefix of whole sources +that fits aggregate byte/token bounds; it never truncates a procedure into +partial steps. A nonempty source set requires a positive safe-integer local +token count. A `no_result` has empty sources and zero source tokens. +Later support-answer code must +still account for its complete prompt and output budgets separately. +`AnswerSourcesResult` returns `serializedSources` and `sourceTokens` for that +trusted bot integration. A missing token counter cannot produce an uncounted +bot payload. Portal search DTOs do not contain this model source envelope. +Serialization is canonical JSON of every returned source DTO field, including +its exact reference and citation; counting only body text is insufficient. + +## Citations and use + +Customer-readable portal sources can carry a safe article browse reference. +Bot-only sources carry an approved source label without a staff URL or a +browse capability. A bot source receives a browse reference only when the +same effective customer can independently read that portal article. Hosts +resolve safe browse references into their own routes; private source-system +URLs never become citations. + +Return exact article/revision references for downstream answer validation. +`AnswerSourceReference` also binds collection policy, content hash, and current +application/governance/validation generations. It is an observation fence, +not a lease or authorization capability. `confirmAnswerSources` checks those +references under fresh effective-customer access before they are used again. +Reconfirmation is exact and all-or-nothing: it does not fit a smaller prefix +or return the still-valid subset when any requested source fails. +Retrieval authorization is not a capability to publish a later answer after +inputs change. Support Desk must recheck current source authority and its own +ticket/turn fence before committing a reply. Cache and adapter keys must +include instance, collection, use/audience-policy binding, and exact revision; +a cache hit cannot replace current authoritative confirmation. + +## Maintenance, retirement, and repair + +Only maintenance scans physical pages of the authoritative record collection. +It counts every scanned row before filtering, uses the backend's opaque +continuation cursor, and treats article/collection heads and their causal jobs +as hints. Candidate deduplication uses resource kind and ID. The worker rereads +the current authoritative resource; job payloads and historical generations +are not content sources. Current collection hints register only a directory +ID, allowing authorized discovery of empty collections. The reader still +confirms collection labels and portal access. + +`repairRetrievalPage` scans at most the minimum of its requested limit, +`maxRepairScanRows`, and `maxMaintenanceBatches`. Defaults therefore scan at +most 32 physical rows, even though the configurable scan ceiling is 100. +Each unique resource gets at most one collection registration or article +advancement batch on that page; +`repairArticleIndex` can use the full shared batch allowance for its one +article. A completed scan page or cycle is not proof all pending projections +are finished. Hosts persist the actual backend `nextCursor` and repeat full +cycles to revisit pending heads/jobs without starving later resources. Repair +does not mutate or acknowledge authoritative causal jobs; they remain +replay-safe hints. + +Derived writes and cleanup must be generation-fenced and idempotent so a +delayed job cannot restore obsolete content. Persist bounded per-article +pending/blocked progress and capacity reasons. Do not mark an article indexed +until its desired targets are committed and obsolete scopes are cleaned. +Repeated bounded scan cycles and checkpoints repair missed or failed work. +The host owns scheduling, retry cadence, visibility, and operator recovery; +Spine's in-process event bus is not a durable delivery mechanism. + +Retirement, moves, policy revocation, proof revocation, and changed source +eligibility may leave temporary stale hints. Current publication checks must +reject those hints while repair catches up. There is no cross-partition +transaction or claim that projection repair completes before revocation takes +effect. Capacity failure leaves visible repair work rather than accepting a +partial index as complete. + +Cleanup reclaims obsolete postings while retaining bounded generation floors +and historical scope identities. Directory/catalog/scope lifetime admission +and epoch limits remain finite, as declared in [COLLECTIONS.md](COLLECTIONS.md). +Do not delete those floors to make space or imply an unimplemented compaction +protocol. + +`ArticleIndexStatusDto` reports `status` as `pending`, `ready`, or `blocked`, +an `indexed` boolean, nullable article/projection generations, and an optional +coarse reason (`capacity`, `source-unavailable`, or `conflict`). A converged +withdrawal is `ready` with `indexed: false`; ready does not necessarily mean +there is a usable indexed publication. Terms, postings, hashes, and private +sources are absent. Repair-page diagnostic counts and `nextCursor` are +staff-only and never become customer search totals. +Staff maintenance is not a customer no-result path: unexpected configuration, +adapter, or storage errors remain visible exceptions. Supported admission and +source-hold conditions retain their named status/withdrawal behavior. + +## Evaluation and acceptance + +Use representative fictional product questions and paraphrases, including +known no-result cases. Verify deterministic ordering and supported citations, +then measure retrieval coverage and latency on the activated configuration. +Host owners sign off measured quality/latency budgets; this component does not +invent a percentage target or certify real product knowledge from fixtures. + +Public-entry tests must cover separate portal/bot audiences, bot-only labels, +draft exclusion, stale index/cache and policy/proof/source revocation, +applicability mismatches, safe titles/snippets/counts/errors, whole-source +budgets, and instrumented physical read/page ceilings. Maintenance tests cover +duplicate/out-of-order jobs, partial failure, bounded resumable scans, +capacity admission, retirement/move cleanup, and repair convergence. Memory +and real-Azurite evidence are source gates; D1 consumer conformance and real +host workflows retain their later release/activation gates. + +The executable source cases live in [retrieval tests](../tests/retrieval.test.ts) +and [physical-bound tests](../tests/retrieval-bounds.test.ts), using +[fictional retrieval fixtures](../test/retrieval-fixtures.ts). A current-head +gate report is the evidence of a passing run; these links do not certify a +host's real product content or deployment. diff --git a/packages/application/README.md b/packages/application/README.md index e5451bf..dcd6ece 100644 --- a/packages/application/README.md +++ b/packages/application/README.md @@ -1,15 +1,17 @@ # @pegma/knowledge-base-application -This unpublished KB-02 source package composes contracts/core with +This unpublished KB-02/KB-03 source package composes contracts/core with host-supplied Storage Core, Authorization Core, Audit, and a clock. Source -implementation and repository gates determine KB-02 completion; neither this +implementation and repository gates determine task completion; neither this package nor local tests establish a live host or production readiness. The [declared layout](https://github.com/pegma-dev/knowledge-base/blob/main/docs/COLLECTIONS.md) records the agreement made before durable operations. [Host composition](https://github.com/pegma-dev/knowledge-base/blob/main/docs/HOST_COMPOSITION.md) describes the host authentication, current-resource authorization, verified-evidence, and privacy -boundaries. KB-03 retrieval, API/MCP, real-host acceptance, and production -activation remain later tasks. +boundaries. [Retrieval](https://github.com/pegma-dev/knowledge-base/blob/main/docs/RETRIEVAL.md) +documents bounded lexical lookup, authoritative confirmation, citations, and +repair. API/MCP, real-host acceptance, and production activation remain later +tasks. GitHub links in this unpublished README track development `main`; they are not frozen version documentation. KB-05 release preparation must pin those @@ -17,7 +19,8 @@ references to verified release source before first publication. The application API owns authorized commands, application-generation CAS, bounded immutable revision/evidence history, exact review/publication, -transactional Audit/receipts/causal jobs, and safe published-content DTOs. +transactional Audit/receipts/causal jobs, bounded retrieval/repair, and safe +published-content DTOs. Collections own audience policy; articles inherit it without per-article ACLs. Role models, token issuance, sessions, HTTP, provider SDKs, arbitrary URL fetching, code execution, and a new database are outside this package. @@ -32,7 +35,8 @@ or a support model. ## Composition and commands `createKnowledgeBaseApplication` takes `store` and `clock`, with optional -`limits`, `evidenceVerifier`, and `privateSources`. Hosts authenticate callers +`limits`, `evidenceVerifier`, `privateSources`, and nested `retrieval` settings. +Hosts authenticate callers and resolve current scoped `AccessContext` values. The [public types](https://github.com/pegma-dev/knowledge-base/blob/main/packages/application/src/types.ts) define commands and purpose-specific results; the package owns no HTTP routes or credentials. @@ -84,6 +88,39 @@ proof availability, and revocation remain live checks. Article CAS cannot globally fence separate collection/ validation-policy partitions. +## Bounded retrieval and repair + +`listPortalCollections` and `searchPublishedArticles` require current portal +authority. `retrieveAnswerSources` and `confirmAnswerSources` use the effective +customer's `articleRead`, `botRead`, independent bot audience, and exact product +applicability. Read results report `results` or `no_result`, never candidate +totals. Titles, snippets, content, and citations come from freshly confirmed +publications rather than index text. Bot-only citations have a safe label; +`portalArticle` appears only when that customer can also browse the article. + +The default lexical projection uses approved titles, summaries, and tags, not +body text. Requests use only bounded keyed reads. Optional +`retrieval.candidateAdapter` hints remain untrusted; the host adapter must +report all physical work, including empty pages and discarded rows. +Adapters may match approved body text/synonyms with zero metadata overlap; +bounded preselection preserves their order, and confirmed metadata scores +rank results with adapter-order ties. Hosts own relevance evaluation and +provider data controls; current publication checks remain mandatory. +`retrieval.tokenCounter` is a trusted local counter over the complete +`serializedSources` returned with `sourceTokens`. Retrieval fits the largest +ranked prefix of whole articles within aggregate byte/token budgets with a +positive local count; reconfirmation is exact and all-or-nothing. +`retrieval.limits` can only lower fixed component ceilings. +See [retrieval](https://github.com/pegma-dev/knowledge-base/blob/main/docs/RETRIEVAL.md) +for the exact API, limits, authority/reference fences, and evaluation boundary. + +`repairArticleIndex`, `repairRetrievalPage`, and `getArticleIndexStatus` require +`indexManage`. Only maintenance performs bounded physical scans with opaque +cursors. Pending/blocked status remains visible until repair converges; +`ready` with `indexed: false` means a converged withdrawal. Projection cleanup +may lag retirement/revocation, but current authority checks still reject +ineligible publications. The host owns scheduling and recovery. + ## Storage and limits All accepted head changes, immutable rows, generic Audit actions, receipts, and diff --git a/packages/application/src/index.ts b/packages/application/src/index.ts index 6223999..66d4c2d 100644 --- a/packages/application/src/index.ts +++ b/packages/application/src/index.ts @@ -2,6 +2,11 @@ import { createArticleServices } from "./articles.js"; import { createGovernanceServices } from "./governance.js"; import { createReadServices } from "./reads.js"; import { createKnowledgeRepository } from "./repository.js"; +import { createPublicationChecker } from "./publication.js"; +import { resolveRetrievalLimits } from "./retrieval-limits.js"; +import { createRetrievalMaintenanceServices } from "./retrieval-maintenance.js"; +import { createRetrievalRepository } from "./retrieval-repository.js"; +import { createRetrievalServices } from "./retrieval.js"; import type { KnowledgeBaseApplication, KnowledgeBaseApplicationOptions, @@ -15,6 +20,7 @@ export function createKnowledgeBaseApplication( const repository = createKnowledgeRepository(options.store, options.limits); const services: KnowledgeBaseServiceOptions = { clock: options.clock, + limits: repository.limits, ...(options.evidenceVerifier === undefined ? {} : { evidenceVerifier: options.evidenceVerifier }), @@ -22,10 +28,29 @@ export function createKnowledgeBaseApplication( ? {} : { privateSources: options.privateSources }), }; + const retrievalLimits = resolveRetrievalLimits(options.retrieval?.limits); + const retrievalRepository = createRetrievalRepository( + options.store, + retrievalLimits, + ); + const publications = createPublicationChecker(repository, services); return Object.freeze({ ...createArticleServices(repository, services), ...createGovernanceServices(repository, services), ...createReadServices(repository, services), + ...createRetrievalServices({ + store: options.store, + services, + ...(options.retrieval === undefined + ? {} + : { options: options.retrieval }), + }), + ...createRetrievalMaintenanceServices( + repository, + retrievalRepository, + publications, + { store: options.store, retrievalLimits }, + ), }); } @@ -42,4 +67,7 @@ export { RepositoryIntegrityError, } from "./storage-helpers.js"; export type * from "./types.js"; +export type * from "./retrieval-types.js"; +export { defaultKnowledgeRetrievalLimits } from "./retrieval-types.js"; +export { retrievalRecords, type RetrievalRecord } from "./retrieval-records.js"; export { knowledgePermissions } from "@pegma/knowledge-base-contracts"; diff --git a/packages/application/src/lexical.ts b/packages/application/src/lexical.ts new file mode 100644 index 0000000..0e21ca7 --- /dev/null +++ b/packages/application/src/lexical.ts @@ -0,0 +1,120 @@ +import type { PublishedArticleDto } from "./types.js"; +import { RepositoryCapacityError } from "./storage-helpers.js"; + +const maximumQueryCharacters = 256; +const maximumQueryTerms = 8; +const maximumIndexTerms = 256; +const maximumTermCharacters = 256; +const questionWords = new Set([ + "a", + "an", + "and", + "are", + "as", + "at", + "be", + "can", + "do", + "does", + "for", + "from", + "how", + "i", + "in", + "is", + "it", + "me", + "my", + "of", + "on", + "or", + "please", + "the", + "to", + "with", + "you", + "your", +]); + +type SearchableMetadata = Pick< + PublishedArticleDto, + "title" | "summary" | "tags" +>; + +/** Deterministic lexical terms only; aliases must be explicit approved tags. */ +function terms(value: string): string[] { + if (typeof value !== "string") + throw new TypeError("Search metadata must be text"); + const normalized = value + .normalize("NFKD") + .replace(/\p{M}+/gu, "") + .toLowerCase(); + const result = normalized.match(/[\p{L}\p{N}]+/gu) ?? []; + if (result.some((term) => term.length > maximumTermCharacters)) { + throw new TypeError("Search term exceeds the supported length"); + } + return result.filter((term) => !questionWords.has(term)); +} + +/** Reject oversized input; never silently truncate a customer's query. */ +export function normalizeQuery(query: string): readonly string[] { + if ( + typeof query !== "string" || + query.length === 0 || + query.length > maximumQueryCharacters || + /[\u0000-\u001f\u007f]/u.test(query) + ) + throw new TypeError("Query must contain at most 256 characters of text"); + const normalized = [...new Set(terms(query))]; + if (normalized.length > maximumQueryTerms) { + throw new TypeError("Query contains more than eight distinct search terms"); + } + return Object.freeze(normalized); +} + +/** + * Projection input is approved title/summary/tags, never body text or evidence. + * Overlarge metadata is a visible indexing failure, not a partial projection. + */ +export function indexArticleTerms( + article: SearchableMetadata, + limit = maximumIndexTerms, +): readonly string[] { + if (!Number.isSafeInteger(limit) || limit < 1 || limit > maximumIndexTerms) { + throw new TypeError("Index term limit must be between one and 256"); + } + if (!Array.isArray(article.tags) || article.tags.length > 16) { + throw new TypeError("Approved tags exceed their schema bound"); + } + const result = [ + ...new Set([ + ...terms(article.title), + ...terms(article.summary), + ...article.tags.flatMap(terms), + ]), + ].sort(); + if (result.length > limit) { + throw new RepositoryCapacityError("index_terms"); + } + return Object.freeze(result); +} + +/** Score only locally confirmed approved metadata, never posting-row text. */ +export function scoreConfirmedArticle( + article: SearchableMetadata, + queryTerms: readonly string[], +): number { + if (queryTerms.length > maximumQueryTerms) { + throw new TypeError("Scoring query exceeds its term bound"); + } + const title = new Set(terms(article.title)); + const summary = new Set(terms(article.summary)); + const tags = new Set(article.tags.flatMap(terms)); + let score = 0; + for (const term of queryTerms) { + if (title.has(term)) score += 12; + if (tags.has(term)) score += 8; + if (summary.has(term)) score += 3; + } + return score; +} diff --git a/packages/application/src/publication.ts b/packages/application/src/publication.ts new file mode 100644 index 0000000..d4d9ccf --- /dev/null +++ b/packages/application/src/publication.ts @@ -0,0 +1,405 @@ +import { hasPermission, type AccessContext } from "@pegma/authorization-core"; +import { + knowledgePermissions, + type Applicability, + type Article, + type ArticleRevision, + type CollectionUse, + type IsoTimestamp, + type ValidationPolicyReference, + type VerificationEvidence, +} from "@pegma/knowledge-base-contracts"; +import { + isPublicationBoundToCurrentPolicies, + KnowledgeBaseError, + knowledgeLimits, + publishArticle, +} from "@pegma/knowledge-base-core"; + +import { + KnowledgeBaseNotFoundError, + KnowledgeBasePrerequisiteError, +} from "./errors.js"; +import { loadGovernanceContext } from "./governance.js"; +import type { + ArticlePublicationState, + KnowledgeRepository, +} from "./repository.js"; +import { + canonicalJson, + RepositoryCapacityError, + RepositoryConflictError, + RepositoryIntegrityError, + requireIdentifier, + snapshotData, +} from "./storage-helpers.js"; +import type { + KnowledgeBaseServiceOptions, + PublishedArticleDto, + SourceSnapshot, +} from "./types.js"; + +export type PublicationPurpose = "portal" | "bot" | "index"; + +export interface PublicationCheckRequest { + readonly articleId: string; + readonly purpose: PublicationPurpose; + readonly access: AccessContext; + /** Exact applicability, including absence of build/locale; no inferred fallback. */ + readonly applicability?: Applicability; +} + +/** Internal authority only. Never spread source fences into customer/model DTOs. */ +export interface PublicationAuthorityBinding { + readonly articleId: string; + readonly revision: number; + readonly contentHash: string; + readonly articleGeneration: number; + readonly collectionId: string; + readonly governanceGeneration: number; + readonly validationPolicy: ValidationPolicyReference; + readonly validationGeneration: number; + readonly collectionPolicyVersion: number; + readonly collectionPolicyHash: string; + readonly validationPolicyHash: string; + readonly sourceGeneration: number; + readonly sourceSnapshotHash: string; +} + +export interface CheckedPublication { + readonly article: PublishedArticleDto; + readonly binding: PublicationAuthorityBinding; + /** Whether this effective caller can browse the independently governed portal. */ + readonly portalBrowseable: boolean; + /** Maintenance metadata under the same governance fence, never an access grant. */ + readonly enabledUses: readonly ("portal" | "bot")[]; +} + +interface ConfirmationState { + readonly access: AccessContext; + readonly purpose: PublicationPurpose; + readonly binding: PublicationAuthorityBinding; + readonly revision: ArticleRevision; + readonly source: SourceSnapshot; + readonly use?: CollectionUse; +} + +function unavailable(): KnowledgeBaseNotFoundError { + return new KnowledgeBaseNotFoundError("article"); +} + +function clockTime(options: KnowledgeBaseServiceOptions): IsoTimestamp { + const at = options.clock.now(); + if ( + typeof at !== "string" || + !Number.isFinite(Date.parse(at)) || + new Date(at).toISOString() !== at + ) { + throw new TypeError("Clock must return a canonical ISO timestamp"); + } + return at; +} + +function allows(use: CollectionUse, access: AccessContext): boolean { + return ( + use.enabled && + (use.audience.kind === "anonymous" || + hasPermission(access, use.audience.permission)) + ); +} + +function authorize(access: AccessContext, purpose: PublicationPurpose): void { + if (purpose === "index") { + if (!hasPermission(access, knowledgePermissions.indexManage)) + throw unavailable(); + return; + } + if ( + !hasPermission(access, knowledgePermissions.articleRead) || + (purpose === "bot" && !hasPermission(access, knowledgePermissions.botRead)) + ) + throw unavailable(); +} + +function isUnavailable(error: unknown): boolean { + return ( + error instanceof KnowledgeBaseError || + error instanceof KnowledgeBaseNotFoundError || + error instanceof KnowledgeBasePrerequisiteError || + error instanceof RepositoryCapacityError || + error instanceof RepositoryConflictError || + error instanceof RepositoryIntegrityError + ); +} + +function immutable(value: T): T { + if (value !== null && typeof value === "object") { + for (const child of Object.values(value)) immutable(child); + Object.freeze(value); + } + return value; +} + +async function publishedEvidence( + repository: KnowledgeRepository, + current: ArticlePublicationState, +): Promise { + const published = current.published; + if (published === undefined) throw unavailable(); + const references = published.approval.binding.evidence; + if ( + !Array.isArray(references) || + references.length > knowledgeLimits.evidence + ) + throw new RepositoryIntegrityError(); + return Promise.all( + references.map(async (reference) => { + const [evidence, revoked] = await Promise.all([ + repository.getEvidenceVersion( + current.articleId, + published.revision.number, + reference.id, + reference.version, + ), + repository.isEvidenceRevoked(current.articleId, reference.hash), + ]); + if (evidence === null || revoked || evidence.hash !== reference.hash) + throw unavailable(); + return evidence; + }), + ); +} + +/** One authority path for portal reads, customer bot retrieval, and private indexing. */ +export function createPublicationChecker( + repository: KnowledgeRepository, + options: KnowledgeBaseServiceOptions, +): { + readonly check: ( + request: PublicationCheckRequest, + ) => Promise; + readonly recheck: (checked: CheckedPublication) => Promise; +} { + const confirmations = new WeakMap(); + + async function confirm(state: ConfirmationState): Promise { + authorize(state.access, state.purpose); + if (state.use !== undefined && !allows(state.use, state.access)) + throw unavailable(); + if ( + !Array.isArray(state.source.references) || + state.source.references.length > 32 + ) + throw new RepositoryIntegrityError(); + if (state.source.references.length > 0) { + const verifier = options.privateSources; + if ( + typeof verifier?.canPublish !== "function" || + typeof verifier.isCurrent !== "function" + ) + throw unavailable(); + let eligible: readonly boolean[]; + try { + eligible = await Promise.all([ + verifier.canPublish({ + article: snapshotData(state.revision), + snapshot: snapshotData(state.source), + }), + verifier.isCurrent({ + article: snapshotData(state.revision), + snapshot: snapshotData(state.source), + }), + ]); + } catch { + throw unavailable(); + } + if (eligible.some((value) => value !== true)) throw unavailable(); + } + const [article, collection, validation] = await Promise.all([ + repository.readResourceGeneration("article", state.binding.articleId), + repository.readResourceGeneration( + "collection", + state.binding.collectionId, + ), + repository.readResourceGeneration( + "validation", + state.binding.validationPolicy.id, + ), + ]); + if ( + article !== state.binding.articleGeneration || + collection !== state.binding.governanceGeneration || + validation !== state.binding.validationGeneration + ) + throw unavailable(); + authorize(state.access, state.purpose); + } + + return { + async check(request) { + const access = immutable(snapshotData(request.access)); + const articleId = request.articleId; + requireIdentifier(articleId, "articleId"); + if (!["portal", "bot", "index"].includes(request.purpose)) + throw new TypeError("Unknown publication purpose"); + const purpose = request.purpose; + const applicability = + request.applicability === undefined + ? undefined + : snapshotData(request.applicability); + authorize(access, purpose); + try { + const loaded = + await repository.readArticlePublicationVersioned(articleId); + const current = loaded?.value; + const publication = current?.published; + const review = current?.publicationReview; + const source = current?.publishedProvenance; + if ( + current === undefined || + current.state === "retired" || + current.publicationHeld || + publication === undefined || + review === undefined || + source === undefined + ) + throw unavailable(); + const revision = publication.revision; + if ( + applicability !== undefined && + canonicalJson(applicability) !== canonicalJson(revision.applicability) + ) + throw unavailable(); + const at = clockTime(options); + const governance = await loadGovernanceContext( + repository, + revision.collectionId, + at, + ); + const policy = governance.context.collection.policy; + const enabledUses: ("portal" | "bot")[] = []; + if (policy.portal.enabled) enabledUses.push("portal"); + if (policy.bot.enabled) enabledUses.push("bot"); + const use = purpose === "index" ? undefined : policy[purpose]; + if (use === undefined ? enabledUses.length === 0 : !allows(use, access)) + throw unavailable(); + if ( + review.governanceGeneration !== governance.governanceGeneration || + canonicalJson(review.binding) !== + canonicalJson(publication.approval.binding) || + source.hash !== review.sourceSnapshotHash || + source.generation !== review.sourceGeneration + ) + throw unavailable(); + const evidence = await publishedEvidence(repository, current); + const proof: Article = { + id: articleId, + state: "in-review", + current: revision, + evidence, + review: publication.approval.binding, + }; + const publishedArticle: Article = { + ...proof, + state: "published", + published: publication, + }; + if ( + !(await isPublicationBoundToCurrentPolicies( + publishedArticle, + governance.context.collection, + governance.context.validationPolicy, + )) + ) + throw unavailable(); + const approvedAt = publication.approval.reviewedAt; + if ( + typeof approvedAt !== "string" || + !Number.isFinite(Date.parse(approvedAt)) || + new Date(approvedAt).toISOString() !== approvedAt || + Date.parse(approvedAt) > Date.parse(at) || + Date.parse(approvedAt) < Date.parse(revision.createdAt) + ) + throw unavailable(); + await publishArticle(proof, { + expectedRevision: revision.number, + binding: publication.approval.binding, + reviewerId: publication.approval.reviewerId, + context: { ...governance.context, at: approvedAt }, + }); + const binding: PublicationAuthorityBinding = { + articleId, + revision: revision.number, + contentHash: revision.contentHash, + articleGeneration: current.generation, + collectionId: revision.collectionId, + governanceGeneration: governance.governanceGeneration, + validationPolicy: revision.validationPolicy, + validationGeneration: governance.validationGeneration, + collectionPolicyVersion: + publication.approval.binding.collectionPolicyVersion, + collectionPolicyHash: + publication.approval.binding.collectionPolicyHash, + validationPolicyHash: + publication.approval.binding.validationPolicyHash, + sourceGeneration: source.generation, + sourceSnapshotHash: source.hash, + }; + const state = immutable( + snapshotData({ + access, + purpose, + binding, + revision, + source, + ...(use === undefined ? {} : { use }), + }), + ); + await confirm(state); + const checked = immutable( + snapshotData({ + article: { + articleId, + collectionId: revision.collectionId, + revision: revision.number, + kind: revision.kind, + title: revision.title, + summary: revision.summary, + content: revision.content, + tags: revision.tags, + applicability: revision.applicability, + contentHash: revision.contentHash, + }, + binding, + portalBrowseable: + hasPermission(access, knowledgePermissions.articleRead) && + allows(policy.portal, access), + enabledUses, + }), + ); + confirmations.set(checked, state); + return checked; + } catch (error) { + if (purpose === "index" && error instanceof RepositoryCapacityError) + throw error; + if (isUnavailable(error)) throw unavailable(); + throw error; + } + }, + async recheck(checked) { + const state = confirmations.get(checked); + if (state === undefined) throw unavailable(); + try { + await confirm(state); + } catch (error) { + if ( + state.purpose === "index" && + error instanceof RepositoryCapacityError + ) + throw error; + if (isUnavailable(error)) throw unavailable(); + throw error; + } + }, + }; +} diff --git a/packages/application/src/reads.ts b/packages/application/src/reads.ts index 4822475..56b969c 100644 --- a/packages/application/src/reads.ts +++ b/packages/application/src/reads.ts @@ -2,16 +2,8 @@ import { hasPermission } from "@pegma/authorization-core"; import { articleKinds, knowledgePermissions, - type Article, type IsoTimestamp, - type VerificationEvidence, } from "@pegma/knowledge-base-contracts"; -import { - isPublicationBoundToCurrentPolicies, - KnowledgeBaseError, - knowledgeLimits, - publishArticle, -} from "@pegma/knowledge-base-core"; import { KnowledgeBaseNotFoundError, @@ -19,11 +11,11 @@ import { requirePermission, } from "./errors.js"; import { loadGovernanceContext } from "./governance.js"; +import { createPublicationChecker } from "./publication.js"; import type { StoredArticle } from "./records.js"; import type { KnowledgeRepository } from "./repository.js"; import { canonicalJson, - RepositoryCapacityError, RepositoryConflictError, RepositoryIntegrityError, requireIdentifier, @@ -84,39 +76,6 @@ function snapshotReferences( return snapshot.references; } -/** Resolve only the bounded exact versions named by a retained publication. */ -async function publishedEvidence( - repository: KnowledgeRepository, - current: StoredArticle, -): Promise { - const published = current.article.published; - if (published === undefined) return []; - const binding = published.approval.binding; - if ( - !Array.isArray(binding.evidence) || - binding.evidence.length > knowledgeLimits.evidence - ) { - throw new RepositoryIntegrityError(); - } - return Promise.all( - binding.evidence.map(async (reference) => { - const [evidence, revoked] = await Promise.all([ - repository.getEvidenceVersion( - current.article.id, - published.revision.number, - reference.id, - reference.version, - ), - repository.isEvidenceRevoked(current.article.id, reference.hash), - ]); - if (evidence === null || revoked || evidence.hash !== reference.hash) { - throw new KnowledgeBaseNotFoundError("article"); - } - return evidence; - }), - ); -} - /** Explicit keyed staff reads and a separately authorized portal-only read. */ export function createReadServices( repository: KnowledgeRepository, @@ -133,6 +92,7 @@ export function createReadServices( | "getReview" | "getPublishedArticle" > { + const publications = createPublicationChecker(repository, options); return { async getCollection(access, request) { access = snapshotData(access); @@ -333,168 +293,13 @@ export function createReadServices( }, async getPublishedArticle(access, request) { - access = snapshotData(access); const input = readInput(request, "articleId"); - const unavailable = () => new KnowledgeBaseNotFoundError("article"); - if (!hasPermission(access, knowledgePermissions.articleRead)) - throw unavailable(); - try { - const current = await requiredArticle(repository, input.articleId); - const publication = current.article.published; - const review = current.publicationReview; - if ( - current.article.state === "retired" || - current.publicationHeld || - publication === undefined || - review === undefined - ) - throw unavailable(); - const at = clockTime(options); - const governance = await loadGovernanceContext( - repository, - publication.revision.collectionId, - at, - ); - const portal = governance.context.collection.policy.portal; - if ( - !portal.enabled || - (portal.audience.kind === "permission" && - !hasPermission(access, portal.audience.permission)) - ) - throw unavailable(); - if ( - review.governanceGeneration !== governance.governanceGeneration || - canonicalJson(review.binding) !== - canonicalJson(publication.approval.binding) - ) - throw unavailable(); - const source = current.publishedProvenance; - if ( - source === undefined || - source.hash !== review.sourceSnapshotHash || - source.generation !== review.sourceGeneration - ) - throw unavailable(); - const references = snapshotReferences(source); - if (references.length > 0) { - const verifier = options.privateSources; - if ( - verifier === undefined || - typeof verifier.canPublish !== "function" || - typeof verifier.isCurrent !== "function" - ) - throw unavailable(); - let sourceEligibility: readonly boolean[]; - try { - sourceEligibility = await Promise.all([ - verifier.canPublish({ - article: snapshotData(publication.revision), - snapshot: snapshotData(source), - }), - verifier.isCurrent({ - article: snapshotData(publication.revision), - snapshot: snapshotData(source), - }), - ]); - } catch { - throw unavailable(); - } - if (sourceEligibility.some((allowed) => allowed !== true)) - throw unavailable(); - } - const [revision, evidence] = await Promise.all([ - repository.getArticleRevision( - current.article.id, - publication.revision.number, - ), - publishedEvidence(repository, current), - ]); - if ( - revision === null || - canonicalJson(revision) !== canonicalJson(publication.revision) - ) - throw unavailable(); - if ( - !(await isPublicationBoundToCurrentPolicies( - current.article, - governance.context.collection, - governance.context.validationPolicy, - )) - ) - throw unavailable(); - const proof: Article = { - id: current.article.id, - state: "in-review", - current: revision, - evidence, - review: publication.approval.binding, - }; - const approvedAt = publication.approval.reviewedAt; - if ( - typeof approvedAt !== "string" || - !Number.isFinite(Date.parse(approvedAt)) || - new Date(approvedAt).toISOString() !== approvedAt || - Date.parse(approvedAt) > Date.parse(at) || - Date.parse(approvedAt) < Date.parse(revision.createdAt) - ) - throw unavailable(); - // Evidence maxAge applies at approval; live revocation and authority still gate every read. - await publishArticle(proof, { - expectedRevision: revision.number, - binding: publication.approval.binding, - reviewerId: publication.approval.reviewerId, - context: { ...governance.context, at: approvedAt }, - }); - const [latestArticle, latestCollection, latestValidation] = - await Promise.all([ - repository.readArticleVersioned(input.articleId), - repository.readCollectionVersioned( - publication.revision.collectionId, - ), - repository.readValidationPolicyVersioned( - governance.context.validationPolicy.id, - ), - ]); - if ( - !hasPermission(access, knowledgePermissions.articleRead) || - latestArticle === null || - latestArticle.value.generation !== current.generation || - latestCollection === null || - latestCollection.value.generation !== - governance.governanceGeneration || - latestValidation === null || - latestValidation.value.generation !== governance.validationGeneration - ) - throw unavailable(); - if ( - portal.audience.kind === "permission" && - !hasPermission(access, portal.audience.permission) - ) - throw unavailable(); - return snapshotData({ - articleId: current.article.id, - collectionId: revision.collectionId, - revision: revision.number, - kind: revision.kind, - title: revision.title, - summary: revision.summary, - content: revision.content, - tags: revision.tags, - applicability: revision.applicability, - contentHash: revision.contentHash, - }); - } catch (error) { - if ( - error instanceof KnowledgeBaseError || - error instanceof KnowledgeBaseNotFoundError || - error instanceof KnowledgeBasePrerequisiteError || - error instanceof RepositoryCapacityError || - error instanceof RepositoryConflictError || - error instanceof RepositoryIntegrityError - ) - throw unavailable(); - throw error; - } + const checked = await publications.check({ + access, + articleId: input.articleId, + purpose: "portal", + }); + return checked.article; }, }; } diff --git a/packages/application/src/repository.ts b/packages/application/src/repository.ts index 6528a30..0b8aeb3 100644 --- a/packages/application/src/repository.ts +++ b/packages/application/src/repository.ts @@ -11,6 +11,7 @@ import type { ArticleRevision, ArticleApproval, Article, + PublishedArticle, Collection, ValidationPolicy, } from "@pegma/knowledge-base-contracts"; @@ -94,11 +95,29 @@ export interface RepositoryResult { readonly value: T; readonly replayed: boolean; } +/** Publication-only hydration; unrelated current draft/proofs remain private. */ +export interface ArticlePublicationState { + readonly articleId: string; + readonly generation: number; + readonly state: Article["state"]; + readonly publicationHeld: boolean; + readonly published?: PublishedArticle; + readonly publishedProvenance?: SourceSnapshot; + readonly publicationReview?: ReviewSnapshot; +} export interface KnowledgeRepository { readonly limits: KnowledgeRepositoryLimits; readArticleVersioned( id: string, ): Promise | null>; + readArticlePublicationVersioned( + id: string, + ): Promise | null>; + /** One keyed head read; never hydrates draft, evidence, or private source rows. */ + readResourceGeneration( + kind: ResourceKind, + id: string, + ): Promise; readCollectionVersioned( id: string, ): Promise | null>; @@ -608,6 +627,59 @@ export function createKnowledgeRepository( version: row.version, }; } + async function readPublication( + id: string, + ): Promise | null> { + const row = await getHead("article", id); + if (row === null) return null; + const pointer = (row.value.data as Head).pointer as ArticlePointer; + const value: ArticlePublicationState = { + articleId: id, + generation: pointer.generation, + state: pointer.state, + publicationHeld: pointer.publicationHeld, + }; + if (pointer.published === undefined) return { value, version: row.version }; + const [revision, approval, publishedProvenance, publicationReview] = + await Promise.all([ + getRevision(id, pointer.published.revision), + required( + "article", + id, + pointer.published.approval, + "publication", + ), + required( + "article", + id, + "provenance:" + pointer.publishedProvenance, + "provenance", + ), + required( + "article", + id, + pointer.publicationReview!, + "review", + ), + ]); + if ( + revision === null || + approval.binding.articleId !== id || + approval.binding.articleRevision !== revision.number || + approval.binding.contentHash !== revision.contentHash + ) { + throw new RepositoryIntegrityError(); + } + return { + value: { + ...value, + published: { revision, approval }, + publishedProvenance, + publicationReview, + }, + version: row.version, + }; + } async function execute( kind: ResourceKind, input: MutationInput, @@ -1081,6 +1153,11 @@ export function createKnowledgeRepository( return { limits, readArticleVersioned: (id) => read("article", id), + readArticlePublicationVersioned: readPublication, + readResourceGeneration: async (kind, id) => { + const row = await getHead(kind, id); + return row === null ? null : (row.value.data as Head).pointer.generation; + }, readCollectionVersioned: (id) => read("collection", id), readValidationPolicyVersioned: (id) => read("validation", id), diff --git a/packages/application/src/retrieval-budget.ts b/packages/application/src/retrieval-budget.ts new file mode 100644 index 0000000..1b10f7d --- /dev/null +++ b/packages/application/src/retrieval-budget.ts @@ -0,0 +1,158 @@ +import type { + CollectionDefinition, + EntityKey, + Store, +} from "@pegma/storage-core"; + +/** Internal diagnostic/control flow; public retrieval stays content-free. */ +export class RetrievalBudgetError extends Error { + constructor(readonly reason: "work" | "operation" = "work") { + super( + reason === "operation" + ? "Knowledge retrieval cannot enumerate or mutate its request Store" + : "Knowledge retrieval exhausted its bounded work allowance", + ); + this.name = "RetrievalBudgetError"; + } +} + +export interface RequestReadLimits { + readonly maxPhysicalReads: number; + readonly maxIndexReads: number; + readonly maxPostingEntries: number; + readonly maxCandidateHeads: number; + readonly maxConfirmations: number; + readonly indexCollectionName: string; +} + +export interface ExternalRetrievalWork { + readonly keyedReads: number; + readonly physicalRows: number; + readonly postingEntries: number; + readonly pagesRead?: number; +} + +export interface RetrievalReadBudget { + readonly store: Store; + remainingCandidateWork(): Required; + indexEntries(count: number): void; + candidateHead(): void; + confirmation(): void; + accountExternal(work: ExternalRetrievalWork): void; +} + +/** + * A fresh wrapper belongs to exactly one request. Each scoped Store keyed read + * reserves its allowance before awaiting the backing Store, including misses. + * External candidate calls are sequential: check allowance before dispatch, + * then charge their reported work with accountExternal after return. The + * wrapper never owns or caches persistence. + */ +export function createRetrievalReadBudget( + backing: Store, + limits: RequestReadLimits, +): RetrievalReadBudget { + const captured = Object.freeze({ ...limits }); + for (const bound of [ + captured.maxPhysicalReads, + captured.maxIndexReads, + captured.maxPostingEntries, + captured.maxCandidateHeads, + captured.maxConfirmations, + ]) { + if (!Number.isSafeInteger(bound) || bound < 1) + throw new TypeError("Retrieval read bounds must be positive integers"); + } + let physicalReads = 0; + let indexReads = 0; + let entries = 0; + let candidateHeads = 0; + let confirmations = 0; + const count = (value: number) => { + if (!Number.isSafeInteger(value) || value < 0) + throw new RetrievalBudgetError(); + return value; + }; + const reserve = (collection: string) => { + if ( + physicalReads >= captured.maxPhysicalReads || + (collection === captured.indexCollectionName && + indexReads >= captured.maxIndexReads) + ) + throw new RetrievalBudgetError(); + physicalReads += 1; + if (collection === captured.indexCollectionName) indexReads += 1; + }; + const store: Store = Object.freeze({ + collection(definition: CollectionDefinition) { + const target = backing.collection(definition); + return new Proxy(target, { + get(object, property) { + if (property === "get") + return async (key: EntityKey) => { + reserve(definition.name); + return object.get(key); + }; + if (property === "getVersioned") + return async (key: EntityKey) => { + reserve(definition.name); + return object.getVersioned(key); + }; + // Retrieval must neither scan a corpus nor mutate its authority/hints. + throw new RetrievalBudgetError("operation"); + }, + }); + }, + }); + return Object.freeze({ + store, + remainingCandidateWork() { + const reads = Math.max( + 0, + Math.min( + captured.maxPhysicalReads - physicalReads, + captured.maxIndexReads - indexReads, + ), + ); + return Object.freeze({ + keyedReads: reads, + physicalRows: reads, + pagesRead: reads, + postingEntries: Math.max(0, captured.maxPostingEntries - entries), + }); + }, + indexEntries(value: number) { + entries += count(value); + if (entries > captured.maxPostingEntries) + throw new RetrievalBudgetError(); + }, + candidateHead() { + candidateHeads += 1; + if (candidateHeads > captured.maxCandidateHeads) + throw new RetrievalBudgetError(); + }, + confirmation() { + confirmations += 1; + if (confirmations > captured.maxConfirmations) + throw new RetrievalBudgetError(); + }, + accountExternal(work: ExternalRetrievalWork) { + // Adapter accounting is host-supplied. Validate it and count work before + // consuming any hint; declared work cannot grant more authority or budget. + const reads = Math.max( + count(work.keyedReads), + count(work.physicalRows), + count(work.pagesRead ?? 0), + ); + physicalReads += reads; + indexReads += reads; + entries += count(work.postingEntries); + if ( + physicalReads > captured.maxPhysicalReads || + indexReads > captured.maxIndexReads || + entries > captured.maxPostingEntries + ) + throw new RetrievalBudgetError(); + }, + }); +} diff --git a/packages/application/src/retrieval-limits.ts b/packages/application/src/retrieval-limits.ts new file mode 100644 index 0000000..98b1e48 --- /dev/null +++ b/packages/application/src/retrieval-limits.ts @@ -0,0 +1,32 @@ +import { + defaultKnowledgeRetrievalLimits, + type KnowledgeRetrievalLimits, +} from "./retrieval-types.js"; + +/** Instance admission settings can reduce the initial fixed component ceilings. */ +export function resolveRetrievalLimits( + overrides: Partial = {}, +): KnowledgeRetrievalLimits { + if ( + overrides === null || + typeof overrides !== "object" || + Array.isArray(overrides) + ) + throw new TypeError("Retrieval limits must be an object"); + const names = Object.keys(defaultKnowledgeRetrievalLimits); + if (Object.keys(overrides).some((name) => !names.includes(name))) + throw new TypeError("Unknown knowledge retrieval limit"); + const resolved = { ...defaultKnowledgeRetrievalLimits, ...overrides }; + for (const name of names as (keyof KnowledgeRetrievalLimits)[]) { + const value = resolved[name]; + if ( + !Number.isSafeInteger(value) || + value < 1 || + value > defaultKnowledgeRetrievalLimits[name] + ) + throw new TypeError( + "Knowledge retrieval limits must be positive integers within their ceilings", + ); + } + return Object.freeze(resolved); +} diff --git a/packages/application/src/retrieval-maintenance.ts b/packages/application/src/retrieval-maintenance.ts new file mode 100644 index 0000000..1d7a1d5 --- /dev/null +++ b/packages/application/src/retrieval-maintenance.ts @@ -0,0 +1,566 @@ +import type { AccessContext } from "@pegma/authorization-core"; +import { knowledgePermissions } from "@pegma/knowledge-base-contracts"; +import type { Store } from "@pegma/storage-core"; + +import { KnowledgeBaseNotFoundError, requirePermission } from "./errors.js"; +import { indexArticleTerms } from "./lexical.js"; +import type { + CheckedPublication, + createPublicationChecker, +} from "./publication.js"; +import { knowledgeRecords } from "./records.js"; +import type { KnowledgeRepository } from "./repository.js"; +import type { + RetrievalBlockedReason, + RetrievalProjectionState, + RetrievalProjectionTarget, +} from "./retrieval-records.js"; +import type { createRetrievalRepository } from "./retrieval-repository.js"; +import type { + ArticleIndexInput, + ArticleIndexStatusDto, + KnowledgeRetrievalApplication, + KnowledgeRetrievalLimits, + RepairRetrievalPageInput, +} from "./retrieval-types.js"; +import { + canonicalJson, + fingerprint, + RepositoryCapacityError, + RepositoryConflictError, + RepositoryIntegrityError, + requireGeneration, + requireIdentifier, + snapshotData, +} from "./storage-helpers.js"; + +type PublicationChecker = ReturnType; +type RetrievalRepository = ReturnType; +type MaintenanceMethods = Pick< + KnowledgeRetrievalApplication, + "repairArticleIndex" | "repairRetrievalPage" | "getArticleIndexStatus" +>; + +interface MaintenanceOptions { + readonly store: Store; + readonly retrievalLimits: KnowledgeRetrievalLimits; +} + +interface BatchBudget { + remaining: number; +} + +interface DesiredProjection { + readonly articleGeneration: number | null; + readonly checked?: CheckedPublication; + readonly targets: readonly RetrievalProjectionTarget[]; + /** An oversized publication is withdrawn, then visibly held for admission. */ + readonly capacity: boolean; +} + +function objectInput(value: T, fields: readonly string[]): T { + const input = snapshotData(value); + if ( + input === null || + typeof input !== "object" || + Array.isArray(input) || + Object.keys(input).some((field) => !fields.includes(field)) + ) + throw new TypeError("Maintenance input contains unsupported fields"); + return input; +} + +function articleInput(value: ArticleIndexInput): ArticleIndexInput { + const input = objectInput(value, ["articleId"]); + requireIdentifier(input.articleId, "articleId"); + return input; +} + +/** + * Orchestrates the one derived repository. It neither owns another index nor + * mutates authoritative records/jobs. Hosts persist the returned scan cursor. + */ +export function createRetrievalMaintenanceServices( + repository: KnowledgeRepository, + retrieval: RetrievalRepository, + checker: PublicationChecker, + options: MaintenanceOptions, +): MaintenanceMethods { + const limits = snapshotData(options.retrievalLimits); + for (const [bound, ceiling] of [ + [limits.maxMaintenanceBatches, 32], + [limits.maxRepairScanRows, 100], + [limits.maxTermsPerArticle, 256], + ] as const) { + if (!Number.isSafeInteger(bound) || bound < 1 || bound > ceiling) + throw new TypeError("Maintenance bounds exceed their supported ceiling"); + } + const records = options.store.collection(knowledgeRecords); + + function caller(access: AccessContext): AccessContext { + const current = snapshotData(access); + requirePermission(current, knowledgePermissions.indexManage); + return current; + } + + async function desired( + access: AccessContext, + articleId: string, + ): Promise { + const before = await repository.readResourceGeneration( + "article", + articleId, + ); + let checked: CheckedPublication; + try { + checked = await checker.check({ articleId, purpose: "index", access }); + } catch (error) { + if (!(error instanceof KnowledgeBaseNotFoundError)) throw error; + // An old negative observation cannot withdraw a newly published revision. + const after = await repository.readResourceGeneration( + "article", + articleId, + ); + if (after !== before) throw new RepositoryConflictError(); + return { articleGeneration: after, targets: [], capacity: false }; + } + let terms: readonly string[]; + try { + terms = indexArticleTerms(checked.article, limits.maxTermsPerArticle); + } catch (error) { + if ( + !(error instanceof TypeError) && + !(error instanceof RepositoryCapacityError) + ) + throw error; + return { + articleGeneration: checked.binding.articleGeneration, + checked, + targets: [], + capacity: true, + }; + } + if (terms.length > limits.maxTermsPerArticle) + return { + articleGeneration: checked.binding.articleGeneration, + checked, + targets: [], + capacity: true, + }; + const bindingHash = await fingerprint(checked.binding); + return { + articleGeneration: checked.binding.articleGeneration, + checked, + capacity: false, + targets: checked.enabledUses.map((use) => { + const scope = { + collectionId: checked.binding.collectionId, + policyVersion: checked.binding.collectionPolicyVersion, + use, + }; + return { + scope, + hint: { + ...scope, + articleId, + articleRevision: checked.binding.revision, + contentHash: checked.binding.contentHash, + generation: checked.binding.articleGeneration, + sourceGeneration: checked.binding.sourceGeneration, + bindingHash, + }, + terms, + }; + }), + }; + } + + async function recheckDesired( + articleId: string, + plan: DesiredProjection, + ): Promise { + if (plan.checked !== undefined) { + // Preserve the original object: the checker owns its private confirmation. + await checker.recheck(plan.checked); + } else if ( + (await repository.readResourceGeneration("article", articleId)) !== + plan.articleGeneration + ) + throw new RepositoryConflictError(); + } + + function status( + articleId: string, + articleGeneration: number | null, + state: RetrievalProjectionState | null, + value: ArticleIndexStatusDto["status"], + indexed = false, + reason?: RetrievalBlockedReason, + ): ArticleIndexStatusDto { + return { + articleId, + status: value, + indexed, + articleGeneration, + projectionGeneration: state?.generation ?? null, + ...(reason === undefined ? {} : { reason }), + }; + } + + function sameTargets( + state: RetrievalProjectionState, + plan: DesiredProjection, + ): boolean { + const targetKey = (value: { + readonly scope: RetrievalProjectionTarget["scope"]; + readonly hint: RetrievalProjectionTarget["hint"]; + }) => canonicalJson({ scope: value.scope, hint: value.hint }); + return ( + state.targets.length === plan.targets.length && + canonicalJson(state.targets.map(targetKey).sort()) === + canonicalJson(plan.targets.map(targetKey).sort()) + ); + } + + async function currentStatus( + access: AccessContext, + articleId: string, + ): Promise { + const state = await retrieval.readArticleProjection(articleId); + let plan: DesiredProjection; + try { + plan = await desired(access, articleId); + await recheckDesired(articleId, plan); + } catch (error) { + if (error instanceof RepositoryCapacityError) + return status(articleId, null, state, "blocked", false, "capacity"); + if ( + !(error instanceof RepositoryConflictError) && + !(error instanceof KnowledgeBaseNotFoundError) + ) + throw error; + const generation = await repository.readResourceGeneration( + "article", + articleId, + ); + return status(articleId, generation, state, "pending", false, "conflict"); + } + if (plan.capacity) + return status( + articleId, + plan.articleGeneration, + state, + "blocked", + false, + "capacity", + ); + if (state === null) + return status( + articleId, + plan.articleGeneration, + null, + plan.articleGeneration === null ? "ready" : "pending", + ); + const sourceGeneration = plan.articleGeneration ?? state.sourceGeneration; + if (state.sourceGeneration !== sourceGeneration) + return status( + articleId, + plan.articleGeneration, + state, + "pending", + false, + "conflict", + ); + // Initial admission failures intentionally retain only a minimal marker. + // It remains useful only while a positive plan still needs admission; + // withdrawn or otherwise changed plans need cleanup instead of an old hold. + const same = sameTargets(state, plan); + const positiveAdmissionMarker = + state.status === "blocked" && + state.reason === "capacity" && + state.targets.length === 0 && + state.knownScopes.length === 0 && + state.pendingScopes.length === 0 && + plan.targets.length > 0; + if ( + (!same && !positiveAdmissionMarker) || + (state.status === "blocked" && plan.targets.length === 0) + ) + return status( + articleId, + plan.articleGeneration, + state, + "pending", + false, + plan.targets.length === 0 ? "source-unavailable" : "conflict", + ); + if (state.status === "blocked") + return status( + articleId, + plan.articleGeneration, + state, + "blocked", + false, + state.reason, + ); + return status( + articleId, + plan.articleGeneration, + state, + state.status, + state.status === "ready" && plan.targets.length > 0, + ); + } + + async function markBlocked( + articleId: string, + state: RetrievalProjectionState | null, + reason: RetrievalBlockedReason, + sourceGeneration?: number, + ): Promise { + if (state === null && sourceGeneration === undefined) return null; + try { + return await retrieval.markArticleProjectionBlocked( + articleId, + state?.generation ?? 1, + reason, + state === null ? sourceGeneration : undefined, + ); + } catch (error) { + if (!(error instanceof RepositoryConflictError)) throw error; + // A stale worker must not attach its failure to a newer plan. + return retrieval.readArticleProjection(articleId); + } + } + + async function repair( + access: AccessContext, + articleId: string, + budget: BatchBudget, + ): Promise { + for ( + let attempt = 0; + attempt < repository.limits.maxConflictAttempts; + attempt += 1 + ) { + if (budget.remaining === 0) return currentStatus(access, articleId); + let state = await retrieval.readArticleProjection(articleId); + let plan: DesiredProjection | undefined; + try { + plan = await desired(access, articleId); + if (plan.articleGeneration === null && state === null) + return status(articleId, null, null, "ready"); + await recheckDesired(articleId, plan); + const generation = (state?.generation ?? 0) + 1; + requireGeneration(generation, 1); + state = await retrieval.beginArticleProjection({ + articleId, + generation, + sourceGeneration: plan.articleGeneration ?? state!.sourceGeneration, + targets: plan.targets, + }); + await recheckDesired(articleId, plan); + while (state.status === "pending" && budget.remaining > 0) { + await recheckDesired(articleId, plan); + budget.remaining -= 1; + const advanced = await retrieval.advanceArticleProjection( + articleId, + state.generation, + ); + state = advanced.state; + await recheckDesired(articleId, plan); + if (advanced.complete) break; + } + if (plan.capacity) { + state = await markBlocked(articleId, state, "capacity"); + return status( + articleId, + plan.articleGeneration, + state, + "blocked", + false, + "capacity", + ); + } + return status( + articleId, + plan.articleGeneration, + state, + state.status, + state.status === "ready" && plan.targets.length > 0, + state.status === "blocked" ? state.reason : undefined, + ); + } catch (error) { + if (error instanceof RepositoryCapacityError) { + state = await markBlocked( + articleId, + state, + "capacity", + plan?.articleGeneration ?? undefined, + ); + return status( + articleId, + plan?.articleGeneration ?? null, + state, + "blocked", + false, + "capacity", + ); + } + if (error instanceof RepositoryConflictError) { + // Contention is not a durable hold. A same-plan winner may still be + // advancing this exact generation; blocking it would stall recovery. + continue; + } + if (error instanceof KnowledgeBaseNotFoundError) { + await markBlocked(articleId, state, "source-unavailable"); + continue; + } + throw error; + } + } + return currentStatus(access, articleId); + } + + async function repairCollectionDirectory( + collectionId: string, + ): Promise { + for ( + let attempt = 0; + attempt < repository.limits.maxConflictAttempts; + attempt += 1 + ) { + try { + const current = await repository.readCollectionVersioned(collectionId); + if (current === null) return "ready"; + // Only the opaque ID is derived. Request readers re-authorize policy. + await retrieval.registerCollection(collectionId); + const latest = await repository.readResourceGeneration( + "collection", + collectionId, + ); + if (latest === current.value.generation) return "ready"; + } catch (error) { + if (error instanceof RepositoryCapacityError) return "blocked"; + if (!(error instanceof RepositoryConflictError)) throw error; + } + } + return "pending"; + } + + return { + async repairArticleIndex(access, request) { + access = caller(access); + const input = articleInput(request); + const result = await repair(access, input.articleId, { + remaining: limits.maxMaintenanceBatches, + }); + requirePermission(access, knowledgePermissions.indexManage); + return result; + }, + + async getArticleIndexStatus(access, request) { + access = caller(access); + const input = articleInput(request); + const result = await currentStatus(access, input.articleId); + requirePermission(access, knowledgePermissions.indexManage); + return result; + }, + + async repairRetrievalPage(access, request) { + access = caller(access); + const input: RepairRetrievalPageInput = objectInput(request, [ + "cursor", + "limit", + ]); + const requestedLimit = input.limit ?? limits.maxRepairScanRows; + if ( + !Number.isSafeInteger(requestedLimit) || + requestedLimit < 1 || + requestedLimit > limits.maxRepairScanRows + ) + throw new TypeError("Repair page size exceeds the physical scan bound"); + // Each candidate receives one advancement, even when early articles block. + // The requested page size is an upper bound, not an obligation to scan it. + const limit = Math.min(requestedLimit, limits.maxMaintenanceBatches); + if ( + input.cursor !== undefined && + (typeof input.cursor !== "string" || + input.cursor.length === 0 || + input.cursor.length > 16_384) + ) + throw new TypeError("Expected a bounded opaque repair continuation"); + const page = await records.scan({ + limit, + ...(input.cursor === undefined ? {} : { cursor: input.cursor }), + }); + if (!Array.isArray(page.records) || page.records.length > limit) + throw new RepositoryIntegrityError(); + if (page.nextCursor !== null && typeof page.nextCursor !== "string") + throw new RepositoryIntegrityError(); + const candidates = new Map< + string, + { readonly kind: "article" | "collection"; readonly id: string } + >(); + for (const row of page.records) { + if ( + row.key.partition !== row.value.partition || + row.key.id !== row.value.id + ) + throw new RepositoryIntegrityError(); + const value = row.value; + if ( + value.resourceKind !== "article" && + value.resourceKind !== "collection" + ) + continue; + if (value.kind !== "head" && value.kind !== "job") continue; + if ( + value.partition !== + value.resourceKind + + ":" + + (await fingerprint([value.resourceKind, value.resourceId])) || + (value.kind === "head" && value.id !== "head") || + (value.kind === "job" && !value.id.startsWith("job:")) + ) + throw new RepositoryIntegrityError(); + // Jobs are hints only. Never index their old payload or generation. + if (value.kind === "job") { + const data = value.data as { readonly task?: unknown }; + if ( + data.task !== + (value.resourceKind === "article" + ? "article_changed" + : "collection_changed") + ) + continue; + } + candidates.set(canonicalJson([value.resourceKind, value.resourceId]), { + kind: value.resourceKind, + id: value.resourceId, + }); + } + let repaired = 0; + let pending = 0; + let blocked = 0; + for (const candidate of candidates.values()) { + const state = + candidate.kind === "article" + ? (await repair(access, candidate.id, { remaining: 1 })).status + : await repairCollectionDirectory(candidate.id); + if (state === "ready") repaired += 1; + else if (state === "blocked") blocked += 1; + else pending += 1; + } + requirePermission(access, knowledgePermissions.indexManage); + return { + physicalRows: page.records.length, + candidates: candidates.size, + repaired, + pending, + blocked, + nextCursor: page.nextCursor, + }; + }, + }; +} diff --git a/packages/application/src/retrieval-records.ts b/packages/application/src/retrieval-records.ts new file mode 100644 index 0000000..b5ad606 --- /dev/null +++ b/packages/application/src/retrieval-records.ts @@ -0,0 +1,227 @@ +import { defineCollection, type StoredRecord } from "@pegma/storage-core"; +import { + canonicalJson, + RepositoryCapacityError, + RepositoryIntegrityError, + requireGeneration, + requireIdentifier, +} from "./storage-helpers.js"; + +export interface RetrievalScope { + readonly collectionId: string; + readonly policyVersion: number; + readonly use: "portal" | "bot"; +} + +/** Derived identity only. A hint never grants authority to content. */ +export interface RetrievalHint extends RetrievalScope { + readonly articleId: string; + readonly articleRevision: number; + readonly contentHash: string; + readonly generation: number; + readonly sourceGeneration: number; + readonly bindingHash: string; +} + +export interface RetrievalPostingPage { + readonly entries: readonly RetrievalHint[]; +} + +export interface RetrievalProjectionTarget { + readonly scope: RetrievalScope; + readonly hint: RetrievalHint; + readonly terms: readonly string[]; +} + +export interface RetrievalStoredTarget { + readonly scope: RetrievalScope; + readonly hint: RetrievalHint; + readonly termHashes: readonly string[]; +} + +export type RetrievalBlockedReason = + "capacity" | "source-unavailable" | "conflict"; + +export interface RetrievalProjectionState { + readonly articleId: string; + /** Monotonic projection-plan fence, independent of article generation. */ + readonly generation: number; + /** Authoritative article generation used to derive this plan. */ + readonly sourceGeneration: number; + readonly status: "pending" | "ready" | "blocked"; + readonly reason?: RetrievalBlockedReason; + readonly targets: readonly RetrievalStoredTarget[]; + readonly pendingScopes: readonly RetrievalScope[]; + readonly knownScopes: readonly RetrievalScope[]; +} + +export type RetrievalRecordKind = + | "directory" + | "catalog" + | "article" + | "scope" + | "manifest" + | "posting" + | "page"; + +export interface RetrievalRecord { + readonly schemaVersion: 1; + readonly partition: string; + readonly id: string; + readonly kind: RetrievalRecordKind; + readonly data: unknown; +} + +const kinds: readonly string[] = [ + "directory", + "catalog", + "article", + "scope", + "manifest", + "posting", + "page", +]; +const maximumNativeBytes = 900_000; +const chunkCharacters = 30_000; +const maximumChunks = 15; + +export function requireRetrievalScope(scope: RetrievalScope): void { + requireIdentifier(scope.collectionId, "collectionId"); + requireGeneration(scope.policyVersion, 1); + if (scope.use !== "portal" && scope.use !== "bot") + throw new TypeError("Expected a retrieval use"); + if ( + Object.keys(scope).some( + (key) => !["collectionId", "policyVersion", "use"].includes(key), + ) + ) + throw new TypeError("Unexpected retrieval scope field"); +} + +export function requireRetrievalHint(hint: RetrievalHint): void { + requireRetrievalScope({ + collectionId: hint.collectionId, + policyVersion: hint.policyVersion, + use: hint.use, + }); + requireIdentifier(hint.articleId, "articleId"); + requireGeneration(hint.articleRevision, 1); + requireGeneration(hint.generation, 1); + requireGeneration(hint.sourceGeneration); + if ( + !/^[a-f0-9]{64}$/u.test(hint.contentHash) || + !/^[a-f0-9]{64}$/u.test(hint.bindingHash) + ) + throw new TypeError("Expected a retrieval digest"); + const allowed = [ + "collectionId", + "policyVersion", + "use", + "articleId", + "articleRevision", + "contentHash", + "generation", + "sourceGeneration", + "bindingHash", + ]; + if ( + Object.keys(hint).length !== allowed.length || + Object.keys(hint).some((key) => !allowed.includes(key)) + ) + throw new TypeError("Unexpected retrieval hint field"); +} + +function validateRecord(record: RetrievalRecord): void { + if ( + record.schemaVersion !== 1 || + !kinds.includes(record.kind) || + typeof record.partition !== "string" || + !/^(directory|catalog:[a-f0-9]{64}|article:[a-f0-9]{64}|scope:[a-f0-9]{64})$/u.test( + record.partition, + ) || + typeof record.id !== "string" || + record.id.length === 0 || + record.id.length > 200 || + /[^A-Za-z0-9:._-]/u.test(record.id) || + record.data === null || + typeof record.data !== "object" || + Array.isArray(record.data) + ) + throw new RepositoryIntegrityError(); +} + +export function encodeRetrievalRecord(record: RetrievalRecord): StoredRecord { + validateRecord(record); + const payload = canonicalJson(record.data); + if (payload.length * 2 > maximumNativeBytes - 4_096) + throw new RepositoryCapacityError("index_record_bytes"); + const parts: string[] = []; + for (let offset = 0; offset < payload.length;) { + let end = Math.min(payload.length, offset + chunkCharacters); + const last = payload.charCodeAt(end - 1); + if (end < payload.length && last >= 0xd800 && last <= 0xdbff) end -= 1; + parts.push(payload.slice(offset, end)); + offset = end; + } + if (parts.length === 0 || parts.length > maximumChunks) + throw new RepositoryCapacityError("index_record_chunks"); + const encoded: Record = { + schemaVersion: 1, + recordPartition: record.partition, + recordId: record.id, + kind: record.kind, + partCount: parts.length, + }; + for (const [index, part] of parts.entries()) encoded["part" + index] = part; + return encoded; +} + +export function decodeRetrievalRecord(record: StoredRecord): RetrievalRecord { + try { + if (record.schemaVersion !== 1 || typeof record.partCount !== "number") + throw new RepositoryIntegrityError(); + requireGeneration(record.partCount, 1); + if (record.partCount > maximumChunks) throw new RepositoryIntegrityError(); + const expected = new Set([ + "schemaVersion", + "recordPartition", + "recordId", + "kind", + "partCount", + ...Array.from({ length: record.partCount }, (_, index) => "part" + index), + ]); + if ( + Object.keys(record).length !== expected.size || + Object.keys(record).some((key) => !expected.has(key)) + ) + throw new RepositoryIntegrityError(); + const parts: string[] = []; + for (let index = 0; index < record.partCount; index += 1) { + const part = record["part" + index]; + if (typeof part !== "string" || part.length > chunkCharacters) + throw new RepositoryIntegrityError(); + parts.push(part); + } + const payload = parts.join(""); + if (payload.length * 2 > maximumNativeBytes - 4_096) + throw new RepositoryIntegrityError(); + const decoded: RetrievalRecord = { + schemaVersion: 1, + partition: record.recordPartition as string, + id: record.recordId as string, + kind: record.kind as RetrievalRecordKind, + data: JSON.parse(payload) as unknown, + }; + validateRecord(decoded); + canonicalJson(decoded.data); + return decoded; + } catch { + throw new RepositoryIntegrityError(); + } +} + +export const retrievalRecords = defineCollection({ + name: "knowledge-base.retrieval.v1", + key: (record) => ({ partition: record.partition, id: record.id }), + codec: { encode: encodeRetrievalRecord, decode: decodeRetrievalRecord }, +}); diff --git a/packages/application/src/retrieval-repository.ts b/packages/application/src/retrieval-repository.ts new file mode 100644 index 0000000..523520c --- /dev/null +++ b/packages/application/src/retrieval-repository.ts @@ -0,0 +1,1063 @@ +import type { + Store, + TransactionAction, + VersionedRecord, +} from "@pegma/storage-core"; +import { + encodeRetrievalRecord, + retrievalRecords, + requireRetrievalHint, + requireRetrievalScope, + type RetrievalBlockedReason, + type RetrievalHint, + type RetrievalPostingPage, + type RetrievalProjectionState, + type RetrievalProjectionTarget, + type RetrievalRecord, + type RetrievalRecordKind, + type RetrievalScope, + type RetrievalStoredTarget, +} from "./retrieval-records.js"; +import type { KnowledgeRetrievalLimits } from "./retrieval-types.js"; +import { resolveRetrievalLimits } from "./retrieval-limits.js"; +import { + canonicalJson, + encodedBytes, + fingerprint, + RepositoryCapacityError, + RepositoryConflictError, + RepositoryIntegrityError, + requireGeneration, + requireIdentifier, + snapshotData, +} from "./storage-helpers.js"; + +export interface BeginArticleProjectionInput { + readonly articleId: string; + readonly generation: number; + readonly sourceGeneration: number; + readonly targets: readonly RetrievalProjectionTarget[]; +} + +export interface RetrievalCatalog { + readonly articleIds: readonly string[]; + readonly scopes: readonly RetrievalScope[]; +} + +export interface RetrievalRepository { + registerCollection(collectionId: string): Promise; + readDirectory(): Promise; + readCatalog(collectionId: string): Promise; + /** Every returned page/entry must be charged before query filtering/deduplication. */ + readPostingPages( + scope: RetrievalScope, + term: string, + ): Promise; + readArticleProjection( + articleId: string, + ): Promise; + beginArticleProjection( + input: BeginArticleProjectionInput, + ): Promise; + advanceArticleProjection( + articleId: string, + expectedGeneration: number, + ): Promise<{ + readonly state: RetrievalProjectionState; + readonly complete: boolean; + readonly changed: boolean; + }>; + markArticleProjectionBlocked( + articleId: string, + generation: number, + reason: RetrievalBlockedReason, + sourceGeneration?: number, + ): Promise; +} + +interface CatalogEntry { + readonly articleId: string; + readonly generation: number; + readonly scopes: readonly RetrievalScope[]; +} +interface CatalogData { + readonly entries: readonly CatalogEntry[]; + /** Retained epoch identities/floors have an explicit finite lifetime cap. */ + readonly epochs: readonly RetrievalScope[]; +} +interface ScopeHead { + readonly generation: number; + readonly articleIds: readonly string[]; + readonly rows: number; + readonly bytes: number; +} +interface StoredPostingEntry { + readonly hint: RetrievalHint; + readonly projectionGeneration: number; +} +interface ManifestEntry extends StoredPostingEntry { + readonly termHash: string; +} +interface Manifest { + readonly articleId: string; + readonly generation: number; + readonly sourceGeneration: number; + readonly target: RetrievalStoredTarget | null; + readonly entries: readonly ManifestEntry[]; +} +interface PostingHead { + readonly termHash: string; + readonly pages: number; +} +interface PostingPage { + readonly termHash: string; + readonly page: number; + readonly entries: readonly StoredPostingEntry[]; +} + +const maximumEpochs = 32; +const maximumKnownScopes = 32; +const maximumAttempts = 3; +const maximumActions = 100; +const maximumTransactionBytes = 3 * 1024 * 1024; +/** Two complete posting rewrites fit even when both terms occupy sixteen pages. */ +const termsPerBatch = 2; +const hashPattern = /^[a-f0-9]{64}$/u; + +function exactObject( + value: unknown, + keys: readonly string[], +): Record { + if (value === null || typeof value !== "object" || Array.isArray(value)) + throw new RepositoryIntegrityError(); + const names = Object.keys(value); + if ( + names.length !== keys.length || + names.some((name) => !keys.includes(name)) + ) + throw new RepositoryIntegrityError(); + return value as Record; +} +function boundedArray( + value: unknown, + maximum: number, + validate: (item: T) => void, +): readonly T[] { + if (!Array.isArray(value) || value.length > maximum) + throw new RepositoryIntegrityError(); + for (const item of value) validate(item as T); + return value as readonly T[]; +} +function unique(values: readonly string[]): void { + if (new Set(values).size !== values.length) + throw new RepositoryIntegrityError(); +} +function digest(value: string): void { + if (typeof value !== "string" || !hashPattern.test(value)) + throw new RepositoryIntegrityError(); +} +function scopeIdentity(scope: RetrievalScope): string { + return canonicalJson(scope); +} +function compare(a: string, b: string): number { + return a < b ? -1 : a > b ? 1 : 0; +} +function sameScope(a: RetrievalScope, b: RetrievalScope): boolean { + return scopeIdentity(a) === scopeIdentity(b); +} +function scopesUnion( + scopes: readonly RetrievalScope[], +): readonly RetrievalScope[] { + const values = new Map(scopes.map((scope) => [scopeIdentity(scope), scope])); + return [...values.entries()] + .sort(([a], [b]) => compare(a, b)) + .map(([, scope]) => scope); +} +function requireScopes( + value: unknown, + maximum = maximumKnownScopes, +): readonly RetrievalScope[] { + const scopes = boundedArray( + value, + maximum, + requireRetrievalScope, + ); + unique(scopes.map(scopeIdentity)); + return scopes; +} +function requireTarget(target: RetrievalStoredTarget): void { + exactObject(target, ["scope", "hint", "termHashes"]); + requireRetrievalScope(target.scope); + requireRetrievalHint(target.hint); + if ( + !sameScope(target.scope, { + collectionId: target.hint.collectionId, + policyVersion: target.hint.policyVersion, + use: target.hint.use, + }) + ) + throw new RepositoryIntegrityError(); + const terms = boundedArray(target.termHashes, 256, digest); + unique(terms); +} +function requireState(state: RetrievalProjectionState): void { + const keys = [ + "articleId", + "generation", + "sourceGeneration", + "status", + "targets", + "pendingScopes", + "knownScopes", + ...(state.reason === undefined ? [] : ["reason"]), + ]; + exactObject(state, keys); + requireIdentifier(state.articleId); + requireGeneration(state.generation, 1); + requireGeneration(state.sourceGeneration, 1); + if (!["pending", "ready", "blocked"].includes(state.status)) + throw new RepositoryIntegrityError(); + if ( + state.reason !== undefined && + !["capacity", "source-unavailable", "conflict"].includes(state.reason) + ) + throw new RepositoryIntegrityError(); + const targets = boundedArray( + state.targets, + 2, + requireTarget, + ); + unique(targets.map((target) => scopeIdentity(target.scope))); + for (const target of targets) + if ( + target.hint.articleId !== state.articleId || + target.hint.generation !== state.sourceGeneration + ) + throw new RepositoryIntegrityError(); + const pending = requireScopes(state.pendingScopes); + const known = requireScopes(state.knownScopes); + if ( + pending.some((scope) => !known.some((item) => sameScope(scope, item))) || + targets.some( + (target) => !known.some((scope) => sameScope(scope, target.scope)), + ) + ) + throw new RepositoryIntegrityError(); + if (state.status === "ready" && pending.length !== 0) + throw new RepositoryIntegrityError(); +} +function requireCatalog(data: CatalogData, collectionId: string): void { + exactObject(data, ["entries", "epochs"]); + const entries = boundedArray(data.entries, 256, (entry) => { + exactObject(entry, ["articleId", "generation", "scopes"]); + requireIdentifier(entry.articleId); + requireGeneration(entry.generation, 1); + for (const scope of requireScopes(entry.scopes, 2)) + if (scope.collectionId !== collectionId) + throw new RepositoryIntegrityError(); + }); + unique(entries.map((entry) => entry.articleId)); + for (const scope of requireScopes(data.epochs, maximumEpochs)) + if (scope.collectionId !== collectionId) + throw new RepositoryIntegrityError(); + if ( + entries.some((entry) => + entry.scopes.some( + (scope) => !data.epochs.some((epoch) => sameScope(scope, epoch)), + ), + ) + ) + throw new RepositoryIntegrityError(); +} +function requireScopeHead(head: ScopeHead): void { + exactObject(head, ["generation", "articleIds", "rows", "bytes"]); + requireGeneration(head.generation, 1); + requireGeneration(head.rows, 1); + requireGeneration(head.bytes, 1); + const ids = boundedArray(head.articleIds, 256, requireIdentifier); + unique(ids); +} +function requireManifest( + manifest: Manifest, + articleId: string, + scope: RetrievalScope, +): void { + exactObject(manifest, [ + "articleId", + "generation", + "sourceGeneration", + "target", + "entries", + ]); + if (manifest.articleId !== articleId) throw new RepositoryIntegrityError(); + requireGeneration(manifest.generation, 1); + requireGeneration(manifest.sourceGeneration, 1); + if (manifest.target !== null) { + requireTarget(manifest.target); + if ( + !sameScope(manifest.target.scope, scope) || + manifest.target.hint.articleId !== articleId || + manifest.target.hint.generation !== manifest.sourceGeneration + ) + throw new RepositoryIntegrityError(); + } + const entries = boundedArray( + manifest.entries, + 256, + (entry) => { + exactObject(entry, ["termHash", "hint", "projectionGeneration"]); + digest(entry.termHash); + requireRetrievalHint(entry.hint); + requireGeneration(entry.projectionGeneration, 1); + if ( + entry.projectionGeneration > manifest.generation || + entry.hint.articleId !== articleId || + !sameScope(scope, { + collectionId: entry.hint.collectionId, + policyVersion: entry.hint.policyVersion, + use: entry.hint.use, + }) + ) + throw new RepositoryIntegrityError(); + }, + ); + unique(entries.map((entry) => entry.termHash)); +} + +export const retrievalTermHash = async (term: string): Promise => { + if ( + typeof term !== "string" || + term.length === 0 || + term.length > 256 || + !/^[\p{L}\p{N}]+$/u.test(term) + ) + throw new TypeError("Expected a bounded normalized lexical term"); + return fingerprint(term); +}; + +/** A repairable derived index; authoritative content always lives in KnowledgeRepository. */ +export function createRetrievalRepository( + store: Store, + overrides: Partial = {}, +): RetrievalRepository { + const limits = resolveRetrievalLimits(overrides); + const records = store.collection(retrievalRecords); + const row = ( + partition: string, + id: string, + kind: RetrievalRecordKind, + data: unknown, + ): RetrievalRecord => ({ schemaVersion: 1, partition, id, kind, data }); + const articlePartition = async (id: string): Promise => + "article:" + (await fingerprint(id)); + const catalogPartition = async (id: string): Promise => + "catalog:" + (await fingerprint(id)); + const scopePartition = async (scope: RetrievalScope): Promise => + "scope:" + (await fingerprint(scope)); + + async function get( + partition: string, + id: string, + kind: RetrievalRecordKind, + ): Promise | null> { + const result = await records.getVersioned({ partition, id }); + if ( + result !== null && + (result.value.partition !== partition || + result.value.id !== id || + result.value.kind !== kind) + ) + throw new RepositoryIntegrityError(); + return result; + } + async function transact( + partition: string, + actions: readonly TransactionAction[], + ): Promise { + if (actions.length > maximumActions) + throw new RepositoryCapacityError("index_transaction_actions"); + let bytes = 0; + for (const action of actions) + bytes += + action.action === "delete" + ? new TextEncoder().encode(canonicalJson(action.key)).length + 256 + : encodedBytes(encodeRetrievalRecord(action.value)) + 256; + if (bytes > maximumTransactionBytes) + throw new RepositoryCapacityError("index_transaction_bytes"); + return (await records.transact(partition, actions)).committed; + } + const write = ( + value: RetrievalRecord, + before: VersionedRecord | null, + ): TransactionAction => + before === null + ? { action: "insert", value } + : { action: "putIfUnchanged", value, version: before.version }; + + async function readState(articleId: string): Promise<{ + state: RetrievalProjectionState; + row: VersionedRecord; + } | null> { + requireIdentifier(articleId); + const before = await get( + await articlePartition(articleId), + "head", + "article", + ); + if (before === null) return null; + try { + const state = before.value.data as RetrievalProjectionState; + requireState(state); + if (state.articleId !== articleId) throw new RepositoryIntegrityError(); + return { state, row: before }; + } catch { + throw new RepositoryIntegrityError(); + } + } + async function directory(): Promise { + const result = await get("directory", "head", "directory"); + if (result === null) return []; + try { + const data = exactObject(result.value.data, ["collectionIds"]); + const ids = boundedArray( + data.collectionIds, + 64, + requireIdentifier, + ); + unique(ids); + if (ids.length > limits.maxDirectoryCollections) + throw new RepositoryCapacityError("index_directory"); + return ids; + } catch (error) { + if (error instanceof RepositoryCapacityError) throw error; + throw new RepositoryIntegrityError(); + } + } + async function registerDirectory(collectionId: string): Promise { + requireIdentifier(collectionId, "collectionId"); + for (let attempt = 0; attempt < maximumAttempts; attempt += 1) { + const before = await get("directory", "head", "directory"); + let ids: readonly string[] = []; + if (before !== null) { + const data = exactObject(before.value.data, ["collectionIds"]); + ids = boundedArray(data.collectionIds, 64, requireIdentifier); + unique(ids); + } + if (ids.length > limits.maxDirectoryCollections) + throw new RepositoryCapacityError("index_directory"); + if (ids.includes(collectionId)) return; + if (ids.length >= limits.maxDirectoryCollections) + throw new RepositoryCapacityError("index_directory"); + if ( + await transact("directory", [ + write( + row("directory", "head", "directory", { + collectionIds: [...ids, collectionId].sort(), + }), + before, + ), + ]) + ) + return; + } + throw new RepositoryConflictError(); + } + async function loadCatalog(collectionId: string): Promise<{ + data: CatalogData; + row: VersionedRecord | null; + partition: string; + }> { + requireIdentifier(collectionId); + const partition = await catalogPartition(collectionId); + const before = await get(partition, "head", "catalog"); + const data = (before?.value.data ?? { + entries: [], + epochs: [], + }) as CatalogData; + try { + requireCatalog(data, collectionId); + } catch { + throw new RepositoryIntegrityError(); + } + return { data, row: before, partition }; + } + async function registerCatalog( + state: RetrievalProjectionState, + collectionId: string, + ): Promise { + await registerDirectory(collectionId); + for (let attempt = 0; attempt < maximumAttempts; attempt += 1) { + const loaded = await loadCatalog(collectionId); + const existing = loaded.data.entries.find( + (entry) => entry.articleId === state.articleId, + ); + if (existing !== undefined && existing.generation > state.generation) + return; + const scopes = state.targets + .filter((target) => target.scope.collectionId === collectionId) + .map((target) => target.scope); + if (existing !== undefined && existing.generation === state.generation) { + if (canonicalJson(existing.scopes) !== canonicalJson(scopes)) + throw new RepositoryConflictError(); + return; + } + if ( + existing === undefined && + loaded.data.entries.length >= limits.maxCatalogArticles + ) + throw new RepositoryCapacityError("index_catalog"); + const epochs = scopesUnion([ + ...loaded.data.epochs, + ...state.knownScopes.filter( + (scope) => scope.collectionId === collectionId, + ), + ]); + if (epochs.length > maximumEpochs) + throw new RepositoryCapacityError("index_epochs"); + const entries = [ + ...loaded.data.entries.filter( + (entry) => entry.articleId !== state.articleId, + ), + { articleId: state.articleId, generation: state.generation, scopes }, + ].sort((a, b) => compare(a.articleId, b.articleId)); + const value = row(loaded.partition, "head", "catalog", { + entries, + epochs, + } satisfies CatalogData); + if (await transact(loaded.partition, [write(value, loaded.row)])) return; + } + throw new RepositoryConflictError(); + } + + async function loadPosting( + partition: string, + scope: RetrievalScope, + termHash: string, + ): Promise<{ + head: VersionedRecord | null; + pages: readonly VersionedRecord[]; + entries: readonly StoredPostingEntry[]; + }> { + const head = await get(partition, "posting:" + termHash, "posting"); + if (head === null) return { head, pages: [], entries: [] }; + const data = head.value.data as PostingHead; + try { + exactObject(data, ["termHash", "pages"]); + if (data.termHash !== termHash) throw new RepositoryIntegrityError(); + requireGeneration(data.pages, 1); + if (data.pages > limits.maxPostingPagesPerTerm) + throw new RepositoryCapacityError("index_posting_pages"); + } catch (error) { + if (error instanceof RepositoryCapacityError) throw error; + throw new RepositoryIntegrityError(); + } + const pages: VersionedRecord[] = []; + const entries: StoredPostingEntry[] = []; + for (let page = 0; page < data.pages; page += 1) { + const loaded = await get( + partition, + "page:" + termHash + ":" + page, + "page", + ); + if (loaded === null) throw new RepositoryConflictError(); + try { + const value = loaded.value.data as PostingPage; + exactObject(value, ["termHash", "page", "entries"]); + if (value.termHash !== termHash || value.page !== page) + throw new RepositoryIntegrityError(); + const members = boundedArray( + value.entries, + 16, + (entry) => { + exactObject(entry, ["hint", "projectionGeneration"]); + requireRetrievalHint(entry.hint); + requireGeneration(entry.projectionGeneration, 1); + if ( + !sameScope(scope, { + collectionId: entry.hint.collectionId, + policyVersion: entry.hint.policyVersion, + use: entry.hint.use, + }) + ) + throw new RepositoryIntegrityError(); + }, + ); + if (members.length > limits.postingPageEntries) + throw new RepositoryCapacityError("index_posting_entries"); + entries.push(...members); + } catch (error) { + if (error instanceof RepositoryCapacityError) throw error; + throw new RepositoryIntegrityError(); + } + pages.push(loaded); + } + return { head, pages, entries }; + } + + async function applyScopeBatch( + state: RetrievalProjectionState, + scope: RetrievalScope, + ): Promise { + const partition = await scopePartition(scope); + const manifestId = "manifest:" + (await fingerprint(state.articleId)); + const desired = + state.targets.find((target) => sameScope(target.scope, scope)) ?? null; + for (let attempt = 0; attempt < maximumAttempts; attempt += 1) { + const global = await readState(state.articleId); + if (global === null || global.state.generation !== state.generation) + throw new RepositoryConflictError(); + const headRow = await get(partition, "head", "scope"); + let head: ScopeHead | null = null; + if (headRow !== null) { + try { + head = headRow.value.data as ScopeHead; + requireScopeHead(head); + } catch { + throw new RepositoryIntegrityError(); + } + if ( + head.rows > limits.maxIndexPartitionRows || + head.bytes > limits.maxIndexPartitionBytes + ) + throw new RepositoryCapacityError("index_partition"); + } + const manifestRow = await get(partition, manifestId, "manifest"); + let previous: Manifest | null = null; + if (manifestRow !== null) { + try { + previous = manifestRow.value.data as Manifest; + requireManifest(previous, state.articleId, scope); + } catch { + throw new RepositoryIntegrityError(); + } + if (previous.generation > state.generation) return true; + if (previous.sourceGeneration > state.sourceGeneration) + throw new RepositoryConflictError(); + if ( + previous.generation === state.generation && + canonicalJson(previous.target) !== canonicalJson(desired) + ) + throw new RepositoryConflictError(); + } + if (head === null && manifestRow !== null) + throw new RepositoryConflictError(); + const articleIds = head?.articleIds ?? []; + if ( + !articleIds.includes(state.articleId) && + articleIds.length >= limits.maxCatalogArticles + ) + throw new RepositoryCapacityError("index_scope_articles"); + const actual = new Map( + (previous?.entries ?? []).map((entry) => [entry.termHash, entry]), + ); + const desiredTerms = new Set(desired?.termHashes ?? []); + const differs = (termHash: string): boolean => { + const entry = actual.get(termHash); + return desiredTerms.has(termHash) + ? entry === undefined || + entry.projectionGeneration !== state.generation || + canonicalJson(entry.hint) !== canonicalJson(desired!.hint) + : entry !== undefined; + }; + // Remove obsolete terms before adding new ones so the actual manifest never exceeds 256. + const work = [...actual.keys()] + .filter((term) => !desiredTerms.has(term)) + .sort() + .concat( + [...new Set([...actual.keys(), ...desiredTerms])] + .filter((term) => desiredTerms.has(term) && differs(term)) + .sort(), + ) + .slice(0, termsPerBatch); + if ( + previous !== null && + previous.generation === state.generation && + work.length === 0 + ) + return true; + const actions: TransactionAction[] = []; + const changes: { + before: RetrievalRecord | null; + after: RetrievalRecord | null; + }[] = []; + let planningConflict = false; + for (const termHash of work) { + const loaded = await loadPosting(partition, scope, termHash); + const old = actual.get(termHash); + const found = loaded.entries.filter( + (entry) => entry.hint.articleId === state.articleId, + ); + // Page reads are not a snapshot of a concurrent compaction. Retry the + // scope CAS plan rather than treating a mixed view as stored corruption. + if (found.length > 1) { + planningConflict = true; + break; + } + const current = found[0]; + if ( + current !== undefined && + current.projectionGeneration > state.generation + ) { + planningConflict = true; + break; + } + if ( + old !== undefined && + (current === undefined || + current.projectionGeneration !== old.projectionGeneration || + canonicalJson(current.hint) !== canonicalJson(old.hint)) + ) { + planningConflict = true; + break; + } + if (old === undefined && current !== undefined) { + planningConflict = true; + break; + } + const replacement: StoredPostingEntry | null = desiredTerms.has( + termHash, + ) + ? { hint: desired!.hint, projectionGeneration: state.generation } + : null; + const members = loaded.entries.filter( + (entry) => entry.hint.articleId !== state.articleId, + ); + if (replacement !== null) members.push(replacement); + members.sort((a, b) => compare(a.hint.articleId, b.hint.articleId)); + const count = Math.ceil(members.length / limits.postingPageEntries); + if (count > limits.maxPostingPagesPerTerm) + throw new RepositoryCapacityError("index_posting_pages"); + const nextHead = + count === 0 + ? null + : row(partition, "posting:" + termHash, "posting", { + termHash, + pages: count, + } satisfies PostingHead); + if (nextHead === null) { + if (loaded.head !== null) + actions.push({ + action: "delete", + key: { partition, id: loaded.head.value.id }, + }); + } else actions.push(write(nextHead, loaded.head)); + if (loaded.head !== null || nextHead !== null) + changes.push({ before: loaded.head?.value ?? null, after: nextHead }); + for ( + let page = 0; + page < Math.max(count, loaded.pages.length); + page += 1 + ) { + const prior = loaded.pages[page] ?? null; + const next = + page < count + ? row(partition, "page:" + termHash + ":" + page, "page", { + termHash, + page, + entries: members.slice( + page * limits.postingPageEntries, + (page + 1) * limits.postingPageEntries, + ), + } satisfies PostingPage) + : null; + if (next === null) { + if (prior !== null) + actions.push({ + action: "delete", + key: { partition, id: prior.value.id }, + }); + } else actions.push(write(next, prior)); + changes.push({ before: prior?.value ?? null, after: next }); + } + if (replacement === null) actual.delete(termHash); + else actual.set(termHash, { ...replacement, termHash }); + } + if (planningConflict) continue; + const manifest: Manifest = { + articleId: state.articleId, + generation: state.generation, + sourceGeneration: state.sourceGeneration, + target: desired, + entries: [...actual.values()].sort((a, b) => + compare(a.termHash, b.termHash), + ), + }; + if (manifest.entries.length > 256) + throw new RepositoryCapacityError("index_article_terms"); + const nextManifest = row(partition, manifestId, "manifest", manifest); + actions.push(write(nextManifest, manifestRow)); + changes.push({ before: manifestRow?.value ?? null, after: nextManifest }); + const nextRows = + (head?.rows ?? 0) + + (headRow === null ? 1 : 0) + + changes.reduce( + (sum, change) => + sum + + (change.after === null ? 0 : 1) - + (change.before === null ? 0 : 1), + 0, + ); + const baseBytes = + (head?.bytes ?? 0) - + (headRow === null + ? 0 + : encodedBytes(encodeRetrievalRecord(headRow.value))) + + changes.reduce( + (sum, change) => + sum + + (change.after === null + ? 0 + : encodedBytes(encodeRetrievalRecord(change.after))) - + (change.before === null + ? 0 + : encodedBytes(encodeRetrievalRecord(change.before))), + 0, + ); + let nextHead: ScopeHead = { + generation: (head?.generation ?? 0) + 1, + articleIds: [...new Set([...articleIds, state.articleId])].sort(), + rows: nextRows, + bytes: 0, + }; + requireGeneration(nextHead.generation, 1); + let nextHeadRow = row(partition, "head", "scope", nextHead); + for (let pass = 0; pass < 12; pass += 1) { + const bytes = + baseBytes + encodedBytes(encodeRetrievalRecord(nextHeadRow)); + if (bytes === nextHead.bytes) break; + nextHead = { ...nextHead, bytes }; + nextHeadRow = row(partition, "head", "scope", nextHead); + } + if (nextRows > limits.maxIndexPartitionRows) + throw new RepositoryCapacityError("index_partition_rows"); + if (nextHead.bytes > limits.maxIndexPartitionBytes) + throw new RepositoryCapacityError("index_partition_bytes"); + actions.unshift(write(nextHeadRow, headRow)); + // Every posting/manifest mutation changes this head. Its CAS also fences deletes. + if (!(await transact(partition, actions))) continue; + return [...new Set([...actual.keys(), ...desiredTerms])].every( + (term) => !differs(term), + ); + } + throw new RepositoryConflictError(); + } + + return { + registerCollection: registerDirectory, + readDirectory: directory, + async readCatalog(collectionId) { + const loaded = await loadCatalog(collectionId); + if (loaded.data.entries.length > limits.maxCatalogArticles) + throw new RepositoryCapacityError("index_catalog"); + const active = loaded.data.entries.filter( + (entry) => entry.scopes.length !== 0, + ); + return { + articleIds: active.map((entry) => entry.articleId), + scopes: scopesUnion(active.flatMap((entry) => entry.scopes)), + }; + }, + async readPostingPages(scope, term) { + requireRetrievalScope(scope); + const termHash = await retrievalTermHash(term); + const loaded = await loadPosting( + await scopePartition(scope), + scope, + termHash, + ); + return loaded.pages.map((page) => ({ + entries: (page.value.data as PostingPage).entries.map((entry) => + snapshotData(entry.hint), + ), + })); + }, + async readArticleProjection(articleId) { + return (await readState(articleId))?.state ?? null; + }, + async beginArticleProjection(input) { + const request = snapshotData(input); + if ( + Object.keys(request).some( + (key) => + ![ + "articleId", + "generation", + "sourceGeneration", + "targets", + ].includes(key), + ) + ) + throw new TypeError("Unexpected projection field"); + requireIdentifier(request.articleId); + requireGeneration(request.generation, 1); + requireGeneration(request.sourceGeneration, 1); + if (!Array.isArray(request.targets) || request.targets.length > 2) + throw new TypeError("Expected bounded projection targets"); + const targets: RetrievalStoredTarget[] = []; + for (const target of request.targets) { + exactObject(target, ["scope", "hint", "terms"]); + requireRetrievalScope(target.scope); + requireRetrievalHint(target.hint); + if ( + !Array.isArray(target.terms) || + target.terms.length > limits.maxTermsPerArticle + ) + throw new RepositoryCapacityError("index_article_terms"); + const termHashes = [ + ...new Set(await Promise.all(target.terms.map(retrievalTermHash))), + ].sort(); + const stored = { scope: target.scope, hint: target.hint, termHashes }; + requireTarget(stored); + if ( + target.hint.articleId !== request.articleId || + target.hint.generation !== request.sourceGeneration + ) + throw new TypeError("Projection hint does not match source"); + targets.push(stored); + } + targets.sort((a, b) => + compare(scopeIdentity(a.scope), scopeIdentity(b.scope)), + ); + unique(targets.map((target) => scopeIdentity(target.scope))); + for (let attempt = 0; attempt < maximumAttempts; attempt += 1) { + const before = await readState(request.articleId); + const current = before?.state; + if ( + current !== undefined && + request.sourceGeneration < current.sourceGeneration + ) + throw new RepositoryConflictError(); + const same = + current !== undefined && + current.sourceGeneration === request.sourceGeneration && + canonicalJson(current.targets) === canonicalJson(targets); + if (same && current.status !== "blocked") return current; + if (!same && request.generation !== (current?.generation ?? 0) + 1) + throw new RepositoryConflictError(); + const knownScopes = scopesUnion([ + ...(current?.knownScopes ?? []), + ...targets.map((target) => target.scope), + ]); + if (knownScopes.length > maximumKnownScopes) + throw new RepositoryCapacityError("index_pending_scopes"); + const state: RetrievalProjectionState = same + ? { ...current, status: "pending" } + : { + articleId: request.articleId, + generation: request.generation, + sourceGeneration: request.sourceGeneration, + status: "pending", + targets, + knownScopes, + pendingScopes: knownScopes, + }; + const { reason: _reason, ...clean } = state; + const partition = await articlePartition(request.articleId); + if ( + await transact(partition, [ + write( + row(partition, "head", "article", clean), + before?.row ?? null, + ), + ]) + ) + return clean; + } + throw new RepositoryConflictError(); + }, + async advanceArticleProjection(articleId, expectedGeneration) { + requireGeneration(expectedGeneration, 1); + const before = await readState(articleId); + if (before === null || before.state.generation !== expectedGeneration) + throw new RepositoryConflictError(); + const state = before.state; + if (state.status === "ready") + return { state, complete: true, changed: false }; + if (state.status === "blocked") + return { state, complete: false, changed: false }; + const scope = state.pendingScopes[0]; + if (scope !== undefined) { + await registerCatalog(state, scope.collectionId); + if (!(await applyScopeBatch(state, scope))) + return { state, complete: false, changed: true }; + } + for (let attempt = 0; attempt < maximumAttempts; attempt += 1) { + const latest = await readState(articleId); + if (latest === null || latest.state.generation !== expectedGeneration) + throw new RepositoryConflictError(); + if (latest.state.status === "blocked") + return { state: latest.state, complete: false, changed: false }; + const pendingScopes = + scope === undefined + ? latest.state.pendingScopes + : latest.state.pendingScopes.filter( + (item) => !sameScope(item, scope), + ); + const complete = pendingScopes.length === 0; + const next: RetrievalProjectionState = { + ...latest.state, + pendingScopes, + knownScopes: complete + ? latest.state.targets.map((target) => target.scope) + : latest.state.knownScopes, + status: complete ? "ready" : "pending", + }; + const partition = latest.row.value.partition; + if ( + await transact(partition, [ + write(row(partition, "head", "article", next), latest.row), + ]) + ) + return { state: next, complete, changed: true }; + } + throw new RepositoryConflictError(); + }, + async markArticleProjectionBlocked( + articleId, + generation, + reason, + sourceGeneration, + ) { + requireGeneration(generation, 1); + if (sourceGeneration !== undefined) + requireGeneration(sourceGeneration, 1); + if (!["capacity", "source-unavailable", "conflict"].includes(reason)) + throw new TypeError("Expected a projection block reason"); + for (let attempt = 0; attempt < maximumAttempts; attempt += 1) { + const before = await readState(articleId); + if ( + before === null && + (generation !== 1 || sourceGeneration === undefined) + ) + throw new RepositoryConflictError(); + if (before !== null && before.state.generation !== generation) + throw new RepositoryConflictError(); + const state: RetrievalProjectionState = + before === null + ? { + articleId, + generation, + sourceGeneration: sourceGeneration!, + status: "blocked", + reason, + targets: [], + pendingScopes: [], + knownScopes: [], + } + : { ...before.state, status: "blocked", reason }; + const partition = + before?.row.value.partition ?? (await articlePartition(articleId)); + if ( + await transact(partition, [ + write( + row(partition, "head", "article", state), + before?.row ?? null, + ), + ]) + ) + return state; + } + throw new RepositoryConflictError(); + }, + }; +} diff --git a/packages/application/src/retrieval-types.ts b/packages/application/src/retrieval-types.ts new file mode 100644 index 0000000..4d3af53 --- /dev/null +++ b/packages/application/src/retrieval-types.ts @@ -0,0 +1,238 @@ +import type { AccessContext } from "@pegma/authorization-core"; +import type { + Applicability, + ArticleContent, +} from "@pegma/knowledge-base-contracts"; + +import type { RetrievalHint, RetrievalScope } from "./retrieval-records.js"; +import type { PublishedArticleDto } from "./types.js"; + +/** Initial hard ceilings. Per-instance overrides may only reduce these values. */ +export const defaultKnowledgeRetrievalLimits = Object.freeze({ + maxDirectoryCollections: 64, + maxCatalogArticles: 256, + maxTermsPerArticle: 256, + postingPageEntries: 16, + maxPostingPagesPerTerm: 16, + maxIndexPartitionRows: 8_192, + maxIndexPartitionBytes: 16 * 1024 * 1024, + maxQueryCharacters: 256, + maxQueryTerms: 8, + maxBotCollections: 4, + maxIndexKeyReads: 128, + maxPostingEntries: 2_048, + maxHeadProbes: 64, + maxConfirmations: 8, + maxResults: 5, + maxContentBytes: 64 * 1024, + maxSourceTokens: 8_192, + maxRequestPhysicalGets: 768, + maxMaintenanceBatches: 32, + maxRepairScanRows: 100, +}); + +export type KnowledgeRetrievalLimits = { + readonly [Key in keyof typeof defaultKnowledgeRetrievalLimits]: number; +}; + +/** Source-free untrusted search hint; it never establishes publication/access. */ +export type KnowledgeCandidateHint = RetrievalHint; +export type KnowledgeRetrievalScope = RetrievalScope; + +/** Counts include misses, malformed rows, duplicates, and filtered-out entries. */ +export interface CandidateWork { + readonly keyedReads: number; + readonly physicalRows: number; + readonly postingEntries: number; + readonly pagesRead: number; +} + +export interface CandidateSearchRequest { + readonly scope: KnowledgeRetrievalScope; + readonly terms: readonly string[]; + readonly cursor?: string; + /** Remaining work, not an invitation to expand or reset a query's budget. */ + readonly budget: CandidateWork; +} + +export interface CandidateSearchPage { + /** First-seen order across pages supplies deterministic preselection rank. */ + readonly hints: readonly KnowledgeCandidateHint[]; + readonly nextCursor: string | null; + /** pagesRead is at least one, including empty pages; entries precede filtering. */ + readonly work: CandidateWork; +} + +/** + * Optional host search source, responsible for stable relevance ordering across + * pages. Body or synonym matches need not overlap title/summary/tag terms. + * Ranking and matching never authorize content: every returned candidate still + * requires the current authoritative publication and audience checks. + * The default implementation uses keyed Store lexical pages. + */ +export interface KnowledgeCandidateAdapter { + search(request: CandidateSearchRequest): Promise; +} + +/** Trusted local counter for the complete source serialization returned to a bot. */ +export interface SourceTokenCounter { + count(serializedSources: string): number; +} + +export interface KnowledgeRetrievalOptions { + readonly limits?: Partial; + readonly candidateAdapter?: KnowledgeCandidateAdapter; + /** Required for bot payloads; absence must never result in an uncounted payload. */ + readonly tokenCounter?: SourceTokenCounter; +} + +export interface ListPortalCollectionsInput { + readonly limit?: number; +} + +export interface PortalCollectionDto { + readonly collectionId: string; + readonly label: string; +} + +export interface PortalCollectionsResult { + readonly outcome: "results" | "no_result"; + readonly collections: readonly PortalCollectionDto[]; +} + +export interface SearchPublishedArticlesInput { + readonly collectionId: string; + readonly query: string; + /** Exact tuple; absent build/locale does not imply a fallback or wildcard. */ + readonly applicability: Applicability; + readonly limit?: number; +} + +/** All text comes from a freshly confirmed publication, never the index. */ +export type PortalSearchArticleDto = Omit & { + readonly snippet: string; +}; + +export interface PortalSearchResult { + readonly outcome: "results" | "no_result"; + readonly articles: readonly PortalSearchArticleDto[]; +} + +/** A current-observation fence, never an authorization capability or lease. */ +export interface AnswerSourceReference { + readonly articleId: string; + readonly collectionId: string; + readonly collectionPolicyVersion: number; + readonly articleRevision: number; + readonly contentHash: string; + readonly applicationGeneration: number; + readonly governanceGeneration: number; + readonly validationGeneration: number; +} + +export interface KnowledgeCitationDto { + readonly label: string; + /** Present only when this same customer separately passes portal authority. */ + readonly portalArticle?: { + readonly articleId: string; + readonly revision: number; + }; +} + +/** Approved source payload for the trusted bot integration, not a portal DTO. */ +export interface AnswerSourceDto { + readonly reference: AnswerSourceReference; + readonly citation: KnowledgeCitationDto; + readonly title: string; + readonly summary: string; + readonly content: ArticleContent; + readonly applicability: Applicability; +} + +export interface RetrieveAnswerSourcesInput { + readonly collectionIds: readonly string[]; + readonly query: string; + readonly applicability: Applicability; + readonly limit?: number; +} + +export interface ConfirmAnswerSourcesInput { + readonly references: readonly AnswerSourceReference[]; + readonly applicability: Applicability; +} + +export interface AnswerSourcesResult { + readonly outcome: "results" | "no_result"; + readonly sources: readonly AnswerSourceDto[]; + /** Complete counted source payload, or an empty string for no_result. */ + readonly serializedSources: string; + /** Zero for no_result; otherwise the trusted counter's complete-payload total. */ + readonly sourceTokens: number; +} + +export interface ArticleIndexInput { + readonly articleId: string; +} + +export type ArticleIndexState = "pending" | "ready" | "blocked"; + +export type ArticleIndexBlockReason = + "capacity" | "source-unavailable" | "conflict"; + +/** Staff-only coarse progress; no terms, postings, hashes, or private sources. */ +export interface ArticleIndexStatusDto { + readonly articleId: string; + readonly status: ArticleIndexState; + /** A ready withdrawal is converged but has no usable indexed publication. */ + readonly indexed: boolean; + readonly articleGeneration: number | null; + readonly projectionGeneration: number | null; + readonly reason?: ArticleIndexBlockReason; +} + +export interface RepairRetrievalPageInput { + readonly cursor?: string; + /** Physical scan rows, counted before filtering or candidate deduplication. */ + readonly limit?: number; +} + +/** Staff maintenance diagnostics; these counts never enter search/customer DTOs. */ +export interface RepairRetrievalPageResult { + readonly physicalRows: number; + readonly candidates: number; + readonly repaired: number; + readonly pending: number; + readonly blocked: number; + readonly nextCursor: string | null; +} + +export interface KnowledgeRetrievalApplication { + listPortalCollections( + access: AccessContext, + input: ListPortalCollectionsInput, + ): Promise; + searchPublishedArticles( + access: AccessContext, + input: SearchPublishedArticlesInput, + ): Promise; + retrieveAnswerSources( + effectiveCustomerAccess: AccessContext, + input: RetrieveAnswerSourcesInput, + ): Promise; + confirmAnswerSources( + effectiveCustomerAccess: AccessContext, + input: ConfirmAnswerSourcesInput, + ): Promise; + repairArticleIndex( + staffAccess: AccessContext, + input: ArticleIndexInput, + ): Promise; + repairRetrievalPage( + staffAccess: AccessContext, + input: RepairRetrievalPageInput, + ): Promise; + getArticleIndexStatus( + staffAccess: AccessContext, + input: ArticleIndexInput, + ): Promise; +} diff --git a/packages/application/src/retrieval.ts b/packages/application/src/retrieval.ts new file mode 100644 index 0000000..86e23ff --- /dev/null +++ b/packages/application/src/retrieval.ts @@ -0,0 +1,723 @@ +import { hasPermission, type AccessContext } from "@pegma/authorization-core"; +import { + knowledgePermissions, + type Applicability, + type CollectionUse, +} from "@pegma/knowledge-base-contracts"; +import type { Store } from "@pegma/storage-core"; + +import { KnowledgeBaseNotFoundError } from "./errors.js"; +import { normalizeQuery, scoreConfirmedArticle } from "./lexical.js"; +import { + createPublicationChecker, + type CheckedPublication, +} from "./publication.js"; +import { createKnowledgeRepository } from "./repository.js"; +import { + createRetrievalReadBudget, + RetrievalBudgetError, +} from "./retrieval-budget.js"; +import { resolveRetrievalLimits } from "./retrieval-limits.js"; +import { + requireRetrievalHint, + retrievalRecords, + type RetrievalHint, + type RetrievalScope, +} from "./retrieval-records.js"; +import { createRetrievalRepository } from "./retrieval-repository.js"; +import type { + AnswerSourceDto, + AnswerSourceReference, + AnswerSourcesResult, + KnowledgeRetrievalApplication, + KnowledgeRetrievalOptions, + PortalCollectionsResult, + PortalSearchArticleDto, + PortalSearchResult, +} from "./retrieval-types.js"; +import { + canonicalJson, + fingerprint, + requireGeneration, + requireIdentifier, + snapshotData, +} from "./storage-helpers.js"; +import type { KnowledgeBaseServiceOptions } from "./types.js"; + +type RetrievalMethods = Pick< + KnowledgeRetrievalApplication, + | "listPortalCollections" + | "searchPublishedArticles" + | "retrieveAnswerSources" + | "confirmAnswerSources" +>; +type Purpose = "portal" | "bot"; + +interface AuthorizedScope { + readonly scope: RetrievalScope; + readonly governanceGeneration: number; + readonly label: string; +} + +interface Candidate { + readonly articleId: string; + readonly firstSeen: number; + readonly terms: Set; + readonly hints: Map; +} + +function ordinal(left: string, right: string): number { + return left === right ? 0 : left < right ? -1 : 1; +} + +function inputSnapshot(input: T, fields: readonly string[]): T { + const value = snapshotData(input); + if ( + value === null || + typeof value !== "object" || + Array.isArray(value) || + Object.keys(value).some((key) => !fields.includes(key)) + ) + throw new TypeError("Retrieval input contains unsupported fields"); + return value; +} + +function applicabilitySnapshot(value: Applicability): Applicability { + const applicability = inputSnapshot(value, [ + "productId", + "productVersion", + "buildId", + "locale", + ]); + requireIdentifier(applicability.productId, "applicability.productId"); + requireIdentifier( + applicability.productVersion, + "applicability.productVersion", + ); + if (Object.hasOwn(applicability, "buildId")) + requireIdentifier(applicability.buildId!, "applicability.buildId"); + if (Object.hasOwn(applicability, "locale")) + requireIdentifier(applicability.locale!, "applicability.locale"); + return applicability; +} + +function requestedLimit(limit: number | undefined, maximum: number): number { + if (limit === undefined) return maximum; + if (!Number.isSafeInteger(limit) || limit < 1 || limit > maximum) { + throw new TypeError("Requested retrieval limit exceeds its ceiling"); + } + return limit; +} + +function allows(use: CollectionUse, access: AccessContext): boolean { + return ( + use.enabled && + (use.audience.kind === "anonymous" || + hasPermission(access, use.audience.permission)) + ); +} + +function mayRead(access: AccessContext, purpose: Purpose): boolean { + return ( + hasPermission(access, knowledgePermissions.articleRead) && + (purpose === "portal" || + hasPermission(access, knowledgePermissions.botRead)) + ); +} + +function noPortalResult(): PortalSearchResult { + return { outcome: "no_result", articles: [] }; +} + +function noCollections(): PortalCollectionsResult { + return { outcome: "no_result", collections: [] }; +} + +function noSources(): AnswerSourcesResult { + return { + outcome: "no_result", + sources: [], + serializedSources: "", + sourceTokens: 0, + }; +} + +function referenceOf(checked: CheckedPublication): AnswerSourceReference { + const binding = checked.binding; + return { + articleId: binding.articleId, + collectionId: binding.collectionId, + collectionPolicyVersion: binding.collectionPolicyVersion, + articleRevision: binding.revision, + contentHash: binding.contentHash, + applicationGeneration: binding.articleGeneration, + governanceGeneration: binding.governanceGeneration, + validationGeneration: binding.validationGeneration, + }; +} + +function validateReference(reference: AnswerSourceReference): void { + inputSnapshot(reference, [ + "articleId", + "collectionId", + "collectionPolicyVersion", + "articleRevision", + "contentHash", + "applicationGeneration", + "governanceGeneration", + "validationGeneration", + ]); + requireIdentifier(reference.articleId, "articleId"); + requireIdentifier(reference.collectionId, "collectionId"); + if (!/^[a-f0-9]{64}$/u.test(reference.contentHash)) + throw new TypeError("Invalid source content hash"); + for (const value of [ + reference.collectionPolicyVersion, + reference.articleRevision, + reference.applicationGeneration, + reference.governanceGeneration, + reference.validationGeneration, + ]) + requireGeneration(value, 1); +} + +function sourceOf(checked: CheckedPublication): AnswerSourceDto { + const article = checked.article; + return snapshotData({ + reference: referenceOf(checked), + citation: { + label: article.title, + ...(checked.portalBrowseable + ? { + portalArticle: { + articleId: article.articleId, + revision: article.revision, + }, + } + : {}), + }, + title: article.title, + summary: article.summary, + content: article.content, + applicability: article.applicability, + }); +} + +function portalArticleOf(checked: CheckedPublication): PortalSearchArticleDto { + const article = checked.article; + return snapshotData({ + articleId: article.articleId, + collectionId: article.collectionId, + revision: article.revision, + kind: article.kind, + title: article.title, + summary: article.summary, + snippet: article.summary, + tags: article.tags, + applicability: article.applicability, + contentHash: article.contentHash, + }); +} + +/** Every call constructs a fresh request-scoped read budget and checker. */ +export function createRetrievalServices(input: { + readonly store: Store; + readonly services: KnowledgeBaseServiceOptions; + readonly options?: KnowledgeRetrievalOptions; +}): RetrievalMethods { + const limits = resolveRetrievalLimits(input.options?.limits); + const candidateAdapter = input.options?.candidateAdapter; + const tokenCounter = input.options?.tokenCounter; + + function requestScope() { + const budget = createRetrievalReadBudget(input.store, { + maxPhysicalReads: limits.maxRequestPhysicalGets, + maxIndexReads: limits.maxIndexKeyReads, + maxPostingEntries: limits.maxPostingEntries, + maxCandidateHeads: limits.maxHeadProbes, + maxConfirmations: limits.maxConfirmations, + indexCollectionName: retrievalRecords.name, + }); + const repository = createKnowledgeRepository( + budget.store, + input.services.limits, + ); + const index = createRetrievalRepository(budget.store, limits); + const checker = createPublicationChecker(repository, input.services); + + async function authorizeCollection( + access: AccessContext, + collectionId: string, + purpose: Purpose, + ): Promise { + if (!mayRead(access, purpose)) return null; + const loaded = await repository.readCollectionVersioned(collectionId); + if (loaded === null) return null; + const collection = loaded.value.collection; + if (!allows(collection.policy[purpose], access)) return null; + if ( + [collection.policy.portal, collection.policy.bot].some( + (use) => use.enabled && use.audience.kind === "anonymous", + ) + ) { + const approval = collection.publicApproval; + if ( + approval === undefined || + approval.collectionId !== collection.id || + approval.policyVersion !== collection.policy.version || + approval.policyHash !== (await fingerprint(collection.policy)) + ) + return null; + } + return { + scope: { + collectionId, + policyVersion: collection.policy.version, + use: purpose, + }, + governanceGeneration: loaded.value.generation, + label: collection.name, + }; + } + + async function queryHints( + scopes: readonly AuthorizedScope[], + terms: readonly string[], + ): Promise { + const candidates = new Map(); + const add = ( + hint: RetrievalHint, + scope: RetrievalScope, + term: string, + ) => { + requireRetrievalHint(hint); + if ( + hint.collectionId !== scope.collectionId || + hint.policyVersion !== scope.policyVersion || + hint.use !== scope.use + ) + return; + const candidate = candidates.get(hint.articleId) ?? { + articleId: hint.articleId, + firstSeen: candidates.size, + terms: new Set(), + hints: new Map(), + }; + candidate.terms.add(term); + candidate.hints.set(canonicalJson(hint), hint); + candidates.set(candidate.articleId, candidate); + }; + + for (const authorized of scopes) { + const scope = authorized.scope; + if (candidateAdapter === undefined) { + for (const term of terms) { + const pages = await index.readPostingPages(scope, term); + for (const page of pages) { + budget.indexEntries(page.entries.length); + for (const hint of page.entries) add(hint, scope, term); + } + } + continue; + } + if (typeof candidateAdapter.search !== "function") + throw new RetrievalBudgetError(); + let cursor: string | undefined; + const seen = new Set(); + for (;;) { + const allowance = budget.remainingCandidateWork(); + // Every external page consumes at least one page/read allowance. + // Do not dispatch work that cannot fit, even with an empty response. + if ( + allowance.pagesRead < 1 || + allowance.keyedReads < 1 || + allowance.physicalRows < 1 + ) + throw new RetrievalBudgetError(); + const page = snapshotData( + await candidateAdapter.search({ + scope: snapshotData(scope), + terms: snapshotData(terms), + ...(cursor === undefined ? {} : { cursor }), + budget: allowance, + }), + ); + inputSnapshot(page, ["hints", "nextCursor", "work"]); + if (!Array.isArray(page.hints)) throw new RetrievalBudgetError(); + const work = inputSnapshot(page.work, [ + "keyedReads", + "physicalRows", + "postingEntries", + "pagesRead", + ]); + for (const key of [ + "keyedReads", + "physicalRows", + "postingEntries", + "pagesRead", + ] as const) { + if ( + !Number.isSafeInteger(work[key]) || + work[key] < 0 || + work[key] > allowance[key] + ) + throw new RetrievalBudgetError(); + } + if ( + work.pagesRead < 1 || + work.postingEntries < page.hints.length || + (page.hints.length > 0 && work.physicalRows < 1) + ) + throw new RetrievalBudgetError(); + budget.accountExternal(work); + for (const hint of page.hints) add(hint, scope, "adapter"); + if (page.nextCursor === null) break; + requireIdentifier(page.nextCursor, "candidate cursor"); + if (seen.has(page.nextCursor)) throw new RetrievalBudgetError(); + seen.add(page.nextCursor); + cursor = page.nextCursor; + } + } + if (candidates.size > limits.maxHeadProbes) + throw new RetrievalBudgetError(); + const current: Candidate[] = []; + for (const candidate of candidates.values()) { + budget.candidateHead(); + const generation = await repository.readResourceGeneration( + "article", + candidate.articleId, + ); + // Draft work can advance this head without changing its publication. + // Only the current checker establishes authority; hints identify it. + if (generation !== null) current.push(candidate); + } + return current.sort((left, right) => + candidateAdapter === undefined + ? right.terms.size - left.terms.size || + ordinal(left.articleId, right.articleId) + : left.firstSeen - right.firstSeen, + ); + } + + async function search( + access: AccessContext, + collectionIds: readonly string[], + terms: readonly string[], + applicability: Applicability, + purpose: Purpose, + resultLimit: number, + ): Promise { + if (!mayRead(access, purpose) || terms.length === 0) return []; + const scopes: AuthorizedScope[] = []; + // Check every requested collection before any derived index lookup. + for (const collectionId of collectionIds) { + const authorized = await authorizeCollection( + access, + collectionId, + purpose, + ); + if (authorized === null) return []; + scopes.push(authorized); + } + const candidates = await queryHints(scopes, terms); + const confirmed: { + checked: CheckedPublication; + score: number; + firstSeen: number; + }[] = []; + // Adapter order is a relevance hint for bounded preselection only. + // Every candidate still needs current publication confirmation. + for (const candidate of candidates.slice(0, limits.maxConfirmations)) { + budget.confirmation(); + let checked: CheckedPublication; + try { + checked = await checker.check({ + articleId: candidate.articleId, + purpose, + access, + applicability, + }); + } catch (error) { + if (error instanceof KnowledgeBaseNotFoundError) continue; + throw error; + } + if ( + ![...candidate.hints.values()].some( + (hint) => + hint.articleId === checked.article.articleId && + hint.collectionId === checked.article.collectionId && + hint.policyVersion === checked.binding.collectionPolicyVersion && + hint.articleRevision === checked.article.revision && + hint.contentHash === checked.article.contentHash, + ) + ) + continue; + const score = scoreConfirmedArticle(checked.article, terms); + // An adapter may match approved body text or synonyms rather than the + // title/summary/tags used by the default lexical index. + if (score > 0 || candidateAdapter !== undefined) + confirmed.push({ checked, score, firstSeen: candidate.firstSeen }); + } + confirmed.sort( + (left, right) => + right.score - left.score || + (candidateAdapter === undefined + ? ordinal( + left.checked.article.articleId, + right.checked.article.articleId, + ) + : left.firstSeen - right.firstSeen), + ); + return confirmed.slice(0, resultLimit).map(({ checked }) => checked); + } + + async function sourceResult( + checked: readonly CheckedPublication[], + fitWholeArticles = false, + ): Promise { + if (checked.length === 0 || typeof tokenCounter?.count !== "function") + return noSources(); + for (let count = checked.length; count > 0; count -= 1) { + const selected = checked.slice(0, count); + const sources = selected.map(sourceOf); + const serializedSources = canonicalJson(sources); + if ( + new TextEncoder().encode(serializedSources).byteLength <= + limits.maxContentBytes + ) { + let sourceTokens: number; + try { + sourceTokens = tokenCounter.count(serializedSources); + } catch { + return noSources(); + } + if (!Number.isSafeInteger(sourceTokens) || sourceTokens <= 0) + return noSources(); + if (sourceTokens <= limits.maxSourceTokens) { + for (const source of selected) await checker.recheck(source); + return { + outcome: "results", + sources, + serializedSources, + sourceTokens, + }; + } + } + // Select only complete top-ranked articles; an exact citation list + // instead remains all-or-nothing during reconfirmation. + if (!fitWholeArticles) return noSources(); + } + return noSources(); + } + + return { + budget, + repository, + index, + checker, + authorizeCollection, + search, + sourceResult, + }; + } + + function queryTerms(query: string): readonly string[] { + if (typeof query !== "string" || query.length > limits.maxQueryCharacters) { + throw new TypeError("Query exceeds its configured character bound"); + } + const terms = normalizeQuery(query); + if (terms.length > limits.maxQueryTerms) + throw new TypeError("Query exceeds its configured term bound"); + return terms; + } + + return { + async listPortalCollections(access, request) { + const caller = snapshotData(access); + const query = inputSnapshot(request, ["limit"]); + const limit = requestedLimit(query.limit, limits.maxDirectoryCollections); + if (!mayRead(caller, "portal")) return noCollections(); + try { + const scope = requestScope(); + const ids = await scope.index.readDirectory(); + if (ids.length > limits.maxDirectoryCollections) return noCollections(); + const authorized: AuthorizedScope[] = []; + for (const id of ids) { + requireIdentifier(id, "collectionId"); + const collection = await scope.authorizeCollection( + caller, + id, + "portal", + ); + if (collection !== null) authorized.push(collection); + } + const selected = authorized + .sort((left, right) => + ordinal(left.scope.collectionId, right.scope.collectionId), + ) + .slice(0, limit); + for (const collection of selected) { + if ( + (await scope.repository.readResourceGeneration( + "collection", + collection.scope.collectionId, + )) !== collection.governanceGeneration + ) { + return noCollections(); + } + } + return selected.length === 0 + ? noCollections() + : { + outcome: "results", + collections: selected.map((collection) => ({ + collectionId: collection.scope.collectionId, + label: collection.label, + })), + }; + } catch { + return noCollections(); + } + }, + + async searchPublishedArticles(access, request) { + const caller = snapshotData(access); + const query = inputSnapshot(request, [ + "collectionId", + "query", + "applicability", + "limit", + ]); + requireIdentifier(query.collectionId, "collectionId"); + const terms = queryTerms(query.query); + const applicability = applicabilitySnapshot(query.applicability); + const limit = requestedLimit(query.limit, limits.maxResults); + try { + const scope = requestScope(); + const checked = await scope.search( + caller, + [query.collectionId], + terms, + applicability, + "portal", + limit, + ); + const articles = checked.map(portalArticleOf); + if ( + articles.length === 0 || + new TextEncoder().encode(canonicalJson(articles)).byteLength > + limits.maxContentBytes + ) + return noPortalResult(); + for (const article of checked) await scope.checker.recheck(article); + return { outcome: "results", articles }; + } catch { + return noPortalResult(); + } + }, + + async retrieveAnswerSources(effectiveCustomerAccess, request) { + const caller = snapshotData(effectiveCustomerAccess); + const query = inputSnapshot(request, [ + "collectionIds", + "query", + "applicability", + "limit", + ]); + if ( + !Array.isArray(query.collectionIds) || + query.collectionIds.length === 0 || + query.collectionIds.length > limits.maxBotCollections + ) { + throw new TypeError("Bot retrieval exceeds its collection bound"); + } + for (const id of query.collectionIds) + requireIdentifier(id, "collectionId"); + if (new Set(query.collectionIds).size !== query.collectionIds.length) + throw new TypeError("Collection ids must be unique"); + const terms = queryTerms(query.query); + const applicability = applicabilitySnapshot(query.applicability); + const limit = requestedLimit(query.limit, limits.maxResults); + if (typeof tokenCounter?.count !== "function") return noSources(); + try { + const scope = requestScope(); + return await scope.sourceResult( + await scope.search( + caller, + query.collectionIds, + terms, + applicability, + "bot", + limit, + ), + true, + ); + } catch { + return noSources(); + } + }, + + async confirmAnswerSources(effectiveCustomerAccess, request) { + const caller = snapshotData(effectiveCustomerAccess); + const query = inputSnapshot(request, ["references", "applicability"]); + const applicability = applicabilitySnapshot(query.applicability); + if ( + !Array.isArray(query.references) || + query.references.length === 0 || + query.references.length > limits.maxResults + ) { + throw new TypeError("Citation references exceed their result bound"); + } + for (const reference of query.references) validateReference(reference); + if ( + new Set(query.references.map((reference) => reference.articleId)) + .size !== query.references.length || + new Set(query.references.map((reference) => reference.collectionId)) + .size > limits.maxBotCollections + ) + throw new TypeError( + "Citation references must have unique articles and bounded collections", + ); + if (typeof tokenCounter?.count !== "function" || !mayRead(caller, "bot")) + return noSources(); + try { + const scope = requestScope(); + for (const collectionId of new Set( + query.references.map((reference) => reference.collectionId), + )) { + if ( + (await scope.authorizeCollection(caller, collectionId, "bot")) === + null + ) + return noSources(); + } + const checked: CheckedPublication[] = []; + for (const reference of query.references) { + scope.budget.candidateHead(); + if ( + (await scope.repository.readResourceGeneration( + "article", + reference.articleId, + )) !== reference.applicationGeneration + ) + return noSources(); + scope.budget.confirmation(); + const confirmed = await scope.checker.check({ + articleId: reference.articleId, + purpose: "bot", + access: caller, + applicability, + }); + if ( + canonicalJson(referenceOf(confirmed)) !== canonicalJson(reference) + ) + return noSources(); + checked.push(confirmed); + } + return await scope.sourceResult(checked); + } catch { + return noSources(); + } + }, + }; +} diff --git a/packages/application/src/types.ts b/packages/application/src/types.ts index 0d21b75..ff2009f 100644 --- a/packages/application/src/types.ts +++ b/packages/application/src/types.ts @@ -23,6 +23,10 @@ import type { import type { Store } from "@pegma/storage-core"; import type { KnowledgeRepositoryLimits } from "./repository.js"; +import type { + KnowledgeRetrievalApplication, + KnowledgeRetrievalOptions, +} from "./retrieval-types.js"; /** Opaque source identity only: no URL, source body, customer text, or credential. */ export interface PrivateSourceReference { @@ -107,6 +111,7 @@ export interface KnowledgeBaseApplicationOptions { readonly store: Store; readonly clock: Clock; readonly limits?: Partial; + readonly retrieval?: KnowledgeRetrievalOptions; /** Missing verifier fails closed for every evidence submission. */ readonly evidenceVerifier?: EvidenceVerifier; /** Missing verifier fails closed wherever a nonempty source snapshot is needed. */ @@ -115,7 +120,7 @@ export interface KnowledgeBaseApplicationOptions { export type KnowledgeBaseServiceOptions = Omit< KnowledgeBaseApplicationOptions, - "store" + "store" | "retrieval" >; export interface CommandInput { @@ -321,7 +326,7 @@ export interface ArticleReadInput { readonly articleId: string; } -export interface KnowledgeBaseApplication { +export interface KnowledgeBaseApplication extends KnowledgeRetrievalApplication { createCollection( access: AccessContext, input: CreateCollectionInput, diff --git a/packages/contracts/src/index.ts b/packages/contracts/src/index.ts index 6f9fea2..7799f12 100644 --- a/packages/contracts/src/index.ts +++ b/packages/contracts/src/index.ts @@ -13,6 +13,8 @@ export const knowledgePermissions = { collectionManage: "knowledge.collection.manage", publicCollectionApprove: "knowledge.collection.approve-public", articleRead: "knowledge.article.read", + botRead: "knowledge.article.bot.read", + indexManage: "knowledge.index.manage", draftRead: "knowledge.article.draft.read", draftWrite: "knowledge.article.draft.write", evidenceRead: "knowledge.article.evidence.read", diff --git a/test/retrieval-fixtures.ts b/test/retrieval-fixtures.ts new file mode 100644 index 0000000..a8ef431 --- /dev/null +++ b/test/retrieval-fixtures.ts @@ -0,0 +1,222 @@ +import type { ArticleDraft } from "@pegma/knowledge-base-core"; +import { + createKnowledgeBaseApplication, + retrievalRecords, + type KnowledgeCandidateHint, + type KnowledgeRetrievalOptions, + type RetrievalRecord, +} from "@pegma/knowledge-base-application"; +import { knowledgePermissions } from "@pegma/knowledge-base-contracts"; +import type { Store } from "@pegma/storage-core"; +import { + access, + admin, + applicationFixture, + at, + customer, + draft, +} from "./application-fixtures.js"; +import { traceStore } from "./trace-store.js"; + +/** Fictional approved wording and alias tags; no semantic-model quality claim. */ +export const retrievalGuides: readonly { + readonly id: string; + readonly draft: ArticleDraft; + readonly questions: readonly string[]; +}[] = [ + { + id: "article/export", + draft: { + ...draft( + "explanation", + "Open Workspace, choose Export, then download the CSV spreadsheet.", + ), + title: "Download a workspace export", + summary: "Save your workspace data as a CSV spreadsheet.", + tags: ["download", "export", "csv", "spreadsheet"], + }, + questions: [ + "How can I download my data as a CSV spreadsheet?", + "Where is workspace export?", + ], + }, + { + id: "article/password", + draft: { + ...draft( + "explanation", + "Choose Forgot password on the sign-in page and follow the reset link.", + ), + title: "Reset a forgotten sign-in password", + summary: "Recover access after forgetting an account password.", + tags: ["reset", "password", "login", "sign-in", "account"], + }, + questions: [ + "I forgot my password and cannot login", + "How do I reset the sign in password?", + ], + }, + { + id: "article/invite", + draft: { + ...draft( + "explanation", + "Open Members, choose Invite, and enter your teammate's email address.", + ), + title: "Invite a teammate to a workspace", + summary: "Add a collaborator through the workspace Members screen.", + tags: ["team", "member", "invite", "collaborator", "add"], + }, + questions: [ + "How can I invite another team member?", + "Add a collaborator to my workspace", + ], + }, +]; + +export const unsupportedRetrievalQuestion = "interplanetary warranty quasar"; + +/** One UTF-8 byte is one fixture token, deliberately unrelated to model billing. */ +export function countSyntheticTokens(text: string): number { + return new TextEncoder().encode(text).byteLength; +} + +export const botCustomer = access(customer.principalId, [ + ...customer.permissions, + knowledgePermissions.botRead, +]); +export const indexAdministrator = access(admin.principalId, [ + ...admin.permissions, + knowledgePermissions.indexManage, +]); +export const retrievalApplicability = draft().applicability; + +/** Actual authoring and index services share one real Store and scripted host facts. */ +export function retrievalFixture( + backing: Store, + options: KnowledgeRetrievalOptions = {}, +) { + const traced = traceStore(backing); + const authoring = applicationFixture(traced.store); + const app = createKnowledgeBaseApplication({ + store: traced.store, + clock: { now: () => at(600_000) }, + evidenceVerifier: { verify: authoring.verify }, + privateSources: authoring.privateSources, + retrieval: { + tokenCounter: { count: countSyntheticTokens }, + ...options, + }, + }); + async function repair(articleId: string) { + for (let attempt = 0; attempt < 16; attempt += 1) { + const status = await app.repairArticleIndex(indexAdministrator, { + articleId, + }); + if (status.status !== "pending") return status; + } + throw new Error( + "Synthetic projection did not settle within 16 bounded calls", + ); + } + async function publishGuide( + guide = retrievalGuides[0]!, + collectionId = "collection/workshop", + ) { + const published = await authoring.publishedArticle( + guide.id, + collectionId, + guide.draft, + ); + const status = await repair(guide.id); + if (status.status !== "ready" || !status.indexed) + throw new Error( + `Synthetic guide indexing was ${status.status}, indexed=${status.indexed}`, + ); + return published; + } + async function corpus() { + await authoring.setupCollection(); + for (const guide of retrievalGuides) await publishGuide(guide); + } + return { + ...authoring, + authoringApp: authoring.app, + app, + traced, + repair, + publishGuide, + corpus, + clearObservations() { + traced.reads.length = 0; + traced.enumerations.length = 0; + traced.transactions.length = 0; + }, + portalInput(query = "export") { + return { + collectionId: "collection/workshop", + query, + applicability: retrievalApplicability, + }; + }, + botInput(query = "export") { + return { + collectionIds: ["collection/workshop"], + query, + applicability: retrievalApplicability, + }; + }, + }; +} + +/** Offline fixture inspection of derived hints; never used in a request handler. */ +export async function allRetrievalRows( + store: Store, +): Promise { + const records = store.collection(retrievalRecords); + const rows: RetrievalRecord[] = []; + let cursor: string | undefined; + for (let page = 0; page < 16; page += 1) { + const result = await records.scan({ + limit: 1_000, + ...(cursor === undefined ? {} : { cursor }), + }); + rows.push(...result.records.map((record) => record.value)); + if (result.nextCursor === null) + return rows.sort((left, right) => + `${left.partition}/${left.id}`.localeCompare( + `${right.partition}/${right.id}`, + ), + ); + cursor = result.nextCursor; + } + throw new Error( + "Synthetic retrieval snapshot exceeded 16 bounded scan pages", + ); +} + +export async function realBotHint( + store: Store, +): Promise { + const hint = (await realBotHints(store))[0]; + if (hint !== undefined) return hint; + throw new Error("Synthetic guide has no maintained bot posting hint"); +} + +export async function realBotHints( + store: Store, +): Promise { + const hints = new Map(); + for (const row of await allRetrievalRows(store)) { + if (row.kind !== "page") continue; + const page = row.data as { + readonly entries: readonly { + readonly hint: KnowledgeCandidateHint; + readonly projectionGeneration: number; + }[]; + }; + for (const entry of page.entries) + if (entry.hint.use === "bot") hints.set(entry.hint.articleId, entry.hint); + } + return [...hints.values()]; +} diff --git a/test/trace-store.ts b/test/trace-store.ts index cacd4c9..2c343d5 100644 --- a/test/trace-store.ts +++ b/test/trace-store.ts @@ -17,9 +17,21 @@ export interface GetTrace { readonly key: EntityKey; } +export interface ReadTrace extends GetTrace { + readonly method: "get" | "getVersioned"; +} + +export interface EnumerationTrace { + readonly collection: string; + readonly method: "list" | "listVersioned" | "scan"; + readonly input: unknown; +} + /** Delegates all data to the real Store; only read timing and transactions vary. */ export function traceStore(backing: Store) { const transactions: TransactionTrace[] = []; + const reads: ReadTrace[] = []; + const enumerations: EnumerationTrace[] = []; let intercept: | (( trace: TransactionTrace, @@ -27,18 +39,41 @@ export function traceStore(backing: Store) { ) => Promise) | undefined; let beforeGet: ((trace: GetTrace) => Promise) | undefined; + let beforeRead: ((trace: ReadTrace) => Promise) | undefined; const store: Store = { collection(definition: CollectionDefinition) { const target = backing.collection(definition); return new Proxy(target, { get(object, property) { - if (property === "get") + if (property === "get" || property === "getVersioned") return async (key: EntityKey) => { - await beforeGet?.({ + const trace: ReadTrace = { collection: definition.name, + method: property, key: structuredClone(key), + }; + reads.push(trace); + await beforeRead?.(trace); + if (property === "get") await beforeGet?.(trace); + return property === "get" + ? object.get(key) + : object.getVersioned(key); + }; + if ( + property === "list" || + property === "listVersioned" || + property === "scan" + ) + return async (input: unknown) => { + enumerations.push({ + collection: definition.name, + method: property, + input: structuredClone(input), }); - return object.get(key); + const method = Reflect.get(object, property, object) as ( + value: unknown, + ) => Promise; + return method.call(object, input); }; if (property === "transact") return async ( @@ -65,12 +100,17 @@ export function traceStore(backing: Store) { return { store, transactions, + reads, + enumerations, intercept: (handler: typeof intercept) => { intercept = handler; }, beforeGet: (handler: typeof beforeGet) => { beforeGet = handler; }, + beforeRead: (handler: typeof beforeRead) => { + beforeRead = handler; + }, }; } diff --git a/tests/retrieval-bounds.test.ts b/tests/retrieval-bounds.test.ts new file mode 100644 index 0000000..6331772 --- /dev/null +++ b/tests/retrieval-bounds.test.ts @@ -0,0 +1,342 @@ +import { + createKnowledgeBaseApplication, + defaultKnowledgeRetrievalLimits, + type CandidateSearchPage, + type KnowledgeCandidateAdapter, +} from "@pegma/knowledge-base-application"; +import { describe, expect, it, vi } from "vitest"; +import { at } from "../test/application-fixtures.js"; +import { storeFactories } from "../test/application-stores.js"; +import { + botCustomer, + countSyntheticTokens, + realBotHint, + retrievalApplicability, + retrievalFixture, + retrievalGuides, +} from "../test/retrieval-fixtures.js"; + +for (const [name, createStore] of storeFactories) { + describe(`retrieval physical and source bounds (${name})`, () => { + it("rejects oversized query, term, scope and result requests before reading storage", async () => { + const f = retrievalFixture(createStore()); + const invalid = [ + { ...f.botInput(), query: "a".repeat(257) }, + { + ...f.botInput(), + query: "one two three four five six seven eight nine", + }, + { ...f.botInput(), collectionIds: ["c/1", "c/2", "c/3", "c/4", "c/5"] }, + { ...f.botInput(), limit: 6 }, + ]; + for (const input of invalid) + await expect( + f.app.retrieveAnswerSources(botCustomer, input), + ).rejects.toBeInstanceOf(TypeError); + expect(f.traced.reads).toEqual([]); + expect(f.traced.enumerations).toEqual([]); + }); + + it("uses keyed reads only and respects total physical gets even when missing rows consume the budget", async () => { + const f = retrievalFixture(createStore(), { + limits: { maxRequestPhysicalGets: 5 }, + }); + await f.corpus(); + f.clearObservations(); + const result = await f.app.retrieveAnswerSources( + botCustomer, + f.botInput("workspace"), + ); + expect(result.sources).toEqual([]); + expect(f.traced.reads.length).toBeGreaterThan(0); + expect(f.traced.reads.length).toBeLessThanOrEqual(5); + expect(f.traced.enumerations).toEqual([]); + expect(f.traced.transactions).toEqual([]); + }, 30_000); + + it("keeps ordinary retrieval within all declared physical ceilings without scans or mutations", async () => { + const f = retrievalFixture(createStore()); + await f.corpus(); + f.clearObservations(); + const answer = await f.app.retrieveAnswerSources( + botCustomer, + f.botInput("workspace"), + ); + expect(answer.sources.length).toBeGreaterThan(0); + expect(f.traced.reads.length).toBeLessThanOrEqual( + defaultKnowledgeRetrievalLimits.maxRequestPhysicalGets, + ); + expect( + f.traced.reads.filter( + (read) => read.collection === "knowledge-base.retrieval.v1", + ).length, + ).toBeLessThanOrEqual(defaultKnowledgeRetrievalLimits.maxIndexKeyReads); + expect(f.traced.enumerations).toEqual([]); + expect(f.traced.transactions).toEqual([]); + }, 30_000); + + it.each([{ maxContentBytes: 1 }, { maxSourceTokens: 1 }])( + "returns no partial procedure when the whole-source allowance is %j", + async (limits) => { + const f = retrievalFixture(createStore(), { limits }); + await f.setupCollection(); + await f.publishGuide(); + const answer = await f.app.retrieveAnswerSources( + botCustomer, + f.botInput(), + ); + expect(answer.sources).toEqual([]); + expect(answer.outcome).toBe("no_result"); + }, + 30_000, + ); + + it("counts complete serialized sources including citations and reference metadata", async () => { + const count = vi.fn(countSyntheticTokens); + const f = retrievalFixture(createStore(), { tokenCounter: { count } }); + await f.setupCollection(); + await f.publishGuide(); + const answer = await f.app.retrieveAnswerSources( + botCustomer, + f.botInput(), + ); + expect(answer.sources).toHaveLength(1); + expect(count).toHaveBeenCalledWith(answer.serializedSources); + expect(answer.sourceTokens).toBe( + countSyntheticTokens(answer.serializedSources), + ); + expect(answer.sourceTokens).toBeGreaterThan( + countSyntheticTokens(answer.sources[0]!.content.text), + ); + expect(answer.sourceTokens).toBeLessThanOrEqual( + defaultKnowledgeRetrievalLimits.maxSourceTokens, + ); + }, 30_000); + + it.each(["maxContentBytes", "maxSourceTokens"] as const)( + "fits whole ranked sources within %s while exact confirmation remains all-or-nothing", + async (budget) => { + const backing = createStore(); + const normal = retrievalFixture(backing); + await normal.setupCollection(); + for (const id of ["article/export-a", "article/export-b"]) + await normal.publishGuide({ ...retrievalGuides[0]!, id }); + const all = await normal.app.retrieveAnswerSources( + botCustomer, + normal.botInput(), + ); + expect(all.sources).toHaveLength(2); + const largestSingle = Math.max( + ...all.sources.map((source) => + countSyntheticTokens(JSON.stringify([source])), + ), + ); + const combined = countSyntheticTokens(all.serializedSources); + const boundary = Math.floor((largestSingle + combined) / 2); + expect(boundary).toBeGreaterThan(largestSingle); + expect(boundary).toBeLessThan(combined); + const limited = retrievalFixture(backing, { + limits: { [budget]: boundary }, + }); + const fitted = await limited.app.retrieveAnswerSources( + botCustomer, + limited.botInput(), + ); + expect(fitted.sources).toEqual([all.sources[0]]); + expect(JSON.parse(fitted.serializedSources)).toEqual(fitted.sources); + expect(fitted.sourceTokens).toBe( + countSyntheticTokens(fitted.serializedSources), + ); + expect( + countSyntheticTokens(fitted.serializedSources), + ).toBeLessThanOrEqual(boundary); + expect( + ( + await limited.app.confirmAnswerSources(botCustomer, { + references: all.sources.map((source) => source.reference), + applicability: retrievalApplicability, + }) + ).sources, + ).toEqual([]); + expect( + ( + await limited.app.confirmAnswerSources(botCustomer, { + references: fitted.sources.map((source) => source.reference), + applicability: retrievalApplicability, + }) + ).sources, + ).toEqual(fitted.sources); + }, + 30_000, + ); + + it("fails closed when the local token counter is missing or returns an invalid count", async () => { + const backing = createStore(); + const f = retrievalFixture(backing); + await f.setupCollection(); + await f.publishGuide(); + for (const tokenCounter of [ + undefined, + { count: () => Number.NaN }, + { count: () => 0 }, + { count: () => -1 }, + { count: () => 1.5 }, + ]) { + const app = createKnowledgeBaseApplication({ + store: backing, + clock: { now: () => at(600_000) }, + retrieval: tokenCounter === undefined ? {} : { tokenCounter }, + }); + expect( + (await app.retrieveAnswerSources(botCustomer, f.botInput())).sources, + ).toEqual([]); + } + }, 30_000); + + it("bounds confirmation count and returned results independently of available candidates", async () => { + const f = retrievalFixture(createStore(), { + limits: { maxHeadProbes: 1, maxConfirmations: 1, maxResults: 1 }, + }); + await f.corpus(); + const answer = await f.app.retrieveAnswerSources( + botCustomer, + f.botInput("workspace"), + ); + expect(answer.sources.length).toBeLessThanOrEqual(1); + }, 30_000); + + it.each([ + "duplicate entries", + "malformed entries", + "unreported physical rows", + "unreported pages", + ] as const)( + "counts %s before filtering an optional candidate adapter response", + async (fault) => { + const backing = createStore(); + const seed = retrievalFixture(backing); + await seed.setupCollection(); + await seed.publishGuide(); + const hint = await realBotHint(backing); + const page: CandidateSearchPage = { + hints: + fault === "malformed entries" + ? [hint, { ...hint, contentHash: "malformed" }] + : fault === "duplicate entries" + ? [hint, hint] + : [hint], + nextCursor: null, + work: { + keyedReads: 1, + physicalRows: + fault === "unreported physical rows" + ? 0 + : fault === "unreported pages" + ? 1 + : 2, + postingEntries: + fault === "duplicate entries" || fault === "malformed entries" + ? 2 + : 1, + pagesRead: fault === "unreported pages" ? 0 : 1, + }, + }; + const search = vi.fn(async () => page); + const f = retrievalFixture(backing, { + candidateAdapter: { search }, + limits: { maxPostingEntries: 1 }, + }); + f.clearObservations(); + const answer = await f.app.retrieveAnswerSources( + botCustomer, + f.botInput(), + ); + expect(answer.sources).toEqual([]); + expect(search).toHaveBeenCalledTimes(1); + expect(f.traced.enumerations).toEqual([]); + }, + 30_000, + ); + + it("stops empty continuation pages and accounts for physical pages with no candidates", async () => { + const search = vi.fn(async () => ({ + hints: [], + nextCursor: "empty-page", + work: { + keyedReads: 1, + physicalRows: 0, + postingEntries: 0, + pagesRead: 1, + }, + })); + const f = retrievalFixture(createStore(), { + candidateAdapter: { search }, + limits: { maxPostingPagesPerTerm: 2 }, + }); + await f.setupCollection(); + await f.publishGuide(); + const answer = await f.app.retrieveAnswerSources( + botCustomer, + f.botInput(), + ); + expect(answer.sources).toEqual([]); + expect(search.mock.calls.length).toBeGreaterThan(0); + expect(search.mock.calls.length).toBeLessThanOrEqual(2); + }); + + it.each(["continuation", "next collection"] as const)( + "stops before dispatching an adapter %s when the shared keyed-read allowance is exhausted", + async (schedule) => { + let page = 0; + const search = vi.fn(async () => ({ + hints: [], + nextCursor: + schedule === "continuation" ? `fresh-page-${++page}` : null, + work: { + keyedReads: 1, + physicalRows: 0, + postingEntries: 0, + pagesRead: 1, + }, + })); + const f = retrievalFixture(createStore(), { + candidateAdapter: { search }, + limits: { maxIndexKeyReads: 1 }, + }); + await f.setupCollection(); + await f.publishGuide(); + if (schedule === "next collection") { + await f.setupCollection("collection/second"); + await f.publishGuide( + { ...retrievalGuides[0]!, id: "article/second" }, + "collection/second", + ); + } + const answer = await f.app.retrieveAnswerSources(botCustomer, { + ...f.botInput(), + collectionIds: + schedule === "next collection" + ? ["collection/workshop", "collection/second"] + : ["collection/workshop"], + }); + expect(answer.sources).toEqual([]); + expect(search).toHaveBeenCalledTimes(1); + expect(search.mock.calls[0]?.[0].budget.keyedReads).toBe(1); + }, + 30_000, + ); + + it("rejects limit configurations above hard ceilings or outside integral positive bounds", () => { + for (const limits of [ + { maxQueryCharacters: 257 }, + { maxRequestPhysicalGets: 769 }, + { maxPostingEntries: 0 }, + { maxHeadProbes: 1.5 }, + { maxResults: -1 }, + ]) + expect(() => retrievalFixture(createStore(), { limits })).toThrow( + TypeError, + ); + }); + }); +} diff --git a/tests/retrieval-maintenance.test.ts b/tests/retrieval-maintenance.test.ts new file mode 100644 index 0000000..a401d6b --- /dev/null +++ b/tests/retrieval-maintenance.test.ts @@ -0,0 +1,535 @@ +import { knowledgePermissions } from "@pegma/knowledge-base-contracts"; +import { createKnowledgeBaseApplication } from "@pegma/knowledge-base-application"; +import { describe, expect, it } from "vitest"; +import { admin, at, author, customer } from "../test/application-fixtures.js"; +import { + allKnowledgeRows, + storeFactories, +} from "../test/application-stores.js"; +import { + allRetrievalRows, + countSyntheticTokens, + indexAdministrator, + retrievalFixture, + retrievalGuides, +} from "../test/retrieval-fixtures.js"; +import { barrier } from "../test/trace-store.js"; + +for (const [name, createStore] of storeFactories) { + describe(`bounded retrieval maintenance (${name})`, () => { + it("requires staff index authority for repair, status and physical scan operations", async () => { + const f = retrievalFixture(createStore()); + for (const operation of [ + () => + f.app.repairArticleIndex(customer, { articleId: "article/export" }), + () => + f.app.getArticleIndexStatus(customer, { + articleId: "article/export", + }), + () => f.app.repairRetrievalPage(customer, { limit: 3 }), + ]) + await expect(operation()).rejects.toMatchObject({ + permission: knowledgePermissions.indexManage, + }); + expect(f.traced.reads).toEqual([]); + expect(f.traced.enumerations).toEqual([]); + expect(f.traced.transactions).toEqual([]); + }); + + it("repairs missed work through bounded physical scan pages and opaque continuation", async () => { + const backing = createStore(); + const f = retrievalFixture(backing); + await f.setupCollection(); + await f.publishedArticle( + "article/export", + "collection/workshop", + retrievalGuides[0]!.draft, + ); + expect( + await f.app.getArticleIndexStatus(indexAdministrator, { + articleId: "article/export", + }), + ).toMatchObject({ status: "pending", indexed: false }); + expect( + (await f.app.searchPublishedArticles(customer, f.portalInput())) + .articles, + ).toEqual([]); + const authoritativeRows = await allKnowledgeRows(backing); + let physicalRows = 0; + let completedCycles = 0; + let indexed = false; + f.clearObservations(); + for (let cycle = 0; cycle < 8 && !indexed; cycle += 1) { + let cursor: string | undefined; + let completed = false; + const cursors = new Set(); + for (let page = 0; page < 128; page += 1) { + const result = await f.app.repairRetrievalPage(indexAdministrator, { + limit: 3, + ...(cursor === undefined ? {} : { cursor }), + }); + expect(result.physicalRows).toBeLessThanOrEqual(3); + expect(result.candidates).toBeLessThanOrEqual(result.physicalRows); + physicalRows += result.physicalRows; + if (result.nextCursor === null) { + completed = true; + completedCycles += 1; + break; + } + expect(cursors.has(result.nextCursor)).toBe(false); + cursors.add(result.nextCursor); + cursor = result.nextCursor; + } + expect(completed).toBe(true); + indexed = ( + await f.app.getArticleIndexStatus(indexAdministrator, { + articleId: "article/export", + }) + ).indexed; + } + expect(indexed).toBe(true); + expect(physicalRows).toBe(authoritativeRows.length * completedCycles); + expect( + f.traced.enumerations.filter((call) => call.method !== "scan"), + ).toEqual([]); + expect( + f.traced.enumerations.every( + (call) => call.collection === "knowledge-base.records.v1", + ), + ).toBe(true); + expect( + await f.app.getArticleIndexStatus(indexAdministrator, { + articleId: "article/export", + }), + ).toMatchObject({ status: "ready", indexed: true }); + expect( + (await f.app.searchPublishedArticles(customer, f.portalInput())) + .articles[0]?.articleId, + ).toBe("article/export"); + }, 30_000); + + it("makes repeated repair idempotent without adding projection history", async () => { + const backing = createStore(); + const f = retrievalFixture(backing); + await f.setupCollection(); + await f.publishGuide(); + const before = await allRetrievalRows(backing); + const first = await f.app.getArticleIndexStatus(indexAdministrator, { + articleId: "article/export", + }); + for (let delivery = 0; delivery < 3; delivery += 1) + expect(await f.repair("article/export")).toEqual(first); + expect(await allRetrievalRows(backing)).toEqual(before); + }, 30_000); + + it("withdraws retirement immediately and converges stale projection cleanup", async () => { + const f = retrievalFixture(createStore()); + await f.setupCollection(); + const published = await f.publishGuide(); + await f.authoringApp.retireArticle(indexAdministrator, { + ...f.command("retire-indexed", published.current.generation), + articleId: "article/export", + }); + expect( + (await f.app.searchPublishedArticles(customer, f.portalInput())) + .articles, + ).toEqual([]); + expect(await f.repair("article/export")).toMatchObject({ + status: "ready", + indexed: false, + }); + expect(await f.repair("article/export")).toMatchObject({ + status: "ready", + indexed: false, + }); + expect( + (await f.app.searchPublishedArticles(customer, f.portalInput())) + .articles, + ).toEqual([]); + }, 30_000); + + it("moves a newly approved revision while cleaning its old collection scope", async () => { + const f = retrievalFixture(createStore()); + await f.setupCollection(); + await f.setupCollection("collection/new-workshop"); + const old = await f.publishGuide(); + await f.authoringApp.updateDraft(author, { + ...f.command("move-for-review", old.current.generation), + articleId: "article/export", + collectionId: "collection/new-workshop", + draft: retrievalGuides[0]!.draft, + }); + let current = await f.app.getDraft(author, { + articleId: "article/export", + }); + current = (await f.submitEvidence(current)).current; + await f.publish(current); + await f.repair("article/export"); + expect( + (await f.app.searchPublishedArticles(customer, f.portalInput())) + .articles, + ).toEqual([]); + const destination = await f.app.searchPublishedArticles(customer, { + ...f.portalInput(), + collectionId: "collection/new-workshop", + }); + expect(destination.articles[0]).toMatchObject({ + articleId: "article/export", + collectionId: "collection/new-workshop", + revision: 2, + }); + }, 30_000); + + it("keeps capacity failure visible while authoritative content remains intact", async () => { + const backing = createStore(); + const f = retrievalFixture(backing, { + limits: { maxIndexPartitionRows: 2 }, + }); + await f.setupCollection(); + await f.publishedArticle( + "article/export", + "collection/workshop", + retrievalGuides[0]!.draft, + ); + const before = await allKnowledgeRows(backing); + const status = await f.repair("article/export"); + expect(status).toMatchObject({ + articleId: "article/export", + status: "blocked", + indexed: false, + reason: "capacity", + }); + expect( + await f.app.getArticleIndexStatus(indexAdministrator, { + articleId: "article/export", + }), + ).toMatchObject({ + status: "blocked", + indexed: false, + reason: "capacity", + }); + expect(await allKnowledgeRows(backing)).toEqual(before); + expect( + ( + await f.app.getPublishedArticle(customer, { + articleId: "article/export", + }) + ).title, + ).toBe(retrievalGuides[0]!.draft.title); + }, 30_000); + + it("replaces a withdrawn policy epoch only after approving a revision under the new audience", async () => { + const f = retrievalFixture(createStore()); + await f.setupCollection(); + const old = await f.publishGuide(); + const before = await f.app.getCollection(admin, { + collectionId: "collection/workshop", + }); + for (const enabled of [false, true]) { + const preview = await f.authoringApp.previewCollectionPolicy(admin, { + collectionId: "collection/workshop", + uses: enabled + ? { + portal: { + enabled: true, + audience: { + kind: "permission", + permission: "workshop.customer", + }, + }, + bot: { + enabled: true, + audience: { + kind: "permission", + permission: "workshop.customer", + }, + }, + } + : { portal: { enabled: false }, bot: { enabled: false } }, + }); + await f.authoringApp.updateCollectionPolicy(admin, { + ...f.command("new-policy-epoch", preview.generation), + collectionId: "collection/workshop", + preview: preview.preview, + }); + expect( + (await f.app.searchPublishedArticles(customer, f.portalInput())) + .articles, + ).toEqual([]); + expect(await f.repair("article/export")).toMatchObject({ + status: "ready", + indexed: false, + }); + } + await f.authoringApp.updateDraft(author, { + ...f.command("reapprove-policy", old.current.generation), + articleId: "article/export", + collectionId: "collection/workshop", + draft: retrievalGuides[0]!.draft, + }); + let current = await f.app.getDraft(author, { + articleId: "article/export", + }); + current = (await f.submitEvidence(current)).current; + await f.publish(current); + expect(await f.repair("article/export")).toMatchObject({ + status: "ready", + indexed: true, + }); + const visible = await f.app.searchPublishedArticles( + customer, + f.portalInput(), + ); + expect(visible.articles).toHaveLength(1); + expect(visible.articles[0]?.revision).toBe(2); + expect( + ( + await f.app.getCollection(admin, { + collectionId: "collection/workshop", + }) + ).collection.policy.version, + ).toBeGreaterThan(before.collection.policy.version); + }, 30_000); + + it("removes one article's shared-term postings without removing another approved guide", async () => { + const f = retrievalFixture(createStore()); + await f.setupCollection(); + const first = await f.publishGuide({ + ...retrievalGuides[0]!, + id: "article/export-a", + }); + await f.publishGuide({ ...retrievalGuides[0]!, id: "article/export-b" }); + await f.authoringApp.retireArticle(indexAdministrator, { + ...f.command("remove-shared-term", first.current.generation), + articleId: "article/export-a", + }); + expect(await f.repair("article/export-a")).toMatchObject({ + status: "ready", + indexed: false, + }); + expect( + ( + await f.app.searchPublishedArticles(customer, f.portalInput()) + ).articles.map((entry) => entry.articleId), + ).toEqual(["article/export-b"]); + }, 30_000); + + it("persists resumable pending work when one maintenance batch is allowed", async () => { + const backing = createStore(); + const f = retrievalFixture(backing, { + limits: { maxMaintenanceBatches: 1 }, + }); + await f.setupCollection(); + await f.publishedArticle( + "article/export", + "collection/workshop", + retrievalGuides[0]!.draft, + ); + f.clearObservations(); + const pending = await f.app.repairArticleIndex(indexAdministrator, { + articleId: "article/export", + }); + expect(pending.status).toBe("pending"); + const indexTransactions = f.traced.transactions.filter( + (call) => call.collection === "knowledge-base.retrieval.v1", + ); + const advances = indexTransactions.filter((call) => + call.partition.startsWith("scope:"), + ); + expect(advances).toHaveLength(1); + const postingHeads = advances + .flatMap((call) => + call.actions.map((action) => + action.action === "delete" + ? action.key.id + : (action.value as { readonly id: string }).id, + ), + ) + .filter((id) => id.startsWith("posting:")); + expect(postingHeads.length).toBeGreaterThan(0); + expect(postingHeads.length).toBeLessThanOrEqual(2); + // One fresh plan, directory registration and catalog registration accompany + // the bounded scope advance; they do not each consume another term batch. + for (const family of ["article:", "catalog:", "scope:", "directory"]) + expect( + indexTransactions.filter((call) => call.partition.startsWith(family)) + .length, + ).toBeLessThanOrEqual(1); + expect(indexTransactions).toHaveLength(f.traced.transactions.length); + expect(indexTransactions.length).toBeLessThanOrEqual(4); + expect( + indexTransactions.every((call) => call.actions.length <= 100), + ).toBe(true); + expect(f.traced.enumerations).toEqual([]); + const recovered = retrievalFixture(backing); + expect(await recovered.repair("article/export")).toMatchObject({ + status: "ready", + indexed: true, + }); + expect( + ( + await recovered.app.searchPublishedArticles( + customer, + recovered.portalInput(), + ) + ).articles[0]?.articleId, + ).toBe("article/export"); + }, 30_000); + + it.each(["article", "collection"] as const)( + "reports blocked capacity when an existing authoritative %s partition exceeds a recomposed instance limit", + async (resource) => { + const backing = createStore(); + const f = retrievalFixture(backing); + await f.setupCollection(); + if (resource === "collection") { + for (let count = 0; count < 4; count += 1) { + const configuration = await f.app.getGovernanceConfiguration( + admin, + { + collectionId: "collection/workshop", + }, + ); + await f.authoringApp.putGovernanceConfiguration(admin, { + ...f.command( + "grow-authoritative-history", + configuration.generation, + ), + collectionId: configuration.collectionId, + configuration: configuration.configuration, + }); + } + } + let current = await f.createDraft( + "article/export", + "collection/workshop", + retrievalGuides[0]!.draft, + ); + current = await f.setSources(current, [ + { + id: "source/private", + system: "synthetic-support", + resourceId: "PRIVATE_CAPACITY_SOURCE", + version: "1", + }, + ]); + current = (await f.submitEvidence(current)).current; + await f.publish(current); + expect(await f.repair(current.articleId)).toMatchObject({ + status: "ready", + indexed: true, + }); + const before = await allKnowledgeRows(backing); + const articleRows = before.filter( + (row) => row.resourceKind === "article", + ).length; + if (resource === "collection") + expect( + before.filter((row) => row.resourceKind === "collection").length, + ).toBeGreaterThan(articleRows); + const limited = createKnowledgeBaseApplication({ + store: backing, + clock: { now: () => at(600_000) }, + privateSources: f.privateSources, + limits: { + maxPhysicalRows: articleRows - (resource === "article" ? 1 : 0), + controlReserveRows: 0, + }, + retrieval: { tokenCounter: { count: countSyntheticTokens } }, + }); + expect( + await limited.repairArticleIndex(indexAdministrator, { + articleId: current.articleId, + }), + ).toMatchObject({ + status: "blocked", + indexed: false, + reason: "capacity", + }); + expect( + await limited.getArticleIndexStatus(indexAdministrator, { + articleId: current.articleId, + }), + ).toMatchObject({ + status: "blocked", + indexed: false, + reason: "capacity", + }); + expect(await allKnowledgeRows(backing)).toEqual(before); + }, + 30_000, + ); + + it("cannot let a delayed old repair restore retired knowledge", async () => { + const backing = createStore(); + const f = retrievalFixture(backing); + await f.setupCollection(); + const published = await f.publishedArticle( + "article/export", + "collection/workshop", + retrievalGuides[0]!.draft, + ); + const gate = barrier(); + let paused = false; + f.traced.intercept(async (trace, commit) => { + if ( + !paused && + trace.collection === "knowledge-base.retrieval.v1" && + trace.partition.startsWith("scope:") + ) { + paused = true; + await gate.wait(); + } + return commit(); + }); + const pending = f.app + .repairArticleIndex(indexAdministrator, { articleId: "article/export" }) + .then( + (value) => ({ value }), + (error: unknown) => ({ error }), + ); + try { + await Promise.race([ + gate.reached, + pending.then(() => { + throw new Error( + "Repair did not reach its scope transaction barrier", + ); + }), + ]); + await f.authoringApp.retireArticle(indexAdministrator, { + ...f.command("retire-during-repair", published.current.generation), + articleId: "article/export", + }); + const newer = retrievalFixture(backing); + expect(await newer.repair("article/export")).toMatchObject({ + status: "ready", + indexed: false, + }); + } finally { + gate.release(); + } + await pending; + f.traced.intercept(undefined); + expect(await f.repair("article/export")).toMatchObject({ + status: "ready", + indexed: false, + }); + expect( + (await f.app.searchPublishedArticles(customer, f.portalInput())) + .articles, + ).toEqual([]); + }, 30_000); + + it("rejects physical repair page limits beyond the configured or hard scan bound", async () => { + const f = retrievalFixture(createStore(), { + limits: { maxRepairScanRows: 3 }, + }); + for (const limit of [0, 4, 1_001, 1.5]) + await expect( + f.app.repairRetrievalPage(indexAdministrator, { limit }), + ).rejects.toBeInstanceOf(TypeError); + expect(f.traced.enumerations).toEqual([]); + }); + }); +} diff --git a/tests/retrieval-review-regressions.test.ts b/tests/retrieval-review-regressions.test.ts new file mode 100644 index 0000000..4dd7004 --- /dev/null +++ b/tests/retrieval-review-regressions.test.ts @@ -0,0 +1,270 @@ +import type { KnowledgeCandidateHint } from "@pegma/knowledge-base-application"; +import { knowledgePermissions } from "@pegma/knowledge-base-contracts"; +import type { TransactionOutcome } from "@pegma/storage-core"; +import { describe, expect, it, vi } from "vitest"; +import { access, admin } from "../test/application-fixtures.js"; +import { storeFactories } from "../test/application-stores.js"; +import { + allRetrievalRows, + botCustomer, + indexAdministrator, + realBotHints, + retrievalApplicability, + retrievalFixture, + retrievalGuides, +} from "../test/retrieval-fixtures.js"; + +function adapterPage(hints: readonly KnowledgeCandidateHint[]) { + return { + hints, + nextCursor: null, + work: { + keyedReads: 1, + physicalRows: 1, + postingEntries: hints.length, + pagesRead: 1, + }, + }; +} + +for (const [name, createStore] of storeFactories) { + describe(`retrieval PR review regressions (${name})`, () => { + it.each([1, 2])( + "preserves adapter relevance order with %i authoritative confirmations and tied local scores", + async (confirmations) => { + const backing = createStore(); + const seed = retrievalFixture(backing); + await seed.setupCollection(); + for (const id of ["article/a-export", "article/z-export"]) + await seed.publishGuide({ ...retrievalGuides[0]!, id }); + const hints = await realBotHints(backing); + const rankedIds = ["article/z-export", "article/a-export"]; + const ranked = rankedIds.map((id) => + hints.find((hint) => hint.articleId === id)!, + ); + expect(ranked.every((hint) => hint !== undefined)).toBe(true); + const search = vi.fn(async () => adapterPage(ranked)); + const f = retrievalFixture(backing, { + candidateAdapter: { search }, + limits: { maxConfirmations: confirmations }, + }); + const result = await f.app.retrieveAnswerSources( + botCustomer, + f.botInput(), + ); + expect(search).toHaveBeenCalledTimes(1); + expect( + result.sources.map((source) => source.reference.articleId), + ).toEqual(rankedIds.slice(0, confirmations)); + }, + 30_000, + ); + + it("uses an adapter's approved body match without requiring title, summary or tag overlap", async () => { + const backing = createStore(); + const seed = retrievalFixture(backing); + await seed.setupCollection(); + const guide = { + ...retrievalGuides[0]!, + draft: { + ...retrievalGuides[0]!.draft, + content: { + format: "plain_text" as const, + text: "Choose the orchid switch before downloading the export.", + }, + }, + }; + await seed.publishGuide(guide); + for (const text of [ + guide.draft.title, + guide.draft.summary, + ...guide.draft.tags, + ]) + expect(text.toLowerCase()).not.toContain("orchid"); + expect( + ( + await seed.app.retrieveAnswerSources( + botCustomer, + seed.botInput("orchid"), + ) + ).sources, + ).toEqual([]); + const hint = (await realBotHints(backing))[0]!; + const f = retrievalFixture(backing, { + candidateAdapter: { search: async () => adapterPage([hint]) }, + }); + const result = await f.app.retrieveAnswerSources( + botCustomer, + f.botInput("orchid"), + ); + expect(result.sources).toHaveLength(1); + expect(result.sources[0]?.content).toEqual(guide.draft.content); + }, 30_000); + + it("does not let a healthy same-plan losing CAS worker block the winner's progress", async () => { + const backing = createStore(); + const loser = retrievalFixture(backing, { + limits: { maxMaintenanceBatches: 1 }, + }); + await loser.setupCollection(); + await loser.publishedArticle("article/export", "collection/workshop", { + ...retrievalGuides[0]!.draft, + title: + "Export amber bronze copper denim emerald flax granite hazel ivory jade khaki lilac mauve navy ochre peach quartz", + }); + const winner = retrievalFixture(backing, { + limits: { maxMaintenanceBatches: 1 }, + }); + const outcomes: TransactionOutcome[] = []; + loser.traced.intercept(async (trace, commit) => { + if ( + trace.collection === "knowledge-base.retrieval.v1" && + trace.partition.startsWith("scope:") + ) { + const progress = await winner.app.repairArticleIndex( + indexAdministrator, + { articleId: "article/export" }, + ); + expect(progress.status).toBe("pending"); + const outcome = await commit(); + outcomes.push(outcome); + return outcome; + } + return commit(); + }); + const result = await loser.app.repairArticleIndex(indexAdministrator, { + articleId: "article/export", + }); + loser.traced.intercept(undefined); + expect(outcomes).toHaveLength(3); + expect(outcomes.every((outcome) => !outcome.committed)).toBe(true); + expect(result).toMatchObject({ status: "pending", indexed: false }); + const progress = (await allRetrievalRows(backing)).find( + (row) => row.kind === "article", + ); + expect(progress?.data).toMatchObject({ status: "pending" }); + expect( + await retrievalFixture(backing).repair("article/export"), + ).toMatchObject({ status: "ready", indexed: true }); + }, 30_000); + + it.each([ + ["retained targets", { maxIndexPartitionRows: 2 }], + ["minimal marker", { maxTermsPerArticle: 1 }], + ] as const)( + "reassesses a blocked %s after policy withdrawal without changing the article head", + async (_label, limits) => { + const backing = createStore(); + const f = retrievalFixture(backing, { limits }); + await f.setupCollection(); + const published = await f.publishedArticle( + "article/export", + "collection/workshop", + retrievalGuides[0]!.draft, + ); + expect(await f.repair("article/export")).toMatchObject({ + status: "blocked", + indexed: false, + reason: "capacity", + }); + expect( + await f.app.getArticleIndexStatus(indexAdministrator, { + articleId: "article/export", + }), + ).toMatchObject({ + status: "blocked", + indexed: false, + reason: "capacity", + }); + const preview = await f.authoringApp.previewCollectionPolicy(admin, { + collectionId: "collection/workshop", + uses: { portal: { enabled: false }, bot: { enabled: false } }, + }); + await f.authoringApp.updateCollectionPolicy(admin, { + ...f.command("withdraw-blocked-policy", preview.generation), + collectionId: "collection/workshop", + preview: preview.preview, + }); + expect( + (await f.app.getDraft(admin, { articleId: "article/export" })) + .generation, + ).toBe(published.current.generation); + expect( + await f.app.getArticleIndexStatus(indexAdministrator, { + articleId: "article/export", + }), + ).toMatchObject({ status: "pending", indexed: false }); + expect(await f.repair("article/export")).toMatchObject({ + status: "ready", + indexed: false, + }); + }, + 30_000, + ); + + it("supports explicitly approved anonymous portal and bot policy then rejects revoked stale hints", async () => { + const f = retrievalFixture(createStore()); + await f.setupCollection(); + const preview = await f.authoringApp.previewCollectionPolicy(admin, { + collectionId: "collection/workshop", + uses: { + portal: { enabled: true, audience: { kind: "anonymous" } }, + bot: { enabled: true, audience: { kind: "anonymous" } }, + }, + }); + await f.authoringApp.updateCollectionPolicy(admin, { + ...f.command("approved-public-policy", preview.generation), + collectionId: "collection/workshop", + preview: preview.preview, + approvePublic: true, + }); + await f.publishGuide(); + const outsider = access("visitor/public", [ + knowledgePermissions.articleRead, + knowledgePermissions.botRead, + ]); + expect( + (await f.app.listPortalCollections(outsider, {})).collections, + ).toContainEqual( + expect.objectContaining({ collectionId: "collection/workshop" }), + ); + expect( + (await f.app.searchPublishedArticles(outsider, f.portalInput())) + .articles, + ).toHaveLength(1); + const answer = await f.app.retrieveAnswerSources(outsider, f.botInput()); + expect(answer.sources).toHaveLength(1); + expect(answer.sources[0]?.citation.portalArticle).toEqual({ + articleId: "article/export", + revision: 1, + }); + const withdrawn = await f.authoringApp.previewCollectionPolicy(admin, { + collectionId: "collection/workshop", + uses: { portal: { enabled: false }, bot: { enabled: false } }, + }); + await f.authoringApp.updateCollectionPolicy(admin, { + ...f.command("withdraw-public-policy", withdrawn.generation), + collectionId: "collection/workshop", + preview: withdrawn.preview, + }); + expect( + (await f.app.listPortalCollections(outsider, {})).collections, + ).toEqual([]); + expect( + (await f.app.searchPublishedArticles(outsider, f.portalInput())) + .articles, + ).toEqual([]); + expect( + (await f.app.retrieveAnswerSources(outsider, f.botInput())).sources, + ).toEqual([]); + expect( + ( + await f.app.confirmAnswerSources(outsider, { + references: answer.sources.map((source) => source.reference), + applicability: retrievalApplicability, + }) + ).sources, + ).toEqual([]); + }, 30_000); + }); +} diff --git a/tests/retrieval.test.ts b/tests/retrieval.test.ts new file mode 100644 index 0000000..29cc1db --- /dev/null +++ b/tests/retrieval.test.ts @@ -0,0 +1,323 @@ +import { knowledgePermissions } from "@pegma/knowledge-base-contracts"; +import { describe, expect, it } from "vitest"; +import { + access, + admin, + author, + customer, + draft, +} from "../test/application-fixtures.js"; +import { storeFactories } from "../test/application-stores.js"; +import { + botCustomer, + retrievalApplicability, + retrievalFixture, + retrievalGuides, + unsupportedRetrievalQuestion, +} from "../test/retrieval-fixtures.js"; + +for (const [name, createStore] of storeFactories) { + describe(`approved lexical retrieval (${name})`, () => { + it("finds representative title/tag paraphrases and returns a safe known no-result", async () => { + const f = retrievalFixture(createStore()); + await f.corpus(); + for (const guide of retrievalGuides) { + for (const query of guide.questions) { + const result = await f.app.searchPublishedArticles( + customer, + f.portalInput(query), + ); + expect(result.outcome).toBe("results"); + expect(result.articles[0]?.articleId).toBe(guide.id); + } + } + expect( + await f.app.searchPublishedArticles( + customer, + f.portalInput(unsupportedRetrievalQuestion), + ), + ).toEqual({ outcome: "no_result", articles: [] }); + }, 30_000); + + it("uses bot-only knowledge without portal browsing or a browse citation", async () => { + const f = retrievalFixture(createStore()); + await f.setupCollection("collection/bot-only", false); + await f.publishGuide(retrievalGuides[0], "collection/bot-only"); + expect( + await f.app.searchPublishedArticles(customer, { + ...f.portalInput(), + collectionId: "collection/bot-only", + }), + ).toEqual({ outcome: "no_result", articles: [] }); + expect( + (await f.app.listPortalCollections(customer, {})).collections, + ).not.toContainEqual( + expect.objectContaining({ collectionId: "collection/bot-only" }), + ); + const answer = await f.app.retrieveAnswerSources(botCustomer, { + ...f.botInput(), + collectionIds: ["collection/bot-only"], + }); + expect(answer.sources).toHaveLength(1); + expect(answer.sources[0]?.citation.label).toBe( + retrievalGuides[0]!.draft.title, + ); + expect(answer.sources[0]?.citation).not.toHaveProperty("portalArticle"); + }, 30_000); + + it("excludes draft-only content and preserves the old publication after a draft move", async () => { + const f = retrievalFixture(createStore()); + await f.setupCollection(); + await f.createDraft("article/draft-only", "collection/workshop", { + ...draft(), + title: "UNAPPROVED_DRAFT_CANARY", + tags: ["unpublishedcanary"], + }); + await f.repair("article/draft-only"); + expect( + ( + await f.app.searchPublishedArticles( + customer, + f.portalInput("unpublishedcanary"), + ) + ).articles, + ).toEqual([]); + const published = await f.publishGuide(); + await f.setupCollection("collection/bot-only", false); + await f.app.updateDraft(author, { + ...f.command("move-unapproved", published.current.generation), + articleId: "article/export", + collectionId: "collection/bot-only", + draft: { + ...draft(), + title: "UNAPPROVED_NEW_TITLE", + content: { format: "plain_text", text: "UNAPPROVED_NEW_BODY" }, + tags: ["unpublishedcanary"], + }, + }); + const result = await f.app.searchPublishedArticles( + customer, + f.portalInput(), + ); + expect(result.articles[0]).toMatchObject({ + articleId: "article/export", + collectionId: "collection/workshop", + revision: 1, + title: retrievalGuides[0]!.draft.title, + }); + expect(JSON.stringify(result)).not.toContain("UNAPPROVED"); + }, 30_000); + + it("requires the exact product, version, build and locale tuple", async () => { + const f = retrievalFixture(createStore()); + await f.setupCollection(); + await f.publishGuide(); + for (const field of [ + "productId", + "productVersion", + "buildId", + "locale", + ] as const) { + const applicability = { ...retrievalApplicability, [field]: "other" }; + expect( + ( + await f.app.searchPublishedArticles(customer, { + ...f.portalInput(), + applicability, + }) + ).articles, + ).toEqual([]); + expect( + ( + await f.app.retrieveAnswerSources(botCustomer, { + ...f.botInput(), + applicability, + }) + ).sources, + ).toEqual([]); + } + }, 30_000); + + it("does not widen a missing customer audience with broad service permissions", async () => { + const f = retrievalFixture(createStore()); + await f.setupCollection(); + await f.publishGuide(); + const wrongAudience = access( + "service/broad", + Object.values(knowledgePermissions), + ); + expect( + (await f.app.listPortalCollections(wrongAudience, {})).collections, + ).toEqual([]); + expect( + (await f.app.searchPublishedArticles(wrongAudience, f.portalInput())) + .articles, + ).toEqual([]); + expect( + (await f.app.retrieveAnswerSources(wrongAudience, f.botInput())) + .sources, + ).toEqual([]); + }, 30_000); + + it.each(["policy", "source", "evidence"] as const)( + "lets current %s withdrawal defeat stale hints and previously returned source references", + async (withdrawal) => { + const f = retrievalFixture(createStore()); + await f.setupCollection(); + let current = await f.createDraft( + "article/export", + "collection/workshop", + retrievalGuides[0]!.draft, + ); + if (withdrawal === "source") + current = await f.setSources(current, [ + { + id: "source/private", + system: "synthetic-support", + resourceId: "PRIVATE_SOURCE_CANARY", + version: "1", + }, + ]); + current = (await f.submitEvidence(current)).current; + current = (await f.publish(current)).current; + await f.repair(current.articleId); + const answer = await f.app.retrieveAnswerSources( + botCustomer, + f.botInput(), + ); + expect(answer.sources).toHaveLength(1); + if (withdrawal === "source") f.trust.canPublishSource = false; + else if (withdrawal === "policy") { + const preview = await f.app.previewCollectionPolicy(admin, { + collectionId: "collection/workshop", + uses: { portal: { enabled: false }, bot: { enabled: false } }, + }); + await f.app.updateCollectionPolicy(admin, { + ...f.command("withdraw-policy", preview.generation), + collectionId: "collection/workshop", + preview: preview.preview, + }); + } else { + const proof = ( + await f.app.getEvidence(admin, { articleId: current.articleId }) + ).evidence[0]!; + await f.app.revokeEvidence(admin, { + ...f.command("withdraw-proof", current.generation), + articleId: current.articleId, + articleRevision: proof.articleRevision, + evidenceId: proof.id, + evidenceVersion: proof.version, + evidenceHash: proof.hash, + reason: "Synthetic proof withdrawal", + }); + } + expect( + (await f.app.searchPublishedArticles(customer, f.portalInput())) + .articles, + ).toEqual([]); + expect( + (await f.app.retrieveAnswerSources(botCustomer, f.botInput())) + .sources, + ).toEqual([]); + expect( + ( + await f.app.confirmAnswerSources(botCustomer, { + references: answer.sources.map((entry) => entry.reference), + applicability: retrievalApplicability, + }) + ).sources, + ).toEqual([]); + }, + 30_000, + ); + + it("returns safe exact citations and reconfirms them instead of trusting an earlier answer payload", async () => { + const f = retrievalFixture(createStore()); + await f.setupCollection(); + const published = await f.publishGuide(); + const answer = await f.app.retrieveAnswerSources( + botCustomer, + f.botInput(), + ); + expect(answer.sources).toHaveLength(1); + expect(answer.sources[0]?.citation.portalArticle).toEqual({ + articleId: "article/export", + revision: 1, + }); + const references = answer.sources.map((entry) => entry.reference); + expect( + ( + await f.app.confirmAnswerSources(botCustomer, { + references, + applicability: retrievalApplicability, + }) + ).sources, + ).toEqual(answer.sources); + expect(JSON.parse(answer.serializedSources)).toEqual(answer.sources); + for (const secret of [ + "PRIVATE_STAFF_EVIDENCE", + "runner/staging", + "staff/verifier", + "reviewerId", + "attestation", + "provenance", + "createdBy", + ]) + expect(answer.serializedSources).not.toContain(secret); + await f.app.updateDraft(author, { + ...f.command("new-draft-turn-fence", published.current.generation), + articleId: "article/export", + collectionId: "collection/workshop", + draft: { ...retrievalGuides[0]!.draft, title: "New unapproved title" }, + }); + expect( + ( + await f.app.confirmAnswerSources(botCustomer, { + references, + applicability: retrievalApplicability, + }) + ).sources, + ).toEqual([]); + }, 30_000); + + it("keeps independently composed stores isolated even for matching article and collection IDs", async () => { + const first = retrievalFixture(createStore()); + const second = retrievalFixture(createStore()); + await first.setupCollection(); + await second.setupCollection(); + await first.publishGuide(); + expect( + ( + await second.app.searchPublishedArticles( + customer, + second.portalInput(), + ) + ).articles, + ).toEqual([]); + expect( + (await second.app.retrieveAnswerSources(botCustomer, second.botInput())) + .sources, + ).toEqual([]); + }, 30_000); + + it("uses deterministic article ordering for equal approved title/tag scores", async () => { + const f = retrievalFixture(createStore()); + await f.setupCollection(); + for (const id of ["article/z-export", "article/a-export"]) + await f.publishGuide({ ...retrievalGuides[0]!, id }); + const first = await f.app.searchPublishedArticles( + customer, + f.portalInput(), + ); + const second = await f.app.searchPublishedArticles( + customer, + f.portalInput(), + ); + expect(first.articles.map((entry) => entry.articleId)).toEqual([ + "article/a-export", + "article/z-export", + ]); + expect(second).toEqual(first); + }, 30_000); + }); +}