Skip to content

fix(service-knowledge): knowledge search asks the object's API exposure and the caller's field-level read rules per source - #36850

Merged
objectstack-fleet[bot] merged 11 commits into
mainfrom
claude/issue-36839-knowledge-exposure-fls
Nov 24, 2026
Merged

objectstack-fleet[bot] merged 11 commits into
mainfrom
claude/issue-36839-knowledge-exposure-fls

Conversation

@objectstack-fleet

@objectstack-fleet objectstack-fleet Bot commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #36839

Clause-②: no
Metadata-protocol: none

维护者速读

  • 用户能看到什么变化:受限用户(以及代其提问的 AI)检索知识库时,若某个知识源包含他无权查看的字段,或其对象未对接口开放、所属包已停用、是未声明 AI 可读的系统对象,该知识源对他不再返回任何结果;有权限的用户与系统任务不受影响。
  • 为什么做:属于「MCP 问数」主线,在知识检索对 MCP 客户开放之前,先堵住低权限用户借 AI 读到其本无权看到的字段内容这一安全缺口。
  • 出错会怎样:最坏情况是受限用户检索不到本该能看到的知识源(只会更严,不会更松);改动可直接回滚。
  • 要你做什么:无。

What changes

Option D of the ruling recorded on #36650 (comment 7121194365, quoted in #36839's body): in the knowledge service, at source granularity, fail closed, no new spec key. Governing text: ADR-0090 D10 rule 1, ADR-0049.

  • Defect class / location / function. Missing field-level and API-exposure enforcement on a row-serving door: KnowledgeService.search (packages/services/service-knowledge/src/knowledge-service.ts) re-checked an object-source hit only with a row read of its id under the caller's context, while the passage it returns is built at index time, under a system context, from every contentFields member, the record title and the source's metadataFields.
  • New knowledge-source-admission.ts, asked by a new private admitSources step before any adapter is searched, for a non-system caller with a data engine bound, once per (caller, object) per search:
    1. disabled package: core's registryObjectPackageDisabled over the engine's registry (the predicate the data route and the analytics door ask; no injected hook needed, so no new dependency on metadata-protocol);
    2. API exposure: canServeApiOperation(enable, 'search') (@objectstack/spec/data), the decision and operation the cross-object search asks;
    3. sys_* objects: served only when isAiReadExposed answers true (enable.aiReadable: true), the MCP record tools' posture;
    4. field gate: every field the source serves (contentFields, '*' = every declared field except id; metadataFields; title), less the credential-class and internal fields recordToDocument never indexes, must be in the security service's getQueryableFields answer; absent it or undefined, getReadableFields less every maskingRule field; with no security service, every field except the maskingRule ones (the contract's fallback, ISecurityService.getQueryableFields).
      A source failing any gate is not searched for that caller. Queryable rather than readable: a passage carries the unmasked value and the search matches on it.
  • Fail closed. A schema read, package probe or field answer that throws refuses every source over that object (logged at error, warn as fallback); a security service answering neither field question refuses too. The system context bypasses, as it bypasses the row re-check; the no-context and no-engine paths are unchanged (they already drop every object-source hit).
  • Wiring. KnowledgeServicePlugin passes a new optional resolveSecurity option resolving security per search (plugin order free). Only a missing answer or the kernel's not-registered refusal (isServiceNotRegisteredError) reads as "no security service"; any other throw from that lookup refuses the object's sources, reported at error once per object per search. KnowledgeFieldSecurity is exported as a type.
  • Objects nobody can judge, and hit origin (review round 1). A caller with no execution context, or a service with no data engine bound, is searched no object source at all (before, an object-source hit with no sourceRecordId reached it). An admitted object source's hit with no sourceRecordId cannot be re-checked and is dropped. KnowledgeService.search drops a hit whose reported sourceId names another source than the one searched. Object admissions are asked concurrently, and the sys_* posture also reads the schema's own name.
  • Not in this PR: @objectstack/knowledge-ragflow. A RAGFlow-side chunk filter added in review round 1 was removed again under the maintainer's ruling recorded on security(knowledge): search hits skip the API-exposure decision and field-level read rules every other row-serving door applies, now that the MCP door serves search_knowledge #36839 (comment 7134290286, option B): the documented RAGFlow API returns no chunk metadata, so the filter could not act, and the package is retired whole on its own card. This PR changes nothing in that package.
  • Pins and claims brought true. row-serving-door-exposure.pin.test.ts now holds knowledge retrieval BY NAME (HELD_BY_NAME: the door imports its decision site, which asks the exposure decision and getQueryableFields, and the behaviour pin exists) instead of naming it unconstrained. The mcp-http-identity note in authz-conformance.matrix.ts states the knowledge-service enforcement its "RLS / FLS / tenant apply exactly as on REST /data" claim relies on once a tool serves knowledge search. content/docs/protocol/knowledge.mdx §5 (new "Source admission" subsection), §7.1 and §9 state the gates and the narrowing. content/docs/permissions/system-context.mdx row 46 now names admitSources (its new system-context bypass read), with the generated register regenerated by check-system-context-census.mjs --write.

Tests

  • New packages/services/service-knowledge/src/__tests__/knowledge-source-admission.test.ts (22), through the real KnowledgeService, refusal and preservation per gate: a member who reads the row but not salary_note gets no hit from the source naming it and the adapter is never asked to search it, while a manager and the system context get it; title and metadataFields hidden each refuse; '*' refuses on one hidden field and does not ask about credential / internal fields; a masked field via the getReadableFields fallback; no security service ⇒ maskingRule fallback; a throwing field answer and an unanswering service fail closed; the answer is asked once per object; apiEnabled: false dropped for an end-user context and kept for the system context; an apiMethods whitelist without search refused and one with list admitted; a disabled package's object dropped and kept for system; a sys_* object without aiReadable dropped, with it kept; a throwing schema read fails closed; an http source is untouched. Two more drive KnowledgeServicePlugin on a real LiteKernel with a registered security service (refusal + preservation) and without one (fallback admits).
  • Red before / green after. With knowledge-service.ts and knowledge-service-plugin.ts restored to the base f77d078d (blob match confirmed), the new file ran 14 failed / 2 passed (the 2 are pure preservation legs); restored to HEAD (blob match, git diff HEAD empty) it runs 16 / 16.
  • Review round 1 added 6 pins to that file: no context and no engine each search no object source; an admitted object source's hit without sourceRecordId is dropped; a hit naming another source is dropped; a security lookup throwing anything but the not-registered miss fails closed with one error log (system preserved); and isServiceNotRegisteredError's discrimination. Red before: with the service and plugin restored to round-1 head 774652cd63 (the lookup back to swallowing every throw), the file ran 5 failed / 17 passed (the 5 behaviour pins); restores matched HEAD. Three fixtures in knowledge-service.test.ts that searched an object source with no context now pass the system context or register the http source their hit names.
  • row-serving-door-exposure.pin.test.ts (core repo project) 4 / 4; with knowledge-service.ts restored to base, the new held-by-name test is red (1 failed / 3 passed), restored blob matches HEAD.
Local runs on head 5cc0e97 (after merging origin/main at 305fe60)
  • Under os-verify-lock, VERDICT command-exit 0: pnpm --filter '@objectstack/service-knowledge^...' --filter '@objectstack/lint...' build, then @objectstack/service-knowledge test (5 files / 71 tests), typecheck (tsc --noEmit + check:test-typecheck OK) and build (check-dts-emitted 2/2); core repo project row-serving-door-exposure.pin.test.ts 4 / 4.
  • node scripts/pm/dispatch-gates.mjs --commands on 5cc0e97: 105 derived; 103 exit 0. NOT MEASURED, PREREQUISITE NOT MET (exit 3; they read dists of packages outside this diff, not built in this worktree): pnpm --filter @objectstack/spec run check:skill-examples, pnpm check:dual-build-cjs-loads. --ran with exit codes: 105 derived, 103 run, 2 NOT-MEASURED, 0 UNRUN.
  • The merge conflicted on content/docs/permissions/system-context.mdx rows 45/46 (main changed row 45, this PR row 46); resolved by keeping both changes, and check-system-context-census.mjs --write reported the register already current.
  • node scripts/check-platform-checklist.mjs --changed-from origin/main: exit 0, no anchored file in the change set.

Acceptance notes

  • metadataFields is gated beside contentFields and title: a hit's metadata serves those values, so leaving them out would keep the same leak; the card's Expected 2 names contentFields and title.
  • title is required only when the object declares a title field (or its schema is unknown), because recordToDocument serves the record's title whatever the source names.
  • A security service whose field answer is undefined on both methods refuses the source (fail closed) rather than falling to the object's own projection.
  • No published accept set narrows: no spec key, value or schema changes. What narrows is runtime results for restricted callers, stated in the changeset.

Verification

Read first, by risk: packages/services/service-knowledge/src/knowledge-source-admission.ts (admitObject, servedFieldsOf, admitSourceFields), the admitSources hunk in knowledge-service.ts, then the plugin's resolveSecurity wiring.

Two-minute check: pnpm --filter @objectstack/service-knowledge exec vitest run src/__tests__/knowledge-source-admission.test.ts — expect 22 passed.


Generated by Claude Code

@github-actions github-actions Bot added size/l documentation Improvements or additions to documentation tests tooling Fix lands in tooling, not a product package — enters pm:queue only with Unblocks: or a named surface labels Nov 24, 2026
@github-actions

github-actions Bot commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

📓 Docs Drift Check

This PR changes 1 package(s): @objectstack/service-knowledge, touching 32 documentable anchor(s). ⚠️ 1 changed file(s) yielded no anchor (packages/services/service-knowledge/src/index.ts), so the pages documenting them are NOT COVERED by this run — this is not a clean bill of health for those files.

5 hand-written doc(s) NAME something this change touched and may need an implementation-accuracy re-verification:

  • content/docs/ai/knowledge-rag.mdx (via KnowledgeService (symbol, a top-level class), KnowledgeServicePlugin (symbol, a top-level class))
  • content/docs/api/data-api.mdx (via /:object/change-owner/cascades (route, bridged from symbol isObjectPackageDisabled — its route source's handler names it))
  • content/docs/permissions/system-context.mdx (via admitSources (symbol, a method of class KnowledgeService), applyPermissionFilter (symbol, a method of class KnowledgeService), getReadableFields (symbol, a method of interface KnowledgeFieldSecurity), isSystemObjectName (symbol, a top-level const))
  • content/docs/protocol/knowledge.mdx (via KnowledgeService (symbol, a top-level class), KnowledgeServicePlugin (symbol, a top-level class), getQueryableFields (symbol, a method of interface KnowledgeFieldSecurity), getReadableFields (symbol, a method of interface KnowledgeFieldSecurity))
  • content/docs/protocol/objectql/state-machine.mdx (via /object/:name/state/:field (route, bridged from symbol isObjectPackageDisabled — its route source's handler names it))

⛔ 4 release-owned page(s) also name something this change touched. These are read-only:

  • content/docs/releases/v15.mdx (via applyPermissionFilter (symbol, a method of class KnowledgeService))
  • content/docs/releases/v17/17-0.mdx (via getLegalNextStates (sdk, the bare tail of client method meta.getLegalNextStates, bound to GET /api/v1/meta/object/:name/state/:field; the bare tail of client method meta.getLegalNextStates, bound to GET /meta/object/:name/state/:field), meta.getLegalNextStates (sdk, the route ledger binds it to GET /api/v1/meta/object/:name/state/:field, selected by route anchor /object/:name/state/:field; the route ledger binds it to GET /meta/object/:name/state/:field, selected by route anchor /object/:name/state/:field))
  • content/docs/releases/v17/17-2.mdx (via getLegalNextStates (sdk, the bare tail of client method meta.getLegalNextStates, bound to GET /api/v1/meta/object/:name/state/:field; the bare tail of client method meta.getLegalNextStates, bound to GET /meta/object/:name/state/:field), meta.getLegalNextStates (sdk, the route ledger binds it to GET /api/v1/meta/object/:name/state/:field, selected by route anchor /object/:name/state/:field; the route ledger binds it to GET /meta/object/:name/state/:field, selected by route anchor /object/:name/state/:field))
  • content/docs/releases/v17/17-6.mdx (via getQueryableFields (symbol, a method of interface KnowledgeFieldSecurity), getReadableFields (symbol, a method of interface KnowledgeFieldSecurity))

content/docs/releases/ is RELEASE-OWNED (AGENTS.md "Documentation Guardrails"): release
notes are written centrally at release time, and a code PR that edits them is the exact PR
that guardrail exists to stop. They are still audited — read-only. If one of them is actually
wrong, file an issue or open a dedicated docs-only PR; do not edit it here.

What this run could not see
  • 1 changed file(s) yielded no anchor (packages/services/service-knowledge/src/index.ts) — pages documenting those are invisible to this run
  • 4 name(s) were too generic to anchor anything (single lowercase words)
  • the SDK route bridge reached 69 of 252 client-bound route-ledger rows — the other 183 have no registrar path: tail to select them, so pages documenting THEIR client methods cannot appear above, on this or any run. Of those 183: 0 are remediable by widening that discovery convention (an in-repo file declares the path; the convention did not scan it); 59 are structural — on a ledger where NOT ONE row is declared in-repo, so no discovery change reaches them at any price; 124 are undecided (no in-repo declaration, on a ledger that has other in-repo registrars — absence and an unreadable spelling are not distinguishable here). The rows themselves: node scripts/docs-audit/affected-docs.mjs --bridge-coverage
  • a page that states a rule by its inputs shares no identifier with the emitter that implements the rule, so an emitter-only diff cannot list it — not on this run and not on any run. Measured on fix(driver-sql): emit varchar(maxLength) for a text field a declared index keys on #11430: content/docs/protocol/objectql/types.mdx documents the text-family column mapping by the ObjectQL type names it maps FROM (text / textarea / html) while the diff changed createColumn; it went unlisted, and it was the page that diff falsified, in four places. No shared token exists to detect this on, so a rule your change carries has to be re-read by hand in the pages that restate it.
  • a key NAME is not a key, so the hand re-read the line above prescribes can land on the wrong schema. The same spelling is authorable on one governed type and a [REMOVED] tombstone on another for each of active, aria, joins, objects, template, tools and version (censused on [finding] tools is a key on BOTH AgentSchema (tombstoned, dead) and SkillSchema (live, cloud-attested), so a name-based search attributes skill examples to the agent key — it produced a false stop-the-line alarm on PR #19059 #19093 over the liveness ledger's governed types, top-level keys); nothing in a search result distinguishes the two, so a grep hit on a LIVE example reads as evidence about the DEAD key. Measured on fix(spec): the agent.tools liveness row says dead — it claimed live on a key the schema tombstoned #19059: content/docs/ai/agents.mdx was reported as contradicting the agent.tools tombstone over its tools: example at :161, which is inside the defineSkill({ block opened at :155 — the page was already correct. Settle ownership by PARSING the value against both schemas, never by the name: that literal PASSES SkillSchema, and as an AgentSchema it FAILS at tools with the tombstone prescription. ⛔ These names are not the whole class — a key retired through a .strict() guidance map leaves no tombstone in the walked shape and none of them here (tool.category, live as AIToolDefinition.category).

Coarse fallback — 4 page(s) merely mention a changed package (the pre-#9192 predicate, kept for the deliberately-wide backstop): node scripts/docs-audit/affected-docs.mjs --json 5727092e72f7c8f34964a98ca0aef01103305719 → packageMentionDocs.

Which tree this was computed on

This run read content/docs from aa4b70fc9a46ef942b8b64f6ff7e65e3fe45b6c6 — the merge of head c4abc0caff32cd85d9000d1e6c92444c3969f862 into base 5727092e72f7c8f34964a98ca0aef01103305719, which is what actions/checkout gives a pull_request run. Not the PR head.

A worktree cut from an older main holds a different content/docs, so re-deriving there can legitimately return a different list — that is a different tree, not a wrong row. To answer on the same tree:

# while this PR is open — GitHub drops the merge commit once it closes
git fetch origin aa4b70fc9a46ef942b8b64f6ff7e65e3fe45b6c6 && git checkout aa4b70fc9a46ef942b8b64f6ff7e65e3fe45b6c6
# afterwards, rebuild it from the two parents, which stay fetchable
git fetch origin 5727092e72f7c8f34964a98ca0aef01103305719 c4abc0caff32cd85d9000d1e6c92444c3969f862 && git checkout -B drift-repro 5727092e72f7c8f34964a98ca0aef01103305719 && git merge --no-ff c4abc0caff32cd85d9000d1e6c92444c3969f862

node scripts/docs-audit/affected-docs.mjs --json 5727092e72f7c8f34964a98ca0aef01103305719

⚠️ That checkout carried uncommitted changes, so the commit above does not fully identify what was read.

Advisory only, and a precision-first one (#9192): a page is listed because it names a
symbol, wire route or SDK method this diff touched — not because it mentions a changed
package. Each row says which anchor put it there, so a wrong row is reportable rather than
merely annoying. To re-verify, run the docs-accuracy-audit workflow scoped to these files:
node scripts/docs-audit/affected-docs.mjs 5727092e72f7c8f34964a98ca0aef01103305719 → pass the list as
args.docs, on the commit named under Which tree this was computed on.

@objectstack-fleet

Copy link
Copy Markdown
Contributor Author

repo:objectstack#4 · os-justin · session_01QSeKYpEsWWE9Y5YtSsDgqZ

席位核对 — L1 REWORK · head 774652cd63edbc0f93d3a113814072ac147f195e · 2026-11-24T07:48Z

  • Shape. Draft PR to main, first line Fixes #36839 (merging closes the card; the diff delivers all of Expected 1–5, so Fixes is right). Clause-②: no · Metadata-protocol: none, copied verbatim from the claim (os-dev.md:276). 10 files, all on governed-free paths (governedPathsIn → []). l1-face: every line ok except one flag, changeset: @objectstack/core is touched with no entry. Cleared on reading: the only core file is src/security/row-serving-door-exposure.pin.test.ts, and core ships files: [dist, README.md, CHANGELOG.md], so the diff publishes nothing from core. @objectstack/dogfood is private. @objectstack/service-knowledge carries the patch changeset.
  • Premise and delivery against the card. The premises hold, and the dev showed each one: security is resolved per search; getQueryableFields exists on plugin-security; getSchema and registry exist on the bound engine; and the disabled-package check needs no injected hook, because registryObjectPackageDisabled comes from @objectstack/core, which the package already depends on.
    • E1: the PR drops a source whose object is in a disabled package, fails canServeApiOperation(enable,'search'), or is a sys_* object without isAiReadExposed. It drops the source before the search, which is stronger than dropping the hit after it. The system context still bypasses.
    • E2: the field gate covers contentFields ('*' meaning every declared field), metadataFields and title, less the credential and internal fields. It checks them against getQueryableFields, falling back to getReadableFields minus maskingRule fields, and to the maskingRule rule alone when no service is registered. Adding metadataFields is a justified widening, and the PR body states it.
    • E3: no spec key is added, and the narrowing is stated in the changeset and in knowledge.mdx §5, §7.1 and §9.
    • E4: the pin now holds the door by name in HELD_BY_NAME, and the matrix note is updated.
    • E5: there are 16 pins through the real KnowledgeService, 2 of them through KnowledgeServicePlugin on a real LiteKernel. They include a caller who can read the row but not the field, and an object with apiEnabled:false.
    • Push-down (PD5): admission runs once per (caller, object) per search, as one getSchema call, one registry probe and one field answer. No query runs per hit, and no ids are materialised. The row re-check is unchanged (one $in query per object).
  • Gates. Check-runs on 774652cd63: 60 success, 10 skipped (all expected opt-in or queue-only), 0 failed, 0 pending. Lint & Repo Gates and TypeScript Type Check are both success.
  • Test evidence. The dev gives a red-before/green-after reading: with knowledge-service.ts and the plugin restored to base f77d078d (blob match), the new file fails 14 and passes 2, and the 2 that pass are the pure preservation tests. At HEAD it passes 16/16. The pin's new by-name test is red at base (1 failed, 3 passed) and green at HEAD (4/4). The commands are named and the counts reported, but no raw output is pasted, which is acceptable here. The refusals return empty results rather than an error envelope, so there is no code/status for the tests to assert.
  • Sentence reads. I read three texts sentence by sentence against the code.
    • The changeset: every bullet matches knowledge-source-admission.ts except one sentence (finding M1).
    • knowledge.mdx: §5 diagram, the new "Source admission" subsection, §7.1 and §9 all match, with M1 and N2 as the exceptions. "granting list does" is held by a test.
    • system-context.mdx: row 46 and the register row admitSources | 1 | 46 match.
    • The matrix note matches.
    • content/docs/ai/knowledge-rag.mdx:76 (flagged by the drift check) describes only RLS. It is still true, just incomplete (N5).
  • Findings.
    • must-fix M1: knowledge-service-plugin.ts:126-132 swallows every throw from ctx.getService('security') and treats it as "no security service". That falls back to the maskingRule-only rule, which admits a source whose hidden field is hidden only by a permission-set rule. On the in-repo kernels a missing service is reported as a throw, so this code cannot tell an absent service from a registered service that cannot be used (for example, a factory registration, which throws "is async"). The analytics door documents the opposite stance: a throw is UNUSABLE and refuses (service-analytics/src/plugin.ts:~683-740). Meanwhile .changeset/36839-knowledge-exposure-fls.md:17 and knowledge.mdx:322 both say "Every gate fails closed: a lookup that throws … keeps the source out", which is false for this lookup. The fix is one of these:

      • (preferred) read absence from the registry, and let any other throw propagate into admitObject, which already fails closed. Add one test for this.
      • Or narrow both sentences to say what the code does.

      mcp/src/plugin.ts:515-521 uses the same swallow, which is why this is a one-round fix and not a redesign.

    • nit N1: row-serving-door-exposure.pin.test.ts:37-39,153 describes "the MCP door's search_knowledge" and "the search_knowledge tool every door builds on it". At this head, no in-repo code serves that tool (only the name constant exists in spec). The sentence becomes true once feat(mcp,service-knowledge): serve search_knowledge on the MCP door, and say when a skill is withheld #36823 lands, which timing 甲 puts after this PR.

    • nit N2: knowledge.mdx:309 says "'*' meaning every field the object declares", but the code leaves out id. Harmless.

    • nit N3: knowledge-service.ts:378 awaits each object's admission in turn. Running them in parallel would cut latency; there is no correctness effect.

    • nit N4 (seat): the claim's file surface (comment 7121224645, never edited) does not list content/docs/permissions/system-context.mdx. The census gate required that file, and the PR body names it. Record this in the ACCEPT.

    • nit N5: content/docs/ai/knowledge-rag.mdx:76 could point to the §5 narrowing. Optional.

  • L2 face. record-recognisers --template --paths <10 files>: the paths alone decide no face, so the changeset's Clause-②: no line (with no arm) decides. Scope has no hits, no governed path is touched, and no L2 is owed at the declared line. One decision is left to the seat: execution-duties.md:106/108 says a runtime security-behaviour change is not clause ②, and only a narrowed published accept set takes the arm. But recent security narrowings fix(plugin-security)!: an app-authored elevation's reads and writes are judged by its caller's organization wall #36386 and fix(service-storage)!: stored bytes outside the inline allow-list are served as attachments, with nosniff and a sandbox CSP #36518 declared Clause-②: no (narrowing) with a ! title. If the seat revises the claim to (narrowing), these all become owed:
    • the ! title,
    • the dogfood battery,
    • a Skills-docs: line,
    • an L2 at CONTRACT_REVIEW_TIER over the whole non-prose diff.
  • Disclosure. The PR body, changeset and commits name the class (missing FLS and exposure enforcement on a row-serving door), the location and the functions. None of them gives a request body or step-by-step reproduction. Clean.
  • Out of scope. None filed. declaredFields accepts both the array and the record form of fields, the same as analytics' maskingRuleFields. I am not raising it.

Adversarial review (read-only, effort xhigh, on this head) — findings folded into this round

  • M1 above = its hole 1 (any throw from the security lookup read as "no security service"; the analytics door refuses instead).
  • S2 (should-fix) — packages/plugins/knowledge-ragflow/src/index.ts ~153/161/180 searches a whole dataset and stamps every hit with the searched source's id, ignoring the stored objectstack_source_id; KnowledgeService.search never checks a hit's origin. Two sources sharing a dataset ⇒ a search of an admitted source can return chunks of a refused one. Fix: filter or verify on the stored source id and drop hits whose source is not the searched one; pin it.
  • S3 (should-fix) — knowledge-service.ts ~343/352: the no-context / no-engine path skips admission on the premise that applyPermissionFilter drops every object-source hit, but ~479 keeps any hit without a sourceRecordId before checking the source kind. Fix: in those two cases drop object sources inside admitSources; pin it.
  • Nits (no push for these alone): sys_* check reads the raw object string, not the resolved schema name (knowledge-source-admission.ts ~172); '*' drift between indexing (every string key) and the gate (declared fields) (servedFieldsOf ~212 vs recordToDocument ~548).

Seat decisions on this round

  • Clause-②: stays no without a (narrowing) arm — execution-duties.md: a runtime permission/security behaviour change is not clause ②; what narrows here is what a restricted caller is served, not a published accept set.
  • N4: content/docs/permissions/system-context.mdx was required by a repo gate and is named in the PR body — accepted as a surface addition.

…udged object sources and foreign hits are never served

Claude-Session: https://claude.ai/code/session_01QSeKYoxFNWhVjbZhqgBjKQ
Co-authored-by: Claude <noreply@anthropic.com>
… lookup and the dropped hits

Claude-Session: https://claude.ai/code/session_01QSeKYoxFNWhVjbZhqgBjKQ
Co-authored-by: Claude <noreply@anthropic.com>
@github-actions github-actions Bot added size/xl and removed size/l labels Nov 24, 2026
@objectstack-fleet

Copy link
Copy Markdown
Contributor Author

repo:objectstack#4 · os-justin · session_01QSeKYpEsWWE9Y5YtSsDgqZ

席位核对 — L1 REWORK (round 2, small) · head 2c9abeffeb0e5b88fd6a3087743d41dbf28a0f32 · 2026-11-24T09:46Z

  • Delta since L1 REWORK at 774652cd63. Two commits: 1f57e48403 (code + pins) and 2c9abeffeb (sentences). 11 files, +250 −62. Checks at 2c9abeffeb: 60 success, 10 expected skip, 0 failed, 0 pending. l1-face: one flag, changeset for @objectstack/core, cleared as in round 1 (test file only; core ships dist). The changeset now also lists @objectstack/knowledge-ragflow (patch), which the diff touches.
  • Round-1 findings — all closed (seat read plus a read-only adversarial re-review on this head; it reasoned red-on-revert from the fixtures, it did not run the suites):
    • M1 closed. knowledge-service-plugin.ts:147-153: only the kernel's not-registered refusal (isServiceNotRegisteredError, :27-29) reads as absence. It matches both kernels' wording (core/src/kernel.ts:290-300, kernel-base.ts:94-101). Any other throw propagates into admitObject and refuses the object's sources (knowledge-service.ts ~383-391); no 500. Pins: knowledge-source-admission.test.ts:344, :350, :373.
    • S2 closed. knowledge-ragflow/src/index.ts:176-179 drops a chunk stamped with another source's id; knowledge-service.ts:247-255 drops any hit whose sourceId is not the searched source. Pins: ragflow-adapter.test.ts:123, knowledge-source-admission.test.ts:298.
    • S3 closed. knowledge-service.ts:369-381 searches no object source without a context or an engine; :506 drops an object-source hit without sourceRecordId; the system bypass at :367 is intact. Pins :259, :274, :286.
  • Findings this round
    • must-fix M2 — a false sentence. content/docs/protocol/knowledge.mdx ~329-332: "a hit is served only as the source it was searched for (an adapter answering another source's passage from a store two sources share has it dropped)". The service-level check sees only the sourceId an adapter reports; an adapter that stamps the searched source's id on every hit (as RAGFlow did before this PR) defeats it. True statement: the service drops a hit whose reported sourceId names another source, and the RAGFlow adapter drops a chunk stamped with another source's id. Say that, as the changeset already does.
    • should-fix S4 — pin what the RAGFlow filter rests on. index.ts:176-179 only works if /api/v1/retrieval echoes each chunk's metadata. If it does not, every chunk reads as unstamped and is kept. (Object-source re-checks already depend on that echo for objectstack_record_id, so this is a stated dependency rather than a new hole.) Do both:
      • for an object source, also send metadata_condition: { objectstack_source_id: source.id }, so the server filters too (the adapter already uses metadata_condition in deleteChunksByDocumentId). Leave file/http sources unconditioned, because RAGFlow-ingested chunks carry no stamp;
      • in ragflow-adapter.test.ts, use a fixture shaped like the documented retrieval answer (cite the RAGFlow API doc/version in a comment) and assert the request body for an object source carries the condition.
    • nit N6 (changeset). "only the kernel's not-registered answer reads as 'no security service'": a getService that returns null/undefined also reads as absent (plugin.ts:149). Say "a missing answer or the kernel's not-registered refusal".
    • nit N7 (changeset). "reported once at error": it is once per object per search. Say so.
    • nit N8 (changeset). "'*' meaning every declared field" → "every declared field except id", as knowledge.mdx now says.
    • nit N9 (no change asked). Absence is read from the kernel's message text. If that wording changes, the effect is fail-closed (noisy, safe).
  • Seat decisions unchanged. Clause-②: no (no (narrowing) arm); N4's surface addition stands.
  • Next. One small push (M2 + S4 + N6–N8). The seat reads the delta and lands it; no further adversarial round unless S4's change touches the admission path.

…sees; changeset wording

Claude-Session: https://claude.ai/code/session_01QSeKYoxFNWhVjbZhqgBjKQ
Co-authored-by: Claude <noreply@anthropic.com>
…owledge-exposure-fls

# Conflicts:
#	content/docs/permissions/system-context.mdx
… sentences that describe one

Claude-Session: https://claude.ai/code/session_01QSeKYoxFNWhVjbZhqgBjKQ
Co-authored-by: Claude <noreply@anthropic.com>
@objectstack-fleet

Copy link
Copy Markdown
Contributor Author

repo:objectstack#4 · os-justin · session_01QSeKYpEsWWE9Y5YtSsDgqZ

席位核对 — ACCEPT · L1 · head c4abc0caff3 · 2026-11-24T15:42Z

Delta over the seat's REWORK at head 2c9abeffeb0 (round 2, record ID: 7127868735). Three commits of the PR's own plus a merge of origin/main (305fe60e6e9):

  • da2eda43c23 — M2 (must-fix): closed. The hit-origin sentence in content/docs/protocol/knowledge.mdx now says what the service check sees (the sourceId an adapter reports) rather than promising that a shared-store passage is dropped. N6, N7, N8 (changeset wording): closed — "a missing answer or the kernel's not-registered refusal", "reported at error once per object per search", "'*' meaning every declared field except id".
  • 5cc0e977533 — the maintainer's ruling on security(knowledge): search hits skip the API-exposure decision and field-level read rules every other row-serving door applies, now that the MCP door serves search_knowledge #36839 (comment 7134290286, option B): the RAGFlow chunk filter and its test are reverted, @objectstack/knowledge-ragflow leaves the changeset with its sentence, and the package is retired on Retire @objectstack/knowledge-ragflow: package, settings option, docs and skill mentions #37004. The PR's own diff no longer touches packages/plugins/knowledge-ragflow/. S4 (pin what the RAGFlow filter rests on) is withdrawn with the filter it was about.
  • c4abc0caff3 — the revert had also removed the adapter-generic caveat on the hit-origin check; restored without the RAGFlow-specific tail ("two sources must not share one adapter-side store"). Docs only.
  • Merge of origin/main — one conflict, content/docs/permissions/system-context.mdx rows 45/46 (main changed 45, this PR 46), resolved keeping both; the census register reported current.

Shape unchanged: Fixes #36839, Clause-②: no (no (narrowing) arm, seat decision of round 1 stands), Metadata-protocol: none; 12 files against main, none governed; changeset @objectstack/service-knowledge patch. PR body updated to drop RAGFlow and cite the ruling.

Gates: check-runs at this head all green when posted (pr-state.mjs --pr 36850); locally 103 of 105 derived families exit 0, two NOT MEASURED for unbuilt out-of-diff dists (check:skill-examples, check:dual-build-cjs-loads), both run in CI.

No must-fix, no should-fix. Lands next; PR #36823 (#36650) merges main after it.

@objectstack-fleet
objectstack-fleet Bot marked this pull request as ready for review November 24, 2026 15:42
@objectstack-fleet
objectstack-fleet Bot added this pull request to the merge queue Nov 24, 2026
Merged via the queue into main with commit 7abf25f Nov 24, 2026
71 checks passed
@objectstack-fleet
objectstack-fleet Bot deleted the claude/issue-36839-knowledge-exposure-fls branch November 24, 2026 16:22
This was referenced Nov 24, 2026
Nenzyz pushed a commit to Nenzyz/objectstack that referenced this pull request Dec 1, 2026
…a restored record re-enters the index (objectstack-ai#37075)

Fixes objectstack-ai#36991

Clause-②: no
Metadata-protocol: none

## 维护者速读
-
用户能看到什么变化:挂了知识检索的应用里,知识源只索引符合条件的记录(例如只索引现行版本);记录改成不符合后,旧内容从检索结果里消失;从回收站恢复的记录,符合条件就能重新被搜到。
- 为什么做:知识检索平台化专题第一阶段的「结果要对」——此前记录变更时完全不看索引条件,草稿会进索引,失效内容一直搜得到。
- 出错会怎样:只影响挂了知识检索服务的应用的检索结果,保存记录本身不受影响;改动可直接撤回,撤回后回到旧行为。
- 要你做的:无。

## What changes

`KnowledgeService.handleRecordUpsert` no longer builds the document from
the event payload. With a data engine bound, each `object` source bound
to the object re-reads the row under the system context, `find(object, {
where: { $and: [where, { id }] }, limit: 1 }, { context: system })` (`{
id }` alone when the source has no `where`):

- a row comes back: the document is built from the re-read row through
the same `recordToDocument(source, objSource, row,
this.schemaFor(object))` gate as the reindex walk, so the
credential-class / `internal` withholding landed by objectstack-ai#36850 holds on this
path too, and the document carries the fields the source lists and the
record `title`, never a credential-class or `internal` field;
- no row: the document is deleted (idempotent).

The plugin's event bridge now routes `data.record.restored`
(`RECORD_RESTORED_EVENT` from `@objectstack/spec/data`) through the same
path; its comment and the `enableEventSync` option docs name all four
per-record events. With no data engine: a source without `where` still
builds from the payload; a source with `where` is skipped and reported
once per source at `warn`. Syncs of one document
(`${source.id}:${recordId}`, upserts and deletes alike) run through an
in-process promise chain, dropped when idle, so two opposite events
cannot interleave. The system context is one helper now shared with
`reindexSource` (same spelling it already used). No adapter-contract
member, no spec change, no queue.

`content/docs/protocol/knowledge.mdx` section 6 is rewritten to say
this, including the measured ordering below; it also drops the claim
that a bare `record.*` event is still accepted (the bridge has had no
branch for it).

### Item 6: where the event fires relative to the write's transaction
(measured on origin/main 8aecf6d)

- `data.record.created` is published at
`packages/objectql/src/engine-insert.ts:1716`, inside the engine body
that `insert` wraps in its own unit when it opens one
(`engine-insert.ts:386`, `executeWithMiddleware(opCtx, inOwnUnit(...))`,
closing at :1805); `data.record.updated` at `engine-update.ts:2445`,
inside `inOwnUnit` opened at `engine-update.ts:529`. So both fire before
that unit, or a caller's `engine.transaction(...)`, commits.
- `publishDataEvent` awaits `realtimeService.publish`
(`engine-realtime-publish.ts:484`), and the in-process adapter awaits
each subscriber
(`packages/services/service-realtime/src/in-memory-realtime-adapter.ts:98`),
so the knowledge handler runs inside the write's async context. A read
with no explicit transaction takes the ambient one
(`engine-driver-options.ts:304-306`), so the re-read sees the row the
write just made. A rolled-back unit leaves the index wrong until the
row's next event or a `reindexSource`, in one of two ways: if the
uncommitted row matched, the document stays built from a row that never
committed (as the payload path did); if it did not match, the document
was deleted, so the committed row, which may still match, is missing
from the index (new with the re-read). Because the sync is inline, a
write's sync can also wait behind an earlier in-flight sync of the same
document (on a single-connection pool, up to the acquire timeout); the
index still ends consistent.
- `data.record.restored` is published at `recycle-bin/restore.ts:470`,
after `writeBack` (:451) has run and committed the restore's own unit
(`restore.ts:756`).
- Bulk `data.records.*` events stay uncovered; the existing warn and doc
callout say so.

## Tests

`src/__tests__/event-sync-data-events.test.ts` is rewritten (it asserted
building from `after`): the bridge cases now cover
`data.record.restored`, and the sync cases run the real plugin and
service against an engine double whose `find` applies scalar equality
and `$and`, refuses any other operator by throwing, and applies `limit`
by presence after the filter. One test per acceptance item: enter on
match; does not enter when not matching; exit when a record stops
matching (and search no longer finds it); no `where`; payload missing a
content field; restored and matching is searchable; restored but not
matching is not indexed; no engine without `where`; no engine with
`where` (skipped, one warn across two events); and three two-event races
(match then no match, no match then match, update then delete) each
ending consistent with the database. In `knowledge-service.test.ts` the
event-path withholding pin now feeds a payload carrying only the id and
a re-read row carrying the credential and internal fields, under `'*'`
and named explicitly.

Ablations, each through `scripts/ablation-replace.mjs` (anchor hit 1 to
0, blob changed, restored to HEAD with `git diff HEAD` empty); the test
imports the source by relative path, so no `dist/` leg:

| Mutation | Red |
|---|---|
| re-read `where` reduced to `{ id }` | 5 of 23 (query shape, not
matching, stops matching, restored not matching, match-then-no-match
race) |
| serialization removed from the upsert path | 3 of 23 (all three races)
|
| `RECORD_RESTORED_EVENT` dropped from the bridge | 2 of 23 (restored
routing, restored searchable); a first attempt with the anchor ending in
a bare close-paren-brace was refused by the tool before any run
(replacement count did not move), and was re-run with a unique anchor |
| document built from the payload instead of the re-read row | 3 of 51
across both files (both withholding pins, missing-content-field) |

## Acceptance notes

- Under `contentFields: ['*']` the event-path document now carries every
string field of the re-read row, exactly what `reindexSource` already
sends for the same row; explicit lists send only the listed fields.
Retiring `'*'` is the epic's row 3, not this card.
- The per-document chain orders syncs in one process only; two processes
publishing for one row are not ordered by it (the card scopes item 5 to
in-process).
- The sync stays inline with the write (as before): a write now also
waits for one system-context read per bound source.

## Verification

Two minutes: `pnpm --filter @objectstack/service-knowledge exec vitest
run src/__tests__/event-sync-data-events.test.ts` should print `Tests 23
passed (23)`.

Read first, by risk:
1. `packages/services/service-knowledge/src/knowledge-service.ts`:
`syncRecord` (the re-read and the miss-means-delete branch) and
`serializeRecordSync`.
2.
`packages/services/service-knowledge/src/knowledge-service-plugin.ts`:
the event-bridge branch now including `RECORD_RESTORED_EVENT`.
3. `content/docs/protocol/knowledge.mdx` section 6: the ordering
statement.

Container run (head 53f2e69, this worktree; re-run at 4ab8a4f after
the text-only patch round: `pnpm --filter @objectstack/service-knowledge
test` VERDICT command-exit 0, `Test Files 8 passed (8)`, `Tests 117
passed (117)`):

<details><summary>Package tests and typecheck</summary>

- `pnpm --filter @objectstack/service-knowledge test`: VERDICT
command-exit 0, `Test Files 8 passed (8)`, `Tests 117 passed (117)`
(event-sync file 23, knowledge-service file 28).
- `pnpm --filter @objectstack/service-knowledge typecheck`: VERDICT
command-exit 0; `check:test-typecheck: OK`, 0 files / 0 errors.
- Dependency closure built first: `pnpm --workspace-concurrency=2
--filter '@objectstack/service-knowledge^...' build`, VERDICT
command-exit 0.

</details>

<details><summary>Derived gate families (dispatch-gates --commands,
100)</summary>

- 98 exit 0, among them `check:system-context-census`,
`check:query-options-erasure`, `check:where-matcher`,
`check:objectql-double-limit`, `check:engine-double-contract`,
`check:doc-authoring`, `check:issue-citations`, `check:nul-bytes`.
- 2 NOT MEASURED, exit 3 PREREQUISITE NOT MET (unbuilt packages outside
this diff's closure): `pnpm --filter @objectstack/spec run
check:skill-examples` (needs `client-react` dist), `pnpm
check:dual-build-cjs-loads` (needs every package's dist). Declared to
CI.
- `dispatch-gates --ran`: 100 derived, 98 run, 2 NOT-MEASURED (derived
from the recorded exit 3), 0 UNRUN.
- Repo-wide lint, `test:repo` and full dogfood are CI's (no `!`, no
narrowing arm).

</details>

---

_Generated by [Claude
Code](https://claude.ai/code/session_01QSeKYpRrYuqSLCvbSk9zrL)_

<!-- signed: repo:objectstack#4 · os-justin ·
session_01QSeKYpRrYuqSLCvbSk9zrL -->

---------

Co-authored-by: Claude <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

documentation Improvements or additions to documentation size/l tests tooling Fix lands in tooling, not a product package — enters pm:queue only with Unblocks: or a named surface

Projects

None yet

2 participants