Skip to content

rrrrrredy/research-toolkit / plugins/research-toolkit

research-toolkit

Flagged

Use for source-backed long-form research and writing in English or Chinese across fields, including revisions and continuation. Understand requirements, develop analysis through substantive research collaboration, and deliver a complete report after independent review, audit and acceptance.

FileKindSize
.codex-plugin/plugin.jsonconfig1.0 KB
.generated-files.jsonconfig6.3 KB
.mcp.jsonconfig158 B
LICENSEother1.0 KB
README.mdmarkdown3.4 KB
README.zh-CN.mdmarkdown3.0 KB
SKILL.mdskill md7.8 KB
SKILL.zh-CN.mdmarkdown6.5 KB
VERSIONother6 B
docs/compatibility.mdmarkdown3.8 KB
docs/compatibility.zh-CN.mdmarkdown3.2 KB
docs/delivery-verification.mdmarkdown19.2 KB
docs/delivery-verification.zh-CN.mdmarkdown16.3 KB
docs/review-completion.mdmarkdown18.0 KB
docs/review-completion.zh-CN.mdmarkdown14.7 KB
docs/usage-data.mdmarkdown15.4 KB
docs/usage-data.zh-CN.mdmarkdown13.9 KB
docs/usage-modes.mdmarkdown55.6 KB
docs/usage-modes.zh-CN.mdmarkdown48.6 KB
hooks/hooks.jsonconfig3.2 KB
mcp.jsonconfig253 B
plugin.jsonconfig1.1 KB
references/gotchas.mdmarkdown6.2 KB
references/gotchas.zh-CN.mdmarkdown3.6 KB
references/horizontal-vertical-analysis.mdmarkdown4.3 KB
references/horizontal-vertical-analysis.zh-CN.mdmarkdown3.2 KB
references/optional-analysis-lenses.mdmarkdown8.1 KB
references/optional-analysis-lenses.zh-CN.mdmarkdown6.1 KB
references/postmortem-lessons.mdmarkdown4.3 KB
references/postmortem-lessons.zh-CN.mdmarkdown3.5 KB
references/quality-gates.mdmarkdown5.7 KB
references/quality-gates.zh-CN.mdmarkdown4.5 KB
references/research-standard.mdmarkdown18.2 KB
references/research-standard.zh-CN.mdmarkdown13.7 KB
references/research-workflow.mdmarkdown25.5 KB
references/research-workflow.zh-CN.mdmarkdown19.9 KB
references/subagents-and-review-loop.mdmarkdown17.0 KB
references/subagents-and-review-loop.zh-CN.mdmarkdown13.4 KB
references/task-continuity.mdmarkdown6.9 KB
references/task-continuity.zh-CN.mdmarkdown5.3 KB
references/writing-style.mdmarkdown18.1 KB
references/writing-style.zh-CN.mdmarkdown14.9 KB
requirements-mcp.txtmarkdown11 B
scripts/agent_session.pyscript6.2 KB
scripts/check_delivery.pyscript44.6 KB
scripts/check_review_completion.pyscript28.5 KB
scripts/cli_agent_session.pyscript9.6 KB
scripts/codex_session.pyscript7.5 KB
scripts/extract_source_text.pyscript10.7 KB
scripts/host_review.pyscript78.4 KB
scripts/install_usage.pyscript9.7 KB
scripts/record_changes.pyscript13.7 KB
scripts/release_updates.pyscript9.8 KB
scripts/research_guidance.pyscript5.8 KB
scripts/research_host.pyscript52.4 KB
scripts/research_mcp.pyscript18.9 KB
scripts/research_records.pyscript28.5 KB
scripts/research_workflow.pyscript40.9 KB
scripts/review_process.pyscript5.2 KB
scripts/review_runner.pyscript20.2 KB
scripts/run_observation.pyscript7.7 KB
scripts/task_context.pyscript21.1 KB
scripts/task_lock.pyscript1.7 KB
scripts/task_reading.pyscript4.0 KB
scripts/task_storage.pyscript3.1 KB
scripts/usage_events.pyscript38.9 KB
scripts/usage_host.pyscript7.8 KB
scripts/usage_opencode.mjsscript3.1 KB

scripts/install_usage.py

View on GitHub
"""Configure Toolkit usage recording in Codex, Claude Code or OpenCode."""
from __future__ import annotations
import argparse
import base64
import json
import os
import re
from pathlib import Path
import sys
import time

import usage_events as usage

EVENTS = ["UserPromptSubmit", "PreToolUse", "PostToolUse", "SubagentStart", "SubagentStop", "Stop", "SessionEnd", "PreCompact"]


def launcher(paths, host, windows=False):
    if not windows:
        return f'"{paths[0]}" "{paths[1]}" --host {host}'
    quoted = ["'"+value.replace("'", "''")+"'" for value in paths]
    script_text = ("$OutputEncoding = [System.Text.UTF8Encoding]::new(); "
                   "[Console]::InputEncoding = $OutputEncoding; "
                   f"[Console]::In.ReadToEnd() | & {quoted[0]} {quoted[1]} --host {host}; exit $LASTEXITCODE")
    return "powershell.exe -NoProfile -NonInteractive -EncodedCommand "+base64.b64encode(script_text.encode("utf-16le")).decode()


def owned_launcher(command, host):
    """Recognize only the exact launchers generated here, including an older install path."""
    if not isinstance(command, str):
        return False
    direct = re.fullmatch(r'"([^"]+)" "([^"]+/scripts/usage_host\.py)" --host ' + re.escape(host), command)
    if direct:
        return command == launcher(direct.groups(), host)
    encoded = re.fullmatch(r'powershell\.exe -NoProfile -NonInteractive -EncodedCommand ([A-Za-z0-9+/=]+)', command)
    if not encoded:
        return False
    try:
        script = base64.b64decode(encoded[1], validate=True).decode('utf-16le')
    except (ValueError, UnicodeError):
        return False
    match = re.search(r" \| & '((?:[^']|'')*)' '((?:[^']|'')*)' --host " + re.escape(host) + r'; exit \$LASTEXITCODE$', script)
    if not match:
        return False
    paths = [value.replace("''", "'") for value in match.groups()]
    return paths[1].endswith('/scripts/usage_host.py') and command == launcher(paths, host, windows=True)


def write_changed(path, text):
    if path.exists():
        before = path.read_text(encoding="utf-8")
        if before == text:
            return
        backup = path.with_name(path.name+".toolkit-backup-"+str(time.time_ns()))
        backup.write_text(before, encoding="utf-8")
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text(text, encoding="utf-8")


def install(host, project, remove=False):
    script = Path(__file__).resolve().with_name("usage_host.py")
    # Quote POSIX paths; Windows uses the explicit PowerShell launcher below.
    # Refuse expansion metacharacters rather than interpolate them.
    paths = [Path(sys.executable).as_posix(), script.as_posix()]
    if any(any(char in item for char in ['"', '$', '`', '%', '\n', '\r']) for item in paths):
        raise ValueError("Install path contains shell metacharacters; use a plain directory path")
    command = launcher(paths, host, windows=os.name == "nt")
    if host == "opencode":
        path = project/".opencode/plugins/research-toolkit-usage.js"
        if path.exists() and "research-toolkit usage observer" not in path.read_text(encoding="utf-8"):
            raise ValueError("Existing OpenCode plugin file is not managed by Toolkit; preserved")
        if remove:
            if path.exists():
                path.unlink()
        else:
            module = script.with_name("usage_opencode.mjs").as_uri()
            write_changed(path, "// research-toolkit usage observer\nimport { createUsagePlugin } from "+json.dumps(module)+";\nexport default createUsagePlugin("+json.dumps(sys.executable)+");\n")
        return path
    path = project/(".codex/hooks.json" if host == "codex" else ".claude/settings.local.json")
    if remove and not path.exists():
        return path
    config = json.loads(path.read_text(encoding="utf-8-sig")) if path.exists() else {}
    if not isinstance(config, dict) or not isinstance(config.get("hooks", {}), dict):
        raise ValueError("Existing agent tool hooks configuration is not an object; preserved")
    groups = config.setdefault("hooks", {})
    for event in EVENTS + (["PostToolUseFailure"] if host == "claude" else []):
        existing = groups.get(event, [])
        if not isinstance(existing, list):
            raise ValueError(f"hooks.{event} must be an array; existing file preserved")
        kept = []
        for group in existing:
            if not isinstance(group, dict) or not isinstance(group.get("hooks", []), list):
                raise ValueError(f"hooks.{event} contains an invalid group; existing file preserved")
            handlers = group.get("hooks", [])
            if any(not isinstance(handler, dict) for handler in handlers):
                raise ValueError(f"hooks.{event} contains an invalid handler; existing file preserved")
            remaining = [handler for handler in handlers if not owned_launcher(handler.get("command"), host)]
            if remaining or not handlers:
                kept.append({**group, "hooks": remaining})
        if not remove:
            kept.append({"hooks": [{"type": "command", "command": command, "timeout": 3}]})
        if kept:
            groups[event] = kept
        else:
            groups.pop(event, None)
    write_changed(path, json.dumps(config, ensure_ascii=False, indent=2)+"\n")
    return path


def main(argv=None, *, setup=False):
    parser = argparse.ArgumentParser(prog=(Path(sys.argv[0]).name + " setup") if setup else None, description=__doc__)
    parser.add_argument("--host", required=True, choices=["codex", "claude", "opencode"])
    parser.add_argument("--project", type=Path, default=Path.cwd())
    parser.add_argument("--channel", choices=sorted(usage.CHANNELS), default="manual")
    parser.add_argument("--form", choices=["skill", "plugin", "cli", "mcp"], default="skill")
    parser.add_argument("--remove", action="store_true")
    parser.add_argument("--no-telemetry", action="store_true", help="Skip usage configuration for this setup.")
    parser.add_argument("--apply", action="store_true", help="Apply optional hooks using the existing recording choice.")
    parser.add_argument("--preview", "--dry-run", action="store_true",
                        help="Show the effective setting, target and planned hooks without writing anything.")
    args = parser.parse_args(argv)
    project = args.project.resolve()
    path = project / (".opencode/plugins/research-toolkit-usage.js" if args.host == "opencode" else
                      ".codex/hooks.json" if args.host == "codex" else ".claude/settings.local.json")
    if args.apply and (args.preview or args.no_telemetry):
        parser.error("--apply cannot be combined with --preview or --no-telemetry")
    if args.preview or args.no_telemetry or (setup and not args.apply):
        enabled = usage.recording_enabled()
        events = EVENTS + (["PostToolUseFailure"] if args.host == "claude" else [])
        if args.host == "opencode":
            events = ["OpenCode usage observer"]
        print(json.dumps({"host": args.host, "preview": True, "recording_enabled": enabled,
                          "target": str(path), "configuration_exists": path.is_file(),
                          "planned_action": "none" if args.no_telemetry else "remove_owned_hooks" if args.remove else
                                            "configure_hooks" if enabled else "none",
                          "hooks": events if (enabled or args.remove) and not args.no_telemetry else [],
                          "configuration_changed": False}))
        return
    if not args.remove and not usage.recording_enabled():
        print(json.dumps({"host": args.host, "path": str(path), "removed": False,
                          "configuration_changed": False,
                          "next": "Basic usage recording is off. No project hooks were installed."}))
        return
    before = path.read_bytes() if path.exists() else None
    path = install(args.host, project, args.remove)
    configuration_changed = before != (path.read_bytes() if path.exists() else None)
    next_step = "Only Toolkit usage recording configuration was removed."
    if not args.remove:
        first_installation = False
        with usage.database() as db:
            usage.set_setting(db, usage.installation_key()+"channel", args.channel)
            usage.set_setting(db, usage.installation_key()+"form", args.form)
            config = usage.settings(db)
            enabled = config["enabled"] == "on" and not usage.disabled_by_environment()
            if enabled:
                usage.notice(db, config)
                if config.get("seen") != "1":
                    usage.enqueue(db, config, "installation_seen", host=args.host, entry=args.form)
                    usage.set_setting(db, "seen", "1")
                    first_installation = True
        if enabled:
            usage.schedule_upload()
        reload_instruction = ("Reload or reopen the Codex session to load this configuration."
                              if args.host == "codex" else
                              "Follow the application's trust or reload instructions to load this configuration.")
        next_step = (
            (("Usage recording configuration was written. " if configuration_changed else
              "Existing usage recording configuration is unchanged and reused. ") +
             ("The installation event is queued. " if first_installation else "") +
             (reload_instruction if configuration_changed else "")).rstrip()
            if enabled else "Usage recording remains off; the existing off setting was preserved."
        )
    visible = usage.visible_notice() if not args.remove else None
    print(json.dumps({"host": args.host, "path": str(path), "removed": args.remove,
                      "configuration_changed": configuration_changed, "next": next_step,
                      **({"usage_notice": visible} if visible else {})}))


if __name__ == "__main__":
    main()
rea-analysis-optimizationmorluto/reaOptimize REA providers and shared analysis workflows for agent context, latency, CPU, and memory while preserving correctness and Evidence. Use for analysis bottlenecks and cache or query design; CI/test-suite optimization belongs to rea-ci-tests-audit.Stars: 472kUpdated Claude CodeCodexVerifiedInstall
rea-ci-tests-auditmorluto/reaAudit REA CI and test suites for correctness, fixture drift, false passes, and measured performance; use for suite or workflow investigations and efficiency changes, rather than ordinary feature testing or a single test failure.Stars: 472kUpdated Claude CodeCodexVerifiedInstall
rea-tool-designmorluto/reaAudit, investigate, design, or change REA investigation tools, CLI/MCP contracts, provider capabilities, and Evidence semantics.Stars: 472kUpdated Claude CodeCodexVerifiedInstall
ponytail-auditDietrichGebert/ponytailQuality audit of the whole repo: bugs, security, real load, missing tests, speed, and what to delete. Most important first.Stars: 194kUpdated Claude CodeCodexVerifiedInstall