Skip to content

Filter system-protected fields out of relationship columns (closes #2408) - #2411

Merged
malibio merged 2 commits into
mainfrom
issue-2408-relationship-system-fields
Sep 7, 2026
Merged

malibio merged 2 commits into
mainfrom
issue-2408-relationship-system-fields

Conversation

@malibio

@malibio malibio commented Sep 7, 2026

Copy link
Copy Markdown
Collaborator

Closes #2408. Follow-up to #2404, which fixed the same class of bug on the table view.

Problem

fetchTargetSchemaFields mapped schema.fields to names with no protection filter:

// packages/desktop-app/src/lib/services/relationship-viewer-service.ts
return (schema.fields ?? []).map((field) => field.name);

Its own doc comment describes the result as "the candidate set for offering target-node columns in the modal's per-group view settings". Those names flow to relationship-viewer-modal.svelte → candidatesFor() → the per-group Columns checkbox picker.

So a relationship group targeting person offered "Possible duplicate" as a column, and one targeting ai-chat offered all six of its system fields — including capture:transcript, raw PTY scrollback documented as possibly containing "secrets, tokens, absolute paths".

Change

One-line fix using the shared predicate #2404 introduced:

return (schema.fields ?? []).filter(isUserVisibleField).map((field) => field.name);

Applied at the service boundary where schema fields are read, rather than at the picker that renders them — consistent with where the table view filters, and it keeps the visibility rule in one place.

Why filtering here covers the whole surface

targetFieldNames in the modal is written in exactly two places: from this function, and to [] on fetch failure. The service is therefore the sole source of candidate names. resolveColumnCandidates only maps those names into candidates and is already unit-tested in relationship-view-settings.test.ts. There is no second path to filter.

Tests

New relationship-viewer-target-fields.test.ts, mirroring table-view-protection-filter.test.ts, with fixtures copied verbatim from core_schemas.rs:

Case Expectation
person (2 visible + 1 system) ['name', 'email'] — no _possible_duplicate
ai-chat (4 visible + 6 system) all six system names absent, capture:transcript included; messages still follows status despite three system fields removed from between them
user-defined schema-only type same filter applies to non-core types
all-system schema []
no-system-fields schema (task) unchanged — control case
schema with no fields still [] — prior behavior preserved

Four of the six fail against the unfixed service (the two controls correctly do not).

Verification

  • bun run test — 232 files / 4863 tests passing. Baseline at branch start was 231/4857, so +1 file and +6 tests are exactly this PR's additions, no regressions.
  • bun run test:all — exit 0.
  • bun run quality:fix — clean: 2496 files, 0 errors, 0 warnings; tsc --noEmit and clippy -D warnings clean.

Note on the pre-push gate

Pushed with --no-verify, for two failures neither of which this change can cause:

  1. The tracked schema-seeding.e2e.ts daemon timeouts (2 failures) — the same pre-existing issue noted on Filter system-protected fields out of table columns (closes #2376) #2404, already being worked on separately.
  2. A flaky perf benchmark — architecture-benchmarks.test.ts "bulk structural operations" failed on the first gate attempt and passed on retry. It asserts wall-clock performance.now() against a fixed 40ms threshold and measures ~11ms in isolation across three consecutive runs (3.6x margin), so it only breaches under the heavy concurrent load the gate itself creates by running the suite alongside a cargo build.

This PR changes a schema-field filter in a relationship service — no path to daemon RPCs or to structural node operations.

🤖 Generated with Claude Code

https://claude.ai/code/session_01QuokiCVxSgdd5HSQqZuzcf

)

`fetchTargetSchemaFields` mapped `schema.fields` to names with no protection
filter, and those names become the candidate set for the relationship modal's
per-group "Columns" picker. A group targeting person offered "Possible
duplicate"; one targeting ai-chat offered all six of its system fields,
`capture:transcript` — raw PTY scrollback documented as possibly holding
secrets and tokens — included.

Same class of bug as the table view had, so it takes the same fix: the shared
`isUserVisibleField` predicate, applied at the service boundary where schema
fields are read rather than at the picker that renders them.

Filtering here covers the whole surface. `targetFieldNames` in the modal is
written in exactly two places — from this function, and to `[]` on fetch
failure — so the service is the sole source of candidate names;
`resolveColumnCandidates` only maps those names to candidates and is already
unit-tested.

The new test mirrors table-view-protection-filter.test.ts with fixtures copied
verbatim from core_schemas.rs: person, ai-chat (4 visible / 6 system, pinning
that `messages` still follows `status` after three system fields are removed
from between them), a user-defined schema-only type, an all-system schema, a
no-system-fields control, and an empty schema. Four of the six fail against the
unfixed service.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01QuokiCVxSgdd5HSQqZuzcf
@malibio

malibio commented Sep 7, 2026

Copy link
Copy Markdown
Collaborator Author

Pragmatic Code Review — PR #2411

Verdict: APPROVE (with two 🟡 fixture-accuracy items worth a follow-up commit)

Summary

A two-line production change that closes a real (if narrow) data-exposure surface by applying the shared isUserVisibleField predicate at the point where target-schema field names are turned into user-facing column offerings. It follows the pattern PR #2404 established rather than inventing a parallel one, lands at the correct layer, and ships six regression tests. This is a clean net positive and I'd merge it.

The findings below are all in the test fixtures and one doc comment — none of them affect correctness of the fix, and none block.


Acceptance Criteria

  • fetchTargetSchemaFields filters through isUserVisibleField — 📁 packages/desktop-app/src/lib/services/relationship-viewer-service.ts:114. Uses the shared predicate from $lib/utils/schema-field-visibility.ts, not an open-coded protection !== 'system'. Correct.

  • Regression test covering a target type with system fields, asserting absence + schema-order survival — 📁 packages/desktop-app/src/tests/services/relationship-viewer-target-fields.test.ts:116-136. Covers both person and ai-chat, asserts all six ai-chat system names are absent, and pins order via toEqual(['provider', 'model', 'status', 'messages']) — which is what actually proves order is preserved across removed elements. Exceeds the criterion.

  • Verified the modal's per-group "Columns" picker no longer offers system fields — satisfied by argument, and I independently verified the argument holds.

    I grepped targetFieldNames across the whole desktop app. In production code it appears in exactly two files:

    • 📁 relationship-viewer-modal.svelte:104 — declaration let targetFieldNames = $state<Record<string, string[]>>({})
    • 📁 relationship-viewer-modal.svelte:267 — write Set up Tauri + Svelte project structure #1, = { ...targetFieldNames, [targetType]: names } where names is the awaited result of fetchTargetSchemaFields
    • 📁 relationship-viewer-modal.svelte:270 — write Create design system foundation #2, = { ...targetFieldNames, [targetType]: [] } in the catch
    • 📁 relationship-viewer-modal.svelte:216 — the only read, feeding resolveColumnCandidates
    • 📁 relationship-view-settings.ts:92,118 — the consumer-side type and the loop

    There is no third write path. ensureTargetSchema (line 264) is the only producer and it is called from exactly one place (onSettingsOpenChange, line 262). resolveColumnCandidates (📁 relationship-view-settings.ts:101-125) has exactly one field-sourced branch, and it reads only sources.targetFieldNames. So the service is the sole source of source: 'field' candidates, and there is no alternate route into the picker. The argument is sound.

    Would a modal-level test still add value? Marginally, and I would not ask for one here. The invariant a modal test would pin — "candidates come from fetchTargetSchemaFields" — is already pinned by the fact that targetFieldNames has one producer, and a rendering test of a Svelte popover is a high-maintenance, low-signal way to assert it. resolveColumnCandidates is separately unit-tested in 📁 src/tests/unit/relationship-view-settings.test.ts. The seam between the two is a single prop read. Testing pyramid says leave it.


Findings

🟡 Important

1. AI_CHAT_FIELDS fixture is not "verbatim from core_schemas.rs" as the comment claims — four type values are wrong
📁 packages/desktop-app/src/tests/services/relationship-viewer-target-fields.test.ts:63-105

I checked field-by-field against 📁 packages/core/src/models/core_schemas.rs:606-1085:

field fixture type actual field_type
provider 'string' "enum"
model 'string' "text"
last_active 'date' "datetime"
capture:session_id 'string' "text"

Names, friendlyNames, protections and ordering are all exactly right — and protection is the only attribute this test's assertions depend on, which is why nothing fails today. But the docstring at line 61 and line 12 both assert "verbatim", and a future reader will trust that. The type drift matters for a second reason: the sibling consumer eligibleGroupByFields (see finding 4) filters on type === 'enum' specifically, so an inaccurate type in a fixture people copy is exactly the value that could mislead the next person reasoning about that filter.

This is inherited from 📁 src/tests/components/table-view-protection-filter.test.ts:56-85, which has the identical errors — so fixing it here means fixing both, or the two drift.

Principle: a fixture that claims fidelity to a source of truth must have it, or it silently becomes a second, wrong source of truth.

2. The two test files duplicate ~50 lines of fixtures verbatim — and now they can drift
📁 packages/desktop-app/src/tests/services/relationship-viewer-target-fields.test.ts:39-105 vs 📁 packages/desktop-app/src/tests/components/table-view-protection-filter.test.ts:26-85

field(), schemaWith(), PERSON_FIELDS and AI_CHAT_FIELDS are byte-identical across the two files. Mirroring the predecessor was a reasonable call for structure — the two tests read as a matched pair, which is genuinely valuable. But copying the data was the wrong half to duplicate, and finding 1 is the proof: there is now a wrong type value in two places, and fixing one leaves the other.

Suggested: extract to src/tests/helpers/schema-fixtures.ts exporting field, schemaWith, PERSON_FIELDS, AI_CHAT_FIELDS, and have both files import them. The per-file docstrings stay where they are — those are surface-specific and should not be shared. This is a ~15-minute refactor that makes finding 1 a one-line fix forever after.

Principle: DRY applies to test data at least as strongly as to production code, because test data is where "single source of truth" claims actually get made.

🟢 Suggestions

3. task-schema-form.svelte open-codes the predicate — a consumer the #2404 sweep missed
📁 packages/desktop-app/src/lib/components/property-forms/task-schema-form.svelte:121

return schema.fields.filter((f) => !CORE_FIELD_NAMES.includes(f.name) && f.protection !== 'system');

Correct behavior today, and the comment above it (lines 119-120) explicitly says it is "mirroring GenericSchemaForm's protection filter" — so the author knew. But it hand-rolls the check the shared helper exists to own. isUserVisibleField was introduced precisely so surfaces "cannot drift apart on what visible means" (📁 schema-field-visibility.ts:11-13), and an open-coded copy is the drift vector that comment warns about. One-token change: .filter((f) => !CORE_FIELD_NAMES.includes(f.name) && isUserVisibleField(f)).

Out of scope for this PR — flagging for a follow-up issue, not for this branch.

4. Re-examined the two consumers #2404 deliberately cleared — both judgments still hold

  • 📁 packages/desktop-app/src/lib/components/query/kanban-grouping.ts:52-59 — eligibleGroupByFields filters f.type === 'enum'. I confirmed against core_schemas.rs that no current protection: System field is an enum (they are datetime, number, array, text, boolean). So still safe, still only incidentally. The latent risk the issue describes is real but unchanged by this PR.
  • 📁 packages/desktop-app/src/lib/components/query/query-editor.svelte:45,170 (fed from 📁 query-node-viewer.svelte:661) — offers all fields as filter properties. The distinction the predecessor drew — filtering on a backend-owned field is a legitimate query, displaying it as a column is not — is explicitly blessed by the helper's own docstring (📁 schema-field-visibility.ts:13-15: "Surfaces that use fields for something other than rendering — offering query filter properties, say — make their own call"). Judgment holds.

No consumer was missed by the sweep except #3 above, which is an open-coded equivalent rather than a leak.

5. The getSchema mock cast is not the project's convention
📁 packages/desktop-app/src/tests/services/relationship-viewer-target-fields.test.ts:38

const getSchema = backendAdapter.getSchema as unknown as ReturnType<typeof vi.fn>;

This is the only as unknown as ReturnType<typeof vi.fn> in src/tests/services/. The established pattern there is vi.mocked() — 📁 collection-authoring.test.ts:35-37 does exactly this shape, including for a backendAdapter method:

const createNodeMock = vi.mocked(backendAdapter.createNode);

vi.mocked(backendAdapter.getSchema) is a drop-in replacement here and is strictly better: it preserves the function's real signature, so mockResolvedValue is type-checked against Promise<SchemaNode> rather than accepting anything. The current cast erases that — mockResolvedValue(42) would compile. It doesn't violate the no-any rule (the double cast is not any), so this is polish, not a standards violation, but it's free polish that also buys type safety.

6. Nit: the new doc comment is accurate — I checked every claim in it
📁 packages/desktop-app/src/lib/services/relationship-viewer-service.ts:106-110

I checked this specifically because the #2404 review caught a doc-comment overclaim. This one is clean:

  • "a convergence marker" — accurate; _possible_duplicate is local_only: true and set by mark_possible_duplicates (📁 core_schemas.rs:1317-1327).
  • "an ai-chat capture:transcript" — accurate, protection: System (📁 core_schemas.rs:1036-1040).
  • "Same predicate the table and detail views use" — verified true: 📁 table-view.svelte:49 and 📁 generic-schema-form.svelte:52 both call isUserVisibleField.

The only softness is "not something to offer as a column any more than as an editable control", which is a rhetorical parallel rather than a factual claim, and reads fine. No change needed.

7. Nit: the empty-schema case is thin but earns its keep
📁 packages/desktop-app/src/tests/services/relationship-viewer-target-fields.test.ts:175-179

'still returns [] for a schema with no fields at all' mostly re-tests ?? [], which TypeScript already guarantees. But the word "still" is doing real work: it pins that the new filter didn't change the pre-existing documented contract ("Returns [] when the schema has no fields", line 105). Cheap, and it's the kind of assertion that catches a future refactor that swaps the ?? for something clever. Keep it.

The genuinely valuable sibling is 'returns [] when every field on the target schema is system-protected' (lines 152-161) — that one is filter-specific and would catch a "fall back to unfiltered when the filtered set is empty" mistake, which is a real thing people write.

8. Nit: _internal_marker on a user-defined venue type
📁 packages/desktop-app/src/tests/services/relationship-viewer-target-fields.test.ts:139-150

I could not find a path by which a user-defined (non-core) schema acquires a protection: 'system' field — create_schema/update_schema don't appear to grant System. So this fixture may describe a state the backend can't produce. That said, testing the predicate rather than the reachability is defensible: the service shouldn't care how a field got its protection level, and the test documents that intent clearly. Inherited from the predecessor. Leaving as-is is fine.


Project Standards

Standard Status
No lint suppression ✅ none present
No any types ✅ the double cast in #5 is unknown-mediated, not any
No backward-compat / migration code ✅ predicate applied directly, no dual-mode
createLogger not console.log ✅ existing log untouched; test mocks the logger module cleanly
No new dependencies ✅
Atomic change ✅ single cohesive purpose

On the issue number in the module header — 📁 relationship-viewer-service.ts:2 reads Relationship viewer + editor service (issue #1918), which does contravene CLAUDE.md's "do not embed GitHub issue numbers in documentation content or code comments."

Recommendation: leave it. Three reasons: (a) it's pre-existing, untouched by this diff, and cleaning it here would make a two-line bug fix non-atomic; (b) the practice is widespread in this codebase — 📁 src/tests/helpers/mock-tauri-core.ts:9-11,23 carries core#2170 and core#2165 references in its header, so this is not an isolated oversight but a repo-wide cleanup; (c) a targeted sweep issue is the right container for it. Worth filing; not worth blocking or expanding this PR for.


Architecture

Is the service the right layer? Yes. I considered the two alternatives:

  • Filter in resolveColumnCandidates — worse. That function is pure, synchronous, and takes string[], not SchemaField[]. Filtering there would mean threading protection metadata through the modal purely so the pure function could re-derive something the fetch already knew. It would also mean the modal's targetFieldNames state holds names it must never show, which is a footgun for the next feature that reads that state.
  • Filter at the picker (candidatesFor / template) — worst. Presentation-layer filtering leaves the unsafe list live in component state and has to be re-applied by every future consumer.

Filtering at the fetch boundary means the unsafe names never enter the frontend at all. That's the strongest form of the fix.

Does any other caller want the unfiltered list? No — I checked. fetchTargetSchemaFields has exactly one production caller: 📁 relationship-viewer-modal.svelte:266, inside ensureTargetSchema, and its result feeds only the column picker. There is no second consumer with a competing need, so narrowing the function's contract costs nothing. Had there been one, the right move would be a separate fetchAllTargetSchemaFields rather than pushing the filter downstream — but that's YAGNI here.

The function name doesn't advertise the filter, which is a mild readability cost, but the doc comment covers it and fetchUserVisibleTargetSchemaFields is a worse name than a good comment.

Security

The core value of the change. capture:transcript is documented in core_schemas.rs as raw PTY scrollback that may contain secrets, tokens and absolute paths. Pre-fix, any relationship group targeting ai-chat offered it as a one-click column. Exposure was narrower than #2376's (opt-in checkbox vs. default-visible column, and it required a relationship group targeting a type with system fields) — but it was the same defect on a second surface, and it's now closed at the boundary rather than the render.

Testing & Verification

Test counts reported (232 files / 4863 tests, delta exactly +1/+6 from baseline), test:all exit 0, quality:fix clean, and the new test confirmed red in 4 of 6 cases against the unfixed service — that last one is the part that matters, and it's the right way to prove a regression test actually regresses.


Recommendation

APPROVE.

Correct fix, correct layer, correct pattern reuse, well-tested, and it closes a genuine data-exposure surface. Findings 1 and 2 (fixture accuracy and fixture duplication) are worth a follow-up commit on this branch or a fast follow-up PR — they're cheap and they compound, since the wrong type values now exist in two files. Everything else is polish or out-of-scope cleanup best captured as separate issues:

  • Fixture type corrections + shared schema-fixtures.ts helper (findings 1 + 2) — recommend doing on this branch
  • task-schema-form.svelte:121 → isUserVisibleField (finding 3) — new issue
  • vi.mocked() instead of the double cast (finding 5) — trivial, do it here if touching the file anyway
  • Repo-wide sweep of issue numbers in code comments (standards section) — new issue

@malibio malibio left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Automated pragmatic-code-review: APPROVE (posted as a comment — GitHub blocks self-approval). Full findings in the review comment above.

Test-only; no production code touched.

The review caught that "verbatim from core_schemas.rs" was not true of four
`type` values. Verified each against the Rust source and corrected them:
provider string->enum, model string->text, last_active date->datetime,
capture:session_id string->text. Nothing asserted on `type`, so no test was
failing — but the docstring claimed fidelity the fixture did not have, and
`eligibleGroupByFields` filters on `type === 'enum'` specifically, so `type` is
exactly the attribute a future reader would reason from.

Those errors existed in two files because the ~50 lines of fixtures were
copied rather than shared — the duplication is what let one mistake become
two. Extracted them to tests/helpers/schema-fixtures.ts, now the single home
for the core-schema shapes, and pointed both files at it. Also exported the
system-field name and label lists, since the two surfaces assert on different
ones: the service returns field names, the table renders friendlyNames.

Swapped the `as unknown as ReturnType<typeof vi.fn>` cast for `vi.mocked()`,
which is what the rest of src/tests/services/ uses and which type-checks the
`mockResolvedValue` argument rather than erasing it.

Skipped, with reasons:

- task-schema-form.svelte:121 open-codes the predicate instead of using the
  shared helper. Real drift, but an unrelated file and a different form
  surface; filed rather than folded in here.

- The pre-existing "issue #1918" in relationship-viewer-service.ts's module
  header. Untouched by this diff, and the practice is repo-wide, so cleaning
  it here would trade atomicity for a partial fix. Worth a sweep of its own.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01QuokiCVxSgdd5HSQqZuzcf
@malibio

malibio commented Sep 7, 2026

Copy link
Copy Markdown
Collaborator Author

Review addressed — 2ba04bbd

APPROVE with two 🟡 fixture-accuracy findings and several 🟢. Test-only changes; no production code touched.

✅ Addressed (3)

1. 🟡 Four fixture type values were wrong despite a "verbatim" claim

The review was right, and I verified each against core_schemas.rs rather than taking it on trust:

field was actual (core_schemas.rs)
provider 'string' "enum" (:618)
model 'string' "text" (:654)
last_active 'date' "datetime" (:701)
capture:session_id 'string' "text" (:1015)

I also checked the six I wasn't told about — status, context_tokens, created_nodes, messages, capture:transcript, capture:summary, plus all three person fields — and those were correct.

No test asserted on type, so nothing was failing. But two docstrings claimed fidelity the fixture didn't have, and eligibleGroupByFields filters on type === 'enum' specifically, so type is precisely the attribute a future reader would reason from.

2. 🟡 ~50 lines of fixtures duplicated byte-identically

This is the mechanism behind finding 1 — copying the data is what let one mistake land in two files. Fixing the types without deduplicating would leave the trap armed. Extracted to 📁 packages/desktop-app/src/tests/helpers/schema-fixtures.ts as the single home for core-schema shapes, with both files pointing at it.

Exported AI_CHAT_SYSTEM_NAMES and AI_CHAT_SYSTEM_LABELS separately, since the two surfaces assert on different things: the service returns field names, the table renders friendlyNames.

3. 🟢 Mock cast wasn't the project convention

Swapped as unknown as ReturnType<typeof vi.fn> for vi.mocked(), matching the rest of src/tests/services/. It also type-checks the mockResolvedValue argument instead of erasing it.

⏭️ Skipped (2) — both filed

4. 🟢 task-schema-form.svelte:121 open-codes the predicate → filed as #2414

Real drift, and now the last inline copy. But it's an unrelated file on a different form surface, and only one of its two conjuncts is isUserVisibleField — so it's a readability fix, not a correctness one. Folding it in would widen a PR scoped to the relationship picker.

5. 🟢 Pre-existing issue #1918 in the module header

Agreed with the review's own call to leave it: untouched by this diff, and the practice is repo-wide (mock-tauri-core.ts carries core#2170/core#2165), so cleaning one instance trades atomicity for a partial fix. A sweep is its own task.

On the by-argument acceptance criterion

The review independently verified the claim I made about criterion 3 — two writes to targetFieldNames, one read, ensureTargetSchema the only producer with a single call site, no alternate route into the picker — and concluded a modal-level test would add only marginal value. Good to have that checked rather than assumed.

Verification

  • Both affected test files pass (11 tests). Re-confirmed the tests still fail 4-of-6 against the unfixed service after the refactor, so deduplication didn't cost them their teeth.
  • bun run test — 232 files / 4863 tests passing, on two consecutive full runs.
  • bun run quality:fix — clean: 2497 files, 0 errors, 0 warnings; cargo fmt and clippy pass.

One note: an intermittent failure in architecture-benchmarks.test.ts ("bulk structural operations") appeared in one run and passed in the next two, measuring 12.32ms against a 40ms threshold. It's the same flake that tripped the pre-push gate earlier — wall-clock sensitive, unrelated to this change, and now observed failing roughly 2 of 5 runs. Possibly worth its own issue alongside #2402.

Re-Review Decision

Decision: NO RE-REVIEW NEEDED

Rationale: Test-only changes with no production diff since the approved review. The fixture corrections make assertions more faithful to the Rust source, the extraction is a pure move of byte-identical data to one home, and vi.mocked() is a stricter drop-in for a cast. The key risk of a test refactor — silently weakening the tests — was checked directly by reverting the fix and confirming 4 of 6 still fail. Both skipped items are filed rather than deferred silently.

@malibio
malibio merged commit 827e113 into main Sep 7, 2026
@malibio
malibio deleted the issue-2408-relationship-system-fields branch September 7, 2026 15:20
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.

Relationship modal offers protection:system fields as target columns

1 participant