Skip to content

Fix/context federation hardening rebased - #105

Merged
deepagent-ai merged 7 commits into
devfrom
fix/context-federation-hardening-rebased
Aug 8, 2026
Merged

Fix/context federation hardening rebased#105
deepagent-ai merged 7 commits into
devfrom
fix/context-federation-hardening-rebased

Conversation

@deepagent-ai

Copy link
Copy Markdown
Contributor

Issue for this PR

Closes #

Type of change

  • Bug fix
  • New feature
  • Refactor / code improvement
  • Documentation

What does this PR do?

Please provide a description of the issue, the changes you made to fix it, and why they work. It is expected that you understand why your changes work and if you do not understand why at least say as much so a maintainer knows how much to value the PR.

If you paste a large clearly AI generated description here your PR may be IGNORED or CLOSED!

How did you verify your code works?

Screenshots / recordings

If this is a UI change, please include a screenshot or recording.

Checklist

  • I have tested my changes locally
  • I have not included unrelated changes in this PR

If you do not follow this template your PR will be automatically rejected.

deepagent-ai and others added 7 commits August 8, 2026 09:50
…e comparison

BUG-007 closed the gap between an overflow estimator and the request that actually reaches the provider. A model context value of zero is an unknown limit, invalid limits are not treated as usable capacity, and every provider turn now checks the complete serialized request before dispatch.

Implementation:
- expose a typed requestBudget result with physical input budget, reserved output, safety margin, and limit provenance;
- use a bounded host guard for unknown context limits and fail closed for invalid or exhausted budgets;
- add the explicit guard soft-landing action and map the preflight failure to ContextOverflowError;
- preserve raw-token phase comparisons and cover unknown, invalid, output-reserved, and guard-state cases in deterministic tests.

The provider is never called after an unavailable budget decision. This commit does not claim provider/model-matrix or credentialed LLM evidence; those remain release gates.
… PromptEpoch authority

BUG-005 makes compaction recovery and history selection durable. The marker, compaction_run state, summary boundary, and PromptEpoch now have explicit ownership and fail-closed transitions instead of relying on an in-memory generation or a best-effort marker write.

Implementation:
- recover requested, summarizing, and in-flight summary states after process restart and mark ambiguous provider work indeterminate;
- create or adopt one durable run per marker, persist the marker part, and stop when a run is indeterminate or no longer matches the active session;
- commit the settled summary and PromptEpoch checkpoint in one immediate transaction with CAS checks;
- make PromptEpoch.activateInTransaction the only epoch transition authority and make promptHistoryEffect validate the checkpoint, summary, compaction marker, and retained tail before projecting history.

The runtime source and schema are now aligned with the durable lifecycle. Deterministic compaction, PromptEpoch, and migration tests cover the state transitions; real-provider crash/restart evidence remains a separate release gate.
…d SummaryProtocolViolation + bounded retry

BUG-006 prevents a summary provider turn from silently becoming a tool-bearing turn and prevents protocol failures from being serialized as an untyped message prefix. Summary dispatches are durable physical attempts with a hard limit of two; a retry gets a fresh assistant message and a new attempt identity.

Implementation:
- make the summary request text-only with toolChoice="none" and reject every tool-input start/delta/end and tool-call/result/error event through the typed SummaryProtocolViolation error;
- preserve the typed failure through processor.processSummary and the compaction retry boundary instead of parsing message text;
- persist prepared, dispatching, streaming, settled, failed, and indeterminate-after-crash attempt states and bound one logical summary run to two physical provider dispatches;
- assert the contract, retry budget, fresh-message behavior, and terminal failure state in deterministic tests.

Provider credentials and a real model's willingness to violate the summary protocol are not covered by this commit; the deterministic oracle is the release gate for the control-flow contract.
…e policy for federation orDie

BUG-008 closes the fail-open paths around context federation. Rollout decisions now require observed runtime readiness, and projection/resolve/prepare failures degrade to an explicit legacy request without claiming that the federated attempt or projection was durable.

Implementation:
- derive readiness from the live location index, coordinator status, database probe, and TTL rather than from rollout configuration alone;
- activate project rollouts against that readiness snapshot and remove v2 context tools only when the required facade is unavailable or not ready;
- preserve legacy code_intel when v2 is cold or degraded;
- convert federation resolve and provider-attempt preparation failures into typed, observable degraded outcomes and keep the request fail-closed when a projection constraint cannot be prepared;
- add contract, registry, and route-manifest coverage for ready, degraded, unavailable, and fallback states.

No claim is made that every deployment topology has live readiness telemetry; those packaged/runtime checks remain a separate release gate.
…ness-aware fallback

BUG-009 makes the final provider request auditable and closes the remaining v2 fallback gap. A receipt is created before each physical request, updated only through compare-and-set state transitions, and correlated with the assistant and observed tool call IDs. The same turn records the final offered tool set, adapter lowering outcome, and complete-request budget decision.

Implementation:
- persist the request ordinal, provider/model, protocol, registry and permission-filtered tool IDs, final tool definitions, budget provenance, provider-attempt ID, and request state in session_tool_request_receipt;
- update prepared, dispatched, and rejected receipts at the production prompt/LLM boundary and backfill every observed tool call ID after the turn;
- map ContextOverflowError through MessageV2 serialization so a budget rejection remains typed at the session boundary;
- retain v1 code_intel when v2 is unavailable and keep readiness/federation decisions explicit in the prompt and registry integration;
- add deterministic receipt, tool-inclusion, migration, fallback, and prompt-boundary assertions;
- extend the credentialed compaction-retention real-LLM suite to inspect committed compaction runs, durable summary attempts, the active PromptEpoch, and the dispatched receipt correlated with the observed write call.

The deterministic tests and route ownership checks are executable locally. The real-LLM oracle is implemented but still requires the qualified provider credentials and sandbox; packaged-runtime parity and crash/restart evidence remain separate release gates.
… hard bound

Co-authors: commits 7dee50a (plan state/live update loop) + 8fbf1bf (plan-gate warn-only).

Fix-A: strict plan semantic admission + compare-and-commit boundary
- strict v2 PlanWriteInput schema (operation/create/advance/replan,
  explicit expected_plan_id/expected_version, replan_reason length guard)
- compareAndCommitPlan(): atomic precondition-check + semantic-validate
  + commit in single await-free boundary; CAS rejects stale writers and
  malformed candidates
- A/B/C quality oracle: Unicode code-point structural info-loss detection
- last-known-good: invalid write never replaces authority, clears latch,
  or creates a new version
- durable human edit mailbox: HTTP envelope with request_id/challenge_id
  idempotency, terminal settlement, typed conflict/busy/unavailable receipts
- cross-version request idempotency; migration fail-closed quarantine
- goal-status-publisher demoted to read-only projection (no new plan versions)
- SessionState.setPlan() call-boundary tests documenting the legacy compat seam

Fix-B: activity-scoped plan protocol tracker + PlanProtocolViolation terminal
- PlanProtocolTracker: per-activity ordinal counter shared across
  runLoop/compaction/steer; schema-decode failure before execute() counts
- first invalid attempt: correctable tool-level error with attempt_ordinal
  injected into output text so the model sees it ("[Plan attempt N of 2]")
- second consecutive invalid/no-progress: PlanProtocolViolationError —
  non-retryable activity-level terminal; finish="error"; no compaction/retry
- PlanProtocolViolation in Session error schema + MessageV2.fromError()
  + DB persistence + reload round-trip test (does NOT degrade to UnknownError)
- section 9.3 deterministic incident fixture (both original and
  forward-compatible payloads): proves physical Provider dispatch <= 2

Fix-C: plan snapshot recovery + App identity/version cursor
- GET /session/:sessionID/plan snapshot endpoint (PlanStore authority)
- plan.updated carries plan_id + plan_version from same DocumentStore ref
- App session-sync fetches snapshot after live subscription using a
  request-baseline cursor: in-flight live events win; stale old-identity
  snapshots cannot roll back a newer live state
- different-identity live event rejected by admission AND triggers
  recalibrateSessionPlan() for a fresh snapshot; tests added
- publish failure observable (warning metric); snapshot self-heals on reload
- JS SDK regenerated with snapshot endpoint types

Fix-D: Provider argument provenance 4-layer receipt
- session_tool_argument_receipt table + migration (20260807090000)
- raw_frame / adapter_assembly / ai_sdk_input / processor_decoded layers
- unavailable_reason required when adapter does not expose raw callback
- hash+length+keys stored; no raw payload, no prompts, no secrets
- receipt write failure does not abort Provider turn

Verification:
- core: 775 pass / 0 fail
- deepagent-code: 1190 pass / 2 fail (pre-existing live-API network
  failures in tool.task_status, not from this work)
- app: 665 pass / 0 fail
- bun typecheck: exit 0 in all three packages

Release note (combined with 7dee50a + 8fbf1bf):
When a Provider returns malformed plan arguments (empty titles, unknown
status, single-step placeholders), the plan tool now rejects them
semantically before committing. The model receives one correctable error
with its attempt ordinal; a second consecutive failure terminates the
activity immediately with PlanProtocolViolation — no further Provider
dispatches occur. The App recovers from the last authoritative snapshot
on reload or reconnect, even if live events were missed.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
@github-actions

github-actions Bot commented Aug 8, 2026

Copy link
Copy Markdown

This PR doesn't fully meet our contributing guidelines and PR template.

What needs to be fixed:

  • No "Type of change" checkbox is checked. Please select at least one.
  • No issue referenced. Please add Closes #<number> linking to the relevant issue.
  • "How did you verify your code works?" section is empty. Please explain how you tested.
  • Not all checklist items are checked. Please confirm you have tested locally and have not included unrelated changes.

Please edit this PR description to address the above within 2 hours, or it will be automatically closed.

If you believe this was flagged incorrectly, please let a maintainer know.

@github-actions

github-actions Bot commented Aug 8, 2026

Copy link
Copy Markdown

Hey! Your PR title Fix/context federation hardening rebased doesn't follow conventional commit format.

Please update it to start with one of:

  • feat: or feat(scope): new feature
  • fix: or fix(scope): bug fix
  • docs: or docs(scope): documentation changes
  • chore: or chore(scope): maintenance tasks
  • refactor: or refactor(scope): code refactoring
  • test: or test(scope): adding or updating tests

Where scope is the package name (e.g., app, desktop, deepagent-code).

See CONTRIBUTING.md for details.

@deepagent-ai
deepagent-ai merged commit 4717456 into dev Aug 8, 2026
5 of 13 checks passed
@deepagent-ai
deepagent-ai deleted the fix/context-federation-hardening-rebased branch August 8, 2026 14:58
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant