Skip to content

Markdown skips extract_markdown in the Claude Code skill pipeline: docs go to the LLM instead of the structural extractor #2383

Open

Description

@lcatlett

Markdown never reaches extract_markdown in the skill pipeline: docs are sent to the LLM instead of the structural extractor

Repo: safishamsi/graphify · Version: graphifyy 0.9.32 (uv tool) · Backend: gemini-3-flash-preview


Summary

graphify/extractors/markdown.py is a deterministic, zero-token markdown extractor. It emits heading nodes, contains edges for heading nesting, and references edges for inline links, reference-style links, and [[wikilinks]] — all at confidence: EXTRACTED, with no LLM.

In the /graphify skill pipeline it never runs on .md files.

Step 3 Part A passes only detect['files']['code'] into extract(). detect classifies .md as document. Documents route to Part B (semantic/LLM extraction). So markdown files are sent to a model to have their structure inferred, while the exact structural parser for them sits unused.

Code does not have this problem: it gets the AST baseline and a semantic layer. references/extraction-spec.md even tells the model so:

Code files: focus on semantic edges AST cannot find (call relationships, shared data, arch patterns). Do not re-extract imports - AST already has those.

There is no equivalent instruction for documents, because no structural pass ran to make one true.

Relation to #2014

This is the complementary direction of #2014 ("Possible silent downgrade of semantic Markdown nodes during AST-only rebuild", fixed in v0.9.21, verified present in 0.9.32).

  • Possible silent downgrade of semantic Markdown nodes during AST-only rebuild #2014: the CLI graphify update path does run extract_markdown on .md, and it replaced the semantic layer with heading nodes. Fixed by making the semantic layer survive an AST-only rebuild.
  • This issue: the Claude Code /graphify skill pipeline never runs extract_markdown on .md at all, so the structural layer is never added in the first place.

Same two layers, opposite failure. #2014 stopped structural from clobbering semantic; this asks for structural to actually run alongside semantic — which is what the code path already does with AST.

Evidence

Same four markdown files, two paths.

Path A — what the pipeline actually did (Part B, Gemini): tokens spent, structure inferred, heading tree absent from the graph.

Path B — calling the structural extractor directly:

from pathlib import Path
from graphify.extract import extract
files = [Path('nlm/SPEC-governed-docs-corpus.md'), Path('nlm/nlm-corpus-spec.md'),
         Path('CONTRACT-technical-implementation-handback.md'), Path('prompts/fable5-prompting.md')]
r = extract(files, cache_root=Path('.'))
nodes: 48  edges: 49
relations: [('contains', 44), ('references', 5)]
input_tokens: 0  output_tokens: 0

Nodes carry real heading structure and source_location:

nlm_spec_governed_docs_corpus                              SPEC-governed-docs-corpus.md
nlm_spec_governed_docs_corpus_spec_governed_docs_corpus    SPEC: Governed Docs Corpus
nlm_spec_governed_docs_corpus_0_prior_art_read_before_...  0. Prior art — read before building anyt…
nlm_spec_governed_docs_corpus_1_why                        1. Why
nlm_spec_governed_docs_corpus_2_what_it_is                 2. What it is

48 nodes and 49 edges, deterministic, for zero tokens — from four files that the pipeline instead sent to an LLM.

Effect on a full run

Input: 28 files (26 documents/images, 2 code), 726k words, at ~/projects/meta-tools (files enumerated in graphify-out/manifest.json; greppable with rg <pattern> ~/projects/meta-tools/). Result: 491 nodes, 388 edges, 177 communities, 1,945,808 input / 64,399 output tokens.

Relation distribution in the resulting graph.json:

relation edges
references 131
calls 105
inherits 67
implements 50
imports 10
contains 8
rationale_for 7
conceptually_related_to 7
cites 2
semantically_similar_to 1

Only 8 contains edges across the whole graph, from 26 document files that collectively hold hundreds of headings — because the heading-structure pass never ran on them. In the four-file structural test above, those same four files alone produce 44.

Downstream, the graphify export wiki audit trail on document communities reports:

## Audit Trail
- EXTRACTED: 4 (50%)
- INFERRED: 4 (50%)

Half of a document community's relationships are model-reasoned, in a graph where a deterministic extractor for those same files was available and unused. 340 of 491 nodes finished with ≤1 connection.

Proposed fix

Run the structural pass on document-classified files before semantic extraction, mirroring the code path:

  1. Part A feeds structural extraction with .md/.mdx/.markdown/.rst files from detect['files']['document'], not just files['code']. _MD_LINKABLE_EXTS in extractors/markdown.py already enumerates the extensions.
  2. Part C merges structural + semantic for documents exactly as it does for code.
  3. references/extraction-spec.md gains the document analogue of the existing code instruction: "Do not re-extract headings or markdown links — the structural pass already has those. Focus on named concepts and relationships the parser cannot see."

This costs no new architecture — it reuses the AST/semantic split already proven on the code path — and it moves document structure from INFERRED to EXTRACTED while reducing token spend.

Measured effect of the fix

I applied it: ran extract() over the 24 document-classified .md files plus the 2 code files, merged the result into the existing semantic graph, and rebuilt. Structural extraction returned 367 nodes and 362 edges for 0 tokens.

nodes edges contains deg-0 components largest component
before 491 388 8 121 171 157
after 832 715 335 122 185 157

What the fix does deliver: +341 nodes, +327 edges, all EXTRACTED at zero token cost, and heading hierarchy going from 8 contains edges to 335.

What it does not deliver, stated plainly: connectivity is unchanged. The largest connected component stays at 157 nodes, fully-disconnected nodes go 121 → 122, and component count rises as each document grows its own heading tree. The structural pass recovers intra-document structure only. In this input the documents contain 2 cross-document markdown links in total, so there was nothing for the link extractor to connect.

I checked that this is not an ID-merge defect: taking one document (nlm/SPEC-governed-docs-corpus.md, 19 nodes in the rebuilt graph) and mapping its nodes to connected components puts 18 of 19 in a single component. The structural heading tree does attach to that document's semantic nodes. The disconnection is genuinely between documents.

That is worth stating because it separates the two problems cleanly. Routing markdown to the structural extractor is a correctness and cost fix, not a connectivity fix. Inter-document connectivity is a genuinely separate gap — see the frontmatter section below.

One incidental finding while testing: graphify.extract uses a process pool, and on macOS (spawn start method) a caller whose module-level code is not under an if __name__ == "__main__": guard causes every worker to abort with "A process in the process pool was terminated abruptly," silently dropping those files with only a per-file warning. The library recovers and reports 21 source file(s) produced zero nodes, which reads like an extraction failure rather than a caller-side spawn problem. A clearer diagnostic here would save debugging time.

Secondary: relation values are not validated against the declared enum

Possibly a separate issue.

The enum in references/extraction-spec.md is:

calls|implements|references|cites|conceptually_related_to|
shares_data_with|semantically_similar_to|rationale_for

85 of 388 edges (21.9%) in the run above carried values outside it — inherits (67), imports (10), contains (8).

These have two distinct origins, and the distinction matters:

  • contains (8) traced entirely to analysis/wall-of-text-analysis.py — emitted by the Python AST extractor, not the LLM. extractors/markdown.py emits it too. This is a legitimate structural relation that the documented enum simply omits.
  • inherits (67) came from document-classified .txt files, i.e. the LLM path inventing a relation the prompt never offered it.

So the enum is both incomplete (it omits relations graphify's own structural extractors legitimately emit) and unenforced (the LLM path adds more on top).

The adjacent field is validated strictly (file_type "MUST be one of exactly these six values... Any other value is invalid and will be rejected"), but relation appears unvalidated. Either enforce the enum, or widen it to include what extractors actually emit — manifest_ingest.py emits depends_on, cargo_introspect.py emits crate_depends_on, and extractors/markdown.py emits contains, none of which are in the documented enum. As it stands the documented schema and the produced graph disagree on roughly a fifth of edges, which makes graph.json unreliable for programmatic consumers.

Optional, lower priority: declarative relations in frontmatter

Independent of the above. Markdown's structural extractor recovers hierarchy (contains) and linkage (references), but not the kind of relationship — whether doc A supersedes, constrains, corrects, or merely mentions doc B. references/extraction-spec.md contains no lifecycle relation terms (supersedes, depends_on, constrains, corrects, derived_from, replaces, refines — all zero occurrences).

Frontmatter is already parsed for provenance (spec line 44: source_url, captured_at, author, contributor). A relations: block would let an author declare relation kind deterministically:

---
relations:
  supersedes: archive/historical/SPEC-old-playbook.md
  rationale_for: specs/indexing-plan.md
  cites: [specs/governed-docs.md]
---

Worth noting for scoping: the Open Knowledge Format (OKF) v0.2 spec — GoogleCloudPlatform/knowledge-catalog, okf/SPEC.md, §6.1 — deliberately declines to type links ("the specific kind... is conveyed by the surrounding prose, not by the link itself"), so this is not something an emerging standard will supply. It would be graphify's own extension.

The measurement above is the argument for it. Once markdown is routed through the structural extractor, the remaining disconnection is not a pipeline defect — it is the absence of any declarable inter-document relationship. Headings and links are recoverable from the file; "this spec supersedes that one" is not, because nothing in the format lets an author write it down.

Reproduction

uv tool install "graphifyy[gemini]" --force
cd <a directory of markdown docs>
python - <<'EOF'
from pathlib import Path
from graphify.extract import extract
import collections, glob
files = [Path(p) for p in glob.glob('**/*.md', recursive=True)][:5]
r = extract(files, cache_root=Path('.'))
print(len(r['nodes']), 'nodes', len(r['edges']), 'edges', r.get('input_tokens'), 'tokens')
print(collections.Counter(e.get('relation') for e in r['edges']).most_common())
EOF

Structural extraction returns nodes and edges at zero token cost. Then run the full /graphify pipeline on the same directory and compare contains edge counts in graphify-out/graph.json — the pipeline's count will be far lower, because Part A never received those files.

Environment

  • graphifyy 0.9.32 via uv tool, Python 3.13
  • macOS (Darwin 25.6.0), Apple Silicon
  • Backend: Gemini gemini-3-flash-preview, 28 chunks, max_concurrency=6, 0 failed chunks

Minor: openai missing from the base install

uv tool install graphifyy does not pull openai, which the Gemini backend requires for its OpenAI-compatible endpoint. With GEMINI_API_KEY set, all 33 chunks of a first run failed in under a second. The error message named the exact fix (uv tool install "graphifyy[gemini]" --force), so impact is low — but installing the extra when a Gemini key is present would remove a guaranteed first-run failure. Happy to file separately.

Activity

  1. Atom1250 commented on Aug 22, 2026

    @Atom1250

    Downstream consequence: mixing the CLI and skill paths freezes the structural layer, and stale heading nodes survive --update indefinitely

    Version: graphifyy 0.9.42 · corpus: ~11,400 nodes, mixed TypeScript monorepo + markdown docs · no Gemini key, so semantic extraction runs through skill subagents.

    This is the same defect from the other side. #2383 establishes that the skill pipeline never runs extract_markdown. The consequence when a project uses both entry points is that structural markdown nodes are not merely absent — they are present and permanently stale.

    How the two layers end up with different ages

    A project following the generated CLAUDE.md runs both paths by design. The install writes:

    After modifying code, run graphify update . to keep the graph current (AST-only, no API cost).

    and the same project runs /graphify --update when docs change. So:

    Path Runs extract_markdown on .md? Result
    CLI graphify update . yes (per #2014's fix) heading nodes minted, _origin: "ast", source_location: "L<n>"
    skill /graphify --update no (this issue) semantic nodes only, source_location: null

    The structural layer is therefore frozen at whenever the CLI last ran, while the semantic layer keeps advancing. Nothing reconciles them, because the skill's build_merge replace-on-re-extract keys on source_file, and the stale nodes' source files are still present — they are just describing headings that have moved or ceased to exist.

    Concrete case

    Renumbering an ADR heading in a docs file:

    - ## ADR-PIVOT-008: Seeded datapoint definitions stay in draft
    + ## ADR-PIVOT-015: Seeded datapoint definitions stay in draft
    

    Ran /graphify --update. It correctly re-extracted the file semantically and produced an ADR-PIVOT-015 node. But the graph afterwards contained both:

    ADR-PIVOT-008: Seeded datapoint definitions stay in draft   L264   _origin=ast   ← heading no longer exists
    ADR-PIVOT-015: Seeded datapoint definitions stay in draft   null                 ← from this run
    

    with the ghost still holding its five contains edges to Context / Decision / Consequences / Rejected alternatives. A query for ADR-PIVOT-008 returned two candidates — which is precisely the ambiguity the renumbering removed from the source file.

    Scale of the drift on one corpus

    Auditing every markdown-sourced node carrying an L<n> anchor against its file:

    • 1 ghost — label appears nowhere in its source file
    • 73 drifted — label still present, but at a different line

    The drifted set includes the surviving ADR-PIVOT-008 node anchored at L314 when the heading now sits at L264. So source_location on structural doc nodes is unreliable in general once any doc edit has occurred, not only after a rename.

    Why this is worse than the layer simply being missing

    If extract_markdown had never run, the graph would be structurally poorer but internally consistent. Because the CLI path does run it, the graph carries assertions with line anchors that look authoritative and are silently wrong. graphify query surfaces the ghost with the same confidence as a live node.

    What would fix it

    Running extract_markdown over changed documents during the skill's --update — the same treatment code gets, structural baseline plus semantic layer — resolves this and #2383 together. The re-extract would replace stale heading nodes for those files rather than leaving them beside the fresh semantic ones.

    Failing that, the incremental merge could prune prior _origin: "ast" doc nodes for any file being re-extracted, on the grounds that nothing in that run can refresh them.

    Workaround in the meantime

    Pruning nodes whose label appears nowhere in their source file, leaving merely-drifted ones alone (a full rebuild fixes those anchors, and removing them would lose real nodes to fix a line number). Worth noting for anyone else hitting this: the rule has to exclude file-root nodes, whose label is a path suffix like nx-import/SKILL.md rather than heading text — an initial pass without that exclusion flagged 80 nodes, of which 79 were legitimate file roots.

  2. rilkerfc commented on Sep 11, 2026

    @rilkerfc

    Measured on 0.9.57 with the same routing gap, from the other end: the heading nodes are not only skipped in the skill path, they are also skipped by headless graphify extract --backend claude-cli, and a later graphify update does not bring them back.

    Setup

    One TypeScript/JavaScript monorepo, 910 code files, 18 markdown files, 44 documents total for the semantic tier, built four ways from the same commit, all with diagnose multigraph clean (0 dangling, 0 duplicate, 0 self-loop).

    Build markdown nodes semantic edges a README section node findable by query?
    graphify update (AST only) 238 (file + heading nodes) 0 yes
    graphify extract --backend claude-cli 18 (one _doc node per file) 44 no
    the above, then graphify update 18 44 no
    skill Part A run over code and .md, then Part C merge with the semantic tier, build_from_json 238 43 yes

    Reading of the code

    detect classifies .md as document; the backend path hands documents to the semantic tier and never calls extract_markdown, and the skill's Part A passes only detect['files']['code'] to extract() (this issue). After a semantic layer exists, the #2014 / #1915 guards keep update from quick-scanning the file, so the headings stay absent. _doc_twin_remap (#1799) handles the file-node twin only.

    Why the headings matter to a reader

    A heading node is a pointer to a section, with a line. In a review workflow "does a document already cover X" is answered by that pointer and then by reading the file. The _doc node carries a good summary, but query no longer lands on the section, so the answer degrades from "README L159, this heading" to "some README".

    What worked

    Running extract() over the .md files as well as code, and merging the semantic tier on top in Part C, keeps both: the heading nodes and their contains structure from extract_markdown, plus the _doc node and its semantic edges for the same file. build_from_json accepted the mix without collisions. If that is an acceptable shape, the fix on the skill side is a one-line change to Part A's file selection; the CLI side would need the backend path to run the structural markdown pass before the semantic one.

    Happy to share the exact census script if useful. Version: graphify 0.9.57 (graphifyy on PyPI), Python 3.12.3, Linux.

  3. joriwang commented on Sep 18, 2026

    @joriwang

    The CLI graphify extract path has the same gap, and on an already-semantic corpus graphify update cannot close it either

    Confirming this from a different entry point than the one reported here. The original report is about the /graphify skill pipeline and notes in passing:

    #2014: the CLI graphify update path does run extract_markdown on .md

    For a docs-only corpus that has already been semantically extracted — which is the steady state for any CI-driven repo — neither CLI entry point runs extract_markdown on any file. Two different gates, same outcome. Verified in 0.9.33 and re-verified unchanged in 0.9.63.

    Gate 1 — graphify extract never routes .md to the structural pass at all

    classify_file() returns FileType.DOCUMENT for .md, so markdown lands in files_by_type["document"] and is dispatched to the semantic/LLM pass. The AST pass is fed only from the code bucket:

    cli.py:2887   code_files = [Path(p) for p in files_by_type.get("code", [])]
    cli.py:3178   ast_result = _ast_extract(code_files, **ast_kwargs)      # 0.9.33
    cli.py:3889   ast_result = _ast_extract(code_files, **ast_kwargs)      # 0.9.63
    

    extract.py does register ".md": extract_markdown in its dispatch table (0.9.33 line 4265), but nothing in the extract path ever hands it a .md. Decisive check: ast_doc_files appears 0 times in cli.py and 5 times in watch.py — the doc-aware routing exists only in the watch/update path. So this is not a gating question for extract; the structural pass has no entry point there.

    Gate 2 — graphify update reaches the gate, and #1915 closes it

    watch.py does add markdown to code_files via ast_doc_files, but then:

    watch.py:1572  # #1915: semantic-backed docs are never AST-quick-scanned; their
                   #        semantic nodes are the sole representation.
    watch.py:1634  extract_targets = [p for p in code_files if p not in semantic_doc_files]
    

    semantic_doc_files is computed from the existing graph, gated on file_type in (document, concept, rationale, paper, code) (#1954). Every doc in a warm corpus has at least a document node, so every doc is excluded and extract_targets contains no markdown.

    _reconcile_markdown_links (watch.py:525) does not help here: its docstring is explicit that it re-points an authored link "only when both files have unique representatives" and prunes links removed from their source — it maintains edges that already exist. On a corpus that was never quick-scanned there are no authored-link edges to reconcile, so it is a no-op. (For the record, PR #3191 which targeted the adjacent #3190 was closed unmerged, merged_at: null.)

    Net: on a warm, docs-only corpus there is no CLI invocation that produces deterministic markdown link edges. --code-only skips documents entirely, so it is not a workaround either.

    Measured impact on a production corpus

    Corporate SSOT repo (robotics engineering specs), 261 Chinese Markdown files, GitLab CI running graphify extract <root> --backend openai on every push, graphify-out/graph.json committed as the deliverable. Measured against graphify 0.9.33 output.

    I extracted every non-image inline link [text](…​.md) from the corpus and resolved it relative to the owning file:

    authored md→md inline links 28
    resolving to a file that exists 21
    present as an edge in graph.json 6
    missing 15

    The missing ones are not obscure. The worst single case:

    ALL/01_SRS_产品需求/ALL-SPEC-0001-V1.0-F1机器人系统需求规格.md
      graph:  1 node  (all_spec_0001_v1_0_document),  degree 0 — completely isolated
      source: 7 authored outbound links, to
                SYS-ADR-0001 电机参数_智元X1_L28
                SYS-ADR-0002 电机参数_智元X1_R52
                SYS-ADR-0003 电机参数_智元X1_R86-2
                SYS-ADR-0004 电机参数_智元X1_R86-3
                SYS-ADR-0006 电机参数_舵机_幻尔-HTD-35H
                ALL-SPEC-0002 关节命名与自由度定义
                ALL-ADR-0001  功能解耦与状态机总览
    

    The system requirements specification is an isolated node in the graph while explicitly naming seven other deliveries in its own markup. Every one of those targets exists in the graph with its own nodes. A deterministic [text](path.md) resolver would have produced all seven edges at zero token cost and confidence: EXTRACTED; instead all seven depend on the LLM choosing to emit them, and it did not.

    Eight other files are in the same fully-isolated state (degree 0), including three SYS-ADR-* motor/hardware parameter docs and an EtherCAT debugging post-mortem.

    Why this compounds with extraction truncation, and one honest caveat

    Because doc↔doc edges have no deterministic floor, they are lost whenever the semantic pass degrades. This corpus also has 154/259 md files reduced to a single node by output-budget truncation (a reasoning model spending max_completion_tokens on hidden CoT — same failure class as LightRAG #3597). A file that comes back hollow loses its whole cross-document neighbourhood with it, and nothing regenerates those edges later.

    Caveat, so the numbers aren't oversold: the correlation is not "hollow ⇒ no edges". Mean node degree is 2.73 for hollow files vs 3.15 for healthy ones, and only 9 of 154 hollow files are fully isolated. So this is not a wholesale collapse — it is specific, high-value, author-declared links missing while lower-value LLM-guessed ones (conceptually_related_to, semantically_similar_to) survive. In a graph where 104 edges are conceptually_related_to/INFERRED and 37 are semantically_similar_to/INFERRED, the authored references edges are the ones an engineer would actually trust, and they are the ones with no deterministic source.

    Suggested direction

    The reporter's framing — "this asks for structural to actually run alongside semantic, which is what the code path already does with AST" — is right, and #2333's COEXIST rule already establishes that an AST layer and a semantic layer can coexist on one document. Extending that to the extract path means feeding markdown-shaped documents into the same _ast_extract(code_files, …) call, which is what PR #3614 does for the skill pipeline.

    Two things worth deciding explicitly, since #1915 exists for a reason:

    1. Bloat. watch._rebuild_code produces a ~4× bloated graph vs graphify . --update — AST-scans Markdown docs, then merges preserved semantic nodes on top #1915 was introduced because quick-scanning semantic-backed docs minted heading nodes on top of semantic nodes (~4× growth). Running both layers on a docs-only corpus re-opens that. An option is to run extract_markdown on semantic-backed docs in edges-only mode — keep the references/links_to edges, discard the heading nodes, since the semantic layer already represents the document. That gets the deterministic cross-document edges without the duplication watch._rebuild_code produces a ~4× bloated graph vs graphify . --update — AST-scans Markdown docs, then merges preserved semantic nodes on top #1915 guards against.
    2. Canonical id mapping. _reconcile_markdown_links already solves "the canonical file node is absent because the target is semantic-backed" by re-pointing to a unique representative. The same mapping is what an edges-only structural pass would need, so the hard part appears to be written.

    If (1) is acceptable I can try the edges-only variant against this corpus and report the before/after edge counts — the 21-link measurement above gives a small, fully enumerable ground truth to score it against.

  4. ChaseFlorell commented on Sep 28, 2026

    @ChaseFlorell

    Data point on a consequence of this, from graphify 0.9.69 with the Claude Code skill pipeline.

    The corpus has ~290 markdown docs, including architecture decision records that cross-link each other with relative links ([ADR-0126](ADR-0126-some-title.md)). Because the docs go to semantic subagents, each chunk mints its own node ID for a cited doc, so a single ADR ended up as 2–4 nodes, e.g.:

    • adr_0096_an_attachment_uploads_on_attach_and_is_claimed_at_submission
    • docs_decisions_adr_0096_an_attachment_uploads_on_attach_and_is_claimed_at_submission
    • adr_0096_attachment_upload_on_attach_claimed_at_submission

    Across the corpus, 97 docs had duplicates (333 surplus nodes). The duplicates split neighbourhoods across communities and produced spurious AMBIGUOUS edges between near-identical reference nodes, which then became "suggested questions" in GRAPH_REPORT.md.

    The link target is a real file in the corpus, so the ID is knowable without an LLM. If markdown went through the structural extractor (or relative links were resolved to the target file's node ID, as #951 proposes), these would be deterministic. As a workaround I post-processed the extraction: grouped nodes by the cited document's number and re-pointed edges to the node from the document's own file.

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

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions