Define error handling strategy and apply consistently

Establish consistent error handling pattern:

1. Define strategy:
   - Boundary operations wrap errors with context (file, taskId, operation)
   - Use existing exception types (GitError, DbError, etc.)
   - Log to stderr with consistent format: 'ERROR: {operation}: {message}'

2. Apply to:
   - db.nim: poll() JSON parsing, openBusDb(), tryClaim()
   - git.nim: fetch failures, cleanup operations
   - context.nim: writeContext(), readContext()
   - state.nim: parseState() calls
   - heartbeat.nim: thread startup

Consolidates: skills-xcl, skills-266, skills-8xv, skills-8vdo, skills-n6zf, skills-tdfm, skills-koes, skills-xgh0, skills-8bi, skills-2wjp, skills-3uv9

Parent: skills-g2wa

Implemented consistent error handling strategy


Define StaleLevel enum instead of string returns

[EVOLVE] LOW state.nim:225-241 - staleLevel() returns strings ('ok','WARN','STALE','DEAD') instead of enum. Define StaleLevel enum in types.nim for type safety.


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


Fix predictable ID generation in genOid()

[SECURITY] HIGH db.nim:14-18 - genOid() uses rand(25) without randomize() call. IDs are predictable/deterministic. Add randomize() at module init or use std/sysrand for crypto-safe IDs.

Fixed: genOid() now uses std/sysrand for cryptographically secure random IDs


Design: Structured task specs (requirements/design/tasks)

Adopt spec-driven development pattern from Kiro/Tessl/GitHub Spec Kit. Each task should have: requirements.md (what), design.md (how), tasks.md (decomposed steps). Agents work from specs not vague prompts. Specs are versioned; agents echo which version they used. Prevents state divergence and 'different reality' footgun.


Check for symlinks before reading context file

[SECURITY] MED context.nim:21,31 - readFile follows symlinks, could read arbitrary files if .worker-ctx.json is symlinked. Check that path is regular file before reading.


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


Design: Stuck agent detection (Rubber Duck)

Detect non-progress and force clarification.

## Pattern (from GPT/Gemini brainstorm)
Track:
- repeated tool calls (same command 3x)
- identical errors
- no diff delta
- no new hypotheses

When triggered, force protocol:
1. Write down 3 hypotheses
2. Run one discriminating experiment per hypothesis
3. If no new info → escalate

## Rubber Duck variant
On stuck: force agent to explain problem in 200 tokens to dumber model.
If can't explain coherently → escalate to human.
Compression reveals the flaw.

## Abstraction Elevator variant
Stuck on syntax → force to pseudocode
Stuck on logic → force to explain with analogies

## Implementation
- worker stuck X - detect non-progress
- Check .worker-state/X.log for repeated patterns
- Inject 'rubber duck' prompt if stuck
- Circuit breaker after N attempts


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.


Design: Token and cost budgets per agent

Prevent token blowup footgun. Implement: hard budgets per agent and per run, limit context sizes, separate heavy/light agents, queueing with backpressure, retry with idempotency tokens. Plan-and-Execute pattern: expensive model plans, cheap models execute (90% cost reduction). From research synthesis.


Compare BOUNDARIES.md with upstream


Design HQ SKILL.md - orchestration instructions

Write the core skill file that teaches agents to orchestrate.

Contents:
- When to use HQ mode
- How to read bd ready and pick work
- How to spawn workers (Task tool? claude CLI?)
- How to monitor progress (worker status, bd comments)
- How to handle review cycles (approve/reject/iterate)
- When to use orch for second opinions
- Error handling and escalation

Output: skills/hq/SKILL.md

Completed - skills/hq/SKILL.md created with core loop, delegation boundaries, communication protocol, and open questions


Create orch skill for multi-model consensus

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


Add error context to date parsing in types.nim:111

[ERROR] MED - Date parsing can fail on malformed JSON input with unhelpful error. parse() throws on invalid format, caller gets generic parse error. Wrap in try/except with context.


worker CLI: spawn requires named arguments --taskId


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.


HQ: Orchestrator skill for multi-agent coordination

**Status: Design/Exploration**

## Vision

`hq` is a skill that teaches any capable coding agent to act as an orchestrator - coordinating workers, managing tasks, and handling review cycles.

Not a new binary. A skill that leverages existing tools:
- `bd` - issue tracking
- `worker` - lifecycle management
- `review-gate` - quality enforcement
- `orch` - multi-model consensus

## Naming

`hq` = headquarters. Short (2 chars), fits existing naming:
- `bd` (2) - beads
- `hq` (2) - headquarters
- `orch` (4) - multi-model
- `worker` (6) - lifecycle

## Architecture

```
ORCHESTRATOR = Agent + Tools + Skills + Context

Tools:     bd, worker, review-gate, orch
Skills:    hq (how to orchestrate)
Context:   .beads/, .worker-state/, repo state
Agent:     Claude (or any capable LLM)
```

The orchestrator IS the conversation. User talks to agent, agent has tools to spawn/manage workers.

## Triggers (all supported)

1. **bd issue** - `bd ready` shows work, orchestrator picks it up
2. **Natural language** - User says "implement feature X"
3. **Scheduled/ambient** - Future: cron-like "check for work"

## How It Works

```
User: "Implement dark mode for settings page"
    │
    ▼
Orchestrator (Claude with hq skill):
    ├── Check bd for existing issue (or create one)
    ├── Decompose if needed (single task or multiple?)
    ├── worker spawn task-001
    ├── Invoke worker Claude (Task tool / claude CLI)
    ├── Monitor via worker status
    ├── Handle review (approve/request-changes)
    ├── worker merge on approval
    └── Report back to user
```

## Skill Structure

```
skills/hq/
├── SKILL.md              # Core orchestration instructions
├── scripts/
│   └── hq-status         # Quick view: bd + worker + review state
└── templates/
    └── worker-system.md  # System prompt for spawned workers
```

## Key Decisions (TBD)

1. **Worker invocation**: Task tool subagent? `claude` CLI? Manual?
2. **Decomposition**: When to split into multiple workers?
3. **Review policy**: Auto-approve simple tasks? Always human?
4. **Failure handling**: Retry? Escalate? Reassign?

## Related

- Worker CLI: src/worker.nim (built, working)
- Review-gate: skills/review-gate/ (built, needs deployment)
- Benchmark harness: skills-qng9 (design phase)

## Prior Art Considered

- Strix (ambient AI assistant)
- Helm (taken - K8s package manager)
- Various agent frameworks (CrewAI, LangGraph, etc.)

Our approach: CLI tools + state files + skills (no daemons)

MVP complete: SKILL.md with orchestration loop, worker-system.md template, hq-status script. Ready for spike testing.

Test comment from agent - exploring messaging


Log parseInt failures in getBranchStatus instead of silent discard

[ERROR] LOW git.nim:139-143 - parseInt failures silently discarded. Return (0,0) explicitly with comment, or log the parse failure.


Extract date format constant in types.nim

[SMELL] LOW - Date format 'yyyy-MM-dd HH:mm:sszzz' hardcoded in toJson/fromJson. Extract to const DateFormat* or use times.IsoDateTimeFormat.

ContextDateFormat already extracted in error handling refactor


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


Design: Review funnel with arbiter agent

Solve review bottleneck footgun (10 agents = 10 PRs to reconcile). Add arbiter/synthesis step: workers → arbiter agent (dedupes, resolves conflicts) → single synthesized PR → human review. Pre-review by lint/style agents so humans see substantive deltas only. From HN discussions on parallel agents.


infra: Security boundaries and sandboxing for workers

**Raised by:** gemini, gpt

**Problem:**
Workers run in worktrees (directories), not containers. Nothing prevents worker from editing SKILL.md, worker CLI source, or accessing .env files. Workers can paste stack traces or config with keys into BD comments.

**gemini:**
> "What prevents a worker from editing the 'SKILL.md' file itself? Or the 'worker' CLI source code? Or accessing the '.env' file of the HQ? The 'worker spawn' command should ideally run in a container (Docker), not just a directory worktree. A directory is not a security boundary."

**gpt:**
> "Workers may exfiltrate secrets via logs, error output, diffs, or BD comments. Add a security gate: prohibit printing env/secrets, sanitize logs in comments. Require secret scanning. Mark some issues 'security-sensitive → human review mandatory.'"

**Suggested fixes:**
1. Container isolation (Docker) for workers
2. Secret scanning on diffs and comments
3. Redaction rules for logs
4. "security-sensitive" issue flag requiring human review
5. Path sandboxing / tool allowlists
6. "cannot self-approve" rules

[RECLASSIFY:2026-01-12T09:44:37-08:00] Moved from HQ to infrastructure layer.

Sandboxing/security is runtime infrastructure, not orchestration logic. Whether workers run in containers, have path restrictions, etc. is below HQ's concern level.


TEST: Logic Fix - Add Factorial


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.


Extract branchName() and worktreePath() helpers in git.nim

[REDUNDANCY] MED git.nim:36,59,89 - Branch pattern 'feat/{taskId}' repeated 3 times. Worktree path repeated at 37,53. Extract helpers: proc branchName(taskId): string and proc worktreePath(taskId): string.


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


HQ SKILL.md design gaps from orch consensus

Orch consensus review of HQ SKILL.md (flash-or, gemini, gpt @ temp 1.2) identified multiple design gaps.

Session: 01KESKA3TVWYVW2PTS0XRBR1Q7

## Architectural Decision

HQ should be a **thin orchestration layer** making decisions, not a monolith handling everything.

Issues have been reclassified to proper layers:
- **HQ**: WIP limits, DoD, templates, core loop, dependency scoping
- **worker CLI**: Launch, rebase, salvage, retry counts
- **review-gate**: CI gates, post-merge verification
- **bd**: Context pruning, message format
- **infrastructure**: Security, disk space

2 issues closed as duplicates:
- skills-gyvt → merged into skills-vdup (retry limits)
- skills-8umb → merged into skills-8hyz (context pruning)

See epic comments for full architectural rationale.

[HQ:arch:2026-01-12T09:35:58-08:00] Architectural review: HQ should be thin orchestration layer. Reclassifying issues to proper layers:

LAYER ASSIGNMENTS:
- HQ: Orchestration decisions (what to work on, approve/reject, WIP limits)
- review-gate: Quality enforcement (CI gates, test verification, evidence)
- worker CLI: Lifecycle & isolation (state machine, retry counts, rebase, launch)
- bd: Issue tracking & messaging (context pruning, message format)
- infrastructure: Runtime concerns (sandboxing, disk space)

ISSUES BEING RECLASSIFIED:
- CI/test gates → review-gate
- Retry counting → worker CLI (merge with skills-vdup)
- Context bloat → bd (merge with skills-8hyz)
- Rebase handling → worker CLI
- Security/sandbox → infrastructure
- Resource exhaustion → infrastructure
- Worker launch → worker CLI
- Post-merge verification → review-gate
- Stale salvage → worker CLI

ISSUES STAYING IN HQ:
- WIP limits, DoD checklist, communication templates, core loop, dependency scoping


Create initial scenario suite (easy/medium/hard)

Write 6-9 scenarios across difficulty levels:

Easy (clear spec, single file):
- Add factorial function
- Fix typo in config
- Add CLI flag

Medium (requires understanding context):
- Refactor function to use new pattern
- Add caching to existing endpoint
- Write tests for existing code

Hard (ambiguous, multi-file, debugging):
- Fix race condition
- Migrate to new library version
- Resolve conflicting requirements

Pausing - need to validate approach with simpler spike first


Create hq-status script

Unified status view across all coordination layers.

Shows:
- bd ready (available work)
- worker status (active workers)
- review-gate status (pending reviews)
- Recent bd comments (coordination messages)

Usage: hq-status [--json]

Output: skills/hq/scripts/hq-status

Completed - skills/hq/scripts/hq-status created


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.


Consider logging cleanup failures in removeWorktree/removeBranch

[ERROR] LOW git.nim:55,60,62 - Cleanup operations ignore failures. May leave orphaned resources. Consider logging failures for debugging.


Design: Role boundaries with tool constraints

Prevent role collapse footgun (planner writing code, tester refactoring). Implement tool-level constraints per agent type: some agents read-only, some propose patches only, only orchestrator commits. Reject outputs that violate role boundaries. From orch consensus and HN practitioner feedback.


HQ: WIP limits and capacity management

**Raised by:** gpt (primary), gemini

**Problem:**
HQ becomes a bottleneck if constantly spawning, reviewing, commenting, merging. Without limits, coordination overhead dominates. Can spawn too many workers and exhaust resources.

**gpt:**
> "HQ becomes a human-like project manager... this doesn't scale unless review time is small and predictable. Cap WIP (workers in WORKING) based on HQ review bandwidth; enforce WIP limits like Kanban. Don't spawn new workers if >N in review or if HQ backlog exists."

**gemini:**
> "Dispatch: Spawn new work only if capacity allows."

**Suggested fixes:**
1. Max workers in WORKING limit
2. Max open PRs / IN_REVIEW limit
3. Prioritize by dependency chain + risk + expected review time
4. Session budget: max workers, max retries, cooldown policy
5. Rate limits on spawning


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


Design: Worker state machine (ASSIGNED→WORKING→REVIEW→MERGED)

Design: Worker state machine

Implementation: Nim (state enum, transition guards)
Design doc: docs/design/worker-state-machine.md

States:
- ASSIGNED → WORKING → IN_REVIEW → APPROVED → COMPLETED
- CONFLICTED (rebase conflict)
- FAILED (error or cancel)

Key patterns:
- Compare-and-set with BEGIN IMMEDIATE
- STALE computed from heartbeat age (not persistent)
- State derived from SQLite, JSON cache optional

See: skills-q40 for language decision

Design complete. 8 states: IDLE → ASSIGNED → WORKING → IN_REVIEW → APPROVED → COMPLETED, plus STALE and FAILED. File-based coordination using atomic rename pattern. Stale detection via heartbeat + PID checks. Integrates with review-gate, message passing, and branch isolation.

Implemented in worker CLI - spawn, status, state machine, branch isolation all working


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.


Design: Event notification vs polling for agent coordination

From orch architecture review.

Current: Agents poll (worker status, bd list) to check state.

Options:
A) Keep polling - simple, stateless, fits "Lego brick" philosophy
B) File watcher (inotify) - wake agents when state changes
C) Simple webhook/callback - agent registers interest
D) bd watch command - blocking wait for changes

Tradeoffs:
- Polling: simple but wasteful, latency
- Events: efficient but complex, requires daemon/watcher

Recommendation needed: Is polling sufficient for our scale?


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.


Remove unused imports in db.nim

[DEAD] LOW db.nim:9 - strformat and strutils imported but unused. Compiler warns about this. Remove unused imports.


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


infra: Ephemeral namespaced environments

Solve shared state pollution footgun. Each worker branch gets: namespaced DB (schema prefix or separate DB), isolated Redis namespace, separate queues, namespaced feature flags. Agents never touch shared prod-like state. Idempotent migrations and fixture loaders. From HN practitioner feedback on database isolation.

[RECLASSIFY:2026-01-12T10:10:20-08:00] Moved to infrastructure layer. Environment isolation is runtime infrastructure.


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


Worker done fails: worktree path is relative, not absolute

## Bug
When running `worker done` from inside a worktree, the rebase fails because the stored worktree path is relative.

## Reproduction
1. worker spawn test-001
2. cd worktrees/test-001
3. (make changes, commit)
4. worker done

## Error
```
fatal: cannot change to 'worktrees/test-001': No such file or directory
```

## Root Cause
- `createWorkerContext` stores whatever path is passed (relative)
- `done` uses `ctx.worktree` for git operations
- When running from inside worktree, relative path doesn't resolve

## Existing tests don't catch this
test-worker.sh bypasses `done` by manually setting state to IN_REVIEW.

## Fix Options
1. Store absolute path in context (cleanest)
2. Resolve path in `done` relative to repo root
3. Always run git operations from repo root

## Found By
Spike: skills-6n4u - manually testing Claude in worker context

Fixed in utils.nim - worktreePath now returns absolute path using findMainRepoDir()


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


Extract msToUnix helper for repeated div 1000

[SMELL] LOW state.nim - 'div 1000' for ms to seconds conversion repeated 8 times. Add helper proc msToUnix(ms: int64): int64 in types.nim.


Fix P1 security bugs (genOid, HeartbeatThread)

Two critical security/safety issues:

1. genOid() - skills-0wk
   - Currently uses rand(25) without randomize()
   - IDs are predictable/deterministic
   - Fix: Use std/sysrand for crypto-safe randomness, or call randomize() at startup

2. HeartbeatThread - skills-bk7x
   - Uses manual alloc0/dealloc
   - Risk of memory leak if startup fails, use-after-free if caller holds reference
   - Fix: Use 'ref HeartbeatThread' with GC management

Parent: skills-g2wa

Both P1 security bugs fixed: genOid uses sysrand, HeartbeatThread uses ref type


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.


Agent Governance: Quality gates and review patterns

Patterns for ensuring quality and appropriate human oversight in multi-agent workflows.

Covers:
- Review processes (who reviews, when, how)
- Role boundaries (what agents can/cannot do)
- Veto and escalation patterns
- Evidence collection for handoffs
- Stuck agent detection and intervention

These patterns apply across HQ, workers, and any future agent types.


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


Spike: manually test Claude in worker context

Simple experiment - no harness, no automation.

## Goal
Learn what happens when Claude tries to complete a task using the worker system.

## Steps
1. Set up a simple fixture (python-math-lib exists)
2. worker spawn test-spike
3. cd into worktree
4. Invoke Claude with task: "Add a factorial function to src/math_utils.py"
5. Include system context about worker commands (start, done, heartbeat)
6. Watch what happens

## Observe
- Does Claude understand the worker flow?
- Does it run worker start / worker done correctly?
- Does it complete the task?
- How many turns? What goes wrong?
- What prompting helps?

## Output
Notes on what worked, what didn't, what's needed.
Inform whether we need the full harness or something simpler.

Spike completed successfully.

Observations:
1. Worker flow works: spawn → start → work → done → approve → merge
2. Found and fixed bug: relative worktree paths (skills-5ry7)
3. Claude (me) completed the task using worker CLI without special prompting
4. ~7 tool calls to complete simple task
5. Test script needed sqlite3 in PATH - added check

The worker system is functional for basic agent tasks.


HQ: Dependency deadlocks and task scoping

**Raised by:** flash-or, gpt

**Problem:**
Real-world coding is rarely perfectly modular. Worker A adds DB field, Worker B needs that field. bd ready is too simple - doesn't detect partial dependencies or cross-cutting changes.

**flash-or:**
> "Deadlocks. 'bd ready' is too simple a check. Implement a 'Blocks/Blocked By' metadata in bd. HQ needs to be able to pause Worker B's spawn until Worker A's merge is complete."

**gpt:**
> "How to split a too-big issue into smaller ones (and who does it). How to handle cross-cutting changes that touch multiple tasks (and merge ordering). Add a 'triage & slicing' step before spawning."

**Suggested fixes:**
1. Better dependency modeling in bd (partial deps)
2. Triage & slicing step before spawn
3. "mutex areas" for shared modules/config
4. Conflict prediction (recent churn/hot files)
5. Architectural guardrails for risky areas


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


Validate taskId to prevent path traversal and command injection

[SECURITY] HIGH git.nim:36,37,53,59,89 - taskId used unsanitized in branch names and file paths. If taskId contains '../' or shell metacharacters, could escape worktree dir. Validate taskId matches safe pattern (alphanumeric + dash/underscore only).


Add LLM-as-judge verification

Use an LLM to evaluate task completion quality.

Components:
- Judge prompt template
- Rubric format (list of criteria)
- Scoring mechanism (0-1 per criterion, aggregate)
- Model selection (haiku for cost, sonnet for quality)

Should take: task description, rubric, code diff/result
Should output: score, reasoning, pass/fail per criterion


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.


Design: Rollback strategy for failed workers

Consensus gap: No rollback strategy. Handle: stuck workers, rejected reviews, merge conflicts. Branch archive/delete, state reset for re-assignment, evidence preservation for debugging.


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.


Verify getBranchStatus() usage or remove

[DEAD] LOW git.nim:130-143 - getBranchStatus() may be unused. Verify usage across codebase, delete if unused.


Evaluate: Git bundle checkpoints (SkillFS pattern)

SkillFS pattern: every agent sandbox is a git repo. Session ends → git bundle stored. New session → restore from bundle, continue where left off. Provides: persistence across sessions, full audit trail via git log, crash recovery. Evaluate if this fits our architecture or if worktrees are sufficient. See github.com/mupt-ai/skillfs


Add error context to createDir/openDatabase in openBusDb

[ERROR] LOW db.nim:97-98 - createDir and openDatabase can fail with unclear exceptions. Consider wrapping with context for permission errors, disk full, etc.

Implemented consistent error handling strategy


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.


Extract common transaction helper for transition functions

[REDUNDANCY] MED state.nim:31-74,76-114 - transition() and transitionToFailed() have near-identical structure. Extract common helper: withTransaction(db, taskId, body) or similar.


bd: Context pruning for comments

From orch consensus on bd comments as message layer.

Problem: As agents add comments, context size grows unbounded.

Solutions to design:
1. bd comments --last N (filter to recent)
2. bd comments --since "1 hour ago"
3. Periodic "summary" comments that checkpoint state
4. Archive old comments to separate file
5. bd comments --summarize (LLM summary of thread)

This enables bd comments to be the inter-agent message layer without context explosion.

[HQ:merge:2026-01-12T09:36:38-08:00] Merged feedback from skills-8umb (orch consensus):

PROBLEM (flash-or, gemini, gpt - all three flagged this):
BD comments will explode with heartbeats/status updates. LLMs have 'middle-loss' - if requirements at top and 50 status comments at bottom, agents lose sight of goal.

QUOTES:
- flash-or: 'Heartbeats should update a single last_seen field, not append comments'
- gemini: 'You need bd show --summary or --limit... critical dependency for launch'
- gpt: 'Enforce structured updates and latest instruction pinning'

SUGGESTIONS:
1. State vs Log distinction - heartbeats update metadata, not comments
2. bd show --summary or --limit command
3. Periodic 'state summary' comments in fixed schema
4. 'Latest instruction' pinning (single canonical HQ comment)

OWNER: bd CLI feature, not HQ logic

[RECLASSIFY:2026-01-12T10:06:41-08:00] Moved to bd layer. Context management is a bd CLI feature.


infra: Worktree disk space and dependency caching

**Raised by:** gemini

**Problem:**
Git worktrees share .git but NOT ignored build artifacts. Spawning 5 workers on Node.js or Rust project downloads 5GB of dependencies (node_modules, target/).

**gemini:**
> "Git worktrees share the '.git' folder, but they do *not* share ignored build artifacts. If you spawn 5 workers on a Node.js or Rust project, you might download 5GB of dependencies. Missing: A caching strategy or a 'pnpm/yarn' shared cache enforcement."

**Suggested fixes:**
1. Shared dependency cache (pnpm store, cargo registry)
2. Disk space monitoring before spawn
3. Cleanup policy for completed worktrees
4. Consider shallow worktrees or sparse checkout

[RECLASSIFY:2026-01-12T09:48:33-08:00] Moved from HQ to infrastructure layer.

Disk space management and dependency caching are infrastructure concerns. HQ shouldn't manage node_modules or cargo caches.


Consider moving query procs from state.nim to db.nim

[BOUNDARY] LOW state.nim:116-180 - getState, getWorker, getAllWorkers are query/repository functions in state machine module. Consider moving to db.nim or queries.nim.


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


HQ: Context bloat from BD comment pollution

**Raised by:** flash-or, gemini, gpt (all three)

**Problem:**
Using bd comments for heartbeats and status updates will explode the issue history. LLMs have "middle-loss" problem - if task requirements are at top and 50 status comments at bottom, agents lose sight of the original goal.

**flash-or:**
> "Heartbeats should update a single 'last_seen' field in the worker metadata, not append a new comment to the issue."

**gemini:**
> "If a worker gets stuck in a loop and posts 50 status updates, HQ's context window fills with noise. You need a 'Context Pruning' strategy... this is a critical dependency for launch."

**gpt:**
> "Comments become long, repetitive, and unsearchable. Critical instructions get buried. Enforce structured updates and 'latest instruction' pinning."

**Suggested fixes:**
1. State vs Log distinction - heartbeats update metadata, not comments
2. bd show --summary or --limit command
3. Periodic "state summary" comments in fixed schema
4. "Latest instruction" pinning (single canonical HQ comment)

**Related:** skills-8hyz (Context pruning for bd comments)

Duplicate of skills-8hyz (Context pruning for bd comments). Merging orch consensus feedback into that issue.


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.


Handle or log fetch failure in createWorktree

[ERROR] MED git.nim:40 - Fetch failure silently ignored before creating worktree. If fetch fails, branch may be stale. Log warning on fetch failure, or use runGitCheck if required.


Log errors in tryClaim before silent rollback

[ERROR] MED db.nim:243-245 - tryClaim catches CatchableError and silently returns false. Can't distinguish 'already claimed' from 'DB error'. Log exception before rollback.


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


Update outdated documentation in skills repo

README.md is missing entries for: doc-review, hq, ops-review, playwright-visit, review-gate. Need to verify status and add them.


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


HQ: Definition of Done checklist

**Raised by:** gpt (primary), flash-or

**Problem:**
"Approve when tests pass + meets requirements" is vague. No explicit acceptance criteria, no checklist per issue type, no non-test validation steps (lint, typecheck, migrations, docs).

**gpt:**
> "Missing: A required checklist per issue type (bugfix vs feature vs refactor). Explicit acceptance criteria pulled from the issue and reiterated in HQ's first comment. Non-test validation steps (lint/typecheck, migrations, docs, perf, backward compatibility). 'No tests exist' path."

**flash-or:**
> "Define 'Definition of Done' (DoD): Explicitly list that DoD includes 'Tests passing in worker's environment.'"

**Suggested fixes:**
1. Standard DoD template HQ posts to issue at kickoff
2. Review checklist (tests, lint, security, docs, rollout/compat)
3. Per-issue-type requirements (bugfix vs feature vs refactor)
4. "No tests" path with compensating validation
5. Codify with tooling: formatter, lint rules, pre-commit, typechecker


Add schema migration pattern for future DB changes

[EVOLVE] MED db.nim:92 - schema_version='1' exists but no migration logic. initSchema() always runs full schema. Add version check + migration proc pattern for ALTER TABLE scenarios.


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)


review-gate: Post-merge verification and rollback

**Raised by:** gpt

**Problem:**
What if merge succeeds but breaks master? CI fails after merge? No revert procedure defined.

**gpt:**
> "Add a 'post-merge verification' stage: Merge → CI required → only then 'bd close'. Define revert procedure and who owns it (HQ vs new worker). Optionally enable 'merge queue' semantics."

**Suggested fixes:**
1. merged_pending_ci status before done
2. Post-merge CI verification required
3. Revert playbook section
4. "fix-forward" task spawning on breakage
5. Consider merge queue semantics

[RECLASSIFY:2026-01-12T09:42:04-08:00] Moved from HQ to review-gate layer.

Post-merge CI verification is quality enforcement. review-gate or CI should handle this, not HQ logic.


Build property-based verification

Verification checks that can be automated:
- file_exists, dir_exists
- function_defined (AST parsing)
- tests_pass (run pytest/npm test/etc)
- compiles (language-specific)
- no_new_lint_errors
- git_state (branch merged, worktree cleaned, etc)

Should be composable and extensible.

Pausing - need to validate approach with simpler spike first


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.


Use parseEnum for heartbeat status instead of case statement

[SMELL] LOW worker.nim:276-280 - Status string parsed with case statement with silent fallback. Use parseEnum or direct HeartbeatStatus input, error on invalid.


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


worker CLI: spawn default branch crash on non-integration repo


Replace manual alloc0/dealloc with ref HeartbeatThread

[SMELL] HIGH heartbeat.nim:70,100 - Uses alloc0/dealloc for HeartbeatThread instead of GC-managed ref. Risk of memory leak if startup fails, use-after-free if caller holds reference after stop. Use 'ref HeartbeatThread' instead.

Fixed: HeartbeatThread now uses ref object with GC management instead of manual alloc/dealloc


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


Document SQLite compile flags in config.nims

[EVOLVE] LOW - SQLite compile flags (SQLITE_THREADSAFE, SQLITE_ENABLE_JSON1, SQLITE_OMIT_LOAD_EXTENSION) are hardcoded. Add comments explaining purpose.


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)


Integrate: review-gate with worker primitives

Connect existing review-gate CLI with new worker system.

## Current state
review-gate CLI exists with:
- check/enable/approve/reject
- Circuit breaker (3 strikes)
- Stop hook integration (for Claude)

## Integration needed
- worker spawn enables review-gate automatically
- worker status shows review state
- worker approve/reject wraps review-gate
- Evidence artifacts feed into review-gate

## File coordination
.worker-state/X.json includes:
  - review_session_id (links to .review-state/)
  - needs_review: true/false
  - review_status: pending/approved/rejected

MVP Tier 1: Wire review-gate to worker state machine

Integrated review-gate with worker: spawn enables review, status/show display review state, approve/reject update review-gate, cancel/merge clean up review state


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'


Design worker system prompt template

Create the system prompt/context that spawned workers receive.

Contents:
- Role definition (you are a worker agent)
- Task context (from bd issue or description)
- Available tools (worker start/done/heartbeat, bd comments)
- Completion criteria
- How to signal blockers/questions
- How to hand off for review

Output: skills/hq/templates/worker-system.md

Completed - skills/hq/templates/worker-system.md created with role definition, available commands, communication protocol, and completion criteria


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


Design: Negative permission pattern

Permission escalation via exclusion, not approval.

## Pattern (from GPT brainstorm)
Instead of asking 'can I do X?', agent asks:
'Which of these should I NOT do?'
  [ ] Delete migrations
  [ ] Modify auth code
  [x] Add new endpoint (safe)

Human clicks exclusions → fast.

## Implementation
- worker permit X - answers permission request
- Worker writes permission request to .worker-state/X.json
- Orchestrator/human sees it via worker status
- Human responds with exclusions
- Worker continues with constraints

## Benefits
- Faster than line-by-line approval
- Human sets constraints, not line edits
- Trains agents to propose options


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.


Extract loadContextFromPath helper in context.nim

[REDUNDANCY] LOW context.nim:21-23,31-33 - Same read+parse pattern repeated. Extract: proc loadContextFromPath(path: string): WorkerContext


Consolidate isStale() and staleLevel() logic

[SMELL] MED state.nim:214-223,225-241 - Both compute heartbeat age with overlapping checks. Have isStale() call staleLevel() \!= 'ok', or extract shared ageStatus() helper.


HQ: Structured communication templates

**Raised by:** gpt (primary), gemini

**Problem:**
BD comments as message bus lacks structure. Questions/answers get buried. No threading. No way to signal "requires HQ decision" vs "FYI". No attachments/artifacts.

**gpt:**
> "Require periodic worker 'state summaries' in a fixed schema (Summary / Risks / Next / Questions / Diffstat). Have HQ post a running 'Decision Log' comment for traceability."

**Suggested templates:**

**HQ kickoff comment:**
- Scope (in/out)
- Acceptance criteria bullets
- Required checks (tests/lint/typecheck)
- Risk areas / files
- "Ask before changing X"

**Worker update (every heartbeat):**
- What changed
- What's next
- Blockers/questions
- Commands run + results
- Link to diff/commits

