@squadrules/mcp 5.14.2 → 5.14.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/.tsbuildinfo +1 -1
- package/dist/embed-docs/mem/adapter-migration.md +1 -1
- package/dist/embed-docs/mem/author-adapter.md +1 -1
- package/dist/embed-docs/mem/bulk-insert-adapters-via-cli.md +1 -1
- package/dist/embed-docs/mem/challenge-type-guide.md +1 -1
- package/dist/embed-docs/mem/critic-loop-guide.md +1 -1
- package/dist/embed-docs/mem/critic-loop.md +1 -1
- package/dist/embed-docs/mem/protocol-linking-guide.md +1 -1
- package/dist/embed-docs/mem/refine-search.md +1 -1
- package/dist/resources/embedded-mcp-resources.js +8 -8
- package/dist/ui/assets/{AccountPage-BCYukuHS.js → AccountPage-_zOczaXd.js} +1 -1
- package/dist/ui/assets/{index-D9Sb7Yn8.js → index-Cgf4n_oz.js} +2 -2
- package/dist/ui/index.html +1 -1
- package/package.json +2 -2
|
@@ -23,14 +23,14 @@ export const mcpResources = {
|
|
|
23
23
|
},
|
|
24
24
|
"mem": {},
|
|
25
25
|
"meta": {
|
|
26
|
-
"adapter-migration": "---\nversion: \"5.14.2\"\nslug: adapter-migration\ntitle: Adapter Migration Workflow\n---\n\n# Adapter Migration Workflow\n\nBatch-migrate all adapters in a space to the current structural scheme. Exports\nevery adapter, applies conservative structural transformations, reports changes\nper adapter, and re-trains the conforming subset autonomously.\n\nThis workflow handles structural migrations only — it preserves semantic content\n(steps, intent, examples) while updating format, headings, and contract shapes\nto match the latest SQUADRULES requirements.\n\n## Activation Patterns\n\n**Run this workflow when the user says ANY of:**\n\n- \"migrate all adapters\" / \"batch update adapters\"\n- \"update adapters to latest scheme\" / \"update adapter structure\"\n- \"run structural migration\" / \"migrate adapters\"\n- \"update all my adapters\" / \"fix adapter structure\"\n- \"apply latest adapter format\" / \"restructure adapters\"\n\n**Trigger pattern:** **migrate** / **batch update** / **structural migration** /\n**update format** + (adapters | all | space).\n\n**Must Never:**\n- Alter semantic content (step text, trigger phrases, examples, intent).\n- Auto-train an adapter without first producing a per-adapter change report.\n- Guess transformations when the adapter structure is ambiguous.\n- Delete adapters or layers during migration.\n- Migrate adapters that already conform (report them as \"no changes needed\").\n- Review the transformed set yourself: a batch overwrite written by your own hand\n is not checked by re-reading your own hand.\n\n**Must Always:**\n- Export every adapter before making any changes.\n- Apply only conservative, reversible structural transformations.\n- Flag ambiguous cases for manual review instead of guessing.\n- Produce a per-adapter change report before executing any writes.\n- Have the transformed set reviewed by a delegated critic before the batch write.\n- Preserve the adapter's slug, version, and chain_root fields.\n\n**Good trigger examples:**\n- \"migrate all my personal adapters to the latest format\" → run this workflow\n- \"update all adapters in the team space\" → run this workflow\n\n**Bad trigger examples:**\n- \"update this one adapter\" → use `author-adapter` with `fix` operation\n- \"create a new adapter\" → use `author-adapter`\n- \"export my adapters\" → use `export` directly\n\n## Preflight Dependencies\n\nBefore running migration, verify readiness:\n\n1. `export` tool is available and callable.\n2. `tune` and `train` tools are available for writes.\n3. A subagent facility is available in this host for the review hop. Without it,\n stop and report the blocker rather than approving your own batch.\n4. Target space is identified (personal or a named group space).\n5. The migration is structural-only (no semantic changes).\n\nIf any tool is unavailable, stop and report the connection blocker with\nremediation guidance. These are checks you perform, not gates: a failure produces\na repair action, so no contract is spent on them.\n\n## Export All Adapters\n\nExport every adapter from the target space using bulk export:\n\n1. Call `export` with `all_adapters: true`, `space_name` set to the target\n space, and `format: skill_tree`.\n2. Record the total adapter count from the response.\n3. For each adapter in the response, extract its slug, URI, and content.\n\nIf the space has no adapters, report this and stop.\n\n## Analyze and Transform\n\nFor each exported adapter, perform structural analysis and apply migrations.\n\n### Structural checks (apply all that are needed)\n\n1. **Heading order** — first H2 must be `Activation Patterns`, last H2 must be\n `Reward Signal`. If missing or out of order, flag for restructuring.\n2. **Contract fences** — all contract JSON blocks must use ` ```json ` (not\n plain ` ``` `). If plain fences contain contract JSON, convert them.\n3. **Frontmatter** — must include `slug`. Add `version` if missing. Preserve\n existing `chain_root` when present.\n4. **Line count** — adapters exceeding 350 lines must be flagged for splitting\n (do NOT auto-split; report as manual review needed).\n5. **Shell interpreter** — every shell contract must include `\"interpreter\"`\n field with an allowed value (`bash`, `sh`, `python3`, `python`, `node`).\n6. **Forward link** — every `forward` contract must set `forward.target`\n matching `squadrules://adapter/<slug>`.\n7. **Critic hop** — a `forward` contract whose target is\n `squadrules://adapter/critic-loop` is the deprecated self-review shape: it\n runs the critic on the thread that produced the work. Flag it for manual\n review; converting a review hop into a delegated one changes verification\n semantics and is not a conservative transformation.\n\n### Transformation rules\n\n- **Conservative only:** If a transformation might change meaning, skip it and\n flag for manual review.\n- **Reversible:** Every change must be expressible as a diff.\n- **Idempotent:** Running migration twice produces no additional changes.\n\nFor each adapter, produce:\n- `status`: `needs_changes` | `up_to_date` | `needs_manual_review`\n- `changes`: list of specific transformations applied\n- `warnings`: list of items flagged for manual review\n- `transformed_content`: the full updated markdown (when `needs_changes`)\n\n## Report Changes\n\nWrite the migration report to `$MIGRATION_REPORT_FILE` — an absolute path you\nallocate under `$SQUADRULES_LOCAL_ARTIFACT_DIR` (resolve a hint from the\n`squadrules_local_artifact_dir` field of the latest `activate`/`forward` response\nand export it; the server never names a path on your machine). Also allocate\n`$WORK_MANIFEST` and `$VERDICT_FILE` in the same directory. Record the\ntransformed drafts as files under one root and write the handoff to\n`$WORK_MANIFEST` as flat keys: `kind: file_set`, `root: <that directory>`, then\n`items:` with one draft path per line.\n\nRecord a summary table in the report:\n\n| Adapter slug | Status | Changes | Warnings |\n|-------------|--------|---------|----------|\n| example-adapter | needs_changes | 3 structural fixes | 0 |\n| another-adapter | up_to_date | 0 | 0 |\n\nFor each adapter with `needs_changes`, show the specific transformations.\nFor each `needs_manual_review`, explain what needs human attention.\n\nA report on your own scratch is a local, reversible artifact, so it carries no\ngate. What is gated is the batch write it precedes.\n\n## Review the Transformed Set\n\nDelegate the review of every transformed draft before anything is written:\n\n```json\n{\"contract\":{\"type\":\"subagent\",\"subagent\":{\"context\":\"Run the critic over the transformed adapter drafts and return its actual report. Call the forward tool with uri squadrules://adapter/critic-loop, submit work from $WORK_MANIFEST (kind file_set, the transformed drafts), calling_protocol_slug adapter-migration, verification_target 'structural migration preserved semantics and did not over-reach', the requirement list of structural checks, and context.verdict_file $VERDICT_FILE with context.iteration and context.max_iterations (8). Do not review the drafts yourself and do not re-delegate the review.\",\"mcp\":[{\"tool_name\":\"forward\",\"arguments\":{\"uri\":\"squadrules://adapter/critic-loop\"}}]},\"required\":true}}\n```\n\n## Apply, Verify, and Report\n\n1. Run the gate at the end of this section against `$VERDICT_FILE` **before** any\n write. `FAIL` → fix the drafts the critic named, run a fresh critic pass the\n same way (a subagent delegating `squadrules://adapter/critic-loop`,\n `iteration` incremented) and run the gate again. Loop automatically; do not ask\n the user whether to continue. At `failure_class: iteration_ceiling`, stop,\n report the unresolved findings, and write nothing.\n2. Apply the migration only on a `PASS` verdict:\n - **Apply all** `needs_changes` adapters.\n - **Leave untouched** every `needs_manual_review` adapter.\n - For content-level fixes (heading order, fence conversion, interpreter\n addition): use `tune` with the transformed content, its URI, and\n `review_evidence` from the verdict file.\n - For changes that alter layer count or identity: use `train` with\n `force_update: true` and the same `review_evidence`.\n - Do NOT change an adapter's space assignment during migration.\n3. After all writes, re-export each migrated adapter to verify structural\n compliance, then report final status:\n\n| Metric | Count |\n|--------|-------|\n| Adapters scanned | N |\n| Already up to date | N |\n| Successfully migrated | N |\n| Migration failed | N |\n| Flagged for manual review | N |\n\nFor each failure, report the error message and suggested fix. Semantic integrity\nwas reviewed before the write; do not present a post-write structural re-export\nas if it re-checked meaning.\n\n```json\n{\"contract\":{\"type\":\"shell\",\"shell\":{\"cmd\":\"head -1 \\\"$VERDICT_FILE\\\" | grep -qi '^PASS$'\",\"interpreter\":\"bash\",\"timeout_seconds\":5},\"required\":true}}\n```\n\n## Reward Signal\n\nOnly reachable after all prior steps are solved.\n\nThe adapter library in the target space now conforms to the current structural\nscheme. Every adapter has:\n- Correct heading order (Activation Patterns first, Reward Signal last).\n- Proper ` ```json ` contract fences.\n- Shell contracts with `interpreter` field.\n- Forward contracts with a `forward.target` adapter URI.\n- Valid frontmatter with `slug` and optional `version`.\n- Been verified post-migration for structural compliance.\n\nSemantic content (steps, intent, examples, triggers) is preserved unchanged.\n\nWhat the verdict gate proves: a delegated critic pass over the transformed drafts\nleft a verdict file reading `PASS`, and the store accepted the writes carrying\nthat evidence. What it does not prove: that the report came from the delegated\ncontext rather than this one, or that the verdict is bound to the drafts it\nreviewed — a content-bound review receipt would be needed for that.\n",
|
|
27
|
-
"author-adapter": "---\nslug: author-adapter\nversion: \"5.14.2\"\ntitle: Author Adapter (Create / Review / Refactor)\n---\n\n# Author Adapter (Create / Review / Refactor)\n\n> **Note to the agent:** SQUADRULES adapters are interfaces for AI agents — you\n> are the primary user. When you author an adapter, you design behaviour for\n> yourself and others. Write for them: single source of truth (never duplicate\n> rules), explicit over implicit (agents fill ambiguity with hallucination),\n> steps teach modes (each step teaches its cognitive mode), truth over fluency\n> (an adapter that reads well but causes wrong behaviour is worse than one that\n> reads rough but executes correctly).\n\n## Activation Patterns\n\nPreferred entry URI: `squadrules://adapter/author-adapter`.\nIf `forward.authoring` is present, use its operation and target throughout this\nrun. Do not reinterpret update as create or change the target mid-run. This\ncontext describes the requested work; it does not override host permissions.\n\nSQUADRULES authoring lifecycle — create, review, or update adapters / workflows.\nSupports three operations:\n- **create** — draft and train a new adapter from scratch.\n- **review** — audit an existing adapter, family, or bundle for structural issues,\n missing cross-references, chaining gaps, DRY violations, stale guidance, or\n agent-hostile ambiguity. Read-only.\n- **update** — apply specific corrections to an existing adapter and\n save the correction. Also triggered by: edit, fix, modify, change, improve, patch, refactor.\n\nA fourth lifecycle operation, **delete**, is not run here: follow the Delete flow\nin `docs/adapter-authoring-guide.md` (export, check the slug is not a chain\ndependency, call `delete`, verify it no longer resolves).\n\n**Run this adapter when the user says ANY of:**\n- \"create a new SQUADRULES adapter\" / \"register a personal adapter\"\n- \"train adapter into personal\" / \"train a workflow\"\n- \"review adapter\" / \"audit adapters\" / \"check adapter families for gaps\"\n- \"update adapter\" / \"edit adapter\" / \"fix adapter\" / \"modify adapter\"\n- \"patch adapter\" / \"refactor adapter\" / \"change adapter\" / \"improve adapter\"\n\n**Trigger pattern:** **create** / **train** / **register** / **review** /\n**audit** / **fix** / **update** / **edit** / **modify** / **change** /\n**improve** / **patch** / **refactor** / **correct** +\n(adapter / workflow).\n\n**Must Never:**\n- Run when the user only asked to execute an existing adapter.\n- Mutate adapters during a `review` operation.\n- Review your own draft: the critic pass is delegated, never performed on the\n drafting thread.\n- Optimise only for pretty wording; this adapter designs agent behaviour.\n- Treat \"update\", \"edit\", or \"modify an existing adapter\" as **create**.\n\n**Must Always:**\n- Infer `{operation}` from trigger: create / review / update.\n- Optimise for truth, low ambiguity, explicit sequencing, and user-need alignment.\n- Include Activation Patterns as the first H2 and Reward Signal as the last H2\n in any newly drafted adapter.\n- Enforce the 350-line limit per file.\n\n## Preflight Dependencies\n\nBefore running authoring actions, verify dependency and auth readiness:\n1. Required MCP tools are available: `activate`, `forward`, `reward`, and the\n operation-dependent tool (`train`, `export`, or `tune`).\n2. A subagent facility is available in this host for the critic pass. Without it\n this adapter cannot verify its own work: stop and report the blocker rather\n than reviewing the draft yourself.\n3. Required auth/session state is valid for the target MCP server.\n\nIf any check fails, attempt AI-assisted remediation automatically, then re-run\npreflight. Only hard-stop when a required tool or auth genuinely cannot be\nestablished autonomously. These are checks you perform, not gates: a failure here\nproduces a repair action, so no contract is spent on them.\n\n## Resolve Intent Autonomously\n\nUse structured `authoring` when provided. For original calls without it, infer\n`{operation}` from the user's trigger — do not stop to ask for confirmation:\n\n| Signal | Operation |\n|---|---|\n| \"create\", \"new\", \"train\", no match from activate | **create** |\n| \"review\", \"audit\", \"check\", \"gaps\", \"cross-references\" | **review** |\n| \"update\", \"edit\", \"fix\", \"modify\", \"change\", \"improve\", \"patch\", \"refactor\" | **update** |\n\nResolve the target from context without a confirmation prompt. Record the\ninferred operation and target, then continue. Escalate to the user only when\nthe request is genuinely ambiguous and no reasonable default exists.\n\n## Gather Requirements\n\n### For `create` — collect details for a new adapter\n\n**1. Determine the pattern:**\n\n| Signal | Pattern |\n|---|---|\n| One workflow, no variants | **Standalone** — one adapter, all steps inline |\n| Multiple issue types / output formats | **Router + Extensions** — router classifies, routes via `activate` |\n| Exceeds 350 lines or too complex for weaker models | **Chain** — split into sequential adapters linked via `forward` + slug |\n\n**2. Collect per adapter:**\n- Title, user problem, agent behaviour, mode map, steps, challenge type per step\n- Domain reference, existing adapters to reuse/compose, DRY/size check\n- Chain position, failure analysis\n\n### For `review` — audit existing adapters\n\nExport target adapter(s). Check: user-need fit, mode/step clarity,\ncross-reference completeness, handoff gaps, DRY violations, contract coverage,\ntruth-first behaviour, activation pattern accuracy, structure compliance\n(first H2 Activation Patterns, last H2 Reward Signal, under 350 lines),\nsibling consistency, chained adapter families, and whether every critic hop in\nthe audited adapters is a `subagent` contract rather than a `forward` contract.\n\n### For `update` — identify the specific issue\n\nExport the target adapter, read the current markdown, identify the exact gap or\nerror, and plan the minimal change.\n\n## Draft Markdown\n\n### Allocate the handoff paths first\n\nThe gates below read files that only exist if you created them. Resolve one hint\nfrom the `squadrules_local_artifact_dir` field of the latest `activate` or\n`forward` response (`project://<rel>` → this project root, `user://<rel>` → your\nhome or `$XDG_CONFIG_HOME`), export the absolute result as\n`SQUADRULES_LOCAL_ARTIFACT_DIR`, then allocate collision-free paths for the\ntarget slug:\n\n```bash\nexport SQUADRULES_LOCAL_ARTIFACT_DIR=\"<resolved absolute path>\"\nD=\"$SQUADRULES_LOCAL_ARTIFACT_DIR/author-adapter-$SLUG\"\nmkdir -p \"$D\"\nexport WORK_MANIFEST=\"$D/work-manifest.txt\" # the critic's submission\nexport VERDICT_FILE=\"$D/verdict.txt\" # the critic's verdict\nexport REVIEW_FINDINGS_FILE=\"$D/findings.md\" # review operation only\n```\n\nThe server never names a path on your machine; you do.\n\n### MCP / Local-Filesystem Boundary\n\n- A personal adapter stored in MCP **cannot** reference local files.\n- Any adapter — system or personal — may chain to another adapter with a\n `forward` contract naming `squadrules://adapter/<slug>`; slugs are globally\n unique, so resolution is deterministic.\n- A personal adapter must still be **self-contained** in its instructions: it\n cannot rely on files that only exist in one repository.\n- When a `shell` check has more than one condition, parses JSON, or does not fit\n one readable line, put it in a **gate script artifact** — it is stored with the\n adapter and materialized at run time, not read from your local files; never\n escape a program inline into `cmd`.\n- Order: `train` the adapter markdown first, then `train` the script as an\n artifact — an artifact attaches only to an adapter that already exists. Pin the\n script's identity with a `# squadrules-artifact:` header, and pass\n `force_update: true` on a re-train that matches it, so a fix updates\n that artifact instead of adding a second one. Input fields and the refusal\n message: the `train` tool description.\n- The artifact train targets `squadrules://adapter/<slug>`, so pin the adapter's\n slug with frontmatter `slug:` instead of guessing the slug `train` derived from\n the title.\n- Keep the contract one line: `interpreter: \"bash\"`, `cmd: python3\n \"$SQUADRULES_LOCAL_ARTIFACT_DIR/artifacts/<name>.py\" --gate <name>`.\n- Verify before shipping — **two** checks, both required:\n 1. `activate` the adapter and confirm `linked_artifacts[].relative_path` is\n exactly the path `cmd` invokes. Follow each row's `materialize` instruction before\n the contract that needs it.\n 2. **Export check:** call MCP **`export`** with\n `uri: \"squadrules://adapter/<slug>\"` and `format: skill_tree` (or\n `skill_zip` for the bundle) and confirm the script is present under\n `artifacts/` at the path the contract invokes. Read the returned\n `diagnostics[]`: `artifact_stored_sha_mismatch` or\n `artifact_relative_path_invalid` means the stored artifact is broken —\n re-train it instead of shipping it.\n- A `cmd` that names a script the export does not contain is a broken adapter:\n it fails at run time with a missing-file error and burns the user's step.\n Fix it before shipping. The only exception is a repository-owned gate that\n the adapter names explicitly and that lives in the user's repository — say so\n in the adapter text, and state how the agent finds it.\n\n### Drafting rules (all operations)\n\n**Right mode at the right time:** Every adapter must help the agent recognise\nwhether the current step is for exploration, clarification, ideation, planning,\nexecution, validation, review, or handoff.\n\n**Truth over fluency:** Prefer explicit prompts, stop conditions, uncertainty\nescalation, and observable verification over narrative reassurance.\n\n**DRY:** Shared content across adapters must live in one place.\n\n**350-line maximum per file.** Split into linked adapters if exceeded.\n\n**Slug convention:** Every adapter gets a short, unique, lowercase-hyphenated slug.\n\n**Structure:** H1 title, first H2 Activation Patterns, second H2 Preflight\nDependencies, middle H2s one per stage with JSON contract block, last H2 Reward\nSignal. Frontmatter: `slug` (required), `version` (optional), `chain_root`\n(required for mid-chain adapters).\n\n**Scripts are obtained, not assumed:** when a step's `cmd` invokes a script, the\nadapter must state in its own text how the agent obtains that file before\nrunning the command — follow the `activate` artifact row's `materialize`\ninstruction, or `export` the adapter. A step that says only \"run `python3\n…/artifacts/x.py`\" leaves the agent guessing where the file is; a\nmissing-file gate failure is the most common\nresult of that omission.\n\n**Contracts:** One per adapter is the default; a second is justified only at a\nboundary that is hard to roll back. Load `challenge-type-guide` for decision\nrules and JSON formats (`forward` with\n`squadrules://adapter/challenge-type-guide`).\n\n**Critic-loop and mutation gates:** Load `critic-loop-guide` for placement,\nthe FAIL gate, and the work-submission rules (`forward` with\n`squadrules://adapter/critic-loop-guide`).\n\nFor `create`: draft the full adapter markdown.\nFor `review`: write a structured gap report to `$REVIEW_FINDINGS_FILE`.\nFor `update`: apply the identified change and show a diff-style summary.\n\n## Critic-Loop Review (create and update only)\n\nFor `create` and `update`: have the draft reviewed. This is an autonomous quality\nloop — the agent owns content, the critic owns quality, and no human approval is\nrequested at any point. The critic must not be you: you wrote the draft, so your\nown re-reading cannot detect what you did not intend to write.\n\nWrite the submission handoff to `$WORK_MANIFEST` as flat keys — `kind: file_set`,\n`root: <directory of the draft>`, then `items:` with the drafted file's path on\none line — and delegate the review to a subagent. Delegate it now; do not audit\nthe draft on this thread first.\n\n```json\n{\"contract\":{\"type\":\"subagent\",\"subagent\":{\"context\":\"Run the critic on the drafted adapter markdown and return its actual report. Call the forward tool with uri squadrules://adapter/critic-loop and submit: work from $WORK_MANIFEST (kind file_set, the drafted file), the original requirement list, calling_protocol_slug author-adapter, verification_target 'structural compliance and agent behaviour', context.verdict_file $VERDICT_FILE, context.iteration and context.max_iterations (8). Follow critic-loop to its end, let it write $VERDICT_FILE, and report back its findings plus the verdict file's first two lines. Do not review the draft yourself and do not re-delegate the review.\",\"mcp\":[{\"tool_name\":\"forward\",\"arguments\":{\"uri\":\"squadrules://adapter/critic-loop\"}}]},\"required\":true}}\n```\n\n## Save After a PASS Verdict\n\nRead the verdict the critic left behind and act on it, then save.\n\n1. Run the gate below. `FAIL` → address **every** finding in the report, then\n start a fresh critic pass the same way (a subagent delegating\n `squadrules://adapter/critic-loop` with the corrected draft, the same\n requirements, and `iteration` incremented) and re-run this gate. Loop\n automatically; do not ask the user whether to continue.\n2. The loop is bounded by `max_iterations`. When `iteration` exceeds it, the\n critic returns `failure_class: iteration_ceiling`: **stop looping**, report the\n unresolved findings, and do not save an unreviewed draft as if it passed.\n3. On `PASS`, capture the verdict file path and save:\n - `create` — call `train` with the drafted markdown and `review_evidence`\n (verdict file path, exit code, stdout). Use `force_update: false` unless an\n overwrite was explicitly requested.\n - `update` — call `tune` with the existing adapter URI, corrected content, and\n `review_evidence`. Use `train` with `force_update: true` only for a required\n structural replacement (changing identity/H1 mapping or layer count). Update\n the corresponding repository source when the adapter is repo-managed, and\n make repository edits in the task's isolated worktree.\n - `review` — do not call `train`; the operation is read-only and this gate is\n satisfied by the findings report at `$REVIEW_FINDINGS_FILE`.\n4. Read the stored adapter back (`export` it, or the CLI on a local transport)\n and compare it against what you intended to save; report the URI and any\n difference. This is the run's completion criterion, not a gate: a remote\n store cannot be observed from a shell command, so no contract asserts it.\n\n```json\n{\"contract\":{\"type\":\"shell\",\"shell\":{\"cmd\":\"head -1 \\\"$VERDICT_FILE\\\" | grep -qi '^PASS$'\",\"interpreter\":\"bash\",\"timeout_seconds\":5},\"required\":true}}\n```\n\n## Reward Signal\n\nAdapter complete when:\n- `create` — a delegated critic returned `PASS`, the adapter is stored via `train`\n with that `review_evidence`, its URI is reported, and the stored copy was read\n back\n- `review` — findings report delivered from `$REVIEW_FINDINGS_FILE`\n- `update` — a delegated critic returned `PASS` on the changed parts, the corrected\n adapter is saved via `tune` (or a required structural replacement), read back and\n reported; repo-managed source updated in the task worktree\n\nWhat this proves: a separate context ran `critic-loop` over the draft and left a\nverdict file that reads `PASS`, and the store accepted that evidence. What it does\nnot prove: that the report came from that context, or that the verdict is bound to\nthe reviewed content — server-issued review receipts would be needed for that.\nReport the outcome as it stands; a passing gate is not a guarantee of correctness.\n\nA successful result means the resulting SQUADRULES adapter is more truthful,\nstep-aware, agent-readable, and aligned with human–AI harmony.\n",
|
|
28
|
-
"bulk-insert-adapters-via-cli": "---\nslug: bulk-insert-adapters-via-cli\nversion: \"5.14.
|
|
29
|
-
"challenge-type-guide": "---\nversion: \"5.14.2\"\nslug: challenge-type-guide\ntitle: Challenge Type Selection Guide\n---\n\n# Challenge Type Selection Guide\n\nDecision rules, JSON formats, interpreter selection, and anti-patterns for\nchoosing SQUADRULES challenge types. Loaded by adapter-authoring agents during\ndrafting and review.\n\n## Activation Patterns\n\n**Typically invoked by:** `author-adapter` and `critic-loop`.\n\n**Can be invoked directly when agent needs:**\n- \"challenge type reference\" / \"which challenge type to use\"\n- \"how to write shell challenges\" / \"challenge format\"\n- \"interpreter selection for challenges\"\n\n**Trigger pattern:** **challenge** + (type | format | selection | guide).\n\n**Must Never:**\n- Be used as an execution adapter.\n- Select `comment` merely because it is easy.\n\n**Must Always:**\n- Be consulted before assigning challenge types to adapter steps.\n- Choose the strongest observable contract available.\n- Match challenge choice to the mode of the step: ask, decide, act, verify, or review.\n\n**Good trigger examples:**\n- drafting a new adapter and need challenge types → load this\n- reviewing challenge type selection in a draft → load this\n\n**Bad trigger examples:**\n- \"Create a new adapter\" → use `author-adapter`\n- \"Review my adapter draft\" → use `critic-loop`\n\n## Core Rules\n\n`comment` is the challenge type of **last resort**. If a step produces any\nobservable artifact — a file, a git state change, an API response, or an exit\ncode — use `shell` or `subagent` instead.\n\n**Mode before challenge type:**\n- **clarify / approve** → `user_input`\n- **chain to another adapter** → `forward` (link to another adapter)\n- **execute or verify local state** → `shell`\n- **delegate to another agent** → `subagent`\n- **pure reasoning with no observable artifact** → `comment`\n\n### Decision Tree\n\n```\nDoes the step chain to another adapter via forward?\n ├─ YES → \"forward\" (target: squadrules://adapter/<slug>)\n └─ NO → Does the step produce or verify a file, command result, or system state?\n ├─ YES → \"shell\" (with interpreter)\n └─ NO → Does the step require human approval or choice?\n ├─ YES → \"user_input\"\n └─ NO → Does the step delegate work to another agent?\n ├─ YES → \"subagent\"\n └─ NO → \"comment\" (last resort — no stronger contract possible)\n```\n\n### Challenge JSON Formats\n\n**shell** (interpreter is REQUIRED)\nExample ```json\n{\"contract\":{\"type\":\"shell\",\"shell\":{\"cmd\":\"<command>\",\"interpreter\":\"bash\",\"timeout_seconds\":30},\"required\":true}}\n```\n\nAllowed interpreters: `bash`, `sh`, `python3`, `python`, `node`. Build tools\n(`terraform`, `docker`, `npm`, etc.) are **not** interpreters — wrap them in a\n`bash` command instead.\n\n**forward** (links to another adapter — bare MCP tool calls are not valid)\nExample ```json\n{\"contract\":{\"type\":\"forward\",\"forward\":{\"target\":\"squadrules://adapter/<slug>\"},\"required\":true}}\n```\n\nThe server validates that the submitted `evidence.target` equals the contract's\n`forward.target`, proving the agent called `forward` with the correct target\nslug. Bare MCP tool calls belong in a `subagent.mcp` list (rung 3), never here.\n\n**user_input**\nExample ```json\n{\"contract\":{\"type\":\"user_input\",\"user_input\":{\"prompt\":\"<specific question>\"},\"required\":true}}\n```\n\n**subagent** (rung 2 — delegated judgment)\nExample ```json\n{\"contract\":{\"type\":\"subagent\",\"subagent\":{\"context\":\"<task description>\"},\"required\":true}}\n```\n\nUse `subagent` when a step delegates work to another agent rather than executing\nit directly. The `context` field provides task-specific guidance; the mandatory\ndelegation instruction is appended automatically. Proof is `evidence.report` —\nthe subagent's actual report, not your summary of it.\n\n**subagent.mcp** (rung 3 — delegated MCP tool work; optional)\nExample ```json\n{\"contract\":{\"type\":\"subagent\",\"subagent\":{\"context\":\"Export all adapters and report slugs and versions\",\"mcp\":[{\"tool_name\":\"export\",\"arguments\":{\"all_adapters\":true}}]},\"required\":true}}\n```\n\n`subagent.mcp` names the real MCP tool calls the **subagent** must make. The tool\ntranscript stays in the subagent's context and never reaches yours; proof is\nstill `evidence.report`. Omit the field for rung-2 judgment work.\n\n**comment** (last resort — max 1 per adapter, closing ACK only)\nExample ```json\n{\"contract\":{\"type\":\"comment\",\"comment\":{\"min_length\":50},\"required\":true}}\n```\n\n### Solution JSON Formats\n\nEvery solution follows the same envelope:\n\n```json\n{\n \"type\": \"<challenge_type>\",\n \"outcome\": \"success | failure | skipped\",\n \"evidence\": { /* type-specific proof data */ },\n \"nonce\": \"<echo from contract>\",\n \"proof_hash\": \"<echo from contract>\"\n}\n```\n\n**shell solution**\n```json\n{\"type\":\"shell\",\"outcome\":\"success\",\"evidence\":{\"exit_code\":0,\"stdout\":\"...\",\"stderr\":\"\",\"duration_seconds\":1.2}}\n```\n\n**forward solution**\n```json\n{\"type\":\"forward\",\"outcome\":\"success\",\"evidence\":{\"target\":\"squadrules://adapter/implement-terraform\",\"success\":true}}\n```\n\n**subagent solution**\n```json\n{\"type\":\"subagent\",\"outcome\":\"success\",\"evidence\":{\"report\":\"<the subagent's actual report>\"}}\n```\n\n**comment solution**\n```json\n{\"type\":\"comment\",\"outcome\":\"success\",\"evidence\":{\"text\":\"Verified all items are complete.\"}}\n```\n\n**user_input solution**\n```json\n{\"type\":\"user_input\",\"outcome\":\"success\",\"evidence\":{\"confirmation\":\"agreed. proceed\",\"timestamp\":\"2026-05-18T14:49:00Z\"}}\n```\n\n## Interpreter Selection\n\n| Task | Interpreter |\n|---|---|\n| File exists, tool installed, git state | `bash` |\n| Simple content grep | `bash` |\n| Multi-line regex or paragraph processing | `python3` |\n| JSON validation | `bash` (jq) or `python3` |\n| YAML / complex data structure checks | `python3` |\n| Node.js ecosystem tools | `node` |\n\n**Rule of thumb:** default to `bash`. If you need multi-line regex, imports for\ndata formats, or complex string processing, use `python3`. Use `node` only when\nthe check requires the Node.js runtime.\n\n`cmd` is always program text: `python3` / `node` receive it as `-c` / `-e` source,\nso these rows describe short inline programs. Once a check needs more than one\nreadable line, stop choosing an interpreter and ship the script as an artifact,\ninvoked through a `bash` wrapper — see\n[Artifacts for Shell Contracts](#artifacts-for-shell-contracts).\n\n## Security and Working Directory Rules\n\nUse `$SQUADRULES_LOCAL_ARTIFACT_DIR` as the base directory for local handoff\nartifacts. File paths within it are provided as variables by the invoking agent\nto avoid collisions between parallel sessions.\n\n**Rules:**\n- all file paths in shell challenges reference variables (e.g., `$DRAFT_FILE`,\n `$VERDICT_FILE`) set by the parent agent — never hardcode filenames\n- the parent agent constructs collision-free paths under\n `$SQUADRULES_LOCAL_ARTIFACT_DIR`\n- when using SQUADRULES MCP, the latest `activate` / `forward` / `next` response\n field `squadrules_local_artifact_dir` is an ordered array of URI hints\n (`project://<rel>`, `user://<rel>`); pick one, resolve on your machine, and\n `export SQUADRULES_LOCAL_ARTIFACT_DIR=\"<absolute>\"`\n- prerequisites create the directory; Reward Signal cleans it up\n- never write credentials or secrets to files\n\n### Resolving `project://` and `user://` URI hints\n\n| Scheme | Resolution | Example |\n|--------|-----------|--------|\n| `project://<rel>` | `<IDE project root>/<rel>` | `project://.local/squadrules/work` |\n| `user://<rel>` | `<$XDG_CONFIG_HOME or $HOME>/<rel>` | `user://.config/squadrules/work` |\n\nWhen your session spans multiple projects, prefer `user://` to avoid ambiguity.\n\n### Worktree placement (for task-isolation adapters)\n\nWhen an adapter requires a git worktree for isolation, the worktree path MUST\nbe **outside** every existing checkout:\n\n```\nREPO_ROOT=/home/user/repos/my-project\n# RIGHT: sibling of the repo\nWT=/home/user/repos/mcp.worktrees/<task-id>\n# WRONG: inside the checkout\n# WT=/home/user/repos/my-project/.mcp.worktrees/<task-id>\n```\n\n**Rule of thumb:** `$(dirname \"$REPO_ROOT\")/mcp.worktrees/<task-id>`\n\n### IDE worktree access limitations\n\nMost IDE file tools scope operations to the open project root. They **cannot**\nreach worktrees placed outside `$REPO_ROOT`. Use the terminal/shell tool for\nexternal worktrees, or open the worktree as a separate project window.\n\n## Composition Patterns\n\n**Multi-check compound command** — chain with `&&`, let the first failure stop.\n\n**Agent-readable shell status** — preserve the original exit status:\n```bash\n( set -o pipefail; <command> ); rc=$?; printf '\\nSQUADRULES_SHELL_EXIT=%s\\n' \"$rc\" >&2; exit \"$rc\"\n```\n\n**Freeze-then-verify** — step N writes checksum, step N+1 verifies before publish.\n\n**Write-then-grep** — subagent writes a verdict file, main agent checks line 1.\n\n**Phase-batch with critic** — batch related items, verify hard artifacts with\nshell, then delegate `critic-loop` for adversarial review from a `subagent`\ncontract. The review must not run on the thread that produced the work.\n\n**Chain-link via forward + slug** — layer N's contract requires `forward` with a\nspecific adapter slug. Use when the adapter exceeds 350 lines or needs\nmulti-path routing. Example:\nExample ```json\n{\"contract\":{\"type\":\"forward\",\"forward\":{\"target\":\"squadrules://adapter/implement-plan\"},\"required\":true}}\n```\n\n## Artifacts for Shell Contracts\n\nA gate that needs more than one short command belongs in a **script shipped with\nthe adapter**, not in the contract's `cmd`. An artifact keeps the contract\nreadable, makes the script independently versionable, and lets one dispatcher\nserve many gates.\n\n**Author it in this order** — an artifact attaches to an adapter that already\nexists:\n\n1. Draft the markdown. The contract stays one line and invokes the script by its\n artifact path. `interpreter` names the wrapper that runs that line, because\n `cmd` is program text for every interpreter:\n Example ```json\n {\"contract\":{\"type\":\"shell\",\"shell\":{\"cmd\":\"python3 \\\"$SQUADRULES_LOCAL_ARTIFACT_DIR/artifacts/my-gates.py\\\" --gate preflight\",\"interpreter\":\"bash\",\"timeout_seconds\":60},\"required\":true}}\n ```\n2. `train` the markdown.\n3. `train` the script with the `mime` matching its extension (`text/x-python`,\n `text/x-shellscript`, `text/javascript`), `artifact_name`, and that adapter's\n `adapter_uri`. Add `relative_path` only when the default\n `artifacts/<artifact_name>` is not the path you want; the identity header and\n slug rules are in the `train` description.\n4. Verify before you run it — **two** checks:\n - `activate` the adapter and check that `linked_artifacts[].relative_path`\n equals the path the contract invokes.\n - **Export check:** `export` the adapter (`format: skill_tree`, or\n `skill_zip` for the bundle) and confirm the script is in the bundle at\n that path, with no `artifact_stored_sha_mismatch` or\n `artifact_relative_path_invalid` in `diagnostics[]`.\n\n A mismatch surfaces only when the gate runs — by then it is the user's\n failed step, not your typo.\n\n**At execution time:** follow the `materialize` instruction carried by that\n`linked_artifacts[]` row — call the MCP `export` tool with the specified\narguments, write the returned content to the `out` path under\n`$SQUADRULES_LOCAL_ARTIFACT_DIR`, verify the digest, and set permissions.\n`forward` responses do not repeat the list, so materialize during the\nrun's first step. When the choice carries no artifact row, the agent obtains the\nscript with **`export`** (`format: skill_tree` or `format: skill_zip`) and takes\nit from `artifacts/`. State which route applies in the adapter text — a step that\ndoes not say how to get the file leaves the agent guessing.\n\n**One script, many gates:** `--gate <name>` on a single dispatcher replaces one\ninlined program per step. Change the gate once, not seven times.\n\nExample ```json\n{\"contract\":{\"type\":\"comment\",\"comment\":{\"min_length\":30},\"required\":true}}\n```\n\n## Reward Signal\n\nOnly reachable after all prior steps are solved.\n\nThe agent can now:\n1. pick the correct challenge type for each adapter step\n2. match challenge type to the step's mode\n3. choose the right interpreter (bash, python3, node)\n4. apply working-directory and security rules\n5. use forward contracts for chain links\n6. use subagent contracts for delegated work\n7. apply stronger verification patterns instead of weak comment checks\n8. ship a multi-step gate as an adapter artifact and keep its contract one line\n",
|
|
30
|
-
"critic-loop-guide": "---\nversion: \"5.14.2\"\nslug: critic-loop-guide\ntitle: Critic Loop Integration and Mutation Gate Guide\n---\n\n# Critic Loop Integration and Mutation Gate Guide\n\nDecision rules for integrating `critic-loop` into adapter protocols: when a\nsolution check (hard verification gate) is required versus when critic-loop\nreview is sufficient, and how to split and batch proofs so reversible work stays\ncheap while irreversible boundaries stay guarded.\n\n## Activation Patterns\n\n**Typically invoked by:** `author-adapter` during adapter drafting, and\nany adapter that includes review or validation phases.\n\n**Can be invoked directly when agent needs:**\n- \"when to add critic loop\" / \"should I use solution check\"\n- \"mutation gate rules\" / \"which actions need hard gates\"\n- \"critic loop vs solution check\" / \"irreversible action rules\"\n- \"add review step to protocol\" / \"where does critic go\"\n\n**Trigger pattern:** **critic loop** / **mutation gate** / **solution check** +\n(integration | when | rules | guide | which | where).\n\n**Must Never:**\n- Be used as an execution protocol.\n- Override the adapter author's judgment on review depth.\n- Recommend solution checks for reversible or local-only actions.\n\n**Must Always:**\n- Distinguish between quality review (critic-loop) and mutation blocking\n (solution checks).\n- Recommend looping critic-loop until PASS at every major phase boundary, fed the\n requirement list and bounded by an iteration ceiling.\n- Restrict solution checks to irreversibility boundaries, and batch reversible\n checkable steps into one strict-conjunction proof.\n\n**Good trigger examples:**\n- drafting a new adapter and deciding where to add review → load this\n- reviewing whether an adapter has the right solution checks → load this\n- \"does my MR step need a solution check?\" → load this\n\n**Bad trigger examples:**\n- \"run the critic loop\" → use `activate` to match `critic-loop`\n- \"create a new protocol\" → use `author-adapter`\n- \"which challenge type for this step?\" → use `challenge-type-guide`\n\n## Core Decision Rule\n\n**Critic-loop** is an adversarial review the calling protocol **loops until it\nreturns PASS** — not a one-shot step. It verifies claims, gathers evidence,\nsearches for contradictions, and checks the work against the original requirement\nlist. Use it for quality and truthfulness review, and whenever a step is\nnon-deterministic or has no objective proof. Run it **before** the work is handed\nto the next step, and before it is presented to the human.\n\n**Solution checks** are per-layer contract verification mechanisms (shell\ncommands, MCP tool calls). Use them ONLY where getting it wrong is expensive or\nimpossible to undo — **irreversible changes on remote systems** and the local\npreconditions that guard them (for example, being on a throwaway worktree/branch\nbefore you commit). Everything else is reversible: give the agent freedom and\nreview with critic-loop instead of adding a hoop.\n\n### What counts as an irreversible remote mutation\n\n| Action | Needs solution check? | Why |\n|--------|----------------------|-----|\n| Create/update merge request | Yes | Remote system state change |\n| Create/update Jira issue | Yes | Remote system state change |\n| Send email | Yes | Cannot unsend |\n| Send Teams message | Yes | Cannot unsend |\n| Create calendar invite | Yes | Sends notifications |\n| Deploy to production | Yes | Irreversible infrastructure change |\n| Delete remote resource | Yes | Irreversible |\n| Push to git remote | Yes | Remote state change |\n| Write/edit local file | No | Use critic-loop instead |\n| Run local tests | No | Read-only / local |\n| Analyze code | No | Read-only |\n| Generate report | No | Local artifact |\n| Read data from API | No | Read-only |\n| Compute / transform data | No | Local operation |\n\nExample ```json\n{\"contract\":{\"type\":\"comment\",\"comment\":{\"min_length\":30},\"required\":true}}\n```\n\n## Proof Splitting: Batch Checkable Steps Into One Proof\n\nSplit proofs by **reversibility cost**, not by step count:\n\n- **One proof per irreversibility boundary.** A boundary is where undoing the next\n part is expensive or impossible: commit to `main`, mutate the human's active\n worktree, `git push`, `gh pr create`, deploy, send.\n- **Batch reversible, checkable steps** and verify them together afterward with a\n single aggregate proof — fewer round-trips, same guarantee.\n- **The aggregate proof must be a strict conjunction** that re-verifies every\n sub-condition (`A && B && C && echo OK`):\n\nExample ```json\n{\"contract\":{\"type\":\"shell\",\"shell\":{\"cmd\":\"test -f \\\"$OUT_A\\\" && test -f \\\"$OUT_B\\\" && grep -q \\\"$EXPECTED\\\" \\\"$OUT_A\\\" && echo OK\",\"interpreter\":\"bash\",\"timeout_seconds\":10},\"required\":true}}\n```\n\n- **Never let an aggregate proof degrade to `echo \"done\"`.** A proof that asserts\n nothing is worse than no gate because it looks like one. If you cannot write a\n real conjunction, the step is non-deterministic → review it with critic-loop\n instead of faking a proof.\n\n### Guard the boundary before you cross it\n\nThe cheapest proof is the precondition that stops an irreversible mistake before\nit happens — for example, confirm you are on a throwaway worktree and branch (not\n`main`, not the human's active checkout) **before** making changes:\n\nExample ```json\n{\"contract\":{\"type\":\"shell\",\"shell\":{\"cmd\":\"test \\\"$(git rev-parse --abbrev-ref HEAD)\\\" != main && git rev-parse --git-common-dir | grep -q worktrees\",\"interpreter\":\"bash\",\"timeout_seconds\":5},\"required\":true}}\n```\n\n## How to Invoke Critic-Loop from an Adapter\n\nReach `critic-loop` at a phase boundary with a **`subagent` contract**, never a\n`forward` contract. A `forward` hop keeps the review on the thread that produced\nthe work: the same agent reads the critic's instructions, performs them, and\nwrites the verdict it is then gated on. The hop names the call the subagent must\nreally make, so it cannot substitute an improvised review:\n\n### After a planning phase\n\nExample ```json\n{\"contract\":{\"type\":\"subagent\",\"subagent\":{\"context\":\"Run the critic on the plan and return its actual report. Call the forward tool with uri squadrules://adapter/critic-loop, submit the work from $WORK_MANIFEST with the requirement list, and let the critic write $VERDICT_FILE. Do not review it yourself.\",\"mcp\":[{\"tool_name\":\"forward\",\"arguments\":{\"uri\":\"squadrules://adapter/critic-loop\"}}]},\"required\":true}}\n```\n\n### After an implementation phase\n\nUse the same contract shape. The subagent receives the calling protocol's\ncontext, drives `critic-loop` to its end in its own context, and returns only its\nreport — the tool transcript never re-enters the caller's reasoning.\n\n`forward` + slug stays correct for **chain continuation** — handing work to the\nnext stage of the same effort, or to a reusable sub-adapter that is not auditing\nthe caller. The test is not \"does it link to an adapter\" but \"is the linked\nadapter the caller's auditor\". Separation is the point: a review the audited agent\nruns on itself restates its work instead of checking it.\n\nA host with no subagent facility cannot satisfy this hop. Report that as a\nblocker; do not fall back to reviewing your own work.\n\n### What to submit for review\n\nThe submission is the **work itself**, not a summary of it. Pass `work` with a\n`kind`, an `items` list, and the absolute `root` the items resolve against:\n\n| `kind` | `items` contain | Resolved by | Typical work |\n|---|---|---|---|\n| `file_set` | paths (absolute, or relative to `root`) | read each file | docs, generated code, configs |\n| `links` | URLs, `squadrules://` resource URIs | fetch each one | published pages, external references |\n| `git_diff` | `base..head` refs, or empty for the working tree | `git diff` | an unpushed implementation |\n| `pr` | PR numbers or URLs | `gh pr view` + `gh pr diff` | a reviewable pull request |\n| `command_output` | commands to run from `root` | run and capture | migrations, builds, data pulls |\n| `inline` | the text itself | read the manifest | a plan, a decision, a message draft |\n\nRecord `work` in the handoff file pointed to by `$WORK_MANIFEST`, as flat keys —\n`kind:`, `root:`, then `items:` with one item per line — so the precondition\nstays a machine-checkable file test instead of prose:\n\nExample ```json\n{\"contract\":{\"type\":\"shell\",\"shell\":{\"cmd\":\"test -f \\\"${WORK_MANIFEST:-}\\\" || test -f \\\"${INPUT_FILE:-}\\\"\",\"interpreter\":\"bash\",\"timeout_seconds\":3},\"required\":true}}\n```\n\nAnything that cannot be resolved is `verification_blocked` — an item the critic\ncould not read is never treated as an item that passed. `input_file` still works\nand means a one-item `file_set`; prefer `work_manifest` for anything that is not\na single document. A `pr` or `git_diff` submission is judged on the diff and the\ntests it touches, not on the description written next to it.\n\n### Feed it the requirements, then loop with a ceiling\n\nPass the original requirement list in the forward context. A critic that sees only\nthe output can check internal consistency but **cannot detect an omitted\nrequirement** — omission leaves no trace in the artifact — so \"no requirements\nlost\" is only enforceable if the critic is given the list and asserts coverage\nitem by item. Then loop: on FAIL, fix, increment `iteration`, and re-invoke until\nPASS or until `max_iterations` is reached. The ceiling is a hard stop that\nsurfaces the unresolved findings; it prevents a weak agent from thrashing forever.\n\n### Verdict handoff pattern\n\nCritic-loop writes a verdict file in the delegated run. The calling adapter reads\nit:\n\n1. Critic-loop writes `$VERDICT_FILE` with `PASS`/`FAIL` on line 1.\n2. Calling adapter's next layer reads the verdict file.\n3. If `FAIL` → **hard stop**: do NOT proceed to reward, do NOT ask the user\n for approval, do NOT continue to the next phase. Address findings first.\n4. If `PASS` → the adapter continues to the next phase.\n\n**FAIL is a hard stop, not an escalation trigger.** A FAIL verdict means the\nwork is not ready. Asking the user \"should I proceed?\" after FAIL bypasses the\nreview. The correct action is to fix the findings and re-invoke critic-loop.\n\n### FAIL gate contract (required after every critic-loop invocation)\n\nEvery adapter that invokes critic-loop **must** include a shell contract that\nfails when the verdict is not PASS. This is the mechanical guard that prevents\nweaker agents from proceeding after FAIL:\n\nExample ```json\n{\"contract\":{\"type\":\"shell\",\"shell\":{\"cmd\":\"head -1 \\\"$VERDICT_FILE\\\" | grep -qi '^PASS$'\",\"interpreter\":\"bash\",\"timeout_seconds\":5},\"required\":true}}\n```\n\nIf the critic wrote FAIL, this shell command exits non-zero. The server rejects\nthe solution and the agent cannot advance to the next layer. Protocol wording\nalone does not stop determined agents; this contract does.\n\n## Train/Tune Evidence Requirement\n\n`train` and `tune` enforce critic-loop PASS at the tool level:\n\n- **Adapter (markdown) `train`** requires `review_evidence`: verdict_file path,\n exit_code (must be 0), and stdout (line 1 must be PASS). Without it, the\n server rejects the store with `REVIEW_EVIDENCE_REQUIRED`.\n- **`tune` with content** requires the same `review_evidence`. Space-only moves\n skip this check.\n- **Artifact trains** (non-markdown mime) skip the evidence check.\n\nThis is the tool-level enforcement of the FAIL gate. Even if an agent bypasses\nthe adapter flow and calls `train` directly, the server rejects the store\nwithout PASS evidence. The agent must run critic-loop, capture the verdict\nfile, and pass it as `review_evidence`.\n\n## Mutation Gate Pattern\n\nUnder the AI-ownership model, agents execute autonomously — irreversible remote\nmutations are **not** gated by a human confirmation prompt. Gate them with\nobjective, machine-checkable contracts instead:\n\n### Pre-mutation readiness (objective, no human prompt)\n\nAssert the preconditions with a shell or forward contract so the action only runs from a\nvalid state — never with a `user_input` \"are you sure?\" prompt:\n\nExample ```json\n{\"contract\":{\"type\":\"shell\",\"shell\":{\"cmd\":\"test -n \\\"$TARGET_REPO\\\" && test -n \\\"$TARGET_BRANCH\\\"\",\"interpreter\":\"bash\",\"timeout_seconds\":5},\"required\":true}}\n```\n\n### Post-mutation verification (objective)\n\nConfirm the mutation actually took effect by reading the remote state back.\nUse a `subagent` contract when the verification requires multi-step reasoning\nor tool orchestration beyond a single shell command:\n\nExample ```json\n{\"contract\":{\"type\":\"subagent\",\"subagent\":{\"context\":\"Verify the remote mutation took effect: read back the created/updated resource and confirm its state matches the intended outcome.\"},\"required\":true}}\n```\n\nThe guarantee comes from critic-loop (truth of intent) plus these objective\npre/post checks — not from asking a human to approve. Do not add `user_input`\nconfirmation gates for remote mutations.\n\n## Critic-Loop Placement Rules\n\n1. **Loop critic-loop until PASS at every major phase boundary** — after planning,\n after implementation, after validation — feeding it the requirement list and\n bounding it with an iteration ceiling.\n2. **Invoke the critic from a separate context** — a `subagent` contract, never a\n `forward` contract on the thread that produced the work.\n3. **Do NOT add critic-loop between every layer** — it is a phase-level review,\n not a step-level check.\n4. **Put one objective proof at each irreversibility boundary** — remote mutation\n or the local precondition that guards it: pre-mutation readiness +\n post-mutation verification, never a human confirmation prompt.\n5. **Batch reversible, checkable steps into one aggregate strict-conjunction\n proof** instead of one proof per step; never let it degrade to `echo \"done\"`.\n6. **Never replace a boundary proof with critic-loop** — critic-loop reviews truth\n after the fact; it does not block an irreversible step.\n7. **Never add a proof for purely local, reversible operations** — critic-loop\n provides sufficient review.\n8. **Never gate what you cannot observe** — if no shell command can see the\n outcome, state it as an instruction with a completion criterion instead of\n inventing a command that prints `ok`.\n\n## Adapter Authoring Checklist\n\nWhen drafting a new adapter, apply this checklist:\n\n1. Identify all phase boundaries in the adapter flow.\n2. Add a `subagent` critic hop at each boundary — never a `forward` hop to\n `critic-loop`.\n3. Identify all steps that perform irreversible remote mutations.\n4. Add objective solution checks (pre-mutation readiness + post-action\n verification) for each — no `user_input` human-confirmation gate.\n5. Verify that no solution checks exist for purely local operations.\n6. Verify that the critic-loop verdict handoff pattern is present.\n7. Verify that a FAIL gate shell contract follows every critic-loop invocation.\n8. Verify that `train`/`tune` calls include `review_evidence` from the critic.\n9. Ensure the adapter's Reward Signal describes what the critic protects, and\n states what the verdict does **not** prove.\n\nExample ```json\n{\"contract\":{\"type\":\"comment\",\"comment\":{\"min_length\":80},\"required\":true}}\n```\n\n## Reward Signal\n\nOnly reachable after all prior steps are solved.\n\nThe agent can now:\n1. Decide when to use critic-loop versus solution checks\n2. Identify irreversible remote mutations that need hard gates\n3. Invoke critic-loop from a delegated subagent at the correct phase boundaries\n4. Apply the mutation gate pattern for remote-system actions\n5. Avoid unnecessary solution checks for local or read-only operations\n",
|
|
31
|
-
"critic-loop": "---\nversion: \"5.14.2\"\nslug: critic-loop\ntitle: Critic Loop\n---\n\n\n\n# Critic Loop\n\nBounded adversarial investigator that the calling protocol **loops until it\nreturns PASS** — not a one-shot review. Receives a work submission (files,\nlinks, a git diff, a pull request, command output, or inline text), the\noriginal requirement list, and the calling protocol's invariants, then\nindependently verifies the submitted work by extracting claims, gathering\nevidence, searching for contradictions, and checking requirement-by-requirement\ncoverage. A FAIL sends the caller back to fix and re-invoke; the loop is bounded\nby an explicit iteration ceiling (see Verdict).\n\n## Activation Patterns\n\n**Typically invoked by:** another protocol at the end of a plan, implement,\nvalidation, or review phase, reached from a `subagent` contract whose\n`subagent.mcp` names `forward` with the stored adapter URI\n`squadrules://adapter/critic-loop`. The critic runs in the delegated context, not\non the audited agent's thread — that separation is why the type is `subagent` and\nnot `forward`.\n\n**Can be invoked directly when agent needs:**\n- \"review phase output\" / \"verify plan\" / \"audit implementation\"\n- \"adversarial review\" / \"critic review\"\n\n**Trigger pattern:** **review** / **verify** / **audit** / **critic** +\n(phase / plan / implementation / output).\n\n**Must Never:**\n- Modify any submitted item or any file other than the verdict path.\n- Trust the executor's assertions without independent evidence.\n- Classify a claim as `verified` based only on absence of contradiction.\n- Keep investigating after a precondition failure that blocks verification.\n- Re-delegate this review to another subagent: you are the separation the caller\n asked for, and nesting a second layer of delegation hides the verdict's author.\n\n**Must Always:**\n- Extract claims before investigating.\n- Verify in-scope claims first.\n- Search for contradictory evidence, not only confirming evidence.\n- Check every item in the supplied requirement list for coverage; a missing\n requirement is a FAIL even when the output is internally consistent.\n- Include confidence in every verdict and failure class in every FAIL verdict.\n- Write `$VERDICT_FILE` on **every** path, including an early-abort, so the\n caller's gate always reads a real verdict instead of failing on a missing file.\n- Preserve the boundary between execution and review.\n\n**Good trigger examples:**\n- implement protocol fires this after planning → run this protocol\n- compose protocol fires this after output generation → run this protocol\n\n**Bad trigger examples:**\n- \"Create a new protocol\" → use `author-adapter`\n- \"Implement a feature\" → use an execution protocol, not this one\n\n## Artifact Contract\n\nThis protocol receives:\n\n```text\n{\n work: {\n kind: 'file_set' | 'links' | 'git_diff' | 'pr' | 'command_output' | 'inline',\n items: string[], // paths | URLs | 'base..head' refs | PR URL/number | commands | text\n root: string // absolute cwd used to resolve relative paths, refs and commands\n },\n work_manifest: string, // absolute path to the handoff file recording `work`\n input_file: string, // accepted alias: a one-item work.kind='file_set'\n calling_protocol_slug: string,\n verification_target: string,\n requirements: string[], // original intent / requirement list to check coverage against\n context: {\n operation: string,\n verdict_file: string, // absolute path where the verdict will be written\n iteration: number, // 1-based loop pass; caller increments after each FAIL\n max_iterations: number // hard ceiling; exceeding it is a terminal FAIL\n }\n}\n```\n\nThe submission is the **work itself**, not an essay about it. Write `work` to\n`$WORK_MANIFEST` as flat keys so the handoff stays machine-checkable:\n`kind:`, `root:`, then `items:` with one item per line. Callers that still pass\nonly `input_file` are handled as `kind: file_set` with that single path; the\nreview rules do not change, only the scope of what is submitted.\n\nThis protocol produces:\n\n```text\n{\n verdict: \"PASS\" | \"FAIL\",\n confidence: \"High\" | \"Medium\" | \"Low\",\n failure_class: string, // incorrect_claim | verification_blocked | requirement_gap | iteration_ceiling\n uncovered_requirements: string[],// requirement items lacking positive evidence (empty on PASS)\n verdict_file: \"{context.verdict_file}\"\n}\n```\n\n## Precondition Check\n\nVerify foundational preconditions before deep investigation. Early-abort if any\nare broken.\n\n**Input:** `$WORK_MANIFEST` (or the older-spelling `$INPUT_FILE`), calling protocol slug, context\n\n**Actions:**\n1. Verify a submission handoff is present: `$WORK_MANIFEST`, or `$INPUT_FILE`\n when the caller passed no manifest.\n2. Verify the verdict output path is writable (parent directory exists).\n3. Load the calling protocol's Must Never / Must Always sections if possible.\n4. Verify the target state is available for review.\n5. Verify required tools are available for the submission's `kind` (a `pr`\n submission with no `gh` on the host is `verification_blocked`, not skipped).\n\n**On early-abort:**\n- verdict = `FAIL`\n- failure class = `verification_blocked`\n- confidence = `Low`\n- write focused diagnostics\n- write `$VERDICT_FILE` with those diagnostics, then skip all later steps\n\n**Output:** verified preconditions or early-abort diagnostics\n\n## Resolve Submission\n\nTurn the submission into the material under review. What cannot be resolved is\nnever guessed at.\n\n**Input:** `work` recorded in `$WORK_MANIFEST` (or the older-spelling `$INPUT_FILE`),\n`work.root`\n\n**Actions:**\n1. Read `kind`, `root`, `items`. An unknown `kind`, an empty `items` list, or a\n malformed manifest is `verification_blocked`.\n2. Resolve every item by kind, always from `work.root`:\n - `file_set` — read each path; relative paths resolve against `root`, and a\n missing path is `verification_blocked`.\n - `links` — fetch each URL; a URL that cannot be fetched is\n `verification_blocked`, not an `unverifiable` claim.\n - `git_diff` — `git -C \"$root\" diff <base>..<head>`, or the working tree when\n no range is given; no `git`, no repository, or a bad ref is\n `verification_blocked`.\n - `pr` — `gh pr view` plus `gh pr diff` for the number or URL; a missing\n `gh`, an expired login, or an unreachable host is `verification_blocked`.\n - `command_output` — run each command from `root` and capture stdout and\n stderr as the material.\n - `inline` — the text recorded in the manifest is the material.\n3. Record the resolved inventory before auditing: `kind`, item count, per-item\n status (`resolved` or `blocked`), and where each item's evidence lives.\n4. A `pr` or `git_diff` submission is reviewed as a diff: claims are checked\n against the changed lines and the tests they touch, never against the\n description written alongside them.\n\n**Output:** resolved work inventory for the audit\n\n## Audit\n\nPerform bounded adversarial review of the target against the resolved work\nsubmission and invariants.\n\n**Input:** resolved work inventory, invariants, verification target, requirement list, context\n\n**Actions:**\n\n**Step 1 — Extract claims**\nExtract every verifiable claim that matters operationally:\n- workflows, commands, tool calls\n- configuration and environment variable claims\n- architecture claims that imply behaviour\n- guarantees and constraints\n- security, auth, and permission claims\n\n**Step 2 — Investigate with scope discipline**\n1. verify all in-scope claims first\n2. review high-risk claims with maximum depth\n3. expand beyond scope only when contradiction signals, dependencies, or\n high-risk impact require it\n4. continue reviewing all in-scope claims even after a normal FAIL condition is met;\n only a precondition failure stops the audit early\n\n**High-risk areas:** setup steps, CLI commands, configuration keys, authentication,\ndeployment, external publishing, destructive operations.\n\n**Step 3 — Gather evidence using the hierarchy**\n\n| Priority | Evidence source |\n|---|---|\n| 1 | source code, config files, schemas, route definitions |\n| 2 | direct runtime verification |\n| 3 | tests |\n| 4 | MCP-queried system state |\n| 5 | external docs, web pages, linked references |\n| 6 | conversational assumption or indirect inference |\n\n**Rules:** higher-priority evidence overrides lower; priority 5–6 alone is not\nenough for `verified`; a submitted link or PR description is priority 5.\n\n**Step 4 — Produce claim verdicts**\nFor each claim: CLAIM, EVIDENCE, EVIDENCE PRIORITY, VERDICT\n(`verified` / `partially_verified` / `unverifiable` / `incorrect`).\nA claim must not be marked `verified` without positive supporting evidence.\n\n**Step 5 — Review the phase boundary**\nCheck whether the calling adapter preserved the right mode boundary.\n\n**Step 6 — Check requirement coverage**\nFor every item in `requirements`, confirm coverage with positive evidence.\nAny `missing` item — or any `partial` high-risk item — forces FAIL with\n`failure_class: requirement_gap`.\n\n**Output:** structured audit findings for the verdict step\n\n## Verdict\n\nTurn the audit into a final PASS / FAIL result.\n\n**Input:** audit findings and verdict file path from context (use it as\n`$VERDICT_FILE`)\n\n**Actions:**\n1. Fail if any critical claim is incorrect.\n2. Fail if verification was blocked.\n3. Fail if the evidence base is too weak for high-risk claims.\n4. Fail if any requirement is `missing`, or a high-risk requirement is only\n `partial` (`failure_class: requirement_gap`); list the uncovered items.\n5. Fail terminally if `context.iteration` exceeds `context.max_iterations`\n (`failure_class: iteration_ceiling`) so the loop stops instead of thrashing.\n6. Otherwise, pass with the appropriate confidence.\n7. Write `$VERDICT_FILE` so line 1 is `PASS` or `FAIL`,\n line 2 is `High`, `Medium`, or `Low`, and the remaining lines summarise key\n findings and any uncovered requirements.\n\n**Verdict contract (calling adapter must obey):**\n- Line 1 is `PASS` → the loop is satisfied; the calling adapter may continue.\n- Line 1 is `FAIL` → the calling adapter **MUST NOT** proceed to reward, **MUST\n NOT** ask the user for approval, and **MUST NOT** continue. It must address the\n findings, increment `context.iteration`, and re-invoke critic-loop from a fresh\n delegated subagent — never on the thread that produced the work under review.\n- `failure_class: iteration_ceiling` → stop looping and surface the unresolved\n findings; never silently pass. The ceiling bounds the loop so a weak agent\n cannot thrash forever.\n\n**Output:** final verdict file\n\n```json\n{\"contract\":{\"type\":\"shell\",\"shell\":{\"cmd\":\"test -f \\\"$VERDICT_FILE\\\" && head -1 \\\"$VERDICT_FILE\\\" | grep -qiE '^(PASS|FAIL)$' && sed -n '2p' \\\"$VERDICT_FILE\\\" | grep -qiE '^(High|Medium|Low)$'\",\"interpreter\":\"bash\",\"timeout_seconds\":5},\"required\":true}}\n```\n\n## Reward Signal\n\nOnly reachable after all prior steps are solved.\n\nThe phase output has been independently challenged and looped until satisfied. The\nresulting verdict is more truthful because it is based on extracted claims,\nexplicit evidence, contradiction search, requirement-by-requirement coverage, and\na clean boundary between execution and review.\n\nThe single contract on this adapter is the verdict-file syntax gate: it is the\none artifact the critic produces, and everything before it is the critic's own\nreasoning. The precondition, submission-resolution, and audit steps carry no\ncontracts because a contract gates an outcome, not a step, and a critic that\ngates itself inward re-delegates work it was delegated to perform.\n\nThat gate asserts the verdict file's **shape**, not the review's soundness: a\n`PASS` is this critic's judgment, and the separation that makes it worth\nsomething is that a critic was run apart from the executor. The caller's own\n`PASS` gate proves only that a file was written saying `PASS`.\n",
|
|
32
|
-
"protocol-linking-guide": "---\nversion: \"5.14.
|
|
33
|
-
"refine-search": "---\nversion: \"5.14.
|
|
26
|
+
"adapter-migration": "---\nversion: \"5.14.3\"\nslug: adapter-migration\ntitle: Adapter Migration Workflow\n---\n\n# Adapter Migration Workflow\n\nBatch-migrate all adapters in a space to the current structural scheme. Exports\nevery adapter, applies conservative structural transformations, reports changes\nper adapter, and re-trains the conforming subset autonomously.\n\nThis workflow handles structural migrations only — it preserves semantic content\n(steps, intent, examples) while updating format, headings, and contract shapes\nto match the latest SQUADRULES requirements.\n\n## Activation Patterns\n\n**Run this workflow when the user says ANY of:**\n\n- \"migrate all adapters\" / \"batch update adapters\"\n- \"update adapters to latest scheme\" / \"update adapter structure\"\n- \"run structural migration\" / \"migrate adapters\"\n- \"update all my adapters\" / \"fix adapter structure\"\n- \"apply latest adapter format\" / \"restructure adapters\"\n\n**Trigger pattern:** **migrate** / **batch update** / **structural migration** /\n**update format** + (adapters | all | space).\n\n**Must Never:**\n- Alter semantic content (step text, trigger phrases, examples, intent).\n- Auto-train an adapter without first producing a per-adapter change report.\n- Guess transformations when the adapter structure is ambiguous.\n- Delete adapters or layers during migration.\n- Migrate adapters that already conform (report them as \"no changes needed\").\n- Review the transformed set yourself: a batch overwrite written by your own hand\n is not checked by re-reading your own hand.\n\n**Must Always:**\n- Export every adapter before making any changes.\n- Apply only conservative, reversible structural transformations.\n- Flag ambiguous cases for manual review instead of guessing.\n- Produce a per-adapter change report before executing any writes.\n- Have the transformed set reviewed by a delegated critic before the batch write.\n- Preserve the adapter's slug, version, and chain_root fields.\n\n**Good trigger examples:**\n- \"migrate all my personal adapters to the latest format\" → run this workflow\n- \"update all adapters in the team space\" → run this workflow\n\n**Bad trigger examples:**\n- \"update this one adapter\" → use `author-adapter` with `fix` operation\n- \"create a new adapter\" → use `author-adapter`\n- \"export my adapters\" → use `export` directly\n\n## Preflight Dependencies\n\nBefore running migration, verify readiness:\n\n1. `export` tool is available and callable.\n2. `tune` and `train` tools are available for writes.\n3. A subagent facility is available in this host for the review hop. Without it,\n stop and report the blocker rather than approving your own batch.\n4. Target space is identified (personal or a named group space).\n5. The migration is structural-only (no semantic changes).\n\nIf any tool is unavailable, stop and report the connection blocker with\nremediation guidance. These are checks you perform, not gates: a failure produces\na repair action, so no contract is spent on them.\n\n## Export All Adapters\n\nExport every adapter from the target space using bulk export:\n\n1. Call `export` with `all_adapters: true`, `space_name` set to the target\n space, and `format: skill_tree`.\n2. Record the total adapter count from the response.\n3. For each adapter in the response, extract its slug, URI, and content.\n\nIf the space has no adapters, report this and stop.\n\n## Analyze and Transform\n\nFor each exported adapter, perform structural analysis and apply migrations.\n\n### Structural checks (apply all that are needed)\n\n1. **Heading order** — first H2 must be `Activation Patterns`, last H2 must be\n `Reward Signal`. If missing or out of order, flag for restructuring.\n2. **Contract fences** — all contract JSON blocks must use ` ```json ` (not\n plain ` ``` `). If plain fences contain contract JSON, convert them.\n3. **Frontmatter** — must include `slug`. Add `version` if missing. Preserve\n existing `chain_root` when present.\n4. **Line count** — adapters exceeding 350 lines must be flagged for splitting\n (do NOT auto-split; report as manual review needed).\n5. **Shell interpreter** — every shell contract must include `\"interpreter\"`\n field with an allowed value (`bash`, `sh`, `python3`, `python`, `node`).\n6. **Forward link** — every `forward` contract must set `forward.target`\n matching `squadrules://adapter/<slug>`.\n7. **Critic hop** — a `forward` contract whose target is\n `squadrules://adapter/critic-loop` is the deprecated self-review shape: it\n runs the critic on the thread that produced the work. Flag it for manual\n review; converting a review hop into a delegated one changes verification\n semantics and is not a conservative transformation.\n\n### Transformation rules\n\n- **Conservative only:** If a transformation might change meaning, skip it and\n flag for manual review.\n- **Reversible:** Every change must be expressible as a diff.\n- **Idempotent:** Running migration twice produces no additional changes.\n\nFor each adapter, produce:\n- `status`: `needs_changes` | `up_to_date` | `needs_manual_review`\n- `changes`: list of specific transformations applied\n- `warnings`: list of items flagged for manual review\n- `transformed_content`: the full updated markdown (when `needs_changes`)\n\n## Report Changes\n\nWrite the migration report to `$MIGRATION_REPORT_FILE` — an absolute path you\nallocate under `$SQUADRULES_LOCAL_ARTIFACT_DIR` (resolve a hint from the\n`squadrules_local_artifact_dir` field of the latest `activate`/`forward` response\nand export it; the server never names a path on your machine). Also allocate\n`$WORK_MANIFEST` and `$VERDICT_FILE` in the same directory. Record the\ntransformed drafts as files under one root and write the handoff to\n`$WORK_MANIFEST` as flat keys: `kind: file_set`, `root: <that directory>`, then\n`items:` with one draft path per line.\n\nRecord a summary table in the report:\n\n| Adapter slug | Status | Changes | Warnings |\n|-------------|--------|---------|----------|\n| example-adapter | needs_changes | 3 structural fixes | 0 |\n| another-adapter | up_to_date | 0 | 0 |\n\nFor each adapter with `needs_changes`, show the specific transformations.\nFor each `needs_manual_review`, explain what needs human attention.\n\nA report on your own scratch is a local, reversible artifact, so it carries no\ngate. What is gated is the batch write it precedes.\n\n## Review the Transformed Set\n\nDelegate the review of every transformed draft before anything is written:\n\n```json\n{\"contract\":{\"type\":\"subagent\",\"subagent\":{\"context\":\"Run the critic over the transformed adapter drafts and return its actual report. Call the forward tool with uri squadrules://adapter/critic-loop, submit work from $WORK_MANIFEST (kind file_set, the transformed drafts), calling_protocol_slug adapter-migration, verification_target 'structural migration preserved semantics and did not over-reach', the requirement list of structural checks, and context.verdict_file $VERDICT_FILE with context.iteration and context.max_iterations (8). Do not review the drafts yourself and do not re-delegate the review.\",\"mcp\":[{\"tool_name\":\"forward\",\"arguments\":{\"uri\":\"squadrules://adapter/critic-loop\"}}]},\"required\":true}}\n```\n\n## Apply, Verify, and Report\n\n1. Run the gate at the end of this section against `$VERDICT_FILE` **before** any\n write. `FAIL` → fix the drafts the critic named, run a fresh critic pass the\n same way (a subagent delegating `squadrules://adapter/critic-loop`,\n `iteration` incremented) and run the gate again. Loop automatically; do not ask\n the user whether to continue. At `failure_class: iteration_ceiling`, stop,\n report the unresolved findings, and write nothing.\n2. Apply the migration only on a `PASS` verdict:\n - **Apply all** `needs_changes` adapters.\n - **Leave untouched** every `needs_manual_review` adapter.\n - For content-level fixes (heading order, fence conversion, interpreter\n addition): use `tune` with the transformed content, its URI, and\n `review_evidence` from the verdict file.\n - For changes that alter layer count or identity: use `train` with\n `force_update: true` and the same `review_evidence`.\n - Do NOT change an adapter's space assignment during migration.\n3. After all writes, re-export each migrated adapter to verify structural\n compliance, then report final status:\n\n| Metric | Count |\n|--------|-------|\n| Adapters scanned | N |\n| Already up to date | N |\n| Successfully migrated | N |\n| Migration failed | N |\n| Flagged for manual review | N |\n\nFor each failure, report the error message and suggested fix. Semantic integrity\nwas reviewed before the write; do not present a post-write structural re-export\nas if it re-checked meaning.\n\n```json\n{\"contract\":{\"type\":\"shell\",\"shell\":{\"cmd\":\"head -1 \\\"$VERDICT_FILE\\\" | grep -qi '^PASS$'\",\"interpreter\":\"bash\",\"timeout_seconds\":5},\"required\":true}}\n```\n\n## Reward Signal\n\nOnly reachable after all prior steps are solved.\n\nThe adapter library in the target space now conforms to the current structural\nscheme. Every adapter has:\n- Correct heading order (Activation Patterns first, Reward Signal last).\n- Proper ` ```json ` contract fences.\n- Shell contracts with `interpreter` field.\n- Forward contracts with a `forward.target` adapter URI.\n- Valid frontmatter with `slug` and optional `version`.\n- Been verified post-migration for structural compliance.\n\nSemantic content (steps, intent, examples, triggers) is preserved unchanged.\n\nWhat the verdict gate proves: a delegated critic pass over the transformed drafts\nleft a verdict file reading `PASS`, and the store accepted the writes carrying\nthat evidence. What it does not prove: that the report came from the delegated\ncontext rather than this one, or that the verdict is bound to the drafts it\nreviewed — a content-bound review receipt would be needed for that.\n",
|
|
27
|
+
"author-adapter": "---\nslug: author-adapter\nversion: \"5.14.3\"\ntitle: Author Adapter (Create / Review / Refactor)\n---\n\n# Author Adapter (Create / Review / Refactor)\n\n> **Note to the agent:** SQUADRULES adapters are interfaces for AI agents — you\n> are the primary user. When you author an adapter, you design behaviour for\n> yourself and others. Write for them: single source of truth (never duplicate\n> rules), explicit over implicit (agents fill ambiguity with hallucination),\n> steps teach modes (each step teaches its cognitive mode), truth over fluency\n> (an adapter that reads well but causes wrong behaviour is worse than one that\n> reads rough but executes correctly).\n\n## Activation Patterns\n\nPreferred entry URI: `squadrules://adapter/author-adapter`.\nIf `forward.authoring` is present, use its operation and target throughout this\nrun. Do not reinterpret update as create or change the target mid-run. This\ncontext describes the requested work; it does not override host permissions.\n\nSQUADRULES authoring lifecycle — create, review, or update adapters / workflows.\nSupports three operations:\n- **create** — draft and train a new adapter from scratch.\n- **review** — audit an existing adapter, family, or bundle for structural issues,\n missing cross-references, chaining gaps, DRY violations, stale guidance, or\n agent-hostile ambiguity. Read-only.\n- **update** — apply specific corrections to an existing adapter and\n save the correction. Also triggered by: edit, fix, modify, change, improve, patch, refactor.\n\nA fourth lifecycle operation, **delete**, is not run here: follow the Delete flow\nin `docs/adapter-authoring-guide.md` (export, check the slug is not a chain\ndependency, call `delete`, verify it no longer resolves).\n\n**Run this adapter when the user says ANY of:**\n- \"create a new SQUADRULES adapter\" / \"register a personal adapter\"\n- \"train adapter into personal\" / \"train a workflow\"\n- \"review adapter\" / \"audit adapters\" / \"check adapter families for gaps\"\n- \"update adapter\" / \"edit adapter\" / \"fix adapter\" / \"modify adapter\"\n- \"patch adapter\" / \"refactor adapter\" / \"change adapter\" / \"improve adapter\"\n\n**Trigger pattern:** **create** / **train** / **register** / **review** /\n**audit** / **fix** / **update** / **edit** / **modify** / **change** /\n**improve** / **patch** / **refactor** / **correct** +\n(adapter / workflow).\n\n**Must Never:**\n- Run when the user only asked to execute an existing adapter.\n- Mutate adapters during a `review` operation.\n- Review your own draft: the critic pass is delegated, never performed on the\n drafting thread.\n- Optimise only for pretty wording; this adapter designs agent behaviour.\n- Treat \"update\", \"edit\", or \"modify an existing adapter\" as **create**.\n\n**Must Always:**\n- Infer `{operation}` from trigger: create / review / update.\n- Optimise for truth, low ambiguity, explicit sequencing, and user-need alignment.\n- Include Activation Patterns as the first H2 and Reward Signal as the last H2\n in any newly drafted adapter.\n- Enforce the 350-line limit per file.\n\n## Preflight Dependencies\n\nBefore running authoring actions, verify dependency and auth readiness:\n1. Required MCP tools are available: `activate`, `forward`, `reward`, and the\n operation-dependent tool (`train`, `export`, or `tune`).\n2. A subagent facility is available in this host for the critic pass. Without it\n this adapter cannot verify its own work: stop and report the blocker rather\n than reviewing the draft yourself.\n3. Required auth/session state is valid for the target MCP server.\n\nIf any check fails, attempt AI-assisted remediation automatically, then re-run\npreflight. Only hard-stop when a required tool or auth genuinely cannot be\nestablished autonomously. These are checks you perform, not gates: a failure here\nproduces a repair action, so no contract is spent on them.\n\n## Resolve Intent Autonomously\n\nUse structured `authoring` when provided. For original calls without it, infer\n`{operation}` from the user's trigger — do not stop to ask for confirmation:\n\n| Signal | Operation |\n|---|---|\n| \"create\", \"new\", \"train\", no match from activate | **create** |\n| \"review\", \"audit\", \"check\", \"gaps\", \"cross-references\" | **review** |\n| \"update\", \"edit\", \"fix\", \"modify\", \"change\", \"improve\", \"patch\", \"refactor\" | **update** |\n\nResolve the target from context without a confirmation prompt. Record the\ninferred operation and target, then continue. Escalate to the user only when\nthe request is genuinely ambiguous and no reasonable default exists.\n\n## Gather Requirements\n\n### For `create` — collect details for a new adapter\n\n**1. Determine the pattern:**\n\n| Signal | Pattern |\n|---|---|\n| One workflow, no variants | **Standalone** — one adapter, all steps inline |\n| Multiple issue types / output formats | **Router + Extensions** — router classifies, routes via `activate` |\n| Exceeds 350 lines or too complex for weaker models | **Chain** — split into sequential adapters linked via `forward` + slug |\n\n**2. Collect per adapter:**\n- Title, user problem, agent behaviour, mode map, steps, challenge type per step\n- Domain reference, existing adapters to reuse/compose, DRY/size check\n- Chain position, failure analysis\n\n### For `review` — audit existing adapters\n\nExport target adapter(s). Check: user-need fit, mode/step clarity,\ncross-reference completeness, handoff gaps, DRY violations, contract coverage,\ntruth-first behaviour, activation pattern accuracy, structure compliance\n(first H2 Activation Patterns, last H2 Reward Signal, under 350 lines),\nsibling consistency, chained adapter families, and whether every critic hop in\nthe audited adapters is a `subagent` contract rather than a `forward` contract.\n\n### For `update` — identify the specific issue\n\nExport the target adapter, read the current markdown, identify the exact gap or\nerror, and plan the minimal change.\n\n## Draft Markdown\n\n### Allocate the handoff paths first\n\nThe gates below read files that only exist if you created them. Resolve one hint\nfrom the `squadrules_local_artifact_dir` field of the latest `activate` or\n`forward` response (`project://<rel>` → this project root, `user://<rel>` → your\nhome or `$XDG_CONFIG_HOME`), export the absolute result as\n`SQUADRULES_LOCAL_ARTIFACT_DIR`, then allocate collision-free paths for the\ntarget slug:\n\n```bash\nexport SQUADRULES_LOCAL_ARTIFACT_DIR=\"<resolved absolute path>\"\nD=\"$SQUADRULES_LOCAL_ARTIFACT_DIR/author-adapter-$SLUG\"\nmkdir -p \"$D\"\nexport WORK_MANIFEST=\"$D/work-manifest.txt\" # the critic's submission\nexport VERDICT_FILE=\"$D/verdict.txt\" # the critic's verdict\nexport REVIEW_FINDINGS_FILE=\"$D/findings.md\" # review operation only\n```\n\nThe server never names a path on your machine; you do.\n\n### MCP / Local-Filesystem Boundary\n\n- A personal adapter stored in MCP **cannot** reference local files.\n- Any adapter — system or personal — may chain to another adapter with a\n `forward` contract naming `squadrules://adapter/<slug>`; slugs are globally\n unique, so resolution is deterministic.\n- A personal adapter must still be **self-contained** in its instructions: it\n cannot rely on files that only exist in one repository.\n- When a `shell` check has more than one condition, parses JSON, or does not fit\n one readable line, put it in a **gate script artifact** — it is stored with the\n adapter and materialized at run time, not read from your local files; never\n escape a program inline into `cmd`.\n- Order: `train` the adapter markdown first, then `train` the script as an\n artifact — an artifact attaches only to an adapter that already exists. Pin the\n script's identity with a `# squadrules-artifact:` header, and pass\n `force_update: true` on a re-train that matches it, so a fix updates\n that artifact instead of adding a second one. Input fields and the refusal\n message: the `train` tool description.\n- The artifact train targets `squadrules://adapter/<slug>`, so pin the adapter's\n slug with frontmatter `slug:` instead of guessing the slug `train` derived from\n the title.\n- Keep the contract one line: `interpreter: \"bash\"`, `cmd: python3\n \"$SQUADRULES_LOCAL_ARTIFACT_DIR/artifacts/<name>.py\" --gate <name>`.\n- Verify before shipping — **two** checks, both required:\n 1. `activate` the adapter and confirm `linked_artifacts[].relative_path` is\n exactly the path `cmd` invokes. Follow each row's `materialize` instruction before\n the contract that needs it.\n 2. **Export check:** call MCP **`export`** with\n `uri: \"squadrules://adapter/<slug>\"` and `format: skill_tree` (or\n `skill_zip` for the bundle) and confirm the script is present under\n `artifacts/` at the path the contract invokes. Read the returned\n `diagnostics[]`: `artifact_stored_sha_mismatch` or\n `artifact_relative_path_invalid` means the stored artifact is broken —\n re-train it instead of shipping it.\n- A `cmd` that names a script the export does not contain is a broken adapter:\n it fails at run time with a missing-file error and burns the user's step.\n Fix it before shipping. The only exception is a repository-owned gate that\n the adapter names explicitly and that lives in the user's repository — say so\n in the adapter text, and state how the agent finds it.\n\n### Drafting rules (all operations)\n\n**Right mode at the right time:** Every adapter must help the agent recognise\nwhether the current step is for exploration, clarification, ideation, planning,\nexecution, validation, review, or handoff.\n\n**Truth over fluency:** Prefer explicit prompts, stop conditions, uncertainty\nescalation, and observable verification over narrative reassurance.\n\n**DRY:** Shared content across adapters must live in one place.\n\n**350-line maximum per file.** Split into linked adapters if exceeded.\n\n**Slug convention:** Every adapter gets a short, unique, lowercase-hyphenated slug.\n\n**Structure:** H1 title, first H2 Activation Patterns, second H2 Preflight\nDependencies, middle H2s one per stage with JSON contract block, last H2 Reward\nSignal. Frontmatter: `slug` (required), `version` (optional), `chain_root`\n(required for mid-chain adapters).\n\n**Scripts are obtained, not assumed:** when a step's `cmd` invokes a script, the\nadapter must state in its own text how the agent obtains that file before\nrunning the command — follow the `activate` artifact row's `materialize`\ninstruction, or `export` the adapter. A step that says only \"run `python3\n…/artifacts/x.py`\" leaves the agent guessing where the file is; a\nmissing-file gate failure is the most common\nresult of that omission.\n\n**Contracts:** One per adapter is the default; a second is justified only at a\nboundary that is hard to roll back. Load `challenge-type-guide` for decision\nrules and JSON formats (`forward` with\n`squadrules://adapter/challenge-type-guide`).\n\n**Critic-loop and mutation gates:** Load `critic-loop-guide` for placement,\nthe FAIL gate, and the work-submission rules (`forward` with\n`squadrules://adapter/critic-loop-guide`).\n\nFor `create`: draft the full adapter markdown.\nFor `review`: write a structured gap report to `$REVIEW_FINDINGS_FILE`.\nFor `update`: apply the identified change and show a diff-style summary.\n\n## Critic-Loop Review (create and update only)\n\nFor `create` and `update`: have the draft reviewed. This is an autonomous quality\nloop — the agent owns content, the critic owns quality, and no human approval is\nrequested at any point. The critic must not be you: you wrote the draft, so your\nown re-reading cannot detect what you did not intend to write.\n\nWrite the submission handoff to `$WORK_MANIFEST` as flat keys — `kind: file_set`,\n`root: <directory of the draft>`, then `items:` with the drafted file's path on\none line — and delegate the review to a subagent. Delegate it now; do not audit\nthe draft on this thread first.\n\n```json\n{\"contract\":{\"type\":\"subagent\",\"subagent\":{\"context\":\"Run the critic on the drafted adapter markdown and return its actual report. Call the forward tool with uri squadrules://adapter/critic-loop and submit: work from $WORK_MANIFEST (kind file_set, the drafted file), the original requirement list, calling_protocol_slug author-adapter, verification_target 'structural compliance and agent behaviour', context.verdict_file $VERDICT_FILE, context.iteration and context.max_iterations (8). Follow critic-loop to its end, let it write $VERDICT_FILE, and report back its findings plus the verdict file's first two lines. Do not review the draft yourself and do not re-delegate the review.\",\"mcp\":[{\"tool_name\":\"forward\",\"arguments\":{\"uri\":\"squadrules://adapter/critic-loop\"}}]},\"required\":true}}\n```\n\n## Save After a PASS Verdict\n\nRead the verdict the critic left behind and act on it, then save.\n\n1. Run the gate below. `FAIL` → address **every** finding in the report, then\n start a fresh critic pass the same way (a subagent delegating\n `squadrules://adapter/critic-loop` with the corrected draft, the same\n requirements, and `iteration` incremented) and re-run this gate. Loop\n automatically; do not ask the user whether to continue.\n2. The loop is bounded by `max_iterations`. When `iteration` exceeds it, the\n critic returns `failure_class: iteration_ceiling`: **stop looping**, report the\n unresolved findings, and do not save an unreviewed draft as if it passed.\n3. On `PASS`, capture the verdict file path and save:\n - `create` — call `train` with the drafted markdown and `review_evidence`\n (verdict file path, exit code, stdout). Use `force_update: false` unless an\n overwrite was explicitly requested.\n - `update` — call `tune` with the existing adapter URI, corrected content, and\n `review_evidence`. Use `train` with `force_update: true` only for a required\n structural replacement (changing identity/H1 mapping or layer count). Update\n the corresponding repository source when the adapter is repo-managed, and\n make repository edits in the task's isolated worktree.\n - `review` — do not call `train`; the operation is read-only and this gate is\n satisfied by the findings report at `$REVIEW_FINDINGS_FILE`.\n4. Read the stored adapter back (`export` it, or the CLI on a local transport)\n and compare it against what you intended to save; report the URI and any\n difference. This is the run's completion criterion, not a gate: a remote\n store cannot be observed from a shell command, so no contract asserts it.\n\n```json\n{\"contract\":{\"type\":\"shell\",\"shell\":{\"cmd\":\"head -1 \\\"$VERDICT_FILE\\\" | grep -qi '^PASS$'\",\"interpreter\":\"bash\",\"timeout_seconds\":5},\"required\":true}}\n```\n\n## Reward Signal\n\nAdapter complete when:\n- `create` — a delegated critic returned `PASS`, the adapter is stored via `train`\n with that `review_evidence`, its URI is reported, and the stored copy was read\n back\n- `review` — findings report delivered from `$REVIEW_FINDINGS_FILE`\n- `update` — a delegated critic returned `PASS` on the changed parts, the corrected\n adapter is saved via `tune` (or a required structural replacement), read back and\n reported; repo-managed source updated in the task worktree\n\nWhat this proves: a separate context ran `critic-loop` over the draft and left a\nverdict file that reads `PASS`, and the store accepted that evidence. What it does\nnot prove: that the report came from that context, or that the verdict is bound to\nthe reviewed content — server-issued review receipts would be needed for that.\nReport the outcome as it stands; a passing gate is not a guarantee of correctness.\n\nA successful result means the resulting SQUADRULES adapter is more truthful,\nstep-aware, agent-readable, and aligned with human–AI harmony.\n",
|
|
28
|
+
"bulk-insert-adapters-via-cli": "---\nslug: bulk-insert-adapters-via-cli\nversion: \"5.14.3\"\ntitle: Bulk Insert Adapters via SQUADRULES CLI\n---\n\n# Bulk Insert Adapters via SQUADRULES CLI\n\n## Activation Patterns\n\nBatch-register multiple SQUADRULES adapters from a local directory tree using the\n`squadrules train` CLI. Handles directory scanning, validation, space targeting,\nand error recovery for bulk operations.\n\n**Run this workflow when the user says ANY of:**\n\n- \"bulk insert adapters\" / \"bulk train adapters\"\n- \"train all adapters in a directory\"\n- \"batch register adapters from folder\"\n- \"upload all .md files to SQUADRULES\"\n- \"sync local adapters to SQUADRULES\" / \"push adapters to SQUADRULES\"\n- \"train directory recursively\" / \"train --recursive\"\n\n**Trigger pattern:** **bulk** / **batch** / **all** / **directory** / **recursive** +\n(train | insert | register | upload | push | sync) + (adapters | workflows).\n\n**Must Never:**\n\n- Train files without first validating their structure.\n- Overwrite existing adapters without explicit `--force`.\n- Train files that contain secrets or token-like strings without\n `--allow-sensitive-upload`.\n- Skip reporting partial failures in a batch.\n\n**Must Always:**\n\n- Verify the target directory exists and contains `.md` files.\n- Show the file list and target space before executing.\n- Report per-file success/failure after the batch completes.\n- Respect the user's choice of space (personal or group).\n\n**Good trigger examples:**\n\n- \"Train all adapters in my-adapters/\" → run this workflow\n- \"Bulk insert the adapters from my export folder\" → run this workflow\n- \"Push all .md files in this directory to my personal space\" → run this workflow\n\n**Bad trigger examples:**\n\n- \"Train this one adapter\" → use `squadrules train <file>` directly\n- \"Create a new adapter\" → use `author-adapter`\n- \"Export my adapters\" → use `squadrules export`\n\n## Preflight Dependencies\n\nVerify before execution:\n\n1. `squadrules` CLI is installed and callable (`squadrules --version`).\n2. Authentication is valid (`squadrules token` returns a token without error).\n3. Target directory path exists and contains at least one `.md` file.\n4. If a space is specified, confirm it exists via `squadrules spaces`.\n5. A subagent facility is available for the review hop below. Without it the\n store will refuse the upload; report the blocker, do not skip the review.\n\nIf any check fails, stop and report the issue with remediation guidance. These\nchecks are performed, not gated — the gate sits at the write.\n\n## Resolve Scope and Validate\n\nResolve the batch operation details autonomously:\n\n1. **Source directory** — absolute path.\n2. **File count** — number of `.md` files found (recursive or flat).\n3. **Target space** — personal (default) or a named group space.\n4. **Force mode** — whether `--force` will be used (overwrites existing).\n\nValidate each `.md` file against SQUADRULES adapter requirements:\n- Has an H1 title.\n- First H2 is \"Activation Patterns\".\n- Last H2 is \"Reward Signal\".\n- Contains at least one fenced `json` block with a top-level `contract` object.\n- Does not exceed 350 lines.\n\nSkip invalid files, train the valid subset, and document every skipped file with\nits validation error and a suggested fix. Do not stop to ask the user.\n\n## Review the Set Before Uploading\n\n`train` refuses a markdown adapter without critic-loop `PASS` evidence, so an\nunreviewed batch uploads nothing. Allocate the handoff paths under\n`$SQUADRULES_LOCAL_ARTIFACT_DIR` — resolve a hint from the\n`squadrules_local_artifact_dir` field of the latest `activate`/`forward` response\nand export it; the server never names a path on your machine. You need\n`$WORK_MANIFEST`, `$VERDICT_FILE`, and `$BULK_LOG_FILE`. List the valid files in\n`$WORK_MANIFEST` as flat keys (`kind: file_set`, `root: <source directory>`, then\n`items:` with one file path per line) and delegate the review:\n\n```json\n{\"contract\":{\"type\":\"subagent\",\"subagent\":{\"context\":\"Run the critic over the adapter files listed in $WORK_MANIFEST and return its actual report. Call the forward tool with uri squadrules://adapter/critic-loop, submitting the file list as work kind file_set with the source directory as root, the requirement list above as requirements, and context.verdict_file $VERDICT_FILE with context.iteration and context.max_iterations (8). Do not review the files yourself.\",\"mcp\":[{\"tool_name\":\"forward\",\"arguments\":{\"uri\":\"squadrules://adapter/critic-loop\"}}]},\"required\":true}}\n```\n\n## Prove the Write Boundary\n\nA directory batch overwrites adapters in a shared space: hard to roll back, so\none gate sits in front of it and one behind it. Run the gate below **before** any\n`train` command. If it exits non-zero, nothing has been uploaded — fix the named\ncondition (install the CLI, re-authenticate, correct `$SOURCE_DIR`, or obtain a\n`PASS` verdict), then run it again.\n\n```json\n{\"contract\":{\"type\":\"shell\",\"shell\":{\"cmd\":\"squadrules --version && squadrules token > /dev/null && test -d \\\"$SOURCE_DIR\\\" && find \\\"$SOURCE_DIR\\\" -name '*.md' | head -1 | grep -q . && head -1 \\\"$VERDICT_FILE\\\" | grep -qi '^PASS$'\",\"interpreter\":\"bash\",\"timeout_seconds\":30},\"required\":true}}\n```\n\n## Run the Batch and Report\n\nRun the batch and keep its report. The CLI reads review evidence from the\n`SQUADRULES_REVIEW_EVIDENCE` environment variable as one JSON object\n(`verdict_file`, `exit_code`, `stdout`) and reuses it for every file in a\ndirectory batch. Therefore:\n\n- If the critic reviewed the set as one submission, export that verdict once and\n train the directory, capturing its report:\n\n ```\n squadrules train <directory> --recursive --model <model> --space <space> [--force] 2>&1 | tee \"$BULK_LOG_FILE\"\n ```\n\n- If the critic reviewed files individually, train file-by-file and re-export\n `SQUADRULES_REVIEW_EVIDENCE` for each file, so no adapter is stored under\n another adapter's verdict; append every run to `$BULK_LOG_FILE`. Move\n non-adapter files (README, reference docs) out of the directory before using\n `--recursive` — the batch skips `README.md` by name and nothing else.\n\nSummarise the outcome for the user:\n\n| Metric | Value |\n|--------|-------|\n| Files attempted | N |\n| Successfully trained | N |\n| Failed | N |\n| Skipped (invalid) | N |\n\nFor each failure, report: file path, error message, suggested fix. If all\nsucceeded, confirm the adapter URIs are accessible via `squadrules spaces`.\nA `REVIEW_EVIDENCE_REQUIRED` failure means the review did not cover that file:\nreview it, then retry; never store an unreviewed adapter to clear the error.\n\nThe batch prints one summary line (`<n> ok, <m> failed (of <total>)`) and one\n`ERR <path>: <error>` line per failure. The gate below reads that captured report\ninstead of trusting a recollection of it, so the write is verified by what the\nCLI actually stored:\n\n```json\n{\"contract\":{\"type\":\"shell\",\"shell\":{\"cmd\":\"test -s \\\"$BULK_LOG_FILE\\\" && grep -qE '[1-9][0-9]* ok, 0 failed' \\\"$BULK_LOG_FILE\\\" && ! grep -q 'ERR ' \\\"$BULK_LOG_FILE\\\"\",\"interpreter\":\"bash\",\"timeout_seconds\":10},\"required\":true}}\n```\n\n## Reward Signal\n\nWorkflow complete when:\n- A delegated critic returned `PASS` over the files being uploaded.\n- All valid adapter files in the target directory have been trained to the\n specified space, and the captured batch report shows `0 failed`.\n- Per-file results have been reported.\n- Any failures have been documented with remediation guidance.\n\nWhat this proves: the store accepted the uploads and the CLI reported no failures\nin the captured output. What it does not prove: that the review covered each file\nindividually when one verdict served a directory batch, or that the verdict came\nfrom the delegated context rather than this one.\n\nA successful bulk insert means the user's local adapter library is now\nregistered in SQUADRULES and available for activation by AI agents.\n",
|
|
29
|
+
"challenge-type-guide": "---\nversion: \"5.14.3\"\nslug: challenge-type-guide\ntitle: Challenge Type Selection Guide\n---\n\n# Challenge Type Selection Guide\n\nDecision rules, JSON formats, interpreter selection, and anti-patterns for\nchoosing SQUADRULES challenge types. Loaded by adapter-authoring agents during\ndrafting and review.\n\n## Activation Patterns\n\n**Typically invoked by:** `author-adapter` and `critic-loop`.\n\n**Can be invoked directly when agent needs:**\n- \"challenge type reference\" / \"which challenge type to use\"\n- \"how to write shell challenges\" / \"challenge format\"\n- \"interpreter selection for challenges\"\n\n**Trigger pattern:** **challenge** + (type | format | selection | guide).\n\n**Must Never:**\n- Be used as an execution adapter.\n- Select `comment` merely because it is easy.\n\n**Must Always:**\n- Be consulted before assigning challenge types to adapter steps.\n- Choose the strongest observable contract available.\n- Match challenge choice to the mode of the step: ask, decide, act, verify, or review.\n\n**Good trigger examples:**\n- drafting a new adapter and need challenge types → load this\n- reviewing challenge type selection in a draft → load this\n\n**Bad trigger examples:**\n- \"Create a new adapter\" → use `author-adapter`\n- \"Review my adapter draft\" → use `critic-loop`\n\n## Core Rules\n\n`comment` is the challenge type of **last resort**. If a step produces any\nobservable artifact — a file, a git state change, an API response, or an exit\ncode — use `shell` or `subagent` instead.\n\n**Mode before challenge type:**\n- **clarify / approve** → `user_input`\n- **chain to another adapter** → `forward` (link to another adapter)\n- **execute or verify local state** → `shell`\n- **delegate to another agent** → `subagent`\n- **pure reasoning with no observable artifact** → `comment`\n\n### Decision Tree\n\n```\nDoes the step chain to another adapter via forward?\n ├─ YES → \"forward\" (target: squadrules://adapter/<slug>)\n └─ NO → Does the step produce or verify a file, command result, or system state?\n ├─ YES → \"shell\" (with interpreter)\n └─ NO → Does the step require human approval or choice?\n ├─ YES → \"user_input\"\n └─ NO → Does the step delegate work to another agent?\n ├─ YES → \"subagent\"\n └─ NO → \"comment\" (last resort — no stronger contract possible)\n```\n\n### Challenge JSON Formats\n\n**shell** (interpreter is REQUIRED)\nExample ```json\n{\"contract\":{\"type\":\"shell\",\"shell\":{\"cmd\":\"<command>\",\"interpreter\":\"bash\",\"timeout_seconds\":30},\"required\":true}}\n```\n\nAllowed interpreters: `bash`, `sh`, `python3`, `python`, `node`. Build tools\n(`terraform`, `docker`, `npm`, etc.) are **not** interpreters — wrap them in a\n`bash` command instead.\n\n**forward** (links to another adapter — bare MCP tool calls are not valid)\nExample ```json\n{\"contract\":{\"type\":\"forward\",\"forward\":{\"target\":\"squadrules://adapter/<slug>\"},\"required\":true}}\n```\n\nThe server validates that the submitted `evidence.target` equals the contract's\n`forward.target`, proving the agent called `forward` with the correct target\nslug. Bare MCP tool calls belong in a `subagent.mcp` list (rung 3), never here.\n\n**user_input**\nExample ```json\n{\"contract\":{\"type\":\"user_input\",\"user_input\":{\"prompt\":\"<specific question>\"},\"required\":true}}\n```\n\n**subagent** (rung 2 — delegated judgment)\nExample ```json\n{\"contract\":{\"type\":\"subagent\",\"subagent\":{\"context\":\"<task description>\"},\"required\":true}}\n```\n\nUse `subagent` when a step delegates work to another agent rather than executing\nit directly. The `context` field provides task-specific guidance; the mandatory\ndelegation instruction is appended automatically. Proof is `evidence.report` —\nthe subagent's actual report, not your summary of it.\n\n**subagent.mcp** (rung 3 — delegated MCP tool work; optional)\nExample ```json\n{\"contract\":{\"type\":\"subagent\",\"subagent\":{\"context\":\"Export all adapters and report slugs and versions\",\"mcp\":[{\"tool_name\":\"export\",\"arguments\":{\"all_adapters\":true}}]},\"required\":true}}\n```\n\n`subagent.mcp` names the real MCP tool calls the **subagent** must make. The tool\ntranscript stays in the subagent's context and never reaches yours; proof is\nstill `evidence.report`. Omit the field for rung-2 judgment work.\n\n**comment** (last resort — max 1 per adapter, closing ACK only)\nExample ```json\n{\"contract\":{\"type\":\"comment\",\"comment\":{\"min_length\":50},\"required\":true}}\n```\n\n### Solution JSON Formats\n\nEvery solution follows the same envelope:\n\n```json\n{\n \"type\": \"<challenge_type>\",\n \"outcome\": \"success | failure | skipped\",\n \"evidence\": { /* type-specific proof data */ },\n \"nonce\": \"<echo from contract>\",\n \"proof_hash\": \"<echo from contract>\"\n}\n```\n\n**shell solution**\n```json\n{\"type\":\"shell\",\"outcome\":\"success\",\"evidence\":{\"exit_code\":0,\"stdout\":\"...\",\"stderr\":\"\",\"duration_seconds\":1.2}}\n```\n\n**forward solution**\n```json\n{\"type\":\"forward\",\"outcome\":\"success\",\"evidence\":{\"target\":\"squadrules://adapter/implement-terraform\",\"success\":true}}\n```\n\n**subagent solution**\n```json\n{\"type\":\"subagent\",\"outcome\":\"success\",\"evidence\":{\"report\":\"<the subagent's actual report>\"}}\n```\n\n**comment solution**\n```json\n{\"type\":\"comment\",\"outcome\":\"success\",\"evidence\":{\"text\":\"Verified all items are complete.\"}}\n```\n\n**user_input solution**\n```json\n{\"type\":\"user_input\",\"outcome\":\"success\",\"evidence\":{\"confirmation\":\"agreed. proceed\",\"timestamp\":\"2026-05-18T14:49:00Z\"}}\n```\n\n## Interpreter Selection\n\n| Task | Interpreter |\n|---|---|\n| File exists, tool installed, git state | `bash` |\n| Simple content grep | `bash` |\n| Multi-line regex or paragraph processing | `python3` |\n| JSON validation | `bash` (jq) or `python3` |\n| YAML / complex data structure checks | `python3` |\n| Node.js ecosystem tools | `node` |\n\n**Rule of thumb:** default to `bash`. If you need multi-line regex, imports for\ndata formats, or complex string processing, use `python3`. Use `node` only when\nthe check requires the Node.js runtime.\n\n`cmd` is always program text: `python3` / `node` receive it as `-c` / `-e` source,\nso these rows describe short inline programs. Once a check needs more than one\nreadable line, stop choosing an interpreter and ship the script as an artifact,\ninvoked through a `bash` wrapper — see\n[Artifacts for Shell Contracts](#artifacts-for-shell-contracts).\n\n## Security and Working Directory Rules\n\nUse `$SQUADRULES_LOCAL_ARTIFACT_DIR` as the base directory for local handoff\nartifacts. File paths within it are provided as variables by the invoking agent\nto avoid collisions between parallel sessions.\n\n**Rules:**\n- all file paths in shell challenges reference variables (e.g., `$DRAFT_FILE`,\n `$VERDICT_FILE`) set by the parent agent — never hardcode filenames\n- the parent agent constructs collision-free paths under\n `$SQUADRULES_LOCAL_ARTIFACT_DIR`\n- when using SQUADRULES MCP, the latest `activate` / `forward` / `next` response\n field `squadrules_local_artifact_dir` is an ordered array of URI hints\n (`project://<rel>`, `user://<rel>`); pick one, resolve on your machine, and\n `export SQUADRULES_LOCAL_ARTIFACT_DIR=\"<absolute>\"`\n- prerequisites create the directory; Reward Signal cleans it up\n- never write credentials or secrets to files\n\n### Resolving `project://` and `user://` URI hints\n\n| Scheme | Resolution | Example |\n|--------|-----------|--------|\n| `project://<rel>` | `<IDE project root>/<rel>` | `project://.local/squadrules/work` |\n| `user://<rel>` | `<$XDG_CONFIG_HOME or $HOME>/<rel>` | `user://.config/squadrules/work` |\n\nWhen your session spans multiple projects, prefer `user://` to avoid ambiguity.\n\n### Worktree placement (for task-isolation adapters)\n\nWhen an adapter requires a git worktree for isolation, the worktree path MUST\nbe **outside** every existing checkout:\n\n```\nREPO_ROOT=/home/user/repos/my-project\n# RIGHT: sibling of the repo\nWT=/home/user/repos/mcp.worktrees/<task-id>\n# WRONG: inside the checkout\n# WT=/home/user/repos/my-project/.mcp.worktrees/<task-id>\n```\n\n**Rule of thumb:** `$(dirname \"$REPO_ROOT\")/mcp.worktrees/<task-id>`\n\n### IDE worktree access limitations\n\nMost IDE file tools scope operations to the open project root. They **cannot**\nreach worktrees placed outside `$REPO_ROOT`. Use the terminal/shell tool for\nexternal worktrees, or open the worktree as a separate project window.\n\n## Composition Patterns\n\n**Multi-check compound command** — chain with `&&`, let the first failure stop.\n\n**Agent-readable shell status** — preserve the original exit status:\n```bash\n( set -o pipefail; <command> ); rc=$?; printf '\\nSQUADRULES_SHELL_EXIT=%s\\n' \"$rc\" >&2; exit \"$rc\"\n```\n\n**Freeze-then-verify** — step N writes checksum, step N+1 verifies before publish.\n\n**Write-then-grep** — subagent writes a verdict file, main agent checks line 1.\n\n**Phase-batch with critic** — batch related items, verify hard artifacts with\nshell, then delegate `critic-loop` for adversarial review from a `subagent`\ncontract. The review must not run on the thread that produced the work.\n\n**Chain-link via forward + slug** — layer N's contract requires `forward` with a\nspecific adapter slug. Use when the adapter exceeds 350 lines or needs\nmulti-path routing. Example:\nExample ```json\n{\"contract\":{\"type\":\"forward\",\"forward\":{\"target\":\"squadrules://adapter/implement-plan\"},\"required\":true}}\n```\n\n## Artifacts for Shell Contracts\n\nA gate that needs more than one short command belongs in a **script shipped with\nthe adapter**, not in the contract's `cmd`. An artifact keeps the contract\nreadable, makes the script independently versionable, and lets one dispatcher\nserve many gates.\n\n**Author it in this order** — an artifact attaches to an adapter that already\nexists:\n\n1. Draft the markdown. The contract stays one line and invokes the script by its\n artifact path. `interpreter` names the wrapper that runs that line, because\n `cmd` is program text for every interpreter:\n Example ```json\n {\"contract\":{\"type\":\"shell\",\"shell\":{\"cmd\":\"python3 \\\"$SQUADRULES_LOCAL_ARTIFACT_DIR/artifacts/my-gates.py\\\" --gate preflight\",\"interpreter\":\"bash\",\"timeout_seconds\":60},\"required\":true}}\n ```\n2. `train` the markdown.\n3. `train` the script with the `mime` matching its extension (`text/x-python`,\n `text/x-shellscript`, `text/javascript`), `artifact_name`, and that adapter's\n `adapter_uri`. Add `relative_path` only when the default\n `artifacts/<artifact_name>` is not the path you want; the identity header and\n slug rules are in the `train` description.\n4. Verify before you run it — **two** checks:\n - `activate` the adapter and check that `linked_artifacts[].relative_path`\n equals the path the contract invokes.\n - **Export check:** `export` the adapter (`format: skill_tree`, or\n `skill_zip` for the bundle) and confirm the script is in the bundle at\n that path, with no `artifact_stored_sha_mismatch` or\n `artifact_relative_path_invalid` in `diagnostics[]`.\n\n A mismatch surfaces only when the gate runs — by then it is the user's\n failed step, not your typo.\n\n**At execution time:** follow the `materialize` instruction carried by that\n`linked_artifacts[]` row — call the MCP `export` tool with the specified\narguments, write the returned content to the `out` path under\n`$SQUADRULES_LOCAL_ARTIFACT_DIR`, verify the digest, and set permissions.\n`forward` responses do not repeat the list, so materialize during the\nrun's first step. When the choice carries no artifact row, the agent obtains the\nscript with **`export`** (`format: skill_tree` or `format: skill_zip`) and takes\nit from `artifacts/`. State which route applies in the adapter text — a step that\ndoes not say how to get the file leaves the agent guessing.\n\n**One script, many gates:** `--gate <name>` on a single dispatcher replaces one\ninlined program per step. Change the gate once, not seven times.\n\nExample ```json\n{\"contract\":{\"type\":\"comment\",\"comment\":{\"min_length\":30},\"required\":true}}\n```\n\n## Reward Signal\n\nOnly reachable after all prior steps are solved.\n\nThe agent can now:\n1. pick the correct challenge type for each adapter step\n2. match challenge type to the step's mode\n3. choose the right interpreter (bash, python3, node)\n4. apply working-directory and security rules\n5. use forward contracts for chain links\n6. use subagent contracts for delegated work\n7. apply stronger verification patterns instead of weak comment checks\n8. ship a multi-step gate as an adapter artifact and keep its contract one line\n",
|
|
30
|
+
"critic-loop-guide": "---\nversion: \"5.14.3\"\nslug: critic-loop-guide\ntitle: Critic Loop Integration and Mutation Gate Guide\n---\n\n# Critic Loop Integration and Mutation Gate Guide\n\nDecision rules for integrating `critic-loop` into adapter protocols: when a\nsolution check (hard verification gate) is required versus when critic-loop\nreview is sufficient, and how to split and batch proofs so reversible work stays\ncheap while irreversible boundaries stay guarded.\n\n## Activation Patterns\n\n**Typically invoked by:** `author-adapter` during adapter drafting, and\nany adapter that includes review or validation phases.\n\n**Can be invoked directly when agent needs:**\n- \"when to add critic loop\" / \"should I use solution check\"\n- \"mutation gate rules\" / \"which actions need hard gates\"\n- \"critic loop vs solution check\" / \"irreversible action rules\"\n- \"add review step to protocol\" / \"where does critic go\"\n\n**Trigger pattern:** **critic loop** / **mutation gate** / **solution check** +\n(integration | when | rules | guide | which | where).\n\n**Must Never:**\n- Be used as an execution protocol.\n- Override the adapter author's judgment on review depth.\n- Recommend solution checks for reversible or local-only actions.\n\n**Must Always:**\n- Distinguish between quality review (critic-loop) and mutation blocking\n (solution checks).\n- Recommend looping critic-loop until PASS at every major phase boundary, fed the\n requirement list and bounded by an iteration ceiling.\n- Restrict solution checks to irreversibility boundaries, and batch reversible\n checkable steps into one strict-conjunction proof.\n\n**Good trigger examples:**\n- drafting a new adapter and deciding where to add review → load this\n- reviewing whether an adapter has the right solution checks → load this\n- \"does my MR step need a solution check?\" → load this\n\n**Bad trigger examples:**\n- \"run the critic loop\" → use `activate` to match `critic-loop`\n- \"create a new protocol\" → use `author-adapter`\n- \"which challenge type for this step?\" → use `challenge-type-guide`\n\n## Core Decision Rule\n\n**Critic-loop** is an adversarial review the calling protocol **loops until it\nreturns PASS** — not a one-shot step. It verifies claims, gathers evidence,\nsearches for contradictions, and checks the work against the original requirement\nlist. Use it for quality and truthfulness review, and whenever a step is\nnon-deterministic or has no objective proof. Run it **before** the work is handed\nto the next step, and before it is presented to the human.\n\n**Solution checks** are per-layer contract verification mechanisms (shell\ncommands, MCP tool calls). Use them ONLY where getting it wrong is expensive or\nimpossible to undo — **irreversible changes on remote systems** and the local\npreconditions that guard them (for example, being on a throwaway worktree/branch\nbefore you commit). Everything else is reversible: give the agent freedom and\nreview with critic-loop instead of adding a hoop.\n\n### What counts as an irreversible remote mutation\n\n| Action | Needs solution check? | Why |\n|--------|----------------------|-----|\n| Create/update merge request | Yes | Remote system state change |\n| Create/update Jira issue | Yes | Remote system state change |\n| Send email | Yes | Cannot unsend |\n| Send Teams message | Yes | Cannot unsend |\n| Create calendar invite | Yes | Sends notifications |\n| Deploy to production | Yes | Irreversible infrastructure change |\n| Delete remote resource | Yes | Irreversible |\n| Push to git remote | Yes | Remote state change |\n| Write/edit local file | No | Use critic-loop instead |\n| Run local tests | No | Read-only / local |\n| Analyze code | No | Read-only |\n| Generate report | No | Local artifact |\n| Read data from API | No | Read-only |\n| Compute / transform data | No | Local operation |\n\nExample ```json\n{\"contract\":{\"type\":\"comment\",\"comment\":{\"min_length\":30},\"required\":true}}\n```\n\n## Proof Splitting: Batch Checkable Steps Into One Proof\n\nSplit proofs by **reversibility cost**, not by step count:\n\n- **One proof per irreversibility boundary.** A boundary is where undoing the next\n part is expensive or impossible: commit to `main`, mutate the human's active\n worktree, `git push`, `gh pr create`, deploy, send.\n- **Batch reversible, checkable steps** and verify them together afterward with a\n single aggregate proof — fewer round-trips, same guarantee.\n- **The aggregate proof must be a strict conjunction** that re-verifies every\n sub-condition (`A && B && C && echo OK`):\n\nExample ```json\n{\"contract\":{\"type\":\"shell\",\"shell\":{\"cmd\":\"test -f \\\"$OUT_A\\\" && test -f \\\"$OUT_B\\\" && grep -q \\\"$EXPECTED\\\" \\\"$OUT_A\\\" && echo OK\",\"interpreter\":\"bash\",\"timeout_seconds\":10},\"required\":true}}\n```\n\n- **Never let an aggregate proof degrade to `echo \"done\"`.** A proof that asserts\n nothing is worse than no gate because it looks like one. If you cannot write a\n real conjunction, the step is non-deterministic → review it with critic-loop\n instead of faking a proof.\n\n### Guard the boundary before you cross it\n\nThe cheapest proof is the precondition that stops an irreversible mistake before\nit happens — for example, confirm you are on a throwaway worktree and branch (not\n`main`, not the human's active checkout) **before** making changes:\n\nExample ```json\n{\"contract\":{\"type\":\"shell\",\"shell\":{\"cmd\":\"test \\\"$(git rev-parse --abbrev-ref HEAD)\\\" != main && git rev-parse --git-common-dir | grep -q worktrees\",\"interpreter\":\"bash\",\"timeout_seconds\":5},\"required\":true}}\n```\n\n## How to Invoke Critic-Loop from an Adapter\n\nReach `critic-loop` at a phase boundary with a **`subagent` contract**, never a\n`forward` contract. A `forward` hop keeps the review on the thread that produced\nthe work: the same agent reads the critic's instructions, performs them, and\nwrites the verdict it is then gated on. The hop names the call the subagent must\nreally make, so it cannot substitute an improvised review:\n\n### After a planning phase\n\nExample ```json\n{\"contract\":{\"type\":\"subagent\",\"subagent\":{\"context\":\"Run the critic on the plan and return its actual report. Call the forward tool with uri squadrules://adapter/critic-loop, submit the work from $WORK_MANIFEST with the requirement list, and let the critic write $VERDICT_FILE. Do not review it yourself.\",\"mcp\":[{\"tool_name\":\"forward\",\"arguments\":{\"uri\":\"squadrules://adapter/critic-loop\"}}]},\"required\":true}}\n```\n\n### After an implementation phase\n\nUse the same contract shape. The subagent receives the calling protocol's\ncontext, drives `critic-loop` to its end in its own context, and returns only its\nreport — the tool transcript never re-enters the caller's reasoning.\n\n`forward` + slug stays correct for **chain continuation** — handing work to the\nnext stage of the same effort, or to a reusable sub-adapter that is not auditing\nthe caller. The test is not \"does it link to an adapter\" but \"is the linked\nadapter the caller's auditor\". Separation is the point: a review the audited agent\nruns on itself restates its work instead of checking it.\n\nA host with no subagent facility cannot satisfy this hop. Report that as a\nblocker; do not fall back to reviewing your own work.\n\n### What to submit for review\n\nThe submission is the **work itself**, not a summary of it. Pass `work` with a\n`kind`, an `items` list, and the absolute `root` the items resolve against:\n\n| `kind` | `items` contain | Resolved by | Typical work |\n|---|---|---|---|\n| `file_set` | paths (absolute, or relative to `root`) | read each file | docs, generated code, configs |\n| `links` | URLs, `squadrules://` resource URIs | fetch each one | published pages, external references |\n| `git_diff` | `base..head` refs, or empty for the working tree | `git diff` | an unpushed implementation |\n| `pr` | PR numbers or URLs | `gh pr view` + `gh pr diff` | a reviewable pull request |\n| `command_output` | commands to run from `root` | run and capture | migrations, builds, data pulls |\n| `inline` | the text itself | read the manifest | a plan, a decision, a message draft |\n\nRecord `work` in the handoff file pointed to by `$WORK_MANIFEST`, as flat keys —\n`kind:`, `root:`, then `items:` with one item per line — so the precondition\nstays a machine-checkable file test instead of prose:\n\nExample ```json\n{\"contract\":{\"type\":\"shell\",\"shell\":{\"cmd\":\"test -f \\\"${WORK_MANIFEST:-}\\\" || test -f \\\"${INPUT_FILE:-}\\\"\",\"interpreter\":\"bash\",\"timeout_seconds\":3},\"required\":true}}\n```\n\nAnything that cannot be resolved is `verification_blocked` — an item the critic\ncould not read is never treated as an item that passed. `input_file` still works\nand means a one-item `file_set`; prefer `work_manifest` for anything that is not\na single document. A `pr` or `git_diff` submission is judged on the diff and the\ntests it touches, not on the description written next to it.\n\n### Feed it the requirements, then loop with a ceiling\n\nPass the original requirement list in the forward context. A critic that sees only\nthe output can check internal consistency but **cannot detect an omitted\nrequirement** — omission leaves no trace in the artifact — so \"no requirements\nlost\" is only enforceable if the critic is given the list and asserts coverage\nitem by item. Then loop: on FAIL, fix, increment `iteration`, and re-invoke until\nPASS or until `max_iterations` is reached. The ceiling is a hard stop that\nsurfaces the unresolved findings; it prevents a weak agent from thrashing forever.\n\n### Verdict handoff pattern\n\nCritic-loop writes a verdict file in the delegated run. The calling adapter reads\nit:\n\n1. Critic-loop writes `$VERDICT_FILE` with `PASS`/`FAIL` on line 1.\n2. Calling adapter's next layer reads the verdict file.\n3. If `FAIL` → **hard stop**: do NOT proceed to reward, do NOT ask the user\n for approval, do NOT continue to the next phase. Address findings first.\n4. If `PASS` → the adapter continues to the next phase.\n\n**FAIL is a hard stop, not an escalation trigger.** A FAIL verdict means the\nwork is not ready. Asking the user \"should I proceed?\" after FAIL bypasses the\nreview. The correct action is to fix the findings and re-invoke critic-loop.\n\n### FAIL gate contract (required after every critic-loop invocation)\n\nEvery adapter that invokes critic-loop **must** include a shell contract that\nfails when the verdict is not PASS. This is the mechanical guard that prevents\nweaker agents from proceeding after FAIL:\n\nExample ```json\n{\"contract\":{\"type\":\"shell\",\"shell\":{\"cmd\":\"head -1 \\\"$VERDICT_FILE\\\" | grep -qi '^PASS$'\",\"interpreter\":\"bash\",\"timeout_seconds\":5},\"required\":true}}\n```\n\nIf the critic wrote FAIL, this shell command exits non-zero. The server rejects\nthe solution and the agent cannot advance to the next layer. Protocol wording\nalone does not stop determined agents; this contract does.\n\n## Train/Tune Evidence Requirement\n\n`train` and `tune` enforce critic-loop PASS at the tool level:\n\n- **Adapter (markdown) `train`** requires `review_evidence`: verdict_file path,\n exit_code (must be 0), and stdout (line 1 must be PASS). Without it, the\n server rejects the store with `REVIEW_EVIDENCE_REQUIRED`.\n- **`tune` with content** requires the same `review_evidence`. Space-only moves\n skip this check.\n- **Artifact trains** (non-markdown mime) skip the evidence check.\n\nThis is the tool-level enforcement of the FAIL gate. Even if an agent bypasses\nthe adapter flow and calls `train` directly, the server rejects the store\nwithout PASS evidence. The agent must run critic-loop, capture the verdict\nfile, and pass it as `review_evidence`.\n\n## Mutation Gate Pattern\n\nUnder the AI-ownership model, agents execute autonomously — irreversible remote\nmutations are **not** gated by a human confirmation prompt. Gate them with\nobjective, machine-checkable contracts instead:\n\n### Pre-mutation readiness (objective, no human prompt)\n\nAssert the preconditions with a shell or forward contract so the action only runs from a\nvalid state — never with a `user_input` \"are you sure?\" prompt:\n\nExample ```json\n{\"contract\":{\"type\":\"shell\",\"shell\":{\"cmd\":\"test -n \\\"$TARGET_REPO\\\" && test -n \\\"$TARGET_BRANCH\\\"\",\"interpreter\":\"bash\",\"timeout_seconds\":5},\"required\":true}}\n```\n\n### Post-mutation verification (objective)\n\nConfirm the mutation actually took effect by reading the remote state back.\nUse a `subagent` contract when the verification requires multi-step reasoning\nor tool orchestration beyond a single shell command:\n\nExample ```json\n{\"contract\":{\"type\":\"subagent\",\"subagent\":{\"context\":\"Verify the remote mutation took effect: read back the created/updated resource and confirm its state matches the intended outcome.\"},\"required\":true}}\n```\n\nThe guarantee comes from critic-loop (truth of intent) plus these objective\npre/post checks — not from asking a human to approve. Do not add `user_input`\nconfirmation gates for remote mutations.\n\n## Critic-Loop Placement Rules\n\n1. **Loop critic-loop until PASS at every major phase boundary** — after planning,\n after implementation, after validation — feeding it the requirement list and\n bounding it with an iteration ceiling.\n2. **Invoke the critic from a separate context** — a `subagent` contract, never a\n `forward` contract on the thread that produced the work.\n3. **Do NOT add critic-loop between every layer** — it is a phase-level review,\n not a step-level check.\n4. **Put one objective proof at each irreversibility boundary** — remote mutation\n or the local precondition that guards it: pre-mutation readiness +\n post-mutation verification, never a human confirmation prompt.\n5. **Batch reversible, checkable steps into one aggregate strict-conjunction\n proof** instead of one proof per step; never let it degrade to `echo \"done\"`.\n6. **Never replace a boundary proof with critic-loop** — critic-loop reviews truth\n after the fact; it does not block an irreversible step.\n7. **Never add a proof for purely local, reversible operations** — critic-loop\n provides sufficient review.\n8. **Never gate what you cannot observe** — if no shell command can see the\n outcome, state it as an instruction with a completion criterion instead of\n inventing a command that prints `ok`.\n\n## Adapter Authoring Checklist\n\nWhen drafting a new adapter, apply this checklist:\n\n1. Identify all phase boundaries in the adapter flow.\n2. Add a `subagent` critic hop at each boundary — never a `forward` hop to\n `critic-loop`.\n3. Identify all steps that perform irreversible remote mutations.\n4. Add objective solution checks (pre-mutation readiness + post-action\n verification) for each — no `user_input` human-confirmation gate.\n5. Verify that no solution checks exist for purely local operations.\n6. Verify that the critic-loop verdict handoff pattern is present.\n7. Verify that a FAIL gate shell contract follows every critic-loop invocation.\n8. Verify that `train`/`tune` calls include `review_evidence` from the critic.\n9. Ensure the adapter's Reward Signal describes what the critic protects, and\n states what the verdict does **not** prove.\n\nExample ```json\n{\"contract\":{\"type\":\"comment\",\"comment\":{\"min_length\":80},\"required\":true}}\n```\n\n## Reward Signal\n\nOnly reachable after all prior steps are solved.\n\nThe agent can now:\n1. Decide when to use critic-loop versus solution checks\n2. Identify irreversible remote mutations that need hard gates\n3. Invoke critic-loop from a delegated subagent at the correct phase boundaries\n4. Apply the mutation gate pattern for remote-system actions\n5. Avoid unnecessary solution checks for local or read-only operations\n",
|
|
31
|
+
"critic-loop": "---\nversion: \"5.14.3\"\nslug: critic-loop\ntitle: Critic Loop\n---\n\n\n\n# Critic Loop\n\nBounded adversarial investigator that the calling protocol **loops until it\nreturns PASS** — not a one-shot review. Receives a work submission (files,\nlinks, a git diff, a pull request, command output, or inline text), the\noriginal requirement list, and the calling protocol's invariants, then\nindependently verifies the submitted work by extracting claims, gathering\nevidence, searching for contradictions, and checking requirement-by-requirement\ncoverage. A FAIL sends the caller back to fix and re-invoke; the loop is bounded\nby an explicit iteration ceiling (see Verdict).\n\n## Activation Patterns\n\n**Typically invoked by:** another protocol at the end of a plan, implement,\nvalidation, or review phase, reached from a `subagent` contract whose\n`subagent.mcp` names `forward` with the stored adapter URI\n`squadrules://adapter/critic-loop`. The critic runs in the delegated context, not\non the audited agent's thread — that separation is why the type is `subagent` and\nnot `forward`.\n\n**Can be invoked directly when agent needs:**\n- \"review phase output\" / \"verify plan\" / \"audit implementation\"\n- \"adversarial review\" / \"critic review\"\n\n**Trigger pattern:** **review** / **verify** / **audit** / **critic** +\n(phase / plan / implementation / output).\n\n**Must Never:**\n- Modify any submitted item or any file other than the verdict path.\n- Trust the executor's assertions without independent evidence.\n- Classify a claim as `verified` based only on absence of contradiction.\n- Keep investigating after a precondition failure that blocks verification.\n- Re-delegate this review to another subagent: you are the separation the caller\n asked for, and nesting a second layer of delegation hides the verdict's author.\n\n**Must Always:**\n- Extract claims before investigating.\n- Verify in-scope claims first.\n- Search for contradictory evidence, not only confirming evidence.\n- Check every item in the supplied requirement list for coverage; a missing\n requirement is a FAIL even when the output is internally consistent.\n- Include confidence in every verdict and failure class in every FAIL verdict.\n- Write `$VERDICT_FILE` on **every** path, including an early-abort, so the\n caller's gate always reads a real verdict instead of failing on a missing file.\n- Preserve the boundary between execution and review.\n\n**Good trigger examples:**\n- implement protocol fires this after planning → run this protocol\n- compose protocol fires this after output generation → run this protocol\n\n**Bad trigger examples:**\n- \"Create a new protocol\" → use `author-adapter`\n- \"Implement a feature\" → use an execution protocol, not this one\n\n## Artifact Contract\n\nThis protocol receives:\n\n```text\n{\n work: {\n kind: 'file_set' | 'links' | 'git_diff' | 'pr' | 'command_output' | 'inline',\n items: string[], // paths | URLs | 'base..head' refs | PR URL/number | commands | text\n root: string // absolute cwd used to resolve relative paths, refs and commands\n },\n work_manifest: string, // absolute path to the handoff file recording `work`\n input_file: string, // accepted alias: a one-item work.kind='file_set'\n calling_protocol_slug: string,\n verification_target: string,\n requirements: string[], // original intent / requirement list to check coverage against\n context: {\n operation: string,\n verdict_file: string, // absolute path where the verdict will be written\n iteration: number, // 1-based loop pass; caller increments after each FAIL\n max_iterations: number // hard ceiling; exceeding it is a terminal FAIL\n }\n}\n```\n\nThe submission is the **work itself**, not an essay about it. Write `work` to\n`$WORK_MANIFEST` as flat keys so the handoff stays machine-checkable:\n`kind:`, `root:`, then `items:` with one item per line. Callers that still pass\nonly `input_file` are handled as `kind: file_set` with that single path; the\nreview rules do not change, only the scope of what is submitted.\n\nThis protocol produces:\n\n```text\n{\n verdict: \"PASS\" | \"FAIL\",\n confidence: \"High\" | \"Medium\" | \"Low\",\n failure_class: string, // incorrect_claim | verification_blocked | requirement_gap | iteration_ceiling\n uncovered_requirements: string[],// requirement items lacking positive evidence (empty on PASS)\n verdict_file: \"{context.verdict_file}\"\n}\n```\n\n## Precondition Check\n\nVerify foundational preconditions before deep investigation. Early-abort if any\nare broken.\n\n**Input:** `$WORK_MANIFEST` (or the older-spelling `$INPUT_FILE`), calling protocol slug, context\n\n**Actions:**\n1. Verify a submission handoff is present: `$WORK_MANIFEST`, or `$INPUT_FILE`\n when the caller passed no manifest.\n2. Verify the verdict output path is writable (parent directory exists).\n3. Load the calling protocol's Must Never / Must Always sections if possible.\n4. Verify the target state is available for review.\n5. Verify required tools are available for the submission's `kind` (a `pr`\n submission with no `gh` on the host is `verification_blocked`, not skipped).\n\n**On early-abort:**\n- verdict = `FAIL`\n- failure class = `verification_blocked`\n- confidence = `Low`\n- write focused diagnostics\n- write `$VERDICT_FILE` with those diagnostics, then skip all later steps\n\n**Output:** verified preconditions or early-abort diagnostics\n\n## Resolve Submission\n\nTurn the submission into the material under review. What cannot be resolved is\nnever guessed at.\n\n**Input:** `work` recorded in `$WORK_MANIFEST` (or the older-spelling `$INPUT_FILE`),\n`work.root`\n\n**Actions:**\n1. Read `kind`, `root`, `items`. An unknown `kind`, an empty `items` list, or a\n malformed manifest is `verification_blocked`.\n2. Resolve every item by kind, always from `work.root`:\n - `file_set` — read each path; relative paths resolve against `root`, and a\n missing path is `verification_blocked`.\n - `links` — fetch each URL; a URL that cannot be fetched is\n `verification_blocked`, not an `unverifiable` claim.\n - `git_diff` — `git -C \"$root\" diff <base>..<head>`, or the working tree when\n no range is given; no `git`, no repository, or a bad ref is\n `verification_blocked`.\n - `pr` — `gh pr view` plus `gh pr diff` for the number or URL; a missing\n `gh`, an expired login, or an unreachable host is `verification_blocked`.\n - `command_output` — run each command from `root` and capture stdout and\n stderr as the material.\n - `inline` — the text recorded in the manifest is the material.\n3. Record the resolved inventory before auditing: `kind`, item count, per-item\n status (`resolved` or `blocked`), and where each item's evidence lives.\n4. A `pr` or `git_diff` submission is reviewed as a diff: claims are checked\n against the changed lines and the tests they touch, never against the\n description written alongside them.\n\n**Output:** resolved work inventory for the audit\n\n## Audit\n\nPerform bounded adversarial review of the target against the resolved work\nsubmission and invariants.\n\n**Input:** resolved work inventory, invariants, verification target, requirement list, context\n\n**Actions:**\n\n**Step 1 — Extract claims**\nExtract every verifiable claim that matters operationally:\n- workflows, commands, tool calls\n- configuration and environment variable claims\n- architecture claims that imply behaviour\n- guarantees and constraints\n- security, auth, and permission claims\n\n**Step 2 — Investigate with scope discipline**\n1. verify all in-scope claims first\n2. review high-risk claims with maximum depth\n3. expand beyond scope only when contradiction signals, dependencies, or\n high-risk impact require it\n4. continue reviewing all in-scope claims even after a normal FAIL condition is met;\n only a precondition failure stops the audit early\n\n**High-risk areas:** setup steps, CLI commands, configuration keys, authentication,\ndeployment, external publishing, destructive operations.\n\n**Step 3 — Gather evidence using the hierarchy**\n\n| Priority | Evidence source |\n|---|---|\n| 1 | source code, config files, schemas, route definitions |\n| 2 | direct runtime verification |\n| 3 | tests |\n| 4 | MCP-queried system state |\n| 5 | external docs, web pages, linked references |\n| 6 | conversational assumption or indirect inference |\n\n**Rules:** higher-priority evidence overrides lower; priority 5–6 alone is not\nenough for `verified`; a submitted link or PR description is priority 5.\n\n**Step 4 — Produce claim verdicts**\nFor each claim: CLAIM, EVIDENCE, EVIDENCE PRIORITY, VERDICT\n(`verified` / `partially_verified` / `unverifiable` / `incorrect`).\nA claim must not be marked `verified` without positive supporting evidence.\n\n**Step 5 — Review the phase boundary**\nCheck whether the calling adapter preserved the right mode boundary.\n\n**Step 6 — Check requirement coverage**\nFor every item in `requirements`, confirm coverage with positive evidence.\nAny `missing` item — or any `partial` high-risk item — forces FAIL with\n`failure_class: requirement_gap`.\n\n**Output:** structured audit findings for the verdict step\n\n## Verdict\n\nTurn the audit into a final PASS / FAIL result.\n\n**Input:** audit findings and verdict file path from context (use it as\n`$VERDICT_FILE`)\n\n**Actions:**\n1. Fail if any critical claim is incorrect.\n2. Fail if verification was blocked.\n3. Fail if the evidence base is too weak for high-risk claims.\n4. Fail if any requirement is `missing`, or a high-risk requirement is only\n `partial` (`failure_class: requirement_gap`); list the uncovered items.\n5. Fail terminally if `context.iteration` exceeds `context.max_iterations`\n (`failure_class: iteration_ceiling`) so the loop stops instead of thrashing.\n6. Otherwise, pass with the appropriate confidence.\n7. Write `$VERDICT_FILE` so line 1 is `PASS` or `FAIL`,\n line 2 is `High`, `Medium`, or `Low`, and the remaining lines summarise key\n findings and any uncovered requirements.\n\n**Verdict contract (calling adapter must obey):**\n- Line 1 is `PASS` → the loop is satisfied; the calling adapter may continue.\n- Line 1 is `FAIL` → the calling adapter **MUST NOT** proceed to reward, **MUST\n NOT** ask the user for approval, and **MUST NOT** continue. It must address the\n findings, increment `context.iteration`, and re-invoke critic-loop from a fresh\n delegated subagent — never on the thread that produced the work under review.\n- `failure_class: iteration_ceiling` → stop looping and surface the unresolved\n findings; never silently pass. The ceiling bounds the loop so a weak agent\n cannot thrash forever.\n\n**Output:** final verdict file\n\n```json\n{\"contract\":{\"type\":\"shell\",\"shell\":{\"cmd\":\"test -f \\\"$VERDICT_FILE\\\" && head -1 \\\"$VERDICT_FILE\\\" | grep -qiE '^(PASS|FAIL)$' && sed -n '2p' \\\"$VERDICT_FILE\\\" | grep -qiE '^(High|Medium|Low)$'\",\"interpreter\":\"bash\",\"timeout_seconds\":5},\"required\":true}}\n```\n\n## Reward Signal\n\nOnly reachable after all prior steps are solved.\n\nThe phase output has been independently challenged and looped until satisfied. The\nresulting verdict is more truthful because it is based on extracted claims,\nexplicit evidence, contradiction search, requirement-by-requirement coverage, and\na clean boundary between execution and review.\n\nThe single contract on this adapter is the verdict-file syntax gate: it is the\none artifact the critic produces, and everything before it is the critic's own\nreasoning. The precondition, submission-resolution, and audit steps carry no\ncontracts because a contract gates an outcome, not a step, and a critic that\ngates itself inward re-delegates work it was delegated to perform.\n\nThat gate asserts the verdict file's **shape**, not the review's soundness: a\n`PASS` is this critic's judgment, and the separation that makes it worth\nsomething is that a critic was run apart from the executor. The caller's own\n`PASS` gate proves only that a file was written saying `PASS`.\n",
|
|
32
|
+
"protocol-linking-guide": "---\nversion: \"5.14.3\"\nslug: protocol-linking-guide\ntitle: Adapter Linking Guide\n---\n\n# Adapter Linking Guide\n\nDecision rules for structuring adapter relationships: layers vs chains,\n`activate` vs `forward` + slug, chain-root collapsing, and MCP argument\nvalidation for deterministic cross-adapter linking.\n\n## Activation Patterns\n\n**Typically invoked by:** `author-adapter` and `critic-loop`.\n\n**Can be invoked directly when agent needs:**\n- \"layers vs chains\" / \"when to split into multiple adapters\"\n- \"how to link adapters\" / \"cross-adapter linking\"\n- \"activate vs forward\" / \"when to use forward with slug\"\n- \"chain-root collapsing\" / \"how chain_root works\"\n\n**Trigger pattern:** **layers** / **chains** / **linking** / **forward** +\n(slug | adapter | workflow).\n\n**Must Never:**\n- Be used as an execution adapter.\n- Recommend chaining when layers suffice.\n\n**Must Always:**\n- Be consulted before splitting an adapter into multiple adapters.\n- Be consulted before adding `forward` calls or `chain_root` frontmatter.\n\n**Good trigger examples:**\n- \"my adapter is 400 lines, should I split?\" → load this\n- \"how do I link adapter A to adapter B?\" → load this\n- \"what is chain_root?\" → load this\n\n**Bad trigger examples:**\n- \"which challenge type for this step?\" → use `challenge-type-guide`\n- \"create a new adapter\" → use `author-adapter`\n\n## Layers vs Chains\n\n**Layers** (H2 steps within one adapter) are the preferred unit of work. Use\nlayers when all steps fit in one adapter under 350 lines and serve a single\ncohesive concern.\n\n**Chain via `forward` + slug** — use only when:\n- the adapter exceeds 350 lines\n- weaker models cannot follow the full adapter in one pass\n- runtime routing to different adapters is needed (Router pattern)\n- a step is reusable across multiple parent adapters (e.g. a shared\n deployment-check adapter)\n\nA review is **not** a chain link: reaching `critic-loop` to audit the current\nrun's work is a `subagent` hop, because a `forward` hop leaves the critic on the\nthread that made the mistakes.\n\nChaining is NOT a replacement for layers. A 6-step adapter that fits in 350\nlines should stay as one adapter with 6 H2 layers.\n\n## `activate` vs `forward` + slug\n\n| Situation | Use |\n|---|---|\n| Initial user-intent resolution | `activate` |\n| Target adapter is known at authoring time | `forward` + slug |\n| Target depends on runtime classification the current adapter cannot resolve | `activate` |\n| Linking to the next adapter in a chain | `forward` + slug |\n| Reusable sub-adapter invoked by multiple parents | `forward` + slug |\n\nNever call `activate` just to get a slug you already know — it wastes a\nround-trip and introduces non-determinism.\n\n## Chaining Back and Forward\n\nWhen a family of adapters has a root conductor and smaller domain extensions,\ndocument both directions of chaining.\n\n### Chaining back with `chain_root`\n\nExtension adapters should include `chain_root` frontmatter and a prerequisite\nclause:\n\n**Prerequisite:** Start from `<root-adapter-slug>` unless the caller already\nprovided a mission brief, safety gates, authorization boundary, and evidence\nrequirements.\n\nThis protects activation entry points. If a user or weak agent activates a\nmid-chain extension directly, the extension can collapse back to the root unless\nit already received the required parent context.\n\n### Chaining forward with `forward`\n\n`chain_root` does not replace explicit `forward` calls inside the chain.\n\nWhen the next adapter is known at authoring time or after deterministic runtime\nclassification, use `forward` with the target slug. Do not call `activate` just\nto rediscover a slug already known by the current adapter.\n\nForwarded adapters should receive: current mission brief, safety gates,\nauthorization boundary, evidence requirements, user constraints, and reason for\nforwarding.\n\nUse `activate` only when the next adapter must be discovered from an ambiguous\nruntime need.\n\n### Multi-layer conductors and extension URIs\n\nWhen executing **`forward`** inside a **multi-layer** adapter (for example a root\nconductor), each continuation follows **`next_call`** for the **same**\n`execution_id` until the last layer directs **`reward`**. A layer that mentions\nanother adapter URI only as routing guidance does **not** cause the server to\nswitch executions.\n\nTo run an extension adapter, call **`forward`** with\n`squadrules://adapter/<slug>` as a **new** first call (adapter URI; omit\n`solution`). That starts a **separate** execution with its own layers.\n\n## System adapters vs user adapters\n\nBoth system and user-authored adapters chain using slugs in `next_action`:\n\n```text\ncall forward with squadrules://adapter/implement-terraform ...\n```\n\nA review hop is not a chain link — reach `critic-loop` from a `subagent` contract\nwhose `subagent.mcp` names `forward`.\n\nSlugs are globally unique (enforced by `train`), so resolution is\ndeterministic — no scoring, no ambiguity.\n\n## Forward-link contracts for chain links\n\nAll `forward` contracts MUST set `forward.target` to the target adapter slug:\n\nExample ```json\n{\"contract\":{\"type\":\"forward\",\"forward\":{\"target\":\"squadrules://adapter/code-review-policy\"},\"required\":true}}\n```\n\nThe server validates that the submitted `evidence.target` equals the contract's\n`forward.target`. This proves the agent called `forward` with the correct slug,\nnot just any `forward` call.\n\nA `forward` contract without `forward.target` is **not valid** — every forward\ncontract must specify its target adapter.\n\n## Chain-root collapsing\n\nWhen a chain has multiple adapters, `activate` might match a mid-chain adapter\ndirectly. Without protection, the agent would start at the wrong step, missing\nprerequisite context gathered by earlier steps.\n\n**`chain_root` frontmatter field** solves this at the server level. Add it to\nevery mid-chain adapter:\n\n```yaml\n---\nslug: implement-plan\nversion: 1.0.0\nchain_root: implement\n---\n```\n\n**Server behaviour:** When `activate` returns a match that has `chain_root`,\nthe server resolves the slug to the root adapter's URI and replaces the\nchoice's `uri` and `next_action` to point there. Multiple mid-chain matches\nfrom the same chain are deduplicated to a single entry.\n\n**Defense in depth:** Each mid-chain adapter should include a **Prerequisites**\nparagraph in its Activation Patterns listing inputs required from earlier steps\nand directing the agent to start from the chain root if those inputs are missing.\n\n**Rules:**\n- The chain root adapter must NOT have `chain_root` in its frontmatter.\n- `chain_root` must refer to an existing slug (the chain entry point).\n- `forward` calls within a chain are unaffected — `chain_root` only changes\n `activate` output routing.\n\n## Personal vs System Adapter Linking\n\n| Adapter type | Can `forward` to | Can be `forward`'d from |\n|---|---|---|\n| System adapter (bundled) | Other system adapters (slug guaranteed to exist) | System or personal adapters |\n| Personal adapter (MCP database) | **Nothing** — must be self-contained | Only via `activate` (runtime discovery) |\n\nPersonal adapters use `subagent` or `comment` contracts to describe what the\nagent should do next, not `forward` contracts to other personal adapters.\nA personal adapter that chains to `squadrules://adapter/some-personal-slug`\nwill fail at runtime when that slug does not exist in the caller's MCP database.\n\nExample ```json\n{\"contract\":{\"type\":\"comment\",\"comment\":{\"min_length\":30},\"required\":true}}\n```\n\n## Reward Signal\n\nOnly reachable after all prior steps are solved.\n\nThe agent can now:\n1. decide when to use layers vs chains\n2. choose `activate` vs `forward` + slug correctly\n3. use slug-based linking for all adapters (system and user)\n4. write valid forward contracts with a target adapter URI\n5. implement `chain_root` collapsing with defense-in-depth safeguards\n6. document chaining back (`chain_root` + prerequisites) and chaining forward\n (`forward` with known slugs) for root + extension families\n",
|
|
33
|
+
"refine-search": "---\nversion: \"5.14.3\"\nslug: refine-search\ntitle: Get help refining your search\n---\n\n# Get help refining your search\n\n**You are an AI agent.** You ran `activate` and got no solid match, or only weak\n/ ambiguous matches. This adapter helps you turn a vague request into a better\nquery so the next `activate` can find the right adapter.\n\nSQUADRULES principle: before acting, understand the user better. The goal is not\nto repeat the failed phrase with minor edits. The goal is to recover the user's\nreal intent.\n\n## Activation Patterns\n\n**Run this adapter when:**\n- `activate` returned no match.\n- `activate` returned only weak choices.\n- The response included a `refine` choice.\n\n**Trigger pattern:** after `activate` when no strong match exists.\n\n**Must Never:**\n- Run when a strong match already exists.\n- Loop refinement endlessly.\n\n**Must Always:**\n- Infer the real goal, context, and missing constraints from the user's request.\n- Build a more specific query than the one that failed.\n- Run at most once per user request; if the second activation still fails, stop\n and offer clarification or adapter creation.\n\n**Good trigger examples:**\n- activate returned only \"refine\" / weak matches → run this adapter\n- \"No adapter matched 'do the thing'\" → run this adapter\n\n**Bad trigger examples:**\n- activate returned a strong match → use that match instead\n- user asked \"what adapters exist?\" → use `activate` / `spaces`, not this\n\n## Extract User Intent\n\nFrom the user's original message, identify:\n- the real goal\n- relevant context\n- missing constraints\n- likely wording that would help SQUADRULES find the right adapter\n\nWrite your analysis, then construct one refined query with 3–8 specific words.\nDo not reuse the vague phrase that already failed.\n\nCall `activate` with the refined query as your next action:\n- **Strong match (score >= 0.5):** pick that choice and `forward`.\n- **Weak matches only:** ask the user to clarify or offer the create path.\n\nDo not loop more than once.\n\n```json\n{\"contract\":{\"type\":\"comment\",\"comment\":{\"min_length\":60},\"required\":true}}\n```\n\n## Reward Signal\n\nOnly reachable after all prior steps are solved.\n\nThe agent has converted a failed literal search into a more truthful,\nuser-aligned activation attempt.\n"
|
|
34
34
|
}
|
|
35
35
|
};
|
|
36
36
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{g as e,y as t}from"./vendor-WsU_UJPA.js";import{t as n}from"./react-BvB9BS1T.js";import{n as r,r as i,t as a}from"./index-
|
|
1
|
+
import{g as e,y as t}from"./vendor-WsU_UJPA.js";import{t as n}from"./react-BvB9BS1T.js";import{n as r,r as i,t as a}from"./index-Cgf4n_oz.js";import{t as o}from"./api-BgTb-tmJ.js";async function s(){let e=await o(`/api/me`);if(!e.ok){let t=await e.json().catch(()=>({})),n=Error(t.message??e.statusText);throw n.statusCode=e.status,n}return e.json()}function c(){return e({queryKey:[`me`],queryFn:s,retry:!1})}var l=n(),u={light:`account.themeOptionLight`,dark:`account.themeOptionDark`};function d(e){if(e.name&&e.name.trim().length>0)return e.name;let t=[e.given_name,e.family_name].filter(e=>typeof e==`string`&&e.trim().length>0);return t.length>0?t.join(` `):e.preferred_username&&e.preferred_username.length>0?e.preferred_username:e.sub}function f(){let{t:e}=t(),{data:n,isLoading:o,isError:s}=c(),{preference:f,setPreference:p}=i();return o?(0,l.jsx)(`p`,{className:`text-[var(--color-text-muted)]`,children:e(`account.loading`)}):s||!n?(0,l.jsxs)(`div`,{children:[(0,l.jsx)(`h1`,{className:`text-[var(--color-text-heading)] text-2xl font-semibold mb-4`,children:e(`account.title`)}),(0,l.jsx)(`p`,{className:`text-[var(--color-text-muted)]`,children:e(`account.notSignedIn`)}),(0,l.jsx)(`a`,{href:`/auth/callback`,className:`mt-4 min-h-[44px] min-w-[44px] inline-flex items-center justify-center px-4 py-2 rounded-[var(--radius-md)] font-medium bg-[var(--color-primary)] text-white no-underline hover:bg-[var(--color-primary-hover)] focus-visible:outline focus-visible:outline-2 focus-visible:outline-[var(--color-focus-ring)] focus-visible:outline-offset-2`,children:e(`account.signIn`)})]}):(0,l.jsxs)(`div`,{children:[(0,l.jsx)(`h1`,{className:`text-[var(--color-text-heading)] text-2xl font-semibold mb-6`,children:e(`account.title`)}),(0,l.jsx)(`p`,{className:`text-[var(--color-text-muted)] mb-6`,children:e(`account.intro`)}),(0,l.jsxs)(`div`,{className:`rounded-[var(--radius-md)] border border-[var(--color-border)] bg-[var(--color-surface-elevated)] p-6`,children:[(0,l.jsxs)(`div`,{className:`mb-6 rounded-[var(--radius-md)] border border-[var(--color-border)] bg-[var(--color-surface)] p-4`,children:[(0,l.jsx)(`h2`,{className:`mb-1 text-base font-semibold text-[var(--color-text-heading)]`,children:e(`account.themeTitle`)}),(0,l.jsx)(`p`,{className:`mb-3 text-sm text-[var(--color-text-muted)]`,children:e(`account.themeDescription`)}),(0,l.jsx)(`label`,{htmlFor:`account-theme-preference`,className:`sr-only`,children:e(`account.themePreferenceLabel`)}),(0,l.jsxs)(`select`,{id:`account-theme-preference`,value:f,onChange:e=>{let t=e.target.value;r(t)&&p(t)},className:`min-h-[44px] w-full max-w-xs rounded-[var(--radius-md)] border border-[var(--color-border)] bg-[var(--color-surface)] px-3 py-2 text-[var(--color-text)] focus-visible:outline focus-visible:outline-2 focus-visible:outline-[var(--color-focus-ring)] focus-visible:outline-offset-2`,children:[(0,l.jsx)(`option`,{value:`system`,children:e(`account.themeOptionSystem`)}),a.map(t=>(0,l.jsx)(`option`,{value:t,children:e(u[t])},t))]})]}),(0,l.jsxs)(`div`,{className:`mb-4`,children:[(0,l.jsx)(`span`,{className:`block text-xs uppercase tracking-wider text-[var(--color-text-muted)] mb-1`,children:e(`account.name`)}),(0,l.jsx)(`span`,{className:`text-[var(--color-text-heading)]`,children:d(n)})]}),n.preferred_username&&n.preferred_username!==d(n)&&(0,l.jsxs)(`div`,{className:`mb-4`,children:[(0,l.jsx)(`span`,{className:`block text-xs uppercase tracking-wider text-[var(--color-text-muted)] mb-1`,children:e(`account.username`)}),(0,l.jsx)(`span`,{className:`text-[var(--color-text-heading)]`,children:n.preferred_username})]}),n.email&&(0,l.jsxs)(`div`,{className:`mb-4`,children:[(0,l.jsx)(`span`,{className:`block text-xs uppercase tracking-wider text-[var(--color-text-muted)] mb-1`,children:e(`account.email`)}),(0,l.jsxs)(`span`,{className:`text-[var(--color-text-heading)]`,children:[n.email,n.email_verified===!0?` (${e(`account.emailVerified`)})`:``]})]}),(0,l.jsxs)(`div`,{className:`mb-4`,children:[(0,l.jsx)(`span`,{className:`block text-xs uppercase tracking-wider text-[var(--color-text-muted)] mb-1`,children:e(`account.accountType`)}),(0,l.jsx)(`span`,{className:`text-[var(--color-text-heading)]`,children:n.account_label})]}),(0,l.jsxs)(`div`,{className:`mb-4`,children:[(0,l.jsx)(`span`,{className:`block text-xs uppercase tracking-wider text-[var(--color-text-muted)] mb-1`,children:e(`account.realm`)}),(0,l.jsx)(`span`,{className:`text-[var(--color-text-heading)]`,children:n.realm})]}),n.identity_provider&&(0,l.jsxs)(`div`,{className:`mb-4`,children:[(0,l.jsx)(`span`,{className:`block text-xs uppercase tracking-wider text-[var(--color-text-muted)] mb-1`,children:e(`account.identityProvider`)}),(0,l.jsx)(`span`,{className:`text-[var(--color-text-heading)]`,children:n.identity_provider})]}),n.groups.length>0&&(0,l.jsxs)(`div`,{className:`mb-4`,children:[(0,l.jsx)(`span`,{className:`block text-xs uppercase tracking-wider text-[var(--color-text-muted)] mb-1`,children:e(`account.groups`)}),(0,l.jsx)(`ul`,{className:`list-disc list-inside text-[var(--color-text-heading)] space-y-1`,children:n.groups.map(e=>(0,l.jsx)(`li`,{children:e},e))})]}),(0,l.jsx)(`div`,{className:`mt-6 flex gap-2 flex-wrap`,children:(0,l.jsx)(`a`,{href:`/auth/logout`,className:`min-h-[44px] min-w-[44px] inline-flex items-center justify-center px-4 py-2 rounded-[var(--radius-md)] font-medium border border-[var(--color-border)] text-[var(--color-text)] bg-transparent no-underline hover:bg-[var(--color-surface-elevated)] focus-visible:outline focus-visible:outline-2 focus-visible:outline-[var(--color-focus-ring)] focus-visible:outline-offset-2`,children:e(`account.logOut`)})})]})]})}export{f as AccountPage};
|