Skip to content

feat(database): conformance-only typed cell adapters for folders, people and task workflows (A2b) - #24870

Merged
Git-on-my-level merged 58 commits into
mainfrom
pgf/a2b-cell-adapters
Nov 9, 2026
Merged

Git-on-my-level merged 58 commits into
mainfrom
pgf/a2b-cell-adapters

Conversation

@Git-on-my-level

@Git-on-my-level Git-on-my-level commented Nov 7, 2026 •

Copy link
Copy Markdown
Member

Requested by David

What changed and why

Compose conformance-only typed cell adapters for folders, people, action items, goals and workstreams over the existing cell UoW, with expand-only query columns and shared simulator/Firestore/Postgres contracts. Restore legacy IDs from document keys without rewriting payloads, use keys for retirement and replacement, and preserve UTC goal-history fallback for falsy or invalid timezones. No serving selectors or configuration change; enrollment remains outside this PR. Firestore folder/event serving behavior and read costs remain unchanged. The earlier legacy person identity recovery remains: FirestorePeople receipt replay of a legacy person document stored without an id field now returns the document key as id (previously the replayed dict had no id); stored payloads are not rewritten. Covered by the shared ID-less conformance cases.

Product invariants affected

none

How it was verified

Round-1 conformance passed all 186 cases on required simulator, Firestore emulator and disposable local Postgres backends. Six focused/failed-file replays passed all 206 cases, including the corrected fingerprint and timeout fixture, strict port contracts, cell migration contracts, and unchanged speaker timing tests.

The full 2,677-file unit command exited 1: 65,732 passed / 4 failed, plus one file timed out. The corrected and timing-sensitive cases passed serialized replay; the unchanged deploy-contract fixture still timed out at 900 seconds in both bulk and isolated runs. Its diagnostic stack was parsing AST import closures. No whole-suite green is claimed. The async scanner and expanded typecheck passed (0 type errors); frozen preflight passed all 43 checks. Metadata validation passed all 4 checks. No production access or GCP tier was used.

Tests

Shared regressions read ID-less documents across all five domains, check mutation-return IDs and key-based retirement/replacement, and verify projections do not add IDs to stored legacy payloads. Goal progress history covers valid, null, empty and invalid timezones through both append and update APIs. Existing migration contracts now reject destructive DDL; the import-only guard permits 120 seconds for process startup under load.

UI evidence

UI-Evidence: none -- backend only

Failure class (fixes)

Failure-Class: none

Review fixes (round 17)

  • Goal focus enumerates the focus set, which locks it sorted, before it reads the requested goal. Folder reorder locks its ids sorted before it checks them. The cross-domain lock-order test now covers focus and reorder.
  • Lock order is a latency property here, not a correctness one. Every body read is SELECT ... FOR UPDATE, and some bodies are data-dependent: append_progress_event locks the goal, then goal_history/<goal>/<day>, and the day comes from users/profile. Those bodies cannot always lock in flush order. Correctness rests on the store treating 40P01 as retryable (store.py:326, bounded and jittered, whole-body replay). New test test_inverted_lock_order_deadlock_is_detected_and_retried uses two real connections that lock a,b and b,a. PostgreSQL aborts one, the retry commits it, and both increments land. 25 related files pass under test.sh.

Review fixes (round 16)

  • Cross-domain bodies take row locks in flush's sorted (entity, id) order, so a concurrent raw write cannot deadlock them. Goal lifecycle detach locks linked tasks before the goal, then workstreams. Folder delete locks conversations before folders, and locks the deleted folder and its target in sorted order. Folder moves lock conversations sorted and refresh counts in sorted folder order. _lock_in_order moves from WorkflowRepo to Repo so the folder adapter can use it.
  • Sweep: import_task_goal_links already locked in order. resolve_work_intent touches only brand-new rows after the task and goal, and the other single-collection paths go through sorted queries. Test: test_cross_domain_bodies_lock_in_flush_order fails on 9e19c3f. 25 related files pass under test.sh.

Review fixes (round 15)

  • A goal update now rejects id, goal_id and account_generation. Before, the patch was copied whole, so it could change identity or generation past the generation checks. Routers pass typed models without these fields. Test: test_goal_update_rejects_identity_and_generation_fields[backend x field].
  • A people.create replay whose person was deleted returns the receipt id, as the Firestore path does, instead of raising KeyError. Test: test_person_create_replay_survives_deleted_person[postgres|sim].
  • Sweep: every other if prior is not None replay in the cell adapters returns a stored id or reads through .get. Workstream and folder updates use typed patch models, so they cannot carry identity fields. Both fixes are mirrored in the sim twin. All 8 new cases fail on a1def7b, and the file passes 71/71.

Review fixes (round 14)

  • A saved None mutation result now replays. receipt() returned None both when there was no receipt and when the saved result was None, so a missing-goal update that was retried after the goal appeared applied the old patch. _idempotent now checks whether a receipt exists (receipt_entry), in the adapter and in its sim twin. Test: test_goal_update_replays_saved_none_after_goal_appears[postgres|sim], which fails on the previous head.
  • Merged origin/main to pick up the flags: dated sweep exceptions for overdue review_by rows; check on the UTC date #24950 registry-gate fix. The flake-fix conflict in test_qualify_parakeet_route.py took main's version (fix: scope Parakeet cleanup test timeout to receiver task #24948). The domain_sim/store.py baseline moved to 1511 -> 1619.

Scoped cleanups (optional)

Cell-native creates retain redundant IDs as a documented metadata exception to payload byte parity. Before W5 enrollment, integrate the Firestore-owned profile timezone source and confirm the naive legacy timestamp policy before serving those paths. Round 5 verifies the list indexes; round 6 aligns raw and typed writer lock ordering. No edits under .github/, backend/database/jobstore/ or backend/testing/store_fixtures.py.

Line-Count-Exception: backend/testing/domain_sim/store.py | 1511 -> 1625 | Shared legacy identity, timezone, chat snapshot, lifecycle, malformed-event, jsonb key-order and typed-generation conformance requires independent simulator behavior in the existing reference adapter.

Housekeeping

Removes lane working notes (.agent-artifacts/pgf/{a2a,b2,merge-owner-fix}-*) that merged with #24852 and #24805. One test-only isolation fix in test_qualify_parakeet_route.py (timeout injection leaked across cases under load).

Long-term data foundation wave A2b (follows #24852). Rebased on main after #24852 merged.

Review fixes (round 7)

  • Object- and array-valued legacy folder order values sort by PostgreSQL jsonb::text (keys by length, then bytes) in the cell cursor and the simulator, matching the SQL order function and index; regression case [{'b': 0}, {'aa': 0, 'z': 0}] across limits and pending/committed rows.

Review fixes (round 8)

  • account_generation filters in cell action-item idempotency and workstream lists compare typed JSON (coalesce(doc->'account_generation','0')=to_jsonb(gen)): missing is 0, wrong-typed legacy values are nonmatches instead of a failing bigint cast; regression test for string, boolean, numeric-string and null values.

Review fixes (round 9)

  • Python mutation guards (CellWorkstreams._require, action-item document reuse) use generation_matches, the twin of the typed SQL filter: a missing field is 0, only JSON numbers match, booleans/strings/null are refused; regression test for update on wrong-typed rows.

🤖 Generated with Claude Code

Review fixes (round 2)

The immutable timestamp decoder now treats PostgreSQL timezone displacement errors (SQLSTATE 22009) as NULL, alongside malformed dates and datetime overflow. Real PostgreSQL regressions cover positive and negative +99:99/+24:00 equivalents in both plain strings and codec-tagged timestamps, including STORED-column writes. Migration 0003 remains expand-only and its checksum is re-pinned before enrollment.

The cell action-item update enforces the same encoded before-state comparison and after-state result as Firestore. Shared conformance covers stale snapshots for changed and no-op patches, rejection without writes or receipts, matching snapshots, and successful receipt replay. The independent simulator is corrected too. The mutation fingerprint is unchanged because Firestore excludes expected_chat_state.

The full shared run also exposed a cell folder-deletion parity defect: rehoming overwrote folder_user_set instead of preserving the stored marker. The one-line cell correction follows Firestore and the independent simulator; the existing shared parametrized regression covers absent, false and true markers, with and without a default folder, inside and outside a UoW.

Round-2 focused regressions passed all 14 cases, and the final required simulator/Firestore-emulator/Postgres conformance plus migration run passed all 225 cases with no skips. Full backend typecheck passed with zero errors. At the round-2 handoff the full selected unit run was still in progress; its unchanged timeout-probe and Opus-discovery failures both pass isolated replay (16 and 68 tests respectively). No whole-suite green is claimed; terminal counts and preflight results will be recorded before handoff.

Review fixes (round 3)

Cell and simulator now preserve terminal/paused/background goals on unfocus, reject invalid relationship dispositions, and apply the same strict workstream patch schema as Firestore so identity and account generation cannot change through update. Shared tests assert no writes on rejection and that rejected requests do not consume idempotency keys.

Round 4 restores backend/database/{folders,goals,workstreams}.py and test_firestore_query_contract.py exactly to their pre-round-3 contents (61e183e). Firestore folder/event serving behavior and read costs stay unchanged. Cell and simulator exclude missing or null discarded fields from default folder listings, matching Firestore's server-side discarded == False predicate before pagination. Include-discarded behavior and the historical post-pagination deleted filter are preserved.

Cell event queries keep a guarded numeric cast and apply stored-type ordering and the query limit before validating the existing Firestore presentation model; malformed rows consume window slots and are then dropped. Workstream numeric inequality excludes nonnumeric stored types; goal ordering includes them. Valid integer strings above bigint range remain readable, with no bigint cast. Oversized doubles consume their query slot and are then dropped, matching Pydantic's existing float-to-int range check; the cell accounts for JSONB decoding integral doubles as Python integers. Shared cases cover malformed strings, null, objects, arrays, fractional/zero/negative/boolean/timestamp sequences, a one-row window consumed by malformed parent IDs/kinds/summaries, missing ordered fields, numeric versus string ordering, and document-key tiebreaks. People name lookup remains string-only in cell and simulator.

Migration 0003 adds all ten generated columns with one ALTER TABLE, preventing repeated table rewrites. Its name remains 0004_task_workflow_typed.sql for lead-owned merge-time renumbering, and the checksum and migration contract are updated.

Round-4 validation supersedes the earlier round-3 result: required simulator/Firestore-emulator/Postgres shared conformance and cell migration tests passed all 327 cases without failures or skips. All 17 focused unit files passed 1,036 cases, including all 50 restored query-contract cases; the standard unit runner deselected one slow query-shape sentinel. The full preflight then included that sentinel and passed all 840 Firestore guard cases and all 39 checks (550.42 seconds). Environment preflight passed 17 checks with 9 optional warnings and 0 failures. Canonical full backend typecheck passed with 0 errors / 76,784 warnings.

The initial preflight timed out the query-shape file at its default 300-second budget; the retry used the supported 1,800-second local per-file override, with no assertion, repository timeout or guard changes. An ad hoc typecheck omitted --pythonpath and reported missing dependencies; the canonical backend/scripts/typecheck.sh invocation explicitly bound this worktree's Python and passed. A conservative 2,694-file unit attempt was stopped after focused coverage passed, following the lead's earlier publication-gate scope. No full-unit-suite or CI green is claimed. No GCP tier, production access, push or PR creation was used.

Known parity differences

No unavoidable bigint-range result difference is known for Firestore-storable values: shared tests require identical accepted large integer strings and rejection of oversized doubles. Firestore does not store integer-typed values outside signed 64-bit range. Cell numeric fields outside that range are dropped after LIMIT, matching the only Firestore-storable numeric representation (double); integer strings are preserved without that bound. This PR does not enroll or serve cell owners.

Review fixes (round 5)

Cell folder pagination now returns the exact SQL ordering key as JSONB text with each row and uses that text unchanged in the next cursor. This removes Python repr differences for legacy objects and arrays, preserves SQL numeric precision, and works for persisted rows and pending UoW writes. PostgreSQL regressions put page boundaries on arrays and non-datetime objects, including equal values with document-key tiebreaks and page sizes one and two.

Migration 0003 retains its filename and one ALTER TABLE for all ten generated columns, with its checksum re-pinned. The folder list and expression index share the immutable cell_folder_order_key(q_order) function. The action-item list index matches the query's coalesced completion, due-null marker, due epoch, negative created epoch, and document-key expressions. Explicit UTC extraction makes the epoch expressions immutable without changing ordering. EXPLAIN regressions inspect the actual adapter queries and require their named indexes with no Sort or Incremental Sort.

Before the fix, all ten new regressions failed: eight pagination cases skipped rows and both index cases required a sort. After the fix, all 31 migration/typed-cell tests passed. No production access, GCP tier, push, PR creation, main merge, full selector, full preflight or repository typecheck was used in round 5; the lead owns the publication gate.

Round-5 terminal validation: required shared simulator/Firestore-emulator/Postgres conformance passed all 306 cases with no skips, and the nine directly related file-isolated unit suites passed all 167 cases. Together with the 31 migration/typed-cell cases, all 504 focused cases passed. Firestore emulators shut down normally; all verification commands and the task-owned heartbeat are stopped. Commit: 7a15c78.

Review fixes (round 6)

Raw and typed cell writers now take document/missing-key locks before the admission/sequence head. The typed UoW retains its per-space advisory serialization, but no longer locks space_heads before the body; raw flush locks all buffered addresses before checking the writable-space fence and replay receipts. The fence, sequence allocation, change log and receipt writes remain in the same transaction through commit. Four two-connection PostgreSQL regressions cover existing and missing rows, raw read-before-write and buffered-only writes, with a one-second lock_timeout and retries disabled. Each verifies distinct connection PIDs, both commits, the final shared row and the sequence head.

The shared event decoder rejects numeric values below -9223372036854775808 as well as above 9223372036854775807. Eight real JSONB round-trip cases verify both numeric bounds, integral doubles losing their float type, and preservation of integer strings outside the numeric range. Migration 0004_task_workflow_typed.sql is unchanged.

The pre-fix regression run reproduced six failures (four lock-order cases and two lower-bound cases), with six passing boundary controls. After the fix, the complete migration/typed-cell and raw-cell suites passed all 71 cases with no skips. No full selector, full preflight or repository typecheck was run in round 6; the lead owns the publication gate. No production access, GCP tier, push, PR creation or main merge was used.

Round-6 terminal validation: all 547 focused cases passed with no failures or skips (71 migration/raw-cell cases, 306 required simulator/Firestore-emulator/Postgres shared cases, 170 directly related file-isolated unit cases). Backend Pyright scoped to the four changed Python files passed with zero errors / 733 warnings. The initial typecheck identified the regression's deliberate protected-method instrumentation; its single targeted annotation documents that test seam. The pinned formatter left all four files unchanged, and git diff --check passed. All verification commands and disposable stores have stopped, and the task-owned heartbeat was verified by PID/parent and terminated. Code commit: cf43cce. No artifacts were committed.

Review fixes (round 10)

  • Strict generation checks on link paths. resolve_work_intent, import_task_goal_links and validate_task_relationship compared generations with Python equality, so a boolean false/true passed the generation 0/1 guards. They now use the typed generation_matches helper, which reads the raw row (the entity model would coerce a boolean to an int). The simulator twin gets the same checks, including its create-reuse, document-id and list_open paths.
  • test_wrong_typed_generation_refuses_task_goal_links covers boolean, string and fractional generations; it fails on the previous head.
  • Verified: 15 cells, workstream, goal, action-item and cell-store conformance suites, 321 passed.

Review fixes (round 11)

  • Key projections keep the JSON type. q_conversation_id, q_idempotency_key and q_goal_id in migration 0004 now project only JSON strings, so a legacy numeric idempotency_key: 123 no longer matches a request for "123". The simulator already compared typed values. q_status is unchanged, since a NULL there would read as active. The pinned 0004 checksum in the migration test is updated (0004 has never been applied outside tests).
  • test_numeric_legacy_idempotency_key_does_not_match_string_request fails on the previous migration and passes now.
  • Verified: the same 15 suites, 322 passed.

Review fixes (round 12)

  • Pending overlay matches migration 0004. The read-your-writes overlay in space_store.py now projects q_conversation_id, q_idempotency_key and q_goal_id as string-only, exactly like the generated columns, so a numeric legacy key edited in the same unit of work no longer matches a string request. test_pending_overlay_keeps_numeric_idempotency_key_typed fails on the previous head.
  • The same rule now covers the two remaining id lookups this PR adds: folder conversations by folder_id and workstream artifacts by workstream_id match only string-valued ids, as the simulator's typed equality does.
  • Verified: the workflow, cells and conformance suites (323 passed) plus 12 folder test files run one per process (99 passed).

CI fix (round 12b)

  • Migration 0004 on a fresh PostgreSQL 17 database. CI failed test_cell_wipe_step, test_directory_router and test_cell_store_conformance at collection time with function cell_query_timestamp(jsonb) does not exist. PostgreSQL 17 builds expression indexes under search_path = pg_catalog, pg_temp, so the SQL cell_folder_order_key could not resolve the decoder while building cell_docs_folder_order. The function now pins SET search_path FROM CURRENT. Reproduced locally on a fresh database: the old migration fails a REINDEX under the restricted path, and the new one passes. test_folder_order_index_rebuilds_under_restricted_search_path covers it. The pinned 0004 checksum is updated.

Review fixes (round 13)

  • Consistent row-lock order. delete_batch, get_by_ids and import_task_goal_links read (and so lock) rows in caller order, while buffered raw writes lock in sorted (entity, entity_id) order at flush; two such transactions could deadlock. A new _lock_in_order helper reads the ids sorted first, in flush's entity order (action items, then goals, then workstreams), before the body runs. test_multi_row_bodies_lock_rows_in_flush_order fails on the previous head.
  • Verified: workflow, cells and conformance suites, 325 passed.

Git-on-my-level and others added 27 commits November 8, 2026 01:34
@Git-on-my-level Git-on-my-level self-assigned this Nov 7, 2026
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 7, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

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

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-09T01:05:41.845311Z 58180b5 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.

@cubic-dev-ai cubic-dev-ai 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.

5 issues found across 27 files

Confidence score: 2/5

  • workstreams.py applies patches to immutable identity fields, which can corrupt a record’s identity or move it across accounts. Reject id, workstream_id, and account_generation before applying patches.
  • space_store.py uses a different lock order from raw cell writes, so concurrent writes can deadlock and exhaust the retry limit. Establish a consistent lock order across both paths.
  • test_cells_task_workflow_migration.py provisions real Postgres in the unit lane, so the default unit run depends on an external database. Move it to the integration suite or mark it as an integration test.
  • folders.py drops legacy conversations that lack discarded, making them disappear from folder results. Treat a missing field as not discarded or backfill it before filtering.

You’re at about 93% of the monthly reviewed-line limit. You may want to disable incremental reviews to conserve quota. Reviews will continue until that limit is exceeded. If you need help avoiding interruptions, please contact [email protected].

Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="backend/tests/unit/test_cells_task_workflow_migration.py">

<violation number="1" location="backend/tests/unit/test_cells_task_workflow_migration.py:34">
P2: This suite provisions real Postgres for nearly every test but runs in the unit lane. Move it to the integration suite or mark it `pytest.mark.integration` so the default unit run does not perform external database setup or silently skip the claimed coverage when Postgres is unavailable.</violation>
</file>

<file name="backend/database/cells/adapters/workstreams.py">

<violation number="1" location="backend/database/cells/adapters/workstreams.py:110">
P1: This update accepts immutable identity fields from the patch. Reject `id`, `workstream_id`, and `account_generation` before applying the patch so authorized callers cannot corrupt key identity or move the record across generations.</violation>
</file>

<file name="backend/database/cells/adapters/folders.py">

<violation number="1" location="backend/database/cells/adapters/folders.py:64">
P2: The folder cursor does not encode the same key used by the SQL sort for object-valued legacy orders, so pagination can omit subsequent folders. Encode the cursor from the same canonical representation as `_FOLDER_KEY`, or make both paths use one shared ordering key.</violation>

<violation number="2" location="backend/database/cells/adapters/folders.py:194">
P2: `conversations_in_folder` drops legacy conversations without `discarded` because this predicate matches only JSON `false`. Treat a missing field as not discarded, or backfill it before filtering, so old conversations remain visible.

(Based on your team's feedback about missing legacy discarded fields.)</violation>
</file>

<file name="backend/database/cells/adapters/space_store.py">

<violation number="1" location="backend/database/cells/adapters/space_store.py:237">
P2: The typed path locks `space_heads` before the body, but raw cell writers lock rows before `flush()` locks `space_heads`; concurrent raw and typed writes can therefore deadlock and exhaust the bounded retry loop. Establish one lock order for both writer paths before enrollment.</violation>
</file>

Reply with feedback, questions, or to request a fix.

View guided diff | Turn on auto-fix | Re-trigger cubic

row = self._require(workstream_id, account_generation)

def build():
row.update(deepcopy(patch.data), updated_at=datetime.now(timezone.utc))

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: This update accepts immutable identity fields from the patch. Reject id, workstream_id, and account_generation before applying the patch so authorized callers cannot corrupt key identity or move the record across generations.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At backend/database/cells/adapters/workstreams.py, line 110:

<comment>This update accepts immutable identity fields from the patch. Reject `id`, `workstream_id`, and `account_generation` before applying the patch so authorized callers cannot corrupt key identity or move the record across generations.</comment>

<file context>
@@ -0,0 +1,462 @@
+        row = self._require(workstream_id, account_generation)
+
+        def build():
+            row.update(deepcopy(patch.data), updated_at=datetime.now(timezone.utc))
+            return row
+
</file context>

def attempt(raw):
# Serialize typed domain algorithms (including collection predicates)
# per space. B2's admission head is locked before reading any rows.
raw.conn.execute('SELECT pg_advisory_xact_lock(hashtextextended(%s, 0))', ('typed-space:' + self.space_id,))

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: The typed path locks space_heads before the body, but raw cell writers lock rows before flush() locks space_heads; concurrent raw and typed writes can therefore deadlock and exhaust the bounded retry loop. Establish one lock order for both writer paths before enrollment.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At backend/database/cells/adapters/space_store.py, line 237:

<comment>The typed path locks `space_heads` before the body, but raw cell writers lock rows before `flush()` locks `space_heads`; concurrent raw and typed writes can therefore deadlock and exhaust the bounded retry loop. Establish one lock order for both writer paths before enrollment.</comment>

<file context>
@@ -0,0 +1,274 @@
+        def attempt(raw):
+            # Serialize typed domain algorithms (including collection predicates)
+            # per space. B2's admission head is locked before reading any rows.
+            raw.conn.execute('SELECT pg_advisory_xact_lock(hashtextextended(%s, 0))', ('typed-space:' + self.space_id,))
+            raw.conn.execute('SELECT space_id FROM space_heads WHERE space_id=%s FOR UPDATE', (self.space_id,))
+            tx = CellSpaceTx(raw, self.adapters)
</file context>

) -> list[dict]:
where = "doc->>'folder_id'=%s"
if not include_discarded:
where += " AND doc->'discarded'='false'::jsonb"

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: conversations_in_folder drops legacy conversations without discarded because this predicate matches only JSON false. Treat a missing field as not discarded, or backfill it before filtering, so old conversations remain visible.

(Based on your team's feedback about missing legacy discarded fields.)

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At backend/database/cells/adapters/folders.py, line 194:

<comment>`conversations_in_folder` drops legacy conversations without `discarded` because this predicate matches only JSON `false`. Treat a missing field as not discarded, or backfill it before filtering, so old conversations remain visible.

(Based on your team's feedback about missing legacy discarded fields.) </comment>

<file context>
@@ -0,0 +1,252 @@
+    ) -> list[dict]:
+        where = "doc->>'folder_id'=%s"
+        if not include_discarded:
+            where += " AND doc->'discarded'='false'::jsonb"
+        rows = self.store.query(
+            'conversations',
</file context>
Suggested change
where += " AND doc->'discarded'='false'::jsonb"
where += " AND (doc->'discarded'='false'::jsonb OR NOT (doc ? 'discarded'))"

@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: 7a15c7823e

ℹ️ 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 +16 to +18
IF encoded IS NULL OR encoded !~ '^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})$' THEN
RETURN NULL;
END IF;

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 timestamp query decoding to the task read codec

For legacy tasks containing a valid timestamp such as due_at='2026-11-01T12:00:00' or '2026-11-01 12:00:00+00:00', this regex produces a null query timestamp even though prepare_action_item_for_read converts it to an aware UTC datetime. Consequently, the cell adapter omits these tasks from matching due-date ranges, unlike FirestoreActionItems.list, which filters projected values. Pagination also constructs its cursor from the non-null projected date while SQL orders the row as undated, potentially returning the same row again. Normalize the accepted legacy formats consistently in the SQL projection and read codec.

Useful? React with 👍 / 👎.

Comment on lines +305 to +309
def resolve_candidate(self, candidate: dict[str, Any], account_generation: int) -> dict[str, Any]:
self._generation(account_generation)
if candidate.get('subject_kind') != 'workstream' or candidate.get('workstream_proposal') is None:
raise WorkstreamConflictError('Candidate is not a workstream create proposal')
proposal = candidate['workstream_proposal']

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 Resolve candidates against their persisted lifecycle state

When resolving a dismissed, expired, or stale candidate, this adapter accepts the supplied proposal and creates work without reading the stored candidate; it also never persists the accepted status or result IDs. In contrast, FirestoreWorkstreams.resolve_candidate_document checks the stored candidate's generation, pending status, and expiry before atomically updating its resolution state alongside the task and workstream. The cell implementation therefore reports successful acceptance while leaving the suggestion unresolved in storage, and can accept proposals the existing port rejects. Preserve that stored-candidate lifecycle contract rather than treating candidate acceptance as an ordinary goal-origin intent.

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: 07924439c2

ℹ️ 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 +112 to +114
data = {k: v for k, v in patch.data.items() if k not in ('status', 'focus_rank')}
row.update(
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.

P2 Badge Synchronize canonical metrics and legacy aliases on goal updates

When a goal already has a canonical metric, updating a released-client alias such as GoalUpdate(data={'target_value': 20}) only changes the alias and leaves metric.target unchanged. Conversely, updating metric leaves existing aliases stale. FirestoreGoals.update_document merges alias updates into the metric and regenerates the aliases, whereas this adapter persists contradictory values that subsequent reads and progress updates continue to use. Apply the same metric/alias normalization before storing the update.

Useful? React with 👍 / 👎.

Comment on lines +322 to +323
def normalized(value):
return value.strip().removeprefix('[screen] ').removesuffix(' [screen]').strip().lower()

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 Handle null legacy descriptions during duplicate lookup

If an incomplete legacy task has description=None, find_active_by_description('Task') raises AttributeError when scanning that row instead of continuing to a matching task or returning None. Such rows are explicitly supported by test_lenient_legacy_entities_do_not_rewrite_defaults, and the read codec preserves their null descriptions. The Firestore adapter's _normalize_description handles falsy values by returning an empty string; preserve that behavior here so one legacy row cannot break duplicate lookup for unrelated tasks.

Useful? React with 👍 / 👎.

Comment on lines +155 to +158
[event, account_generation],
lambda: self._event(workstream_id, event),
)
return WorkstreamEventEntity.model_construct(**result)

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 Validate journal events before advancing the workstream sequence

When a caller supplies an invalid event dictionary, such as {'kind': 'user_note'} without a summary, this path persists it, advances latest_event_sequence, and returns success through model_construct. However, list_events validates stored rows against WorkstreamEvent through event_payloads, so it silently drops the event just acknowledged, leaving a gap in the journal. FirestoreWorkstreams.append_event rejects the same input through parse_payload_strict(WorkstreamEventCreate, ...) before writing. Apply that validation here before invoking _event so rejected events cannot consume sequences or acquire successful mutation receipts.

Useful? React with 👍 / 👎.

The cell cursor and the simulator now render object and array order
values as jsonb::text does (keys by length, then bytes), so limited
folder pages match the SQL index order.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

@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: bb02c3edfc

ℹ️ 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 +350 to +352
self.store.action_items.validate_task_relationship(
TaskRelationshipRule(goal_id=gid, account_generation=account_generation)
)

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 Adopt legacy goal generations when resolving task intents

When the current account generation is nonzero, resolving a task linked to a legacy goal with a missing or zero account_generation fails here because validate_task_relationship requires exact generation equality. FirestoreWorkstreams.resolve_intent_document explicitly accepts generation-zero goals for task-origin intents and atomically promotes them to the current generation. Consequently, an otherwise valid legacy task without a workstream cannot be converted into work through the cell adapter. Preserve that adoption behavior before validating and creating the workstream.

Useful? React with 👍 / 👎.

Comment on lines +263 to +264
self.store.state['goal_events'][goal_id + '/' + eid] = data
row.update(latest_progress_sequence=sequence, 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 Validate goal progress events before persisting them

Calling append_progress_event with an invalid dictionary, such as {'kind': 'metric_update'} without a summary, persists the event and advances latest_progress_sequence, then reports success through model_construct. However, list_progress_events validates rows against GoalProgressEvent and silently drops this acknowledged event. The corresponding FirestoreGoals.append_progress_event rejects the input with parse_payload_strict(GoalProgressEventCreate, ...) before writing. Apply that validation before staging the event so invalid requests cannot consume journal sequences or receive successful receipts.

Useful? React with 👍 / 👎.

A wrong-typed legacy account_generation is a nonmatch instead of a
failing bigint cast in action-item idempotency and workstream lists.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

@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: 14f86a7685

ℹ️ 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 +142 to +143
if row.get('status') in ('achieved', 'abandoned'):
raise GoalConflictError('ended goals cannot be focused')

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 legacy lifecycle state before allowing focus

For a legacy goal with is_active=False and no status, this check allows focus() to change it to status='focused', is_active=True, resurrecting an ended goal. FirestoreGoals.focus_document first calls normalize_goal_storage, which interprets that legacy shape as abandoned and rejects the operation. Normalize the lifecycle state before checking whether the goal can be focused so the cell adapter preserves the existing ended-goal restriction.

Useful? React with 👍 / 👎.

Comment on lines +178 to +180
where = "doc->>'folder_id'=%s"
if not include_discarded:
where += " AND doc->'discarded'='false'::jsonb"

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 dateless conversations from the ordered folder window

When a folder contains a legacy conversation with discarded=False but no created_at, this query includes it and PostgreSQL's default DESC null ordering places it before dated conversations. FirestoreFolders.conversations_in_folder uses order_by('created_at'), which excludes documents missing that field. The cell adapter therefore returns different conversations and lets dateless rows consume the limit or offset, displacing valid dated results. Add the corresponding field-existence predicate before applying ordering and pagination.

Useful? React with 👍 / 👎.

Booleans, strings and null no longer pass the Python generation guards
that the typed SQL filter already rejects.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

@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: d1b39b9b1b

ℹ️ 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".


def receipt(self, mutation_id, operation, data):
digest = hashlib.sha256(json.dumps([operation, data], sort_keys=True, default=str).encode()).hexdigest()
prior = self.store.state['receipts'].get(mutation_id) if mutation_id is not None 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 Hash composite receipt IDs before using them as cell addresses

For valid long idempotency keys, this lookup raises ValueError('invalid entity id') before the mutation can run. The goal and workstream routers accept keys up to 256 characters, but these adapters prepend strings such as focus:{goal_id}: or ws-event:{workstream_id}: and use the result directly as a receipt document ID. _Rows.__getitem__ passes that ID to CellTransaction.get, whose address validator limits entity IDs to 256 characters. The Firestore implementations hash their composite receipt identities instead. Hash or otherwise bound the internal receipt address consistently for lookup and storage so the conformance adapter accepts the same valid keys.

Useful? React with 👍 / 👎.

Comment on lines +302 to +306
metric: dict[str, Any] = {**(row.get('metric') or {'type': 'numeric', 'target': 0}), 'current': current_value}
self.append_progress_event(
goal_id,
{'kind': 'metric_update', 'summary': 'Metric updated', 'metric': metric},
idempotency_key=idempotency_key or uuid.uuid4().hex,

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 first-write-wins behavior for progress retries

If a successful update_progress call is retried with the same idempotency key after the goal's metric target or unit changes, this recomputes the event from the current metric and raises MutationConflict because its digest differs from the saved receipt. FirestoreGoals.update_progress_document explicitly passes first_write_wins=True for keyed progress updates, so the same retry succeeds without appending another event or overwriting later progress. Resolve an existing progress occurrence before comparing the newly reconstructed metric, while retaining strict content-conflict checks for ordinary append_progress_event calls.

Useful? React with 👍 / 👎.

…k paths

resolve_work_intent, import_task_goal_links and validate_task_relationship
compared generations with Python equality, so a boolean generation passed
the generation-0 guards. Use the typed generation_matches helper there and
in the simulator twin.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

@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: 1f88d38865

ℹ️ 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".

return ContinuationCheckpointEntity.model_construct(
**self._idempotent(
'workstreams.checkpoint',
f'checkpoint:{workstream_id}:{idempotency_key}',

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 Scope checkpoint mutation receipts by runtime ID

When two runtimes checkpoint the same workstream using the same idempotency key, the second runtime receives MutationConflict even though it owns a separate checkpoint: this receipt address omits checkpoint['runtime_id'], while the digest includes it. FirestoreWorkstreams.upsert_checkpoint_document scopes its mutation operation as checkpoint-upsert:{workstream_id}:{checkpoint.runtime_id}, allowing these independent requests to succeed. Include the runtime ID in the cell receipt identity so one runtime's keys do not block another runtime's continuation state.

Useful? React with 👍 / 👎.

A legacy numeric idempotency_key 123 matched a request for '123' through
doc->>'idempotency_key'. The conversation, idempotency and goal key
projections now project only string values, as the simulator compares.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

@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: 404c8e4557

ℹ️ 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 +188 to +189
for field in ('conversation_id', 'idempotency_key', 'goal_id', 'status'):
projections['q_' + field] = "doc->>'" + field + "'"

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 typed key projections in the pending-write overlay

When a transaction edits a legacy row containing a numeric conversation_id, idempotency_key, or goal_id, this overlay converts that value to text, whereas migration 0004_task_workflow_typed.sql explicitly projects only JSON strings. For example, updating the description of a task with conversation_id=123 makes tx.action_items.list(conversation_id='123') include it inside the transaction, but the same query excludes it after commit. A numeric legacy idempotency key can likewise incorrectly suppress a create within the UoW. Apply the generated columns' jsonb_typeof(...)= 'string' guards to the overlay so pending and committed queries use identical predicates.

Useful? React with 👍 / 👎.

The read-your-writes overlay projected keys with doc->>, unlike migration
0004, so a numeric legacy idempotency_key edited in the same unit of work
matched a string request again. Folder and workstream-artifact id lookups
now also match only string-valued ids.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

@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: 43b71f4afd

ℹ️ 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".

self.store.state['workstream_artifacts'][workstream_id + '/' + aid] = row
if head is not None:
head['status'] = 'superseded'
self._event(workstream_id, {'kind': 'artifact_version', 'summary': 'Artifact version created'})

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 artifact evidence in the generated journal event

When a valid artifact proposal contains evidence_refs, the descriptor retains them but this generated journal event discards them and uses a summary that identifies neither the logical artifact nor its version. Consequently, list_events returns an artifact-version event with empty evidence, losing the provenance available through the corresponding Firestore port. FirestoreWorkstreams.create_artifact_document copies proposal.evidence_refs into the event and includes the logical key and version in its summary. Preserve that information here so journal-based consumers can identify and trace the artifact change.

Useful? React with 👍 / 👎.

Comment on lines +60 to +63
**data,
'id': wid,
'workstream_id': wid,
'objective': data.get('objective', data.get('title', 'Work')),

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 Persist the default title for workstream drafts that omit it

When a caller supplies a supported port draft such as WorkstreamCreate(data={'objective': 'Finish the report'}), this row never receives a title. WorkstreamEntity.model_construct masks the omission by returning its default empty title, but the stored document and get_workstream_detail payload remain missing the title required by the canonical Workstream model. In contrast, FirestoreWorkstreams.create explicitly supplies data.get('title', 'Work') to _workstream_storage. Apply that same fallback before storing the row so a draft accepted by the existing port does not produce an invalid workstream through the cell adapter.

Useful? React with 👍 / 👎.

Git-on-my-level and others added 2 commits November 8, 2026 22:24
…index builds

PostgreSQL 17 builds expression indexes under search_path = pg_catalog,
pg_temp, so the SQL order key could not resolve cell_query_timestamp and
migration 0004 failed on a fresh CI database.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
delete_batch, get_by_ids and import_task_goal_links locked rows in caller
order while buffered raw writes lock sorted, so two transactions could
deadlock and exhaust the retry budget.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

@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: 978d8cbc7a

ℹ️ 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 +45 to +49
row: dict[str, Any] = {
**data,
'id': gid,
'goal_id': gid,
'status': data.get('status', 'background'),

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 Populate canonical goal defaults before storing new drafts

For a supported draft such as GoalCreate(data={'title': 'Finish report'}), this row omits desired_outcome, source, and the required released-client metric aliases. Neither get() nor get_goal_detail() normalizes the stored goal afterward, so the aggregate contains a goal that fails GoalResponse validation. The Firestore adapter supplies these fields through _new_goal_payload and normalize_goal_storage. Apply equivalent creation normalization so drafts already accepted by the port produce usable goal responses.

Useful? React with 👍 / 👎.

Comment on lines +265 to +266
if event.get('metric') is not None:
row['metric'] = deepcopy(event['metric'])

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 Synchronize released-client aliases when recording progress

When a goal contains both a canonical metric and released-client aliases, update_progress() or a metric-bearing append_progress_event() updates only metric, leaving current_value and the other aliases unchanged. For example, progressing from 1 to 4 returns metric.current=4 alongside current_value=1; subsequent get() and detail reads preserve that contradiction. Unlike the separate GoalUpdate path, this mutation goes through append_progress_event, so normalizing updates alone will not fix it. Match FirestoreGoals.append_progress_document, which updates _metric_aliases(event.metric) in the same goal patch.

Useful? React with 👍 / 👎.

Git-on-my-level and others added 3 commits November 9, 2026 06:38
receipt() returned None both for no receipt and for a saved None result, so
a missing-goal update retried after the goal appeared applied the old patch.
The idempotent path now checks receipt presence, in the adapter and its sim
twin.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
# Conflicts:
#	backend/tests/unit/test_qualify_parakeet_route.py
…eceipt

Goal updates copied every patch field into the row, so a patch could change
goal_id or account_generation past the generation checks; they are rejected
now. A people.create receipt whose person was deleted raised KeyError on
replay; it now returns the receipt id, as Firestore does. Both in the
adapter and its sim twin.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

@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: 9e19c3f1f1

ℹ️ 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".

if row is None:
raise WorkstreamNotFoundError(workstream_id)
return {
'workstream': row.model_dump(),

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 Project workstream details without internal storage metadata

Even for a fully populated, valid workstream draft, row.model_dump() includes id, account_generation, and revision. The canonical Workstream model in backend/models/workstream.py forbids extra fields, so this nested payload fails validation independently of the previously reported missing title and missing aggregate collections. get_goal_detail() likewise exposes these fields in active_threads. Unlike the Firestore detail methods, these cell aggregate reads therefore cannot be decoded through the existing detail projection models. Strip storage-only metadata when building both aggregate projections.

Useful? React with 👍 / 👎.

'created_at': datetime.now(timezone.utc),
}

return self._idempotent('workstreams.intent', 'intent:' + idempotency_key, [request, account_generation], build)

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 account generation in intent receipt identities

If an intent succeeds in one account generation and the same idempotency key is used after the control document advances to another generation, this lookup still addresses the old receipt. Because account_generation participates in the digest but not the receipt identity, the new generation's request raises MutationConflict instead of resolving independently. FirestoreWorkstreams.resolve_intent_document() includes the generation in its receipt ID, so the cell implementation violates the existing generation-scoped idempotency behavior. Include account_generation in the receipt identity for intent resolution and the similarly constructed generation-checked mutation receipts.

Useful? React with 👍 / 👎.

Goal detach locked the goal before its tasks, folder delete locked folders
before conversations, and folder moves locked conversations in caller order,
while flush locks sorted by (entity, id), so a concurrent raw write could
deadlock either path. Each body now locks in flush order; the helper moves to
Repo so folder adapters use it too.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

@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: 90161f0d1a

ℹ️ 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".


@atomic
def get(self, goal_id: str) -> GoalEntity | None:
return self._entity(self._read(goal_id), entity_id=goal_id)

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 Restore the canonical goal ID on legacy point reads

For a supported legacy goal whose payload omits goal_id, this lookup restores only id, leaving GoalEntity.goal_id=None. For example, the row seeded by test_legacy_document_keys_are_identity returns no canonical goal ID through this adapter, whereas FirestoreGoals.get() explicitly supplies goal_id from the document key. Consumers using the canonical field therefore receive an unusable identity, and the goal payload cannot satisfy the required GoalResponse.goal_id field. Supply the missing canonical ID in the read projection without rewriting the stored legacy document.

Useful? React with 👍 / 👎.

Goal focus read the requested goal before enumerating the focus set, and
folder reorder checked rows in caller order. Both now lock sorted first. A
two-connection test forces opposite lock orders and pins the safety net
for data-dependent bodies: PostgreSQL detects the deadlock and the store's
bounded body retry commits both.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

@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: 58180b52ba

ℹ️ 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 +174 to +177
def create_artifact_descriptor(
self, workstream_id: str, proposal: dict[str, Any], *, idempotency_key: str, account_generation: int
) -> ArtifactDescriptorEntity:
self._require(workstream_id, account_generation)

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 Validate artifact proposals before writing descriptors

For an existing workstream, a proposal containing only {'logical_key': 'report', 'version': 1} passes these checks, persists a descriptor without the required kind, uri, or content_hash, and advances the journal with a successful receipt. ArtifactDescriptorEntity.model_construct masks the invalid record, and list_artifact_descriptors subsequently returns it unchanged. The corresponding FirestoreWorkstreams.create_artifact_descriptor validates against ArtifactDescriptorCreate before writing, so the cell adapter accepts and stores data that the existing port rejects. Apply that same validation before staging the descriptor or journal event.

Useful? React with 👍 / 👎.

Comment on lines +85 to +86
for eid, row in self.store.query(
'workstreams', where, args, order='q_updated_at DESC NULLS LAST, entity_id COLLATE "C"', limit=limit

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 existing open-workstream query window

When more open workstreams match than limit, this query selects the globally newest rows, whereas FirestoreWorkstreams.list_open delegates to list_open_workstreams, which applies the Firestore query limit before sorting the selected documents by updated_at. For example, with an older document a, a newer document z, and limit=1, the existing port returns a while this adapter returns z. This makes bounded reads select different workstreams across the conformance backends even with entirely valid records. Preserve the existing document-ID window before sorting, as list_for_goal already does.

Useful? React with 👍 / 👎.

Comment on lines +65 to +68
def __iter__(self):
for key, _ in self.owner.query(self.entity):
self.get(key)
return iter([key for key, row in self.rows.items() if row is not _MISSING])

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 Avoid quadratic collection scans when clearing domain rows

When a domain purge calls _rows().clear(), the inherited MutableMapping.clear repeatedly invokes popitem, and each invocation calls this iterator again. Because every iteration issues a fresh collection query and materializes all remaining documents, clearing N rows performs N+1 collection queries and reads N(N+1)/2 rows; exercising this implementation with 1,000 rows produced 1,001 queries returning 500,500 rows. Goal and workstream purges repeat this for their journal collections while holding the per-space transaction lock. Implement a single-pass clear override that loads the keys once and marks them deleted without querying again for each row.

Useful? React with 👍 / 👎.

Comment on lines +374 to +378
data={
'description': request['anchor_task_description'],
'goal_id': gid,
'workstream_id': wid,
}

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 user ownership on goal-origin anchor tasks

When resolving a valid goal-origin intent, this draft omits owner and source, so CellActionItems.create applies the shared codec's defaults of owner='unknown' and source='legacy'. In contrast, FirestoreWorkstreams.resolve_intent_document creates the same anchor through _task_storage with its default user ownership and source='explicit_goal_intent'. The successful resolution therefore misclassifies an explicitly user-created task as an unattributed legacy task, and subsequent task reads retain that incorrect ownership and provenance. Supply the intent-specific ownership and source when constructing the anchor draft.

Useful? React with 👍 / 👎.

@Git-on-my-level
Git-on-my-level merged commit c933665 into main Nov 9, 2026
63 checks passed
@Git-on-my-level
Git-on-my-level deleted the pgf/a2b-cell-adapters branch November 9, 2026 01:27
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