Commit Graph
210 Commits
Author SHA1 Message Date
ranxianglei 0f75af004f [PR] fix(agent): price the client-local doom gate by prompt mass, not raw body bytes (#7106)
Client local doom gate: price by prompt mass instead of raw bytes, fixing false rejects from the 8MiB dsh_session_log transport field; two-tier contract kept, 8 tests.

Co-authored-by: ZzXxYy1234 <104406571+ZzXxYy1234@users.noreply.github.com>
Source-PR: #7119
(cherry picked from commit 18939eba8855e6bb9fd163b4b12c04280a3fa13c)
(cherry picked from commit 4c50854e5b9116846832a7cd928a9130e2273c37)
2026-11-24 23:31:39 +08:00
ranxianglei 21adc8eab4 revert: egressPlane default stays 0 (owner ruling) — the PR is docs-only now
Owner: '我们没有说要改成100 现在还是需要0'. The default-100 GA flip was
proposed in this series (per the #5469 precedent) and declined.

- src/rollout.ts: reverted to percent 0 (+ original comment).
- tests: the 'unset means off' semantics are restored; three tests that now
  force the off direction use env "0" (wins over both the default and any
  local config file), incl. a hermeticity fix in issue7574-egress-seam
  (delete-env only meant 'off' on machines whose config does not force the
  plane on).
- egress-record direction test rewritten back to 'default 0 — unset env/
  config resolves OFF; explicit 1 opens the gate'.
- docs (en/zh/ja + KDD #24 + CHANGELOG + config docs): every 'GA/default
  100' statement rewritten to 'stays 0, opt-in; a default-100 flip was
  proposed and declined'; the deprecations register's GA gates now read
  'the default-100 flip, pending owner decision'; the flip is listed as the
  first tracked follow-up.
2026-11-24 22:24:50 +08:00
ranxianglei 4f45d7afba docs+rollout: egressPlane GA (default 100) + egress-plane/deprecations docs, storage page refresh, KDD #24
- rollout: egressPlane percent 0 -> 100 (GA; opt-out kept per #5469 precedent)
- tests: 5 sites relying on 'unset = off' now set '0' explicitly; egress-record direction test rewritten to 'GA default ON, explicit 0 closes'
- docs/egress-plane.{md,zh-CN.md}: one-stop egress doc (lineage #7439->#7581->#7617, dual clocks, identity consolidation, flag dependency, on/off resolution order, runbook, timeline)
- docs/deprecations.{md,zh-CN.md}: retirement register (l1 placeholder, conversations, D-lane triggers, msgid switch removals, DROP batch)
- docs/architecture/storage{,.zh-CN}.md refresh; AGENTS.md + design-decisions.md KDD #24; docs index x2
- CHANGELOG + generated config docs
2026-11-24 22:24:50 +08:00
ranxianglei ca5ab2bcaa docs(egress): correct tracker ref #7579→#7577; document (a)/(c) behavior
The original slice referenced #7579 in code comments and docs, but the
block-flow design discussion is #7577 (the D-rulings live there); #7579
is an unrelated open issue. Corrected every reference.

Also updated the egress-block-flow doc (EN + zh) to match what (a) and
(c) actually do:
- fork-to-now copies all four tables directly (SQL), a true point fork
  replays the flow rows to rebuild the state replicas;
- POST /__bili/replicas takes the point-fork path for an egress-on parent
  (201 {ok, pointFork, ...}) instead of returning 400;
- on load, tsStamps is re-derived from the egress view for egress-on
  sessions whose trimmed column has no value (persisted value always wins).
2026-11-24 13:16:48 +08:00
ci-check d867e75463 feat: egress block flow/state — block canonical history + checkpoint retirement (#7579)
Adds two new tables (egress_block_flow, egress_block_state) that make the
block set a first-class op-log citizen alongside the message view
(egress_flow/egress_state). Retires checkpoints (fork_base/replica/auto)
for egress-on sessions in favor of point-fork (4-table copy). Trims the
kstate column for egress-on sessions (tsStamps/tokenSnapshot/lastPassIds
derivable from flow replay).

- DDL: egress_block_flow (append-only I/U/B rows) + egress_block_state
  (read replica, latest snapshot per block). Shared op_seq clock with
  egress_flow.
- ts: EgressViewRow / InsertOp / B-entries carry first-observed wall
  clock (epoch ms), stamped at recordEgressTurn.
- Block recorder: per-turn egress-on gate at the ingest seam; diff prev
  block set → I/U ops + block_state upsert + kstate sidecar.
- Replay + point fork: egressBlockReplay / egressPointFork (4-table copy
  WHERE op_seq <= wm; state replicas rebuilt by flow replay).
- Checkpoint stop: maybeCutForkBaseAsync / createReplica skip egress-on;
  admin /__bili/replicas returns 400.
- kstate trim: tsStamps/tokenSnapshot/lastPassIds excluded from
  sessions.kstate_json for egress-on sessions (legacy byte-identical).
- Tests: replay determinism, point fork, kstate sidecar, B-row
  compaction, reap semantics, corrupt paths.
- Docs: bilingual egress-block-flow.md + index entries + architecture
  file map.

Closes #7579
2026-11-24 13:16:48 +08:00
ci-check a5ffad3652 refactor(web): title subagent sessions from the task after the dispatch prefix
The dispatch prompt is ONE user message: the machine prefix + the parent's
task (anomalyco/opencode packages/core/src/tool/plugin/subagent.ts and
config/plugin/command.ts). Skipping the whole message left most one-shot
subagent sessions untitled until compression created a block topic. Strip
the prefix instead — the task becomes the title immediately.

- session-title.ts: add subagentPromptTask() (strip), hoist the CI
  constant, trailing newline
- server.ts deriveTitle: strip the prefix, title from the task; a
  prefix-only prompt yields no title (derivation retries on later requests)
- prepare-{anthropic,openai,google,responses}.ts: extend the re-derive
  gate with isSubagentPrompt so old boilerplate-titled sessions self-heal
  at the data level (same precedent as #2286)
- reference/architecture.md: file-map entry for src/session-title.ts
  (fixes the architecture-docs CI check)
- tests: strip semantics in title-derive.test.ts (task title, prefix-only,
  case-insensitive, mentions-subagents negative); web-sessions.test.ts
  fallback negatives (normal title kept, hostTitle wins, no-block keeps
  the stored title)
2026-11-23 22:23:39 +08:00
ranxianglei c0fcfa7ee8 fix(#7574): a well-formed short id list on an empty ledger no longer fails the turn
Since msgid pinning is on by default, a client whose ledger was lost
(database restored or rebuilt, session deleted while the client kept the
conversation) sent its usual tail form and got a 400 on every affected
session; three of them in ten minutes latched the session to the unpinned
path for good.

A tail whose entries are well-formed is now the signal it really is: the
turn runs without the pin (content-derived ids) and the response asks for
the full list, which rebuilds the ledger next turn. A tail with broken
entries (empty, too long, reserved prefix, control characters, duplicates)
is still an identity fault with the old 400 path.

This reverses the empty-ledger exception of 2026-11-18 (AGENTS.md KDD #22,
reference/design-decisions.md); both texts are updated.
2026-11-23 19:32:03 +08:00
ranxianglei 4ef435d2b4 chore(#7574): drop four draft files committed at the repo root, refresh stale rollout text
- .pr-body.md, .ci6785-final.txt, .comment-7439.md, .reply-7439.md were
  working notes that slipped into the hand-resolved merge of #6785.
- "KDD #21/#21" -> "KDD #21/#22" in four docs.
- pluginFullResendWatermark is on by default since 2026-11-22 (owner
  ruling); AGENTS.md, design-decisions.md KDD #15, the PR #6785 doc table
  and the web config label still said 5% / experimental.
2026-11-23 17:20:33 +08:00
ranxianglei a24c7112dc Merge origin/master (#6785 egress plane era): handle.ts body-stamp takes the all-four-wires version 2026-11-23 15:28:32 +08:00
ranxianglei 5202c492c5 Merge origin/master: retire the #5844 sessions reattach with the fork ladder it rescued
master's #5844 (sessions reattach) exists to repair legacy persona forks
(the warning log that names the command is gone with the ladder, and tagHash
recording is gone, so the command could never have worked under GA): drop
the CLI subcommand, runReattach, and its test. order-persist.ts stays
deleted.
2026-11-23 13:13:33 +08:00
ranxianglei a4fc29c6f7 Merge origin/master into 2026-11-15_msgid-snapshot-unified
Conflicts resolved:
- src/agent/fork-adopt.ts + src/agent/opencode-v2.ts: union of the two
  fork-branch-point tracks — master's #5509 resolveForkBranchPoint
  (role+text-first, host-declared boundary) stays the base decision;
  this branch's #6262 host-msgid identity track extends it afterwards
  and never beyond a host-capped boundary. Call sites feed BOTH
  msgIds and boundary.
- AGENTS.md + reference/design-decisions.md: master's KDD #20
  (#7537 no estimate-based size refusal, already public on master)
  keeps its number; this branch's three new KDD entries renumber
  #20->#21 (id 存储去重), #21->#22 (pin 增量化), #22->#23 (egress op
  log 正史) — all KDD/des…ions.md references repo-wide
  updated in the same commit.

Verification: tsc clean; fork battery (5509/6262/fork-adopt/
opencode) green; egress battery 129/129; full-suite verdict = CI on
the pushed head.
2026-11-23 11:48:47 +08:00
ranxianglei 891f52994b Retire the legacy |sub: fork ladder end-to-end (trust-stamped-id GA, #7525)
With the client-stamped session id trusted on every lane (percent:100 since
#7525 GA), the content-forecasting fork machinery is write-only: every
reachable session key is either the stamped id verbatim or the #5095
declared lane-token key. Owner ruling 2026-11-23: remove it completely
instead of leaving a debug escape hatch.

Removed:
- src/session-resolve.ts rewritten to the GA shape: resolveSessionOrder(
  rawId, personaTag?, laneToken?) returns the verbatim id (action "raw")
  or the #5095 lane-token fork (action "derived-persona"). Gone: the
  skeleton map + record(), the |sub:aux / |sub:<fp> / |sub:task:<skel8>
  fork rungs, #5719 msgid rescue (tryMsgIdRescue / readStoredMsgIds /
  laneDiscriminator), model-drift absorption, persona re-anchor.
- src/order-persist.ts (the 630KB kv_store namespace "session-order"
  writer) and src/persona-anchor.ts (header-marked retired, kept only as
  a test pin) deleted; boot hydrate + shutdown/exit flush wiring removed
  from src/cli.ts, src/server.ts, src/restart.ts.
- src/rollout.ts: trustStampedId flag entry deleted; the
  BILI_ROLLOUT_TRUST_STAMPED_ID=0 env escape hatch no longer exists.
- src/session-id.ts: anthropicFirstUserFrag (only consumer was the D1-B
  discriminator rung) deleted.
- src/server/handle.ts: the six persona call sites drop their dead
  arguments (history / model / msgIds / storedMsgIdsOf); the observer
  now logs derived- (lane-token) resolutions only — the reanchor/claim
  noise of the retired rungs is gone.

Config-surface removals (declared per repo doctrine):
- rollout.features.trustStampedId (config key) — GA default moved into
  the code; setting it now has no effect.
- env BILI_ROLLOUT_TRUST_STAMPED_ID — read by nothing anymore.
- kv_store row namespace "session-order" key "v1" becomes dead data
  (nothing writes or reads it; left in place — delete manually if
  desired); stateDir()/session-order.json is a stale fallback file that
  nothing produces any more.
- telemetry: the [session-resolve][msgid-rescue] warn line (#5719 /
  #5865-P2) dies with its rung.

Kept (still load-bearing):
- #5095 declared lane-token fork (client-declared, survives GA) —
  tests/trust-stamped-id.test.ts reworked as the GA characterization,
  tests/issue5095-subagent-lane-token.test.ts un-pinned.
- #970 claude agent-header split, aux sidecar lanes, side-lane
  invariants — tests/side-lane-invariants.test.ts un-pinned, its
  (D)/(E)/(E2)/(L) fork assertions flipped to the GA verbatim contract.
- #2601 livePersonaDescendant birth-order follow in src/plugin.ts stays
  (it also serves token-minted lanes); its construction scenario was a
  legacy content-fork, so the two pin suites
  (persona-fork-active-parent-guard, issue2948-aux-lane-lineage-guard)
  are deleted and that path is now covered only indirectly.
- tests/session-continuity-proof.test.ts: scenario A control flipped
  (uncorroborated system drift now rides the raw key, no fork);
  scenario B (host-driven fork API + copy-on-fork) untouched.

16 legacy-pinning test suites deleted, 9 test files de-pinned,
scripts/ci-shard-weights.json re-trimmed (9 removed entries),
reference/architecture.md updated.
2026-11-23 11:36:35 +08:00
ranxianglei 46466ae047 chore: clear retired snapBase plane leftovers (7439 audit before merge)
The #5874 v2 snapshot-base plane (storage.snapBase) was retired before merge
(bc51c9445) — egress op log (rollout.features.egressPlane) is its successor.
Sweep the remnants that would otherwise enter master:

- config.ts: the orphaned 17-line snapBase doc comment (the field itself was
  already removed) is replaced by a one-line retirement note.
- release-gate-local.mjs: --snapbase-full wrote the dead storage.snapBase key
  (silent no-op — the plane was unreachable, same bug 52f81bfb fixed in
  scripts/gate); it now writes rollout.features.egressPlane=true.
- scripts/gate config.example.json + README en/zh: the knob docs still said
  'storage.snapBase' and per-protocol cohorts (the plane has neither).
- docs/architecture/storage{,.zh-CN,.ja}.md: the v2 substrate enumeration
  still listed the deleted fold_journal/egress_snapshot tables.
- AGENTS.md KDD #20 + design-decisions.md #20: both describe fold_journal /
  egress_snapshot as live interval-ref tables; they were deleted in bc51c9445
  (only l1_world survives) — a note marks the pre-retirement description as
  history. The entries are new in this PR, so the fix ships with them.
- schema.ts: SNAPBASE_DDL_V12 -> L1WORLD_DDL_V12 (cosmetic; the DDL creates
  the live l1_world table, the name cited the retired plane).
2026-11-23 10:24:18 +08:00
ranxianglei 6607dfc940 Merge branch 'master' into fix/preflight-413-passthrough 2026-11-23 09:23:44 +08:00
ranxianglei ae11da8789 Merge branch 'master' into 2026-11-15_msgid-snapshot-unified 2026-11-23 00:07:26 +08:00
ranxianglei 7b3a17193b fix: stop refusing oversized requests on local size estimates — forward, and let the upstream's own verdict be authoritative (#7537)
Owner ruling 2026-11-22 (issue #7537, KDD #19/#20): every LOCAL estimate-
based 413 refusal is a product of bili's local guess multiplied by a window
value that is itself often wrong (fallback windows #7205). Their product
silently killed requests that would have succeeded (the #7167/#7382/#2490/
#2847/#2847/#736/#737/#4079 family).

- server.ts: the four local size-413 sites (probe doom gate, #1839 measured
  gate, post-fold measured/doom-bytes gates, deterministic-exhaustion
  mapping) now FORWARD with the local measurement logged as evidence.
  Relay-side refusals keep their status: summary relay down -> 502, relay
  429 -> 503. The BILI_MAX_MESSAGES count gate and the 5GiB byte cap are
  exact resource guards and stay.
- relay.ts: the egress window fuse's two size gates log a profile and
  forward; a NEW upstream size-verdict annotation (413 / size-keyword 400)
  logs bili's own measurement, marks the response x-bili-retryable: false
  and merges a bili_evidence block into JSON error bodies so status-driven
  hosts do not retry-loop an unchanged body.
- server.ts: NEW evidence-backed loop guard — an outbound body that already
  drew an upstream size verdict (SHA-1 scoped, 10-min TTL) is refused
  locally as a byte-identical resend (#496 family); changed bodies and the
  identity fast path re-forward freely.
- The window-shrink note now rides the forward warns (the 413 fail-fast it
  decorated is gone); the duplication profile moved onto the over-window
  forward.
- AGENTS.md KDD #19 + reference/design-decisions.md #20 record the ruling.
- Tests: NEW tests/issue7537-preflight-passthrough.test.ts (3); re-pinned
  issue1841/2490/2847/3645/4079/4185/preflight-fail-fast to passthrough
  semantics; tests/issue3846-local-refusal-evidence.test.ts deleted (the
  local refusal it pinned no longer exists — the loop guard replaces it).

Supersedes PR #7507 (whose two new gates no longer need to exist under
this ruling). Refs #7537 #7507 #7167 #7382 #2490 #2847 #736 #737 #4079
#4543 #1841 #3645 #496 #3846 #3461 #5000
2026-11-22 22:37:54 +08:00
ranxianglei c85e4a3043 docs: sync the PR #6785 surface to the round-2 state (KDD #22)
The review-grade walkthrough (en/zh) still described the pre-round-2
architecture — egress_snapshot tables, messages as the canonical id
truth, no lazy projection, no perf gate. Add the round-2 chapter
(ruling 7439-2/5: op-log canonical numbering, window re-anchor,
sole-canonical + lazy projection, pin-from-flow, envelope freeze,
hard-fail, measured 10w matrix, resident bench) and mark the
superseded sections inline instead of deleting them.

Supporting sync:
- storage.md (en/zh): egress tables + canonical-authority semantics
- msgid-infrastructure.md (en/zh): KDD #22 carve-out on the
  'messages.msg_id is the single id truth' statement
- configuration.md (en/zh): egressPlane knob gains the round-2
  lazy-projection semantics
- index.md (en/zh): pr-6785 doc row
- reference/testing.md: ACP_TEST_EG_BENCH bench lane

No code changes. Docs-only.
2026-11-22 20:39:30 +08:00
ci-check d3ef8d294e fix(ci): add zed-wire.ts to architecture map + drop unused export
- reference/architecture.md: list src/zed-wire.ts in the file tree (the
  architecture-docs guard requires every tracked src/ file to appear).
- src/zed-wire.ts: UnwrappedZedEnvelope is internal-only (used only as the
  return type of unwrapZedEnvelope, imported nowhere) — drop the export so
  the unused-exports guard passes.

[ework:ci-held]
2026-11-22 17:18:19 +08:00
ranxianglei c23ad16dc5 docs: KDD #22 — egress-on op-log authority + lazy messages projection + window re-anchor (ruling 7439)
- reference/design-decisions.md: full KDD #22 entry (owner ruling 2026-11-22,
  discussion #7439 comment-19805485): pin channel single read entry
  snapPinLiveIds (egress_state for egress-on, messages otherwise), egress-on
  stops per-turn unified ingest (lazy projection, one-time O(n) rebuild on
  rollback/restore/web read), in-txn window re-anchor delta superseding the
  pre-resolved lookup (fb88bc2af), acceptance p50 < 1s @ 10w rows.
- AGENTS.md: one-line #22 entry under the KDD list.

docs-only; no code change.
2026-11-22 13:00:18 +08:00
ework-agent 0fc364a1f3 Merge remote-tracking branch 'origin/master' into 2026-11-15_msgid-snapshot-unified 2026-11-22 10:57:01 +08:00
ework-agent a1c556ca4e docs: KDD #7 — 'executes compress locally' misreads as client-side compute; state wire-ownership explicitly
The phrase 'the ACP-native agent OWNS compression — it executes compress
locally' was read literally as client-side compression execution during the
full-lane compression-path investigation (discussion #7487), producing the
wrong conclusion 'the kernel ran inside the dsh host' that had to be
retracted after source-level verification. The compute ALWAYS runs
server-side under the session lock (plugin-protocol.md Why-table); the
sentence is a CARRIER-semantics statement (call+result live in the agent's
re-sent history). Reword both mirrors (AGENTS.md KDD #7 + Tier B ledger)
and name the trap explicitly.

Closes #7502
2026-11-22 09:19:49 +08:00
ework-agent 87e95b59e4 Merge remote-tracking branch 'origin/master' into 2026-11-15_msgid-snapshot-unified
# Conflicts:
#	src/persist.ts
#	src/storage/store.ts
2026-11-21 21:55:20 +08:00
ranxianglei 410d9fe615 Merge pull request #7423 from ranxianglei/2026-11-21_opencode-fork-lineage
[PR] fix: resolve opencode fork parent from its local DB to stop resume crosstalk (#7421)
2026-11-21 21:06:30 +08:00
ework-agent 1f4bd580be docs: seed the sessions/plugin/snapshot config surface + egress-lane-io file map
The PR's snapshot-plane commits added config fields (sessions.*, plugin.snapshotCapBytes, snapshot.shadow) and src/server/egress-lane-io.ts without doc seeds, so three CI gates went red on head 02fc8f4c2:

- config-surface-guard: 11 leaf fields lacked website/config-reference seed entries
- docs-coverage: 11 env vars + 2 top-level keys (sessions, plugin) undocumented (BILI_SESSION_CONTENT_STORE_PIN is env-only)
- architecture-docs: reference/architecture.md missing src/server/egress-lane-io.ts

Added the seeds (process.yaml: sessions block + 9 leaves; server.yaml: plugin.snapshotCapBytes + snapshot.shadow; env-only.yaml: BILI_SESSION_CONTENT_STORE_PIN), the file-map line, and the regenerated docs/configuration.{md,zh-CN.md,ja.md} + website artifacts.

Verified locally: all three gates green, generate idempotent, typecheck clean.

PR #6785 CI fix.
2026-11-21 17:20:04 +08:00
ranxianglei 02fc8f4c2c refactor(egress): one switch, one path — collapse egressOpLog/egressServeLog into egressPlane (#7439 ruling)
The egress plane gets a SINGLE rollout key: egressPlane (default 0).
ON = the complete new path in every lane — sparse-op recording,
serve-from-log (byte-identical swap), and server authority for pinned
plugin lanes (rulings 7439-3/5). OFF = legacy chain, zero rows,
byte-identical to pre-feature. Both predecessor keys never shipped
(default 0, born in rollback state) — no migration.

Owner ruling 2026-11-21: '删掉以前的开关 只留下一个开关'.

Verification: typecheck 0; 13-file storage/egress/fastpath battery
112/112; e2e codex 4-phase pass (rollout off = legacy path).
2026-11-21 16:12:38 +08:00
ework-agent d3ab5abb76 merge: resolve conflicts with master (#7381 pf-tail-ids-cap-and-stamp-decouple)
Conflicts resolved:
1. src/server/prepare-openai.ts: union of fastpath imports (PR's
   DeltaReanchorError/PF_TAIL_IDS_HEADER/evaluateDeltaResend/parseTailIdsForPin
   + master's stampOnlyWatermarkTurn).
2. tests/fastpath.test.ts: union of fastpath imports (PR's
   evaluateDeltaResend/PF_DELTA_HEADER + master's stampOnlyWatermarkTurn).
3. src/agent/pf-channel.ts: kept PR's TAIL_MAX_BYTES byte-budget (supersedes
   master's MAX_TAIL_IDS count-cap; the byte check is stricter and
   tailPayloadFor is the single source of truth for both header emit AND
   full-form suppression).
4. src/server/fastpath.ts: kept BOTH evaluateDeltaResend (PR #6785 delta arm)
   AND stampOnlyWatermarkTurn (master #7367 stamp-only turn).
5. src/storage/shadow.ts: kept master's fileJsonWriter parameter (new in
   master, not in PR branch).
6. tests/pf-channel.test.ts: updated #7367 tail-cap test to match PR branch's
   byte-budget behavior (full slice under 8 KB, not capped to 160).
2026-11-21 15:28:57 +08:00
ci-check 3329c2655f docs: list src/storage-backup-repair.ts in the reference architecture file map (#7156) 2026-11-21 12:32:35 +08:00
ci-check 83e28086c1 docs: register src/opencode-fork-lineage.ts in the architecture file map
The architecture-docs CI gate requires every tracked src/ file in
reference/architecture.md; the new module was missing, failing the lane.
2026-11-21 09:14:29 +08:00
ranxianglei a936b3f0ad feat(storage): egress serve-from-log reconstruction + shadow byte-identity comparison (discussions/7398 seg 4a)
The outbound element array can now be REBUILT from the op-log view alone:
view rows carry role + a unified-content-CAS reference (the message's final
core JSON, hashed at record time — no new content bytes anywhere), and
rebuildOutboundFromLog runs the exact legacy chain (systemToUser ->
coreToOpenai -> hardenOpenaiAssistantContent) over the CAS bodies.

- src/storage/egress-serve.ts (new): rebuild + the degrade ladder — missing
  CAS body / casRef-less legacy rows / tool rows / bad JSON -> null, the
  caller keeps the legacy bytes. v1 scope pinned: text + acp_summary rows.
- src/storage/egress-state.ts: role?/casRef? ride the I and U ops, the B
  base and both replay paths (JSON payload fields only — no schema change;
  absent on pre-seg-4 rows, which serve-from-log skips).
- src/storage/egress-record.ts: rows recorded with the CAS seam
  (store.egressPutContent); system row included with its own casRef.
- src/storage/store.ts: egressPutContent/egressGetContent public seam over
  the existing private content CAS (dedup by sha256, refcount).
- src/server/prepare-openai.ts: captures the legacy core elements + the
  recorded source; behind egressServeLog (default 0) it rebuilds from the
  log and logs IDENTICAL|DIVERGENT vs the legacy bytes. NO swap: the
  pipeline always sends the legacy path until the shadow gate proves it.
- rollout: egressServeLog {percent: 0} (env BILI_ROLLOUT_EGRESS_SERVE_LOG,
  requires egressOpLog on); config docs regenerated (348 entries, stable).
- tests/egress-serve.test.ts (new, 6 tests): byte identity vs the legacy
  chain (plain + summary re-voicing + table-replayed + post-compaction)
  and the three degrade directions (#3617).
- Battery: egress-state/record/serve 24/24, perf-suite set 53/53,
  typecheck + build clean.
2026-11-20 19:11:15 +08:00
ranxianglei 5b3b55cb61 feat(storage): egress op-log recording seam — shadow-record the outbound view as sparse ops (discussions/7398 seg 3)
The four upper-layer shapes now land in the op log behind rollout key
egressOpLog (default 0 = zero impact):

  1. new message            -> exactly one +I (tail append)
  2. nudge injection        -> structurally absent: the recording seam sits
                               BEFORE the nudge/scratch append, so the
                               ephemeral rows never reach the tables
  3. compress fold          -> one -D over the folded span + one +I for the
                               summary row; any -D batch triggers compaction
                               (replay into a base row, state table bounded)
  4. content edit           -> exactly one +U (msgid/ref stable, content-only)

recordEgressTurn (new src/storage/egress-record.ts) builds deterministic
view rows (system row first; msgid/ref/tokens/type/contentHash), diffs
against the previous turn's view, appends the sparse ops, and compacts on
folds. Wired in prepare-openai between recordNudgeInject and the single
return: feature-gated, try/catch with per-session disable on any error
(shadow lane — the pipeline never throws from it).

SessionStore.egressOpLogStore() -> UnifiedShadow.egressOpLogSync() exposes
the sqlite UnifiedStore (null on legacy mode / network backends -> the
turn is skipped exactly like every other sqlite-lane fast path).

Tests: tests/egress-record.test.ts 6/6 (build determinism, tail append =
one op, fold = -D + +I + compaction, edit = one +U, identical view = zero
ops, rollout-off default both directions). Battery 71/71.
Full battery + CI green.
2026-11-20 18:56:33 +08:00
ranxianglei b31e7e17e6 feat(storage): egress op-log outbound view — dual-table state+flow with replay, compaction, any-seq rollback (discussions/7398)
New egress_state + egress_flow tables (both PK (session_id, log_seq),
msgid secondary index): the outbound view becomes an op log instead of a
rebuilt blob. Row types: B=base, I=insert (after-anchor or tail, msgid +
render triple ref/tokens/type + content_hash), D=delete (inclusive
msgid endpoints), U=content update (msgid-stable).

Replay is deterministic: read the state table in log_seq order, apply
per row type; any anchor/endpoint/id violation throws
EgressStateCorruptError (whole-session legacy degrade, never fuzzy).
Compaction = one txn: write the replayed base as a B row, physically
delete the state rows below it (cancelled intermediates vanish); the
append-only flow table keeps every op, so any historical log_seq stays
reconstructible via egressStateViewAt.

No pipeline wiring yet — the tables are written/read through
UnifiedStore thin methods only; recording ops at the four upper-layer
sites (new message / nudge-ephemeral / compress fold / content update)
and serving from the log come next, behind a rollout key.
2026-11-20 18:38:13 +08:00
ranxianglei 950eb8d9b1 fix: 超长会话截断尾清单也能 pin——增量接受规则改为「尾部对齐 + 重叠段逐行对账」
ed71f127 之后 >2048 会话的 body 清单永远是被截断的尾段,其头在会话中部、
永远 ≠ 账本前沿 ⇒ 旧「锚点+宽度」规则每轮失配 ⇒ 服务端发「full」⇒ 客户端
永远只能再发同一份截断清单 ⇒ pin 死到会话结束(载体一旦超 8KB/戳陈旧
断一次即触发,2xx 救不回来——客户端已经没有全量可发了)。

新规则(只改服务端 tryIncrementalPin,客户端零改动):清单声明覆盖连续
尾段 [T-L, T-1];与账本的重叠段 [T-L, C-1] 逐行相等才接受,任一行漂移
降级发「full」(D1:永不 400);重叠之后的新增核逐槽筛查。稳态形态
(锚点+新增,L=N+1)= 单行重叠特例 = 原锚点检查,行为字节级不变;
2048 截断清单的重叠 ≈2047 行,证明更强。修完「退回全量」退化为
「发你有的」,任何结尾正确的形态都能 pin,死循环结构上消失。
空账本例外(B1:短数组打空账本 = 采集故障,R3 路径)不动。

测试:I2 用例 (a) 语义翻转(历史整段尾清单现在是合法 pin)重写为
重叠段漂移用例;新增 I7(C=3000 账本、2048 保留窗截断清单 pin 成功 +
一行漂移降级)、I8(稳态单行重叠特例双向)。定向 10 文件 171/171 绿,
tsc/build/architecture-docs 全绿。

KDD #21(AGENTS.md + design-decisions.md)接受规则文案同步。
2026-11-19 20:39:44 +08:00
ranxianglei c0df208e90 feat(msgid): 增量 pin 全客户端覆盖(#7064 §9 phase 2,owner 裁定 2026-11-18)
- 两形态上移申报通道:客户端每轮照旧全量算,但短数组(≤账本 frontier 锚定的
  尾部窗口)就是合法尾式——openai 走 pf-tail-ids、opencode V1/V2 走 x-bili-msg-ids
  短列表、responses/anthropic 走 body biliMsgIds 短列表,服务端按长度区分全量/尾部
- 空账本上的短数组 = 采集故障:沿用旧 R3 路径(400+熔断/conv-bound 降 content),
  B1/D2 行为不变;非空账本上的长度不符 = 漂移类,降级发全量、永不 400
- 尾部新 id 逐槽过校验(? 跳过,空/超长/保留前缀/控制字符/与账本前缀重复拒绝)
- x-bili-msgid-mode 信号头扩展到 responses/anthropic 车道
- opencode V1(anthropic header)与 V2(responses header)接 pfIdTailForm 尾式:
  稳态只发锚点+新增,压缩/分叉后的重写轮发全量重锚
- omp/claude/codex/google 无需接线(无全量申报或本就是增量车道),KDD #21 记录
- 默认开(pluginMsgIdIncremental 0→100,owner:新存储结构的核心部分);
  回滚 env BILI_ROLLOUT_PLUGIN_MSG_ID_INCREMENTAL=0
- KDD #21 更新 + AGENTS.md + #7064 本地 §9;新增 I4-I7/pfIdTailForm 测试
2026-11-19 00:44:52 +08:00
ranxianglei 2837c38282 (PR#6785 review) docs: drop the ghost checksums.ts entry that ced9644f0 orphaned — the architecture-docs CI guard greps reference/architecture.md for tracked src files and fails on the dead module 2026-11-19 00:11:39 +08:00
ranxianglei 8575e4e2fe Merge branch 'master' into 2026-11-15_msgid-snapshot-unified 2026-11-18 23:23:26 +08:00
ranxianglei 2cbbc1d350 feat(msgid): pin 通道增量化——稳态只发尾部、快照轮才发全量(#7064 §8,owner 裁定 2026-11-18)
背景:msgid pin 通道每轮发全量清单,opencode 的 16KiB header 预算在千条以上
长会话里让 pin 永久失效(有用户实测「发的是全量、最后超长度发不了」),pi/dsh
的 body 数组同样无界增长。裁定:不管哪个客户端都不发全量、只发增量。

- 稳态:客户端不再发 biliMsgIds body 字段 / x-bili-msg-ids header,复用既有
  有界通道 x-bili-pf-tail-ids(锚点+新增 cores,? 占位)携带增量(零新增
  发送代码,同一采集缝/chokepoint);服务端 tryIncrementalPin 按「锚点=账本
  尾部 live 行 + 宽度 C+N=视图长度」钉住增量,前缀 cores 无条件从账本 live
  行重盖(ingest 是 INSERT OR IGNORE,ref 空间稳定的前提)
- 全量形式不删且优先:启动(账本空)/压缩/fork/截断后的重锚轮照发全量;
  任何一条失配=降级为 full(不 pin、不 400、不 latch)——两轮收敛
- 信号头 x-bili-msgid-mode: incremental|full 与 x-bili-pf-seq 同一响应发出;
  4xx/宿主缩水/'full' 信号立即清 mode 回全量(回滚自愈)
- 客户端:pf-channel 单一状态机 + pfSuppressFullMsgIds 单一抑制点,pi/dsh
  各一行接线;opencode 留 phase 2(/responses 计头 run 的 off-by-one)
- 灰度:rollout flag pluginMsgIdIncremental 默认 0,off = 字节级同改前
- KDD #21;新测试 I1/I2/I3(增量 pin/失配降级矩阵/全量优先/? 槽位)+
  pf-channel 信号学习/抑制/缩水清除/4xx 清除
2026-11-18 19:24:13 +08:00
ranxianglei 001e16f12a msgid 生命周期梳理:存储瘦身(D1/D2/D3)+ fork 车道回归修复(discussion #7064)
一句话说清:把"每轮都存一份消息 id 清单"改成"只存头尾一小段",并修掉
fork 后子会话落到父会话代理车道上的回归。

存储瘦身(方案见 GitHub discussion #7064,owner 裁定 2026-11-17):
- l1_world 不再存全量 id 和校验和:改成 tail-512/head-32 id 窗口 + count +
  max_pos,只是记账游标,永不做身份判分叉(D1:尾锚比对不匹配时最强动作
  是 reanchor,绝不 400)
- D2:会话一旦有宿主身份(conversations 里有非 proxy 命名空间的声明),
  跳过 id 判定直接走 anchor,R3 熔断只在无宿主身份的裸会话上保留
- D3:tail 锚常活——hit turns(水印快路径命中轮)也刷新窗口,不再只在全量
  重发轮才动
- fold_journal 去掉 covered_ids:改 [start_seq, end_seq] 区间 + input_hash
  (对折叠时原始行逐字节取指纹,供服务摘要前按区间重推、防篡改)
- egress_snapshot 去掉 ids_json:改水印边界聚合(对 seq ≤ watermark 的存活行
  按 seq/msg_id/content_hash 取 sha256)

fork 车道回归修复:
- stage-0 游标前进(尾锚 reanchor/扩展)后 bump revisionEpoch,让快照刷新
  的 epoch 证明保持一致;否则 fork 出的子会话会落到父会话的代理车道
  (plugin-fork ×6 / plugin-fork-contract ×6 回归即此)
- identity.ts 窗口比对修正:prefix-contain 取代 tail-overlap(纯扩展场景
  原来永远判 0 重叠 → 误 reanchor),shrink 改真后缀判定,extend/append
  的 head 窗口跟随新消息走

配套:
- KDD #20(reference/design-decisions.md + AGENTS.md)
- 新增测试:D2 convBound→anchor、D3 hit-turn 刷新(issue5874-2x2-p3);
  egress/fold-journal 测试按新 API 重写
- tsc --noEmit 干净;定向 116/116 全绿
2026-11-18 10:40:12 +08:00
shreynshah 0b2ce30272 fix(pi): negotiate full Anthropic requests for bili
Fixes #6796. Preserve bili compression by disabling incompatible native thread deltas through Pi session-local model compatibility.

(cherry picked from commit 7d790d9970)
2026-11-18 10:16:19 +08:00
ranxianglei 5ea371460d Merge branch 'master' into 2026-11-15_msgid-snapshot-unified 2026-11-17 16:26:23 +08:00
ranxianglei 80daffc2f5 fix(storage): keep the reply stash out of the messages table (direction C1, #6947)
The first cut of this fix persisted the turn-final reply as non-tail rows
in the messages table. That breaks the table's contract: its seq space is
the ref-ledger substrate — on the first fold, persist.maybeRestampToLedger
aligns every live ref onto the store row's seq+1 (#4316), so a non-view row
interleaved in the table desyncs every post-fold ref (golden wire drift:
responses/google legs, body #10 onward).

C1: the stash lives only in sessions.metadata_json.handoffReply. That column
is persisted in both the legacy file and the unified DB, identical in both
views (digest-equal), so the reply still lands durably in the database for
#6947's 'anything reading the DB loses the turn's final reply' concern —
without touching the view, the ledger, or any wire. A client re-send then
persists the reply as a normal view row with the kernel-minted ref, exactly
as before #6947.

- handoff-response.ts: unchanged from the previous cut (metadata-only stash,
  plan-ready rows with the codec-canonical ids, restampForJoin sidecars)
- ingest.ts: keep the planStoredMessageRow/HandoffReplyStashRow exports the
  capture uses; no planner emission
- store.ts / mysql.ts: back to the pre-cut delta/full paths (the join
  extension is gone with the table rows)
- tests: rewrite for C1 (stash never reaches the table; re-send is base
  behavior; identity join-key parity; golden re-baseline = metadata section
  only)

Local (node 22, clean env): issue6947 12/12, fork 4 files 91/91, lane/
storage/golden 6 files + storage-engine-proofs green at BASE expectations,
build OK.
2026-11-17 10:58:38 +08:00
ci-check 0283c812cd fix: dedupe responses-system-sections.ts module-map entry (ci-fixes merge left a second, less complete row) 2026-11-16 23:45:03 +08:00
ci-check 1a2e0c3bcb Merge remote-tracking branch 'origin/ci-fixes' into 2026-11-15_msgid-snapshot-unified 2026-11-16 23:35:29 +08:00
ranxianglei d08ce0dff9 #6785 review: register src/responses-system-sections.ts in the architecture map
The #6944 merge added the shared Responses developer-section joiner
(#6922) without its architecture.md entry, which the architecture-docs
guard requires. One-line module-map registration.
2026-11-16 22:30:01 +08:00
ci-check 1a4450bc85 Merge remote-tracking branch 'upstream/master' into HEAD 2026-11-16 20:44:19 +08:00
ci-check 8ed56be997 docs(architecture): add src/responses-system-sections.ts to the module map (#6922) 2026-11-16 20:42:39 +08:00
ranxianglei 301e1a5459 Merge pull request #6151 from ranxianglei/nudge-debug-pi
[PR] feat: pi lane — show the injected nudge text verbatim in the terminal when debug is on
2026-11-16 20:35:23 +08:00
ci-check 01b69f2975 fix: drop internal-only slim.ts exports and add slim.ts to the architecture file map (#6785 CI gates) 2026-11-16 12:38:17 +08:00
ranxianglei 57a5bcae91 docs: align architecture docs with the v2 plane (#6785)
reference/architecture.md: drop the three retired plane files from the
map (snap-egress, snapshot/assemble, snapshot/delta), re-point the
snapshot/ + snap.ts entries, note the egress splice/cut on
snapshot-render. storage-relations en/zh diagrams: the plane box now
shows l1_world / fold_journal / egress_snapshot / checkpoints (existing)
instead of the never-shipped snap_rows/snap_log/snap_ckpt; the fold and
GC flow boxes re-pointed. architecture/storage en/zh/ja: the kstate
convergence sentence no longer names a retired table (#6858 tracks the
follow-up). checksums/types headers: dropped the S4/snap_rows red-line
wording for the retired plane.
2026-11-16 00:10:09 +08:00
ranxianglei 3a68dcbbad integrate: #5901 (snapshot plane) + #6564 (msgid delivery) on master — pre-merge gate:local + full-CI validation
# Conflicts:
#	src/server/prepare-responses.ts
2026-11-14 16:43:44 +08:00
ranxianglei 5e38cf1792 fix(#5874 2x2): review round 1 — B0-B4 + M1-M6 (plane bypass, 400 funnel, frontier commit-on-accept, pure continuation, shared stage-0, codec-level pin)
Review of PR #6299 found four blockers and six majors; this is the
complete fix round.

B0 (root): a chained turn on the responses lane has no full-view
reconstruction (the D lane is skipped for pluginMode and #4804
augmentation is WS-only), so its kernel view is a delta, not the world.
Flushing that view to the plane deleted every row it did not contain.
Now a chained turn that is neither cohort (msgid-pinned stage-0) nor
WS-anchored sets session.skipPlaneFlush (one-shot, consumed by the
persist build — snapShadowSync returns before any plane work) and
passes bypass:true to applySnapEgress (the outbound is the legacy
bytes; the plane stays stale-but-intact until the next full/cohort
turn, which re-syncs it one-round).

B1: FoundationRejectError was swallowed by the lane 'kernel transform
failed, forwarding unchanged' catch -> 200. Both lane catches now
rethrow it first; the server funnel maps it to a 400 with
x-bili-snapshot: identity and {error:{type:'snapshot_identity_fault'}}
before the generic 503 path.

B3: a plugin chained round with EMPTY input (a pure provider-chain
continuation) is routed to the raw-body passthrough
(prepareResponsesCompact) at the dispatcher — no dev-message
injection, no chain-id strip, no kernel round. The injected dev
message + stripped id on a no-content round produced a blind provider
response that the host then chained from (permanent context loss).

B4: the delta frontier advanced at egress-build time with no rollback
on upstream failure. The selection now stashes pendingResponsesDelta
on the Prepared and commits session.responsesDelta only in the relay
when the upstream response status is < 400 (4xx -> null = reseed next
round; never advances on failure).

M1: stage-0 arming now requires the pluginLaneServerHistory rollout
(featureEnabled in runStage0), tying R3 to the rollout that makes it
reachable. M2: checkR3Identity is now the single R3 arbiter, called in
runStage0. M3: the R3 breaker latch persists (l1_world.r3_latched_at,
probe-first ALTER, upsert — the first fault precedes the session's
first l1 row) and survives a process restart; a latched session
degrades forever, never 400s again. M4: A1d pins the kernel-core
byte-identity at the CODEC level (the new element's core is
byte-identical between the M1 full-array parse and the M2 standalone
parse, wireIndex aside). M6: session.responsesDelta is cleared at
every stage-0 resync (s0.resynced). M5: PR body rewritten to match
the code.

Shared stage-0: the pin + R3 + stage-0 decision + assembly moved out
of the openai lane into src/snapshot/stage0.ts (runStage0), wired
into BOTH the openai and responses lanes (the responses lane reads
biliMsgIds/biliLedgerSeqs from its body; cohort = pluginMode +
declared).

Tests: tests/issue5874-2x2-p3.test.ts 40/40 (was 33): new A1d (M4
codec pin), B0a (skipPlaneFlush leaves the plane untouched), B0b
(egress bypass ref-identity), M3 (latch persistence across store
instances), and HTTP e2e B1 (400 + header + zero upstream forwards),
B3 (pure continuation raw passthrough), B4 (400 turn does not commit
the frontier; the next round re-seeds the full view). Regression:
snaplane-p2+snapshot-render+chain+shadow 41/41, storage-engine-proofs
+opencode-rolling 22/22, snapbase-p0+snaplane-p1+fastpath+
responses-previous-response-id 23/23, tsc clean.
2026-11-14 16:10:48 +08:00