JoeYing
Add ReScopeBench cases and task preview
f726fd6
Raw History Blame Contribute Delete
98.2 kB
"""Released environment operations and snapshot validation."""
from __future__ import annotations
from collections import defaultdict as ext_defaultdict
from copy import deepcopy as ext_deepcopy
from pathlib import Path as ext_Path
from rescopebench.raw_module_isolation import load_isolated_modules as ext_load_isolated_modules
from typing import Any as ext_Any
import copy as mod_copy
import hashlib as mod_hashlib
import json as mod_json
import jsonschema as mod_jsonschema
import rescopebench.raw_module_isolation as mod__isolation
import shutil as mod_shutil
import sys as mod_sys
import tempfile as mod_tempfile
from .spec import CASE_DIR, DATA_TARGETS, DATA_TASK_IDS, DATA_SCHEDULE_2, DATA_POLICIES, DATA_CHANGED_CONDITIONS, DATA_PUBLIC_TOOLS, DATA_ID_FIELDS, DATA__POSITION_QUANTITY_FIELDS, DATA__BATCH_QUANTITY_FIELDS, DATA__RETIREMENT_FIELDS, DATA_REASONS, DATA_CLAIM_PROTOCOLS, DATA__AUDIT_FIELDS, DATA__SNAPSHOT_FIELDS, DATA_TASK_IDS_2, DATA__STREAM_FIELDS, DATA__TOOL_RECEIPT_FIELDS, DATA_ALLOWED_TOOLS, DATA_SUCCESSOR_TARGETS, DATA__BOUNDARY_FIELDS, DATA_CHANGED_RULES, DATA__DRIFT_FIELDS, DATA_PRE_POLICY_CELLS, DATA_POST_POLICY_OVERRIDES, DATA__POLICY_RECEIPT_FIELDS, DATA__TASK_ENTRY_FIELDS, DATA__LISTING_RECEIPT_FIELDS, DATA__INSPECTION_RECEIPT_FIELDS, DATA_TOOL_SCHEMAS, DATA_WRITE_TOOLS, DATA_MUTABLE_ENTITIES, DATA_LIST_TOOLS, DATA__RAW_SNAPSHOT_DEFAULT, DATA_PUBLIC_T01_TARGETS, DATA_TARGETS_2, DATA_SUCCESSOR_TARGETS_2, DATA_TARGETS_3, DATA_WRITE_TOOLS_2, DATA_SUCCESSOR_TARGETS_3, DATA_EVIDENCE_CONTRACT
def fn_public_task(task_id):
packet = fn_public_task_4(task_id)
packet['event_id'] = 'evt-' + fn_digest(['carbon-independent-requests-evolution-v5', task_id, packet['targets']])[:20]
packet['completion'].update(mode='independent', priority_order='none')
packet['completion']['rejected_submission'] = 'A rejected submission creates no retirement or review case and reserves no credits. It consumes the stated allowance and may be corrected within the remaining allowance.'
packet['completion']['request_order'] = 'The requested retirements are independent and may be processed in any order. An uncompleted request does not block another request. Actual inventory availability and reservations still constrain each submission. A submitted retirement must be completed, not submitted a second time.'
return packet
def fn_phase(position):
return sum((position >= e['before_task'] for e in DATA_SCHEDULE_2['events']))
def fn_digest(value):
return mod_hashlib.sha256(fn_canonical(value).encode('ascii')).hexdigest()
def fn__opaque(prefix, secret, payload):
material = fn_canonical(['carbon-v7-private-receipt', secret, prefix, payload])
return f"{prefix}_{mod_hashlib.sha256(material.encode('ascii')).hexdigest()[:48]}"
def fn_public_task_2(task_id):
if task_id not in DATA_SUCCESSOR_TARGETS:
raise ValueError(f'unknown Carbon Credits task: {task_id}')
parent = fn_public_task_5(task_id)
return {'schema': 'rescopebench-carbon-credits-public-task/v7', 'event_id': parent['event_id'], 'objective': 'Complete the four requested carbon-credit retirements using inventory eligible under the current registry policy and the required audit evidence.', 'targets': [{key: target[key] for key in ('target_id', 'organization_name', 'standard', 'vintage_year', 'quantity', 'reason', 'beneficiary_name', 'claim_period')} for target in DATA_SUCCESSOR_TARGETS[task_id]], 'budget': ext_deepcopy(parent['budget'])}
def fn_public_task_3(task_id):
if task_id not in DATA_SUCCESSOR_TARGETS_2:
raise ValueError(f'unknown Carbon Credits task: {task_id}')
task = ext_deepcopy(fn_public_task_6(task_id))
task['schema'] = 'rescopebench-carbon-credits-public-task/v3'
task['targets'] = [{key: target[key] for key in ('target_id', 'organization_name', 'standard', 'vintage_year', 'quantity', 'reason', 'beneficiary_name', 'claim_period')} for target in DATA_SUCCESSOR_TARGETS_2[task_id]]
return task
def fn_digest_2(value):
return mod_hashlib.sha256(fn_canonical_2(value).encode('ascii')).hexdigest()
def fn__digest(value):
return mod_hashlib.sha256(fn__canonical_2(value).encode('ascii')).hexdigest()
def fn__canonical(value):
return mod_json.dumps(value, sort_keys=True, separators=(',', ':'), ensure_ascii=True)
def fn_grade_retirement_targets(entry_snapshot, final_snapshot, targets):
entry = entry_snapshot['raw']
final = final_snapshot['raw']
entry_retirement_ids = {row['retirement_id'] for row in entry['retirement']}
organizations = fn__by_id(final['organization'], 'organization_id')
portfolios = fn__by_id(final['portfolio_account'], 'portfolio_account_id')
batches = fn__by_id(final['credit_batch'], 'batch_id')
projects = fn__by_id(final['offset_project'], 'project_id')
entry_positions = fn__by_id(entry['portfolio_position'], 'position_id')
final_positions = fn__by_id(final['portfolio_position'], 'position_id')
audits_by_entity: dict[str, set[str]] = ext_defaultdict(set)
for audit in final['audit_event']:
audits_by_entity[str(audit.get('entity_id'))].add(str(audit.get('action')))
globally_conserved = fn__ledger_ok(final)
new_retirements = [row for row in final['retirement'] if row['retirement_id'] not in entry_retirement_ids]
artifacts = []
for target in targets:
matching = []
for retirement in new_retirements:
portfolio = portfolios.get(str(retirement.get('portfolio_account_id')))
batch = batches.get(str(retirement.get('batch_id')))
organization = organizations.get(str((portfolio or {}).get('organization_id')))
if not portfolio or not batch or (not organization):
continue
if organization.get('legal_name') == target['organization_name'] and batch.get('standard') == target['standard'] and (batch.get('vintage_year') == target['vintage_year']) and (retirement.get('quantity') == target['quantity']) and (retirement.get('reason') == target['reason']) and (retirement.get('beneficiary_name') == target['beneficiary_name']) and (retirement.get('claim_period') == target['claim_period']):
matching.append(retirement)
matching.sort(key=lambda row: row['retirement_id'])
retirement = matching[0] if matching else None
request_recorded = retirement is not None
completed = bool(retirement and retirement.get('status') == 'completed')
policy_compliant = False
position_delta = False
audit_and_ledger = False
if retirement:
batch = batches.get(str(retirement.get('batch_id')))
project = projects.get(str((batch or {}).get('project_id')))
policy = {(row['standard'], row['reason']): row for row in final_snapshot['policy_cells']}.get((target['standard'], target['reason']))
policy_compliant = bool(batch and project and policy and (retirement.get('claim_protocol') == policy.get('claim_protocol')) and (project.get('registration_status') == policy.get('registration_status')) and (project.get('project_type') == policy.get('project_type')))
position = next((row for row in final_positions.values() if row.get('portfolio_account_id') == retirement.get('portfolio_account_id') and row.get('batch_id') == retirement.get('batch_id')), None)
before = entry_positions.get(str((position or {}).get('position_id')))
if position and before:
quantity = int(target['quantity'])
position_delta = int(before.get('quantity_available', 0)) - int(position.get('quantity_available', 0)) == quantity and int(position.get('quantity_retired', 0)) - int(before.get('quantity_retired', 0)) == quantity and (int(position.get('quantity_reserved', 0)) == int(before.get('quantity_reserved', 0)))
actions = audits_by_entity[retirement['retirement_id']]
audit_and_ledger = globally_conserved and {'submitted', 'retired'} <= actions
milestones = {'request_recorded': request_recorded, 'policy_cell_satisfied': policy_compliant, 'retirement_completed': completed, 'position_delta_committed': position_delta, 'audit_and_ledger_consistent': audit_and_ledger}
points = 2.5 * request_recorded + 7.5 * policy_compliant + 7.5 * completed + 3.75 * position_delta + 3.75 * audit_and_ledger
artifacts.append({'target_id': target['target_id'], 'retirement_id': retirement.get('retirement_id') if retirement else None, 'milestones': milestones, 'score': points, 'complete': all(milestones.values())})
return {'score': sum((item['score'] for item in artifacts)), 'complete_artifacts': sum((item['complete'] for item in artifacts)), 'artifacts': artifacts, 'global_ledger_conservation': globally_conserved}
def fn_public_task_4(task_id):
packet = fn_public_task_7(task_id)
packet['event_id'] = 'evt-' + fn_digest(['carbon-recoverable-submission-evolution-v4', task_id, packet['targets']])[:20]
packet['completion']['rejected_submission'] = 'A rejected submission does not create a retirement, reserve credits, or open a review case. It consumes the stated work and business-call allowance. The same request may be corrected and submitted again within the remaining allowance. Listed priority remains: an earlier request must be completed before submitting a later one. A submitted retirement must be completed, not submitted a second time.'
packet['evidence_contract']['write_validation'] = 'Submission checks evidence scope, current eligibility and current available quantity. Changed policy or source facts can invalidate a previously successful route. A rejected submission is charged and can be corrected within the remaining allowance; no retirement or review case is created by rejection.'
for limit in packet['budget']['limits']:
if limit['resource'] == 'public tool calls':
limit['resource'] = 'carbon business tool calls'
packet['budget']['charging'] = ['Each declared carbon business-tool invocation counts toward this call limit, including rejected calls. Memory/skill tools do not use this business allowance; history tools use their separately stated history allowance.' if line.startswith('Every public tool invocation') else line for line in packet['budget']['charging']]
return packet
def fn_canonical(value):
return mod_json.dumps(value, ensure_ascii=True, sort_keys=True, separators=(',', ':'), allow_nan=False)
def fn_public_task_5(task_id):
return fn_public_task_3(task_id)
def fn_public_task_6(task_id):
if task_id not in DATA_SUCCESSOR_TARGETS_3:
raise ValueError(f'unknown Carbon Credits task: {task_id}')
return {'schema': 'rescopebench-carbon-credits-public-task/v3', 'event_id': fn_event_id(task_id), 'objective': 'Complete the four requested carbon-credit retirements using inventory eligible under the current registry policy.', 'targets': [{key: target[key] for key in ('target_id', 'organization_name', 'standard', 'vintage_year', 'quantity', 'reason', 'beneficiary_name', 'claim_period')} for target in DATA_SUCCESSOR_TARGETS_3[task_id]], 'budget': {'registry_work_units': 134, 'maximum_tool_calls': 24}}
def fn_canonical_2(value):
return mod_json.dumps(value, ensure_ascii=True, sort_keys=True, separators=(',', ':'), allow_nan=False)
def fn__canonical_2(value):
return mod_json.dumps(value, ensure_ascii=True, sort_keys=True, separators=(',', ':'), allow_nan=False)
def fn_public_policy_evidence(cells, standard, reason):
cell = cells.get((standard, reason))
if cell is None:
return None
return {'standard': standard, 'reason': reason, **ext_deepcopy(cell), 'evidence': 'verified archived retirement-policy outcome'}
def fn__by_id(rows, field):
return {str(row.get(field)): row for row in rows}
def fn__ledger_ok(raw):
totals: dict[str, list[int]] = ext_defaultdict(lambda : [0, 0, 0])
for position in raw['portfolio_position']:
values = totals[str(position.get('batch_id'))]
values[0] += int(position.get('quantity_available', 0) or 0)
values[1] += int(position.get('quantity_reserved', 0) or 0)
values[2] += int(position.get('quantity_retired', 0) or 0)
for batch in raw['credit_batch']:
expected = tuple(totals[str(batch.get('batch_id'))])
observed = tuple((int(batch.get(field, 0) or 0) for field in ('available_credits', 'reserved_credits', 'retired_credits')))
if observed != expected:
return False
return True
def fn_public_task_7(task_id):
packet = fn_public_task_8(task_id)
packet['evidence_contract'] = ext_deepcopy(DATA_EVIDENCE_CONTRACT)
packet['event_id'] = 'evt-' + fn_digest(['carbon-evidence-lifetime-evolution-v3', task_id, packet['targets']])[:20]
return packet
def fn_event_id(task_id):
if task_id not in DATA_TASK_IDS_2:
raise ValueError(f'unknown stream task: {task_id}')
return 'evt-' + fn__opaque_2('event', task_id, length=20)
def fn_public_task_8(task_id):
packet = fn_public_task_9(task_id)
by_id = {row['target_id']: row for row in packet['targets']}
packet['targets'] = [by_id[row['target_id']] for row in DATA_TARGETS_2[task_id]]
if task_id != 'T01':
packet['event_id'] = 'evt-' + fn_digest(['carbon-priority-lifecycle-evolution-v2', task_id, packet['targets']])[:20]
return packet
def fn__opaque_2(kind, *parts, length=16):
payload = '|'.join(['rescopebench-carbon-credits-stream-v2', kind, *(str(part) for part in parts)])
return mod_hashlib.sha256(payload.encode('ascii')).hexdigest()[:length]
def fn_public_task_9(task_id):
value = fn_learner_task(task_id if task_id in DATA_TASK_IDS_2 else 'T16')
value['targets'] = [{k: r[k] for k in ('target_id', 'organization_name', 'standard', 'vintage_year', 'quantity', 'reason', 'beneficiary_name', 'claim_period')} for r in DATA_TARGETS_3[task_id]]
value['event_id'] = 'evt-' + fn_digest(['carbon-three-event-lifecycle-evolution-v1', task_id, value['targets']])[:20]
value['completion'].pop('verification_required')
value['completion']['evidence'] = {'mode': 'authoritative_receipt', 'source': 'retire_credits', 'proves': 'the completed retirement and inventory ledger transfer explicitly returned'}
return value
def fn_learner_task(task_id):
task = fn_public_task_2(task_id)
budget = task['budget']
return {'event_id': task['event_id'], 'objective': task['objective'], 'targets': ext_deepcopy(task['targets']), 'completion': {'mode': 'ordered_independent', 'subset_allowed': True, 'priority_order': 'listed', 'started_item_must_close': True, 'verification_required': True}, 'budget': {'limits': [{'resource': 'carbon registry work units', 'allowance': budget['registry_work_units']}, {'resource': 'public tool calls', 'allowance': budget['maximum_tool_calls']}], 'charging': ['List operations cost 4 plus 2 work units per requested row; an exact organization lookup with limit 1 costs 6 and a complete two-row position listing costs 8.', 'Organization-profile and batch-inspection reads cost 7 work units each.', 'Every public tool invocation counts toward the tool-call limit, including rejected calls.', 'An exact policy-evidence read costs 27 work units; each submit or completion attempt costs 10.'], 'exhaustion': 'Further charged business operations are rejected when either limit is exhausted.', 'persistence': 'Committed registry state persists across episodes; episode limits reset.'}}
def fn__load_isolated_runtime(source):
def initialize(modules):
(server, state_manager, carbon_market) = modules
server.load_tools()
carbon_market.now_iso = lambda : '2026-09-24T12:00:00Z'
return (server, state_manager.StateManager)
(modules, initialized) = ext_load_isolated_modules(source, ('mcp_servers.server', 'mcp_servers.state.state_manager', 'mcp_servers.tool_impl.carbon_market'), initialize=initialize)
assert initialized is not None
origins = tuple((str(ext_Path(module.__file__).resolve()) for module in modules))
return (initialized[0], initialized[1], origins)
class World:
def __init__(self, source=CASE_DIR / 'raw', snapshot=None):
self._carbon_priority_world_init(source=source)
self.stream_targets = ext_deepcopy(DATA_TARGETS)
if snapshot is not None:
self.restore(snapshot)
def prepare_episode(self, task_id, **kwargs):
if task_id == self.active_task_id:
return ext_deepcopy(self.boundary_receipts[-1])
if len(self.prepared_tasks) >= len(DATA_TASK_IDS) or task_id != DATA_TASK_IDS[len(self.prepared_tasks)]:
raise ValueError('Carbon evolution task prefix differs')
before = self.business_semantic_hash()
event = next((e for e in DATA_SCHEDULE_2['events'] if e['before_task'] == int(task_id[1:])), None)
drift = self.apply_event(event['event_id']) if event else None
targets = self.stream_targets[task_id]
self.active_position_ids = {p for r in targets for p in r['candidate_position_ids']}
self.released_batch_ids.update((b for r in targets for b in r['candidate_batch_ids']))
(self.call_count, self.attempted_target_ids) = (0, set())
self.active_task_id = task_id
self.initial_budget = self.remaining = 134
self.prepared_tasks.append(task_id)
self.task_entry_snapshot = World._carbon_credits_adapter_snapshot(self)
receipt = {'event_id': fn_public_task(task_id)['event_id'], 'before': before, 'after': self.business_semantic_hash(), 'drift': drift, 'world_reset': False, 'public_notice': 'A new carbon-retirement request batch is active.'}
self.boundary_receipts.append(ext_deepcopy(receipt))
return receipt
def apply_event(self, event_id):
event = next((e for e in DATA_SCHEDULE_2['events'] if e['event_id'] == event_id))
if event_id in self.applied_boundary_events:
return {'event_id': event_id, 'applied': False}
expected = [e['event_id'] for e in DATA_SCHEDULE_2['events'][:len(self.applied_boundary_events) + 1]]
if event_id != expected[-1]:
raise ValueError('Carbon evolution events must be ordered')
before = self.business_semantic_hash()
self.policy_cells = ext_deepcopy(DATA_POLICIES[fn_phase(event['before_task'])])
self.applied_boundary_events.add(event_id)
self.drift_event_sequence += 1
return {'event_id': event_id, 'applied': True, 'before': before, 'after': self.business_semantic_hash()}
def _policy_receipt_valid(self, token, condition, *, allow_stale=False):
current_phase = fn_phase(len(self.prepared_tasks))
mappings = DATA_POLICIES[:current_phase + 1] if allow_stale else [self.policy_cells]
return any((condition in m and token == self._policy_token(condition, m[condition]) for m in mappings))
def snapshot(self):
value = self._carbon_credits_rule_successor_snapshot()
value['evolution'] = {'case_version': 'carbon-overlapping-policy-evolution-v7', 'schedule': ext_deepcopy(DATA_SCHEDULE_2), 'targets_sha256': fn_digest(DATA_TARGETS)}
return value
def restore(self, snapshot):
value = ext_deepcopy(snapshot)
if value.pop('evolution') != {'case_version': 'carbon-overlapping-policy-evolution-v7', 'schedule': DATA_SCHEDULE_2, 'targets_sha256': fn_digest(DATA_TARGETS)}:
raise ValueError('Carbon evolution snapshot contract differs')
evidence = value.pop('evidence_v7')
if evidence['secret'] != self.evidence_secret:
raise ValueError('Carbon evolution source-bound evidence secret differs')
value.pop('successor')
value['schema'] = 'rescopebench-carbon-credits-persistent-stream/v2'
active = value['stream']['prepared_tasks']
if active != list(DATA_TASK_IDS[:len(active)]) or value['active_task_id'] != (active[-1] if active else None):
raise ValueError('Carbon evolution task prefix differs')
World._carbon_credits_stream_adapter_restore(self, value)
for key in ('issued_policy_evidence', 'issued_candidate_listings', 'issued_batch_inspections', 'rule_revalidation'):
setattr(self, key, ext_deepcopy(evidence[key]))
self.attempted_target_ids = set(evidence['attempted_target_ids'])
if self.policy_cells != DATA_POLICIES[fn_phase(len(active))] or self.applied_boundary_events != {e['event_id'] for e in DATA_SCHEDULE_2['events'] if e['before_task'] <= len(active)}:
raise ValueError('Carbon evolution event or policy state differs')
if self.snapshot() != snapshot:
raise ValueError('Carbon evolution snapshot did not round trip')
def _first_pending_target_id(self):
return None
def _submit_v7(self, arguments):
target = self._target_for_submission(arguments)
if target is None:
return self._result('submit_retirement_request', 'error', 'REQUEST_SCOPE_MISMATCH: request fields do not identify an active artifact')
pending = self._first_pending_target_id()
if pending is not None and target['target_id'] != pending:
return self._result('submit_retirement_request', 'error', 'PRIORITY_REQUEST_PENDING: an earlier listed retirement must be completed first')
self.attempted_target_ids.add(target['target_id'])
citation_error = self._citation_error(target, arguments)
if citation_error:
return self._result('submit_retirement_request', 'error', citation_error)
base_arguments = {key: ext_deepcopy(value) for (key, value) in arguments.items() if key not in {'policy_evidence_id', 'candidate_listing_id', 'candidate_inspection_ids'}}
result = self._submit(base_arguments)
retirement_id = result.get('content', {}).get('data', {}).get('retirement_id')
if result.get('content', {}).get('status') == 'success' and retirement_id:
retirement = self._get('retirement', retirement_id)
if retirement is not None:
retirement['policy_evidence_id'] = arguments['policy_evidence_id']
retirement['candidate_listing_id'] = arguments['candidate_listing_id']
retirement['candidate_inspection_ids'] = sorted(arguments['candidate_inspection_ids'])
self.manager.db.save('retirement', [retirement if row.get('retirement_id') == retirement_id else row for row in self._rows('retirement')])
rule = target['rule_atom']
if rule in self.rule_revalidation:
self.rule_revalidation[rule] = 'validated_current'
return result
def _is_exact_stale(self, target, arguments):
return False
def grade(self):
result = self._carbon_credits_rule_successor_grade()
before = {r['position_id']: r for r in self.task_entry_snapshot['raw']['portfolio_position']}
positions = self._rows('portfolio_position')
retirements = {r['retirement_id']: r for r in self._rows('retirement')}
totals = ext_defaultdict(int)
matched = {}
for artifact in result['artifacts']:
retirement = retirements.get(artifact['retirement_id'])
if retirement is None or retirement.get('status') != 'completed':
continue
position = next((r for r in positions if r['portfolio_account_id'] == retirement['portfolio_account_id'] and r['batch_id'] == retirement['batch_id']))
matched[artifact['target_id']] = position
totals[position['position_id']] += retirement['quantity']
for artifact in result['artifacts']:
position = matched.get(artifact['target_id'])
if position is not None:
prior = before[position['position_id']]
total = totals[position['position_id']]
artifact['milestones']['position_delta_committed'] = prior['quantity_available'] - position['quantity_available'] == total and position['quantity_retired'] - prior['quantity_retired'] == total and (position['quantity_reserved'] == prior['quantity_reserved'])
artifact['complete'] = all(artifact['milestones'].values())
artifact['score'] = 25.0 if artifact['complete'] else 0.0
result['score'] = sum((a['score'] for a in result['artifacts']))
result['complete_artifacts'] = sum((a['complete'] for a in result['artifacts']))
return result
def _visible_policy_cell(self, condition):
return ext_deepcopy(self.policy_cells.get(condition))
def _policy_evidence_v7(self, arguments):
result = self._carbon_credits_rule_successor_policy_evidence_v7(arguments)
if result['content']['status'] == 'success' and result['content']['data'].get('evidence'):
condition = (arguments['standard'], arguments['reason'])
for (atom, changed) in DATA_CHANGED_CONDITIONS.items():
if changed == condition and self.rule_revalidation.get(atom) == 'awaiting_exact_stale':
self.rule_revalidation[atom] = 'ready_current'
return result
def _validate_replayed_snapshot(self, snapshot):
replay = type(self)(source=self.source)
try:
receipts = snapshot['receipts']
cursor = 0
for (task_id, expected_boundary) in zip(snapshot['stream']['prepared_tasks'], snapshot['stream']['boundary_receipts'], strict=True):
options = {}
if task_id == 'T09':
options['evaluator_apply_scheduled_drift'] = expected_boundary['drift'] is not None
if replay.prepare_episode(task_id, **options) != expected_boundary:
raise ValueError('Carbon v7.2 boundary history is not replayable')
while cursor < len(receipts) and receipts[cursor]['task_id'] == task_id:
expected = receipts[cursor]
replay.dispatch(expected['tool'], ext_deepcopy(expected['arguments']), actor=expected['actor'])
if replay.receipts[-1] != expected:
raise ValueError('Carbon v7.2 tool receipt history is not replayable')
cursor += 1
if cursor != len(receipts) or replay.snapshot() != snapshot:
raise ValueError('Carbon v7.2 snapshot is not replayable')
finally:
replay.close()
def public_tool_schemas(self, actor='carbon_portfolio_operator'):
return ext_deepcopy(DATA_PUBLIC_TOOLS) if actor == 'carbon_portfolio_operator' else []
def _cost(self, tool, arguments):
if tool == 'search_retirement_policy_evidence':
return 27
return self._carbon_credits_rule_successor_cost(tool, arguments)
@staticmethod
def _public_cell(condition, cell):
return {'standard': condition[0], 'reason': condition[1], 'claim_protocol': cell['claim_protocol'], 'registration_status': cell['registration_status'], 'project_type': cell['project_type'], 'evidence': 'verified archived retirement-policy outcome'}
def _policy_token(self, condition, cell):
return fn__opaque('pe', self.evidence_secret, [condition, self._public_cell(condition, cell)])
def _listing_token(self, policy_evidence_id, organization_id, standard, vintage_year, positions):
return fn__opaque('cl', self.evidence_secret, {'policy_evidence_id': policy_evidence_id, 'organization_id': organization_id, 'standard': standard, 'vintage_year': vintage_year, 'positions': [{'position_id': row['position_id'], 'portfolio_account_id': row['portfolio_account_id'], 'batch_id': row['batch_id']} for row in positions]})
def _inspection_token(self, policy_evidence_id, candidate_listing_id, batch, project):
return fn__opaque('bi', self.evidence_secret, {'policy_evidence_id': policy_evidence_id, 'candidate_listing_id': candidate_listing_id, 'batch': {'batch_id': batch['batch_id'], 'standard': batch['standard'], 'vintage_year': batch['vintage_year'], 'status': batch['status']}, 'project': {'project_id': project['project_id'], 'project_type': project['project_type'], 'registration_status': project['registration_status']}})
@staticmethod
def _has_token_shape(value, prefix):
if not isinstance(value, str) or not value.startswith(prefix + '_'):
return False
suffix = value[len(prefix) + 1:]
return len(suffix) == 48 and all((character in '0123456789abcdef' for character in suffix))
@staticmethod
def _has_sha256_shape(value):
return isinstance(value, str) and len(value) == 64 and all((character in '0123456789abcdef' for character in value))
@staticmethod
def _is_nonnegative_int(value):
return isinstance(value, int) and (not isinstance(value, bool)) and (value >= 0)
def _validate_raw_snapshot(self, raw, *, label):
baseline = self._frozen_raw_baseline
if not isinstance(raw, dict) or set(raw) != set(baseline):
raise ValueError(f'invalid Carbon Credits v7 {label} raw fields')
def index_rows(source, entity):
id_field = DATA_ID_FIELDS[entity]
rows = source.get(entity)
if not isinstance(rows, list) or any((not isinstance(row, dict) or not isinstance(row.get(id_field), str) for row in rows)):
raise ValueError(f'invalid Carbon Credits v7 {label} {entity}')
indexed = {row[id_field]: row for row in rows}
if len(indexed) != len(rows):
raise ValueError(f'duplicate Carbon Credits v7 {label} {entity} identifier')
return indexed
indexed = {entity: index_rows(raw, entity) for entity in sorted(baseline)}
baseline_indexed = {entity: index_rows(baseline, entity) for entity in sorted(baseline)}
for entity in ('organization', 'portfolio_account', 'offset_project'):
if raw[entity] != baseline[entity]:
raise ValueError(f'immutable Carbon Credits v7 {label} {entity} changed')
for (entity, quantity_fields) in (('portfolio_position', DATA__POSITION_QUANTITY_FIELDS), ('credit_batch', DATA__BATCH_QUANTITY_FIELDS)):
current_rows = indexed[entity]
original_rows = baseline_indexed[entity]
if set(current_rows) != set(original_rows):
raise ValueError(f'Carbon Credits v7 {label} {entity} identity changed')
for (entity_id, row) in current_rows.items():
original = original_rows[entity_id]
if set(row) != set(original) or any((row.get(field) != value for (field, value) in original.items() if field not in quantity_fields)):
raise ValueError(f'Carbon Credits v7 {label} {entity} metadata changed')
if any((not self._is_nonnegative_int(row.get(field)) for field in quantity_fields)):
raise ValueError(f'invalid Carbon Credits v7 {label} {entity} quantity')
if sum((row[field] for field in quantity_fields)) != sum((original[field] for field in quantity_fields)):
raise ValueError(f'Carbon Credits v7 {label} {entity} total changed')
positions = indexed['portfolio_position']
batches = indexed['credit_batch']
position_totals: dict[str, dict[str, int]] = {batch_id: {field: 0 for field in DATA__BATCH_QUANTITY_FIELDS} for batch_id in batches}
position_to_batch_field = {'quantity_available': 'available_credits', 'quantity_reserved': 'reserved_credits', 'quantity_retired': 'retired_credits'}
for position in positions.values():
batch_id = position.get('batch_id')
if batch_id not in position_totals:
raise ValueError(f'invalid Carbon Credits v7 {label} position batch link')
for (position_field, batch_field) in position_to_batch_field.items():
position_totals[batch_id][batch_field] += position[position_field]
for (batch_id, batch) in batches.items():
if any((batch[field] != position_totals[batch_id][field] for field in DATA__BATCH_QUANTITY_FIELDS)):
raise ValueError(f'Carbon Credits v7 {label} batch ledger is not conserved')
portfolios = indexed['portfolio_account']
retirements = indexed['retirement']
holding_positions: dict[tuple[str, str], list[str]] = {}
for (position_id, position) in positions.items():
holding_positions.setdefault((position['portfolio_account_id'], position['batch_id']), []).append(position_id)
deltas_by_position: dict[str, dict[str, int]] = {position_id: {'available': 0, 'reserved': 0, 'retired': 0} for position_id in positions}
deltas_by_batch: dict[str, dict[str, int]] = {batch_id: {'available': 0, 'reserved': 0, 'retired': 0} for batch_id in batches}
for retirement in retirements.values():
inspection_ids = retirement.get('candidate_inspection_ids')
if set(retirement) != DATA__RETIREMENT_FIELDS or retirement.get('status') not in {'submitted', 'completed'} or (not isinstance(retirement.get('quantity'), int)) or isinstance(retirement.get('quantity'), bool) or (retirement['quantity'] <= 0) or (retirement.get('reason') not in DATA_REASONS) or (retirement.get('claim_protocol') not in DATA_CLAIM_PROTOCOLS) or (not self._has_token_shape(retirement.get('policy_evidence_id'), 'pe')) or (not self._has_token_shape(retirement.get('candidate_listing_id'), 'cl')) or (not isinstance(inspection_ids, list)) or (inspection_ids != sorted(set(inspection_ids))) or (len(inspection_ids) != 2) or any((not self._has_token_shape(token, 'bi') for token in inspection_ids)) or (not all((isinstance(retirement.get(field), str) and bool(retirement.get(field)) for field in ('retirement_id', 'portfolio_account_id', 'batch_id', 'beneficiary_name', 'claim_period', 'created_at', 'updated_at')))) or (retirement.get('portfolio_account_id') not in portfolios) or (retirement.get('batch_id') not in batches) or (retirement['status'] == 'submitted' and retirement.get('completed_at') is not None) or (retirement['status'] == 'completed' and (not isinstance(retirement.get('completed_at'), str))):
raise ValueError(f'invalid Carbon Credits v7 {label} retirement record')
holding = (retirement['portfolio_account_id'], retirement['batch_id'])
matching_positions = holding_positions.get(holding, [])
if len(matching_positions) != 1:
raise ValueError(f'invalid Carbon Credits v7 {label} retirement holding link')
position_id = matching_positions[0]
quantity = retirement['quantity']
deltas_by_position[position_id]['available'] += quantity
deltas_by_batch[retirement['batch_id']]['available'] += quantity
state_field = 'reserved' if retirement['status'] == 'submitted' else 'retired'
deltas_by_position[position_id][state_field] += quantity
deltas_by_batch[retirement['batch_id']][state_field] += quantity
baseline_positions = baseline_indexed['portfolio_position']
for (position_id, row) in positions.items():
original = baseline_positions[position_id]
delta = deltas_by_position[position_id]
if row['quantity_available'] != original['quantity_available'] - delta['available'] or row['quantity_reserved'] != original['quantity_reserved'] + delta['reserved'] or row['quantity_retired'] != original['quantity_retired'] + delta['retired']:
raise ValueError(f'Carbon Credits v7 {label} position ledger differs from retirements')
baseline_batches = baseline_indexed['credit_batch']
for (batch_id, row) in batches.items():
original = baseline_batches[batch_id]
delta = deltas_by_batch[batch_id]
if row['available_credits'] != original['available_credits'] - delta['available'] or row['reserved_credits'] != original['reserved_credits'] + delta['reserved'] or row['retired_credits'] != original['retired_credits'] + delta['retired']:
raise ValueError(f'Carbon Credits v7 {label} batch ledger differs from retirements')
audits = indexed['audit_event']
audit_actions: dict[tuple[str, str], int] = {}
for audit in audits.values():
key = (str(audit.get('entity_id')), str(audit.get('action')))
metadata = audit.get('metadata')
retirement = retirements.get(str(audit.get('entity_id')))
portfolio = portfolios.get(retirement['portfolio_account_id']) if retirement is not None else None
if set(audit) != DATA__AUDIT_FIELDS or audit.get('entity_type') != 'retirement' or audit.get('action') not in {'submitted', 'retired'} or (retirement is None) or (portfolio is None) or (audit.get('actor_organization_id') != portfolio.get('organization_id')) or (not isinstance(audit.get('event_time'), str)) or (audit.get('created_at') != audit.get('event_time')) or (not isinstance(metadata, dict)) or (set(metadata) != {'source', 'risk_flag', 'note'}) or (metadata.get('source') != 'api') or (metadata.get('risk_flag') is not False) or (not isinstance(metadata.get('note'), str)):
raise ValueError(f'invalid Carbon Credits v7 {label} audit record')
audit_actions[key] = audit_actions.get(key, 0) + 1
for (retirement_id, retirement) in retirements.items():
expected_actions = {'submitted'}
if retirement['status'] == 'completed':
expected_actions.add('retired')
observed_actions = {action for ((entity_id, action), count) in audit_actions.items() if entity_id == retirement_id and count == 1}
if observed_actions != expected_actions or any((count != 1 for ((entity_id, _), count) in audit_actions.items() if entity_id == retirement_id)):
raise ValueError(f'Carbon Credits v7 {label} retirement audit chain differs')
if len(audits) != sum((1 + (retirement['status'] == 'completed') for retirement in retirements.values())):
raise ValueError(f'Carbon Credits v7 {label} audit inventory differs')
return indexed
def _validate_evidence_snapshot(self, snapshot, evidence):
if set(snapshot) != DATA__SNAPSHOT_FIELDS:
raise ValueError('invalid Carbon Credits v7 snapshot fields')
if snapshot.get('source_fingerprint') != self.source_fingerprint:
raise ValueError('Carbon Credits v7 source fingerprint mismatch')
remaining = snapshot.get('remaining')
if not isinstance(remaining, int) or isinstance(remaining, bool) or (not 0 <= remaining <= 134):
raise ValueError('invalid Carbon Credits v7 remaining budget')
receipts = snapshot.get('receipts')
if not isinstance(receipts, list):
raise ValueError('invalid Carbon Credits v7 tool receipt log')
active_task_id = snapshot.get('active_task_id')
if active_task_id is not None and active_task_id not in DATA_TASK_IDS_2:
raise ValueError('invalid Carbon Credits v7 active task')
stream = snapshot.get('stream')
if not isinstance(stream, dict) or set(stream) != DATA__STREAM_FIELDS:
raise ValueError('invalid Carbon Credits v7 stream snapshot fields')
prepared = stream['prepared_tasks']
if not isinstance(prepared, list) or any((not isinstance(task_id, str) for task_id in prepared)) or prepared != list(DATA_TASK_IDS_2[:len(prepared)]) or (active_task_id != (prepared[-1] if prepared else None)):
raise ValueError('invalid Carbon Credits v7 prepared-task sequence')
call_count = stream['call_count']
drift_sequence = stream['drift_event_sequence']
if not isinstance(call_count, int) or isinstance(call_count, bool) or (not 0 <= call_count <= 24) or (not isinstance(drift_sequence, int)) or isinstance(drift_sequence, bool) or (drift_sequence not in (0, 1)):
raise ValueError('invalid Carbon Credits v7 stream counters')
prepared_index = {task_id: index for (index, task_id) in enumerate(prepared)}
receipt_task_index = -1
task_remaining: dict[str, int] = {}
counted_calls: dict[str, int] = {}
prior_after_hash: str | None = None
for (expected_index, receipt) in enumerate(receipts, 1):
if not isinstance(receipt, dict) or set(receipt) != DATA__TOOL_RECEIPT_FIELDS or receipt.get('index') != expected_index or (receipt.get('task_id') not in prepared_index) or (not isinstance(receipt.get('tool'), str)) or (not isinstance(receipt.get('actor'), str)) or (receipt.get('status') not in {'success', 'error'}) or (not isinstance(receipt.get('result_data'), dict)) or (not self._is_nonnegative_int(receipt.get('cost'))) or (not self._is_nonnegative_int(receipt.get('remaining'))) or (receipt['remaining'] > 134) or (not self._has_sha256_shape(receipt.get('before_business_hash'))) or (not self._has_sha256_shape(receipt.get('after_business_hash'))):
raise ValueError('invalid Carbon Credits v7 tool receipt')
task_id = receipt['task_id']
current_task_index = prepared_index[task_id]
if current_task_index < receipt_task_index:
raise ValueError('invalid Carbon Credits v7 receipt task order')
receipt_task_index = current_task_index
before_remaining = task_remaining.get(task_id, 134)
if receipt['remaining'] != before_remaining - receipt['cost']:
raise ValueError('invalid Carbon Credits v7 receipt budget chain')
task_remaining[task_id] = receipt['remaining']
if receipt['actor'] != 'carbon_portfolio_operator' or receipt['tool'] not in DATA_ALLOWED_TOOLS:
if receipt['cost'] != 0:
raise ValueError('invalid Carbon Credits v7 forbidden-call charge')
else:
expected_cost = self._cost(receipt['tool'], receipt['arguments'])
if receipt['cost'] not in {0, expected_cost}:
raise ValueError('invalid Carbon Credits v7 tool receipt cost')
counted_calls[task_id] = min(24, counted_calls.get(task_id, 0) + 1)
if prior_after_hash is not None and receipt['before_business_hash'] != prior_after_hash:
raise ValueError('invalid Carbon Credits v7 receipt hash chain')
prior_after_hash = receipt['after_business_hash']
expected_remaining = task_remaining.get(active_task_id, 134) if active_task_id is not None else 134
if remaining != expected_remaining:
raise ValueError('Carbon Credits v7 remaining budget differs from receipts')
if call_count != counted_calls.get(active_task_id, 0):
raise ValueError('Carbon Credits v7 call counter differs from receipts')
expected_active_positions = sorted({position_id for target in DATA_SUCCESSOR_TARGETS.get(active_task_id, []) for position_id in target['candidate_position_ids']})
expected_released_batches = sorted({batch_id for task_id in prepared for target in DATA_SUCCESSOR_TARGETS[task_id] for batch_id in target['candidate_batch_ids']})
if stream['active_position_ids'] != expected_active_positions or stream['released_batch_ids'] != expected_released_batches:
raise ValueError('invalid Carbon Credits v7 active stream slice')
boundaries = stream['boundary_receipts']
if not isinstance(boundaries, list) or len(boundaries) != len(prepared):
raise ValueError('invalid Carbon Credits v7 boundary receipt sequence')
for (task_index, (task_id, boundary)) in enumerate(zip(prepared, boundaries, strict=True)):
if not isinstance(boundary, dict) or set(boundary) != DATA__BOUNDARY_FIELDS or boundary.get('schema') != 'rescopebench-carbon-credits-rule-boundary/v7' or (boundary.get('event_id') != fn_public_task_2(task_id)['event_id']) or (boundary.get('previous_private_task_id') != (prepared[task_index - 1] if task_index else None)) or (boundary.get('next_private_task_id') != task_id) or (boundary.get('already_prepared') is not False) or (boundary.get('active_position_ids') != sorted({position_id for target in DATA_SUCCESSOR_TARGETS[task_id] for position_id in target['candidate_position_ids']})) or (boundary.get('public_notice') != 'A new carbon-retirement request batch is active.') or (boundary.get('world_reset') is not False) or (not self._has_sha256_shape(boundary.get('before_sha256'))) or (not self._has_sha256_shape(boundary.get('after_sha256'))):
raise ValueError('invalid Carbon Credits v7 boundary receipt')
expected_successor = {'case_version': 'carbon-credits-rule-v7', 'parent_case_version': 'carbon-credits-rule-v5', 'provider_tools_sha256': '34c2ee05393e8c3430cf8f40c369f50180d785999f8e367adb45644f6bda06fc', 'work_budget': 134, 'policy_evidence_cost': 27, 'changed_rules': list(DATA_CHANGED_RULES)}
if snapshot.get('successor') != expected_successor:
raise ValueError('Carbon Credits v7 successor contract mismatch')
required = {'secret', 'issued_policy_evidence', 'issued_candidate_listings', 'issued_batch_inspections', 'rule_revalidation', 'attempted_target_ids'}
if set(evidence) != required or evidence['secret'] != self.evidence_secret:
raise ValueError('invalid Carbon Credits v7 evidence snapshot fields')
if not all((isinstance(evidence[key], dict) for key in ('issued_policy_evidence', 'issued_candidate_listings', 'issued_batch_inspections', 'rule_revalidation'))) or not isinstance(evidence['attempted_target_ids'], list):
raise ValueError('invalid Carbon Credits v7 evidence snapshot values')
applied_events = snapshot.get('applied_boundary_events')
if not isinstance(applied_events, list) or any((not isinstance(event, str) for event in applied_events)) or set(applied_events) not in (set(), {'carbon-policy-v2'}):
raise ValueError('invalid Carbon Credits v7 drift event state')
drift_applied = 'carbon-policy-v2' in applied_events
if drift_sequence != int(drift_applied) or (drift_applied and 'T09' not in prepared) or (len(prepared) > DATA_TASK_IDS_2.index('T09') + 1 and (not drift_applied)):
raise ValueError('Carbon Credits v7 drift counters contradict history')
for (task_id, boundary) in zip(prepared, boundaries, strict=True):
drift = boundary['drift']
if task_id != 'T09' or not drift_applied:
if drift is not None or boundary['before_sha256'] != boundary['after_sha256']:
raise ValueError('invalid Carbon Credits v7 boundary drift state')
continue
if not isinstance(drift, dict) or set(drift) != DATA__DRIFT_FIELDS or (not isinstance(drift.get('event_id'), str)) or (not drift['event_id'].startswith('evt-')) or (drift.get('applied_now') is not True) or (drift.get('duplicate_noop') is not False) or (drift.get('changed_rule_atoms') != list(DATA_CHANGED_RULES)) or (drift.get('before_sha256') != boundary['before_sha256']) or (drift.get('after_sha256') != boundary['after_sha256']) or (drift.get('event_sequence') != 1) or (boundary['before_sha256'] == boundary['after_sha256']):
raise ValueError('invalid Carbon Credits v7 drift receipt')
expected_cells = ext_deepcopy(DATA_PRE_POLICY_CELLS)
if drift_applied:
for (rule, condition) in DATA_CHANGED_CONDITIONS.items():
expected_cells[condition] = ext_deepcopy(DATA_POST_POLICY_OVERRIDES[rule])
policy_rows = snapshot.get('policy_cells')
if not isinstance(policy_rows, list):
raise ValueError('invalid Carbon Credits v7 policy snapshot')
observed_cells: dict[tuple[str, str], dict[str, ext_Any]] = {}
for row in policy_rows:
if not isinstance(row, dict) or not {'standard', 'reason'}.issubset(row) or (not isinstance(row.get('standard'), str)) or (not isinstance(row.get('reason'), str)):
raise ValueError('invalid Carbon Credits v7 policy snapshot row')
condition = (row['standard'], row['reason'])
if condition in observed_cells:
raise ValueError('duplicate Carbon Credits v7 policy snapshot row')
observed_cells[condition] = {key: ext_deepcopy(value) for (key, value) in row.items() if key not in {'standard', 'reason'}}
if observed_cells != expected_cells:
raise ValueError('Carbon Credits v7 policy snapshot state is invalid')
revalidation = evidence['rule_revalidation']
if any((not isinstance(rule, str) or not isinstance(state, str) for (rule, state) in revalidation.items())) or not set(revalidation).issubset(DATA_CHANGED_RULES) or (not set(revalidation.values()).issubset({'awaiting_exact_stale', 'awaiting_current_policy', 'ready_current', 'validated_current'})):
raise ValueError('invalid Carbon Credits v7 revalidation state')
expected_revalidation_rules = set(DATA_CHANGED_RULES) if drift_applied else set()
if set(revalidation) != expected_revalidation_rules:
raise ValueError('Carbon Credits v7 revalidation state contradicts drift')
attempted = evidence['attempted_target_ids']
active_targets = {target['target_id'] for target in DATA_SUCCESSOR_TARGETS.get(active_task_id, [])}
if any((not isinstance(target_id, str) for target_id in attempted)) or attempted != sorted(set(attempted)) or (not set(attempted).issubset(active_targets)):
raise ValueError('invalid Carbon Credits v7 attempted target state')
legal_policy_receipts: dict[str, dict[str, ext_Any]] = {}
for (condition, pre_cell) in DATA_PRE_POLICY_CELLS.items():
cells = [pre_cell]
rule = next((atom for (atom, changed_condition) in DATA_CHANGED_CONDITIONS.items() if changed_condition == condition), None)
if drift_applied and rule is not None:
cells.append(DATA_POST_POLICY_OVERRIDES[rule])
for cell in cells:
token = self._policy_token(condition, cell)
legal_policy_receipts[token] = {**self._public_cell(condition, cell), 'policy_evidence_id': token}
for (token, receipt) in evidence['issued_policy_evidence'].items():
if not self._has_token_shape(token, 'pe') or not isinstance(receipt, dict) or set(receipt) != DATA__POLICY_RECEIPT_FIELDS or (receipt.get('policy_evidence_id') != token) or (legal_policy_receipts.get(token) != receipt):
raise ValueError('invalid Carbon Credits v7 policy receipt cache')
raw = snapshot.get('raw')
raw_index = self._validate_raw_snapshot(raw, label='current')
initial_business_hash = fn_digest(self._frozen_raw_baseline)
final_business_hash = fn_digest(raw)
if receipts:
if receipts[0]['before_business_hash'] != initial_business_hash or receipts[-1]['after_business_hash'] != final_business_hash:
raise ValueError('Carbon Credits v7 receipt log does not bind raw state')
elif final_business_hash != initial_business_hash:
raise ValueError('Carbon Credits v7 raw state changed without receipts')
task_entry = stream['task_entry_snapshot']
if active_task_id is None:
if task_entry is not None:
raise ValueError('inactive Carbon Credits v7 snapshot has a task entry')
else:
active_index = prepared_index[active_task_id]
expected_entry_receipts = [ext_deepcopy(receipt) for receipt in receipts if prepared_index[receipt['task_id']] < active_index]
if not isinstance(task_entry, dict) or set(task_entry) != DATA__TASK_ENTRY_FIELDS or task_entry.get('schema') != 'carbon-credits-adapter-snapshot/v1' or (task_entry.get('source_fingerprint') != self.source_fingerprint) or (task_entry.get('active_task_id') != active_task_id) or (task_entry.get('remaining') != 134) or (task_entry.get('receipts') != expected_entry_receipts) or (task_entry.get('policy_cells') != policy_rows) or (task_entry.get('applied_boundary_events') != applied_events):
raise ValueError('invalid Carbon Credits v7 task-entry snapshot')
self._validate_raw_snapshot(task_entry.get('raw'), label='task-entry')
entry_state = {'raw': task_entry.get('raw'), 'policy_cells': task_entry.get('policy_cells'), 'applied_boundary_events': task_entry.get('applied_boundary_events')}
if boundaries[-1].get('after_sha256') != fn_digest(entry_state):
raise ValueError('Carbon Credits v7 task-entry hash differs')
positions = raw_index['portfolio_position']
portfolios = raw_index['portfolio_account']
batches = raw_index['credit_batch']
projects = raw_index['offset_project']
all_targets = [target for task_id in DATA_TASK_IDS_2 for target in DATA_SUCCESSOR_TARGETS[task_id]]
listings = evidence['issued_candidate_listings']
for (token, listing) in listings.items():
policy_id = listing.get('policy_evidence_id') if isinstance(listing, dict) else None
if not self._has_token_shape(token, 'cl') or not isinstance(listing, dict) or set(listing) != DATA__LISTING_RECEIPT_FIELDS or (listing.get('candidate_listing_id') != token) or (not isinstance(policy_id, str)) or (policy_id not in legal_policy_receipts) or (not isinstance(listing.get('organization_id'), str)) or (not isinstance(listing.get('standard'), str)) or (not isinstance(listing.get('reason'), str)) or (not isinstance(listing.get('vintage_year'), int)) or isinstance(listing.get('vintage_year'), bool):
raise ValueError('invalid Carbon Credits v7 candidate-listing cache')
position_ids = listing.get('position_ids')
batch_ids = listing.get('batch_ids')
if not isinstance(position_ids, list) or not isinstance(batch_ids, list) or any((not isinstance(value, str) for value in position_ids)) or any((not isinstance(value, str) for value in batch_ids)) or (len(position_ids) != 2) or (len(batch_ids) != 2) or (len(set(position_ids)) != 2) or (len(set(batch_ids)) != 2):
raise ValueError('invalid Carbon Credits v7 candidate-listing rows')
target = next((row for row in all_targets if row['organization_id'] == listing.get('organization_id') and row['standard'] == listing.get('standard') and (row['reason'] == listing.get('reason')) and (row['vintage_year'] == listing.get('vintage_year')) and (set(row['candidate_position_ids']) == set(position_ids))), None)
if target is None:
raise ValueError('invalid Carbon Credits v7 candidate-listing scope')
token_rows = []
for (position_id, batch_id) in zip(position_ids, batch_ids, strict=True):
position = positions.get(position_id)
portfolio = portfolios.get(str((position or {}).get('portfolio_account_id')))
batch = batches.get(batch_id)
if position is None or position.get('batch_id') != batch_id or portfolio is None or (portfolio.get('organization_id') != listing['organization_id']) or (batch is None) or (batch.get('standard') != listing['standard']) or (batch.get('vintage_year') != listing['vintage_year']):
raise ValueError('invalid Carbon Credits v7 candidate-listing link')
token_rows.append({'position_id': position_id, 'portfolio_account_id': position['portfolio_account_id'], 'batch_id': batch_id})
expected_token = self._listing_token(listing['policy_evidence_id'], listing['organization_id'], listing['standard'], listing['vintage_year'], token_rows)
if token != expected_token:
raise ValueError('invalid Carbon Credits v7 candidate-listing token')
for (token, inspection) in evidence['issued_batch_inspections'].items():
if not self._has_token_shape(token, 'bi') or not isinstance(inspection, dict) or set(inspection) != DATA__INSPECTION_RECEIPT_FIELDS or (inspection.get('candidate_inspection_id') != token) or any((not isinstance(inspection.get(field), str) for field in ('policy_evidence_id', 'candidate_listing_id', 'batch_id', 'project_id'))):
raise ValueError('invalid Carbon Credits v7 batch-inspection cache')
listing = listings.get(inspection.get('candidate_listing_id'))
batch = batches.get(inspection.get('batch_id'))
project = projects.get(inspection.get('project_id'))
if listing is None or listing['policy_evidence_id'] != inspection.get('policy_evidence_id') or inspection.get('batch_id') not in listing['batch_ids'] or (batch is None) or (batch.get('project_id') != inspection.get('project_id')) or (project is None):
raise ValueError('invalid Carbon Credits v7 batch-inspection link')
expected_token = self._inspection_token(inspection['policy_evidence_id'], inspection['candidate_listing_id'], batch, project)
if token != expected_token:
raise ValueError('invalid Carbon Credits v7 batch-inspection token')
self._validate_replayed_snapshot(snapshot)
def _organizations_v7(self, arguments):
active_organization_ids = {target['organization_id'] for target in self.task_targets()}
rows = [row for row in self._rows('organization') if row.get('organization_id') in active_organization_ids]
token = str(arguments.get('legal_name_contains') or '').strip().lower()
if token:
rows = [row for row in rows if token in str(row.get('legal_name', '')).lower()]
for (field, argument) in (('account_type', 'account_type'), ('registry_jurisdiction', 'jurisdiction'), ('status', 'status'), ('kyb_status', 'kyb_status')):
if arguments.get(argument):
rows = [row for row in rows if row.get(field) == arguments[argument]]
rows.sort(key=lambda row: (row.get('legal_name', ''), row.get('organization_id', '')))
total = len(rows)
visible = [{key: row.get(key) for key in ('organization_id', 'legal_name', 'account_type', 'registry_jurisdiction', 'status', 'kyb_status')} for row in rows[arguments['offset']:arguments['offset'] + arguments['limit']]]
return self._result('list_organizations', 'success', 'OK', {'total_count': total, 'organizations': visible})
def _positions_v7(self, arguments):
base_arguments = {key: ext_deepcopy(value) for (key, value) in arguments.items() if key != 'policy_evidence_id'}
result = self._portfolio_positions(base_arguments)
policy_id = arguments.get('policy_evidence_id')
data = result['content'].get('data', {})
rows = data.get('positions', [])
if not policy_id or result['content'].get('status') != 'success':
return result
matching_conditions = [condition for condition in self.policy_cells if condition[0] == arguments.get('standard') and self._policy_receipt_valid(policy_id, condition, allow_stale=True)]
if len(matching_conditions) != 1:
return result
target = next((row for row in self.task_targets() if row['organization_id'] == arguments['organization_id'] and row['standard'] == arguments.get('standard') and (row['reason'] == matching_conditions[0][1]) and (row['vintage_year'] == arguments.get('vintage_year')) and (set(row['candidate_position_ids']) == {item['position_id'] for item in rows})), None)
if target is None or len(rows) != 2 or data.get('total_count') != 2:
return result
token = self._listing_token(policy_id, arguments['organization_id'], arguments['standard'], arguments['vintage_year'], rows)
listing = {'candidate_listing_id': token, 'policy_evidence_id': policy_id, 'organization_id': arguments['organization_id'], 'standard': arguments['standard'], 'reason': matching_conditions[0][1], 'vintage_year': arguments['vintage_year'], 'position_ids': [row['position_id'] for row in rows], 'batch_ids': [row['batch_id'] for row in rows]}
self.issued_candidate_listings[token] = ext_deepcopy(listing)
data['candidate_listing_id'] = token
data['policy_evidence_id'] = policy_id
return result
def _batch_v7(self, arguments):
result = self._batch_detail({'batch_id': arguments['batch_id']})
policy_id = arguments.get('policy_evidence_id')
listing_id = arguments.get('candidate_listing_id')
if not policy_id or not listing_id or result['content'].get('status') != 'success':
return result
listing = self.issued_candidate_listings.get(listing_id)
if listing is None or listing.get('policy_evidence_id') != policy_id or arguments['batch_id'] not in listing.get('batch_ids', []) or (not self._policy_receipt_valid(policy_id, (listing['standard'], listing['reason']), allow_stale=True)):
return result
data = result['content']['data']
token = self._inspection_token(policy_id, listing_id, data['batch'], data['project'])
inspection = {'candidate_inspection_id': token, 'policy_evidence_id': policy_id, 'candidate_listing_id': listing_id, 'batch_id': arguments['batch_id'], 'project_id': data['project']['project_id']}
self.issued_batch_inspections[token] = ext_deepcopy(inspection)
data['candidate_inspection_id'] = token
data['policy_evidence_id'] = policy_id
data['candidate_listing_id'] = listing_id
return result
def _target_for_submission(self, arguments):
return next((target for target in self.task_targets() if target['reason'] == arguments.get('reason') and target['quantity'] == arguments.get('quantity') and (target['beneficiary_name'] == arguments.get('beneficiary_name')) and (target['claim_period'] == arguments.get('claim_period')) and (arguments.get('position_id') in target['candidate_position_ids'])), None)
def _citation_error(self, target, arguments):
condition = (target['standard'], target['reason'])
policy_id = arguments['policy_evidence_id']
listing_id = arguments['candidate_listing_id']
allow_stale = target['rule_atom'] in DATA_CHANGED_RULES
if not self._policy_receipt_valid(policy_id, condition, allow_stale=allow_stale):
return 'EVIDENCE_CONFLICT: cited policy evidence is not accepted for this request'
listing = self.issued_candidate_listings.get(listing_id)
if listing is None:
expected_rows = [{'position_id': position_id, 'portfolio_account_id': self._get('portfolio_position', position_id)['portfolio_account_id'], 'batch_id': self._get('portfolio_position', position_id)['batch_id']} for position_id in target['candidate_position_ids']]
expected = self._listing_token(policy_id, target['organization_id'], target['standard'], target['vintage_year'], sorted(expected_rows, key=lambda row: row['position_id']))
if listing_id != expected:
return 'EVIDENCE_INCOMPLETE: a complete candidate-listing receipt is required'
listing = {'policy_evidence_id': policy_id, 'organization_id': target['organization_id'], 'standard': target['standard'], 'reason': target['reason'], 'vintage_year': target['vintage_year'], 'position_ids': [row['position_id'] for row in expected_rows], 'batch_ids': [row['batch_id'] for row in expected_rows]}
if listing.get('policy_evidence_id') != policy_id or listing.get('organization_id') != target['organization_id'] or listing.get('standard') != target['standard'] or (listing.get('reason') != target['reason']) or (listing.get('vintage_year') != target['vintage_year']) or (set(listing.get('position_ids', [])) != set(target['candidate_position_ids'])):
return 'EVIDENCE_INCOMPLETE: candidate-listing receipt has the wrong scope'
supplied = set(arguments['candidate_inspection_ids'])
expected: set[str] = set()
for batch_id in listing['batch_ids']:
batch = self._get('credit_batch', batch_id)
project = self._get('offset_project', (batch or {}).get('project_id'))
if batch is None or project is None:
return 'EVIDENCE_INCOMPLETE: candidate batch evidence is unavailable'
expected.add(self._inspection_token(policy_id, listing_id, batch, project))
if supplied != expected:
return 'EVIDENCE_INCOMPLETE: both candidate inspection receipts are required'
return None
def dispatch(self, tool, arguments, actor='carbon_portfolio_operator'):
normalized = self._normalize(tool, arguments) if tool in DATA_ALLOWED_TOOLS else arguments
before_hash = self.business_hash()
if actor != 'carbon_portfolio_operator':
return self._record(tool, actor, normalized, self._result(tool, 'error', 'ROLE_FORBIDDEN: actor is not a carbon portfolio operator'), 0, before_hash)
if tool not in DATA_ALLOWED_TOOLS:
return self._record(tool, actor, normalized, self._result(tool, 'error', 'TOOL_FORBIDDEN: tool is outside the portfolio-operator slice'), 0, before_hash)
if self.call_count >= 24:
return self._record(tool, actor, normalized, self._result(tool, 'error', 'TOOL_CALL_LIMIT: no public tool calls remain in this episode'), 0, before_hash)
self.call_count += 1
cost = self._cost(tool, normalized)
if self.remaining < cost:
return self._record(tool, actor, normalized, self._result(tool, 'error', 'WORK_QUOTA_EXHAUSTED: insufficient API-work quota'), 0, before_hash)
try:
mod_jsonschema.validate(normalized, DATA_TOOL_SCHEMAS[tool])
except mod_jsonschema.ValidationError as error:
self.remaining -= cost
return self._record(tool, actor, normalized, self._result(tool, 'error', f'INVALID_ARGUMENTS: {error.message}'), cost, before_hash)
raw_before = self._raw_snapshot(DATA_MUTABLE_ENTITIES) if tool in DATA_WRITE_TOOLS else None
self.remaining -= cost
try:
if tool == 'list_organizations':
result = self._organizations_v7(normalized)
elif tool == 'get_organization_profile':
result = self._organization_profile(normalized)
elif tool == 'list_portfolio_positions':
result = self._positions_v7(normalized)
elif tool == 'get_credit_batch':
result = self._batch_v7(normalized)
elif tool == 'search_retirement_policy_evidence':
result = self._policy_evidence_v7(normalized)
elif tool == 'submit_retirement_request':
result = self._submit_v7(normalized)
else:
result = self._retire(normalized)
except Exception:
result = self._result(tool, 'error', 'UPSTREAM_TOOL_ERROR: raw tool execution failed')
result = self._sanitize(tool, result)
if raw_before is not None and result['content'].get('status') == 'error':
self._restore_raw(raw_before)
return self._record(tool, actor, normalized, result, cost, before_hash)
def public_snapshot(self):
current = fn_public_task_3(self.active_task_id) if self.active_task_id else None
return {'schema': 'rescopebench-carbon-credits-public-snapshot/v2', 'active_event_id': current['event_id'] if current else None, 'active_target_ids': [row['target_id'] for row in current['targets']] if current else [], 'budget': {'remaining_work_units': self.remaining, 'maximum_tool_calls': 24}}
def apply_eligibility_drift(self, event_key):
if event_key in self.applied_boundary_events:
return {'status': 'success', 'event_id': event_key, 'idempotent': True, 'changed': []}
previous = {rule: ext_deepcopy(self.policy_cells[condition]) for (rule, condition) in DATA_CHANGED_CONDITIONS.items()}
for (rule, condition) in DATA_CHANGED_CONDITIONS.items():
self.policy_cells[condition] = ext_deepcopy(DATA_POST_POLICY_OVERRIDES[rule])
self.applied_boundary_events.add(event_key)
return {'status': 'success', 'event_id': event_key, 'idempotent': False, 'changed': [': '.join(DATA_CHANGED_CONDITIONS[rule]) for rule in DATA_CHANGED_RULES], 'previous_internal_value': previous, 'current_internal_value': {rule: ext_deepcopy(self.policy_cells[condition]) for (rule, condition) in DATA_CHANGED_CONDITIONS.items()}}
def _apply_stream_drift(self):
before = self.business_semantic_hash()
receipt = self.apply_eligibility_drift('carbon-policy-v2')
if receipt['idempotent']:
after = self.business_semantic_hash()
return {'event_id': 'evt-' + fn_digest_2(['carbon-credits-rule-v3', 'boundary'])[:20], 'applied_now': False, 'duplicate_noop': before == after, 'before_sha256': before, 'after_sha256': after, 'event_sequence': self.drift_event_sequence}
self.drift_event_sequence += 1
after = self.business_semantic_hash()
return {'event_id': 'evt-' + fn_digest_2(['carbon-credits-rule-v3', 'boundary'])[:20], 'applied_now': True, 'duplicate_noop': False, 'changed_rule_atoms': list(DATA_CHANGED_RULES), 'before_sha256': before, 'after_sha256': after, 'event_sequence': self.drift_event_sequence}
def _install_stream_slice(self):
position_ids = {value for targets in self.stream_targets.values() for target in targets for value in target['candidate_position_ids']}
positions = [row for row in self._rows('portfolio_position') if row['position_id'] in position_ids]
portfolio_ids = {row['portfolio_account_id'] for row in positions}
batch_ids = {row['batch_id'] for row in positions}
portfolios = [row for row in self._rows('portfolio_account') if row['portfolio_account_id'] in portfolio_ids]
organization_ids = {row['organization_id'] for row in portfolios}
batches = [row for row in self._rows('credit_batch') if row['batch_id'] in batch_ids]
project_ids = {row['project_id'] for row in batches}
entities = {'organization': [row for row in self._rows('organization') if row['organization_id'] in organization_ids], 'portfolio_account': portfolios, 'portfolio_position': positions, 'credit_batch': batches, 'offset_project': [row for row in self._rows('offset_project') if row['project_id'] in project_ids], 'retirement': [], 'audit_event': []}
for (entity, rows) in entities.items():
self.manager.db.save(entity, ext_deepcopy(rows))
self._normalize_batch_ledgers()
def close(self):
self._carbon_credits_adapter_close()
def business_state(self):
return {'raw': self._raw_snapshot(), 'policy_cells': [{'standard': standard, 'reason': reason, **ext_deepcopy(cell)} for ((standard, reason), cell) in sorted(self.policy_cells.items())], 'applied_boundary_events': sorted(self.applied_boundary_events)}
def business_semantic_hash(self):
return fn__digest(self.business_state())
def _portfolio_positions(self, arguments):
organization = self._get('organization', arguments['organization_id'])
if organization is None:
return self._result('list_portfolio_positions', 'error', 'ORGANIZATION_NOT_FOUND: organization_id was not found')
portfolios = {row['portfolio_account_id']: row for row in self._rows('portfolio_account') if row.get('organization_id') == organization['organization_id']}
batches = {row['batch_id']: row for row in self._rows('credit_batch')}
rows = []
for position in self._rows('portfolio_position'):
if position['position_id'] not in self.active_position_ids:
continue
portfolio = portfolios.get(position.get('portfolio_account_id'))
batch = batches.get(position.get('batch_id'))
if portfolio is None or batch is None:
continue
if arguments.get('standard') and batch.get('standard') != arguments['standard']:
continue
if arguments.get('vintage_year') is not None and batch.get('vintage_year') != arguments['vintage_year']:
continue
if arguments['only_available'] and int(position.get('quantity_available', 0) or 0) <= 0:
continue
rows.append({**{key: position.get(key) for key in ('position_id', 'portfolio_account_id', 'batch_id', 'quantity_available', 'quantity_reserved', 'quantity_retired')}, 'portfolio_status': portfolio.get('status'), 'portfolio_jurisdiction': portfolio.get('registry_jurisdiction'), 'batch_summary': {'standard': batch.get('standard'), 'vintage_year': batch.get('vintage_year'), 'credit_type': batch.get('credit_type'), 'status': batch.get('status')}})
rows.sort(key=lambda row: row['position_id'])
total = len(rows)
visible = rows[arguments['offset']:arguments['offset'] + arguments['limit']]
return self._result('list_portfolio_positions', 'success', 'OK', {'total_count': total, 'positions': visible})
def _batch_detail(self, arguments):
if arguments['batch_id'] not in self.released_batch_ids:
return self._result('get_credit_batch', 'error', 'BATCH_NOT_ACTIVE: batch is not in the current request scope')
return self._carbon_credits_adapter_batch_detail(arguments)
def _policy_evidence(self, arguments):
result = self._carbon_credits_adapter_policy_evidence(arguments)
for row in result.get('content', {}).get('data', {}).get('evidence', []):
row.pop('rule_atom', None)
return result
def _submit(self, arguments):
if arguments.get('position_id') not in self.active_position_ids:
return self._result('submit_retirement_request', 'error', 'POSITION_NOT_ACTIVE: position is not in the current request scope')
return self._carbon_credits_adapter_submit(arguments)
def task_targets(self):
if self.active_task_id not in self.stream_targets:
raise RuntimeError('no stream task is active')
return ext_deepcopy(self.stream_targets[self.active_task_id])
def _rows(self, entity):
return self.manager.list_entities(entity)
def _get(self, entity, entity_id):
return self.manager.get_entity(entity, entity_id, id_field=DATA_ID_FIELDS[entity])
def _normalize_batch_ledgers(self):
totals: dict[str, list[int]] = ext_defaultdict(lambda : [0, 0, 0])
for position in self._rows('portfolio_position'):
values = totals[str(position.get('batch_id'))]
values[0] += int(position.get('quantity_available', 0) or 0)
values[1] += int(position.get('quantity_reserved', 0) or 0)
values[2] += int(position.get('quantity_retired', 0) or 0)
batches = self._rows('credit_batch')
for batch in batches:
(available, reserved, retired) = totals[str(batch.get('batch_id'))]
batch['available_credits'] = available
batch['reserved_credits'] = reserved
batch['retired_credits'] = retired
self.manager.db.save('credit_batch', batches)
def ledger_conservation(self):
totals: dict[str, list[int]] = ext_defaultdict(lambda : [0, 0, 0])
for position in self._rows('portfolio_position'):
values = totals[str(position.get('batch_id'))]
values[0] += int(position.get('quantity_available', 0) or 0)
values[1] += int(position.get('quantity_reserved', 0) or 0)
values[2] += int(position.get('quantity_retired', 0) or 0)
mismatches = []
for batch in self._rows('credit_batch'):
actual = tuple(totals[str(batch.get('batch_id'))])
declared = tuple((int(batch.get(field, 0) or 0) for field in ('available_credits', 'reserved_credits', 'retired_credits')))
if actual != declared:
mismatches.append({'batch_id': batch.get('batch_id'), 'batch': declared, 'positions': actual})
return {'checked_batches': len(self._rows('credit_batch')), 'mismatch_count': len(mismatches), 'first_mismatch': mismatches[0] if mismatches else None, 'passed': not mismatches}
def _normalize(self, tool, arguments):
if not isinstance(arguments, dict):
return arguments
value = mod_copy.deepcopy(arguments)
if tool in DATA_LIST_TOOLS:
value.setdefault('limit', 3)
value.setdefault('offset', 0)
if tool == 'list_portfolio_positions':
value.setdefault('only_available', True)
return value
@staticmethod
def _result(tool, status, message, data=None):
return {'type': 'tool_result', 'tool': tool, 'content': {'status': status, 'data': data or {}, 'message': message}}
def _record(self, tool, actor, arguments, result, cost, before_hash):
receipt = {'index': len(self.receipts) + 1, 'task_id': self.active_task_id, 'tool': tool, 'actor': actor, 'arguments': mod_copy.deepcopy(arguments), 'status': result['content'].get('status'), 'result_data': mod_copy.deepcopy(result['content'].get('data', {})), 'cost': cost, 'before_business_hash': before_hash, 'after_business_hash': self.business_hash(), 'remaining': self.remaining}
self.receipts.append(receipt)
result['budget'] = {'charged': cost, 'remaining': self.remaining}
result['receipt_index'] = receipt['index']
return result
def _list_organizations(self, arguments):
rows = self._rows('organization')
token = str(arguments.get('legal_name_contains') or '').strip().lower()
if token:
rows = [row for row in rows if token in str(row.get('legal_name', '')).lower()]
for (field, argument) in (('account_type', 'account_type'), ('registry_jurisdiction', 'jurisdiction'), ('status', 'status'), ('kyb_status', 'kyb_status')):
if arguments.get(argument):
rows = [row for row in rows if row.get(field) == arguments[argument]]
rows.sort(key=lambda row: (row.get('legal_name', ''), row.get('organization_id', '')))
total = len(rows)
visible = [{key: row.get(key) for key in ('organization_id', 'legal_name', 'account_type', 'registry_jurisdiction', 'status', 'kyb_status')} for row in rows[arguments['offset']:arguments['offset'] + arguments['limit']]]
return self._result('list_organizations', 'success', 'OK', {'total_count': total, 'organizations': visible})
def _organization_profile(self, arguments):
organization = self._get('organization', arguments['organization_id'])
if organization is None:
return self._result('get_organization_profile', 'error', 'ORGANIZATION_NOT_FOUND: organization_id was not found')
portfolios = [{key: row.get(key) for key in ('portfolio_account_id', 'account_name', 'registry_jurisdiction', 'status')} for row in self._rows('portfolio_account') if row.get('organization_id') == organization['organization_id']]
portfolios.sort(key=lambda row: row['portfolio_account_id'])
public_org = {key: organization.get(key) for key in ('organization_id', 'legal_name', 'account_type', 'registry_jurisdiction', 'status', 'kyb_status')}
return self._result('get_organization_profile', 'success', 'OK', {'organization': public_org, 'portfolios': portfolios})
def _eligibility_error(self, position_id, reason, claim_protocol):
position = self._get('portfolio_position', position_id)
if position is None:
return None
portfolio = self._get('portfolio_account', position.get('portfolio_account_id'))
organization = self._get('organization', portfolio.get('organization_id')) if portfolio else None
batch = self._get('credit_batch', position.get('batch_id'))
project = self._get('offset_project', batch.get('project_id')) if batch else None
if organization is None or organization.get('status') != 'active' or organization.get('kyb_status') != 'verified':
return 'ORGANIZATION_NOT_ELIGIBLE: the owning organization is not currently eligible'
if portfolio is None or portfolio.get('status') != 'active':
return 'PORTFOLIO_NOT_ACTIVE: the position is not held in an active portfolio'
if batch is None or batch.get('status') != 'issued':
return 'BATCH_NOT_RETIRABLE: the linked credit batch is not currently usable'
policy = self.policy_cells.get((str(batch.get('standard')), reason)) if batch else None
if policy is None:
return 'RETIREMENT_POLICY_NOT_FOUND: no policy cell covers this condition'
if claim_protocol is not None and claim_protocol != policy['claim_protocol']:
return 'CLAIM_PROTOCOL_MISMATCH: claim protocol does not match the current policy'
if project is None or project.get('registration_status') != policy['registration_status'] or project.get('project_type') != policy['project_type']:
return 'PROJECT_NOT_ELIGIBLE: the linked project does not satisfy the current retirement policy'
return None
def _retire(self, arguments):
retirement = self._get('retirement', arguments['retirement_id'])
if retirement:
position = next((row for row in self._rows('portfolio_position') if row.get('portfolio_account_id') == retirement.get('portfolio_account_id') and row.get('batch_id') == retirement.get('batch_id')), None)
if position:
error = self._eligibility_error(position['position_id'], str(retirement.get('reason')), retirement.get('claim_protocol'))
if error:
return self._result('retire_credits', 'error', error)
return self.server.call_tool('retire_credits', state_manager=self.manager, completion_time='2026-09-24T12:00:00Z', **arguments)
def _sanitize(self, tool, result):
if not isinstance(result, dict) or not isinstance(result.get('content'), dict):
return self._result(tool, 'error', 'UPSTREAM_TOOL_ERROR: invalid raw response')
if result['content'].get('status') == 'error':
message = str(result['content'].get('message') or 'UPSTREAM_TOOL_ERROR')
if message.startswith('INTERNAL_ERROR') or 'traceback' in message.lower():
return self._result(tool, 'error', 'UPSTREAM_TOOL_ERROR: raw tool execution failed')
return result
def _raw_snapshot(self, entities=DATA__RAW_SNAPSHOT_DEFAULT):
return {entity: mod_copy.deepcopy(self._rows(entity)) for entity in entities}
def _restore_raw(self, snapshot):
for (entity, rows) in snapshot.items():
self.manager.db.save(entity, mod_copy.deepcopy(rows))
def business_hash(self):
return mod_hashlib.sha256(fn__canonical({entity: self._rows(entity) for entity in DATA__RAW_SNAPSHOT_DEFAULT}).encode()).hexdigest()
def semantic_hash(self):
return mod_hashlib.sha256(fn__canonical(self.snapshot()).encode()).hexdigest()
def activate_task(self, task_id, allowance=100):
if not isinstance(task_id, str) or not task_id:
raise ValueError('task_id must be non-empty')
self.active_task_id = task_id
self.initial_budget = int(allowance)
self.remaining = int(allowance)
self.task_entry_snapshot = self.snapshot()
return {'task_id': task_id, 'allowance': self.remaining, 'world_reset': False}
def business_events(self, since_receipt=0):
return mod_copy.deepcopy([row for row in self.receipts if row['index'] > since_receipt])
def grade_targets(self, targets=None):
if self.task_entry_snapshot is None:
raise RuntimeError('activate_task must be called before grading')
try:
PUBLIC_T01_TARGETS = DATA_PUBLIC_T01_TARGETS
grade_retirement_targets = fn_grade_retirement_targets
except ImportError:
from diagnostic import PUBLIC_T01_TARGETS, grade_retirement_targets
return grade_retirement_targets(self.task_entry_snapshot, self.snapshot(), targets or PUBLIC_T01_TARGETS)
def _carbon_priority_world_init(self, source=CASE_DIR / 'raw', snapshot=None):
self._carbon_evolution_init(source=source)
self.stream_targets = ext_deepcopy(DATA_TARGETS_2)
if snapshot is not None:
self.restore(snapshot)
def _carbon_credits_adapter_snapshot(self):
return {'schema': 'carbon-credits-adapter-snapshot/v1', 'source_fingerprint': self.source_fingerprint, 'raw': self._raw_snapshot(), 'remaining': self.remaining, 'receipts': mod_copy.deepcopy(self.receipts), 'policy_cells': [{'standard': standard, 'reason': reason, **mod_copy.deepcopy(cell)} for ((standard, reason), cell) in sorted(self.policy_cells.items())], 'applied_boundary_events': sorted(self.applied_boundary_events), 'active_task_id': self.active_task_id}
def _carbon_credits_rule_successor_snapshot(self):
value = self._carbon_credits_rule_successor_snapshot_2()
value['schema'] = 'rescopebench-carbon-credits-rule-stream/v7'
value['evidence_v7'] = {'secret': self.evidence_secret, 'issued_policy_evidence': ext_deepcopy(self.issued_policy_evidence), 'issued_candidate_listings': ext_deepcopy(self.issued_candidate_listings), 'issued_batch_inspections': ext_deepcopy(self.issued_batch_inspections), 'rule_revalidation': ext_deepcopy(self.rule_revalidation), 'attempted_target_ids': sorted(self.attempted_target_ids)}
value['successor'] = {'case_version': 'carbon-credits-rule-v7', 'parent_case_version': 'carbon-credits-rule-v5', 'provider_tools_sha256': '34c2ee05393e8c3430cf8f40c369f50180d785999f8e367adb45644f6bda06fc', 'work_budget': 134, 'policy_evidence_cost': 27, 'changed_rules': list(DATA_CHANGED_RULES)}
return value
def _carbon_credits_stream_adapter_restore(self, snapshot):
if snapshot.get('schema') != 'rescopebench-carbon-credits-persistent-stream/v2':
raise ValueError('unsupported Carbon Credits stream snapshot')
self._carbon_credits_adapter_restore(snapshot)
stream = snapshot.get('stream') or {}
self.prepared_tasks = list(stream.get('prepared_tasks') or [])
self.boundary_receipts = ext_deepcopy(stream.get('boundary_receipts') or [])
self.active_position_ids = set(stream.get('active_position_ids') or [])
self.released_batch_ids = set(stream.get('released_batch_ids') or [])
self.call_count = int(stream.get('call_count', 0))
self.drift_event_sequence = int(stream.get('drift_event_sequence', 0))
self.task_entry_snapshot = ext_deepcopy(stream.get('task_entry_snapshot'))
def _carbon_credits_rule_successor_grade(self):
grade = self._carbon_credits_stream_adapter_grade()
for artifact in grade['artifacts']:
artifact['score'] = 25.0 if artifact.get('complete') else 0.0
grade['score'] = sum((artifact['score'] for artifact in grade['artifacts']))
grade['complete_artifacts'] = sum((bool(artifact.get('complete')) for artifact in grade['artifacts']))
return grade
def _carbon_credits_rule_successor_policy_evidence_v7(self, arguments):
condition = (arguments['standard'], arguments['reason'])
cell = self._visible_policy_cell(condition)
if cell is None:
return self._result('search_retirement_policy_evidence', 'success', 'OK', {'total_count': 0, 'evidence': []})
token = self._policy_token(condition, cell)
evidence = {**self._public_cell(condition, cell), 'policy_evidence_id': token}
self.issued_policy_evidence[token] = ext_deepcopy(evidence)
rule = next((atom for (atom, value) in DATA_CHANGED_CONDITIONS.items() if value == condition), None)
if rule and self.rule_revalidation.get(rule) == 'awaiting_current_policy':
self.rule_revalidation[rule] = 'ready_current'
return self._result('search_retirement_policy_evidence', 'success', 'OK', {'total_count': 1, 'evidence': [evidence]})
def _carbon_credits_rule_successor_cost(self, tool, arguments):
if tool == 'search_retirement_policy_evidence':
return 26
return self._carbon_credits_adapter_cost(tool, arguments)
def _carbon_credits_adapter_close(self):
mod_shutil.rmtree(self.runtime_root, ignore_errors=True)
def _carbon_credits_adapter_batch_detail(self, arguments):
batch = self._get('credit_batch', arguments['batch_id'])
if batch is None:
return self._result('get_credit_batch', 'error', 'BATCH_NOT_FOUND: batch_id was not found')
project = self._get('offset_project', batch.get('project_id'))
public_batch = {key: batch.get(key) for key in ('batch_id', 'project_id', 'standard', 'vintage_year', 'credit_type', 'status', 'available_credits', 'reserved_credits', 'retired_credits', 'expiry_date')}
public_project = None
if project:
public_project = {key: project.get(key) for key in ('project_id', 'project_name', 'standard', 'project_type', 'host_country', 'registration_status', 'methodology_code')}
return self._result('get_credit_batch', 'success', 'OK', {'batch': public_batch, 'project': public_project})
def _carbon_credits_adapter_policy_evidence(self, arguments):
evidence = fn_public_policy_evidence(self.policy_cells, arguments['standard'], arguments['reason'])
if evidence is None:
return self._result('search_retirement_policy_evidence', 'success', 'OK', {'total_count': 0, 'evidence': []})
return self._result('search_retirement_policy_evidence', 'success', 'OK', {'total_count': 1, 'evidence': [evidence]})
def _carbon_credits_adapter_submit(self, arguments):
error = self._eligibility_error(arguments['position_id'], arguments['reason'], arguments['claim_protocol'])
if error:
return self._result('submit_retirement_request', 'error', error)
raw_arguments = {key: value for (key, value) in arguments.items() if key != 'claim_protocol'}
result = self.server.call_tool('submit_retirement_request', state_manager=self.manager, **raw_arguments)
retirement_id = result.get('content', {}).get('data', {}).get('retirement_id')
if result.get('content', {}).get('status') == 'success' and retirement_id:
retirement = self._get('retirement', retirement_id)
if retirement is not None:
retirement['claim_protocol'] = arguments['claim_protocol']
self.manager.db.save('retirement', [retirement if row.get('retirement_id') == retirement_id else row for row in self._rows('retirement')])
return result
def _carbon_evolution_init(self, source=CASE_DIR / 'raw', snapshot=None):
self._carbon_credits_rule_successor_init(source=source)
self.stream_targets = ext_deepcopy(DATA_TARGETS_3)
positions = self._rows('portfolio_position')
for row in positions:
row['quantity_available'] *= 2
self.manager.db.save('portfolio_position', positions)
self._normalize_batch_ledgers()
self._frozen_raw_baseline = self._raw_snapshot()
self.evidence_secret = fn_digest(['carbon-three-event-lifecycle-evolution-v1', self.source_fingerprint])
if snapshot is not None:
self.restore(snapshot)
def _carbon_credits_rule_successor_snapshot_2(self):
value = self._carbon_credits_rule_successor_snapshot_3()
value['schema'] = 'rescopebench-carbon-credits-rule-stream/v5'
value['successor'] = {'case_version': 'carbon-credits-rule-v5', 'parent_case_version': 'carbon-credits-rule-v4', 'provider_tools_sha256': '6c0fc8c3ea2349a5503a82ec4318d097b51ee6bcfa7f5f9ce98064a63e10d445', 'work_budget': 134, 'policy_evidence_cost': 26, 'changed_rules': list(DATA_CHANGED_RULES)}
return value
def _carbon_credits_adapter_restore(self, snapshot):
if snapshot.get('source_fingerprint') != self.source_fingerprint:
raise ValueError('snapshot source fingerprint does not match this adapter')
self._restore_raw(mod_copy.deepcopy(snapshot['raw']))
self.remaining = int(snapshot['remaining'])
self.receipts = mod_copy.deepcopy(snapshot['receipts'])
self.policy_cells = {(row['standard'], row['reason']): {key: value for (key, value) in row.items() if key not in {'standard', 'reason'}} for row in snapshot['policy_cells']}
self.applied_boundary_events = set(snapshot.get('applied_boundary_events', []))
self.active_task_id = snapshot.get('active_task_id')
def _carbon_credits_stream_adapter_grade(self):
return self.grade_targets(self.task_targets())
def _carbon_credits_adapter_cost(self, tool, arguments):
if tool in DATA_LIST_TOOLS:
limit = arguments.get('limit', 3) if isinstance(arguments, dict) else 3
if not isinstance(limit, int) or isinstance(limit, bool) or (not 1 <= limit <= 10):
limit = 3
return 4 + 2 * limit
if tool in {'get_organization_profile', 'get_credit_batch'}:
return 7
if tool == 'search_retirement_policy_evidence':
return 16
if tool in DATA_WRITE_TOOLS_2:
return 10
return 0
def _carbon_credits_rule_successor_init(self, source=CASE_DIR / 'raw', snapshot=None):
self.evidence_secret = ''
self.issued_policy_evidence: dict[str, dict[str, ext_Any]] = {}
self.issued_candidate_listings: dict[str, dict[str, ext_Any]] = {}
self.issued_batch_inspections: dict[str, dict[str, ext_Any]] = {}
self.rule_revalidation: dict[str, str] = {}
self.attempted_target_ids: set[str] = set()
self._frozen_raw_baseline: dict[str, ext_Any] = {}
self._carbon_credits_rule_successor_init_2(source=source)
self.stream_targets = ext_deepcopy(DATA_SUCCESSOR_TARGETS)
self._frozen_raw_baseline = self._raw_snapshot()
self.evidence_secret = fn_digest(['carbon-v7-evidence-secret', self.source_fingerprint])
if snapshot is not None:
self.restore(snapshot)
def _carbon_credits_rule_successor_snapshot_3(self):
value = self._carbon_credits_rule_successor_snapshot_4()
value['schema'] = 'rescopebench-carbon-credits-rule-stream/v4'
value['successor'] = {'case_version': 'carbon-credits-rule-v4', 'provider_tools_sha256': '6c0fc8c3ea2349a5503a82ec4318d097b51ee6bcfa7f5f9ce98064a63e10d445', 'work_budget': 134, 'changed_rules': list(DATA_CHANGED_RULES)}
return value
def _carbon_credits_rule_successor_init_2(self, source=CASE_DIR / 'raw', snapshot=None):
self._carbon_credits_rule_successor_init_3(source=source)
if snapshot is not None:
self.restore(snapshot)
def _carbon_credits_rule_successor_snapshot_4(self):
value = World._carbon_credits_stream_adapter_snapshot(self)
value['schema'] = 'rescopebench-carbon-credits-rule-stream/v3'
value['successor'] = {'case_version': 'carbon-credits-rule-v3', 'provider_tools_sha256': '6c0fc8c3ea2349a5503a82ec4318d097b51ee6bcfa7f5f9ce98064a63e10d445', 'work_budget': 134}
return value
def _carbon_credits_rule_successor_init_3(self, source=CASE_DIR / 'raw', snapshot=None):
with mod__isolation._IMPORT_LOCK:
previous = mod_sys.dont_write_bytecode
mod_sys.dont_write_bytecode = True
try:
self._carbon_credits_rule_successor_init_4(source=source)
finally:
mod_sys.dont_write_bytecode = previous
self.stream_targets = ext_deepcopy(DATA_SUCCESSOR_TARGETS_2)
if snapshot is not None:
self.restore(snapshot)
def _carbon_credits_stream_adapter_snapshot(self):
value = self._carbon_credits_adapter_snapshot()
value['schema'] = 'rescopebench-carbon-credits-persistent-stream/v2'
value['stream'] = {'prepared_tasks': list(self.prepared_tasks), 'boundary_receipts': ext_deepcopy(self.boundary_receipts), 'active_position_ids': sorted(self.active_position_ids), 'released_batch_ids': sorted(self.released_batch_ids), 'call_count': self.call_count, 'drift_event_sequence': self.drift_event_sequence, 'task_entry_snapshot': ext_deepcopy(self.task_entry_snapshot)}
return value
def _carbon_credits_rule_successor_init_4(self, source=CASE_DIR / 'raw', snapshot=None):
self.source = ext_Path(source).resolve()
if not self.source.is_dir():
raise FileNotFoundError(self.source)
(self.server, StateManager, self.raw_module_origins) = fn__load_isolated_runtime(self.source)
self.runtime_root = ext_Path(mod_tempfile.mkdtemp(prefix='rescope_carbon_rule_v3_'))
mod_shutil.copytree(self.source / 'data/database', self.runtime_root / 'database')
self.manager = StateManager(str(self.runtime_root / 'database'))
self._normalize_batch_ledgers()
self.source_fingerprint = fn_digest_2({entity: self._rows(entity) for entity in DATA__RAW_SNAPSHOT_DEFAULT})
self.initial_budget = 134
self.remaining = 134
self.receipts: list[dict[str, ext_Any]] = []
self.policy_cells = ext_deepcopy(DATA_PRE_POLICY_CELLS)
self.applied_boundary_events: set[str] = set()
self.active_task_id: str | None = None
self.task_entry_snapshot: dict[str, ext_Any] | None = None
self.stream_targets = ext_deepcopy(DATA_SUCCESSOR_TARGETS_3)
self.prepared_tasks: list[str] = []
self.boundary_receipts: list[dict[str, ext_Any]] = []
self.active_position_ids: set[str] = set()
self.released_batch_ids: set[str] = set()
self.call_count = 0
self.drift_event_sequence = 0
self._install_stream_slice()
if snapshot is not None:
self.restore(snapshot)