Commit Graph

67 Commits

Author SHA1 Message Date
68775d327f fix(packaging): ship lib/embed/, without which the published tarball cannot load
`package.json` declared

    "files": ["lib/*.js", "lib/loop.js", "lib/loop/*.js", "lib/types/*.d.ts"]

`lib/*.js` matches ONE level. `lib/embed/http.js` therefore never entered the
tarball, while `lib/index.js:35` imports it:

    import { createHttpEmbedder } from './embed/http.js'

## How this survived

Every test in this repo runs from the source tree, where the file obviously
exists. `npm pack --dry-run` printed "10 files" — a plausible number nobody had
reason to read through. The defect is only reachable from the one path that
ships: installing the tarball.

Measured, extracting the tarball and importing it:

    IMPORT FAILED: ERR_MODULE_NOT_FOUND
    Cannot find module '.../package/lib/embed/http.js'
      imported from '.../package/lib/index.js'

After the fix, the same command:

    IMPORT OK, exports: StableMem,apply,default,defaultPath,inject,instanceKey,lastUserText,name

## Fix

`lib/embed/*.js` added to the allowlist. The tarball goes from 10 to 11 files
(86.1 kB) and `lib/embed/http.js` is in it.

## Criterion

`test/packaging.test.js`:

1. every `.js` under `lib/` must be matched by at least one `files` pattern.
   The patterns compile to regexes the way npm treats them (`*` does not cross
   `/`), so the criterion needs no hand-maintained file list and cannot drift.
2. every relative import in `lib/index.js` must resolve on disk — otherwise
   criterion 1 could pass vacuously for a file that does not exist.

Reverting `files` to the old list turns criterion 1 red:

    not ok 1 - packaging: every file under lib/ is covered by package.json "files"
    these files live under lib/ but no "files" pattern reaches them ...
      lib/embed/http.js

## Why it belongs in this branch

V6 made the embedder assembly load-bearing (two instances, one per side). A
release that cannot import `lib/embed/http.js` has no embedder at all, so the
distinction V6 introduced would never reach a user. The bug predates this
branch; its blast radius is the shipped artifact.

Gates: npm test 294/294 (0 skipped), npm run check 12/12, npm pack 11 files.
2026-11-05 11:38:56 +08:00
c97775bd18 feat(memory): encode stored blocks on the document side, questions on the query side (V6)
The HTTP protocol carries a `side` field — `query` or `document`, HA's
`PurposeQuery`/`PurposeDocument` (`http_embedder.go:105` / `:109`). The port made
it a construction-time setting of the adapter (default `query`) and then **no
call site ever supplied it**: both the write path (`lib/index.js`) and the recall
path (`lib/recall.js`) took the default.

So every stored block was encoded as if it were a question. Nothing fails when
that happens — both sides produce unit vectors of the declared width — which is
exactly why it survived: the corruption is only visible in retrieval quality,
and retrieval quality was already the known-unmeasured part.

## Why two instances and not a per-call argument

`side` is a property of what you are encoding, so a per-call parameter is the
more natural shape. It is not the shape used here, for one reason: the adapter
travels `side` verbatim in the request body from a closure, and giving it a
second, per-call way to receive the same field would leave two sources of truth
for one wire value. Creating two adapters over the same endpoint/model/dimension
— identical fingerprint, differing only in `side` — keeps the wire contract as it
was and puts the distinction where it belongs: in assembly.

`lib/embed/http.js` is therefore **unchanged**.

An injected `config.embedder` (tests, a future local adapter) has no second
instance, so the write path falls back to it (`documentEmbedder ?? embedder`).
That is the previous behaviour, not a second code path — and it is pinned.

## Criterion

`test/phase-b-v6-sides.test.js` starts a real HTTP server that records the `side`
of every request, then drives the **production assembly** (`apply()` with
`config.embed`):

    commit  → request body side === 'document'
    recall  → request body side === 'query'

The assertion is on the field that actually went out on the wire, not on an
internal variable. A second test pins the injection fallback: a single injected
embedder must still serve both paths, or every existing test and every
single-sided adapter breaks.

Mutation M-V6 — pointing the write path back at `this.embedder`:

    not ok 1 - V6: storing a block encodes it on the document side, asking encodes the query side
    error: V6: a block being STORED must be encoded on the document side. ...
      + actual - expected
      + 'query'
      - 'document'

## What this does NOT establish

That the provider actually encodes the two sides differently. `side` is a
request field; what the endpoint does with it is the endpoint's business, and
this repo has no model whose asymmetry is measurable. What is now true is that
the distinction reaches the wire instead of being silently defaulted away.

Gates: npm test 292/292 (0 skipped), npm run check 12/12. Frozen faces untouched.
2026-11-05 11:35:02 +08:00
28866ac6e6 feat(memory): name why centring is disabled, instead of only reporting that it is (C5)
`centroidStatus` computed four distinct ways for centring to be unavailable and
then flattened all of them into `available: false`. The result was that
`no_centroid` and `dim_mismatch` both looked like `stale: null`, and `isotropic`
was indistinguishable from a healthy space except by `available`. That answers
"may I centre?" and says nothing about "why is semantic recall never
correcting?" — four different operator actions (build a centroid, fix the
dimension, wait for a rebuild, accept that this space has no common direction)
collapsed into one symptom.

Every branch now carries `reason`:

    ok           available: true
    no_centroid  no row for this space at all
    dim_mismatch a centroid exists but its width is not this query's
    zero_sample  a row exists but was built from zero vectors
    stale        usable in principle, no longer describes the space (drift > 20%)
    isotropic    permanent property of the space: no common direction to remove

`zero_sample` is a fifth cause beyond the four the plan names, because the Go
branch has it too (`centroid_store.go:179-185`) and it is not the same problem
as a missing row.

## Criterion

`test/phase-b-c5-reasons.test.js` — one fixture per reason, asserting **the
reason value itself** (not `available`, which is multi-valued). Plus:

- an invariant test: `available === (reason === 'ok')`, so `reason` cannot drift
  into decoration that disagrees with the conclusion it explains;
- a test that `centroidRecallState` still projects `stale: null` (the scorer must
  not start reacting to staleness) *while* `reason` travels through, so an
  operator can still see why.

Every call injects `schedule: () => {}`. `centroidStatus` schedules a rebuild
when it judges a space stale — a criterion that calls it without isolating that
side effect ends up triggering the very behaviour it is inspecting. C4e's first
version proved that the hard way.

## Mutation

Collapsing all six reasons into one value (`reason: 'unavailable'`) turns all
eight criteria red:

    not ok 1 - C5: a space with blocks but no centroid row reports no_centroid
    not ok 2 - C5: a centroid of the wrong width reports dim_mismatch
    not ok 3 - C5: a centroid row with zero samples reports zero_sample
    not ok 4 - C5: a centroid that drifted past the ratio reports stale
    not ok 5 - C5: an isotropic space reports isotropic, not stale
    not ok 6 - C5: a healthy space reports ok, and only ok carries available=true
    not ok 7 - C5: reason and available never disagree
    not ok 8 - C5: centroidRecallState keeps its stale:null projection but carries the reason

## What this does NOT change

Scoring, gating and the recall path are untouched: nothing reads `reason` to
decide whether to centre, and `centroidRecallState` keeps `stale: null`. This is
a reporting seam, not a behaviour change — C4's own criteria (C4a/b/c/d/e/g/h/i)
and phase-b-h's C3 assertions stay green.

Gates: npm test 290/290 (0 skipped), npm run check 12/12. Frozen faces untouched.
2026-11-05 11:32:49 +08:00
5cb97edf39 fix(memory): stop scoring renormalised floating-point dust as a direction (C4 follow-up)
`centerVector` treated any positive norm as a direction:

    norm = Math.sqrt(norm)
    if (!(norm > 0)) return null
    for (...) out[index] /= norm

A block that IS the space mean differs from it only by floating-point residue
(~1e-17). That residue passes `norm > 0`, gets normalised to unit length, and
then scores against the query as if it were signal.

## Measured

Space of two identical blocks, query deliberately off the block direction (if
the query equalled the mean, its centred form would collapse and centring would
fall back to raw scores, hiding the defect):

    raw cosine, no centroid        0.8608
    with centroid, before this fix 0.2183   <- dust, renormalised
    with centroid, after this fix  no hit   <- dust judged "no direction"

At the default `minScore = 0.5` the 0.2183 scores were filtered anyway, so the
user-visible outcome (0 hits) does not change. What changes is that the number
is no longer manufactured: with `minScore: 0` the earlier build would surface
those blocks at a noise-derived score, and a future change to the threshold
would have made that reachable.

CENTER_EPSILON = 1e-9 is the floor. It also matches the Go side, where the
cosine of a zero vector is 0 rather than a random angle.

## Criterion C4i — and what it deliberately does not pin

C4i asserts the invariant: **every returned hit must carry the raw cosine
(0.8608); a value near 0.22 means dust was renormalised.** It therefore accepts
either of two future policies — drop such blocks (what this commit does), or
skip centring entirely for a space with no variance. The only thing it forbids
is continuing to score dust.

Reverting the guard (`norm > CENTER_EPSILON` -> `norm > 0`) makes C4i red, which
is the mutation this criterion exists for.

## KNOWN LIMITATION — reported upward, not fixed here

A space whose blocks are all identical now returns NO hits where it previously
returned them at 0.8608, because centring subtracts the only direction the space
has. That is not introduced by this commit — epsilon only made it deterministic —
but it is a real recall loss for a realistic case (the same note stored twice),
and it is a C4 regression against the pre-C4 behaviour.

Two candidates, deliberately NOT applied here because both change scoring
semantics and one departs from HA:

  (a) keep dropping them (current, HA-consistent: Go's cosine of a zero vector
      is 0, so those blocks fall below any threshold too);
  (b) do not centre a space whose mean norm is ~1.0 — there is no variance to
      remove — which preserves the 0.8608 raw scores. This adds an upper
      threshold HA does not have, so it is the parent's call.

No criterion pins "0 hits" for the duplicate space: pinning it would encode the
limitation as intended behaviour.

Gates: npm test 282/282 (0 skipped), frozen faces untouched.
2026-11-05 11:30:48 +08:00
363b1ba21a docs(memory): record what the C4 write path costs, and two "unwired" calls that aren't
Three comments that were either wrong or silent. No behaviour change.

## The first-build cost claim was false

`#ensureCentroid` said "首次建的代价很小:那时块还少" (the first build is cheap —
there are few blocks then). That is exactly backwards for the situation the code
exists to fix: a production database that already holds thousands of vectored
blocks while `graph_centroid` is empty. The W8 scenario IS a database with many
blocks and no centroid.

Measured on a real database (512 dims, 2000 vectored blocks, empty centroid
table, first commit through the production path):

    FIRST commit after upgrade   105.1 ms   (synchronous SELECT + parse + mean)
    STEADY commits               8.7-9.4 ms (loadCentroid SELECT + centroidStatus COUNT)

and the first build grows linearly with the space (~420 ms at 8000 blocks). The
number is now in the comment, together with the decision it justifies: keep the
one-time stall rather than move the build to the async path, because an async
first build leaves the first recalls after an upgrade silently uncorrected —
precisely when n is large enough for centring to matter. A bounded stall is
easier to notice than a silent degradation.

The steady-state ~9 ms is new with C4 and is now stated as such: every commit
pays one `loadCentroid` SELECT plus the `countVectored` COUNT inside
`centroidStatus`. C3-k forbids that COUNT on the recall path, not on the write
path.

## Two calls with no production caller, and why neither is a dangling wire

`saveSpaceCentroid` and `#centroidRebuiltAt` both looked like the defects this
round kept finding (code written, never wired). They are not, but leaving that
unwritten meant the next reader had to re-derive it — and the two live cases
(`saveSpaceCentroid` in `lib/`, the throttle state on disk) really were dangling.

- `saveSpaceCentroid` is the public programmatic seam for a caller that computed
  a centroid elsewhere. Production centroids are derived from the blocks by
  `store.rebuildCentroid`, driven from `commit` via `#ensureCentroid`. Stated in
  its JSDoc, along with the fact that the only in-repo caller is a test.
- `#centroidRebuiltAt` stays in memory, and the reason `graph_centroid.built_at`
  cannot replace it is now written down: `built_at` records a BUILD, the throttle
  needs the last SCHEDULE, and the two diverge precisely when a rebuild throws.
  Throttling on `built_at` would re-schedule on every commit after a failed
  rebuild — write amplification on the failure path. The cost of the in-memory
  map (one extra bounded async rebuild after a restart, measured 85.5 ms at
  2000x512) is smaller, and it is stated next to it.

Gates: npm test 281/281, npm run check 12/12. Frozen faces untouched.
2026-11-05 11:23:32 +08:00
febf9f6f3c test(memory): pin the C4 gates that were left unguarded (C4 follow-up, supervision)
Three of C4's control surfaces had no criterion at all: deleting them left every
suite green. This commit adds the criteria, and the two defects they exposed.

## What was unguarded, measured

Each mutation below was applied to a scratch copy of lib/ and run against the
suite as it stood at 05e93b2.

1. The `isAnomalous` gate in `scoreVectorCandidates`
   `centroid?.isAnomalous === true &&` -> `centroid !== undefined &&`
   Result: c4 6/6 green, phase-b-h 137/137 green, phase-b-a 38/38 green.
   Why: every C4 fixture is anisotropic (two of them assert isAnomalous ===
   true), and C4c is "no centroid row", which is a different branch from "a
   centroid that was judged isotropic". The only isotropic assertion in the repo
   (phase-b-h:1133) checks `rebuildCentroid`'s verdict, not the scoring path.

2. `countVectored` on the recall hot path
   `store.countVectored(fingerprint)` inserted before the centroid read.
   Result: c4 6/6 green, phase-b-h + phase-b-a 175/175 green.
   Why: nothing scans lib/recall.js for the C3-k boundary. phase-b-a:67 does read
   recall.js, but it asserts the F2 fingerprint gate.

3. MIN_SAMPLE (this one is a defect, not just a missing criterion)
   A one-vector mean IS that vector, so its norm is exactly 1.0 and it clears
   0.6 by construction. Measured with a real clock and the real commit path on
   the C4 corpus: right after the 8th commit the centroid reported
   `vectorCount=1 meanLength=1.0000`, and a recall that returns 3 rows without a
   centroid returned 1 with it — the block that formed the "mean" was centred to
   the zero vector and dropped. The drift rebuild corrects it ~2s later, so the
   window is short but the state is wrong, and in a slowly growing space it lasts
   until the throttle expires.

## What this commit adds

- `BlockStore.MIN_SAMPLE` (= 2) and `vectors.length >= MIN_SAMPLE` in the
  anisotropy verdict. Two is the smallest number for which the mean is a property
  of the set rather than of one member.
- **C4h** pins both halves of that: the verdict (`isAnomalous === false` for one
  vector, with `meanLength === 1` asserted as the precondition that makes the
  0.6 test insufficient) and the consequence (the only block stays recallable).
- **C4g** pins the isotropic gate. Fixture numbers come from running the same
  probe against a gated and an ungated build, not from paper: 8 orthogonal
  one-hot vectors, `meanLength = 0.353553`, `isAnomalous === false`; a query
  along `unit(ones)` yields 8 hits of cosine 0.3536 with the gate, and 0 hits
  without it (every centred cosine turns negative and V5's structural gate drops
  the lot). A three-axis query additionally pins 0.8111 / 0.4867 / 0.3244.
  The identical-pair query is deliberately NOT the main assertion: with both
  sides centred its cosine is 1 either way, so it cannot discriminate.
- **C3-k** statically scans lib/recall.js for `countVectored(` / `centroidStatus(`
  after stripping comments, and carries a positive self-check: the same scan must
  find `centroidStatus(` in lib/index.js, so a broken regex cannot leave the two
  "must not contain" assertions vacuously true.
- **C4d** gained the assertion it was missing. It asserted that a centroid
  exists, is anomalous and has the right width — all true of a centroid built
  from a single block. It now also asserts `vectorCount === CORPUS.length`, and
  waits for the drift rebuild before asserting on contents. Without the count
  assertion C4d is green while the mean describes one block.

## Mutations verified (each red in a scratch copy, working tree untouched)

  delete isAnomalous gate        -> C4g red
  countVectored in recall.js     -> C3-k red
  drop MIN_SAMPLE                -> C4h red
  revert "refresh a drifted centroid" -> C4d + C4e red

## Documentation that had drifted from the code

- recall.js still said "No centroid centering here. C4 ... is a separate slice
  layered on top of this one" directly above the function that now implements
  centering. Replaced with a pointer to where it actually lives.
- The one-sided-centring cosine was recorded as 0.3787 in the comment and "near
  0.38" in C4b's message. Measured on C4b's own five-block fixture it is 0.1897
  (cosine is symmetric, so centring either single side gives the same value).
  Both now say 0.1897 and name the fixture.

## Measured costs (for the write path this slice touches)

Pre-populated space, 512 dims, 2000 vectored blocks, empty graph_centroid — the
state a production database is in when it upgrades:

    FIRST commit after upgrade   105.1 ms   (synchronous O(n*d) rebuild)
    STEADY commits               8.7-9.4 ms (loadCentroid SELECT + centroidStatus COUNT)

The first build is accepted as-is: it happens once per space lifetime, it is
bounded, and moving it to the async path would leave the first recalls after an
upgrade silently uncorrected — a bounded stall is easier to notice than a silent
degradation. The steady-state COUNT is new with C4; C3-k keeps it off the recall
path, where it would run every turn.

## Real path (dsh headless, overlay on the real profile)

Same corpus and query, only the centroid row differs:

    centroid present (count=8, meanLength=0.972934)
      [1] (text 0.63) 第七号仓库的备用门禁码是 QP47-812。
    centroid deleted
      [1] (text 0.69) 这段时间一切照旧,没有什么特别的事情。
      [2] (text 0.69) 第七号仓库的备用门禁码是 QP47-812。

top-1 moves from the hub to the target, which is the behaviour C4 exists for.

## What this does NOT establish

Centring changes angles; it does not calibrate absolute scores. DEFAULT_MIN_SCORE
= 0.5 was never derived from a centred distribution, and the uncalibrated-absolute-
score problem recorded in phase-b-p1-vector-wiring.test.js:51-58 remains open.
A green C4 means "centring is wired into scoring and changes the ranking in an
anisotropic space", never "semantic recall is good now".

C5 (distinguishing no_centroid / dim_mismatch / stale / isotropic reasons) is
untouched: `centroidRecallState` still returns `stale: null`.

Gates: npm test 281/281 (0 skipped), npm run check 12/12, npm pack 10 files.
Frozen faces untouched: docs/, README.md, scripts/, lib/loop*.
2026-11-05 11:21:02 +08:00
05e93b2f5c fix(memory): let the write path refresh a drifted centroid (C4 follow-up)
0a6adff 里我自己留了一个洞,而且正是这一整轮反复抓的同一个病:逻辑写了,但没被调到。

`#ensureCentroid` 当时的形状是「没有中心就建一个,有就 return」:

    if (this.store.loadCentroid(fingerprint) !== undefined) return
    this.store.rebuildCentroid(fingerprint)

于是中心永远停在第一次 commit 的快照上。`rebuildCentroid` 只算一次,
之后块数一直涨,均值却再不动 —— 块数翻八倍,它还描述着 1 条块。
召回侧只 `loadCentroid` 纯读,永远不会自己纠正。

根子在于 `centroidStatus`:它内部早写好了完整判据(块数漂移 > 20% ⇒ stale,
10 分钟节流 + 异步重建),而在 C4 之前它在 lib/ 里**没有任何生产调用者**。
我接线时只接了「建第一次」,让它继续当着死代码 —— 这跟 P1/C4 要修的
「代码写了没接线」是同一类错误,只是换了一层。

修法:有中心时不再 return,交给 `centroidStatus` 判。它自己决定要不要重建。
仍然放在 commit 之后而不是召回路径,正是因为它第一行是 `countVectored`,
C3-k 明令该查询不得进每轮 pre-step 的热路径。

判据 C4e:写入侧必须让漂移的中心重新跟上

    commit 1 条  → 中心 vectorCount = 1
    再写 7 条    → 漂移 700% >> 20%
    假时钟拨过 2s → 中心 vectorCount 必须 = 8

M4 变异(退回 0a6adff 的「有中心就 return」)红原文:

    C4e: a centroid that drifted past the 20% ratio must be rebuilt by the
    write path. It is still describing 1 blocks while 8 carry vectors
    —— nothing in lib/ ever consults the stale judgement, so the mean stays
    frozen on whatever the first commit happened to see.

★ C4e 第一版是假绿,一并记下来

第一版在断言前调了 `mem.store.centroidStatus(SPACE)` 来验 stale 前置。
但 `centroidStatus` 自己就会调度重建 —— 于是不管写入侧接没接,重建都会发生,
判据在自证。M4 变异下它 6/6 全绿,才把这个问题揪出来。
改成手工算漂移比(不碰 centroidStatus)之后,M4 才咬得住。

同一类陷阱会在任何「被测函数恰好也能触发被测行为」的地方复现,
所以判据里宁可自己算前置常量,也不去调那个会把副作用带进来的接口。

★ What this does NOT establish

C4e 证的是「漂移会被发现并触发重建」,不证重建的时机对用户体验无感 ——
10 分钟节流窗口内中心仍是旧的,这段时间召回用的还是上一个快照的均值。
窗口长度与漂移比的关系需要实测分布,属效果范畴,不在本片。

三门:npm test 278/278(0 skipped)、npm run check 12/12、npm pack 10 files 79.3 kB。
冻结面:docs/、README.md、scripts/、lib/loop* 零改动。
2026-11-05 10:47:43 +08:00
0a6adff5cb fix(memory): wire centroid centering into both the write path and scoring (C4)
C4 的判据原文:「校正时查询向量与块向量都去均值,不能只处理一边」
(docs/phase-b-criteria.md:253,依据 HA centroid_store.go:443-451 的 centerBoth)。

C4 缺的不是一半,是两层都没接

1. 中心从来不存在。`saveSpaceCentroid`(lib/index.js) / `centroidStatus` /
   `centroidRecallState` 在整个 lib/ 里没有生产调用者,`rebuildCentroid`
   只有测试在调。所以生产库的 `graph_centroid` 永远是空表,`loadCentroid`
   永远返回 undefined,`isAnomalous` 永远 false —— 校正一次也不会发生。
   实测:`/tmp/p1/e2e.db` 的 `graph_centroid` 零行。

2. 打分不用中心。`lib/recall.js` 全文没有 centroid 一词,
   `scoreVectorCandidates` 只算裸余弦。`centerBoth` 全仓零命中。

只做第 2 层就是又一个「代码写了没接线」:判据会绿、实现会绿、生产永远 false。

写入侧:lib/index.js
  · 新增 `#ensureCentroid(fingerprint)`,在 commit 成功后调用
  · 只在「本空间没有中心行」时建一次;有行就交给已有的 stale 判定
  · 失败吞掉:一次重建失败不能让写入失败(同 D1:向量侧故障不得带走主路径)
  · 不放在召回侧:rebuildCentroid 是 O(n·d)(实测 dim=512、2000 块 85.5ms),
    而召回每轮 pre-step 都跑;C3-k 也明令 countVectored 不得进热路径,
    而 centroidStatus 第一行就是它

打分侧:lib/recall.js
  · `scoreVectorCandidates` 读一次中心(loadCentroid 纯读,一次索引查询)
  · 仅当 `isAnomalous === true` 且 `centroid.dim === queryVector.length` 时启用
  · 两侧同时减均值 + 重新归一化(新增 `centerVector`,对齐 HA CenterVector)
  · 维度不符 ⇒ 不校正也不报错;减完是零向量 ⇒ 退回未校正路径
  · 门控是正确性不是性能:各向同性空间无条件校正会毁掉结果
    (实测 8 块正交 mean norm 0.3536:命中数 8 → 1,7 块余弦 +0.0496 → −0.1416,
     且因 V5 结构性门(vectorScore <= 0 且 symbolHit === 0 直接丢弃)
     minScore 调到 -1 也救不回来)

判据:test/phase-b-c4-centering.test.js(283 行,已登记进 npm test)

  C4-0  前置:空间真的会被判为各向异性(mean norm 0.9729 >= 0.6)
  C4a   born-RED:去均值把 top-1 从 hub 翻到 target
        红原文(28e18d0):hub=0.6949(v=0.9928) target=0.6901(v=0.9859)
        绿后:            target=0.6300(v=0.9000)
  C4b   mutation-GUARD:同值对余弦恒为 1(纯代数,不依赖语料)。
        未实现时本来就绿(裸余弦同值对 = 1),只有「只减一边」能让它红。
        这条不可省:实测只减 query 时 C4a 的 top-1 仍然是 target,C4a 抓不到。
  C4c   guard:没有中心时照常返回结果(hub 仍然赢),不是让召回失败
  C4d   第一层的守门人:走真 apply() + commit() + recall(),不手工 rebuildCentroid,
        断言写完 8 条后 loadCentroid 必须已存在,且端到端 top-1 是 target
        —— 没有这条,前三条的绿只能证明算术,证明不了接线

变异自证(三档,全部在临时副本做,真改 lib/)

  M1 去掉中心化(loadCentroid 恒 undefined)        → C4a + C4d 红(5→3 pass)
  M2 块侧不中心化(只减 query,即 M-C4)            → C4a + C4b + C4d 红(5→2 pass)
     C4b 红原文:got 0.18974704073471832 —— 只减一边的签名
  M3 去掉写入侧 #ensureCentroid                    → 仅 C4d 红(5→4 pass)
     C4d 红原文:after commits through the production path a centroid must exist
     这一档证明 C4d 是唯一守住第一层的判据

一处必要适配(不是削弱)

  test/phase-b-h.test.js 的 `ticket②-strong mutation` 原本依赖「commit 之后
  本空间没有中心」来让「用错 key 查不到」成为可观测事实。C4 让 commit 自动
  建中心之后,这个前提变了,它会因为「本来就有一个中心」而红 —— 红的原因
  与它要守的约束无关。改法:commit 之后显式清掉本空间那一行,并加一条
  前置断言。用例语义完全保留,只是把前提重新立起来。

★ What this does NOT establish

  中心化改变的是向量间的夹角,因此能改变排序。它不能让未校准的绝对分数
  变得可用:去均值之后余弦仍然是余弦,而 DEFAULT_MIN_SCORE = 0.5 从来不是
  从中心化后的分布推出来的。阈值校准仍是
  phase-b-p1-vector-wiring.test.js:51-58 记录的已知未解问题。

三门:npm test 277/277(0 skipped)、npm run check 12/12、npm pack 10 files 79.0 kB。
冻结面:docs/、README.md、scripts/、lib/loop* 零改动。
2026-11-05 10:41:38 +08:00
28e18d0258 test(memory): bound what P1's green does and does not establish (P1 follow-up)
Two discipline holes left after 1309afe / 09be4de, both closed here.

1. The boundary was unstated. A one-hot keyword-family fixture proves the
   PLUMBING — that the computed query vector reaches scoring — and says nothing
   about retrieval quality. Left implicit, a green P1 invites the reading
   "semantic recall works". The measured counter-evidence is now in the file:
   on the real chinese-clip space a true hit scored 0.8345 while an unrelated
   block scored 0.8598, so absolute scores are not calibrated and no threshold
   may be read off them. That is a known unresolved problem outside P1's scope.

2. `dsh` missing used to `t.skip`. A skip keeps `npm test` green while the only
   end-to-end evidence for P1 never runs — the same shape as a criterion that is
   committed but never speaks. It now fails, and says why.

No behavioural change: 272/272 tests, 12/12 checkpoints, 0 skipped on a box
where `dsh` is present. Verified the mutation discipline still bites — deleting
`'hybrid'` from ORDINARY_DEGRADATIONS turns L10, L11, L10† and L11† red.
2026-11-05 01:22:57 +08:00
09be4de0eb test(memory): pin that ORDINARY_DEGRADATIONS decides the log LEVEL (P1 follow-up)
P1 registered two healthy modes in `ORDINARY_DEGRADATIONS` — `hybrid` (the wired
success path) and `no_vector_space` (a space with nothing comparable to score) —
and the commit message claimed that meant "a healthy wired recall does not log a
warning every turn". Nothing tested it. Measured on 1309afe:

    M-a  delete 'hybrid'            → # tests 268  # pass 268  # fail 0
    M-b  delete 'no_vector_space'   → # tests 268  # pass 268  # fail 0
    M-ab delete both                → # tests 268  # pass 268  # fail 0

while the behaviour really broke (real apply(), debugLog=false):

    mutated hybrid recall → lines=[['warn', '... degraded=hybrid ... inject=138ch']]
    released hybrid recall → lines=[]

A false fault alarm on the happiest path, every single turn, and the suite green.

Why the existing tests could not see it: A3d/D3b assert the LABEL
(`hits.degraded === 'hybrid'`). Removing a member from the Set does not change any
label — it changes only whether `logRecallTurn` treats that label as a fault. The
defect lived exactly in the gap between "the label is right" and "the level is
right", and `grep ORDINARY_DEGRADATIONS test/` was empty. A claim in a commit
message with nothing behind it is the same failure mode as a guard that cannot
fail.

What this commit adds (test/memory-log.test.js only — lib/ untouched)

  L10    one group, three outcomes at the SAME verbosity (debugLog: false):
         `hybrid`               → zero lines
         `no_vector_space`      → zero lines
         `embed_error`          → exactly one line, type 'warn'   ← the control
         Each case asserts its own PRECONDITION first (the run really was
         `hybrid` / `no_vector_space`, and something was really injected), so a
         silent log cannot be confused with a build that never reached the route.
         Without the third case, "silent" would also be satisfied by a build that
         logs nothing at all — which is the original bug the log channel exists
         for (L4).
  L10†   real mutation: 'hybrid' removed from the Set → L10.1 red
  L11†   real mutation: 'no_vector_space' removed → L10.2 red
         Both via `withMutatedIndex` (copy the package, rewrite ONE anchor,
         `count === 1` self-check, import fresh). The mutant runs the SAME
         `assertLevelContract` body the released build passes — a criterion copied
         for the mutant can drift, a shared one cannot. The mutation then asserts
         the throw is `ERR_ASSERTION` AND that the message starts with the specific
         sub-assertion name, so an import failure cannot make it green for the
         wrong reason.
  L11    measured behaviour, pinned so nobody "fixes" it later: a fused recall
         whose candidates were ALL refused by `minScore` still reports `hybrid`
         with zero hits, and is still silent. `no_vector_space` is returned at
         exactly one place (`recall.js`, `vectorScores.size === 0`) and means
         "there was nothing to score" — never "everything was filtered". Collapsing
         the two would hide a threshold set too high behind a "fresh space" story.

Two fixture pitfalls found while writing this, both recorded in the test because
each one silently disarmed its own case:

  · `commit` embeds when an embedder is mounted, so the `no_vector_space` case has
    to write its block BEFORE the embedder appears. The first attempt mounted the
    embedder first, the space filled up, and the label came back `hybrid` — the
    assertion then failed for its own precondition rather than for the subject.
  · `StableMem.recall()` forwards only `topK`/`signal`, so a `minScore` passed
    there never reaches the scorer and L11's precondition would have passed on an
    unchanged result. It drives `recallBlocksHybrid` directly instead.

Not asserted, deliberately: `'no_embedder'`, `'aborted'` and `'vector_ready_unused'`
are also in the Set, but their silence is already carried by L1/L5 (no embedder)
and W11e/W12 elsewhere. Adding them here would inflate the group without covering a
new decision.

旁证 (not acceptance): npm test 272/272, npm run check 12/12, npm pack --dry-run
10 files / 75.3 kB. docs/ and README.md untouched.
2026-11-05 00:51:17 +08:00
1309afec93 fix(memory): wire the computed query vector into recall scoring (P1)
`recallBlocksHybrid` computed `queryVector`, verified its length against the
declared space, and then threw it away:

    return withDiagnosis(recallBlocks(store, query, scoped), 'vector_ready_unused')

`scoped` carries only `topK` / `signal` / `fingerprint` / `dimension`. So every
V1–V7 scoring branch inside `recallBlocks` was live code reachable ONLY from
unit tests that hand-built a `vectorScores` Map — `vectorScores:` appeared 10
times in test/phase-b-a.test.js and ZERO times under lib/. Production recall was
pure symbol/FTS: the whole vector half of phase B was unreachable, and the only
symptom was a diagnostic label nobody was watching.

Why BOTH options are now passed (structural, not stylistic)

  · `vectorScores` alone reaches only the V1 exact-band tie adjustment (:438).
    The fused candidate assembly at :233 is gated on `Number.isFinite(minScore)`,
    so without a threshold the vector route can never admit a block the symbol
    path missed — which is exactly what V5 exists for.
  · `minScore` alone does nothing: :299 additionally requires `vectorScores` to
    BE a Map before it builds vector candidates.
One seam, three guards. Half of it is a no-op, which is why measuring the
half-wiring mutation below matters.

Scheme A, and why not B

A: keep the existing API (`vectorScores: Map<string, number>` + `minScore`), and
   have `recallBlocksHybrid` score the query vector against the space's stored
   vectors before calling `recallBlocks` once.
B: change `recallBlocks`'s signature to accept a `queryVector` and score inside.

Chosen: A. B would touch a signature that phase A's golden fixture and nine call
sites depend on being synchronous and vector-free (`recallBlocks` MUST NOT return
a thenable — A1 pins it structurally), and it would move cosine arithmetic into a
function whose contract is literally "store + query text". A leaves
`recallBlocks` byte-untouched: the seam it already exposes is driven, so A2's
45-case golden comparison cannot drift. Both routes must also be fused in ONE
scoring pass anyway (V5 admits vector-only candidates; V7 forbids truncating
before fusion), so "call twice and merge" was never an option.

Cost, measured before choosing (this box, 2000 blocks x 512 dims)

  narrow `SELECT id, vector`    21 ms   (vs 70 ms for `allBlocks(-1)`)
  parse + cosine over 2000      60 ms
  ⇒ ~81 ms per recall; at 8000 blocks ~310 ms.

Affordable because it runs once per TURN (pre-step), not per candidate, and
because the scan is bounded by SQL: `fingerprint = ?` and `vector_dim = ?` are
pushed into the store so rows from a retired space or a wrong width are never
decoded. A phase-A store (no embedded blocks at all) pays one indexed SELECT
returning no rows. It does not add a new order of cost either: the fused path
already walks every block for symbol union (`allBlocks(-1)`); this replaces that
blind decode with a narrow one for the vector half. The remaining ceiling is a
single very large space — a number to measure before raising topK, not a reason
to ship a path that never runs. Fail-closed per §0.2/F5: blocks with an empty
fingerprint are deliberately not scored.

New diagnostic modes, both non-faults

  `hybrid`           the healthy wired path (symbol + vector fused). Explicit
                     `case` in `degradationNotice` because `default:` exists to
                     make an UNKNOWN mode say "unknown, not absent" — routing the
                     healthiest mode through it would print a false degradation
                     notice on every turn that had a vector hit.
  `no_vector_space`  a space is configured and the embedder answered, but no
                     block in it carries a usable vector (fresh space). Says
                     "nothing was scored" without claiming a provider failure.
                     An empty Map must NOT be passed to the fused route: it would
                     open candidate assembly and score symbol matches as
                     `0.7*0 + 0.3*coverage`, the V2 regression.

The criterion (test/phase-b-p1-vector-wiring.test.js)

End-to-end, because a unit test cannot see this bug: the defect is that nobody
passes the options, so asserting the options work proves nothing. The chain is
real sqlite file → real `apply()`/`commit()` write path (no hand-built vectors,
no injected embedder object: the plugin's own HTTP adapter is used) → real
`recallBlocksHybrid` → real headless `dsh --profile headless` with the shipped
`cordis.patch.yml` loop overlay (so P0 still applies) → the persisted
`session.v4.jsonl.zstd` → the stub LLM's answer, which is a pure function of the
system prompt it received.

Corpus, MEASURED before any assertion was written. Deterministic keyword-family
projection into 8 unit axes: family 0 is the target's vocabulary, families 1..7
are one axis per distractor, unmapped text → zero vector. Query
「上次说的那个四位数是什么来着?」:

  symbol path hits (target)   0     ← precondition 1
  hand-built vectorScores top1 = target, score 0.70   ← precondition 2
  query shares no CJK 2-gram with any block

Both preconditions are asserted in-suite (P1-0) so a later corpus edit cannot
make the e2e criterion unfalsifiable. An earlier attempt used the real
chinese-clip-vit-b16 model; its top-1 for the same kind of query was an unrelated
block (0.83 "入职培训"), so that corpus could never have gone green — the fake
embedder makes the question decidable instead of probabilistic.

The access code is `QP47-812` rather than a bare number so the stub's extractor
(`[A-Z]{2}\d{2}-\d{3}`) cannot collide with anything else in the prompt.

Born red against c1f7e06 (clean `git archive` of that commit, same test file):

  P1: the answer must come from block memory through the vector route.
    expected: QP47-812
    actual:   "未知"
    symbol-path hits: 0 (must be 0)
    recall diagnosis: degraded=vector_ready_unused hits=0
    recall section injected: (none)

Mutations — three, each a real edit to lib/recall.js, each restored after:

  M1 drop the wiring      `recallBlocks(store, query, scoped)`  → P1 red
  M2 half the seam        `minScore = undefined`                → P1 red
  M3 empty the scan       `const rows = []`                     → A3d red

  M1 raw: not ok 2 - P1: a semantic-only question is answered from block
          memory via the vector route
            expected: QP47-812
            actual:   "未知"
            recall diagnosis: degraded=hybrid hits=0
  M2 raw: identical text — and that is the point. Passing `vectorScores` alone
          keeps the new `hybrid` label looking healthy while the answer is still
          empty, because `minScore` is what opens the fused candidate assembly.
  M3 raw: Expected values to be strictly equal — `hybrid` unreachable, so the
          label is evidence rather than decoration.

Restoration is verified by hash, not by eye: `sha256sum lib/recall.js` is
8eb0faa660c973ea5114268001d49cf43f83ef92b2945897cfc6f7512541a498 before and
after every mutation, and `git diff` (staged vs worktree) is empty.

Test updates forced by the wiring (not cosmetic)

  A3c   the old assertion was "a healthy embedder reports vector_ready_unused,
        NOT hybrid". That was correct while the vector was unused; over a corpus
        with no vectors in the active space the honest label is now
        `no_vector_space`, and A3d pins `hybrid` once a vector exists.
  A3c†  replaced a test that only compared two local string literals (it could
        never fail for a real reason) with a mutation of the actual scoring pass.
  D3b   `hybrid` instead of the group-A stage label.
  index the two new modes are added to ORDINARY_DEGRADATIONS, so a healthy wired
        recall does not log a warning every turn.

Not in this slice: C4 (centering) is the next layer on this exact path and
deliberately not done inline, so its mutation stays citable. V6 and C5 untouched.

旁证 (not acceptance): npm test 268/268, npm run check 12/12.
2026-11-05 00:07:29 +08:00
c1f7e06b22 test(memory): 补 377e02c 的判据假绿 —— multiCarrier 名不符实,真多块零覆盖
`multiCarrier(texts, convention)` 名叫"多块",实际 `content: [{ type: 'text',
text: joined }]` 恒为 1 个 block。所以 S2a/S2b 读起来是"多块路径已覆盖",
实际一条都没走多块分支:

  M1 在 `const rendered = ...` 前插 `if (blocks.length > 1) return null`
     (即 V2 那个错误实现)→ 22 条判据 pass 20 / fail 0,全绿。

这正是上一轮 375→377e02c 留下的假绿:不是缺测试,是 helper 名字把人骗了。
名字夸大覆盖范围比没有测试更毒,因为它读起来像有。

改法(只动 test,lib/loop.js 零改动,sha256 f28c5564… 前后一致):

- `multiCarrier` → `singleBlockCarrier`,实现不动,JSDoc 写明
  "产出:1 个 text block 承载 N 个 section(lib/index.js:932 的真实形状)"
  并记下它曾叫 multiCarrier 这段历史。
- 新增 `trueMultiCarrier(texts, kind)`:N 个 text block,每个 block 一个
  section,rendered = texts.join('')(glued)。注释写明真多块没有 spaced 变体。
- S2a/S2b → singleBlockCarrier;S3 标题改成 "single content block carrying N
  sections != those sections …" 并改用 singleBlockCarrier。
- S2c/S2d → trueMultiCarrier(['a','b']),断言不变。

变异自证(两条都咬住,且撤净后 sha256 回到基线):
  M1 `if (blocks.length > 1) return null`   → S2c 红("got 1 message(s)")
  M2 删掉 glued 分支(只剩 `rendered !== spaced`)→ S2b 红("got 1")

对 5c6aaf5 的干净 archive 跑本判据:tests 22 / pass 10 / fail 12,
其中 S2c("got 1 message(s)")与 S2d("got 2")如实为红。
2026-11-04 18:32:16 +08:00
377e02c943 fix(memory): make the loop actually promote real recall into system
`promoteSnapshotSections` accepted only ONE carrier spelling: `content: []`.
The plugin never emits that shape. `lib/index.js:932` always attaches exactly
one `{ type: 'text', text: injected }` block whose text IS `sections[0].text`,
so `promotedSection`'s `if (blocks.length > 0) return null` matched on every
real recall and the promotion was a no-op in production. Recall stayed in
user/message history — the exact defect 6d9ad62 claimed to fix.

6d9ad62's "surface recall as a system section instead of history" was never
true: the promotion it relies on was blocked by that content-non-empty check.
The unit tests could not see it because their `snapshotMessage()` helper built
`content: []` — a shape no producer emits — and the old P4 asserted "real
content blocks are NOT promoted", which is the opposite of reality.

It was confirmed today, from `lib/index.js:932`'s constant one-text-block
injection, and is fixed here.

The rule is now "move the text, don't rewrite it": a snapshot carrier with
content is promoted only when the rendered blocks equal the sections' text
under one of the two canonical joins (`''` glued, `'\n\n'` spaced), and the
promoted section text is the rendered content, so relocation is assertable.
Non-text blocks, mismatched text, and the stock runtime-context snapshot (whose
content carries a preamble the sections do not) pass through untouched.

Tests: S1-S7 plus real multi-block S2c/S2d pin the acceptance surface; every
negative case carries a positive control in the same decision, so the old
"content non-empty => reject" rule cannot satisfy it. P4 is split into P4a/b
(content == sections promotes; content != sections does not) with P4c proving
the split is decided by text, not by presence of content.
`test/loop-system-e2e.test.js` mounts the real HologramAgentLoop on real dsh
services, runs one turn, and asserts on the request the adapter received: the
recall is in the system prompt (E1) and in no non-system message body (E2),
carried by exactly one message (E2b).
2026-11-04 18:24:58 +08:00
5c6aaf53cf feat(memory): land the loop ports without wiring them
The four files under lib/loop/ were written against 0.2.1-rc.2 and have been
verified to import on their own; they are the substrate a replacement loop
needs to take over step(). This commit only puts them in the tree — lib/loop.js
is untouched, so nothing imports them yet and behaviour is unchanged.

Two packaging facts they bring with them:

  files  `lib/*.js` does not recurse, so lib/loop/ was shipping nothing.
         `lib/loop.js` and `lib/loop/*.js` are now listed separately because
         neither glob covers the other.
  peer   runtime-context.js imports @deepseek-ai/dsh-session, which the peer
         table never declared. G2b's allowlist covered it, so the static guard
         passed over a real declaration gap.

test/loop-ports.test.js pins the port interface rather than its behaviour: the
modules import alone, the export names survive, and the inbox projection keeps
key "inbox" / stateVersion 1. That literal pair is a wire format shared with
stock-loop sessions — a different key silently reads as "no pending input", a
different version makes stateSchema.parse refuse stored rows. The schema's
parse() is also exercised against seven malformed persisted rows, since
replacing a zod schema with a hand-written check is exactly the kind of change
that can be a no-op and still look fine.
2026-11-04 17:27:36 +08:00
f1b74a35ef feat(memory): ship the profile overlay that mounts the replacement loop
6d9ad62 added `lib/loop.js` — a subclass of the harness `AgentLoop` that moves
per-turn recall out of conversation history and into the system prompt. That
class was never instantiated by anything: the commit proved the pure
`promoteSnapshotSections` function, not that a replacement loop can actually be
mounted. This commit adds the two pieces the mount needs.

`cordis.patch.yml` is the overlay that does it, and it is the only artefact that
proves the swap is possible:

- `- id: agent-loop / disabled: true` is mandatory and is addressed by ID, not
  by name. `AgentLoop`'s constructor ends with
  `ctx.effect(() => ctx.agents.setFactory(this))`
  (dsh-agent-loop/lib/index.js:1590) and `setFactory` throws when a factory is
  already registered (dsh-agent/lib/index.js:429-437). Leaving the base row
  enabled fails startup with "an agent factory is already registered".
- The inserted row reuses the package itself under the `dsh-memory/loop`
  subpath, with no `config` block: `HologramAgentLoop` declares no `static
  Config`, so it inherits the parent schema and the profile's own `agent-loop`
  config rows keep working through the inherited constructor.

`package.json` gains that subpath export plus `lib/loop.js` in `files`. Without
the export the overlay resolves to nothing and the profile cannot boot — the
two changes only work together, which is why they land in one commit.

Measured on this machine with the overlay applied to a headless profile
(`~/.dsh/profiles/headless/cordis.patch.yml`), dsh 0.2.1-rc.2:

- `dsh --profile headless "回答两个字:收到了"` -> exit 0, stdout `收到了`;
  `--dump-config` shows `- id: agent-loop` with `disabled: true` alongside
  `- id: hologram-agent-loop, name: dsh-memory/loop`.
- A tool round trip returns the tool's output: asking for
  `echo TOOL_OK_42` via bash yields `TOOL_OK_42`.
- SIGINT during a long task exits in 1s with code 130, stdout empty.
- The web profile's patch layer is still `[]` — untouched.

npm test: 247 pass, 0 fail.
2026-11-04 17:07:48 +08:00
6d9ad62a8f feat(memory): surface recall as a system section instead of history
Per-turn recall currently enters through the `agent/pre-step` waterfall, and
that hook can only return `messages`. The recall block therefore lands in
conversation history as a user message: the model reads its own memory as if a
user had said it. `systemPrompt.context` cannot fix this — it runs before the
turn text is known, so it can only render input-independent text.

The loop's `preStep` is the first seam holding BOTH the assembled prompt and
this turn's claimed messages. `lib/loop.js` subclasses the harness AgentLoop and
wraps that seam on the agent instance: a pure snapshot carrier message is moved
out of `messages` and into `assembly.sections`, so it becomes part of the system
prompt for that turn and never enters history.

Deliberately decoupled from the memory plugin: nothing imports it or matches its
name. Promotion keys off the shape every snapshot-style injector already uses
(`source.sections`, the same shape `dsh-time-context` emits).

Constraints honoured, each of which was a measured failure elsewhere:
- The promoted section carries `interpolate: false`; recalled text is free text
  and may contain `{{...}}`, which the strict interpolator rejects.
- The subclass defines no constructor and no static `inject`. The parent already
  registers the turnBoundary + inbox projections, calls `setFactory(this)`, and
  declares `{{provider}}`/`{{model}}`; re-registering any of them throws at
  startup.
- Only the instance's `preStep` is patched, never the prototype, which other
  agents share.

Also wires the new peer: `scripts/link-dsh.sh` gains dsh-agent/dsh-agent-loop
(without them the package cannot resolve at test time), package.json declares
dsh-agent-loop as a peer and adds the new test file, and G2b's allowlist admits
dsh-agent-loop as a first-party harness package, with the reason recorded.

npm test: 247 pass, 0 fail.
2026-11-04 14:54:49 +08:00
783a7f87bb feat(memory): observable recall log behind config.debugLog
The plugin shipped with zero console.* and zero ctx.logger calls, so a
production recall failure left no trace: `degraded` is a return value the
caller sees once, and the injected text is only visible if the model quotes
it. Everything below is observability — no scoring, no DDL, no docs/README,
no new dependencies.

## The line

One summary per recall turn, covering the four fact groups asked for:

  recall   query=<n>ch hits=<n> topK=<n> zeroHit=yes|no
  budget   budget=<n> source=explicit|host|fallback kept=<n> singleHitOverBudget=yes|no
  degrade  degraded=<mode> skipped=<n> skippedDim=<n> err=<summary>
  inject   inject=<n>ch

`query` is LENGTH ONLY (code points, so CJK is not double-counted). The query
is the user's own message and a memory log is the last place it should be
copied; length beside `hits` is enough to tell "searched nothing" from
"searched the skill catalog".

`source` reads straight off segmentRecallBudget's own decision, and `kept` is
the post-slice count, so the line cannot disagree with what was injected.
`inject` is measured AFTER rendering, i.e. the exact string contextForStep
returns — not a re-derived estimate.

## Level policy (and why it is not always info)

  · fault — degraded not in {ok,no_embedder,aborted,vector_ready_unused}
    -> warn, emitted EVEN WITH debugLog OFF. A failed search is the per-turn
    event where absence of evidence is not evidence of absence.
  · zero injection -> debug (the commonest case on the shipping default must
    cost nothing at normal verbosity, but still be one greppable line).
  · otherwise -> info, only when debugLog is true.

`no_embedder` and `aborted` are deliberately NOT faults: the former is the
shipping configuration, the latter a deliberate stop. This is the same
judgement W11e already made for the model-facing notice — a constant warning
trains the reader to skip the channel.

## Logger source, and why ctx.logger alone was not enough

Source is ctx.logger('dsh-memory'); if the cordis build has no logger service
the code falls back to a console.warn/console.error shim (debug/info also go
to warn — stdout is never written, since `dsh --profile headless` prints the
ANSWER on stdout, so a line there is not noise but a corrupted answer).

★ Measured, and the reason this change installs its own sink: cordis ships
exactly ONE default exporter, an in-memory ring buffer
(cordis/lib/index.js:594-603), and no dsh bundle adds a terminal one. Calling
ctx.logger.info(...) in a real profile therefore writes to a buffer nobody
drains — the plugin would have looked instrumented while a headless run still
printed nothing. installStderrSink registers a scoped exporter on that same
service: it filters by message.name (the exporters map is process-wide, so
without the name check it would reprint every other plugin's warnings under
this prefix) and by severity, then renders with Logger.format and writes to
stderr. Disposal rides on ctx.effect inside LoggerService.exporter.

Two robustness details, both earned the hard way:
  · the whole line travels as ONE `%s` argument — Logger.format expands
    %s/%d/%o in the format string, so a provider error containing `%s` would
    otherwise truncate the rest of the line (verified: "50% off %s" came out
    "50% off undefined NaN");
  · err is flattened to one line and cut at 80 chars — a log line must stay a
    line;
  · every logging path is wrapped, because a throwing logger would turn an
    observability feature into a recall outage.

## Verification

test/memory-log.test.js (L1–L8b, 12 tests) pins: default is silent; the
summary carries all four fact groups in exactly ONE line; the query text
never appears; explicit/host/fallback source naming; a fault warns with
debugLog off; a zero-injection turn is debug not info; log-on equals log-off
for both the injected text and lastRecall; stdout is never written; the line
reaches stderr; foreign loggers are not reprinted. L4† is a real mutation —
it patches lib/index.js on a copy and asserts L4 goes red — because a guard
that cannot fail is not a guard (the W11d† lesson).

Self-tested in a real headless profile (dsh 0.2.1-rc.2, llmsproxy), same
question, only debugLog differing. Answer stayed "4471" on stdout in both:

  debugLog=true   dsh-memory: info: recall query=21ch hits=1 topK=3 zeroHit=no
                  | budget=838860 source=host kept=1 singleHitOverBudget=no
                  | degraded=no_embedder skipped=0 skippedDim=0 err=-
                  | inject=144ch
  debugLog=false  (no dsh-memory line; stderr carry only node's
                  ExperimentalWarning)
  zero-hit turn   dsh-memory: debug: recall ... zeroHit=yes ... inject=0ch
  fault, OFF      dsh-memory: warn: recall ... degraded=embed_error
                  err=fetch failed | inject=290ch   <- speaks without opt-in

npm test: 237 tests, 237 pass, 0 fail (the W11d†ctx failure is gone — see
below). npm run check: 12/12 checkpoints.

## One test edit, forced by the caller change

W11d†ctx's mutation anchor was `const hits = await this.recall(query, { signal })`,
which no longer exists: contextForStep now rebinds as `const raw` because the
hits it renders come out of segmentRecallBudget (the preceding commit's work,
not this one). The anchor moves to the `raw` binding it would sit beside. The
mutation still flips W11d; only the anchor text changed.
2026-11-04 08:15:23 +08:00
ca0b5ff813 fix(memory-b): keep non-enumerable recall diagnostics through budget slicing 2026-11-03 21:35:59 +08:00
2069cd5f25 feat(memory-b): budget-segment recall injection in the real host path 2026-11-03 21:31:36 +08:00
771a053eea docs(CL-1F): restore A1 semantics and cite V7 logs for G1
A1: revert to the 06155d4 wording (recallBlocks stays synchronous, a new
async recallBlocksHybrid is added). The previous basis claimed the async
pre-step handler justified making recallBlocks async, which the code
contradicts: lib/recall.js:229 exports a sync recallBlocks with zero awaits,
and lib/recall.js:613 is the async wrapper.

G1: replace the stale count with the readings already present in the V7
evidence logs (/tmp/v7-order-20261101-173334-t1..t3.log = npm test,
225/225/0; c1..c3.log = npm run check, 12/12), noting that phase A is a
subset of the whole-suite run. No new test/check run was performed.
2026-11-01 17:52:52 +08:00
7fc3d46b9a docs(CL-1): revert V2 documentation changes 2026-11-01 17:41:52 +08:00
591f34070d feat(memory-b): port V7 largeTopK candidate bound before fusion 2026-11-01 17:37:48 +08:00
06155d4bcc feat(memory-b): expose text document side as interface only 2026-11-01 17:21:46 +08:00
8a87c973d2 test(memory-b): add self-built tier-3 flip case 2026-11-01 17:08:54 +08:00
e2536f14f3 feat(memory-b): port V5 candidate assembly and asymmetric MinScore 2026-11-01 15:50:17 +08:00
5b217c1f78 feat(memory-b): expose V3 vector and symbol attribution 2026-11-01 15:34:55 +08:00
b7eff5db66 test(memory-b): strengthen C3 recall and corruption mutants 2026-11-01 12:39:53 +08:00
d73d47c081 feat(memory-b): port C3 centroid staleness and async rebuild scheduling 2026-11-01 12:32:16 +08:00
d57c9dc798 feat(memory-b): port V2 non-exact fusion weights
Also clear three stale counts the release train authorised: criteria A1
wording (sync + hybrid), criteria G1 counts (173/12), README test-site count.
2026-11-01 12:01:22 +08:00
fc92db9f5b feat(memory-b): port V1 exact vector pin adjustment 2026-11-01 11:51:13 +08:00
8bdd9f5ce0 test(memory-b): make F8 mutants bite the positive criteria 2026-11-01 11:11:37 +08:00
96adb172eb test(memory-b): add F8 checkpoint for width validation 2026-11-01 11:01:44 +08:00
b5d3f6ec73 feat(memory-b): add F7 fingerprint space stats 2026-11-01 10:50:46 +08:00
f62b826c64 test(memory-b): 补 unknownSpace / dimensionMismatch 的文案判据(四态齐)
你的复核成立:renderUnavailableTail 每态一个 clauses.push,但只有
spaceMismatch(D5b)与 noVector(D5c)有判据。删掉另两段,全套仍绿 ——
它们在渲染层是装饰,与恒 0 的 skipped_dim 同型。

我复现时先得到「各红 1 条」,查下去发现那是副本缺 README 导致
「README states no counts」那条报 ENOENT 的噪音,不是判据咬住。
去掉噪音后确认:你的结论正确,两态确实全绿。

补四条(每态一条判据 + 一条抑制变异)
  D5e  unknownSpace:断言「1 without a space label」,且断言文本里
       **不含** browse / exact text —— 该态走语义路,借用 noVector 的
       「可浏览」说法会误导(这是 F6 那条 browse≠recall 口径的第三次复用)
  D5f  dimensionMismatch:断言「1 whose width does not match this provider」
       **且**指向「fix the config」这一补救,且不含 browse
  D5e† 删 unknownSpace 的 clauses.push ⇒ 必须红
  D5f† 删 dimensionMismatch 的 clauses.push ⇒ 必须红

真变异实测(删整段 clauses.push)
  删 unknownSpace   → not ok D5e、not ok D5e†   (2 红)
  删 dimensionMismatch → not ok D5f、not ok D5f†(2 红)
每条变异同时咬住「本体判据」与「自己的 suppression 测试」,不是只红一条。

两处写作教训
- D5f 的构造必须走 raw putBlock:F8 正确地拒绝显式传错宽度,
  所以「库里有窄向量行」现实中只来自历史数据或修复脚本
- D5e†/D5f† 初版只 new Context() 没装 systemPrompt/tools 服务,
  dispose 时 "Cannot read properties of undefined (reading 'context')"
  —— apply() 的 inject 需要它们,已补

现状:四态 noVector / unknownSpace / spaceMismatch / dimensionMismatch
在**渲染层**各有判据与抑制变异,不再有装饰态。

验证
- npm test 166/166(162 + D5e/D5f/D5e†/D5f†)
- npm run check 10/10
- 干净副本实数见后续消息
2026-10-30 17:26:16 +08:00
99d0670ebe fix(memory-b): 返工 ③④ —— trigger 直判据 + skipped_dim 不再是假字段
③ trigger 补直写判据(此前只有间接覆盖)
你的复核准确:摘掉 trigger 的 WHEN 会让 F3/D3 红,所以「间接有守卫」——
但没有一条盯 raw-writer。而 trigger 存在的全部理由就是防 raw-writer
(修复脚本、迁移、运维手敲 sqlite3)。putBlock 自己就能把列写对,
所以真实风险是「trigger 全没了也没人发现」。

MIG5 三条:
  - raw UPDATE 把 vector 改成长度不符 ⇒ vector_dim 被拉回真值;清空则归 0
  - raw INSERT 带错误 vector_dim ⇒ 被 trigger 覆盖为真值
  - MIG5† 分别 DROP 两个 trigger,各自断言「谎言能存活」
真变异:从 DDL 里删掉整段 trigger ⇒ MIG5 前两条红(MIG5† 仍绿,因为它
主动 DROP,不依赖 DDL 是否存在 —— 这是两者分工正确的标志)。

④ skipped_dim 恒 0 是假字段,选 (a) 补维度过滤
你的诊断对,且比我的注释更狠:一个永远不能非零的字段,配合
`typeof === 'number'` 的断言,把 F4「维度失配与指纹失配分开计数」
做成了摆设。这与更早那处 assert.equal(skipped, 2) 是同一类。

实现:
- searchFts / 包含兜底都携带 dimension(来自 vector_dim 列)
- recallBlocks 新增 dimension 选项,在**空间过滤之后**做维度过滤
  ★ 顺序有意:先空间后维度,保证一块同时 stale 且窄时只计一次(记 space),
    否则两个计数会重复计同一行、谁也加不出「被丢弃的块数」
- skippedDim 与 skipped 分别挂在返回数组上(F4 要分开)
- recallBlocksHybrid 把 space.dimension 注入 scoped,六个降级分支自动继承
- lastRecall.skipped_dim 改为读真实值

判据 F4b 四条:
  - 同指纹不同宽度 ⇒ skippedDim=1 且 skipped=0(不串桶)
  - 同时存在旧空间块与窄向量块 ⇒ skipped=1、skippedDim=1,不双计
  - last_recall.skipped_dim 能非零
  - F4b† 变异:删维度过滤 ⇒ skippedDim 归 0、窄向量被召回 ⇒ 红
实测:hits=[C 正常],skipped=1,skippedDim=1,两者都能非零。

一处测试构造的调整:窄向量块用 raw 写入而非 commit —— F8(正确地)
拒绝显式传错的宽度,所以「库里存在窄向量行」在现实中只能来自
历史数据或修复脚本,与 trigger 那条判据的假设一致。

文档
- criteria: F4 补「两个都能非零」与恒 0 字段的教训
- dev-notes 增第 6 类「恒为 0 / 恒为真的字段」,含自查问句
  「这个字段的取值集合里,有没有一个能让我这条断言失败?」

验证
- npm test 162/162(155 + MIG5 三条 + F4b 四条)
- npm run check 10/10
- 干净副本实数见后续消息
2026-10-30 17:07:19 +08:00
d9280773aa fix(memory-b): 返工 —— last_recall 可查询 + renderIndex 按态分述
① embedFailure 有落点了(此前只有注释)
你的判断准确:degraded 是**单次调用的返回值**,调用方看得见但运营方查不到;
criteria:282 要的是「可查询」,两者不能互相顶替 —— 就像 states 不能顶替 skipped。

实现:
- StableMem.lastRecall:最近一次 recall 的 {mode, skipped_fp, skipped_dim,
  embed_error, at},由 recall 路径写入
- stats() 增加 last_recall 字段(形状照 criteria:282)
- 健康召回记 'vector_ready_unused'(A 组语义),失败记 'embed_error'/'aborted'
- **不进四态**:那是从行派生的库状态,塞进单次事件会让同一时刻读两次
  得到不同数字 —— 正是 D4 要避免的

判据 3 条:真 adapter 抛错后 stats().last_recall.mode 读得到该次降级;
干净召回会覆盖;D3b† 变异(删掉写入)⇒ 判据红。

② renderIndex 按态分述,不再一句包四态
你实测的四态揉成一句是真的错:旧句尾「still searchable by exact text」
对 noVector 成立、对 spaceMismatch 在生产召回路径上**不成立**
(带 fp 召回 0 条,不带 fp 浏览 1 条 —— 与 F6 裁定的 browse≠recall 同一条口径)。

改成分态子句:
  spaceMismatch     → 「from a retired space (reachable by browse only, not by recall)」
  unknownSpace      → 「without a space label (semantic recall unavailable)」
  dimensionMismatch → 「width does not match this provider (fix the config, then re-embed)」
  noVector          → 「not yet embedded (still reachable by exact text)」

③ 无 embedder 走常态静默(P2,一并改)
无 embedder 是出货默认,不是异常。原来 2 块 noVector 每轮都被告知一次
「召回不了」,而与 exact recall 仍能命中相冲突,且与 W11e 的静默口径相反。
现在 space() === null 直接返回 ''(只留计数行);运营侧从 stablemem_stats 查。
测试用 reportNoVectorAlways 钩子单独覆盖该措辞,生产默认 false。

判据 4 条:D5b(mismatch 必须说 browse、不得说 still searchable)、
D5c(noVector 说 text recall,且先实证 exact recall 真能命中)、
D5d(无 embedder 时不重复告知)、D5b†(单句尾部 ⇒ 红)。
另把 D5/D5† 改为需要配置空间——它们原来在无 embedder 下断言,
与 D5d 的新口径直接冲突。

实测两场景
  A 无 embedder:renderIndex 只报「2 durable note(s)」,无警告;states noVector=2
  B 旧空间块:renderIndex 报「1 from a retired space (reachable by browse only,
    not by recall)」;states spaceMismatch=1;生产召回 0 条 skipped=1

验证
- npm test 155/155(151 + 返工 4 条)
- npm run check 10/10
- 干净副本实数见后续消息
2026-10-30 16:49:55 +08:00
160b5b5139 fix(memory-b): 三项验收整改 —— 去写死数字 / F8 硬报错 / blockStates 去 JSON.parse
一、skipped 断言不再写死数字
原 assert.equal(hits.skipped, 2) 属于「手抄数字」——与刚删掉的 README 计数同类:
fixture 一改就悄悄不再描述事实。
改为从构造库现算:expectedSkipped = counts.unknownSpace + counts.spaceMismatch,
并先断言 expectedSkipped > 0(防止变成「0 == 0」的假通过)。

二、F8 从「事后统计」改成「写侧硬报错」
原状:写侧维度校验只降级成「不嵌入」,坏向量仍能落库,靠 blockStates
的 dimensionMismatch 事后兜住 —— 那是 accounting,不是 validation,
与 criteria:165 的「硬报错」不符。

实现:putBlock 新增可选 expectedDimension,声明了宽度且不符 ⇒ 抛错不落库。
commit 在「调用方显式传 vector」时传 expectedDimension。

★ 两个入口必须分清,否则会与 W4 打架:
  - 调用方 bug(显式传了宽度不对的向量)⇒ **必须抛**,否则它以
    「块在、召回不了」的形式沉默很久
  - provider 异常(embedding 返回宽度不对)⇒ 按 W4 降级为不嵌入,块仍写入
    (把上游抖动抛给用户 = 让一次 provider 故障变成写入失败)
判据含三例:显式传错宽度抛;显式传对宽度通过;provider 返回错宽度降级不抛。
F8† 变异:把宽度检查改成恒不触发 ⇒ 坏向量落库 ⇒ 判据红。

三、blockStates 不再解析向量(性能账)
实测 2000 块 × 2048 维:
  改前 354ms/次(其中 255ms 是纯 JSON.parse)
  改后 4ms/次(约 90×)
而 renderIndex 每轮都调它 —— 这是挂在 pre-step 热路径上的固定成本。

做法:memory_blocks 新增 vector_dim 列(维度是行事实,不是负载内容),
  - putBlock 写入时一并写
  - 迁移时为存量行回填一次(只此一次,不在读路径)
  - 加两个触发器保证 vector 与 vector_dim 永不脱节:
      ★ 理由:既然这一列的存在就是为了「不解析负载」,那每个写入者都背上了
        保持一致的义务。漏一个写入者(修复脚本、测试 fixture、未来迁移)
        就产生一行「维度是谎话」的数据 —— accounting 报它 active,
        而召回静默跳过它。用触发器让这个状态**不可表示**,而不是只劝阻。
  - 静态判据:blockStates 函数体内不得出现 JSON.parse(防以后「顺手简化」改回去)

四、embedFailure 记账
不进四态(它是单次调用事件,不是库状态),criteria 已补说明:
四态是库状态、从行派生;embedFailure 属于 recallBlocksHybrid 的 degraded,
由 W 组覆盖。塞进库状态会让「同一时刻读两次得到不同数字」,正是 D4 要避免的。

顺带修:F4† 的变异锚点因 blockStates 改写而失效(withMutatedCopy 显式报
「anchor not found」——这条守卫按设计响亮失败,没有静默变绿)。

验证
- npm test 148/148(143 + F8 四条 + 性能守卫一条)
- npm run check 10/10
- 性能实测见上
- 干净副本实数见后续消息
2026-10-30 16:29:05 +08:00
b73607ed02 feat(memory-b): F3/F4 四态派生计数 + D3 工具面 + D5 提示渲染
顺序遵守裁定:F2 过滤先落地(上一条 425c441),这一条才加计数。
先做计数会数出一个恒为 0 的假指标。

四态定义与归属
  noVector           vector 为空                     回填
  unknownSpace       有 vector 但 fp 为空            重嵌(说不出来属空间)
  spaceMismatch      有 vector、有 fp ≠ active        重嵌到当前空间
  dimensionMismatch  有 vector 但宽度不对             改 provider 配置(F4:与上面分开)
  embedFailure       本次调用拿不到向量                ← 不在这里,它是单次事件不是库状态

F3/F4 判据(4 条行为 + 3 条变异)
  F3   四态从库派生;skipped 非零(实测 skipped=2,不是恒 0)
  F4   dim 与 fp 分开计数,且不互相重复计入
  F3   改库/删库后计数跟着变(证明不是内存累加,D4)
  F3   skipped 在符号路也计(fusion.go:495 同款:只测向量路等于没测)
  F3†  内存累加器实现 ⇒ 「跟随数据库」断言红
  F3†symbol 计数只挂在向量路 ⇒ 符号路的 skipped 断言红
  F4†  把 dim 并进 spaceMismatch ⇒ 分桶断言红

D4:从 DB 派生,不累加
store.blockStates(activeFp, activeDim) 每次扫行计算,无缓存无累加。
判据用「绕过插件直接 UPDATE / DELETE,计数必须跟着变」证明。

D3/D5:两个消费者,一个来源
- renderIndex() 与 stablemem_stats 都调 blockStates(),不各留一份
- D5 的提示读同一个 unavailable 计数(noVector+unknownSpace+
  spaceMismatch+dimensionMismatch),说明「N 条暂不可语义召回,
  仍可按精确文本检索」
- D3 判据含无空间/有空间两例:无 active space 时 mismatch 必然为 0
  (没有参照物),这条我第一版判据写错了,已按实际语义修正

★ 一处新工具引入的回归(已修)
新增 stablemem_stats 时把工具名硬编码,第二个实例挂载时撞名
"tool 'stablemem_stats' is already registered" —— 与之前 prompt context
名同型:isolate() 不分区工具名。已改为可从 config.statsToolName 覆写,
loader 测试同步传参。

★ 一处「注册了但跑不到」的坑(已修)
registerTools 里我用了 return ctx.tools.register(...),后续第二个
register 永远不可达,但文件读起来像注册了两个。已去掉 return 并注释。

验证
- npm test 143/143(138 + F3/F4 四条 + 变异三条 + D3/D5 两条)
- npm run check 10/10
- 实测数字(5 块构造库):
    blockStates('fp-cur',3) = {total:5, active:1, noVector:1,
      unknownSpace:1, spaceMismatch:1, dimensionMismatch:1}
    recall("缓存", fp-cur) → 返回 1 条, skipped=2
    recall("4324", fp-cur) → 返回 2 条, skipped=2
- 干净副本实数见后续消息
2026-10-30 15:59:22 +08:00
48c52497c2 feat(memory-b): F6 三段口径固化成判据 + A1b 降级记账
裁定:F6 选 (a),措辞改写,不留互斥读法
原措辞「仍可按文本调出、不参与向量召回」读起来像互斥。实际是三层:
  「按文本调出」= store 级无空间浏览,**不是生产召回路径**。

不改 F2 去迁就 F6 字面自洽的理由:F2 是 fusion.go:495 同款安全缺陷修复,
优先级高于 F6 的措辞。所以 F6 改成三段并列,每段一条断言,
**同一个用例内全断言**:

  数据层:指纹变更后旧块仍在库中 —— 块数不减、按 fp 分组两行都在
  浏览层:store 级不带空间参数的文本查询仍能取到旧块
  召回层:带 fingerprint 的生产召回路径必须把旧块过滤掉(F2 承担)

为什么必须一个用例:只断言「过滤掉了」会漏掉数据被误删
(删库在召回层看起来就是「过滤正确」);只断言「能调出」会把 F2 挡回去。

F6 判据 3 条
  F6          三段全断言 + 反向对照(当前空间块两层都能取到,
              防止断言因为「什么都找不到」而假成立)
  F6†data     变异:putBlock 顺手 purge 其它空间的行走道 ⇒ 数据层断言红
  F6†recall   变异:去掉空间过滤器 ⇒ 召回层断言红
两条变异各自只咬自己那一段,与 F6†data/†recall 的分工一致。

★ F6†data 的变异写法踩了三次坑(据实记)
  1. 只写 form(没真改代码)—— 那不是变异,是自测
  2. 注入 SQL 里的转义引号把测试文件写成 SyntaxError
  3. 最终用 String.fromCharCode(39) 拼引号 + 数组 join 构造注入文本,
     避开嵌套模板字符串的转义地狱

裁定 2:A1b 降级要记账
A1b 原先逐字节锁死 recallBlocks 源码,F2 合法地要改它,已降级为
「不传 fingerprint 时行为不变」。但降级后的 A1b-behaviour 只跑 golden
**前 5 个** case,变异 A(非精确带分数微调)下它可能是绿的。
已在判据注释写明:**结论不由 A1b 单独给出,由 A2 兜**
(A2 走全部 45 例、比精确分数);A1b-behaviour 只是烟测,不是权威。

同步进 memo:docs/dev-notes-mutation-criteria.md 增第 5 条
「判据降级时,覆盖面必须一起交代」—— 这不是失效模式,是记账纪律。
自查问句:这条判据降级后,原本由它兜住的结论现在由谁兜?
答案必须是一个具体的、覆盖更广的判据名。

验证
- npm test 131/131、npm run check 10/10
- 干净副本(git archive + link-dsh)实数见后续消息
2026-10-30 15:39:03 +08:00
425c441470 feat(memory-b): F5 固化为 fail-closed 判据 + F2 符号路空间过滤
裁定 1(F5):fail-closed,写侧直接拒收
docs/phase-b-criteria.md §0.2 从「待拍板」改为「已定」:
  无名向量的块直接拒收,比放过再靠下游兜更能守住空间隔离;
  安全语义优先,**不为 HA 的疑似缺陷同构**
  (HA 的 block_recall.go:140 三个 && 让空 fp 被放行,这是要修正而非复刻的行为)。
落点分两层并写明「缺一层都不算落实」:
  写侧 putBlock 抛错(已实现)
  读侧存量行归 unknownSpace、不参与向量召回(F 组)

F5 判据(5 种输入形态 + 变异)
  省略 / 空串 / undefined / 数字 / null 一律抛错,且都不落库
  合法形态仍工作(无向量无 fp;有向量有 fp)
  F5† 变异:删掉写侧守卫 ⇒ 无名向量被接受 ⇒ F5 必红

顺带修一处:lib/store.js 的 vectorFP 加 String() 归一。
原先变异摘掉守卫后会以 SQLite bind 错误崩,掩盖了真正的断言失败
(变异因为错误的原因变红 = 不算证据)。

裁定 2(F2):先过滤,后计数
F2 —— 空间过滤必须覆盖符号路,不只向量路
- store.searchFts 现在返回 fingerprint / hasVector,
  两条 intake 路径(FTS 与包含兜底)都携带身份字段
  ★ 兜底路径第一版漏了这两个字段,导致过滤器看到 hasVector === undefined
    而放行 —— 正是「过滤器只覆盖两个入口中的一个」那种 bug
- recallBlocks 新增 fingerprint 选项,在 pool 构建后统一过滤
  刻意**不复刻** HA 的三连 &&:本仓 fail-closed,
  带向量但无法命名空间的块一律排除(§0.2 裁定)
  无向量的块不受影响(它们本来也不参与向量路,文本仍可检索)
- recallBlocksHybrid 在函数入口解析一次空间并注入 options,
  六个降级分支全部经 scoped 调用 —— 逐调用点设置会在加第七个分支时漏掉一条

F2 判据(4 条行为 + 2 条独立变异)
  F2   符号路命中旧空间块 → 被排除
  F2   不传 fingerprint → 过滤器不生效(phase A 行为不变)
  F2b  有向量但 fp 为空 → fail-closed 排除(HA 此处会放行)
  F2   hybrid 在所有降级路径上应用同一过滤
  F2†  删掉过滤器 → 旧空间块回来
  F2†b 让 searchFts 不携带身份 → 过滤器失明(过滤只剩一个入口)

A1b 的调整(必须说明)
A1b 原先逐字节锁死 recallBlocks 源码,而 F2 合法地需要改这个函数。
改为守它真正要守的东西:**不传 fingerprint 时行为不变**
  - 静态:过滤器必须 gated 在显式传入的 fingerprint 上
  - 行为:golden fixture 前 5 例逐字段一致
依据:golden 语料 12 个块全部没有 fingerprint,
所以 F2 对 phase A 是纯增量;A2 仍全绿即为证。

验证(干净副本:git archive → 空目录 → link-dsh → 自跑)
见下一条消息附实数。

未 amend / 未 force push。
2026-10-30 15:29:23 +08:00
e2c2bb41b7 docs: 删掉 README「nothing to install」假声明,改正 peer 叙述
d144284 补了「Prerequisite: link the harness packages first」章节,但留下两处
与新章节自相矛盾的话,这一提交收掉:

1. README §Install 的安装注释 `npm install  # nothing to install; dsh packages
   are peers` —— 直接删。实测它不成立:干净副本里 npm install 只拉到 cordis
   (四个 peer 里唯一非 optional 的)加它的传递依赖,dsh-llm /
   dsh-system-prompt / dsh-tools 三个仍然缺;不 install 更彻底,四个全缺。
   改成说明 peer 归属 + 指向前置章节的链接。
2. 新章节开头 `This repository has **no runtime dependencies**` —— 同样不成立
   (lib/index.js 运行时 import 三个 @deepseek-ai 包)。改成「不以本插件自身
   依赖的形式拉取任何东西」,把 peer 归属说清,并写明 npm install 只解决
   cordis 一个。
3. 症状段补一句 npm run check 同样红(实测 exit=1,checkpoints.js 在 import
   阶段就 ERR_MODULE_NOT_FOUND),原文只提了 npm test。
4. scripts/link-dsh.sh 头部注释里的 `zero runtime dependencies` 一并改成同义
   但不撒谎的说法。

验证(自己跑,不转述)
- 干净副本 git archive HEAD + 本补丁,不 link:
    not ok loader / phase-b-g / phase-b-h / plugin
    # tests 34  # pass 30  # fail 4
    npm run check exit=1(Cannot find package '@deepseek-ai/cordis')
- 同一副本 bash scripts/link-dsh.sh 之后:
    # tests 120  # pass 120  # fail 0
    npm run check exit=0,10 条 ✔
- npm install 单独一步(不 link)也复现:四文件 ERR_MODULE_NOT_FOUND,
  缺的是 dsh-system-prompt / dsh-llm(cordis 已装)
- README 全文再无「nothing to install / no runtime dependencies / zero
  runtime dependencies」类断言(grep 零命中)
- README 计数禁令仍绿,无 .orig/.rej/.bak 入库

更正一处旧结论:交接说「不 link 时 4 个文件 ERR_MODULE_NOT_FOUND」= 少 4 个
用例,不对。那四个文件在 import 阶段就死,用例根本没注册,所以 npm test 汇总
是 34 tests,不是 116/120。已在 README 里写成「a handful of tests rather than
the full suite」,避免再误导。
2026-10-30 15:07:45 +08:00
d1442848c4 docs: README 补前置准备(干净 clone 直接跑 npm test 会红 4 个文件)
缺口(评审复现,我独立复现确认)
git archive HEAD 到空目录、原样 npm test:
  # tests 34  # pass 30  # fail 4
  not ok test/loader.test.js / phase-b-g.test.js / phase-b-h.test.js / plugin.test.js
根因:Cannot find package '@deepseek-ai/cordis'。
而 README 全文对 link-dsh.sh / node_modules / 前置准备零命中 ——
正文只写「npm test 是 how many 的权威」,默认读者已经跑过 link-dsh.sh,
而这个前提谁都没写。

这与本轮刚修的那个缺口同族:判据/文档声称的能力,在没有守卫的地方悄悄不成立。
(刚删掉 README 计数,理由是「没守卫就会漂」;「npm test 是权威」这句话
  同样没有守卫 —— 它默认了一个没人写下来的前置。)

修法(按裁定选 ①,不用 pretest 钩子)
README §Verify 开头新增「Prerequisite: link the harness packages first」:
- 说清本仓零运行时依赖,@deepseek-ai/* 全部是 peer,
  必须来自机器上已装的 dsh(vendoring 会与它要运行的 harness 漂开)
- 给命令 bash scripts/link-dsh.sh
- 明确写出跳过它的症状:四个文件 ERR_MODULE_NOT_FOUND
  (loader / plugin / guard / http 四套,与实测逐一对齐),
  并说明这是缺前置的正常形态,不是树坏了
- 补非默认安装根的可选参数

按裁定的第二条不加判据去测「干净 clone 能跑测试」(成本高于收益),写清楚就够。

顺带一处:README 的计数禁令只匹配数字形态(119 tests / 10 checkpoints /
10/10 passed),新段落用了英文「four files」,不被误报 ——
在守卫里加注释说明这个 scope,以及为什么不去匹配文字形态
(「四个文件报 ERR_MODULE_NOT_FOUND」是合法的散文,再往下写就变成小解析器)。

验证
- 干净 clone 复现:无链接 4 红;bash scripts/link-dsh.sh 之后 120/120、check 10/10
- README 描述的失败文件清单与实测逐一一致
- npm test 连跑 5 次 120/120
- npm run check 3 次,exit=0、10 条全绿
- README 计数禁令仍绿(未误报新段落)
- 无 .orig / .rej 残留,未 amend / 未 force push
2026-10-30 15:02:38 +08:00
0e65dfee64 fix(check): checkpoint 全废时 runner 仍报通过 + 补回丢失的覆盖
缺口(评审复现,我独立复现确认)
上一条替换旧 README 判据时,把它的第二条断言一起带走了。
旧 test 同时守两件事:
  1) README 计数与实现一致      已判定不值得守,删
  2) checkpoints.js 至少注册一条 值得守,跟着 1 一起消失
grep 全仓:没有任何东西守 2。

实测后果(很安静)
把 helper 换成空操作、调用点全保留:
  npm run check  ->  0/0 checkpoints passed, exit=0
  npm test       ->  120 条全绿
即 checkpoint 全废、runner 报通过、测试一条不红。

修法:守结果,不守成因
scripts/checkpoints.js 结尾(if (failed > 0) 之前):
  if (results.length === 0) {
    console.error('no checkpoints were registered ...')
    process.exitCode = 1
  }
放 runner 而不是补回静态计数的理由:静态计数只能抓 helper 改名;
results.length === 0 抓的是结果,改名、被 stub、条件跳过都会红。

但 process.exit(0) 能绕过任何脚本内检查,所以另加一条外部断言
(test/phase-b-g-static.test.js)三层:
  - declared > 0                    helper 没被改名
  - 源码含 if (results.length === 0)
  - 该守卫确实设置 process.exitCode = 1
分工:runner 守结果,测试守 runner 还带着那道守卫。

实测
  0 条注册(stub)    -> no checkpoints were registered, exit=1
  条件跳过            -> 同上, exit=1
  正常态              -> 10/10 passed, exit=0
  变异:删 runner 守卫 -> not ok 6
  变异:helper 全改名  -> not ok 6

docs/dev-notes-mutation-criteria.md 增第 4 类
判据被替换时,旧判据的覆盖静默消失
- 形态:一条 test 守两件事
- 实测后果:0/0 passed / exit 0 / 120 全绿
- 守结果不守成因的四类成因对照表(含 process.exit(0) 是拦不住的那格)
- 自查问句:这条判据除了名字里那件事,还顺手守了什么
- 探针经验:不要用注释掉调用去验零注册,会变成 SyntaxError

验证
- npm test 120/120、npm run check 10/10
- npm test 3 次、npm run check 3 次(带 exit code 核对)全绿
- 无 .orig / .rej / /tmp/mut-* 残留
- 未 amend / 未 force push
2026-10-30 14:44:09 +08:00
fc5fe11590 docs: 去掉 README 计数并在判据侧禁止它 + 变异判据方法论 dev-notes
1. README 计数去掉(不留守卫)
去掉「119 tests」与「10 checkpoints / 10/10 checkpoints passed」。
理由按裁定:一个没有守卫、被手改过五次的数字是负资产,
它给人的确定感是假的;加守卫要翻倍套件时间,不值。

守卫反过来断言「README 不得出现计数」:
  /\b\d+\s+tests\b/i
  /\b\d+\s+checkpoints\b/i
  /\b\d+\s*\/\s*\d+\s+checkpoints passed/i
三种写法实测都能抓住(120 tests / 12 checkpoints / 12/12 passed)。

顺带处理一处同类:原文「(6 tests)」是手抄的测试数,删;
「12 blocks × 15 queries = 45 cases」是 fixture 自身内容量,也删并改为
指向 fixture 文件 —— 由文件决定的东西不该在文档里再写一份。
(README 现在的口径:表格说「验什么」,`npm test` / `npm run check` 说「多少」。)

2. docs/dev-notes-mutation-criteria.md(新)
把三轮踩出来的方法论落成仓库文档,README 的 Verify 段加指针。
三类失效模式,每条都给「形态 / 实测证据 / 正确形态 / 自查问句」:

  ① 自测型假变异(犯四次:W11† / W11d†a / W11d†b / W12†)
     变异在 test/ 里自己拼替身,一行 lib/ 没碰 ⇒ 真回退下保持绿
     实测:M-a / M-b 下 W11d†a / W11d†b 均绿,只有 W11d 红

  ② 清单写死(W11f)
     手写 MODES 漏掉新 case;future_mode_a/b 测的是「掉进 default 的」,
     永远测不到「有人新写了一个 case」
     实测:植入 brand_new_mode(零命中时撒谎)→ 写死版全绿,扫描版红
     并记下边界:自动推导不能替代「提取本身也要被守卫」,
     所以还需要 declared.length >= 4 + W11f-a(guards the guard)

  ③ 变异共享状态并发撞车(我自己引入的)
     就地改写 lib/*.js,而 node --test 并行跑文件 ⇒ 别的文件读到中间态
     实测:约 1/30 偶发失败,症状像 flaky 断言;A1b / G2b / G5 这类
     读源码的判据会读到被改坏的中间态
     修法:在 lib/ 副本上变异(复制 lib + package.json + 软链 node_modules),
     finally 清理,锚点失配显式失败

文末给通用自查清单 9 条 + 一句话记住三条。

验证
- npm test 119/119、npm run check 10/10
- 连跑 6 次全量 0 失败
- 无 .orig / .rej / /tmp/mut-* 残留
- 未 amend / 未 force push,199553f 之后是新提交
2026-10-30 14:36:41 +08:00
199553f91a test(memory-b): W11f 模式清单改为从源码 case 字面量推导
接你备好的两个加固 patch(w11f-hardening-test / -README),
应用后 md5 与期望一致,lib/ 零改动:
  test/phase-b-h.test.js  655fd63d8c18d88a7b7885868654fb80
  README.md               dcf50c6138a8357ca21363f09a104597
  lib/recall.js           c8fdffd25d5340291adf6cb26e1741f(未变)

盲区(我在 d972a2d 上独立复现了)
在 lib/recall.js 里植入一个会撒谎的新分支:
    case 'brand_new_mode':
      return '[Memory] New mode degraded; matches below may be incomplete.'
旧版 W11f / W11f† / W11f†b 三条**全绿**。
根因:MODES 是手写清单,新 case 不在里面。
而 future_mode_a / future_mode_b 那两个名字有误导性 ——
它们测的是「掉进 default 的未知模式」,永远测不到「有人新写了一个 case」。
而正常演进恰恰就是新写 case,那时 default: 与手写清单**两头都管不到**。

加固(补丁采用)
- 模式清单从源码 case '<literal>' 扫出来,不再手写
- declared.length >= 4 + 三个必需 mode 的存在性断言:
  提取失效就响亮失败,而不是迭代空列表照样绿
- 新增 W11f-a(guards the guard):用变异往源码塞一个新 case,
  断言扫描能看见 —— 因为「扫描器坏掉」是这套判据唯一能静默失效的方式
- 追加 'mode_with_no_branch_at_all' 覆盖「无 case、落 default」那一态

同一植入下新旧对比(我实测)
  旧版(写死 MODES) → # pass 3 / # fail 0,漏
  新版(源码扫描)   → not ok W11f
    'brand_new_mode + zero hits must not promise entries below;
     got: [Memory] New mode degraded; matches below may be incomplete.'

另做了两个更狠的探针,确认它不会静默失效:
- 函数改名导致导入失败 → 整个文件响亮失败(不是静默绿)
- 保留函数名但把 case '<literal>' 全改成常量引用(语法合法仍可导入)
  → not ok W11f: 'expected at least 4 case literals in degradationFound,
     found 0: ' —— 正是设计意图

也没变松:W11f†(删 aborted 分叉)/ W11f†b(删 default 分叉)仍各自只咬自己那半。

验证
- npm test 119/119(+W11f-a)
- npm run check 10/10
- 连跑 8 次全量 0 失败
- 变异 runner 零残留(/tmp/mut-?????? = 0)
- 未 amend / 未 force push,d972a2d 之后是新提交
2026-10-30 14:13:39 +08:00
d972a2d135 fix(memory-b): W11f —— aborted / default 零命中时不再承诺条目
接你备好的四个 patch(ready-lib / ready-test / README / docs),
应用前逐个审过内容,dry-run 干净,应用后 md5 与你给的期望值一致:
  lib/recall.js          c8fdffd25d5340291fadf6cb26e1741f
  test/phase-b-h.test.js c06685abb7672fa806ca37e0d1cb8947
  README.md              3c183b045dd7de4a54338ed9d01b3738

问题(我上一轮修 embed_error 时只修了那一个分支)
  aborted 与 default: 在零命中时仍说「matches below are …」,而下面没有条目。
  aborted + 零命中不是边角 —— 用户点停止、且这条查询本来就查不到东西,
  是取消最常见的形态。
  default: 更糟:它是未来任何未知模式**唯一**会走的路,
  最不该在这里开始编。

修法(补丁采用)
  把「有没有条目」只问一次,四个分支共用:
    const nothing = !Array.isArray(hits) || hits.length === 0
  default 用「nothing was found, so treat this as "unknown", not "absent"」——
  把「没搜到 ≠ 没有」这条口径落在**兜底分支**上,
  而不是每加一个模式才记得补一次。

W11f 判据:表驱动、双向
  遍历 [undefined, no_embedder, embed_error, aborted, vector_ready_unused,
        future_mode_a, future_mode_b]
  零命中:notice 非空时不得含 matches below|below are|entries below
  有条目:notice 非空时必须指向条目,且不得说 found nothing
  第二条以前完全没人管 —— W11/W11c 只查「出现 FAILED / cancelled」,
  不查它是否指向了真实存在的条目。

两条变异各自独立(实测,不是「都红就算数」)
  M-A 只删 aborted 分叉
    not ok 57 - W11f
    not ok 58 - W11f†
    ok     59 - W11f†b        ← default 那半仍绿
  M-B 只删 default 分叉
    not ok 57 - W11f
    ok     58 - W11f†         ← aborted 那半仍绿
    not ok 59 - W11f†b
  若两条变异下红的是同一批,那就是重复计数(W11d†a/†b 的老毛病)。

验证
- npm test 118/118
- npm run check 10/10
- 连跑 8 次全量,0 失败(按你的要求超过 5 次)
- 变异 runner 零残留:/tmp/mut-?????? 前后均为 0
  (/tmp/mut-probe 是 10:17 的历史副本,与本轮无关,未动)

未 amend / 未 force push,80d188e 之后是新提交。
2026-10-30 14:00:07 +08:00
80d188efc1 fix(memory-b): P0 no_embedder 逐轮注入 + 变异改为真改 lib/(并修掉自引入竞态)
P0 —— no_embedder 每轮注入(随 82b7546 进了远端)
复现(真链路,config 不给 embed = phase A 出货默认,10 个普通回合)
  10/10 回合被注入,共 2130 字符,均值 213 字符/次
注入原文是恒定、无条目的两行记忆头。

根因:W11d 拆两处短路时把 no_embedder 一起放行了。
问题不在「该不该说」,在「不该每轮说」——它是一条永久配置事实,
renderIndex()(systemPrompt.context)已经每轮在讲。
代价不只是 token:每轮一段恒定无条目的记忆头,模型的正确反应是学会跳过
该段,等真降级出现时也不看,正好废掉 W11 的用意。

修法
- no_embedder 返回 ''(注释写明理由与被测数字)
- 顺手修文案矛盾:embed_error + 零命中原来会说「matches below are…」
  但下面没有条目。现在分两种措辞:
    零命中 -> "FAILED … and the lexical fallback found nothing"
    有命中 -> "FAILED …; matches below are lexical/symbolic only"
- aborted / embed_error 不动

判据 W11e:默认配置(无 embedder)+ 零命中 ⇒ 注入必须为 ''
修复后同一探针:10 个回合 0 个被注入,0 字符
W11e 与 W11d 互为反向守卫:真·本轮事件要说,持续状态不该每轮说。

变异纪律(你指出的第四次同型,我认)
W11d†a / W11d†b 原来是测试里自己拼的局部函数,不碰 lib/ ——
真回退下它们保持绿,只有 W11d 变红。已删除,不留作计数。
换成三条真变异:W11e† / W11d† / W11d†ctx,
都真改源码、import 变异版、断言行为翻转。

★ 改真变异时我自己引入了竞态,并被抓到
第一版 withMutatedSource 直接在磁盘上改写 lib/recall.js 再还原。
node --test 是并行跑测试文件的,别的文件正在同时 import 它。
实测 1/30 左右偶发失败,症状看起来像「断言 flaky」,其实是 harness 竞态。
已改为 withMutatedCopy:整体复制 lib/ + package.json + 软链 node_modules
到临时目录,在副本上改、在副本上 import,完全不碰共享树。
验证:连续 30 次全量 0 失败;变异锚点漂移时显式报错(不会静默通过)。

文档
- README:W11e 的理由与实测数字、变异纪律(必须改 lib/,改 test/ 不算)、
  以及上面这条「变异共享状态不能与代码并发跑」的竞态记录
- docs/phase-b-criteria.md:W11e 进表、W11d 的变异列改为两条独立真变异、
  ★★ 变异纪律段(同型四次:W11†/W11d†a/W11d†b/W12†)

验证
- npm test 115/115
- npm run check 10/10
- 连跑 3 次 test + 3 次 check 全绿
- 另跑 30 次全量确认竞态已除(0 失败)
2026-10-30 13:34:18 +08:00
82b754661d fix(memory-b): W11d 两处短路 + W12 abort/失败分流 + 文档订正
W11d —— 你说得对,不是一行。两处短路各能独立吃掉提示
  ① lib/index.js contextForStep: `if (hits.length === 0) return ''`
  ② lib/recall.js renderRecall:  `if (!Array.isArray(hits) || hits.length === 0) return ''`

修法(按你给的形态):「有没有条目」与「有没有话要说」分开判:
    const notice = degradationNotice(hits)
    if (lines.length === 0 && notice === '') return ''
不写成「notice 非空就总出 header」——那样健康路径零命中回合每轮灌一行记忆头,
白烧 token 还教模型忽略这一段。

四场景实测(真 Context/SystemPrompt/ToolRuntime/真 adapter/真 http)
  A 降级+命中   -> empty=false failed=true  entries=true   54ms
  B 降级+零命中 -> empty=false failed=true  entries=false  51ms   ← W11d
  C1 健康+命中  -> empty=false failed=false entries=true    7ms
  C2 健康+零命中-> empty=true  failed=false entries=false   2ms   ← 正确沉默
与你实测四条一致。

W11d 判据 + **两条独立变异**
  W11d†a 只把 renderRecall 短路改回去  -> not ok 50 - W11d
  W11d†b 只把 contextForStep 短路加回来 -> not ok 50 - W11d
两条分别实测,证明「只修一处无效」,也证明每处都有人守着。

W12 abort 与 embed_error 分流(你上一条四项里的 ③)
原来两者都报 embed_error ⇒ 用户主动取消时提示「搜索失败」,会诱导无谓重试。
现在:options.signal.aborted 或 AbortError ⇒ 'aborted',其余 ⇒ 'embed_error'。
degradationNotice 新增 aborted 分支,措辞是「was cancelled」而不是「FAILED」。
W12 判据:两种标签、两种文案、必须不同。
变异(合并成 'embed_error')→ W10b / W11c / W12 三条同时红。
已同步 W10b/W11c/W11d 的断言(它们原假设 embed_error)。

② README:224 订正
`recall('etcd 端口', 5)` 已失效——第二形参变成 options 后,数字不是 {topK},
默认值生效。改为 `recall(q, { topK: 5 })`,并补 await(commit/recall 都是 async),
另加一段说明这个静默失效,以及「不 await 也能写」正是 W6 守着的脆弱假设。

④ docs/phase-b-criteria.md 补 W 组(原 0 命中)
新增 §W 表:W1/W5/W4/W6/W7/W8/W9/W9b/W10/W11/W11d/W12,
每条写「逼出它的 bug」与变异,并记下这组的共同教训:
判据用替身/短路/自造形状时,验的是替身而不是真代码。
(W9 假 embedder、W11d 两处短路互相掩盖、V3b 自造 2 段 batch 是同一形态。)

★ 你那条附带发现我也记下了:探针把成功响应写成 {vector:[...]},
而适配器只认 {embedding} 或 {data[0].embedding}(lib/embed/http.js:199-202),
于是「健康路径」实际一直在走 embed_error,C1 误报 FAILED。
自造 mock 时形状必须照适配器真读的字段抄,否则验的是自己的 mock。

验证
- npm test 113/113(108 + W11d/W11d†a/W11d†b + W12/W12†)
- npm run check 10/10
- 提交前连跑 3 次 test + 3 次 check,6 次全绿
2026-10-30 11:24:17 +08:00
72f02b866a fix(memory-b): W10 读路径取消 + W11 降级可见
W10 读路径完全没有取消(真 bug,与 W9 同形)
复现(真 adapter + 挂死的本地 http,timeoutMs 压到 2000,50ms abort)
  recall_elapsed_ms = 2004
  decision messages = 2 (aborted after 50ms)
  in-flight provider calls = 1
生产口径 DEFAULT_TIMEOUT_MS = 30_000 ⇒ 每次 pre-step 都可能卡 30 秒,
用户取消毫无作用。

根因链
  lib/recall.js:437  embedText(String(query ?? ''))     ← 只有一个实参
  lib/index.js:237   recall(query, topK)                ← 没有 signal 形参
  lib/index.js:257   contextForStep(messages)           ← 没有 signal 形参
  lib/index.js:431   payload.signal 只被读了 .aborted 一次,之后不传

修复:signal 逐层透传
  agent/pre-step payload.signal → contextForStep(messages, signal)
  → recall(query, {topK, signal}) → recallBlocksHybrid(..., {signal})
  → embedText(text, options.signal)
修复后同一复现脚本:recall_elapsed_ms = 54

W10 判据(走真 hook 链,不是直调 seam)
  W10  真 adapter + 挂死 server + 50ms abort 走 pre-step ⇒ <500ms,
       且 degraded === 'embed_error'
  W10b 同一件事在 seam 层,防止将来重构 hook 链把回归藏起来
W10† 变异(删掉 options.signal 实参)
  not ok 44 - W10: aborting a pre-step interrupts the recall embedding promptly
    error: 'an aborted pre-step must not wait for the embedding provider; took 30001ms'
  not ok 45 - W10b
  恢复后 # pass 108 / # fail 0
  ★ 30001ms 正是生产口径那个 30 秒

W11 降级必须能被模型看见(你提醒的口径)
确认属实:renderRecall 原来只拼 header + 命中行,完全不渲染 degraded。
而且 hits.degraded 是 enumerable:false(A 组 golden 比较需要),
所以它对 JSON.stringify / Object.keys / 任何序列化日志都不可见 ——
断言这个属性等于什么都没证明。文本是模型唯一的信道。

新增:
- renderRecall 渲染降级提示行
- degradationNotice(hits) 导出,三分支(no_embedder / embed_error /
  vector_ready_unused=不打扰模型),default 兜底防未来新模式静默落到 ''
- embed_error 的措辞点明「此处没有记忆不等于没记录过」,因为降级时
  「没有证据」不等于「证据为无」

W11 判据
  W11  降级 ⇒ 渲染文本含 FAILED 与 not prove it is unrecorded,
       并顺带断言 JSON.stringify 确实看不见 degraded(说明为什么需要文本信道)
  W11b 健康召回不出现任何提示(不误报)
  W11c 端到端:aborted pre-step 的文本既有命中也有提示,且 <500ms
W11† 变异(renderRecall 去掉提示行)
  not ok 46 - W11
  not ok 48 - W11c
  恢复后 108/108

一处自我更正:W11c 初版没有任何实质断言(注释里写「text 可能为空,
所以只断言类型」),那是假测试。已改为种子一条符号路可命中的块,
断言文本非空、含 FAILED、含命中值、且 <500ms。

★ 顺带记录一次操作事故:改 renderRecall 时我的 Python 替换把整个
  文件匹配进去,lib/recall.js 被写成 53 MB。已 git checkout 恢复并重做,
  当前文件 521 行、syntax OK、全量测试通过。以后大段替换先备份。

验证
- npm test 108/108(102 + W10/W10b + W11/W11b/W11c)
- npm run check 10/10
- 提交前连跑 3 次 test + 3 次 check,6 次全绿
2026-10-30 11:01:22 +08:00
170bc5fde2 fix(memory-b): W9 —— adapter 的 embedText 丢掉 caller signal(真 bug)
复现(真 adapter + 本地真 http server,3s 回包,50ms abort)
  signal forwarded? outcome=RESOLVED vector=[0.1,0.2,0.3] elapsed=3012ms
  ★ caller abort ignored — signal dropped by embedText signature

根因:lib/index.js:173 调 embedText(text, options.signal),而
lib/embed/http.js:152 声明的是 embedText(text) —— 第二实参被 JS 静默丢弃。
生产语义:用户已取消,工具继续阻塞到 adapter 自己的 30s 超时,
而且最后还把向量写进库;isConcurrencySafe 的兄弟调用一起被堵。

为什么 99 条全绿
W5/W5† 用的是手写慢 embedder,它自己 addEventListener('abort') 了 ——
判据测的是「我希望的行为」,没测真实 adapter。与上一轮 V3b 自造
2 段 batch 是同一形态:替身站到了唯一可能出错的那段代码前面。

修复
- embedText(text, signal):用 AbortSignal.any([signal, controller.signal])
  融合两个取消源。两个语义都保留:
    · 用户取消要立刻停(实测 50ms -> 53ms)
    · provider 卡死也要停(实测无 signal 时 151ms 超时;
      有未取消的 caller signal 时仍 151ms 超时)
  Node >= 22.5 已有 AbortSignal.any,不手写 fuse、不轮询。
- 同步修 Embedder 的 JSDoc 与 interface 类型,把第二个参数写进契约

W9 判据(真链路,不用假 embedder)
  W9  caller abort 打断真实请求:耗时 < 500ms 且确实抛出
  W9b adapter 自身 timeout 在有 caller signal 时仍然生效
  W9c 端到端(真 server + 真 adapter + ctx.tools.execute):
      块仍写入、vector 为空、error.info.code === 'ABORTED'

W9† 变异(贴红绿原文)
  ★ 第一次变异不干净:只改签名,函数体仍引用 signal ⇒ 抛 ReferenceError
    ⇒ W9 看到「很快抛错」判为通过。这是假绿。
  干净的变异(签名单参 + 去掉 fuse):
    not ok 41 - W9: a caller abort interrupts a REAL http embedding call promptly
      an aborted call must reject, not resolve with a vector
    not ok 43 - W9c: end-to-end — aborted tool call still writes the block
  恢复后 # pass 102 / # fail 0

f. 同形问题全仓扫描结论(grep + 实参/形参比对,非「我觉得」)
  lib/ 里所有传到 Embedder 的调用点:
    lib/index.js:173  embedText(text, options.signal)   -> 形参 (text, signal) ✔
    lib/recall.js:434 embedText(String(query ?? ''))    -> 单参,合法 ✔
  自动比对脚本报了一处 withDiagnosis 4>3 的告警,手工核对为误报:
  6 处调用实参分别为 2/2/3/3/3/2,正则被 Object.defineProperty 干扰。
  结论:无其它「传了实参、对面签名不收」的调用点。

README:376 修正
原文写「exec.signal is forwarded into embedText」——参数确实传了但对面对掉,
比没传更糟(读文档的人会以为验过)。改为与代码一致的表述,
并注明「W5 只覆盖管道,适配器侧由 W9 覆盖」。
另记下变异必须干净这条:失败原因不对的变异不算证据。

验证
- npm test 102/102(99 + W9/W9b/W9c)
- npm run check 10/10
- 提交前连跑 3 次 test + 3 次 check,6 次全绿
2026-10-30 10:41:42 +08:00