Repository navigation
feat(annotations): add enforced typed annotation foundation (#2757) - #2757
Conversation
…ates Problem: polylogue-rxdo.7 asks for the missing external-agent-labeling loop (export evidence -> label under a declared schema -> import as candidates -> query back -> judge -> report). Storage was ~75% ready (assertions table, upsert chokepoint, judge lifecycle all real) but two foundations were missing: labels had no declared shape (queryable JSON blobs, not analytical variables), and the DSL's `value` field on the `assertion` unit was substring-only, unable to express `value.score>=4`. What changed: this is the first coherent slice of the larger bead -- schema registry + typed value predicates, since the annotation_batches provenance container and JSONL/CLI/MCP import surface build on this foundation (per the bead's own scoping note). - polylogue/annotations/schema.py: AnnotationField/AnnotationSchema declarations (typed value shape, target ObjectRefKind grain, evidence policy, abstention convention) plus a registry and validate_annotation_value/validate_annotation_row. - polylogue/annotations/write.py: upsert_annotation_assertion(), the atomic single-row write a future batch importer would loop over -- validates a label against a schema, then writes through the existing single assertion-write chokepoint (upsert_assertion), inheriting its 37t.15 agent-authored candidate-coercion invariant for free. Uses a distinct id-derivation namespace from the existing freeform upsert_annotation() note helper so the two "annotation" concepts never collide on identity. - polylogue/archive/query/expression.py: the `assertion` unit now accepts dynamic `value.<dotted.path>` fields with `=`/`>`/`>=`/`<`/ `<=` operators (`value.score:>=4`, `value.status:approved`), lowered in polylogue/storage/sqlite/archive_tiers/archive.py via `json_extract(value_json, '$.path')` (bound parameter, CAST AS REAL for comparison operators). Other units continue to reject `value.*` as unknown fields. - docs/plans/topology-target.yaml, docs/topology-status.md: topology projection regenerated for the new polylogue/annotations/ package (also picked up pre-existing stale LOC entries for a few unrelated files -- topology regen recomputes every file, not just this diff's). Deferred (explicitly, tracked in the bead): the annotation_batches provenance container, a JSONL/CLI/MCP import surface that loops over upsert_annotation_assertion for many rows, a concrete registered delegation-discourse schema (belongs to the consuming Fable campaign, polylogue-212.9.1), and referential-integrity checking of target/ evidence refs against the live archive (this slice validates ref *shape*, not that the ref resolves to a real row -- that needs the batch importer's archive handle). Verification: - devtools test tests/unit/annotations/test_schema.py tests/unit/annotations/test_write.py tests/unit/cli/test_query_expression.py tests/unit/storage/test_archive_tiers_assertion_write_through.py -> 463 passed, 1 skipped (pre-existing skip, unrelated). - devtools test tests/unit/storage/test_archive_tiers_assertions.py -> 25 passed, 1 failed; confirmed via git stash the failure (test_fresh_user_tier_has_no_legacy_overlay_tables, a stale `context_deliveries` table-set expectation) is pre-existing on master, unrelated to this diff. - mypy --strict on every touched/new file -> no issues. - ruff format --check / ruff check on every touched/new file -> clean. - devtools render topology-projection && devtools render topology-status; devtools render all --check -> no drift. - Manual roundtrip smoke test (schema-validated candidate write -> value.score/value.status DSL query -> judge accept -> active row visible via value.score:>=4 AND status:active) exercised end to end against a real sqlite archive before writing the pinned test. Ref polylogue-rxdo.7 Co-Authored-By: Claude <[email protected]>
Problem: the annotation foundation allowed unregistered or drifted schema definitions to share one provenance identity, and typed value predicates could coerce strings and booleans into numeric matches or lose JSON scalar type during equality queries.\n\nWhat changed: require an exact active registry definition at the public annotation writer, reject non-finite analytical numbers, preserve quoted JSON scalar literals and alternations in the DSL, and guard range comparisons with SQLite JSON type checks. Production-route tests cover writer rejection, candidate writes, typed SQLite queries, and judgment promotion.\n\nRef polylogue-rxdo.7\n\nCo-Authored-By: Claude <[email protected]>
Problem: typed annotation equality still allowed SQLite to conflate JSON booleans with numeric zero/one, while schema declarations accepted invalid closed-vocabulary values and non-finite bounds. Huge integers could also raise OverflowError during finite-number validation. Guard equality by SQLite JSON type as well as extracted value, reject non-scalar and non-finite query literals, validate every closed declaration vocabulary at construction, and handle arbitrary-size finite integers without float coercion. Add production-route regressions for writer validation, boolean/number/null/missing alternation, and finite bounds. Ref polylogue-rxdo.7 Co-Authored-By: Claude <[email protected]>
Problem: the annotation foundation had to be rebuilt on master after the embedding reconciliation changed the generated topology surfaces. The replacement also needs the latest parent phase record and its two explicit residual child beads without overwriting newer unrelated task state. Select the latest rxdo.7 record by updated_at, retain rxdo.7.1 and rxdo.7.2 as open children, and regenerate topology projection/status against merged master. No bead or pull request is closed. Ref polylogue-rxdo.7 Co-Authored-By: Claude <[email protected]>
|
Warning Review limit reached
Next review available in: 46 minutes Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available. How can I continue?After more reviews become available, a review can be triggered using the To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews. How do review limits work?CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability. For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window. Please refer docs for additional details. Review details⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: ASSERTIVE Plan: Pro Run ID: 📒 Files selected for processing (12)
✨ Finishing Touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: c7d1349c6f
ℹ️ 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".
| conn, | ||
| assertion_id=assertion_id, | ||
| target_ref=normalized_target_ref, | ||
| kind=AssertionKind.ANNOTATION, |
There was a problem hiding this comment.
Put annotation candidates in the review queue
With the default author_kind="agent", this writes schema labels as status=candidate but with kind=annotation; the standard review readers (list_assertion_candidates / list_assertion_candidate_reviews) default to ASSERTION_CLAIM_KINDS, which does not include AssertionKind.ANNOTATION. In that default flow, imported annotation candidates will not appear for review unless every caller remembers to override kinds, so they are effectively hidden from the normal promotion/judgment queue.
Useful? React with 👍 / 👎.
| return upsert_assertion( | ||
| conn, | ||
| assertion_id=assertion_id, | ||
| target_ref=normalized_target_ref, | ||
| kind=AssertionKind.ANNOTATION, | ||
| key=row_key, | ||
| value=stamped_value, |
There was a problem hiding this comment.
Skip upserts for already judged annotations
When an automated import reuses the same schema/target/author/row_key after that candidate has been accepted, rejected, deferred, or superseded, this unconditional upsert still runs the conflict update. upsert_assertion preserves the terminal status for non-user authors, but it still replaces value_json, body, and evidence, so a rerun can silently change a judged annotation without a new review; the existing transform/pathology candidate writers avoid this by returning existing non-candidate rows instead of upserting them.
Useful? React with 👍 / 👎.
## Summary Persist versioned annotation schemas and independent annotation-batch provenance in the durable user tier. The change registers the concrete `delegation.discourse@v1` schema, keeps complete repository reads, and exposes byte-bounded public batch-reference payloads. ## Problem The typed annotation foundation remained process-local: schema identity could drift across restarts, batches for the same target were not independently attributable, and public reference resolution could reflect arbitrarily large opaque values. Durable provenance also needed exact retry semantics without normalizing opaque ObjectRef identity. ## Solution - Add the verified additive user.db v6 migration for `annotation_schemas` and `annotation_batches`, with canonical fresh-DDL parity and backup-manifest coverage. - Persist immutable schema declarations/fingerprints and reject incompatible id/version reuse, mutable aliases, NFC collisions, and invalid UTF-8 declarations. - Persist independent annotation-batch provenance, validation totals/failures, assertion refs, and batch-scoped insert-once assertions. - Preserve exact opaque ObjectRef bytes across hot/cold replay. - Resolve `annotation-batch:` refs through full durable reads while projecting bounded previews with exact counts, omitted-byte evidence, SHA-256 descriptors, and fixed-size invalid-Unicode fallbacks. - Regenerate topology/layering/documentation surfaces. Built on the typed foundation from PR #2757. Ref `polylogue-rxdo.7.1`. ## Acceptance criteria - [x] Cold reopen resolves the same schema definition and fingerprint. - [x] Incompatible schema id/version reuse fails closed. - [x] `delegation.discourse@v1` is registered. - [x] Independent batches for the same schema/target remain distinguishable and queryable. - [x] Durable v5→v6 migration requires verified backup evidence and matches fresh DDL. - [x] Public batch-reference responses are byte bounded without truncating repository reads. Deferred: JSONL/CLI/MCP batch import remains `polylogue-rxdo.7.2`; structural target joins remain `polylogue-kmts`. ## Verification - `devtools test ...` — 155 focused durable/schema/ref/migration/public-route tests passed; run `20260712T152900Z-focused-test-3014481-3ad91648`. - Final release-gap selection — 12 passed; run `20260712T160837Z-focused-test-3325379-546339d8`. - Pre-push `devtools verify --quick` — 15/15 passed; run `20260712T161026Z-quick-3331317-d0b5478e`. - `devtools lab policy schema-versioning` — 0 derived helpers, 0 invalid durable migrations. - `.agent/scripts/bd-graph-lint` — no cycles; only inherited missing-AC findings for `polylogue-2ilz` and `polylogue-nu2h`. - `git diff --check` — clean. The default testmon selection expanded to 14,730 tests because `surfaces/payloads.py` is a dependency hub, so it was aborted rather than turned into a blanket suite run. `devtools verify --all` was not run. ## Adversarial review Five independent passes found and drove repairs for mutable schema aliases, NFC key collisions, hot/cold schema divergence, count-only response caps, unbounded missing refs, opaque-ref normalization, and invalid-Unicode escape paths. The fifth pass reported no other legitimate gaps after isolating its final lone-surrogate blocker; that blocker is fixed and regression-pinned. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **New Features** * Added durable, versioned annotation schema storage with canonical identity/fingerprints. * Added write-once annotation batch provenance storage with listing and filtering. * Annotation upserts can optionally link annotations to an immutable batch and validate drift. * Added `annotation-batch` reference resolution with bounded previews and truncation/caveat reporting. * Bundled the built-in “delegation discourse” annotation schema. * **Documentation** * Updated schema versioning, storage layout, and internal durability/topology docs for user annotation tiers (v6). * **Bug Fixes** * Fail-closed handling for malformed, oversized, and invalid-Unicode `annotation-batch` references. * **Tests** * Expanded durable storage and API contract coverage for schemas and batches. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Co-authored-by: Claude <[email protected]>
Summary
Add the typed-annotation foundation on current master: closed schema
declarations, an explicit registry, a schema-enforced assertion writer, and
type-correct predicates over JSON annotation values. This fresh branch replaces
unmerged PRs #2752 and #2756 without rewriting their published history and is
based on master
7fd5b6bb9after PR #2755.Ref polylogue-rxdo.7
Problem
External labels currently degrade into untyped JSON blobs. The archive cannot
prove that a label was written under the active schema definition, and query
predicates cannot reliably distinguish JSON strings, numbers, booleans, and
null. The earlier branches predated merged topology changes; a fresh branch is
required to preserve public history and regenerate derived surfaces against
current master.
Solution
AnnotationFieldandAnnotationSchemamodels plus an explicitAnnotationSchemaRegistryinpolylogue/annotations/schema.py.unknown, draft, deprecated, drifted, and non-finite values. Runtime
declarations reject unknown closed-vocabulary values and non-finite bounds;
arbitrarily large finite JSON integers do not pass through float coercion.
chokepoint, preserving candidate/non-injected safety semantics.
value.<path>equality and range predicates for assertion queries. SQLguards JSON type before comparison, so strings, numbers, booleans, null, and
missing paths remain distinct; equality alternation preserves each scalar's
identity and numeric ranges reject non-finite right-hand sides.
polylogue-rxdo.7record plus openchildren
.7.1and.7.2, preserving unrelated master Beads records.Acceptance criteria
Satisfied in this foundation phase:
Explicitly deferred:
polylogue-rxdo.7.1: durableannotation_schemasandannotation_batches, immutable fingerprints, a concretedelegation-discourse schema, and queryable batch provenance
polylogue-rxdo.7.2: bounded JSONL import, live target/evidence-spanvalidation, CLI/MCP contracts, disagreement/adjudication roundtrips, and
rendering
polylogue-kmts: structural-target joins without row multiplicationThe parent bead remains open; neither child is optional for its full
acceptance criteria. No prior PR or bead changes state through this PR body.
Verification
values/bounds, scalar identity/alternation, and public-writer rejection
->
23 passed, 14733 deselected in 25.18sdevtools verify --quickwith the regenerated/merged working tree-> all 15 steps exited 0 in 47.63s, including mypy, generated surfaces,
topology, layering, schema roundtrip, and safety gates
devtools verify --quickatc7d1349c6-> all 15 steps exited 0 in 23.53s
devtools render topology-projection && devtools render topology-status->
917 rows,764 stable,6 TBD.agent/scripts/bd-graph-lint->
dup_labels=0,inversions=0; two inherited missing-AC records(
polylogue-2ilz,polylogue-nu2h) are unchanged and outside this diffGitHub-hosted jobs may still fail before startup while the repository account
is billing-locked; that state produces no job logs or substantive CI result.
Anti-vacuity: the focused tests exercise the real SQLite assertion writer,
typed SQL lowering, archive query readback, and candidate judgment. Removing
the active-registry check, finite guards, JSON-type equality guard, or
candidate chokepoint causes the corresponding production-route regression to
fail. The equality fixture places
truebeside numeric1, andfalsebesidenumeric
0, so SQLite coercion cannot pass unnoticed.Adversarial review notes
The independent audit of PR #2756 found four real gaps: boolean/number equality
coercion, missing runtime enforcement of closed declaration vocabularies,
accepted non-finite bounds/equality literals, and
OverflowErroron huge finiteinteger validation. Logical commit
ea1e75fafcarries the repair on currentmaster with mutation-sensitive regressions. The replacement diff was then
rechecked after merged PR #2755 and regenerated without carrying stale topology
bytes.