zcode-app-cli 3.3.5-1

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 (169) hide show
  1. package/LICENSE +24 -0
  2. package/README.md +642 -0
  3. package/bin/zcode.js +848 -0
  4. package/config.example.json +110 -0
  5. package/package.json +81 -0
  6. package/vendor/.node-bundle-meta.json +6 -0
  7. package/vendor/extraction.json +11 -0
  8. package/vendor/node_modules/@zcode/tui/dist/index.js +161875 -0
  9. package/vendor/node_modules/@zcode/tui/package.json +14 -0
  10. package/vendor/packages/android-emulator-plugin/.mcp.json +19 -0
  11. package/vendor/packages/android-emulator-plugin/.zcode-plugin/plugin.json +63 -0
  12. package/vendor/packages/android-emulator-plugin/README.md +134 -0
  13. package/vendor/packages/android-emulator-plugin/commands/android-dev.md +11 -0
  14. package/vendor/packages/android-emulator-plugin/dist/lib/path.d.ts +4 -0
  15. package/vendor/packages/android-emulator-plugin/dist/lib/path.js +17 -0
  16. package/vendor/packages/android-emulator-plugin/dist/lib/result.d.ts +5 -0
  17. package/vendor/packages/android-emulator-plugin/dist/lib/result.js +22 -0
  18. package/vendor/packages/android-emulator-plugin/dist/lib/run.d.ts +18 -0
  19. package/vendor/packages/android-emulator-plugin/dist/lib/run.js +99 -0
  20. package/vendor/packages/android-emulator-plugin/dist/mcp/server.d.ts +3 -0
  21. package/vendor/packages/android-emulator-plugin/dist/mcp/server.js +47607 -0
  22. package/vendor/packages/android-emulator-plugin/dist/providers/app.d.ts +39 -0
  23. package/vendor/packages/android-emulator-plugin/dist/providers/app.js +50 -0
  24. package/vendor/packages/android-emulator-plugin/dist/providers/avd.d.ts +37 -0
  25. package/vendor/packages/android-emulator-plugin/dist/providers/avd.js +185 -0
  26. package/vendor/packages/android-emulator-plugin/dist/providers/build.d.ts +68 -0
  27. package/vendor/packages/android-emulator-plugin/dist/providers/build.js +131 -0
  28. package/vendor/packages/android-emulator-plugin/dist/providers/config.d.ts +7 -0
  29. package/vendor/packages/android-emulator-plugin/dist/providers/config.js +29 -0
  30. package/vendor/packages/android-emulator-plugin/dist/providers/device.d.ts +20 -0
  31. package/vendor/packages/android-emulator-plugin/dist/providers/device.js +91 -0
  32. package/vendor/packages/android-emulator-plugin/dist/providers/logs.d.ts +15 -0
  33. package/vendor/packages/android-emulator-plugin/dist/providers/logs.js +31 -0
  34. package/vendor/packages/android-emulator-plugin/dist/providers/preflight.d.ts +15 -0
  35. package/vendor/packages/android-emulator-plugin/dist/providers/preflight.js +123 -0
  36. package/vendor/packages/android-emulator-plugin/dist/providers/project-template.d.ts +13 -0
  37. package/vendor/packages/android-emulator-plugin/dist/providers/project-template.js +211 -0
  38. package/vendor/packages/android-emulator-plugin/dist/providers/project.d.ts +33 -0
  39. package/vendor/packages/android-emulator-plugin/dist/providers/project.js +195 -0
  40. package/vendor/packages/android-emulator-plugin/dist/providers/screenshot.d.ts +14 -0
  41. package/vendor/packages/android-emulator-plugin/dist/providers/screenshot.js +73 -0
  42. package/vendor/packages/android-emulator-plugin/dist/providers/sdk.d.ts +14 -0
  43. package/vendor/packages/android-emulator-plugin/dist/providers/sdk.js +185 -0
  44. package/vendor/packages/android-emulator-plugin/dist/providers/ui.d.ts +92 -0
  45. package/vendor/packages/android-emulator-plugin/dist/providers/ui.js +146 -0
  46. package/vendor/packages/android-emulator-plugin/hooks/hooks.json +3 -0
  47. package/vendor/packages/android-emulator-plugin/package.json +35 -0
  48. package/vendor/packages/android-emulator-plugin/skills/android-dev/INSTALL_ENVIRONMENT.md +357 -0
  49. package/vendor/packages/android-emulator-plugin/skills/android-dev/SKILL.md +73 -0
  50. package/vendor/packages/android-emulator-plugin/templates/compose-app/README.md +5 -0
  51. package/vendor/packages/document-skills-plugin/.zcode-plugin/plugin.json +8 -0
  52. package/vendor/packages/document-skills-plugin/package.json +8 -0
  53. package/vendor/packages/document-skills-plugin/skills/docx/LICENSE.txt +13 -0
  54. package/vendor/packages/document-skills-plugin/skills/docx/SKILL.md +201 -0
  55. package/vendor/packages/document-skills-plugin/skills/docx/references/chart-templates.md +386 -0
  56. package/vendor/packages/document-skills-plugin/skills/docx/references/common-rules.md +419 -0
  57. package/vendor/packages/document-skills-plugin/skills/docx/references/decorations.md +537 -0
  58. package/vendor/packages/document-skills-plugin/skills/docx/references/design-system.md +1797 -0
  59. package/vendor/packages/document-skills-plugin/skills/docx/references/docx-js-advanced.md +257 -0
  60. package/vendor/packages/document-skills-plugin/skills/docx/references/docx-js-core.md +332 -0
  61. package/vendor/packages/document-skills-plugin/skills/docx/references/faq.md +323 -0
  62. package/vendor/packages/document-skills-plugin/skills/docx/references/math-formulas.md +276 -0
  63. package/vendor/packages/document-skills-plugin/skills/docx/references/ooxml.md +222 -0
  64. package/vendor/packages/document-skills-plugin/skills/docx/references/toc.md +264 -0
  65. package/vendor/packages/document-skills-plugin/skills/docx/routes/comment.md +88 -0
  66. package/vendor/packages/document-skills-plugin/skills/docx/routes/create.md +207 -0
  67. package/vendor/packages/document-skills-plugin/skills/docx/routes/edit.md +115 -0
  68. package/vendor/packages/document-skills-plugin/skills/docx/routes/format.md +120 -0
  69. package/vendor/packages/document-skills-plugin/skills/docx/routes/read.md +114 -0
  70. package/vendor/packages/document-skills-plugin/skills/docx/scenes/academic.md +783 -0
  71. package/vendor/packages/document-skills-plugin/skills/docx/scenes/contract.md +463 -0
  72. package/vendor/packages/document-skills-plugin/skills/docx/scenes/copywriting.md +139 -0
  73. package/vendor/packages/document-skills-plugin/skills/docx/scenes/exam.md +698 -0
  74. package/vendor/packages/document-skills-plugin/skills/docx/scenes/official-doc.md +411 -0
  75. package/vendor/packages/document-skills-plugin/skills/docx/scenes/report.md +340 -0
  76. package/vendor/packages/document-skills-plugin/skills/docx/scenes/resume.md +534 -0
  77. package/vendor/packages/document-skills-plugin/skills/docx/scripts/__init__.py +1 -0
  78. package/vendor/packages/document-skills-plugin/skills/docx/scripts/add_toc_placeholders.py +749 -0
  79. package/vendor/packages/document-skills-plugin/skills/docx/scripts/document.py +1333 -0
  80. package/vendor/packages/document-skills-plugin/skills/docx/scripts/postcheck.py +807 -0
  81. package/vendor/packages/document-skills-plugin/skills/docx/scripts/templates/comments.xml +3 -0
  82. package/vendor/packages/document-skills-plugin/skills/docx/scripts/templates/commentsExtended.xml +3 -0
  83. package/vendor/packages/document-skills-plugin/skills/docx/scripts/templates/commentsExtensible.xml +3 -0
  84. package/vendor/packages/document-skills-plugin/skills/docx/scripts/templates/commentsIds.xml +3 -0
  85. package/vendor/packages/document-skills-plugin/skills/docx/scripts/templates/people.xml +3 -0
  86. package/vendor/packages/document-skills-plugin/skills/docx/scripts/utilities.py +374 -0
  87. package/vendor/packages/document-skills-plugin/skills/docx/setup.sh +177 -0
  88. package/vendor/packages/document-skills-plugin/skills/pdf/LICENSE.txt +13 -0
  89. package/vendor/packages/document-skills-plugin/skills/pdf/SKILL.md +919 -0
  90. package/vendor/packages/document-skills-plugin/skills/pdf/briefs/academic.md +1058 -0
  91. package/vendor/packages/document-skills-plugin/skills/pdf/briefs/creative.md +770 -0
  92. package/vendor/packages/document-skills-plugin/skills/pdf/briefs/poster.md +702 -0
  93. package/vendor/packages/document-skills-plugin/skills/pdf/briefs/process-advanced.md +284 -0
  94. package/vendor/packages/document-skills-plugin/skills/pdf/briefs/process.md +319 -0
  95. package/vendor/packages/document-skills-plugin/skills/pdf/briefs/report.md +1659 -0
  96. package/vendor/packages/document-skills-plugin/skills/pdf/configs/components.md +153 -0
  97. package/vendor/packages/document-skills-plugin/skills/pdf/configs/fonts.md +93 -0
  98. package/vendor/packages/document-skills-plugin/skills/pdf/configs/visual_framework.md +263 -0
  99. package/vendor/packages/document-skills-plugin/skills/pdf/references/resume-academic.tex +130 -0
  100. package/vendor/packages/document-skills-plugin/skills/pdf/references/resume-altacv.tex +190 -0
  101. package/vendor/packages/document-skills-plugin/skills/pdf/scripts/cover_validate.js +367 -0
  102. package/vendor/packages/document-skills-plugin/skills/pdf/scripts/design_engine.py +2816 -0
  103. package/vendor/packages/document-skills-plugin/skills/pdf/scripts/html2pdf-next.js +754 -0
  104. package/vendor/packages/document-skills-plugin/skills/pdf/scripts/html2poster.js +256 -0
  105. package/vendor/packages/document-skills-plugin/skills/pdf/scripts/pdf.py +2959 -0
  106. package/vendor/packages/document-skills-plugin/skills/pdf/scripts/pdf_qa.py +901 -0
  107. package/vendor/packages/document-skills-plugin/skills/pdf/scripts/poster_validate.py +1337 -0
  108. package/vendor/packages/document-skills-plugin/skills/pdf/scripts/setup.sh +269 -0
  109. package/vendor/packages/document-skills-plugin/skills/pdf/scripts/toc_validate.py +2075 -0
  110. package/vendor/packages/document-skills-plugin/skills/pdf/typesetting/charts.md +320 -0
  111. package/vendor/packages/document-skills-plugin/skills/pdf/typesetting/cover-backgrounds.md +384 -0
  112. package/vendor/packages/document-skills-plugin/skills/pdf/typesetting/cover.md +1442 -0
  113. package/vendor/packages/document-skills-plugin/skills/pdf/typesetting/fill-engine.md +527 -0
  114. package/vendor/packages/document-skills-plugin/skills/pdf/typesetting/geometry.md +142 -0
  115. package/vendor/packages/document-skills-plugin/skills/pdf/typesetting/overflow.md +630 -0
  116. package/vendor/packages/document-skills-plugin/skills/pdf/typesetting/pagination.md +367 -0
  117. package/vendor/packages/document-skills-plugin/skills/pdf/typesetting/palette.md +217 -0
  118. package/vendor/packages/document-skills-plugin/skills/pdf/typesetting/typography.md +20 -0
  119. package/vendor/packages/ios-simulator-plugin/.mcp.json +15 -0
  120. package/vendor/packages/ios-simulator-plugin/.zcode-plugin/plugin.json +34 -0
  121. package/vendor/packages/ios-simulator-plugin/README.md +111 -0
  122. package/vendor/packages/ios-simulator-plugin/commands/ios-dev.md +11 -0
  123. package/vendor/packages/ios-simulator-plugin/dist/lib/path.d.ts +4 -0
  124. package/vendor/packages/ios-simulator-plugin/dist/lib/path.js +18 -0
  125. package/vendor/packages/ios-simulator-plugin/dist/lib/result.d.ts +5 -0
  126. package/vendor/packages/ios-simulator-plugin/dist/lib/result.js +20 -0
  127. package/vendor/packages/ios-simulator-plugin/dist/lib/run.d.ts +17 -0
  128. package/vendor/packages/ios-simulator-plugin/dist/lib/run.js +83 -0
  129. package/vendor/packages/ios-simulator-plugin/dist/mcp/server.d.ts +3 -0
  130. package/vendor/packages/ios-simulator-plugin/dist/mcp/server.js +46833 -0
  131. package/vendor/packages/ios-simulator-plugin/dist/providers/build.d.ts +112 -0
  132. package/vendor/packages/ios-simulator-plugin/dist/providers/build.js +99 -0
  133. package/vendor/packages/ios-simulator-plugin/dist/providers/logs.d.ts +21 -0
  134. package/vendor/packages/ios-simulator-plugin/dist/providers/logs.js +26 -0
  135. package/vendor/packages/ios-simulator-plugin/dist/providers/preflight.d.ts +12 -0
  136. package/vendor/packages/ios-simulator-plugin/dist/providers/preflight.js +62 -0
  137. package/vendor/packages/ios-simulator-plugin/dist/providers/project.d.ts +35 -0
  138. package/vendor/packages/ios-simulator-plugin/dist/providers/project.js +288 -0
  139. package/vendor/packages/ios-simulator-plugin/dist/providers/screenshot.d.ts +22 -0
  140. package/vendor/packages/ios-simulator-plugin/dist/providers/screenshot.js +30 -0
  141. package/vendor/packages/ios-simulator-plugin/dist/providers/sim.d.ts +60 -0
  142. package/vendor/packages/ios-simulator-plugin/dist/providers/sim.js +116 -0
  143. package/vendor/packages/ios-simulator-plugin/dist/providers/ui.d.ts +57 -0
  144. package/vendor/packages/ios-simulator-plugin/dist/providers/ui.js +67 -0
  145. package/vendor/packages/ios-simulator-plugin/hooks/hooks.json +3 -0
  146. package/vendor/packages/ios-simulator-plugin/package.json +35 -0
  147. package/vendor/packages/ios-simulator-plugin/skills/ios-dev/SKILL.md +45 -0
  148. package/vendor/packages/ios-simulator-plugin/templates/swiftui-app/README.md +5 -0
  149. package/vendor/packages/restore-legacy-sessions-plugin/.zcode-plugin/plugin.json +9 -0
  150. package/vendor/packages/restore-legacy-sessions-plugin/README.md +35 -0
  151. package/vendor/packages/restore-legacy-sessions-plugin/commands/restore-legacy-sessions.md +11 -0
  152. package/vendor/packages/restore-legacy-sessions-plugin/package.json +8 -0
  153. package/vendor/packages/restore-legacy-sessions-plugin/skills/restore-legacy-sessions/SKILL.md +92 -0
  154. package/vendor/packages/restore-legacy-sessions-plugin/skills/restore-legacy-sessions/scripts/restore-conversation.mjs +648 -0
  155. package/vendor/packages/restore-legacy-sessions-plugin/skills/restore-legacy-sessions/scripts/scan-legacy-sessions.mjs +422 -0
  156. package/vendor/packages/skill-creator-plugin/.zcode-plugin/plugin.json +8 -0
  157. package/vendor/packages/skill-creator-plugin/package.json +8 -0
  158. package/vendor/packages/skill-creator-plugin/skills/skill-creator/SKILL.md +159 -0
  159. package/vendor/packages/zcode-guide-plugin/.zcode-plugin/plugin.json +8 -0
  160. package/vendor/packages/zcode-guide-plugin/README.md +22 -0
  161. package/vendor/packages/zcode-guide-plugin/package.json +8 -0
  162. package/vendor/packages/zcode-guide-plugin/skills/diagnosing-commands/SKILL.md +66 -0
  163. package/vendor/packages/zcode-guide-plugin/skills/diagnosing-hooks/SKILL.md +66 -0
  164. package/vendor/packages/zcode-guide-plugin/skills/diagnosing-mcp/SKILL.md +97 -0
  165. package/vendor/packages/zcode-guide-plugin/skills/diagnosing-plugins/SKILL.md +59 -0
  166. package/vendor/packages/zcode-guide-plugin/skills/diagnosing-skills/SKILL.md +61 -0
  167. package/vendor/packages/zcode-guide-plugin/skills/zcode-configuration-guide/SKILL.md +99 -0
  168. package/vendor/zcode.cjs +2926 -0
  169. package/zcode-runtime.lock.json +8 -0
@@ -0,0 +1,630 @@
1
+ # Overflow Prevention — Anti-Overflow Layout System
2
+
3
+ > PDF is static: no scrollbars, no reflow, no viewport adaptation. Every element must fit within its container BEFORE rendering. This document defines the architectural approach to guarantee zero overflow in any generated PDF.
4
+ >
5
+ > **This is the "too much content" side.** For the mirror problem ("too little content" / empty pages), see `typesetting/fill-engine.md` — the anti-void adaptive engine.
6
+ >
7
+ > Related:
8
+ > - `fill-engine.md` — Anti-void engine (font floor, fill ratio, paragraph inflation, Y-axis anchoring)
9
+ > - `pagination.md` — Pagination & cross-page integrity
10
+
11
+ ---
12
+
13
+ ## Core Philosophy
14
+
15
+ **"Measure first, draw second."**
16
+
17
+ Never use `draw_text(x, y)` or `draw_image(x, y)` directly. All content must pass through a constraint system that pre-calculates sizes and enforces boundaries. Think CSS Box Model, but for a fixed canvas.
18
+
19
+ ---
20
+
21
+ ## 1. Bounding Box System (Horizontal Overflow Prevention)
22
+
23
+ Every element entering a page is a **Block** with a maximum available width (`Max_Width`).
24
+
25
+ ### Calculating Max_Width
26
+
27
+ ```python
28
+ # Single-column layout
29
+ max_width = page_width - left_margin - right_margin
30
+
31
+ # Dual-column layout
32
+ col_gap = 12 # points
33
+ max_width = (page_width - left_margin - right_margin - col_gap) / 2
34
+
35
+ # Nested containers (e.g., table cell)
36
+ cell_max_width = col_width - cell_padding_left - cell_padding_right
37
+ ```
38
+
39
+ ### Absolute Rule
40
+
41
+ > **No Block's rendered width may exceed its parent's `Max_Width`. Period.**
42
+
43
+ If a Block's calculated width > Max_Width, apply fallback strategies (see §5).
44
+
45
+ ---
46
+
47
+ ## 1.5 🔴 Page Content Centering (Horizontal Centering Iron Rule)
48
+
49
+ > **Symptom:** Cover or body content is shifted left on the page, with noticeably more whitespace on the right than left.
50
+
51
+ **Root cause:** Asymmetric left/right margins, or cover uses single-side anchors without considering right-side balance.
52
+
53
+ **Iron rule:**
54
+
55
+ 1. **Left/right margins must be symmetric:** `left_margin == right_margin`. No asymmetric margins allowed.
56
+ 2. **Cover:** For left-aligned templates (e.g., Template 01/02/03/05/07), the text starting point should be within `0.10*W ~ 0.15*W`, and the right margin should be between `0.05*W ~ 0.15*W`. Center-aligned templates (Template 04/06) must be absolutely centered.
57
+ 3. **Body:** ReportLab's `Frame` / `SimpleDocTemplate` must have `leftMargin == rightMargin`. LaTeX's `\geometry{left=X, right=X}` must be symmetric. HTML must use `margin: 0 auto` or `padding-left == padding-right`.
58
+
59
+ ```python
60
+ # ReportLab: Force symmetric margins
61
+ from reportlab.lib.units import inch
62
+ MARGIN = 1 * inch # Left and right must use same variable
63
+ doc = SimpleDocTemplate(
64
+ "output.pdf",
65
+ leftMargin=MARGIN,
66
+ rightMargin=MARGIN, # ← Must match leftMargin
67
+ topMargin=MARGIN,
68
+ bottomMargin=MARGIN,
69
+ )
70
+
71
+ # ❌ WRONG: leftMargin=72, rightMargin=36 → Content shifts left
72
+ ```
73
+
74
+ ```latex
75
+ % LaTeX: Force symmetric margins
76
+ \usepackage[left=2.5cm, right=2.5cm, top=2.5cm, bottom=2.5cm]{geometry}
77
+ % ❌ WRONG: left=3cm, right=1.5cm
78
+ ```
79
+
80
+ ---
81
+
82
+ ## 2. Text Overflow: Font Metrics Pre-Calculation
83
+
84
+ ### The Wrong Way
85
+ ```python
86
+ # ❌ NEVER estimate by character count
87
+ if len(text) > 20:
88
+ wrap() # Wrong — 20 CJK chars ≠ 20 Latin chars ≠ 20 mixed chars
89
+ ```
90
+
91
+ ### The Right Way — ReportLab
92
+ ```python
93
+ from reportlab.pdfbase.pdfmetrics import stringWidth
94
+ from reportlab.platypus import Paragraph
95
+ from reportlab.lib.styles import ParagraphStyle
96
+
97
+ # Measure actual rendered width
98
+ text_width = stringWidth("Your text here", "Microsoft YaHei", 10)
99
+
100
+ if text_width > max_width:
101
+ # Use Paragraph for automatic wrapping — NEVER plain strings in tables
102
+ style = ParagraphStyle(
103
+ 'CellText',
104
+ fontName='Microsoft YaHei',
105
+ fontSize=10,
106
+ leading=14,
107
+ wordWrap='CJK', # Enables CJK-aware line breaking
108
+ )
109
+ element = Paragraph(text, style)
110
+ else:
111
+ element = text # Plain string is fine if it fits
112
+ ```
113
+
114
+ ### Key Rules
115
+ - **Always use `Paragraph()` for table cell content** — plain strings don't wrap and will overflow
116
+ - **CJK text is wider**: Budget ~12pt per character at 10pt font size (vs ~6pt for Latin)
117
+ - **URLs and long strings**: If a single "word" exceeds column width, enable `wordWrap='CJK'` or split manually
118
+ - **Hyphenation**: For English text, consider `pyphen` for proper hyphenation of long words
119
+
120
+ ### The Right Way — LaTeX
121
+ ```latex
122
+ % Use tabularx for auto-wrapping columns
123
+ \usepackage{tabularx}
124
+ \begin{tabularx}{\columnwidth}{lXX} % X columns auto-wrap
125
+ Header 1 & This long text will wrap & Another wrapping column \\
126
+ \end{tabularx}
127
+
128
+ % For URLs
129
+ \usepackage{url}
130
+ \url{https://very-long-url-that-would-overflow.example.com/path/to/resource}
131
+ ```
132
+
133
+ ### The Right Way — Playwright/HTML
134
+ ```css
135
+ /* Global text overflow prevention */
136
+ p, td, li, .content {
137
+ overflow-wrap: break-word;
138
+ word-break: break-word;
139
+ hyphens: auto;
140
+ }
141
+
142
+ /* Strict CJK line-break rules */
143
+ body {
144
+ line-break: strict;
145
+ word-break: normal;
146
+ }
147
+
148
+ /* Table cells must constrain content */
149
+ /* ⚠️ overflow:hidden + ellipsis only for single-line short text cells.
150
+ Multi-line td should use overflow-wrap: break-word, not overflow: hidden,
151
+ otherwise text gets truncated. Especially important in Playwright PDFs. */
152
+ td {
153
+ max-width: 0; /* Forces column to respect assigned width */
154
+ overflow: hidden;
155
+ text-overflow: ellipsis; /* Only for single-line cells */
156
+ }
157
+ ```
158
+
159
+ ---
160
+
161
+ ## 3. Image & Chart Overflow: Proportional Scaling
162
+
163
+ ### Absolute Rule
164
+
165
+ > **Never insert an image or chart at its original dimensions. Always compute fit-to-container scaling.**
166
+
167
+ ### ReportLab Pattern
168
+ ```python
169
+ from reportlab.platypus import Image
170
+ from reportlab.lib.units import mm
171
+
172
+ def fit_image(img_path, max_w, max_h):
173
+ """Scale image to fit within max_w × max_h, preserving aspect ratio."""
174
+ img = Image(img_path)
175
+ orig_w, orig_h = img.drawWidth, img.drawHeight
176
+
177
+ ratio_w = max_w / orig_w if orig_w > max_w else 1.0
178
+ ratio_h = max_h / orig_h if orig_h > max_h else 1.0
179
+ ratio = min(ratio_w, ratio_h)
180
+
181
+ img.drawWidth = orig_w * ratio
182
+ img.drawHeight = orig_h * ratio
183
+ return img
184
+
185
+ # Usage
186
+ available_width = page_width - left_margin - right_margin
187
+ max_img_height = A4[1] * 0.35 # ~294pt ≈ 10cm — prevents image from eating page + leaves room for caption
188
+ img = fit_image("chart.png", available_width, max_img_height)
189
+ story.append(img)
190
+ ```
191
+
192
+ ### LaTeX Pattern
193
+ ```latex
194
+ \usepackage{adjustbox}
195
+
196
+ % Always constrain to column width
197
+ \includegraphics[max width=\columnwidth]{chart.png}
198
+
199
+ % Or with adjustbox for both dimensions
200
+ \begin{adjustbox}{max width=\columnwidth, max height=0.4\textheight}
201
+ \includegraphics{chart.png}
202
+ \end{adjustbox}
203
+ ```
204
+
205
+ ### Playwright/HTML Pattern
206
+ ```css
207
+ img, svg, .chart-container {
208
+ max-width: 100%;
209
+ max-height: 45vh; /* Prevent one image from eating an entire page */
210
+ height: auto;
211
+ object-fit: contain; /* Preserve aspect ratio */
212
+ }
213
+ ```
214
+
215
+ > **Why `max-height: 45vh`?** Without a height cap, a tall image combined with `break-inside: avoid` (from pagination.md) gets pushed to the next page — leaving the current page mostly empty and the image occupying an entire page alone. 45vh ensures any image fits within half a page, leaving room for surrounding text on the same page.
216
+
217
+ ---
218
+
219
+ ## 3.5 Horizontal Flex/Inline Layout Overflow (Flow Bars, Step Lists, Tag Rows)
220
+
221
+ **Problem:** LLMs commonly generate horizontal `display: flex` layouts (process flow bars, step indicators, tag rows, icon grids) without any width constraint or wrap control. When content is longer than expected (e.g. "Theory Framework (ASPICE / V-Model)" as a step label), the total width exceeds the container, pushing content beyond the right page boundary.
222
+
223
+ **Playwright PDF consequence:** When any element causes `scrollWidth > clientWidth`, Playwright shrinks the **entire page** to fit, causing all content to appear left-shifted with blank space on the right. This affects ALL pages, not just the one with the overflow.
224
+
225
+ ### Iron Rules (Direct HTML Flow)
226
+
227
+ **Rule 3.5.1 — Mandatory `flex-wrap` for ≥3 inline items:**
228
+ ```css
229
+ /* Any horizontal row with 3+ children MUST have flex-wrap */
230
+ .flow-bar, .step-row, .tag-row, .icon-grid {
231
+ display: flex;
232
+ flex-wrap: wrap; /* MANDATORY for 3+ items */
233
+ gap: 12px; /* Consistent spacing */
234
+ max-width: 100%; /* Never exceed container */
235
+ }
236
+ ```
237
+
238
+ **Rule 3.5.2 — Flex children must have `min-width` + `flex-shrink`:**
239
+ ```css
240
+ .flow-step, .tag-item {
241
+ flex: 1 1 auto; /* Grow, shrink, auto basis */
242
+ min-width: 80px; /* Prevent crushing to 0 */
243
+ max-width: 100%; /* Never exceed container alone */
244
+ overflow-wrap: break-word; /* Break long words */
245
+ word-break: break-all; /* CJK fallback */
246
+ }
247
+ ```
248
+
249
+ **Rule 3.5.3 — Arrow/connector separators must not be rigid:**
250
+ ```css
251
+ /* ❌ WRONG — rigid arrow div between flex items */
252
+ <div class="step">Step 1</div>
253
+ <div class="arrow">→</div> /* Fixed-width, prevents shrinking */
254
+ <div class="step">Step 2</div>
255
+
256
+ /* ✅ RIGHT — arrow as pseudo-element, doesn't affect flex layout */
257
+ .flow-step + .flow-step::before {
258
+ content: '→';
259
+ margin: 0 8px;
260
+ color: #999;
261
+ flex-shrink: 0;
262
+ }
263
+ ```
264
+
265
+ **Rule 3.5.4 — Threshold-based layout switching:**
266
+
267
+ | Item count | Recommended layout | Notes |
268
+ |------------|-------------------|-------|
269
+ | 1-3 items | Horizontal flex (no wrap needed if items are short) | Still add `max-width: 100%` on container |
270
+ | 4-6 items | Horizontal flex + `flex-wrap: wrap` | Items may wrap to 2 rows |
271
+ | 7+ items | Vertical stack or CSS Grid 2×N | Horizontal becomes unreadable |
272
+ | Items with long text (>15 CJK chars / >25 Latin chars) | Vertical stack regardless of count | Long labels don't fit side-by-side |
273
+
274
+ ### Quick Self-Check
275
+
276
+ Before generating any horizontal flex layout, verify:
277
+ ```
278
+ □ Container has max-width: 100% (or explicit width ≤ page width)?
279
+ □ flex-wrap: wrap is set (if ≥3 items)?
280
+ □ Each child has min-width + max-width constraints?
281
+ □ Separators (arrows, dots, lines) are pseudo-elements, not rigid divs?
282
+ □ Long text items have overflow-wrap: break-word?
283
+ ```
284
+
285
+ ---
286
+
287
+ ## 4. Table Overflow: Dynamic Column Width Allocation
288
+
289
+ Tables are the #1 source of horizontal overflow.
290
+
291
+ ### Strategy: Weight-Based Column Width
292
+
293
+ ```python
294
+ from reportlab.pdfbase.pdfmetrics import stringWidth
295
+ from reportlab.platypus import Table, TableStyle, Paragraph
296
+ from reportlab.lib.styles import ParagraphStyle
297
+
298
+ def calculate_col_widths(data, font_name, font_size, available_width, min_col=30):
299
+ """Calculate column widths based on content weight.
300
+
301
+ Each column's width is proportional to its widest content,
302
+ with a minimum width and total constrained to available_width.
303
+ """
304
+ n_cols = len(data[0])
305
+
306
+ # Measure max content width per column
307
+ max_widths = [0] * n_cols
308
+ for row in data:
309
+ for i, cell in enumerate(row):
310
+ text = str(cell) if not isinstance(cell, Paragraph) else cell.text
311
+ w = stringWidth(text, font_name, font_size) + 8 # +8pt padding
312
+ max_widths[i] = max(max_widths[i], w)
313
+
314
+ total_natural = sum(max_widths)
315
+
316
+ if total_natural <= available_width:
317
+ # Everything fits — distribute remaining space proportionally
318
+ extra = available_width - total_natural
319
+ return [w + extra * (w / total_natural) for w in max_widths]
320
+ else:
321
+ # Must compress — allocate proportionally with minimum
322
+ col_widths = []
323
+ for w in max_widths:
324
+ allocated = max(min_col, available_width * (w / total_natural))
325
+ col_widths.append(allocated)
326
+
327
+ # Normalize to exactly fit available_width
328
+ scale = available_width / sum(col_widths)
329
+ return [w * scale for w in col_widths]
330
+
331
+
332
+ def build_safe_table(data, available_width, font_name='Microsoft YaHei', font_size=9):
333
+ """Build a table guaranteed not to overflow horizontally.
334
+
335
+ All text cells are wrapped in Paragraph() for automatic line-breaking.
336
+ """
337
+ wrap_style = ParagraphStyle(
338
+ 'TableCell',
339
+ fontName=font_name,
340
+ fontSize=font_size,
341
+ leading=font_size + 3,
342
+ wordWrap='CJK',
343
+ )
344
+
345
+ # Wrap all cells in Paragraph
346
+ wrapped_data = []
347
+ for row in data:
348
+ wrapped_row = [Paragraph(str(cell), wrap_style) for cell in row]
349
+ wrapped_data.append(wrapped_row)
350
+
351
+ col_widths = calculate_col_widths(data, font_name, font_size, available_width)
352
+
353
+ # Verify total width
354
+ assert sum(col_widths) <= available_width + 0.5, \
355
+ f"Table width {sum(col_widths):.1f} exceeds available {available_width:.1f}"
356
+
357
+ table = Table(wrapped_data, colWidths=col_widths, repeatRows=1)
358
+ return table
359
+ ```
360
+
361
+ ### LaTeX Table Width Management
362
+ ```latex
363
+ % For tables that MUST fit single column
364
+ \begin{tabularx}{\columnwidth}{l X X r} % X = flexible width columns
365
+ ...
366
+ \end{tabularx}
367
+
368
+ % For wide tables in twocolumn mode → span full page
369
+ \begin{table*}[t]
370
+ \begin{tabularx}{\textwidth}{l X X X X r}
371
+ ...
372
+ \end{tabularx}
373
+ \end{table*}
374
+
375
+ % Last resort: shrink to fit (verify ≥ 6pt after scaling)
376
+ \resizebox{\columnwidth}{!}{%
377
+ \begin{tabular}{lllllll}
378
+ ...
379
+ \end{tabular}
380
+ }
381
+ ```
382
+
383
+ ### LaTeX Equation Width Management (Dual-Column)
384
+
385
+ Equations are the **#2 overflow source** after tables in two-column papers (ACM `sigconf` column ~241pt, IEEE ~252pt).
386
+
387
+ ```latex
388
+ % ❌ WRONG — two full equations on one line
389
+ \begin{equation}
390
+ \mathbf{e}_u = \sum \frac{1}{\sqrt{...}} \mathbf{e}_i, \quad
391
+ \mathbf{e}_i = \sum \frac{1}{\sqrt{...}} \mathbf{e}_u
392
+ \end{equation}
393
+
394
+ % ✅ CORRECT — one equation per line
395
+ \begin{align}
396
+ \mathbf{e}_u &= \sum \frac{1}{\sqrt{...}} \mathbf{e}_i, \\
397
+ \mathbf{e}_i &= \sum \frac{1}{\sqrt{...}} \mathbf{e}_u.
398
+ \end{align}
399
+
400
+ % ✅ For wide fractions (softmax, attention)
401
+ % Factor out sub-expressions into separate definitions
402
+ \begin{equation}
403
+ \alpha_{uv} = \frac{\exp(f(u,v))}{\sum_k \exp(f(u,k))},
404
+ \quad \text{where } f(u,v) = \text{LeakyReLU}(\ldots)
405
+ \end{equation}
406
+
407
+ % ✅ For contrastive losses: use multline
408
+ \begin{multline}
409
+ \mathcal{L}_{\text{SSL}}^u =
410
+ -\log \frac{\exp(\text{sim}(z_u', z_u'')/\tau)}
411
+ {\sum_{v \neq u} \exp(\text{sim}(z_u', z_v'')/\tau)}.
412
+ \end{multline}
413
+ ```
414
+
415
+ **Quick heuristic:** if `equation` body > 60 raw characters (excluding `\label`), it probably overflows dual-column. Use `align`, `split`, `multline`, or factor out sub-expressions.
416
+
417
+ See `academic.md` Rules M1–M4 for full patterns.
418
+
419
+ ### LaTeX Algorithm Width Management (Dual-Column)
420
+
421
+ ```latex
422
+ \SetAlFnt{\small} % ❗ MANDATORY in dual-column
423
+ \SetAlCapFnt{\small}
424
+
425
+ % Break long Input/Output across lines:
426
+ \KwInput{Graph $\mathcal{G}_R$, $\mathcal{G}_S$\\
427
+ \quad dim $d$, layers $L$, lr $\eta$, reg $\lambda$}
428
+
429
+ % Or use algorithm* to span full width
430
+ \begin{algorithm*}[t] ... \end{algorithm*}
431
+ ```
432
+
433
+ ### ⚠️ `\columnwidth` vs `\textwidth` in Two-Column Layouts
434
+
435
+ | Context | `\columnwidth` | `\textwidth` |
436
+ |---------|---------------|-------------|
437
+ | Single-column doc | = page content width | = page content width (same) |
438
+ | Two-column doc (`table` float) | = **one column** (~252pt) | = **full page** (~504pt) |
439
+ | Two-column doc (`table*` float) | = one column | = full page |
440
+
441
+ **Rule:** Inside `table` (single-col float), ALWAYS use `\columnwidth`. Inside `table*` (full-width float), use `\textwidth`.
442
+
443
+ `check-tex` detects `\resizebox{\textwidth}` inside single-column floats as error `RESIZEBOX_TEXTWIDTH`.
444
+
445
+ ---
446
+
447
+ ## 5. Fallback & Degradation Strategies
448
+
449
+ When content doesn't fit even after wrapping and scaling, apply these strategies **in order**:
450
+
451
+ ### Automatic Degradation Ladder
452
+
453
+ | Step | Strategy | Limit | Notes |
454
+ |------|----------|-------|-------|
455
+ | 1 | Wrap text into Paragraph | — | Always do this first |
456
+ | 2 | Shrink font by 1pt | **Min 14pt** (single-col) / **12pt** (dual-col) | ⚠️ Enforced by `fill-engine.md` Safety Net 1 |
457
+ | 3 | Reduce padding/spacing | Min 4pt padding | Don't go below 4pt cell padding |
458
+ | 4 | Switch to landscape | Only if user allows | Never change orientation silently |
459
+ | 5 | Split into multiple elements | — | e.g., one wide table → two tables |
460
+ | 6 | Log warning + render anyway | — | If all else fails, at least don't crash |
461
+
462
+ ### ReportLab Font Degradation
463
+ ```python
464
+ def fit_text_with_degradation(text, font_name, base_size, max_width, min_size=14):
465
+ """Try progressively smaller font sizes until text fits.
466
+
467
+ NOTE: min_size enforced by fill-engine.md Safety Net 1.
468
+ Single-column: min_size=14. Dual-column: min_size=12.
469
+ If text still doesn't fit at min_size → trigger page break, do NOT shrink further.
470
+ """
471
+ for size in range(base_size, min_size - 1, -1):
472
+ if stringWidth(text, font_name, size) <= max_width:
473
+ return size
474
+ return min_size # Absolute floor — log warning
475
+ ```
476
+
477
+ ### Table Column Degradation
478
+ ```python
479
+ def degrade_table_if_needed(data, available_width, font_name, base_font_size=10):
480
+ """Try fitting table, degrading font size if needed."""
481
+ for font_size in [base_font_size, base_font_size - 1, base_font_size - 2]:
482
+ col_widths = calculate_col_widths(data, font_name, font_size, available_width)
483
+ if all(w >= 25 for w in col_widths): # Minimum 25pt per column
484
+ return font_size, col_widths
485
+
486
+ # Still doesn't fit — consider splitting table or landscape
487
+ return base_font_size - 2, col_widths
488
+ ```
489
+
490
+ ---
491
+
492
+ ## 6. Vertical Overflow: Y-Cursor & Smart Pagination
493
+
494
+ Horizontal overflow → wrap/scale/shrink.
495
+ Vertical overflow → paginate.
496
+
497
+ ### Y-Cursor Architecture (ReportLab Platypus handles this, but understand it)
498
+
499
+ ```
500
+ Page Start
501
+ ├── Current_Y = top_margin
502
+ ├── Draw Block A (height = 80pt)
503
+ │ └── Current_Y += 80 + spacing
504
+ ├── Draw Block B (height = 120pt)
505
+ │ └── Current_Y += 120 + spacing
506
+ ├── Check: Current_Y + Next_Block_Height > (page_height - bottom_margin)?
507
+ │ ├── YES → New page, reset Current_Y = top_margin
508
+ │ └── NO → Continue drawing
509
+ └── ...
510
+ ```
511
+
512
+ ### Anti-Tear Rules (Elements That Must Not Split)
513
+
514
+ ```python
515
+ from reportlab.platypus import KeepTogether
516
+
517
+ # 1. Heading + first paragraph — MANDATORY
518
+ story.append(KeepTogether([
519
+ heading,
520
+ first_paragraph,
521
+ ]))
522
+
523
+ # 2. Image/chart + caption — MANDATORY
524
+ story.append(KeepTogether([
525
+ chart_image,
526
+ caption_paragraph,
527
+ ]))
528
+
529
+ # 3. Table title + table (short tables ≤ 15 rows)
530
+ if len(data) <= 15:
531
+ story.append(KeepTogether([table_title, table]))
532
+
533
+ # 4. Long tables: repeat header on each page
534
+ table = Table(data, repeatRows=1) # First row repeats on every page
535
+ ```
536
+
537
+ ### Orphan/Widow Prevention
538
+
539
+ - If a paragraph's last line would be alone on the next page → pull at least 2 lines forward
540
+ - If a section heading lands at page bottom with no body text → push to next page
541
+ - ReportLab: `KeepTogether` handles most cases; `allowSplitting=False` for critical blocks
542
+
543
+ ### LaTeX Vertical Overflow
544
+ ```latex
545
+ % Prevent orphans and widows
546
+ \widowpenalty=10000
547
+ \clubpenalty=10000
548
+
549
+ % Prevent page break after heading
550
+ \usepackage{titlesec}
551
+ \titlespacing*{\section}{0pt}{12pt plus 4pt minus 2pt}{6pt plus 2pt minus 2pt}
552
+
553
+ % Keep float near text
554
+ \usepackage[section]{placeins} % \FloatBarrier at each \section
555
+ ```
556
+
557
+ ---
558
+
559
+ ## 7. Two-Pass Rendering (Advanced — for Complex Documents)
560
+
561
+ For critical documents where overflow would be unacceptable:
562
+
563
+ ### Pass 1: Virtual Layout (Measurement)
564
+
565
+ Calculate all element sizes without rendering. Build a **Layout Tree**:
566
+
567
+ ```python
568
+ layout_tree = [
569
+ {"type": "heading", "width": 450, "height": 28, "page": 1},
570
+ {"type": "paragraph", "width": 450, "height": 84, "page": 1},
571
+ {"type": "table", "width": 450, "height": 220, "page": 1},
572
+ {"type": "chart", "width": 400, "height": 300, "page": 2},
573
+ # ...
574
+ ]
575
+ ```
576
+
577
+ ### Collision Detection
578
+
579
+ ```python
580
+ def check_overflow(layout_tree, page_width, left_margin, right_margin):
581
+ """Verify no element overflows page boundaries."""
582
+ max_x = page_width - right_margin
583
+ violations = []
584
+ for elem in layout_tree:
585
+ right_edge = left_margin + elem["width"]
586
+ if right_edge > max_x:
587
+ violations.append({
588
+ "element": elem["type"],
589
+ "page": elem["page"],
590
+ "overflow_by": right_edge - max_x,
591
+ })
592
+ return violations
593
+ ```
594
+
595
+ ### Pass 2: Render with Confirmed Layout
596
+
597
+ Only render after Pass 1 confirms zero violations. If violations found → apply degradation strategies from §5, then re-run Pass 1.
598
+
599
+ **In practice**: ReportLab's Platypus engine already does a form of two-pass rendering internally (`doc.multiBuild()`). Use `multiBuild` + `afterFlowable` callbacks for complex documents that need cross-referencing or dynamic layout adjustment.
600
+
601
+ ---
602
+
603
+ ## Quick Reference: Which Route Uses What
604
+
605
+ | Mechanism | ReportLab (Report) | LaTeX (Academic) | Playwright (Creative) |
606
+ |-----------|-------------------|-------------------|----------------------|
607
+ | Text wrapping | `Paragraph()` + `wordWrap='CJK'` | `tabularx` X columns | CSS `overflow-wrap: break-word` |
608
+ | Image scaling | `fit_image()` helper | `\includegraphics[max width=]` | CSS `max-width: 100%` |
609
+ | Table width | `calculate_col_widths()` | `tabularx` / `resizebox` | CSS `table-layout: fixed` |
610
+ | Font degradation | `fit_text_with_degradation()` | `\small` / `\footnotesize` | CSS `font-size` step-down |
611
+ | Page break | `PageBreak()` / `KeepTogether` | `\newpage` / `\FloatBarrier` | CSS `break-before: page` |
612
+ | Header repeat | `Table(repeatRows=1)` | `\endhead` in longtable | `thead { display: table-header-group }` |
613
+ | Orphan/widow | `KeepTogether` | `\widowpenalty=10000` | CSS `orphans: 2; widows: 2` |
614
+
615
+ ---
616
+
617
+ ## Checklist (Run Before Every PDF Build)
618
+
619
+ ```
620
+ □ All table cells use Paragraph() wrapping, not plain strings?
621
+ □ sum(colWidths) ≤ available_width verified in code?
622
+ □ Images scaled to fit container (not original size)?
623
+ □ Long tables have repeatRows=1 (or thead header-group)?
624
+ □ Heading + first paragraph wrapped in KeepTogether?
625
+ □ Chart + caption wrapped in KeepTogether?
626
+ □ CJK text uses wordWrap='CJK' style?
627
+ □ URL/long-string cells have word-break handling?
628
+ □ Font degradation fallback exists for tight columns?
629
+ □ Last page content ratio ≥ 40%?
630
+ ```