Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 20 additions & 7 deletions src/conflict-watch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
// no conversation data — only the evidence notes.

import { markDirty, type Session } from "./session.js";
import { isSiblingConflictDetail } from "./thirdparty-scan.js";

export type ConflictKind = "third-party-plugin" | "unannounced-rewrite" | "orphan-reap" | "native-compaction";

Expand Down Expand Up @@ -68,7 +69,7 @@ export function formatConflictSection(events: ConflictEvent[], now: number = Dat
// read as a live alarm (it previously said "two compressors ..." imperatively
// even when every event was months old).
const { active, historical } = splitConflictEvents(events, now);
lines.push(`COMPRESSION CONFLICTS — ${events.length} event(s) in this session (${active.length} active · ${historical.length} historical; active = within ${CONFLICT_ACTIVE_WINDOW_MS / 86_400_000} days). Two compressors on one conversation (bili + a third-party compression plugin or client native compaction) double-compress and corrupt message refs:`);
lines.push(`COMPRESSION CONFLICTS — ${events.length} event(s) in this session (${active.length} active · ${historical.length} historical; active = within ${CONFLICT_ACTIVE_WINDOW_MS / 86_400_000} days). Two compressors on one conversation (bili + another compression plugin — third-party or bili's own sibling — or client native compaction) double-compress and corrupt message refs:`);
for (const e of events.slice(-10)) {
lines.push(` [${fmtTime(e.at)}] ${e.kind} — ${e.detail}`);
}
Expand All @@ -80,11 +81,18 @@ export function formatConflictSection(events: ConflictEvent[], now: number = Dat
lines.push(" [suspected] = name-only keyword match — verify the plugin actually compresses before acting; a context dashboard/viewer/tool is NOT a compressor.");
}
const allSuspected = suspectedCount > 0 && suspectedCount === events.length;
lines.push(active.length === 0
? "All events above are older than 7 days (historical stock): the double-compression risk may no longer be live. Verify the other compressor is removed or blocked by bili, then clear this ledger — Web UI conflict banner / session page, or POST /__bili/conflicts/clear?session=<id>."
: allSuspected
? "Every event above is [suspected]: confirm each named plugin really compresses before removing anything — do not drop a read-only tool on the strength of its name."
: "Keep exactly ONE compressor per conversation: remove/disable the other plugin (or its native auto-compaction), then start a fresh session.");
// #2261: a ledger naming ONLY bili's own siblings (billion-context-pi /
// opencode-acp) is not a foreign-compressor alarm — they stand down while
// bili drives the session (#820/#920), so never command removal for them.
const siblingEvents = events.filter((e) => e.kind === "third-party-plugin" && isSiblingConflictDetail(e.detail));
const siblingsOnly = siblingEvents.length > 0 && siblingEvents.length === events.length;
lines.push(siblingsOnly
? "Every event above names bili's OWN sibling extension (billion-context-pi / opencode-acp), not a third-party compressor: while bili drives the session it stands down automatically (BILLION_CONTEXT_NATIVE marker in native mode, /bili/ baseUrl self-check otherwise), so no second compressor is active. Verify your bili/sibling versions are recent, then clear this ledger — Web UI conflict banner / session page, or POST /__bili/conflicts/clear."
: active.length === 0
? "All events above are older than 7 days (historical stock): the double-compression risk may no longer be live. Verify the other compression plugin is removed or blocked by bili, then clear this ledger — Web UI conflict banner / session page, or POST /__bili/conflicts/clear?session=<id>."
: allSuspected
? "Every event above is [suspected]: confirm each named plugin really compresses before removing anything — do not drop a read-only tool on the strength of its name."
: "Keep exactly ONE compressor per conversation: remove/disable the other plugin (or its native auto-compaction), then start a fresh session.");
return lines;
}

Expand All @@ -98,18 +106,23 @@ export interface ConflictSummary {
/** #2102: timestamp of the newest event across all sessions, or null. */
lastAt: number | null;
kinds: Partial<Record<ConflictKind, number>>;
/** #2261: plugin-kind events naming bili's OWN siblings (billion-context-pi /
* opencode-acp) — display-time classification of recorded details, additive
* to `kinds`, so surfaces can stop calling first-party siblings "third-party". */
sibling: number;
latest: Array<{ sessionId: string; at: number; kind: ConflictKind; detail: string }>;
}

export function summarizeConflicts(sessions: Session[], now: number = Date.now()): ConflictSummary {
const summary: ConflictSummary = { sessions: 0, events: 0, active: 0, historical: 0, lastAt: null, kinds: {}, latest: [] };
const summary: ConflictSummary = { sessions: 0, events: 0, active: 0, historical: 0, lastAt: null, kinds: {}, latest: [], sibling: 0 };
for (const s of sessions) {
const events = conflictEventsOf(s);
if (events.length === 0) continue;
summary.sessions += 1;
summary.events += events.length;
for (const e of events) {
summary.kinds[e.kind] = (summary.kinds[e.kind] ?? 0) + 1;
if (e.kind === "third-party-plugin" && isSiblingConflictDetail(e.detail)) summary.sibling += 1;
if (now - e.at <= CONFLICT_ACTIVE_WINDOW_MS) summary.active += 1; else summary.historical += 1;
if (summary.lastAt === null || e.at > summary.lastAt) summary.lastAt = e.at;
}
Expand Down
28 changes: 26 additions & 2 deletions src/thirdparty-scan.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,21 @@ export function isDesignBenign(finding: ThirdPartyFinding, pluginAgent: string |
return false;
}

/** #2261: reverse-map a recorded conflict detail back to its plugin entry so
* display surfaces can tell bili's OWN siblings apart from true third parties
* — every other surface labels the whole "third-party-plugin" kind as a
* foreign compressor, which mislabels first-party siblings and commands
* removal of extensions that stand down by design (#820/#920). Detail shape
* (single producer, server.ts scan site): "<client>: <entry> (<source>)[ [suspected]]".
* Classifying at display time (not record time) also covers stock ledgers
* written by older versions before any sibling tag existed. */
export function isSiblingConflictDetail(detail: string): boolean {
const m = /^(\S+): (.+) \((.+)\)( \[suspected\])?$/.exec(detail.trim());
if (!m) return false;
const entry = m[2]!;
return isLegacyBcpEntry(entry) || isOpencodeAcpEntry(entry);
}

export const SCAN_CACHE_TTL_MS = 5 * 60 * 1000;

// Compression-ACTION tokens only. Bare "context" is deliberately EXCLUDED
Expand Down Expand Up @@ -139,10 +154,19 @@ function isBiliSelf(entry: string): boolean {
return /[/\\]billion-context([/\\]|$)/.test(entry.trim());
}

/** #2261: opencode-acp entry identity — bare name, npm spec (with or without
* version), or any path whose segments contain opencode-acp. Shared by the
* scanner and the conflict-display sibling classifier so the two can never
* drift apart. */
export function isOpencodeAcpEntry(entry: string): boolean {
const trimmed = entry.trim();
const bare = trimmed.replace(/^npm:/, "");
return bare === "opencode-acp" || /^opencode-acp@/.test(bare) || /(^|[/\\])opencode-acp([/\\]|$)/.test(trimmed);
}

function classifyOpencodeEntry(c: Collector, entry: string, source: string): void {
if (isBiliSelf(entry)) return;
const trimmed = entry.trim();
if (/^opencode-acp(@|$)/.test(trimmed) || /[/\\]opencode-acp([/\\]|$)/.test(trimmed)) {
if (isOpencodeAcpEntry(entry)) {
add(c, { client: "opencode", entry, source, match: "known", knownId: "opencode-acp" });
return;
}
Expand Down
10 changes: 8 additions & 2 deletions src/web/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -374,11 +374,17 @@ export const WEB_CLIENT = `(function () {
// #2102: attribute per kind family present; split active from historical
// stock; detail pointer must target a cross-session surface (acp_status
// renders conflicts for the CURRENT session only).
// #2261: bili's own siblings (billion-context-pi / opencode-acp) are NOT
// third-party plugins — the server counts them separately so the sentence
// never mislabels them or commands removal of something that stands down.
const pluginN = (c.kinds && c.kinds["third-party-plugin"]) || 0;
const siblingN = Math.max(0, Math.min(typeof c.sibling === "number" ? c.sibling : 0, pluginN));
const tpN = pluginN - siblingN;
const nativeN = c.events - pluginN;
const what = [pluginN > 0 ? t("conflict.what_plugin") : "", nativeN > 0 ? t("conflict.what_native") : ""].filter(Boolean).join(t("conflict.what_join"));
const what = [tpN > 0 ? t("conflict.what_plugin") : "", siblingN > 0 ? t("conflict.what_sibling") : "", nativeN > 0 ? t("conflict.what_native") : ""].filter(Boolean).join(t("conflict.what_join"));
const active = typeof c.active === "number" ? c.active : c.events;
cb.innerHTML = '<strong>' + t("conflict.on") + "</strong>" + t("conflict.found") + escapeHtml(what) + (active > 0 ? t("conflict.risk_active") : t("conflict.risk_historical")) + '<span class="mono">(' + bili_conflictLine(c) + ")</span>" + t("conflict.where") + '<button id="conflicts-clear-btn" class="btn sm">' + t("conflict.clear_btn") + "</button>";
const risk = tpN === 0 && nativeN === 0 ? t("conflict.risk_sibling") : (active > 0 ? t("conflict.risk_active") : t("conflict.risk_historical"));
cb.innerHTML = '<strong>' + t("conflict.on") + "</strong>" + t("conflict.found") + escapeHtml(what) + risk + '<span class="mono">(' + bili_conflictLine(c) + ")</span>" + t("conflict.where") + '<button id="conflicts-clear-btn" class="btn sm">' + t("conflict.clear_btn") + "</button>";
cb.classList.toggle("info", active === 0);
cb.classList.toggle("warn", active > 0);
const btn = $("conflicts-clear-btn");
Expand Down
6 changes: 6 additions & 0 deletions src/web/i18n.ts
Original file line number Diff line number Diff line change
Expand Up @@ -88,9 +88,12 @@ export const MESSAGES: Record<Locale, Record<string, string>> = {
// client-native rewrites must not read as "third-party plugin" evidence.
"conflict.found": ":发现",
"conflict.what_plugin": "与 bili 并存的第三方压缩插件",
// #2261: bili's own siblings are first-party — never label them third-party.
"conflict.what_sibling": "与 bili 并存的 bili 自家兄弟扩展(billion-context-pi / opencode-acp)",
"conflict.what_native": "客户端原生自动压缩改写会话历史",
"conflict.what_join": "、",
"conflict.risk_active": "的痕迹。两个压缩器作用于同一会话会双压缩、破坏消息引用,可能导致上下文错乱——请只保留一个压缩器。",
"conflict.risk_sibling": "的痕迹。它们是 bili 自家的兄弟扩展,不是第三方压缩插件:当 bili 主导会话时会自动让位(native 模式经 BILLION_CONTEXT_NATIVE 标记、launcher/手动接线经 /bili/ baseUrl 自检),没有第二个压缩器在活动——确认版本较新后清除本记录即可,无需移除任何插件。",
"conflict.risk_historical": "的痕迹(最近 7 天无新事件,以下为存量记录)——确认另一个压缩器已移除或被 bili 拦截后,可点右侧按钮清除。",
"conflict.where": "详情见下方 Sessions 页或 GET /__bili/stats → conflicts。",
"conflict.clear_btn": "清除记录",
Expand Down Expand Up @@ -442,9 +445,12 @@ export const MESSAGES: Record<Locale, Record<string, string>> = {
// #2102: composed per kind family present — see the zh entry above.
"conflict.found": ": traces of ",
"conflict.what_plugin": "a third-party compression plugin co-resident with bili",
// #2261: see the zh entry above — siblings are first-party.
"conflict.what_sibling": "a bili sibling extension (billion-context-pi / opencode-acp) co-resident with bili",
"conflict.what_native": "client-native auto-compaction rewriting conversation history",
"conflict.what_join": " and ",
"conflict.risk_active": " were found. Two compressors on one conversation double-compress and corrupt message refs, which can scramble context — keep exactly one compressor.",
"conflict.risk_sibling": " were found. These are bili's OWN sibling extensions, not third-party compressors: while bili drives the session they stand down automatically (BILLION_CONTEXT_NATIVE marker in native mode, /bili/ baseUrl self-check otherwise), so no second compressor is active — verify your versions are recent and clear this record; nothing needs removing.",
"conflict.risk_historical": " were found (no events in the last 7 days — stock records only) — once you've confirmed the other compressor is removed or blocked by bili, clear them with the button.",
"conflict.where": "Details: Sessions page below or GET /__bili/stats → conflicts.",
"conflict.clear_btn": "Clear records",
Expand Down
64 changes: 63 additions & 1 deletion tests/issue1206-thirdparty-scan.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ process.env.NODE_ENV = "test";

import { createInitialState } from "acp-kernel";
import type { Session } from "../src/session.ts";
import { clearScanCache, conflictScanEnabled, isDesignBenign, scanClientPlugins, sniffScanClient, type ThirdPartyFinding } from "../src/thirdparty-scan.js";
import { clearScanCache, conflictScanEnabled, isDesignBenign, isOpencodeAcpEntry, isSiblingConflictDetail, scanClientPlugins, sniffScanClient, type ThirdPartyFinding } from "../src/thirdparty-scan.js";
import { CONFLICT_LEDGER_MAX, conflictEventsOf, formatConflictSection, recordConflict, summarizeConflicts } from "../src/conflict-watch.js";
import { resolveHermesHome, resolveKimiHome, resolveOmpHome, resolvePiHome } from "../src/client-config.js";
import { SessionStore, _setStoreForTest } from "../src/persist.js";
Expand Down Expand Up @@ -381,3 +381,65 @@ test("summarizeConflicts aggregates across sessions", () => {
assert.equal(summary.latest[0]?.sessionId, a.id);
assert.equal(summarizeConflicts([b]).events, 0);
});

// #2261: display-time sibling classification — first-party siblings must never
// be labeled "third-party" or commanded removed on any surface.

test("isOpencodeAcpEntry recognizes every spec form, rejects lookalikes (#2261)", () => {
assert.ok(isOpencodeAcpEntry("opencode-acp"));
assert.ok(isOpencodeAcpEntry("npm:opencode-acp"));
assert.ok(isOpencodeAcpEntry("opencode-acp@stable"));
assert.ok(isOpencodeAcpEntry("/home/u/node_modules/opencode-acp/index.js"));
assert.ok(!isOpencodeAcpEntry("my-opencode-acp-fork"));
assert.ok(!isOpencodeAcpEntry("context-forge"));
});

test("isSiblingConflictDetail maps recorded details back to sibling entries (#2261)", () => {
assert.ok(isSiblingConflictDetail("pi: npm:billion-context-pi (/home/dog/.pi/agent/settings.json)"));
assert.ok(isSiblingConflictDetail("pi: billion-context-pi@0.1.75 (~/.pi/settings.json)"));
assert.ok(isSiblingConflictDetail("opencode: opencode-acp (global config)"));
assert.ok(isSiblingConflictDetail("opencode: npm:opencode-acp@1.2.3 (/u/.config/opencode/opencode.json)"));
assert.ok(!isSiblingConflictDetail("pi: npm:context-forge (/home/dog/.pi/agent/settings.json) [suspected]"));
assert.ok(!isSiblingConflictDetail("dsh: dsh-context (profile/package.json) [suspected]"));
assert.ok(!isSiblingConflictDetail("event 5"), "non-plugin detail shapes never classify");
});

test("opencode scan: npm:-prefixed opencode-acp spec classifies as known sibling, not suspected keyword (#2261)", () => {
clearScanCache();
const root = tmp("bili-2261-oc-npm-");
const file = path.join(root, ".config", "opencode", "opencode.json");
assertTestOwned(file, root);
writeFile(file, JSON.stringify({ plugin: ["npm:opencode-acp"] }));
const res = scanClientPlugins("opencode", { env: hermeticEnv(root), cwd: root });
const f = res.findings.find((x) => x.entry === "npm:opencode-acp");
assert.ok(f, "npm:-prefixed spec must be found");
assert.equal(f?.match, "known");
assert.equal(f?.knownId, "opencode-acp");
});

test("summarizeConflicts counts sibling-tagged plugin events additively (#2261)", () => {
const a = makeSession();
recordConflict(a, "third-party-plugin", "pi: npm:billion-context-pi (/home/dog/.pi/agent/settings.json)");
recordConflict(a, "third-party-plugin", "pi: npm:context-forge (/home/dog/.pi/agent/settings.json) [suspected]");
recordConflict(a, "orphan-reap", "1 block(s) deactivated: b1");
const s = summarizeConflicts([a]);
assert.equal(s.events, 3);
assert.equal(s.kinds["third-party-plugin"], 2);
assert.equal(s.sibling, 1, "only the bcp event classifies as sibling");
});

test("formatConflictSection: sibling-only ledgers drop the one-compressor command (#2261)", () => {
const s = makeSession();
recordConflict(s, "third-party-plugin", "pi: npm:billion-context-pi (/home/dog/.pi/agent/settings.json)");
recordConflict(s, "third-party-plugin", "opencode: opencode-acp (global config)");
const text = formatConflictSection(conflictEventsOf(s)).join("\n");
assert.ok(text.includes("OWN sibling extension"), "names them as bili's own siblings");
assert.ok(!text.toLowerCase().includes("keep exactly one compressor"), "no hard removal command for siblings");
assert.ok(text.includes("/__bili/conflicts/clear"), "points at the clear path");

const mixed = makeSession();
recordConflict(mixed, "third-party-plugin", "pi: npm:billion-context-pi (/home/dog/.pi/agent/settings.json)");
recordConflict(mixed, "third-party-plugin", "pi: npm:real-compressor-x (/home/dog/.pi/agent/settings.json)");
const mixedText = formatConflictSection(conflictEventsOf(mixed)).join("\n");
assert.ok(mixedText.toLowerCase().includes("keep exactly one compressor"), "any non-sibling event keeps the strong footer");
});
Loading