@estebanforge/pi-antigravity-bridge 1.13.3 → 1.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,21 @@
2
2
 
3
3
  All notable changes to this project will be documented in this file.
4
4
 
5
+ ## [1.14.0] - 2026-11-24
6
+
7
+ ### Fixed
8
+
9
+ - One oversized tool result no longer erases earlier turns from the context digest (#25): tool-result bodies are capped per part (head + tail with an elision marker) before the delta budget is spent, so a single >8KB read/bash result can no longer starve the mid-session handoff.
10
+ - Assistant tool calls now render into the digest (`[tool call: name(args)]`, args capped and redacted) instead of vanishing with their text blocks; a turn carrying only tool calls ships too, where it used to be skipped entirely (#25).
11
+ - A config.json saved before the digest-default flip no longer silently keeps the digest off (#25): `migrateStaleDigestDefault` at session start flips the stale `digest: false` to the shipped ON default once, writes a `digestMigrated` marker so later deliberate `/agy digest off` survives, and respects `AGY_DIGEST`. One-time ambiguity window: an `/agy digest off` chosen between the flip commit and this release migrates to ON once (the toast explains how to keep it off).
12
+ - A bound turn whose digest build fails the stream-json byte cap no longer permanently loses that delta (#25 follow-up): the settle write holds the watermark when nothing shipped, so the window re-offers on the next turn (the re-offer re-includes the prior turn's user prompt, which already reached the conversation as that turn's prompt - a small duplicate, never a loss); partial renders (budget cut old turns) still advance and now log the skipped span (`digest` event, AGY_DEBUG-visible) for cap-deciding data.
13
+ - An ACP `session/load` failure that silently falls back to a fresh agy conversation no longer ships a blind turn (#25): bound turns carry an as-if-fresh fallback variant (system prompt gate open, full `bound: false` digest) that the driver swaps in at the load-failure point; the variant honors the same `/agy digest off` and `/agy system-prompt off` choices as the normal turn, and with both off no variant is built at all. stream-json cannot detect its stale-id drop, so the fallback is ACP-only.
14
+
15
+ ### Changed
16
+
17
+ - ACP digest cap raised 8k to 24k chars after a live probe (scripts/probe-acp-context.mjs): a 120k-char embeddedContext block shipped and the model recalled needle strings at both block extremities exactly (end needle on the digest turn; start needle again on a bound follow-up with no block re-sent, proving the block persists server-side), so 24k is transport-safe and shrinks the newest-first partial-render hole. stream-json keeps its 8k inline clamp under the ~25KB prompt cap.
18
+ - AskAntigravity model param description now names the configured default (gemini-4-hydrogen) and the Gemini 4 lines. Removed the legacy flash/pro examples: callers read them as the house default, hard-coded `model: "flash"`, and skipped the hydrogen default entirely (flash resolves to the deprecated 3.x era).
19
+
5
20
  ## [1.13.3] - 2026-11-23
6
21
 
7
22
  ### Fixed
@@ -68,7 +68,7 @@ import { agyAuthenticationMessage } from "../src/agy-install.js";
68
68
  import { createAgySetupOffer } from "../src/agy-setup.js";
69
69
  import { ensureQueuedMessagesDefaults } from "../src/queued-messages.js";
70
70
  import type { TurnDriver, TurnOutcome } from "../src/driver-types.js";
71
- import { configPath, configWarningsMessage, loadConfig, logsDir, MAX_TURN_CAP_MIN, parseCapMinutes, removeLegacyAcpBin, saveConfig, type AcpConfig, type AgyMode, type BridgeTools, type Engine, type ThinkingTier } from "../src/config.js";
71
+ import { configPath, configWarningsMessage, loadConfig, logsDir, MAX_TURN_CAP_MIN, migrateStaleDigestDefault, parseCapMinutes, removeLegacyAcpBin, saveConfig, type AcpConfig, type AgyMode, type BridgeTools, type Engine, type ThinkingTier } from "../src/config.js";
72
72
  import { agyMissingMessage, ENGINE_SETTINGS_ROW_ID, engineSettingsRow, isAgyInstalled, savedEngineMessage, showEnginePicker, shouldOfferEnginePicker } from "../src/engine-picker.js";
73
73
  import { agyVersionVerdict, agyUpdateMessage, checkAgyCliVersion, describeAgyVersionCheck, MIN_AGY_ACP_VERSION, MIN_AGY_VERSION, MIN_GEMINI_DIR_VERSION, probeGeminiDirFlag, resolveStreamHomeMode } from "../src/agy-version.js";
74
74
  import { isValidAgyAgentName, listAgyAgents } from "../src/agents.js";
@@ -231,6 +231,7 @@ export default async function (pi: ExtensionAPI): Promise<void> {
231
231
  let gateActive = false;
232
232
  let managedAcpCleanupRan = false;
233
233
  let legacyConfigCleanupRan = false;
234
+ let digestMigrationRan = false;
234
235
  let legacyConfigCleanupFailed = false;
235
236
  let legacyEnvAcpWarningShown = false;
236
237
  let legacyFileAcpWarningShown = false;
@@ -868,6 +869,25 @@ export default async function (pi: ExtensionAPI): Promise<void> {
868
869
  fileLog.log("legacy-acp-config-cleanup", { error: String(err) }, "error");
869
870
  }
870
871
  }
872
+ // One-time digest-default migration (issue #25): a config saved before
873
+ // the default flip carries digest:false as a bare default, silently
874
+ // keeping mid-session context handoffs off. Best-effort like the
875
+ // cleanup above: a failure must never block session_start.
876
+ if (!digestMigrationRan) {
877
+ digestMigrationRan = true;
878
+ try {
879
+ const migrated = migrateStaleDigestDefault().migrated;
880
+ fileLog.log("digest-default-migration", { migrated }, migrated ? "info" : "debug");
881
+ if (migrated && ctx.hasUI) {
882
+ ctx.ui.notify(
883
+ "digest was still off from an older default; enabled it (keeps context visible on model switches). Keep it off with /agy digest off.",
884
+ "info",
885
+ );
886
+ }
887
+ } catch (err) {
888
+ fileLog.log("digest-default-migration", { error: String(err) }, "warn");
889
+ }
890
+ }
871
891
  if (!legacyEnvAcpWarningShown && process.env.AGY_ACP_BIN?.trim()) {
872
892
  legacyEnvAcpWarningShown = true;
873
893
  const msg = "AGY_ACP_BIN is set but no longer used; turns run \"agy acp\" from the CLI. Remove it from your shell config, then start a new terminal.";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@estebanforge/pi-antigravity-bridge",
3
- "version": "1.13.3",
3
+ "version": "1.14.0",
4
4
  "description": "Gemini provider for Pi on the Antigravity ACP server (official Google ACP) or the stream-json agy CLI. Use antigravity/* models in Pi. Full /model picker support. Models runs Pi's tools. ToS safe to use.",
5
5
  "keywords": [
6
6
  "pi-package",
package/src/acp/driver.ts CHANGED
@@ -293,7 +293,10 @@ export class AcpDriver implements TurnDriver {
293
293
  }
294
294
 
295
295
  async #executeTurn(turn: ActiveTurn): Promise<void> {
296
- const request = turn.request;
296
+ // Reassigned when a load failure applies the request's fresh-mode
297
+ // fallback (issue #25): everything after session setup must read the
298
+ // swapped variant.
299
+ let request = turn.request;
297
300
  const conn = await this.#ensureConnection(request);
298
301
  let reused = false;
299
302
 
@@ -340,6 +343,14 @@ export class AcpDriver implements TurnDriver {
340
343
  this.#failTurn(turn, `ACP session failed: ${describe(err2)}`);
341
344
  return;
342
345
  }
346
+ if (request.fallback) {
347
+ // The recreated conversation holds nothing: swap in the as-if-
348
+ // fresh variant the provider prebuilt (system prompt + full
349
+ // digest) instead of shipping the bound-mode prompt blind.
350
+ this.#log("session-load-fallback-applied", { sessionId: request.conversationId });
351
+ request = { ...request, prompt: request.fallback.prompt, contextBlock: request.fallback.contextBlock };
352
+ turn.request = request;
353
+ }
343
354
  } else {
344
355
  this.#failTurn(turn, `ACP session failed: ${describe(err)}`);
345
356
  return;
package/src/ask-tool.ts CHANGED
@@ -64,7 +64,7 @@ COMPACT OUTPUT (param: digest): when true, the prompt is prefixed to request com
64
64
  THINKING LEVEL (params: thinking, effort - SYNONYMS for one knob):
65
65
  - pi calls it thinking, agy calls it effort. Same thing. Pass ONE of the two.
66
66
  - Values (pi vocabulary): minimal|low|medium|high|xhigh|max. Clamped to agy's low|medium|high; unknown values fall back to low. "peer review on high thinking" -> thinking: "high".
67
- - An explicit level beats a tier embedded in model ("flash high") and the configured default. Omit both for the configured default.`;
67
+ - An explicit level beats a tier embedded in model ("gemini-4-carbon-high") and the configured default. Omit both for the configured default.`;
68
68
 
69
69
  // Delegations legitimately run long (research, review, analysis); a short
70
70
  // default kills the run mid-task and the caller re-pays the whole prompt.
@@ -669,7 +669,7 @@ export async function registerAskAntigravityTool(
669
669
  model: Type.Optional(
670
670
  Type.String({
671
671
  description:
672
- "Model alias or exact id. Friendly: 'flash', 'pro', 'gemini'. Add a tier: 'flash high'. Pin a version: '3.5 flash'. Exact: 'gemini-3.6-flash-medium'. Omit for the configured default.",
672
+ "Model alias or exact id. Omit for the configured default (gemini-4-hydrogen, fast all-rounder). Gemini 4 lines: 'gemini-4-hydrogen' (default), 'gemini-4-neon' (more capable), 'gemini-4-carbon' (most capable). Tier via suffix: 'gemini-4-carbon-high'. Legacy 'flash'/'pro' resolve to the deprecated 3.x era.",
673
673
  }),
674
674
  ),
675
675
  thinking: Type.Optional(
package/src/config.ts CHANGED
@@ -175,6 +175,11 @@ export interface AgyConfig {
175
175
  * message, and a conversation opened mid-session starts without prior
176
176
  * pi-side context. */
177
177
  digest: boolean;
178
+ /** Migration marker (issue #25): set once when a stale persisted
179
+ * digest:false from the pre-default-flip era is upgraded to the ON
180
+ * default. Presence keeps later deliberate `/agy digest off` choices
181
+ * from being re-migrated. */
182
+ digestMigrated?: boolean;
178
183
  /** Prepend pi's composed system prompt (pi tool guidance + the global
179
184
  * agent-dir AGENTS.md and ancestor AGENTS.md/CLAUDE.md) to the FIRST
180
185
  * prompt of each fresh agy conversation.
@@ -348,6 +353,22 @@ export function removeLegacyAcpBin(configFile: string = configPath()): boolean {
348
353
  return true;
349
354
  }
350
355
 
356
+ /** One-time handoff for upgraders from the digest-off default era (issue
357
+ * #25): pre-flip saves baked digest:false into config.json as a bare
358
+ * default, and silently keeping it makes mid-session handoffs lose
359
+ * history. Runs at session_start (loadConfig stays side-effect free);
360
+ * AGY_DIGEST env wins; the marker key keeps a deliberate post-migration
361
+ * `/agy digest off` from being flipped back. Returns whether a stale
362
+ * false was rewritten (caller warns once). */
363
+ export function migrateStaleDigestDefault(configFile: string = configPath()): { migrated: boolean } {
364
+ const file = readConfigFile(configFile);
365
+ if (process.env.AGY_DIGEST !== undefined) return { migrated: false };
366
+ if (file.digestMigrated) return { migrated: false };
367
+ if (file.digest !== false) return { migrated: false };
368
+ saveConfig({ digest: true, digestMigrated: true }, configFile);
369
+ return { migrated: true };
370
+ }
371
+
351
372
  /** Load config merged over defaults. Env vars override the file when set. */
352
373
  export function loadConfig(configFile: string = configPath()): AgyConfig {
353
374
  let file: Partial<AgyConfig> = readConfigFile(configFile);
@@ -39,6 +39,14 @@ export interface DriverTurnRequest extends DriverProfile {
39
39
  * resource block instead of inline prompt text (G1 on ACP). Stream-json
40
40
  * embeds the digest in the prompt string and ignores this. */
41
41
  contextBlock?: { uri: string; text: string };
42
+ /** Fresh-session variant for the ACP load-failure path (issue #25): when
43
+ * session/load fails and the driver falls back to a new session, it
44
+ * swaps prompt/contextBlock for this, so the fresh conversation still
45
+ * receives the system prompt and the full bound:false digest instead of
46
+ * answering blind. The provider prebuilds it for bound turns; the
47
+ * stream-json driver ignores it (the CLI drops stale ids silently and
48
+ * the swap point is undetectable). */
49
+ fallback?: { prompt: string; contextBlock?: { uri: string; text: string } };
42
50
  signal?: AbortSignal;
43
51
  /** Overall turn cap in minutes (default 10). Fractional values are valid
44
52
  * (tests use sub-minute caps). 0 disables the cap. */
package/src/provider.ts CHANGED
@@ -41,6 +41,7 @@ import { mapAgyToolToNative } from "./native-tools.js";
41
41
  import { toAgyEffort, type AgyModelEntry } from "./models.js";
42
42
  import { SessionStore } from "./sessions.js";
43
43
  import { detectQuotaNotice, quotaErrorMessage } from "./quota-notice.js";
44
+ import { redactText } from "./redact.js";
44
45
  import { loadConfig } from "./config.js";
45
46
  import { GATE_MARKER, mapNativeToShadow, stripMarkerFields } from "./approval-gate.js";
46
47
  import type { ApprovalDecision, ApprovalPayload, ApprovalParkApi } from "./mcp-server.js";
@@ -287,6 +288,39 @@ function stripCompactionWrapping(t: string): string {
287
288
  return t.trim();
288
289
  }
289
290
 
291
+ /** Per-part body caps so one oversized entry cannot starve the delta budget
292
+ * (issue #25: a single >8KB tool result used to erase every earlier turn).
293
+ * Head+tail keeps the result's opening and its final summary/error lines. */
294
+ const TOOL_RESULT_HEAD = 800;
295
+ const TOOL_RESULT_TAIL = 300;
296
+
297
+ function capToolResultBody(t: string): string {
298
+ if (!t) return "(no text output)";
299
+ const overflow = t.length - TOOL_RESULT_HEAD - TOOL_RESULT_TAIL;
300
+ if (overflow <= 0) return t;
301
+ return `${t.slice(0, TOOL_RESULT_HEAD)}\n[${overflow} chars elided]\n${t.slice(-TOOL_RESULT_TAIL)}`;
302
+ }
303
+
304
+ const TOOL_CALL_ARGS_CAP = 200;
305
+
306
+ function renderToolCalls(content: unknown): string {
307
+ if (!Array.isArray(content)) return "";
308
+ const lines: string[] = [];
309
+ for (const b of content) {
310
+ if (typeof b !== "object" || b === null || (b as { type?: string }).type !== "toolCall") continue;
311
+ const { name, arguments: args } = b as { name?: string; arguments?: unknown };
312
+ let argsText: string;
313
+ try {
314
+ argsText = JSON.stringify(args ?? {});
315
+ } catch {
316
+ argsText = "(unserializable args)";
317
+ }
318
+ if (argsText.length > TOOL_CALL_ARGS_CAP) argsText = `${argsText.slice(0, TOOL_CALL_ARGS_CAP)}…`;
319
+ lines.push(`[tool call: ${name ?? "?"}(${redactText(argsText)})]`);
320
+ }
321
+ return lines.join("\n");
322
+ }
323
+
290
324
  export interface DigestOptions {
291
325
  /** Provider id whose assistant turns are already in agy's own DB and so
292
326
  * must be skipped to avoid double-counting. Default "antigravity". */
@@ -321,6 +355,13 @@ export interface DigestOptions {
321
355
  /** Soft cap on the digest body when no tighter budget applies. */
322
356
  const DIGEST_MAX_CHARS = 8000;
323
357
 
358
+ /** ACP digest cap: the embeddedContext transport carried a 120k-char probe
359
+ * block with exact needle recall at both block extremities
360
+ * (scripts/probe-acp-context.mjs, 2026-11-24), so 24k is transport-safe
361
+ * and shrinks the newest-first partial-render hole. stream-json keeps
362
+ * DIGEST_MAX_CHARS: its digest rides inline under the prompt byte cap. */
363
+ const ACP_DIGEST_MAX_CHARS = 24_000;
364
+
324
365
  /** stream-json single-prompt silent-drop cap (issue #2, probed 2026-09-30):
325
366
  * the CLI drops any prompt past ~25KB with SUCCESS and an empty response,
326
367
  * and the dropped turn leaves the conversation permanently unresponsive. */
@@ -329,13 +370,13 @@ const STREAM_JSON_PROMPT_CAP = 25_000;
329
370
  const STREAM_JSON_PROMPT_MARGIN = 4_096;
330
371
 
331
372
  /** Per-engine digest cap. ACP ships the digest as an embeddedContext
332
- resource block: no prompt cap applies, so the default cap stands. On
333
- stream-json the digest rides inline in the prompt, so it must fit under
373
+ resource block: no prompt cap applies, so the probe-raised cap stands.
374
+ On stream-json the digest rides inline in the prompt, so it must fit under
334
375
  the silent-drop budget alongside the user's own prompt bytes. Returns
335
376
  null when the budget is already exhausted (ship nothing rather than a
336
377
  digest that would push the turn over the drop cap). */
337
378
  export function digestMaxCharsForEngine(engine: string, promptLength: number): number | null {
338
- if (engine === "acp") return DIGEST_MAX_CHARS;
379
+ if (engine === "acp") return ACP_DIGEST_MAX_CHARS;
339
380
  const budget = STREAM_JSON_PROMPT_CAP - promptLength - STREAM_JSON_PROMPT_MARGIN;
340
381
  return budget > 0 ? Math.min(DIGEST_MAX_CHARS, budget) : null;
341
382
  }
@@ -393,16 +434,36 @@ export function compactionFingerprint(m: Message): string {
393
434
  * Fidelity note: other-provider assistant turns contribute only their text
394
435
  * blocks; tool-call and thinking blocks are dropped. The intent (which tool)
395
436
  * is lost, but their results still surface separately as toolResult messages. */
396
- export function buildContextDigest(
437
+ export interface DigestResult {
438
+ /** Digest body, "" when nothing rendered. */
439
+ text: string;
440
+ /** First index of the delta window (after clamp adjustments). */
441
+ windowStart: number;
442
+ /** Exclusive window end (run extraction boundary). */
443
+ windowEnd: number;
444
+ /** Oldest message index whose content is actually in the digest.
445
+ * == windowStart when the whole window rendered; == windowEnd when
446
+ * nothing fit; in between when the budget cut old turns (the pi-lens
447
+ * watermark invariant: the record may only claim delivery of what
448
+ * rendered). */
449
+ deliveredFrom: number;
450
+ }
451
+
452
+ export function buildContextDigestResult(
397
453
  messages: Message[],
398
454
  watermark: number,
399
455
  opts: DigestOptions = {},
400
- ): string {
456
+ ): DigestResult {
401
457
  const own = opts.ownProvider ?? "antigravity";
402
458
  const maxChars = opts.maxChars ?? DIGEST_MAX_CHARS;
403
- if (messages.length === 0) return "";
459
+ if (messages.length === 0) {
460
+ return { text: "", windowStart: 0, windowEnd: 0, deliveredFrom: 0 };
461
+ }
404
462
 
405
463
  const deltaParts: string[] = [];
464
+ // Message index each delta part was rendered from: the budget cut has to
465
+ // report which messages actually shipped, not just how many parts.
466
+ const partIdx: number[] = [];
406
467
 
407
468
  // 1. Compaction summary (never in agy's DB, so always high-value), but
408
469
  // only when THIS summary has not shipped in a previous digest.
@@ -438,19 +499,22 @@ export function buildContextDigest(
438
499
  const m = messages[i];
439
500
  if (m.role === "assistant") {
440
501
  if (opts.bound !== false && m.provider === own) continue; // our own turn: already in agy's DB
441
- const t = blocksToText(m.content).trim();
502
+ const t = [blocksToText(m.content).trim(), renderToolCalls(m.content)].filter(Boolean).join("\n");
442
503
  if (!t) continue;
443
504
  deltaParts.push(`[assistant turn from ${m.provider}]\n${t}`);
505
+ partIdx.push(i);
444
506
  } else if (m.role === "user") {
445
507
  const t = blocksToText(m.content);
446
508
  if (t.includes(COMPACTION_MARKER)) continue; // delivered as the summary part
447
509
  if (!t.trim()) continue;
448
510
  deltaParts.push(`[earlier user message]\n${t}`);
511
+ partIdx.push(i);
449
512
  } else if (m.role === "toolResult") {
450
513
  const t = blocksToText(m.content).trim();
451
514
  deltaParts.push(
452
- `[tool result: ${m.toolName}${m.isError ? " (error)" : ""}]\n${t || "(no text output)"}`,
515
+ `[tool result: ${m.toolName}${m.isError ? " (error)" : ""}]\n${capToolResultBody(t)}`,
453
516
  );
517
+ partIdx.push(i);
454
518
  }
455
519
  }
456
520
 
@@ -467,15 +531,18 @@ export function buildContextDigest(
467
531
  summaryPart = `${summaryPart.slice(0, room)}\n${MARKER}`;
468
532
  }
469
533
  let delta = deltaParts.join(SEP);
534
+ let oldestKept = partIdx.length > 0 ? partIdx[0] : end;
470
535
  if (maxChars > 0) {
471
536
  const budget = Math.max(0, maxChars - (summaryPart ? summaryPart.length + SEP.length : 0));
472
537
  if (delta.length > budget) {
473
538
  const kept: string[] = [];
474
539
  let used = 0;
540
+ oldestKept = end;
475
541
  for (let i = deltaParts.length - 1; i >= 0; i--) {
476
542
  const cost = deltaParts[i].length + (kept.length > 0 ? SEP.length : 0);
477
543
  if (used + cost > budget) break;
478
544
  kept.unshift(deltaParts[i]);
545
+ oldestKept = partIdx[i];
479
546
  used += cost;
480
547
  }
481
548
  if (kept.length > 0) {
@@ -487,9 +554,18 @@ export function buildContextDigest(
487
554
  }
488
555
  }
489
556
 
490
- return [summaryPart, delta]
557
+ const text = [summaryPart, delta]
491
558
  .filter((s): s is string => typeof s === "string" && s.length > 0)
492
559
  .join(SEP);
560
+ return { text, windowStart: start, windowEnd: end, deliveredFrom: text ? oldestKept : end };
561
+ }
562
+
563
+ export function buildContextDigest(
564
+ messages: Message[],
565
+ watermark: number,
566
+ opts: DigestOptions = {},
567
+ ): string {
568
+ return buildContextDigestResult(messages, watermark, opts).text;
493
569
  }
494
570
 
495
571
  /** Build a fresh AssistantMessage shell for this turn. Mutated as blocks
@@ -1552,6 +1628,11 @@ async function runTurnDriver(
1552
1628
  // Summary id carried forward from the record; the gate below overwrites it
1553
1629
  // only when a digest actually ships, so skipped turns never lose it.
1554
1630
  let settleSummaryId = existing?.digestSummaryId;
1631
+ // Settle writes (both store.set paths) use these: they default to normal
1632
+ // advance semantics and the digest build overrides them when a wanted
1633
+ // digest failed to ship (see the delivery invariant at the build site).
1634
+ let nextCount = messageCount;
1635
+ let nextBoundary: string | undefined = settleBoundary;
1555
1636
 
1556
1637
  // Continuation: resolve parked round-trips from pi's toolResult messages,
1557
1638
  // then re-attach to the still-running agy turn. No new user event is sent:
@@ -1790,16 +1871,17 @@ async function runTurnDriver(
1790
1871
  // agy's server-side prompt cache.
1791
1872
  const wantDigest = (config.digest || compactionHandoff || compactionResume) && !runTruncated;
1792
1873
  const maxChars = digestMaxCharsForEngine(engine, promptBytes);
1793
- const digest =
1874
+ const digestRes =
1794
1875
  wantDigest && maxChars !== null && late.length === 0 && !resume
1795
- ? buildContextDigest(context.messages, watermark, {
1876
+ ? buildContextDigestResult(context.messages, watermark, {
1796
1877
  bound: Boolean(existing?.conversationId),
1797
1878
  seenSummaryId: existing?.digestSummaryId,
1798
1879
  maxChars,
1799
1880
  end: run.runStart,
1800
1881
  includeLast: compactionResume,
1801
1882
  })
1802
- : "";
1883
+ : undefined;
1884
+ const digest = digestRes?.text ?? "";
1803
1885
  // Byte-level fail closed (issue #2): the char budget over-reserves for
1804
1886
  // ASCII but a multibyte digest can still exceed the remaining byte
1805
1887
  // room. ACP carries no prompt cap, so the check is stream-json only.
@@ -1809,6 +1891,35 @@ async function runTurnDriver(
1809
1891
  promptBytes + STREAM_JSON_PROMPT_MARGIN + Buffer.byteLength(digest, "utf8") > STREAM_JSON_PROMPT_CAP
1810
1892
  ? ""
1811
1893
  : digest;
1894
+ // Watermark delivery invariant (issue #25 follow-up): the record may
1895
+ // only claim what reached agy. When a built digest failed the byte
1896
+ // check, nothing shipped, so the settle write HOLDS the pre-turn
1897
+ // watermark - the whole window re-offers next turn, duplicating
1898
+ // nothing because nothing arrived. (maxChars null is defensive: a
1899
+ // spent budget co-occurs with runTruncated, which skips the digest
1900
+ // deliberately.) Partial renders (budget cut the oldest turns) still
1901
+ // advance: the hole can never re-fit under the newest-first budget,
1902
+ // and re-offering it every turn would re-embed cap-sized duplicate
1903
+ // blocks into agy's DB; the hole is logged instead.
1904
+ const digestDropped = wantDigest && (maxChars === null || (digest !== "" && !digestFinal));
1905
+ if (digestDropped) {
1906
+ nextCount = existing?.lastMessageCount ?? watermark;
1907
+ nextBoundary = existing?.digestBoundary;
1908
+ }
1909
+ deps.log?.(
1910
+ "digest",
1911
+ {
1912
+ engine,
1913
+ bound: Boolean(existing?.conversationId),
1914
+ maxChars,
1915
+ bytes: digestFinal ? Buffer.byteLength(digestFinal, "utf8") : 0,
1916
+ windowStart: digestRes?.windowStart,
1917
+ windowEnd: digestRes?.windowEnd,
1918
+ deliveredFrom: digestRes?.deliveredFrom,
1919
+ shipped: Boolean(digestFinal),
1920
+ },
1921
+ digestDropped ? "warn" : "info",
1922
+ );
1812
1923
  // The delivered summary id persists only when a digest actually shipped:
1813
1924
  // late/resume/budget-skipped turns carry the previous id forward so the
1814
1925
  // summary is not lost to a turn that never delivered it.
@@ -1867,6 +1978,40 @@ async function runTurnDriver(
1867
1978
  // prompt is text-only); user-message images ride them on ACP natively
1868
1979
  // and staged files on stream-json.
1869
1980
  const runImages = [...images, ...late.flatMap((l) => l.images ?? [])];
1981
+ // Issue #25: an ACP session/load failure silently creates a fresh agy
1982
+ // conversation mid-turn, and the bound-mode prompt (G10 gate closed by
1983
+ // the binding, bound:true digest skipping own turns) would ship blind.
1984
+ // This variant is built as-if-fresh; the driver swaps it in only when
1985
+ // the load actually fails. stream-json cannot detect that drop, so it
1986
+ // is ACP-only.
1987
+ const requestConversation = redeliveryConversation ?? existing?.conversationId ?? null;
1988
+ const acpFallback =
1989
+ deps.engine === "acp" && requestConversation && !resume && late.length === 0
1990
+ ? (() => {
1991
+ const fbSys = config.systemPrompt
1992
+ ? getCurrentSystemPrompt(context.messages) || undefined
1993
+ : undefined;
1994
+ const freshDigest = wantDigest
1995
+ ? buildContextDigestResult(context.messages, 0, {
1996
+ bound: false,
1997
+ maxChars: ACP_DIGEST_MAX_CHARS,
1998
+ end: run.runStart,
1999
+ includeLast: compactionResume,
2000
+ })
2001
+ : null;
2002
+ // Both features off: the variant would equal the plain prompt.
2003
+ if (!fbSys && !freshDigest?.text) return undefined;
2004
+ return {
2005
+ prompt: buildFullPrompt(fbSys, "", deliveredPrompt) + stageImageNote(runImages),
2006
+ contextBlock: freshDigest?.text
2007
+ ? {
2008
+ uri: `urn:pi-bridge:context-digest/fresh/${messageCount}`,
2009
+ text: `${DIGEST_PREAMBLE}\n\n${freshDigest.text}`,
2010
+ }
2011
+ : undefined,
2012
+ };
2013
+ })()
2014
+ : undefined;
1870
2015
  const fullPrompt =
1871
2016
  (late.length > 0
1872
2017
  ? buildLateResultPrompt(late, deliveredPrompt || undefined)
@@ -1885,6 +2030,7 @@ async function runTurnDriver(
1885
2030
  prompt: fullPrompt,
1886
2031
  images: runImages.length > 0 ? runImages : undefined,
1887
2032
  agent,
2033
+ fallback: acpFallback,
1888
2034
  contextBlock: embeddedDigest
1889
2035
  ? {
1890
2036
  uri: `urn:pi-bridge:context-digest/${messageCount}`,
@@ -1950,8 +2096,8 @@ async function runTurnDriver(
1950
2096
  store.set(key, {
1951
2097
  conversationId: parkedConv,
1952
2098
  lastStepIdx: -1,
1953
- lastMessageCount: messageCount,
1954
- digestBoundary: settleBoundary,
2099
+ lastMessageCount: nextCount,
2100
+ digestBoundary: nextBoundary,
1955
2101
  digestSummaryId: settleSummaryId,
1956
2102
  });
1957
2103
  deps.pendingCompactionHandoff?.delete(key);
@@ -2080,8 +2226,8 @@ async function runTurnDriver(
2080
2226
  store.set(key, {
2081
2227
  conversationId: outcome.conversationId,
2082
2228
  lastStepIdx: -1,
2083
- lastMessageCount: messageCount,
2084
- digestBoundary: settleBoundary,
2229
+ lastMessageCount: nextCount,
2230
+ digestBoundary: nextBoundary,
2085
2231
  digestSummaryId: settleSummaryId,
2086
2232
  });
2087
2233
  deps.pendingCompactionHandoff?.delete(key);