Skip to content

gate: dsh 协议矩阵车道(四门)+ dsh proxy 车道 — wire 硬断言 (#3475) - #3500

Merged
ranxianglei merged 70 commits into
feat/gate-plugin-lanesfrom
2026-10-17_dsh-gate-protocol-matrix
Oct 17, 2026
Merged

ranxianglei merged 70 commits into
feat/gate-plugin-lanesfrom
2026-10-17_dsh-gate-protocol-matrix

Conversation

@ranxianglei

Copy link
Copy Markdown
Owner

Closes #3475

Stacked on feat/gate-plugin-lanes (#3462) — rebase-clean on its head; after #3462 merges into master this PR rebases onto master with no expected conflicts (touches only scripts/gate/plugin-lanes.mjs, scripts/gate/README.md, .github/workflows/ci-gate-plugins.yml input description, .gitignore).

What

The gate's dsh lanes now cover all four protocols dsh's model client (pi-ai) speaks, plus a dsh proxy-mode lane for same-host two-activation-path contrast (owner addendum from #3462 review):

lane cordis api bili front door upstream door
dsh openai-completions /v1/chat/completions /v1/chat/completions (existing, byte-identical config)
dsh-responses openai-responses /v1/responses /v1/responses
dsh-anthropic anthropic-messages /v1/messages /v1/messages (SDK appends path)
dsh-google google-generative-ai /v1beta/models/<id>:streamGenerateContent same (no google→chat egress translation exists in bili — see Findings)
dsh-proxy openai-completions /bili/<upstream>/v1/chat/completions prefix /v1/chat/completions (codex-shape prefix lane; profile WITHOUT the bili bundle so the fetch intercept can't flip it back into plugin mode)

Same dsh headless driver, same corpus flow (t1 read → mid-window nudge → small-window fold → post-fold recall); only the provider api + baseURL suffix differ.

Wire hard assertions per door (WIRE_EXPECT): every recorder POST must match the door's path regex AND body top-level shape (messages / input / system+messages / contents); first request dumped to <lane>/egress-sample.json as round-trip evidence. Nudge-on-wire stays the hard assertion of #3401 (text must ride a forwarded body; log alone never counts).

Blocked-lane semantics (opencode2/#3461 rule, extended):

  • ENV-BLOCKED: upstream door unhealthy — all requests rejected + no turn completed, OR degraded mid-flow (some 200s then 4xx/5xx, flow incomplete — the self-hosted responses→chat mapping-bug shape). Traffic + wire shape stay hard; turn-dependent records drop out of the tally.
  • CLIENT-BLOCKED: zero upstream traffic + every turn died on a client config-validation error (the dsh-google case today, see Findings). Whole lane drops out; auto-promotes when the client ships the protocol — no script change needed.

Calibration fixes (found by running the matrix against a real model)

  • GATE_OUTPUT_TOKENS (default 4096 = old value): bili.json output + dsh cordis maxTokens. Thinking models degenerate to zero-visible-text turns when the output budget < their thinking budget.
  • p1 extraction now takes the MAX payload over the whole post-t1 log (window-source flip lines land mid-t1 before payload-bearing lines; old slice-at-first-match read 0).
  • Post-fold widening (phase 3b): adaptive-small-window recipes only (dsh family + claude). When the folded session's floor sits at the preflight target edge, widen the small window so t4 lands with margin instead of tripping the [Bug] Codex 额度中断后恢复长会话,preflight SSE 摘要为空并持续 502 #726 dead-end cooldown. Fixed-SMALL_WINDOW lanes untouched.
  • Mid-seed guard: mid window seeded above the derived small window.
  • Lane-local dsh install (GATE_DSH_VERSION, default latest) + lane TMPDIR: system dsh 0.1.x lacks headless --json, and a stale global billion-context shadows the candidate bundle via Node resolution from the global anchor.
  • t1 dual marker (S40+S07): verifies the gate precondition (model actually read the corpus middle) instead of letting downstream S07 recalls fail for fixture reasons. Applies to ALL lanes' t1 turn — stricter precondition check, disclosed below.

Behavior changes (explicit)

  1. New lanes are OPT-IN: GATE_AGENTS default unchanged; CI workflow input description lists them, default value unchanged.
  2. Existing lanes' generated configs are byte-identical (parity harness vs pre-Gate's dsh lane only validates the chat protocol — all four protocols supported by dsh need to be run once each (#3416 f | gate 的 dsh 车道只验证了 chat 一门协议——dsh 支持的四种协议都要各跑一次(#3416 续) #3475 file: cordis.patch.yml 388 bytes SAME, all 8 files SAME). Exception: the t1 prompt now asks for two markers — every lane's t1 turn changes wording; the S07@t1 record is a new hard record (a lane whose model elides the corpus middle now fails at t1 instead of at t2/t4).
  3. New env knobs, defaults preserve old behavior: GATE_OUTPUT_TOKENS=4096, GATE_DSH_SMALL_WINDOW=0 (derive), GATE_DSH_VERSION=latest.
  4. claude lane gains phase-3b post-fold widening (it has an adaptive smallWindow) — new capability, fires only when the floor sits at the target edge.
  5. No bili config surface change (gate-local env vars only; nothing under ~/.config/billion-context/).

Local validation (real model, OpenAI-compatible endpoint; endpoint stays internal, door availability only)

GATE_AGENTS=dsh,dsh-responses,dsh-anthropic,dsh-google,dsh-proxy GATE_OUTPUT_TOKENS=8192 → plugin-lanes: 56/56 passed (dsh-responses:env, dsh-google:client), exit 0:

lane verdict wire evidence (recorder)
dsh GREEN 17/17 16 reqs all POST /v1/chat/completions, top-level [model,messages,stream,stream_options,store,max_completion_tokens,tools,prompt_cache_key]; nudge text on wire; fold shrink 65%; S07 recalled pre+post fold
dsh-responses ENV-BLOCKED (mid-flow) 12 reqs all POST /v1/responses, top-level [model,input,stream,prompt_cache_key,store,max_output_tokens,tools] (genuine Responses shape); first 6 OK then HTTP 400 storm — self-hosted door's internal responses→chat mapping rejects spec-conformant multi-turn input; turn assertions excluded per #3461 rule
dsh-anthropic GREEN 17/17 16 reqs all POST /v1/messages?beta=true, top-level [model,messages,max_tokens,stream,system,tools]; nudge on wire; fold 65%; recalls intact
dsh-google CLIENT-BLOCKED zero upstream traffic; every turn died on dsh's cordis ValidationError (api expected "openai-completions" | "openai-responses" | "anthropic-messages"); whole lane excluded; auto-promotes when dsh ships the protocol
dsh-proxy GREEN 16/16 13 reqs via /bili/<upstream>/v1/chat/completions prefix, all on-shape; nudge on wire (log INJECT); fold 100%; prefix claim via manifest (29 tools); S07 recalled pre+post fold

Each lane also dumps its first egress request to <lane>/egress-sample.json. The dsh lane's generated profile config is byte-identical to pre-#3475 (parity harness, 8/8 files SAME).

Findings for the owner (not fixed here)

  1. The dsh-google cell is blocked on DSH's config surface, not bili. dsh-llm-pi-ai exposes exactly three explicit provider apis — const PROTOCOLS = { openai-completions, openai-responses, anthropic-messages } — in both 0.2.0-rc.2 (latest) and 0.2.1-rc.1 (next tag), with a comment saying the rest are "absent for want of a consumer rather than a blocker". pi-ai the library implements google-generative-ai; dsh's cordis schema refuses it at profile load. Acceptance fix: address all code review findings (condense, routing, session-id, dead code) #2 (google wire round-trip) is unreachable from dsh until dsh ships the protocol; the lane is built and auto-promotes. If the google wire must be validated NOW, that needs a different client (out of scope per the issue) or a dsh-side change (different repo).
  2. bili does NOT translate google→chat on egress (flagged in first triage reply): relay rebuilds the outbound body in the incoming protocol's shape; tests/e2e-google-compress.test.ts pins google-shaped egress against a strict mock, and tests/issue2658-dsh-anthropic-google-compaction.test.ts itself notes "no known dsh+google traffic yet". "google in, chat out" would be a new wire feature — needs its own issue + owner decision.
  3. Self-hosted SGLang-class endpoints reject spec-conformant multi-turn responses input at their internal chat mapping (messages[].content part type output_text fails pydantic validation) — the exact Three issues found during real-model stress testing: WS passthrough can't connect — HTTP upstream is guaranteed to die; | 真模型压测发现的三个问题:WS 直通连不上 HTTP 上游必死、超限时死锁+紧急提示风暴、compress 激活本身太重 #3461-sibling failure class the issue predicted; the mid-flow env-blocked rule exists for this. Endpoint stays unnamed here (internal infra).

ework-agent and others added 30 commits October 16, 2026 10:37
…dition no longer rides wall-clock luck

The AC12 boot-reconcile scenario requires the sweep to reach the
grandchild before the intermediate child adopts. listSessions() orders
by lastSeen desc and the two turns are ~seconds apart on a fast box, but
the timestamps are ambient: a coarse clock or any reload path restamping
lastSeen ties/flips the order — observed deterministically on the
windows-latest CI lanes (every completed run of master since the batch).
Once the child is visited first it legitimately adopts from the root,
and the grandchild adopting from a now-block-bearing parent is CORRECT
behavior under the #2807 contract, so the assertion fires for the wrong
reason. Pin grandchild.lastSeen one minute past the child's after the
strip step; production behavior is unchanged (both visit orders are
legal outcomes).
…3338)

The engine self-bootstrap capped its ~11 MB better-sqlite3 fetch at 10 s while
the self-updater budgets 60 s for its own comparable tarball pull. On a
non-trivial network (corporate proxy / slow link) that forced >1.1 MB/s
sustained before TLS/CONNECT overhead, so a single slow boot on Node<=21 (no
builtin node:sqlite) aborted the download and armed the 6 h cooldown — locking
the machine into legacy-only storage for hours even though a working engine was
obtainable.

Align BOOTSTRAP_TIMEOUT_MS with the updater's 60 s budget. Only behavioral
change: the startup wait ceiling in the narrow path where unified storage is
requested AND no engine exists AND auto-download is allowed AND cache misses;
the 6 h cooldown bounds it to at most once per window per machine.

Adds a test seam + three regression tests: a floor guard on the production
budget, an abort path (budget < download time), and a success path
(budget > download time).
…3351)

maybeAdoptDerivedFork set metadata.derivedBlocksAdopted = true unconditionally
right after maybeAdoptResume, even when the registered parent had zero folded
blocks at first contact. Because the request-time link lands exactly once
(handle.ts gates it on derivedFromSessionId === undefined), that prematurely-
persisted marker made every later boot sweep skip the session — so a multi-hop
grandchild whose intermediate parent was still young (no folds yet) permanently
lost block inheritance and kept replaying its full raw history (#2807 symptom
recurrence in a P->C->G topology).

maybeAdoptResume now returns { adoptedActive, seededRefs } and the gate closes
only when adoptedActive > 0 — the same discipline reconcileDerivedLineage
already applies (it sets the marker solely on a successful adoption). Ref-only
seeding against a young, block-less parent leaves the door open so a later boot
can adopt the blocks the parent folds afterwards.

Regression tests pin both directions: the gate stays OPEN when the registered
parent has no blocks at first contact (fails under the old unconditional set),
and CLOSES when the parent carries fully-present blocks.
…roxy respawn (#3380)

A proxy-death/give-up path cleared register.toolsReady even though tool
registrations belong to the host CONTEXT (they survive proxy death; execute
closures read the live base, #983). The next successful respawn then forced a
re-registration that DSH rejects ('tool X is already registered'), the retry
loop burned the identical doomed failure forever (145x/h in the incident),
toolsReady stayed false permanently, and every model request lost its
x-bili-plugin* identity headers — wire mode, anonymous zero-fold ledgers, and
413 preflight_compress_failed on large sessions until the host restarted.

- proxy-death paths no longer clear toolsReady (only the #2101 context-change
  path resets it); a respawn therefore restores identity with NO doomed
  re-registration flight
- registration is idempotent: a name this process already holds is adopted
  instead of thrown on (converges partial/dirty states), logged once
- consecutive failures escalate: capped exponential back-off (10s -> 5min,
  REG_RETRY_MAX_MS) + one loud client-event notice with the recovery action
  after 5 failures; retries never stop (#983/#2082)
- /acp exposes wire-mode identity loss (warning line + last error) instead of
  staying silent; a previously-serving proxy reads as 'temporarily
  unreachable ... recovering', not 'install'
- maybeRetry gate widened so a baseless-but-toolsReady state can still drive
  respawn/recovery

Tests: tests/issue3380-dsh-rereg-selflock.test.ts (incident repro, idempotent
adoption, back-off schedule + integration heal, one-time notice, /acp surface).
The env-variable description row still said 'default 8' while L173 and the
env table already say 0 (the code default is 0 since #3050). One-line fix in
en + zh.
…lt upstream (#3344/#3129)

#3129 switched the no-CLOUD_CODE_URL default from cloudcode-pa to
daily-cloudcode-pa (bare cloudcode-pa 400s on /v1internal:*), but the docs
still named only the old production host. Updated README en/zh, CLIENTS en/zh
(default-upstream sentence + MITM-fallback domain whitelist), cli help text,
and web i18n notes.
…on keys (#3344)

compress.absorb (#3293) and compress.imageCompression (#3266) were removed,
so users who had enabled them get their config silently ignored on upgrade.
Added a one-time INERT warning (same pattern as the existing
warnInertStripImages / warnInertResignPassthrough) that scans all three
compress levels and names the exact offending paths.
…leanup error (#3344)

killAndVerify sent SIGTERM to a replacement process that survived, then only
logged an error asking for manual cleanup. Added a SIGKILL round with its own
verification window before falling back to the manual-cleanup error, so a
stuck replacement is reaped automatically. Updated the #3044 regression test:
a SIGTERM-ignoring stub is now reaped by the escalation instead of leaking.
The writeHead wrapper stamped the ack header on whatever status the pipeline
wrote, including failures. A host trusting it unconditionally would skip its
resend after a failed turn and lose the user's message. Now the header is set
only for 2xx. In-repo clients already gate on 200, so this tightens the
contract without changing live behavior. Added a failure-path regression test.
…; output-restore floor respects proven budgets (#3406 items 2+4)

Item 2 — the #3286 ownership fast path judged envelope ownership by a
builtAtMs+1.5s grace window, so a sibling writing inside that window (legacy
mode, sidecar disabled — never touches index.db) was adopted as ours and its
envelope clobbered on the next save. The token now records the stat taken
right after OUR write landed (size+mtime); the fast path fires only when the
file still matches that stamp byte-for-byte. Unstamped tokens (debounced
kernel-internal saves, restore-replica seeds, crash before stamping) always
take the full read. Residual window shrinks from 1.5s to ~µs.

Item 4 — restoreOutputBudget's no-ceiling branch raised a session's recorded
high-water to OUTPUT_RESTORE_ABSOLUTE_FLOOR (32768); providers hard-capping
maxOutputTokens below that reject the raised value outright (400). A high-water
at/above the new trust line (4096, aligned with OUTPUT_CLAMP_MIN_OUTPUT) is
the provider-accepted budget and is restored as-is, never raised above;
missing/below-line high-waters keep the #3071 floor (born-starved, fork
rattle, death-spiral decay chains).

Item 3 (label resume vs background scan race, #3214) — NOT changed: no
low-risk mutex exists without a persistence-format/index change (details in
the PR body); deliberately stopped per the risk gate.
…te (#3434)

Between `forward …` and the outcome (client disconnect "0 bytes written" or
the idle-watchdog abort) bili logged nothing when the upstream accepted the
request and then sent no bytes, so an upstream stall read as proxy-side silence.

Arm a one-shot first-byte watchdog around the initial fetch in relay.forward:
if response headers have not arrived after 30s, log ONE warn naming method +
masked target + lane. Deduped once per origin per process (windowSourceLogged
pattern) so a long-prefill local model logs at most one line, not one per slow
request. Cleared on fetch settle or client abort; fires only while pending.

Additive logging only — deliberately NO fast-fail (would truncate legitimate
long prefills, cf. #1706/#1714) and NO new config surface (code constant +
_setForTest seam).
… gate

The four package-name/preset-id constants in dsh-compaction-disable.ts are
consumed only within that module; dropping their leading export satisfies the
unused-exports CI gate without changing any behavior or public surface.

Refs #3451
…mped (#3406 item 2)

Owner-directed follow-up to the review finding: the stamp only covered explicit writeNow/flushSync, so the per-turn markDirty -> scheduleSave path (kernel-internal debounce) never stamped and the #3049 fast path died on every debounced save. The debounce now lives in SessionStore (same coalescing/unref semantics as the kernel's); the firing write lands through store.writeNow and is stamped on success. flushSync supersedes the armed timer (kernel contract), flushAll drains host-pending builders before the kernel flush, cancelAll clears them, hasPending reports host timers. Two regression tests pin both sides: debounced saves collapse to the first full read, and a foreign write between debounced saves still forces the full read and survives.
…tovers

Fix #3344 range-review leftovers: stale docs, kernel lockfile, INERT config warns, SIGKILL escalation, 2xx-only ack
fix(fork): close the derived-blocks gate only on real block adoption (#3351)
…isable-vendor

feat: disable dsh native auto-compaction in web profiles at load time (#3354)
fix: dsh plugin — stop the re-registration self-lock after a failed proxy respawn (#3380)
…3329)

The pending-ack maps in opencode-native, omp-native and dsh-native were
keyed by request URL. Two conversations sharing one provider URL could
cross-attribute x-bili-applied-seq when a response arrived late or the
slot was evicted, poisoning both watermarks and killing incremental turns
for both via the sticky dead flag.

- native-intercept: thread each dispatch's outgoing headers into
  state.onResponse (new third arg); outgoingHeadersOf() covers all four
  fire sites (routed/rewrite x first/retry).
- incremental-client: x-bili-turn-id header, newIncrementalTurnId(),
  generic sweepStale().
- opencode/omp/dsh adapters: stamp the turn id on the outgoing request,
  key the pending map by it, attribute responses by it; drop the
  single-in-flight-per-URL guard (concurrent conversations now run their
  own turns - the server lane's per-conversation lock already makes that
  safe); TTL becomes memory hygiene only. dsh gains a TTL (it had none).
- regression tests: same-URL late-response cross-attribution for opencode
  and omp; per-dispatch header threading in native-intercept.
插件车道进仓库:真宿主 CLI × 真模型回归(#3416),远程默认不跑
…-keying

fix: attribute incremental-turn acks by per-request turn id, not URL (#3329)
…bootstrap-timeout

fix: align SQLite engine self-download timeout with the updater (10s -> 60s)
Redoes the image pre-compression removed in #3295 in simplified form:
on every outbound request (after kernel folding, before protocol
encoding, one shared pass over the generic message structure) an image
whose longest edge exceeds 1600px (BILI_IMAGE_RESCALE_MAX_DIM) or whose
base64 body exceeds 100KB is re-encoded fit-inside (never upscaled,
original format kept) on an outbound COPY only - session storage keeps
the original bytes byte-exact. A re-encode saving less than 20% of the
bytes is discarded (keep-smaller), so small and low-benefit images pass
through untouched. Only PNG/JPEG/BMP are handled (pure-JS jimp encoder,
zero native dependencies - sharp does not return).

Each shrunken image carries a stable annotation beside it reporting
current vs original size. Lanes that register bili tools name
read_original_image("mNNNNN") in the annotation: proxy-injection lanes
get it via the per-protocol manifest lists, plugin lanes (DSH/opencode)
via handlePluginManifest; tool-rejecting lanes (codex) get size-only
notes and no tool. read_original_image returns the original bytes from
local session storage (incomingImageIndex spill files); its results are
structurally exempt from re-shrinking - the zero-state loop guard
against the #3266 guess-reject-resend disease.

Output is deterministic: content-hash encode cache (one encode per
unique image), stable note text derived only from dims/bytes/ref - the
same history produces byte-identical outbound bodies, so upstream
prefix caching is undisturbed (#3266 lesson). Observability: one log
line per unique image and one per original-image read (ref, sizes,
session cumulative count+bytes); no hard cap.

Knobs (config surface): top-level config key imageRescale (boolean,
default true), env BILI_IMAGE_RESCALE ("0"/"false" off, live-read),
env BILI_IMAGE_RESCALE_MAX_DIM (default 1600, env-only). Documented in
CONFIGURATION.md en+zh. Legacy compress.imageCompression.* INERT
warnings remain owned by #3344/#3355.

Also removes the dead external:["sharp"] leftover from #3295 in
tsup.config.ts and adds jimp to the inlined devDependencies list.
kernel/** untouched.
…-starvation

fix(#3384): gate the #2490 refused-ledger planning floor so healthy dsh sessions keep their output budget
CONFIGURATION.md en+zh: top-level imageRescale key row, detailed
section, env quick-table rows and long-form env entries for
BILI_IMAGE_RESCALE / BILI_IMAGE_RESCALE_MAX_DIM. CHANGELOG [Unreleased]
entry stating the behavior change (since #3295 images passed through
byte-identical at original resolution; now large outbound images are
sent shrunken by default on an outbound copy only).
IMAGE_RESCALE_DEFAULT_MAX_DIM was dead (knobs.ts carries its own
default); rescaleImage and RescaleCtx are module-internal.
The rescale pass reassigned processedMessages in-place, so Prepared
(and thus rememberPluginMessages) persisted the rescaled copies plus
synthetic note messages instead of the wire originals. Encode from a
separate egressMessages local; persistence keeps byte-exact originals
(spec: storage stores what the wire received).
awork and others added 15 commits October 17, 2026 13:56
…esults (#3402)

New AbsorbConfig.mediaOnly (default unset = neutral): when true, isAbsorbCandidate rejects media-less results, appendAbsorbPrompts exempts media-bearing candidates from the minToolTokens floor (image bytes are not counted in text), and applyAbsorb mirror-rejects a non-media target so screening and execution agree. Bumps acp-kernel 0.0.128 -> 0.0.129 (rebased onto master whose kernel is already at 0.0.128 via the #3406 screen-observability change).

kernel-change: optional mediaOnly gate for absorb distillation — host-side config plumbing alone cannot express candidate scoping inside the kernel's absorb pipeline
…t parity (#3402)

Host applies the product policy the kernel leaves neutral: resolveAbsorbSettings defaults mediaOnly to true (image-bearing results only), so pure-text large results are no longer marked by default and the old over-compression mode is gone; mediaOnly:false restores legacy full-text behavior. absorb.enabled still defaults false. New config key compress.absorb.mediaOnly (boolean) added to the schema, cleaning loop, and plugin-lane divergence fields; config docs regenerated (EN/ZH/website). Adds a regression test pinning that the plugin-lane absorb prompt gate and the manifest advertisement read the same base config block (#3293: prompt appears iff tool is advertised). CHANGELOG backfills the entry #3309 omitted and records this revival.
The generated config index table already carried compress.absorb.mediaOnly, but the hand-maintained '#### absorb' reference prose still showed the pre-mediaOnly field set and described 'large tool results'. Add mediaOnly to the Type line + sub-field bullets and reword to 'qualifying tool results' so the authoritative reference is internally consistent.
…ibution before absorb section (cache-seam, #3422 review)
…data key (#3422)

Rebased onto master 2164823: the digests also fold in #3431's
config-file epoch metadata stamp (master-side change landed on the
same lines since the branch diverged). Regenerated with
scripts/update-storage-render-goldens.ts; diff is digest-only.
…-keys INERT list (#3402)

The #3309 revert revived absorb, but #3344 still listed compress.absorb alongside compress.imageCompression as a removed/inert key: old-config parsing dropped absorb and tests/removed-compress-keys-inert.test.ts asserted it parsed to undefined. Pull absorb out of INERT_REMOVED_COMPRESS_KEYS (imageCompression stays removed), correct the warning text, and update the test so absorb is asserted kept while only imageCompression warns.
…oved-key pin with #3402

CI red (run 38991748164, 3 shards): master's tests/removed-compress-keys-inert.test.ts
(#3344) pins compress.absorb as INERT (feature removed by #3293), while this PR
revives it — the key parses again, so the undefined assertion fails deterministically.

Drop absorb from INERT_REMOVED_COMPRESS_KEYS (imageCompression stays — its #3266
removal stands), narrow the warning text accordingly, and update the pin test:
absorb now asserts PARSED ({enabled,minToolTokens} survive) and absent from the
warning; imageCompression keeps its full-path naming assertions.
feat: dsh web admin relay (security.adminRelay) — remote browsers open the bili panel (#3373)
feat(absorb): revive absorb scoped to image results + fix plugin-lane tool visibility (#3402)
…ub-spans (#3192 #3205)

A client-dropped message leaves NO array slot, so array-adjacency segmentation plus both position-based mergers (mergeRangesToThreshold, formatRanges) each bridge across it and re-emit one span bracketing the recorded-dead ref — the self-contradictory receipt from #3192. Treat the dead ref as a segmentation gap (same level as covered/pruned/carrier): break the group at the hole in buildCompressibleRanges, then tag the following range noMergeBefore so neither merger can re-bridge across it.

Supersedes the host whole-span-drop from #3195/#3204 at the source: the surviving sub-spans are now advertised instead of the whole doomed span being dropped. The host excludeDeadRefRanges filter stays as a no-op safety net. Strict no-op when state.deadRefs is empty.

kernel package.json 0.0.124 -> 0.0.125; new kernel/tests/dead-ref-split.test.ts; updated tests/compress-recovery-ranges.test.ts #3192 to assert the split sub-spans.
…e fix (#3385 / #3338 directive 3)

The Node >= 22.5 upgrade lever and mirror list live only in lane logs and
the web banner today — surfaces the user never sees. acp_status is the one
surface the MODEL reads every session, so mirror the degrade reason line
there ("relay this to the user"):

  STORAGE — storage: shadow (unified-first reads, dual-write)
    ⚠ degraded — no SQLite engine available (...) — upgrade hint (relay this to the user)

Healthy storage and the intentional BILI_ENCRYPTION_KEY legacy opt-out
stay quiet. Tests build a real store with engines forced unavailable (the
recording seams fire exactly as in production) and pin _setStoreForTest so
ccrLoopConfig cannot rebuild a healthy store mid-call and clobber the
degraded state.
…ergency nudge backs off per session (#3461)

Problem 2a (host-side): when preflight exhausts every foldable range and the gap cannot close by construction (futility math with no unusable draws, nothing-compressible exits, zero-dispatch exits), the final fail-fast now answers 413 non-retryable instead of 502. Relay-dependent exhaustion (empty/truncated/incomplete summaries, budget draws, pool saturation, sticky verdicts) deliberately stays 502 — retry/canary machinery owns that class. PreflightFailure gains an optional deterministic marker set only at the structurally doomed sites.

Problem 2b: the emergency tier-1 nudge arm was a pure function of contextUsage >= 0.7, so a headless client retrying an over-window turn re-injected the EMERGENCY prompt on EVERY request (measured 7 injections in 1 second). emergencyNudgeArmed() now gates the arm per session: first pressure round injects, then re-arms only when a reduction landed (reductionKeyOf changed), a full flat growth step (default 50K, KDD#8) of tokens accumulated, or the 10-minute valve elapsed. Pressure admitted by every standing gate but held by the backoff reports nudgeOutcome 'gated' so self-heal streaks (#2155/#3004) keep crediting active rounds instead of starving.

Test updates follow the status mapping: structurally doomed byte-relay/image lanes (issue1841 A, issue496 r2/r3, issue767, issue857) now assert 413; issue1841 B (fixture relay always returns empty summaries) reverts to 502 as relay-dependent; issue2155 idle-loop arithmetic pins the gated-round credit.
…back

fix(storage): builtin npm+npmmirror mirror fallback + Node upgrade hint for the SQLite engine download (#3338)
Over-limit exits: structurally doomed preflight answers 413, emergency nudge backs off per session
…f-kernel-split

kernel: split compressible ranges around recorded-dead refs so receipts never bracket them (#3192 #3205)
@ranxianglei

Copy link
Copy Markdown
Owner Author

🤖 Powered by ework · qwen3.8-27b

(ai: vllm-qwen/qwen3.8-27b)

查重:不重复。 open+closed 按 "dsh protocol matrix / plugin-lanes / wire assertion / #3475" 多角度检索,无同症状同机制条目;本 PR 对应独立需求 #3475(dsh 协议矩阵车道)。

结论:暂不可合

代码本身质量高、逻辑正确、默认行为不变;但集成状态有一个必须先处理的阻塞项(rebase 冲突,且草率解冲突会回退 master 已合入的修复)+ 一个中文文档缺口 + 一个未定位的手动 CI 红。

我拉了分支核对了代码、确认了 CI、试 rebase 到当前 master(master 已从 #3462 前进到 94e0fe04a)。逐条:

① 是什么

功能 PR 审查,不是 bug。给 CI 门禁脚本 scripts/gate/plugin-lanes.mjs 加 dsh 的四个协议门车道(openai-completions/responses/anthropic/google)+ 一条 dsh proxy 模式对照车道,并对每个门做 wire 硬断言(每个上行 POST 的路径正则 + 顶层 body 形状必须匹配该协议,防「静默换线」读成绿)。审的是它能不能合。

② 什么原因(要解决的)

dsh 的模型客户端(pi-ai)会说四种协议,原门禁只测 openai-completions 一门;#3475 要补齐其余三门 + proxy 模式,并加 wire 层硬断言。合理,方向与 #3416/#3462 一致。

③ 影响范围与严重程度

  • 产品面:零。 只动 scripts/gate/(CI 测试基建)+ 一个 workflow 描述行 + .gitignore,不碰 src/、kernel/、任何用户可见行为。新车道全 OPT-IN(GATE_AGENTS 默认不变),新 env 旋钮默认全保持旧行为。
  • 就「能不能合」:中-高。 不是代码错,是分支基线过期。

④ 怎么实现的

一个 headless dsh 驱动参数化四种 pi-ai api,只有 cordis 的 api+baseURL 后缀不同,其余共享;openai-completions native 变体生成的 cordis.patch.yml 声称与 #3475 前逐字节相同(作者 parity harness 8/8 SAME——本地无真模型端点,我无法复跑验证,记为作者声明)。WIRE_EXPECT 按门钉死 pathRe+bodyCheck;blocked-lane(env/client 两类)从 tally 剔除对应记录,沿用 opencode2/#3461 规则。设计干净、注释讲 why、错误处理带上下文。

⑤ 是否有回归 —— 有,最关键的一条

本 PR 从 c68a8b42 分叉,早于 #3462 里另外两个已合入 master 的提交。试 rebase 到当前 master,在 plugin-lanes.mjs 和 README.md 出内容冲突(mergeable_state=dirty 的来源)。其中 plugin-lanes.mjs 冲突来自 989bf4e80(已在 master)。逐行比对后,本 PR 相对 master 回退了三个已合入的 gate 修复:

项 master(989bf4e) 本 PR
t2 重试 3 次尝试 + S07 marker 门槛 旧的 2 次循环(head.mjs:374),break 不查 marker
dsh setWindow /g 改写所有 contextWindow(多模型) 退回只改第一个(head.mjs:718)
opencode v1 bin GATE_OC1_BIN 旋钮 硬编码 "opencode"(head.mjs:899)——按 989 说明,CI 镜像里裸 opencode 解析到 v2 会崩

rebase 时若这几处 hunk 保了本 PR 侧,等于把 master 刚修好的又改坏(典型「修 A 坏 B」)。另:p1/mid 标定两边用了不同机制(989=wire body 种子取 max;本 PR=整段日志 idle 行取 max),rebase 需拍板合并策略(建议两者都留)。
高危模式逐项:语义漂移=是(上述三处);fail-fast→吞错=否;阈值/时序漂移=否(窗口逻辑等价);输出格式=仅新增 egress-sample.json(additive);缓存/重试=不涉及。

⑥ 是否破坏缓存

不涉及(纯 CI 脚本,无缓存/游标/去重键)。

⑦ 是否改设计方向 / 文档

不改产品架构。但一个文档缺口:#3462 的 eaa4c5703 已把 README 拆成 EN + ZH companion,而本 PR 的文档更新是针对旧单文件写的——rebase 后只会落到 README.md,不会进 README.zh-CN.md,中文文档将缺新车道说明,违反 zh/en 同步约定,需一并补。

⑧ 是否引入新配置

只加门禁本地 env 旋钮,不进 ~/.config/billion-context/、不动 bili 配置面:GATE_OUTPUT_TOKENS=4096(=旧值)、GATE_DSH_SMALL_WINDOW=0(派生)、GATE_DSH_VERSION=latest。默认全保持旧行为,无需迁移。

CI

手动门禁 ci-gate-plugins.yml 在 head 1d85a1a 上是 failure;该 workflow 仅 workflow_dispatch 触发、非必需合并门禁。job 级日志我这边的 token 权限拿不到(404),无法确认是环境(端点 secret)还是车道问题——上面第⑤条的 GATE_OC1_BIN 回退是可疑贡献项之一,建议 rebase 后对已知好端点重跑确认。

收工判定

暂不可合。 需要:(1) rebase 到当前 master,解冲突时保 master 侧那三处 989 修复 + 套用本 PR 矩阵代码;(2) 新车道文档补进 README.zh-CN.md;(3) 重跑手动门禁 CI 确认绿。代码质量本身达标。

要我直接在 2026-10-17_dsh-gate-protocol-matrix 分支上做 rebase + 修(保 989 三修复、补 zh 文档)再推上去吗?你点头我就动手;或者让作者自己 rebase 也行。

ranxianglei and others added 6 commits October 17, 2026 14:51
…nudgeOn gate (#3482)

Step 2 (B-class sites, #3417 follow-up):
- omp body-pck stamp channel: hostProfileFor(agent).stampsBodyPromptCacheKey
  (site 3); Cowork-transport possibility is registry property
  coworkTransportPossible, per-request truth stays environmental (site 2).
- codex/claude-responses instructions fingerprint: WIRE_CLIENTS registry with
  instructionsFingerprintKeyed; session-id.ts observes, never decides (site 4).
- billing block (#2189) extraction gated by laneDecisions.billingBlockWanted
  (profile-declared OR wire-observed — evidence over defaults); wantsBillingBlock
  now has a real consumer (site 1).
- ledger floor call sites unchanged: dshLedgerFloorTokens carries no lane-name
  check (#1729 guard is deliberately identity-blind, #2193).

Step 2.5 (nudgeOn single point):
- four hand-copied willInjectNudge conjunctions -> nudgeOn() nine-input pure
  function; responses' deliberate differences (compaction-trigger exemption,
  codex-intercept health window) are explicit inputs; openai/google's redundant
  shouldInject conjunct is subsumed by compressSurfaceOn.
- 1024-point boolean cube + verbatim legacy formulas per lane pin equivalence.

Structural guard extended: B-class sites carry no raw lane-name gates; every
WIRE_CLIENTS entry needs a matches().

Zero wire byte changes (pure migration).
The agent-side consumer (src/agent/pi.ts) imported hostProfileFor from
server/lane-decisions, whose preflight import drags acp-kernel and proxy
server modules into dist/agent/pi.js / omp.js client-process bundles
(measured: both doubled, ~1.33 MB -> ~2.79 MB). Move layer-1 HostProfile
registry (table + resolver + ANONYMOUS) into src/host-profiles.ts with
zero imports; lane-decisions re-imports/re-exports it; pi.ts imports the
leaf directly. Structural guard pins host-profiles.ts import-free.

Bundle sizes restored: pi.js 1330878 / omp.js 1330742 (master baseline
1329672 / 1329536; delta now only the ~1 KB leaf table).
…se flakes

Windows runner flake: listen(0) can land in an OS-reserved port range and
emit error (EACCES/EADDRINUSE) instead of listening; events.once(server,
"listening") rejects on error, so a failed listen strands the test promise
("Promise resolution is still pending but the event loop has already
resolved") and cancels siblings. Retry ephemeral-port listens, destroy
keep-alive sockets in teardown (closeAllConnections), and bound every test
with a 60s timeout so any residual hang surfaces with a stack.
lane 统一决策点收尾:四处 B 类名字旁路迁入 + nudgeOn 单点(#3482)
…tions (#3475)

Extend the dsh gate lanes from one protocol to all four pi-ai protocols
(openai-completions / openai-responses / anthropic-messages /
google-generative-ai) plus a dsh proxy-mode lane for same-host
two-activation-path contrast. Same headless driver and corpus flow; only
the cordis provider api + baseURL suffix differ per lane.

- per-door WIRE_EXPECT hard assertion: every recorder POST must match the
  door path regex AND body top-level shape; first request dumped to
  egress-sample.json as round-trip evidence
- blocked semantics: ENV-BLOCKED (door unhealthy: all-rejected or degraded
  mid-flow, opencode2/#3461 rule) and CLIENT-BLOCKED (client config surface
  cannot express the api yet — dsh's cordis schema lists no
  google-generative-ai in 0.2.0-rc.2 / 0.2.1-rc.1); excluded from tally,
  printed at exit
- calibration fixes from real-model runs: GATE_OUTPUT_TOKENS (thinking
  models degenerate when output budget < thinking budget), p1 = max over
  full post-t1 log, post-fold small-window widening for adaptive recipes,
  mid-seed guard, lane-local dsh install (GATE_DSH_VERSION) + lane TMPDIR
- t1 dual marker (S40+S07): verify the read precondition so downstream
  S07 recalls can't fail for fixture reasons

Existing lanes' generated configs are byte-identical to pre-#3475
(parity harness); new lanes are GATE_AGENTS opt-in. Local real-model run:
56/56 passed (dsh-responses:env, dsh-google:client).
@ranxianglei
ranxianglei force-pushed the 2026-10-17_dsh-gate-protocol-matrix branch from 1d85a1a to 4f012b9 Compare October 17, 2026 07:40
@ranxianglei

Copy link
Copy Markdown
Owner Author

🤖 Powered by ework · qwen3.8-27b

(ai: vllm-qwen/qwen3.8-27b)

冲突已解决:PR 分支已 rebase 到当前 master、逐 hunk 解完冲突并推送,GitHub 状态 mergeable: True / clean,head = 4f012b9dd。上一轮 review 提的前两个阻塞项(保 989 三修复、补中文文档)都已处理。

八问

  1. 是什么问题:PR 分支基线过期,与 master 在 scripts/gate/plugin-lanes.mjs 和 scripts/gate/README.md 出内容冲突,GitHub 把 PR 标成 dirty(不可合)。不是代码缺陷,是基线落后。

  2. 什么原因导致的:分支从 c68a8b42 分叉,之后 master 又合入了两个提交——989bf4e80(gate:wire 种子中窗校准 + t2 重试加固 + opencode-v1 bin 旋钮)和 eaa4c5703(README 拆成 EN+ZH 双文件)。前者改了和本 PR 相同的代码段(p1 提取、dsh recipe),后者把本 PR 在改的单文件 README 换成了双语文件 → 两处内容冲突。

  3. 影响范围与严重程度:只影响本 PR 的合并状态,产品面零(纯 CI 门禁脚本+文档)。真正的风险是解冲突方式——若整块保 PR 侧,会回退 master 刚合入的三个 gate 修复(t2 重试加固、dsh setWindow 多模型 /g、GATE_OC1_BIN),等于把刚修好的又改坏。本次解法消除了这个风险。

  4. 怎么修复的:rebase 到 master,按「两侧意图都保留」逐 hunk 解:

    • p1 提取:取并集——留 PR 的整段日志取 max 修法(窗口切换行落在 t1 中段、旧 slice-at-first-match 读到 0)+ master 的 wire 种子(recorder 实际请求体 /4)。两者都是单调 max(),取大者、互不覆盖,注释都保留;
    • dsh recipe:留 PR 的参数化结构(四协议 + proxy 车道共享 helper),把 master 的 setWindow /g(多模型 cordis 全部 contextWindow 一起改)移植进共享 helper 并带原因注释;
    • t2 重试加固(3 次尝试 + S07 marker 门槛)与 GATE_OC1_BIN:git 自动合并成功,逐行核对原样保留;
    • 文档:EN README 用 PR 矩阵章节的英文翻译补齐(dsh 四门表、proxy 激活路径、wire 形状硬断言、ENV/CLIENT-BLOCKED 规则、t1 双标记流程步);同一章节 + 双标记步骤 + 三个新旋钮说明镜像进 README.zh-CN.md,补上上轮指出的 zh/en 同步缺口。
  5. 是否有回归问题:无。master 989bf4e80 引入的四项既有行为(wire 种子、t2 重试加固、setWindow /g、OC1 bin 旋钮)在 rebase 后文件里逐项验证保留;本 PR 自身触碰的既有行为(原有 dsh 车道的生成配置)维持作者声明的字节级 parity。高危模式逐项:语义漂移=否(并集解法两侧都不丢)、fail-fast→吞错=否、阈值/时序漂移=否、输出格式=仅新增 egress-sample.json(additive,dsh 家族车道)。

  6. 是否破坏缓存:不涉及(纯 CI 脚本,无缓存/游标/去重键)。

  7. 是否改了设计方向:不涉及。

  8. 是否引入了新的配置:没有新增。全部是 PR 原本就披露的门禁本地 env 旋钮:GATE_OUTPUT_TOKENS=4096(=旧值)、GATE_DSH_SMALL_WINDOW=0(派生)、GATE_DSH_VERSION=latest;默认全保持旧行为,不进 bili 配置面。rebase 本身未引入任何新的行为变更。

验证:node --check 通过;merge-tree 对当前 master 零冲突;diff 只覆盖本 PR 自己的 5 个文件(workflow 描述行、.gitignore、两个 README、plugin-lanes.mjs);GitHub 已回 clean。

剩余一步:手动门禁 ci-gate-plugins.yml(仅 workflow_dispatch)需要重新触发跑一遍确认绿——这是上轮「暂不可合」三条里的第三条。说一声我就帮你 dispatch,或你自己点也行。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant