@iasiv5/dsh-skills 1.3.4 → 1.3.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (85) hide show
  1. package/README.md +1 -0
  2. package/package.json +3 -4
  3. package/skills/answer-me-with-html/SKILL.md +3 -3
  4. package/skills/answer-me-with-html/references/video.md +1 -0
  5. package/skills/answer-me-with-html/scripts/am.mjs +1671 -1131
  6. package/skills/code-review/results.tsv +6 -0
  7. package/skills/code-review/test-prompts.json +63 -10
  8. package/skills/darwin-skill/README.md +136 -121
  9. package/skills/darwin-skill/README_EN.md +138 -123
  10. package/skills/darwin-skill/SKILL.md +256 -421
  11. package/skills/darwin-skill/_archive/hero-2.0.gif +0 -0
  12. package/skills/darwin-skill/assets/banner-en.svg +1 -1
  13. package/skills/darwin-skill/assets/banner.svg +2 -2
  14. package/skills/darwin-skill/assets/chart-loop-en.html +2 -2
  15. package/skills/darwin-skill/assets/chart-loop-en.png +0 -0
  16. package/skills/darwin-skill/assets/chart-loop.html +2 -2
  17. package/skills/darwin-skill/assets/chart-loop.png +0 -0
  18. package/skills/darwin-skill/assets/chart-phases-en.html +12 -12
  19. package/skills/darwin-skill/assets/chart-phases-en.png +0 -0
  20. package/skills/darwin-skill/assets/chart-phases.html +13 -13
  21. package/skills/darwin-skill/assets/chart-phases.png +0 -0
  22. package/skills/darwin-skill/assets/darwin-3.0-launch.mp4 +0 -0
  23. package/skills/darwin-skill/assets/hero.gif +0 -0
  24. package/skills/darwin-skill/assets/result-card-example.png +0 -0
  25. package/skills/darwin-skill/docs/index.html +93 -357
  26. package/skills/darwin-skill/references/about-author.md +101 -0
  27. package/skills/darwin-skill/references/eval-protocol.md +156 -0
  28. package/skills/darwin-skill/references/skilllens-evidence.md +2 -1
  29. package/skills/darwin-skill/references/v3-evidence.md +114 -0
  30. package/skills/darwin-skill/scripts/darwin.py +400 -0
  31. package/skills/darwin-skill/scripts/screenshot.mjs +3 -2
  32. package/skills/darwin-skill/showcase.html +93 -357
  33. package/skills/darwin-skill/templates/result-card.html +36 -20
  34. package/skills/darwin-skill/templates/result-card.png +0 -0
  35. package/skills/darwin-skill/test-prompts.json +36 -12
  36. package/skills/docx/SKILL.md +5 -4
  37. package/skills/docx/scripts/office/helpers/__init__.py +22 -4
  38. package/skills/docx/scripts/office/helpers/pptx_chart.py +124 -11
  39. package/skills/docx/scripts/office/helpers/pptx_slide.py +43 -3
  40. package/skills/docx/scripts/office/soffice.py +85 -1
  41. package/skills/docx/scripts/office/validate.py +50 -7
  42. package/skills/docx/scripts/office/validators/base.py +16 -4
  43. package/skills/docx/scripts/office/validators/docx.py +59 -6
  44. package/skills/docx/scripts/office/validators/pptx.py +116 -8
  45. package/skills/docx/scripts/office/validators/redlining.py +292 -113
  46. package/skills/impeccable/SKILL.md +4 -2
  47. package/skills/impeccable/reference/adapt.md +1 -1
  48. package/skills/impeccable/reference/animate.md +17 -0
  49. package/skills/impeccable/reference/critique-rubric.md +496 -0
  50. package/skills/impeccable/reference/critique.md +12 -504
  51. package/skills/impeccable/reference/degraded/documenter.md +1 -1
  52. package/skills/impeccable/reference/degraded/motion-reviewer.md +29 -0
  53. package/skills/impeccable/reference/document.md +3 -1
  54. package/skills/impeccable/reference/foundations.md +44 -0
  55. package/skills/impeccable/reference/hooks.md +3 -3
  56. package/skills/impeccable/reference/live-setup.md +1 -1
  57. package/skills/impeccable/reference/live.md +26 -12
  58. package/skills/impeccable/reference/new-work-comp.md +24 -0
  59. package/skills/impeccable/reference/new-work-world.md +20 -0
  60. package/skills/impeccable/reference/new-work.md +6 -34
  61. package/skills/impeccable/reference/typeset.md +6 -0
  62. package/skills/impeccable/reference/visualize.md +1 -1
  63. package/skills/impeccable/scripts/VERSION +1 -1
  64. package/skills/impeccable/scripts/engine-checksums.txt +5 -5
  65. package/skills/impeccable/scripts/live-browser.js +51 -22
  66. package/skills/pdf/{forms.md → FORMS.md} +1 -1
  67. package/skills/pdf/{reference.md → REFERENCE.md} +3 -2
  68. package/skills/xlsx/SKILL.md +19 -14
  69. package/skills/xlsx/scripts/office/helpers/__init__.py +22 -4
  70. package/skills/xlsx/scripts/office/helpers/pptx_chart.py +124 -11
  71. package/skills/xlsx/scripts/office/helpers/pptx_slide.py +43 -3
  72. package/skills/xlsx/scripts/office/soffice.py +85 -1
  73. package/skills/xlsx/scripts/office/validate.py +50 -7
  74. package/skills/xlsx/scripts/office/validators/base.py +16 -4
  75. package/skills/xlsx/scripts/office/validators/docx.py +59 -6
  76. package/skills/xlsx/scripts/office/validators/pptx.py +116 -8
  77. package/skills/xlsx/scripts/office/validators/redlining.py +292 -113
  78. package/skills/xlsx/scripts/recalc.py +731 -136
  79. package/skills-manifest.json +1 -1
  80. /package/skills/darwin-skill/{assets → _archive}/chart-ratchet-en.html +0 -0
  81. /package/skills/darwin-skill/{assets → _archive}/chart-ratchet-en.png +0 -0
  82. /package/skills/darwin-skill/{assets → _archive}/chart-ratchet.html +0 -0
  83. /package/skills/darwin-skill/{assets → _archive}/chart-ratchet.png +0 -0
  84. /package/skills/darwin-skill/{templates → _archive}/result-card-dark.html +0 -0
  85. /package/skills/darwin-skill/{templates → _archive}/result-card-white.html +0 -0
@@ -103,7 +103,7 @@
103
103
  ]);
104
104
 
105
105
  // Command vocabulary (values + labels + icons) comes from the canonical source,
106
- // skill/scripts/live/vocabulary.mjs, which live-server.mjs serializes into
106
+ // crates/live/src/vocabulary.rs, which the engine's live server serializes into
107
107
  // window.__IMPECCABLE_VOCAB__ when it serves /live.js (same injection path as
108
108
  // the token/port above, so it is always present here). The icons stack above
109
109
  // each chip label and recolor to C.brand when selected (strokes use
@@ -116,13 +116,12 @@
116
116
  });
117
117
 
118
118
  // The Live chrome inventory (which surfaces exist, and the element ids each
119
- // one owns) comes from the canonical source, skill/scripts/live/ui-surfaces.mjs,
120
- // which the /live.js assembler serializes into these globals alongside the
121
- // token/port/vocabulary. This file is served raw and injected as a classic
122
- // script, so it cannot import that module; the private impeccable-site repo
123
- // imports it directly to check its Live UI lab holds a snapshot for every
124
- // surface, which only works while the list has exactly one definition.
125
- // Add a surface in ui-surfaces.mjs, not here.
119
+ // one owns) comes from the canonical source, SURFACES in
120
+ // crates/live/src/vocabulary.rs, which the /live.js assembler
121
+ // (crates/live/src/browser_assets.rs) serializes into these globals alongside
122
+ // the token/port/vocabulary. This file is served raw and injected as a classic
123
+ // script, so it cannot import that list, which must keep exactly one
124
+ // definition. Add a surface in vocabulary.rs, not here.
126
125
  const LIVE_CHROME_MOUNT_CONTRACT = Array.isArray(window.__IMPECCABLE_LIVE_MOUNT_CONTRACT__)
127
126
  ? window.__IMPECCABLE_LIVE_MOUNT_CONTRACT__
128
127
  : ['root', 'transport', 'state', 'actions'];
@@ -153,9 +152,9 @@
153
152
  // behind checkpoint), and without this the bar jumps backward mid-generation.
154
153
  // Unranked phases always pass so we never block a phase we do not model.
155
154
  //
156
- // Every `agent_phase` name here is emitted by recordAgentPhase() in
157
- // live-server.mjs and listed in AGENT_PHASES in live/vocabulary.mjs, which the
158
- // event validator enforces. This file is served raw and injected as an IIFE,
155
+ // Every `agent_phase` name here is recorded by record_agent_phase() in
156
+ // crates/live/src/server_state.rs and listed in AGENT_PHASES in
157
+ // crates/live/src/vocabulary.rs, which the event validator enforces. This file is served raw and injected as an IIFE,
159
158
  // so it cannot import that list; adding a phase means adding it in both.
160
159
  // `queued`, `generating`, `variants_progress`, and `variants_ready` are set
161
160
  // locally by this file and never arrive over the wire.
@@ -212,7 +211,7 @@
212
211
  // Survives cleanupAcceptedSession on purpose: the id of an accept whose
213
212
  // POST was acknowledged (intent durable, epoch fenced) but whose actual
214
213
  // source promotion hasn't reported back yet. Accept is optimistic, so the
215
- // teardown nulls pendingAcceptedSession long before live-accept.mjs runs;
214
+ // teardown nulls pendingAcceptedSession long before `impeccable live-accept` runs;
216
215
  // this marker is what lets the SSE 'error' branch still recognize a late
217
216
  // accept failure and say the variant was not saved (issue #384). Released
218
217
  // when the real accept result arrives or a new session starts.
@@ -1728,7 +1727,7 @@
1728
1727
  return btn;
1729
1728
  }
1730
1729
 
1731
- // Insert mode helpers (mirrors skill/scripts/live/insert-ui.mjs)
1730
+ // Insert mode helpers (the engine's insert checks are in crates/live/src/event_validation.rs)
1732
1731
 
1733
1732
  function detectInsertAxisFromStyle(style) {
1734
1733
  const display = style?.display || 'block';
@@ -6237,7 +6236,7 @@
6237
6236
  // carry that answer back, so the journal, `live-status`, and `live-resume`
6238
6237
  // can tell "the user is comparing variants" from "nothing ever rendered".
6239
6238
 
6240
- // Mirror of the caps in live/event-validation.mjs. Trimming here keeps a
6239
+ // Mirror of the caps in crates/live/src/event_validation.rs. Trimming here keeps a
6241
6240
  // stack-trace-sized error from being rejected outright and lost.
6242
6241
  const MOUNT_URL_MAX = 2000;
6243
6242
  const MOUNT_ERROR_MAX = 1000;
@@ -6462,7 +6461,7 @@
6462
6461
  removeVariantStateStylesheet();
6463
6462
  clearMountErrorCard();
6464
6463
  clearSession();
6465
- clearHandled();
6464
+ clearHandled(sessionId);
6466
6465
  resetSessionFileMeta();
6467
6466
  currentSessionId = null;
6468
6467
  parameterGenerationState = 'idle';
@@ -7513,8 +7512,25 @@
7513
7512
  let liveBarHiddenByHelper = false;
7514
7513
 
7515
7514
  function applyLiveBarPreference(hidden) {
7515
+ const wasHidden = liveBarHiddenByHelper;
7516
7516
  liveBarHiddenByHelper = hidden === true;
7517
7517
  setLiveBarHidden(liveBarHiddenByHelper);
7518
+ // A hidden bar has no Pick or Insert control, so a choice remembered
7519
+ // from a visible session stops capturing the page's clicks until the
7520
+ // bar is back. The stored prefs stay as they are.
7521
+ if (liveBarHiddenByHelper && !wasHidden && state === 'PICKING') {
7522
+ clearInsertPicking();
7523
+ hideHighlight();
7524
+ setLiveState('IDLE');
7525
+ syncPageInteractionCursor();
7526
+ } else if (!liveBarHiddenByHelper && wasHidden) {
7527
+ enterPickingIfArmed();
7528
+ syncPageInteractionCursor();
7529
+ }
7530
+ }
7531
+
7532
+ function enterPickingIfArmed() {
7533
+ if (state === 'IDLE' && (pickActive || insertActive) && !liveBarHiddenByHelper) setLiveState('PICKING');
7518
7534
  }
7519
7535
 
7520
7536
  // A plain live session must never notice this code: hiding remembers the
@@ -7819,13 +7835,21 @@
7819
7835
  hasProjectContext = !!msg.hasProjectContext;
7820
7836
  // The generate lane runs without PRODUCT.md by design and never
7821
7837
  // sends the user to init, so its quiet chrome skips this notice.
7822
- if (!hasProjectContext && !liveBarHiddenByHelper) showToast(`No PRODUCT.md found. Variants will be brand-agnostic. Run ${IMPECCABLE_COMMAND} init to generate one.`, 7000);
7838
+ // A first session gets the first move instead: what to click
7839
+ // matters more than a missing file, and it shows once.
7840
+ if (liveFirstRun && !liveBarHiddenByHelper) {
7841
+ liveFirstRun = false;
7842
+ if (!insertActive) pickActive = true;
7843
+ saveInteractionPrefs();
7844
+ updateGlobalBarState();
7845
+ showToast('Click anything on the page to restyle it.', 8000);
7846
+ } else if (!hasProjectContext && !liveBarHiddenByHelper) showToast(`No PRODUCT.md found. Variants will be brand-agnostic. Run ${IMPECCABLE_COMMAND} init to generate one.`, 7000);
7823
7847
  console.log('[impeccable] Live mode connected.');
7824
7848
  syncAgentPollingUi(!!msg.agentPolling);
7825
7849
  startAgentStatusPoll();
7826
7850
  restoreFromActiveSessions(msg.activeSessions, 'sse_connected');
7827
7851
  recoverMissedGenerationCompletion(msg.activeSessions);
7828
- if (state === 'IDLE' && (pickActive || insertActive)) setLiveState('PICKING');
7852
+ enterPickingIfArmed();
7829
7853
  syncPageInteractionCursor();
7830
7854
  syncPageChatFocus('sse-connected');
7831
7855
  break;
@@ -8022,7 +8046,7 @@
8022
8046
  function handleServerLost() {
8023
8047
  const recoveryState = currentSessionId ? state : 'IDLE';
8024
8048
  if (state === 'GENERATING' || state === 'CYCLING' || state === 'SAVING') {
8025
- showToast('Live server connection lost. Your session is saved; reopen this page or restart live-poll.mjs to continue.', 6000);
8049
+ showToast('Live server connection lost. Your session is saved; reopen this page or restart `impeccable live-poll` to continue.', 6000);
8026
8050
  }
8027
8051
  hideBar();
8028
8052
  hideHighlight();
@@ -10543,7 +10567,11 @@ void main() {
10543
10567
  return { pickActive: !!prefs.pickActive, insertActive: false };
10544
10568
  }
10545
10569
  } catch { /* ignore */ }
10546
- return { pickActive: false, insertActive: false };
10570
+ // Nothing stored: this browser's first Live session here. Pick turns on
10571
+ // when the helper connects with the bar visible (see `connected`), so the
10572
+ // first click on the page already does something; the generate lane hides
10573
+ // the bar, and a Pick nobody can see or turn off would eat app clicks.
10574
+ return { pickActive: false, insertActive: false, firstRun: true };
10547
10575
  }
10548
10576
 
10549
10577
  function saveInteractionPrefs() {
@@ -10561,6 +10589,7 @@ void main() {
10561
10589
  }
10562
10590
 
10563
10591
  let pickActive = loadInteractionPrefs().pickActive;
10592
+ let liveFirstRun = loadInteractionPrefs().firstRun === true;
10564
10593
  let insertActive = loadInteractionPrefs().insertActive;
10565
10594
  let configureKind = 'replace';
10566
10595
  let insertLineEl = null;
@@ -10614,7 +10643,7 @@ void main() {
10614
10643
  const STEER_AWAIT_TIMEOUT_MS = 120000;
10615
10644
  const AGENT_STATUS_POLL_MS = 5000;
10616
10645
  const AGENT_DISCONNECTED_MARK = 'oklch(62% 0 0 / 0.78)';
10617
- const AGENT_DISCONNECTED_TIP = 'Agent disconnected - run live-poll.mjs to connect';
10646
+ const AGENT_DISCONNECTED_TIP = 'Agent disconnected - run impeccable live-poll to connect';
10618
10647
  // The indicator tracks whether a poll is parked, which is what decides if
10619
10648
  // steering can reach the agent right now. That goes quiet two ways, and they
10620
10649
  // need different copy: nobody is polling at all, or the agent took the work
@@ -11205,7 +11234,7 @@ void main() {
11205
11234
  return head + 'The agent is still busy with the current generation - your message was not lost, but it never got picked up. Send it again once the variants land.';
11206
11235
  }
11207
11236
  if (!agentPollingConnected) {
11208
- return head + 'No agent is polling right now. Run live-poll.mjs, then send it again.';
11237
+ return head + 'No agent is polling right now. Run impeccable live-poll, then send it again.';
11209
11238
  }
11210
11239
  return head + 'The agent picked it up but never replied with steer_done. Check the agent session for a stalled or failed steer.';
11211
11240
  }
@@ -13859,7 +13888,7 @@ void main() {
13859
13888
  scout.observe(document.body, { childList: true, subtree: true });
13860
13889
  }
13861
13890
 
13862
- if (state === 'IDLE' && (pickActive || insertActive)) setLiveState('PICKING');
13891
+ enterPickingIfArmed();
13863
13892
  syncPageInteractionCursor();
13864
13893
  syncPageChatFocus('init-complete');
13865
13894
  }
@@ -1,7 +1,7 @@
1
1
  **CRITICAL: You MUST complete these steps in order. Do not skip ahead to writing code.**
2
2
 
3
3
  If you need to fill out a PDF form, first check to see if the PDF has fillable form fields. Run this script from this file's directory:
4
- `python scripts/check_fillable_fields <file.pdf>`, and depending on the result go to either the "Fillable fields" or "Non-fillable fields" and follow those instructions.
4
+ `python scripts/check_fillable_fields.py <file.pdf>`, and depending on the result go to either the "Fillable fields" or "Non-fillable fields" and follow those instructions.
5
5
 
6
6
  # Fillable fields
7
7
  If the PDF has fillable form fields:
@@ -39,7 +39,8 @@ import pypdfium2 as pdfium
39
39
 
40
40
  pdf = pdfium.PdfDocument("document.pdf")
41
41
  for i, page in enumerate(pdf):
42
- text = page.get_text()
42
+ textpage = page.get_textpage()
43
+ text = textpage.get_text_range()
43
44
  print(f"Page {i+1} text length: {len(text)} chars")
44
45
  ```
45
46
 
@@ -533,7 +534,7 @@ with open("cropped.pdf", "wb") as output:
533
534
  - Process pages individually with pypdfium2
534
535
 
535
536
  ### 2. For Text Extraction
536
- - `pdftotext -bbox-layout` is fastest for plain text extraction
537
+ - `pdftotext` is fastest for plain text extraction
537
538
  - Use pdfplumber for structured data and tables
538
539
  - Avoid `pypdf.extract_text()` for very large documents
539
540
 
@@ -20,7 +20,7 @@ license: Complete terms in LICENSE.txt
20
20
  ## Requirements for every output
21
21
 
22
22
  - **Professional font** (Arial, Times New Roman) throughout, unless the user says otherwise.
23
- - **Zero formula errors.** Never ship while `recalc.py` reports `errors_found`. If you think an error predates you, prove it: load the *original* with `data_only=True` and look at that cell. An error you introduced looks exactly like one you inherited.
23
+ - **Zero formula errors.** Never ship while `recalc.py` reports `errors_found`; the one exception is under `not_computed` below. If you think an error predates you, prove it: load the *original* with `data_only=True` and look at that cell. An error you introduced looks exactly like one you inherited.
24
24
  - **Use formulas, never hardcoded results.** Write `sheet['B10'] = '=SUM(B2:B9)'`, not the Python-computed total. The sheet must recalculate when its inputs change.
25
25
  - **Follow the user's spec literally.** Exact tab names, exact column headers, and the formula they spelled out. A redesign that computes something else fails, however elegant.
26
26
  - **Document every assumption and hardcoded number** where the reader will see it — a cell comment, or an adjacent cell at a table's end. Cite a real source when one exists (`Source: Company 10-K, FY2024, Page 45, Revenue Note, [SEC EDGAR URL]`); when the number came from the user, say so plainly.
@@ -37,7 +37,7 @@ formula cell reads back as `None` to anything reading cached values — `pandas`
37
37
  python scripts/recalc.py output.xlsx [timeout_seconds] # default 30
38
38
  ```
39
39
 
40
- LibreOffice computes every formula, the file is **rewritten in place**, and you get JSON:
40
+ LibreOffice computes the formulas **on a copy**, only their values go into your file, and you get JSON:
41
41
  `status` (`success` | `errors_found`), `total_formulas`, `total_errors`, and an
42
42
  `error_summary` naming up to 100 cells per error type (`locations_truncated` says how many it
43
43
  withheld — trust `total_errors`, not the length of the list). Fix what it names and run it
@@ -49,24 +49,23 @@ workbook.
49
49
  range or a reference to the wrong row yields a clean, error-free file with wrong numbers.
50
50
  Write 2–3 formulas first and check they pull the values you expect, before building out a grid.
51
51
 
52
- **A workbook that links to another file loses those links** if you re-save it with openpyxl and
53
- then recalculate. Such a formula reads `='[1]Returns Analysis'!$B$2` — the `[1]` is an index
54
- into the workbook's external-reference list, naming a *separate file on disk*, not a sheet.
55
- That file is rarely present here, so the cell's cached value is the only thing holding its
56
- data. openpyxl strips that value on save; LibreOffice then has to resolve the reference for
57
- real, fails, writes `#NAME?`, and deletes every link. `recalc.py` refuses to run in that state
58
- — copy those cells' values out of the original before you save over them (`--force` overrides,
59
- and accepts the loss).
52
+ **`not_computed` lists formulas LibreOffice cannot evaluate, even on `success`**: a function it lacks
53
+ (`_xlfn.XLOOKUP`, `_xlfn.LET`…) or a link to another workbook (`='[1]Returns Analysis'!$B$2`). They
54
+ keep what they held: after an openpyxl save, nothing until Excel opens it. For their numbers sooner,
55
+ read the original with `data_only=True`; keep the formulas. A sound formula depending on a listed one,
56
+ directly or not, reports `#NAME?` too: leave it and tell the user. A cell that tests one
57
+ (`IFERROR(B1,0)`) gets LibreOffice's fallback, and a kept value may be stale: say so. After editing
58
+ sheet XML, delete each changed formula's `<v>`: a mistake that keeps its value is listed, not reported.
60
59
 
61
60
  ## Choosing formulas that survive verification
62
61
 
63
- LibreOffice implements fewer functions than Excel, and one it cannot evaluate becomes a
64
- literal `#NAME?` baked into the file you deliver.
62
+ LibreOffice implements fewer functions than Excel, and a formula it cannot evaluate has no value
63
+ until Excel opens the file.
65
64
 
66
65
  - **Prefer Excel-2007-era functions** — `SUMIFS`, `INDEX`, `MATCH`, `IFERROR`, `SUMPRODUCT` — which need no prefix.
67
66
  - **Six post-2007 functions work, but only with an `_xlfn.` prefix**, because openpyxl writes your formula into the XML verbatim and Excel stores post-2007 names prefixed (its UI hides the prefix): `_xlfn.TEXTJOIN`, `_xlfn.CONCAT`, `_xlfn.IFS`, `_xlfn.SWITCH`, `_xlfn.MAXIFS`, `_xlfn.MINIFS`. Written bare, each yields `#NAME?`.
68
- - **Never use `XLOOKUP`, `XMATCH`, `SORT`, `FILTER`, `UNIQUE`, or `SEQUENCE`.** The runtime's LibreOffice cannot evaluate them under *any* prefix. Newer builds do evaluate them, but they are spilling array functions and an openpyxl-written file has no spill metadata, so only the top-left cell of the range gets a value — and `recalc.py` reports `total_errors: 0` on the truncated result. Use `INDEX`/`MATCH` for lookups, and sort, filter, and de-duplicate in Python before writing the cells.
69
- - A formula LibreOffice could not parse is written back **lowercased** — a quick tell beside a `#NAME?`.
67
+ - **Never use `XLOOKUP`, `XMATCH`, `SORT`, `FILTER`, `UNIQUE`, or `SEQUENCE`.** The runtime's LibreOffice cannot evaluate them, and one that can fills only the top-left cell of their result, since an openpyxl-written file has no spill metadata. Use `INDEX`/`MATCH` for lookups, and sort, filter, and de-duplicate in Python before writing the cells.
68
+ - A missing `)` is reported as `unbalanced brackets`. Too few arguments (`=ROUND(A1)`) is not: LibreOffice returns a value, and Excel may offer to repair the file.
70
69
 
71
70
  ## openpyxl gotchas
72
71
 
@@ -76,6 +75,12 @@ literal `#NAME?` baked into the file you deliver.
76
75
  - **Merged cells: write the top-left anchor only.** Every other cell in the range is a `MergedCell` whose `.value` is read-only.
77
76
  - **`.xlsm` loses its macros unless you pass `keep_vba=True`** to `load_workbook`.
78
77
  - **A sheet name containing a space must be quoted** in a cross-sheet reference: `='Assumptions Inputs'!$B$5`. Unquoted, it evaluates to `#VALUE!`.
78
+ - **Saving an upload drops its text boxes, shapes and slicers.** First search `xl/drawings/` for `<xdr:sp ` (with the space) and look for an `xl/slicers/` part; if found, tell the user or edit the sheet XML directly.
79
+ - **Nothing mends a malformed workbook**: an unclosed quote in a number format (`'0.00 "USD'`), a defined name starting with `=`, or duplicate or empty table headers are saved as written, and Excel may offer to repair the file.
80
+ - **Partly bold or italic cell text is flattened** unless `load_workbook(rich_text=True)`; such a `.value` is then a `CellRichText`, not a `str`.
81
+ - **Every new formula needs its own `number_format`** (date, %, currency): nothing infers it, so a date shows as `45337` and 30% as `0.3`.
82
+ - **On every new chart set `chart.roundedCorners = False`, `.overlay = False` on its legend and on each title you gave it (`chart.legend`, `chart.title`, `chart.x_axis.title`…), and, if it has axes (not pie or doughnut), `chart.x_axis.delete = False` and `chart.y_axis.delete = False`**, or Excel may draw the title or legend over the plot, round the frame, or draw no axes.
83
+ - **With a `DateAxis`, set `chart.y_axis.crossAx = 500`**, or Excel may offer to repair the file.
79
84
 
80
85
  ## Financial models
81
86
 
@@ -5,7 +5,7 @@ import stat
5
5
  import tempfile
6
6
  import urllib.parse
7
7
  import zipfile
8
- from pathlib import Path
8
+ from pathlib import Path, PureWindowsPath
9
9
 
10
10
  OOXML_FAMILY = {
11
11
  ".docx": "docx",
@@ -21,16 +21,24 @@ _SCHEME_RE = re.compile(r"^[A-Za-z][A-Za-z0-9+.\-]*:")
21
21
  SLIDE_REL_TYPE = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/slide"
22
22
 
23
23
 
24
+ def one_line(text: str, limit: int) -> str:
25
+ return "".join(c if c.isprintable() else c.encode("unicode_escape").decode() for c in text)[:limit]
26
+
27
+
28
+ def names_another_root(name: str) -> bool:
29
+ return bool(PureWindowsPath(name).anchor)
30
+
31
+
24
32
  def opc_target(target: str, source_part: str, target_mode: str = "") -> str | None:
25
33
  if not target:
26
34
  return None
27
35
  if target_mode.lower() == "external":
28
36
  return None
37
+ target = urllib.parse.unquote(target)
38
+
29
39
  if _SCHEME_RE.match(target):
30
40
  return None
31
41
 
32
- target = urllib.parse.unquote(target)
33
-
34
42
  if "\\" in target:
35
43
  raise ValueError(f"relationship target is not a POSIX part name: {target!r}")
36
44
 
@@ -52,12 +60,15 @@ def opc_target(target: str, source_part: str, target_mode: str = "") -> str | No
52
60
 
53
61
  if not parts:
54
62
  raise ValueError(f"relationship target resolves to nothing: {target!r}")
63
+ if names_another_root("/".join(parts)):
64
+ raise ValueError(f"relationship target is not a part name: {target!r}")
55
65
  return "/".join(parts)
56
66
 
57
67
 
58
68
  def rels_source_part(rels_file: Path, unpacked_dir: Path) -> str:
59
69
  owner_dir = rels_file.parent.parent.relative_to(unpacked_dir)
60
- return posixpath.join(owner_dir.as_posix(), rels_file.name[: -len(".rels")]).lstrip("./")
70
+ part = posixpath.join(owner_dir.as_posix(), rels_file.name[: -len(".rels")])
71
+ return part.removeprefix("./")
61
72
 
62
73
 
63
74
  def part_text(data: bytes) -> str:
@@ -76,12 +87,19 @@ def safe_extract(zf: zipfile.ZipFile, dest: Path) -> None:
76
87
  for m in zf.infolist():
77
88
  if stat.S_ISLNK(m.external_attr >> 16):
78
89
  raise ValueError(f"symlink archive entry not allowed: {m.filename!r}")
90
+ if names_another_root(m.filename):
91
+ raise ValueError(f"unsafe archive entry: {m.filename!r}")
79
92
  target = (dest / m.filename).resolve()
80
93
  if not target.is_relative_to(dest):
81
94
  raise ValueError(f"unsafe archive entry: {m.filename!r}")
82
95
  zf.extract(m, dest)
83
96
 
84
97
 
98
+ def folder_entries(package: Path) -> list[str]:
99
+ with zipfile.ZipFile(package) as zf:
100
+ return [info.filename for info in zf.infolist() if info.is_dir()]
101
+
102
+
85
103
  def rezip(src_dir: Path, out_path: Path) -> None:
86
104
  files = sorted(p for p in src_dir.rglob("*") if p.is_file())
87
105
  ct = src_dir / "[Content_Types].xml"
@@ -1,15 +1,20 @@
1
- """Find chart XML that PowerPoint refuses but the schema accepts.
1
+ """Find chart XML that PowerPoint refuses or repairs.
2
2
 
3
- Detection only: for either fault more than one repair is valid, and only the
4
- author knows which was meant.
3
+ Detection only: more than one repair is usually valid, and only the author knows
4
+ which was meant.
5
5
  """
6
6
 
7
7
 
8
8
  from __future__ import annotations
9
9
 
10
+ import html
10
11
  import re
12
+ from collections import Counter
11
13
  from typing import Mapping
12
14
 
15
+ from defusedxml import ElementTree
16
+ from defusedxml.common import DefusedXmlException
17
+
13
18
  from . import part_text
14
19
 
15
20
 
@@ -19,8 +24,12 @@ _GROUPING_RE = re.compile(r"""<c:grouping\b[^>]*?\bval=["'](\w+)["']""")
19
24
  _DLBL_POS_RE = re.compile(r"""<c:dLblPos\b[^>]*?\bval=["'](\w+)["']""")
20
25
 
21
26
  def _strip_ext_lst(text: str) -> str:
27
+ return _strip_outermost(text, "c:extLst")
28
+
29
+
30
+ def _strip_outermost(text: str, name: str) -> str:
22
31
  out, cursor = [], 0
23
- for lo, hi in _ext_lst_spans(text):
32
+ for lo, hi in _outermost_spans(text, name):
24
33
  out.append(text[cursor:lo])
25
34
  cursor = hi
26
35
  out.append(text[cursor:])
@@ -139,18 +148,113 @@ def _check_chart_axis_references(part: str, xml: str) -> list[str]:
139
148
  return problems
140
149
 
141
150
 
142
- def _ext_lst_spans(text: str) -> list[tuple[int, int]]:
151
+ def _shown(value: str) -> str:
152
+ return '"' + repr(value[:20])[1:-1] + '"'
153
+
154
+
155
+ DECIMAL_SETTINGS = (
156
+ "crossesAt", "max", "min", "majorUnit", "minorUnit", "logBase",
157
+ "forward", "backward", "intercept", "x", "y", "w", "h",
158
+ "splitPos", "custUnit", "pictureStackUnit",
159
+ )
160
+ _DECIMAL_SETTING_RE = re.compile(
161
+ rf"""<c:({"|".join(DECIMAL_SETTINGS)})\b[^<>]*?\bval=["']([^"'<>]*)["']"""
162
+ )
163
+ _DECIMAL_RE = re.compile(
164
+ r"[+-]?(\d+(\.\d*)?|\.\d+)([eE][+-]?\d+)?"
165
+ r"|[+-]?(inf|infinity|nan(\(\w*\))?|\u221e|1\.#(inf|qnan|snan|ind)\d*)",
166
+ re.IGNORECASE,
167
+ )
168
+
169
+
170
+ def _check_decimal_settings(part: str, xml: str) -> list[str]:
171
+ problems = []
172
+ for name, raw in sorted(set(_DECIMAL_SETTING_RE.findall(_strip_ext_lst(xml)))):
173
+ value = html.unescape(raw)
174
+ if _DECIMAL_RE.fullmatch(value.strip()):
175
+ continue
176
+ fix = "Fix: write a plain number, or remove the element"
177
+ if name == "crossesAt" and value.strip() == "autoZero":
178
+ fix = ("Fix: leave valAxisCrossesAt: 0 out of the pptxgenjs options, the axis "
179
+ "crosses at zero anyway. In the XML, write "
180
+ '<c:crosses val="autoZero"/> or a number')
181
+ problems.append(
182
+ f"{part}: <c:{name} val={_shown(value)}> is not a number, and PowerPoint "
183
+ f"will offer to repair the deck. {fix}"
184
+ )
185
+ return problems
186
+
187
+
188
+ def _local(tag: str) -> str:
189
+ return tag.rsplit("}", 1)[-1]
190
+
191
+
192
+ def _drawn_series(root) -> list:
193
+ found, to_visit = [], [root]
194
+ while to_visit:
195
+ for child in to_visit.pop():
196
+ name = _local(child.tag)
197
+ if name == "ser":
198
+ found.append(child)
199
+ elif name == "AlternateContent":
200
+ to_visit.extend(child[:1])
201
+ elif name != "extLst":
202
+ to_visit.append(child)
203
+ return found
204
+
205
+
206
+ def _check_series_order(part: str, xml: str) -> list[str]:
207
+ try:
208
+ root = ElementTree.fromstring(xml.encode("utf-8", "surrogateescape"))
209
+ except (ElementTree.ParseError, DefusedXmlException, LookupError, ValueError):
210
+ return []
211
+ orders = Counter()
212
+ for series in _drawn_series(root):
213
+ own = [c.get("val", "") for c in series if _local(c.tag) == "order"]
214
+ if own and own[0].isascii() and own[0].isdigit():
215
+ orders[own[0]] += 1
216
+ repeated = sorted((o for o, n in orders.items() if n > 1), key=lambda o: (len(o), o))
217
+ if not repeated:
218
+ return []
219
+ return [
220
+ f"{part}: two or more series share the <c:order> value {', '.join(o[:12] for o in repeated)}, "
221
+ f"and PowerPoint will offer to repair the deck. Fix: number <c:order> "
222
+ f"(and <c:idx>) 0, 1, 2... across every series in the chart, a combo "
223
+ f"chart's line series carrying on from its bars"
224
+ ]
225
+
226
+
227
+ PRESET_DASHES = frozenset({
228
+ "solid", "dot", "dash", "lgDash", "dashDot", "lgDashDot", "lgDashDotDot",
229
+ "sysDash", "sysDot", "sysDashDot", "sysDashDotDot",
230
+ })
231
+ _PRESET_DASH_RE = re.compile(r"""<a:prstDash\b[^<>]*?\bval=["']([^"'<>]*)["']""")
232
+
233
+
234
+ def _check_preset_dashes(part: str, xml: str) -> list[str]:
235
+ values = {html.unescape(v) for v in _PRESET_DASH_RE.findall(_strip_ext_lst(xml))}
236
+ return [
237
+ f"{part}: <a:prstDash val={_shown(value)}> is not a dash style, and PowerPoint "
238
+ f"will offer to repair the deck. Use one of {', '.join(sorted(PRESET_DASHES))}. "
239
+ f"In pptxgenjs, lineDash takes one such word for the whole chart, not an array"
240
+ for value in sorted(values)
241
+ if value.strip() not in PRESET_DASHES
242
+ ]
243
+
244
+
245
+ def _outermost_spans(text: str, name: str) -> list[tuple[int, int]]:
143
246
  spans: list[tuple[int, int]] = []
144
247
  depth = 0
145
248
  start = 0
146
- for match in re.finditer(r"<(/?)c:extLst\b[^>]*?(/?)>", text):
249
+ for match in re.finditer(rf"<(/?){name}\b[^<>]*?(/?)>", text):
147
250
  closing, self_closing = match.group(1), match.group(2)
148
251
  if self_closing:
149
252
  continue
150
253
  if closing:
151
- depth -= 1
152
- if depth == 0:
153
- spans.append((start, match.end()))
254
+ if depth:
255
+ depth -= 1
256
+ if depth == 0:
257
+ spans.append((start, match.end()))
154
258
  else:
155
259
  if depth == 0:
156
260
  start = match.start()
@@ -158,13 +262,22 @@ def _ext_lst_spans(text: str) -> list[tuple[int, int]]:
158
262
  return spans
159
263
 
160
264
 
161
- CHART_CHECKS = (_check_stacked_label_positions, _check_chart_axis_references)
265
+ CHART_CHECKS = (
266
+ _check_stacked_label_positions,
267
+ _check_chart_axis_references,
268
+ _check_decimal_settings,
269
+ _check_series_order,
270
+ _check_preset_dashes,
271
+ )
272
+
273
+
274
+ _COMMENT_OR_PI_RE = re.compile(r"<!--.*?(?:-->|\Z)|<\?(?!xml\s).*?(?:\?>|\Z)", re.DOTALL)
162
275
 
163
276
 
164
277
  def find_chart_problems(files: Mapping[str, bytes]) -> list[str]:
165
278
  problems: list[str] = []
166
279
  for part in sorted(n for n in files if _CHART_PART_RE.fullmatch(n)):
167
- xml = part_text(files[part])
280
+ xml = _strip_outermost(_COMMENT_OR_PI_RE.sub("", part_text(files[part])), "mc:Fallback")
168
281
  for check in CHART_CHECKS:
169
282
  problems.extend(check(part, xml))
170
283
  return problems
@@ -1,7 +1,8 @@
1
- """Pick the slide-XML schema errors PowerPoint refuses the file over.
1
+ """Find the slide-XML defects known or predicted to make PowerPoint refuse or repair the file.
2
2
 
3
- A denylist over lxml's messages, so an unrecognised error class is a miss rather
4
- than a false alarm.
3
+ Schema errors are picked by a denylist over lxml's messages, so an unrecognised
4
+ error class is a miss rather than a false alarm. Animations that name a shape
5
+ the slide no longer has are found by reading the part.
5
6
  """
6
7
 
7
8
 
@@ -43,6 +44,14 @@ FATAL_SLIDE_ERRORS: tuple[tuple[re.Pattern[str], str], ...] = (
43
44
  re.compile(r"\}nvGrpSpPr': Missing child element"),
44
45
  "a <p:nvGrpSpPr> with no children",
45
46
  ),
47
+ (
48
+ re.compile(r"\}(?:off|ext|chOff|chExt)', attribute '\w+': '-?(?:Infinity|NaN)'"),
49
+ "a position or size that is not a number (check the x, y, w, h you worked out)",
50
+ ),
51
+ (
52
+ re.compile(r"\}prstDash', attribute 'val'"),
53
+ "an unknown line dash style (for line.dashType try dash, sysDash or solid)",
54
+ ),
46
55
  )
47
56
 
48
57
 
@@ -50,6 +59,37 @@ def is_schema_verdict(error: str) -> bool:
50
59
  return error.startswith("Element ")
51
60
 
52
61
 
62
+ _PML = "{http://schemas.openxmlformats.org/presentationml/2006/main}"
63
+ _MC = "{http://schemas.openxmlformats.org/markup-compatibility/2006}"
64
+
65
+ _NAMES_A_SHAPE = frozenset({f"{_PML}spTgt", f"{_PML}bldP", f"{_PML}bldGraphic"})
66
+
67
+
68
+ def _shape_id(value: str | None) -> int | str | None:
69
+ text = (value or "").strip()
70
+ if text.isascii() and text.isdigit() and len(text) <= 18:
71
+ return int(text)
72
+ return text or None
73
+
74
+
75
+ def stranded_animation_targets(root) -> list[str]:
76
+ timing = root.find(f"{_PML}timing")
77
+ if timing is None:
78
+ timing = root.find(f"{_MC}AlternateContent/{_MC}Choice/{_PML}timing")
79
+ if timing is None:
80
+ return []
81
+
82
+ on_slide = {_shape_id(e.get("id")) for e in root.iter("{*}cNvPr")}
83
+ named = {_shape_id(e.get("spid")) for e in timing.iter(*_NAMES_A_SHAPE)} - {None}
84
+ stranded = named - on_slide
85
+ return [
86
+ f"<p:timing> animates shape id {spid if isinstance(spid, int) else repr(spid[:16])}, which is gone, so PowerPoint will "
87
+ f"offer to repair the deck. Fix: delete the slide's whole <p:timing> element "
88
+ f"(the slide loses its animations), or put the shape back"
89
+ for spid in sorted(stranded, key=str)
90
+ ]
91
+
92
+
53
93
  def fatal_slide_errors(errors: set[str]) -> list[str]:
54
94
  out = []
55
95
  for error in sorted(errors):