Repository navigation
Commit e6b424b
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
File tree
- .changeset
- content/docs/permissions
- packages
- services/service-knowledge/src
- spec/liveness
- scripts
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
| 1 | + | |
| 2 | + | |
| 3 | + | |
| 4 | + | |
| 5 | + | |
| 6 | + | |
| 7 | + | |
| 8 | + | |
| 9 | + | |
| 10 | + | |
| 11 | + | |
| 12 | + | |
| 13 | + | |
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
709 | 709 | | |
710 | 710 | | |
711 | 711 | | |
712 | | - | |
713 | | - | |
714 | | - | |
715 | | - | |
| 712 | + | |
| 713 | + | |
| 714 | + | |
| 715 | + | |
716 | 716 | | |
717 | 717 | | |
718 | 718 | | |
| |||
Large diffs are not rendered by default.
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
| 1 | + | |
| 2 | + | |
| 3 | + | |
| 4 | + | |
| 5 | + | |
| 6 | + | |
| 7 | + | |
| 8 | + | |
| 9 | + | |
| 10 | + | |
| 11 | + | |
| 12 | + | |
| 13 | + | |
| 14 | + | |
| 15 | + | |
| 16 | + | |
| 17 | + | |
| 18 | + | |
| 19 | + | |
| 20 | + | |
| 21 | + | |
| 22 | + | |
| 23 | + | |
| 24 | + | |
| 25 | + | |
| 26 | + | |
| 27 | + | |
| 28 | + | |
| 29 | + | |
| 30 | + | |
| 31 | + | |
| 32 | + | |
| 33 | + | |
| 34 | + | |
| 35 | + | |
| 36 | + | |
| 37 | + | |
| 38 | + | |
| 39 | + | |
| 40 | + | |
| 41 | + | |
| 42 | + | |
| 43 | + | |
| 44 | + | |
| 45 | + | |
| 46 | + | |
| 47 | + | |
| 48 | + | |
| 49 | + | |
| 50 | + | |
| 51 | + | |
| 52 | + | |
| 53 | + | |
| 54 | + | |
| 55 | + | |
| 56 | + | |
| 57 | + | |
| 58 | + | |
| 59 | + | |
| 60 | + | |
| 61 | + | |
| 62 | + | |
0 commit comments