Merge pull request 'feat(skills): add lawnb-pdf-download skill' (#5) from stage2/s2-20-index-coverage-build into main

Reviewed-on: #5
This commit was merged in pull request #5.
This commit is contained in:
2026-10-28 13:26:36 +00:00
7 changed files with 371 additions and 0 deletions
@@ -0,0 +1,93 @@
---
name: lawnb-pdf-download
disable-model-invocation: true
description: Use when asked to save LAWnB (로앤비 전자법률도서관) 주석서 pages as PDF files — click a TOC item (장·절·조·총설·전론·후론), press 인쇄, "save as PDF", rename, merge per 대항목 and delete the temp files. Covers 주석 민법, 주석 상법, 주석 민사소송법 and similar books on academynext-lawnb-com.libra.cnu.ac.kr via ego-browser. Draft; verify the page structure before trusting it.
---
# LAWnB 주석서 → PDF
Repeats the manual "목차 항목 클릭 → 우측 상단 인쇄 → PDF로 저장" flow for many items, then merges
the per-item PDFs into one file per 대항목 and deletes the temp PDFs. Built from ~25 runs
(채권총칙·채권각칙·상속법·상법, ~1,100 pages printed). Personal research use under the library's licence
only; save one file per requested item and do not redistribute.
Read the `ego-browser` skill first (`ego-browser skill`). Scripts here are templates for `ego-browser nodejs`.
## Prerequisites
- Someone is logged in to the library proxy in ego lite (the print layer calls `/Login/GetLoginChk`).
- Run every `ego-browser` command with the sandbox **disabled** (it must launch the app), and every command that
writes to the user's destination folder too (the sandbox only allows writes under the working directory).
Keep the temp PDFs in the session scratchpad dir.
- The user's own visible tab cannot be controlled (it is not in a task space). Open the same book URL in an
agent task space; the result is identical because each page is addressed by id.
## Workflow
1. **Find the book.** Run `scripts/find_books.js`. A book = the sid prefix, e.g. `D021FC603232FC8E`
(채권총칙), `D021436693BDE2F6` (채권각칙), `D021D0E9032210F7` (상속법), `D0216150ACD3F2DF` (상법 총칙·상행위),
`D021E22544FFC822` (상법 보험). Confirm the book name on the opened page (line after "로앤비"), not from memory.
Book URL = `https://academynext-lawnb-com.libra.cnu.ac.kr/Info/ContentView?sid=<BOOK>_<anyNodeId>`.
2. **Probe the TOC.** Render `scripts/probe_toc.js` with `{bookUrl, rootRegex, depth}` and read the tree. Decide:
which children are 대항목, whether a 절/관 is a link-less group, how many pages each has. Compare with the
user's request: the user's ranges and names can contain typos (e.g. 제527조~제533조 vs ~제553조); use the site
and say so.
3. **Print.** Render `scripts/print_items.js` with the groups (`key` + regex on the child's own text). Fewer
than ~40 pages: run in the foreground. More: `run_in_background` (foreground limit is 10 min, ~10 s per page;
stdout appears only at the end, so check progress by counting files in tmpDir). A rerun skips existing files.
4. **Verify** with `scripts/verify_pdfs.py <tmpDir>`: duplicates, article heading vs filename, empty files.
Look at every `총설`/`전론` first heading line. Check the printed log for `FAIL` and `SAVED-UNVERIFIED`.
5. **Merge** with `scripts/merge_pdfs.py config.json` (pdfunite; page sums compared; temp files deleted only
if everything matched). Final names = exactly what the user gave; add nothing else unless told, and report
any extra file you made.
6. **Report**: per output file name, page count, number of merged items, anything deviating from the request.
Render a template: `python3 scripts/render.py scripts/print_items.js cfg.json $SCRATCH/run.js && ego-browser nodejs < $SCRATCH/run.js`
## How the site works (what the scripts rely on)
- Every page-level TOC anchor has `href="javascript:doc.showTargetContent('<BOOK>|<id>|R1')"`. Call that function
directly; no click needed. Roman-numeral sub-headings (Ⅰ, Ⅱ ...) have three-part ids
(`<BOOK>|<id>|<id2>|R1`) and are sections of the same page — never print them separately.
- 인쇄: click `#pring_set` → a layer opens → click its `인쇄` button (find by text, click by coordinates) → a popup
`ContentPrintView` opens. The browser's native print dialog is not automatable, so the scripts run
`Page.printToPDF` on that popup instead. Say this to the user: same content, page breaks may differ slightly.
- The popup prints the whole subtree of the selected item (an article with 150 sub-sections gives 150+ pages).
- 절/관/장 nodes are usually link-less `<li>` (text node only) or anchors without a page id. The 대항목 for such a
node = every page anchor beneath it, in TOC order (including 총설, 전론, 후론, 부칙, 보론, nested 관).
- TOC text uses `[총설]`, `[전론 : ...]`, `[후론2 : ...]`, `제22조의2`, `제4장의2`; match with regexes that allow `의N`.
## Pitfalls (each one cost a rerun)
- **Stale page.** Printing before the new page is rendered saves the previous page (제741조 came out as 총설).
The script waits 4.5 s+, checks the popup text contains the title and differs from the last page, and retries.
Raise `waitMs` if mismatches appear.
- **Env vars and argv do not reach ego scripts.** Inject config text (render.py). Heredoc or `< file` only.
- **Shell.** The shell is zsh: arrays are 1-indexed and `$var` is not word-split. Use the Python scripts for
loops/merging. Sort numerically (item 100+ sorts before 11 as text).
- **Key collisions.** `제4장` vs `제4장의2` need `(?:의(\d+))?` in the key regex; temp file keys like `4` and `4_2`
must not match each other (merge_pdfs.py uses `\d{2,}` for NN).
- **Timeouts/killing.** A foreground run is killed at 10 min. Use background + rerun. Kill a hung run with
`pkill -f "ego-browser nodejs"` only when you started it.
- **Deleting temp files.** Write `rm "${T:?}"/*.pdf` — the safety check rejects an unguarded `$T`. Delete only the
temp PDFs you created. merge_pdfs.py already does this (`deleteTmp: true`).
- **One group, one file.** A 대항목 with a single page is merged by copying; the individual and merged files are then
identical, which is fine.
- Items with only `Ⅰ.` sub-headings and no own page id (e.g. 노동관계법 in 불법행위) are single pages.
## Config examples
print_items (상법 제2편 제6·7장):
```json
{"task": "lawnb 상법2 6-7",
"bookUrl": "https://academynext-lawnb-com.libra.cnu.ac.kr/Info/ContentView?sid=D0216150ACD3F2DF_100266",
"rootRegex": "^제2편 상행위",
"groups": [{"key": "6", "match": "^제6장"}, {"key": "7", "match": "^제7장"}],
"tmpDir": "/abs/scratchpad/tmp_sb/"}
```
merge_pdfs:
```json
{"tmpDir": "/abs/scratchpad/tmp_sb", "destDir": "/abs/.../주석_상법",
"prefix": "주석상법_제2편_", "groups": [["6", "제6장_중개업"], ["7", "제7장_위탁매매업"]], "deleteTmp": true}
```
Use `"^제4장(?!의)"` for 제4장 and `"^제4장의2"` for 제4장의2.
@@ -0,0 +1,12 @@
// List every book entry button on the LAWnB 주석서 main page with its sid.
// The sid prefix (before "_") identifies the book; the suffix is a TOC node id.
// Run (sandbox disabled): ego-browser nodejs < find_books.js
const task = await taskSpace("lawnb find books " + Date.now());
const page = task.page("p1");
await page.goto("https://academynext-lawnb-com.libra.cnu.ac.kr/Info/ContentMain/Jusuk", { timeout: 30000 });
await page.waitForTimeout(3000);
const rows = await page.evaluate(() => [...document.querySelectorAll('[onclick]')]
.filter(e => /showOriginalView/.test(e.getAttribute('onclick')))
.map((e, i) => i + ': ' + e.textContent.trim().replace(/\s+/g, ' ') + ' | ' + (e.getAttribute('onclick').match(/sid=([^']+)/) || [])[1]));
console.log(rows.join('\n'));
await task.finish({ keep: [] });
@@ -0,0 +1,59 @@
#!/usr/bin/env python3
"""Merge the individual PDFs of each group into one file, then (optionally) delete the temp files.
Usage: python3 -I merge_pdfs.py <config.json> (run with the sandbox disabled when dest is outside the working dir)
config.json = {
"tmpDir": "/abs/tmp/dir", # where print_items.js wrote s{key}_{NN}_{label}.pdf
"destDir": "/abs/destination/folder", # must already exist
"prefix": "주석상법_제2편_", # final name = prefix + name + ".pdf"
"groups": [["6", "제6장_중개업"], ["7", "제7장_위탁매매업"]], # [key, name] in the order wanted
"deleteTmp": true # delete the temp PDFs after every group merged cleanly
}
A group with one file is copied. Page sums are compared with the merged file.
Nothing is deleted unless every group merged with matching page counts and
the number of merged inputs equals the number of files in tmpDir.
"""
import json
import os
import re
import shutil
import subprocess
import sys
cfg = json.load(open(sys.argv[1], encoding="utf-8"))
T, D = cfg["tmpDir"], cfg["destDir"]
def pages(p):
out = subprocess.run(["pdfinfo", p], capture_output=True, text=True).stdout
return int(re.search(r"Pages:\s+(\d+)", out).group(1))
all_files = [f for f in os.listdir(T) if f.endswith(".pdf")]
used, ok = 0, True
for key, name in cfg["groups"]:
pat = re.compile(r"s%s_(\d{2,})_" % re.escape(key))
fs = sorted((f for f in all_files if pat.match(f)), key=lambda f: int(pat.match(f).group(1)))
nums = [int(pat.match(f).group(1)) for f in fs]
if nums != list(range(1, len(nums) + 1)):
print("GAP in numbering for", key, nums[:10]); ok = False; continue
paths = [os.path.join(T, f) for f in fs]
out = os.path.join(D, cfg["prefix"] + name + ".pdf")
if len(paths) == 1:
shutil.copyfile(paths[0], out)
else:
subprocess.run(["pdfunite"] + paths + [out], check=True)
s, m = sum(pages(p) for p in paths), pages(out)
used += len(paths)
flag = "OK" if s == m else "MISMATCH(inputs %d)" % s
ok &= (s == m)
print(f"{name} | {len(paths)}건 | {m}쪽 {flag}")
if cfg.get("deleteTmp") and ok and used == len(all_files):
for f in all_files:
os.remove(os.path.join(T, f))
os.rmdir(T)
print("temp deleted:", len(all_files), "files")
else:
print("temp NOT deleted (used %d of %d files, ok=%s)" % (used, len(all_files), ok))
@@ -0,0 +1,100 @@
// Print LAWnB 주석서 TOC pages to PDF, one file per page-level item.
// Render with render.py, then run (sandbox must be disabled):
// ego-browser nodejs < rendered.js
//
// CFG = {
// task: "unique task space name",
// bookUrl: "https://academynext-lawnb-com.libra.cnu.ac.kr/Info/ContentView?sid=<BOOK>_<anyNodeId>",
// rootRegex: "^제2장 계약", // TOC node whose DIRECT children are the 대항목
// groups: [ {key: "2", match: "^제2절"}, {key: "t", match: "^\\[총설\\]$"} ],
// tmpDir: "/abs/path/ending/with/slash/", // scratch dir for individual PDFs
// waitMs: 4500 // optional; wait after selecting a page
// }
// Each group = every page-level anchor (href id with exactly two parts) found
// anywhere under the matching child <li>, in TOC order. Files are written as
// s{key}_{NN}_{label}.pdf (NN = 01.. in TOC order; label = 총설 | 제N조 | 부칙 | [제목] | X)
// Files that already exist are skipped, so a crashed or timed-out run can be
// started again unchanged.
const CFG = __CFG__;
const task = await taskSpace(CFG.task);
const page = task.page("p1");
const fs = await import("node:fs/promises");
await fs.mkdir(CFG.tmpDir, { recursive: true });
const WAIT = CFG.waitMs || 4500;
await page.goto(CFG.bookUrl, { timeout: 30000 });
await page.waitForTimeout(3000);
const groups = await page.evaluate((cfg) => {
const ownText = (li) => { const a = li.querySelector(':scope > a'); return a ? a.innerText.trim() : [...li.childNodes].filter(n => n.nodeType === 3).map(n => n.textContent.trim()).join(''); };
const root = [...document.querySelectorAll('li')].find(li => new RegExp(cfg.rootRegex).test(ownText(li)));
if (!root) return { __error: 'root not found: ' + cfg.rootRegex };
const ol = root.querySelector(':scope > ol, :scope > ul');
const out = {};
for (const li of ol.children) {
const t = ownText(li);
for (const g of cfg.groups) {
if (out[g.key] || !new RegExp(g.match).test(t)) continue;
out[g.key] = [...li.querySelectorAll('a')]
.filter(x => /showTargetContent\('[^'|]+\|\d+\|R1'\)/.test(x.getAttribute('href') || ''))
.map(x => ({ t: x.innerText.trim(), h: x.getAttribute('href') }));
}
}
return out;
}, CFG);
if (groups.__error) throw new Error(groups.__error);
const label = (t) => {
if (t === '[총설]') return '총설';
const m = t.match(/^제\d+조(?:의\d+)?/);
if (m) return m[0];
if (/^부칙/.test(t)) return '부칙';
const g = t.match(/^\[([^\]:]+)/);
return g ? g[1].replace(/\s+/g, '') : 'X';
};
const norm = (s) => s.replace(/\s+/g, '').replace(/[\[\]]/g, '');
let lastTxt = "";
async function printOne(h, title, outPath) {
for (let attempt = 1; attempt <= 3; attempt++) {
try {
if (attempt > 1) { await page.goto(CFG.bookUrl, { timeout: 30000 }); await page.waitForTimeout(3000); }
await page.evaluate((h) => { doc.showTargetContent(h.match(/showTargetContent\('([^']+)'\)/)[1]); }, h);
await page.waitForTimeout(WAIT + attempt * 1000); // too short a wait prints the previous page
await page.click("#pring_set", { label: "인쇄 버튼 클릭" });
await page.waitForTimeout(1500);
const btn = await page.evaluate(() => [...document.querySelectorAll('button')]
.filter(e => /^인쇄$/.test(e.innerText.trim()) && e.offsetParent)
.map(e => { const r = e.getBoundingClientRect(); return { x: r.x + r.width / 2, y: r.y + r.height / 2 }; }));
const popupP = page.waitForEvent("popup", { timeout: 15000 + attempt * 5000 });
await page.mouse.click(btn[0].x, btn[0].y, { label: "레이어 인쇄 버튼" });
const p2 = await popupP; // ContentPrintView popup
await page.waitForTimeout(2500);
const txt = await p2.evaluate(() => document.body.innerText);
const titleOk = title === '[총설]' ? txt.includes('[총설]') : norm(txt).includes(norm(title).slice(0, 10));
const ok = titleOk && txt !== lastTxt; // identical text = stale previous page
if (!ok && attempt < 3) { console.log(" mismatch/stale, retry", title); await p2.close(); continue; }
const r = await p2.cdp("Page.printToPDF", { printBackground: true, preferCSSPageSize: true });
await fs.writeFile(outPath, Buffer.from(r.data, "base64"));
lastTxt = txt;
console.log(ok ? "saved" : "SAVED-UNVERIFIED", outPath.split('/').pop(), "|", title, "|", (await fs.stat(outPath)).size);
await p2.close();
return true;
} catch (e) { console.log(" retry", title, attempt, String(e).slice(0, 80)); }
}
console.log("FAIL", title);
return false;
}
for (const g of CFG.groups) {
const items = groups[g.key];
if (!items) { console.log("NO MATCH for group", g.key, g.match); continue; }
console.log("GROUP", g.key, items.length);
let n = 0;
for (const it of items) {
n++;
const pth = CFG.tmpDir + "s" + g.key + "_" + String(n).padStart(2, '0') + "_" + label(it.t) + ".pdf";
try { await fs.stat(pth); continue; } catch (e) { /* not there yet */ }
await printOne(it.h, it.t, pth);
}
}
console.log(await task.finish({ keep: [] }));
@@ -0,0 +1,31 @@
// Dump the TOC subtree under one node of a LAWnB 주석서 book.
// Render with render.py (CFG = {bookUrl, rootRegex}) and run:
// ego-browser nodejs < rendered.js (sandbox must be disabled)
//
// Output: one line per TOC node. "pages" = number of page-level anchors
// (href id has exactly two parts) under that child. Roman-numeral sub-headings
// (three-part ids) are NOT pages; they are sections of the page above them.
const CFG = __CFG__;
const task = await taskSpace("lawnb probe " + Date.now());
const page = task.page("p1");
await page.goto(CFG.bookUrl, { timeout: 30000 });
await page.waitForTimeout(3500);
const lines = await page.evaluate((cfg) => {
const ownText = (li) => { const a = li.querySelector(':scope > a'); return a ? a.innerText.trim() : [...li.childNodes].filter(n => n.nodeType === 3).map(n => n.textContent.trim()).join(''); };
const root = [...document.querySelectorAll('li')].find(li => new RegExp(cfg.rootRegex).test(ownText(li)));
if (!root) return ['ROOT NOT FOUND for ' + cfg.rootRegex];
const isPage = (x) => /showTargetContent\('[^'|]+\|\d+\|R1'\)/.test(x.getAttribute('href') || '');
const out = [];
const walk = (li, d, maxDepth) => {
const a = li.querySelector(':scope > a');
const t = ownText(li);
const pages = [...li.querySelectorAll('a')].filter(isPage).length;
out.push(' '.repeat(d) + (t || '(no text)') + (a ? '' : ' [group: no link]') + ' pages=' + pages);
const ol = li.querySelector(':scope > ol, :scope > ul');
if (ol && d < maxDepth) [...ol.children].forEach(c => walk(c, d + 1, maxDepth));
};
walk(root, 0, cfg.depth || 1);
return out;
}, CFG);
console.log(lines.join('\n'));
await task.finish({ keep: [] });
@@ -0,0 +1,19 @@
#!/usr/bin/env python3
"""Inject a JSON config into a script template and write the result.
ego-browser scripts do not inherit environment variables or argv, so every
input has to be written into the script text. This helper replaces the
literal token __CFG__ in a template with the JSON config.
Usage:
python3 render.py <template.js> <config.json> <output.js>
"""
import json
import sys
template, cfg_path, out_path = sys.argv[1:4]
cfg = json.load(open(cfg_path, encoding="utf-8"))
src = open(template, encoding="utf-8").read()
assert "__CFG__" in src, "template has no __CFG__ placeholder"
open(out_path, "w", encoding="utf-8").write(src.replace("__CFG__", json.dumps(cfg, ensure_ascii=False)))
print("rendered", out_path)
@@ -0,0 +1,57 @@
#!/usr/bin/env python3
"""Check the individual PDFs written by print_items.js.
Usage: python3 -I verify_pdfs.py <tmpDir>
Reports: file count, duplicate files (same hash = a stale page was printed
twice), articles whose first heading does not match the file label, empty
PDFs, and the first heading + page count of every non-article file
(총설 / 전론 / 후론 ...) so a human can eyeball them.
Exit status 1 when anything is wrong.
"""
import hashlib
import os
import re
import subprocess
import sys
tmp = sys.argv[1]
files = sorted(f for f in os.listdir(tmp) if f.endswith(".pdf"))
bad = 0
def text(path):
return subprocess.run(["pdftotext", path, "-"], capture_output=True, text=True).stdout
def pages(path):
out = subprocess.run(["pdfinfo", path], capture_output=True, text=True).stdout
return int(re.search(r"Pages:\s+(\d+)", out).group(1))
seen = {}
for f in files:
h = hashlib.md5(open(os.path.join(tmp, f), "rb").read()).hexdigest()
if h in seen:
print("DUPLICATE", f, "==", seen[h])
bad = 1
seen[h] = f
print("files:", len(files))
for f in files:
p = os.path.join(tmp, f)
m = re.match(r"s.+?_(\d{2,})_(.+)\.pdf$", f)
lab = m.group(2)
lines = [l.strip() for l in text(p).split("\n") if l.strip()]
if not lines:
print("EMPTY", f)
bad = 1
continue
if re.match(r"제\d+조(의\d+)?$", lab):
if not any(re.match(re.escape(lab) + r"(\s|\[|$)", l) for l in lines[:14]):
print("MISMATCH", f, "| first lines:", lines[2:4])
bad = 1
else:
head = next((l for l in lines[2:14] if l), "")
print(f"{f} | {pages(p)}쪽 | {' / '.join(lines[2:4])[:80]}")
sys.exit(bad)