Repository navigation
Description
Problem
Native Word charts (word/charts/chartN.xml, usually backed by an embedded workbook in word/embeddings/*.xlsx) can't be seen, addressed, read, updated or created. A drawing that contains c:chart turns into an anonymous ChartRun { type: "chart", kind: "chart" } (classifyDrawing in src/core/ast/read.ts), and read prints `[chart]` with no id, type, title or data (src/cli/read/markdown.ts). So an agent asked to "update the chart with Q4's numbers" or "add a bar chart of this table" has two options: give up, or render a PNG and use images add. That leaves a picture where the user expected a chart they can edit in Word.
Repro (main @ e176d62), using an open-source fixture: an appendix from a US Treasury (TIGTA) Annual Audit Plan, committed to LibreOffice's test corpus:
curl -sSfLO https://raw.githubusercontent.com/LibreOffice/core/a05ad6dd36f73647cdf0839d2c18dbc1d399c792/chart2/qa/extras/data/docx/PieChartDataLabels.docx
docx read PieChartDataLabels.docx # `[chart]` <!-- docx:p p2 align="center" --> (no id, no title, no data)
docx find PieChartDataLabels.docx "Audit Focus" # no matches: the chart title is invisible
docx wc PieChartDataLabels.docx # 43 words; the 12 slice labels and the title aren't counted
docx images list PieChartDataLabels.docx # []
docx raw part get PieChartDataLabels.docx --name word/charts/chart1.xml # the only way to see the data| What | Today |
|---|---|
| Visibility | `[chart]` with no locator, type, title, series or size |
| Data | only via raw part get, as cached c:strCache/c:numCache values. The source of truth for Word's Edit Data is the embedded workbook, which no verb can reach |
| Edit the paragraph around it | works: chart part, part rels and xlsx come through byte-identical (verified) |
delete --at p2 |
drawing removed; chart1.xml, its rels, the 58 KB xlsx and the document rel stay behind as a harmless orphan (verified) |
| Update the data | none. raw part edit on the cache "works", but the workbook goes stale: both Word and LibreOffice render the cache and ignore the workbook (verified, below), so the doc looks right until someone clicks Edit Data |
| Create a chart | none. The raw pipeline can't even do it by hand: raw part add refuses word/charts/_rels/chart1.xml.rels ("Relationship parts aren't created directly"), so a chart can't be wired to its workbook |
| Validation | docx validate checks WML-root parts only; chart XML is never schema-checked (raw part edit inserting <c:bogus/> into a chart passes every gate), even though dml-chart.xsd is already bundled |
Proposal: a charts noun, in four phases
Images are the precedent (images add/list/extract/replace/delete, imgN). Each phase ships on its own and keeps the write-read loop closed.
Phase 1: visibility (chartN locator, docx:chart hint, AST)
-
chartNis a positional id, in document order, forkind: "chart"only. SmartArt, shapes and other drawings keep their current placeholder; they aren't charts. LikeimgN/eqN/tbxN, the numbering covers every story a chart can live in: body, table cells, text boxes and headers/footers (LibreOffice'schart-in-footer.docxhas one). -
The
ChartRunAST gains:idchartTypes: string[](a list: one plot area can hold several, e.g.testSeriesIdxOrder.docxisbarChart+lineCharton a secondary axis)title?series: { name, categories, values, nameRef?, categoriesRef?, valuesRef?, formatCode? }[], from the cachesdataSource: "embedded" | "external" | "none"widthEmu/heightEmutrackedChange?, same asImageRun
By the "everything we parse is in the AST" rule, the parsed data belongs here.
-
readkeeps the placeholder token and adds a metadata hint, following thedocx:imageshape. The locator rides as a bare leading token, per the naming rule:`[chart]` <!-- docx:chart chart0 type="pie3D" title="Audit Focus Areas" series="1" points="12" size="6x3.6in" --> `[chart]` <!-- docx:chart chart1 type="bar+line" series="2" points="13" -->chart0,typeand the series/points counts always show: they're what an agent decides on.titleshows when there is one. Everything else is deviation-only:data="external"/data="none"(embedded is the norm),readonlyfor chartex (below),float/wraplike images, and possiblystale="yes"when the cache disagrees with the workbook. The importer drops the hint like every otherdocx:comment. (The separate in-progress fix that makes`[chart]`safe to copy back througheditis out of scope here.) -
wckeeps counting whatreadshows; open question 1 covers whether chart text should count.
Phase 2: charts list / charts extract
docx charts list FILE # JSON array; id is the --at handle
docx charts extract FILE --at chart0 [--csv | --json] [-o PATH]
listitems:{ id, at: "p2", type, title, series: [names], points, data: "embedded"|"external"|"none", workbook?: "word/embeddings/Microsoft_Excel_Worksheet1.xlsx" }.extract --csvwrites one header row (category,<series 1>,<series 2>…) and one row per category, from the caches. The caches are what the reader sees on the page, and they're the only data adata="none"or external chart has.--jsongives the full series objects, including refs and formatCode.extract's CSV is exactly whatset-datatakes in, so extract → edit the CSV → set-data is the loop.
Phase 3: charts set-data --at chartN --csv PATH|-
docx charts set-data FILE --at chart0 --csv q4.csv [--title "Revenue by Quarter"] [--dry-run] [-o PATH]
docx charts set-data FILE --batch updates.jsonl # {"at":"chart0","csv":"…"}: all ids as read
This rewrites both the chart caches and the embedded workbook, in place, through XmlNode refs. It never regenerates either: the TIGTA workbook has 8 sheets, a chartsheet, external links and print areas, and all of that has to survive.
- Resolve
chart0→<c:chart r:id>→ chart part → its part rels →c:externalData r:id→packagerel → embedded xlsx (or anoleObjectexternal link, or nothing). - Parse the CSV (RFC 4180). The header row holds the series names and the first column the categories. An empty cell is a gap, written as a missing
c:pt, not as 0. - Caches. Per series: rewrite
tx/strCache,cat(keep the existing cache kind: a date axis is anumRefwith a dateformatCode; POI's radar and stock charts use Excel serials such as 37261),val/numCache, and everyptCount. Prune per-point overrides (c:dPt,c:dLbl) whoseidxfalls past the new count. Adding a series clones the lastc:serwith freshidx/orderand strips itsspPr/dPtso the palette colors it by index. Removing one drops the trailingc:ser. - Refs. Recompute each
c:ffrom the existing top-left anchor and orientation (series in columns or rows, detected from the existing ranges). Keep the sheet name, quoted the way Excel quotes it ('Summary-Staff Day Alloc'!$D$5:$D$16). - Workbook (jszip + our XML parser; see "xlsx" below):
- Resolve the sheet by name through
xl/workbook.xml→xl/_rels/workbook.xml.rels. Never guesssheetN.xml: in the TIGTA workbook, "Summary-Staff Day Alloc" isrId6→worksheets/sheet5.xml. - Write cells and keep each existing cell's
sstyle. Strings go intosharedStrings.xmlwhen it exists, as inline strings otherwise. - Keep
<row>/<c>sorted, and update<dimension>. - When an
xl/tables/tableN.xmlcovers the range (Word's default chart workbook always hasTable1), update itsref, and itstableColumn/@namevalues to the new header text. A mismatch makes Excel "repair" the file. - On shrink, clear the cells that fell out of the old range.
- Resolve the sheet by name through
- Refuse (
UNSUPPORTED+ hint, nothing written) when:- A target cell holds a formula. In the TIGTA workbook every value is a shared formula (
D5 = H5/$H$18,ref="D5:D16"). We can't recalculate, and overwriting would silently break the author's model. See open question 2. - The data is an external link. LibreOffice's
TableOnPage3.docxpoints atfile:///C:\Users\…\Graph for pipeline 13 Feb.xlsxwithTargetMode="External". See open question 3. - It's a chartex chart (box & whisker, sunburst, waterfall, histogram, funnel, treemap). Its
mc:Fallbackis a PNG we can't regenerate, the same staleness problem the text-box Fallback had, but with no way to mirror it. These are read-only in v1. - The CSV equals the current data. A no-op is an error (
MATCH_NOT_FOUND-style), per the output contract.
- A target cell holds a formula. In the TIGTA workbook every value is a shared formula (
- Tracking. We don't yet know whether Word tracks chart-data edits; find out with the
scripts/word-redlines.shoracle before shipping. Until then follow the images/raw precedent: untracked; under document-level tracking, apply untracked plus a[docx-cli]audit comment; reject--track. - Output.
respondAckprintscharts.set-data chart0 (2 series × 4 points), andreadimmediately shows the new counts and title.
--title TEXT rewrites the c:title rich text in place, keeping the first run's a:rPr. It creates a title when there isn't one and sets autoTitleDeleted val="0".
Phase 4: charts add (authoring) and charts delete
docx charts add FILE (--after LOC | --before LOC | --at-end) --type column|bar|line|pie --csv PATH|- \
[--title T] [--width IN] [--height IN] [--legend right|bottom|none] [--grouping clustered|stacked|percent]
docx charts delete FILE --at chart0
addprints the mintedchartN(respondMinted). It writes:word/charts/chartN.xmlwith content-type Overrideapplication/vnd.openxmlformats-officedocument.drawingml.chart+xmlword/charts/_rels/chartN.xml.relswith apackagerelword/embeddings/Microsoft_Excel_WorksheetN.xlsxwith a Default or Override forapplication/vnd.openxmlformats-officedocument.spreadsheetml.sheet- a document
chartrelationship - an inline
<w:drawing>run whosedocPrid comes fromnextDrawingId
- Types, first wave:
column(barChart+barDir=col, the type people mean by "bar chart" in Word),bar(horizontal),line,pie. Second wave:doughnut,area,scatter, plus stacked/percent grouping. 3-D variants and chartex types aren't authored. - Write every default explicitly. We verified that both Word and LibreOffice smooth a line series when
c:smoothis absent, and that Word draws a rounded chart frame whenc:roundedCornersis absent. So the emitter writesc:roundedCorners val="0",c:smooth val="0",c:date1904 val="0",c:varyColors,c:markerandc:legendPos, rather than trusting the spec defaults. - The
chartStyle/chartColorStyleparts are optional. Our probe had neither, and Word (Mac) and LibreOffice both rendered it with theme-accent series colors (verified). Leave them out of v1. - Emitters are JSX components (
<ChartSpace>,<BarChart>,<Series>,<ChartDrawing>) in a newsrc/core/chart/, which also holds the read model and theChartslens (new Charts(document).list() / extract() / setData() / add() / delete()). LikeFontswith the theme, the workbook isn't a view: the lens reads, mutates and stagesword/embeddings/*.xlsxthroughdocument.pkgonly when a chart verb runs, so unrelated saves never re-zip it. deleteremoves the drawing run (an untracked removal of the last run keeps the paragraph, or not, the same wayimages deletedoes). It then prunes the document rel only whenisRelationshipReferencedsays it's unreferenced, and the chart/xlsx parts only when nothing else targets them. When in doubt, leave the orphan.
xlsx: no new dependency
package.json has no xlsx library; jszip and fast-xml-parser are already there.
- SheetJS (
xlsx): Apache-2.0, but the npm package is frozen at 0.18.5 with open advisories (prototype pollution, ReDoS), and newer builds ship only from their own CDN. Large. - ExcelJS (MIT): heavy, and it writes back from its own model. Anything it doesn't model is dropped (chartsheets, external links, printer settings, the TIGTA workbook's structure), which breaks the "mutate in place, don't round-trip" invariant one package down.
Both directions are small enough to own:
- Patching (phase 3): locate the sheet → set cells → maintain
sharedStrings,dimensionandtable. A few hundred lines over our ownXmlNode, in the same in-place style as the rest of the codebase. - Writing (phase 4): verified minimal workbook of 5 parts, about 2 KB:
[Content_Types].xml,_rels/.rels,xl/workbook.xml,xl/_rels/workbook.xml.rels,xl/worksheets/sheet1.xmlwith inline strings. LibreOffice opens it (soffice --convert-to csvgives back the exact grid), and Word renders a document that embeds it. Not yet verified: whether Word's Edit Data is happy with it, or wants Word's own default shape (styles.xml,sharedStrings.xml,theme1.xml,tables/table1.xmlwithref+tableColumnnames, as in every Word-made workbook in the corpora). Test that once, by hand, before choosing. Mimicking Word's shape costs about 4 KB and no code risk.
Smaller fixes this work needs (each also useful on its own)
- Schema-validate chart parts. Validate
c:chartSpace-rooted parts against the already-bundleddml-chart.xsd, indocx validateand in the raw part gates (WML_ROOT_TAGSinsrc/core/raw/validate.tsdecides what gets checked today). - Part-level relationships in raw. Let
rawaddress them (e.g.raw insert --part word/charts/chart1.xml --xml '<Relationship …/>'), so the escape hatch can wire a chart to its workbook. Today the hand-built path dead-ends there. - chartex reading.
classifyDrawingshould also recognizecx:chart(graphicData…/drawing/2014/chartex), so chartex charts get achartNand areadonlyhint instead of falling through tokind: "drawing".
Empirical findings (probed by hand through docx raw, rendered in both engines)
- Minimal charts render in both engines. A bar, line and pie chart, each a bare
c:chartSpacewith caches only (no workbook, no style/colors parts, noc:lang/c:date1904), wired throughraw part add+raw insert <Relationship>+raw insert <w:p><w:drawing>…<c:chart r:id/>, renders in Word for Mac and in LibreOffice, with no repair prompt. - The same chart with an embedded workbook renders too.
c:externalData r:id+c:autoUpdate val="0"+ apackagerel to the 2 KB workbook renders in both engines. The part rels had to be injected outside docx-cli; see smaller fix 2. - Both engines render the cache. With the cache changed (120 → 30) and the workbook left alone, Word and LibreOffice both draw 30. A cache-only edit therefore looks correct, and Edit Data then shows (and may restore) the old number. That's why
set-datamust write both. - Spec defaults are unsafe (see Phase 4): an absent
c:smoothgives a smoothed line in both engines, and an absentc:roundedCornersgives Word a rounded frame. - POI's
chartex.docxdoesn't use Word's chartex markup. It wraps its chartex charts inmc:AlternateContent Requires="cx"with a PNGmc:Fallback, and LibreOffice renders the fallback. But inside the chartex graphicData it usesc:chartand the plainchartrelationship type. Word-native chartex iscx:chart+ the…/2014/relationships/chartExrel (from the spec; we didn't check against a Word-made file). Test against both shapes.
Tests and coverage
-
Third-party fixtures go in
tests/fixtures/, unmodified, each recorded with source URL, commit, license and sha256 in a fixtures NOTICE (MPL-2.0 is file-level copyleft: committing the files unmodified next to MIT code is fine, and we keep the notice):PieChartDataLabels.docx, the primary realistic fixture. LibreOffice core, MPL-2.0,chart2/qa/extras/data/docx/@a05ad6dd36. 120 KB, sha25652c3ddfc…2374. The content is a TIGTA Annual Audit Plan appendix (a US federal work, so the content is public domain as well). Onepie3DCharttitled "Audit Focus Areas" with 12 categories, a0.0%formatCode, a rich-text title and athemeOverridepart. Its 58 KB, 8-sheet embedded workbook has a chartsheet, external links, a quoted sheet name, and values that are shared formulas, which makes it the refuse-formulas test case. It also has three sections with headers/footers and prose around the chart.
https://github.com/LibreOffice/core/blob/master/chart2/qa/extras/data/docx/PieChartDataLabels.docxtestSeriesIdxOrder.docx, the combo-chart fixture. LibreOffice core, MPL-2.0, @9ca4fa05eb. 26 KB, sha2561ef1d7ce…ef93. Real data (wine grape production in kt vs price in $/t, 2000-01 … 2012-13f):barChart+lineChartwith a secondary axis, an accounting formatCode, and series refs that start at different rows ($A$4vs$A$2). Exercisestype="bar+line".
https://github.com/LibreOffice/core/blob/master/chart2/qa/extras/data/docx/testSeriesIdxOrder.docxchartex.docx, the breadth fixture. Apache POI, Apache-2.0,test-data/document/@528591ba11. 133 KB, sha2565d7f0ca9…0b57. Six charts: bar, line, radar (date categories), stock, and two chartex (box & whisker, sunburst) with PNG fallbacks. Each has an embedded workbook plus style/colors parts. The data is placeholder, so it's for type coverage, not realism.
https://github.com/apache/poi/blob/trunk/test-data/document/chartex.docx- Optional edge cases, all LibreOffice MPL-2.0:
sw/qa/extras/ooxmlexport/data/chart-in-footer.docx(chart in a footer),chart2/qa/extras/data/docx/TableOnPage3.docx(externally linked workbook, anonymized text),chart2/qa/extras/data/docx/testMultipleChart.docx(three charts). - Already in the repo:
tests/fixtures/strict-profile.docx, a placeholder bar chart in the Strict profile namespace. Make sure the chart reader handles Strict too.
-
A dogfooding builder,
tests/fixtures/setup/charts.tsinCORE_FIXTURES:createa short quarterly report, thencharts adda column, line and pie chart,charts set-dataone of them to add a series and a category, and--titleanother. It round-trips through LibreOffice, and its read joins theeval:readsnapshots. The hint is a read-output change, so review the snapshot diff for length andsignalRatio. -
Unit tests:
- the reader on every fixture: types, titles, series, refs, date and multi-level categories, literal (
numLit/strLit) data set-datakeeps caches and workbook consistent: re-open the xlsx and compare cells to caches, including shape changes in both directions,table1.xmlref/columns and sharedStrings- every refusal path (formula, external link, chartex, no-op) exits nonzero and writes nothing
--batchresolves all ids against the document as readdeletenever dangles a rel- chart parts pass
dml-chart.xsd
- the reader on every fixture: types, titles, series, refs, date and multi-level categories, literal (
-
Word check (one-time, manual): open a
charts addresult and aset-dataresult in Word, click Edit Data, and confirm the grid matches and that nothing gets repaired. That settles the minimal-vs-Word-shaped workbook question. -
Weak-agent scenario: a new
quarterly-reportscenario whose fixture is built bycharts add.task.md, as a human would phrase it:Our Q4 numbers came in (below). Please update the revenue chart in the report so it includes Q4, change its title to "Revenue by Quarter, FY2026", and add a pie chart right after the summary paragraph showing each region's share of full-year revenue. They need to stay real charts I can click into and edit in Word, not pictures.
criteria.md(judge only) checks:chart0's caches and its embedded workbook both contain Q4- the new title is in place
- a second
c:chartexists with apieChartand its own workbook - no
images addPNG stands in for a chart (today's failure mode) - the render shows both charts
(Folding into
invoicewould also work, e.g. "the invoice has a spend-by-category chart; update it", but a report is where charts naturally live.) -
Docs: REFERENCE.md (the
chartsnoun, thechartNlocator, thedocx:charthint), a top-leveldocx --helpone-liner (that's how weak agents find features),src/cli/CLAUDE.md, a newsrc/core/chart/CLAUDE.md, and the skill's workflows section (the extract → edit CSV → set-data loop).
Open questions
- Chart text in
find/replace/wc. The title, series names and category labels are text a human reads first, and issue Text in text boxes is invisible to read/find/replace —mc:AlternateContentis never unwrapped #4 (text boxes) set the precedent thatreplace --allmustn't exit 0 while "Acme" sits somewhere visible. Proposal:findreports matches aschart0.replaceeither updates cache + workbook, or counts the chart hits and fails loudly.wccounts whatreadshows: the title, and labels only if the hint prints them. - Formula-backed data (the TIGTA case): refuse (proposed), offer
--overwrite-formulas(it replaces formulas with constants and says so), or refuse with a hint naming the precedent cells? We can't recalculate, so writing to the precedents won't update the cached<v>. - External workbooks: refuse, or
--cache-onlywith a warning that Word will refresh from the link (c:autoUpdate)? Updating a linked chart's cache is really a "this document lies until refresh" operation. - Does Word track chart edits? Check with the oracle (step 7 of phase 3). If Word doesn't, untracked plus an audit comment is the honest equivalent.
- The CSV dialect: do number formats in the CSV (
12%,$1,200,2026-01-31) set theformatCode, or must values be bare, with--formatseparate? Proposal: bare numbers, plus an optional--number-formatthat writes both the cacheformatCodeand the cell style. - Markdown authoring: should
insert/create --fromaccept a fenced```chartblock (type/title + a GFM table)? Not in v1: verbs are discoverable and the hint isn't parse-back. But it would makecreatea full report builder later. - The verb surface: a combined
charts set --at chart0 [--csv] [--title](likeheaders set), or keepset-data+--title?charts replace(swap a chart for a new type) is a later want.
🤖 Generated with Claude Code
Activity
kklimuk commentedon Nov 6, 2026
🤖 docx-cli triage
I opened #51 as the first slice of this issue: Phase 1 visibility and Phase 2
charts list/charts extract, both read-only.chartNlocator, thedocx:chartread hint, the cached series in the AST, a newcharts.docxfixture, and the docs.set-data, Phase 4add/delete, chartex, charts in headers/footers, and chart text infind/wc.The PR description lists the decisions that are yours to make.
Action needed: approve/merge — review #51, which is a first slice so it references #43 rather than closing it, and tick the decisions checklist in the PR.
Generated by Claude Code
feat(charts): chartN locator, docx:chart read hint, charts list/extract