Compound capture

From jikig-ai/soleur · View interactive version

Compound capture is an AI agent skill from the GitHub repository jikig-ai/soleur. This skill should be used when capturing solved problems as categorized documentation with YAML frontmatter for fast lookup. It auto-documents solutions after confirmation and builds searchable institutional knowledge.

How to use this skill

Skill file

<!-- soleur-cloud-mode:start -->

Cloud Mode (Devin): before pipeline work run bash "${CLAUDE_PLUGIN_ROOT}/scripts/cloud-detect.sh". If CLAUDE_PLUGIN_ROOT is unset (cloud exec shells do not export it), resolve the root by IDENTITY, never by script basename: for d in "$HOME/.local/share/devin/cli/plugins/cache" and /opt/.devin/plugins, skip unless [ -d "$d" ], then MANIFEST="$(find "$d" -path '*/.claude-plugin/plugin.json' -exec grep -l '"name"[[:space:]]*:[[:space:]]*"soleur"' {} + 2>/dev/null | head -1)", ROOT="${MANIFEST%/.claude-plugin/plugin.json}" — one resolution, two consumers: $ROOT/scripts/cloud-detect.sh and $ROOT/scripts/precommit-guard.sh. (Shape check, not authentication: a planted {"name":"soleur"} dir passes — ADR-179 A11.) local or not-local:no-devin-env proceeds normally; any other not-local:<reason> applies <plugin-root>/devin/INSTRUCTIONS.md §Cloud Mode: emit the --banner, fan out sequentially with Reviewed-Coverage: sequential-fallback disclosure (never claim an independent review ran), message_user ack before any secrets read or production mutation, and run precommit-guard.sh before any git commit — hooks do not fire in cloud.

<!-- soleur-cloud-mode:end -->

<!-- grok-harness-invoke:start -->

Grok Build (plugins/soleur/lib/harness.ts invokeSkill()): Read this SKILL.md in this process and run it to completion. A one-segment soleur:<name> in this document names a SKILL — on Grok Build, Read plugins/soleur/skills/<name>/SKILL.md in this process; it is not a nested tool_use. A multi-segment id such as soleur:<domain>:<name> names an AGENT: spawn it, never Read it, and on Grok Build spawn_subagent takes the id with its colons replaced by hyphens (agentIdToGrokSubagentType). Claude Code: Skill tool for a skill (soleur:<name>), Task tool with subagent_type for an agent. Forbidden is executing a subset, not the Read.

<!-- grok-harness-invoke:end -->

compound-capture Skill

Purpose: Automatically document solved problems to build searchable institutional knowledge with category-based organization (enum-validated problem types).

Headless Mode Detection

If $ARGUMENTS contains --headless, set HEADLESS_MODE=true. Strip --headless from $ARGUMENTS before processing remaining args. Headless mode affects Steps 2, 3, 5, 8, and auto-consolidation Step E.

Overview

This skill captures problem solutions immediately after confirmation, creating structured documentation that serves as a searchable knowledge base for future sessions.

Organization: Single-file architecture - each problem documented as one markdown file in its symptom category directory (e.g., knowledge-base/project/learnings/performance-issues/n-plus-one-briefs.md). Files use YAML frontmatter for metadata and searchability.


<critical_sequence name="documentation-capture" enforce_order="strict">

Documentation Capture Process

<step number="1" required="true">

Step 1: Detect Confirmation

Auto-invoke after phrases:

OR manual: /doc-fix command

Non-trivial problems only:

Skip documentation for:

</step>

<step number="2" required="true" depends_on="1">

Step 2: Gather Context

Extract from conversation history:

Check for session-state.md: Run git branch --show-current. If on a feat-* branch, check if knowledge-base/project/specs/feat-<name>/session-state.md exists. If it does, read it and incorporate forwarded errors from ### Errors and decisions from ### Decisions into the context below. These came from preceding pipeline phases whose context was compacted.

Required information:

Session errors (beyond the target problem):

Scan conversation history AND session-state.md (if present) for errors unrelated to the main problem investigation documented above. Only capture errors that are NOT part of the investigation attempts. Skip trivial errors immediately corrected (typos in commands, expected test failures during TDD).

Extract for each error found:

If no session errors are found, output "Session errors: none detected" (do not skip silently — the explicit acknowledgment prevents the model from accidentally dropping errors by judging the session as clean).

Environment details:

BLOCKING REQUIREMENT: If critical context is missing (module name, exact error, stage, or resolution steps):

Headless mode: Infer missing fields from session context (conversation history, session-state.md, git log). Skip any field that cannot be reasonably inferred — do not prompt. Proceed to Step 3 with whatever context is available.

Interactive mode: Ask user and WAIT for response before proceeding to Step 3:

I need a few details to document this properly:

1. Which module had this issue? [ModuleName]
2. What was the exact error message or symptom?
3. What stage were you in? (0-6 or post-implementation)

[Continue after user provides details]

</step>

<step number="3" required="false" depends_on="2">

Step 3: Check Existing Docs

Search knowledge-base/project/learnings/ for similar issues. Prefer faceted search when the current learning carries a specific tags: or category: value — facet filters cut noise before grep runs and keep related-doc lookups focused:

# Faceted (preferred when the learning has a tag or category)
soleur:kb-search --tag eager-loading
soleur:kb-search --category performance-issues n+1

Fall back to raw grep when no facet fits or the facet artifact is missing:

# Keyword grep (fallback)
grep -r "exact error phrase" knowledge-base/project/learnings/

# Symptom category browse
ls knowledge-base/project/learnings/[category]/

Valid tag/category values are listed in knowledge-base/kb-tags.txt and knowledge-base/kb-categories.txt. Both are untracked caches (ADR-235) and may be absent on a fresh checkout — run bash scripts/ensure-kb-index.sh --soft first, which regenerates them only when stale and prints nothing when fresh.

IF similar issue found:

Headless mode: Auto-select "Create new doc with cross-reference" without prompting.

Interactive mode: Present decision options:

Found similar issue: knowledge-base/project/learnings/[path]

What's next?
1. Create new doc with cross-reference (recommended)
2. Update existing doc (only if same root cause)
3. Other

Choose (1-3): _

WAIT for user response, then execute chosen action.

ELSE (no similar issue found):

Proceed directly to Step 4 (no user interaction needed).

</step>

<step number="4" required="true" depends_on="2">

Step 4: Generate Filename

Format: [sanitized-symptom]-[module]-[YYYYMMDD].md

Sanitization rules:

Examples:

</step>

<step number="5" required="true" depends_on="4" blocking="true">

Step 5: Validate YAML Schema

CRITICAL: All docs require validated YAML frontmatter with enum validation.

<validation_gate name="yaml-schema" blocking="true">

Validate against schema:

Load schema.yaml and classify the problem against the enum values defined in yaml-schema.md. Ensure all required fields are present and match allowed values exactly.

BLOCK if validation fails:

❌ YAML validation failed

Errors:
- problem_type: must be one of schema enums, got "compilation_error"
- severity: must be one of [critical, high, medium, low], got "invalid"
- symptoms: must be array with 1-5 items, got string

Please provide corrected values.

GATE ENFORCEMENT: Do NOT proceed to Step 6 (Create Documentation) until YAML frontmatter passes all validation rules defined in schema.yaml.

Headless mode exception: If HEADLESS_MODE=true and YAML validation fails after auto-correction attempts, skip the problematic learning and continue with remaining work. Log the skipped learning for manual review.

</validation_gate>

</step>

<step number="6" required="true" depends_on="5">

Step 6: Create Documentation

Determine category from problem_type: Use the category mapping defined in yaml-schema.md (lines 49-61).

Create documentation file:

Determine the category from the validated YAML problem_type field and generate a filename. Then:

  1. Create the category directory: mkdir -p knowledge-base/project/learnings/<category>
  2. Write the documentation file to knowledge-base/project/learnings/<category>/<filename>.md using the template from resolution-template.md

Replace <category> with the mapped category and <filename> with the generated filename.

Result:

Create documentation: Populate the structure from resolution-template.md with context gathered in Step 2 and validated YAML frontmatter from Step 5.

</step>

<step number="7" required="false" depends_on="6">

Step 7: Cross-Reference & Required-Reading Detection

If similar issues found in Step 3:

Update existing doc:

Append a "See also" cross-reference link to the similar document, using the new document's filename and path.

Update new doc:

Already includes cross-reference from Step 6.

Update patterns if applicable:

If this repo keeps knowledge-base/project/patterns/: extend an existing page, or note it for a new page once 5 or more learnings share the class (a page needs 5+ evidence entries, so one learning cannot create one). Structure pages with pattern-page-template.md. A pattern page is added or extended by a reviewed PR, never written directly. Otherwise emit one line: skipped: no patterns directory.

