Skip to content

feat(dream): verified shared harness, immutable corrections, and all-user cleanup - #21480

Merged
Git-on-my-level merged 37 commits into
mainfrom
lane/dream-fold-cleanup
Oct 15, 2026
Merged

Git-on-my-level merged 37 commits into
mainfrom
lane/dream-fold-cleanup

Conversation

@Git-on-my-level

@Git-on-my-level Git-on-my-level commented Oct 14, 2026 •

Copy link
Copy Markdown
Member

Dream v2 replaces K=3 planning and the bounded/full split with one owner-scoped shaped-agent session, immediate tool feedback and repair, two independent evidence verifiers, and journaled reversible effects. This is the complete architecture in PR #21480, with eligibility all and no phased rollout. Reviewed by an Opus architecture review and a Grok code review; all blockers and majors from both are addressed in this PR.

Architecture

  • Neutral utils/agent_capabilities owns uniform seen refs, bounded search/read, guarded edits and journal/Undo. A per-kind registry declares schema semantics, validation, key, apply, Undo, display, default policy and allowed fields. Dream injects its prompt, seed, size policy and Review attention/ranking. Chat mounting remains a follow-up integration. Explicit owner requests bypass autonomous never-redo/cleanup protections while keeping source, account-generation and privacy fences.
  • The six tools are search, read, propose_edit, ask, learn_term and finish. Tool errors expose code/field/ref/expected/retryable; infrastructure errors are not model-retryable. Same-turn finish processes all other calls and is ignored after rejection so repair can continue. Token/USD accounting bounds spend; 64 turns are a loose backstop. Search hydration counts against read bytes and capture similarity work is bounded.
  • Two verifiers use independent audit/falsification framing and see cited evidence with minimal context, excluding proposer reasons and each other's results. Both agree plus eligibility and no Undo demotion permits apply. A true boolean split or agreed demoted proposal competes for value-ranked Review slots; values 1–2 never appear. Missing, invalid or zero votes remain unverified and are neither applied nor offered. Two disagreements drop.
  • Reasoning and verify use dedicated Gemini capacity with the exact configured Luna-only non-Gemini fallback. Both lanes recover consistently from reservation outages and dedicated 429s. No company pay-as-you-go Gemini route is introduced. Tools/results and nested schemas cross the Vertex wire; a stable prefix uses provisioned-throughput implicit caching with observed and unknown usage accounted separately.
  • Captured speech remains unchanged. Encrypted overlays are mirrored inline on conversations, avoiding a per-corrected-row fetch; legacy sibling overlays remain readable. Corrupt/unavailable read projections render original speech and count the failure. Writers stay strict. Owner segment edits have headroom beyond the autonomous entry cap. Dependent corrections cannot be undone underneath later edits. Apply/Undo rebuild projected transcript vectors and sync the conversation index.
  • Speaker-only final-pass promotion preserves captured IDs, clocks and speech while retaining corrections. Explicit manual merges relocate overlay anchors and Undo receipts atomically after processing; moved sources refuse new corrections and recovery retains the destination. New Review kinds retain the released edit response branch/enum, with additive typed operation data for current clients. Empty-after retirements show the localized removed state in Recent Changes and the Dream report.
  • Automatic kinds: spelling, title, overview, vocabulary, merge_memories, retire_memory, supersede_memory, dismiss_person, merge_people, merge_tasks, retire_task, merge_conversations and set_language. User-authored memories require explicit acceptance; autonomous task/person cleanup protects manual, edited, linked, recurring, confirmed and voice records. Cleanup Undo fences owned fields and generation while preserving unrelated writes. Duplicate captures use hide-with-link and retain audio. Memory lifecycle/merges atomically commit predecessor/tail/graph/outbox/journal effects.

All-user admission and default arithmetic

dream_due is a durable queue ordered by backlog/staleness-adjusted due time. Dirty writes enqueue with that priority. Independent discovery initializes missing rows in 20 pages of 499 owners per hourly sweep (9,980 owners/sweep), without waiting for model sessions. Due hunts remain queued (daily; six-hour cadence for heavy owners); capped users are rescheduled rather than occupying the queue head. Leases retain stale-reclaim and late-effect fences.

Defaults: 2,000,000 reserved tokens/minute, expected 12,000 tokens/session, $0.00001 configured ceiling/token, $10/owner/day and $15,000 globally/day. Admission initially holds the expected $0.12, rather than the 256k-token session ceiling. Before each turn, a transaction tops up the owner and one of 64 fixed global spend shards; shard quotas sum to the global cap. Turns settle to actual accounted use and release unused minute holds; unknown attempts retain their charge. The env kill switch and dream_control/global.enabled jointly control all hosts with a ten-second last-known cache.

At an assumed 120-second session, concurrency derives to ceil(2,000,000 / 12,000 × 2) = 334 (maximum 512). A 28-minute drain each hour gives a token-capacity upper bound of 4,667 expected sessions/hour, or 112,000/day. An explicitly hypothetical 100,000 due-owner population at one expected session/day costs $12,000/day at the configured ceiling, within the $15,000 cap; initial discovery needs 11 hourly sweeps. These are planning bounds, not measured user counts or a live throughput guarantee. Larger sessions, heavy-user cadence, provider contention and exhausted caps leave work queued fairly.

Synthetic replay receipts use scripted serialized bytes divided by four, with no provider calls. Light/medium/heavy one-turn fixtures account for 5,435 / 5,436 / 5,436 tokens, respectively, including two verifier calls: $0.05435 / $0.05436 / $0.05436 at the configured ceiling. The larger recurring-name fixture discovers 90 captures, repairs one rejection and applies 25 changes across eight turns/four verifier calls: 68,768 accounted tokens, $0.68768. These validate accounting mechanics and workload bounds, not actual bills, cache savings or model quality.

Folded maintenance

Retired: semantic consolidation planning/candidate discovery, semantic retries/quarantine, cooldown/overflow orchestration and maintenance-host Dream draining. Retired selector/runtime bindings are removed. Memory hygiene uses verifier decisions instead of unanimity.

Kept: deterministic TTL; explicit required-intake normalization/completion; committed projection outboxes and queued recurrence delivery; daily new-fact formation/standing triggers; stranded finalization; ingest prevention, speaker teaching and task refresh; retention, privacy/deletion and X ingestion. The dev maintenance schedule still owns required deterministic work. Newly dead .github workflows: none. No workflow source was authored. Inventory: backend/docs/runbooks/dream-cleanup-fold.md; architecture/rollback: backend/docs/runbooks/dream-agent.md.

Validation

Passed: focused backend suites (the final 11-file run has 324 passing tests, including all 16 review regressions), 16 loopback Firestore SDK tests, 48 Flutter Review tests, all four OpenAPI export checks, released app-client compatibility, generated Dart/Swift/TypeScript checks, and current Pyright with zero errors. The full backend suite completed once across 1,824 files: 26 files initially failed. Functional failures were fixed and passed targeted reruns. The final outstanding CPU-only failures are canonical memory vectors, vector filters, voice-message cleanup and wrapped-error sanitization; all four reproduce against pinned main 1b25b59d2d41c7fe297a0889aab4e4c8bdf685a9 with the unchanged 0.30-second guard. No test threshold, allowlist or gate was relaxed. Full-tree module-stub inspection also finds two existing violations in apps-exception-hardening/task-integrations-sanitization on both this branch and pinned main; changed-file inspection passes.

The canonical preflight manifest selected 74 checks. Of these, 73 have passing receipts, including reruns after fixing runtime-env composition, dead code and local Flutter telemetry setup. The product line-count ratchet cannot complete because synthetic-merge temporary Git objects are outside this sandbox. The supervisor must run that check with the normal commit/push and exact-head CI. Proposed line-count allowance text is also in .agent-brief/pr-body-additions.md; its synthetic-merge counts still need the supervisor's check.

Not verified: deployed capacity/coverage, actual provider bills or cache hits, model precision, physical-device acceptance, or store-distributed decoder capture. Loopback HTTP and simulator evidence from the architecture implementation are synthetic, not production acceptance. Rollback is the kill switch plus previous image; keep correction overlays/receipts and account for older images without projection display.

Product invariants

  • INV-MEM-4: reversible canonical lifecycle under source/privacy/head/generation fences; required intake, TTL and outboxes retain their owners.
  • INV-MEM-1: one canonical lifecycle and current-read visibility, with retired history retained.
  • INV-UI-3: localized Review before/after, surrounding speech and reachable Undo/Redo for automatic changes.

Failure-Class: none

These fixes address the unshipped architecture introduced in this PR; they do not establish a separate production incident or failure-class registry entry.

Synthetic applied changes in the Dev simulator

Synthetic post-Undo Redo state

Line-Count-Exception: backend/database/conversation_finalization_jobs.py | 2635 -> 2652 | Bind client projections to the correction overlay in the existing finalization transaction, so a concurrent correction cannot admit stale client output.
Line-Count-Exception: backend/database/conversations.py | 3985 -> 4015 | Preserve captured transcript identities and projection fences at their transaction owners; registry and overlay transfer logic live in separate modules.

@mintlify

mintlify Bot commented Oct 14, 2026 •

Copy link
Copy Markdown

Preview deployment for your docs. Learn more about Mintlify Previews.

Project Status Preview Updated
omi 🟢 Ready View Preview Oct 15, 2026, 5:56 AM

💡 Tip: Enable Automations to automatically generate PRs for you.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 14, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-15T06:53:35.953293Z 79783ed New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@Git-on-my-level Git-on-my-level changed the title feat(dream): add full-owner memory hygiene and cleanup inventory feat(dream): build verified all-user agent harness and fold cleanup Oct 14, 2026

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

One high-severity finding: the new memory-hygiene Review journal stores canonical memory snapshots outside the encrypted field allowlist.

Open in Web View Automation 

Sent by Cursor Security Agent: Security Reviewer

Comment on lines +190 to +202
'memory_hygiene': {
'edit': edit.model_dump(exclude={'value'}),
'before': before,
'after': after,
'graphs': graphs,
'source_generation': generation,
},
'revision': 0,
}
data['memory_hygiene']['after_graphs'] = {
key: (None if key == target_id or key == new_id else graph) for key, graph in graphs.items()
}
tx.set(ref, store.encode_doc(uid, data))

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔒 Agentic Security Review
Severity: HIGH

The new Review journal writes full canonical MemoryItem before/after snapshots (content, evidence, lineage) plus graph assertions under top-level memory_hygiene, then calls encode_doc(). Encryption only covers _CONTENT_FIELDS (item, source, change, edits, before, memory_edit, summary). memory_hygiene is not in that set, so those snapshots land as plaintext Firestore JSON on users/{uid}/review_changes/{id}.

Sibling Review writers store the same class of snapshots in encrypted before / memory_edit. This path therefore creates an at-rest copy of owner memory facts in a collection the rest of Review keeps ciphertext-only. Undo/redo rewrites the same unencrypted blob, including undone_rows.

Impact: Operators, backups, or Firestore exports of review_changes can read owner memory facts that existing Review journals keep encrypted. Reachable on auto-apply and on accepted Review answers for the journal retention window.

Fix in Cursor Fix in Web

Reviewed by Cursor Security Reviewer for commit 513bd13. Configure here.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 513bd13079

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +114 to +118
source_type='agent_conclusion',
source_id=change.change_id,
source_version='v1',
artifact_preservation=ArtifactPreservationState.not_applicable,
quote_refs=[{'ref': ev} for ev in edit.evidence],

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Bind generated facts to their conversation evidence

When an automatic supersede_memory creates a replacement from conversation evidence, this records the Review change ID as source_id and keeps the conversation references only in quote_refs. Canonical conversation deletion and reprocessing discover affected rows through MemoryItem.source_ids, which is computed exclusively from each evidence object's source_id and conversation_id, so the new active fact is absent from the conversation's source cohort and can remain stored and projected after its supporting conversation is deleted. Persist the cited conversation identities in the canonical evidence fields used by source replacement.

Useful? React with 👍 / 👎.

Comment thread backend/models/dream_edit.py Outdated
Comment on lines +131 to +132
if self.kind == 'supersede_memory' and bool(self.other) == bool(self.after.strip()):
raise ValueError('Supersede requires exactly one of other or after')

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Normalize after before selecting the replacement path

For supersede_memory with a valid other reference and whitespace-only after, this validator treats after as empty and accepts the payload, but record_change later tests the unstripped string's truthiness and attempts to create an additional replacement tail containing blank content. That tail fails MemoryItem validation, causing an otherwise valid existing-memory supersession to be reported as invalid evidence. Strip the field during validation or use after.strip() consistently when deciding whether to create a tail.

Useful? React with 👍 / 👎.

Comment on lines +23 to +25
def commit_review_memory_items(
transaction, db_client, uid, operation_id, items, *, source_generation, stamp=False, new_evidence=None
):

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Keep reversal rows aligned with their projection commit

Undo and redo call this bridge with the default stamp=False, so restored active rows retain a historical ledger_commit_id while their new vector outbox event carries the reversal commit ID. The outbox worker writes that event commit into vector metadata, but hydrate_and_filter_vector_hits requires the vector commit to equal the authoritative item's ledger_commit_id; consequently an undone retirement/supersession is rejected as a stale projection and disappears from vector-backed memory search. Either stamp the restored row with the reversal commit or emit projection metadata matching the deliberately restored ledger stamp.

Useful? React with 👍 / 👎.

Comment thread backend/utils/dream_reads.py Outdated
# The shared reader already orders newest first, bounds scans, and enforces
# current/default visibility. Rehydrate through Dream's owner-scoped reader.
try:
rows = MemoryService().read(uid, limit=100, authoritative=True)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Use the bounded memory-list reader for Dream context

For every full-context pass this selects authoritative=True, whose CanonicalMemoryBackend.read_authoritative path calls read_canonical_memories; that function materializes the user's entire canonical memory_items collection before applying the requested limit. Thus limit=100 does not bound Firestore reads, and owners with large histories incur a full collection scan on each Dream run, increasing cost and risking the long pass timing out before planning. Use the keyset-bounded list path, or add a genuinely bounded authoritative query for the newest 100 visible rows.

Useful? React with 👍 / 👎.

Comment on lines +190 to +194
'memory_hygiene': {
'edit': edit.model_dump(exclude={'value'}),
'before': before,
'after': after,
'graphs': graphs,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Encrypt the memory hygiene journal payload

This stores complete before/after MemoryItem snapshots and graph assertions under a new top-level memory_hygiene key, but review_store.encode_doc encrypts only keys listed in _CONTENT_FIELDS, which does not include memory_hygiene. As a result, memory content, provenance, and the proposed edit are written in plaintext to review_changes, despite the journal being described as encrypted. Register the new payload as an encrypted content field or place it inside an already encrypted envelope.

Useful? React with 👍 / 👎.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 66698aa11f

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +87 to +90
target = fact(uid, target_id, before[target_id])
if target.status != MemoryItemStatus.active:
raise store.ReviewConflict('Memory has a newer edit')
now = max(datetime.now(timezone.utc), target.updated_at, target.valid_from or target.captured_at)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Respect ledger authority before retiring facts

For an automatic full-context retirement or supersession targeting a direct_user_statement, explicit_remember, or onboarding fact, this gate checks only that the row is active and then closes it. Those sources outrank agent conclusions in models/knowledge_ledger_policy.py, and the existing daily reconciliation path explicitly enforces that ordering in _target_authority; bypassing it lets a background model silently replace a user-authored fact. Refuse the mutation or require Review whenever the proposed authority is lower than the target's authority.

Useful? React with 👍 / 👎.

Comment on lines +124 to +128
fresh = target.model_copy(
update={
'memory_id': new_id,
'content': edit.after,
'evidence': [evidence, *target.evidence],

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Reclassify replacement sensitivity before emitting outboxes

When supersede_memory introduces free-form after text whose sensitivity differs from the old fact—for example, a conversation-derived health fact replacing an ordinary unslotted fact—model_copy inherits the target's sensitivity_labels without inspecting the new content. memory_item_outbox_events consequently emits vector/projection upserts whenever those inherited labels are unrestricted, potentially sending newly sensitive conversation content to an external provider. Derive sensitivity from the replacement content/evidence or fail closed before committing the active tail.

Useful? React with 👍 / 👎.

'superseded_by': None,
'canonical_memory_id': None,
'user_asserted': False,
'write_reason': LedgerWriteReason.agent_reusable_conclusion,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Mark background replacement tails as daily reconciliation

For a new tail created by the scheduled background Dream pass, labeling it agent_reusable_conclusion gives it authority rank 400 rather than the daily_reconciliation rank 300. The sweep's _target_authority then treats subsequent daily reconciliation candidates as lower authority and refuses to amend this row, so a Dream-generated fact can remain current even when later reconciliation has newer evidence. Use the background reconciliation write reason for this path rather than the request-serving agent-conclusion reason.

Useful? React with 👍 / 👎.

Comment on lines +133 to +136
'captured_at': now,
'updated_at': now,
'valid_from': now,
'valid_to': None,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve the replacement fact's effective time

When conversation evidence says a replacement became true before the Dream run—for example, “Since January, lives in New Toytown” processed in October—this assigns the processing timestamp as valid_from and also closes the predecessor at that timestamp. Historical and as-of reads therefore report the old fact as valid for the intervening months even though the generated text explicitly describes an earlier transition. Carry a validated effective time from the cited evidence or require a structured time field instead of using wall-clock apply time.

Useful? React with 👍 / 👎.

Comment thread app/lib/backend/schema/review.dart Outdated
Comment on lines +328 to +331
before: hygiene != null && (_str(edit['before']) ?? '').isEmpty ? targetLabel : _str(edit['before']) ?? '',
after: hygiene != null && (_str(edit['after']) ?? '').isEmpty && kind == 'supersede_memory'
? _str(json['other_label']) ?? ''
: _str(edit['after']) ?? '',

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Show complete facts before accepting hygiene proposals

When a retirement omits before, or a supersession references an existing other fact, the client substitutes target_label/other_label for the current and suggested values. The backend truncates each of those labels to 180 characters, while canonical facts can be much longer, so qualifiers beyond that prefix are hidden even in the detail sheet and the user may approve retiring or replacing a materially different fact. Send the validated full fact contents in the hygiene payload and reserve labels for compact card headings.

Useful? React with 👍 / 👎.

description='Retire garbage (not merely low-importance facts), facts misattributed from another speaker, or facts contradicted by evidence. Supersede an old fact only with a newer time-scoped fact about the same attribute; age alone is not staleness.'
)
target: str = Field(description=Edit.model_fields['target'].description)
before: str = Field(default='', description=Edit.model_fields['before'].description)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Make hygiene suppression independent of optional before

When the model alternates between omitting before—which this schema explicitly permits—and supplying the exact target content, the same retirement or supersession receives different edit_key values because edit_key() hashes before. After the user dismisses or undoes the first form, its suppression marker therefore does not block the second form, allowing a later unanimous Dream pass to reapply the same lifecycle change and, for text replacements, create another tail. Build hygiene keys from the canonical target and replacement identity/content while excluding this optional snapshot field.

Useful? React with 👍 / 👎.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 5c60326a1e

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread backend/database/conversations.py Outdated
Comment on lines 779 to 780
if is_soft_deleted(conversation) or conversation.get('dream_duplicate_of'):
return False

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Keep duplicate captures in portability exports

When Dream sets dream_duplicate_of, this unconditional visibility check also filters the row when include_discarded=True. The streaming account export calls iter_all_conversations(uid, include_discarded=True), which still passes every row through this predicate, so the redundant capture’s transcript and metadata are omitted from the supposedly exhaustive portability export even though this cleanup intentionally preserves both recordings. Hide these rows from normal product reads without excluding them from export/compliance reads.

Useful? React with 👍 / 👎.

Comment on lines +171 to +174
edit_key=key,
expected_documents={document_id: raw},
expected_records=fences,
exact_undo=True,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Revalidate the merge survivor on redo

For merge_tasks and merge_conversations, only the retired target is placed in the exact Undo/Redo journal; the initial expected_records snapshot of other is not retained as a reversal fence. After undo, the user can delete or materially edit the survivor and then press Redo: the target still matches its fence, so Redo hides it again and writes superseded_by/dream_duplicate_of pointing at a missing or now-incompatible record. Persist and validate the survivor’s state for Redo, or reject Redo when it is no longer an eligible survivor.

Useful? React with 👍 / 👎.

Comment thread backend/utils/dream_cleanup_edits.py Outdated
'updated_at': now,
}
elif edit.kind == 'merge_conversations':
patch = {'dream_duplicate_of': edit.other.split('/', 1)[1]}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Exclude Dream duplicates from conversation counts

A merge_conversations cleanup only adds dream_duplicate_of, so the normal list filters the target in is_visible_conversation, but get_conversations_count still counts it: that aggregation filters on discarded and subtracts only deleted == true tombstones. After any such merge, /v1/conversations/count and the folder/starred search overview counts exceed the number of conversations their corresponding lists can render, which can break pagination and archive totals. Account for this new hidden state in the count path.

Useful? React with 👍 / 👎.

Comment on lines +174 to +176
exact_undo=True,
)
return 'applied'

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Invalidate cached task lists after cleanup writes

When merge_tasks or retire_task commits, this path writes action_items directly through the Review transaction and returns without calling bump_action_items_list_version. The /v1/action-items cache is versioned specifically by that counter, so an already-cached page can continue returning the now-deleted task—and Undo/Redo can likewise return the previous state—until the cache TTL expires (30 seconds by default and configurable up to 300). Bump the version after each successful task cleanup or reversal.

Useful? React with 👍 / 👎.

Comment on lines +135 to +136
'captured_at': now,
'updated_at': now,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Reset short-term expiry for replacement tails

When supersede_memory creates a new tail from a short-term fact, model_copy inherits the predecessor’s expires_at while moving captured_at to now. If the active short-term row is already past its TTL—which default reads explicitly continue exposing while adjudication is pending—the subsequent MemoryItem validation rejects the replacement because expires_at <= captured_at; even before expiry, the new fact receives only the predecessor’s remaining lifetime. Set a fresh short-term expiry from the replacement capture time while continuing to preserve the original tier.

Useful? React with 👍 / 👎.

Git-on-my-level and others added 6 commits October 14, 2026 19:54
…ad bounds

- Route retire/supersede of user-authored facts (direct_user_statement,
  explicit_remember, onboarding) through Review instead of unanimous
  auto-apply, mirroring the daily sweep's authority ordering
- Normalize whitespace-only supersede after-text at every typed boundary so
  validators, apply path and edit keys agree; existing-fact supersession
  with blank after no longer attempts a blank replacement tail
- Give short-term replacement tails a fresh expiry from their own capture
  time instead of inheriting a possibly-past predecessor expires_at
- Use the bounded keyset memory list for Dream full-context passes instead
  of the full-collection authoritative seam
- Keep Dream duplicate captures in export/compliance reads while folding
  them out of product reads
@Git-on-my-level Git-on-my-level changed the title feat(dream): build verified all-user agent harness and fold cleanup feat(dream): build shared verified agent harness with reversible cleanup Oct 14, 2026
Git-on-my-level and others added 8 commits October 14, 2026 23:35
- Bind supersede replacement facts to their conversation evidence cohort with
  one evidence object per cited conversation (bare conversation ids), so
  canonical deletion/reprocessing discovers the new active tail
- Stamp restored rows with the reversal commit on hygiene Undo/Redo so vector
  hydration never rejects the projection as stale
- Never drop the predecessor's restricted sensitivity labels on free-form
  replacement tails and screen new content with the shared secret patterns
- Label scheduled-pass replacement tails daily_reconciliation (rank 300) so the
  sweep can still amend them; user-accepted Review keeps agent rank 400
- Carry an optional evidenced effective_from on supersede replacements instead
  of always using wall-clock apply time; future/unparsable times fall back
- Journal merge survivors as redo-only witness fences: Redo refuses to restore
  superseded_by/dream_duplicate_of links after the survivor changed or vanished
- Mark merged duplicate captures dream_duplicate and subtract them from product
  conversation counts (never from export counts), deduped against tombstones
- Bump the action-items list cache version after task cleanup and reversals
- Send full validated fact contents in hygiene proposals (target_content/
  other_content) and prefer them over 180-char labels in the app client
@Git-on-my-level Git-on-my-level changed the title feat(dream): build shared verified agent harness with reversible cleanup feat(dream): verified shared harness, immutable corrections, and all-user cleanup Oct 15, 2026
Git-on-my-level and others added 2 commits October 15, 2026 09:58
Per-kind capability registry, authority-aware protections, structured tool errors, fail-soft inline overlays, owned-field Undo fences, two-vote split semantics, deterministic canary, all-user due queue with sharded budget, dynamic kill switch, Luna-only reserved fallback, backward-compatible Review wire.

Failure-Class: none

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Git-on-my-level and others added 3 commits October 15, 2026 12:21
… kill cache

Failure-Class: none

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…sor until page visited

Failure-Class: none

Co-Authored-By: Claude Opus 5.5 <[email protected]>
# Conflicts:
#	config/deployment-setting-classification.json
#	config/feature-flags.yaml
Git-on-my-level and others added 2 commits October 15, 2026 13:12
…tory

Failure-Class: none

Co-Authored-By: Claude Opus 5.5 <[email protected]>
# Conflicts:
#	backend/deploy/runtime_env.yaml
#	backend/deploy/runtime_env/prod.overlay.yaml

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 59ed62da85

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +39 to +42
if any(
offset + i >= len(segments) or segment.get('text') != segments[offset + i].get('text')
for i, segment in enumerate(captured)
):

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Re-anchor corrections after chronological merge sorting

When manually merging overlapping conversations and at least one source has a transcript correction, _merge_transcript_segments globally sorts the destination segments by adjusted start time, but this validation assumes every source remains a contiguous block at offset + i. For example, sources with segments at t0/t10 and t5 produce the order A0, B0, A1, so A1 is compared with B0 and the otherwise valid background merge is rolled back. Locate each source segment in the actual merged ordering before relocating its correction anchors instead of using source-length offsets.

Useful? React with 👍 / 👎.

Comment on lines +33 to +34
if starred is not None and bool(data.get('starred')) != starred:
return False

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Match the explicit false filter for starred counts

When /v1/conversations/count is requested with starred=false, Firestore's starred == False aggregation excludes legacy documents that lack the field, but this predicate coerces a missing value to False. A Dream duplicate with no stored starred field is therefore absent from the aggregation yet still subtracted by the marker scan, making the count smaller than the corresponding list and potentially negative. Require an explicitly stored false value when reproducing this query predicate.

Useful? React with 👍 / 👎.

Comment on lines +820 to +823
if (
conversation.get('dream_duplicate_of')
or conversation.get('discarded')
or is_completed_rule_discard(conversation)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Apply pagination offsets after hiding Dream duplicates

Once a dream_duplicate_of row appears before visible rows, normal conversation pagination applies offset to the raw Firestore query and only then filters this row here. For example, with raw order [hidden, A, B, C] and limit=2, page one is filled as [A, B], while offset=2 starts page two at B, returning it twice and shifting later conversations across pages. Exclude duplicate rows in the indexed query or count the offset over visible rows rather than filtering after the raw offset.

Useful? React with 👍 / 👎.

{
**patch,
'has_transcript_corrections': True,
'transcript_correction_overlay': store.encode_doc(uid, {'source': combined}),

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Bound the encrypted inline correction overlay

For conversations with a large correction history, the 700,000-byte limit is checked against plaintext JSON, but this field stores the same history after AES-GCM and base64 encoding, which expands it to roughly 933 KB before adding the existing encrypted transcript and other conversation fields. The earlier size guard does not include this newly constructed field, so a valid edit can exceed Firestore's document limit and fail with an unhandled write error instead of the advertised correction-limit response. Check the final encoded document size or omit the inline mirror when only the sibling overlay document fits.

Useful? React with 👍 / 👎.

Comment on lines +43 to +44
vector_db.delete_transcript_chunk_vectors(uid, conversation_id)
vector_db.upsert_transcript_chunk_vectors(uid, conversation_id, chunks)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Make transcript vector rebuilding fail open

When Pinecone or the embedding provider fails after a transcript correction commits, this deletes all existing chunk vectors and then lets the upsert exception escape. The segment-edit endpoint consequently returns an error even though the Firestore correction and Review journal are already durable, while the conversation also loses semantic transcript search until another rebuild happens. Build the replacement vectors before destructive cleanup or enqueue a retryable projection update without turning a projection outage into an apparent write failure.

Useful? React with 👍 / 👎.

Comment on lines +188 to +189
else:
patch = {'language': edit.after}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Mark accepted language corrections as user-owned

When a user accepts a set_language Review proposal, answer_proposal applies it with user authority, but this patch stores only the language and never sets language_user_set. The automatic validation guard checks precisely that marker, so a later Dream pass can silently replace the language the user explicitly approved. Stamp the ownership marker for user-authority applications while leaving autonomous language corrections unmarked.

Useful? React with 👍 / 👎.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 79783ed882

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +90 to +92
row = action_items.get_action_item(uid, key)
generation = control_cache['generation']
return row if row and row.get('account_generation', 0) == generation and not row.get('deleted') else None

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Exclude locked tasks from Dream reads

When an unpaid owner's action item has is_locked=true, this path still returns its complete description and metadata to the Dream model as long as its generation matches. Product task reads and semantic search explicitly filter locked items, and other Dream readers reject locked conversations and memories, so a history/semantic search can bypass the same access boundary and use locked content as evidence for owner-visible edits or proposals. Return no row or raise the locked-record error here as well.

Useful? React with 👍 / 👎.

'transcript_correction_overlay': store.encode_doc(uid, {'source': combined}),
},
)
transaction.set(overlay, store.encode_doc(uid, {'source': combined}))

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Include transcript correction history in portability exports

