Author SHA1 Message Date
jhogyuandClaude Opus 5.5 0ab9275770 Merge branch 'main' into stage1-stage2-sync-20260930
Resolve add/add conflicts in favor of main: the sync branch versions of the
v.8 Part 1/2/4 YAMLs and Stage 2 MEMORY/SKILL/IO docs are older snapshots
already present in main history.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 15:59:56 +09:00
jhogyu 06605d308c Merge pull request 'feat(skills): add lawnb-pdf-download skill' (#5) from stage2/s2-20-index-coverage-build into main
Reviewed-on: #5
2026-10-28 13:26:36 +00:00
jhogyuandClaude Sonnet 5.5 b066471945 feat(skills): add lawnb-pdf-download skill for saving LAWnB 주석서 pages as PDF
Scripts to probe a book's TOC, print each page-level item to PDF via the
print popup, verify, merge per 대항목 and clean up temp files. Invoked only
by /lawnb-pdf-download (disable-model-invocation).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-28 22:16:22 +09:00
jhogyu 6ee013d83b Merge pull request 'feat(stage2): S2_20 v.2 YAMLs (G1, G2 draft/verify, G3 CU repair) and legal reference PDFs' (#4) from stage2/s2-20-index-coverage-build into main
Reviewed-on: #4
2026-10-28 12:26:47 +00:00
jhogyuandClaude Opus 5.5 18fa95368b chore(stage2): add 주석 민법·상법 chapter PDFs to legal references
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 21:05:43 +09:00
jhogyuandClaude Opus 5.5 ee943358e3 feat(stage2): add S2_20 v.2 YAMLs for G1, G1+G2 and G1+G2+G3 (CU repair)
- Stage_2_S2_20_G1.yml: T0 prepare (input binding, index load, coverage, CU packets)
- Stage_2_S2_20_G1_G2.yml: CU drafting and verification (T2a/T3a/T1/T2b/T3b, gpt-6.1-sol)
- Stage_2_S2_20_G1_G2_G3.yml: CU repair loader, repair LLM and re-verification
  (T4p/T4/T3c); packet limit 260,000 chars to match the backend preflight limit
- 작업구조도설계_S2_20_v.2.md design doc, work history, previous YAML kept as outdated
- MEMORY.md entries for G2 and G3

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 21:05:33 +09:00
jhogyu b8f3ca927c Merge pull request 'Stage2/s2 20 index coverage build' (#3) from stage2/s2-20-index-coverage-build into main
Reviewed-on: #3
2026-10-28 02:29:29 +00:00
jhogyu 348413044b chore: sync Stage 1 and Stage 2 working files
Include only YAML_Prompts/1. Stage_1 and YAML_Prompts/2. Stage_2.
2026-09-30 20:13:00 +09:00
436 changed files with 226906 additions and 428 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)
@@ -0,0 +1,250 @@
<working_directory>
- root: 'prompt_updates_sequential/Case_02_Comparison_Research/'
- main: 'prompt_updates_sequential/Case_02_Comparison_Research/YAML_Prompts/2. Stage_2'
</working_directory>
분석 대상:
'2. Stage_2/Default_Agent/Stage_2_Clean/agent_scripts/' 폴더의 'Stage_2_S2_00.yml'
사용 자료:
'main' directory의 'Stage_2_00_Analysis_v1.md'
<task>
'Stage_2_S2_00.yml' 작업 실행 단계별 input & output file들에 대해
- Input file들의 정확한 file name, file format, source folder 위치
- Output file들의 정확한 file name, file format, file 저장 folder 위치
를 정확하게 식별하여 그것을 문서로 작성한다.
</task>
<method>
<task>에 제시된 작업을 수행한 후,
아래 형식대로 .md 문서로 내용을 작성한다:
<형식>
- 'Stage_2_S2_00.yml' 작업의 DAG structure (refer to 'Stage_2_00_Analysis_v1.md')
- DAG structure의 각 단계별 작업명에 대해 input & output file 제시
- input file의 정확한 file name, file format, source folder 위치
- output file의 정확한 file name, file format, file 저장 folder 위치
</형식>
작성한 마크다운 문서는 'main' directory에 'Stage_2_00_IO_info.md'로 저장한다.
</method>
---------------------------------------------------------------------------------
'Stage_2_S2_00.yml'에서 사용될 자산 중 `s2_00_request.json`은 현재 'Stage_2_Clean' 폴더에 존재하는가? 예, 아니오로 답하고, 답이 '아니오'이면 그 이유를 한 문단 이내로 설명하라.
[ANSWER]
아니오. 현재 `Stage_2_Clean` 폴더와 그 하위 폴더에 `s2_00_request.json`은 없습니다. 이 파일은 고정 배포 자산이 아니라 외부 orchestrator가 실행 요청을 전달하는 제어 입력이며, `Stage_2_S2_00.yml`은 이를 `Stage_2_Clean` 내부가 아닌 논리 workspace root 기준 `stage2_control/s2_00_request.json` 경로에서 읽도록 지정하고 있습니다.
---------------------------------------------------------------------------------
그렇다면 `s2_00_request.json`은 'Stage_2_S2_00.yml'이 실행되는 도중에 만들어지는 파일인가? 예, 아니오로 답하고 한 문단 이내로 설명하라.
[ANSWER]
아니오. `s2_00_request.json`은 `Stage_2_S2_00.yml`이 실행 중에 생성하는 파일이 아니라, **외부 orchestrator가 실행 전에 준비해야 하는 입력 파일**입니다. YAML의 실행 코드는 초기 단계에서 `stage2_control/s2_00_request.json`을 읽고 그 안의 요청 식별자와 Stage 1 입력·배포 경로를 검증하며, 이 파일을 생성하거나 저장하는 처리는 수행하지 않습니다.
---------------------------------------------------------------------------------
현재 Stage 1 작업이 마무리되고 Stage 2 작업으로 넘어갈 때 고정 handoff 파일들은 'Stage_2_00_IO_info.md'의 "3.2 Stage 1 사건 고정 입력 16개" section에 제시되어 있다. 그리고 그 표에는 `s2_00_request.json`이 존재하지 않는다. 그렇다면, `s2_00_request.json`은 어떤 순간에 어떻게 생성되는가? `s2_00_request.json`가 생성되는 과정을 한 문단 이내로 설명하라.
[ANSWER]
`s2_00_request.json`은 Stage 1이 만드는 16개 사건 산출물과 별도로, **외부 orchestrator가 Stage 1의 실행 결과를 S2_00에 넘길 실행 요청을 준비하는 시점에 작성해야 하는 제어 파일**입니다. 계약상 orchestrator는 `schema_version`을 `stage2_s2_00_execution_request.v1`, `workflow_id`를 `S2_00`으로 설정하고, `request_id`, `attempt_id`, `stage1_run_root_ref`(Stage 1 사건 산출물 폴더), `stage1_deployment_root_ref`(Stage 1 배포 폴더)를 채워 workspace의 `stage2_control/s2_00_request.json`에 저장한 다음 S2_00을 호출해야 합니다. 다만 **현재 확인한 YAML에는 이 파일을 생성하는 구현이 없으며, 외부 orchestrator의 생성 코드가 실제로 구현되어 있는지도 확인하지 않았습니다.** 따라서 이는 현재 코드가 요구하는 사전 준비 절차이지, Stage 1 완료 시 자동 생성되는 것으로 확인된 과정은 아닙니다.
---------------------------------------------------------------------------------
'Stage_2_S2_00.yml'이 정상적으로 실행되기 위해서 `s2_00_request.json`은 반드시 필요한 파일인가? 만일 그렇다면 `s2_00_request.json`의 역할을 한 문단 이내로 짧게 그러나 정교하게 설명하라.
[ANSWER]
예. 현재 `Stage_2_S2_00.yml`의 실행 경로에서는 `s2_00_request.json`이 **반드시 필요한 실행 제어 입력**입니다. 이 파일은 요청 규격과 대상 workflow를 확인하는 `schema_version`·`workflow_id`, 요청과 시도를 식별하는 `request_id`·`attempt_id`, 읽어야 할 Stage 1 사건 산출물 및 배포 자산의 위치를 지정하는 `stage1_run_root_ref`·`stage1_deployment_root_ref`의 정확히 6개 필드로 구성됩니다. 즉, 사건 내용 자체를 전달하는 대신 **이번 실행이 어떤 요청이며 어느 위치의 Stage 1 자료를 처리할지 지정**합니다. 실행 코드는 이를 먼저 읽고 검증하므로, 파일이 없거나 필드 검증에 실패하면 후속 입력 처리로 진행하지 못합니다.
---------------------------------------------------------------------------------
위 답변에서 **현재 확인한 YAML에는 이 파일을 생성하는 구현이 없으며, 외부 orchestrator의 생성 코드가 실제로 구현되어 있는지도 확인하지 않았습니다.**라고 하였다. 그렇다면 현재 `s2_00_request.json`이 생성되는 구현 과정이 없다는 의미이므로, stage 2 작업이 정상적으로 진행될 수 없을 것이다. 나의 판단이 정확한가? 예, 아니오로 답하고 한 문단 이내로 설명하라.
[ANSWER]
아니오. **생성 구현을 확인하지 않았다는 사실이 생성 구현이 없다는 뜻은 아니므로**, 현재 정보만으로 Stage 2가 정상 진행될 수 없다고 단정할 수는 없습니다. 다만 외부 orchestrator나 다른 사전 준비 절차에서 `s2_00_request.json`을 제공하지 않는다면, 현재 `Stage_2_S2_00.yml`은 필수 입력을 읽지 못해 실패하므로 **“이 파일을 준비하는 절차가 실제로 없다면 S2_00을 정상 실행할 수 없다”는 조건부 판단은 정확합니다.**
---------------------------------------------------------------------------------
'2. Stage_2/Default_Agent/Stage_2_Clean/'에서 외부 orchestrator가 `s2_00_request.json`을 생성하는 코드가 실제로 구현되어 있는지 확인하라. 실제 구현된 코드의 존재 유무를 예, 아니오로 답하고 한 문단 이내로 설명하라.
[ANSWER]
아니오. 지정하신 `Stage_2_Clean/` 전체를 검색하고 관련 코드를 확인한 결과, 외부 orchestrator가 `s2_00_request.json`을 구성하여 `stage2_control/s2_00_request.json`에 저장하는 실제 구현은 없습니다. 존재하는 것은 파일 경로·필수 필드를 정한 계약과 schema, 해당 파일을 읽고 검증하는 실행 코드, 그리고 테스트용 request 객체를 만들어 모의 reader로 제공하는 코드입니다. 따라서 **이 폴더 안에는 필수 request를 소비하는 구현은 있지만, 실행 전에 생성·저장하는 구현은 빠져 있습니다.**
---------------------------------------------------------------------------------
`Stage_2_S2_00.yml` 작업 흐름도에서 `s2_00_request.json`을 생성·저장하는 구현을 어느 시점에 삽입하는 것이 가장 효율적인가? 한 문단 이내로 답하라.
[ANSWER]
**Stage 1의 필수 산출물 준비를 확인한 직후, `Stage_2_S2_00.yml`을 호출하기 직전의 외부 orchestrator 단계**에 삽입하는 것이 가장 효율적입니다. 이 시점에 이번 실행의 `request_id`·`attempt_id`와 확정된 Stage 1 사건·배포 폴더 경로를 포함한 6개 필드를 구성하고, schema 검증 후 `stage2_control/s2_00_request.json`에 저장하여 읽기 가능한 상태임을 확인한 다음 S2_00을 호출하면 됩니다. 흐름도에는 **`Stage 1 산출물 준비 확인 → request 생성·검증·저장 → S2_00 호출 → 기존 request 읽기·검증`**으로 배치하며, 동일 workspace의 고정 request 경로를 여러 실행이 덮어쓰지 않도록 생성부터 S2_00의 입력 읽기 완료까지 실행을 격리하거나 직렬화해야 합니다.
---------------------------------------------------------------------------------
`Stage_2_S2_00.yml` 작업 흐름도 맨 앞단에 `s2_00_request.json`을 생성·저장하는 구현을 신설하는 것은 어떤가? 한 문단 이내로 타당성을 평가하라.
[ANSWER]
**조건부로 타당합니다.** `Stage_2_S2_00.yml`의 맨 앞에 request를 생성·검증·저장하는 선행 task를 두고, 완료 후 기존 ingress task를 실행하면 누락된 준비 절차를 명시적으로 연결할 수 있습니다. 다만 현재 request에서 읽는 `request_id`·`attempt_id`와 Stage 1 사건·배포 폴더 경로를 **새 선행 task에는 외부 실행 인자로 공급해야** 하며, 이 공급 경로 없이 생성 단계만 추가하면 필요한 값을 확보할 수 없어 문제가 해결되지 않습니다. 따라서 외부 인자 전달 계약, 저장 성공 후 ingress 실행을 보장하는 의존 관계, 동일 workspace의 고정 request 경로에 대한 동시 실행 충돌 방지를 함께 구현한다면 합리적인 구성입니다.
---------------------------------------------------------------------------------
`s2_00_request.json`을 생성·저장하는 구현을 신설하기 위해서 아래와 같은 구조의 작업을 생각중이다:
<작업>
1. `Stage_2_S2_00.yml`의 맨 앞에 request를 생성·검증·저장하는 선행 task를 둔다.
- 조건: 현재 request에서 읽는 `request_id`·`attempt_id`와 Stage 1 사건·배포 폴더 경로를 새 선행 task에는 외부 실행 인자로 공급한다.
2. 선행 task 완료 후 기존 ingress task를 실행하는 구조를 만든다.
<restrictions>
외부 인자 전달 계약, 저장 성공 후 ingress 실행을 보장하는 의존 관계, 동일 workspace의 고정 request 경로에 대한 동시 실행 충돌 방지를 함께 구현한다.
</restrictions>
</작업>
`s2_00_request.json`을 생성·저장하는 구현을 위한 <작업> 내역을 한 문단 이내로 평가하라.
[ANSWER]
제안한 작업은 **필수 request의 생성 책임과 실행 순서를 명확히 한다는 점에서 타당합니다.** 외부 인자 계약에 필수값·형식·허용 경로를 명시하고, 선행 task가 정확히 6개 필드의 request를 구성·검증한 뒤 저장 및 read-back 일치를 확인해야 하며, 실패하면 ingress가 실행되지 않도록 의존 관계를 설정해야 합니다. 특히 동시 실행 통제는 **request 저장 순간뿐 아니라 기존 ingress의 request 2회 읽기와 입력 hydration이 완료될 때까지** 동일 workspace의 다른 실행이 고정 경로를 덮어쓰지 못하도록 유지해야 합니다. 또한 현재 배포 YAML은 단일 task 계약과 코드·자산 hash 결속을 전제로 하므로, 선행 task 추가에 맞춰 관련 workflow·배포 계약·검증 코드와 hash도 함께 갱신해야 하며, 이 작업의 완료가 기존 release의 실행 제한 등 다른 문제까지 해소한다는 뜻은 아닙니다.
---------------------------------------------------------------------------------
아래는 `s2_00_request.json`을 생성·저장하는 구현을 위해 반드시 고려되어야 할 요소들이다:
<factors>
외부 인자 계약에 필수값·형식·허용 경로를 명시하고, 선행 task가 정확히 6개 필드의 request를 구성·검증한 뒤 저장 및 read-back 일치를 확인해야 하며, 실패하면 ingress가 실행되지 않도록 의존 관계를 설정해야 합니다. 특히 동시 실행 통제는 **request 저장 순간뿐 아니라 기존 ingress의 request 2회 읽기와 입력 hydration이 완료될 때까지** 동일 workspace의 다른 실행이 고정 경로를 덮어쓰지 못하도록 유지해야 합니다. 또한 현재 배포 YAML은 단일 task 계약과 코드·자산 hash 결속을 전제로 하므로, 선행 task 추가에 맞춰 관련 workflow·배포 계약·검증 코드와 hash도 함께 갱신해야 하
</factors>
위 <factors>를 고려하여 `s2_00_request.json`을 생성·저장하는 작업을 `Stage_2_S2_00.yml`의 맨 앞에 신설할 정교한 작업 plan을 작성하라.
[ANSWER]
[s2-00-request-preparation.md](/Users/hogyujhang/Library/CloudStorage/Dropbox/Business/Eroom AI Partners/Legal POC portfolio/민사에이전트-사해행위취소및대여금청구/POC - Law-aid Agent/프롬프트/prompt_updates_sequential/Case_02_Comparison_Research/plans/s2-00-request-preparation.md)
---------------------------------------------------------------------------------
다음의 분석 작업을 수행하라.
<analysis_task>
1. 's2-00-request-preparation.md'에 제시된 작업 내역이 `s2_00_request.json`을 생성·저장하는 구현을 위해 가장 단순하고 효율적인 작업 내역인가? 즉, Occam's Razor의 principle을 충실히 따르는 작업 내역인지 분석하라.
2. 1번의 분석이 's2-00-request-preparation.md' 작업 내역을 좀 더 단순화하고 효율적으로 구현할 가능성이 존재한다는 내용이라면 1번 분석 내용을 반영하여 's2-00-request-preparation.md'을 재작성하고 그 내용을 's2-00-request-preparation_v1.md'으로 저장하라.
</analysis_task>
[ANSWER]
/Users/hogyujhang/Library/CloudStorage/Dropbox/Business/Eroom AI Partners/Legal POC portfolio/민사에이전트-사해행위취소및대여금청구/POC - Law-aid Agent/프롬프트/prompt_updates_sequential/Case_02_Comparison_Research/plans/s2-00-request-preparation_v1.md
---------------------------------------------------------------------------------
<task>
아래 제시된 <조건>을 반영하여, 's2-00-request-preparation_v1.md'에 제시된 내용 중 "Objective" section 이하에 제시된 내용만을 작업 내역으로 사용하여 `s2_00_request.json`을 생성·저장하는 구현하고, 'Stage_2_S2_00.yml'을 신규 작성한다.
<조건>
"4단계 — 실제 영향 범위만 빌드·배포 갱신" section에 제시된 항목 중 `R/agent_scripts/Stage_2_S2_00.yml`을 새로 생성하되, 기존 'Stage_2_S2_00.yml'파일은 'Stage_2_S2_00_outdated_9_09.yml'로 원 저장소에 저장한다.
</조건>
</task>
<restrictions>
1. <task>에서 지시한 작업 외 그 어떤 다른 작업도 수행하지 않는다.
2. 작업 마무리 후, main 디렉토리의 MEMORY.md의 "How to Write MEMORY.md" section 바로 아래에 작업 내역을 압축 요약하여 기입한다.
</restrictions>
---------------------------------------------------------------------------------
위 답변에서 언급한 "위 세 기능을 확인할 수 있는 backend 코드 또는 문서 경로"는 stage 1 yaml 파일 및 assets 들을 의미하는가? 한 문단 이내로 답하라.
[ANSWER]
아니오. 여기서 말한 backend 코드·문서는 **Stage 1 YAML과 자산을 실행하고 Stage 2 호출을 관리하는 AgentBackend 또는 외부 orchestrator의 구현·명세**를 뜻합니다. 구체적으로 ① `request_id`·`attempt_id`·Stage 1 사건 및 배포 폴더 경로를 두 task에 동일하게 전달하는 방식, ② prepare 실패 시 ingress를 실행하지 않는 제어 방식, ③ 동일 workspace에서 여러 실행이 고정 request 파일을 덮어쓰지 못하게 하는 직렬화 방식을 확인할 자료입니다. Stage 1 YAML·자산은 입력 파일과 경로를 파악하는 데 도움이 되지만, 그 안에 이러한 실행 제어 구현이나 명세가 포함되어 있지 않다면 해당 자료를 대신할 수 없습니다.
---------------------------------------------------------------------------------
앞에서 언급한 "위 세 기능을 확인할 수 있는 backend 코드 또는 문서 경로"는 다음과 같다:
[1] 'prompt_updates_sequential/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.7/extension_research/Default_Agent': stage 1 실행을 위해 필요한 모든 assets
[2] 'prompt_updates_sequential/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.8': stage 1 실행을 위한 실제 yaml 파일들
[3] 'prompt_updates_sequential/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.7/extension_research/' 폴더의 4개 파일(stage 1 실행을 위한 실제 yaml 파일들을 분석한 보고서):
- Analysis_Doc_stage_1_part_1_investrigation_final.md
- Analysis_Doc_stage_1_part_2_investrigation_final.md
- Analysis_Doc_stage_1_part_3_investrigation_final.md
- Analysis_Doc_stage_1_part_4_investrigation_final.md
[1], [2], [3]에 제시된 자료들이 위 답변에서 언급한 "**Stage 1 YAML과 자산을 실행하고 Stage 2 호출을 관리하는 AgentBackend 또는 외부 orchestrator의 구현·명세**"를 의미하는지 판단하고 그 내역을 두 문단 이내로 답하라.
---------------------------------------------------------------------------------
내가 원하는 것은 stage 2 작업 실행을 위해 우선적으로 `s2_00_request.json`을 생성·저장하는 구현하는 것이며, 이를 구현할 때 기존 stage 2 작업과 consistent하게 만드는 것이다. 이 경우, 앞에서 요구한 backend 구현·명세 전체가 반드시 필요한가? 한 문단 이내로 답변하라.
[ANSWER]
아니오. **기존 Stage 2와 일관되게 `s2_00_request.json`을 생성·검증·저장하는 코드 자체를 구현하는 데 backend 구현·명세 전체가 반드시 필요한 것은 아닙니다.** 기존 6필드 계약, 경로 검증, canonical JSON 직렬화, localdocs 저장·read-back 방식을 재사용하고 네 외부 인자를 받는 함수로 구현한 뒤 테스트할 수 있습니다. backend 정보는 이후 그 인자를 실제로 공급하고, 선행 task 실패 시 후행 실행을 차단하며, 동시 실행을 통제하는 **운영 연결을 완성·검증할 때 필요한 범위만** 확인하면 됩니다. 앞서 이 연결 정보가 없다는 이유로 코드 구현까지 중단한 것은 필요 이상으로 작업 범위를 묶은 판단이었습니다.
---------------------------------------------------------------------------------
현재 session에서 작업한 내역들을 압축 요약하여 "How to Write MEMORY.md" section 바로 아래에 기입하고 git commit하라.
---------------------------------------------------------------------------------
'/Users/hogyujhang/Library/CloudStorage/Dropbox/Business/Eroom AI Partners/Legal POC portfolio/민사에이전트-사해행위취소및대여금청구/POC - Law-aid Agent/프롬프트/prompt_updates_sequential/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1'
'/Users/hogyujhang/Library/CloudStorage/Dropbox/Business/Eroom AI Partners/Legal POC portfolio/민사에이전트-사해행위취소및대여금청구/POC - Law-aid Agent/프롬프트/prompt_updates_sequential/Case_02_Comparison_Research/YAML_Prompts/2. Stage_2'
2개 폴더에서 발생한 작업에 대해서만 "수정/삭제/미추적파일" 내용을 commit하고 push까지 끝내라.
M/ -> `Case_02_Comparison_Research/YAML_Prompts/2. Stage_2/`
R/ -> `M/Default_Agent/Stage_2_Clean/`
@@ -0,0 +1,966 @@
# 2026-10-28 신규(v.2 G1): 작업구조도설계_S2_20_v.2.md의 6개 묶음 중 G1 준비(T0 prepare)를 구현한다.
# 옛 S2_20(Stage_2_S2_20.yml, Default_Agent/Stage_2_Clean 자산·weaviate)은 Stage_2_S2_20_outdated_kept.yml로 보존했고 이 파일과 무관하다.
# 범위: task는 T0 하나다. task_procedure는 G1 → G2(T2a draft_lead_* → T3a verify_lead_{same_ordinal} → T1 load_rest →
# T2b draft_rest_* → T3b verify_rest_{same_ordinal})까지 적고 OUT으로 닫는다. G2 task를 넣기 전에는 이 파일만으로 돌리지 않는다.
# G3를 붙일 때 OUT 자리에 T4p load_repair_cu(wait: all verify_lead_*, all verify_rest_*, load_rest)를 둔다.
# 원칙: 단순 해법 우선. 코드는 결정적 결속·상태·크기만 정하고, 법리 판단(경로 확정·요건 배정·문안)은 G2 LLM이 블록 2 원문을 읽고 한다.
#
# 입력(모두 raw 바이트 sha로 결속하고 s2_20/snapshot/에 복사한다; I5·I6 원본 폴더와 I7 전체는 읽지 않는다)
# I3 S2_10 7.3.3: filter/filter_status.json(FILTER_COMPLETE 계열만) → claim_identity_review.json(artifacts sha) →
# claims_index.json(bound sha) → claims/RC-NN.json(index sha); s2_10_status.json(bound sha) → work/plan.json(본문 정규 JSON sha =
# plan_sha256 = s2_10_status.plan_sha256, S2_10과 같은 계산)
# → plan의 source·artifacts sha와 registry_sha256·mapping_sha256. 각 파일은 한 번만 읽고 검사한 바이트를 그대로 쓰고 복사한다
# I2 S2_00 v7_7 handoff: S2_10 plan이 sha로 결속한 사본 work/source/RC-NN.json(분할 RC 병합본)·work/llm_input/common.json으로 읽는다
# I1 Stage 1 원본: s2_00/v7_7/ingress/stage1_input_manifest.json의 path·raw_sha256(쓰는 파일만 읽음, sha 불일치 = run BLOCKED).
# manifest 자체는 S2_10 결속 사슬 밖이다(plan ingress_status_sha256 경유 결속은 백엔드 파일 확인 뒤 추가); sha는 snapshot에 남긴다
# I4 등록부: S2_10 plan registry_sha256(S2_10 설정에 내장된 등록부의 sha)을 색인 manifest registry_sha256과 대조
# I7 사전 색인 Default_Agent/Stage_2/rulebook_build/: rulebook_index/{manifest.json, NNN.json}, rulebooks/{claim,elements}/NNN.md
# I8 세 표: Default_Agent/Stage_2/rulebook_build/tables/{relief_invariants, object_class_spans, module_registry}.json
# (빌드 산출물에 없으므로 indexing_scratchpad/의 세 파일을 업로드할 때 함께 올린다, v.2 §11-8)
# I9 stage2_control/s2_20_values.json(선택): {"objects": {"OBJ-…": 가액 자료}}. 없으면 NEEDS_INPUT
# I10 stage2_control/s2_20_request.json(선택): {"prefer": "cost|speed", "hold_mode": "questions|draft",
# "answers": {"CU-NNN": "HOLD 질문에 대한 답(HOLD → 전송)"}, "path_hint": {"CU-NNN": "P2"}, "cp_split": [["CU-…", …], …]}
# 출력(root stage2_runs/from-stage1/s2_20, 실행마다 delete_folder로 비우고 다시 쓴다; S2_10 root 밖)
# snapshot/{입력 경로 사본, index/{manifest.json, NNN.json}, snapshot_manifest.json}
# bundle/{case_bundle.json, complaints/CP-NN.json, claims/CU-NNN.json} (CU 묶음: S2_10 청구문·issues·relief_method_order·
# legality flags·holds·relations·relief 행·객체 행·요건 행 목록·STOP 목록·thread 범위·ref 원본 본문(facts)·evidence_refs·allowed_refs)
# packet/{1_common.md(블록 1), 2_kind/NNN.md(블록 2 = 두 정리본 파일 전체), 2_kind/none.md(종 null), 2_kind/NNN-CU-NNN.md(경로 절 제외본),
# 3_cu/CU-NNN.json(블록 3 = bundle/claims/CU-NNN.json과 같은 바이트)}. 이름순이 블록 순서와 같다(동적 preflight 정렬 방식과 무관하게)
# items/{lead.json, rest.json} review/holds.json prepare.json(마지막에 쓴다)
# 항목: {run_id, cu_id, cp_id, case_kind_index, status, block2_path, block3_path, cache_key "s2_20:draft:NNN", cache_shared, packet_chars}
# stdout: {"status": "PREPARED", …, "dynamic_fanout": lead 항목}. 실패하면 {"status": "BLOCKED", "error", "dynamic_fanout": []}과
# 빈 items/lead.json·rest.json을 써서 G2 로더가 빈 fan-out으로 지나가게 한다.
#
# 상태(v.2 §8.7 → 설계 §4 T0 0.5): 우선순위 BLOCKED > EXCLUDE_RECOMMENDED > HOLD > DRAFT_WITH_LAWYER_NOTE > DRAFT_WITH_PLACEHOLDERS > READY
# BLOCKED: CU ref가 Stage 1 원본에서 풀리지 않음. EXCLUDE: 무조건(conditional false) 제외 권고.
# HOLD: CU 결정 HOLD, S2_10 holds 대상, 청구 standing DOUBTFUL, 상속 단위 provisional, 색인 STALE, 패킷 한도 초과.
# LAWYER_NOTE: 조건부 제외 권고, CONFIRMATION_EXCEPTION, 종 null, BRANCH 구성원(방법 분기), 주위적 CU가 HOLD인 예비적 CU, I10 답변 반영.
# PLACEHOLDERS: relief_detail 빈 값, RELIEF_DETAIL_MISSING·RELIEF_KIND_UNRESOLVED, 부대청구 이율·기산일 미정.
# review(전송하되 변호사 검토): 정리 기록 REC_CROSS_KIND·REC_RESTORE_BLOCKED, 구성원 종 불일치, 상류 문면의 가나 문자(NON_KOREAN_TEXT,
# 7.3.3 미해결 혼입; T2가 옮겨 쓰지 않게 알린다), object_class 미정(OBJECT_CLASS_FOLLOWS_RELIEF·OBJECT_CLASS_UNRESOLVED).
# HOLD·EXCLUDE·BLOCKED는 항목을 만들지 않고 review/holds.json에 사유·질문만 낸다(hold_mode=draft면 색인 STALE 외의 HOLD도 전송).
# 로컬 하네스(S2_10 7.3.3 실출력 + handoff 본문으로 만든 합성 Stage 1) 결과: N=15, L=9, HOLD 6(CU-010·015·016·017·018·020),
# LAWYER_NOTE 5(CU-002·004·005·019·021), wave 단일 2 = 두 stage 2 → prefer=cost. 최대 패킷 79(CU-007) 229,654자, 135(CU-005)
# 204,405자(블록 1을 예산 20,000자로 계산, 합성 본문 기준). 실제 Stage 1 본문은 더 클 수 있어 CU-007이 넘칠 위험이 있다(추정):
# 그때는 아래 한도 처리 ①로 맥락 thread 본문을 빼고(하네스 222,203자), 그래도 넘으면 HOLD다. 실제 크기는 온라인 G1 실행으로 확인한다.
#
# 설계서와 다르게 단순화한 곳(이유)
# 1. 상속 S1~S7 판정을 코드로 하지 않는다. 관계(배우자·자녀)와 포기 수리가 원본에 문장으로만 있어 결정적으로 읽을 수 없다.
# provisional 상속 단위의 CU는 HOLD로 두고 등록부 heirs·renounced로 만든 질문을 낸다. 답은 I10 answers로 받는다.
# 2. 경로 힌트는 후보 경로 전부 + relief_kind만 준다(경로 확정은 T2). 한도 처리 순서: ① 맥락 thread 사실(own=false)의 본문을 빼고
# ref·evidence_index만 남긴다(CU 자신의 ref 본문은 그대로) ② I10 path_hint로 경로가 지정된 CU만 restrict_paths ③ 그래도 넘으면
# CU를 급부 성분 단위로 나누는 대신 HOLD(PACKET_OVERFLOW) 질문을 낸다(T5 재결합 계약을 만들지 않는다).
# 3. 모듈은 발동 목록(REMEDY/{index}, STANDING/SUCCESSION, JOINDER)만 적는다. 규칙 본문은 블록 2 원문에 있다.
# 코드 값은 135 가액배상의 checks(가집행·특례이율 배제) 하나다.
# 4. 블록 1은 세 표 데이터와 "Lnnnn 주석 무시" 안내만 둔다. 과업 규칙·출력 스키마·실무제요 발췌는 G2 T2 프롬프트에 둔다.
# 5. object_class는 CU 종의 구간표 후보로만 정한다(객체별 교집합 생략). 후보 하나면 그 값, EACH_OF면 후보 목록,
# FOLLOWS(급부 대상 클래스를 따름)면 null + OBJECT_CLASS_FOLLOWS_RELIEF, ONE_OF 후보 둘 이상이면 null + OBJECT_CLASS_UNRESOLVED.
# 6. 증거 폐포는 ref 본문의 E-NNN과 포인터가 속한 증거 항목의 evidence_index다.
# 7. 패킷 한도는 설계 §5.2대로 블록 1(예산 20,000자로 계산; 나머지는 T2 정적 프롬프트 몫)+2+3 합계 240,000자로 잰다. 백엔드 한도(agent.py:34 파일당 240,000자, 38행 합계 500,000자)보다
# 보수적이라 두 한도를 모두 지키고, 넘는 경우 HOLD가 더 일찍 생길 뿐이다.
# 8. 묶음 설계(최적정보묶음 v.2)에서 이번에 만들지 않은 칸: 기간(제척기간) 위험의 LAWYER_NOTE 발동, registrations[]·목적물 표시 행,
# 이름 규칙(§10-7), requested_scope_check(§7, 대신 CP에 primary_goal·constraints), coverage{refs_resolved}, handoff 본문과 원본 대조(§10-4).
# 급부 성분의 obligor·recipient·counter_performance와 금액·이율 출처 규칙(§8.3 R1~R5, §8.4), non_parties·원고 자격 상태,
# LES source_bo_ids 풀이(§10-4)도 만들지 않는다. 이번 사건 상태 배정은 이것 없이 설계값과 같다. 해당 판단은 T2가 원문·ref 본문으로 하고
# T3·T7이 검사한다. CU 단위 BLOCKED가 있어도 run은 PREPARED이고 prepare.json counts.BLOCKED와 holds.json에 나온다.
# 10. 패킷 한도 초과로 HOLD가 된 주위적 CU에는 "예비적 CU에 변호사 판단 사항" 규칙이 다시 적용되지 않는다(예비적 판정이 패킷 측정보다 앞선다).
# 9. 같은 급부 성분을 공유하는 PRIMARY·BRANCH 구성원은 relief 행 하나로 합친다(member에 둘 다 적음).
#
# G2 작성 시 지킬 것: T2a·T2b는 같은 명시 llm_prompt_cache_key 하나를 쓴다(자동 키는 task 이름별이라 둘이 갈린다; 항목별 키는 P6 뒤).
# T2 프롬프트 어디에도 {{item.*}}를 넣지 않는다(첫 user 메시지가 접두어 경계다). CU별 값은 전부 블록 3에 있다. T1은 {{prev.Task_S2_20_prepare.status}}가 PREPARED가 아니거나 항목 run_id가 prepare.json run_id와 다르면 빈 목록을 낸다
# (Localdocs 초기화 실패 시 옛 items가 남을 수 있다). T3는 rbidx/2.1.0의 valid_ids·required_rids·stop_ids를 그대로 옮기고
# s2_20/snapshot/index/NNN.json을 읽는다(write_binary_file 사본이라 raw sha가 같다).
# 온라인 probe만 먼저 돌릴 때는 task_procedure를 IN → Task_S2_20_prepare → OUT으로 바꾼 사본을 쓴다.
# 미확인(실행 전 probe): P7 code task가 Default_Agent/Stage_2/rulebook_build/를 read_binary_doc로 읽는가;
# P8 stage1_input_manifest의 path가 stage1_run_root_ref 기준이고 signal ref 접두사가 "signal:<경로>" 행과 맞는가;
# P9 delete_folder가 s2_20 root를 지우는가(S2_10 reset과 같은 호출).
Agent:
name: Stage_2_S2_20_v2
description: "S2_20 v.2(사전 색인 rbidx/2.1.0) — G1 준비(T0 prepare): 스냅샷·색인 적재·coverage 확인·세 층 묶음·상태 판정·항목과 패킷 조립, 종별 선두 CU fan-out을 연다. task_procedure는 G1 → G2(T2a·T3a·T1·T2b·T3b) 연결까지 적는다."
version: 2.0.0-g1
Stages:
- name: S2_20_draft_pleadings
description: S2_10 7.3.3 CU별 청구취지·청구원인 초안과 소장 묶음(CP) 병합. 이 파일은 G1(T0)만 구현한다.
skip_confirm: true
tools:
mcpServers:
localdocs:
type: streamable-http
url: http://mcp-localdocs:8012/mcp
description: workspace-bound documents
code-executor:
type: streamable-http
url: https://code-executor.mcp.eroomai.com/mcp
description: inline Python execution
tasks:
- task_name: Task_S2_20_prepare
description: T0 prepare — 0.1 입력 결속·스냅샷, 0.2″ 색인 적재(sha 대조), 0.3 coverage 확인, 0.4 묶음 3층, 0.5 상태 판정, 0.6 항목·패킷. dynamic_fanout = 종별 선두 CU 항목(items/lead.json).
mcp: code-executor
tool_name: run_code
parameters:
language: python
requirements: httpx
network: agent-network
timeout: 300
code: |
import base64, datetime, hashlib, itertools, json, math, re, unicodedata
import httpx
CFG = {
"output_root": "stage2_runs/from-stage1/s2_20",
"s2_10_root": "stage2_runs/from-stage1/s2_10",
"s2_00_root": "stage2_runs/from-stage1/s2_00/v7_7",
"build_root": "Default_Agent/Stage_2/rulebook_build",
"request_path": "stage2_control/s2_20_request.json",
"values_path": "stage2_control/s2_20_values.json",
"packet_limit": 240000,
"common_budget": 20000,
"concurrency": 14,
"kind_checks": {
"135": {"금전지급": {"가집행": "붙이지 않는다", "특례이율": "적용하지 않는다",
"근거": "요건사실론 사해행위취소 §4.4(판례 2000다3583 UNVERIFIED)"}},
},
}
PARSER_VERSION = "rbidx/2.1.0"
SENDABLE = ("READY", "DRAFT_WITH_PLACEHOLDERS", "DRAFT_WITH_LAWYER_NOTE")
DIRECTIVES = {
"READY": "필요한 값이 갖추어져 있다. 그대로 작성한다.",
"DRAFT_WITH_PLACEHOLDERS": "비는 값은 [NEEDS_INPUT: 항목] 자리표시자로 두고 questions에 올린다. 감정이 필요한 금액은 일부청구로 쓰고 '감정 후 확장'을 적는다.",
"DRAFT_WITH_LAWYER_NOTE": "lawyer_notes의 각 항목을 questions에 '변호사 판단 사항'으로 올린다. 조건부 제외 권고가 있으면 흡수 문안과 독립 유지 문안을 둘 다 쓴다.",
"HOLD": "hold_mode=draft 잠정 초안이다. questions를 앞에 두고 금액·지분은 비워 둔다.",
}
class Localdocs:
def __init__(self):
self.client = httpx.Client(timeout=60)
self.headers = {"Content-Type": "application/json", "Accept": "application/json, text/event-stream"}
self.ids = itertools.count(10)
self.url = "http://mcp-localdocs:8012/mcp"
self.rpc("initialize", {"protocolVersion": "2025-03-26", "capabilities": {}, "clientInfo": {
"name": "s2-20-prepare", "version": "1.0", "user_id": "{{__user_hash__}}", "workspace_id": "{{__workspace_hash__}}"}})
self.rpc("notifications/initialized", {}, notification=True)
def rpc(self, method, params, notification=False):
body = {"jsonrpc": "2.0", "method": method, "params": params}
if not notification:
body["id"] = next(self.ids)
r = self.client.post(self.url, json=body, headers=self.headers)
r.raise_for_status()
if r.headers.get("mcp-session-id"):
self.headers["mcp-session-id"] = r.headers["mcp-session-id"]
if notification:
return {}
text = r.text.strip()
if r.headers.get("content-type", "").startswith("text/event-stream"):
rows = [json.loads(x[6:]) for x in text.splitlines() if x.startswith("data: ")]
rows = [x for x in rows if x.get("id") == body["id"]]
if not rows:
raise RuntimeError("MCP response missing")
data = rows[-1]
else:
data = json.loads(text)
if "error" in data or "result" not in data:
raise RuntimeError("MCP RPC error: " + str(data.get("error", "missing result")))
return data["result"]
def call(self, name, args):
result = self.rpc("tools/call", {"name": name, "arguments": args})
texts = [x["text"] for x in result.get("content", []) if x.get("type") == "text"]
structured = result.get("structuredContent", {})
if not texts and isinstance(structured, dict) and "result" in structured:
value = structured["result"]
texts = [value if isinstance(value, str) else json.dumps(value, ensure_ascii=False)]
message = "\n".join(texts).strip()
if re.match(r"^(?:Error:\s*)?(?:Document|File|Folder) not found:", message, re.I):
raise FileNotFoundError(message)
if result.get("isError") or re.match(r"^Error(?::|\s)", message):
raise RuntimeError("MCP tool error: " + message)
if not texts:
raise RuntimeError("Empty response for " + name)
return message
def binary(self, path):
raw = self.call("read_binary_doc", {"doc_name": unicodedata.normalize("NFC", path)})
try:
data = json.loads(raw)
except json.JSONDecodeError:
data = json.JSONDecoder().raw_decode(raw.strip())[0]
if not isinstance(data, dict) or "content_base64" not in data:
if re.search(r"not found|does not exist|파일.*없", str(data), re.I):
raise FileNotFoundError(path)
raise RuntimeError("Binary envelope invalid: " + path)
return base64.b64decode(data["content_base64"], validate=True)
def binary_optional(self, path):
try:
return self.binary(path)
except FileNotFoundError:
return None
def write(self, path, text):
self.call("write_file", {"path": unicodedata.normalize("NFC", path), "content": text, "overwrite": True})
def write_binary(self, path, raw):
self.call("write_binary_file", {"path": unicodedata.normalize("NFC", path),
"content_base64": base64.b64encode(raw).decode("ascii"), "overwrite": True})
def reset(self, root):
if root != CFG["output_root"]:
raise RuntimeError("OUTPUT_RESET_PATH_INVALID")
try:
message = self.call("delete_folder", {"path": root, "force": True})
if message != "Successfully deleted folder: " + root:
raise RuntimeError("OUTPUT_RESET_UNCONFIRMED: " + message)
except FileNotFoundError:
pass
def close(self):
self.client.close()
class Blocked(Exception):
def __init__(self, code, detail=""):
super().__init__(code + ": " + str(detail))
self.code, self.detail = code, str(detail)
def require(ok, code, detail=""):
if not ok:
raise Blocked(code, detail)
def sha(raw):
return hashlib.sha256(raw).hexdigest()
def pack(x):
return json.dumps(x, ensure_ascii=False, separators=(",", ":"))
def loads(raw):
"""SKILL §12.3: tolerate trailing garbage after the first JSON value"""
text = raw.decode("utf-8") if isinstance(raw, bytes) else raw
try:
return json.loads(text)
except json.JSONDecodeError:
return json.JSONDecoder().raw_decode(text.strip())[0]
def split_target(t):
return [x.strip() for x in str(t).split("|") if x.strip()]
# ---------------- rulebook_index.py rbidx/2.1.0 runtime functions used by T0 (copied; only sha256() is named sha() here) ----------------
def verify(entry, claim_raw, elem_raw):
if entry["parser_version"] != PARSER_VERSION: return "PARSER_VERSION"
if entry["claim"]["sha256"] != sha(claim_raw): return "SHA_CLAIM"
if entry["elements"]["sha256"] != sha(elem_raw): return "SHA_ELEMENTS"
return None
def block2(claim_raw, elem_raw):
"""whole files, verbatim"""
return claim_raw.decode("utf-8"), elem_raw.decode("utf-8")
def restrict_paths(entry, elem_text, keep):
"""packet-overflow rule: drop the per-path sections of the other paths (keep = path id).
An unknown path id changes nothing (the caller then falls back to splitting the CU)."""
sections = entry["elements"]["path_sections"]
if keep not in sections:
return elem_text
spans = sorted(v for k, v in sections.items() if k != keep)
out, cur = [], 0
for s, e in spans:
out.append(elem_text[cur:s]); cur = max(cur, e)
out.append(elem_text[cur:])
return "".join(out)
# ---------------- 0.1 inputs, binding and snapshot ----------------
class Inputs:
"""every byte read is kept for the snapshot (raw sha, never re-serialized)"""
def __init__(self, io):
self.io, self.raw = io, {}
def get(self, path, optional=False):
if path in self.raw:
return self.raw[path]
raw = self.io.binary_optional(path) if optional else self.io.binary(path)
if raw is not None:
self.raw[path] = raw
return raw
def json(self, path, optional=False):
raw = self.get(path, optional)
return None if raw is None else loads(raw)
def load_s2_10(inp, cfg):
root = cfg["s2_10_root"]
status = inp.json(root + "/filter/filter_status.json")
require(str(status.get("status", "")).startswith("FILTER_COMPLETE"), "S2_10_NOT_COMPLETE", status.get("status"))
bound = {a["path"]: a["raw_sha256"] for a in status["artifacts"]}
cir_path = root + "/filter/claim_identity_review.json"
require(sha(inp.get(cir_path)) == bound.get(cir_path), "BIND_MISMATCH", cir_path)
index_path = root + "/claims_index.json"
require(sha(inp.get(index_path)) == status["bound"]["claims_index_sha256"], "BIND_MISMATCH", index_path)
claims = {}
for row in inp.json(index_path)["clusters"]:
require(sha(inp.get(row["path"])) == row["sha256"], "BIND_MISMATCH", row["path"])
claims[row["cluster_id"]] = inp.json(row["path"])
s2_status_path = root + "/s2_10_status.json"
require(sha(inp.get(s2_status_path)) == status["bound"]["s2_10_status_sha256"], "BIND_MISMATCH", s2_status_path)
plan = inp.json(root + "/work/plan.json")
body = json.dumps({k: v for k, v in plan.items() if k != "plan_sha256"}, ensure_ascii=False, sort_keys=True, separators=(",", ":"))
require(sha(body.encode("utf-8")) == plan.get("plan_sha256") == inp.json(s2_status_path).get("plan_sha256"),
"BIND_MISMATCH", root + "/work/plan.json")
sources = {}
for row in plan["clusters"]:
require(sha(inp.get(row["source_path"])) == row["source_sha256"], "BIND_MISMATCH", row["source_path"])
sources[row["cluster_id"]] = inp.json(row["source_path"])["rc"]
for a in plan["artifacts"]:
require(sha(inp.get(a["path"])) == a["raw_sha256"], "BIND_MISMATCH", a["path"])
common = inp.json(plan["common_path"])
return inp.json(cir_path), claims, plan, sources, common
class Stage1:
"""ref = '<logical id or signal path>#<json pointer>' resolved in the Stage 1 original (manifest path + raw sha)"""
def __init__(self, inp, cfg):
self.inp = inp
man = inp.json(cfg["s2_00_root"] + "/ingress/stage1_input_manifest.json")
self.root = man.get("stage1_run_root_ref") or "."
self.rows = [r for r in man["sources"] if r.get("path") and r.get("raw_sha256")]
self.docs = {}
def row(self, prefix):
for r in self.rows:
lid = r["logical_input_id"]
if lid in (prefix, "signal:" + prefix, "signal:" + prefix.split("signals/", 1)[-1]) or r["path"] == prefix:
return r
raise KeyError(prefix)
def doc(self, prefix):
if prefix not in self.docs:
r = self.row(prefix)
path = r["path"] if self.root in (".", "") else self.root.rstrip("/") + "/" + r["path"]
raw = self.inp.get(path)
require(sha(raw) == r["raw_sha256"], "STAGE1_SHA_MISMATCH", path)
self.docs[prefix] = loads(raw)
return self.docs[prefix]
def resolve(self, ref):
prefix, _, pointer = ref.partition("#")
node = self.doc(prefix)
for tok in pointer.split("/")[1:]:
tok = tok.replace("~1", "/").replace("~0", "~")
node = node[int(tok)] if isinstance(node, list) else node[tok]
return node
def evidence_ids(self, ref, body):
"""1-hop closure: E-NNN named in the body, plus the evidence item a pointer sits in"""
ids = set(re.findall(r"\bE-\d{3}\b", pack(body)))
prefix, _, pointer = ref.partition("#")
m = re.match(r"^/items/(\d+)", pointer)
if m and prefix in ("evidence_indexed", "evidence_event_candidates"):
item = self.doc(prefix)["items"][int(m.group(1))]
if isinstance(item, dict) and item.get("evidence_index"):
ids.add(item["evidence_index"])
return sorted(ids)
def evidence_list(stage1):
"""case-level evidence list: short scalar fields of every evidence_indexed item"""
out = []
for i, item in enumerate(stage1.doc("evidence_indexed")["items"]):
row = {"ref": "evidence_indexed#/items/%d" % i}
row.update({k: v for k, v in item.items() if isinstance(v, (str, int, float)) and len(str(v)) <= 200})
out.append(row)
return out
# ---------------- 0.2″ index load, 0.3 coverage ----------------
def load_index(io, inp, cfg, plan, kind_set, review):
b = cfg["build_root"]
man_raw = io.binary(b + "/rulebook_index/manifest.json")
man = loads(man_raw)
require(man["registry_sha256"] == plan["registry_sha256"], "INDEX_REGISTRY_MISMATCH",
"%s vs S2_10 %s" % (man["registry_sha256"], plan["registry_sha256"]))
require(man["parser_version"] == PARSER_VERSION, "INDEX_FORMAT_MISMATCH", man["parser_version"])
tables = {}
for name, want in sorted(man["coverage"]["inputs"]["tables"].items()):
raw = inp.get(b + "/tables/" + name)
require(sha(raw) == want, "TABLES_MISMATCH", name)
tables[name] = loads(raw)
if plan.get("mapping_sha256") != man["coverage"]["inputs"]["mapping_sha256"]:
review.append({"code": "INDEX_COVERAGE_MAPPING_DIFFERS",
"note": "색인 coverage가 다른 S2_10 구제 후보표로 검사됨, 재빌드 권장"})
entries = {e["index"]: e for e in man["entries"]}
kinds, copies = {}, {"manifest.json": man_raw}
for k in sorted(kind_set):
n = "%03d" % k
if k not in entries:
kinds[k] = {"stale": "INDEX_ENTRY_MISSING"}
continue
idx_raw = io.binary_optional(b + "/rulebook_index/" + n + ".json")
claim_raw = io.binary_optional(b + "/rulebooks/claim/" + n + ".md")
elem_raw = io.binary_optional(b + "/rulebooks/elements/" + n + ".md")
if idx_raw is None or claim_raw is None or elem_raw is None:
kinds[k] = {"stale": "INDEX_FILE_MISSING"}
continue
entry = loads(idx_raw)
why = "INDEX_SHA" if sha(idx_raw) != entries[k]["index_sha256"] else verify(entry, claim_raw, elem_raw)
if why:
kinds[k] = {"stale": why}
continue
claim_text, elem_text = block2(claim_raw, elem_raw)
kinds[k] = {"entry": entry, "claim": claim_text, "elements": elem_text}
copies[n + ".json"] = idx_raw
return man, tables, kinds, copies
# ---------------- 0.4 bundles, 0.5 status ----------------
def member_claims(unit, claims):
out = []
for m in unit["members"]:
doc = claims.get(m["cluster_id"]) or {"claims": []}
c = next((c for c in doc["claims"] if c["seq"] == m["seq"]), None)
out.append((m, c))
return out
def relief_rows(cu_id, kind, mclaims, cfg):
rows, seen = [], {}
for m, c in mclaims:
if m["role"] == "ABSORBED":
continue
parts = c.get("relief_components") or [c]
for p in parts:
same = seen.get(pack([p.get("relief_kind"), p.get("relief_detail")]))
if same is not None: # PRIMARY/BRANCH members sharing one component (e.g. the same 취소 row)
same["member"] += ", %s/%s" % (m["cluster_id"], m["seq"])
continue
row = {"relief_row_id": "%s-R%d" % (cu_id, len(rows) + 1), "member": "%s/%s" % (m["cluster_id"], m["seq"]),
"relief_kind": p.get("relief_kind"), "relief_detail": p.get("relief_detail"),
"refs": p.get("key_facts_refs") or []}
checks = cfg["kind_checks"].get(str(kind), {}).get(row["relief_kind"])
if checks:
row["checks"] = checks
rows.append(row)
seen[pack([p.get("relief_kind"), p.get("relief_detail")])] = row
return rows
def object_rows(object_ids, kind, sources, rcs, tables, values):
spans = tables["object_class_spans.json"]["spans"]
span = next((s for s in spans if kind is not None and any(a <= kind <= b for a, b in s["ranges"])), None)
out = []
for oid in object_ids:
src = next((o for rc in rcs for o in sources[rc].get("objects", []) if o["object_id"] == oid), {})
row = {"object_id": oid, "label": src.get("label"), "control": src.get("control"),
"value": (values.get("objects") or {}).get(oid, "NEEDS_INPUT")}
row["object_class"] = None
if span is None or span["rule"] == "NOT_REQUIRED":
pass
elif "FOLLOWS" in span["candidates"]:
row["review"] = "OBJECT_CLASS_FOLLOWS_RELIEF" # the class follows the object of the relief row
elif span["rule"] == "ONE_OF" and len(span["candidates"]) == 1:
row["object_class"] = span["candidates"][0]
elif span["rule"] == "EACH_OF":
row["object_class_candidates"] = span["candidates"]
else:
row["object_class_candidates"], row["review"] = span["candidates"], "OBJECT_CLASS_UNRESOLVED"
out.append(row)
return out
def scoped_threads(rcs, sources, own_refs, object_ids):
"""§10 rule 5: threads sharing an object or a ref with the CU, plus the RC common thread T-00"""
out = []
for rc in rcs:
for t in sources[rc].get("threads", []):
refs = [m["ref"] for m in t.get("materials", [])]
if (t["thread_id"].endswith("/T-00") or t.get("object_id") in object_ids
or set(refs) & own_refs):
out.append({"thread_id": t["thread_id"], "label": t.get("label"), "object_id": t.get("object_id"),
"refs": refs})
return out
def succession_question(unit, registry):
p = next((r for r in registry if r["party_id"] == unit.get("succession_of")), {})
return ("상속 원고 단위 %s(%s)가 잠정(provisional)이다. 망 %s의 상속인 후보 %s, 상속포기 %s에 대해 "
"피상속인과의 관계(배우자·직계비속·직계존속)와 포기 심판 수리 여부를 확인해 상속인 범위와 상속분을 정하라"
"(민법 §1000·§1003·§1043, 2020그42)." % (unit.get("unit_id"), "·".join(unit.get("names", [])),
p.get("name", unit.get("succession_of")),
"·".join(p.get("heirs", [])) or "미상", "·".join(p.get("renounced", [])) or "없음"))
def build_cu(unit, ctx):
claims, sources, cir, stage1, kinds, tables, cfg = (ctx[k] for k in ("claims", "sources", "cir", "stage1", "kinds", "tables", "cfg"))
cu_id = unit["identity_id"]
mclaims = member_claims(unit, claims)
keys = ["%s/%s" % (m["cluster_id"], m["seq"]) for m, _ in mclaims]
hold, lawyer, placeholders, review, blocked = [], [], [], [], []
rcs = sorted({m["cluster_id"] for m, _ in mclaims})
primary = next((c for m, c in mclaims if m["role"] == "PRIMARY"), mclaims[0][1])
kind = primary["case_kind_index"]
if len({c["case_kind_index"] for _, c in mclaims}) > 1:
review.append({"code": "MEMBER_KIND_DIFFERS", "note": "구성원의 사건 종류가 다르다; PRIMARY의 종을 쓴다"})
flags = [f for f in cir["legality_flags"] if set(split_target(f["target"])) & set(keys)]
holds = [h for h in cir["holds"] if set(h["cand_refs"]) & set(keys)]
sg = [g for g in cir["satisfaction_groups"] if set(g["members"]) & set(keys)]
crg = [g for g in cir["cross_rc_groups"] if set(g["members"]) & set(keys)]
ancillary = [a for a in cir["ancillary_claims"] if a["attached_to"] in keys]
# status reasons (v.2 §8.7 as mapped in the S2_20 design §4 T0 0.5)
if unit["decision"] == "HOLD":
hold.append({"code": "CU_DECISION_HOLD", "detail": unit.get("reason")})
for h in holds:
hold.append({"code": "S2_10_HOLD", "detail": h["question"]})
for m, c in mclaims:
if c.get("standing") == "DOUBTFUL":
hold.append({"code": "STANDING_DOUBTFUL", "detail": "%s/%s 당사자 적격 DOUBTFUL: %s" % (m["cluster_id"], m["seq"], c.get("standing_note"))})
units = [sources[rc]["pair"].get("unit") or {} for rc in rcs]
for u in units:
if u.get("succession_of") and u.get("provisional"):
hold.append({"code": "SUCCESSION_UNRESOLVED", "detail": succession_question(u, ctx["common"]["party_registry"])})
if kind is not None and kinds[kind].get("stale"):
hold.append({"code": "INDEX_STALE", "detail": "규칙문서 색인이 정리본과 맞지 않음(%s), 재빌드 뒤 재실행" % kinds[kind]["stale"]})
unconditional = [f for f in flags if f["code"] == "EXCLUDE_RECOMMENDED" and f.get("conditional") is False]
for f in flags:
if f["code"] == "EXCLUDE_RECOMMENDED" and f.get("conditional") is not False:
lawyer.append("조건부 제외 권고(%s): %s" % (f.get("reason"), f.get("condition")))
if f["code"] == "CONFIRMATION_EXCEPTION":
lawyer.append("확인의 이익 예외 주장: %s" % f.get("condition"))
if kind is None:
lawyer.append("사건 종류 미정(REGISTRY_GAP): 규칙문서 없이 급부 클래스 불변식만 적용한다")
if any(m["role"] == "BRANCH" for m, _ in mclaims):
lawyer.append("구제 방법 분기: %s" % " / ".join(unit.get("relief_method_order") or
["%s/%s %s" % (m["cluster_id"], m["seq"], m["role"]) for m, _ in mclaims]))
rows = relief_rows(cu_id, kind, mclaims, cfg)
for r in rows:
d = r["relief_detail"]
if d and (d.get("act") is None or d.get("target") is None):
placeholders.append("%s relief_detail act·target 빈 값" % r["relief_row_id"])
for m, c in mclaims:
codes = [x for x in c.get("relief_review_codes") or [] if x in ("RELIEF_DETAIL_MISSING", "RELIEF_KIND_UNRESOLVED")]
if codes:
placeholders.append("%s/%s %s" % (m["cluster_id"], m["seq"], ",".join(codes)))
for a in ancillary:
if a.get("rate_basis") is None or a.get("from") is None:
placeholders.append("부대청구(%s) 이율·기산일 미정" % a["kind"])
answer = (ctx["request"].get("answers") or {}).get(cu_id)
if answer:
hold = [h for h in hold if h["code"] == "INDEX_STALE"]
lawyer.append("변호사 답변 반영: %s" % answer)
if kind is not None and not kinds[kind].get("stale"):
for flag in kinds[kind]["entry"]["elements"]["flags"]:
if flag in ("REC_CROSS_KIND", "REC_RESTORE_BLOCKED"):
review.append({"code": flag, "note": "요건사실론 정리 기록 플래그; 전송하되 변호사 검토"})
# facts: S2_10 refs of the CU + materials of the scoped threads, bodies from the Stage 1 originals
own = []
for r in rows:
own += r["refs"]
for _, c in mclaims:
own += c.get("key_facts_refs") or []
own = sorted(set(own))
object_ids = sorted({o for _, c in mclaims for o in c.get("object_ids") or []})
threads = scoped_threads(rcs, sources, set(own), set(object_ids))
facts, evidence_ids = [], set()
for ref in sorted(set(own) | {r for t in threads for r in t["refs"]}):
try:
body = stage1.resolve(ref)
except (KeyError, IndexError, ValueError, TypeError) as exc:
blocked.append({"code": "REF_UNRESOLVED", "detail": "%s (%s)" % (ref, type(exc).__name__)})
continue
ev = stage1.evidence_ids(ref, body)
evidence_ids.update(ev)
facts.append({"ref": ref, "own": ref in own, "evidence_index": ev, "body": body})
evidence_rows = [e for e in ctx["evidence"] if e.get("evidence_index") in evidence_ids]
if blocked:
status = "BLOCKED"
elif unconditional:
status = "EXCLUDE_RECOMMENDED"
elif hold:
status = "HOLD"
elif lawyer:
status = "DRAFT_WITH_LAWYER_NOTE"
elif placeholders:
status = "DRAFT_WITH_PLACEHOLDERS"
else:
status = "READY"
entry = kinds[kind]["entry"] if kind is not None and not kinds[kind].get("stale") else None
ics = {ic for rc in rcs for ic in sources[rc].get("declared_ics") or []}
bundle = {
"cu_id": cu_id, "decision": unit["decision"], "confidence": unit.get("confidence"),
"restructure_kind": unit.get("restructure_kind"), "relief_method_order": unit.get("relief_method_order"),
"open_flags": unit.get("open_flags") or [],
"members": [{"key": k, "role": m["role"], "sentence": c["sentence"], "join": c.get("join"), "alt_of": c.get("alt_of"),
"standing": c.get("standing"), "standing_note": c.get("standing_note")} for k, (m, c) in zip(keys, mclaims)],
"parties": {rc: {"plaintiffs": claims[rc]["pair"]["plaintiffs"], "defendant": claims[rc]["pair"]["defendant"],
"unit": sources[rc]["pair"].get("unit")} for rc in rcs},
"case_kind": {"index": kind, "name": primary.get("case_kind"),
"rulebooks": None if entry is None else {"claim": entry["claim"]["file"], "claim_sha256": entry["claim"]["sha256"],
"elements": entry["elements"]["file"], "elements_sha256": entry["elements"]["sha256"]}},
"modules": ([] if kind is None else ["REMEDY/%d" % kind])
+ (["STANDING/SUCCESSION"] if any(u.get("succession_of") for u in units) else [])
+ (["JOINDER"] if len(rows) > 1 or sg or crg or any(c.get("alt_of") for _, c in mclaims) else []),
"relief": rows,
"ancillary": ancillary,
"objects": object_rows(object_ids, kind, sources, rcs, tables, ctx["values"]),
"path_hint": {"relief_kinds": sorted({r["relief_kind"] for r in rows if r["relief_kind"]}),
"candidates": [] if entry is None else [p["id"] for p in entry["elements"]["paths"]],
"lawyer_path": (ctx["request"].get("path_hint") or {}).get(cu_id)},
"elements_rows": [] if entry is None else [{"r_id": r["id"], "class": r["class"], "paths": r["paths"],
"paths_qualified": r["paths_qualified"]} for r in entry["elements"]["r_rows"]],
"stop_ids": [] if entry is None else list(entry["claim"]["ids"]["STOP"]),
"relations": {"relation_labels": unit.get("relation_labels") or [], "satisfaction_groups": sg, "cross_rc_groups": crg},
"legality_flags": flags,
"s2_10_holds": holds,
"defense_hints": [h for rc in rcs for ic in sources[rc].get("issue_clusters", []) if ic.get("cluster_id") in ics
for h in (ic.get("defense_hints") or []) + (ic.get("legal_sustainability_watchpoints") or [])],
"issues": [dict(i, rc=rc) for rc in rcs for i in claims[rc].get("issues") or []],
"threads": threads,
"facts": facts,
"evidence_refs": evidence_rows,
"allowed_refs": sorted({f["ref"] for f in facts} | {e["ref"] for e in evidence_rows}),
"review": review,
}
kana = sorted(set(re.findall(r"[\u3040-\u30fa\u30fc-\u30ff]+", pack(bundle))))
if kana: # S2_10 7.3.3 known contamination; the draft must not copy it (T3 V7)
review.append({"code": "NON_KOREAN_TEXT", "note": "상류 문면에 가나 문자: " + ", ".join(kana[:10])})
reasons = {"hold": hold, "lawyer": lawyer, "placeholders": placeholders, "blocked": blocked}
return bundle, status, reasons
def group_complaints(units, claims, cir, request):
"""CP candidates: connected RCs (same CU, shared object, SG/CRG/relation label); I10 cp_split wins"""
parent = {}
def find(x):
parent.setdefault(x, x)
while parent[x] != x:
x = parent[x]
return x
def union(a, b):
parent[find(a)] = find(b)
rc_of = {}
for u in units:
rcs = [m["cluster_id"] for m in u["members"]]
rc_of[u["identity_id"]] = rcs[0]
for rc in rcs:
union(rc, rcs[0])
for lab in u.get("relation_labels") or []:
union(rcs[0], lab["with"].split("/")[0])
for g in cir["satisfaction_groups"] + cir["cross_rc_groups"]:
rcs = [m.split("/")[0] for m in g["members"]]
for rc in rcs:
union(rc, rcs[0])
by_object = {}
for rc, doc in claims.items():
find(rc)
for c in doc["claims"]:
for o in c.get("object_ids") or []:
by_object.setdefault(o, rc)
union(rc, by_object[o])
groups = {}
for u in units:
groups.setdefault(find(rc_of[u["identity_id"]]), []).append(u["identity_id"])
lists = [sorted(g) for g in groups.values()]
split = request.get("cp_split")
if split:
fixed = [sorted(g) for g in split]
named = [c for g in fixed for c in g]
require(len(named) == len(set(named)) and set(named) <= set(rc_of), "CP_SPLIT_INVALID", named)
taken = {c for g in fixed for c in g}
lists = fixed + [g for g in ([c for c in g if c not in taken] for g in lists) if g]
return {"CP-%02d" % (i + 1): g for i, g in enumerate(sorted(lists))}
def build_cp(cp_id, cus, bundles, statuses, common, values):
rcs = sorted({k.split("/")[0] for c in cus for k in (m["key"] for m in bundles[c]["members"])})
plaintiffs, defendants = {}, {}
for c in cus:
for rc, p in bundles[c]["parties"].items():
for x in p["plaintiffs"]:
plaintiffs.setdefault(x["party_id"], x)
defendants.setdefault(p["defendant"]["party_id"], p["defendant"])
names = [bundles[c]["case_kind"]["name"] for c in cus if bundles[c]["case_kind"]["name"]]
first = names[0]["사건 종류"] if names else None
return {
"cp_id": cp_id, "status": "CANDIDATE", "cus": [{"cu_id": c, "status": statuses[c]} for c in cus], "rcs": rcs,
"plaintiffs": list(plaintiffs.values()), "defendants": list(defendants.values()),
"case_name_candidate": None if first is None else first + (" 등" if len({n["사건 종류"] for n in names}) > 1 else ""),
"joinder_candidates": [{"cu_id": c, "relations": bundles[c]["relations"],
"alt_of": [m for m in bundles[c]["members"] if m["alt_of"] is not None]} for c in cus],
"court_inputs": {"objects": sorted({o["object_id"] for c in cus for o in bundles[c]["objects"]}),
"values": values or "NEEDS_INPUT"},
"primary_goal": common.get("primary_goal"),
"constraints": common.get("constraints"),
}
# ---------------- 0.6 packets and items ----------------
def common_block(tables):
text = ("# S2_20 공통 블록(블록 1)\n정리본의 `<!-- Lnnnn -->` 주석은 제작 좌표이므로 무시한다.\n\n"
+ "".join("## %s\n%s\n\n" % (n, pack(t)) for n, t in sorted(tables.items())))
return text
def kind_block(k, kd, elements_text=None):
e = kd["entry"]
return ("# 블록 2 — 사건 종류 index %d %s\n\n## 청구취지작성규칙 정리본 %s\n\n%s\n\n## 요건사실론 정리본 %s\n\n%s\n"
% (k, e["case_kind"], e["claim"]["file"], kd["claim"], e["elements"]["file"],
kd["elements"] if elements_text is None else elements_text))
def prepare(io, cfg):
out = cfg["output_root"]
io.reset(out)
run = {"run_id": "s2_20-" + datetime.datetime.now(datetime.timezone.utc).strftime("%Y%m%dT%H%M%SZ"),
"date": datetime.date.today().isoformat()}
inp, review = Inputs(io), []
request = inp.json(cfg["request_path"], optional=True) or {}
values = inp.json(cfg["values_path"], optional=True) or {}
cir, claims, plan, sources, common = load_s2_10(inp, cfg)
stage1 = Stage1(inp, cfg)
units = cir["identity_units"]
missing = [u["identity_id"] for u in units if any(c is None for _, c in member_claims(u, claims))]
require(not missing, "MEMBER_CLAIM_MISSING", missing)
kind_set = {c["case_kind_index"] for u in units for _, c in member_claims(u, claims)
if c["case_kind_index"] is not None}
man, tables, kinds, index_copies = load_index(io, inp, cfg, plan, kind_set, review)
ctx = {"claims": claims, "sources": sources, "cir": cir, "stage1": stage1, "kinds": kinds, "tables": tables,
"cfg": cfg, "common": common, "request": request, "values": values, "evidence": evidence_list(stage1)}
bundles, statuses, reasons = {}, {}, {}
for u in units:
bundles[u["identity_id"]], statuses[u["identity_id"]], reasons[u["identity_id"]] = build_cu(u, ctx)
# predecessor HOLD: the preliminary CU stays sendable with a lawyer note (never pulled down to HOLD)
cu_of = {m["key"]: c for c, b in bundles.items() for m in b.get("members", [])}
for c, b in bundles.items():
for m in b.get("members", []):
if m.get("alt_of") is not None:
main = cu_of.get(m["key"].split("/")[0] + "/" + str(m["alt_of"]))
if main and statuses[main] == "HOLD" and statuses[c] in SENDABLE:
reasons[c]["lawyer"].append("주위적 청구(%s) HOLD: 예비적 청구를 단독 청구로 유지할지" % main)
statuses[c] = "DRAFT_WITH_LAWYER_NOTE"
cps = group_complaints(units, claims, cir, request)
cp_of = {c: cp for cp, cus in cps.items() for c in cus}
hold_mode = request.get("hold_mode", "questions")
# hold_mode=draft sends HOLD CUs as provisional drafts, except a HOLD caused by a stale index (no rulebook to send)
send = [c for c in sorted(bundles) if statuses[c] in SENDABLE or (
hold_mode == "draft" and statuses[c] == "HOLD" and all(h["code"] != "INDEX_STALE" for h in reasons[c]["hold"]))]
# packets: 1_common.md, 2_kind/NNN.md, 3_cu/CU-NNN.json (= the CU bundle); names sort in block order.
# Block 1 is counted at its full budget because G2's T2 static prompt carries the rest of the design's block 1.
common_text = common_block(tables)
require(len(common_text) <= cfg["common_budget"], "COMMON_BLOCK_OVER_BUDGET", len(common_text))
io.write(out + "/packet/1_common.md", common_text)
b1_len = cfg["common_budget"]
kind_text = {None: "# 블록 2 — 규칙문서 없음\n사건 종류 미정(REGISTRY_GAP). 공통 블록의 급부 클래스 불변식만 적용하고 다른 종의 규칙문서를 쓰지 않는다.\n"}
io.write(out + "/packet/2_kind/none.md", kind_text[None])
for k in sorted(kind_set):
if not kinds[k].get("stale") and any(bundles[c]["case_kind"]["index"] == k for c in send):
kind_text[k] = kind_block(k, kinds[k])
io.write(out + "/packet/2_kind/%03d.md" % k, kind_text[k])
items = []
for c in send:
b = bundles[c]
k = b["case_kind"]["index"]
b["cp"] = {"cp_id": cp_of[c], "cus": cps[cp_of[c]],
"defendants": sorted({bundles[x]["parties"][rc]["defendant"]["name"] for x in cps[cp_of[c]] for rc in bundles[x].get("parties", {})})}
b2_path = out + ("/packet/2_kind/none.md" if k is None else "/packet/2_kind/%03d.md" % k)
b2_len = len(kind_text[k])
shared = True
b["drafting_status"] = statuses[c]
b["instructions"] = DIRECTIVES[statuses[c]]
b["lawyer_notes"] = reasons[c]["lawyer"]
b["placeholders"] = reasons[c]["placeholders"]
b["hold_questions"] = [h["detail"] for h in reasons[c]["hold"]] if statuses[c] == "HOLD" else []
b["run"] = run
b3_text = pack(b)
total = b1_len + b2_len + len(b3_text)
if total > cfg["packet_limit"]:
# overflow ①: keep context-thread facts as ref + evidence_index only (the CU's own ref bodies stay)
for f in b["facts"]:
if not f["own"]:
f["body"], f["body_dropped"] = None, True
b3_text = pack(b)
total = b1_len + b2_len + len(b3_text)
if total > cfg["packet_limit"] and k is not None:
# overflow ②: lawyer-given path → drop the other per-path sections (this CU no longer shares the kind prefix)
keep = b["path_hint"]["lawyer_path"]
if keep in kinds[k]["entry"]["elements"]["path_sections"]:
text = kind_block(k, kinds[k], restrict_paths(kinds[k]["entry"], kinds[k]["elements"], keep))
b2_path, b2_len, shared = out + "/packet/2_kind/%03d-%s.md" % (k, c), len(text), False
io.write(b2_path, text)
total = b1_len + b2_len + len(b3_text)
if total > cfg["packet_limit"]:
statuses[c] = b["drafting_status"] = "HOLD"
reasons[c]["hold"].append({"code": "PACKET_OVERFLOW",
"detail": "패킷 %d자가 한도 %d자를 넘는다. 요건사실론 경로를 지정하면(path_hint) 다른 경로 절을 빼고 보낸다" % (total, cfg["packet_limit"])})
b["instructions"] = None
b["hold_questions"] = [h["detail"] for h in reasons[c]["hold"]]
continue
items.append({"run_id": run["run_id"], "cu_id": c, "cp_id": cp_of[c], "case_kind_index": k, "status": statuses[c],
"block2_path": b2_path, "block3_path": out + "/packet/3_cu/%s.json" % c,
"cache_key": "s2_20:draft:%s" % ("none" if k is None else "%03d" % k), "cache_shared": shared,
"packet_chars": {"block1": len(common_text), "block1_budget": b1_len, "block2": b2_len,
"block3": len(b3_text), "total": total}})
sent = {i["cu_id"] for i in items}
for c in sorted(bundles):
b = bundles[c]
if "run" not in b:
b["drafting_status"] = statuses[c]
b["hold_questions"] = [h["detail"] for h in reasons[c]["hold"] + reasons[c]["blocked"]]
b["run"] = run
io.write(out + "/bundle/claims/%s.json" % c, pack(b))
if c in sent:
io.write(out + "/packet/3_cu/%s.json" % c, pack(b))
# lead/rest split (§4 T0 0.6) and prefer=cost|speed by wave count
items.sort(key=lambda x: (x["case_kind_index"] is None, x["case_kind_index"] or 0, x["cp_id"], x["cu_id"]))
seen, lead, rest = set(), [], []
for it in items:
k = it["case_kind_index"]
if k is not None and it["cache_shared"] and k not in seen:
seen.add(k)
lead.append(it)
else:
rest.append(it)
n, l, conc = len(items), len(lead), cfg["concurrency"]
one, two = math.ceil(n / conc), math.ceil(l / conc) + math.ceil((n - l) / conc)
prefer = request.get("prefer") or ("speed" if two > one else "cost")
if prefer == "speed":
lead, rest = items, []
for cp, cus in cps.items():
io.write(out + "/bundle/complaints/%s.json" % cp, pack(build_cp(cp, cus, bundles, statuses, common, values)))
case_bundle = {
"run": run, "parties": common.get("party_registry"), "plaintiff_capacity_matrix": common.get("plaintiff_capacity_matrix"),
"units": common.get("units"), "standing_watchpoints": common.get("standing_watchpoints"),
"objects": common.get("object_registry"), "constraints": common.get("constraints"), "primary_goal": common.get("primary_goal"),
"cu_index": [{"cu_id": u["identity_id"], "members": ["%s/%s" % (m["cluster_id"], m["seq"]) for m in u["members"]],
"status": statuses[u["identity_id"]], "cp_id": cp_of[u["identity_id"]]} for u in units],
"relations": {"satisfaction_groups": cir["satisfaction_groups"], "cross_rc_groups": cir["cross_rc_groups"]},
"ancillary_claims": cir["ancillary_claims"], "evidence": ctx["evidence"],
"complaints": cps,
}
io.write(out + "/bundle/case_bundle.json", pack(case_bundle))
holds = {"run": run, "review": review,
"items": [{"cu_id": c, "status": statuses[c], "reasons": reasons[c]["hold"] + reasons[c]["blocked"],
"exclude_flags": [f for f in bundles[c]["legality_flags"] if f["code"] == "EXCLUDE_RECOMMENDED"]}
for c in sorted(bundles) if c not in sent]}
io.write(out + "/review/holds.json", pack(holds))
io.write(out + "/items/lead.json", pack(lead))
io.write(out + "/items/rest.json", pack(rest))
snapshot = []
for path, raw in sorted(inp.raw.items()):
io.write_binary(out + "/snapshot/" + path, raw)
snapshot.append({"path": path, "raw_sha256": sha(raw), "byte_length": len(raw)})
for name, raw in sorted(index_copies.items()):
io.write_binary(out + "/snapshot/index/" + name, raw)
snapshot.append({"path": out + "/snapshot/index/" + name, "raw_sha256": sha(raw), "byte_length": len(raw)})
io.write(out + "/snapshot/snapshot_manifest.json", pack({"run": run, "files": snapshot}))
counts = {}
for c in statuses.values():
counts[c] = counts.get(c, 0) + 1
result = {"status": "PREPARED", "run": run, "prefer": prefer, "hold_mode": hold_mode,
"counts": counts, "sent": n, "kinds": l,
"waves": {"single_stage": one, "two_stage": two}, "complaints": cps, "review": review,
"lead": [i["cu_id"] for i in lead], "rest": [i["cu_id"] for i in rest]}
io.write(out + "/prepare.json", pack(result))
result["dynamic_fanout"] = lead
return result
def failure(io, cfg, exc):
result = {"status": "BLOCKED", "dynamic_fanout": [],
"error": {"code": getattr(exc, "code", "S2_20_PREPARE_FAILED"), "detail": getattr(exc, "detail", str(exc))[:1000]}}
try:
out = cfg["output_root"]
io.write(out + "/items/lead.json", "[]")
io.write(out + "/items/rest.json", "[]")
io.write(out + "/prepare.json", pack(result))
except Exception as log_exc:
result["diagnostic"] = str(log_exc)[:300]
return result
# ---- main ----
io = None
try:
io = Localdocs()
result = prepare(io, CFG)
except Exception as exc:
result = failure(io, CFG, exc)
finally:
if io is not None:
io.close()
print(json.dumps(result, ensure_ascii=False))
# ---- G2 task 자리(다음 단계에서 작성) ----
# Task_S2_20_draft_lead_* T2a LLM fan-out. preflight_files: [stage2_runs/from-stage1/s2_20/packet/1_common.md, "{{item.block2_path}}", "{{item.block3_path}}"]
# Task_S2_20_verify_lead_* T3a 코드 체인(V1~V9) → s2_20/verify/CU-NNN.json
# Task_S2_20_load_rest T1 코드 정적 로더: items/rest.json → dynamic_fanout
# Task_S2_20_draft_rest_* T2b LLM fan-out(T2a와 같은 프롬프트·같은 preflight)
# Task_S2_20_verify_rest_* T3b 코드 체인
task_procedure:
IN:
nexts:
- Task_S2_20_prepare
wait_until: []
Task_S2_20_prepare:
nexts:
- Task_S2_20_draft_lead_*
- Task_S2_20_verify_lead_*
- Task_S2_20_load_rest
wait_until:
- IN
Task_S2_20_draft_lead_*:
nexts:
- Task_S2_20_verify_lead_{same_ordinal}
wait_until:
- Task_S2_20_prepare
Task_S2_20_verify_lead_*:
nexts:
- Task_S2_20_load_rest
wait_until:
- Task_S2_20_draft_lead_{same_ordinal}
Task_S2_20_load_rest:
nexts:
- Task_S2_20_draft_rest_*
- Task_S2_20_verify_rest_*
- OUT
wait_until:
- all Task_S2_20_verify_lead_*
- Task_S2_20_prepare
Task_S2_20_draft_rest_*:
nexts:
- Task_S2_20_verify_rest_{same_ordinal}
wait_until:
- Task_S2_20_load_rest
Task_S2_20_verify_rest_*:
nexts:
- OUT
wait_until:
- Task_S2_20_draft_rest_{same_ordinal}
OUT:
nexts: []
wait_until:
- all Task_S2_20_verify_rest_*
- Task_S2_20_load_rest

Some files were not shown because too many files have changed in this diff Show More