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


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


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.


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.


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.


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.


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.


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.


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.


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


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


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


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


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


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


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)


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


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.


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.


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?


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.


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.


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


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.


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


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


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.


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.


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


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


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.


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.


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.


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.


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


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.


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


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.


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
1. Add NixOS option (possibly as boot-time toggle)
2. Test with common apps (Firefox, terminals, etc.)
3. Build skill to query UI elements

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


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.


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


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)


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


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


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.


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.


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