Required-Reading Detection (Optional Proactive Suggestion):

If this issue has automatic indicators suggesting it might be critical:

Then in the decision menu, add a note:

💡 This might be worth adding to Required Reading (Option 2)

But NEVER auto-promote. User decides via decision menu (Option 2).

Required-reading entries:

When user selects Option 2, propose a pattern page with required_reading: true. In a repo without a patterns directory, append the entry to knowledge-base/project/learnings/patterns/required-reading.md.

</step>

<step number="8" required="false" depends_on="6">

Step 8: Route Learning to Definition

After capturing and cross-referencing the learning, route the insight to the skill, agent, or command definition that needs it. This ensures definitions improve over time with sharp-edge gotchas that prevent repeated mistakes.

Skip this step if:

<!-- markdownlint-disable-next-line MD001 -- h4 under h3 is correct; linter resets at <step> tags -->

8.1 Detect Active Components

Identify which skills, agents, or commands were invoked in this session by examining the conversation history.

Map detected component names to file paths:

If no components detected, skip to the decision menu.

If the learning is about what a word means — the session settled, sharpened or disputed an internal term — the target is not a component definition: invoke soleur:kb-glossary and route it to knowledge-base/project/glossary.md as a pointer to the file that settles the term, then continue with any component insight that remains.

8.2 Select Target

If one component detected: propose it as the routing target.

If multiple detected: use AskUserQuestion to present a numbered list ordered by relevance to the learning content. Include an option to skip.

Headless mode: If HEADLESS_MODE=true and multiple components detected, select the component most relevant to the learning content using LLM judgment. If one component detected, use it. Do not prompt.

If the target file does not exist at the expected path, warn and skip.

8.3 Propose Edit

Route two categories of insights to each target:

A. Solution insight (the main learning):

  1. Read the target definition file
  2. Find the most relevant existing section for a new bullet -- do not create new sections
  3. If no section with bullets exists in the target file, warn and skip this target
  4. Draft a one-line bullet capturing the sharp edge -- non-obvious gotcha only, skip if the insight is general knowledge the model already knows
  5. Display the proposed edit showing the section name, existing bullets, and the new bullet

B. Error prevention (from session errors):

  1. Check the learning file's ## Session Errors section. For each error with a **Prevention:** line, determine if the error could have been prevented by a skill instruction in the target definition.
  2. If yes, draft a one-line bullet for the target's Sharp Edges or equivalent section (e.g., "Verify relative paths by tracing each ../ step before prescribing them in plans.").
  3. If the target has no section suitable for preventive bullets, skip.
  4. Display the proposed edit alongside the solution edit.

This dual-routing ensures session errors feed back into the definitions that caused them, not just the learning archive.

8.4 Apply

Gated-block guard (proposer-agnostic eval gate). Before applying, run node plugins/soleur/skills/eval-harness/scripts/eval-gate.cjs --check <target-file>. If gated:false, apply normally. If gated:true, you MUST run the gate for the proposed edit — do NOT eyeball whether the classifier block changed and assume accept. Write the proposed-edited file to a temp path and run eval-gate.cjs --candidate-file <tmp> --target <target> --target-task <synthesized row>: the SCRIPT (not the agent) decides the identical-block short-circuit (when Step 8.3's bullet lands outside the soleur:go routing table / triage rubric block — the common case — the script extracts an identical block and returns accept with no API spend; when the block did change, the script runs promptfoo and computes the verdict in verdict.cjs). Then follow heal-skill step 6.0 (buffer pre-check → accept-applies / reject-logs-to-.claude/.skill-edit-rejections.jsonl-and-does-NOT-stamp-synced_to). Headless (HEADLESS_MODE=true) — fail CLOSED: if the gate did not run to an accept:true (e.g. unattended, to avoid spending the gate's API budget), DO NOT apply the gated-block edit — DEFER it (record a one-line deferred note; the edit is preserved in the learning context and re-attempted interactively; the #5703 CI backstop re-asserts at PR time). Fail-closed on any gate error. The gate validates a prose-rule change to a classifier surface only; it never displaces a deterministic hook fix.

Apply the proposed edit to the definition file. Filing a GitHub issue is NOT an option in either mode -- the backlog-growth pressure that produced 22 stale compound: route-to-definition proposal issues by 2026-05 is the original problem this step exists to avoid. If Step 8.3 produced a draft, it has already cleared the "skip if no suitable section / insight is general knowledge" gate; that gate is the only safety hatch.

Headless mode (HEADLESS_MODE=true): Before writing, assert the resolved target path is prefixed by plugins/soleur/skills/, plugins/soleur/agents/, or plugins/soleur/commands/ — refuse otherwise. Then write the edit to the target file directly without prompting. The prefix check enforces hr-write-boundary-sentinel-sweep-all-write-sites for this new write surface; the Step 8.1 path map is the implicit allowlist, this assertion makes it explicit.

Interactive mode: Use AskUserQuestion with options:

In both modes, after writing the edit, update the learning file's synced_to frontmatter to prevent soleur:sync from re-proposing this pair:

Do NOT commit -- the edits are staged for the normal workflow completion protocol.

</step>

</critical_sequence>


Automatic Consolidation (feature branches)

After documentation is complete and before the decision menu, automatically consolidate and archive KB artifacts on feature branches. This replaces the former manual Option 2 in the decision menu.

Branch detection:

Run git branch --show-current to get the current branch. If it does not start with feat-, feat/, fix-, or fix/, skip consolidation entirely.

If on a feature branch (feat-*, feat/*, fix-*, or fix/*), run the following steps automatically:

Auto-Consolidation Step A: Artifact Discovery

Extract the slug from the current branch name by stripping the branch type prefix. Handle all prefix variants:

Glob for related artifacts:

Search for artifacts matching the feature slug. Replace <slug> with the actual feature slug derived from the branch name:

find knowledge-base/project/brainstorms/ -name "*<slug>*" -not -path "*/archive/*" 2>/dev/null
find knowledge-base/project/plans/ -name "*<slug>*" -not -path "*/archive/*" 2>/dev/null
test -d "knowledge-base/project/specs/feat-<slug>" && echo "knowledge-base/project/specs/feat-<slug>/"

If no artifacts found: Skip consolidation silently and proceed to the decision menu.

If artifacts found: Present the discovered list:

Found artifacts for feat-<slug>:

1. knowledge-base/project/brainstorms/2026-02-09-<slug>-brainstorm.md
2. knowledge-base/project/plans/2026-02-09-feat-<slug>-plan.md
3. knowledge-base/project/specs/feat-<slug>/

Proceed with consolidation? (Y/n/add more)

Replace <slug> with the actual feature slug throughout.

If user selects "add more," prompt for additional file paths and append to the list.

Auto-Consolidation Step B: Knowledge Extraction

A single agent reads ALL discovered artifacts and proposes updates to:

The agent produces proposals as structured markdown blocks. Each proposal specifies:

Auto-Consolidation Step C: Approval Flow

Present proposals one at a time:

Proposal 1 of N:

Target: knowledge-base/project/constitution.md
Section: Architecture > Always
Content:
- Archive completed feature artifacts after consolidation to prevent knowledge-base bloat

Accept / Skip / Edit? _

Accept: Apply the proposal immediately (see Step D).

Skip: Move to the next proposal. The skipped content is not applied.

Edit: User provides corrected text. Re-display the edited proposal for Accept/Skip.

Idempotency check: Before applying, perform a simple substring check against the target file. If similar content already exists, flag it:

Similar content found in constitution.md:
  "Archive outdated learnings to knowledge-base/project/learnings/archive/"

Still apply this proposal? (Y/n)

Auto-Consolidation Step D: Apply Accepted Proposals

Apply each accepted proposal immediately after approval:

Auto-Consolidation Step E: Archival

Archive ALL discovered artifacts regardless of how many proposals were accepted or skipped.

Run the archival script from the repository root:

bash "${CLAUDE_PLUGIN_ROOT}/skills/archive-kb/scripts/archive-kb.sh"

The script discovers artifacts matching the current branch's feature slug, creates archive directories, and moves each artifact with a timestamped prefix using git mv. It handles untracked files automatically. If the script exits non-zero, display the error and stop -- do not proceed to Step F.

Context-aware archival confirmation:

Headless mode: Auto-archive without prompting (equivalent to answering "Y").

Interactive mode:

If at least one proposal was accepted:

Overview files updated. Archive the source artifacts? (Y/n)

If all proposals were skipped:

No project updates applied. Still archive the source artifacts? (Y/n)

Auto-Consolidation Step F: Commit

All changes (project edits + archival moves) go into a single commit:

git add -A knowledge-base/
git commit -m "compound: consolidate and archive feat-<slug> artifacts"

Replace <slug> with the actual feature slug.

This ensures git revert restores everything in one operation.

After commit, proceed to the decision menu.


<decision_gate name="post-documentation" wait_for_user="true">

Decision Menu After Capture

Headless mode: If HEADLESS_MODE=true, auto-select "Continue workflow" without presenting the menu.

Interactive mode: After successful documentation, present options and WAIT for user response:

✓ Solution documented

File created:
- knowledge-base/project/learnings/[category]/[filename].md

What's next?
1. Continue workflow (recommended)
2. Add to Required Reading - Propose a pattern page (`required_reading: true`)
3. Link related issues - Connect to similar problems
4. Add to existing skill - Add to a learning skill (e.g., hotwire-native)
5. Create new skill - Extract into new learning skill
6. View documentation - See what was captured
7. Other

Note: Consolidation and archival of KB artifacts now runs automatically before this menu on feat-* branches. See "Automatic Consolidation" section above.

Handle responses:

Option 1: Continue workflow

Option 2: Add to Required Reading ⭐ PRIMARY PATH FOR CRITICAL PATTERNS

User selects this when:

Action:

  1. Extract pattern from the documentation
  2. Fill the template sections (root cause, fix with a short wrong-versus-correct example, evidence)
  3. Write the pattern page with required_reading: true (or, without a patterns directory, append the entry to knowledge-base/project/learnings/patterns/required-reading.md)
  4. Add cross-reference back to this doc
  5. Only after step 3 wrote the entry or page: confirm "✓ Required-reading entry proposed."

Option 3: Link related issues

Option 4: Add to existing skill

User selects this when the documented solution relates to an existing learning skill:

Action:

  1. Prompt: "Which skill? (hotwire-native, etc.)"
  2. Determine which reference file to update (resources.md, patterns.md, or examples.md)
  3. Add link and brief description to appropriate section
  4. Confirm: "✓ Added to [skill-name] skill in [file]"

Example: For Hotwire Native Tailwind variants solution:

Option 5: Create new skill

User selects this when the solution represents the start of a new learning domain:

Action:

  1. Prompt: "What should the new skill be called? (e.g., stripe-billing, email-processing)"
  2. Run python3 "${CLAUDE_PLUGIN_ROOT}/skills/skill-creator/scripts/init_skill.py" [skill-name]
  3. Create initial reference files with this solution as first example
  4. Confirm: "✓ Created new [skill-name] skill with this solution as first example"

Option 6: View documentation

Option 7: Other

</decision_gate>


<integration_protocol>

Integration Points

Invoked by:

Invokes:

Handoff expectations:

All context needed for documentation should be present in conversation history before invocation.

</integration_protocol>


<success_criteria>

Success Criteria

Documentation is successful when ALL of the following are true:

</success_criteria>


Error Handling

Missing context:

YAML validation failure:

Similar issue ambiguity:

Module not in modules documentation:


Execution Guidelines

MUST do:

MUST NOT do:


Quality Guidelines

Good documentation has:

Avoid:


Example Scenario

User: "That worked! The N+1 query is fixed."

Skill activates:

  1. Detect confirmation: "That worked!" triggers auto-invoke
  2. Gather context:
  1. Check existing: No similar issue found
  2. Generate filename: n-plus-one-brief-generation-BriefSystem-20251110.md
  3. Validate YAML:

```yaml

module: Brief System

date: 2025-11-10

problem_type: performance_issue

component: rails_model

symptoms:

root_cause: missing_include

severity: high

tags: [n-plus-one, eager-loading, performance]

```

✅ Valid

  1. Create documentation:
  1. Cross-reference: None needed (no similar issues)

Output:

✓ Solution documented

File created:
- knowledge-base/project/learnings/performance-issues/n-plus-one-brief-generation-BriefSystem-20251110.md

What's next?
1. Continue workflow (recommended)
2. Add to Required Reading - Propose a pattern page (`required_reading: true`)
3. Link related issues - Connect to similar problems
4. Add to existing skill - Add to a learning skill (e.g., hotwire-native)
5. Create new skill - Extract into new learning skill
6. View documentation - See what was captured
7. Other

Future Enhancements

Not in Phase 7 scope, but potential:

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.