@dsh-cc/tool-search 0.9.4 → 0.9.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.i18n.yaml CHANGED
@@ -2,5 +2,5 @@
2
2
  # side as of the last confirmed-consistent state. Both languages carry equal authority;
3
3
  # after editing either side, bring the other along and re-record with:
4
4
  # pnpm check:readme --write
5
- README.md: bc13632287366853350d5b3328bb41aec94e5c5a
6
- README.zh.md: 51b808f9d4f177cae462ad04ecda893de761f4de
5
+ README.md: 21c0e7ff49ced4e2f7b0591ad675ff989645ba32
6
+ README.zh.md: ecb6df7986ef29d5f3e1b44fa28b3dafbb5b1f92
package/README.md CHANGED
@@ -33,6 +33,61 @@ The design rides the repo's effect conventions:
33
33
  - **Deferred names never leak into the prompt.** Only activated (`alwaysLoad` or loaded) tools enter the schema; reserved-but-unloaded names are known for restriction/`toolOrder` purposes but never model-visible.
34
34
  - **ToolSearch itself is lazy, with hysteresis.** While the searchable pool is empty, only the `ToolSearch` *name* is reserved (restrictable, not visible); the first non-`alwaysLoad` deferred registration brings the tool into the model-visible set, and it then stays registered for the rest of the session even if the pool empties again — a mid-session removal would shift the assembled tool order and break the cached prefix. An empty pool also makes the tool's "tools are hidden, search to load them" description actively misleading, which is why it is withheld.
35
35
 
36
+ ## Semantic tool discovery (S1-05)
37
+
38
+ Lexical ranking cannot see a query that shares no literal token with a tool's metadata — a Chinese question against English metadata, or a paraphrase of the same request. The optional discovery layer puts an independent relevance judgment in front of the existing activation path: every admitted deferred candidate is scored against the query through the System One decision runtime (the optional `ctx.systemoneDecisions` service that the `decision-usage` plugin provides), and only candidates whose judged relevance **and** direct fit both clear their thresholds become activations. Tool names, schemas, and return messages still come from deterministic code; the model answers only "is this candidate relevant", with one question pair per candidate, so one candidate's metadata cannot contaminate another's judgment.
39
+
40
+ The layer is **off by default** and never rewrites the lexical path on its own:
41
+
42
+ | `mode` | Behavior |
43
+ | --- | --- |
44
+ | `off` | Default. Zero runner calls; `search()` and `execute` behave exactly as before, including result ordering and the default five items. |
45
+ | `shadow` | Runs the judgment and records the suggested difference; the original lexical hits still execute. |
46
+ | `active` | Activates the judged names in deterministic order (relevance, direct fit, lexical score, name ascending), capped at `min(max_results, max-activations)`. |
47
+
48
+ Settings live in the `cc-tool-discovery` namespace; raw keys are kebab-case:
49
+
50
+ | Key | Type, range | Default |
51
+ | --- | --- | --- |
52
+ | `mode` | `off \| shadow \| active` | `off` |
53
+ | `timeout-ms` | integer, 100–5000; time ceiling for the whole discovery transaction | `1200` |
54
+ | `max-input-tokens` | integer, 512–16384; per runner request, including questions and headroom | `4096` |
55
+ | `max-candidates` | integer, 1–128; cap on the complete eligible pool | `64` |
56
+ | `batch-size` | integer, 1–16 | `8` |
57
+ | `max-query-chars` | integer, 64–8192 | `2048` |
58
+ | `max-metadata-chars` | integer, 128–8192; combined cap per description and search hint | `2048` |
59
+ | `min-relevance-index` | finite number, 0–4; experimental threshold | `3` |
60
+ | `min-direct-fit` | number, 0–1; experimental threshold | `0.75` |
61
+ | `max-activations` | integer, 1–20 | `3` |
62
+ | `cache-entries` | integer, 0–1024; zero disables the cache | `128` |
63
+ | `cache-ttl-ms` | integer, 0–300000 | `60000` |
64
+
65
+ These thresholds are first-round evaluation parameters, not measured quality guarantees. Any invalid value disables the judgment entirely: the runner is not called, the lexical path runs, and the failure is reported once through `ctx.logger.warn`. The same whole-path fallback applies when the route, the service, or a complete answer is missing, and when a hard bound is exceeded — an oversized query or metadata field, a pool over `max-candidates`, a batch that cannot be split into whole groups that fit the request window, a timeout, caller cancellation, or a catalog/permission change before activation. A partial judgment is never blended with lexical hits, and a valid judgment that finds nothing relevant activates nothing (it is not backfilled from lexical hits). Admission is checked on both ends: a candidate the scope denies never enters the pool, and `activate()` re-checks the permission gate before loading, so a recommendation can never widen a scope.
66
+
67
+ The offline evaluator (`scripts/eval-discovery.mjs`) runs against one local, redacted corpus and never touches the network. It has four modes:
68
+
69
+ | `--mode` | Purpose |
70
+ | --- | --- |
71
+ | `replay` | **Oracle integrity pin.** The judgment is synthesized from each case's `expectedNames`, so an F1 number here would be tautological by construction. It stays a pure policy-layer pin — pool, questions, batching, scoring and selection against the redacted fixture — and is never gated on F1. |
72
+ | `selfcheck` | **Corpus health.** Schema integrity, the legacy subset floors, and the per-class coverage floors. |
73
+ | `judge-stub` | **The F1 gate arm CI runs.** A frozen, deliberately imperfect keyword/rule scorer over candidate metadata drives the real policy layer; gold labels are used for scoring only, never for judging, so the F1 line is meaningful and deterministic. |
74
+ | `live` | **Evidence, not a gate.** The shipped `createDiscoveryRuntime` driven through a scripted fake lane adapter: multi-batch sequences sharing one deadline, over-cap candidate pools, `unavailable`, cancellation, and the `exact` short-circuit. |
75
+
76
+ The `judge-stub` thresholds are pre-registered in the design doc (§ Scoring) and gated on the tune split only: aggregate restricted micro-F1 ≥ 0.85, per-class restricted micro-F1 ≥ 0.80 for classes with at least 12 items (and positives), and — because the negative-only class has no positives and its F1 is undefined — that class is gated on false-activation ≤ 0.10 plus exact-set accuracy 1.0 instead.
77
+
78
+ **Corpus schema v2** (`scripts/lib/eval-corpus.mjs`): `{ schemaVersion: 2, corpusVersion, description?, cases[] }`. `corpusVersion` is an integer bumped whenever the cases change, and every report pins it. Each case carries a `class` — the gating dimension, one of `direct-fit`, `lexical-trap` (lexical overlap / wrong-server traps), `multi-intent`, `negative-only` (`expectedNames: []`), `keyword-stuffing` (metadata keyword-stuffing) — plus optional `alsoClasses` for declared multi-label membership, which is how the corpus reaches ≥ 12 memberships per class without an exclusive split. The legacy `subset: chinese|synonym|none|restricted` filter and its floors are kept. A query may not equal a candidate's `name`: an exact-name query short-circuits the judge before it is ever called, so such a case could not measure judge quality.
79
+
80
+ **Splits.** `--split tune|held-out|full` (default `tune`). Ordering the cases by the hash of their id cuts the corpus 2/3 tune / 1/3 held-out; only `tune` is ever gated, `held-out` is reserved for the one-time flip evaluation, and `full` is for inspection.
81
+
82
+ Run either way:
83
+
84
+ ```bash
85
+ node packages/core/tool-search/scripts/eval-discovery.mjs --mode <mode>
86
+ pnpm --filter @dsh-cc/tool-search run eval:discovery -- --mode <mode>
87
+ ```
88
+
89
+ Every mode prints aggregate numbers, class labels and case ids only — never query text, candidate descriptions or notes. `replay` adds Recall@3 per subset beside the lexical control, activation precision, admission leaks and a reproducibility check; `judge-stub` prints the per-class F1 table and the gate verdict; `live` asserts the failure battery and reports micro-F1 plus nominal/tail latency ungated (p95 on a corpus this size is the ~3rd-largest sample). CI runs `selfcheck` and `judge-stub` only; no arm needs the network.
90
+
36
91
  ## Model Experience
37
92
 
38
93
  Turn one, the model sees only `ToolSearch` plus whatever is already loaded (including `alwaysLoad` tools) — or, in a session with no deferred tools at all, no `ToolSearch` either. It searches for a capability by keywords, and the result names the now-available tools. On the next turn those tools are first-class: declare them, call them. Already-loaded tools drop out of the deferred set, so a second search for them is correctly empty.
@@ -41,5 +96,5 @@ An empty search result always says *why*, so the model never mistakes "nothing d
41
96
 
42
97
  ## Known Limitations and Deferred Work
43
98
 
44
- - **Matching is lexical, not semantic.** Ranking uses weighted substring/token scoring; there is no embedding/vector search. This keeps the seam dependency-free and deterministic, at the cost of synonyms that share no token.
99
+ - **Matching is lexical unless discovery is enabled.** Ranking uses weighted substring/token scoring; there is no embedding/vector search. The optional S1-05 layer adds a model relevance judgment for synonyms and Chinese queries, but it is off by default and falls back to the lexical path on any failure.
45
100
  - **Global activation.** Loading happens on the host plane (global registration); a per-agent scope sees a loaded tool only if its restriction admits it. There is no per-conversation discovery history — loading is an in-memory effect, so a re-registered composition starts from the deferred pool again.
package/README.zh.md CHANGED
@@ -32,6 +32,61 @@ ctx.toolSearch.registerDeferred({
32
32
  - **延迟名字永不泄漏进提示词。** 只有已激活(`alwaysLoad` 或已加载)的工具才进 schema;被预留而未加载的名字仅用于限制/`toolOrder` 判定,不对外可见。
33
33
  - **ToolSearch 自身懒注册、带迟滞。** 可搜索池为空时只预留 `ToolSearch` 这个名字(可限制、不可见);首个非 `alwaysLoad` 的延迟注册才把它带进模型可见集,此后即使池再次清空也保持注册——会话中途注销会移动组装后的工具顺序、击穿缓存前缀。空池时该工具"工具被隐藏、搜索后加载"的描述会主动误导模型,这正是它在空池时不展示的原因。
34
34
 
35
+ ## 语义工具发现(S1-05)
36
+
37
+ 词法排序看不见与工具元数据不共享任何字面词元的查询——中文问题对上英文元数据,或同一个请求换一种说法。可选的发现层在既有激活路径前加一次独立的相关性判断:每个已准入的延迟候选都通过 System One 决策运行时针对查询打分(该运行时即 `decision-usage` 插件提供的可选 `ctx.systemoneDecisions` 服务),只有相关性判断**与**直接匹配度都越过阈值的候选才会成为激活项。工具名、schema 与返回消息仍由确定性代码产生;模型只回答"这个候选是否相关",每个候选一对问题,因此一个候选的元数据不会污染另一个的判断。
38
+
39
+ 该层**默认关闭**,且绝不会自行改写词法路径:
40
+
41
+ | `mode` | 行为 |
42
+ | --- | --- |
43
+ | `off` | 默认。零次 runner 调用;`search()` 与 `execute` 与之前完全一致,包括结果顺序与默认五条。 |
44
+ | `shadow` | 执行判断并记录建议差异;仍然执行原来的词法命中。 |
45
+ | `active` | 按确定性顺序(相关性、直接匹配度、词法分数、名字升序)激活判断出的名字,上限为 `min(max_results, max-activations)`。 |
46
+
47
+ 设置位于 `cc-tool-discovery` 命名空间;原始键为 kebab-case:
48
+
49
+ | 键 | 类型与范围 | 默认值 |
50
+ | --- | --- | --- |
51
+ | `mode` | `off \| shadow \| active` | `off` |
52
+ | `timeout-ms` | 整数,100–5000;整次发现事务的时间上限 | `1200` |
53
+ | `max-input-tokens` | 整数,512–16384;单次 runner 请求,含问题与余量 | `4096` |
54
+ | `max-candidates` | 整数,1–128;完整候选池上限 | `64` |
55
+ | `batch-size` | 整数,1–16 | `8` |
56
+ | `max-query-chars` | 整数,64–8192 | `2048` |
57
+ | `max-metadata-chars` | 整数,128–8192;描述与搜索提示各自的合并上限 | `2048` |
58
+ | `min-relevance-index` | 有限数,0–4;实验性阈值 | `3` |
59
+ | `min-direct-fit` | 数,0–1;实验性阈值 | `0.75` |
60
+ | `max-activations` | 整数,1–20 | `3` |
61
+ | `cache-entries` | 整数,0–1024;为零则关闭缓存 | `128` |
62
+ | `cache-ttl-ms` | 整数,0–300000 | `60000` |
63
+
64
+ 这些阈值是第一轮评估参数,而非已测的质量保证。任何一个值非法都会彻底关闭判断:不调用 runner,运行词法路径,并通过 `ctx.logger.warn` 只报告一次。同样的整路回退也适用于路由、服务或完整答案缺失,以及越过任何硬性边界的情况——查询或元数据字段过长、候选池超过 `max-candidates`、批次无法拆成装得进请求窗口的整组、超时、调用方取消,或激活前目录/权限发生变化。部分判断绝不与词法命中混合;判断有效但没有找到相关工具时不激活任何东西(不会用词法命中回填)。准入在两端都检查:作用域拒绝的候选根本不进池,`activate()` 在加载前再查一次权限闸,因此推荐绝不会扩大作用域。
65
+
66
+ 离线评估器(`scripts/eval-discovery.mjs`)只针对一份本地脱敏语料运行,全程不访问网络。它有四种模式:
67
+
68
+ | `--mode` | 用途 |
69
+ | --- | --- |
70
+ | `replay` | **oracle 完整性钉。** 判断由每个用例的 `expectedNames` 合成,因此这里的 F1 在构造上就是同义反复。它只作纯策略层钉——候选池、问题、分批、打分与选取,对照脱敏 fixture——永不因 F1 被门控。 |
71
+ | `selfcheck` | **语料健康度。** 校验 schema、既有的 subset 下限,以及按类的覆盖下限。 |
72
+ | `judge-stub` | **CI 运行的 F1 门禁臂。** 一个冻结的、故意不完美的关键词/规则打分器对候选元数据打分,驱动真实策略层;金标只用于算分,绝不参与判断,因此 F1 线既有意义又是确定性的。 |
73
+ | `live` | **证据臂,不做门禁。** 用真实的 `createDiscoveryRuntime` 通过脚本化的假 lane 适配器跑:共享同一截止时间的多批序列、超限候选池、`unavailable`、取消,以及 `exact` 短路。 |
74
+
75
+ `judge-stub` 的阈值在设计文档(§ Scoring,计分)里预先登记,且只对 tune 划分生效:受限 micro-F1 总体 ≥ 0.85;对至少有 12 条(且有正样本)的类,受限 micro-F1 ≥ 0.80;而 negative-only 类没有正样本、F1 无定义,故改为门控误激活率 ≤ 0.10 与精确集合准确率 1.0。
76
+
77
+ **语料 schema v2**(`scripts/lib/eval-corpus.mjs`):`{ schemaVersion: 2, corpusVersion, description?, cases[] }`。`corpusVersion` 是整数,用例一变就递增,每份报告都会带上它。每个用例带一个 `class`——即门控维度,取值为 `direct-fit`、`lexical-trap`(词法重叠/错误服务陷阱)、`multi-intent`、`negative-only`(`expectedNames: []`)、`keyword-stuffing`(元数据关键词堆砌)——外加可选的 `alsoClasses` 声明多标签归属;正是靠它在不做排他划分的前提下也能达到每类 ≥ 12 条归属。既有的 `subset: chinese|synonym|none|restricted` 过滤及其下限保留。查询不得等于某个候选的 `name`:精确名字查询会在判断器被调用之前短路,这种用例根本量不出判断质量。
78
+
79
+ **划分。** `--split tune|held-out|full`(默认 `tune`)。按用例 id 的哈希排序把语料切成 2/3 tune、1/3 held-out;只有 `tune` 会被门控,`held-out` 留给一次性的翻转评估,`full` 用于检视。
80
+
81
+ 两种运行方式:
82
+
83
+ ```bash
84
+ node packages/core/tool-search/scripts/eval-discovery.mjs --mode <mode>
85
+ pnpm --filter @dsh-cc/tool-search run eval:discovery -- --mode <mode>
86
+ ```
87
+
88
+ 每种模式只输出聚合数字、类标签与用例 id——绝不输出查询文本、候选描述或备注。`replay` 另按子集打印 Recall@3 并与词法对照并列,给出激活精确率、准入泄漏与可复现性检查;`judge-stub` 打印按类的 F1 表与门禁结论;`live` 断言故障电池,并无门控地报告 micro-F1 与标称/尾部延迟(这个规模的语料上 p95 只是第 3 大样本)。CI 只跑 `selfcheck` 与 `judge-stub`,没有任何模式需要联网。
89
+
35
90
  ## 模型体验
36
91
 
37
92
  第一轮,模型只看到 `ToolSearch` 加已加载的(包括 `alwaysLoad` 的)工具——而在完全没有延迟工具的会话里,连 `ToolSearch` 也不出现。它按关键字搜索某个能力,结果里点名现在可用哪些工具。下一轮这些工具就成头等公民:声明它们,调用它们。已加载的工具会退出延迟集合,因此再次搜索它们会正确地得到空结果。
@@ -40,5 +95,5 @@ ctx.toolSearch.registerDeferred({
40
95
 
41
96
  ## 已知限制与暂缓事项
42
97
 
43
- - **匹配是词法而非语义的。** 排序用加权的子串/词元打分;没有嵌入/向量检索。这让接缝保持零依赖且确定,代价是无法命中不共享词元的同义词。
98
+ - **匹配是词法的,除非启用了发现层。** 排序用加权的子串/词元打分;没有嵌入/向量检索。可选的 S1-05 层为同义词与中文查询补上一次模型相关性判断,但它默认关闭,且任何失败都会回退到词法路径。
44
99
  - **全局激活。** 加载发生在宿主平面(全局注册);某个 per-agent 作用域只有在它的限制放行时才能看到已加载的工具。没有按会话的记忆历史——加载是内存里的 effect,因此重新组装后又会从延迟池重新开始。
@@ -0,0 +1,208 @@
1
+ /**
2
+ * The in-process judgment cache of S1-05 tool discovery: a bounded LRU with
3
+ * lazy TTL expiry, plus same-key request coalescing with independent caller
4
+ * cancellation.
5
+ *
6
+ * Design: `docs/plans/2026-11-02-systemone-05-tool-discovery.md`
7
+ * § "Lifecycle, cache, and failure handling" and § "Settings". The protocol
8
+ * this file implements is the one shared with S1-06/S1-11/S1-12 and verified in
9
+ * `specs/tla/decision-gate-coalescing`:
10
+ *
11
+ * - **cache-then-coalesce**: a completed judgment is stored BEFORE waiters are
12
+ * woken, and an in-flight run is joined rather than duplicated;
13
+ * - **only complete answers are cached**: a rejected run (timeout, transport
14
+ * error, missing route, partial batch) and an abandoned run (every waiter
15
+ * left) store nothing;
16
+ * - **per-caller independent cancellation**: each waiter's own `AbortSignal`
17
+ * ends only that waiter's wait — nothing is published on its behalf — while
18
+ * the shared request keeps running for the others;
19
+ * - **last waiter aborts the request**: the underlying factory's signal fires
20
+ * only when the refcount drops to zero;
21
+ * - **post-await revalidation** stays with the caller (design step 9): this
22
+ * layer only guarantees that a run whose catalog/admission/identity/threshold
23
+ * inputs changed is a DIFFERENT key, so a stale judgment is never reused.
24
+ *
25
+ * The model's invariants map onto this file as `AbortOnlyWhenAllCancelled` and
26
+ * `SettledHoldsSlot` (the refcounted {@link Flight}), `CacheCompleteOnly` (a
27
+ * failed or abandoned run stores nothing), and `NoConsumeAfterCancel` (a
28
+ * cancelled waiter resolves `cancelled` and publishes nothing).
29
+ *
30
+ * There is no persistence, no background sweep, and no timer: an expired entry
31
+ * is discovered at read time and treated as absent.
32
+ *
33
+ * @module @dsh-cc/tool-search/discovery-cache
34
+ */
35
+ import type { DiscoveryRouteIdentity } from './discovery.ts';
36
+ /**
37
+ * Key-format version. Bumping it retires every previously stored entry without
38
+ * having to reason about collisions with an older field order.
39
+ */
40
+ export declare const DISCOVERY_CACHE_KEY_VERSION = "tool-discovery-key-v1";
41
+ /**
42
+ * The keyless route identity returned by `identifyRoute` (design
43
+ * § "File responsibilities": the consumer re-reads it after every await and
44
+ * compares all seven fields). One canonical declaration lives in the policy
45
+ * layer; it is re-exported here so cache-key consumers need a single import.
46
+ */
47
+ export type { DiscoveryRouteIdentity };
48
+ /**
49
+ * Every settings threshold that shapes a judgment, camelCase (design §
50
+ * "Settings"). These are part of the cache key because changing one changes
51
+ * which candidates fit the window and which answers survive the thresholds.
52
+ * The two CACHE knobs (`cacheEntries`, `cacheTtlMs`) are deliberately NOT here:
53
+ * they govern reuse, not what a judgment means.
54
+ */
55
+ export interface DiscoveryThresholds {
56
+ /** Time ceiling for the whole discovery transaction. */
57
+ readonly timeoutMs: number;
58
+ /** Per runner request, including questions and headroom. */
59
+ readonly maxInputTokens: number;
60
+ /** Cap on the complete eligible pool. */
61
+ readonly maxCandidates: number;
62
+ /** Candidates per runner request before window splitting. */
63
+ readonly batchSize: number;
64
+ /** Longest query, in characters, that may be judged. */
65
+ readonly maxQueryChars: number;
66
+ /** Combined per-field cap on the metadata sent for a candidate. */
67
+ readonly maxMetadataChars: number;
68
+ /** Experimental relevance threshold. */
69
+ readonly minRelevanceIndex: number;
70
+ /** Experimental direct-fit threshold. */
71
+ readonly minDirectFit: number;
72
+ /** Upper bound on activated names. */
73
+ readonly maxActivations: number;
74
+ }
75
+ /**
76
+ * Everything the design's § "Lifecycle, cache, and failure handling" requires
77
+ * in the key, in one value. The host resolves `project`/`session`/`agent`, and
78
+ * `originSeq` is the persisted session watermark (`Number(agent.session.seq)`)
79
+ * — never `events.length` (design § "Inputs, questions, and output").
80
+ */
81
+ export interface DiscoveryCacheKeyParts {
82
+ /** Project key resolved by the host. */
83
+ readonly project: string;
84
+ /** Session id. */
85
+ readonly session: string;
86
+ /** Agent id within the session. */
87
+ readonly agent: string;
88
+ /** Persisted sequence watermark at entry. */
89
+ readonly originSeq: number;
90
+ /** The raw query; trimmed by {@link buildDiscoveryCacheKey}. */
91
+ readonly query: string;
92
+ /** Hash of the full visible catalog. */
93
+ readonly catalogHash: string;
94
+ /** Hash of the scope's admission (permission) set. */
95
+ readonly admissionHash: string;
96
+ /** The full route identity and revision. */
97
+ readonly route: DiscoveryRouteIdentity;
98
+ /** Question-set version (`tool-discovery-v1`). */
99
+ readonly questionVersion: string;
100
+ /** Policy version (`tool-discovery-policy-v1`). */
101
+ readonly policyVersion: string;
102
+ /** Every threshold that shapes the judgment. */
103
+ readonly thresholds: DiscoveryThresholds;
104
+ }
105
+ /**
106
+ * Build the cache key for one discovery transaction.
107
+ *
108
+ * The fields are serialized in a fixed order as a JSON array, so a value can
109
+ * never bleed into the next slot (a length-prefixed/escaped join would have to
110
+ * re-derive that invariant). The query is trimmed first: `" x "` and `"x"`
111
+ * describe the same judgment and must share a key.
112
+ * @param parts - the transaction identity.
113
+ * @returns an opaque, deterministic key string.
114
+ */
115
+ export declare function buildDiscoveryCacheKey(parts: DiscoveryCacheKeyParts): string;
116
+ /**
117
+ * How one caller's wait ended: a complete judgment, or that caller's own
118
+ * cancellation. A cancelled caller must activate nothing (design §
119
+ * "Lifecycle, cache, and failure handling": cancellation is never backfilled
120
+ * with lexical activation), so the two outcomes are distinguished here instead
121
+ * of relying on a rejected promise.
122
+ */
123
+ export type DiscoveryRunOutcome<T> = {
124
+ readonly status: 'ok';
125
+ readonly value: T;
126
+ } | {
127
+ readonly status: 'cancelled';
128
+ };
129
+ /** Cache construction options. */
130
+ export interface DiscoveryCacheOptions<T> {
131
+ /** Maximum stored entries; `0` disables storage entirely (settings `cache-entries`). */
132
+ readonly maxEntries: number;
133
+ /** Entry lifetime in milliseconds; `<= 0` means no entry is ever reusable (settings `cache-ttl-ms`). */
134
+ readonly ttlMs: number;
135
+ /**
136
+ * Whether a completed judgment may be stored. Defaults to "only a fully
137
+ * validated `selected` judgment": the design forbids caching timeouts,
138
+ * cancellation, missing routes, partial batches and lexical fallbacks.
139
+ */
140
+ readonly cacheable?: (value: T) => boolean;
141
+ /** Clock, injectable for tests; defaults to `Date.now`. */
142
+ readonly now?: () => number;
143
+ }
144
+ /**
145
+ * In-process LRU cache with TTL and refcounted same-key coalescing.
146
+ *
147
+ * One instance per plugin fiber (design § "Lifecycle, cache, and failure
148
+ * handling": plugin unload aborts its requests and clears the cache — call
149
+ * {@link DiscoveryCache.clear} from the unload path). Storage is a `Map`, whose
150
+ * iteration order is the LRU order: a read re-inserts the entry at the MRU end,
151
+ * a write beyond `maxEntries` evicts from the front.
152
+ */
153
+ export declare class DiscoveryCache<T> {
154
+ private readonly entries;
155
+ private readonly flights;
156
+ private readonly maxEntries;
157
+ private readonly ttlMs;
158
+ private readonly cacheable;
159
+ private readonly now;
160
+ constructor(options: DiscoveryCacheOptions<T>);
161
+ /** Stored entries currently held (expired ones are dropped as they are read). */
162
+ get size(): number;
163
+ /** Keys with an in-flight shared run. */
164
+ get pending(): number;
165
+ /**
166
+ * Resolve one discovery transaction, reusing a cached judgment or joining the
167
+ * in-flight run for the same key.
168
+ *
169
+ * - a warm entry is returned without invoking `factory`;
170
+ * - concurrent callers with the same key share ONE `factory` invocation;
171
+ * - `signal` cancels only THIS caller's wait (resolving `cancelled`, so the
172
+ * caller activates nothing); the shared request is aborted only when the
173
+ * last waiter's signal aborts;
174
+ * - a factory rejection (timeout, transport error, partial batch) is
175
+ * propagated to every remaining waiter and caches nothing.
176
+ * @param key - the key from {@link buildDiscoveryCacheKey}.
177
+ * @param factory - performs the judgment; receives the shared abort signal.
178
+ * @param signal - the calling transaction's own cancellation signal.
179
+ * @returns the judgment, or `cancelled` when this caller left.
180
+ */
181
+ run(key: string, factory: (signal: AbortSignal) => Promise<T>, signal?: AbortSignal): Promise<DiscoveryRunOutcome<T>>;
182
+ /**
183
+ * Drop every stored entry and abort every in-flight run, resolving its
184
+ * waiters as cancelled. This is the plugin-unload / rollback hook (design
185
+ * § "Lifecycle, cache, and failure handling" and § "Release gates and
186
+ * rollback").
187
+ */
188
+ clear(): void;
189
+ /** A warm, unexpired entry, promoted to the MRU end. */
190
+ private read;
191
+ /** Store one completed judgment, evicting the least recently used entry. */
192
+ private store;
193
+ /** The flight for a key, starting one when this caller is the first. */
194
+ private flightOf;
195
+ /** Invoke the factory once and settle the flight when it finishes. */
196
+ private start;
197
+ /** Store (when allowed), then wake every remaining waiter with the value. */
198
+ private complete;
199
+ /** Propagate a failed run to every remaining waiter; nothing is cached. */
200
+ private fail;
201
+ /** Forget the flight for a key, leaving a newer one in place if it replaced this. */
202
+ private detach;
203
+ /** Remove one waiter, aborting the shared request when it was the last. */
204
+ private leave;
205
+ /** Register one caller as a waiter of a flight. */
206
+ private awaitFlight;
207
+ }
208
+ //# sourceMappingURL=discovery-cache.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"discovery-cache.d.ts","sourceRoot":"","sources":["../src/discovery-cache.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAiCG;AAEH,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,gBAAgB,CAAA;AAE5D;;;GAGG;AACH,eAAO,MAAM,2BAA2B,0BAA0B,CAAA;AAElE;;;;;GAKG;AACH,YAAY,EAAE,sBAAsB,EAAE,CAAA;AAEtC;;;;;;GAMG;AACH,MAAM,WAAW,mBAAmB;IAClC,wDAAwD;IACxD,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAA;IAC1B,4DAA4D;IAC5D,QA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