Repository navigation
feat(knowledge-pgvector): run one leg or both by the search's retrieval mode; report the three modes, hybrid by default - #38745
Conversation
…AdapterSearchOptions.retrieval (wip)
…or leg by a passage's own text
…al mode; report the three modes, hybrid by default
Claude-Session: https://claude.ai/code/session_01JQwxbaASqBozmmj1n5tbUf Co-authored-by: Claude <noreply@anthropic.com>
…ectstack-ai/objectstack into claude/project-thread-vj79kz-pgvector
…e its per-search refusal code ADR-0161's K2 row on the adapter surface no longer says "no hybrid toggle": the contract carries the modes an adapter runs and the mode a search runs in, which a source declares. Protocol doc 7.1 says the same. The contract doc of AdapterSearchOptions.retrieval names the refusal of a mode the adapter does not list: SERVICE_UNAVAILABLE in a search's refused, VALIDATION_ERROR at save and registration. Claude-Session: https://claude.ai/code/session_01JQwxbaASqBozmmj1n5tbUf Co-authored-by: Claude <noreply@anthropic.com>
…ectstack-ai/objectstack into claude/project-thread-vj79kz-pgvector
…e; count the new isomorphic pin The knowledge source form's Search group and its Retrieval mode select get their translation bundle entries, translated in the ten locales, and the ADR-0122 pin count moves 880 -> 881 for KnowledgeRetrievalModeSchema. Claude-Session: https://claude.ai/code/session_01JQwxbaASqBozmmj1n5tbUf Co-authored-by: Claude <noreply@anthropic.com>
…ed metadata-form catalog Claude-Session: https://claude.ai/code/session_01JQwxbaASqBozmmj1n5tbUf Co-authored-by: Claude <noreply@anthropic.com>
…ition into any statement Claude-Session: https://claude.ai/code/session_01JQwxbaASqBozmmj1n5tbUf Co-authored-by: Claude <noreply@anthropic.com>
…e; regenerate the spec artifacts after the merge of main The merge of main had left the ai shards of the generated spec artifacts without main's TurnEnd rows; check:generated --fix rewrites them from a fresh build. Claude-Session: https://claude.ai/code/session_01JQwxbaASqBozmmj1n5tbUf Co-authored-by: Claude <noreply@anthropic.com>
…to claude/project-thread-vj79kz-pgvector
…-vj79kz-pgvector # Conflicts: # content/docs/protocol/knowledge.mdx # packages/plugins/knowledge-pgvector/src/pgvector-adapter.ts
📓 Docs Drift Check2 anchor(s) derived from 1 changed package(s); no hand-written page names any of them. What this run could not see
Coarse fallback — 3 page(s) merely mention a changed package (the pre-#9192 predicate, kept for the deliberately-wide backstop): Which tree this was computed onThis run read A worktree cut from an older # while this PR is open — GitHub drops the merge commit once it closes
git fetch origin f0518d8aee06f6e7720e269ab9871051a998522b && git checkout f0518d8aee06f6e7720e269ab9871051a998522b
# afterwards, rebuild it from the two parents, which stay fetchable
git fetch origin f576dee5816597cfe3aa044a3f6020754c48327b 6707107d1680f0965c67e9805130810f6ab98573 && git checkout -B drift-repro f576dee5816597cfe3aa044a3f6020754c48327b && git merge --no-ff 6707107d1680f0965c67e9805130810f6ab98573
node scripts/docs-audit/affected-docs.mjs --json f576dee5816597cfe3aa044a3f6020754c48327b |
|
repo:objectstack#2 · os-warren · session_01JQwxbaASqBozmmj1n5tbUf Check Changeset is red because of the stack, not this PR's own change. This branch is stacked on #38720, and the gate diffs against Generated by Claude Code |
…mode form ship as a patch Claude-Session: https://claude.ai/code/session_01JQwxbaASqBozmmj1n5tbUf Co-authored-by: Claude <noreply@anthropic.com>
…ectstack-ai/objectstack into claude/project-thread-vj79kz-pgvector
…into claude/project-thread-vj79kz-pgvector
|
repo:objectstack#2 · os-warren · session_01JQwxbXyLoBzNYY1U8SNPFu Contract-review-claim: session_01JQwxbXyLoBzNYY1U8SNPFu · head a78b4c4 · 2026-11-30T13:41Z |
|
repo:objectstack#2 · os-warren · session_01JQwxbXyLoBzNYY1U8SNPFu Contract reviewServed-tier: PR #38745, ① Derived judgments
Tests: ② Semver level
③ Boundary flags
Implemented-by: VERDICT: FAIL One must-fix: the |
A mode outside the store's list ran both legs on the one-leg scale; it is now refused (400 VALIDATION_ERROR) before anything is embedded or read. The exported adapter's capabilities grow a member, so the changeset says Clause-② yes (widening). The README's keyword-index sentence says a vector search does not build a missing index. Claude-Session: https://claude.ai/code/session_01JQwxbaASqBozmmj1n5tbUf Co-authored-by: Claude <noreply@anthropic.com>
|
repo:objectstack#2 · os-warren · session_01JQwxbXyLoBzNYY1U8SNPFu Contract-review-claim: session_01JQwxbXyLoBzNYY1U8SNPFu · head 6707107 · 2026-11-30T14:07Z |
|
repo:objectstack#2 · os-warren · session_01JQwxbXyLoBzNYY1U8SNPFu Contract reviewServed-tier: Delta round on PR #38745 ( ① Derived judgments
② Semver level
③ Boundary flags
Implemented-by: VERDICT: PASS |
|
repo:objectstack#2 · os-warren · session_01JQwxbXyLoBzNYY1U8SNPFu 维护者速读
席位核对ACCEPT · L1 · area o2-A · Head-sha
|
…ta-scoped search, through a GIN index on metadata (objectstack-ai#38758) <!-- claude-projects-attribution: {"github_login":"os-steve"} --> _Requested by **Steve** · [project thread](https://claude.ai/code/project/chan_01FdL1XeUyvVNxLreh3F4Qi9?thread=cmsg_01FdL1XeUyvVNxLreh3F4Qi9BSi9ocXhcrBSeFbQv8dAV4)_ Fixes objectstack-ai#38747 Clause-②: no Metadata-protocol: none ## 维护者速读 - 用户能看到什么变化:自建 PostgreSQL 上按单位范围检索知识库时,数据库先取出范围内的条款再算相似度,不再把全部条款都算一遍;种子表上向量这一路从约 300 毫秒降到约 2 毫秒,检索结果不变。 - 为什么做:知识库检索提速专题的第一项,替首家客户(政策问答,总是按提问人所在单位范围检索)解决带范围检索和不带范围一样慢、并发时超时的问题。 - 出错会怎样:碰到的是带单位范围检索的用户;数据库账号没有建索引权限时,检索不会被拒绝,照旧慢速返回同样的结果,并在日志里记一条警告、写明要执行的建索引语句;回退本合并即可撤回,已建的索引留着无害。 - 要你做什么:无。 This PR lands on its own once reviewed; it no longer waits for objectstack-ai#38745 (the retrieval-mode PR that edits the same file's `search()` legs; maintainer ruling 2026-11-30 12:02:57Z). `overlap-check` reads the two as merging cleanly in either order. ## What changes - **`sql.ts`** — a GIN index on `metadata` with `jsonb_path_ops`, `knowledge_vec_dWIDTH_metadata`, added to the passage table's DDL beside the other three indexes (`metadataIndexDdl`, `metadataIndexName`). `metadataScopeForms(field, ids)` returns the containment values of one scope term as JSON text: per id, `{field: "id"}` and `{field: ["id"]}`, and, when the id is how PostgreSQL prints a `numeric` (optional minus, no leading zero, optional fraction, no exponent), `{field: id}` and `{field: [id]}` as numbers. - **`pgvector-adapter.ts`, the metadata scope-term block** — each `metadata` term is now `(metadata @> ANY($N::jsonb[]) AND EXACT)`, where `EXACT` is today's predicate byte for byte (the `jsonb_array_elements` EXISTS) and `$N` binds the forms above. The containment is a superset of the exact match (card What 3: "Keep today's exact predicate as a recheck ANDed with the containment disjunction"), so results cannot change; the recheck is required, not decorative: containment compares numbers by value, so `{"unit": 1.5}` contains a stored `1.50` whose text the exact match compares as `1.50`. The one `inScope` string still feeds the `vec` CTE, the `cand` CTE and the `stats` count, so all three read through the index. - `@> ANY(jsonb[])` is one bound parameter per term rather than an explicit `OR` of 2-4 parameters per id: the planner runs it as one Bitmap Index Scan over the array (plan below), and a term at the contract's bound (500 ids) stays one parameter instead of up to 2,000. - **`bench/instrument.test.mjs`** — the one params pin at :189 (claim amendment, seat 11:32Z) now lists the containment-forms array this change binds as `$5`, and asserts the WHERE carries `metadata @> ANY($5::jsonb[])`. No other line in that file changes, so the comment above it still names only the ids and the field. - **`pgvector-adapter.ts`, `ensureMetadataIndex`** — the existing-table path (card What 1), the twin of `ensureKeywordIndex`, called from the scope-term block when a search holds a `metadata` term. It looks the index up with `to_regclass` first and creates it only when absent. ### Existing tables: does the DDL path already run, and what the first time costs - `vectorTableDdl` runs from `ensureVectorTable`, which is reached only by `upsert` and `beginBuild`, and is skipped for the life of the process once any search has found the table (`tableExists` fills the same `tables` set). So a process whose first touch of a width is a search would never run the DDL: a table made by an earlier release would stay without the index until a process happened to write first. That is why the search-time ensure exists, exactly as the keyword index has one. - **Lock:** plain `CREATE INDEX` takes a SHARE lock — reads go on, writes (`upsert`, purge, build pages) wait for the build. Measured here: on 58,500 passages of 1024 dimensions (338 MB table) the build took **32 ms** (index 256 kB), and `ANALYZE` 264 ms (the ensure does not run `ANALYZE`; autovacuum does). The card's acceptance DB measured 0.27 s build and 2.1 s `ANALYZE` with real metadata. - **Why not `CONCURRENTLY`:** an interrupted concurrent build leaves an INVALID index under the name, and `IF NOT EXISTS` then takes it for a made one forever, so scoped searches would silently stay on the sequential scan; it also cannot run inside a transaction block and waits for every older transaction. The table's other three indexes are plain for the same reason. - **Why look up first:** measured on this PG16, `CREATE INDEX IF NOT EXISTS` on an index that already exists still waits for the table lock — with a writer's transaction open it was cancelled by a 800 ms `lock_timeout`, while `to_regclass` answered at once. The lookup keeps the steady state lock-free. - **A role that may not create it** (seat ruling 2026-11-30 11:32Z, option B): the search is **not** refused. `ensureMetadataIndex` records the width in `metadataUnindexed` (the failure twin of `metadataIndexed`), logs ONE `warn` naming the consequence and the full `CREATE INDEX` statement to run as a database owner, and never tries again in that process; the search runs the same statement, which the planner answers by today's sequential scan, so the hits are today's. Once an owner runs the statement, the next search reads through the index with no restart (the statement text does not change). A missing index is a functional degradation, so `warn`, not `error` (AGENTS.md degradation levels). Coded refusals in `src/errors.ts`, `ensureKeywordIndex` and B2's `SET LOCAL statement_timeout` are untouched. ## Before / after: one scoped `vec` statement Seeded table, local PostgreSQL 16.15 + pgvector 0.6.0, `jit = off`: 58,500 passages, 1024 dimensions, `owning_unit` over 350 units (a tenth of the passages list two units), scope `owning_unit = u7` (336 passages hold it, 81 below distance 1). Statement: the adapter's own `vec` CTE, recorded from a real search and re-run under `EXPLAIN (ANALYZE, BUFFERS)`; four runs each. Shared container, so treat absolute milliseconds as indicative. | | plan | execution time (4 runs) | top 5 | |:--|:--|:--|:--| | before (base f782a12, no metadata index) | Seq Scan, 58,420 rows removed by filter | 296.7 / 338.5 / 295.7 / 306.5 ms | c56007, c35707, c3857, c39557, c53557 | | after (this branch) | Bitmap Index Scan on `knowledge_vec_d1024_metadata` | 2.27 / 1.95 / 1.80 / 1.67 ms | c56007, c35707, c3857, c39557, c53557 (same) | In the plans `COSINE_DISTANCE_OP` stands for pgvector's cosine-distance operator and `LESS_THAN` for the less-than sign; the query vector is elided. <details><summary>Before: EXPLAIN (ANALYZE, BUFFERS), run 4</summary> ```text Subquery Scan on vec (cost=113850.70..113850.86 rows=5 width=14) (actual time=306.476..306.483 rows=5 loops=1) Buffers: shared hit=214374 read=40771 -> Limit (cost=113850.70..113850.81 rows=5 width=22) (actual time=306.473..306.479 rows=5 loops=1) Buffers: shared hit=214374 read=40771 InitPlan 1 (returns $0) -> Index Scan using knowledge_generation_active on knowledge_generation g (cost=0.14..8.16 rows=1 width=0) (actual time=0.013..0.013 rows=1 loops=1) Index Cond: (source_id = 'policy'::text) Filter: (generation = 1) Buffers: shared hit=1 read=1 -> WindowAgg (cost=113842.53..114061.91 rows=9750 width=22) (actual time=306.472..306.475 rows=5 loops=1) Buffers: shared hit=214374 read=40771 -> Sort (cost=113842.53..113866.91 rows=9750 width=14) (actual time=306.461..306.463 rows=5 loops=1) Sort Key: ((knowledge_vec_d1024.embedding COSINE_DISTANCE_OP '[QUERY_VECTOR_1024]'::vector)), knowledge_vec_d1024.chunk_id Sort Method: quicksort Memory: 28kB Buffers: shared hit=214374 read=40771 -> Result (cost=0.00..113196.54 rows=9750 width=14) (actual time=5.417..306.362 rows=81 loops=1) One-Time Filter: $0 Buffers: shared hit=214374 read=40771 -> Seq Scan on knowledge_vec_d1024 (cost=0.00..113172.16 rows=9750 width=24) (actual time=5.398..305.971 rows=81 loops=1) Filter: ((source_id = 'policy'::text) AND (generation = 1) AND ((embedding COSINE_DISTANCE_OP '[QUERY_VECTOR_1024]'::vector) LESS_THAN '1'::double precision) AND (SubPlan 2)) Rows Removed by Filter: 58420 Buffers: shared hit=214023 read=40770 SubPlan 2 -> Function Scan on jsonb_array_elements e (cost=0.02..1.89 rows=1 width=0) (actual time=0.001..0.001 rows=0 loops=29101) Filter: (((v #>> '{}'::text[]) = ANY ('{u7}'::text[])) AND (jsonb_typeof(v) = ANY ('{string,number}'::text[]))) Rows Removed by Filter: 1 Planning: Buffers: shared read=1 Planning Time: 0.239 ms Execution Time: 306.523 ms ``` </details> <details><summary>After: EXPLAIN (ANALYZE, BUFFERS), run 4</summary> ```text Subquery Scan on vec (cost=96.94..97.01 rows=2 width=14) (actual time=1.625..1.631 rows=5 loops=1) Buffers: shared hit=1254 -> Limit (cost=96.94..96.99 rows=2 width=22) (actual time=1.624..1.628 rows=5 loops=1) Buffers: shared hit=1254 InitPlan 1 (returns $0) -> Index Scan using knowledge_generation_active on knowledge_generation g (cost=0.14..8.16 rows=1 width=0) (actual time=0.008..0.009 rows=1 loops=1) Index Cond: (source_id = 'policy'::text) Filter: (generation = 1) Buffers: shared hit=2 -> WindowAgg (cost=88.78..88.82 rows=2 width=22) (actual time=1.623..1.626 rows=5 loops=1) Buffers: shared hit=1254 -> Sort (cost=88.78..88.78 rows=2 width=14) (actual time=1.619..1.620 rows=5 loops=1) Sort Key: ((knowledge_vec_d1024.embedding COSINE_DISTANCE_OP '[QUERY_VECTOR_1024]'::vector)), knowledge_vec_d1024.chunk_id Sort Method: quicksort Memory: 28kB Buffers: shared hit=1254 -> Result (cost=21.26..88.77 rows=2 width=14) (actual time=0.108..1.593 rows=81 loops=1) One-Time Filter: $0 Buffers: shared hit=1254 -> Bitmap Heap Scan on knowledge_vec_d1024 (cost=21.26..88.76 rows=2 width=24) (actual time=0.094..1.320 rows=81 loops=1) Recheck Cond: (metadata @> ANY ('{"{\"owning_unit\": \"u7\"}","{\"owning_unit\": [\"u7\"]}"}'::jsonb[])) Filter: ((source_id = 'policy'::text) AND (generation = 1) AND ((embedding COSINE_DISTANCE_OP '[QUERY_VECTOR_1024]'::vector) LESS_THAN '1'::double precision) AND (SubPlan 2)) Rows Removed by Filter: 87 Heap Blocks: exact=168 Buffers: shared hit=902 -> Bitmap Index Scan on knowledge_vec_d1024_metadata (cost=0.00..21.26 rows=12 width=0) (actual time=0.032..0.032 rows=336 loops=1) Index Cond: (metadata @> ANY ('{"{\"owning_unit\": \"u7\"}","{\"owning_unit\": [\"u7\"]}"}'::jsonb[])) Buffers: shared hit=6 SubPlan 2 -> Function Scan on jsonb_array_elements e (cost=0.02..1.89 rows=1 width=0) (actual time=0.002..0.002 rows=1 loops=81) Filter: (((v #>> '{}'::text[]) = ANY ('{u7}'::text[])) AND (jsonb_typeof(v) = ANY ('{string,number}'::text[]))) Planning: Buffers: shared hit=2 Planning Time: 0.243 ms Execution Time: 1.668 ms ``` </details> ## Tests New: `src/__tests__/scope-containment-38747.test.ts` (no database: statement shape and index DDL) and `src/__tests__/scope-containment-38747.live-postgres.test.ts` (live PostgreSQL + pgvector via `live-pg.testkit.ts`). No test reads wall-clock time. Per-shape equivalence (card: "One equivalence test per shape"). Each live case seeds passages of that shape plus controls, runs the real search for each id list, and asserts the hits equal both an explicit expected list and today's exact predicate evaluated in SQL on the same rows, written independently of the adapter: | stored shape | stored values | id lists checked | hits | |:--|:--|:--|:--| | string | `u1`, `u2`, `7`, `U1`, empty string, `1.50` | `u1`; `u1,u2`; `7`; `U1`; `1.5`; `1.50`; `nope` | exactly the equal string; `1.5` holds nothing | | number | `7`, `7.5`, `-3`, `0`, `1e21`, `1.50` (raw), `100` | `7`, `7.5`, `-3`, `0`, `1000000000000000000000`, `1e+21`, `1.50`, `1.5`, `100`, `7.0`, `07`, `1e2`, `+7`, `-0` | only the stored text: `1.50` held by `1.50` not `1.5`; `1e21` by its printed digits; no other spelling | | list of strings | `[u1,u2]`, `[u3]`, `[]` | `u1`; `u2,x`; `u3`; `x` | any equal element | | list of numbers | `[7,8]`, `[1.5]`, `[-3]`, `[1.50,2]` (raw) | `7`; `8,-3`; `1.5`; `1.50`; `2` | any element by stored text | | mixed list | `[7, "u1", null, {id: u2}, true, ["u3"]]` | `7`, `u1`, `u2`, `u3`, `true`, `null` | only the string and number elements | | missing | no `unit` key; `{}` | `u1`, `x` | none | | null | `null` | `null`, `u1` | none (the string `"null"` control holds) | | object | `{id: u1}`, `{u1: true}` | `u1`, `{"id": "u1"}`, `id` | none | | boolean | `true`, `false` | `true`, `false` | none (the string `"true"` control holds) | Plus: a database that refuses the metadata `CREATE INDEX` (live PostgreSQL, the refusal stubbed at the pool so the case needs no role privileges on CI): the scoped search answers the same top 5, ids and scores, as the indexed path for two queries, one `CREATE INDEX` attempt, exactly one warning carrying the statement, index still absent. The same with a REAL role, as a one-off probe outside the suite: a role owning the store's schema and generation table but not the passage table got `must be owner of table knowledge_vec_d384`; both searches answered `p0:1.0000, p15:0.9839, p28:0.9683, p7:0.9531, p22:0.9385`, the indexed top 5; one warning; index absent. And: the vector leg's `EXPLAIN` on 20,000 seeded passages names `Bitmap Index Scan on knowledge_vec_d384_metadata` and no `Seq Scan` (planner left at its defaults, after `ANALYZE`); a table whose metadata index was dropped gets it back at a new process's first metadata-scoped search (a record-scoped search does not make it) and answers as before. Unit: index DDL string; forms for string, number-text, non-number-text, escaping, lone surrogates; the term's text and bound values in `vec`, `cand` and `stats`; union with a record term; no containment for a record-only scope; the ensure runs once and looks up before creating; when the create fails the search still ranks, warns once with the statement, and neither looks up nor creates again. **Counts at head 6f65533:** the two new files hold 12 unit + 12 live cases; package total 165 tests in 18 files, all passing with live PostgreSQL (`OS_EXPECT_LIVE_DIALECT_MATRIX=1`). **Red first / ablations** (both new files, live PG; every mutation through `scripts/ablation-replace.mjs`, restore proven by blob hash and an empty `git diff HEAD`): | leg | result | |:--|:--| | base code (`sql.ts` and the adapter at f782a12, new tests kept) | 13 red: 11 unit + the live EXPLAIN and existing-table cases; the record-only preservation case and the 9 equivalence cases green, as invariance pins must be on the code they are measured against | | recheck neutralised (exact match ORed with TRUE) | 4 red: number, list of numbers, and the two statement-shape pins | | array forms dropped | 7 red: list of strings, mixed list, existing table, 4 unit | | number forms dropped | 5 red: number, list of numbers, mixed list, existing table, 1 unit | | search-time ensure call deleted | 4 red: existing table + 3 unit | | DDL line deleted from `vectorTableDdl` | 2 red: DDL pin + existing table | | fallback ablated: the 503 refusal put back where the create fails | 2 red: the unit fallback case and the live refused-index case | | failure not remembered (`metadataUnindexed` check removed) | 2 red: the same two (a second attempt, a second warning) | <details><summary>Local readings at head 6f65533</summary> - `pnpm --filter @objectstack/knowledge-pgvector test` with live PostgreSQL 16.15 + pgvector 0.6.0 (`OS_EXPECT_LIVE_DIALECT_MATRIX=1`): Test Files 18 passed (18); Tests 165 passed (165). `pnpm --filter @objectstack/knowledge-pgvector typecheck`: exit 0 (`tsc --noEmit` and `check:test-typecheck`). - `node scripts/pm/dispatch-gates.mjs --commands --repo objectstack-ai/objectstack` derived 70 families over the 6 changed paths, run after a full `turbo run build` (exit 0); each with stdin from /dev/null, exit captured before any pipe; all 70 exit 0; reconciliation `--ran`: 70 run, 0 NOT-MEASURED, 0 UNRUN. - `node scripts/pm/overlap-check.mjs --branch=claude/issue-38747-pgvector-scope-gin` (run before the push and again at 6f65533): VERDICT clean; merges cleanly with origin/main and with objectstack-ai#38745. - CI at 6f65533: 57 check-runs, 39 success, 18 skipped, 0 failure — including Lint & Repo Gates, TypeScript Type Check, Build Core, Test Core (12/12 shards), Check Changeset. ```text node scripts/check-adr-0087-registration.mjs --base origin/main :: exit 0 node scripts/check-adr-0087-registration.mjs --self-test :: exit 0 node scripts/check-changeset-no-major.mjs --base origin/main :: exit 0 node scripts/check-closing-keyword-parity.mjs :: exit 0 node scripts/check-closing-keyword-parity.mjs --self-test :: exit 0 node scripts/check-comment-mask-adoption.mjs :: exit 0 node scripts/check-comment-mask-adoption.mjs --self-test :: exit 0 node scripts/check-comment-mask-corpus.mjs :: exit 0 node scripts/check-dts-emitted.mjs --self-test :: exit 0 node scripts/check-empty-changeset.mjs --base origin/main :: exit 0 node scripts/check-empty-changeset.mjs --self-test :: exit 0 node scripts/check-issue-citations.mjs :: exit 0 node scripts/check-plugin-teardown-shape.mjs :: exit 0 node scripts/check-plugin-teardown-shape.mjs --self-test :: exit 0 node scripts/check-temporal-live-filter.mjs :: exit 0 node scripts/check-temporal-live-filter.mjs --self-test :: exit 0 node scripts/check-tenant-audit-census.mjs :: exit 0 node scripts/check-tenant-audit-census.mjs --self-test :: exit 0 node scripts/ci/assert-turbo-remote-cache.mjs --self-test :: exit 0 node scripts/ci/plan-test-core-shards.mjs --self-test :: exit 0 node scripts/ci/prune-turbo-cache.mjs --self-test :: exit 0 node scripts/ci/snapshot-next.mjs --self-test :: exit 0 node scripts/docs-audit/check-affected-docs.mjs :: exit 0 node scripts/docs-audit/check-drift-comment.mjs :: exit 0 node scripts/pm/check-governed-queue-guard.mjs --self-test :: exit 0 node scripts/pm/release-rehearsal-clone.mjs --self-test :: exit 0 node scripts/release-pending-publish.mjs --self-test :: exit 0 pnpm --filter @objectstack/spec run check:duration-unit-keys :: exit 0 pnpm --filter @objectstack/spec run check:error-code-provenance :: exit 0 pnpm check:adr-anchors :: exit 0 pnpm check:adr-symbol-anchors :: exit 0 pnpm check:changeset-gate-self-tests :: exit 0 pnpm check:ci-filter-parity :: exit 0 pnpm check:closed-ceremony-text :: exit 0 pnpm check:cross-package-test-inputs :: exit 0 pnpm check:dispatcher-error-vocabulary :: exit 0 pnpm check:doc-authoring :: exit 0 pnpm check:driver-memory-census :: exit 0 pnpm check:dts-closure :: exit 0 pnpm check:dual-build-cjs-loads :: exit 0 pnpm check:engine-double-contract :: exit 0 pnpm check:error-status-conformance :: exit 0 pnpm check:gitlink-declared :: exit 0 pnpm check:issue-citations :: exit 0 pnpm check:keyed-text-bounds :: exit 0 pnpm check:lean-entry-closure :: exit 0 pnpm check:logger-receiver-detach :: exit 0 pnpm check:nul-bytes :: exit 0 pnpm check:object-def-param-keys :: exit 0 pnpm check:objectql-double-limit :: exit 0 pnpm check:optional-error-sink :: exit 0 pnpm check:org-identifier :: exit 0 pnpm check:page-declaration-shape :: exit 0 pnpm check:platform-object-tenancy-census :: exit 0 pnpm check:published-files :: exit 0 pnpm check:query-options-erasure :: exit 0 pnpm check:refd-timer-probe :: exit 0 pnpm check:registry-log-declared :: exit 0 pnpm check:rest-log-spy-declared :: exit 0 pnpm check:slot-lookup :: exit 0 pnpm check:sourcemap-no-sources-content :: exit 0 pnpm check:system-context-census :: exit 0 pnpm check:test-source-alias :: exit 0 pnpm check:tier-file-adoption :: exit 0 pnpm check:type-check-coverage :: exit 0 pnpm check:type-check-debt :: exit 0 pnpm check:undeclared-dep-imports :: exit 0 pnpm check:vouch-for-reference-callers :: exit 0 pnpm check:watch-hint-literal :: exit 0 pnpm check:where-matcher :: exit 0 ``` </details> ## Acceptance notes - The bench params pin (`bench/instrument.test.mjs:189`) is updated in this PR under the claim amendment; it was red at 620fadf and is green at 6f65533. - `pgvector-adapter.ts` is over 1,000 lines; the ensure method sits beside its twin `ensureKeywordIndex` rather than in a new module because the claim's file surface admits no new source file. - `ensureKeywordIndex` still sends `CREATE INDEX IF NOT EXISTS` without a lookup first, so its once-per-process run waits on an open writer; not changed here. ## Verification Read first, by risk: `pgvector-adapter.ts` scope-term block (the AND of containment and exact match); `sql.ts` `metadataScopeForms` (the number-text rule); `pgvector-adapter.ts` `ensureMetadataIndex`. Two-minute check: with a pgvector PostgreSQL in `OS_TEST_POSTGRES_URL`, `pnpm --filter @objectstack/knowledge-pgvector exec vitest run src/__tests__/scope-containment-38747.live-postgres.test.ts` — expect 12 passed, including "the vector leg reads the passages in scope through the metadata index" and "a database that refuses the metadata index". --- _Generated by [Claude Code](https://claude.ai/code/session_01ADHkmTLwBddAv8qQwmLzdk)_ <!-- signed: repo:objectstack#3 · os-steve · session_01ADHkmTLwBddAv8qQwmLzdk --> --------- Co-authored-by: Claude <noreply@anthropic.com>
…the knowledge service reranks after the permission re-check (objectstack-ai#38764) <!-- claude-projects-attribution: {"github_login":"os-steve"} --> _Requested by **Steve** · [project thread](https://claude.ai/code/project/chan_01FdL1XeUyvVNxLreh3F4Qi9?thread=cmsg_01FdL1XeUyvVNxLreh3F4Qi9DAwBxBGNv4CexdUyBYJXSw)_ Fixes objectstack-ai#38760 Refs objectstack-ai#38750 Clause-②: no Metadata-protocol: none ## 维护者速读 - 用户能看到什么变化:用户无感;知识平台边界那份架构决策记录里追加一条 2026-11-30 的说明,写明知识源可以声明自己的检索结果要重排、用哪个重排模型由部署方配置、由知识服务在权限复核之后统一重排,不改任何代码。 - 为什么做:这是知识检索重排专题的第一步,把你当天说的「有就用」和「开了开关,一律重排」写进决策记录,后面几步的实现才有依据。 - 出错会怎样:说明里若有和你的裁决不一致的句子,后面做实现的人会照着错的文字去做;它只是一处文档追加,可以直接撤回,不影响任何在运行的系统。 - 要你做什么:请你审阅并批准这条说明;它改的是受管的决策记录,你批准它,由知识服务在权限复核之后重排这一条就算正式记下,不再另开决策卡。 ## What changes One file, add-only. `docs/adr/0161-knowledge-platform-boundary-platform-owns-assembly-sync-split-record-return-knowledge-source-is-a-governed-type.md` gains its sixth dated note: 28 lines added, none changed and none removed (614 lines to 642). The note records the maintainer's rulings of 2026-11-30 on the epic for knowledge retrieval rerank. A knowledge source may declare that its searches are reranked. The deployment configures the reranker, and no source names a model. The knowledge service reranks, after the permission re-check and before the cut to `topK`. The adapter contract does not change. Five insertions, in the form the five earlier notes of this record use. Line numbers are at head `6552e290`. | Lines | Where | What is added | |---|---|---| | 24 | Header, after the `**Amended**` line of the fifth note | A sixth `**Amended**` line, dated 2026-11-30. It names what the note amends, the maintainer's words with their times, and ruling record `7276086125`. | | 142 to 161 | K1, under "What follows from the two lists" | The note itself: an opening paragraph, 16 bullets and a last paragraph. | | 186 | K2, under "The rule for all of them" | A cross-reference. Three rows of the table name rerank and are read with the note. | | 281 | K4, in the cross-reference block that is already there | A cross-reference. One more source key is declared, `source.retrieval.rerank`. | | 468 | K8, under the note of 2026-11-30 | A cross-reference. Rule 4 and three sentences of that note are read with the note. | ### Each amended place No existing line is edited. This record's convention is add-only, so the note quotes the old sentence and states how it reads from the merge. The two sentences marked "new sentence" are the note's own wording. Every other entry in the third column is the note's reading of a text it leaves as written. In the last column, "body 1" to "body 3" are items 1 to 3 under "Rulings" in the body of the epic, which record the maintainer's 「有就用」 (10:13Z) and 「所以还是应该按照主流系统的做法,开了开关,一律重排」 (10:37Z). "D1" to "D4" are the first four of the six decisions of the epic that he answered with 「全部同意」 (10:47Z), as ruling record `7276086125` on the epic records them. | Place, with its line on `main` at `acf3b33e` | Old sentence | New sentence or reading | Ruling | |---|---|---|---| | K1, the "Rerank" row of the adapter's table (104) | "Whether a second model reorders candidates, and which." | Reading: neither is the adapter's. Whether: a knowledge source declares it. Which: the deployment configures the reranker, and no source names a model. The knowledge service reranks, after the permission re-check and before the cut to `topK`. The row keeps the adapter's own search. | body 1, D1 | | K1, the second sentence of the list (112), as the note of 2026-11-29 left it (119) | "The service does not choose a model, compute a vector, compute a score for a candidate, rerank or parse a file. It may re-order the hits it is about to answer by the ordering their source declares against a fact about the caller that the platform resolves, by position alone, and it changes the order the adapters answered in no other way." | New sentence: "The service does not choose a model, compute a vector, compute a score for a candidate or parse a file. It may re-order the hits it is about to answer in two ways, and it changes the order the adapters answered in no other way: by the ordering their source declares against a fact about the caller that the platform resolves, by position alone; and by reranking them, where their source declares it and the deployment has configured a reranker, after the permission re-check and before the cut to `topK`." | D1, body 1 and 3 | | The note of 2026-11-29, one sentence (119) | "This is not rerank, which stays the adapter's in the table above: the service reads no passage text and calls no model to do it." | Reading: the re-order by a declared ordering is still not rerank, and the service still reads no passage text and calls no model to do it. Rerank no longer "stays the adapter's". To rerank, the service hands the question and passage text to a model. | D1 | | The title (1), the D1 key-words line (9) and TL;DR item 1 (41) | Each says that adapters own rerank. | Reading: the word "no longer covers whether the hits of a search are reranked, by which model, or by whom, and it covers only what an adapter does inside its own search". | body 1, D1 | | K2, three rows (149, 153, 157) | "Engines are integrated for embedding, hybrid retrieval, rerank and file parsing."; the "no rerank" of the §3.4 row; "Embedding calls, vector storage, hybrid retrieval and rerank stay the adapter's." | Reading: the first stays true as a sentence, because a reranker is an engine the deployment brings, and it is the knowledge service that calls it. The §3.4 row keeps its "no rerank", because the adapter contract carries none. Of the third, the first three stay the adapter's and reranking is the service's. Each text is rewritten by the PR whose code makes the new sentence true. | D1 | | K8, rule 4 (417), as the note of 2026-11-30 left it (422) | "Which provider, which key, how to batch, rerank toggles and parser options stay in the adapter's own plugin options. Hybrid weights are declared by the knowledge source. A parameter of one search request is not configuration." | New sentence: "Which provider, which key, how to batch and parser options stay in the adapter's own plugin options. Hybrid weights are declared by the knowledge source, and so is whether its searches are reranked. The reranker is the deployment's configuration, and no source names a model. A parameter of one search request is not configuration." | body 1 | | The note of 2026-11-30 under K8, three sentences (422, 438) | 「K8 第 4 条:「hybrid weights」改划给知识源声明;rerank toggles、parser options 照旧留在驱动。」; under 「永远不进知识源协议」, 「融合算法及其常数、重排、分数阈值、分词器。平台以后如果统一做重排,那是知识服务的配置。」; "Rerank, a score threshold, a tokenizer and the fusion algorithm with its constant never enter the source (section 六, above)." | Reading: "Of rerank, a switch enters the source and nothing else does: no source names a reranker or a model. That switch is not an adapter's option. The fusion algorithm with its constant, a score threshold and a tokenizer still never enter the source, and parser options stay the adapter's." The sentence 「平台以后如果统一做重排,那是知识服务的配置。」 stands. | body 1; these words are later than the rulings that note records (06:00Z to 07:57Z) | ### What the note states beside the amended readings Each is quoted in the note from the words named here. - **The source key.** `source.retrieval.rerank`, an optional boolean, in the `source.retrieval` group the fifth note declares (body 1). - **No reranker is configured.** The search runs normally, the report marks the source with the reason `no_reranker` in `notReranked`, and saving or publishing the source shows a notice. It is never a refusal and never fewer hits (body 2; the two names are the ruling record's). - **A reranker is configured and the source declares it.** Every search is reranked. Only 0 or 1 candidate makes no call and sets no marker. At most 50 passages are sent per search (body 3). - **A configured reranker fails or times out.** The adapter order is kept, the source is marked `failed`, there is one attempt under a limit of 3 s, and it is not a coded refusal (D2). - **One model and one wire format for v1** (D3). The note names neither. - **A hosted deployment.** Hosted reranking comes after row 6 of the epic shows a gain, or a hosted customer asks. Until then a hosted source that declares rerank is searched normally and marked (D4). Left to the rows of the epic by name, under "Not in this note": the hosted recipient and its charging (D5, which is not decided); how a deployment states its reranker and what the knowledge service calls it through (rows 2 and 3); how many candidates are reranked under the ceiling of 50; how a rerank and a declared `affinity` follow one another; how the hits of several sources stand against each other; what `notReranked` looks like on the report and in the answer of `search_knowledge`; how the notice is shown; a per-search argument on the tool. No file under `packages/`, `content/`, `skills/` or `ui/` changes, and no other ADR does. The note declares; it builds nothing. ## Why The epic puts the record before the code. Its row 1 is this note, and the first decision of ruling record `7276086125` says of it: "Accepting row 1's ADR-0161 note records it; no separate decision card." Until this note merges, the ADR gives rerank to the adapter in every place the table above lists, and rule 4 of K8 keeps "rerank toggles" in the adapter's plugin options. Row 2 of the epic brings the key with its reader, and it needs the record to say so first. ## Tests The diff touches no package, so there is no build closure to make and no package test or type-check owed. What was measured on the text itself, at head `6552e290`: - **Quotations.** A script compared every quoted span of the 28 added lines with its source, read over REST or from the ADR at the base. The added text holds 16 spans in corner brackets: each is a verbatim substring of the body of the epic, of ruling record `7276086125` or `7276461244`, or of the ADR at the base where it already quotes the record of the fifth note. 0 mismatches. It holds 50 spans in double quotation marks: 48 are verbatim in one of those sources, and 2 are the note's own wording, which are the two "new sentence" entries of the table above. - **Bytes.** The added lines hold no raw control byte, no HTML comment and no model identifier. - **The reading of `main` the last paragraph of the note cites**, taken at `acf3b33e31`. `packages/services/service-knowledge/src/knowledge-service-search.ts#searchByKey` re-checks the hits as the caller (`applyPermissionFilter`), orders them by a declared `affinity` (`affinityOrderFor`) and cuts them to `topK`, with no rerank between. Tests aside, in `packages/services/service-knowledge/src` and the `src` of `knowledge-memory`, `knowledge-pgvector` and `knowledge-turso`, the word `rerank` is on one line, which is the class note K2 lists. The control word `embed` is on 412 lines, so the search reads those directories. - **Anchors.** Every code citation in the note is a path with a symbol, never a line number, and `check:adr-symbol-anchors` reads all of them (its verdict line is below). No ablation: the diff changes no behaviour a test pins. ## Acceptance notes **Against the card's acceptance lines.** 1. "Every amended sentence agrees with the design on objectstack-ai#38750 (option B) and with rulings D1 to D4." The table above gives each amended place with the ruling it rests on. 2. "No sentence promises row 2 behaviour that the epic does not rule." The note states no pool size, no widening factor, no order between rerank and `affinity`, no settings key name and no shape for the reranker contract. Each of these is named under "Not in this note" and left to its row. 3. "The `Amended` line is dated." Line 24, dated 2026-11-30. 4. "The note does not change any other ADR. It adds no code." One file changes. **Five things for the approver to weigh.** The note marks no ◆, because each of these rests on a text this record or the epic already has. They are the places where the wording is the note's and not a quotation. - a. **What the "Rerank" row keeps.** The note says the row keeps "the adapter's own search", and rests that on two sentences this record already has: "how candidates are found" (the "Hybrid retrieval" row) and "Changing the adapter changes how candidates are found and ranked" (Consequences). - b. **"The declaration is not silent (ADR-0078)".** A source that declares rerank where no reranker is configured is accepted and its search is answered. The note reads body 2 against ADR-0078: each such search says that its source was not reranked, and the author is told on save and on publish. - c. **Nothing is registered in K8.** The note says that the reranker's contract, client and settings (rows 2 and 3 of the epic) are not members of the adapter contract. It rests that on K8's own definition, under "What counts as a member": a member is what an adapter author must read, and no adapter reads these. - d. **A cross-reference under K4.** The card's list of places does not name K4. This record gives every new source key a cross-reference there, as the fifth note did for `source.retrieval`, so one was added. It changes no sentence of K4. - e. **The K2 rows are read through a cross-reference and are not edited.** Draft objectstack-ai#38720 edits the K2 row at line 153 in place, with the code that makes its new sentence true. This note's sentence about that row, that it keeps its "no rerank", holds for the row as it is on `main` and as objectstack-ai#38720 leaves it. **The names D1 to D6.** This record already writes "ruling D1", "ruling D2" and "ruling D5" for rulings of its own. The note therefore writes the six decisions of the epic as `objectstack-ai#38750 D1` to `objectstack-ai#38750 D6`, and says in its opening paragraph that none of them is a ruling of this record. It writes `row N of objectstack-ai#38750` for the same reason. **The card's line numbers, read on `main` at `acf3b33e`.** All twelve lines the card names (1, 9, 41, 104, 112, 119, 149, 153, 157, 417, 422, 438) exist and carry the text the card expects. Two labels are exchanged: the card gives 422 for rule 4 of K8 and 417 for the note of 2026-11-30. On `main`, rule 4 is line 417, and line 422 is that note's bullet "Rule 4, amended", which carries 「永远不进知识源协议」. Line 438 is that note's bullet "Not in this note". No line moved. **Overlap with the open drafts on this file.** `node scripts/pm/overlap-check.mjs --repo=objectstack-ai/objectstack`, run at `6552e2905b` before the push, printed `VERDICT clean exit 0`. It read `origin/main` at `acf3b33e31` and the six open heads that change this file (objectstack-ai#38745, objectstack-ai#38732, objectstack-ai#38730, objectstack-ai#38722, objectstack-ai#38721 and objectstack-ai#38720), and each merges cleanly with this branch. The order expected exit 1 against objectstack-ai#38720. It is clean because the note is add-only and inserts at none of the lines objectstack-ai#38720 changes. It was run again before this pull request opened, with `origin/main` at `8426fa0c89` (one commit later, which does not change this file): the same six heads, each merging cleanly, `VERDICT clean exit 0`. The landing order is the card's: after objectstack-ai#38720. **Not done here.** `content/docs/protocol/knowledge.mdx` and the class note of `KnowledgeService` are rewritten by the rows whose code makes their new sentences true. There is no changeset: `docs/adr/` is published by no package, and the PR carries `skip-changeset`. ## Verification **Read first, by risk.** One file changes, so these are its three hunks of most risk. 1. Line 146, the bullet "The sentence of the list, amended again". It is the one sentence that gives the knowledge service a second way to re-order hits. 2. Line 156, the bullet "Rule 4 of K8, amended again". The new rule 4 is composed by this note from body 1. 3. Line 150, the bullet "No reranker is configured". It holds the reading against ADR-0078 (item b above). **Two-minute check.** One click: open the "Files changed" tab. Expected: one file, +28 −0, five hunks, every changed line an addition. **Landing.** `docs/adr/**` is a governed surface. This is opened as a draft. The hand-off to the maintainer is the seat's, and the approval is the maintainer's. Nothing here requests a reviewer, marks it ready or arms auto-merge. **CI.** NOT MEASURED: the check-runs of this pull request, reason: it did not exist when this body was written. The report on the card carries the one reading taken after it opened. **Gates, run locally on head `6552e290`.** `node scripts/pm/dispatch-gates.mjs --commands --repo objectstack-ai/objectstack` derived 21 commands from the diff. All 21 ran in the foreground, each exit code was captured before any pipe, and all 21 are exit 0. The reconciliation: ```text Run reconciliation — 21 derived, 21 run, 0 NOT-MEASURED, 0 UNRUN. ✓ dispatch-gates --ran: 21 derived famil(ies) accounted for — 21 run, 0 NOT-MEASURED (a DERIVED zero — all 21 recorded an exit code and none of them is 3). ``` <details> <summary>The 21 commands and their exit codes</summary> ```text node scripts/check-adr-links.mjs :: exit 0 node scripts/check-adr-links.mjs --self-test :: exit 0 node scripts/check-closing-keyword-parity.mjs :: exit 0 node scripts/check-closing-keyword-parity.mjs --self-test :: exit 0 node scripts/check-comment-mask-corpus.mjs :: exit 0 node scripts/ci/plan-test-core-shards.mjs --self-test :: exit 0 pnpm --filter @objectstack/lint run check:doc-formula-expressions :: exit 0 pnpm check:adr-anchors :: exit 0 pnpm check:adr-index :: exit 0 pnpm check:adr-symbol-anchors :: exit 0 pnpm check:ci-filter-parity :: exit 0 pnpm check:closed-ceremony-text :: exit 0 pnpm check:cross-package-test-inputs :: exit 0 pnpm check:doc-authoring :: exit 0 pnpm check:driver-memory-census :: exit 0 pnpm check:gitlink-declared :: exit 0 pnpm check:nul-bytes :: exit 0 pnpm check:pm-governed-merges :: exit 0 pnpm check:pm-prior-rulings :: exit 0 pnpm check:refd-timer-probe :: exit 0 pnpm check:watch-hint-literal :: exit 0 ``` </details> <details> <summary>Verdict lines of the gates that read the ADR</summary> ```text ✅ check-adr-links: 1284 relative link destination(s) under docs/adr/ resolve ✅ check-adr-symbol-anchors: 4574 anchors across 165 records resolve — 1704 symbol (1675 declaration, 29 literal), 2818 file-level, 52 cross-repo, 6 exempt, 128 continuation. [cut here: the rest of the line is a note on what the count is not] adr-index --report: OK — docs/adr/README.md is current, every record parsed, self-test 60 assertions green. Report-only: this line never reds the step. check-nul-bytes: OK (scanned 29002 text file(s) -- 29002 tracked, 0 untracked-not-ignored; skipped 101 binary; no raw ASCII control bytes). ✓ doc authoring guard: 24253 customer-facing string(s) across 1963 spec sources clean — no internal issue-id references (message 3603 · strictObject 5655 · tombstone 1510 · describe 12078 · functionBuilt 529 · functionDeclared 878). ``` </details> <details> <summary>One gate first read NOT MEASURED, then green</summary> At the first head, `151609a7`, `pnpm --filter @objectstack/lint run check:doc-formula-expressions` answered exit 3, PREREQUISITE NOT MET: two workspace packages it imports were not built in the fresh worktree. That is a run that measured nothing, not a red gate. The two packages were built under the shared verify lock, and the gate was run again (the lock's verdict line is cut after the wait): ```text VERDICT command-exit 0 · held the lock 23s · waited 167s (2m47s) pnpm --filter @objectstack/lint run check:doc-formula-expressions :: exit 0 ``` At the final head it ran with the other 20 and answered exit 0. </details> **Left to CI, not run locally.** The repo-wide lint, the type-check lanes, the test shards, and the families `dispatch-gates` prints outside the derived list. The commit trailer gate ran in the pre-push hook on the pushed range and is green. ## Human Minimum - [x] 1. No schema and no code changes. - [x] 2. No new name is declared in code. The names the note writes are the rulings'. - [x] 3. No formatter ran. `pnpm lint` is NOT MEASURED locally: the repo-wide scan is CI's, and the diff is one Markdown file. - [x] 4. One card, one branch off `main` at `acf3b33e31`, one pull request. - [x] 5. Nothing publishes, so no changeset; both declaration lines are filled in above. - [x] 6. `packages/spec` is not touched. - [x] 7. No edit to `content/docs/references/`, to a `CHANGELOG.md` or to `content/docs/releases/`. - [x] 8. Title, body and comments are in English. The maintainer's Chinese words are quoted unchanged, and the 维护者速读 section is in Chinese as the fleet's rule asks. - [x] The *Before Submitting* list is done for what a docs-only diff reaches; `pnpm lint` is as item 3 says. --- _Generated by [Claude Code](https://claude.ai/code/session_01ADHkmPDtfMCw4FJfyFfQ7v)_ <!-- signed: repo:objectstack#3 · os-steve · session_01ADHkmPDtfMCw4FJfyFfQ7v --> --------- Co-authored-by: Claude <noreply@anthropic.com>
…r reports the modes it runs (objectstack-ai#38720) <!-- claude-projects-attribution: {"github_login":"os-warren"} --> _Requested by **Warren** · [project thread](https://claude.ai/code/project/chan_01U5RdnAAmkSQmZbqh6FtqZ8?thread=cmsg_01U5RdnAAmkSQmZbqh6FtqZ8QCBjsNDZa4iwo35VN5fKKg)_ Part of objectstack-ai#38692 Clause-②: yes (widening) Metadata-protocol: added Skills-docs: follow-up objectstack-ai#38732 (the `source.retrieval.mode` row of the objectstack-ai skill lands there; `skills/` is a governed path and takes its own PR) ## 维护者速读 - 知识源作者可以选择检索方式(按意思、按字词、两者结合),不选则沿用存储默认;本单只定义写法与驱动上报,用户暂无可见变化。 - 属于知识管理专题「一期 a:检索方式」,解决条款类问答被语义检索漏掉的问题。 - 出错只会是新写法被误拒或误收;未写此项的知识源行为不变,可直接撤回。 - 无。 ## Stack Base: `main`. First of the phase-1a series; the adapter PRs and the service PR build on it. The ruling it builds on is on `main`: ADR-0161, the dated note of 2026-11-30 under K8 (phase 0, merged as 95ffacc); this branch has `main` merged in. **Lands together with objectstack-ai#38722, right after it.** This PR adds the key and both contract members with their suite cases, but no reader: the service's reader is objectstack-ai#38722, and the two adapters that declare `implements.retrieval` are objectstack-ai#38721 and objectstack-ai#38745. That splits K8 rule 1 and K4 ("lands with its first reader, in the same PR") across stacked PRs, because the stack bases force it. Until objectstack-ai#38722 lands, a declared mode is carried and ignored, and the `planned` liveness row warns an author so (`authorWarn` and `authorHint`; objectstack-ai#38722 drops both when it flips the row to `live`). So objectstack-ai#38720 is not merged or released without objectstack-ai#38722, which merges right after it. ## What changes - `knowledge_source.source.retrieval?: { mode?: 'vector' | 'keyword' | 'hybrid' }`, strict from birth; `retrieval: {}` is accepted and declares nothing. Not part of the index fingerprint or the recipe hash. - `IKnowledgeAdapter.capabilities.retrieval?: { modes, default }` (`AdapterRetrievalCapability`) and `AdapterSearchOptions.retrieval?: { mode }`, optional as every search member is (K8 rule 2); omitted means the adapter's default. - Contract suite (`runKnowledgeAdapterContract`): `implements.retrieval`; a declared report must be valid, and one seeded fixture is searched under each listed mode (`vector` leaves the keyword-only clause out, `keyword` answers it alone, the default handed explicitly equals no member). - ADR-0161 K2 row and protocol doc §7.1 rewritten (see Acceptance notes); the contract doc names the refusal code. - Studio form row for the mode (static three options; PR 4 of the series makes it list the store's modes), liveness row `planned` (flipped to `live` by the service PR), protocol doc §3.4, generated baselines. ## Tests - `packages/spec`: new knowledge-source cases (three modes parse, `{}` accepted, an invalid mode's message, `vectorWeight`/`keywordWeight`/`fusion` refused as unknown keys, JSON Schema enum + `additionalProperties: false`). - `service-knowledge`: index-fingerprint test pins that neither hash moves for `{}` or any mode. - Contract suite exercised by the turso and live-pgvector adapter PRs. ## Acceptance notes - `AdapterSearchOptions.retrieval` is optional, as built (`retrieval?`, omitted means the adapter's default, as K8 rule 2 has every search member): the maintainer ruled it on objectstack-ai#38692 (comment 7272337479, 2026-11-30 07:57Z), the question the phase-0 contract review (7271729439) escalated. - Per-search refusal code (point 4), proposed: `SERVICE_UNAVAILABLE` (503), reused rather than added. It is an ADR-0112 standard catalog code (`packages/spec/src/api/error-code-ledger.zod.ts`, the standard map), so no new ledger entry; it is the code a source whose adapter is not mounted already carries in `refused`, since in both cases the deployment cannot serve the source as written. It is objectstack-ai#38722's to write and the maintainer's to confirm (open question C): the contract doc of `AdapterSearchOptions.retrieval` here names no code. The save refuses with `VALIDATION_ERROR` (400), as the ruling fixes. - ADR-0161's K2 row (adapter surface) is rewritten as the row asks of each PR that adds a member: it no longer says "no hybrid toggle"; protocol doc §7.1 likewise. This makes the PR Tier H (an ADR file is touched). - Phase 1b (`vectorWeight`) is not built; the strict shape refuses it today. ## Verification - Two-minute check: `pnpm --filter @objectstack/spec exec vitest run src/ai/knowledge-source.test.ts` → all pass, including the retrieval describe. - Local gates from `dispatch-gates.mjs --commands`: all measured gates green (`check:spec-parsed-alias` found a missing isomorphism pin, fixed in e805371); not measured in this container (exit 3 or unbuilt closure, no verdict): `check-plugin-teardown-shape --self-test` (shallow clone), `check:skill-examples`, `check:dual-build-cjs-loads`, `check:i18n`, `check:dts-closure`. ## Human Minimum - [x] 1. Schemas start as Zod; `packages/spec` holds no runtime logic. - [x] 2. Every name I added uses the casing for its kind. - [x] 3. No formatter ran; `pnpm lint` passes. - [ ] 4. One issue, one branch off an up-to-date `main`, one pull request. (Stacked: see "Stack" above.) - [x] 5. A change that publishes carries a changeset, and both declaration lines are filled in here and in the changeset. - [x] 6. `packages/spec` touched: its generated artifacts are regenerated and committed. - [x] 7. No hand edits to `content/docs/references/`, `packages/*/CHANGELOG.md` or `content/docs/releases/`. - [x] 8. Title, body and comments are in English. - [x] The *Before Submitting* list in CONTRIBUTING.md is done. 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01JQwxbaASqBozmmj1n5tbUf <!-- signed: repo:objectstack#2 · os-warren · session_01JQwxbaASqBozmmj1n5tbUf --> --------- Co-authored-by: Claude <noreply@anthropic.com>
Requested by Warren · project thread
Part of #38692
Clause-②: yes (widening)
Metadata-protocol: none
维护者速读
Stack
Base:
main. The spec PR #38720 is merged andmainis merged in, so this diff is the adapter's own 6 files; it lands in the same release as the service PR #38722, the first reader of the mode. Built onmainafter #38726 (B2) merged: the ranking statement still runs under B2'sSET LOCAL statement_timeoutin a transaction of its own, a failed search is still refused by the coded errors ofsrc/errors.ts, and the pool default is B2's 20. The ruling it implements is onmain: ADR-0161, the dated note of 2026-11-30 under K8.What changes
knowledge-pgvectorreportscapabilities.retrieval = { modes: ['vector', 'keyword', 'hybrid'], default: 'hybrid' }.keywordnever calls the embedder (distance column is a constant);vectorwrites no keyword condition at all (noLIKE/ILIKE, notsquery), not just none into the fusion. That leg is most of a hybrid statement's cost: on PG17 + pgvector 0.8.7 over 59,949 clauses, vector-only took the statement from 1,655 ms to 445 ms at the same top-10 quality (os-bob, 知识源加「检索方式」和混合比例:只用向量 / 只用关键词 / 混合(可设比例),由应用元数据指定,单次检索可覆盖 #38692).hybridunchanged,fuse(rows, topK, legs)bit-identical for two legs.400 VALIDATION_ERROR) before anything is embedded or ranked, rather than run on the one-leg scale (review S1).Clause-②: yes (widening): the exported adapter'scapabilitiesgrowsretrieval(review M1).Tests
retrieval-modes.test.ts(recording pool): legs per mode, no embedder call underkeyword, empty question, hybrid bit-identity over ranks 1..200 withObject.is, single-leg scores, and a pin that avectorsearch sends no statement holdingLIKE,ILIKE,tsqueryor@@(withhybridas the control that does).OS_TEST_POSTGRES_URL), at 6707107 (main with feat(spec): a knowledge source declares its retrieval mode; an adapter reports the modes it runs #38720 merged): 179 tests passed; typecheck clean.Acceptance notes
Verification
pnpm --filter @objectstack/knowledge-pgvector exec vitest run src/__tests__/retrieval-modes.test.ts→ all pass (no database needed).Human Minimum
packages/specholds no runtime logic.pnpm lintpasses.main, one pull request. (Stacked: see "Stack" above.)packages/spectouched: its generated artifacts are regenerated and committed. (Not touched.)content/docs/references/,packages/*/CHANGELOG.mdorcontent/docs/releases/.🤖 Generated with Claude Code
https://claude.ai/code/session_01JQwxbaASqBozmmj1n5tbUf