This introduces a retained owner subcollection containing full manual/Dream correction text, timestamps, and undone entries, but services/users/data_export.py never enumerates transcript_corrections. The conversation export only projects active entries; undone entries are skipped, while the inline mirror remains an opaque encrypted envelope, so an account export cannot recover the user's retained correction history. Add a decoded, owner-scoped export for this collection (and its journal linkage).

Useful? React with 👍 / 👎.

Comment on lines +439 to +440
overlay_ref = conversation_ref.parent.parent.collection('transcript_corrections').document(conversation_ref.id)
overlay = overlay_ref.get(transaction=transaction).to_dict()

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Read correction overlays before finalization writes

When a corrected conversation is creating a new finalization job and extra_updates contains a projection-family field, _create_or_get_finalization_intent_txn has already called transaction.set(job_ref, ...) before its finally block reaches this get. Firestore transactions reject reads after their first write, so this path aborts finalization instead of binding the client projection. Load and validate the overlay before any job/projection writes, or include it in the transaction's initial read phase.

AGENTS.md reference: backend/AGENTS.md:L225-L225

Useful? React with 👍 / 👎.

Comment on lines +28 to +30
async with asyncio.timeout(DRAIN_TIMEOUT_SECONDS):
await run_blocking(db_executor, dream_report.require_owner, uid)
report = await dream_agent.run_pass(
uid, trigger='manual', timeout_seconds=FULL_PASS_SECONDS if full else 70
)
report = await dream_agent.run_pass(uid, trigger='manual', timeout_seconds=PASS_TIMEOUT_SECONDS)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Keep Run Now within the mobile request timeout

For medium or heavy owners, this now waits synchronously for a pass that may run for PASS_TIMEOUT_SECONDS (1620 seconds), while the Flutter executeApi call uses the default 300-second write timeout and supplies no override. Any pass lasting over five minutes is therefore shown as a failed Run Now request even though the server may retain its lease and continue work; an immediate retry can then be refused as already in progress. Return an accepted/run ID for polling, or keep the synchronous pass below the released client's timeout.

Useful? React with 👍 / 👎.

Comment on lines +57 to +59
journal['witness_fences'] = {
path: witness_snapshot(uid, path, raw) for path, raw in witnesses.items() if raw is not None
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Encrypt task survivor witness content

For merge_tasks, this stores the surviving task's complete description, owner, and due date under the top-level witness_fences key. review_store.encode_doc encrypts only its _CONTENT_FIELDS allowlist, which does not include witness_fences, so user task content is written in plaintext to review_changes even though the surrounding edit payload is encrypted. Encrypt this fence or retain only a keyed fingerprint sufficient for Redo validation.

Useful? React with 👍 / 👎.

Comment on lines +292 to +293
old_global_budget['reserved_usd'] = (
float(old_global_budget.get('reserved_usd', 0)) + reservation - previous_charge

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Preserve settled spend when reclaiming leases

When one or more turns have already settled more than the default expected_tokens hold, the lease's budget_charge_usd exceeds reservation_usd. If that worker later becomes abandoned, this calculation subtracts the larger settled charge and adds back only the smaller initial reservation in both the owner and global ledgers, effectively refunding known billed tokens. Subsequent passes can then exceed the configured daily ceilings; retain at least previous_charge when reclaiming, plus any conservative allowance required for the unknown tail.

Useful? React with 👍 / 👎.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant