"""The existing whole-page workflow's prompt and selection I/O. This module never generates images or judges artistic quality. It prepares the exact built-in image-tool arguments and preserves explicit agent observations. """ from pathlib import Path from datetime import datetime, timezone import argparse import hashlib import json import re import shutil import sys WORKSPACE = Path(__file__).resolve().parents[1] TEMPLATE = WORKSPACE / 'docs/manga-page-prompt-template.txt' LOCAL_TEMPLATE = WORKSPACE / 'docs/manga-local-repair-prompt-template.txt' RULES = WORKSPACE / 'docs/manga-expression-rules.md' ASPECTS = ('manuscriptRules', 'pageLayout', 'compositionAnatomy', 'sourceVoiceDesign') MARKER = '{{PAGE_CONTENT}}' READ_FIELDS = ('actualPageRead', 'actualVoiceOrder', 'pageLayout', 'compositionAnatomy', 'imageFindings') IMAGE_BINDING_FIELDS = ('candidate', 'imageSha256') DESIGN_CHECKS = ('headProportions', 'face', 'physique') ATTEMPT_PHASES = ('initial', 'layoutChanged', 'correction') ATTEMPT_OUTCOMES = ('image', 'noImage', 'technicalFailure') WITH_REMAINING = 'withRemainingCorrections' PRIORITY_FIELDS = ('criticalIntegrity', 'stagingAndFinish', 'localManuscript', 'minorDifferences') def output_path(root, name, call): return (Path(root) / 'local-repairs' / name / 'raw-output.png' if call.get('generationMode') == 'croppedLocalEdit' else Path(root) / 'candidates' / f'{name}.png') def digest(path): return hashlib.sha256(Path(path).read_bytes()).hexdigest() def read_json(path): return json.loads(Path(path).read_text(encoding='utf-8-sig')) def save_new(path, value): path = Path(path) path.parent.mkdir(parents=True, exist_ok=True) with path.open('x', encoding='utf-8') as stream: json.dump(value, stream, ensure_ascii=False, indent=2) stream.write('\n') def candidate_paths(root, name): if not re.fullmatch(r'P\d{2,3}-v[1-9]\d*', name): raise ValueError('Candidate must be P01-v1 (or a three-digit page).') root = Path(root).resolve() return root, root / 'records' / f'{name}-call.json', root / 'candidates' / f'{name}.png' def page_number(name): if not re.fullmatch(r'P\d{2,3}(?:-v[1-9]\d*)?', name): raise ValueError('Page must be P01 or a candidate such as P01-v1.') return int(name.split('-')[0][1:]) def timestamp(value): parsed = datetime.fromisoformat(value) if parsed.tzinfo is None: raise ValueError('Actual call times must include a timezone.') return parsed def value_digest(value): return hashlib.sha256(json.dumps(value, ensure_ascii=False, sort_keys=True).encode('utf-8')).hexdigest() def attempt_state(root, page, additional=None): """Reconstruct page budgets from call outcomes, never from version numbers. Archived legacy images are real calls even without the new result record. Legacy failure files must be explicitly imported; prepared prompts alone are not evidence that the image tool was called. """ root = Path(root).resolve() number = page_number(page) events, candidates, unrecorded, unavailable, crop_materials = [], [], [], [], [] for path in (root / 'records').glob('P*-call.json'): name = path.name.removesuffix('-call.json') if page_number(name) != number: continue call = read_json(path) if call.get('candidate') != name: raise ValueError('Call/candidate mismatch in attempt history.') result_path = root / 'records' / f'{name}-attempt.json' result = (additional if additional and additional['candidate'] == name else read_json(result_path) if result_path.is_file() else None) image_path = output_path(root, name, call) generated = call.get('status') == 'generated' if generated: if not image_path.is_file() or digest(image_path) != call.get('sha256'): unavailable.append({'candidate': name, 'image': str(image_path), 'imageSha256': call['sha256'], 'reason': 'missing' if not image_path.is_file() else 'hashMismatch'}) else: row = {'candidate': name, 'image': str(image_path), 'imageSha256': call['sha256']} (crop_materials if call.get('generationMode') == 'croppedLocalEdit' else candidates).append(row) if call.get('recordKind') == 'composition': if result: raise ValueError('A composite is not an image-tool call; do not count it as an attempt.') continue if result: if result.get('candidate') != name or result.get('outcome') not in ATTEMPT_OUTCOMES: raise ValueError('Invalid attempt result/candidate.') if result.get('phase') not in ATTEMPT_PHASES: raise ValueError('Invalid attempt phase.') if (result['outcome'] == 'image') != generated: raise ValueError('Attempt image outcome differs from the archived call.') if not generated and image_path.exists(): raise ValueError('An existing image cannot be recorded as a no-image result; verify and recover the call.') if generated and result.get('imageSha256') != call['sha256']: raise ValueError('Attempt result identifies a different image.') event = {k: result[k] for k in ('candidate', 'callId', 'outcome', 'phase', 'startedAtUtc', 'endedAtUtc')} event['resultSha256'] = value_digest(result) elif generated: when = call.get('startedAtUtc') or call['archivedAtUtc'] event = {'candidate': name, 'callId': name, 'outcome': 'image', 'phase': None, 'startedAtUtc': when, 'endedAtUtc': call.get('endedAtUtc') or call['archivedAtUtc']} else: if (call.get('status') != 'prepared' or (root / 'records' / f'{name}-generation-failure.json').is_file() or image_path.exists()): unrecorded.append(name) continue event['callSha256'] = digest(path) events.append(event) events.sort(key=lambda e: (timestamp(e['startedAtUtc']), timestamp(e['endedAtUtc']), e['candidate'])) counts = dict.fromkeys(ATTEMPT_PHASES, 0) has_image = False ids = set() for event in events: if event['callId'] in ids: raise ValueError('The same actual call was recorded more than once.') ids.add(event['callId']) expected = 'correction' if has_image else 'layoutChanged' if counts['initial'] >= 10 else 'initial' if event['phase'] is not None and event['phase'] != expected: raise ValueError('Attempt phase disagrees with the actual page history; do not reset the budget.') event['phase'] = expected if event['outcome'] != 'technicalFailure': counts[expected] += 1 if event['outcome'] == 'image': has_image = True next_phase = 'correction' if has_image else 'layoutChanged' if counts['initial'] >= 10 else 'initial' reached = counts[next_phase] >= 10 # An output awaiting archive/recovery is not proof that no image exists. page_images = [p for p in (root / 'candidates').glob('P*-v*.png') if re.fullmatch(r'P\d{2,3}-v[1-9]\d*', p.stem) and page_number(p.stem) == number] recorded_names = {c['candidate'] for c in candidates + unavailable} unrecorded.extend(p.stem for p in page_images if p.stem not in recorded_names) candidates.sort(key=lambda c: int(c['candidate'].split('-v')[1])) return {'page': number, 'imageState': ('available' if candidates else 'cropMaterialOnly' if crop_materials else 'unavailable' if has_image else 'unverified' if page_images else 'ungenerated'), 'initialAttempts': counts['initial'], 'layoutChangedAttempts': counts['layoutChanged'], 'correctionAttempts': counts['correction'], 'correctionLimit': 10, 'limitReached': reached, 'nextPhase': None if reached else next_phase, 'remainingAttempts': max(0, 10 - counts[next_phase]), 'candidates': candidates, 'unavailableCandidates': sorted(unavailable, key=lambda c: c['candidate']), 'attempts': events, 'unrecordedResults': sorted(set(unrecorded)), **({'cropMaterials': crop_materials} if crop_materials else {})} def record_attempt(root, name, input_path): """Record one completed tool invocation; exact replays are idempotent.""" root, call_path, candidate = candidate_paths(root, name) call = read_json(call_path) if call.get('recordKind') == 'composition': raise ValueError('A composite is not an image-tool call; record the originating crop call only.') candidate = output_path(root, name, call) payload = read_json(input_path) if not isinstance(payload, dict): raise ValueError('The actual attempt result must be a JSON object.') required = {'candidate', 'callId', 'outcome', 'phase', 'startedAtUtc', 'endedAtUtc', 'toolResponse'} if payload.get('outcome') == 'image': required.add('imageSha256') if set(payload) != required or payload.get('candidate') != name: raise ValueError('Record candidate, callId, outcome, phase, actual times, toolResponse, and imageSha256 only for image output.') if any(not isinstance(payload[k], str) or not payload[k].strip() for k in required): raise ValueError('Attempt result fields must be nonempty strings from the actual call.') if payload['outcome'] not in ATTEMPT_OUTCOMES or payload['phase'] not in ATTEMPT_PHASES: raise ValueError('Unknown attempt outcome or phase.') if timestamp(payload['endedAtUtc']) < timestamp(payload['startedAtUtc']): raise ValueError('Actual call end precedes its start.') result_path = root / 'records' / f'{name}-attempt.json' if result_path.is_file(): if read_json(result_path) != payload: raise ValueError('Preserve the existing actual-call result; do not replace it or count it twice.') return attempt_state(root, name) for existing in (root / 'records').glob('P*-attempt.json'): if read_json(existing).get('callId') == payload['callId']: raise ValueError('The same actual callId already has a result.') if payload['outcome'] == 'image': if call.get('status') != 'generated' or not candidate.is_file() or digest(candidate) != payload['imageSha256']: raise ValueError('Archive and verify the actual image before recording an image outcome.') elif call.get('status') == 'generated' or candidate.exists(): raise ValueError('An existing image cannot be recorded as no image or technical failure.') # Validate chronology before writing. Past over-limit calls are preserved, # not erased; prepare refuses any further automatic attempts. state = attempt_state(root, name, additional=payload) save_new(result_path, payload) return state def material(path, role, base=None): path = Path(path) if base is not None and not path.is_absolute(): path = Path(base) / path path = path.resolve(strict=True) if not path.is_file(): raise ValueError(f'Not a file: {path}') return {'path': str(path), 'role': role, 'sha256': digest(path)} def judgment_basis(root): config = read_json(Path(root) / 'production-inputs.json') designs = config.get('designs') if not isinstance(designs, list) or not designs: raise ValueError('production-inputs.json must name the actual supplied design image(s).') basis = [material(config['source'], 'source', root)] basis += [material(p, 'officialDesign', root) for p in designs] basis.append(material(RULES, 'humanManuscriptRules')) for p in config.get('judgmentMaterials', []): basis.append(material(p, 'userJudgmentMaterial', root)) return basis def reject_generated_image_inputs(root, refs): """Reject known manuscript outputs, including exact renamed copies. This is a provenance guard, not image recognition. Unrecorded crops and externally generated images still require source verification by the agent. """ generated_hashes = set() for call_path in (root / 'records').glob('P*-call.json'): output_hash = read_json(call_path).get('sha256') if output_hash: generated_hashes.add(output_hash) for ref in refs: path = Path(ref['path']) in_this_book = any(path.is_relative_to(root / folder) for folder in ('candidates', 'pages')) in_other_book = (path.parent.name in ('candidates', 'pages') and (path.parent.parent / 'production-inputs.json').is_file()) if in_this_book or in_other_book or ref['sha256'] in generated_hashes: raise ValueError('Generated manuscripts cannot be official or additional reference materials, ' 'including renamed copies. Use --edit with --crop and --edit-scope for a local correction.') def pack_original_references(root, refs, max_paths, reference_priority=(), board_format='png', board_count=1): """Transport supplied pixels together; boards never become official designs.""" if not isinstance(max_paths, int) or not 1 <= max_paths <= 16: raise ValueError('Reference transport needs an actual tool path limit between 1 and 16.') if board_format not in ('png', 'webp'): raise ValueError('Original-reference boards require lossless PNG or WebP.') if len(refs) <= max_paths: return None try: from PIL import Image, ImageDraw except ImportError as error: raise ValueError('Pixel-exact reference packing needs Pillow. Run prepare with the bundled Python runtime.') from error edits = [ref for ref in refs if ref['role'] == 'editTarget'] originals = [ref for ref in refs if ref['role'] != 'editTarget'] slots = max_paths - len(edits) if slots < 1: raise ValueError('The edit target must remain separate from the original references.') by_path = {ref['path']: ref for ref in originals} if len(by_path) != len(originals): raise ValueError('Do not pass duplicate originals when packing references.') priority = [str(Path(p).resolve(strict=True)) for p in reference_priority] if len(set(priority)) != len(priority) or any(p not in by_path for p in priority): raise ValueError('Reference priority must name distinct supplied originals, lowest paper priority first.') # Merge only the minimum low-priority subset needed to remove the # excess. Six paths become one pair plus four untouched inputs. excess = len(originals) - slots if not isinstance(board_count, int) or not 1 <= board_count <= min(slots, excess): raise ValueError('Choose a feasible number of composite boards; six inputs require only one pair.') affected = excess + board_count if len(priority) < affected: raise ValueError(f'Choose {affected} low-priority originals with --reference-priority, lowest first; do not automatically merge every input.') group_size, remainder = divmod(affected, board_count) groups = [] offset = 0 for index in range(board_count): count = group_size + (index < remainder) groups.append([by_path[p] for p in priority[offset:offset + count]]) offset += count merged_paths = set(priority[:affected]) groups.extend([[ref] for ref in originals if ref['path'] not in merged_paths]) original_order = {ref['path']: i for i, ref in enumerate(originals)} groups.sort(key=lambda group: min(original_order[ref['path']] for ref in group)) directory = Path(root) / 'reference-boards' directory.mkdir(parents=True, exist_ok=True) boards = [] for group in groups: if len(group) == 1: boards.append({'image': group[0], 'tiles': [{'original': group[0]}], 'directOriginal': True}) continue identity = {'version': 3, 'originals': group, 'columns': 2, 'padding': 16, 'labelHeight': 24, 'encoding': 'lossless PNG; omit only an entirely opaque alpha channel'} if board_format == 'webp': identity.update(version=4, encoding='lossless WebP; exact RGBA pixels') board_path = directory / ('originals-' + value_digest(identity) + '.' + board_format) sidecar = board_path.with_suffix('.json') if board_path.exists() and sidecar.exists(): board = read_json(sidecar) if board.get('identity') != identity or board.get('image', {}).get('sha256') != digest(board_path): raise ValueError('A cached original-reference board changed; recover it before reuse.') boards.append(board) continue if board_path.exists() or sidecar.exists(): raise ValueError('Incomplete original-reference board cache; recover the file before reuse.') sizes = [] for original in group: if digest(original['path']) != original['sha256']: raise ValueError('A supplied original changed during reference packing.') with Image.open(original['path']) as source_image: sizes.append(source_image.size) columns = min(2, len(group)) column_widths = [max(sizes[i][0] for i in range(column, len(group), columns)) for column in range(columns)] row_heights = [max(height for _, height in sizes[i:i + columns]) for i in range(0, len(group), columns)] width = sum(column_widths) + 16 * (columns + 1) height = sum(row_heights) + 40 * len(row_heights) + 16 canvas = Image.new('RGBA', (width, height), (255, 255, 255, 255)) draw = ImageDraw.Draw(canvas) tiles = [] for index, (original, size) in enumerate(zip(group, sizes)): column, row = index % columns, index // columns x = 16 + sum(column_widths[:column]) + 16 * column y = 40 + sum(row_heights[:row]) + 40 * row with Image.open(original['path']) as source_image: pixels = source_image.convert('RGBA') canvas.paste(pixels, (x, y)) # No mask, resizing, crop, recoloring or redraw. pixel_hash = hashlib.sha256(pixels.tobytes()).hexdigest() draw.text((x, y - 20), str(index + 1), fill=(0, 0, 0, 255)) tiles.append({'original': original, 'label': index + 1, 'rectangle': [x, y, *size], 'rgbaPixelSha256': pixel_hash}) # Avoid a larger RGBA upload when every source pixel is opaque. Removing # that redundant channel and optimizing PNG are lossless; verification # below still compares every decoded RGBA pixel with its source. encoded_canvas = canvas.convert('RGB') if canvas.getchannel('A').getextrema() == (255, 255) else canvas with board_path.open('xb') as output: if board_format == 'webp': encoded_canvas.save(output, format='WEBP', lossless=True, quality=100, method=6, exact=True) else: encoded_canvas.save(output, format='PNG', optimize=True, compress_level=9) if encoded_canvas is not canvas: encoded_canvas.close() canvas.close() # Verify the encoded result, rather than assuming paste preserved the inputs. with Image.open(board_path) as encoded: for tile in tiles: x, y, tile_width, tile_height = tile['rectangle'] pixels = encoded.crop((x, y, x + tile_width, y + tile_height)).convert('RGBA') if hashlib.sha256(pixels.tobytes()).hexdigest() != tile['rgbaPixelSha256']: raise ValueError('A packed reference differs from the original pixels.') if digest(tile['original']['path']) != tile['original']['sha256']: raise ValueError('A supplied original changed during reference packing.') board = {'identity': identity, 'image': material(board_path, 'originalPixelBoard'), 'dimensions': [width, height], 'tiles': tiles, 'pixelExactCopiesVerified': True} save_new(sidecar, board) boards.append(board) return {'mode': 'pixelExactOriginalBoards', 'maxImagePaths': max_paths, 'editTargets': edits, 'boards': boards, 'priorityOrder': priority, 'mergedOriginalPaths': priority[:affected], 'groupPolicy': 'only the minimum lowest-priority subset needed for the chosen number of composite boards', 'compositeBoardCount': board_count, 'toolImagePaths': [ref['path'] for ref in edits] + [board['image']['path'] for board in boards]} def validate_reference_transport(record): transport = record.get('referenceTransport') if transport is None: return if transport.get('mode') != 'pixelExactOriginalBoards': raise ValueError('Unknown reference transport; original provenance is required.') refs = record['imageReferences'] edits = [ref for ref in refs if ref['role'] == 'editTarget'] originals = [ref for ref in refs if ref['role'] != 'editTarget'] flattened = [] for board in transport['boards']: if digest(board['image']['path']) != board['image']['sha256']: raise ValueError('A packed original-reference image changed or is missing.') flattened.extend(tile['original'] for tile in board['tiles']) if not board.get('directOriginal') and board.get('pixelExactCopiesVerified') is not True: raise ValueError('The encoded reference-board pixels were not verified.') paths = [ref['path'] for ref in edits] + [board['image']['path'] for board in transport['boards']] if (sorted(flattened, key=lambda ref: ref['path']) != sorted(originals, key=lambda ref: ref['path']) or transport['editTargets'] != edits): raise ValueError('Reference packing must preserve every original and keep the edit target separate.') if (paths != transport['toolImagePaths'] or paths != record['arguments']['referenced_image_paths'] or len(paths) > transport['maxImagePaths']): raise ValueError('Actual tool references differ from the recorded original-reference transport.') for ref in originals: if digest(ref['path']) != ref['sha256']: raise ValueError('A supplied original differs from the one packed for this call.') def prepare(root, name, spec_path, edit=None, references=(), template_path=None, active_designs=(), edit_scope=None, pack_references=None, reference_priority=(), reference_board_format='png', reference_board_count=1, crop_box=None): if edit is not None and (not isinstance(edit_scope, str) or not edit_scope.strip()): raise ValueError('Local editing requires --edit-scope describing the necessary correction and what to preserve.') if edit is None and edit_scope is not None: raise ValueError('--edit-scope requires an explicit --edit manuscript image.') if (edit is not None) != (crop_box is not None): raise ValueError('Local repair requires --edit, --crop LEFT TOP RIGHT BOTTOM and --edit-scope. ' 'Never pass a full page for editing; regenerate from original materials without --edit instead.') root, call_path, candidate = candidate_paths(root, name) state = attempt_state(root, name) if state['unrecordedResults']: raise ValueError('Import existing actual call results with record-attempt before resuming; do not reset counts.') if state['limitReached']: raise ValueError('Page attempt limit reached; compare all saved candidates and select the best version. Continue other pages.') for selection_path in (root / 'records').glob(f"P{state['page']:02}-selection-*.json"): selection = read_json(selection_path) if (selection.get('selectionMode') == 'afterStop' and selection.get('attemptStateSha256') == value_digest(state)): try: checked_selection_record(root, selection['comparison']['candidate'], {'path': str(selection_path), 'sha256': digest(selection_path)}) except (ValueError, OSError, KeyError, TypeError): # Preserve unsupported historical stops, but do not make them # permanent instructions to abandon the current workflow. continue raise ValueError('Generation already ended and candidates were selected after a recorded stop; ' 'continue other pages, not more automatic repairs for the same remaining defects.') if state['imageState'] == 'unavailable': raise ValueError('Previously generated images are unavailable; recover the saved output instead of treating the page as ungenerated.') spec_path = Path(spec_path).resolve(strict=True) basis = judgment_basis(root) if edit is not None and template_path is not None: raise ValueError('Cropped repair uses the live local template, not a full-page template.') template_path = Path(LOCAL_TEMPLATE if edit is not None else template_path or TEMPLATE).resolve(strict=True) template = template_path.read_text(encoding='utf-8-sig') if template.count(MARKER) != 1: raise ValueError('The live template must contain exactly one PAGE_CONTENT marker.') page_content = spec_path.read_text(encoding='utf-8-sig').strip() if not page_content or MARKER in page_content: raise ValueError('Write page-specific content; do not copy the common template into it.') prompt = template.replace(MARKER, page_content) official = [m for m in basis if m['role'] == 'officialDesign'] refs = list(official) if active_designs: by_path = {m['path']: m for m in official} chosen = [str(Path(p).resolve(strict=True)) for p in active_designs] if len(set(chosen)) != len(chosen) or any(p not in by_path for p in chosen): raise ValueError('Active designs must be distinct actual supplied design paths from production-inputs.json.') refs = [by_path[p] for p in chosen] active_official_paths = [m['path'] for m in refs] supplied_reference_paths = {m['path'] for m in basis if m['role'] == 'userJudgmentMaterial'} for path in references: ref = material(path, 'additionalImageReference') if ref['path'] not in supplied_reference_paths: raise ValueError('Additional image references must be original supplied materials registered in ' 'production-inputs.json judgmentMaterials; generated manuscripts are not allowed.') refs.append(ref) reject_generated_image_inputs(root, refs) edit_target = material(edit, 'editTarget') if edit is not None else None local = None if edit_target: if edit_target['path'] in {m['path'] for m in refs}: raise ValueError('The edit target must be a manuscript, separate from the official and original references.') # Validate names before creating any crop artifacts. if call_path.exists() or candidate.exists() or (root / 'prompts' / f'{name}.txt').exists(): raise ValueError('Use a new candidate name; existing prompts and calls are history.') from manga_local_repair import context_crop local = context_crop(edit, crop_box, root / 'local-repairs' / name) edit_target = material(local['contextCrop']['path'], 'editTarget') refs.insert(0, edit_target) prompt = '修正範囲と保持対象:' + edit_scope.strip() + '\n\n' + prompt prompt_path = root / 'prompts' / f'{name}.txt' if call_path.exists() or candidate.exists() or prompt_path.exists(): raise ValueError('Use a new candidate name; existing prompts and calls are history.') transport = pack_original_references(root, refs, pack_references, reference_priority, reference_board_format, reference_board_count) if pack_references is not None else None if transport: mapping = ['画像参照の渡し方:一時参照画像は、提供実原画を描き直し・拡縮・切り抜き・色変更せず並べたもの。' '各区画は元の人物・衣装の資料。配置用の数字や資料名は漫画へ印字しない。'] for index, board in enumerate(transport['boards'], start=1 + len(transport['editTargets'])): names = '、'.join(f"区画{tile.get('label', 1)}={Path(tile['original']['path']).name}" for tile in board['tiles']) mapping.append(f'参照画像{index}:{names}') prompt = '\n'.join(mapping) + '\n\n' + prompt arguments = {'prompt': prompt, 'referenced_image_paths': transport['toolImagePaths'] if transport else [m['path'] for m in refs], 'transparent_background': False} if state['attempts'] and state['attempts'][-1]['outcome'] == 'noImage': previous = read_json(root / 'records' / f"{state['attempts'][-1]['candidate']}-call.json") if arguments == previous['arguments'] and refs == previous['imageReferences']: raise ValueError('The last call returned no image. Assess its actual reply and legitimately clarify ' 'the instructions for permissible content; do not repeat identical arguments.') record = {'candidate': name, 'status': 'prepared', 'preparedAtUtc': datetime.now(timezone.utc).isoformat(), 'tool': 'image_gen.imagegen', 'arguments': arguments, 'template': material(template_path, 'liveTemplate'), 'pageSpec': material(spec_path, 'pageSpec'), 'imageReferences': refs, 'judgmentBasis': basis, 'activeOfficialDesignPaths': active_official_paths, 'generationMode': 'croppedLocalEdit' if edit_target else 'freshFromOriginalMaterials', 'assessmentVersion': 2, 'humanAcceptance': False, 'artisticQualityAutomaticallyAssessed': False} if edit_target: record.update(editTarget=edit_target, editScope=edit_scope.strip(), localRepair=local) if transport: record['referenceTransport'] = transport validate_reference_transport(record) prompt_path.parent.mkdir(parents=True, exist_ok=True) with prompt_path.open('x', encoding='utf-8') as stream: stream.write(prompt) save_new(call_path, record) return arguments def archive(root, name, source): root, call_path, candidate = candidate_paths(root, name) record = read_json(call_path) candidate = output_path(root, name, record) validate_reference_transport(record) observation_path = root / 'records' / f'{name}-observation.json' source = Path(source).resolve(strict=True) if record['status'] != 'prepared' or candidate.exists() or observation_path.exists(): raise ValueError('This call already has output or observations; use a new candidate.') if (root / 'records' / f'{name}-attempt.json').exists(): raise ValueError('This call already has a no-image result; recover the actual execution record before archiving.') if not source.read_bytes().startswith(b'\x89PNG\r\n\x1a\n'): raise ValueError('Archive the original PNG returned by the built-in image tool.') candidate.parent.mkdir(parents=True, exist_ok=True) shutil.copy2(source, candidate) image_hash = digest(source) if digest(candidate) != image_hash: raise ValueError('Output copy verification failed.') record.update(status='generated', archivedAtUtc=datetime.now(timezone.utc).isoformat(), builtInOutput=str(source), archivedOutput=str(candidate), sha256=image_hash) call_path.write_text(json.dumps(record, ensure_ascii=False, indent=2) + '\n', encoding='utf-8') if record.get('generationMode') == 'croppedLocalEdit': return {'material': str(candidate), 'imageSha256': image_hash, 'selected': False, 'nextAction': 'composeLocal', 'pageCandidate': False} return create_observation(root, name, record, candidate) def create_observation(root, name, record, candidate): observation_path = root / 'records' / f'{name}-observation.json' image_hash = digest(candidate) observation = {'candidate': name, 'imageSha256': image_hash, 'judgmentBasis': record['judgmentBasis'], 'actualPageRead': '', 'comparisonWithHumanIntent': '', 'actualVoiceOrder': None, 'decision': None, **{key: {'pass': None, 'evidence': ''} for key in ASPECTS}, 'unresolvedDefects': None, 'acceptedMinorDifferences': [], 'finishAndDetails': '', 'humanAcceptance': False} observation['manuscriptRules']['readingOrder'] = {'pass': None, 'evidence': ''} observation['pageLayout']['staging'] = {'pass': None, 'evidence': ''} observation['compositionAnatomy']['skeleton'] = {'pass': None, 'evidence': ''} observation['compositionAnatomy']['worldScale'] = {'pass': None, 'evidence': ''} observation['sourceVoiceDesign']['checks'] = {key: {'pass': None, 'evidence': ''} for key in DESIGN_CHECKS} save_new(observation_path, observation) return {'image': str(candidate), 'observation': str(observation_path), 'judgmentBasis': record['judgmentBasis'], 'selected': False} def compose_local(root, name, crop_call, allowed, alpha=None, feather=0): root, call_path, candidate = candidate_paths(root, name) _, source_call_path, _ = candidate_paths(root, crop_call) source_call = read_json(source_call_path) if (page_number(name) != page_number(crop_call) or source_call.get('generationMode') != 'croppedLocalEdit' or source_call.get('status') != 'generated'): raise ValueError('Compose a generated crop call of the same page.') if call_path.exists() or candidate.exists() or (root / 'records' / f'{name}-observation.json').exists(): raise ValueError('Use a new composite candidate name; preserve prior outputs.') if not (root / 'records' / f'{crop_call}-attempt.json').is_file(): raise ValueError('Record the actual crop call before composing; a mask change is not a new call.') raw = material(output_path(root, crop_call, source_call), 'generatedCropMaterial') if raw['sha256'] != source_call['sha256']: raise ValueError('The raw crop differs from its actual call output.') from manga_local_repair import compose report = compose(source_call['localRepair'], raw, allowed, root / 'local-repairs' / name, candidate, alpha, feather) record = {**source_call, 'candidate': name, 'recordKind': 'composition', 'generationMode': 'cropComposite', 'originatingCall': material(source_call_path, 'cropCall'), 'rawCrop': raw, 'composite': report, 'archivedOutput': str(candidate), 'sha256': digest(candidate), 'archivedAtUtc': datetime.now(timezone.utc).isoformat()} save_new(call_path, record) return {**create_observation(root, name, record, candidate), 'preservation': report, 'generationAttemptsAdded': 0} def reading_inputs(root, name): """Expose actual reading materials without the authored plan or old verdict. This is an input packet, not evidence that the images were opened or that any visual judgment is correct. """ root, call_path, candidate = candidate_paths(root, name) call = read_json(call_path) if call.get('generationMode') == 'croppedLocalEdit': raise ValueError('A raw crop is a material, not a page. Use compose-local before reading or selecting a page.') if call.get('status') != 'generated' or call.get('sha256') != digest(candidate): raise ValueError('Read the exact archived output for this candidate.') n = int(name.split('-')[0][1:]) neighbors = [root / 'pages' / f'P{i:02}.png' for i in (n-1, n+1) if i > 0] result = {'candidate': name, 'image': str(candidate), 'imageSha256': digest(candidate), 'officialImages': [m for m in judgment_basis(root) if m['role'] == 'officialDesign'], 'neighbors': [str(p) for p in neighbors if p.is_file()], 'source': material(read_json(root / 'production-inputs.json')['source'], 'source', root)['path'], 'qualityAutomaticallyAssessed': False} result['readingFields'] = list(READ_FIELDS) + (['finishAndDetails'] if call.get('assessmentVersion', 1) >= 2 else []) if call.get('recordKind') == 'composition': validate_composite_record(call, candidate) result['localRepairViews'] = { 'beforePage': call['localRepair']['snapshot']['path'], 'beforeNativeCrop': call['localRepair']['contextCrop']['path'], 'rawGeneratedCrop': call['rawCrop']['path'], 'afterNativeCrop': call['composite']['alignedCrop']['path'], 'allowedMask': call['composite']['allowedMask']['path'], 'inspect': 'Open final page and native before/after region, including mask boundary and overlapping objects.'} return result def validate_composite_record(call, candidate): origin = call['originatingCall'] if digest(origin['path']) != origin['sha256']: raise ValueError('Originating crop call changed.') source_call = read_json(origin['path']) if (source_call.get('generationMode') != 'croppedLocalEdit' or source_call.get('status') != 'generated' or source_call.get('sha256') != call['rawCrop']['sha256'] or source_call.get('localRepair') != call['localRepair'] or source_call.get('imageReferences') != call['imageReferences']): raise ValueError('Composite lineage differs from the actual crop call.') from manga_local_repair import verify verify(call['localRepair'], call['rawCrop'], call['composite'], candidate) def composition_reading_inputs(plan_path): """Show planned pictures/voices without their author's success claims.""" plan = read_json(plan_path) pages = [] for page in plan['pages']: panels = [] for panel in page['panels']: visible = {key: panel[key] for key in ('number','position','size','shape','image') if key in panel} visible['voices'] = [{key: voice[key] for key in ('speaker','text','kind','placement') if key in voice} for voice in panel.get('voices', [])] visible['soundEffects'] = [{key: sound[key] for key in ('text','kind','placement') if key in sound} for sound in panel.get('soundEffects', [])] panels.append(visible) pages.append({'number':page['number'], 'panels':panels}) return {'readingMode':plan.get('readingMode'), 'pages':pages, 'sourcePlanSha256':digest(plan_path), 'stagingAutomaticallyAssessed':False} def validate_image_binding(root, name, payload): """Require the assessor to identify the image, not inherit archive metadata.""" _, _, candidate = candidate_paths(root, name) if payload.get('candidate') != name: raise ValueError('Assessment candidate mismatch; do not apply another candidate\'s reading or passes.') if payload.get('imageSha256') != digest(candidate): raise ValueError('Assessment image mismatch; reread this actual output instead of carrying previous passes.') def record_reading(root, name, input_path, reason=None): """Freeze the existing step-3 image reading before comparison/selection.""" root, call_path, candidate = candidate_paths(root, name) reading_inputs(root, name) payload = read_json(input_path) validate_image_binding(root, name, payload) fields = (*READ_FIELDS, 'finishAndDetails') if read_json(call_path).get('assessmentVersion', 1) >= 2 else READ_FIELDS if set(payload) != set(fields) | set(IMAGE_BINDING_FIELDS): raise ValueError('Record candidate, imageSha256 and image observations only: '+', '.join(fields)+'. No pass/decision defaults.') data = {key: payload[key] for key in fields} for key in ('actualPageRead', 'pageLayout', 'compositionAnatomy', *(['finishAndDetails'] if 'finishAndDetails' in fields else [])): if not isinstance(data[key], str) or not data[key].strip(): raise ValueError(f'Unobserved image reading: {key}') if not isinstance(data['actualVoiceOrder'], list): raise ValueError('Read the actual voices; use [] only for a silent image.') for voice in data['actualVoiceOrder']: if not isinstance(voice, dict) or any(not isinstance(voice.get(k), str) or not voice[k].strip() for k in ('speaker', 'text', 'location')): raise ValueError('Each actual voice needs text, observed speaker (or 不明), and image location.') if not isinstance(data['imageFindings'], list) or any(not isinstance(s, str) or not s.strip() for s in data['imageFindings']): raise ValueError('imageFindings must list observed differences or concerns, or []. Classify them after comparison.') index_path = root / 'records' / f'{name}-reading-index.json' entries = read_json(index_path)['entries'] if index_path.is_file() else [] if entries and (not isinstance(reason, str) or not reason.strip()): raise ValueError('Preserve the previous reading; state the image-based reason for rereading.') path = root / 'records' / f'{name}-reading-{len(entries)+1:03}.json' record = {'candidate': name, 'imageSha256': digest(candidate), 'judgmentBasis': judgment_basis(root), 'recordedAtUtc': datetime.now(timezone.utc).isoformat(), 'rereadReason': reason, 'supersedes': entries[-1] if entries else None, 'reading': data, 'qualityAutomaticallyAssessed': False} save_new(path, record) entries.append({'path': str(path), 'sha256': digest(path)}) index_path.write_text(json.dumps({'candidate': name, 'entries': entries},ensure_ascii=False,indent=2)+'\n',encoding='utf-8') return {'readingRecord': entries[-1], 'imageFindings': data['imageFindings'], 'selected': False, 'qualityAutomaticallyAssessed': False} def accepted_minor_differences(payload): """Validate explicit dispositions, without deciding visual severity. Missing means no exceptions for older records, never an inferred approval. An empty list permits no exceptions; the actual decision stays unassessed. """ entries = payload.get('acceptedMinorDifferences', []) if not isinstance(entries, list): raise ValueError('Assess acceptedMinorDifferences explicitly; use [] when there are none.') findings = {} for entry in entries: if (not isinstance(entry, dict) or set(entry) != {'finding', 'reason'} or any(not isinstance(entry[k], str) or not entry[k].strip() for k in ('finding', 'reason'))): raise ValueError('Each accepted minor difference needs the recorded finding and a concrete reason.') if entry['finding'] in findings: raise ValueError('Duplicate accepted minor difference.') findings[entry['finding']] = entry['reason'] return findings def validate_recorded_reading(root, name, observation, candidate, basis, allow_remaining=False): index_path = root / 'records' / f'{name}-reading-index.json' if not index_path.is_file(): raise ValueError('Missing image reading. Use reading-inputs, read the actual images, then record-reading before comparison.') index = read_json(index_path) if index.get('candidate') != name or not index.get('entries'): raise ValueError('Invalid image-reading history.') # Old readings remain part of the evidence, including resolved doubts. for entry in index['entries']: p = Path(entry['path']).resolve(strict=True) if p.parent != (root / 'records').resolve() or digest(p) != entry['sha256']: raise ValueError('Image reading was moved, replaced or edited; preserve it and record a reasoned reread.') record = read_json(index['entries'][-1]['path']) if record['imageSha256'] != digest(candidate) or record['judgmentBasis'] != basis: raise ValueError('Image or judgment materials changed; record an explicit reread of the current materials.') raw = record['reading'] accepted = accepted_minor_differences(observation) if set(accepted) - set(raw['imageFindings']): raise ValueError('An accepted minor difference is absent from the recorded image findings.') remaining = set(observation['unresolvedDefects']) if allow_remaining else set() if remaining & set(accepted): raise ValueError('A required correction cannot also be an accepted minor difference.') if set(raw['imageFindings']) - set(accepted) - remaining: raise ValueError('The image reading has unresolved findings; classify permissible minor differences ' 'with reasons, or preserve the required correction. Do not erase the reading.') for key in ('actualPageRead', 'actualVoiceOrder'): if observation.get(key) != raw[key]: raise ValueError(f'{key} differs from the recorded image reading; do not substitute the planned answer.') if 'finishAndDetails' in raw and observation.get('finishAndDetails') != raw['finishAndDetails']: raise ValueError('finishAndDetails differs from the actual reading; do not inherit old quality judgments.') for key in ('pageLayout', 'compositionAnatomy'): if observation.get(key, {}).get('evidence') != raw[key]: raise ValueError(f'{key} differs from the recorded visible evidence; record an explicit reread if needed.') assessed = observation.get('observedAtUtc') if not assessed or datetime.fromisoformat(assessed) <= datetime.fromisoformat(record['recordedAtUtc']): raise ValueError('Compare and decide after the image reading; old pass notes cannot be carried forward.') def validate_observation(observation, candidate, basis, allow_remaining=False): if observation.get('imageSha256') != digest(candidate): raise ValueError('The observation belongs to a different image.') if observation.get('judgmentBasis') != basis: raise ValueError('Keep the source/user materials attached to this observation.') if observation.get('decision') not in (('retain', 'reject') if allow_remaining else ('retain',)): raise ValueError('No explicit retain decision; the candidate remains unselected.') for field in ('actualPageRead', 'comparisonWithHumanIntent'): if not isinstance(observation.get(field), str) or not observation[field].strip(): raise ValueError(f'Unassessed: {field}') for key in ASPECTS: item = observation.get(key, {}) if (not isinstance(item, dict) or type(item.get('pass')) is not bool or (not allow_remaining and item['pass'] is not True) or not isinstance(item.get('evidence'), str) or not item['evidence'].strip()): raise ValueError(f'Unassessed or failed: {key}') specific = [('readingOrder', observation['manuscriptRules'].get('readingOrder', {})), ('staging', observation['pageLayout'].get('staging', {})), ('skeleton', observation['compositionAnatomy'].get('skeleton', {})), ('worldScale', observation['compositionAnatomy'].get('worldScale', {}))] checks = observation['sourceVoiceDesign'].get('checks', {}) if not isinstance(checks, dict): raise ValueError('Assess head proportions, face and physique separately against the actual design.') specific += [(key, checks.get(key, {})) for key in DESIGN_CHECKS] for key, item in specific: if (not isinstance(item, dict) or type(item.get('pass')) is not bool or (not allow_remaining and item['pass'] is not True) or not isinstance(item.get('evidence'), str) or not item['evidence'].strip()): raise ValueError(f'Unassessed or failed: {key}. Other passing aspects cannot compensate.') if not isinstance(observation.get('actualVoiceOrder'), list): raise ValueError('Read the actual voices first; use an explicit empty list for a silent page.') defects = observation.get('unresolvedDefects') if (not isinstance(defects, list) or any(not isinstance(s, str) or not s.strip() for s in defects) or len(set(defects)) != len(defects)): raise ValueError('Required corrections must be explicitly assessed and listed without duplicates.') if not allow_remaining and defects != []: raise ValueError('Required corrections are unresolved or not assessed; accepted minor differences cannot waive them.') if allow_remaining: failed = any(observation[k]['pass'] is False for k in ASPECTS) or any(v['pass'] is False for _, v in specific) if failed != bool(defects) or observation['decision'] != ('reject' if defects else 'retain'): raise ValueError('Preserve failed checks and their required corrections; do not relabel a rejected image as passed.') accepted_minor_differences(observation) if observation.get('humanAcceptance') is not False: raise ValueError('This command records agent selection, not human acceptance.') def checked_candidate(root, name, allow_remaining=False): root, call_path, candidate = candidate_paths(root, name) record = read_json(call_path) if record.get('generationMode') == 'croppedLocalEdit': raise ValueError('A raw crop is not a full-page candidate; compose-local first.') validate_reference_transport(record) if record['status'] != 'generated' or record['sha256'] != digest(candidate): raise ValueError('Generated output does not match its call record.') if record.get('recordKind') == 'composition': validate_composite_record(record, candidate) observation = read_json(root / 'records' / f'{name}-observation.json') if observation.get('candidate') != name: raise ValueError('Candidate/observation mismatch.') current_basis = judgment_basis(root) current_designs = [m for m in current_basis if m['role'] == 'officialDesign'] if 'activeOfficialDesignPaths' in record: by_path = {m['path']: m for m in current_designs} declared = record['activeOfficialDesignPaths'] if not declared or len(set(declared)) != len(declared) or any(p not in by_path for p in declared): raise ValueError('Active official references no longer match the supplied design materials.') current_designs = [by_path[p] for p in declared] original_designs = [m for m in record['imageReferences'] if m['role'] == 'officialDesign'] if current_designs != original_designs: raise ValueError('The current supplied design must have been passed to the image tool; use a new call.') # Preserve the original call basis. An updated source/criterion needs an # explicit re-read and updated observation, not a silent pass or new image. validate_observation(observation, candidate, current_basis, allow_remaining) if record.get('assessmentVersion', 1) >= 2 and (not isinstance(observation.get('finishAndDetails'), str) or not observation['finishAndDetails'].strip()): raise ValueError('Unassessed: finishAndDetails. Read linework, tones, grain, blur and repair boundaries.') validate_recorded_reading(root, name, observation, candidate, current_basis, allow_remaining) return root, candidate def eligible_candidate(root, name, basis): """Only compare outputs made from the current source and actual designs.""" _, call_path, _ = candidate_paths(root, name) call = read_json(call_path) source = [m for m in basis if m['role'] == 'source'] if [m for m in call['judgmentBasis'] if m['role'] == 'source'] != source: return False designs = [m for m in basis if m['role'] == 'officialDesign'] active = call.get('activeOfficialDesignPaths') if active is not None: by_path = {m['path']: m for m in designs} if not active or len(set(active)) != len(active) or any(p not in by_path for p in active): return False designs = [by_path[p] for p in active] return [m for m in call['imageReferences'] if m['role'] == 'officialDesign'] == designs def validate_generation_stop(root, state, stop): """Bind an exceptional stop to evidence; noImage alone is not a stop reason. The agent must assess content/recovery from the actual reply and sources. This function checks the record, never makes a safety judgment itself. """ if not isinstance(stop, dict) or stop.get('kind') not in ('contentUnavailable', 'technicalFailure', 'userStopped'): raise ValueError('An exceptional generation stop needs its specific kind and evidence; noImage alone is insufficient.') for key in ('reason', 'evidence'): if not isinstance(stop.get(key), str) or not stop[key].strip(): raise ValueError('Record the actual stop reason and evidence, including content assessment or recovery attempted.') if stop['kind'] != 'userStopped': events = state['attempts'] expected = 'noImage' if stop['kind'] == 'contentUnavailable' else 'technicalFailure' if (not events or events[-1]['outcome'] != expected or stop.get('callId') != events[-1]['callId']): raise ValueError('Generation stop must refer to the actual latest call and its outcome.') if stop['kind'] == 'contentUnavailable': assessment = stop.get('contentAssessment') if not isinstance(assessment, dict) or assessment.get('basis') != 'sourceContent': raise ValueError('Content stop needs a source-content assessment; an output refusal label alone is insufficient.') for key in ('prohibitedContent', 'whyClarificationCannotResolve'): if not isinstance(assessment.get(key), str) or not assessment[key].strip(): raise ValueError('Identify the specific prohibited source content and why legitimate clarification cannot resolve it.') latest = read_json(Path(root) / 'records' / f"{events[-1]['candidate']}-attempt.json") response_hash = hashlib.sha256(latest['toolResponse'].encode('utf-8')).hexdigest() if assessment.get('toolResponseSha256') != response_hash: raise ValueError('Content assessment must refer to the exact saved tool response.') source = assessment.get('sourceEvidence') if not isinstance(source, dict): raise ValueError('Content assessment needs the actual source material, location and finding.') sources = {m['path']: m for m in judgment_basis(root) if m['role'] in ('source', 'officialDesign', 'userJudgmentMaterial')} source_path = str(Path(source.get('path', '')).resolve()) if source_path not in sources or source.get('sha256') != sources[source_path]['sha256']: raise ValueError('Content assessment source must match a current registered original material.') for key in ('location', 'finding'): if not isinstance(source.get(key), str) or not source[key].strip(): raise ValueError('Record where and what was read in the source, independently of the refusal label.') if Path(source_path).suffix.lower() in ('.txt', '.md', '.json', '.csv'): excerpt = source.get('excerpt') if (not isinstance(excerpt, str) or not excerpt.strip() or excerpt not in Path(source_path).read_text(encoding='utf-8-sig')): raise ValueError('Content assessment excerpt must occur in the actual source text.') return stop def revision_targets(root, candidates, chosen=None): """Carry concrete earlier defects into comparison, never infer their resolution.""" targets = [] for row in candidates: if row['candidate'] == chosen: continue observation = read_json(Path(root) / 'records' / f"{row['candidate']}-observation.json") for finding in observation['unresolvedDefects']: targets.append({'sourceCandidate': row['candidate'], 'sourceImageSha256': row['imageSha256'], 'finding': finding}) return targets def comparison_inputs(root, page): """Expose every current-source candidate; leave choice and visual reasons unfilled.""" root = Path(root).resolve() state = attempt_state(root, page) basis = judgment_basis(root) candidates = [] for row in state['candidates']: name = row['candidate'] if not eligible_candidate(root, name, basis): continue checked_candidate(root, name, allow_remaining=True) path = root / 'records' / f'{name}-observation.json' observation = read_json(path) candidates.append({**row, 'image': str(root / 'candidates' / f'{name}.png'), 'observation': str(path), 'observationSha256': digest(path), 'decision': observation['decision'], 'unresolvedDefects': observation['unresolvedDefects'], 'acceptedMinorDifferences': observation.get('acceptedMinorDifferences', []), 'finishAndDetails': observation.get('finishAndDetails', ''), 'priorityEvidence': {key: None for key in PRIORITY_FIELDS}}) return {'page': state['page'], 'correctionAttempts': state['correctionAttempts'], 'candidates': candidates, 'revisionTargets': revision_targets(root, candidates), 'unavailableCandidates': state['unavailableCandidates'], 'unrecordedResults': state['unrecordedResults'], 'cropMaterials': state.get('cropMaterials', []), 'humanAcceptance': False, 'artisticQualityAutomaticallyAssessed': False} def validate_revision_checks(root, name, comparison, candidates): required = {(t['sourceCandidate'], t['finding']): t for t in revision_targets(root, candidates, name)} checks = comparison.get('revisionChecks', []) if not isinstance(checks, list) or any(not isinstance(c, dict) for c in checks): raise ValueError('revisionChecks must compare earlier defects with the chosen actual image.') keys = [(c.get('sourceCandidate'), c.get('finding')) for c in checks] if len(keys) != len(set(keys)) or set(keys) != set(required): raise ValueError('Account for every earlier candidate defect in revisionChecks; do not erase a repair goal.') defects = comparison['unresolvedDefects'] for check in checks: target = required[(check['sourceCandidate'], check['finding'])] if check.get('sourceImageSha256') != target['sourceImageSha256']: raise ValueError('A revision check refers to a different source image.') if not isinstance(check.get('evidence'), str) or not check['evidence'].strip(): raise ValueError('State the visible before/after evidence for each repair goal, not the edit instruction.') if check.get('result') not in ('resolved', 'remaining'): raise ValueError('Each repair goal must be resolved with evidence or preserved as remaining.') if check['result'] == 'remaining' and check.get('unresolvedDefect') not in defects: raise ValueError('A remaining repair goal must stay in the chosen image unresolvedDefects.') if check['result'] == 'resolved' and check.get('unresolvedDefect'): raise ValueError('A resolved repair goal cannot also carry an unresolved defect.') def validate_limit_selection(root, name, comparison, after_stop=False, normal=False, require_revision_checks=False, require_priority=False, repair_base=False): root, _, candidate = candidate_paths(root, name) if not isinstance(comparison, dict): raise ValueError('Candidate comparison must be a JSON object.') state = attempt_state(root, name) if state['unrecordedResults']: raise ValueError('Candidate selection requires the complete actual call history; recover unrecorded results.') if after_stop: validate_generation_stop(root, state, comparison.get('generationStop')) elif not normal and not repair_base and state['correctionAttempts'] < 10: raise ValueError('At-limit selection requires the complete actual history and at least 10 correction calls.') if normal and not repair_base and state['correctionAttempts'] >= 10: raise ValueError('At the correction limit, use select --at-limit with the complete comparison.') if (comparison.get('page') != page_number(name) or comparison.get('candidate') != name or comparison.get('imageSha256') != digest(candidate) or comparison.get('correctionAttempts') != state['correctionAttempts']): raise ValueError('Selection page, candidate, image or attempt count differs from actual history.') if not isinstance(comparison.get('reason'), str) or not comparison['reason'].strip(): raise ValueError('State why this actual image is the best saved candidate, including remaining problems.') basis = judgment_basis(root) eligible = {c['candidate']: c for c in state['candidates'] if eligible_candidate(root, c['candidate'], basis)} rows = comparison.get('comparedCandidates', []) if (not isinstance(rows, list) or any(not isinstance(r, dict) for r in rows) or len(rows) != len(eligible) or {r.get('candidate') for r in rows} != set(eligible) or name not in eligible): raise ValueError('Compare every available current-source candidate, including the original and rejected versions.') for row in rows: current = eligible[row['candidate']] observation_path = root / 'records' / f"{row['candidate']}-observation.json" if (row.get('imageSha256') != current['imageSha256'] or row.get('observationSha256') != digest(observation_path)): raise ValueError('Candidate comparison is stale or bound to another image/observation.') if not isinstance(row.get('reason'), str) or not row['reason'].strip(): raise ValueError('Each compared candidate needs an image-based comparison reason.') if require_priority: evidence = row.get('priorityEvidence', {}) if not isinstance(evidence, dict) or any(not isinstance(evidence.get(k), str) or not evidence[k].strip() for k in PRIORITY_FIELDS): raise ValueError('Each candidate needs priorityEvidence: criticalIntegrity, stagingAndFinish, ' 'localManuscript, minorDifferences. Compare actual outputs, not prompt compliance or age.') checked_candidate(root, row['candidate'], allow_remaining=True) observation = read_json(root / 'records' / f'{name}-observation.json') if comparison.get('unresolvedDefects') != observation['unresolvedDefects']: raise ValueError('Selection must preserve every remaining correction from the chosen image.') if not repair_base and observation['unresolvedDefects'] and qualifying_candidates(root, comparison): raise ValueError('A candidate meets the acceptance criteria; do not choose a rejected version over it.') if normal and not repair_base and observation['decision'] != 'retain': raise ValueError('Normal selection requires a qualifying image; keep remaining corrections at the limit or an evidenced stop.') if require_revision_checks: validate_revision_checks(root, name, comparison, list(eligible.values())) return root, candidate, state, basis def record_repair_base(root, name, input_path): """Choose the best starting art without falsifying a reject or publishing it.""" comparison = read_json(input_path) root, _, state, basis = validate_limit_selection(root, name, comparison, normal=True, require_revision_checks=True, require_priority=True, repair_base=True) sequence = len(list((root / 'records').glob(f'P{page_number(name):02}-repair-base-*.json'))) + 1 path = root / 'records' / f'P{page_number(name):02}-repair-base-{sequence:03}.json' save_new(path, {'comparison': comparison, 'attemptStateSha256': value_digest(state), 'judgmentBasis': basis, 'recordedAtUtc': datetime.now(timezone.utc).isoformat(), 'adopted': False, 'artisticQualityAutomaticallyAssessed': False}) return {'repairBase': name, 'record': str(path), 'adopted': False, 'unresolvedDefects': comparison['unresolvedDefects']} def qualifying_candidates(root, comparison): return [row['candidate'] for row in comparison['comparedCandidates'] if read_json(Path(root) / 'records' / f"{row['candidate']}-observation.json")['decision'] == 'retain'] def selection_note(name, count, defects, no_qualifying=False, stop=None): ending = ('残る修正点:' + '、'.join(defects) + '。これらの修正が残っているバージョンです。' if defects else '修正必須の問題は解消しています。') qualification = '通常の採用基準を満たす候補はありません。' if no_qualifying else '' stop_note = f"追加生成を止めた理由:{stop['reason']}。" if stop else '' return f'P{page_number(name):02}は{count}回修正を試行し、生成済み候補から{name}を採用。' + qualification + ending + stop_note def select(root, name, at_limit=None, after_stop=None, comparison=None): if sum(x is not None for x in (at_limit, after_stop, comparison)) > 1: raise ValueError('Choose one of --comparison, --at-limit or --after-stop.') selection_record = None if at_limit is None and after_stop is None and comparison is None: state = attempt_state(root, name) if state['correctionAttempts'] >= 10: raise ValueError('At the correction limit, compare all candidates and use select --at-limit.') basis = judgment_basis(root) eligible = [c for c in state['candidates'] if eligible_candidate(root, c['candidate'], basis)] if len(eligible) > 1: raise ValueError('Multiple candidates require select --comparison and an image-based comparison of every version.') root, candidate = checked_candidate(root, name) defects, status, count = [], 'complete', None else: normal = comparison is not None comparison = read_json(comparison if normal else after_stop if after_stop is not None else at_limit) root, candidate, state, basis = validate_limit_selection( root, name, comparison, after_stop is not None, normal=normal, require_revision_checks=True, require_priority=True) defects = comparison['unresolvedDefects'] status = WITH_REMAINING if defects else 'complete' count = state['correctionAttempts'] qualified = qualifying_candidates(root, comparison) stop = comparison['generationStop'] if after_stop is not None else None report_text = selection_note(name, count, defects, not qualified, stop) prefix = f'P{page_number(name):02}-selection-' sequence = len(list((root / 'records').glob(prefix + '*.json'))) + 1 path = root / 'records' / f'{prefix}{sequence:03}.json' save_new(path, {'schemaVersion': 4, 'selectionMode': 'normal' if normal else 'afterStop' if after_stop is not None else 'atLimit', 'selectionStatus': status, 'comparison': comparison, 'qualifyingCandidates': qualified, 'noCandidateMeetsCriteria': not qualified, 'attemptStateSha256': value_digest(state), 'judgmentBasis': basis, 'reportText': report_text, 'selectedAtUtc': datetime.now(timezone.utc).isoformat(), 'humanAcceptance': False, 'artisticQualityAutomaticallyAssessed': False}) selection_record = {'path': str(path), 'sha256': digest(path)} target = root / 'pages' / f'{name.split("-")[0]}.png' target.parent.mkdir(parents=True, exist_ok=True) shutil.copy2(candidate, target) result = {'selectedByAgent': name, 'path': str(target), 'sha256': digest(target), 'selectionStatus': status, 'unresolvedDefects': defects, 'humanAcceptance': False, 'artisticQualityAutomaticallyAssessed': False} if selection_record: result.update(selectionRecord=selection_record, correctionAttempts=count, reportText=report_text, noCandidateMeetsCriteria=not qualified) return result def checked_selection_record(root, name, reference): path = Path(reference['path']).resolve(strict=True) if (path.parent != (root / 'records').resolve() or not re.fullmatch(rf'P{page_number(name):02}-selection-\d{{3,}}\.json', path.name) or digest(path) != reference['sha256']): raise ValueError('Selection record was moved, replaced or edited.') record = read_json(path) mode = record.get('selectionMode', 'atLimit') if mode not in ('normal', 'atLimit', 'afterStop'): raise ValueError('Unknown selection mode.') _, candidate, state, basis = validate_limit_selection( root, name, record['comparison'], mode == 'afterStop', normal=mode == 'normal', require_revision_checks=record.get('schemaVersion', 1) >= 3, require_priority=record.get('schemaVersion', 1) >= 4) defects = record['comparison']['unresolvedDefects'] status = WITH_REMAINING if defects else 'complete' qualified = qualifying_candidates(root, record['comparison']) modern = record.get('schemaVersion', 1) >= 2 if modern and (record.get('qualifyingCandidates') != qualified or record.get('noCandidateMeetsCriteria') != (not qualified)): raise ValueError('Selection must report whether any saved candidate meets the acceptance criteria.') stop = record['comparison'].get('generationStop') if mode == 'afterStop' else None if (record.get('attemptStateSha256') != value_digest(state) or record.get('judgmentBasis') != basis or record.get('selectionStatus') != status or record.get('humanAcceptance') is not False or record.get('artisticQualityAutomaticallyAssessed') is not False or record.get('reportText') != selection_note(name, state['correctionAttempts'], defects, modern and not qualified, stop)): raise ValueError('Selection record differs from current attempts, materials or remaining corrections.') return candidate, record def page_status(root, page, generation_stop=None): """Derive the next workflow action and report from live history, not a cached final snapshot.""" root = Path(root).resolve() state = attempt_state(root, page) if generation_stop is not None: validate_generation_stop(root, state, generation_stop) number = state['page'] result = {'page': number, 'imageState': state['imageState'], 'initialAttempts': state['initialAttempts'], 'layoutChangedAttempts': state['layoutChangedAttempts'], 'correctionAttempts': state['correctionAttempts'], 'remainingAttempts': state['remainingAttempts'], 'nextPhase': state['nextPhase'], 'limitReached': state['limitReached'], 'candidates': state['candidates'], 'unavailableCandidates': state['unavailableCandidates'], 'noCandidateMeetsCriteria': None, 'selectedCandidate': None, 'unresolvedDefects': []} if state.get('cropMaterials'): result['cropMaterials'] = state['cropMaterials'] def finish(status, action, note): result.update(status=status, nextAction=action, reportText=f'P{number:02}:' + note) return result if state['unrecordedResults']: result['unrecordedResults'] = state['unrecordedResults'] return finish('recordsIncomplete', 'recoverRecords', '実呼出・画像の記録を復旧する。未生成とは確定しない。') if not state['candidates']: if state.get('cropMaterials'): return finish('generatedCropMaterial', 'composeLocal', '局所生成素材あり。原寸で必要範囲を元ページへ合成し、全頁候補を確認する。未生成ではない。') if state['imageState'] != 'ungenerated': return finish('generatedUnavailable', 'recoverImages', '生成実績あり。画像を取り出せないため保存先を復旧する。未生成ではない。') status = 'ungenerated' if state['attempts'] else 'unattempted' if state['limitReached'] or generation_stop is not None: note = f"画像なし。構成保持{state['initialAttempts']}回、レイアウト変更{state['layoutChangedAttempts']}回。" if generation_stop: note += generation_stop['reason'] + '。' return finish(status, 'reportAndContinue', note + 'この頁の状態を報告して他頁を続ける。') if state['attempts'] and state['attempts'][-1]['outcome'] == 'technicalFailure': return finish(status, 'recoverCall', '技術障害の実行状態と既出力を確認し復旧する。試行回数に加算しない。') if state['nextPhase'] == 'layoutChanged': return finish(status, 'reviseLayoutAndGenerate', '原文・キャラデザを保ってレイアウトを変更し、生成を続ける。') return finish(status, 'clarifyAndGenerate' if state['attempts'] else 'generate', '構成をできるだけ保ち、前の返答を確認して指示の曖昧さ・矛盾を正当に明確化し、生成を続ける。') basis = judgment_basis(root) eligible = [c for c in state['candidates'] if eligible_candidate(root, c['candidate'], basis)] result['eligibleCandidates'] = [c['candidate'] for c in eligible] if not eligible: return finish('generatedForOtherSource', 'checkCurrentSource', '生成実績あり。現在の原資料に対応する候補がないため、資料の版と候補を照合する。') pending, qualified = [], [] for row in eligible: name = row['candidate'] try: checked_candidate(root, name, allow_remaining=True) if read_json(root / 'records' / f'{name}-observation.json')['decision'] == 'retain': qualified.append(name) except (ValueError, OSError, KeyError, TypeError) as error: pending.append({'candidate': name, 'reason': str(error)}) result['qualifyingCandidates'] = qualified result['noCandidateMeetsCriteria'] = False if qualified else None if pending else True selected_path = root / 'pages' / f'P{number:02}.png' selected_hash = digest(selected_path) if selected_path.is_file() else None for path in sorted((root / 'records').glob(f'P{number:02}-selection-*.json'), reverse=True): try: record = read_json(path) name = record['comparison']['candidate'] candidate, record = checked_selection_record(root, name, {'path': str(path), 'sha256': digest(path)}) if digest(candidate) != selected_hash: continue result.update(selectedCandidate=name, unresolvedDefects=record['comparison']['unresolvedDefects'], selectionRecord={'path': str(path), 'sha256': digest(path)}, selectionStatus=record['selectionStatus'], noCandidateMeetsCriteria=not qualifying_candidates(root, record['comparison'])) finish('selectedWithRemainingCorrections' if result['unresolvedDefects'] else 'selected', 'continueNextPage', '') result['reportText'] = record['reportText'] return result except (ValueError, OSError, KeyError, TypeError) as error: result.setdefault('invalidSelectionRecords', []).append({'path': str(path), 'reason': str(error)}) continue # Keep historical records, but do not let them end current work. if not state['limitReached'] and generation_stop is None: matching = [c['candidate'] for c in eligible if c['imageSha256'] == selected_hash and c['candidate'] in qualified] if matching and len(eligible) == 1: result.update(selectedCandidate=matching[0], selectionStatus='complete') return finish('selected', 'continueNextPage', f"修正{state['correctionAttempts']}回で{matching[0]}を通常採用。修正必須の問題なし。") if pending: result['pendingReadings'] = pending return finish('generatedUnselected', 'readCandidates', '生成済み候補あり。未確認・資料更新後の候補を実画像で確認する。') if state['limitReached'] or generation_stop is not None: return finish('generatedUnselected', 'compareCandidates', '生成済み候補をすべて比較して選定する。' + ('通常の採用基準を満たす候補なし。最良の版を残件つきで選び報告する。' if not qualified else '採用基準を満たす候補から選ぶ。')) if qualified: if len(eligible) > 1: return finish('generatedUnselected', 'compareCandidates', '通常採用でも全候補を比較し、修正目的の結果と構図・演技の後退を記録して --comparison で選ぶ。追加生成しない。') return finish('generatedUnselected', 'selectCandidate', '採用基準を満たす生成済み候補を採用して次へ進む。追加生成しない。') if state['attempts'][-1]['outcome'] == 'technicalFailure': return finish('generatedUnselected', 'recoverCall', '生成済み候補を保存したまま、技術障害の実行状態・既出力を確認して復旧する。') return finish('generatedUnselected', 'reviseAndGenerate', f"修正必須の問題が残る。修正{state['correctionAttempts']}/10回。" '所見と前の返答から修正範囲・指示を見直す。原資料から全頁再生成、または切り出し生成と合成で続ける。同じ指示をそのまま繰り返さない。') def production_status(root, expected_pages): if expected_pages < 1: raise ValueError('Expected whole-book page count must be positive.') pages = [page_status(root, f'P{number:02}') for number in range(1, expected_pages + 1)] return {'pages': pages, 'fullySelected': all(p['status'] in ('selected', 'selectedWithRemainingCorrections') for p in pages), 'fullyCorrected': all(p['status'] == 'selected' for p in pages), 'artisticQualityAutomaticallyAssessed': False, 'humanAcceptance': False} def verify_delivery(root, manifest_path, reading_path, expected_pages): """Read-only integrity check for the existing whole-book reading step. A successful result does not judge whether the image observations are true. The producers remain responsible for actual artistic/manuscript judgments. """ root = Path(root).resolve() if expected_pages < 1: raise ValueError('Expected whole-book page count must be positive.') manifest = read_json(manifest_path) rows = manifest if isinstance(manifest, list) else manifest['selectedPages'] if len(rows) != expected_pages or sorted(r['page'] for r in rows) != list(range(1, expected_pages+1)): raise ValueError('Whole-book selected-page coverage is incomplete or duplicated.') report = read_json(reading_path) source_hash = material(read_json(root/'production-inputs.json')['source'], 'source', root)['sha256'] if report.get('sourceSha256') != source_hash: raise ValueError('Whole-book reading must use the actual current source.') if report.get('decision') not in ('retain', WITH_REMAINING) or ( report.get('decision') == 'retain' and report.get('unresolved') != []): raise ValueError('Whole-book reading is pending or contains unresolved findings; not a completed manuscript.') accepted_minor_differences(report) if not isinstance(report.get('sequenceRead'), str) or not report['sequenceRead'].strip(): raise ValueError('Read actual staging, time and continuity across the whole sequence.') reads = report.get('pages', []) if len(reads) != expected_pages or sorted(r['page'] for r in reads) != list(range(1, expected_pages+1)): raise ValueError('Whole-book image-reading coverage is incomplete or duplicated.') by_page = {r['page']: r for r in reads} parallel = len({r.get('producerThreadId') for r in rows if r.get('producerThreadId')}) > 1 remaining, delivery_notes = [], [] for row in rows: if int(row['candidate'].split('-')[0][1:]) != row['page']: raise ValueError('Delivery page number differs from its assessed candidate.') observation_path = Path(row['observation']).resolve(strict=True) if observation_path.name != f"{row['candidate']}-observation.json": raise ValueError('Delivery observation differs from its assessed candidate.') producer_root = observation_path.parent.parent if material(read_json(producer_root/'production-inputs.json')['source'], 'source', producer_root)['sha256'] != source_hash: raise ValueError('Delivery candidate belongs to a different source.') selection = None if row.get('selectionRecord'): candidate, selection = checked_selection_record(producer_root, row['candidate'], row['selectionRecord']) defects = selection['comparison']['unresolvedDefects'] if row.get('selectionStatus') != selection['selectionStatus'] or row.get('unresolvedDefects') != defects: raise ValueError('Delivery manifest must preserve selection status and every remaining correction.') else: _, candidate = checked_candidate(producer_root, row['candidate']) state = attempt_state(producer_root, row['candidate']) basis = judgment_basis(producer_root) if sum(eligible_candidate(producer_root, c['candidate'], basis) for c in state['candidates']) > 1: raise ValueError('Multiple delivery candidates require the preserved full comparison selectionRecord.') defects = [] if row.get('selectionStatus', 'complete') != 'complete' or row.get('unresolvedDefects', []) != []: raise ValueError('Remaining corrections require an explicit candidate selection record.') selected = Path(row.get('original') or row.get('image')).resolve(strict=True) image_hash = digest(candidate) if digest(selected) != image_hash or row['sha256'] != image_hash: raise ValueError(f"P{row['page']:02}: delivery image differs from the assessed original.") reading = by_page[row['page']] expected_decision = WITH_REMAINING if defects else 'retain' if (reading.get('imageSha256') != image_hash or reading.get('decision') != expected_decision or reading.get('unresolved') != defects): raise ValueError(f"P{row['page']:02}: whole-book image reading is missing, failed or unresolved.") if defects: if reading.get('deliveryNote') != selection['reportText']: raise ValueError('Delivery report must state the selected version, attempt count and remaining corrections.') remaining.extend(f"P{row['page']:02}:{defect}" for defect in defects) delivery_notes.append(selection['reportText']) accepted_minor_differences(reading) if parallel and (not reading.get('readerThreadId') or reading['readerThreadId'] == row.get('producerThreadId')): raise ValueError('Use the existing other production threads for the final image reading; the parent only aggregates.') if (report.get('decision') != (WITH_REMAINING if remaining else 'retain') or report.get('unresolved') != remaining): raise ValueError('Whole-book report must preserve the remaining corrections of all selected pages.') return {'verifiedPages': expected_pages, 'recordIntegrityVerified': True, 'fullyCorrected': not remaining, 'unresolved': remaining, 'deliveryNotes': delivery_notes, 'artisticQualityAutomaticallyAssessed': False, 'humanAcceptance': False} def main(): parser = argparse.ArgumentParser(description=__doc__) sub = parser.add_subparsers(dest='action', required=True) for command in ('prepare', 'archive', 'compose-local', 'record-repair-base', 'reading-inputs', 'comparison-inputs', 'record-reading', 'record-attempt', 'attempt-state', 'page-status', 'select'): item = sub.add_parser(command) item.add_argument('root', type=Path) item.add_argument('candidate') if command == 'prepare': item.add_argument('page_spec', type=Path) item.add_argument('--edit', type=Path, help='Immutable source page. Only its --crop region is sent to the image tool.') item.add_argument('--crop', type=int, nargs=4, metavar=('LEFT', 'TOP', 'RIGHT', 'BOTTOM'), help='Native context crop, exclusive right/bottom. Required with --edit; no whole-page editing.') item.add_argument('--edit-scope', help='Required with --edit: the necessary correction and the composition/content to preserve.') item.add_argument('--reference', type=Path, action='append', default=[], help='Original supplied image registered in judgmentMaterials; never a generated manuscript.') item.add_argument('--design', type=Path, action='append', default=[], help='Actual supplied design(s) for all characters and costumes visible on this page; defaults to all supplied designs.') item.add_argument('--pack-references', type=int, metavar='MAX_PATHS', help='When explicitly authorized, tile original pixels to fit the actual tool path limit; keep every original and a separate edit target.') item.add_argument('--reference-priority', type=Path, action='append', default=[], metavar='ORIGINAL', help='Lowest paper priority first: choose only the original images needed for minimum packing; leave the others as separate inputs.') item.add_argument('--reference-board-format', choices=('png', 'webp'), default='png', help='Lossless board encoding for technical input recovery; never resize, crop, or recolor original pixels.') item.add_argument('--reference-board-count', type=int, default=1, help='After an actual large-board input failure, use smaller composite boards; choose only the required extra low-priority originals.') elif command == 'archive': item.add_argument('source', type=Path) elif command == 'compose-local': item.add_argument('crop_call', help='Generated crop call name, distinct from this new page candidate.') item.add_argument('--mask', type=Path, required=True, help='Full native page-sized binary L PNG allowed mask.') item.add_argument('--alpha', type=Path, help='Optional L PNG blend alpha confined inside --mask.') item.add_argument('--feather', type=float, default=0, help='Optional inward feather in native pixels.') elif command == 'record-repair-base': item.add_argument('input', type=Path, help='All-candidate comparison; preserve rejection and do not adopt.') elif command == 'record-reading': item.add_argument('input', type=Path) item.add_argument('--reason', help='Required when rereading; keep previous records unchanged.') elif command == 'record-attempt': item.add_argument('input', type=Path, help='Actual tool result JSON; archive image outputs first.') elif command == 'select': modes = item.add_mutually_exclusive_group() modes.add_argument('--comparison', type=Path, help='Image-based comparison of every saved candidate for normal selection before the limit.') modes.add_argument('--at-limit', type=Path, help='Comparison of all saved candidates after 10 correction calls; keep unresolved defects.') modes.add_argument('--after-stop', type=Path, help='Same full comparison with an evidenced exceptional generationStop; not a noImage shortcut.') elif command == 'page-status': item.add_argument('--stop', type=Path, help='Evidenced exceptional generation stop JSON, if applicable.') status = sub.add_parser('production-status') status.add_argument('root', type=Path) status.add_argument('--pages', type=int, required=True) delivery = sub.add_parser('verify-delivery') delivery.add_argument('root', type=Path) delivery.add_argument('manifest', type=Path) delivery.add_argument('reading', type=Path) delivery.add_argument('--pages', type=int, required=True) composition = sub.add_parser('composition-reading-inputs') composition.add_argument('plan', type=Path) args = parser.parse_args() try: if args.action == 'composition-reading-inputs': result = composition_reading_inputs(args.plan) elif args.action == 'prepare': result = prepare(args.root, args.candidate, args.page_spec, args.edit, args.reference, active_designs=args.design, edit_scope=args.edit_scope, pack_references=args.pack_references, reference_priority=args.reference_priority, reference_board_format=args.reference_board_format, reference_board_count=args.reference_board_count, crop_box=args.crop) elif args.action == 'archive': result = archive(args.root, args.candidate, args.source) elif args.action == 'compose-local': result = compose_local(args.root, args.candidate, args.crop_call, args.mask, args.alpha, args.feather) elif args.action == 'record-repair-base': result = record_repair_base(args.root, args.candidate, args.input) elif args.action == 'reading-inputs': result = reading_inputs(args.root, args.candidate) elif args.action == 'comparison-inputs': result = comparison_inputs(args.root, args.candidate) elif args.action == 'record-reading': result = record_reading(args.root, args.candidate, args.input, args.reason) elif args.action == 'record-attempt': result = record_attempt(args.root, args.candidate, args.input) elif args.action == 'attempt-state': result = attempt_state(args.root, args.candidate) elif args.action == 'page-status': result = page_status(args.root, args.candidate, read_json(args.stop) if args.stop else None) elif args.action == 'production-status': result = production_status(args.root, args.pages) elif args.action == 'verify-delivery': result = verify_delivery(args.root, args.manifest, args.reading, args.pages) else: result = select(args.root, args.candidate, args.at_limit, args.after_stop, args.comparison) except (ValueError, OSError, KeyError, TypeError) as error: parser.exit(1, str(error) + '\n') print(json.dumps(result, ensure_ascii=False)) if __name__ == '__main__': sys.stdout.reconfigure(encoding='utf-8') main()