Skip to content

Commit e6b424b

Browse files
refactor(service-knowledge): split KnowledgeService into five concern modules behind a delegating facade (#38700)
<!-- claude-projects-attribution: {"github_login":"os-warren"} --> _Requested by **Warren** · [project thread](https://claude.ai/code/project/chan_01U5RdnAAmkSQmZbqh6FtqZ8?thread=cmsg_01U5RdnAAmkSQmZbqh6FtqZ8W62rw26qiBZJAr6pmoyBhB)_ Fixes #38660 Clause-②: no Metadata-protocol: none ## 维护者速读 - 用户无感:知识检索服务的内部代码按功能拆成五个文件,检索、索引构建、记录同步和保存校验的行为都不变。 - 属于知识检索专题:原来五千多行挤在一个文件里,后面的对账、保存校验、检索改进几张卡只能排队改它;拆开后可以各改各的文件、并行推进。 - 若拆分有误,会表现为知识检索、索引或记录同步出错;这次只搬代码,整体撤回这次合并即可恢复原状。 - 改动超过三千行,需要你批准后才能合并。 ## What changes `packages/services/service-knowledge/src/knowledge-service.ts` goes from **5,571 to 1,658 lines** and is now a facade: `KnowledgeService` keeps every field, its constructor and every member with its name, signature and (for a public member) docblock, and each moved member forwards to its body in one call. Move-only: no member is renamed, no behaviour changes, nothing is added to or removed from the package entry (`index.ts` is untouched). The shape is the one the earlier facade splits use (`SqlDriver` and objectql `engine.ts`): each body is a module-level function whose `this` is typed as the part of a per-module host interface it reads; each host member is typed as the class member (`KnowledgeService['x']`), so a member renamed or retyped on the class is a compile error in the facet. The class's one static block builds the host once per service (`knowledge-service-host.ts`): methods go as closures that call the service at call time (an instance spy or a subclass override is still the one reached), fields as getters, plus a setter for the six fields a body assigns. | New module | Lines | What it holds | |---|---|---| | `knowledge-service-sources.ts` | 415 | adapters, the source registry, enablement | | `knowledge-service-indexing.ts` | 1,483 | build, index state, durable build records, reconcile | | `knowledge-service-record-sync.ts` | 944 | record sync, sync state and dead letters, backlog | | `knowledge-service-search.ts` | 1,147 | search and answer, freshness, scope narrowing | | `knowledge-service-admission.ts` | 580 | save admission, tenancy posture, organization and permission scoping | | `knowledge-service-top-level.ts` | 1,067 | every top-level declaration of the old file other than the class (the options/logger/held-reading shapes, helpers, constants, refusal texts, record-to-document assembly), moved whole and in order | | `knowledge-service-host.ts` | 62 | the host holder (built once per service, kept in a WeakMap) and the intersection of the five host interfaces | None of the names collides with the existing `knowledge-build.ts`, `knowledge-build-actions.ts`, `knowledge-record-sync-queue.ts`, `knowledge-sync-state.ts`, `knowledge-source-admission.ts`, `knowledge-search-scope.ts`, `knowledge-organization-scope.ts` or `split/`, and nothing was folded into those modules. ### Every moved member and its new file `*` marks a public member (its docblock stays on the class); every other member is private and its docblock moved with its body. | File | # | Members | |---|---|---| | `knowledge-service-sources.ts` | 25 | `settleEnablement`*, `registerAdapter`*, `getAdapter`*, `adapterIdFor`*, `boundAdapterId`*, `refuseUnplacedSource`, `reportUnmountedAdapters`*, `listAdapters`*, `registerSource`*, `registerMetadataSource`*, `metadataSources`*, `onSourcesChanged`*, `sourcesChanged`, `unregisterSource`*, `dropMetadataSource`*, `forget`, `listSources`*, `describeSources`*, `getSource`*, `describeSource`*, `handed`, `handedSources`, `adapterLabel`, `faceOfKey`, `requireEntry` | | `knowledge-service-indexing.ts` | 32 | `planIndex`, `prepareDocuments`, `readChunkTarget`, `reindexSource`*, `reindexWith`, `walkObjectSource`, `completeBuild`, `readIndexStateOf`, `buildRecord`*, `rebuildSource`*, `rebuildOf`, `buildUnderLease`, `syncStateIdentity`, `syncStateWriteFailed`, `storedCounts`, `recordBuildStart`, `recordBuildProgress`, `recordBuildEnd`, `closeStaleBuild`, `closeInterruptedBuilds`*, `buildSourcesAtBoot`*, `buildReloadedSource`*, `buildIfDue`, `stopBuilds`*, `reconcileSources`*, `enqueueReconcile`, `reconcilePass`, `reconcileOf`, `reconcileExclusion`, `requestReconcile`*, `armReconcile`, `cancelPendingReconcile` | | `knowledge-service-record-sync.ts` | 29 | `recordSources`*, `hasDurableSyncState`*, `syncStateOf`*, `pendingRecordSyncs`*, `recordSyncFailure`*, `requestSourceReconcile`, `clearRepairedFailures`, `deadLettersOf`, `recordSyncQueued`* (getter), `enqueueRecordSync`*, `publishRecordSyncs`, `processRecordSync`*, `resolveRecordSync`, `coveredByBuild`, `processRecordSyncBatch`*, `syncRecordGroup`, `recordSyncWaiting`, `sourceRowCount`, `considerBacklogReconcile`, `syncRows`, `handleRecordUpsert`*, `syncRecord`, `syncRow`, `writeSynced`, `reportUnindexable`, `reportWhereUnenforceable`, `serializeRecordSync`, `schemaFor`, `handleRecordDelete`* | | `knowledge-service-search.ts` | 19 | `search`*, `searchWithRefusals`*, `searchByKey`, `sourcesGroupableBy`, `groupKeyOf`, `affinityOrderFor`, `affinityFactsOf`, `answerByRecord`, `checkFreshness`, `dropUnverifiedHits`, `repairStale`, `planSearches`, `unprovenIndex`, `searchRound`, `sourcesInScope`, `sourcesNarrowedToVisible`, `readVisibleIds`, `checkScope`, `resolveSearchTargets` | | `knowledge-service-admission.ts` | 9 | `admitSources`, `admissionDeps`, `admitAuthoredSource`*, `unmountedAdapterSaveText`, `reportGateFailure`, `readTenancyPosture`, `scopeByOrganization`, `sourcesForObject`, `applyPermissionFilter` | 114 members moved. **Stay on the class**, as they were: the 25 fields; eight members that were already one-call delegations at the base (`heldReading`, `adapterFor`, `indexedSources`, `label`, `readIndexState`, `useRecordSyncQueue`, `facedRefusals`, `routeRecordSyncs`); and two `exceptions` rows (below). ### The facade gate `scripts/facade-delegation-registry.json` gains a `facades` row for `KnowledgeService`, a `ceilings` row for `knowledge-service.ts` (`baseLines` 1658 at `baseCommit` 4c4a984, `maxLines` 1758 = `CEILING_MARGIN` 100, ruling 6897467376), and two `exceptions` rows (card #38660): - `constructor`: state-owning, it reads `defaultTopK` and `enabledByConfiguration` off the options into the instance's own fields (the card's "facade keeps fields, constructor"). - `knowledgeTools`: bare-this, its body hands the service itself to `createKnowledgeTools(this)`; a facet body is handed the host, so moving it would hand the tool executor the host instead of the service. The gate's self-test (N7) holds `DECLARED_WATCH_HINTS` equal to the registry's facade files, so `scripts/check-facade-delegation-only.mjs` gains the one path string; nothing else in the gate changes. ### Three generated or ledgered consequences of the move - `content/docs/permissions/system-context.mdx`: the four `isSystem` read sites (`admitAuthoredSource`, `admitSources`, `applyPermissionFilter`, `searchByKey`) now live in the admission and search modules; the generated site register was rewritten by `node scripts/check-system-context-census.mjs --write` (four anchor paths, nothing else on the page). - `scripts/tenant-audit-census.mjs`: one `UNTYPED_RECEIVERS` row for `knowledge-service-record-sync.ts`, receiver `adapter` (`this.adapterFor(source)` read through the host, `engine: false`), the same receiver the existing `knowledge-reap-guard.ts` row already rules on. Inside the class the census read the method's return type; through the host it cannot. - `packages/spec/liveness/knowledge_source.json`: the ledger cited ten bodies as `knowledge-service.ts#NAME`; `check:liveness` resolves the symbol in the cited file, and `documentKeyOf` no longer lives there, so the gate turned red. Each of the ten citations now names the module that holds the body (`dropMetadataSource` in sources; `walkObjectSource`, `reindexWith`, `buildIfDue` in indexing; `syncRecord` in record sync; `admitAuthoredSource` in admission; `affinityOrderFor` in search; `recordToDocument`, `objectSourcesFor`, `documentKeyOf` in top-level). No verdict or other text changes. The ledger ships in `@objectstack/spec`, so the changeset names that package with a `patch` too. ### Net growth beyond a pure move (package source: 5,571 lines before, 7,356 after) - 114 one-call stubs on the class (the bodies' signatures kept; 7 non-literal parameter defaults become `?` on the stub and stay on the facet, which emits the same declaration; `async` dropped on the stubs so each returns the facet's own promise, the `SqlDriver` precedent). - The static host block on the class: 120 lines. - Five host interfaces, one per facet module: 220 lines; a `this` parameter on each facet function that reads the service (110 of 114). - 44 one-line docblocks on facet functions: 40 point a public member's body at the class's docblock, 4 name a private member that had none. - Module headers (about 30 lines each) and the import blocks of the seven new modules. - The re-export block in `knowledge-service.ts` (every name it exported before is still exported from it), and `export` added to 43 top-level declarations a facet or the facade reads (none reaches `index.ts`). - `knowledge-service-host.ts`: 62 lines. - No type is re-declared. ### Published bytes and the changeset The package's `dist` changes (its code moves between chunks), so this is not `skip-changeset`: one `patch` changeset for `@objectstack/service-knowledge` (and `@objectstack/spec`, for the ledger above). The published declaration is unchanged where it is public: built before and after, `dist/index.d.ts` carries the same 95 top-level declarations with the same text (94 byte-identical, imports and the export list equal as sets); the one that differs is `KnowledgeService`, whose declaration is line-for-line identical once comments are set aside: the 70 private members whose docblocks moved with their bodies lose those comments. The bundle lists its declarations in another order. `dist/testing.d.ts` is byte-identical. ## Tests No test file changed. Every moved body was checked as a move, not a rewrite: a throwaway verifier (not committed) proves each of the 114 functions' body, parameters, type parameters, return type and `async` are token-identical to the base member, every string and template literal byte-identical, and each of the 68 top-level declarations byte-identical but for an added `export`; it reds on a one-character change (negative control). Readings at head `ad4f458a7c` unless a block says otherwise. <details><summary>service-knowledge suite and typecheck at ad4f458: 25 files, 836 tests pass</summary> `os-verify-lock.sh -c 'pnpm --filter @objectstack/service-knowledge test && pnpm --filter @objectstack/service-knowledge typecheck'`: `Test Files 25 passed (25)`, `Tests 836 passed (836)`, typecheck (tsc plus `check:test-typecheck`) clean, `VERDICT command-exit 0`. The same 25 files and 836 tests as on `main`; no test file changed. </details> <details><summary>knowledge pins in other packages at 5fffac6: all pass</summary> Run at the merge head `5fffac643b`; between it and `ad4f458a7c` the package source differs only in seven comment lines (facet docblock wording and two module headers), plus the liveness ledger and the changeset. - core row-serving and knowledge pins: 3 files, 34 tests - service-knowledge-memory: 2 files, 56 tests - service-knowledge-turso: 3 files, 267 tests - mcp: 1 file, 22 tests - runtime: 4 files, 198 tests - service-settings: 4 files, 192 tests - objectql: 1 file, 7 tests - rest: 1 file, 82 tests - spec token-estimate: 1 file, 29 tests - cli pin: 1 file, 2 tests - NOT MEASURED: service-knowledge-pgvector live tests, reason: they need a running Postgres, which this container does not have; CI runs them. </details> <details><summary>Derived gate families at ad4f458: 121 derived, 118 exit 0, 3 NOT MEASURED</summary> `node scripts/pm/dispatch-gates.mjs --commands` (no paths; derived from the tree of objectstack-ai/objectstack at `ad4f458a7c`) named 121 commands; all 121 were run, each exit code captured before any pipe, and `--ran` reconciled the record: `121 derived famil(ies) accounted for — 118 run, 3 NOT-MEASURED (3 DERIVED from a recorded exit 3)`. Among the 118 at exit 0: `check-facade-delegation-only` (`KnowledgeService`: 150 members, 123 delegations, 25 fields, 2 named exceptions; `knowledge-service.ts` 1658 lines, ceiling 1758) and its self-test, `tenant-audit-census` and its self-test, `check:system-context-census`, spec `check:liveness`, `check:empty-state`, the changeset gates, `check-plugin-teardown-shape --self-test`, `check:platform-checklist` and `check:pm-dispatch-gates`. NOT MEASURED (each exited 3, prerequisite not met: they read the built `dist/` of every package, and this container did not build the whole workspace; CI runs them): - `pnpm --filter @objectstack/spec run check:skill-examples` - `pnpm check:dual-build-cjs-loads` - `pnpm check:published-readme-exports` `node scripts/check-platform-checklist.mjs --changed-from origin/main`: exit 0, no anchored file in the change set. </details> <details><summary>Published declaration, built before and after</summary> `dist/index.d.ts`: 95 top-level declarations before and after; 94 byte-identical, imports and the export list equal as sets. `KnowledgeService` is line-for-line identical once comments are set aside (70 private members lose the docblocks that moved with their bodies). `dist/testing.d.ts`: byte-identical. </details> ## Acceptance notes - `knowledge-service.ts` is 1,658 lines, below the 2,000 bar; what remains is the public docblocks (the published contract), the 25 documented fields, the stubs and the host block. - Five files outside the package change because they cite the moved code, none in behaviour: the facade gate's watch-hint list and its registry, one tenant-audit census row, the generated `isSystem` register on the system-context page, and the `knowledge_source` liveness ledger. These are additions to the claim's file surface, declared here. - The cards that follow on the new files (reconcile, save admission, adjacent passages) land in `knowledge-service-indexing.ts`, `knowledge-service-admission.ts` and `knowledge-service-search.ts` respectively. ## Verification Read first, by risk: 1. `knowledge-service.ts`, the `static` block at the end of the class: every field a body assigns needs its setter there (six do), or the write lands on nothing; the five host interfaces type-check that every member a body reads is there. 2. `knowledge-service-host.ts`: the host is built once per service and cached, so a body's `this` is the same object across calls. 3. `knowledge-service.ts`, the stubs of `registerMetadataSource`, `planIndex`, `reindexSource`, `reconcileSources`, `search`, `searchWithRefusals` and `answerByRecord`, whose non-literal defaults moved to the facet. Two-minute check: `pnpm --filter @objectstack/service-knowledge test` (expect 25 files, 836 tests passing, the same suite as `main`) and `node scripts/check-facade-delegation-only.mjs` (expect the `KnowledgeService` line: 150 members, 123 delegations, 25 fields, 2 named exceptions, and `knowledge-service.ts: 1658 lines, ceiling 1758`). Signed: repo:objectstack#2 · os-warren · session_01JQwxbZLuMpo8YX4ACmyoNd --- _Generated by [Claude Code](https://claude.ai/code/session_01JQwxbZLuMpo8YX4ACmyoNd)_ 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01JQwxbZLuMpo8YX4ACmyoNd --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 751e839 commit e6b424b

14 files changed

Lines changed: 6162 additions & 4333 deletions
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
---
2+
'@objectstack/service-knowledge': patch
3+
'@objectstack/spec': patch
4+
---
5+
6+
refactor(service-knowledge): `KnowledgeService` keeps its members and forwards each to the module that owns its concern
7+
8+
Clause-②: no
9+
Metadata-protocol: none
10+
11+
An internal move with no behaviour change. The bodies of `KnowledgeService` now live in five modules beside it (adapters and sources; build, index state and reconcile; record sync; search; save admission and scoping), and each member of the class forwards to its body in one call. Every member keeps its name, signature and docblock, so the package's public declaration is unchanged and nothing is added to or removed from the package entry. The published bundle's code moves between chunks; the published declaration file loses only the comments of private members and lists its declarations in another order.
12+
13+
`@objectstack/spec`'s `knowledge_source` liveness ledger cites each body at the module that now holds it.

‎content/docs/permissions/system-context.mdx‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -709,10 +709,10 @@ and CI refuses one that differs from what the tree produces.
709709
| `packages/runtime/src/sandbox/body-runner.ts#executionContextFromHook` | 1 | 65 |
710710
| `packages/services/service-automation/src/runtime-identity.ts#stampSystemInsertOwner` | 1 | 60 |
711711
| `packages/services/service-knowledge/src/knowledge-affinity.ts#resolveAffinityFacts` | 1 | 46a |
712-
| `packages/services/service-knowledge/src/knowledge-service.ts#admitAuthoredSource` | 1 | 46 |
713-
| `packages/services/service-knowledge/src/knowledge-service.ts#admitSources` | 1 | 46 |
714-
| `packages/services/service-knowledge/src/knowledge-service.ts#applyPermissionFilter` | 1 | 46 |
715-
| `packages/services/service-knowledge/src/knowledge-service.ts#searchByKey` | 1 | 46 |
712+
| `packages/services/service-knowledge/src/knowledge-service-admission.ts#admitAuthoredSource` | 1 | 46 |
713+
| `packages/services/service-knowledge/src/knowledge-service-admission.ts#admitSources` | 1 | 46 |
714+
| `packages/services/service-knowledge/src/knowledge-service-admission.ts#applyPermissionFilter` | 1 | 46 |
715+
| `packages/services/service-knowledge/src/knowledge-service-search.ts#searchByKey` | 1 | 46 |
716716
| `packages/services/service-mailbox/src/ingest/mail-ingest-service.ts#authorizeRematch` | 1 | 47b |
717717
| `packages/services/service-mailbox/src/ingest/mail-ingest-service.ts#ingest` | 1 | 47b |
718718
| `packages/services/service-mailbox/src/mail-read-visibility.ts#gateMiddleware` | 1 | 47 |

‎packages/services/service-knowledge/src/knowledge-service-admission.ts‎

Lines changed: 580 additions & 0 deletions
Large diffs are not rendered by default.
Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* [#38660] The one host per `KnowledgeService` that its facets
5+
* (`knowledge-service-sources.ts`, `-indexing.ts`, `-record-sync.ts`,
6+
* `-search.ts` and `-admission.ts`) are handed as `this`.
7+
*
8+
* {@link KnowledgeServiceHost} is every facet's host at once: each facet declares,
9+
* in its own module, the members its bodies read (its `...Host` interface,
10+
* each member typed AS the class member), and each facet method types its
11+
* `this` as the `Pick` of that interface it reads.
12+
*
13+
* The host is filled by the factory `KnowledgeService`'s static block installs,
14+
* the one place that can read the class's private members; it is built on the
15+
* first call that needs it and kept for the service's life. A method goes as a
16+
* closure that calls it on the service at call time, so an instance spy or a
17+
* subclass override is still the one reached; a field goes as a getter (and a
18+
* setter when a body assigns it), so a body reads and writes the service's own
19+
* state. This module imports the class and the facets for types only, so it
20+
* forms no evaluation cycle. `index.ts` re-exports nothing from it.
21+
*/
22+
23+
import type { KnowledgeService } from './knowledge-service.js';
24+
import type { KnowledgeSourcesHost } from './knowledge-service-sources.js';
25+
import type { KnowledgeIndexingHost } from './knowledge-service-indexing.js';
26+
import type { KnowledgeRecordSyncHost } from './knowledge-service-record-sync.js';
27+
import type { KnowledgeSearchHost } from './knowledge-service-search.js';
28+
import type { KnowledgeAdmissionHost } from './knowledge-service-admission.js';
29+
30+
/** What every facet reads of the service: the one host the static block builds. */
31+
export type KnowledgeServiceHost = KnowledgeSourcesHost &
32+
KnowledgeIndexingHost &
33+
KnowledgeRecordSyncHost &
34+
KnowledgeSearchHost &
35+
KnowledgeAdmissionHost;
36+
37+
/** The host of each service: built on first use, kept for the service's life. */
38+
class KnowledgeServiceHostHolder {
39+
private readonly hosts = new WeakMap<KnowledgeService, KnowledgeServiceHost>();
40+
private build: ((service: KnowledgeService) => KnowledgeServiceHost) | undefined;
41+
42+
/** Called once, from `KnowledgeService`'s static block. */
43+
install(build: (service: KnowledgeService) => KnowledgeServiceHost): void {
44+
this.build = build;
45+
}
46+
47+
/** The host of `service`, built on first use. */
48+
of(service: KnowledgeService): KnowledgeServiceHost {
49+
let host = this.hosts.get(service);
50+
if (host === undefined) {
51+
if (this.build === undefined) {
52+
throw new Error('KnowledgeService has not installed its host factory');
53+
}
54+
host = this.build(service);
55+
this.hosts.set(service, host);
56+
}
57+
return host;
58+
}
59+
}
60+
61+
/** The one holder; `KnowledgeService`'s static block installs its factory. */
62+
export const knowledgeServiceHost = new KnowledgeServiceHostHolder();

0 commit comments

Comments
 (0)