Extract code blocks from peer CLI output and write them to disk. Primary pattern — filename header before a code block: **`app.py`** — description **app.py** `app.py`: ```python code... ``` Fallback pattern — bare triple-backtick block with no fil
(peer_output, context_message="")
| 529 | |
| 530 | |
| 531 | def _auto_apply_peer_code(peer_output, context_message=""): |
| 532 | """ |
| 533 | Extract code blocks from peer CLI output and write them to disk. |
| 534 | |
| 535 | Primary pattern — filename header before a code block: |
| 536 | **`app.py`** — description **app.py** `app.py`: |
| 537 | ```python |
| 538 | code... |
| 539 | ``` |
| 540 | |
| 541 | Fallback pattern — bare triple-backtick block with no filename header. |
| 542 | When no filename is found in the block, the expected filename is inferred |
| 543 | from `context_message` (the original user request). Only the first |
| 544 | qualifying bare block is used to avoid writing ambiguous files. |
| 545 | |
| 546 | Returns list of filenames written, or empty list if none found. |
| 547 | """ |
| 548 | import os |
| 549 | files_written = [] |
| 550 | _CODE_EXTS = ('.py', '.js', '.ts', '.html', '.css', '.json') |
| 551 | |
| 552 | def _safe_write(fname, code): |
| 553 | """Syntax-check (Python only), then write via safety layer.""" |
| 554 | if fname.endswith('.py'): |
| 555 | try: |
| 556 | from core.linter import check_syntax |
| 557 | if check_syntax(code.rstrip(), fname): |
| 558 | return False # syntax error — skip |
| 559 | except Exception: |
| 560 | pass |
| 561 | fpath = os.path.join(os.getcwd(), fname) |
| 562 | result = tool_write_file(fpath, code.rstrip() + '\n') |
| 563 | if result.startswith("[ERROR]") or result.startswith("[CANCELLED]"): |
| 564 | warning(f"Failed to write {fname} from peer: {result}") |
| 565 | return False |
| 566 | files_written.append(fname) |
| 567 | success(f"Written {fname} from peer review ({len(code)} chars)") |
| 568 | return True |
| 569 | |
| 570 | # ── Primary: filename header immediately before a fenced code block ────── |
| 571 | _block_re = re.compile( |
| 572 | r'(?:\*{1,2}`?(\w[\w.\-]*\.\w+)`?\*{0,2}|`(\w[\w.\-]*\.\w+)`:?)' |
| 573 | r'\s*(?:—[^\n]*)?\s*\n' |
| 574 | r'```(?:\w+)?\n(.*?)```', |
| 575 | re.DOTALL, |
| 576 | ) |
| 577 | for m in _block_re.finditer(peer_output): |
| 578 | fname = m.group(1) or m.group(2) |
| 579 | code = m.group(3) |
| 580 | if not fname or not code or len(code.strip()) < 50: |
| 581 | continue |
| 582 | if not any(fname.endswith(ext) for ext in _CODE_EXTS): |
| 583 | continue |
| 584 | _safe_write(fname, code) |
| 585 | |
| 586 | # ── Fallback: bare fenced blocks — infer filename from context ──────────── |
| 587 | # Only runs when the primary pass wrote nothing. |
| 588 | if not files_written: |
no test coverage detected