Skip to content

Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.

fix(pi): capture divergent sibling branches (#6381)

z1gon401c1f7ef1e4
diff --git a/examples/pi-coding-agent-extension/DESIGN.md b/examples/pi-coding-agent-extension/DESIGN.md
index ac16ab2ad..c179bcfc8 100644
--- a/examples/pi-coding-agent-extension/DESIGN.md
+++ b/examples/pi-coding-agent-extension/DESIGN.md
@@ -78,7 +78,7 @@ Injection is two-pass, and that is the interesting part. Historical user message
The OV session id is `pi-<pi session id>`, derived locally by the shared `deriveHarnessSessionId`. Nothing round-trips to open a session: the id is deterministic, so the first write can carry it.
-**Capture.** `turn_end` hands the whole branch to `extractBranchCapturePayloads` (`lib/capture-adapter.mjs`), which takes the entries past `syncedEntryCount`, normalizes roles, renders tool parts with bounded input and output, and decides entry by entry whether to capture. There are two decision modes. Normally it is the shared `shouldCaptureText` heuristic. Under takeover it is a faithful mode that drops only empty text, slash commands and OpenViking's own status messages: once the boundary advances, a short acknowledgement may be represented to the model *only* through the archive overview, so discarding it as low-signal would lose it outright. A branch shorter than the watermark means pi navigated to a different branch, so the watermark resets to zero and the branch is re-extracted from the start.
+**Capture.** `turn_end` hands the whole branch to `extractBranchCapturePayloads` (`lib/capture-adapter.mjs`), which takes the entries past `syncedEntryCount`, normalizes roles, renders tool parts with bounded input and output, and decides entry by entry whether to capture. There are two decision modes. Normally it is the shared `shouldCaptureText` heuristic. Under takeover it is a faithful mode that drops only empty text, slash commands and OpenViking's own status messages: once the boundary advances, a short acknowledgement may be represented to the model *only* through the archive overview, so discarding it as low-signal would lose it outright. The manager also remembers the pi entry id at the numeric watermark. A shorter branch or a different entry at that position means pi navigated to another branch, so the watermark resets to zero and the branch is re-extracted from the start. This catches equal-length siblings as well as shorter branches.
**Delivery.** Payloads leave in one batched request through the shared `sendSessionMessages`. Retryable failures are written to the shared disk pending queue and replayed later. The result distinguishes delivered, queued and permanently lost payloads. A non-retryable rejection or failed enqueue advances the capture watermark to avoid duplicate replay, but also records a persistent capture gap; takeover never trims across that gap. The watermark only moves when the whole extraction has either been delivered, queued or recorded as permanently lost.
diff --git a/examples/pi-coding-agent-extension/index.ts b/examples/pi-coding-agent-extension/index.ts
index ee4bc9cfb..e9f068572 100644
--- a/examples/pi-coding-agent-extension/index.ts
+++ b/examples/pi-coding-agent-extension/index.ts
@@ -188,7 +188,7 @@ export default async function (pi: ExtensionAPI) {
: [];
if (config.takeoverEnabled) {
takeover.restore(branch);
- sync.restoreWatermark(takeover.state.syncedEntryCount);
+ sync.restoreWatermark(takeover.state.syncedEntryCount, branch);
}
await sync.replayPending();
diff --git a/examples/pi-coding-agent-extension/lib/capture-adapter.d.mts b/examples/pi-coding-agent-extension/lib/capture-adapter.d.mts
index b502604de..bb50f3d79 100644
--- a/examples/pi-coding-agent-extension/lib/capture-adapter.d.mts
+++ b/examples/pi-coding-agent-extension/lib/capture-adapter.d.mts
@@ -2,9 +2,11 @@ export function extractBranchCapturePayloads(
branch: any[],
syncedEntryCount?: number,
cfg?: Record<string, any>,
+ syncedEntryId?: string,
): {
payloads: any[];
nextEntryCount: number;
+ nextEntryId: string;
observedEntryCount: number;
resetWatermark: boolean;
};
diff --git a/examples/pi-coding-agent-extension/lib/capture-adapter.mjs b/examples/pi-coding-agent-extension/lib/capture-adapter.mjs
index f4096e8fc..3b5fc8a30 100644
--- a/examples/pi-coding-agent-extension/lib/capture-adapter.mjs
+++ b/examples/pi-coding-agent-extension/lib/capture-adapter.mjs
@@ -20,10 +20,11 @@ function entryPayload(entry) {
return entry;
}
-export function extractBranchCapturePayloads(branch, syncedEntryCount = 0, cfg = {}) {
+export function extractBranchCapturePayloads(branch, syncedEntryCount = 0, cfg = {}, syncedEntryId = "") {
const entries = Array.isArray(branch) ? branch : [];
const previousCount = Math.max(0, Number(syncedEntryCount) || 0);
- const resetWatermark = entries.length < previousCount;
+ const resetWatermark = entries.length < previousCount
+ || Boolean(syncedEntryId && entries[previousCount - 1]?.id !== syncedEntryId);
const start = resetWatermark ? 0 : Math.min(previousCount, entries.length);
const payloads = [];
@@ -59,6 +60,7 @@ export function extractBranchCapturePayloads(branch, syncedEntryCount = 0, cfg =
return {
payloads,
nextEntryCount: entries.length,
+ nextEntryId: entries.at(-1)?.id || "",
observedEntryCount: entries.length,
resetWatermark,
};
diff --git a/examples/pi-coding-agent-extension/sync.ts b/examples/pi-coding-agent-extension/sync.ts
index 79ec41168..b836ab22e 100644
--- a/examples/pi-coding-agent-extension/sync.ts
+++ b/examples/pi-coding-agent-extension/sync.ts
@@ -31,6 +31,8 @@ export class SyncManager {
private logger: ReturnType<typeof createLogger>;
private ovSessionId: string | null = null;
private syncedEntryCount = 0;
+ /** Entry at the numeric watermark; detects a same-length sibling branch. */
+ private syncedEntryId = "";
/**
* Messages this session lost for good: non-retryable (4xx) rejections and
* queued entries whose retry budget ran out. They are counted as accepted so
@@ -70,9 +72,9 @@ export class SyncManager {
return extracted.payloads.length;
}
- restoreWatermark(n: number): void {
- const next = Math.max(0, Math.floor(Number(n) || 0));
- this.syncedEntryCount = next;
+ restoreWatermark(n: number, branch: any[]): void {
+ this.syncedEntryCount = Math.max(0, Math.floor(Number(n) || 0));
+ this.syncedEntryId = branch[this.syncedEntryCount - 1]?.id || "";
}
async ensureSession(piSessionId: string): Promise<boolean> {
@@ -208,8 +210,16 @@ export class SyncManager {
return { added: 0, tokens: 0, allDelivered: true, queued: 0, permanentFailures: 0 };
}
- const extracted = extractBranchCapturePayloads(branch, this.syncedEntryCount, this.config);
- if (extracted.resetWatermark) this.syncedEntryCount = 0;
+ const extracted = extractBranchCapturePayloads(
+ branch,
+ this.syncedEntryCount,
+ this.config,
+ this.syncedEntryId,
+ );
+ if (extracted.resetWatermark) {
+ this.syncedEntryCount = 0;
+ this.syncedEntryId = "";
+ }
const sent = await this.sendPayloads(extracted.payloads);
const added = sent.accepted;
let tokens = 0;
@@ -219,6 +229,7 @@ export class SyncManager {
const allDelivered = sent.delivered === added && sent.permanentFailures === 0;
if (added === extracted.payloads.length) {
this.syncedEntryCount = extracted.nextEntryCount;
+ this.syncedEntryId = extracted.nextEntryId;
}
if (added > 0 && !this.config.takeoverEnabled) {
await this.commitIfNeeded();
diff --git a/examples/pi-coding-agent-extension/tests/sync-barrier.test.mjs b/examples/pi-coding-agent-extension/tests/sync-barrier.test.mjs
index 0a0a32c95..3d6e7fed7 100644
--- a/examples/pi-coding-agent-extension/tests/sync-barrier.test.mjs
+++ b/examples/pi-coding-agent-extension/tests/sync-barrier.test.mjs
@@ -236,27 +236,37 @@ test("a current-session processing entry keeps the takeover barrier closed", asy
});
});
-test("restoreWatermark prevents pi -c from re-syncing already captured entries", async () => {
+test("capture cursor skips continuations and re-extracts sibling branches", async () => {
await withPendingDir(async () => {
const calls = [];
const c = client({
fetchJSON: async (_path, init) => {
- calls.push(...JSON.parse(init.body).messages);
+ calls.push(JSON.parse(init.body).messages.map((payload) => payload.parts[0].text));
return { ok: true, result: {} };
},
});
const sync = new SyncManager(c, config());
await sync.ensureSession("pi-session");
- sync.restoreWatermark(1);
-
- const result = await sync.syncBranch([
- { type: "message", message: { role: "user", content: "Already captured entry should be skipped." } },
- { type: "message", message: { role: "user", content: "Fresh entry should be captured now." } },
+ const [root, a, b, next] = ["root", "branch-a", "branch-b", "next"].map((id) => ({
+ id, type: "message", message: { role: "user", content: id },
+ }));
+ const branchA = [root, a];
+ const branchB = [root, b];
+ sync.restoreWatermark(1, branchA);
+
+ assert.equal((await sync.syncBranch(branchA)).added, 1);
+ assert.equal((await sync.syncBranch(branchA)).added, 0);
+ await sync.syncBranch(branchB);
+ await sync.syncBranch(branchA);
+ await sync.syncBranch([...branchB, next]);
+
+ assert.equal(sync.syncedCount, 3);
+ assert.deepEqual(calls, [
+ ["branch-a"],
+ ["root", "branch-b"],
+ ["root", "branch-a"],
+ ["root", "branch-b", "next"],
]);
-
- assert.equal(result.added, 1);
- assert.equal(calls.length, 1);
- assert.match(calls[0].parts[0].text, /Fresh entry/);
});
});