Per-repo LSP profiles in Nix flakes

Define language servers, versions, and settings pinned per repo in flake.nix.

Benefits:
- Claude Code LSP becomes deterministic across machines/CI
- CI can run headless LSP diagnostics as first-class check
- Ephemeral LS sandboxes for experimental refactors

Example: pin rust-analyzer version per project to avoid skill breakage.


Update orch skill to match CLI v0.1.0

The orch skill (in ~/.claude/skills/orch/) is out of sync with the orch CLI.

Needed updates:
- Fix model aliases: gpt-5 → gpt-5.2, claude-opus-4.1 → claude-opus-4.5
- Add new aliases: deepseek, r1, qwen, qwen-fast, glm, sonar, sonar-pro
- Document --synthesize flag for response aggregation
- Document stdin piping support
- Document orch models command
- Document orch sessions command
- Add --websearch, --serial, --allow-expensive options

Reference: ~/proj/orch/README.md and src/orch/models_registry.py

Updated skill with current CLI features and model aliases


spec-review: Define output capture and audit trail

Reviews happen in terminal then disappear. No audit trail, no diffable history.

Add:
- Guidance to tee output to review file (e.g., specs/{branch}/review.md)
- Standard location for gate check results
- Template for recording decisions and rationale


Evaluate: jwz for transient agent state

Evaluate jwz as complement to beads for agent coordination.

## Current Understanding
- beads: persistent issues (multi-session, dependencies)
- jwz: transient messages (session coordination, async)

## Questions to Answer
1. Does jwz add value beyond what beads provides?
2. Is the Zig dependency acceptable?
3. Can we achieve same with simpler file-based approach?
4. How does jwz handle multi-repo coordination?

## Evaluation Criteria
- Complexity vs benefit
- Cross-agent compatibility
- Git integration quality
- Maintenance burden

## Deliverable
Recommendation: adopt jwz, build alternative, or extend beads


Consolidate: Merge overlapping cross-agent design tasks

Merge overlapping research/design tasks into coherent work items.

## Current Overlap
- skills-3gk: Research: Cross-agent hook alternatives
- skills-3ja: Design: Cross-agent quality gate architecture
- skills-thk: Design: Hybrid hook + gate architecture
- skills-6fu: Research: State management for cross-agent workflows

These all touch the same problem space.

## Proposed Consolidation
1. Close overlapping tasks with "consolidated" reason
2. Create single "Design: Cross-agent enforcement architecture" task
3. Update epic description to reference consolidated task

## Deliverable
Clean task list with no duplication

Created skills-8sj, closed 4 overlapping tasks


Ensure git access to both local Forgejo and ops-jrz1 Forgejo

Need reliable access to both git servers for plugin development and deployment:

**Local Forgejo (home):**
- URL: http://192.168.1.108:3000
- Currently down/unreachable at times
- Used for skills repo remote

**ops-jrz1 Forgejo (VPS):**
- URL: https://git.clarun.xyz
- Production server
- Target for emes plugin deployment

**Tasks:**
- Verify local Forgejo is running (systemctl status)
- Add ops-jrz1 as additional remote for skills repo
- Consider mirroring skills repo to both
- Document which forge is source of truth

Multi-push configured: origin pushes to both local and clarun Forgejos


Brainstorm agent-friendly doc conventions

# Agent-Friendly Doc Conventions - Hybrid Architecture

## FINAL ARCHITECTURE: Vale + LLM Hybrid

### Insight
> "Good old deterministic testing (dumb robots) is the best way to keep in check LLMs (smart robots) at volume."

### Split by Tool

| Category | Rubrics | Tool |
|----------|---------|------|
| Vale-only | Format Integrity, Deterministic Instructions, Terminology Strictness, Token Efficiency | Fast, deterministic, CI-friendly |
| Vale + LLM | Semantic Headings, Configuration Precision, Security Boundaries | Vale flags, LLM suggests fixes |
| LLM-only | Contextual Independence, Code Executability, Execution Verification | Semantic understanding required |

### Pipeline

```
┌─────────────────────────────────────────────────────────────┐
│ Stage 1: Vale (deterministic, fast, free)                   │
│ - Runs in CI on every commit                                │
│ - Catches 40% of issues instantly                           │
│ - No LLM cost for clean docs                                │
└─────────────────────┬───────────────────────────────────────┘
                      │ only if Vale passes
                      ▼
┌─────────────────────────────────────────────────────────────┐
│ Stage 2: LLM Triage (cheap model)                           │
│ - Evaluates 3 semantic rubrics                              │
│ - Identifies which need patches                             │
└─────────────────────┬───────────────────────────────────────┘
                      │ only if issues found
                      ▼
┌─────────────────────────────────────────────────────────────┐
│ Stage 3: LLM Specialists (capable model)                    │
│ - One agent per failed rubric                               │
│ - Generates patches                                         │
└─────────────────────────────────────────────────────────────┘
```

### Why This Works
- Vale is battle-tested, fast, CI-native
- LLM only fires when needed (adaptive cost)
- Deterministic rules catch predictable issues
- LLM handles semantic/contextual issues

---

## Vale Rules Needed

### Format Integrity
- Existence: code blocks without language tags
- Regex for unclosed fences

### Deterministic Instructions
- Existence: hedging words ("might", "may want to", "consider", "you could")

### Terminology Strictness
- Consistency: flag term variations

### Token Efficiency
- Existence: filler phrases ("In this section we will...", "As you may know...")

### Semantic Headings (partial)
- Existence: banned headings ("Overview", "Introduction", "Getting Started")

### Configuration Precision (partial)
- Existence: vague versions ("Python 3.x", "recent version")

### Security Boundaries (partial)
- Existence: hardcoded API key patterns

---

## NEXT STEPS

1. Create Vale style for doc-review rubrics
2. Test Vale on sample docs
3. Design LLM prompts for semantic rubrics only
4. Wire into orch or standalone


Dual-publish pattern: Convert remaining skills

Convert skills to dual-publish pattern (Nix + Claude plugin):

**Pattern established with orch:**
- Keep SKILL.md at root (Nix deployment)
- Add .claude-plugin/plugin.json (Claude marketplace)
- Copy to skills/<name>.md (Claude auto-discovery)

**Skills to convert:**
- [ ] worklog
- [ ] code-review (has lenses dependency)
- [ ] ops-review (has lenses dependency)
- [ ] playwright-visit
- [ ] screenshot-latest
- [ ] niri-window-capture
- [ ] web-search
- [ ] web-research