**Suggested fixes:**
1. Kickoff template posted by HQ
2. Periodic state summary schema for workers
3. Decision log comment (edited/superseding)
4. "Latest instruction" pinning


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)


Extract column width constants for status table

[EVOLVE] LOW worker.nim:84,104-108 - Column widths hardcoded (14,12,8,12,8). Extract to constants or compute dynamically.


Verify usage of BusJsonlPath, BlobsDir, WorkersDir constants

[DEAD] LOW - Constants defined in types.nim:64-66 but may be unused. Verify usage in db.nim/state.nim, delete if unused.


Test HQ Workflow


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.


Architectural cleanup: error handling, validation, utilities

# Architectural Cleanup Epic

Code review of worker CLI scaffold revealed 44 issues that cluster into 5 systemic patterns.
Rather than fixing individually, address the underlying architecture.

## Pattern Analysis

| Pattern | Issues | % |
|---------|--------|---|
| Error handling gaps | 11 | 25% |
| DRY / missing utilities | 12 | 27% |
| Input validation missing | 4 | 9% |
| Dead code | 5 | 11% |
| Type safety | 3 | 7% |

## Recommended Approach

### 1. Create utils.nim module
Consolidates 12 extraction issues:
- branchName(taskId): string
- worktreePath(taskId): string
- msToUnix(ms: int64): int64
- optField[T](row, idx): Option[T]
- withTransaction template
- validateTaskId(id): string

### 2. Define error handling strategy
Template for 11 error issues:
- Wrap boundary operations (file I/O, git, DB) with context
- Consistent exception types or Result pattern
- Structured logging to stderr

### 3. Fix P1 security issues
- genOid(): Use std/sysrand or proper UUID
- HeartbeatThread: Use ref type, not alloc0/dealloc

### 4. Module reorganization (optional)
- Move Message type to types.nim
- Move query procs from state.nim to db.nim
- All helpers to utils.nim

## Success Criteria
- No silent failures in error paths
- taskId validated at CLI entry points
- Common patterns extracted to utils.nim
- P1 security bugs fixed
- Compiler warnings resolved (unused imports)

## Related Issues
P1 bugs: skills-0wk, skills-xcl, skills-73yu, skills-bk7x
Error handling: skills-266, skills-8xv, skills-8vdo, skills-n6zf, skills-tdfm, skills-koes, skills-xgh0, skills-8bi, skills-2wjp, skills-3uv9
Extraction: skills-3d9o, skills-dtk, skills-8fd, skills-dszn, skills-qiq0, skills-luzk, skills-5x2o, skills-r3k, skills-2xc, skills-f8yd, skills-y76g, skills-sisi
Validation: skills-vuj2, skills-16zf
Dead code: skills-ghlb, skills-5ax, skills-kvdl, skills-ib9u, skills-fdu
Type safety: skills-audh, skills-0dxd

All 4 sub-tasks completed: utils.nim, error handling, P1 security fixes, dead code cleanup


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


Remove unused 'by' parameter from approve() or implement reviewer tracking

[DEAD] MED worker.nim:121 - 'by' parameter declared but never used. Remove parameter, or implement reviewer tracking in state transition.


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.


HQ: Retry counting and infinite loop prevention

**Raised by:** flash-or, gemini, gpt (all three)

**Problem:**
HQ is stateless between sessions. "3 failures then escalate" won't work unless HQ explicitly reads failure count from history. Could burn $50 in API credits in 10 minutes if HQ and worker get into a loop.

**flash-or:**
> "If HQ gives bad instructions, the worker will fail. HQ might interpret this as 'worker failed' and spawn a *new* worker, or keep requesting changes with the same flawed logic. Implement a Global Token Budget per Task ID."

**gemini:**
> "Unless HQ explicitly reads the *count* of previous failures from bd history every time it wakes up, it won't know it's on attempt #4. 'worker status' must return retry_count."

**gpt:**
> "Escalate on *pattern*, not count. Add categories of failure (requirements unclear, infra failing, code quality mismatch) with different remedies."

**Suggested fixes:**
1. worker status returns retry_count
2. worker request-changes auto-increments counter in state
3. Global token/cost budget per task ID
4. Failure categories with different remedies
5. Hard stop for human intervention regardless of retry count

**Related:** skills-vdup (Retry limits and escalation policy)

Duplicate of skills-vdup (Retry limits and escalation policy). Merging orch consensus feedback into that issue.


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.


Return status from startGlobalHeartbeat when already running

[ERROR] LOW heartbeat.nim:107-108 - startGlobalHeartbeat silently returns if already running. Return bool or log that heartbeat is already active.