Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Prev Previous commit
Next Next commit
fix(pi): retain captures after flush failures
  • Loading branch information
pi-dal committed Aug 21, 2026
commit 0ff42dbf0cf9caba6bd418570febb59b30139dd1
26 changes: 19 additions & 7 deletions integrations/pi/plugins/powercontext/src/capture.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ export interface CaptureInput {
sessionId: string
turnId: string
signal?: AbortSignal
onFlushFailure?: (position: number) => void
}

export function buildSourceId(scopeId: string, sessionId: string, turnId: string, prompt: string): string {
Expand All @@ -46,14 +47,19 @@ function sourcePosition(value: unknown): number | undefined {
return position
}

async function flushThrough(input: CaptureInput, position: number): Promise<void> {
async function flushThrough(input: CaptureInput, position: number): Promise<boolean> {
for (let index = 0; index < input.config.flushMaxCalls; index += 1) {
const result = await input.client.request('flush_memory', { scope_id: input.scopeId }, input.signal)
const cursor = result.kind === 'json' && result.value && typeof result.value === 'object'
? (result.value as { current_cursor?: unknown }).current_cursor
: undefined
if (typeof cursor === 'number' && cursor >= position) return
try {
const result = await input.client.request('flush_memory', { scope_id: input.scopeId }, input.signal)
const cursor = result.kind === 'json' && result.value && typeof result.value === 'object'
? (result.value as { current_cursor?: unknown }).current_cursor
: undefined
if (typeof cursor === 'number' && cursor >= position) return true
} catch {
// A transient flush failure should not discard the captured position.
}
}
return false
}

export async function captureUserPrompt(input: CaptureInput): Promise<number | undefined> {
Expand All @@ -78,7 +84,13 @@ export async function captureUserPrompt(input: CaptureInput): Promise<number | u
},
}, input.signal)
const position = result.kind === 'json' ? sourcePosition(result.value) : undefined
if (input.config.flushOnCapture && position !== undefined) await flushThrough(input, position)
if (input.config.flushOnCapture && position !== undefined && !(await flushThrough(input, position))) {
try {
input.onFlushFailure?.(position)
} catch {
// Pending-source bookkeeping is auxiliary; it must not affect the turn.
}
}
return position
} catch {
// Source persistence is auxiliary; it must not delay or break the Pi turn.
Expand Down
1 change: 1 addition & 0 deletions integrations/pi/plugins/powercontext/src/recall.ts
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,7 @@ export async function recallBeforeAgentStart(input: BeforeAgentStartInput): Prom
sessionId: sessionId(input.sessionId),
turnId: nextTurnId(input.branch),
signal,
onFlushFailure: (position) => input.runtime.recordCapture?.(scopeId, position),
})
if (position !== undefined && !input.runtime.config.flushOnCapture) {
input.runtime.recordCapture?.(scopeId, position)
Expand Down
82 changes: 82 additions & 0 deletions integrations/pi/plugins/powercontext/tests/extension.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -168,6 +168,88 @@ describe('PowerContext Pi extension', () => {
expect(JSON.parse(String(flush?.[1]?.body))).toEqual({ scope_id: 'project:demo' })
})

it('retries an immediate flush after a transient failure', async () => {
vi.stubEnv('POWERCONTEXT_PI_FLUSH_ON_CAPTURE', 'true')
vi.stubEnv('POWERCONTEXT_PI_FLUSH_MAX_CALLS', '4')
let flushAttempts = 0
const fetch = vi.fn(async (url: string) => {
if (url.endsWith('/v1/context/prepare')) {
return new Response(JSON.stringify({
schema: 'powercontext.prepared-context.v1',
status: 'empty',
content: null,
content_bytes: 0,
}))
}
if (url.endsWith('/v1/sources/content')) return new Response(JSON.stringify({ position: 7 }))
if (url.endsWith('/v1/memory/flush')) {
flushAttempts += 1
return flushAttempts === 1
? new Response(JSON.stringify({ error: { message: 'temporary failure' } }), { status: 500 })
: new Response(JSON.stringify({ current_cursor: 7 }))
}
throw new Error(`unexpected request: ${url}`)
})
vi.stubGlobal('fetch', fetch)
const beforeAgentStart = installExtension().get('before_agent_start')

await beforeAgentStart?.({
prompt: 'continue implementation',
systemPrompt: 'Base instructions',
}, {
cwd: '/workspace/repo',
sessionManager: {
getSessionId: () => 'session-42',
getBranch: () => [],
},
})

expect(flushAttempts).toBe(2)
})

it('retains a captured position for compaction after immediate flush retries fail', async () => {
vi.stubEnv('POWERCONTEXT_PI_FLUSH_ON_CAPTURE', 'true')
vi.stubEnv('POWERCONTEXT_PI_FLUSH_MAX_CALLS', '1')
let flushAttempts = 0
const fetch = vi.fn(async (url: string) => {
if (url.endsWith('/v1/context/prepare')) {
return new Response(JSON.stringify({
schema: 'powercontext.prepared-context.v1',
status: 'empty',
content: null,
content_bytes: 0,
}))
}
if (url.endsWith('/v1/sources/content')) return new Response(JSON.stringify({ position: 7 }))
if (url.endsWith('/v1/memory/flush')) {
flushAttempts += 1
return flushAttempts === 1
? new Response(JSON.stringify({ error: { message: 'temporary failure' } }), { status: 500 })
: new Response(JSON.stringify({ current_cursor: 7 }))
}
throw new Error(`unexpected request: ${url}`)
})
vi.stubGlobal('fetch', fetch)
const handlers = installExtension()
const context = {
cwd: '/workspace/repo',
sessionManager: {
getSessionId: () => 'session-42',
getBranch: () => [],
},
}

await handlers.get('before_agent_start')?.({
prompt: 'continue implementation',
systemPrompt: 'Base instructions',
}, context)
expect(flushAttempts).toBe(1)

await handlers.get('session_before_compact')?.({}, context)

expect(flushAttempts).toBe(2)
})

it('does not persist a prompt when capture is disabled', async () => {
vi.stubEnv('POWERCONTEXT_PI_CAPTURE_PROMPTS', 'false')
const fetch = vi.fn().mockResolvedValue(new Response(JSON.stringify({
Expand Down