Skip to content

feat(topology): materialize session identity and lineage graph #866

Closed

Description

@Sinity

Problem

Polylogue has partial lineage fields, but no durable topology graph that coding agents can rely on for sessions, continuations, sidechains, subagents, forks, unresolved native parents, and artifact/source provenance.

Current substrate is useful but incomplete:

  • conversations.parent_conversation_id and branch_type give one resolved parent edge.
  • messages.parent_message_id and branch_index give message-local lineage.
  • identity_ledger tracks provider/source identity across reset cycles, not session topology.
  • work_threads summarize lineage for insights, but are not a general graph contract.
  • Parser/materialization paths can drop or null unresolved provider-native parent edges when the canonical parent row is absent.

This issue owns the graph. #864, #839, #802, #838, and #848 consume or supply evidence, but none of them should invent topology ad hoc.

Scope

Define and materialize a canonical topology model for:

  • conversation/session lineage;
  • message branches;
  • provider-native parent/child IDs;
  • continuations, sidechains, forks, and subagents;
  • raw/source/artifact/hook links where available;
  • unresolved parent edges that can be repaired when the parent arrives later;
  • edge provenance, confidence, observed source, and resolution state.

Expected implementation shape:

  • Keep conversations.parent_conversation_id as the fast resolved parent pointer where it is sufficient.
  • Add a typed topology projection/table set when one FK cannot preserve the semantics, for example topology edges with edge type, native IDs, resolved IDs, raw/artifact evidence, confidence, status, and timestamps.
  • Move work_threads to consume this topology projection, or document exactly why work_threads remains a derived lineage summary rather than the topology source of truth.
  • Expose topology reads through archive operations / Python API first. Reader, MCP, and context packs should adapt the shared read model later.

Likely files/modules:

  • polylogue/storage/sqlite/schema_ddl_archive.py
  • polylogue/storage/sqlite/schema_ddl_identity.py
  • possible new polylogue/storage/sqlite/schema_ddl_topology.py
  • polylogue/pipeline/prepare_enrichment.py
  • polylogue/pipeline/materialization_runtime.py
  • polylogue/pipeline/services/ingest_batch/
  • polylogue/storage/repository/archive/tree.py
  • polylogue/archive/conversation/threads.py
  • polylogue/storage/insights/session/threads.py
  • polylogue/operations/archive.py
  • polylogue/sources/parsers/claude/code_parser.py
  • polylogue/sources/parsers/codex.py
  • ChatGPT parser branch/message handling
  • docs/architecture.md
  • docs/insights.md if thread semantics change

Non-goals

Dependencies

Acceptance criteria

  • Missing provider-native parents are preserved as durable unresolved edges instead of being discarded.
  • Late parent arrival deterministically resolves or repairs previously unresolved edges.
  • Cycles are rejected, quarantined, or marked invalid with structured evidence.
  • Claude Code subagent/sidechain, Codex continuation, and ChatGPT branch/message fixtures are covered.
  • Topology read model exposes ancestors, descendants, siblings, thread/root membership, edge type, confidence, and provenance.
  • work_threads either consumes the topology model or is explicitly documented as a derived lineage summary.
  • No topology semantics land only in provider metadata.

Verification

Focused checks should include:

  • parser fixture tests for Claude Code, Codex, and ChatGPT lineage shapes;
  • storage topology tests for unresolved parents, late repair, cycles, ancestors/descendants/siblings, and provenance;
  • thread/insight refresh tests if work_threads changes;
  • devtools verify-schema-roundtrip when schema DDL or schema packages change;
  • devtools render-all --check when generated docs change;
  • devtools verify --quick, then full devtools verify before PR readiness.

Suggested new test file: tests/unit/storage/test_session_topology.py.

Refs #864 #839 #802 #840 #838 #848 #859 #852.