**Why dual-publish:**
- Cross-agent support (Gemini, OpenCode can't use Claude plugins)
- Nix provides system-level deployment
- Claude plugin system provides hooks, marketplace discovery
- See skills-bo8 for Gemini path restriction issue

All 16 skills converted to dual-publish pattern


Set up agent skills for Gemini CLI

The AI agent skills (worklog, web-search, etc.) configured in .skills are not currently working when using the Gemini CLI. \n\nObserved behavior:\n- 'worklog' command not found even after 'direnv reload'.\n- .envrc sources ~/proj/skills/bin/use-skills.sh, but skills are not accessible in the Gemini agent session.\n\nNeed to:\n1. Investigate how Gemini CLI loads its environment compared to Claude Code.\n2. Update 'use-skills.sh' or direnv configuration to support Gemini CLI.\n3. Ensure skill symlinks/binaries are correctly in the PATH for Gemini.

No MCP/extensions. Gemini CLI lacks native skill support (feature request #11506 pending). Current workaround: GEMINI.md references skill paths for manual reading. Revisit when native support lands.


Compare BOUNDARIES.md with upstream


Create orch skill for multi-model consensus

Build a skill that exposes orch CLI capabilities to agents for querying multiple AI models


Define agent autonomy policy for skills

Disagreement in consensus:

GPT: Stricter determinism to prevent 'agent drift'
Gemini: skill: should be a hint, agent can deviate if skill fails

Options:
1. Constraint (must use skill, fail if broken)
2. Heuristic (should use, can justify deviation)
3. Configurable per-proto or per-step

UX consideration: agents stuck in loops trying broken skills.

Needs decision before widespread adoption.

Parked: waiting on gastown (Steve Yegge's orchestration layer for beads). Revisit when gastown lands.


Reframe elevation as scaffolding

Elevation pipeline is over-optimistic. Auto-generation will produce garbage.

Reframe:
- Rename to 'Pattern Extraction' or 'Skill Drafting'
- Output is skeleton/scaffold, not complete skill
- Require N>=3 similar executions before suggesting
- Generate promotion checklist:
  - Preconditions
  - Inputs/outputs contract
  - Failure modes observed
  - Determinism score
- Generate tests as part of elevation

Human-in-the-loop is mandatory, not optional.

From consensus: both models flagged as medium severity.

Parked with ADR-001: skills-molecules integration deferred. Current simpler approach (skills as standalone) works well. Revisit when complex orchestration needed.


Add README.md for web-search skill

web-search skill has SKILL.md and scripts but no README.md. AGENTS.md says README.md is for humans, contains installation instructions, usage examples, prerequisites.

Added README.md with prerequisites, usage examples, and cross-references


RFC: .skills manifest pattern for per-repo skill deployment

Document the .skills file pattern where projects declare skills in a manifest, .envrc reads it, and agents can query/edit it.


Prototype elevation pipeline

Build pipeline: successful molecule → skill draft
1. On molecule close, option to 'elevate'
2. Analyze squashed trace
3. Extract generalizable pattern
4. Generate SKILL.md draft
5. Human approval gate

Start simple: script that takes squashed molecule ID and outputs draft SKILL.md

Migrated from dotfiles-2p2.


Research: Cross-agent hook alternatives

Claude Code has hooks (Stop, SessionStart, etc.) for mechanical enforcement. Other agents don't.

Research alternatives for cross-agent quality gates:

1. **External wrapper** - Script that launches agent, monitors output, gates exit
2. **Protocol-based** - Agent follows instructions in AGENTS.md, posts to state store
3. **Orchestrator pattern** - Meta-agent spawns worker + reviewer, enforces gate
4. **Hybrid** - Hooks where available, protocol elsewhere

Evaluate:
- Enforcement strength (mechanical vs cooperative)
- Implementation complexity
- Agent compatibility
- Failure modes

Output: Comparison doc with recommendation


Design: Cross-agent quality gate architecture

Design a quality gate pattern that works regardless of agent.

Requirements:
- Worker agent can be Claude, Gemini, OpenCode, etc.
- Reviewer agent can be any capable model
- Gate blocks completion until reviewer approves
- Circuit breakers prevent infinite loops
- Works in autonomous/unattended scenarios

Building on alice/idle research (docs/research/idle-alice-quality-gate.md):
- alice uses Claude hooks + jwz state
- We need agent-agnostic equivalent

Considerations:
- State management: jwz vs beads vs simple files
- Enforcement: mechanical vs protocol-based
- Reviewer selection: orch consensus vs single model
- Activation: opt-in prefix vs context-based

Output: Architecture doc with component design


Fix ai-skills.nix missing sha256 hash

modules/ai-skills.nix:16 has empty sha256 placeholder for opencode-skills npm package. Either get actual hash or remove/comment out the incomplete fetchFromNpm approach.


Reframe: Epic around abstract layers (not tools)

Reframe skills-hf1 epic around concepts, not implementations.

## Abstract Layers

| Layer | Concept | Purpose |
|-------|---------|---------|
| **Message Passing** | Async agent coordination | Session handoffs, status updates |
| **Memory** | Persistent work items | Issues, dependencies, review state |
| **Enforcement** | Quality gates | Block completion until approved |

## Current Problem
Epic references specific tools (jwz, beads, hooks) rather than concepts.
Makes it hard to swap implementations.

## Proposed Changes
1. Update epic description with layer abstractions
2. Define interface requirements for each layer
3. Note current implementations as examples, not requirements

## Deliverable
Updated epic with tool-agnostic framing

Epic skills-hf1 reframed around abstract layers


spec-review: Expand NFR checklist in prompts

Current prompts mention 'performance, security, accessibility' but miss many critical NFRs.

Expand to include:
- Security (authn/authz, secrets, threat model)
- Privacy/compliance (GDPR, PII)
- Observability (logging, metrics, tracing)
- Reliability (SLOs, failure modes)
- Rollout/rollback strategy
- Migration/backfill
- Data retention/lifecycle
- Cost constraints


Skills + Molecules Integration

Integrate skills system with beads molecules.

Key concepts from consensus brainstorm:
1. Skills = procedural knowledge (HOW), Molecules = work tracking (WHAT)
2. Link via skill: field in molecule nodes
3. Wisps as execution traces for debugging/replay
4. Elevation pipeline: successful molecule → auto-generate skill draft
5. Skills as transition middleware (on_enter/on_exit hooks)

Implementation phases:
- Phase 1: Document findings (ADR)
- Phase 2: Wisp execution trace format
- Phase 3: Elevation pipeline prototype
- Phase 4: Test on real skill (worklog)

Migrated from dotfiles-jjb.


Decide on screenshot-latest skill deployment

DEPLOYED.md shows screenshot-latest as 'Not yet deployed - Pending decision'. Low risk skill that finds existing files. Need to decide whether to deploy or archive.

Decided to deploy - low risk, useful for avoiding path typing. Added to dotfiles claude.nix.


Design graph-based doc discovery

How does doc-review find and traverse documentation?

Approach: Start from README.md or AGENTS.md, graph out from there.

Design questions:
- Parse markdown links to find related docs?
- Follow only relative links or also section references?
- How to handle circular references?
- Depth limit or exhaustive traversal?
- What about orphan docs not linked from root?
- How to represent the graph for chunking decisions?

Considerations:
- Large repos may have hundreds of markdown files
- Not all .md files are "documentation" (changelogs, templates, etc.)
- Some docs are generated and shouldn't be patched

Deliverable: Algorithm/pseudocode for doc discovery + chunking strategy.


spec-review: Add Prerequisites section documenting dependencies

SKILL.md and process docs assume orch is installed, prompt files exist, models are available, but none of this is documented.

Add:
- orch install instructions/link
- Required env vars and model availability
- Prompt file locations
- Expected repo structure (specs/ convention)
- Troubleshooting section for common failures


Document beads vs tissue split during emes testing

During emes testing on ops-jrz1:
- Local dev: beads (skills repo, dotfiles, etc.)
- ops-jrz1: tissue (emes ecosystem testing)

Need to document:
- Which tracker for which repos
- How to context-switch mentally
- Whether to bridge or keep separate
- Exit criteria: when do we converge?

Superseded by abstract layer approach - memory layer abstracts beads/tissue


LSP diagnostic harvest → auto-create beads

Periodic/nightly headless LSP scan that:
- Gathers diagnostics (unused vars, type errors, deprecations, lint warnings)
- Groups by subsystem/module
- Auto-creates beads with severity thresholds
- Enables 'refactor quests' - parent bead with children per symbol

Run via CI or cron, feed results back into beads automatically.


Replace SKILL.md with upstream version

Upstream has 644 lines vs our 122. Missing: self-test questions, notes quality checks, token checkpointing, database selection, field usage table, lifecycle workflow, common patterns, troubleshooting


spec-review: Add context/assumptions step to prompts

Reviews can become speculative without establishing context first.

Add to prompts:
- List assumptions being made
- Distinguish: missing from doc vs implied vs out of scope
- Ask clarifying questions if critical context missing


Create ui-query skill for AT-SPI integration

Create a skill that provides programmatic UI tree access via AT-SPI.

## Context
AT-SPI is now enabled in dotfiles (services.gnome.at-spi2-core + QT_LINUX_ACCESSIBILITY_ALWAYS_ON).
This complements niri-window-capture (visual) with semantic UI data.

## Capabilities
- Read text from GTK/Qt widgets directly (no OCR)
- Find UI elements by role (button, text-field, menu)
- Query element states (focused, enabled, checked)
- Get element positions for potential input simulation
- Navigate parent/child relationships

## Suggested structure
skills/ui-query/
├── SKILL.md
├── scripts/
│   ├── list-windows.py      # Windows with AT-SPI info
│   ├── get-text.py          # Extract text from window/element
│   ├── find-element.py      # Find by role/name
│   └── query-state.py       # Element states
└── README.md

## Notes
- Start simple: list windows, get text
- pyatspi available via python3Packages.pyatspi
- Use accerciser (now installed) to explore the tree


Searchable Claude Code conversation history

## Context
Claude Code persists full conversations in `~/.claude/projects/<project>/<uuid>.jsonl`. This is complete but not searchable - can't easily find "that session where we solved X".

## Goal
Make conversation history searchable without requiring manual worklogs.

## Approach

### Index structure
```
~/.claude/projects/<project>/
  <uuid>.jsonl           # raw conversation (existing)
  index.jsonl            # session metadata + summaries (new)
```

### Index entry format
```json
{
  "uuid": "f9a4c161-...",
  "date": "2025-12-17",
  "project": "/home/dan/proj/skills",
  "summary": "Explored Wayland desktop automation, AT-SPI investigation, vision model benchmark",
  "keywords": ["wayland", "niri", "at-spi", "automation", "seeing-problem"],
  "commits": ["906f2bc", "0b97155"],
  "duration_minutes": 90,
  "message_count": 409
}
```

### Features needed
1. **Index builder** - Parse JSONL, extract/generate summary + keywords
2. **Search CLI** - `claude-search "AT-SPI wayland"` → matching sessions
3. **Auto-index hook** - Update index on session end or compaction

## Questions
- Generate summaries via AI or extract heuristically?
- Index per-project or global?
- How to handle very long sessions (multiple topics)?

## Value
- Find past solutions without remembering dates
- Model reflection: include relevant past sessions in context
- Replace manual worklogs with auto-generated metadata

Prototype complete: bin/claude-search indexes 122 sessions, searches by keyword. Future: auto-index hook, full-text search, keyword extraction.


Research: State management for cross-agent workflows

Evaluate state management options for cross-agent coordination.

Options:
1. **jwz** - emes tool, append-only JSONL, git-mergeable, Zig
2. **beads** - Our tool, graph-based issues, Rust
3. **Simple files** - JSON/JSONL in .state/ directory
4. **Environment variables** - Ephemeral session state

Criteria:
- Cross-agent access (all can read/write via CLI)
- Git compatibility (mergeable, not conflicting)
- Persistence (session vs permanent)
- Query capability (search, filter)
- Complexity (dependencies, setup)

Context:
- beads for persistent issues/work
- jwz for transient session coordination
- May need both for different purposes

Output: Recommendation on state management strategy


Add artifact provenance to traces

Current: files_created lists paths only.
Problem: Can't detect regressions or validate outputs.

Add:
- Content hash (sha256)
- File size
- For modifications: git_diff_summary (files changed, line counts)

Example:
  outputs:
    artifacts:
      - path: docs/worklogs/...
        sha256: abc123...
        size: 1234
        action: created|modified

Enables: diff traces, regression testing, validation.


spec-review: Add severity labeling to prompts and reviews

Reviews produce flat lists mixing blockers with minor nits. Hard to make decisions.

Add to prompts:
- Require severity labels: Blocker / High / Medium / Low
- Sort output by severity
- Include impact and likelihood for each issue


Epic: emes plugin architecture alignment

Convert skills to emes-style plugin architecture for portability across Claude Code, Gemini, and VPS deployment (ops-jrz1).

**emes tools (evil-mind-evil-sword org):**
- tissue: Git-native issue tracking (machine-first)
- idle: Quality gate (blocks exit until reviewer approves)
- jwz: Async messaging with identity/git context
- marketplace: Plugin distribution registry

**Conversion work:**
1. Add .claude-plugin/plugin.json to each skill
2. Restructure: SKILL.md → skills/<name>.md (auto-discovery)
3. Add hooks/ where applicable (quality gates)
4. Create marketplace.json registry
5. Test with ops-jrz1 deployment

**Key principles from emes:**
- Pull context on-demand (not big upfront injections)
- Mechanical enforcement via hooks (not prompts)
- References over inline content
- Machine-first interfaces (JSON output)

**Candidates for conversion:**
- orch (simple CLI wrapper)
- worklog (scripts + templates)
- code-review (has lenses, might want hooks)
- ops-review (same pattern)

Dual-publish complete. Ongoing cross-agent work continues under skills-hf1


Add atomic file operations to update scripts

Files affected:
- skills/update-opencode/scripts/update-nix-file.sh
- .specify/scripts/bash/update-agent-context.sh

Issues:
- Uses sed -i which can corrupt on error
- No rollback mechanism despite creating backups
- Unsafe regex patterns with complex escaping

Fix:
- Write to temp file, then atomic mv
- Validate output before replacing original
- Add rollback on failure

Severity: MEDIUM

Implemented atomic updates using temp files and traps in update-nix-file.sh, update-agent-context.sh, and deploy-skill.sh. Added validation before replacing original files.


Compare STATIC_DATA.md with upstream


Set up bd-issue-tracking Claude Code skill from beads repo

Install the beads Claude Code skill from https://github.com/steveyegge/beads/tree/main/examples/claude-code-skill

This skill teaches Claude how to effectively use beads for issue tracking across multi-session coding workflows. It provides strategic guidance on when/how to use beads, not just command syntax.

Files to install to ~/.claude/skills/bd-issue-tracking/:
- SKILL.md - Core workflow patterns and decision criteria
- BOUNDARIES.md - When to use beads vs markdown alternatives
- CLI_REFERENCE.md - Complete command documentation
- DEPENDENCIES.md - Relationship types and patterns
- WORKFLOWS.md - Step-by-step procedures
- ISSUE_CREATION.md - Quality guidelines
- RESUMABILITY.md - Making work resumable across sessions
- STATIC_DATA.md - Using beads as reference databases

Can symlink or copy the files. Restart Claude Code after install.


Remove dead code: unused ARGS variable

File: .specify/scripts/bash/create-new-feature.sh

Line 8: ARGS=() declared but never used
Line 251: export SPECIFY_FEATURE - unclear if used downstream

Fix:
- Remove unused ARGS declaration
- Verify SPECIFY_FEATURE is used or remove

Severity: LOW

Invalid: ARGS is used (line 58, 64). SPECIFY_FEATURE is used by common.sh for feature detection. No dead code.


Compare CLI_REFERENCE.md with upstream


Add conversational patterns to orch skill

## Context
The orch skill currently documents consensus and single-shot chat, but doesn't
teach agents how to use orch for multi-turn conversations with external AIs.

## Goal
Add documentation and patterns for agent-driven conversations where the calling
agent (Claude Code) orchestrates multi-turn dialogues using orch primitives.

## Patterns to document

### Session-based multi-turn
```bash
# Initial query
RESPONSE=$(orch chat "Analyze this" --model claude --format json)
SESSION=$(echo "$RESPONSE" | jq -r .session_id)

# Continue conversation
orch chat "Elaborate on X" --model claude --session $SESSION

# Inspect state
orch sessions info $SESSION
orch sessions show $SESSION --last 2 --format text
```

### Cross-model dialogue
```bash
# Get one model's take
CLAUDE=$(orch chat "Review this" --model claude --format json)
CLAUDE_SAYS=$(echo "$CLAUDE" | jq -r '.responses[0].content')

# Ask another model to respond
orch chat "Claude said: $CLAUDE_SAYS

What's your perspective?" --model gemini
```

### When to use conversations vs consensus
- Consensus: quick parallel opinions on a decision
- Conversation: deeper exploration, follow-up questions, iterative refinement

## Files
- skills/orch/SKILL.md

## Related
- orch-c3r: Design: Session introspection for agent-driven conversations (in orch repo)

Added conversational patterns section to orch SKILL.md: sessions, cross-model dialogue, iterative refinement, consensus vs chat guidance.


worklog skill: remove org-mode references, use markdown instead

The worklog skill currently references org-mode format (.org files) in the template and instructions. Update to use markdown (.md) instead:

1. Update ~/.claude/skills/worklog/templates/worklog-template.org → worklog-template.md
2. Convert org-mode syntax to markdown (#+TITLE → # Title, * → ##, etc.)
3. Update skill instructions to reference .md files
4. Update suggest-filename.sh to output .md extension

Context: org-mode is less widely supported than markdown in tooling and editors.

Migrated worklog skill from org-mode to markdown. Template, scripts, and SKILL.md updated. Backward compatible with existing .org files.


Fix: Gemini path restrictions for skills (skills-bo8)

Concrete fix for Gemini not reading ~/.claude/skills/.

## Problem
Gemini's ReadFile tool restricts to workspace directories.
Symlinked ~/.claude/skills/ is blocked.

## Options

### A: Copy skills into workspace
- Add skills/ to project repos
- Pro: Works immediately
- Con: Duplication, sync issues

### B: Shell workaround in skill
- Use \`cat\` instead of ReadFile
- Pro: No duplication
- Con: Fragile, skill must know about limitation

### C: Configure Gemini allowed paths
- Research if Gemini has path config
- Pro: Clean solution
- Con: May not exist

### D: MCP server for skills
- Skills exposed via MCP
- Pro: Agent-agnostic
- Con: Complexity, user said not interested in MCP

## Deliverable
Working solution for Gemini to read skills

Fix found: Gemini includeDirectories setting


Design: Cross-agent enforcement architecture

Unified design for cross-agent quality gates and coordination.

Consolidates: skills-3gk, skills-3ja, skills-thk, skills-6fu

## Abstract Layers

### 1. Message Passing Layer
- **Purpose:** Async agent coordination, session handoffs
- **Interface:** post(topic, message), read(topic), reply(id, message)
- **Requirements:** Append-only, git-mergeable, agent-attributed

### 2. Memory Layer
- **Purpose:** Persistent work items, review state
- **Interface:** create(issue), update(id, state), query(filters)
- **Requirements:** Cross-session, dependency tracking, searchable

### 3. Enforcement Layer
- **Purpose:** Quality gates, completion blocking
- **Interface:** check_gate(session) -> allow/block, register_reviewer(session)

## Enforcement Strategies

| Agent | Mechanism | Strength |
|-------|-----------|----------|
| Claude Code | Stop hook | Mechanical |
| Gemini CLI | Stop hook | Mechanical |
| OpenCode | Orchestrator | Protocol |
| Codex | Orchestrator | Protocol |
| Any | Wrapper script | External |

## State Schema

```
review_state:
  session_id: string
  status: pending | in_review | approved | rejected
  worker_agent: string
  reviewer_agent: string
  issues_found: [issue_ids]
  approved_at: timestamp
```

## Circuit Breakers
- Semantic drift detection
- Three-strike tool failures
- Budget/time limits

## Deliverables
1. Architecture diagram
2. Interface definitions
3. State schema
4. Hook configuration templates
5. Orchestrator flow pseudocode

Architecture design complete: docs/design/cross-agent-enforcement-architecture.md


Consolidate skill list definitions (flake.nix + ai-skills.nix)

Skill list duplicated in:
- flake.nix (lines 15-27)
- modules/ai-skills.nix (lines 8-18)

Issues:
- Manual sync required when adding skills
- No validation that referenced skills exist

Fix:
- Single source of truth for skill list
- Consider generating one from the other

Severity: MEDIUM

Created skills.nix as single source of truth for skill names and descriptions. Updated flake.nix and Home Manager module to use it.


Define skill versioning strategy

Git SHA alone is insufficient. Need tuple approach:

- skill_source_rev: git SHA (if available)
- skill_content_hash: hash of SKILL.md + scripts
- runtime_ref: flake.lock hash or Nix store path

Questions to resolve:
- Do Protos pin to versions (stable but maintenance) or float on latest (risky)?
- How to handle breaking changes in skills?
- Record in wisp trace vs proto definition?

From consensus: both models flagged versioning instability as high severity.

ADRs revised with orch consensus feedback


spec-review: Add spike/research task handling

Tasks like 'Investigate X' can linger without clear outcomes.

Add to REVIEW_TASKS:
- Flag research/spike tasks
- Require timebox and concrete outputs (decision record, prototype, risks)
- Pattern for handling unknowns


Investigate pre-compression hook for worklogs

## Revised Understanding

Claude Code already persists full conversation history in `~/.claude/projects/<project>/<session-id>.jsonl`. Pre-compact hooks aren't needed for data capture.

## Question
What's the ideal workflow for generating worklogs from session data?

## Options

### 1. Post-session script
- Run after exiting Claude Code
- Reads most recent session JSONL
- Generates worklog from conversation content
- Pro: Async, doesn't interrupt flow
- Con: May forget to run it

### 2. On-demand slash command
- `/worklog-from-session` or similar
- Reads current session's JSONL file
- Generates worklog with full context
- Pro: Explicit control
- Con: Still need to remember

### 3. Pre-compact reminder
- Hook prints reminder: "Consider running /worklog"
- Doesn't automate, just nudges
- Pro: Simple, non-intrusive
- Con: Easy to dismiss

### 4. Async batch processing
- Process old sessions whenever
- All data persists in JSONL files
- Pro: No urgency, can do later
- Con: Context may be stale

## Data Format
Session files contain:
- User messages with timestamp
- Assistant responses with model info
- Tool calls and results
- Git branch, cwd, version info

## Next Steps
- Decide preferred workflow
- Build script to parse session JSONL → worklog format

Pivoted: worklogs may be redundant given full conversation persistence. New approach: make conversations searchable directly.


ops-review skill

Multi-lens review skill for operational infrastructure (Nix, shell, Docker, CI/CD).

Based on code-review pattern with linter-first hybrid architecture.

## Phases
- Phase 1: Skeleton + Core Safety (secrets, shell-safety, blast-radius, privilege)
- Phase 2: Reliability (idempotency, supply-chain, observability)
- Phase 3: Architecture (nix-hygiene, resilience, orchestration)

## Design
See specs/ops-review/plan.md

## Success Criteria
- Review dotfiles/ and find real issues
- Review prox-setup/ and find real issues
- <10% false positive rate on Phase 1
- Quick mode <30s

All 10 lenses implemented with orch consensus. Testing delegated to target repos (dotfiles-je5, prox-setup-kqg).


Create skill skeleton

Create directory structure and base files:
- skills/ops-review/SKILL.md (workflow, modeled on code-review)
- skills/ops-review/README.md (user docs)
- skills/ops-review/lenses/README.md (lens index)

Blocks all lens work.

Created skeleton: SKILL.md, README.md, lenses/README.md


Lens: resilience

Create resilience.md lens for fault tolerance:
- Missing timeouts on network calls
- No retries with backoff
- Missing circuit breakers
- No graceful shutdown (SIGTERM)
- Missing resource limits

Boundary: Owns runtime tolerance, NOT change safety

Lens created with orch consensus: added health checks/liveness, DNS caching, storage/logging, retry safety warning


Lens: orchestration

Create orchestration.md lens for execution ordering:
- Unclear prerequisites
- Missing order documentation
- Circular dependencies
- Assumed prior state
- Implicit coupling

Most complex - needs cross-file context

Lens created with orch consensus: added shutdown ordering, CI/CD pipelines, job concurrency, thundering herd


Integration: flake.nix + ai-skills.nix

Add ops-review to deployment:
- Add to flake.nix availableSkills
- Update modules/ai-skills.nix for ops lens deployment
- Deploy to ~/.config/lenses/ops/

Added ops-review to flake.nix availableSkills, updated ai-skills.nix with description and lens deployment to ~/.config/lenses/ops/


Validation: test on dotfiles

Run Phase 1 lenses on ~/proj/dotfiles:
- Verify findings are real issues
- Check false positive rate <10%
- Document any needed lens refinements

Tested on dotfiles - found 7 shell-safety issues (SC2155), 1 blast-radius issue (prune without dry-run). Lenses working correctly.


Validation: test on prox-setup

Run Phase 1 lenses on ~/proj/prox-setup:
- Verify findings are real issues
- Check false positive rate <10%
- Document any needed lens refinements

Reassigned to prox-setup repo - repo teams own their own testing


Lens: secrets

Create secrets.md lens for credential hygiene:
- Hardcoded secrets, API keys, tokens
- SOPS config issues
- Secrets in logs/error messages
- Secrets via CLI args
- Missing encryption

Linter integration: gitleaks patterns

Created secrets.md lens with Nix store, Docker layer, CI masking checks. Reviewed via orch consensus.


Lens: shell-safety

Create shell-safety.md lens (shellcheck-backed):
- Missing set -euo pipefail
- Unquoted variables (SC2086)
- Unsafe command substitution
- Missing error handling
- Hardcoded paths

Linter integration: shellcheck JSON output

Created shell-safety.md lens with temp file safety, input validation, set -e nuance, guard snippets. Reviewed via orch consensus.


Lens: blast-radius

Create blast-radius.md lens for change safety:
- Destructive ops without confirmation
- Missing dry-run mode
- No rollback strategy
- Bulk ops without batching
- Missing pre-flight checks

LLM-primary: understanding implications

Created blast-radius.md with targeting/scoping, empty var expansion, env gates, scope in output, mitigation downgrades. Reviewed via orch consensus.


Lens: privilege

Create privilege.md lens for least-privilege:
- Unnecessary sudo/root
- Containers as root
- chmod 777 patterns
- Missing capability drops
- Docker socket mounting
- systemd without sandboxing

Created privilege.md with network binding, setuid/setgid, K8s specifics, compensating controls, curl|sudo bash. Reviewed via orch consensus.


Lens: idempotency

Create idempotency.md lens for safe re-execution:
- Scripts that break on re-run
- Missing existence checks
- Non-atomic operations
- Check-then-act race conditions
- Missing cleanup on failure

Boundary: Owns convergence, NOT rollback or retries

Lens created with orch consensus feedback: added optimistic locking, non-deterministic naming, delete idempotency, false positive risks


Lens: supply-chain

Create supply-chain.md lens for provenance:
- Unpinned versions (latest tags)
- Actions not pinned to SHA
- Missing flake.lock/SRI hashes
- Unsigned artifacts
- Untrusted registries

Lens created with orch consensus: added Terraform/Tofu, build-time network access, GH Actions permissions, builtins.fetchTarball


Lens: observability

Create observability.md lens for visibility:
- Silent failures
- Missing health checks
- Incomplete metrics
- Missing structured logging
- No correlation IDs

Lens created with orch consensus: added resource visibility, heartbeats, version/build metadata, log rotation


Lens: nix-hygiene

Create nix-hygiene.md lens (statix/deadnix-backed):
- Dead code (unused bindings)
- Anti-patterns (with lib abuse, IFD)
- Module boundary violations
- Overlay issues
- Missing option types

Linter integration: statix + deadnix JSON

Lens created with orch consensus: added lib.mkIf guards, mkDefault/mkForce, reproducibility/purity, build efficiency, expanded false positives


Research: emes idle quality gate for code-review

Evaluate whether code-review skill should use idle-style quality gate (block exit until review approved). Would enforce review completion mechanically.

Research complete - alice pattern documented, recommendation: review reminder hook instead


spec-review: Add traceability requirements across artifacts

Prompts don't enforce spec → plan → tasks linkage. Drift can occur without detection.

Add:
- Require trace matrix or linkage in reviews
- Each plan item should reference spec requirement
- Each task should reference plan item
- Flag unmapped items and extra scope


Update main README to list all 9 skills

Main README.md 'Skills Included' section only lists worklog and update-spec-kit. Repo actually has 9 skills: template, worklog, update-spec-kit, screenshot-latest, niri-window-capture, tufte-press, update-opencode, web-research, web-search.

Updated README with table listing all 14 skills (5 deployed, 8 available, 1 development template)


Consider repo-setup-verification skill

The dotfiles repo has a repo-setup-prompt.md verification checklist that could become a skill.

**Source**: ~/proj/dotfiles/docs/repo-setup-prompt.md

**What it does**:
- Verifies .envrc has use_api_keys and skills loading
- Checks .skills manifest exists with appropriate skills
- Optionally checks beads setup
- Verifies API keys are loaded

**As a skill it could**:
- Be invoked to audit any repo's agent setup
- Offer to fix missing pieces
- Provide consistent onboarding for new repos

**Questions**:
- Is this better as a skill vs a slash command?
- Should it auto-fix or just report?
- Does it belong in skills repo or dotfiles?

Decided: keep as prompt doc in dotfiles, not a skill. Claude can read it when asked. No wrapper benefit, and it's dotfiles-specific setup (not general skill). ai-tools-doctor handles version checking separately.


Design doc-review skill

# doc-review skill

Fight documentation drift with a non-interactive review process that generates patchfiles for human review.

## Problem
- No consistent documentation system across repos
- Stale content accumulates
- Structural inconsistencies (docs not optimized for agents)

## Envisioned Workflow

```bash
# Phase 1: Generate patches (non-interactive, use spare credits, test models)
doc-review scan ~/proj/foo --model claude-sonnet --output /tmp/foo-patches/

# Phase 2: Review patches (interactive session)
cd ~/proj/foo
claude  # human reviews patches, applies selectively
```

## Design Decisions Made

- **Trigger**: Manual invocation (not CI). Use case includes burning extra LLM credits, testing models repeatably.
- **Source of truth**: Style guide embedded in prompt template. Blessed defaults, overridable per-repo.
- **Output**: Patchfiles for human review in interactive Claude session.
- **Chunking**: Based on absolute size, not file count. Logical chunks easy for Claude to review.
- **Scope detection**: Graph-based discovery starting from README.md or AGENTS.md, not glob-all-markdown.

## Open Design Work

### Agent-Friendly Doc Conventions (needs brainstorming)
What makes docs agent-readable?
- Explicit context (no "as mentioned above")
- Clear section headers for navigation
- Self-contained sections
- Consistent terminology
- Front-loaded summaries
- ???

### Prompt Content
Full design round needed on:
- What conventions to enforce
- How to express them in prompt
- Examples of "good" vs "bad"

### Graph-Based Discovery
How does traversal work?
- Parse links from README/AGENTS.md?
- Follow relative markdown links?
- Depth limit?

## Skill Structure (tentative)
```
skills/doc-review/
├── prompt.md           # Core review instructions + style guide
├── scan.sh             # Orchestrates: find docs → invoke claude → emit patches
└── README.md
```

## Out of Scope (for now)
- Cross-repo standardization (broader than skills repo)
- CI integration
- Auto-apply without human review


Define trace security and redaction policy

Wisps will leak secrets without explicit policy.

Required:
- Default-deny for env vars (allowlist: PROJECT, USER, etc.)
- Redaction rules for sensitive fields
- No file contents by default
- Classification field: internal|secret|public

Implementation:
- redact: ["env.AWS_SECRET_ACCESS_KEY", "inputs.token"]
- Sanitization before writing to disk
- Block elevation if classification=secret

From consensus: both models flagged as medium-high severity.

ADRs revised with orch consensus feedback


Prototype: Convert orch skill to emes-style

First conversion to validate the pattern. Add .claude-plugin/plugin.json, restructure to skills/ directory, test discovery.

Converted orch to emes-style: added .claude-plugin/plugin.json, skills/orch.md, documented pattern in docs/emes-conversion-guide.md


Gemini skills access: ReadFile path restrictions block .claude/skills/

Gemini agent couldn't read skill files from .claude/skills/orch/SKILL.md due to path restrictions. ReadFile tool restricts paths to workspace directories, so .claude/skills/ (symlinked from home-manager) is blocked. Agent had to fall back to shell cat command. Breaks skills portability across agents. Potential fixes: copy skills into repo, configure allowed paths, use MCP, or document workaround.

Fix found: Gemini includeDirectories setting


spec-review: Add Definition of Ready checklists for each phase

'Ready for /speckit.plan' and similar are underspecified.

Add concrete checklists:
- Spec ready for planning: problem statement, goals, constraints, acceptance criteria, etc.
- Plan ready for tasks: milestones, risks, dependencies, test strategy, etc.
- Tasks ready for bd: each task has acceptance criteria, dependencies explicit, etc.


Benchmark AT-SPI overhead and coverage

## Goal
Measure AT-SPI's runtime overhead and coverage across apps.

## Prerequisites
- Enable `services.gnome.at-spi2-core.enable = true` in NixOS
- Set `QT_LINUX_ACCESSIBILITY_ALWAYS_ON=1` for Qt apps
- Rebuild and re-login

## Overhead benchmarks
1. **Startup time**: App launch with/without AT-SPI
2. **Memory**: RSS delta with AT-SPI enabled
3. **CPU**: Idle CPU with AT-SPI bus running
4. **UI latency**: Input-to-paint latency (if measurable)

## Coverage audit
For each app, document:
- Does it expose accessibility tree?
- How complete is the tree? (all elements vs partial)
- Are coordinates accurate?
- Are element types/roles correct?

### Apps to test
- [ ] Firefox
- [ ] Ghostty terminal
- [ ] Nautilus/file manager
- [ ] VS Code / Electron app
- [ ] A Qt app (if any installed)

## Query benchmarks
- Time to enumerate all elements in a window
- Time to find element by role/name
- Memory overhead of pyatspi queries

## Depends on
- skills-pdg (Enable AT-SPI for UI tree access)


spec-review: Add anti-hallucination constraints to prompts

Models may paraphrase and present as quotes, or invent requirements/risks not in the doc.

Add:
- 'Quotes must be verbatim'
- 'Do not assume technologies/constraints not stated'
- 'If missing info, list as open questions rather than speculating'


Create spec-review skill for orch + spec-kit integration

A new skill that integrates orch multi-model consensus with spec-kit workflows.

**Purpose**: Use different models/temps/stances to review spec-kit artifacts before phase transitions.

**Proposed commands**:
- /spec-review.spec - Critique current spec for completeness, ambiguity, gaps
- /spec-review.plan - Evaluate architecture decisions in plan
- /spec-review.gate - Go/no-go consensus before phase transition

**Structure**:
```
skills/spec-review/
├── SKILL.md
├── commands/
│   ├── spec.md
│   ├── plan.md
│   └── gate.md
└── prompts/
    └── ...
```

**Key design points**:
- Finds spec/plan files from current branch or specs/ directory
- Invokes orch with appropriate prompt, models, stances
- Presents consensus/critique results
- AI reviewing AI is valuable redundancy (different models/temps/stances)

**Dependencies**:
- orch CLI must be available (blocked on dotfiles-3to)
- spec-kit project structure conventions


Add direnv helper for per-repo skill deployment

Create sourceable helper script and documentation for the standard per-repo skill deployment pattern using direnv + nix build.


Research OpenCode agents for skill integration

DEPLOYMENT.md:218 has TODO to research OpenCode agents. Need to understand how Build/Plan/custom agents work and whether skills need agent-specific handling.

Researched OpenCode agents - documented in DEPLOYMENT.md. Skills deploy globally, permissions control per-agent access.


Design: orch as local agent framework

# Orch Evolution: From Consensus Tool to Agent Framework

## Current State
- `orch consensus` - multi-model queries
- `orch chat` - single model queries
- No state, no pipelines, no retries

## Proposed Extensions

### Pipeline Mode
```bash
orch pipeline config.yaml
```
Where config.yaml defines:
- Stages (triage → specialists → verify)
- Routing logic (if triage finds X, run specialist Y)
- Retry policy

### Evaluate Mode (doc-review specific)
```bash
orch evaluate doc.md --rubrics=1,4,7 --output=patches/
```
- Applies specific rubrics to document
- Outputs JSON or patches

### Parallel Mode
```bash
orch parallel --fan-out=5 --template="evaluate {rubric}" rubrics.txt
```
- Fan-out to multiple parallel calls
- Aggregate results

## Open Questions
1. Does this belong in orch or a separate tool?
2. Should orch pipelines be YAML-defined or code-defined?
3. How does this relate to Claude Code Task subagents?
4. What's the minimal viable extension?

## Context
Emerged from doc-review skill design - need multi-pass evaluation but don't want to adopt heavy framework (LangGraph, etc.)


orch skill is documentation-only, needs working invocation mechanism

The orch skill provides SKILL.md documentation but no working invocation mechanism.

**Resolution**: Install orch globally via home-manager (dotfiles-3to). The skill documents a system tool, doesn't need to bundle it.

**Blocked by**: dotfiles-3to (Add orch CLI to home-manager packages)

Updated docs to use globally installed orch CLI


Refactor deploy-skill.sh: dedupe injection calls

File: bin/deploy-skill.sh (lines 112-189)

Issues:
- Three nearly-identical inject_nix_config() calls
- Only difference is config block content and target file
- Repeated pattern bloats file

Fix:
- Parameterize inject_nix_config() better
- Or create config-specific injection functions
- Reduce duplication

Severity: MEDIUM

Refactored injection logic using inject_home_file helper, deduping Claude, OpenCode and Antigravity blocks.


orch: add command to show available/configured models

## Problem

When trying to use orch, you have to trial-and-error through models to find which ones have API keys configured. Each failure looks like:

```
Error: GEMINI_API_KEY not set. Required for Google Gemini models.
```

No way to know upfront which models are usable.

## Proposed Solution

Add `orch models` or `orch status` command:

```bash
$ orch models
Available models:
  ✓ flash      (GEMINI_API_KEY set)
  ✓ gemini     (GEMINI_API_KEY set)
  ✗ deepseek   (OPENROUTER_KEY not set)
  ✗ qwen       (OPENROUTER_KEY not set)
  ✓ gpt        (OPENAI_API_KEY set)
```

Or at minimum, on failure suggest alternatives:
```
Error: GEMINI_API_KEY not set. Try --model gpt or --model deepseek instead.
```

## Context

Hit this while trying to brainstorm with high-temp gemini - had to try 4 models before realizing none were configured in this environment.


Investigate waybar + niri integration improvements

Look into waybar configuration and niri compositor integration.

Potential areas:
- Waybar modules for niri workspaces
- Status indicators
- Integration with existing niri-window-capture skill
- Custom scripts in pkgs/waybar-scripts

Related: dotfiles has home/waybar.nix (196 lines) and pkgs/waybar-scripts/

Moved to dotfiles repo - waybar config lives there


skill: semantic-grep using LSP

Use workspace/symbol, documentSymbol, and references instead of ripgrep.

Example: 'Find all places where we handle User objects but only where we modify the email field directly'
- LSP references finds all User usages
- Filter by AST analysis for .email assignments
- Return hit list for bead or further processing

Better than regex for Go interfaces, Rust traits, TS types.


Compare bd-issue-tracking skill files with upstream

Fetch upstream beads skill files and compare with our condensed versions to identify differences


Benchmark vision model UI understanding

## Goal
Measure how well vision models can answer UI questions from screenshots.

## Test cases
1. **Element location**: "Where is the Save button?" → coordinates
2. **Element identification**: "What buttons are visible?" → list
3. **State detection**: "Is the checkbox checked?" → boolean
4. **Text extraction**: "What does the error message say?" → text
5. **Layout understanding**: "What's in the sidebar?" → structure

## Metrics
- Accuracy: Does the answer match ground truth?
- Precision: How close are coordinates to actual element centers?
- Latency: Time from query to response
- Cost: Tokens consumed per query

## Prompt engineering questions
- Does adding a grid overlay help coordinate precision?
- What prompt format gives most actionable coordinates?
- Can we get bounding boxes vs point coordinates?

## Comparison baseline
- Manual annotation of test screenshots
- AT-SPI data (once enabled) as ground truth

## Depends on
- Test screenshots from real apps
- Ground truth annotations

Benchmark complete. Vision models excellent for semantic understanding, approximate for coordinates. Recommend hybrid AT-SPI + vision. See docs/research/vision-ui-benchmark-2025-12-29.md


Skills + Molecules Integration

Integrate skills with beads molecules system.

Design work tracked in dotfiles (dotfiles-jjb).

Components:
- Checklist support (lightweight skills)
- Audit integration (bd audit for skill execution)
- Skill frontmatter for triggers/tracking
- Proto packaging alongside skills

See: ~/proj/dotfiles ADR work

Superseded by skills-4u0 (migrated from dotfiles)


Compare WORKFLOWS.md with upstream


Research: Agent capability matrix

Document what each agent can and cannot do for cross-agent design decisions.

Agents to cover:
- Claude Code (claude CLI)
- Gemini (gemini CLI / AI Studio)
- OpenCode
- Codex (OpenAI)

Capabilities to assess:
- Hooks / lifecycle events
- Subagent spawning
- File system access (paths, restrictions)
- CLI tool execution
- State persistence
- Context window / memory

Output: Matrix showing capability parity and gaps

Capability matrix complete: docs/research/agent-capability-matrix.md


Code Review: {{target}}

Multi-lens code review workflow for {{target}}.

## Philosophy
The LLM stays in the loop at every step - this is agent-assisted review, not automated parsing. The agent applies judgment about what's worth filing, how to prioritize, and what context to include.

## Variables
- target: File or directory to review

## Workflow
1. Explore codebase to find candidates (if target is directory)
2. Run lenses via orch consensus for multi-model perspective
3. Analyze findings - LLM synthesizes across lenses and models
4. File issues with judgment - group related, set priorities, add context
5. Summarize for digest

## Lenses Available
- bloat: size, complexity, SRP violations
- smells: readability, naming, control flow
- dead-code: unused, unreachable, obsolete
- redundancy: duplication, YAGNI, parallel systems


Run bloat lens on {{target}}

Run bloat review lens via orch:

```bash
orch consensus "$(cat ~/.config/lenses/bloat.md)" flash gemini --file {{target}} --mode open
```

Look for: file size, function length, complexity, SRP violations.
Record findings for later filing.


Run smells lens on {{target}}

Run smells review lens via orch:

```bash
orch consensus "$(cat ~/.config/lenses/smells.md)" flash gemini --file {{target}} --mode open
```

Look for: naming issues, control flow smells, data smells, structural issues.
Record findings for later filing.


Run dead-code lens on {{target}}

Run dead-code review lens via orch:

```bash
orch consensus "$(cat ~/.config/lenses/dead-code.md)" flash gemini --file {{target}} --mode open
```

Look for: zombie code, unreachable paths, obsolete shims, import cruft.
Record findings for later filing.


Run redundancy lens on {{target}}

Run redundancy review lens via orch:

```bash
orch consensus "$(cat ~/.config/lenses/redundancy.md)" flash gemini --file {{target}} --mode open
```

Look for: duplication, parallel systems, YAGNI violations, consolidation opportunities.
Record findings for later filing.


Analyze and file findings as beads

Review all lens findings and file actionable items as beads in the TARGET REPO.

## LLM Judgment Required
This is NOT mechanical parsing. The agent should:

1. **Synthesize across lenses** - same issue may appear in bloat + smells
2. **Prioritize by impact** - P2 for blocking issues, P3 for cleanup
3. **Group related findings** - one issue for 'split this file' vs 5 separate issues
4. **Add context** - why it matters, suggested approach, quick-win vs big-refactor
5. **Skip noise** - LOW severity findings unless pattern emerges

## Filing Pattern
```bash
cd <target-repo>
bd create --title="refactor: <clear action>" --type=task --priority=<2|3> --body="<context>

Found by <lens> review."
```

## Key Questions
- Is this worth someone's time to fix?
- Can related findings be grouped into one actionable issue?
- What's the right priority given the codebase context?


Summarize review findings

Create summary of code review findings for {{target}}:

- Total findings by severity (HIGH/MED/LOW)
- Top issues by category
- Recommendations for immediate action
- Technical debt assessment

This summary will become the squash digest.


Explore {{target}} for review candidates

If {{target}} is a directory, explore to find files worth reviewing.

## For Bloat Lens
- Find files over 300 lines (warning) or 500 lines (critical)
- Find functions over 50 lines
- Identify files with multiple responsibilities

## For Other Lenses
- Sample representative files from different modules
- Prioritize high-traffic code over rarely-used

## Output
List of specific files to run through lenses, prioritized by likely issues.

Skip if {{target}} is already a specific file.


use-skills.sh: stderr from nix build corrupts symlinks when repo is dirty

In use-skills.sh, the line:

```bash
out=$(nix build --print-out-paths --no-link "${SKILLS_REPO}#${skill}" 2>&1) || {
```

The `2>&1` merges stderr into stdout. When the skills repo is dirty, nix emits a warning to stderr which gets captured into $out and used as the symlink target.

Result: symlinks like:
```
orch -> warning: Git tree '/home/dan/proj/skills' is dirty
/nix/store/j952hgxixifscafb42vmw9vgdphi1djs-ai-skill-orch
```

Fix: redirect stderr to /dev/null or filter it out before creating symlink.


spec-review: File discovery is brittle, can pick wrong file silently

The fallback `find ... | head -1` is non-deterministic and can select wrong spec/plan/tasks file without user noticing. Branch names with `/` also break path construction.

Fixes:
- Fail fast if expected file missing
- Print chosen file path before proceeding
- Require explicit confirmation if falling back
- Handle branch names with slashes


Configure Claude Code LSP integration

Claude Code now has LSP (Language Server Protocol) integration that provides semantic code understanding.

## Key Features
- Go to Definition - Jump to symbol declarations
- Find References - Locate all usages (safe refactoring)
- Hover/Type Info - Get signatures, docstrings, types
- Diagnostics - See compiler errors/warnings directly

## Setup Required
1. Enable via env var: ENABLE_LSP_TOOL=1
2. Install language servers on PATH:
   - TypeScript: typescript-language-server
   - Python: pyright or python-lsp-server
   - Go: gopls
   - Rust: rust-analyzer
   - Nix: nil or nixd

3. Optional: MCP adapter like cclsp for robust AI→LSP bridging

## Tasks
- [ ] Add language servers to Nix packages
- [ ] Set ENABLE_LSP_TOOL=1 in shell environment
- [ ] Test with representative projects
- [ ] Consider creating an LSP skill documenting available servers

## References
- Discovered via orch consensus with sonar, flash-or, glm
- Related to skills+molecules integration (semantic code understanding for traces)

LSP servers deployed (gopls, pyright, typescript-language-server, rust-analyzer, nil, elixir-ls); ENABLE_LSP_TOOL=1 in sessionVariables; requires new session to test


Define structured skill reference schema

Replace simple skill: string with structured object.

Current (too weak):
  skill: worklog

Proposed:
  skill:
    id: worklog
    ref: "git+file://...#worklog@abc123"
    inputs:
      session: "{{session}}"
    expects:
      files: ["docs/worklogs/{{session}}.org"]

From orch consensus: both GPT and Gemini flagged this as critical gap.
No mechanism to pass args from molecule to skill.

Deferred: structured schema was for molecule→skill integration. Current approach (agent reads SKILL.md directly) works well. Skills as entrypoints are simpler than protos. Revisit if programmatic workflows become active.


Orch-in-the-Middle: LSP proxy for multi-model refactors

Write an LSP proxy (Go/Rust) that:
- Intercepts rename/code-action requests from editor
- Sends to Orch for multi-model proposals
- Validates proposals against real headless LSP
- Returns winning WorkspaceEdit to editor

Get consensus refactoring inside VS Code/Neovim by configuring LSP server path in home-manager.

Parked: waiting on gastown (Steve Yegge's orchestration layer for beads). Revisit when gastown lands.


spec-review: Balance negativity bias in prompts

'Be critical' and 'devil's advocate' can bias toward over-flagging without acknowledging what's good.

Add:
- 'List top 3 strongest parts of the document'
- 'Call out where document is sufficiently clear/testable'
- Categorize :against concerns as confirmed/plausible/rejected


Cross-agent skill portability and quality gates

Design and implement cross-agent skill portability and quality gates.

## Problem Statement

Skills and quality enforcement must work regardless of which agent is orchestrator, worker, or reviewer. Current agents (Claude, Gemini, OpenCode, Codex) have different capabilities.

## Abstract Architecture

### Layer 1: Message Passing
**Purpose:** Async agent coordination, session handoffs, status updates

| Requirement | Description |
|-------------|-------------|
| Append-only | No overwrites, git-mergeable |
| Agent-attributed | Know which agent posted |
| Topic-based | Namespaced conversations |
| Async | Agents don't block each other |

*Possible implementations:* jwz, beads extensions, simple JSONL files

### Layer 2: Memory
**Purpose:** Persistent work items, dependencies, review state

| Requirement | Description |
|-------------|-------------|
| Cross-session | Survives compaction, restarts |
| Dependency tracking | Issue X blocks issue Y |
| Queryable | Find by status, type, assignee |
| Git-native | Lives in repo, versioned |

*Possible implementations:* beads, tissue, structured markdown

### Layer 3: Enforcement
**Purpose:** Quality gates that block completion until approved

| Requirement | Description |
|-------------|-------------|
| Mechanical where possible | Hooks for Claude/Gemini |
| Protocol fallback | Orchestrator-enforced for others |
| Circuit breakers | Prevent infinite loops |
| Reviewable | Human can inspect decisions |

*Possible implementations:* Stop hooks, orchestrator gates, wrapper scripts

## Goals

1. **Portable skills** - Same SKILL.md works in any agent
2. **Portable quality gates** - Adversarial review across agents
3. **Flexible orchestration** - Any agent can play any role
4. **Implementation-agnostic** - Swap tools without changing patterns

## Completed Work
- ADR-005: Dual-publish architecture
- Agent capability matrix
- Web research on patterns
- orch integration for multi-model

## Key Decisions Pending
- Message passing: jwz vs beads vs simple files
- Enforcement: Hook-first vs orchestrator-first
- Reviewer: Dedicated skill vs orch consensus


Add tests for agent file update logic

File: .specify/scripts/bash/update-agent-context.sh (lines 360-499)

Critical logic with NO test coverage:
- Malformed agent files (missing sections)
- Multiple section headers on same line
- Empty file handling
- Timestamp update verification
- State machine correctness

Risk: HIGH - corrupts agent context files on failure

Fix:
- Create test fixtures for various file states
- Test each state transition
- Verify idempotency

Severity: HIGH

33 tests added covering all major code paths. Also fixed bug where Recent Changes section was skipped when preceded by Active Technologies.


skill: rename_symbol with LSP + validation

Skill that performs safe renames:
1. Uses LSP textDocument/rename
2. Runs formatters
3. Checks LSP diagnostics post-rename
4. Opens bead if errors remain
5. Updates doc references using hover/signatureHelp

Input: new name, scope. Output: clean rename or bead with issues.


Add doc-review skill

Create skill for doc-review CLI tool (~/proj/doc-review). Tool lints markdown docs for AI agent consumption using Vale + LLM hybrid architecture. Needs: 1) flake.nix in doc-review project, 2) skill SKILL.md, 3) register in availableSkills

doc-review skill created in skills/doc-review/SKILL.md


ADR: Skills and Molecules Integration Design

Write Architecture Decision Record documenting:
- Current state (skills via Nix/direnv, molecules via beads)
- Decision to link via skill: references
- Wisp trace format spec
- Elevation pipeline design
- Anti-patterns to avoid

Location: docs/adr/001-skills-molecules-integration.md

Migrated from dotfiles-dn8 (was in_progress).

## Current State
- ADR-001 drafted (high-level integration)
- ADR-002, 003, 004 drafted and revised (manifest, versioning, security)
- Orch consensus feedback incorporated

## Parked
Deferring finalization until we see Steve Yegge's new orchestration work and how it might inform our design.

Parked: ADR updated to 'Parked' status. Current simpler approach (skills as standalone, agent judgment) works well. Molecules not actively used. Revisit when orchestration needs grow.


Handle concurrency and multi-agent execution

Not addressed in ADR. Questions:

- What happens when two agents run same skill on same mol step?
- How to handle partial failures and resumptions?
- Trace merging: append-only log vs latest-wins?

Needs:
- execution_id and parent_execution_id in traces
- Step completion idempotency declaration
- Define how multiple traces attach to one mol node

Can defer until basic integration works.


worklog: consolidate git commands into extract-metrics.sh

Context Gathering section has raw git commands, but extract-metrics.sh also exists. Feature envy - split logic. Move all git context gathering into the script, skill makes single call. Found by smells lens review.


Skills: verify symbols via LSP before suggesting

Inversion: let LSP answer facts, let models answer strategy.

Before Claude suggests using a function/type:
- Verify existence via workspace/symbol or go-to-definition
- If not found, propose alternatives that ARE found
- Gather definition, references, inferred types, diagnostics as context

Reduces hallucinated APIs and grounds patches in reality.


Define wisp execution trace format

Design structured format for skill execution traces in wisps:
- skill_version (git SHA + flake hash)
- inputs (context refs, env vars)
- tool_calls [{cmd, args, exit_code, duration}]
- checkpoints [{step, summary, timestamp}]
- outputs (file diffs or refs)

Enable: replay, diff traces, regression testing

Migrated from dotfiles-ub9.

Parked with ADR-001: skills-molecules integration deferred. Current simpler approach (skills as standalone) works well. Revisit when complex orchestration needed.


Desktop automation for Wayland/niri

Explore and implement desktop automation solutions for Wayland (niri compositor).

## The Seeing Problem

How can an AI agent understand what's on screen?

### Layers (bottom to top)
1. **Window awareness** - what's open, app_id, title → niri IPC ✅
2. **Window geometry** - size, position, monitor → niri IPC ✅
3. **Pixel capture** - screenshots → niri screenshot-window ✅
4. **Understanding** - UI elements, coordinates, semantics → **GAP**

### Two paths to understanding (layer 4)

**Path A: AT-SPI (structured)**
- Pros: precise coordinates, semantic element types, states
- Cons: runtime overhead, requires NixOS config, app compliance varies
- Coverage: GTK ✅, Qt (with env var), Electron ❓

**Path B: Vision model (visual)**
- Pros: universal (works on any pixels), no system config needed
- Cons: API latency, token cost, coordinate precision unclear
- Coverage: anything visible ✅

### Hybrid approach
Run both, benchmark tradeoffs:
- AT-SPI overhead vs query precision
- Vision model latency/cost vs coverage
- When to use which (or both for validation)

## What we have
- niri-window-capture skill (screenshots, window list)
- niri IPC for window/monitor geometry

## Context
Wayland's security model blocks X11-style automation. Solutions require:
- Compositor-specific IPC (niri msg)
- App opt-in via AT-SPI accessibility
- Or vision model interpretation of pixels


Orch skill: document or handle orch not in PATH

Skill docs show 'orch consensus' but orch requires 'uv run' from ~/proj/orch. Either update skill to invoke correctly or document installation requirement.


beads new --from-cursor: capture symbol context

When creating a bead, auto-capture LSP context:
- Current symbol FQN (fully qualified name)
- Definition snippet
- Top 10 references/callers
- Current diagnostics for the symbol

Makes beads self-contained without copy/paste archaeology. Symbol URI allows jumping back to exact location even if file moved.


Compare DEPENDENCIES.md with upstream


Compare ISSUE_CREATION.md with upstream


Simplify branch name generation in create-new-feature.sh

File: .specify/scripts/bash/create-new-feature.sh (lines 137-181)

Issues:
- 3 nested loops/conditionals
- Complex string transformations with multiple sed operations
- Stop-words list and filtering logic hard to maintain

Fix:
- Extract to separate function
- Simplify word filtering logic
- Add input validation

Severity: MEDIUM

Simplifed generate_branch_name logic, added main() function, and BASH_SOURCE guard for testability.


Apply niri-window-capture code review recommendations

CODE-REVIEW-niri-window-capture.md identifies action items: add dependency checks to scripts, improve error handling for niri failures, add screenshot directory validation, implement rate limiting. See High/Medium priority sections.

Implemented all 4 high-priority recommendations from code review: dependency checks, directory validation, error handling, audit logging


Design: Portable adversarial reviewer

Design a reviewer agent/skill that can run on any capable model.

alice is Claude Opus with specific tools. We need:
- Model-agnostic reviewer prompt/instructions
- Tool requirements (read-only: Read, Grep, Glob, Bash)
- Integration with orch for multi-model consensus
- Decision format (APPROVED/ISSUES)
- Issue filing (beads or tissue)

Key principles from alice:
- Work for the USER, not the agent
- Assume errors exist, find them
- Steel-man then attack
- Seek second opinions

Output: Reviewer skill spec that works across agents

Covered in architecture design doc - adversarial reviewer section


spec-review: Define consensus thresholds and decision rules

'Use judgment' for mixed results leads to inconsistent decisions.

Define:
- What constitutes consensus (2/3? unanimous?)
- How to handle NEUTRAL votes
- Tie-break rules
- When human override is acceptable and how to document it


worklog: clarify or remove semantic compression references

SKILL.md references 'semantic compression is a planned workflow' multiple times but it's not implemented. Speculative generality - adds cognitive load for non-existent feature. Either implement or move to design notes. Found by smells lens review.


Prototype: End-to-end cross-agent workflow

Build a working prototype of cross-agent quality gate.

## Scenario
1. Worker agent (any) does task
2. Posts status to message layer
3. Reviewer agent (any) checks work
4. Posts approval/issues to memory layer
5. Gate checks memory, allows/blocks completion

## Test Matrix

| Orchestrator | Worker | Reviewer | Enforcement |
|--------------|--------|----------|-------------|
| Claude | Claude | Gemini | Hook |
| Claude | Gemini | Claude | Hook |
| OpenCode | Claude | Gemini | Orchestrator |
| Manual | OpenCode | Claude | Protocol |

## Components to Build
1. Message layer interface (post/read status)
2. Memory layer interface (review state)
3. Gate check CLI (for hooks and manual)
4. Reviewer skill/prompt

## Success Criteria
- At least 2 agent combinations working
- Gate actually blocks when review fails
- State persists across agent boundaries


Define skill manifest format

Skills need to declare their interface so beads can validate.

Manifest should include:
- Required inputs (args, env vars)
- Optional inputs with defaults
- Expected outputs (files, artifacts)
- Preconditions (tools, repos, permissions)

Location: SKILL.md frontmatter or separate manifest.yaml

Enables: Proto validation before spawning, better error messages.

ADRs revised with orch consensus feedback


Refactor update-agent-context.sh: array+loop for agents

File: .specify/scripts/bash/update-agent-context.sh (772 lines)

Issues:
- 12 nearly-identical if-blocks in update_all_existing_agents() (lines 632-701)
- Should be refactored into loop with array of agent configurations
- Current pattern repeats: if [[ -f "$CLAUDE_FILE" ]]; then update_agent_file...

Fix:
- Create AGENTS array with (file, name, format) tuples
- Replace 12 if-blocks with single for loop
- Estimated reduction: 60 lines

Severity: HIGH

update-agent-context.sh is .specify upstream code, not maintained here


Cross-language FFI wormholes via LSP

Bridge FFI boundaries where standard LSPs go blind:
- Rust extern C → clangd lookup
- Go CGO → match C symbols
- Python FFI → trace bindings

Generate synthetic go-to-definition maps. When hovering over C call in Rust, intercept hover request, query C LSP, inject C definition into Rust tooltip.

Enables seamless polyglot navigation.


Enable AT-SPI for UI tree access

## Findings

AT-SPI (Assistive Technology Service Provider Interface) provides semantic UI tree access - buttons, labels, text fields, their states and coordinates.

### Current state
- AT-SPI is **disabled** on this NixOS system
- Environment has `NO_AT_BRIDGE=1` and `GTK_A11Y=none`
- No apps are exposing accessibility info

### To enable
```nix
services.gnome.at-spi2-core.enable = true;
```

Then rebuild and re-login (apps must start fresh to register with bus).

### App support
- **GTK apps**: Should work automatically
- **Qt apps**: Need `QT_LINUX_ACCESSIBILITY_ALWAYS_ON=1` env var
- **Electron**: Varies by app, often poor support

### Trade-offs
- Adds runtime overhead to all GTK/Qt apps
- May want as boot-time option rather than always-on
- Only useful for automation/accessibility use cases

### Tools once enabled
- `python3-pyatspi` / `dogtail` for querying UI tree
- `accerciser` for visual inspection of accessibility tree

### Next steps
**Blocked by dotfiles-0l3** - NixOS config change filed in dotfiles repo.

After dotfiles change deployed:
1. Test with common apps (Firefox, terminals, etc.)
2. Build skill to query UI elements

## Related
Parent epic: skills-kg7 (Desktop automation for Wayland/niri)


worklog: remove inline section list, reference template

SKILL.md lists 11 sections that duplicate worklog-template.org. Will drift. Replace with directive to parse sections from template dynamically. Found by bloat lens review.


Clean up stale beads.left.jsonl merge artifact

bd doctor flagged multiple JSONL files. beads.left.jsonl is empty merge artifact that should be removed: git rm .beads/beads.left.jsonl


Add README.md for web-research skill

web-research skill has SKILL.md and scripts but no README.md. AGENTS.md says README.md is for humans, contains installation instructions, usage examples, prerequisites.

Added README.md with prerequisites, usage examples, and cross-references


Extract shared logging library from scripts

Duplicated logging/color functions across multiple scripts:
- bin/deploy-skill.sh
- skills/tufte-press/scripts/generate-and-build.sh
- Other .specify scripts

Pattern repeated:
- info(), warn(), error() functions
- Color definitions (RED, GREEN, etc.)
- Same 15-20 lines in each file

Fix:
- Create scripts/common-logging.sh
- Source from all scripts that need it
- Estimated reduction: 30+ lines of duplication

Severity: MEDIUM

Minimal duplication: only 2 files with different logging styles. Shared library overhead not justified.


Test integration on worklog skill

Use worklog skill as first real test case:
- Create wisp for worklog execution
- Capture execution trace
- Test squash → digest
- Validate trace format captures enough info for replay

Migrated from dotfiles-drs.


Implement playwright-visit skill for browser automation

## Overview
Browser automation skill using Playwright to visit web pages, take screenshots, and extract content.

## Key Findings (from dotfiles investigation)

### Working Setup
- Use `python312Packages.playwright` from nixpkgs (handles Node driver binary patching for NixOS)
- Use `executable_path='/run/current-system/sw/bin/chromium'` to use system chromium
- No `playwright install` needed - no browser binary downloads

### Profile Behavior
- Fresh/blank profile every launch by default
- No cookies, history, or logins from user's browser
- Can persist state with `storage_state` parameter if needed

### Example Code
```python
from playwright.sync_api import sync_playwright

with sync_playwright() as p:
    browser = p.chromium.launch(
        executable_path='/run/current-system/sw/bin/chromium',
        headless=True
    )
    page = browser.new_page()
    page.goto('https://example.com')
    print(page.title())
    browser.close()
```

### Why Not uv/pip?
- Playwright pip package bundles a Node.js driver binary
- NixOS can't run dynamically linked executables without patching
- nixpkgs playwright handles this properly

## Implementation Plan
1. Create `skills/playwright-visit/` directory
2. Add flake.nix with devShell providing playwright
3. Create CLI script with subcommands:
   - `screenshot <url> <output.png>` - capture page
   - `text <url>` - extract text content
   - `html <url>` - get rendered HTML
   - `pdf <url> <output.pdf>` - save as PDF
4. Create skill definition for Claude Code integration
5. Document usage in skill README

## Dependencies
- nixpkgs python312Packages.playwright
- System chromium (already in dotfiles)

## Related
- dotfiles issue dotfiles-m09 (playwright skill request)

Implemented: SKILL.md, visit.py CLI (screenshot/text/html/pdf), flake.nix devShell, README. Network down so couldn't test devShell build, but code complete.


Add tests for config injection (deploy-skill.sh)

File: bin/deploy-skill.sh (lines 112-137)

Critical logic with NO test coverage:
- Idempotency (running twice should be safe)
- Correct brace matching in Nix
- Syntax validity of injected config
- Rollback on failure

Risk: MEDIUM-HIGH - can break dotfiles Nix config

Fix:
- Test idempotent injection
- Validate Nix syntax after injection
- Test with malformed input

Severity: MEDIUM

21 tests added covering idempotency, brace preservation, inject_home_file wrapper, edge cases


Design: Hybrid hook + gate architecture

Design enforcement that uses hooks where available, orchestrator gates elsewhere.

## Hook-Capable Agents (Claude, Gemini)
- Stop hook checks beads for review status
- Mechanical enforcement - agent can't bypass

## Non-Hook Agents (OpenCode, Codex)
- Orchestrator pattern enforces gate
- Orchestrator checks beads before declaring done
- Worker can't bypass because doesn't control session

## Shared Components
- beads: persistent state (issues, review status)
- jwz: transient state (session messages, async handoffs)
- review-gate CLI: checks state, returns exit code

## Deliverable
Architecture doc showing:
1. Hook configuration for Claude/Gemini
2. Orchestrator flow for OpenCode/Codex
3. State schema in beads
4. review-gate CLI design


Design: Circuit breaker patterns

Design circuit breakers to prevent agent infinite loops.

## Patterns to Implement

### Semantic Drift Detection
- Embed last N agent thoughts
- If >95% similar, inject "try different approach"
- Use cheap embedding model

### Three-Strike Tool Rule
- Track tool call signatures (tool + args + error)
- 3 identical failures → force strategy shift
- Implement in PostToolUse hook

### Budget-Based Interrupts
- Allocate token budget per sub-task
- Pause if >50% budget used with <30% progress
- Request plan refinement

### Time-Based Breaker
- Timeout per task type
- Escalate to review if exceeded

## Implementation Options
- Hook-based (Claude/Gemini)
- Wrapper-based (all agents)
- Orchestrator-enforced (all agents)

## Deliverable
- Circuit breaker design doc
- Prototype implementation for one pattern

Covered in architecture design doc (docs/design/cross-agent-enforcement-architecture.md)


Define trace levels (audit vs debug)

Two trace levels to manage noise vs utility:

1. Audit trace (minimal, safe, always on):
   - skill id/ref, start/end
   - high-level checkpoints
   - artifact hashes/paths
   - exit status

2. Debug trace (opt-in, verbose):
   - tool calls with args
   - stdout/stderr snippets
   - expanded inputs
   - timing details

Consider OpenTelemetry span model as reference.
GPT proposed this; Gemini focused on rotation/caps instead.


Define skill trigger conditions

How does an agent know WHEN to apply a skill/checklist?

Options:
- frontmatter triggers: field with patterns
- File-based detection
- Agent judgment from description
- Beads hooks on state transitions
- LLM-based pattern detection

Resolved: agent judgment from description is the standard. Good descriptions + 'When to Use' sections are sufficient. No new trigger mechanism needed - would add complexity without clear benefit.


worklog: merge Guidelines and Remember sections

Guidelines (8 points) and Remember (6 points) sections overlap significantly - both emphasize comprehensiveness, future context, semantic compression. Consolidate into single principles list. Found by bloat lens review.


Investigate: Sandbox for research-only subagents

Can we ensure research/explore subagents run in a restricted sandbox?

## Context
When spawning subagents for research tasks (codebase exploration, web search, reading files), they should be read-only and sandboxed - no writes, no destructive commands.

## Questions to Answer
1. Does Claude Code Task tool support sandbox restrictions for subagents?
2. Can we pass sandbox mode to Gemini CLI subagents?
3. How does OpenCode's permission system work for subagents?
4. Can Codex subagents inherit sandbox restrictions?

## Desired Behavior
- Research subagent can: Read, Grep, Glob, WebFetch, WebSearch
- Research subagent cannot: Write, Edit, Bash (destructive), delete

## Security Benefit
Prevents research tasks from accidentally (or maliciously) modifying files or running destructive commands.

Related: Cross-agent quality gate architecture (skills-3ja)


Compare RESUMABILITY.md with upstream


Resolve web search design questions

web_search_brainstorm.md has unanswered design questions: single smart skill vs explicit flags, specific sources priority, raw links vs summaries. Need user input to finalize web-search/web-research direction.

Resolved: keep 2 skills, web-search for OpenCode only (Claude has built-in), web-research for both. Source filtering via WebSearch domains. Summaries by default.


Refactor update-agent-context.sh: reduce nesting depth

File: .specify/scripts/bash/update-agent-context.sh

Issues:
- update_existing_agent_file() has 4-level deep nesting (lines 360-499)
- State machine with multiple variables: in_tech_section, in_changes_section, tech_entries_added
- 70+ lines of while loop processing

Fix:
- Extract file processing to separate function
- Consider sed/awk for line-based transformations
- Use guard clauses to reduce nesting

Severity: HIGH


Design checklist support for skills

Design how checklists fit into the skills system.

Questions:
- Skill-as-checklist (SKILL.md with just items, no scripts)?
- Separate checklist format?
- Trigger conditions in frontmatter?
- Integration with bd audit for tracking?

Tiers considered:
1. AGENTS.md (simplest, no tracking)
2. Skill-as-checklist (deployed, invokable)
3. Proto (full tracking, overhead)


Research Steve Yegge's orchestration work

Steve Yegge is working on something new related to AI orchestration. Research what it is and how it might inform our skills+molecules integration design.

Blocks: skills-hin (ADR finalization)


Investigate hooks for parallel orch queries

When using orch skill, it would be useful to spin off multiple model queries in parallel automatically (e.g., gemini + gpt simultaneously). Explore if Claude Code hooks can trigger parallel background processes when the orch skill is invoked.

Investigated. Hooks are synchronous with 60s timeout - unsuitable for background orch queries. Alternatives: (1) SessionStart hook for initial consensus, (2) Explicit skill invocation, (3) PostToolUse for validation. orch consensus already runs models in parallel internally.


Add tests for branch name generation

File: .specify/scripts/bash/create-new-feature.sh (lines 137-181)

Critical logic with NO test coverage:
- Word filtering with stop-words
- Acronym detection
- Unicode/special character handling
- Max length boundary (244 bytes)
- Empty/single-word descriptions

Risk: HIGH - affects all branch creation

Fix:
- Create test suite with edge cases
- Test stop-word filtering accuracy
- Test boundary conditions

Severity: HIGH

Created test suite with 27 tests covering stop words, acronyms, word limits, special chars, unicode, edge cases, and fallback logic


Reorganize lens directory structure

Current structure puts ops lenses as subdirectory of code-review lenses:

```
~/.config/lenses/           <- code-review lenses
~/.config/lenses/ops/       <- ops-review lenses
```

This is asymmetric. Consider:

Option A: Separate top-level directories
```
~/.config/lenses/code-review/
~/.config/lenses/ops-review/
```

Option B: Keep flat but with prefixes
```
~/.config/lenses/code-*.md
~/.config/lenses/ops-*.md
```

Option C: Per-skill lens directories
```
~/.claude/skills/code-review/lenses/
~/.claude/skills/ops-review/lenses/
```

Requires updating:
- modules/ai-skills.nix (deployment paths)
- skills/code-review/SKILL.md (expected paths)
- skills/ops-review/SKILL.md (expected paths)

Reorganized lens directories: code-review → ~/.config/lenses/code/, ops-review → ~/.config/lenses/ops/. Updated ai-skills.nix, SKILL.md, and README references.


worklog: extract hardcoded path to variable

SKILL.md repeats ~/.claude/skills/worklog/ path 4-5 times. Define SKILL_ROOT once, reference throughout. Found by bloat+smells lens review.


Create skills marketplace.json registry

Central registry of all skills for plugin discovery. Follow emes marketplace pattern.

Created .claude-plugin/marketplace.json with orch as first plugin. More plugins added as skills are converted.