[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6C1M6WPWR3KAPRY6XFHQW4A":3,"skill-same:01M6C1M6WPWR3KAPRY6XFHQW4A":89},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":8,"repositoryFullName":9,"ownerLogin":10,"ownerAvatarUrl":11,"ownerAccountNo":12,"ownerDisplayName":13,"repositoryNo":14,"starsCount":15,"licenseSpdxId":16,"licenseFileUrl":17,"sourceHtmlUrl":18,"categories":19,"keywords":30,"publishedAt":53,"linkOnly":54,"markdownContent":55,"markdownBody":56,"frontMatter":57,"refName":65,"commitSha":66,"skillDirectory":67,"forksCount":68,"repositoryHtmlUrl":69,"repositoryHomepageUrl":70,"ownerHtmlUrl":71,"ownerBlogUrl":72,"ownerDescription":73,"updatedAt":74,"install":75,"resources":88},"01M6C1M6WPWR3KAPRY6XFHQW4A","rlm-query","RLM 子智能体查询","Spawn sub-agent to process focused context and return structured result","派生子智能体来处理聚焦的上下文，并返回结构化的结果。","jmagly\u002Faiwg","jmagly","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F1159087?v=4","01M6C10AK8N2WCSQN11FYGTJWN","Joseph Magly","01M6C10AQ8A2RMED1Y1BSVY7NF",229,"MIT",null,"https:\u002F\u002Fgithub.com\u002Fjmagly\u002Faiwg\u002Fblob\u002Fmain\u002Fagentic\u002Fcode\u002Faddons\u002Frlm\u002Fskills\u002Frlm-query\u002FSKILL.md",[20,25],{"categoryNo":21,"categoryName":22,"taxonomyType":23,"taxonomyTypeDesc":24},"01M8BRZZF9D7PVFN5MXSPWWD61","AI 工程师","PROFESSION","适用职业",{"categoryNo":26,"categoryName":27,"taxonomyType":28,"taxonomyTypeDesc":29},"01M8CC8YC2FQ8GKM03816XMZV6","RLM 递归上下文处理","SCENARIO","使用场景",[31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52],"rlm","query","rlm query","spawn","depth","result","sub-agent","direction","efficiency","only","process","graph","context","write","read","prompt","grep","haiku","model","Bash","cache","file","2026-11-10 10:12:30",false,"---\nnamespace: aiwg\nname: rlm-query\nplatforms: [all]\ndescription: Spawn sub-agent to process focused context and return structured result\ncommandHint:\n  argumentHint: '\"\u003Ccontext-file> \u003Csub-prompt>\" [--model \u003Cmodel>] [--output \u003Cfile>] [--depth \u003Cn>] [--neighbors-of \u003Cid>] [--direction \u003Cin|out|both>] [--graph \u003Cname>] [--no-cache] [--cache-only]'\n  allowedTools: 'Read, Write, Grep, Glob, Bash'\n  model: haiku\n  category: rlm\n  modelRole: efficiency\n  modelTier: economy\n---\n\n# RLM Query\n\nSpawn a focused sub-agent to process a specific portion of context and return a structured result. This is the command equivalent of RLM's `llm_query()` function.\n\n## Core Philosophy\n\nSub-agents receive ONLY the specified context, not the full conversation history. This prevents context overload and improves output quality by enforcing focused, single-purpose queries.\n\n## Usage\n\n```\n\u002Frlm-query \u003Ccontext-file> \u003Csub-prompt>\n\u002Frlm-query \u003Cglob-pattern> \u003Csub-prompt> --output result.txt\n\u002Frlm-query file.ts \"extract all function names\" --model haiku\n\u002Frlm-query \"src\u002F**\u002F*.test.js\" \"count total assertions\" --depth 2\n```\n\n## Parameters\n\n### context-file (required)\nFile path or glob pattern specifying the context source.\n\n**Valid patterns**:\n- Single file: `src\u002Fauth\u002Flogin.ts`\n- Glob pattern: `src\u002F**\u002F*.test.ts`\n- Multiple files: `src\u002Fauth\u002F*.ts`\n\n**Context loading**:\n- Files matching pattern are read and provided to sub-agent\n- If pattern matches multiple files, all are included\n- Large file sets (>10 files) should be avoided (use filtering)\n\n### sub-prompt (required)\nThe specific task for the sub-agent. Should be:\n- Focused and specific (single responsibility)\n- Clear output format expectation\n- Self-contained (no references to parent conversation)\n\n**Good sub-prompts**:\n- \"Extract all exported function names as JSON array\"\n- \"Identify security issues and list in bullet format\"\n- \"Count total test assertions and return as integer\"\n- \"Summarize this function's purpose in one sentence\"\n\n**Poor sub-prompts** (avoid):\n- \"Analyze this\" (too vague)\n- \"Look at this and tell me what you think\" (no format)\n- \"Check if this relates to the earlier discussion\" (references parent context)\n\n### --model \u003Cmodel> (optional)\nOverride the default model for the sub-agent.\n\n**Available models**:\n- `opus` - Highest capability (expensive, for complex analysis)\n- `sonnet` - Balanced (default for most queries)\n- `haiku` - Fast and cheap (for simple extraction)\n\n**Model selection guidance** (per REF-089 Appendix B; GRADE: LOW, peer-review pending):\n- Use `haiku` for: counting, extracting simple patterns, yes\u002Fno questions\n- Use `sonnet` for: summarization, moderate analysis, code review\n- Use `opus` for: complex reasoning, architectural decisions, multi-step analysis\n\n**RLM root vs sub-agent**: When `rlm-query` itself dispatches sub-calls (recursion via `--depth >1`), the *root* agent should be coding-capable (sonnet or opus). Per REF-089, \"Qwen3-8B (non-coder) struggled without sufficient coding capabilities.\" Sub-agents performing simple extraction can safely be `haiku`; sub-agents performing analysis or synthesis should be `sonnet` or higher.\n\n**Output token limits**: RLM root agents emit code, which can be verbose. Models with output token limits below 4k will underperform. Surface a warning when the configured model has lower limits.\n\n### --output \u003Cfile> (optional)\nSave the sub-agent's response to a file instead of returning inline.\n\n**Use cases**:\n- Intermediate results in multi-stage workflows\n- Large outputs that would clutter conversation\n- Results that need to persist for later reference\n\n**Behavior**:\n- File is created\u002Foverwritten with sub-agent response\n- Command returns path to file instead of full content\n- File can be used as input to subsequent `rlm-query` calls\n\n### --neighbors-of \u003Cid> (optional, requires aiwg index)\n\nResolve the context source from the artifact index's dependency graph instead of from a glob pattern. Pass an artifact ID (path or REF-XXX identifier) — the skill resolves its neighbors and dispatches the sub-prompt over them.\n\n**Requires**: `aiwg index` capability available (built and reachable). When the index is unavailable, the skill errors with a remediation pointer.\n\n**Resolution**:\n\n```bash\n# At depth=1 (default), maps directly to the index CLI:\naiwg index neighbors --graph \u003Cgraph> --node \u003Cid> --direction \u003Cdir> --json\n\n# At depth >1, the skill expands recursively by calling neighbors on each\n# result up to \u003CN> hops, deduplicating along the way.\n```\n\n### --direction \u003Cin|out|both> (optional, with --neighbors-of)\n\nRestrict which side of the dependency graph to traverse. Defaults to `both`. Aligns with the `aiwg index neighbors` CLI direction flag.\n\n- `in` — upstream (artifacts that depend on the node)\n- `out` — downstream (artifacts the node depends on)\n- `both` — both directions (default)\n\n### --graph \u003Cname> (optional, with --neighbors-of)\n\nWhich dependency graph to query. Defaults to `project`. Valid values match the `aiwg index neighbors --graph` flag (e.g., `framework`, `project`, `codebase`, or a user-defined graph name).\n\n### --no-cache (optional, #1203)\n\nBypass the result cache: do not read existing cache entries, but still write the result for future calls. Use to force a re-run when you suspect external state has changed in a way the cache key would not capture.\n\n### --cache-only (optional, #1203)\n\nRead-only audit: error out if the call would not be a cache hit. Useful to verify reproducibility before committing or to gauge what re-running would cost.\n\n### --depth \u003Cn> (optional)\n\nWhen `--neighbors-of` is set, controls graph traversal depth (default: `1`). Otherwise tracks current recursion depth (internal use).\n\n**Purpose**:\n- Prevents infinite recursion if sub-agent spawns sub-queries\n- Logs depth for debugging complex query chains\n- Default: 0 (top-level query)\n\n**Recursion limit**: Maximum depth of 3 levels\n- Depth 0: Parent agent\n- Depth 1: First sub-agent\n- Depth 2: Sub-agent's sub-agent\n- Depth 3: Maximum (further nesting blocked)\n\n## Planned Capabilities\n\nThese flags are reserved in the design but not yet implemented. Tracked in Gitea #1201.\n\n- `--save-trajectory \u003Cpath>` — Persist a structured trajectory of the dispatch + sub-agent result suitable for offline analysis or future fine-tuning. Format: JSON Lines with one entry per call. REF-089 (p. 5) reports a 28.3% performance improvement from 1,000 trajectory samples for fine-tuning RLM-specialized models. When implemented, this flag will be added to `argumentHint` and become enforceable by the canonical command surface contract test.\n\n## Execution Flow\n\n### Phase 1: Context Loading\n\n**Argument resolution** — pick the context-source axis from the parsed flags:\n\n1. **If `--neighbors-of \u003Cid>` is present** (graph-bounded; #1206):\n   - Verify `aiwg index` is available. Run `aiwg index stats --json` once; on failure, error with \"neighbors-of requires aiwg index — run `aiwg index build` first\".\n   - Resolve direct neighbors:\n     ```bash\n     aiwg index neighbors --graph \"${graph:-project}\" \\\n       --node \"\u003Cid>\" \\\n       --direction \"${direction:-both}\" \\\n       --json\n     ```\n   - If `--depth N` (N > 1): expand iteratively. For each new neighbor, run the same `aiwg index neighbors` call; deduplicate by node id; stop after N hops or when the frontier is empty.\n   - Map the resolved node IDs to file paths via `aiwg index query --id \u003Cid> --json` (or use the `path` field returned by `neighbors` directly when present).\n   - Treat the deduplicated path list as the context source. Skip the glob\u002Fpath branch below.\n   - On empty result set, error with the offending node id and a suggestion to verify it exists via `aiwg index query \"\u003Cid>\"`.\n\n2. **Else if a glob pattern or single path is supplied**:\n   - Resolve the glob with `find` \u002F `glob` semantics\n   - Use the matched file list as the context source\n\n3. **Read** all resolved files into memory.\n4. **Cache lookup** (#1203, unless `--no-cache`):\n   - Compute content hash for each resolved file (or pull from `aiwg index query --id \u003Cid> --json`)\n   - Compose `CacheKey = { inputs[], query, subPrompt, model, aggregateStrategy }` and call `computeHash(key)` (`src\u002Frlm\u002Fcache\u002Fhash.ts`)\n   - If `aiwg rlm-cache` reports a hit (`get(root, hash)` succeeds): return the cached `result.json` immediately and log `cache_hit=true` in the cost report. Skip dispatch.\n   - If miss and `--cache-only`: error with the hash and exit non-zero.\n   - Otherwise: continue to Phase 2 dispatch. After dispatch, write `{result, manifest, metadata}` via `put(root, entry)`.\n5. **Validate** total context size (\u003C50% of model window).\n6. If too large, error and suggest filtering (`--neighbors-of` with smaller `--depth`, narrower glob, or `--use-index` with stricter query).\n\n**Communication**:\n```\nContext source: {neighbors-of \u003Cid> @ depth N | pattern}\nMatched files:  {count}\nTotal size:     {size} tokens\nSpawning sub-agent with {model}...\n```\n\n### Phase 2: Sub-Agent Invocation\n\n1. Create isolated sub-agent instance\n2. Provide ONLY the specified context (no parent conversation)\n3. Execute sub-prompt\n4. Capture response\n5. Validate response format (if expected format specified)\n\n**Sub-agent receives**:\n```\nContext:\n{file contents}\n\nTask:\n{sub-prompt}\n\nInstructions:\n- Focus only on the provided context\n- Output in the requested format\n- Do not reference external information\n- Be concise and specific\n```\n\n### Phase 3: Result Processing\n\n**If --output specified**:\n1. Write sub-agent response to file\n2. Return file path\n\n**Otherwise**:\n1. Return sub-agent response inline\n2. Preserve formatting\n\n**Communication**:\n```\nSub-agent completed.\nModel: {model}\nDuration: {time}\n\nResult:\n{response}\n\nOR\n\nResult saved to: {output-file}\n```\n\n## Integration with rlm-batch\n\n`\u002Frlm-query` works seamlessly with `\u002Frlm-batch` for parallel fan-out:\n\n```\n# Fan-out: Query multiple files in parallel\n\u002Frlm-batch \"src\u002Fcomponents\u002F*.tsx\" \"\u002Frlm-query {file} 'extract props interface'\"\n\n# Fan-in: Aggregate results\n\u002Frlm-query \"results\u002F*.json\" \"combine all JSON arrays into single array\"\n```\n\nSee `@$AIWG_ROOT\u002Fagentic\u002Fcode\u002Faddons\u002Frlm\u002Fcommands\u002Frlm-batch.md` for batch processing patterns.\n\n## Error Handling\n\n### Context Too Large\n\n```\nError: Context exceeds safe limit\n\nPattern: src\u002F**\u002F*.ts\nMatched files: 87\nTotal size: 120k tokens (60% of window)\n\nSuggestion:\n1. Use more specific glob: src\u002Fauth\u002F**\u002F*.ts\n2. Split into multiple queries: \u002Frlm-batch\n3. Use haiku model (larger window)\n```\n\n### No Files Matched\n\n```\nError: No files matched pattern\n\nPattern: src\u002F**\u002F*.test.ts\nMatches: 0\n\nVerify:\n1. Pattern syntax is correct\n2. Files exist at specified path\n3. Working directory is correct\n```\n\n### Recursion Depth Exceeded\n\n```\nError: Maximum recursion depth exceeded\n\nCurrent depth: 3\nLimit: 3\n\nA sub-agent cannot spawn more sub-queries at this depth.\nConsider restructuring query chain to be less nested.\n```\n\n### Sub-Agent Failure\n\n```\nError: Sub-agent failed to complete query\n\nModel: sonnet\nError: {error message}\n\nOptions:\n1. Retry with different model: --model opus\n2. Simplify sub-prompt\n3. Reduce context size\n```\n\n## User Communication\n\n**At start**:\n```\nRLM Query: Spawning sub-agent\n\nContext: {pattern} ({count} files, {size} tokens)\nPrompt: {sub-prompt}\nModel: {model}\nDepth: {depth}\n\nProcessing...\n```\n\n**On completion**:\n```\n─────────────────────────────────────────\nRLM Query: Complete\n─────────────────────────────────────────\n\nDuration: {time}\nModel: {model} ({tokens} tokens)\n\n{response OR \"Result saved to: {file}\"}\n```\n\n**On error**:\n```\n─────────────────────────────────────────\nRLM Query: Failed\n─────────────────────────────────────────\n\nError: {error summary}\nContext: {pattern}\nModel: {model}\n\n{Suggestions for resolution}\n```\n\n## Best Practices\n\n### Context Scoping\n\n**Good**:\n```\n# Focused single file\n\u002Frlm-query src\u002Fauth\u002Flogin.ts \"extract exported functions\"\n\n# Specific subset\n\u002Frlm-query \"src\u002Fauth\u002F*.ts\" \"list all interfaces\"\n```\n\n**Bad**:\n```\n# Too broad (hundreds of files)\n\u002Frlm-query \"src\u002F**\u002F*\" \"analyze everything\"\n\n# Unfocused multi-file\n\u002Frlm-query \"**\u002F*.{ts,js,tsx,jsx,json,md}\" \"find issues\"\n```\n\n### Sub-Prompt Design\n\n**Good**:\n```\n# Clear output format\n\"extract function names as JSON array\"\n\n# Specific task\n\"count total test cases and return integer\"\n\n# Bounded scope\n\"summarize function purpose in one sentence\"\n```\n\n**Bad**:\n```\n# Vague\n\"look at this code\"\n\n# Multi-task\n\"analyze, refactor, and document this code\"\n\n# Unbounded\n\"tell me everything about this\"\n```\n\n### Model Selection\n\n| Query Type | Model | Rationale |\n|------------|-------|-----------|\n| Count items | haiku | Fast extraction |\n| Extract pattern | haiku | Simple regex\u002Fparsing |\n| Summarize | sonnet | Balanced quality\u002Fcost |\n| Analyze complexity | sonnet | Moderate reasoning |\n| Architectural review | opus | Complex reasoning |\n| Security audit | opus | High-stakes analysis |\n\n### Output Strategy\n\n**Return inline** (default):\n- Simple extractions (\u003C500 words)\n- JSON\u002Fstructured data\n- Single values (counts, booleans)\n\n**Use --output**:\n- Large responses (>1000 words)\n- Intermediate results in workflows\n- Results referenced by multiple later queries\n\n## Examples\n\n### Example 1: Simple Extraction (haiku)\n\n**Task**: Extract all exported function names from an auth module.\n\n```\n\u002Frlm-query src\u002Fauth\u002Fhelpers.ts \"extract all exported function names as JSON array\" --model haiku\n```\n\n**Sub-agent receives**:\n```\nContext:\n\u002F\u002F src\u002Fauth\u002Fhelpers.ts\nexport function validateEmail(email: string): boolean { ... }\nexport function hashPassword(pwd: string): string { ... }\nfunction internalHelper() { ... }  \u002F\u002F not exported\n\nTask:\nextract all exported function names as JSON array\n```\n\n**Sub-agent returns**:\n```json\n[\"validateEmail\", \"hashPassword\"]\n```\n\n**Duration**: ~2 seconds\n\n### Example 2: Moderate Analysis with Output (sonnet)\n\n**Task**: Review test file for missing edge cases, save to intermediate file.\n\n```\n\u002Frlm-query test\u002Fauth\u002Flogin.test.ts \"identify missing edge cases and list in bullet format\" --output .aiwg\u002Fworking\u002Fedge-cases.md\n```\n\n**Sub-agent receives**:\n```\nContext:\n\u002F\u002F test\u002Fauth\u002Flogin.test.ts\ndescribe('login', () => {\n  it('should accept valid credentials', () => { ... });\n  it('should reject invalid password', () => { ... });\n});\n\nTask:\nidentify missing edge cases and list in bullet format\n```\n\n**Sub-agent returns** (saved to `.aiwg\u002Fworking\u002Fedge-cases.md`):\n```\nMissing edge cases:\n- Null\u002Fempty username input\n- Null\u002Fempty password input\n- Account lockout after N failed attempts\n- Session expiration handling\n- Concurrent login from multiple devices\n```\n\n**Command returns**:\n```\nResult saved to: .aiwg\u002Fworking\u002Fedge-cases.md\n```\n\n**Duration**: ~8 seconds\n\n### Example 3: Complex Nested Query (opus, depth tracking)\n\n**Task**: Multi-level analysis where sub-agent spawns its own sub-query.\n\n```\n# Top-level query (depth 0)\n\u002Frlm-query src\u002Fapi\u002F \"for each endpoint file, extract security checks\" --depth 0\n```\n\n**Sub-agent at depth 1 decides to spawn sub-query**:\n```\n# Sub-agent internally runs (depth 1):\n\u002Frlm-query src\u002Fapi\u002Fauth.ts \"extract middleware chain\" --depth 1\n```\n\n**Sub-sub-agent at depth 2 processes single file**:\n```\n# Depth 2: Simple extraction\nContext: src\u002Fapi\u002Fauth.ts\nResult: [\"authenticate\", \"rateLimit\", \"validateInput\"]\n```\n\n**Depth 1 sub-agent aggregates**:\n```\nEndpoint: \u002Fapi\u002Fauth\nSecurity checks: authenticate, rateLimit, validateInput\n```\n\n**Parent receives**:\n```\nSecurity Analysis:\n- \u002Fapi\u002Fauth: authenticate, rateLimit, validateInput\n- \u002Fapi\u002Fusers: authenticate, authorize\n- \u002Fapi\u002Fadmin: authenticate, authorize, auditLog\n```\n\n**Duration**: ~30 seconds (depth 0→1→2, sequential)\n\n**Note**: This is acceptable because depth stays within limit (≤3). If depth 2 tried to spawn another query, it would be blocked.\n\n## Success Criteria\n\nThis command succeeds when:\n- [ ] Context loaded from specified files\n- [ ] Sub-agent spawned with isolated context\n- [ ] Sub-prompt executed successfully\n- [ ] Result returned or saved to file\n- [ ] Depth tracking prevents excessive recursion\n- [ ] User informed of outcome\n\n## References\n\n- @$AIWG_ROOT\u002Fagentic\u002Fcode\u002Faddons\u002Frlm\u002Fcommands\u002Frlm-batch.md - Batch parallel queries\n- @$AIWG_ROOT\u002Fagentic\u002Fcode\u002Faddons\u002Frlm\u002Fdocs\u002Frlm-patterns.md - RLM design patterns\n- @$AIWG_ROOT\u002Fagentic\u002Fcode\u002Faddons\u002Faiwg-utils\u002Frules\u002Fsubagent-scoping.md - Subagent scoping rules (context minimization)\n- @$AIWG_ROOT\u002Fagentic\u002Fcode\u002Faddons\u002Faiwg-utils\u002Frules\u002Finstruction-comprehension.md - Instruction following for sub-prompts\n","# RLM Query\n\nSpawn a focused sub-agent to process a specific portion of context and return a structured result. This is the command equivalent of RLM's `llm_query()` function.\n\n## Core Philosophy\n\nSub-agents receive ONLY the specified context, not the full conversation history. This prevents context overload and improves output quality by enforcing focused, single-purpose queries.\n\n## Usage\n\n```\n\u002Frlm-query \u003Ccontext-file> \u003Csub-prompt>\n\u002Frlm-query \u003Cglob-pattern> \u003Csub-prompt> --output result.txt\n\u002Frlm-query file.ts \"extract all function names\" --model haiku\n\u002Frlm-query \"src\u002F**\u002F*.test.js\" \"count total assertions\" --depth 2\n```\n\n## Parameters\n\n### context-file (required)\nFile path or glob pattern specifying the context source.\n\n**Valid patterns**:\n- Single file: `src\u002Fauth\u002Flogin.ts`\n- Glob pattern: `src\u002F**\u002F*.test.ts`\n- Multiple files: `src\u002Fauth\u002F*.ts`\n\n**Context loading**:\n- Files matching pattern are read and provided to sub-agent\n- If pattern matches multiple files, all are included\n- Large file sets (>10 files) should be avoided (use filtering)\n\n### sub-prompt (required)\nThe specific task for the sub-agent. Should be:\n- Focused and specific (single responsibility)\n- Clear output format expectation\n- Self-contained (no references to parent conversation)\n\n**Good sub-prompts**:\n- \"Extract all exported function names as JSON array\"\n- \"Identify security issues and list in bullet format\"\n- \"Count total test assertions and return as integer\"\n- \"Summarize this function's purpose in one sentence\"\n\n**Poor sub-prompts** (avoid):\n- \"Analyze this\" (too vague)\n- \"Look at this and tell me what you think\" (no format)\n- \"Check if this relates to the earlier discussion\" (references parent context)\n\n### --model \u003Cmodel> (optional)\nOverride the default model for the sub-agent.\n\n**Available models**:\n- `opus` - Highest capability (expensive, for complex analysis)\n- `sonnet` - Balanced (default for most queries)\n- `haiku` - Fast and cheap (for simple extraction)\n\n**Model selection guidance** (per REF-089 Appendix B; GRADE: LOW, peer-review pending):\n- Use `haiku` for: counting, extracting simple patterns, yes\u002Fno questions\n- Use `sonnet` for: summarization, moderate analysis, code review\n- Use `opus` for: complex reasoning, architectural decisions, multi-step analysis\n\n**RLM root vs sub-agent**: When `rlm-query` itself dispatches sub-calls (recursion via `--depth >1`), the *root* agent should be coding-capable (sonnet or opus). Per REF-089, \"Qwen3-8B (non-coder) struggled without sufficient coding capabilities.\" Sub-agents performing simple extraction can safely be `haiku`; sub-agents performing analysis or synthesis should be `sonnet` or higher.\n\n**Output token limits**: RLM root agents emit code, which can be verbose. Models with output token limits below 4k will underperform. Surface a warning when the configured model has lower limits.\n\n### --output \u003Cfile> (optional)\nSave the sub-agent's response to a file instead of returning inline.\n\n**Use cases**:\n- Intermediate results in multi-stage workflows\n- Large outputs that would clutter conversation\n- Results that need to persist for later reference\n\n**Behavior**:\n- File is created\u002Foverwritten with sub-agent response\n- Command returns path to file instead of full content\n- File can be used as input to subsequent `rlm-query` calls\n\n### --neighbors-of \u003Cid> (optional, requires aiwg index)\n\nResolve the context source from the artifact index's dependency graph instead of from a glob pattern. Pass an artifact ID (path or REF-XXX identifier) — the skill resolves its neighbors and dispatches the sub-prompt over them.\n\n**Requires**: `aiwg index` capability available (built and reachable). When the index is unavailable, the skill errors with a remediation pointer.\n\n**Resolution**:\n\n```bash\n# At depth=1 (default), maps directly to the index CLI:\naiwg index neighbors --graph \u003Cgraph> --node \u003Cid> --direction \u003Cdir> --json\n\n# At depth >1, the skill expands recursively by calling neighbors on each\n# result up to \u003CN> hops, deduplicating along the way.\n```\n\n### --direction \u003Cin|out|both> (optional, with --neighbors-of)\n\nRestrict which side of the dependency graph to traverse. Defaults to `both`. Aligns with the `aiwg index neighbors` CLI direction flag.\n\n- `in` — upstream (artifacts that depend on the node)\n- `out` — downstream (artifacts the node depends on)\n- `both` — both directions (default)\n\n### --graph \u003Cname> (optional, with --neighbors-of)\n\nWhich dependency graph to query. Defaults to `project`. Valid values match the `aiwg index neighbors --graph` flag (e.g., `framework`, `project`, `codebase`, or a user-defined graph name).\n\n### --no-cache (optional, #1203)\n\nBypass the result cache: do not read existing cache entries, but still write the result for future calls. Use to force a re-run when you suspect external state has changed in a way the cache key would not capture.\n\n### --cache-only (optional, #1203)\n\nRead-only audit: error out if the call would not be a cache hit. Useful to verify reproducibility before committing or to gauge what re-running would cost.\n\n### --depth \u003Cn> (optional)\n\nWhen `--neighbors-of` is set, controls graph traversal depth (default: `1`). Otherwise tracks current recursion depth (internal use).\n\n**Purpose**:\n- Prevents infinite recursion if sub-agent spawns sub-queries\n- Logs depth for debugging complex query chains\n- Default: 0 (top-level query)\n\n**Recursion limit**: Maximum depth of 3 levels\n- Depth 0: Parent agent\n- Depth 1: First sub-agent\n- Depth 2: Sub-agent's sub-agent\n- Depth 3: Maximum (further nesting blocked)\n\n## Planned Capabilities\n\nThese flags are reserved in the design but not yet implemented. Tracked in Gitea #1201.\n\n- `--save-trajectory \u003Cpath>` — Persist a structured trajectory of the dispatch + sub-agent result suitable for offline analysis or future fine-tuning. Format: JSON Lines with one entry per call. REF-089 (p. 5) reports a 28.3% performance improvement from 1,000 trajectory samples for fine-tuning RLM-specialized models. When implemented, this flag will be added to `argumentHint` and become enforceable by the canonical command surface contract test.\n\n## Execution Flow\n\n### Phase 1: Context Loading\n\n**Argument resolution** — pick the context-source axis from the parsed flags:\n\n1. **If `--neighbors-of \u003Cid>` is present** (graph-bounded; #1206):\n   - Verify `aiwg index` is available. Run `aiwg index stats --json` once; on failure, error with \"neighbors-of requires aiwg index — run `aiwg index build` first\".\n   - Resolve direct neighbors:\n     ```bash\n     aiwg index neighbors --graph \"${graph:-project}\" \\\n       --node \"\u003Cid>\" \\\n       --direction \"${direction:-both}\" \\\n       --json\n     ```\n   - If `--depth N` (N > 1): expand iteratively. For each new neighbor, run the same `aiwg index neighbors` call; deduplicate by node id; stop after N hops or when the frontier is empty.\n   - Map the resolved node IDs to file paths via `aiwg index query --id \u003Cid> --json` (or use the `path` field returned by `neighbors` directly when present).\n   - Treat the deduplicated path list as the context source. Skip the glob\u002Fpath branch below.\n   - On empty result set, error with the offending node id and a suggestion to verify it exists via `aiwg index query \"\u003Cid>\"`.\n\n2. **Else if a glob pattern or single path is supplied**:\n   - Resolve the glob with `find` \u002F `glob` semantics\n   - Use the matched file list as the context source\n\n3. **Read** all resolved files into memory.\n4. **Cache lookup** (#1203, unless `--no-cache`):\n   - Compute content hash for each resolved file (or pull from `aiwg index query --id \u003Cid> --json`)\n   - Compose `CacheKey = { inputs[], query, subPrompt, model, aggregateStrategy }` and call `computeHash(key)` (`src\u002Frlm\u002Fcache\u002Fhash.ts`)\n   - If `aiwg rlm-cache` reports a hit (`get(root, hash)` succeeds): return the cached `result.json` immediately and log `cache_hit=true` in the cost report. Skip dispatch.\n   - If miss and `--cache-only`: error with the hash and exit non-zero.\n   - Otherwise: continue to Phase 2 dispatch. After dispatch, write `{result, manifest, metadata}` via `put(root, entry)`.\n5. **Validate** total context size (\u003C50% of model window).\n6. If too large, error and suggest filtering (`--neighbors-of` with smaller `--depth`, narrower glob, or `--use-index` with stricter query).\n\n**Communication**:\n```\nContext source: {neighbors-of \u003Cid> @ depth N | pattern}\nMatched files:  {count}\nTotal size:     {size} tokens\nSpawning sub-agent with {model}...\n```\n\n### Phase 2: Sub-Agent Invocation\n\n1. Create isolated sub-agent instance\n2. Provide ONLY the specified context (no parent conversation)\n3. Execute sub-prompt\n4. Capture response\n5. Validate response format (if expected format specified)\n\n**Sub-agent receives**:\n```\nContext:\n{file contents}\n\nTask:\n{sub-prompt}\n\nInstructions:\n- Focus only on the provided context\n- Output in the requested format\n- Do not reference external information\n- Be concise and specific\n```\n\n### Phase 3: Result Processing\n\n**If --output specified**:\n1. Write sub-agent response to file\n2. Return file path\n\n**Otherwise**:\n1. Return sub-agent response inline\n2. Preserve formatting\n\n**Communication**:\n```\nSub-agent completed.\nModel: {model}\nDuration: {time}\n\nResult:\n{response}\n\nOR\n\nResult saved to: {output-file}\n```\n\n## Integration with rlm-batch\n\n`\u002Frlm-query` works seamlessly with `\u002Frlm-batch` for parallel fan-out:\n\n```\n# Fan-out: Query multiple files in parallel\n\u002Frlm-batch \"src\u002Fcomponents\u002F*.tsx\" \"\u002Frlm-query {file} 'extract props interface'\"\n\n# Fan-in: Aggregate results\n\u002Frlm-query \"results\u002F*.json\" \"combine all JSON arrays into single array\"\n```\n\nSee `@$AIWG_ROOT\u002Fagentic\u002Fcode\u002Faddons\u002Frlm\u002Fcommands\u002Frlm-batch.md` for batch processing patterns.\n\n## Error Handling\n\n### Context Too Large\n\n```\nError: Context exceeds safe limit\n\nPattern: src\u002F**\u002F*.ts\nMatched files: 87\nTotal size: 120k tokens (60% of window)\n\nSuggestion:\n1. Use more specific glob: src\u002Fauth\u002F**\u002F*.ts\n2. Split into multiple queries: \u002Frlm-batch\n3. Use haiku model (larger window)\n```\n\n### No Files Matched\n\n```\nError: No files matched pattern\n\nPattern: src\u002F**\u002F*.test.ts\nMatches: 0\n\nVerify:\n1. Pattern syntax is correct\n2. Files exist at specified path\n3. Working directory is correct\n```\n\n### Recursion Depth Exceeded\n\n```\nError: Maximum recursion depth exceeded\n\nCurrent depth: 3\nLimit: 3\n\nA sub-agent cannot spawn more sub-queries at this depth.\nConsider restructuring query chain to be less nested.\n```\n\n### Sub-Agent Failure\n\n```\nError: Sub-agent failed to complete query\n\nModel: sonnet\nError: {error message}\n\nOptions:\n1. Retry with different model: --model opus\n2. Simplify sub-prompt\n3. Reduce context size\n```\n\n## User Communication\n\n**At start**:\n```\nRLM Query: Spawning sub-agent\n\nContext: {pattern} ({count} files, {size} tokens)\nPrompt: {sub-prompt}\nModel: {model}\nDepth: {depth}\n\nProcessing...\n```\n\n**On completion**:\n```\n─────────────────────────────────────────\nRLM Query: Complete\n─────────────────────────────────────────\n\nDuration: {time}\nModel: {model} ({tokens} tokens)\n\n{response OR \"Result saved to: {file}\"}\n```\n\n**On error**:\n```\n─────────────────────────────────────────\nRLM Query: Failed\n─────────────────────────────────────────\n\nError: {error summary}\nContext: {pattern}\nModel: {model}\n\n{Suggestions for resolution}\n```\n\n## Best Practices\n\n### Context Scoping\n\n**Good**:\n```\n# Focused single file\n\u002Frlm-query src\u002Fauth\u002Flogin.ts \"extract exported functions\"\n\n# Specific subset\n\u002Frlm-query \"src\u002Fauth\u002F*.ts\" \"list all interfaces\"\n```\n\n**Bad**:\n```\n# Too broad (hundreds of files)\n\u002Frlm-query \"src\u002F**\u002F*\" \"analyze everything\"\n\n# Unfocused multi-file\n\u002Frlm-query \"**\u002F*.{ts,js,tsx,jsx,json,md}\" \"find issues\"\n```\n\n### Sub-Prompt Design\n\n**Good**:\n```\n# Clear output format\n\"extract function names as JSON array\"\n\n# Specific task\n\"count total test cases and return integer\"\n\n# Bounded scope\n\"summarize function purpose in one sentence\"\n```\n\n**Bad**:\n```\n# Vague\n\"look at this code\"\n\n# Multi-task\n\"analyze, refactor, and document this code\"\n\n# Unbounded\n\"tell me everything about this\"\n```\n\n### Model Selection\n\n| Query Type | Model | Rationale |\n|------------|-------|-----------|\n| Count items | haiku | Fast extraction |\n| Extract pattern | haiku | Simple regex\u002Fparsing |\n| Summarize | sonnet | Balanced quality\u002Fcost |\n| Analyze complexity | sonnet | Moderate reasoning |\n| Architectural review | opus | Complex reasoning |\n| Security audit | opus | High-stakes analysis |\n\n### Output Strategy\n\n**Return inline** (default):\n- Simple extractions (\u003C500 words)\n- JSON\u002Fstructured data\n- Single values (counts, booleans)\n\n**Use --output**:\n- Large responses (>1000 words)\n- Intermediate results in workflows\n- Results referenced by multiple later queries\n\n## Examples\n\n### Example 1: Simple Extraction (haiku)\n\n**Task**: Extract all exported function names from an auth module.\n\n```\n\u002Frlm-query src\u002Fauth\u002Fhelpers.ts \"extract all exported function names as JSON array\" --model haiku\n```\n\n**Sub-agent receives**:\n```\nContext:\n\u002F\u002F src\u002Fauth\u002Fhelpers.ts\nexport function validateEmail(email: string): boolean { ... }\nexport function hashPassword(pwd: string): string { ... }\nfunction internalHelper() { ... }  \u002F\u002F not exported\n\nTask:\nextract all exported function names as JSON array\n```\n\n**Sub-agent returns**:\n```json\n[\"validateEmail\", \"hashPassword\"]\n```\n\n**Duration**: ~2 seconds\n\n### Example 2: Moderate Analysis with Output (sonnet)\n\n**Task**: Review test file for missing edge cases, save to intermediate file.\n\n```\n\u002Frlm-query test\u002Fauth\u002Flogin.test.ts \"identify missing edge cases and list in bullet format\" --output .aiwg\u002Fworking\u002Fedge-cases.md\n```\n\n**Sub-agent receives**:\n```\nContext:\n\u002F\u002F test\u002Fauth\u002Flogin.test.ts\ndescribe('login', () => {\n  it('should accept valid credentials', () => { ... });\n  it('should reject invalid password', () => { ... });\n});\n\nTask:\nidentify missing edge cases and list in bullet format\n```\n\n**Sub-agent returns** (saved to `.aiwg\u002Fworking\u002Fedge-cases.md`):\n```\nMissing edge cases:\n- Null\u002Fempty username input\n- Null\u002Fempty password input\n- Account lockout after N failed attempts\n- Session expiration handling\n- Concurrent login from multiple devices\n```\n\n**Command returns**:\n```\nResult saved to: .aiwg\u002Fworking\u002Fedge-cases.md\n```\n\n**Duration**: ~8 seconds\n\n### Example 3: Complex Nested Query (opus, depth tracking)\n\n**Task**: Multi-level analysis where sub-agent spawns its own sub-query.\n\n```\n# Top-level query (depth 0)\n\u002Frlm-query src\u002Fapi\u002F \"for each endpoint file, extract security checks\" --depth 0\n```\n\n**Sub-agent at depth 1 decides to spawn sub-query**:\n```\n# Sub-agent internally runs (depth 1):\n\u002Frlm-query src\u002Fapi\u002Fauth.ts \"extract middleware chain\" --depth 1\n```\n\n**Sub-sub-agent at depth 2 processes single file**:\n```\n# Depth 2: Simple extraction\nContext: src\u002Fapi\u002Fauth.ts\nResult: [\"authenticate\", \"rateLimit\", \"validateInput\"]\n```\n\n**Depth 1 sub-agent aggregates**:\n```\nEndpoint: \u002Fapi\u002Fauth\nSecurity checks: authenticate, rateLimit, validateInput\n```\n\n**Parent receives**:\n```\nSecurity Analysis:\n- \u002Fapi\u002Fauth: authenticate, rateLimit, validateInput\n- \u002Fapi\u002Fusers: authenticate, authorize\n- \u002Fapi\u002Fadmin: authenticate, authorize, auditLog\n```\n\n**Duration**: ~30 seconds (depth 0→1→2, sequential)\n\n**Note**: This is acceptable because depth stays within limit (≤3). If depth 2 tried to spawn another query, it would be blocked.\n\n## Success Criteria\n\nThis command succeeds when:\n- [ ] Context loaded from specified files\n- [ ] Sub-agent spawned with isolated context\n- [ ] Sub-prompt executed successfully\n- [ ] Result returned or saved to file\n- [ ] Depth tracking prevents excessive recursion\n- [ ] User informed of outcome\n\n## References\n\n- @$AIWG_ROOT\u002Fagentic\u002Fcode\u002Faddons\u002Frlm\u002Fcommands\u002Frlm-batch.md - Batch parallel queries\n- @$AIWG_ROOT\u002Fagentic\u002Fcode\u002Faddons\u002Frlm\u002Fdocs\u002Frlm-patterns.md - RLM design patterns\n- @$AIWG_ROOT\u002Fagentic\u002Fcode\u002Faddons\u002Faiwg-utils\u002Frules\u002Fsubagent-scoping.md - Subagent scoping rules (context minimization)\n- @$AIWG_ROOT\u002Fagentic\u002Fcode\u002Faddons\u002Faiwg-utils\u002Frules\u002Finstruction-comprehension.md - Instruction following for sub-prompts\n",{"name":5,"namespace":58,"platforms":59,"commandHint":61,"description":7},"aiwg",[60],"all",{"model":48,"category":31,"modelRole":39,"modelTier":62,"allowedTools":63,"argumentHint":64},"economy","Read, Write, Grep, Glob, Bash","\"\u003Ccontext-file> \u003Csub-prompt>\" [--model \u003Cmodel>] [--output \u003Cfile>] [--depth \u003Cn>] [--neighbors-of \u003Cid>] [--direction \u003Cin|out|both>] [--graph \u003Cname>] [--no-cache] [--cache-only]","main","6754967c344ccb087a8de06972f55a41067b291b","agentic\u002Fcode\u002Faddons\u002Frlm\u002Fskills\u002Frlm-query",36,"https:\u002F\u002Fgithub.com\u002Fjmagly\u002Faiwg","https:\u002F\u002Faiwg.io","https:\u002F\u002Fgithub.com\u002Fjmagly","https:\u002F\u002Fintegrolabs.io","ml\u002Fai, industrial automation, safety\u002Fsecurity, ssi\r\n\r\nmagly.net\r\nintegrolabs.io\r\naiwg.io\r\nfortemi.com\r\npagenary.com\r\nbytecask.com","2026-11-14 10:46:34",{"source":9,"skillName":5,"commands":76,"prompt":86,"zipAvailable":87},[77,80,83],{"tool":78,"command":79},"npx","npx skills add jmagly\u002Faiwg --skill rlm-query",{"tool":81,"command":82},"bunx","bunx skills add jmagly\u002Faiwg --skill rlm-query",{"tool":84,"command":85},"pnpm","pnpm dlx skills add jmagly\u002Faiwg --skill rlm-query","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fjmagly\u002Faiwg\u002Fblob\u002Fmain\u002Fagentic\u002Fcode\u002Faddons\u002Frlm\u002Fskills\u002Frlm-query\u002FSKILL.md",true,[],[90,98,103,127,146,151],{"skillNo":91,"name":92,"nameZh":17,"description":93,"descriptionZh":17,"repositoryFullName":9,"ownerLogin":10,"ownerAvatarUrl":11,"ownerAccountNo":12,"ownerDisplayName":13,"repositoryNo":14,"starsCount":15,"licenseSpdxId":16,"licenseFileUrl":17,"sourceHtmlUrl":94,"categories":95,"keywords":96,"publishedAt":97},"01M78KW7PZJ9YQZQMW84SN2YD4","plugin-search","Search marketplaces for plugins using configured local manifests and directory caches; rank matching plugins by observed installs, review tier and cache dates without installing or fetching anything","https:\u002F\u002Fgithub.com\u002Fjmagly\u002Faiwg\u002Fblob\u002Fmain\u002Fagentic\u002Fcode\u002Fplugins\u002Futils\u002Fskills\u002Fplugin-search\u002FSKILL.md",[],[],"2026-11-15 14:19:17",{"skillNo":99,"name":92,"nameZh":17,"description":93,"descriptionZh":17,"repositoryFullName":9,"ownerLogin":10,"ownerAvatarUrl":11,"ownerAccountNo":12,"ownerDisplayName":13,"repositoryNo":14,"starsCount":15,"licenseSpdxId":16,"licenseFileUrl":17,"sourceHtmlUrl":100,"categories":101,"keywords":102,"publishedAt":97},"01M78KSEZS9ZNNFESY9ANW22S0","https:\u002F\u002Fgithub.com\u002Fjmagly\u002Faiwg\u002Fblob\u002Fmain\u002Fagentic\u002Fcode\u002Faddons\u002Faiwg-utils\u002Fskills\u002Fplugin-search\u002FSKILL.md",[],[],{"skillNo":104,"name":105,"nameZh":17,"description":106,"descriptionZh":17,"repositoryFullName":9,"ownerLogin":10,"ownerAvatarUrl":11,"ownerAccountNo":12,"ownerDisplayName":13,"repositoryNo":14,"starsCount":15,"licenseSpdxId":16,"licenseFileUrl":17,"sourceHtmlUrl":107,"categories":108,"keywords":109,"publishedAt":53},"01M70QA0BSYJ49EES9V4RE8QH1","host-hardening","Read-only system hardening baseline and plan-first host hardening recommendations for SSH, Docker bind addresses, firewall persistence, datastores, exporters and audit retention.","https:\u002F\u002Fgithub.com\u002Fjmagly\u002Faiwg\u002Fblob\u002Fmain\u002Fagentic\u002Fcode\u002Fplugins\u002Fsecurity-engineering\u002Fskills\u002Fhost-hardening\u002FSKILL.md",[],[110,111,112,113,114,45,115,116,117,118,119,120,121,50,122,40,123,124,125,126],"hardening","host","host hardening","verification","secrets","request","remediation","recommendations","audit","plan","port","bind","access","retention","re","never","firewall",{"skillNo":128,"name":129,"nameZh":17,"description":130,"descriptionZh":17,"repositoryFullName":9,"ownerLogin":10,"ownerAvatarUrl":11,"ownerAccountNo":12,"ownerDisplayName":13,"repositoryNo":14,"starsCount":15,"licenseSpdxId":16,"licenseFileUrl":17,"sourceHtmlUrl":131,"categories":132,"keywords":133,"publishedAt":53},"01M70PNT2Z4HMZPRBTAF6073NN","exposure-analysis","Read-only firewall analysis and effective host exposure reconstruction for Docker published ports, UFW bypass, stale rules, CDN scope, IPv6 asymmetry and external probe allowlists.","https:\u002F\u002Fgithub.com\u002Fjmagly\u002Faiwg\u002Fblob\u002Fmain\u002Fagentic\u002Fcode\u002Fplugins\u002Fforensics\u002Fskills\u002Fexposure-analysis\u002FSKILL.md",[],[134,135,136,137,138,44,45,139,120,125,50,140,111,141,40,142,143,126,144,145],"analysis","exposure analysis","collection","reconstruction","operator","credentials","unknown","internet","local","scope","ports","ufw",{"skillNo":147,"name":105,"nameZh":17,"description":106,"descriptionZh":17,"repositoryFullName":9,"ownerLogin":10,"ownerAvatarUrl":11,"ownerAccountNo":12,"ownerDisplayName":13,"repositoryNo":14,"starsCount":15,"licenseSpdxId":16,"licenseFileUrl":17,"sourceHtmlUrl":148,"categories":149,"keywords":150,"publishedAt":53},"01M70P8QATMPKA78E4FT5D2TNA","https:\u002F\u002Fgithub.com\u002Fjmagly\u002Faiwg\u002Fblob\u002Fmain\u002Fagentic\u002Fcode\u002Fframeworks\u002Fsecurity-engineering\u002Fskills\u002Fhost-hardening\u002FSKILL.md",[],[110,111,112,124,125,126,121,123,117,114,45,115,116,118,119,120,113,50,122,40],{"skillNo":152,"name":129,"nameZh":17,"description":130,"descriptionZh":17,"repositoryFullName":9,"ownerLogin":10,"ownerAvatarUrl":11,"ownerAccountNo":12,"ownerDisplayName":13,"repositoryNo":14,"starsCount":15,"licenseSpdxId":16,"licenseFileUrl":17,"sourceHtmlUrl":153,"categories":154,"keywords":155,"publishedAt":53},"01M70NMPVJ5H0JH131P60FW4R8","https:\u002F\u002Fgithub.com\u002Fjmagly\u002Faiwg\u002Fblob\u002Fmain\u002Fagentic\u002Fcode\u002Fframeworks\u002Fforensics-complete\u002Fskills\u002Fexposure-analysis\u002FSKILL.md",[],[134,135,145,144,138,143,142,40,137,44,45,139,120,136,50,140,111,126,125,141]]