Activity

  1. added
    type:feat
    phase:architecture
    area:insights
    on May 6, 2026
  2. Sinity commented on May 7, 2026

    @Sinity
    OwnerAuthor

    Reconnaissance Report -- #866: topology/lineage graph

    Status: BLOCKED -- cannot start yet

    This issue depends on #864/#839/#840/#802. After audit:

    Recommendation: Cannot start until #864 has a stable shape for parent-conversation identity resolution. #840's inventory comment on lineage fields is needed but not a hard block.


    Build this

    1. Topology edge table (topology_edges): durable directed edges with:

      • edge_type: continuation, sidechain, fork, subagent, parent-of, child-of, unresolved
      • source_conversation_id, target_conversation_id (canonical Polylogue IDs once resolved)
      • source_provider_id, target_provider_id (native provider IDs, always preserved)
      • confidence: enum (resolved, inferred, unresolved, ambiguous)
      • edge_provenance: observed-source, parser-inferred, repaired
      • resolved_at, created_at, updated_at
      • Reach foreign keys for resolved edges
    2. Unresolved edge preservation: When parent_conversation_provider_id exists but the canonical parent row is absent (not yet ingested or before this child), store the edge with confidence=unresolved and target_conversation_id=NULL. Do NOT silently drop it.

    3. Late-parent repair: On ingest of a new conversation, check topology_edges for unresolved edges whose target_provider_id matches the new arrival. Resolve the FK, update confidence to resolved, and set resolved_at.

    4. Cycle detection: Before inserting any resolved edge, walk ancestors. If the proposed parent is a descendant of the child, reject with confidence=cyclic and structured evidence (the cycle path).

    5. Topology read model: Expose through ArchiveOperations:

      • get_conversation_ancestors(conv_id)
      • get_conversation_descendants(conv_id)
      • get_conversation_siblings(conv_id)
      • get_thread_root(conv_id)
      • get_thread_members(thread_root_id)
    6. work_threads consumes topology: Either rebuild work_threads from topology_edges or document exactly that work_threads is a derived lineage summary.


    Do NOT build this

    • Do NOT build a graph-first UI (feat(reader): finish interactive reader and unified surface shell #848 owns reader UI).
    • Do NOT create a generic knowledge graph (no entity extraction, no semantic web).
    • Do NOT store topology semantics only in provider_meta (use canonical tables).
    • Do NOT use raw JSONL rescans as the normal topology read model.
    • Do NOT add productivity/work-quality inference.
    • Do NOT add a new conversations column for every topology attribute -- use dedicated edges table(s).
    • Do NOT over-abstract: one topology_edges table with a typed edge_type enum is sufficient.
    • Do NOT make unresolved edges silently disappear.

    Files to touch

    File Change
    polylogue/storage/sqlite/schema_ddl_topology.py (NEW) topology_edges DDL, indexes, upgrade migration
    polylogue/storage/sqlite/schema_bootstrap.py Include new DDL module
    polylogue/pipeline/prepare_enrichment.py (L44-49) Write unresolved edges instead of discarding; check for children to repair
    polylogue/pipeline/materialization_runtime.py (L276-280) Ensure native parent ID flows through
    polylogue/pipeline/services/ingest_batch/ Post-ingest repair hook
    polylogue/operations/archive.py Topology read operations
    polylogue/archive/conversation/threads.py Consume topology model or document derivation
    polylogue/storage/insights/session/threads.py (if separate) Same
    polylogue/sources/parsers/claude/code_parser.py (L238-260) Ensure all lineage signals (subagent, sidechain, continuation) are captured with native IDs
    polylogue/sources/parsers/codex.py (L434-461) Same
    polylogue/sources/parsers/chatgpt.py Verify message-parent detection (currently only L70-74)
    docs/architecture.md Topology section
    tests/unit/storage/test_session_topology.py (NEW) Focused topology tests

    Coordination


    Focused tests

    # Parser fixture tests for lineage shapes:
    pytest tests/unit/sources/ -k "claude_code or codex or chatgpt" -q
    
    # Topology storage tests (new file):
    pytest tests/unit/storage/test_session_topology.py -q
    
    # Cycle detection, late repair, unresolved preservation:
    # (within above test file)
    
    # Insight refresh if work_threads changes:
    pytest tests/unit/storage/test_session_insight_refresh.py -q
    
    # Schema roundtrip:
    devtools verify-schema-roundtrip
    
    # Docs:
    devtools render-all --check
    
    # Broad gates:
    devtools verify --quick
    devtools verify  # before PR readiness
    

    Acceptance matrix

    Criterion Verifiable by
    Missing native parents preserved as unresolved edges Storage test: ingest child before parent, verify edge exists with confidence=unresolved
    Late parent arrival resolves edges Storage test: ingest parent after child, verify edge resolved, resolved_at set
    Cycles rejected/quarantined Storage test: create A->B->C, then try C->A, verify rejection
    Claude Code subagent/sidechain, Codex continuation, ChatGPT branch fixtures covered Parser fixture tests
    Topology read model (ancestors, descendants, siblings, thread root/members, edge type, confidence, provenance) Operation tests
    work_threads consumes topology or documented as derived summary Code inspection + docs
    No topology in provider_meta Schema inspection

    Ambiguities / Risks

    1. Unclear: Whether fix(archive): store context and protocol artifacts semantically, not via projection fallbacks #839's artifact-level semantics change what "target" a topology edge points to (conversation vs. message vs. artifact vs. action-event). Issue body says conversation and message targets; clarify in comment.
    2. Unclear: The ChatGPT parser (L70-74) only sets parent_message_provider_id per message. It does NOT set parent_conversation_provider_id on the conversation. Does ChatGPT have continuation/branch semantics to expose?
    3. Risk: The make_conversation_id(provider, provider_conversation_id) pattern may not produce stable IDs if provider_conversation_id format varies. Need to verify with existing fixtures.
    4. Unclear: Whether topology_edges should be a separate table or use conversations.parent_conversation_id as a resolved edge and add a parallel unresolved-edges table. The issue body favors a separate typed topology table.
  3. reopened this on May 7, 2026
  4. Sinity commented on May 7, 2026

    @Sinity
    OwnerAuthor

    Reopening after closed-issue/codebase reconciliation. This topology issue is not implemented; the close state appears to have preserved only reconnaissance.

    Current evidence on master:

    • No topology_edges, schema_ddl_topology, SessionTopology, or tests/unit/storage/test_session_topology.py exists.
    • The only durable lineage substrate is still conversations.parent_conversation_id plus derived thread/read helpers.
    • polylogue/pipeline/prepare_enrichment.py:53-58 still drops unresolved native parent references when the candidate parent is not in cache.known_ids.
    • tests/unit/pipeline/test_ingest_batch.py:285-301 explicitly asserts missing parent FKs are cleared to None, which is the opposite of this issue's unresolved-edge preservation requirement.

    Remaining scope stays here: canonical topology edge model, unresolved-edge preservation, late-parent repair, cycle handling, typed read operations, and storage/parser fixtures for Claude Code, Codex, and ChatGPT lineage shapes.

    Scope note: exclude this from #944 except as a referenced reopened issue.

  5. 9 remaining items

  6. Sinity commented on May 18, 2026

    @Sinity
    OwnerAuthor

    Decomposed into 4 slices

    Sequence: A blocks B/C/D. B/C/D can proceed in parallel after A lands.

  7. Sinity commented on May 24, 2026

    @Sinity
    OwnerAuthor

    Absorbed slice

    Slice D — typed read model API (was #1261)

    Scope:

    • Add operations on polylogue/operations/archive.py (or new topology operations module): get_topology(conv_id), get_ancestors, get_descendants, get_siblings, get_thread_root
    • Decide work_threads policy: consume topology OR document explicitly as derived lineage summary
    • Reader/MCP/context-packs adapt later (separate slices, not this one)

    Acceptance:

    • Contract tests in tests/unit/api/ for each read
    • work_threads decision recorded in PR + relevant module docstring
    • No new topology semantics live in provider_meta

    Optional expansion: expose graph queries via MCP as polylogue.get_session_topology for multi-agent orchestration use case.

    Original issue ref: #1261 — closed, content preserved here.

  8. Sinity commented on May 25, 2026

    @Sinity
    OwnerAuthor

    Cross-link from a 2026-05-25 archive audit: this issue's "session identity and lineage graph" is the prerequisite primitive for several follow-up insight tools. Concretely surfaced by data:

    • 28.4% of conversations (2,256/7,951) have parent_conversation_id set today — that's the substrate this issue would materialize against.
    • Without logical_conversation_id as a first-class join key, monthly session-count aggregates are wildly off: Jan 2026 reports 1,705 sessions / 280h engaged, May reports 125 sessions / 248h engaged. Same total engaged hours, 13× different session count — purely because of segmentation policy. The last_message_at-keyed rollup measures JSONL files, not logical chats.
    • :agent-acompact suffix is a marginal effect (72 conversations total, 0.9%). The bulk of the divergence is general resume-chain segmentation. Don't special-case :agent-acompact — use the general parent chain.

    Concrete deliverable that downstream issues now depend on:

    • Materialized logical_conversation_id column (or view) on session_profiles that walks the parent chain to a root.
    • Expose logical_session_count alongside session_count in day_session_summaries, week_session_summaries, productivity_rollups, session_tag_rollups.
    • One MCP tool get_logical_session(conversation_id) returning the full lineage (root + descendants + ordered timestamps).
    • Acceptance: SELECT COUNT(DISTINCT logical_conversation_id) FROM session_profiles WHERE first_message_at LIKE '2026-01%' returns a value strictly between 202 (conversations.created_at count for January, the lower bound) and 1,705 (session_profiles count, the upper bound).
    • Hygiene check: detect orphan children (parent_conversation_id points to a missing row) and any cycles; surface as MCP tool find_lineage_anomalies().

    Downstream consumers waiting on this primitive: #1529 (find_resume_candidates uses logical IDs as ranking keys), #1527 (workflow_shape rolls up at the logical level), #1528 (terminal_state of a logical session = state of its latest descendant).

  9. Sinity commented on May 25, 2026

    @Sinity
    OwnerAuthor

    Implemented the logical-session identity slice on feature/feat/logical-session-identity.

    What changed:

    • schema v13 adds session_profiles.logical_conversation_id, materialized from the existing parent-chain/thread-root helpers;
    • full rebuild and incremental refresh now write that logical root consistently;
    • day summaries and tag rollups retain physical conversation_count and add logical_session_count plus logical_conversation_ids_json;
    • week summaries union logical ids across day rows instead of blindly summing day logical counts;
    • Python API and MCP now expose get_logical_session(conversation_id) as the compact read-pull envelope: root, thread, siblings, descendants, cycle flag;
    • get_session_topology remains the full graph surface, so this does not duplicate topology edges.

    Focused local verification:

    • pytest tests/unit/api/test_topology_api.py ... tests/unit/mcp/test_insight_shape_tools.py -q -> 113 passed
    • python -m mypy polylogue ... touched tests -> clean across 859 source files
    • ruff format --check polylogue tests && ruff check polylogue tests -> clean
    • devtools render-all --check -> OK

    Remaining before closing #866: live archive rebuild/distribution evidence on the latest schema. This should be batched with the pending #1530 live evidence because schema v13 supersedes the earlier v12 rebuild target.

  10. Sinity commented on May 27, 2026

    @Sinity
    OwnerAuthor

    Claude Code 2.1.139+: machine-readable agent identity via OTEL + env vars

    Claude Code now emits agent lineage through two new channels:

    1. OTEL spans (2.1.139): llm_request spans carry agent_id + parent_agent_id attributes. tool spans carry the same. The parent_agent_id is set by the dispatching Agent tool span, so subagent lineage traces back to the originating session.

    2. CLAUDE_CODE_SESSION_ID (2.1.132): exported into every Bash subprocess environment. Any tool call, hook, or subprocess can read it.

    For polylogue topology, these provide observed lineage evidence (parser-independent, machine-assigned) alongside the existing parser-inferred parent references. A topology edge backed by both parser inference AND OTEL parent_agent_id has higher confidence than either alone.

    Suggested adjustment: Add OTEL agent_id/parent_agent_id and CLAUDE_CODE_SESSION_ID as recognized topology evidence sources in the edge-confidence model. These don't replace parser-inferred lineage — they're an independent signal that raises confidence or catches mismatches.

  11. Sinity commented on May 28, 2026

    @Sinity
    OwnerAuthor

    Future extension: dynamic agent addressability via topology

    Once the static lineage primitives are solid (topology_edges, logical session identity, typed read API), the natural extension is dynamic agent addressability: making a session routable at runtime via its logical session ID.

    What this enables:

    • Cross-agent messaging: "send this finding to the Codex session working on issue #N"
    • Operator routing: the operator can direct work to a specific running session
    • Polylogue-mediated subagent dispatch: a parent session asks polylogue to spawn a subagent and receives results through a shared channel
    • Integration with the blackboard surface: notes posted to a session's scope are visible to that session and related sessions

    Implementation sketch:

    • The channel ID IS the logical session ID (already materialized in session_profiles.logical_conversation_id)
    • Dynamic state ("is this session currently running?") is queried from agent-view or hook metadata — polylogue doesn't need to track liveness itself
    • Messaging is blackboard notes scoped to the channel's session ID
    • Read path: polylogue.read_channel(session_id) returns notes + lineage context

    Prerequisite for: recursive agent orchestration vision.

    This is a future extension, not current scope for #866. The static lineage primitives need to be solid first.

  12. Sinity commented on May 28, 2026

    @Sinity
    OwnerAuthor

    Infrastructure already exists in the codebase. topology_edges table + session_profiles.logical_conversation_id for #866. provider_events table for #1486.

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    area:insightsarea:schemaarea:storagephase:architecturetype:feat

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions