Skip to content

zrwangems/dsh-zrwang-plugin / ars/skills/sr-screener

sr-screener

Flagged

系统综述文献筛选:把方案或 PROSPERO 协议转成资格规则,双盲筛选标题摘要与全文,第三人裁决冲突,输出 PRISMA 2020 计数、EndNote/Zotero RIS 分组与可交付给论文技能的 literature_corpus。Triggers: systematic review screening, screen papers, PRISMA counts, pilot screening, adjudicate conflicts | 文献筛选, 系统综述筛选, PRISMA 计数, 筛选冲突裁决。

FileKindSize
SKILL.mdskill md33.1 KB
_shared/ARCHITECTURE.mdmarkdown51.7 KB
_shared/MODE_REGISTRY.mdmarkdown6.7 KB
_shared/agents/compliance_agent.mdmarkdown9.4 KB
_shared/artifact_reproducibility_pattern.mdmarkdown9.8 KB
_shared/benchmark_report.schema.jsonconfig2.7 KB
_shared/benchmark_report_pattern.mdmarkdown8.8 KB
_shared/bibliographic_integrity_signals.mdmarkdown8.1 KB
_shared/collaboration_depth_rubric.mdmarkdown11.5 KB
_shared/compliance_checkpoint_protocol.mdmarkdown8.9 KB
_shared/compliance_report.schema.jsonconfig8.1 KB
_shared/contracts/README.mdmarkdown54.7 KB
_shared/contracts/activity/adjudication_activity_input.schema.jsonconfig18.5 KB
_shared/contracts/activity/adjudication_activity_store.schema.jsonconfig18.7 KB
_shared/contracts/audit/audit_jsonl.schema.jsonconfig5.4 KB
_shared/contracts/audit/audit_sidecar.schema.jsonconfig8.4 KB
_shared/contracts/audit/audit_verdict.schema.jsonconfig5.4 KB
_shared/contracts/audit/cross_document_consistency_advisory.schema.jsonconfig20.4 KB
_shared/contracts/audit/cross_document_consistency_advisory_draft.schema.jsonconfig23.4 KB
_shared/contracts/audit/cross_document_source_manifest.schema.jsonconfig6.3 KB
_shared/contracts/audit/tortured_phrase_advisory.schema.jsonconfig30.9 KB
_shared/contracts/audit/tortured_phrase_snapshot.schema.jsonconfig4.9 KB
_shared/contracts/audit/tortured_phrase_snapshot_manifest.schema.jsonconfig7.3 KB
_shared/contracts/capability/stage_capability_matrix.jsonconfig23.5 KB
_shared/contracts/claim_standing/candidate_ledger.schema.jsonconfig23.1 KB
_shared/contracts/claim_standing/query_plan.schema.jsonconfig12.7 KB
_shared/contracts/claim_standing/query_plan_v1_1.schema.jsonconfig20.3 KB
_shared/contracts/claim_standing/retrieval_input.schema.jsonconfig14.4 KB
_shared/contracts/claim_standing/stance_record.schema.jsonconfig11.7 KB
_shared/contracts/claim_standing/transmission_ledger.schema.jsonconfig7.6 KB
_shared/contracts/cross_model/codex_citation_receipt.schema.jsonconfig4.7 KB
_shared/contracts/cross_model/codex_citation_request.schema.jsonconfig986 B
_shared/contracts/cross_model/promotion_bakeoff_sealed_commitment.schema.jsonconfig1.5 KB
_shared/contracts/cross_model/promotion_bakeoff_sealed_reveal.schema.jsonconfig1.5 KB
_shared/contracts/degradation_registry.jsonconfig42.5 KB
_shared/contracts/evaluator/full.jsonconfig6.3 KB
_shared/contracts/evidence/claim_registry.schema.jsonconfig2.3 KB
_shared/contracts/evidence/claim_registry_coverage_report.schema.jsonconfig4.8 KB
_shared/contracts/evidence/evidence_row.schema.jsonconfig14.3 KB
_shared/contracts/evidence/evidence_row_v1_1.schema.jsonconfig11.4 KB
_shared/contracts/evidence/evidence_row_v1_2.schema.jsonconfig21.8 KB
_shared/contracts/evidence/evidence_row_v1_3.schema.jsonconfig10.7 KB
_shared/contracts/human_subjects/authority_profile_registry.schema.jsonconfig16.7 KB
_shared/contracts/human_subjects/committee_correspondence.schema.jsonconfig9.9 KB
_shared/contracts/human_subjects/content_coverage_advisory.schema.jsonconfig19.9 KB
_shared/contracts/human_subjects/irb_context_record.schema.jsonconfig12.1 KB
_shared/contracts/human_subjects/resolved_authority_context.schema.jsonconfig11.8 KB
_shared/contracts/human_subjects/review_pathway_rule_trace.schema.jsonconfig9.5 KB
_shared/contracts/human_subjects/review_pathway_trace_request.schema.jsonconfig4.8 KB
_shared/contracts/human_subjects/submission_packet_inventory.schema.jsonconfig8.5 KB
_shared/contracts/human_subjects/submission_packet_manifest.schema.jsonconfig32.2 KB
_shared/contracts/passport/audit_artifact_entry.schema.jsonconfig10.8 KB
_shared/contracts/passport/bibliographic_integrity_signal.schema.jsonconfig48.9 KB
_shared/contracts/passport/citation_provenance.schema.jsonconfig4.8 KB
_shared/contracts/passport/citation_verification_summary.schema.jsonconfig8.2 KB
_shared/contracts/passport/claim_audit_result.schema.jsonconfig7.8 KB
_shared/contracts/passport/claim_drift.schema.jsonconfig3.8 KB
_shared/contracts/passport/claim_intent_manifest.schema.jsonconfig6.6 KB
_shared/contracts/passport/constraint_violation.schema.jsonconfig3.6 KB
_shared/contracts/passport/excluded_source_entry.schema.jsonconfig1.7 KB
_shared/contracts/passport/experiment_alignment_result.schema.jsonconfig4.8 KB
_shared/contracts/passport/experiment_provenance_entry.schema.jsonconfig10.0 KB
_shared/contracts/passport/human_read_log.schema.jsonconfig3.8 KB
_shared/contracts/passport/inquiry_ledger_ref.schema.jsonconfig881 B
_shared/contracts/passport/literature_corpus_entry.schema.jsonconfig30.3 KB
_shared/contracts/passport/preregistration_artifact.schema.jsonconfig4.3 KB
_shared/contracts/passport/rejection_log.schema.jsonconfig3.3 KB
_shared/contracts/passport/reset_ledger_entry.schema.jsonconfig7.1 KB
_shared/contracts/passport/run_ledger.schema.jsonconfig8.0 KB
_shared/contracts/passport/standing_constraint_entry.schema.jsonconfig2.6 KB
_shared/contracts/passport/temporal_audit_results.schema.jsonconfig8.8 KB
_shared/contracts/passport/terminal_policies.schema.jsonconfig8.1 KB
_shared/contracts/passport/timeline.schema.jsonconfig4.7 KB
_shared/contracts/passport/uncited_assertion.schema.jsonconfig3.3 KB
_shared/contracts/passport/uncited_audit_failure.schema.jsonconfig4.4 KB
_shared/contracts/passport/user_attested_read_resolution.schema.jsonconfig3.2 KB
_shared/contracts/passport/version_records.schema.jsonconfig4.9 KB
_shared/contracts/patch/block_manifest.schema.jsonconfig2.1 KB
_shared/contracts/patch/legacy/v1_0/revision_patch.schema.jsonconfig5.3 KB
_shared/contracts/patch/revision_patch.schema.jsonconfig8.9 KB
_shared/contracts/pdf/pdf_content_classifier_diagnostic.schema.jsonconfig1.2 KB
_shared/contracts/pdf/pdf_content_classifier_worker.schema.jsonconfig2.2 KB
_shared/contracts/pdf/pdf_read_preflight.schema.jsonconfig6.8 KB
_shared/contracts/re_review/input_manifest.schema.jsonconfig7.6 KB
_shared/contracts/re_review/legacy/v1_0/input_manifest.schema.jsonconfig6.2 KB
_shared/contracts/re_review/legacy/v1_0/precommitment.schema.jsonconfig8.9 KB
_shared/contracts/re_review/legacy/v1_0/traceability.schema.jsonconfig34.2 KB
_shared/contracts/re_review/legacy/v1_0/verdict_record.schema.jsonconfig10.5 KB
_shared/contracts/re_review/precommitment.schema.jsonconfig8.6 KB
_shared/contracts/re_review/traceability.schema.jsonconfig37.7 KB
_shared/contracts/re_review/verdict_record.schema.jsonconfig10.5 KB
_shared/contracts/research_workflow/inquiry_branch_ledger.schema.jsonconfig17.0 KB
_shared/contracts/research_workflow/research_workflow_profile.schema.jsonconfig7.2 KB
_shared/contracts/research_workflow/research_workflow_profile_selection_receipt.schema.jsonconfig3.9 KB
_shared/contracts/review_target/constructive_review_findings.schema.jsonconfig7.0 KB
_shared/contracts/review_target/criteria_registry.schema.jsonconfig4.0 KB
_shared/contracts/review_target/review_criteria_binding_manifest.schema.jsonconfig7.9 KB
_shared/contracts/review_target/review_criteria_source_receipt.schema.jsonconfig5.6 KB
_shared/contracts/review_target/review_target_context.schema.jsonconfig4.5 KB
_shared/contracts/review_target/review_target_declaration.schema.jsonconfig4.6 KB
_shared/contracts/reviewer/full.jsonconfig3.7 KB
_shared/contracts/reviewer/methodology_focus.jsonconfig2.2 KB
_shared/contracts/reviewer/review_panel_provenance.schema.jsonconfig7.8 KB
_shared/contracts/reviewer/review_panel_provenance_carrier.schema.jsonconfig4.1 KB
_shared/contracts/reviewer/review_panel_provenance_input.schema.jsonconfig3.5 KB
_shared/contracts/revision/author_adjudication.schema.jsonconfig7.8 KB
_shared/contracts/revision/author_adjudication_input.schema.jsonconfig1.2 KB
_shared/contracts/revision/claim_strength_drift_disposition.schema.jsonconfig3.6 KB
_shared/contracts/revision/claim_strength_drift_disposition_input.schema.jsonconfig3.1 KB
_shared/contracts/revision/claim_strength_drift_findings.schema.jsonconfig4.2 KB
_shared/contracts/revision/claim_surface_manifest.schema.jsonconfig3.3 KB
_shared/contracts/revision/integrity_correction_authorization.schema.jsonconfig4.3 KB
_shared/contracts/revision/integrity_correction_authorization_input.schema.jsonconfig1.5 KB
_shared/contracts/revision/integrity_correction_list.schema.jsonconfig1.8 KB
_shared/contracts/revision/integrity_pass_receipt.schema.jsonconfig809 B
_shared/contracts/revision/revision_evidence_bundle.schema.jsonconfig4.9 KB
_shared/contracts/revision/revision_roadmap.schema.jsonconfig11.2 KB
_shared/contracts/submission/format_profile.example.yamlconfig971 B
_shared/contracts/submission/format_profile.schema.jsonconfig4.6 KB
_shared/contracts/submission/submission_verification_report.schema.jsonconfig10.3 KB
_shared/contracts/submission/venue_profile.schema.jsonconfig4.1 KB
_shared/contracts/writer/full.jsonconfig3.6 KB
_shared/cross_model_verification.mdmarkdown83.3 KB
_shared/description-original.mdmarkdown1.1 KB
_shared/dsh-runtime.mdmarkdown1.5 KB
_shared/evals_lift_report.schema.jsonconfig5.0 KB
_shared/ground_truth_isolation_pattern.mdmarkdown16.0 KB
_shared/handoff_schemas.mdmarkdown96.9 KB
_shared/human_subjects_authority_registry.jsonconfig49.5 KB
_shared/mode_spectrum.mdmarkdown5.2 KB
_shared/model_tiering.mdmarkdown12.6 KB
_shared/output_language_pair.mdmarkdown7.7 KB
_shared/policy_data/nature_policy.mdmarkdown3.9 KB
_shared/prisma_trAIce_protocol.mdmarkdown10.2 KB
_shared/raise_framework.mdmarkdown7.5 KB
_shared/references/authority_content_coverage_advisory_protocol.mdmarkdown14.0 KB
_shared/references/claim_standing_candidate_ledger_protocol.mdmarkdown19.2 KB
_shared/references/claim_strength_ladder.mdmarkdown5.5 KB
_shared/references/cross_document_consistency_advisory_protocol.mdmarkdown13.5 KB
_shared/references/evidence_row_protocol.mdmarkdown14.4 KB
_shared/references/firm_rules.mdmarkdown11.0 KB
_shared/references/human_subjects_authority_protocol.mdmarkdown13.1 KB
_shared/references/intent_clarification_protocol.mdmarkdown11.9 KB
_shared/references/irb_terminology_glossary.mdmarkdown12.4 KB
_shared/references/per_source_method_weaknesses.mdmarkdown4.2 KB
_shared/references/protected_hedging_phrases.mdmarkdown8.9 KB
_shared/references/psychometric_terminology_glossary.mdmarkdown8.7 KB
_shared/references/review_criteria_consumer_protocol.mdmarkdown10.3 KB
_shared/references/review_form_note.mdmarkdown11.3 KB
_shared/references/review_pathway_rule_trace_protocol.mdmarkdown8.3 KB
_shared/references/routing_core.mdmarkdown5.7 KB
_shared/references/submission_packet_manifest_protocol.mdmarkdown13.6 KB
_shared/references/word_count_conventions.mdmarkdown9.0 KB
_shared/research_workflow_profiles/field_general.jsonconfig1.2 KB
_shared/review_criteria_registry.jsonconfig11.5 KB
_shared/review_criteria_sources/msr-2027-technical-papers.2026-08-24.jsonconfig2.0 KB
_shared/review_criteria_sources/sigsoft-empirical-standards.2026-08-24.jsonconfig1.4 KB
_shared/sprint_contract.schema.jsonconfig19.0 KB
_shared/style_calibration_protocol.mdmarkdown6.9 KB
_shared/templates/codex_audit_multifile_template.mdmarkdown16.7 KB
agents/protocol_architect_agent.mdmarkdown6.4 KB
agents/qc_auditor_agent.mdmarkdown5.2 KB
agents/reporter_agent.mdmarkdown3.7 KB
agents/screening_reviewer_agent.mdmarkdown5.4 KB
examples/example_config_dta.jsonconfig1.8 KB
examples/example_protocol_dta.mdmarkdown3.8 KB
examples/quick_screen_example.mdmarkdown3.0 KB
references/decision_rules.mdmarkdown6.7 KB
references/failure_paths.mdmarkdown4.1 KB
references/orchestration.mdmarkdown12.4 KB
references/protocol_template.mdmarkdown6.2 KB
references/quality_control.mdmarkdown6.0 KB
references/reporting_and_handoff.mdmarkdown5.8 KB
references/reviewer_roles.mdmarkdown4.0 KB
scripts/_claim_audit_constants.pyscript13.7 KB
scripts/_markdown_lint_util.pyscript9.0 KB
scripts/_next_verified_at_ms.pyscript6.5 KB
scripts/_skill_lint.pyscript13.6 KB
scripts/ars_cache_invalidate.pyscript1.3 KB
scripts/ars_mark_read.pyscript18.2 KB
scripts/ars_write_scope_guard.pyscript30.9 KB
scripts/audit_snapshot.pyscript23.5 KB
scripts/bibliographic_integrity_signals.pyscript32.2 KB
scripts/build_claim_standing_candidate_ledger.pyscript54.3 KB
scripts/build_claim_standing_query_plan.pyscript25.0 KB
scripts/build_content_coverage_advisory.pyscript45.1 KB
scripts/build_cross_document_consistency_advisory.pyscript77.9 KB
scripts/build_outputs.pyscript33.0 KB
scripts/build_review_pathway_rule_trace.pyscript34.2 KB
scripts/build_submission_packet_manifest.pyscript88.1 KB
scripts/build_workflow.pyscript20.0 KB
scripts/check_audit_artifact_consistency.pyscript103.9 KB
scripts/check_benchmark_report.pyscript2.4 KB
scripts/check_claim_audit_consistency.pyscript68.9 KB
scripts/check_claim_standing_freshness.pyscript9.7 KB
scripts/check_claim_standing_transmissions.pyscript17.9 KB
scripts/check_committee_correspondence.pyscript14.9 KB
scripts/check_corpus_consumer_protocol.pyscript13.7 KB
scripts/check_cross_model_handoff_contract.pyscript9.9 KB
scripts/check_data_access_level.pyscript5.2 KB

