SYNTOLOGY HomeExplorerAtlasCodeMethodologyAboutDevelopersFeedPricing
Paper · 2608.24275 · 2026

RePolicy: Reinforcement Learning for Safety-Policy Invocation in Agent Safeguards REPOLICY: REINFORCEMENT LEARNING FOR SAFETY-POLICY INVOCATION IN AGENT SAFEGUARDS

Xiang Wang, Xiangnan He, Junfeng Fang, Boxuan Zhang, Houcheng Jiang, Qiyong Zhong

arXiv · PDF · Open in the Atlas

Code that ran

7 of 7 samples (functions and classes) lifted from this paper's linked repositories executed on a synthesized input in Syntology's jail (0 of them constructed an object rather than computing a result; 1 honoured the contract we drafted, 0 violated it and 0 have no contract verdict; 6 failures of our instrument; 0 no recorded run), measured 2026-11-24; bodies inline only under a permissive licence as GitHub detects it. Not a reproduction of the paper's results.

"Ran" means the function executed on a synthesized input and returned a value. It is not a reproduction of the paper's results. This record, dated, as JSON: /api/ran/2608.24275.json · badge: /api/ran/2608.24275.svg

Each repository's role is a label: a classifier's output recorded on the link, or, where no role is recorded, what the Papers with Code archive marked. The line under it names its basis. Neither says who wrote the code.

RepositoryRoleRan
jianghoucheng/RePolicy community
Papers with Code archive
7 ran · 0 no recorded run
FunctionStatusWhere it lives
_safe_extra_info Ran
ran; our contract draft was wrong, not the code
jianghoucheng/RePolicy/repolicy/reward.py
code served (permissive licence) · get_code("32dc96cedc1539d7")
How it ran

Ran in Syntology's sandbox on this synthesized input (drafted by a language model, Claude Haiku 4.5, prompt python_fixture_v1) and returned dict. The image it ran in was not recorded. If your copy returns the same type on these inputs, it matched what we observed; nothing here checks that. It does NOT mean the output is correct: nothing has compared it to the paper.

import json
from typing import Any

def _safe_extra_info(extra_info: Any) -> dict[str, Any]:
    if not isinstance(extra_info, dict):
        return {}
    out = dict(extra_info)
    for key in ['local_to_global_policy', 'local_to_global_clause', 'global_to_local_policy', 'global_to_local_clause']:
        if isinstance(out.get(key), str):
            try:
                out[key] = json.loads(out[key])
            except Exception:
                out[key] = {}
    return out


# Test case 1: dict with JSON string values
extra_info_1 = {
    'local_to_global_policy': '{"rule": "test"}',
    'local_to_global_clause': '{"clause": 1}',
    'global_to_local_policy': '{"policy": "valid"}',
    'global_to_local_clause': '{"invalid json',
    'other_key': 'some_value'
}

# Test case 2: dict with non-string values
extra_info_2 = {
    'local_to_global_policy': {'already': 'dict'},
    'local_to_global_clause': 123,
    'global_to_local_policy': None,
    'global_to_local_clause': ['list', 'value']
}

# Test case 3: non-dict input
extra_info_3 = "not a dict"

# Test case 4: empty dict
extra_info_4 = {}

# Test case 5: dict with only some special keys
extra_info_5 = {
    'local_to_global_policy': '{"valid": "json"}',
    'random_key': 'random_value'
}

ARGS = {
    'extra_info': extra_info_1
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1
Imports
none outside the standard library — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type dict — a dict output has no array shape of its own; none is stated — the instrument coerces any output to an array; for a dict output the recorded ndim 0 and dtype family float describe that coercion, not the output, and are not stated
Environment
image not recorded; re-verify against syntology-harvest-sandbox:v5-deps; not recorded for this sample: the harness installs a cuda-to-cpu shim (cuda_shim.py) before every sample and no run records whether a sample needed it; seed: none by the harness; any seed is in the setup block
compute_policy_reward Ran
ran, honoured the contract we drafted
jianghoucheng/RePolicy/repolicy/reward.py
code served (permissive licence) · get_code("145372cb0ea2e9c6")
How it ran

Ran in Syntology's sandbox on this synthesized input (drafted by a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API) and returned tuple, ndim 1, dtype family float; no output shape is stated. The image it ran in was not recorded. If your copy returns the same type and ndim on these inputs, it matched what we observed; nothing here checks that. It does NOT mean the output is correct: nothing has compared it to the paper.

import json
import re

# Set up seed for reproducibility
import torch
torch.manual_seed(0)

# Define test data
solution_str = '''
json
{
    "name": "get_policy",
    "arguments": {
        "policy_ids": ["Policy_1", "Policy_A", "Policy_2"]
    }
}

'''

extra_info = {
    "gold_local_policy_ids": ["Policy_1", "Policy_2"],
    "decoy_local_policy_ids": ["Policy_X", "Policy_Y"]
}

ARGS = {
    "solution_str": solution_str,
    "extra_info": extra_info
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
torch — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type tuple, ndim 1, dtype family float — a tuple output has no array shape of its own; none is stated
dtype family
int means an integer dtype; float means any other dtype the instrument saw, bool and complex included (fixture_check.py records only these two families)
Environment
image not recorded; re-verify against syntology-harvest-sandbox:v5-deps; not recorded for this sample: the harness installs a cuda-to-cpu shim (cuda_shim.py) before every sample and no run records whether a sample needed it; seed: none by the harness; any seed is in the setup block
compute_score Ran
ran; our contract draft was wrong, not the code
jianghoucheng/RePolicy/repolicy/reward.py
code served (permissive licence) · get_code("f25814da449d7149")
How it ran

Ran in Syntology's sandbox on this synthesized input (drafted by a language model, Claude Haiku 4.5, prompt python_fixture_v1) and returned dict. The image it ran in was not recorded. If your copy returns the same type on these inputs, it matched what we observed; nothing here checks that. It does NOT mean the output is correct: nothing has compared it to the paper.

import json

ARGS = {
    'data_source': 'test_data_source',
    'solution_str': '''
    <JUDGE>unsafe</JUDGE>
    
    <tool_call>
    {"name": "get_policy", "arguments": {"policy_ids": ["Policy_1", "Policy_2"]}}
    </tool_call>
    ''',
    'ground_truth': {
        'label': 'unsafe'
    },
    'extra_info': {
        'gold_label': 'unsafe',
        'gold_local_policy_ids': [1, 2],
        'decoy_local_policy_ids': [3, 4],
        'local_to_global_policy': '{}',
        'local_to_global_clause': '{}',
        'global_to_local_policy': '{}',
        'global_to_local_clause': '{}'
    }
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1
Imports
none outside the standard library — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type dict — a dict output has no array shape of its own; none is stated — the instrument coerces any output to an array; for a dict output the recorded ndim 0 and dtype family float describe that coercion, not the output, and are not stated
Environment
image not recorded; re-verify against syntology-harvest-sandbox:v5-deps; not recorded for this sample: the harness installs a cuda-to-cpu shim (cuda_shim.py) before every sample and no run records whether a sample needed it; seed: none by the harness; any seed is in the setup block
extract_judge_label Ran
ran; our contract draft was wrong, not the code
jianghoucheng/RePolicy/repolicy/reward.py
code served (permissive licence) · get_code("48488830b0aa3e65")
How it ran

Ran in Syntology's sandbox on this synthesized input (drafted by a language model, Claude Haiku 4.5, prompt python_fixture_v1) and returned tuple, ndim 1, dtype family float; no output shape is stated. The image it ran in was not recorded. If your copy returns the same type and ndim on these inputs, it matched what we observed; nothing here checks that. It does NOT mean the output is correct: nothing has compared it to the paper.

import re

JUDGE_TAG_RE = re.compile('<JUDGE>\\s*(safe|unsafe)\\s*</JUDGE>', re.IGNORECASE)

LABEL_WORD_RE = re.compile('\\b(safe|unsafe)\\b', re.IGNORECASE)

RESULT_LINE_RE = re.compile('(?:judge|judgment|judge_result|result|label)\\s*[::]\\s*(safe|unsafe)\\b', re.IGNORECASE)

def strip_markdown_fences(text: str) -> str:
    text = (text or '').strip()
    if text.startswith('```'):
        text = re.sub('^```(?:json|text)?', '', text, flags=re.IGNORECASE).strip()
        text = re.sub('```$', '', text).strip()
    return text

def extract_judge_label(text: str) -> tuple[str | None, float]:
    """Extract safe/unsafe with a forgiving format score."""
    text = strip_markdown_fences(text)
    match = JUDGE_TAG_RE.search(text)
    if match:
        return (match.group(1).lower(), 1.0)
    match = RESULT_LINE_RE.search(text)
    if match:
        return (match.group(1).lower(), 0.7)
    labels = [m.group(1).lower() for m in LABEL_WORD_RE.finditer(text)]
    unique = set(labels)
    if len(unique) == 1:
        return (labels[-1], 0.4)
    return (None, 0.0)


ARGS = {
    "text": "<JUDGE>safe</JUDGE>"
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1
Imports
none outside the standard library — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type tuple, ndim 1, dtype family float — a tuple output has no array shape of its own; none is stated
dtype family
int means an integer dtype; float means any other dtype the instrument saw, bool and complex included (fixture_check.py records only these two families)
Environment
image not recorded; re-verify against syntology-harvest-sandbox:v5-deps; not recorded for this sample: the harness installs a cuda-to-cpu shim (cuda_shim.py) before every sample and no run records whether a sample needed it; seed: none by the harness; any seed is in the setup block
extract_tool_policy_ids Ran
ran; our contract draft was wrong, not the code
jianghoucheng/RePolicy/repolicy/reward.py
code served (permissive licence) · get_code("7699b17ed75b44ad")
How it ran

Ran in Syntology's sandbox on this synthesized input (drafted by a language model, Claude Haiku 4.5, prompt python_fixture_v1) and returned tuple, ndim 1, dtype family float; no output shape is stated. The image it ran in was not recorded. If your copy returns the same type and ndim on these inputs, it matched what we observed; nothing here checks that. It does NOT mean the output is correct: nothing has compared it to the paper.

import json
import re

MAX_POLICIES_PER_CALL = 5

POLICY_RE = re.compile('\\bPolicy_(?:\\d+|[A-Z]{1,2})\\b')

TOOL_CALL_RE = re.compile('<tool_call>\\s*(\\{.*?\\})\\s*</tool_call>', re.DOTALL)

def strip_markdown_fences(text: str) -> str:
    text = (text or '').strip()
    if text.startswith('```'):
        text = re.sub('^```(?:json|text)?', '', text, flags=re.IGNORECASE).strip()
        text = re.sub('```$', '', text).strip()
    return text

def extract_tool_policy_ids(text: str) -> tuple[set[str], bool, int]:
    """Extract policy ids from the supported Qwen/Hermes tool-call form.

    Returns (policy_ids, valid_single_call, call_count). A valid call means the
    model called get_policy exactly once with 1..MAX_POLICIES_PER_CALL local
    policy ids.
    """
    text = strip_markdown_fences(text or '')
    matches = TOOL_CALL_RE.findall(text)
    if len(matches) != 1:
        return (set(), False, len(matches))
    try:
        obj = json.loads(matches[0])
    except Exception:
        return (set(), False, len(matches))
    if obj.get('name') != 'get_policy':
        return (set(), False, len(matches))
    arguments = obj.get('arguments')
    if not isinstance(arguments, dict):
        return (set(), False, len(matches))
    policy_ids = arguments.get('policy_ids')
    if not isinstance(policy_ids, list):
        return (set(), False, len(matches))
    parsed = {pid for pid in policy_ids if isinstance(pid, str) and POLICY_RE.fullmatch(pid)}
    valid = 1 <= len(parsed) <= MAX_POLICIES_PER_CALL and len(parsed) == len(policy_ids)
    return (parsed, valid, len(matches))


# Test case 1: Valid tool call with multiple policy IDs
valid_tool_call = '''<tool_call>
{
  "name": "get_policy",
  "arguments": {
    "policy_ids": ["Policy_1", "Policy_2", "Policy_A"]
  }
}
</tool_call>'''

# Test case 2: Valid tool call with markdown fences
valid_with_markdown = '''```json
<tool_call>
{
  "name": "get_policy",
  "arguments": {
    "policy_ids": ["Policy_0"]
  }
}
</tool_call>
'''

# Test case 3: Invalid - no tool calls
no_tool_call = "This is just plain text"

# Test case 4: Valid - single policy ID
single_policy = '<tool_call>{"name": "get_policy", "arguments": {"policy_ids": ["Policy_X"]}}</tool_call>'

ARGS = {
    "text": valid_tool_call
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1
Imports
none outside the standard library — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type tuple, ndim 1, dtype family float — a tuple output has no array shape of its own; none is stated
dtype family
int means an integer dtype; float means any other dtype the instrument saw, bool and complex included (fixture_check.py records only these two families)
Environment
image not recorded; re-verify against syntology-harvest-sandbox:v5-deps; not recorded for this sample: the harness installs a cuda-to-cpu shim (cuda_shim.py) before every sample and no run records whether a sample needed it; seed: none by the harness; any seed is in the setup block
normalize_label Ran
ran; our contract draft was wrong, not the code
jianghoucheng/RePolicy/repolicy/reward.py
code served (permissive licence) · get_code("f67c43acf1151351")
How it ran

Ran in Syntology's sandbox on this synthesized input (drafted by a language model, Claude Haiku 4.5, prompt python_fixture_v1) and returned str. The image it ran in was not recorded. If your copy returns the same type on these inputs, it matched what we observed; nothing here checks that. It does NOT mean the output is correct: nothing has compared it to the paper.

import torch
import numpy as np

torch.manual_seed(0)

ARGS = {
    'label': 'safe'
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1
Imports
numpy, torch — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type str — a str output has no array shape of its own; none is stated — the instrument coerces any output to an array; for a str output the recorded ndim 0 and dtype family float describe that coercion, not the output, and are not stated
Environment
image not recorded; re-verify against syntology-harvest-sandbox:v5-deps; not recorded for this sample: the harness installs a cuda-to-cpu shim (cuda_shim.py) before every sample and no run records whether a sample needed it; seed: none by the harness; any seed is in the setup block
strip_markdown_fences Ran
ran; our contract draft was wrong, not the code
jianghoucheng/RePolicy/repolicy/reward.py
code served (permissive licence) · get_code("a3372598c979a291")
How it ran

Ran in Syntology's sandbox on this synthesized input (drafted by a language model, Claude Haiku 4.5, prompt python_fixture_v1) and returned str. The image it ran in was not recorded. If your copy returns the same type on these inputs, it matched what we observed; nothing here checks that. It does NOT mean the output is correct: nothing has compared it to the paper.

import re

def strip_markdown_fences(text: str) -> str:
    text = (text or '').strip()
    if text.startswith('```'):
        text = re.sub('^```(?:json|text)?', '', text, flags=re.IGNORECASE).strip()
        text = re.sub('```$', '', text).strip()
    return text

# Test cases for the function
ARGS = {
    "text": "```json\n{\"key\": \"value\"}\n```"
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1
Imports
none outside the standard library — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type str — a str output has no array shape of its own; none is stated — the instrument coerces any output to an array; for a str output the recorded ndim 0 and dtype family float describe that coercion, not the output, and are not stated
Environment
image not recorded; re-verify against syntology-harvest-sandbox:v5-deps; not recorded for this sample: the harness installs a cuda-to-cpu shim (cuda_shim.py) before every sample and no run records whether a sample needed it; seed: none by the harness; any seed is in the setup block

Also present in other papers' code

Of 7 samples lifted from this paper's linked repositories, 7 carry a function identity and 0 do not. Of the 7 distinct functions with an identity, 0 are also present in other papers whose code we hold (0 with at least one paper dated earlier, 0 the same month, 0 later) and 7 are only here among the 52,977 papers whose code Syntology holds (as of 2026-09-26).

Only here means: among the 52,977 papers whose code Syntology holds (51,887 with lifted samples, 1,090 through their assemblies only), as of 2026-09-26, no other paper's lifted samples or current assembly bricks contain an identical function body after normalisation.

Presence, not direction: an identical function body in two papers' repositories does not say who wrote it, which came from which, or that either paper's method rests on it. Matching is exact after normalisation, so a renamed or edited function is not matched. Dates are when papers appeared, not when code was written. Only .py files the harvester lifted are covered; notebooks are not read. A new-style arXiv id YYMM.NNNN dates a paper to the month 20YY-MM; otherwise Paper.year dates it to the year; otherwise it is undated. Dates are when the paper appeared, not when the code was written. Read 2026-11-24.

Repositories linked to this paper

Some links come from the archived Papers with Code dataset (CC BY-SA 4.0): attribution and licence.

Abstract

Safeguarding language model agents requires assessing complete execution trajectories under context-dependent safety policies. Existing policy-aware safeguards mainly rely on prompting or supervised fine-tuning, limiting their ability to adapt to unseen trajectories and changing policy contexts. We propose RePolicy, an agent safeguard that learns safety-policy invocation through reinforcement learning. Given an agent trajectory and a dynamic policy library, RePolicy invokes the applicable policy and uses its content to produce a policygrounded rationale and safety judgment. We construct PolicyTraj-20K to support supervised initialization, followed by GRPO with verifiable rewards and policy-context perturbation. Experiments across six agent safety benchmarks show that RePolicy achieves strong overall safety-detection performance and robust policy invocation under varying policy contexts. Our code is available at: https://github.com/jianghoucheng/RePolicy

For agents

The same record, over MCP at https://syntology.ai/mcp:

get_harvested_code_for_paper("2608.24275")
get_code_for_paper("2608.24275")
have("2608.24275")

The run record, dated, one paper per request, free:

curl https://syntology.ai/api/ran/2608.24275.json

A badge for a README (the split and the date, never a ratio):

[![Syntology run record](https://syntology.ai/api/ran/2608.24275.svg)](https://syntology.ai/paper/2608.24275)

Connect an agent — have() is free.