scripts/ars_write_scope_guard.py

View on GitHub
#!/usr/bin/env python3
"""ARS write-scope guard — PreToolUse hook (#134 Slice 1, the MVP).

Spec: docs/design/2026-06-01-ars-134-conductor-rescope-deterministic-write-guard-spec.md

Blocks out-of-scope file writes by the 23 Bucket A single-phase agents, backed by
the machine-readable scope manifest at scripts/ars_phase_scope_manifest.json.

WHEN THE FENCE ENGAGES (#973): only when a Bucket A role runs as a separately dispatched
subagent whose payload `agent_type` maps to a manifest key, in an install that wires this
hook (the plugin install). Today that means the plugin-shipped `synthesis_agent` and
`research_architect_agent`. Most roles run inline in the main session by default; a
main-session payload carries no `agent_type`, so those writes are unconstrained here and
the prompt-level Phase Boundary blocks are the only fence
(scripts/fixtures/write_scope_guard/captured_payloads.json pins the real payload shapes).

COVERAGE CLAIM — stated precisely, NOT over-promised (spec §3.3 / §7):
  * DETERMINISTIC for the structured editing tools (Write / Edit / MultiEdit): a write
    outside the agent's declared scope is denied regardless of the agent's prompt. This is
    the load-bearing win.
  * Bash for Bucket A agents: DENIED WHOLESALE. A single-phase agent may not run any Bash;
    it uses the Grep/Glob tools to search and Write/Edit/MultiEdit to write. Six review
    rounds established WHY nothing finer is sound: neither "this Bash writes a file" (a
    denylist — `python -c`/`sh -c`/`make`/custom scripts all write, unenumerable) nor "this
    Bash is read-only" (an allowlist — `rg --pre`/`git grep -O`/`sort --compress-program`/
    `GIT_EXTERNAL_DIFF=…` all execute subprocesses, and "read-only" varies by flag, env, and
    binary version) can be decided reliably from a command string without a sandbox. All-deny
    is the only Bash policy that reaches ZERO fail-open by construction. The cost is a clean
    false-deny of ad-hoc read-only Bash, which the agent does not need (it has Grep/Glob).
  This is NOT "deterministic enforcement of all writes" — it is deterministic for the
  structured tools plus a clean wholesale Bash deny for fenced agents. The honest win is
  making the #133 shape (a helpful agent calling a write tool into a downstream phase dir)
  deterministically impossible, and closing the direct-shell-write path for Bucket A entirely.

The testable core is `evaluate_decision(payload, manifest, workspace_root)` — a pure
function. `main()` only wires stdin -> evaluate_decision -> stdout JSON.

PAYLOAD CONTRACT (first-party verified against official Claude Code hook docs 2026-06-01):
  Available: session_id, transcript_path, cwd, permission_mode, hook_event_name, effort,
  tool_name, tool_input, plus subagent-conditional agent_id / agent_type. For an agent
  defined in a project or user agents dir, `agent_type` equals its frontmatter `name`
  (e.g. "bibliography_agent"); for an agent shipped by this plugin it is the plugin-scoped
  identifier ("academic-research-skills:synthesis-agent", #971). The manifest keys the bare
  name; `_manifest_key` maps the scoped form back to it, and maps a pre-#1037 underscore
  name (LEGACY_AGENT_NAMES) to the current one. Captured payloads (Claude Code
  2.1.296, #973) also carry `tool_use_id` and `prompt_id`; the guard does not read them, so
  their presence or absence never changes a decision.

TOOL_INPUT SHAPES: Write / Edit / MultiEdit each carry a SINGLE top-level `file_path`.
  Write: {file_path, content}; Edit: {file_path, old_string, new_string};
  MultiEdit: {file_path, edits:[{old_string,new_string},...]} — edits[] is multiple
  edits to that ONE file, NOT multiple distinct paths. Bash: {command}.
  (Official hooks input table does not enumerate MultiEdit; the single-top-level-file_path
  shape is taken from the tool definition. The path-extraction below reads ONLY the
  top-level file_path and FAILS LOUD if a structured write tool ever lacks one — so a
  schema drift cannot silently fail the guard open.)

TOOL-NAME BOUNDARY (#1022): the guard inspects a call only when `tool_name` is exactly
  "Write", "Edit", "MultiEdit" or "Bash" (case-sensitive), the same four names as the
  PreToolUse matcher in hooks/hooks.json. Any other name, `edit`, `apply_patch` and
  `NotebookEdit` included, passes through with no permissionDecision: neither the scope
  check nor the infrastructure self-protection runs for it, and the normal permission flow
  still applies. Names are deliberately not casefolded or aliased. A host tool under another
  name may carry another tool_input shape: read as Edit, a payload without a top-level
  file_path would be denied for every caller once the manifest loads, the main session
  included, and a patch that touches several files would be checked on one path at most.
  A port that routes another write tool here adds its name to the matcher and to
  INSPECTED_TOOLS together with a target extractor for that tool's verified payload shape,
  and tests for both.
"""

import fnmatch
import json
import os
import sys
from pathlib import Path

MANIFEST_FILENAME = "ars_phase_scope_manifest.json"

# Structured editing tools: deterministic, single top-level file_path. The 23 Bucket A
# agents emit markdown / yaml / bib / txt into their phase dir via these three tools;
# NotebookEdit is deliberately out of Slice 1 scope (no Bucket A agent writes notebooks,
# and its hook input shape is unverified — adding it would be speculative coverage).
STRUCTURED_WRITE_TOOLS = {"Write", "Edit", "MultiEdit"}

# Tools the guard inspects at all. Everything else -> allow (out of scope).
INSPECTED_TOOLS = STRUCTURED_WRITE_TOOLS | {"Bash"}

# Claude Code reports an agent shipped by a plugin as "<plugin name>:<agent name>" (#971).
# Only THIS plugin's prefix is stripped: another plugin's agent that happens to share a
# manifest name is not an ARS agent and stays out of the fence. Pinned to the `name` in
# .claude-plugin/plugin.json by the guard tests.
PLUGIN_AGENT_NAMESPACE = "academic-research-skills:"

# The four plugin-exposed agents took hyphenated frontmatter names (#1037): claude.ai
# rejects an agent name with an underscore. An agent file copied into a project or user
# agents dir before #1037 still reports its old underscore name, so the guard maps each
# old name to the current one and keeps fencing it. The values must equal the current
# frontmatter names; the guard tests pin that.
LEGACY_AGENT_NAMES = {
    "synthesis_agent": "synthesis-agent",
    "research_architect_agent": "research-architect-agent",
    "report_compiler_agent": "report-compiler-agent",
    "screening_reviewer_agent": "screening-reviewer-agent",
}

# Step 2 infrastructure self-protection — normalized workspace-relative path patterns
# that NO agent (and not even the unconstrained main session) may write. These are the
# enforcement surface: tampering with them would fail the guard open.
INFRA_PROTECTED_GLOBS = [
    "hooks/hooks.json",
    "hooks/*.sh",
    ".claude-plugin/plugin.json",  # declares the hook routing — disabling it neuters the guard
    # The hook script, its manifest, and the cross-check lint, protected by filename both
    # in any SUBDIR (`**/name`) AND at the workspace root (bare `name`). A deny-list
    # widening only protects MORE paths, so it is safe — unlike a per-agent allow-glob
    # widening, which would loosen scope. Covering both forms ensures a future directory
    # move can't fail the guard open (spec §3.2: "the hook script and any helper modules
    # it imports"). (`**/name` matches subdirs only, not root — see _matches_any — so the
    # bare entries are load-bearing for a root-level copy, not redundant.)
    "**/ars_write_scope_guard.py",
    "ars_write_scope_guard.py",
    "**/ars_phase_scope_manifest.json",
    "ars_phase_scope_manifest.json",
    "**/check_v3_10_134_write_scope.py",  # the three-way name cross-check lint
    "check_v3_10_134_write_scope.py",
    # Agent definition files: the agent_type==name binding lives in their frontmatter;
    # renaming an agent out of the manifest would fail the guard open. Covers the per-skill
    # source dirs, the shared dir, AND the top-level plugin-shipped `agents/` dir (the
    # #413-materialized byte-identical copies — these carry the same name binding and were
    # previously unprotected; closed in #448 when the plugin-root anchoring re-established
    # which files count as plugin infra).
    "deep-research/agents/*.md",
    "academic-paper/agents/*.md",
    "academic-paper-reviewer/agents/*.md",
    "academic-pipeline/agents/*.md",
    "shared/agents/*.md",
    "agents/*.md",
    # CLAUDE.md / .claude/CLAUDE.md are DELIBERATELY NOT protected (#459). They were
    # added to guard ARS's own repo CLAUDE.md, but two generic doc filenames collide
    # with the user's own project under the clone+symlink install layout: there
    # CLAUDE_PLUGIN_ROOT is unset, the plugin_root fallback resolves to the cloned repo
    # root, and a user working IN that repo has plugin_root == workspace_root — so their
    # own CLAUDE.md sits at plugin_root and the infra glob re-denied it (the #448 bug
    # resurfacing on a layout the #449 plugin-root anchoring can't distinguish, because
    # home-turf and clone-as-user are the SAME runtime condition). Unlike every entry
    # above, CLAUDE.md is NOT load-bearing: it documents the guard binding, it is not the
    # binding — editing it cannot fail the guard open. So protecting it bought soft-policy
    # comfort at the cost of a hard false-deny for real users. The right home for "don't let
    # an agent rewrite ARS's own instruction doc" is review / CI, not the write-scope guard,
    # which must protect ENFORCEMENT files only. See #459 (and #448/#449 for the history).
]


def _normalize_target(raw_path, cwd, workspace_root):
    """Step 1 — resolve to a workspace-root-relative canonical path.

    Returns (rel_path, escaped_workspace). rel_path is None when the target escapes
    the workspace root (path traversal); escaped_workspace is True then.

    Resolves symlinks on the existing parent chain WITHOUT requiring the leaf to exist
    (the write may create it), so a `phase2_x/../hooks/hooks.json` raw path is
    canonicalized to `hooks/hooks.json` BEFORE any deny-list / glob match runs.
    """
    if not os.path.isabs(raw_path):
        raw_path = os.path.join(cwd, raw_path)
    # CRITICAL: do NOT os.path.abspath() first — abspath collapses `..` LEXICALLY, which
    # would resolve `symlinked_dir/../x` to a sibling of symlinked_dir's *name* before the
    # symlink is followed, blinding the guard to the real target (caught in review). Instead
    # os.path.realpath() resolves symlinks AND `..` together in true filesystem order. It
    # tolerates a not-yet-created leaf (resolving the existing prefix and appending the
    # rest), so a brand-new file path still canonicalizes correctly.
    normalized = os.path.realpath(raw_path)

    real_ws = os.path.realpath(workspace_root)
    try:
        common = os.path.commonpath([normalized, real_ws])
    except ValueError:
        # Different drives / mixed abs-rel — treat as escape.
        return None, True
    if common != real_ws:
        return None, True
    rel = os.path.relpath(normalized, real_ws)
    # `commonpath(...) == real_ws` already proves the path did not escape; do NOT also
    # reject `rel.startswith("..")` — that would false-deny a legitimate root-level file
    # literally named `..foo` (caught in review). Only the workspace root itself (rel == ".")
    # is not a writable target.
    if rel == ".":
        return None, True
    return rel, False


def _match_segments(path_segs, pat_segs):
    """Path-segment-aware glob match. A `*` / `?` / `[...]` matches only WITHIN one
    segment (never across `/`); the literal segment `**` matches ONE OR MORE whole
    segments (a descendant — NOT zero, so `dir/**` covers files UNDER dir, not the bare
    dir node itself). This gives `dir/**` and `**/name` their intended PATH semantics —
    unlike bare fnmatch, whose `*` spans `/` and would let a root-level `phase2_x.md` match
    `phase2_*` (the false-open regression caught at review).

    ITERATIVE (NFA-style) matcher over (path_index, pattern_index) states — NOT recursive.
    A `**` previously recursed once per consumed segment, blowing Python's recursion limit
    (~1000) on a deep path and crashing the hook (caught in review). The worklist keeps a
    visited set so it is O(len(path) * len(pattern)) and cannot stack-overflow at any depth.
    """
    n, m = len(path_segs), len(pat_segs)
    # State = (i, j): path_segs[i:] still to match against pat_segs[j:].
    stack = [(0, 0)]
    seen = set()
    while stack:
        i, j = stack.pop()
        if (i, j) in seen:
            continue
        seen.add((i, j))
        if j == m:
            if i == n:
                return True
            continue  # pattern exhausted but path remains -> this branch fails
        head = pat_segs[j]
        if head == "**":
            # `**` consumes ONE OR MORE segments. So it requires >=1 remaining path segment,
            # then may consume just that one (advance both) or keep consuming (advance path
            # only). A trailing `**` (j == m-1) therefore needs >=1 remaining segment — so
            # `dir/**` matches a descendant, never the bare `dir` node; a leading `**/name`
            # matches name in any subdir but NOT at root (the bare INFRA pattern covers root).
            if i < n:
                stack.append((i + 1, j + 1))  # `**` ate exactly this segment
                stack.append((i + 1, j))      # `**` keeps eating
            continue
        # A literal segment pattern: needs a path segment that fnmatches it.
        if i < n and fnmatch.fnmatch(path_segs[i], head):
            stack.append((i + 1, j + 1))
    return False


def _matches_any(rel_path, globs):
    """Workspace-root-anchored glob match against the normalized relative path.

    Path-segment-aware (a `*` never crosses `/`). Conventions:
      * `dir/**`  — anything strictly UNDER `dir` (>=1 segment below). The bare `dir`
                    node is intentionally NOT matched: every real Bucket A write is to a
                    FILE inside its phase dir, and matching the bare single-segment path
                    would let a root file `phase2_x.md` masquerade as the `phase2_*` dir
                    (the false-open caught at review).
      * `**/name` — `name` in any subdirectory. For a file that may ALSO live at the
                    workspace root, the INFRA list carries both `**/name` and the bare
                    `name` (a deny-list, so widening is safe — see INFRA_PROTECTED_GLOBS).
    """
    # Glob patterns are authored with `/`; segment-split the path on the same separator.
    # On Windows, rel_path (from os.path.relpath) uses `\`, so normalize `\` -> `/` THERE.
    # On POSIX this MUST stay a no-op: `\` is a LEGAL filename character, so an
    # unconditional replace would rewrite a root-level file literally named
    # `phase2_x\notes.md` (one segment) into `phase2_x/notes.md` (two segments) and let it
    # masquerade as the `phase2_*` dir — a fence-escape false-allow (#330 PR #450 caught by
    # cross-model review). Gate on os.sep so the rewrite only fires where `\` is a separator.
    if os.sep == "\\":
        rel_path = rel_path.replace("\\", "/")
    segs = [s for s in rel_path.split("/") if s not in ("", ".")]
    for g in globs:
        pat = [s for s in g.split("/") if s != ""]
        if _match_segments(segs, pat):
            return True
    return False


def _infra_protected_target(raw_path, cwd, plugin_root):
    """Step 2 — is the write target one of the ARS plugin's OWN enforcement files?

    #448 root-cause fix: infra self-protection must be anchored to the PLUGIN root, not
    the user's PROJECT root. The two enforcement surfaces have different anchors:
      * Bucket A phase-scope (Step 4) fences agents to their phaseN_ dir inside the USER'S
        project — anchored on workspace_root (= CLAUDE_PROJECT_DIR).
      * Infra self-protection (here) protects the ARS plugin's own files from tampering —
        those live under the plugin install dir, so it MUST be anchored on plugin_root.
    Conflating them was the bug: matching the plugin's infra filenames (`CLAUDE.md`,
    `hooks/*.sh`, `shared/agents/*.md`, ...) against a user PROJECT path denied the user's
    own same-named files — even from the trusted main session.

    A target is an infra target IFF it resolves INSIDE plugin_root AND its plugin-root-
    relative path matches INFRA_PROTECTED_GLOBS. A target outside plugin_root (the normal
    case in a user project where plugin_root != workspace_root) is never an infra target.

    A None plugin_root here returns False ("no infra root known -> not infra-protected").
    evaluate_decision never calls in with None — it substitutes workspace_root first — so
    this is a pure defensive guard, not a path any real caller exercises.
    """
    if not plugin_root:
        return False
    # Resolve the target the SAME way _normalize_target does (realpath, tolerant of a
    # not-yet-created leaf), but anchored on plugin_root instead of workspace_root.
    rp = raw_path
    if not os.path.isabs(rp):
        rp = os.path.join(cwd, rp)
    normalized = os.path.realpath(rp)
    real_plugin = os.path.realpath(plugin_root)
    try:
        common = os.path.commonpath([normalized, real_plugin])
    except ValueError:
        return False  # different drives -> cannot be inside plugin root
    if common != real_plugin:
        return False  # target resolves OUTSIDE the plugin root -> not an infra file
    rel = os.path.relpath(normalized, real_plugin)
    if rel == ".":
        return False  # the plugin root dir itself is not an enumerated infra FILE
    return _matches_any(rel, INFRA_PROTECTED_GLOBS)


def _manifest_key(agent_type):
    """The manifest key for a payload agent_type: this plugin's scoped identifier
    ("academic-research-skills:synthesis-agent") maps to the bare name the manifest keys
    ("synthesis-agent") (#971), and a pre-#1037 underscore name maps to its current
    hyphenated name (#1037); anything else is returned unchanged."""
    if not isinstance(agent_type, str):
        return agent_type
    if agent_type.startswith(PLUGIN_AGENT_NAMESPACE):
        agent_type = agent_type[len(PLUGIN_AGENT_NAMESPACE):]
    return LEGACY_AGENT_NAMES.get(agent_type, agent_type)


def _allow_unconstrained(agent_type):
    """The decision for an actor that Slice 1 does not fence (main session / Bucket B/C/D).

    Single source for both the escaped-path allow (#302) and the Step-3 allow, so the two
    can't drift. A write tool firing with NO agent_type still surfaces a fail-loud advisory
    (spec §3.4) — do not silently no-op a possibly-regressed payload.
    """
    result = {"decision": "allow", "reason": ""}
    if not agent_type:
        result["absent_agent_type_advisory"] = True
    return result


def _extract_structured_target(tool_input):
    """Single top-level file_path for Write/Edit/MultiEdit.

    Returns the file_path string, or None if absent (schema drift -> fail loud upstream).
    """
    if not isinstance(tool_input, dict):
        return None
    fp = tool_input.get("file_path")
    return fp if isinstance(fp, str) and fp else None


def evaluate_decision(payload, manifest, workspace_root, plugin_root=None):
    """Pure decision function implementing the spec §3.2 logic (Bash policy per §7, shipped).

    Returns a dict: {"decision": "allow"|"deny", "reason": str, ...advisory flags}.

    Two enforcement paths:
      * Structured tools (Write/Edit/MultiEdit) — deterministic write-scope: extract the
        single top-level file_path, run infra self-protection FIRST (anchored on plugin_root,
        #448), then normalize against workspace_root for the escape check, then Bucket A glob.
      * Bash — DENY ALL for a Bucket A agent (spec §3.2 Step-4 hardening: neither a denylist
        of "mutation-capable" Bash nor an allowlist of "read-only" Bash is sound, because
        neither property is stable across commands/flags/env/versions; only all-deny reaches
        zero fail-open by construction). The agent uses the Grep/Glob tools for search and the
        structured tools for writes. Non-Bucket-A Bash passes through.

    plugin_root (#448): the ARS plugin install dir, used to anchor infra self-protection
    (Step 2). main() ALWAYS supplies a concrete root (CLAUDE_PLUGIN_ROOT or the resolved
    repo root), so the None default exists only for the ARS-on-ARS unit tests and for any
    caller that genuinely cannot determine a plugin root.

    When None, infra protection falls back to workspace_root. This is correct ONLY when the
    plugin and the workspace are the same tree (ARS developing ARS): it then reproduces the
    pre-#448 behavior byte-for-byte. It is NOT a safe default under a real plugin install
    (plugin_root != workspace_root) — there it would both re-deny the user's own CLAUDE.md
    and FAIL to protect plugin infra (those files are mere workspace escapes). So a real
    runtime caller MUST pass plugin_root; do not rely on this fallback off the home turf.
    """
    if not plugin_root:
        plugin_root = workspace_root
    # The pure core defends itself too — not only main() — so a non-dict payload (`[]`,
    # null, a string) passed straight to evaluate_decision can't crash on `.get` (review).
    if not isinstance(payload, dict):
        return {"decision": "allow", "reason": ""}
    tool_name = payload.get("tool_name", "")
    tool_input = payload.get("tool_input")
    if not isinstance(tool_input, dict):  # [] / null / str -> treat as empty (no crash)
        tool_input = {}
    cwd = payload.get("cwd") or workspace_root
    agent_type = payload.get("agent_type")
    agent_key = _manifest_key(agent_type)
    agents = (manifest or {}).get("agents", {})
    is_bucket_a = bool(agent_key) and agent_key in agents

    # Tools we don't inspect (Read, Grep, WebFetch, ...) -> allow.
    if tool_name not in INSPECTED_TOOLS:
        return {"decision": "allow", "reason": ""}

    # --- Bash path: DENY ALL Bash for a Bucket A agent. Non-Bucket-A Bash passes through. ---
    if tool_name == "Bash":
        if is_bucket_a:
            return {
                "decision": "deny",
                "reason": (f"ARS scope guard: {agent_type} (a single-phase agent) may not use "
                           "Bash. Use the Grep/Glob tools to search and the Write/Edit/MultiEdit "
                           "tools to make file changes — those are scope-enforced deterministically. "
                           "Bash is denied wholesale because neither 'writes a file' nor 'is "
                           "read-only' is a property that can be decided reliably from a command "
                           "string (a tool can spawn a subprocess or be steered by an env var); "
                           "all-deny is the only policy that cannot fail open (spec §3.2/§3.3/§7)."),
                "bash_denied": True,
            }
        # Non-Bucket-A (main session / Bucket B/C/D) Bash -> pass through unconstrained.
        return {"decision": "allow", "reason": ""}

    # --- Structured tools: Step 1 extract + normalize the single top-level file_path. ---
    raw = _extract_structured_target(tool_input)
    if raw is None:
        # Schema drift: a structured write tool with no top-level file_path. Do NOT
        # silently allow — fail loud (deny + advisory) so the guard cannot fail open.
        return {
            "decision": "deny",
            "reason": (f"ARS scope guard: {tool_name} payload carried no top-level "
                       "file_path (unexpected schema) — denying to avoid silent "
                       "fail-open. Re-verify the tool_input shape."),
            "schema_drift_advisory": True,
        }
    # --- Step 2: infrastructure self-protection (anchored on plugin_root). RUNS FIRST,
    #     BEFORE the user-workspace escape check. ---
    # #448: anchored on the PLUGIN root, not the user's PROJECT root. Two reasons it must
    # precede the escape check:
    #   (a) Under a plugin install, the plugin's own files live OUTSIDE the user workspace,
    #       so they are "escaped" relative to workspace_root — the escape branch would let a
    #       main-session write to them through. Checking infra first keeps them protected
    #       wherever they physically sit.
    #   (b) A target inside the USER's project that merely shares a filename with an ARS infra
    #       file (the user's own CLAUDE.md / hooks/*.sh / shared/agents/*.md) resolves OUTSIDE
    #       plugin_root, so _infra_protected_target returns False and it is left to Step 3/4 —
    #       which is exactly the #448 fix.
    # _infra_protected_target resolves the target on its own (realpath, anchored on
    # plugin_root) so it is correct regardless of the workspace-relative `escaped` flag.
    if _infra_protected_target(raw, cwd, plugin_root):
        return {
            "decision": "deny",
            "reason": (f"ARS scope guard: {raw} is part of the ARS plugin's enforcement "
                       "infrastructure and may not be written by any agent."),
        }

    rel, escaped = _normalize_target(raw, cwd, workspace_root)
    if escaped:
        # The escape / path-traversal deny is a BUCKET A FENCE, not a global one (#302).
        # Slice 1's stated scope (§3.3) is confining the 23 Bucket A single-phase agents to
        # their phase dir; the main session and Bucket B/C/D agents are unconstrained. A
        # main-session write to a sibling git worktree (a mainstream layout) resolves outside
        # the workspace root and MUST be allowed — fencing it here contradicted the Step-3
        # "unconstrained by Slice 1" gate below. So: only a Bucket A agent is denied for an
        # escape; a non-Bucket-A actor falls through to the Step-3 allow.
        #   Infra self-protection already ran above (anchored on plugin_root), so an escaped
        # target that is an ARS plugin file was already denied; what remains here is a genuine
        # non-infra escape (e.g. a sibling worktree), correctly allowed for non-Bucket-A.
        if is_bucket_a:
            return {
                "decision": "deny",
                "reason": (f"ARS scope guard: {agent_type} write target {raw!r} escapes the "
                           "workspace root (path traversal) — denied."),
            }
        return _allow_unconstrained(agent_type)

    # --- Step 3: agent gating. ---
    if not is_bucket_a:
        # Main session or a Bucket B/C/D agent: unconstrained by Slice 1.
        return _allow_unconstrained(agent_type)

    # --- Step 4: Bucket A glob check (path already normalized in Step 1). ---
    allowed = agents[agent_key].get("allowed_write_globs", [])
    if not _matches_any(rel, allowed):
        return {
            "decision": "deny",
            "reason": (f"ARS scope guard: {agent_type} may not write {rel} "
                       f"(outside allowed_write_globs {allowed})."),
        }
    return {"decision": "allow", "reason": ""}


def render_hook_output(decision):
    """Render the PreToolUse stdout JSON.

    DENY -> explicit `permissionDecision: "deny"` (spec §3.2 first-party-verified schema).
    Non-deny -> PASS-THROUGH: emit NO permissionDecision, so the call falls back to the
    normal permission flow. Emitting `"allow"` here would be an explicit GRANT that skips
    every other permission rule (review finding) — a guard that only ADDS denials must never
    silently widen what the rest of the permission system would otherwise have asked about.
    """
    if decision.get("decision") == "deny":
        return json.dumps({
            "hookSpecificOutput": {
                "hookEventName": "PreToolUse",
                "permissionDecision": "deny",
                "permissionDecisionReason": decision.get("reason", ""),
            }
        })
    # Pass-through: a bare hookSpecificOutput with no permissionDecision key.
    return json.dumps({"hookSpecificOutput": {"hookEventName": "PreToolUse"}})


def _load_manifest():
    here = os.path.dirname(os.path.abspath(__file__))
    path = os.path.join(here, MANIFEST_FILENAME)
    with open(path, encoding="utf-8") as fh:
        return json.load(fh)


def main():
    try:
        payload = json.load(sys.stdin)
    except (json.JSONDecodeError, ValueError):
        # Malformed payload: do not block (avoid wedging the session); pass through.
        print(render_hook_output({"decision": "allow", "reason": ""}))
        return 0

    # Valid JSON of the wrong SHAPE ([], null, a string) must not wedge the session either
    # — only a JSON object carries a tool call (review finding: payload.get would crash).
    if not isinstance(payload, dict):
        print(render_hook_output({"decision": "allow", "reason": ""}))
        return 0

    # Hot-path early-exit: PreToolUse fires on EVERY tool call (Read, Grep, WebFetch...),
    # not just writes. Bail before touching the manifest on disk for the common non-write
    # case — the matcher in hooks.json already narrows to write tools, but defend here too.
    if payload.get("tool_name", "") not in INSPECTED_TOOLS:
        print(render_hook_output({"decision": "allow", "reason": ""}))
        return 0

    # Workspace root: prefer CLAUDE_PROJECT_DIR, else the payload cwd. This anchors the
    # Bucket A phase-scope check (Step 4) to the USER'S project.
    workspace_root = os.environ.get("CLAUDE_PROJECT_DIR") or payload.get("cwd") or os.getcwd()

    # Plugin root (#448): anchors infra self-protection (Step 2) to the ARS plugin's OWN
    # files, NOT the user's project. CLAUDE_PLUGIN_ROOT is set on a plugin install; the
    # git-clone+symlink track has no such env var, so fall back to this script's repo root
    # (scripts/ -> repo root, where .claude-plugin/plugin.json lives). Use resolve() (NOT
    # abspath) so a symlinked script / scripts dir — the norm for the ~/.claude/skills
    # symlink install track — resolves to the REAL plugin tree, not the symlink's location
    # (abspath would not follow the symlink and compute the wrong root).
    plugin_root = os.environ.get("CLAUDE_PLUGIN_ROOT") or str(
        Path(__file__).resolve().parents[1])

    try:
        manifest = _load_manifest()
    except (OSError, json.JSONDecodeError):
        # Manifest unreadable: fail loud to stderr (advisory) but do not wedge writes.
        sys.stderr.write("[ARS write-scope guard] manifest unreadable; passing through.\n")
        print(render_hook_output({"decision": "allow", "reason": ""}))
        return 0

    decision = evaluate_decision(payload, manifest, workspace_root, plugin_root)

    # Surface fail-loud advisories to stderr (visible to the user/transcript), never silent.
    if decision.get("absent_agent_type_advisory"):
        sys.stderr.write("[ARS write-scope guard] write tool fired with no agent_type; "
                         "allowed (main session) but surfaced per no-silent-no-op rule.\n")
    if decision.get("schema_drift_advisory"):
        sys.stderr.write("[ARS write-scope guard] structured write tool lacked a top-level "
                         "file_path; denied to avoid silent fail-open.\n")

    print(render_hook_output(decision))
    return 0


if __name__ == "__main__":
    sys.exit(main())
add-product-e2e-evalpaperclipai/paperclipAdd or extend a Paperclip full-stack runner E2E workflow, fixture, matcher, or report evidence path for local or Daytona execution.Stars: 115kUpdated Claude CodeCodexVerifiedInstall
add-runner-evalpaperclipai/paperclipAdd or extend a Paperclip Runner protocol evaluation definition, roster, assertion, or report fixture with provenance and narrow validation.Stars: 115kUpdated Claude CodeCodexVerifiedInstall
diagnose-why-work-stoppedpaperclipai/paperclipCompatibility entry point for failed, stalled, looping, or over-recovered Paperclip work. Use fix-failed-paperclip-run for the full diagnosis, regression, repair, real verification, and green-PR workflow; honor an explicitly requested diagnosis-only scope.Stars: 115kUpdated Claude CodeCodexVerifiedInstall
fix-failed-paperclip-runpaperclipai/paperclipDiagnose and fix failed, stuck, slow, or incorrectly blocked Paperclip tasks and runs. Use with a task/run URL or failure report to trace the root cause, prove a regression red then green, check second-order effects, verify the real workflow, and deliver a PR with passing checks.Stars: 115kUpdated Claude CodeCodexVerifiedInstall