From 8e7587d20574111f35ea15f1d141cfc32a68ddf2 Mon Sep 17 00:00:00 2001 From: HeavyGee <133152184+heavygee@users.noreply.github.com> Date: Tue, 26 May 2026 17:25:41 +0100 Subject: [PATCH 0001/1600] docs(tooling): add agent tooling charter and PR review loop Fork-local operator docs for worktree discipline, driver soup, and enforced cold review before open-PR pushes (rubric aligned with upstream bot). Co-authored-by: Cursor --- docs/tooling/README.md | 159 +++++++++++++ docs/tooling/cold-pr-review-rubric.md | 65 ++++++ docs/tooling/driver-manifest.example.yaml | 14 ++ docs/tooling/driver-soup.md | 163 ++++++++++++++ docs/tooling/pr-review-loop.md | 253 +++++++++++++++++++++ docs/tooling/rebase-690-onto-692.md | 257 ++++++++++++++++++++++ docs/tooling/worktree-testing.md | 184 ++++++++++++++++ 7 files changed, 1095 insertions(+) create mode 100644 docs/tooling/README.md create mode 100644 docs/tooling/cold-pr-review-rubric.md create mode 100644 docs/tooling/driver-manifest.example.yaml create mode 100644 docs/tooling/driver-soup.md create mode 100644 docs/tooling/pr-review-loop.md create mode 100644 docs/tooling/rebase-690-onto-692.md create mode 100644 docs/tooling/worktree-testing.md diff --git a/docs/tooling/README.md b/docs/tooling/README.md new file mode 100644 index 00000000000..ba33f596d42 --- /dev/null +++ b/docs/tooling/README.md @@ -0,0 +1,159 @@ +# Agent Tooling — Meta Bot Charter + +This directory is the **canonical contract** for repo, testing, and dev maintenance across active agents on the HAPI hub and adjacent projects on this machine. + +**Meta bot** = the agent (or session) explicitly tasked with keeping this contract accurate, the machine helpers working, and feature agents from stepping on each other. + +Feature agents should **read the relevant doc below at session start**; meta bot reads **all of them** and fixes drift. + +--- + +## Scope + +| Layer | What | Meta bot owns | +|-------|------|----------------| +| **HAPI API / hub** | `~/coding/hapi` (upstream/main mirror), `~/coding/hapi-driver` (daily soup), `~/coding/hapi-*` PR worktrees, `hapi-active` symlink | Driver manifest rebuild, worktree hygiene, live swing | +| **Adjacent HAPI repos** | e.g. `hapi-garden`, `hapi-session-attention`, any `~/coding/hapi-*` worktree with an open branch | Same rules; confirm which tree is active before debugging "prod" | +| **Machine helpers** | `~/.local/bin/hapi-use-worktree`, `hapi-use-main`, `gh` wrapper, `pr-post-push-check*`, `hapi-sessions-health.sh` | Installed, executable, match docs | +| **Agent hooks** | `~/.claude/settings.json`, `~/.cursor/hooks.json`, `~/coding/AGENTS.local.md` | Policy text matches docs; note IDE vs CLI hook parity gaps | +| **Upstream boundary** | `tiann/hapi` PRs | No operator-local files, no AI attribution (see repo `AGENTS.local.md`) | + +**Not in scope for meta bot by default:** unrelated repos with no HAPI session unless the operator assigns them. + +--- + +## Tooling index + +| Doc | Purpose | +|-----|---------| +| [worktree-testing.md](./worktree-testing.md) | `hapi-active` symlink, `hapi-use-worktree`, service swing | +| [driver-soup.md](./driver-soup.md) | Daily driver manifest, merge-train PR worktrees, garden vs soup | +| [pr-review-loop.md](./pr-review-loop.md) | Pre-PR verification + cold review; pre-push open-PR gate; post-push PR comment poll | +| [cold-pr-review-rubric.md](./cold-pr-review-rubric.md) | Open-PR cold review bar (match upstream HAPI Bot severity) | + +--- + +## Meta bot responsibilities + +### 1. Worktree and live hub discipline + +- `~/coding/hapi` primary checkout tracks **upstream/main** (mirror) — not the daily driver. +- `~/coding/hapi-driver` is the **bleeding-edge soup** on `:3006` via `hapi-active` (see [driver-soup.md](./driver-soup.md)). +- **`hapi-driver` is read-only between rebuilds** — only `hapi-driver-rebuild` may change it; no hand-edits or `cp` patches. +- One agent → one PR worktree; never two agents in the same tree. +- Before any live test: `readlink -f ~/coding/hapi-active` matches the intended worktree. +- Every worktree: `hub/.env` → `~/.hapi/hub.env`. +- Frontend changes: `bun run build` in that worktree's `web/` before `hapi-use-worktree`. +- After testing: `hapi-use-driver` (legacy alias: `hapi-use-main`) unless operator wants the feature left live. + +See [worktree-testing.md](./worktree-testing.md). + +### 2. PR and review hygiene + +Enforce for **all** agents (IDE, Claude Code, Cursor CLI/HAPI): + +1. `/verification-before-completion` before any success claim or PR. +2. `/requesting-code-review` cold diff before `gh pr create` **and before every push** to a branch with an open PR (full `origin/...HEAD`; see [cold-pr-review-rubric.md](./cold-pr-review-rubric.md)). +3. After push to an open PR: unresolved thread poll (hook or manual). +4. Reply + **resolve** every addressed review thread. + +**Enforcement stack (weakest → strongest):** + +| Mechanism | Works in Cursor CLI/HAPI? | +|-----------|---------------------------| +| `~/coding/AGENTS.local.md` rules | Yes (if agent reads them) | +| `~/.local/bin/git` wrapper on `git push origin` (open PR) | Yes (stderr STOP reminder; non-blocking) | +| `~/.local/bin/gh` wrapper on `gh pr create` | Yes (stderr checklist) | +| Claude `PreToolUse` on `gh pr create` + `git push origin*` | Claude only | +| Claude `PostToolUse` post-push poll | Claude only | +| Cursor IDE `beforeShellExecution` / `postToolUse` | IDE yes; headless `agent` **often no** (probe 2026-05-26) | + +When CLI hooks do not fire, meta bot runs manual fallback after push: + +```bash +~/.local/bin/pr-post-push-check-core.sh "$(git branch --show-current)" +``` + +See [pr-review-loop.md](./pr-review-loop.md). + +### 3. Session and runner health + +Monitor hub-connected agents: + +```bash +hapi-sessions-health.sh # all sessions +hapi-sessions-health.sh --watch # BBS panel, 15s refresh +hapi-sessions-health.sh jellybot # filter by path/flavor/id +``` + +Meta bot triages `STUCK?`, `ZOMBIE`, and missing runner PIDs; escalates or kills stale processes per operator policy. + +Script: `scripts/hapi-sessions-health.sh` (repo root). + +### 4. Verification commands (HAPI default) + +From the **active worktree** (not necessarily main): + +```bash +bun typecheck # repo root +bun run test # cli + hub +cd web && bun run build # before hub UI test +``` + +Meta bot does not merge or declare "done" without evidence from these (or the repo's documented subset for a given change). + +### 5. Documentation maintenance + +When tooling behavior changes, meta bot updates **in the same change**: + +- The relevant file under `docs/tooling/` +- Repo `AGENTS.local.md` (operator-local, never upstream) +- Machine scripts at `~/.local/bin/` if source-of-truth moved + +Keep [pr-review-loop.md](./pr-review-loop.md) honest about IDE vs CLI hook support. + +### 6. Worktree lifecycle + +After merge: + +```bash +hapi-use-main +git worktree remove ~/coding/hapi- # or --force if needed +``` + +Meta bot periodically lists `git worktree list` and flags stale trees. + +--- + +## Session-start checklist (meta bot) + +```bash +readlink -f ~/coding/hapi-active +git worktree list +systemctl is-active hapi-hub.service +test -L ~/coding/hapi/hub/.env && test -L ~/coding/hapi-active/hub/.env +hapi-sessions-health.sh | head -40 +``` + +Then read both tooling docs if anything changed since last session. + +--- + +## Session-start checklist (feature agents) + +1. Read repo `AGENTS.local.md` (or `~/coding/AGENTS.local.md`). +2. Confirm `git branch --show-current` and `pwd` — worktree, not main checkout. +3. Skim [worktree-testing.md](./worktree-testing.md) if touching hub or systemd. +4. Skim [pr-review-loop.md](./pr-review-loop.md) before push/PR. + +--- + +## Escalation to operator + +Meta bot stops and asks when: + +- `hapi-active` points at unknown path +- Hub won't start after swing (missing build, bad env, port conflict) +- Multiple agents in `STUCK?` on same repo +- Hook/machine drift (doc says X, system does Y) +- Upstream PR would include operator-local or secret files diff --git a/docs/tooling/cold-pr-review-rubric.md b/docs/tooling/cold-pr-review-rubric.md new file mode 100644 index 00000000000..d6d9ac272b0 --- /dev/null +++ b/docs/tooling/cold-pr-review-rubric.md @@ -0,0 +1,65 @@ +# Cold PR Review Rubric + +Distilled from [`.github/prompts/codex-pr-review.md`](../../.github/prompts/codex-pr-review.md). Use this for `/requesting-code-review` before **every** push to a branch with an open upstream PR — not only at `gh pr create`. + +## Scope + +Review the **full PR diff** against the PR base branch: + +```bash +git fetch origin +git diff origin/...HEAD +``` + +On follow-up pushes, review the full diff again. Upstream bot re-runs on the latest head; your cold read must match that scope. + +## Severity levels + +| Level | Meaning | +|-------|---------| +| **Blocker** | Correctness bug, security hole, data loss, broken build/CI — must fix before push | +| **Major** | Regression, missing error handling, race/lifecycle bug, inadequate tests for changed behavior | +| **Minor** | Maintainability, naming, edge case with low blast radius | +| **Nit** | Style, optional polish — note only | + +Map to the review skill: Blocker/Major = Critical/Important; fix before push. + +## What to check + +1. **Correctness** — logic matches intent; state mutations traced through full lifecycle (connect → active → disconnect → reconnect where relevant). +2. **Security** — no secret leakage; validate untrusted input; no unsafe defaults. +3. **Regressions** — existing behavior preserved unless intentionally changed. +4. **Data loss** — persistence, sync, cache invalidation, versioned updates. +5. **Performance** — avoid obvious hot-path waste in changed code. +6. **Maintainability** — matches repo conventions (`AGENTS.md`, package READMEs, 4-space indent, strict TS). +7. **Tests** — changed behavior has coverage; note gaps as Major if behavior is non-trivial. + +## Review bar (match upstream bot) + +- **Findings first**, ordered by severity. +- **Evidence**: cite `path:line` from the diff. +- **No speculation** — if uncertain, say so or ask (max 4 questions). +- **Diff focus** — only flag issues on added/changed lines; use context lines to validate, not to nit unchanged code. +- **High signal** — if confidence < 80%, do not report as a finding. +- **Concrete fixes** — every Blocker/Major includes a minimal suggested change. +- **No praise** — issues and risks only. + +## HAPI-specific context + +Monorepo: `cli/`, `hub/` (or `server/`), `web/`, `shared/`. Run verification from repo root (`bun typecheck`, `bun run test`) for touched packages. + +## Output format (for your own notes) + +```markdown +**Findings** +- [Blocker|Major|Minor|Nit] Title — evidence `path:line` + Suggested fix: ... + +**Summary** +- N Blocker, N Major, ... +- Ready to push: yes/no +``` + +## After upstream bot comments + +Reply to each thread with fix SHA + one sentence. Resolve with `resolveReviewThread`. See [pr-review-loop.md](./pr-review-loop.md). diff --git a/docs/tooling/driver-manifest.example.yaml b/docs/tooling/driver-manifest.example.yaml new file mode 100644 index 00000000000..614238d7010 --- /dev/null +++ b/docs/tooling/driver-manifest.example.yaml @@ -0,0 +1,14 @@ +# Daily driver manifest — operator-local copy lives at ~/.config/hapi/driver-manifest.yaml +# Rebuild: hapi-driver-rebuild [--build-web] [--verify] [--activate] +# +# ~/coding/hapi-driver is READ-ONLY between rebuilds — only hapi-driver-rebuild may change it. +# Layer order matters. Each layer merges into driver/integration on top of base. + +base: upstream/main + +layers: + # Current daily-driver soup: pluggable voice + session list attention + - branch: feat/pluggable-voice-backend + - pr: 699 + + # Add unmerged PRs / branches below (top merges last): diff --git a/docs/tooling/driver-soup.md b/docs/tooling/driver-soup.md new file mode 100644 index 00000000000..b51e5d15e15 --- /dev/null +++ b/docs/tooling/driver-soup.md @@ -0,0 +1,163 @@ +# Daily Driver + Merge-Train Worktrees + +Three git layers on this machine: + +``` +~/coding/hapi primary repo checkout → upstream/main mirror (reference) +~/coding/hapi-main symlink → ~/coding/hapi (when primary is on main) +~/coding/hapi-driver driver/integration — bleeding-edge soup on :3006 +~/coding/hapi- one worktree per upstream PR you are formulating +~/coding/hapi-garden XR garden (API proxied to :3006 — rides the soup) +``` + +`hapi-active` → the **active HAPI tree**. Both `hapi-hub.service` and `hapi-runner.service` run from this symlink (same commit, same repo — hub + cli). + +--- + +## Unified stack switch + +HAPI is **one monorepo** (`hub/`, `cli/`, `web/`, `shared/`). A switch must move **hub and runner together** or you get split-brain (e.g. hub has `#684` Cursor models, npm runner does not). + +| Service | Runs from | +|---------|-----------| +| `hapi-hub.service` | `$HOME/coding/hapi-active/hub` | +| `hapi-runner.service` | `$HOME/coding/hapi-active/cli` via `hapi-runner-from-active` | + +```bash +hapi-use-worktree ~/coding/hapi-driver # prompts, then restarts hub + runner +hapi-use-driver # same, daily driver path +``` + +**Always prompts** before restart (kills remote agent sessions). Non-interactive requires `HAPI_STACK_SWITCH_YES=1`. + +After `hapi-driver-rebuild`, run `hapi-use-driver` when ready — rebuild alone does not restart services. + +## Daily driver (soup) + +**Manifest:** `~/.config/hapi/driver-manifest.yaml` (operator-local; example in repo) + +```yaml +base: upstream/main +layers: + - branch: feat/pluggable-voice-backend + - pr: 692 + - branch: origin/feat/session-list-attention +``` + +Layers merge **in order** onto `driver/integration` inside `~/coding/hapi-driver`. + +### Read-only driver tree + +**`~/coding/hapi-driver` is read-only between rebuilds.** The only supported way to change it is: + +```bash +# 1. Edit ~/.config/hapi/driver-manifest.yaml (add/remove layers) +# 2. Rebuild — resets to base + merges manifest (destroys local edits) +hapi-driver-rebuild --build-web [--verify] +# 3. When ready, swing live stack (prompts) +hapi-use-driver +``` + +**Forbidden on `hapi-driver`:** hand-edits, `cp` from other checkouts, local commits, `bun run build` as a substitute for rebuild. Uncommitted changes block rebuild (git stash) and are easy to lose. + +**To put new code on `:3006` without editing the driver tree:** merge-train PR in a worktree, then `hapi-use-worktree ~/coding/hapi-` (operator confirms). + +### Rebuild (does not restart hub by default) + +```bash +hapi-driver-rebuild # merge from manifest +hapi-driver-rebuild --build-web # also build web/dist +hapi-driver-rebuild --verify # typecheck + test +hapi-driver-rebuild --activate # calls hapi-use-worktree (hub + runner; prompts) +``` + +**Prefer** rebuild without `--activate`, then when ready: + +```bash +hapi-use-driver # restarts hapi-hub + hapi-runner together +``` + +### When upstream moves + +1. Edit manifest (drop merged PRs, add new ones) +2. `hapi-driver-rebuild --build-web --verify` +3. Garden smoke: `curl -sf http://127.0.0.1:3006/health` + quick VR/web check +4. Log drift in `~/coding/hapi-garden/GARDEN_LOGBOOK.md` if API changed + +--- + +## PR formulation worktrees (clean upstream PRs) + +**Never** file upstream PRs from `hapi-driver`. Work in dedicated trees. + +```bash +# Simple PR off upstream/main +hapi-worktree-create session-attention --branch feat/session-list-attention + +# Merge train: your PR stacks on unmerged work +hapi-worktree-create voice-labels --branch fix/voice-flavor-labels \ + --after feat/pluggable-voice-backend + +hapi-worktree-create stacked --branch feat/my-thing --after pr:692 +``` + +Each creates `~/coding/hapi-`, branch from `upstream/main` (or `--base`), optional `--after` merges. + +Before every commit / `gh pr create`: + +```bash +pwd +git branch --show-current +``` + +--- + +## Garden vs soup + +Garden shared mode (`garden-web.service` → `:5174` → API `:3006`) always talks to **whatever hapi-active runs**. + +- Soup changes hub routes/voice → may break garden until garden UI adapts +- Garden worktree (`hapi-garden`) is independent frontend; hub soup is the experiment surface +- Treat garden regressions as driver-manifest / API contract issues, not separate hub installs + +--- + +## Scripts + +| Command | Purpose | +|---------|---------| +| `hapi-driver-rebuild` | Rebuild soup from manifest | +| `hapi-worktree-create` | New PR worktree (+ merge train) | +| `hapi-use-worktree ` | Swing `hapi-active` + restart **hub + runner** | +| `hapi-use-driver` | Swing to daily driver soup | +| `hapi-runner-from-active` | systemd helper — runner CLI from `hapi-active/cli` | +| `hapi-sessions-health.sh` | Session monitor | + +Sources: `scripts/tooling/` in repo; installed to `~/.local/bin/`. + +--- + +## First-time setup + +```bash +mkdir -p ~/.config/hapi +cp ~/coding/hapi/docs/tooling/driver-manifest.example.yaml ~/.config/hapi/driver-manifest.yaml +# edit layers + +hapi-driver-rebuild --build-web --verify +hapi-use-driver # prompts; restarts hub + runner together +``` + +Primary mirror: + +```bash +cd ~/coding/hapi && git checkout main && git merge --ff-only upstream/main +ln -sfn ~/coding/hapi ~/coding/hapi-main +``` + +Move an existing feature branch off primary into its own worktree before switching primary to `main`: + +```bash +hapi-worktree-create pluggable-voice --branch feat/pluggable-voice-backend +cd ~/coding/hapi && git checkout main +``` diff --git a/docs/tooling/pr-review-loop.md b/docs/tooling/pr-review-loop.md new file mode 100644 index 00000000000..48983e3b01a --- /dev/null +++ b/docs/tooling/pr-review-loop.md @@ -0,0 +1,253 @@ +# PR Review Loop — Pre-PR Checks, Pre-Push Cold Review, and Post-Push Monitoring + +## Overview + +Three forcing functions keep PR quality high: + +1. **Pre-PR gate** — before `gh pr create` runs, the agent must confirm verification + cold-read review skills ran. +2. **Pre-push cold review (open PR)** — before `git push origin ` when that branch has an open PR, inject mandatory `/requesting-code-review` on the full PR diff (upstream bot bar). +3. **Post-push monitor** — after every push to a branch with an open PR, wait 5 minutes for bot reviewers, then surface unresolved threads + next-push reminder. + +Wired in Claude Code via `~/.claude/settings.json` and Cursor via `~/.cursor/hooks.json`. Terminal/Codex use `~/.local/bin/git` stderr wrapper. + +Rubric: [cold-pr-review-rubric.md](./cold-pr-review-rubric.md) + +--- + +## Part 1 — Pre-PR Gate + +### Purpose + +Agents have session familiarity with code they just wrote. This creates blind spots. +Two skills exist to counter this: + +- **`/verification-before-completion`** — forces the agent to run actual verification + commands and read the output before making any success claim. No "should work", + no partial checks. +- **`/requesting-code-review`** — dispatches a cold-read code review subagent that + traces every state mutation through the full lifecycle (connect → active → + disconnect → reconnect) as if seeing the code for the first time. + +Both must be run and findings addressed before a PR is filed. + +### Claude Code enforcement: PreToolUse hook + +In `~/.claude/settings.json`, a PreToolUse hook fires when `gh pr create` is about +to execute and injects a mandatory checklist into the model's context: + +```json +"PreToolUse": [ + { + "matcher": "Bash", + "hooks": [ + { + "type": "command", + "if": "Bash(gh pr create*)", + "command": "echo '{\"hookSpecificOutput\":{\"hookEventName\":\"PreToolUse\",\"additionalContext\":\"STOP — MANDATORY PRE-PR CHECKLIST: Before creating this PR you MUST have run /verification-before-completion (all checks passing with evidence) AND /requesting-code-review (cold diff read, all findings addressed). If you have not done BOTH, do not proceed — stop and run the skills first.\"}}'" + } + ] + } +] +``` + +The `additionalContext` message is injected into the model's context window before +the `gh pr create` command executes, forcing a pause and checklist confirmation. + +### Cursor enforcement (global, `~/.cursor/hooks.json`) + +| Event | Script | Behavior | +|-------|--------|----------| +| `beforeShellExecution` | `~/.cursor/hooks/pr-before-shell-gates.sh` | On `gh pr create`: pre-PR checklist via `agent_message`. On `git push origin ` with open PR: cold-review STOP via `agent_message`. | +| `postToolUse` (matcher: `Shell`, timeout: 360s) | `~/.cursor/hooks/pr-post-push-check.sh` | After push: 5 min bot poll + unresolved threads + next-push reminder via `additional_context` | + +Shared logic: `~/.local/bin/pr-open-push-lib.sh` (branch/PR lookup, cold-review message), `~/.local/bin/pr-post-push-check-core.sh` (post-push poll). + +Policy: `~/coding/AGENTS.local.md` (all agents). Wrappers: `~/.local/bin/gh` (pre-PR create), `~/.local/bin/git` (open-PR push stderr reminder). + +**Cursor CLI / HAPI headless `agent`:** `beforeShellExecution` may not fire in `--output-format stream-json` sessions. Use `~/.local/bin/git` + AGENTS.local + manual cold review until hook parity lands. + +--- + +## Part 2 — Pre-Push Cold Review (Open PR) + +### Purpose + +Upstream HAPI Bot re-reviews the **full PR diff** on every push. Session familiarity after your last push creates blind spots. Before each `git push origin` on a branch with an open PR: + +1. `/requesting-code-review` on `origin/...HEAD` ([rubric](./cold-pr-review-rubric.md)) +2. `/verification-before-completion` on touched packages +3. Fix Blocker/Major before push + +### Claude Code: PreToolUse on `git push origin*` + +`~/.local/bin/pr-git-push-prehook-claude.sh` reads tool input, looks up open PR for branch, injects `additionalContext` STOP block. + +### Cursor: `beforeShellExecution` + +Same message via `agent_message` in `pr-before-shell-gates.sh`. + +### Terminal / Codex + +`~/.local/bin/git` prints the STOP block to stderr (non-blocking). Codex has no user-level PreToolUse hook — AGENTS.local + wrapper are the contract. + +--- + +## Part 3 — Post-Push Comment Monitor + +### Purpose + +After pushing to a branch with an open PR, wait 5 minutes for bot reviewers to process +the new commits, then surface any unresolved threads and latest comments so the agent +sees them automatically without being asked. + +### Claude Code Implementation + +Claude Code supports **PostToolUse hooks** — shell commands that run after a tool +executes, with the ability to inject text into the model's context via JSON output. + +#### Hook script: `~/.local/bin/pr-post-push-check` + +```bash +#!/usr/bin/env bash +# PostToolUse hook: after git push to a branch with an open PR, wait 5 minutes +# then check for unresolved review threads and new comments. +# Outputs additionalContext JSON so Claude sees the results automatically. + +set -euo pipefail + +input=$(cat) +cmd=$(echo "$input" | jq -r '.tool_input.command // ""') + +# Only trigger on git push to origin +[[ "$cmd" =~ ^git\ push\ origin ]] || exit 0 + +# Extract branch (last token after 'origin') +branch=$(echo "$cmd" | sed 's/.*origin[[:space:]]*//' | awk '{print $1}') +[ -z "$branch" ] && exit 0 + +# Find open PR for this branch +pr=$(gh pr list --head "$branch" --json number --jq '.[0].number' 2>/dev/null || true) +[ -z "$pr" ] || [ "$pr" = "null" ] && exit 0 + +echo "⏳ PR #$pr detected — waiting 5 minutes for bot review before checking comments..." >&2 +sleep 300 + +# Count unresolved threads +owner_repo=$(gh repo view --json nameWithOwner --jq '.nameWithOwner' 2>/dev/null || echo "") +owner=$(echo "$owner_repo" | cut -d/ -f1) +repo=$(echo "$owner_repo" | cut -d/ -f2) + +unresolved_count=$(gh api graphql -f query="{ + repository(owner:\"$owner\", name:\"$repo\") { + pullRequest(number: $pr) { + reviewThreads(first: 50) { + nodes { id isResolved } + } + } + } +}" --jq '[.data.repository.pullRequest.reviewThreads.nodes[] | select(.isResolved == false)] | length' 2>/dev/null || echo "?") + +# Grab latest comments (last 40 lines) +latest=$(gh pr view "$pr" --comments 2>/dev/null | tail -40 || echo "(could not fetch comments)") + +jq -n \ + --arg ctx "5-minute post-push check on PR #$pr: $unresolved_count unresolved thread(s). + +UNRESOLVED THREADS: $unresolved_count — reply and resolve any findings before proceeding. + +Latest comments: +$latest" \ + '{"hookSpecificOutput":{"hookEventName":"PostToolUse","additionalContext":$ctx}}' +``` + +#### Hook wiring: `~/.claude/settings.json` + +Add to the `hooks` object: + +```json +"PostToolUse": [ + { + "matcher": "Bash", + "hooks": [ + { + "type": "command", + "command": "cat | /home/heavygee/.local/bin/pr-post-push-check", + "timeout": 360, + "statusMessage": "Waiting 5 min for bot review on PR..." + } + ] + } +] +``` + +The hook receives the full tool input on stdin as JSON: +```json +{ "tool_name": "Bash", "tool_input": { "command": "git push origin feat/my-branch" } } +``` + +The script filters on the command string, so non-push Bash commands exit 0 immediately +with no output. + +`additionalContext` is injected into the model's next context window automatically — +Claude will see the unresolved thread count and comments without any user prompt. + +--- + +### Manual fallback (no hook / CI-only) + +If hooks are disabled, run the shared poll directly: +```bash +~/.local/bin/pr-post-push-check-core.sh +``` + +--- + +--- + +## What to do with findings + +When the hook reports unresolved threads: + +1. Read each finding carefully +2. Make the code fix (new commit) +3. Reply to the specific GitHub thread: + ```bash + gh api repos/tiann/hapi/pulls/692/comments//replies \ + -f body="Fixed in : " + ``` +4. Resolve the thread: + ```bash + gh api graphql -f query='mutation { + resolveReviewThread(input: {threadId: "PRRT_..."}) { + thread { id isResolved } + } + }' + ``` +5. Push again (which will trigger a new 5-minute wait) + +**Rule:** A finding is not done until it is replied to AND resolved. Unresolved threads +signal to maintainers that the issue is still open. + +--- + +## Finding thread IDs + +```bash +gh api graphql -f query='{ + repository(owner:"tiann",name:"hapi") { + pullRequest(number: 692) { + reviewThreads(first: 50) { + nodes { + id + isResolved + comments(first: 1) { + nodes { databaseId body } + } + } + } + } + } +}' --jq '.data.repository.pullRequest.reviewThreads.nodes[] + | select(.isResolved == false) + | {threadId: .id, commentId: .comments.nodes[0].databaseId, body: .comments.nodes[0].body[:80]}' +``` diff --git a/docs/tooling/rebase-690-onto-692.md b/docs/tooling/rebase-690-onto-692.md new file mode 100644 index 00000000000..894f7200aec --- /dev/null +++ b/docs/tooling/rebase-690-onto-692.md @@ -0,0 +1,257 @@ +# Rebase PR #690 onto post-#692 main + +## Context + +PR #690 (`feat(voice): dynamic settings voice picker`) and PR #692 +(`feat(voice): pluggable voice backend with Gemini Live & Qwen Realtime`) share +several files. #692 is intended to merge first. This document tells you exactly +what to do to land #690 cleanly afterward. + +**The good news:** the two PRs are mostly complementary. #692 adds multi-backend +infrastructure (Gemini Live, Qwen), #690 adds a voice picker UI for ElevenLabs +voices. They touch the same files in different places, not the same lines. + +--- + +## Branch setup + +```bash +# Work in the existing worktree for #690 +cd ~/coding/hapi # or wherever feat/voice-picker-upstream lives +git branch --show-current # confirm: feat/voice-picker-upstream + +# Fetch the merged upstream +git fetch upstream +git rebase upstream/main +``` + +The rebase will likely pause on conflicts in several files. Work through them +file by file using the guide below. + +--- + +## File-by-file conflict guide + +### 1. `hub/src/web/routes/voice.ts` — main conflict zone + +**What #692 brought:** +- `GET /voice/backend` — returns configured backend type +- `GET /voice/gemini-token` — proxies Gemini API key, returns WS proxy URL +- `POST /voice/qwen-token` — Qwen/DashScope token +- `buildVoiceWsUrl()` helper (uses URL API to avoid double-slash on trailing HAPI_PUBLIC_URL) +- Restructured `POST /voice/token` (ElevenLabs only, simpler — no voice-agent mapping) + +**What #690 adds on top:** +- `voiceId` field on the token request schema +- `parseVoiceAgentMap()` — parses `ELEVENLABS_VOICE_AGENT_MAP` env var +- `getOrCreateAgentIdForVoice()` — per-voice ElevenLabs agent creation/lookup +- `getVoiceAgentName()` — generates names like `"Hapi Voice Assistant [voice:voiceId]"` +- `createNamedHapiAgent()` — creates agents with custom names and voice IDs +- `findHapiAgent()` enhanced to accept optional `agentName` +- Enhanced `POST /voice/token` with multi-fallback voice selection logic +- `GET /voice/voices` — returns user's ElevenLabs voice list with metadata +- `POST /voice/telemetry` — voice analytics events + +**Strategy:** Keep everything #692 added. Bolt #690's additions onto it: +- The enhanced token endpoint logic wraps around #692's simpler version +- The `/voice/voices` and `/voice/telemetry` endpoints are additive (no conflict) +- `buildVoiceWsUrl()` from #692 is correct — do not replace it + +--- + +### 2. `hub/src/web/routes/voice.test.ts` — additive + +#692 has its own test additions. #690 adds a comprehensive suite for: +- `GET /voice/voices` (auth, API key handling, field mapping) +- `POST /voice/token` with voice-specific agent logic (mapping preference, fallbacks) + +These test different things. Accept both test blocks. The auth middleware pattern +in #690's tests should match how #692 wired auth — check the route registration +in `hub/src/web/server.ts` to confirm the middleware order is the same. + +--- + +### 3. `shared/src/voice.ts` — keep #692 version + +**#692 adds** (all net-new, keep everything): +- `VOICE_CHINESE_LANGUAGE_BLOCK` +- `VoiceToolDefinition`, `GeminiLiveConfig` interfaces +- `buildGeminiLiveConfig(language?)`, `buildGeminiLiveFunctionDeclarations()` +- Constants: `GEMINI_LIVE_MODEL`, `QWEN_REALTIME_MODEL`, `QWEN_REALTIME_VOICE`, `DEFAULT_VOICE_BACKEND` +- `VoiceBackendType` = `'elevenlabs' | 'gemini-live' | 'qwen-realtime'` + +**#690's `VOICE_SYSTEM_PROMPT`** is an older, shorter version. **#692's version is +more complete** (has CRITICAL RULE, Tool Usage section, First Interaction section, +identity guardrails). **Keep #692's prompt, discard #690's.** + +The `VOICE_FIRST_MESSAGE` constant is identical in both — no conflict. + +--- + +### 4. `web/src/api/voice.ts` — additive + +**#692 adds:** `fetchQwenToken()`, `fetchGeminiToken()`, backend-related types and +helpers (ElevenLabs agent management moved server-side). + +**#690 adds:** `fetchVoices()`, `sendVoiceTelemetry()`, `VoiceTokenRequest` with +`voiceId` field. + +**Strategy:** Keep #692's structure. Add these two functions from #690: +```typescript +export async function fetchVoices(api: ApiClient): Promise<{ voices: VoiceInfo[] }> { ... } +export async function sendVoiceTelemetry(api: ApiClient, event: TelemetryEvent): Promise { ... } +``` +Check that `VoiceInfo` and `TelemetryEvent` types are defined (they may be in +`web/src/lib/voices.ts` which #690 creates — see below). + +--- + +### 5. `web/src/api/client.ts` — additive + +**#692 adds:** `fetchVoiceBackend()`, `fetchQwenToken()`, `fetchGeminiToken()`. +Also `fetchVoiceToken()` already accepts `voiceId?: string` (compatible with #690). + +**#690 adds:** `fetchVoices()`, `sendVoiceTelemetry()`. + +**Strategy:** Accept #692's additions. Add #690's two missing methods. No structural +conflict — they call different endpoints. + +--- + +### 6. `web/src/lib/locales/en.ts` — additive, no conflict + +**#692 adds:** +```typescript +'settings.voice.proactive': 'Start voice session with summary', +'settings.voice.proactive.description': '...', +``` + +**#690 adds:** +```typescript +'settings.voice.voice': 'Voice', +'settings.voice.voiceDefault': 'Default', +``` + +Keep both groups. They are different keys. + +--- + +### 7. `web/src/lib/locales/zh-CN.ts` — same as en.ts + +Both sets of keys are additive. Keep both. + +--- + +### 8. `web/src/routes/settings/index.tsx` — main UI merge + +**#692 adds:** +- Proactive/reactive toggle (localStorage `hapi-voice-proactive`) +- Language selector for voice + +**#690 adds:** +- Voice picker UI with dynamic voice list, audio preview controls +- `PlayIcon` component +- `isVoiceOpen` state, voice selection state +- Calls `fetchVoices()` on mount (ElevenLabs API) +- Passes `voiceId` to `fetchVoiceToken()` via context or direct call +- Telemetry integration via `sendVoiceTelemetry()` + +**Strategy:** +1. Keep #692's proactive toggle and language selector as-is +2. Add #690's voice picker as a separate settings section — but make it + **backend-aware**, not ElevenLabs-only (see section below) +3. The picker should show for all three backends, with each surfacing + its own voice list + +**Do NOT gate the picker to ElevenLabs only.** All three backends have +voice options that users should be able to choose: + +| Backend | Voice source | Current default | +|---------|-------------|-----------------| +| ElevenLabs | Dynamic from `GET /voice/voices` (API) | env default | +| Gemini Live | Static list of prebuilt voices | `'Aoede'` (hardcoded) | +| Qwen Realtime | Static list of available voices | `'Mia'` (hardcoded in `QWEN_REALTIME_VOICE`) | + +**Correct architecture:** +1. Add `voiceName?: string` to `VoiceSessionConfig` (in `web/src/realtime/types.ts`, + added by #692) +2. Each backend session reads it: + - `GeminiLiveVoiceSession`: pass to `prebuiltVoiceConfig.voiceName` instead of + hardcoded `'Aoede'` + - `QwenVoiceSession`: pass to `session.update` `voice` field instead of + hardcoded `QWEN_REALTIME_VOICE` + - `RealtimeVoiceSession` (ElevenLabs): already passes `voiceId` to + `fetchVoiceToken()` — keep as-is +3. The picker in settings renders different options depending on active backend: + - ElevenLabs: dynamic fetch from `fetchVoices()` + - Gemini: static list — known prebuilt voices are: + `Aoede, Charon, Fenrir, Kore, Puck` (plus any others in the Gemini Live docs) + - Qwen: static list — check DashScope docs for available voice IDs +4. Selected voice is stored in a per-backend localStorage key + (e.g. `hapi-voice-gemini`, `hapi-voice-qwen`, `hapi-voice-elevenlabs`) so + switching backends doesn't clobber each other's selection + +--- + +### 9. `web/src/realtime/RealtimeVoiceSession.tsx` — verify only + +Both versions handle ElevenLabs only and should be compatible. Confirm #690's +version doesn't accidentally remove the multi-backend registration logic #692 added +(the `VoiceBackendSession` wrapper that switches between ElevenLabs / Gemini / Qwen). +If #690's version of this file predates that wrapper, **keep #692's version** and +only apply any ElevenLabs-specific changes #690 made on top. + +--- + +### 10. New files from #690 (no conflict, just verify they land) + +- `web/src/lib/voices.ts` — voice type definitions, `VOICES` constant, `getFallbackVoices()` +- `web/src/lib/voices.test.ts` — unit tests for voices lib +- `web/src/lib/voice-context.tsx` — React context for voice selection + +These files don't exist in #692's tree. They should apply cleanly. After rebase, +verify they compile (`bun run build` in `web/`). + +--- + +## After resolving all conflicts + +```bash +# Verify it builds +cd web && bun run build && cd .. + +# Run tests +bun test hub/src/web/routes/voice.test.ts +bun test web/src/lib/voices.test.ts + +# Force-push the rebased branch +git push origin feat/voice-picker-upstream --force-with-lease +``` + +Then check PR #690 — GitHub will update the diff automatically. Run +`/verification-before-completion` and `/requesting-code-review` before declaring +the rebase done. + +--- + +## Things to watch + +**ElevenLabs-specific agent logic stays server-side.** +`ELEVENLABS_VOICE_AGENT_MAP`, `getOrCreateAgentIdForVoice`, `createNamedHapiAgent` — +all of this is ElevenLabs infrastructure. Guard it at the route level in +`hub/src/web/routes/voice.ts` so it only runs when `VOICE_BACKEND=elevenlabs`. +The `/voice/voices` endpoint is also ElevenLabs-only — return 404 or an empty list +when the backend is Gemini or Qwen rather than calling the ElevenLabs API. + +**Voice selection is a UI concern for all three backends.** +The picker in the settings UI should work regardless of backend. Only the *data +source* for the voice list differs (dynamic API vs static constants). The +`VoiceSessionConfig.voiceName` field carries the selection through to whichever +session implementation is active. + +**Gemini prebuilt voice names** — at time of writing the available voices are +`Aoede, Charon, Fenrir, Kore, Puck`. Verify against the Gemini Live API docs before +hardcoding the static list; Google adds voices periodically. + +**Qwen voice IDs** — check DashScope realtime docs for the current list. `Mia` is +the current default set in `QWEN_REALTIME_VOICE` in `shared/src/voice.ts`. diff --git a/docs/tooling/worktree-testing.md b/docs/tooling/worktree-testing.md new file mode 100644 index 00000000000..af004aeae30 --- /dev/null +++ b/docs/tooling/worktree-testing.md @@ -0,0 +1,184 @@ +# Worktree Testing — Feature Branches Without Polluting Main + +## Problem + +A running systemd service needs a stable directory to execute from. If you do feature +work directly in `~/coding/hapi` (the primary checkout), you end up with: + +- Dirty working tree when you need a clean upstream/main reference +- Risk of accidentally committing local-only operator files (`.env`, `AGENTS.local.md`, etc.) +- No isolation between the **daily driver soup** and PR formulation worktrees +- Multiple agents working in the same directory at the same time causing conflicts + +**See [driver-soup.md](./driver-soup.md)** for the three-layer model (mirror / driver / PR worktrees). + +## Solution: Symlink Indirection + +``` +hapi-hub.service + ↓ WorkingDirectory +~/coding/hapi-active ←── symlink, swappable + ↓ currently points to +~/coding/hapi-driver (daily driver soup — target default) + or +~/coding/hapi- (worktree, under test) +``` + +The service units always point at `~/coding/hapi-active`. Swapping what that symlink +points to (and restarting **hub + runner**) is all it takes to test any branch, with zero +edits to systemd files. + +State lives entirely outside the repo at `~/.hapi/` (SQLite DB, JWT secret, tokens, +logs). Worktree swaps are transparent to it. + +--- + +## One-Time Setup (already done on this machine) + +### 1. Systemd units use the symlink path + +`/etc/systemd/system/hapi-hub.service`: +```ini +[Service] +User=heavygee +WorkingDirectory=/home/heavygee/coding/hapi-active/hub +EnvironmentFile=/home/heavygee/.hapi/hub.env +ExecStart=/home/heavygee/.bun/bin/bun run src/index.ts +Restart=on-failure +RestartSec=5 +``` + +`/etc/systemd/system/hapi-runner.service` — `ExecStart=/home/heavygee/.local/bin/hapi-runner-from-active` (CLI from `hapi-active/cli`, not npm global). + +### 2. `hapi-active` symlink created + +```bash +ln -sfn ~/coding/hapi-driver ~/coding/hapi-active # daily driver default +``` + +### 3. Hub env is canonical at `~/.hapi/hub.env` + +`hub/.env` in both main checkout and every worktree is a symlink to it: +```bash +ln -s ~/.hapi/hub.env ~/coding/hapi/hub/.env +``` + +Never create a separate `.env` with different keys. + +### 4. Helper scripts installed at `~/.local/bin/` + +Symlinks to `scripts/tooling/` in this repo: `hapi-use-worktree`, `hapi-use-driver`, `hapi-worktree-create`, `hapi-driver-rebuild`, `hapi-runner-from-active`. Legacy alias: `hapi-use-main` → same as `hapi-use-driver`. + +--- + +## Daily Workflow + +### Create a new feature worktree + +```bash +# Preferred — prints hapi-use-worktree command when done +hapi-worktree-create --branch feat/ + +# Manual — always branch from upstream/main +git worktree add ~/coding/hapi- -b feat/ upstream/main +ln -s ~/.hapi/hub.env ~/coding/hapi-/hub/.env +``` + +**Naming convention:** flat under `~/coding/` — `~/coding/hapi-`, never +a subdirectory. + +### Develop in the worktree + +```bash +cd ~/coding/hapi- +# edit, commit — all normal git operations work +# PRs must be created from here, not from ~/coding/hapi +git branch --show-current # confirm you're on the right branch before staging +``` + +### Test live against the running service + +```bash +hapi-use-worktree ~/coding/hapi- +``` + +This script: +1. Validates `hub/` exists in the target path +2. Creates `hub/.env` symlink if missing +3. Warns and optionally builds web (`bun run build`) if `web/dist/index.html` is absent +4. Swings `~/coding/hapi-active` to the worktree (`ln -sfn`) +5. Restarts **`hapi-hub.service` and `hapi-runner.service`** (prompts first) + +### Restore to daily driver + +```bash +hapi-use-driver +# legacy alias: hapi-use-main +``` + +Swings `hapi-active` back to `~/coding/hapi-driver` and restarts **hub + runner** (same prompt as any stack switch). + +### Verify after switch + +```bash +readlink -f ~/coding/hapi-active # must equal your worktree path +curl -sf http://127.0.0.1:3006/health +systemctl is-active hapi-hub.service hapi-runner.service +``` + +--- + +## Script source (canonical) + +Do not copy script bodies into this doc — they drift. Source of truth: + +| Installed | Repo path | +|-----------|-----------| +| `~/.local/bin/hapi-use-worktree` | `scripts/tooling/hapi-use-worktree.sh` | +| `~/.local/bin/hapi-use-driver` | `scripts/tooling/hapi-use-driver.sh` | +| `~/.local/bin/hapi-use-main` | legacy wrapper → `hapi-use-driver` (not `~/coding/hapi`) | +| `~/.local/bin/hapi-worktree-create` | `scripts/tooling/hapi-worktree-create.sh` | +| `~/.local/bin/hapi-runner-from-active` | `scripts/tooling/hapi-runner-from-active.sh` | + +`hapi-use-worktree` restarts **`hapi-hub.service` and `hapi-runner.service`** from the same tree. Non-interactive switch requires `HAPI_STACK_SWITCH_YES=1`. + +--- + +## Side Effects and Caveats + +**`garden-web.service`** — runs separately in `~/coding/hapi-garden/`, proxies to +hub on `:3006`. It is completely unaffected by worktree swaps. + +**State (`~/.hapi/`)** — the SQLite database, JWT secret, and session tokens all live +outside the repo. Swapping worktrees does not wipe sessions or require re-auth. + +**Web build** — the hub serves the web UI from `web/dist/`. If you have frontend +changes in your worktree, build before swinging: `cd ~/coding/hapi-/web && bun run build`. +`hapi-use-worktree` will warn you if `dist/index.html` is missing. + +**Multiple agents** — each agent should work in its own named worktree. Never have two +agents editing the same worktree simultaneously. The main checkout (`~/coding/hapi`) +is read-only reference — no agent commits there directly. + +**Cleanup** — when a feature branch is merged, remove its worktree: +```bash +git worktree remove ~/coding/hapi- +# or if it has uncommitted changes: +git worktree remove --force ~/coding/hapi- +``` + +--- + +## Adapting for Other Agents (Cursor, etc.) + +The mechanism is shell + symlinks — fully agent-agnostic. Read **`AGENTS.local.md`** and [driver-soup.md](./driver-soup.md) at session start. + +What agents need to know: +1. **`~/coding/hapi-driver` is read-only between rebuilds** — only `hapi-driver-rebuild` may change it (no edits, no `cp`, no local commits). Update `~/.config/hapi/driver-manifest.yaml` then rebuild. +2. **Never formulate upstream PRs in `~/coding/hapi-driver`** — use `~/coding/hapi-` worktrees +3. **`~/coding/hapi` primary checkout** should track `upstream/main` (mirror) — see [driver-soup.md](./driver-soup.md) +4. **Create PR worktrees** with `hapi-worktree-create` (prints the `hapi-use-worktree` line) or `git worktree add` +5. **Rebuild daily driver** with `hapi-driver-rebuild` — edit `~/.config/hapi/driver-manifest.yaml` first +6. **Swing live stack** with `hapi-use-worktree` / `hapi-use-driver` — **restarts hub + runner, kills sessions**; **operator must confirm** at `Proceed? [y/N]` (do not auto-answer unless explicitly told) +7. **`git branch --show-current` before every commit and `gh pr create`** +8. After "ready to demo", confirm `readlink -f ~/coding/hapi-active` matches the worktree — editing alone does not change `:3006` From 95976f8521775c7bbeac5694e43b758842e2d0b9 Mon Sep 17 00:00:00 2001 From: HeavyGee <133152184+heavygee@users.noreply.github.com> Date: Wed, 27 May 2026 01:14:04 +0100 Subject: [PATCH 0002/1600] docs(plans): add self-bootstrapping config plan Four-phase roadmap for self-configuring hapi: backend picker (Phase 1, ready to start after #692), SQLite config table, API key management UI, and first-run wizard. via [HAPI](https://hapi.run) Co-Authored-By: HAPI --- .../2026-05-25-self-bootstrapping-config.md | 141 ++++++++++++++++++ 1 file changed, 141 insertions(+) create mode 100644 docs/plans/2026-05-25-self-bootstrapping-config.md diff --git a/docs/plans/2026-05-25-self-bootstrapping-config.md b/docs/plans/2026-05-25-self-bootstrapping-config.md new file mode 100644 index 00000000000..82cf42071fb --- /dev/null +++ b/docs/plans/2026-05-25-self-bootstrapping-config.md @@ -0,0 +1,141 @@ +# Self-Bootstrapping Configuration + +**Status:** Planning +**Author:** HeavyGee +**Date:** 2026-05-25 + +## Vision + +Hapi should be self-configuring after a minimal bootstrap. API keys, voice backend selection, Telegram token, CORS origins — all entered through the web UI and stored in the hub's SQLite DB. The config file drops to the absolute minimum needed to start the process. + +--- + +## Minimal bootstrap (target) + +```bash +# All that should ever need to go in a file +HAPI_LISTEN_PORT=3006 +HAPI_PUBLIC_URL=https://your-domain +# JWT secret and CLI token auto-generated on first run (already works) +``` + +Everything else is configured through a first-run wizard or the settings page. + +--- + +## Phases + +### Phase 1 — Backend picker (follow-on to PR #692) + +Small, self-contained, concrete value now. + +- `GET /api/voice/backends` returns only the backends with keys configured on the hub +- Settings page adds a **Voice backend** dropdown — hidden if only one backend available +- Frontend passes selection to `VoiceBackendSession` +- ElevenLabs → voice picker still shown; Gemini/Qwen → voice picker hidden +- Selection stored in localStorage + +Files touched: `hub/src/web/routes/voice.ts`, `web/src/routes/settings/index.tsx`, `web/src/realtime/VoiceBackendSession.tsx` + +### Phase 2 — Config table in SQLite + +Introduces the persistence layer for runtime config. + +- New `settings` table: `key TEXT PRIMARY KEY, value TEXT, updated_at INTEGER` +- `getConfiguration()` checks DB first, falls back to env var, falls back to default +- Values written to DB survive restarts without touching the env file +- Keys that genuinely require restart (port, listen host, JWT secret) flagged as `restart_required` and handled separately +- No encryption initially — self-hosted assumption, SQLite file is already on a trusted host + +Hub files: `hub/src/store/`, `hub/src/configuration.ts` + +### Phase 3 — API key management UI + +Settings page sections for each integration, behind the existing auth wall. + +**Voice section:** +- ElevenLabs API key — masked input, **Test connection** button (calls `GET /voice/voices`, shows count) +- Gemini API key — masked input, **Test connection** button (hits Gemini models endpoint) +- DashScope API key — masked input, **Test connection** button +- Active backend dropdown (Phase 1, now reads from DB not env) + +**Notifications section:** +- Telegram bot token — masked input, **Test** button +- VAPID keys — auto-generated button + +**Hub section:** +- Public URL +- CORS origins +- (Port/host remain file-only — restart required, flag clearly) + +Each key: save → hub writes to DB → config layer picks up immediately, no restart. + +Web files: `web/src/routes/settings/index.tsx` (already the right place) +Hub files: new `hub/src/web/routes/config.ts` + +### Phase 4 — First-run wizard + +For new installs with no config at all. + +- Hub detects first run (no owner, no CLI token set) +- Serves a `/setup` route (pre-auth, but rate-limited / IP-gated) +- Step 1: Set admin password / generate CLI token — shown once, copy to CLI config +- Step 2: Public URL + optional CORS origins +- Step 3: Add at least one voice backend key (skippable) +- Step 4: Optional Telegram +- Done → redirect to normal app + +This is the "zero SSH" experience. Someone could install the binary, point a domain at it, open the URL, and be fully configured without ever touching a file. + +--- + +## Design decisions + +### Secrets in DB vs env + +Env vars are the conventional pattern for secrets, but they require file access and restart. For a self-hosted single-user tool, storing keys in SQLite is pragmatically fine. The SQLite file is already on the trusted host behind auth. + +Future option: encrypt DB values at rest using the JWT secret as the key. Creates a clean bootstrap — you need the JWT secret (in the file) to decrypt the DB (which has everything else). One secret to rule them all. + +### Hot reload + +API keys read from DB on each request — no caching at the module level for those values. Port, listen host, JWT secret remain file-only because they're needed before the DB is open. Everything else: change in UI → takes effect on next request, no restart. + +### Config layer changes + +`getConfiguration()` currently reads env at call time (already refactored from the static import). Extend to: + +```typescript +async function getConfigValue(key: string, envVar: string, defaultValue?: string): Promise { + const dbValue = await store.getSetting(key) + if (dbValue) return dbValue + return process.env[envVar] ?? defaultValue +} +``` + +The async change ripples through callers, but most are already in async contexts. + +--- + +## What this is NOT + +- Not a multi-user permission system — Hapi is single-owner, the auth wall is the boundary +- Not a hosted/SaaS config store — all local, all in the SQLite file alongside the rest of the data +- Not trying to replace docker-compose or secrets managers for power users — env vars still work as overrides + +--- + +## Filing order + +1. PR: backend picker (small, ships with voice work) — **ready to start** +2. Issue: config table + settings API — file upstream to gauge interest before investing +3. PR: API key management UI — depends on 2 +4. PR: first-run wizard — depends on 3, biggest lift, most user-facing value + +--- + +## Related + +- PR #690 — voice picker (ElevenLabs voices in settings) +- PR #692 — pluggable voice backend (Gemini Live + Qwen) +- `docs/plans/2026-05-25-voice-picker-handoff.md` — voice work context From a1f62093ad906a4acc5ba0f354085342b8a32a35 Mon Sep 17 00:00:00 2001 From: HeavyGee <133152184+heavygee@users.noreply.github.com> Date: Sun, 24 May 2026 03:31:13 +0100 Subject: [PATCH 0003/1600] chore(fork): operator agent docs and drop upstream root AGENTS.md Single canonical guide at docs/operator/AGENTS.md; merge=ours keeps AGENTS.md deleted when syncing tiann/hapi. Upstream PR branches must still be cut from upstream/main only. Co-authored-by: Cursor --- .cursor/rules/operator-fork.mdc | 13 + .gitattributes | 2 + AGENTS.md | 148 --- docs/operator-local-tooling.md | 54 + docs/operator/AGENTS.md | 296 +++++ .../2026-05-23-upstream-voice-pr-handoff.md | 9 + ...026-05-23-voice-agent-state-integration.md | 1069 +++++++++++++++++ ...2026-05-23-web-agent-chat-import-picker.md | 128 ++ 8 files changed, 1571 insertions(+), 148 deletions(-) create mode 100644 .cursor/rules/operator-fork.mdc create mode 100644 .gitattributes delete mode 100644 AGENTS.md create mode 100644 docs/operator-local-tooling.md create mode 100644 docs/operator/AGENTS.md create mode 100644 docs/plans/2026-05-23-upstream-voice-pr-handoff.md create mode 100644 docs/plans/2026-05-23-voice-agent-state-integration.md create mode 100644 docs/plans/2026-05-23-web-agent-chat-import-picker.md diff --git a/.cursor/rules/operator-fork.mdc b/.cursor/rules/operator-fork.mdc new file mode 100644 index 00000000000..d0db8436302 --- /dev/null +++ b/.cursor/rules/operator-fork.mdc @@ -0,0 +1,13 @@ +--- +description: Operator fork - canonical agent guide is docs/operator/AGENTS.md only +alwaysApply: true +--- + +# heavygee/hapi operator fork + +This repo is a **fork** of `tiann/hapi`. Root **`AGENTS.md` is intentionally absent** - upstream's copy is not used here. + +**Read `docs/operator/AGENTS.md`** - single canonical guide (HAPI baseline + fork intent + upstream PR discipline). + +- Upstream PR branches: from `upstream/main` only; never include `docs/operator/`, `docs/plans/`, or `AGENTS.md` edits in the PR diff. +- Plans: `docs/plans/`. diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 00000000000..5ab9ec991aa --- /dev/null +++ b/.gitattributes @@ -0,0 +1,2 @@ +# Fork-only: keep AGENTS.md deleted when merging upstream/main (requires: git config merge.ours.driver true) +AGENTS.md merge=ours diff --git a/AGENTS.md b/AGENTS.md deleted file mode 100644 index d924ba67df9..00000000000 --- a/AGENTS.md +++ /dev/null @@ -1,148 +0,0 @@ -# AGENTS.md - -Work style: telegraph; noun-phrases ok; drop grammar; - -Short guide for AI agents in this repo. Prefer progressive loading: start with the root README, then package READMEs as needed. - -## What is HAPI? - -Local-first platform for running AI coding agents (Claude Code, Codex, Gemini) with remote control via web/phone. CLI wraps agents and connects to hub; hub serves web app and handles real-time sync. - -## Repo layout - -``` -cli/ - CLI binary, agent wrappers, runner daemon -hub/ - HTTP API + Socket.IO + SSE + Telegram bot -web/ - React PWA for remote control -shared/ - Common types, schemas, utilities -docs/ - VitePress documentation site -website/ - Marketing site -``` - -Bun workspaces; `shared` consumed by cli, hub, web. - -## Architecture overview - -``` -┌─────────┐ Socket.IO ┌─────────┐ SSE/REST ┌─────────┐ -│ CLI │ ──────────── │ Hub │ ──────────── │ Web │ -│ (agent) │ │ (server)│ │ (PWA) │ -└─────────┘ └─────────┘ └─────────┘ - │ │ │ - ├─ Wraps Claude/Codex ├─ SQLite persistence ├─ TanStack Query - ├─ Socket.IO client ├─ Session cache ├─ SSE for updates - └─ RPC handlers ├─ RPC gateway └─ assistant-ui - └─ Telegram bot -``` - -**Data flow:** -1. CLI spawns agent (claude/codex/gemini), connects to hub via Socket.IO -2. Agent events → CLI → hub (socket `message` event) → DB + SSE broadcast -3. Web subscribes to SSE `/api/events`, receives live updates -4. User actions → Web → hub REST API → RPC to CLI → agent - -## Reference docs - -- `README.md` - User overview, quick start -- `cli/README.md` - CLI commands, config, runner -- `hub/README.md` - Hub config, HTTP API, Socket.IO events -- `web/README.md` - Routes, components, hooks -- `docs/guide/` - User guides (installation, how-it-works, FAQ) - -## Shared rules - -- No backward compatibility: breaking old formats freely -- Prioritize Pragmatism, and Avoid Overengineering. -- Write necessary tests ONLY. -- TypeScript strict; no untyped code -- Bun workspaces; run `bun` commands from repo root -- Path alias `@/*` maps to `./src/*` per package -- Prefer 4-space indentation -- Zod for runtime validation (schemas in `shared/src/schemas.ts`) - -## Common commands (repo root) - -```bash -bun typecheck # All packages -bun run test # cli + hub tests -bun run dev # hub + web concurrently -bun run build:single-exe # All-in-one binary -``` - -## Key source dirs - -### CLI (`cli/src/`) -- `api/` - Hub connection (Socket.IO client, auth) -- `claude/` - Claude Code integration (wrapper, hooks) -- `codex/` - Codex mode integration -- `agent/` - Multi-agent support (Gemini via ACP) -- `runner/` - Background daemon for remote spawn -- `commands/` - CLI subcommands (auth, runner, doctor) -- `modules/` - Tool implementations (ripgrep, difftastic, git) -- `ui/` - Terminal UI (Ink components) - -### Hub (`hub/src/`) -- `web/routes/` - REST API endpoints -- `socket/` - Socket.IO setup -- `socket/handlers/cli/` - CLI event handlers (session, terminal, machine, RPC) -- `sync/` - Core logic (sessionCache, messageService, rpcGateway) -- `store/` - SQLite persistence (better-sqlite3) -- `sse/` - Server-Sent Events manager -- `telegram/` - Bot commands, callbacks -- `notifications/` - Push (VAPID) and Telegram notifications -- `config/` - Settings loading, token generation -- `visibility/` - Client visibility tracking - -### Web (`web/src/`) -- `routes/` - TanStack Router pages -- `routes/sessions/` - Session views (chat, files, terminal) -- `components/` - Reusable UI (SessionList, SessionChat, NewSession/) -- `hooks/queries/` - TanStack Query hooks -- `hooks/mutations/` - Mutation hooks -- `hooks/useSSE.ts` - SSE subscription -- `api/client.ts` - API client wrapper - -### Shared (`shared/src/`) -- `types.ts` - Core types (Session, Message, Machine) -- `schemas.ts` - Zod schemas for validation -- `socket.ts` - Socket.IO event types -- `messages.ts` - Message parsing utilities -- `modes.ts` - Permission/model mode definitions - -## Testing - -- Test framework: Vitest (via `bun run test`) -- Test files: `*.test.ts` next to source -- Run: `bun run test` (from root) or `bun run test` (from package) -- Hub tests: `hub/src/**/*.test.ts` -- CLI tests: `cli/src/**/*.test.ts` -- No web tests currently - -## Common tasks - -| Task | Key files | -|------|-----------| -| Add CLI command | `cli/src/commands/`, `cli/src/index.ts` | -| Add API endpoint | `hub/src/web/routes/`, register in `hub/src/web/index.ts` | -| Add Socket.IO event | `hub/src/socket/handlers/cli/`, `shared/src/socket.ts` | -| Add web route | `web/src/routes/`, `web/src/router.tsx` | -| Add web component | `web/src/components/` | -| Modify session logic | `hub/src/sync/sessionCache.ts`, `hub/src/sync/syncEngine.ts` | -| Modify message handling | `hub/src/sync/messageService.ts` | -| Add notification type | `hub/src/notifications/` | -| Add shared type | `shared/src/types.ts`, `shared/src/schemas.ts` | - -## Important patterns - -- **RPC**: CLI registers handlers (`rpc-register`), hub routes requests via `rpcGateway.ts` -- **Versioned updates**: CLI sends `update-metadata`/`update-state` with version; hub rejects stale -- **Session modes**: `local` (terminal) vs `remote` (web-controlled); switchable mid-session -- **Permission modes**: `default`, `acceptEdits`, `bypassPermissions`, `plan` -- **Namespaces**: Multi-user isolation via `CLI_API_TOKEN:` suffix - -## Critical Thinking - -1. Fix root cause (not band-aid). -2. Unsure: read more code; if still stuck, ask w/ short options. -3. Conflicts: call out; pick safer path. -4. Unrecognized changes: assume other agent; keep going; focus your changes. If it causes issues, stop + ask user. diff --git a/docs/operator-local-tooling.md b/docs/operator-local-tooling.md new file mode 100644 index 00000000000..4187f9d6d9a --- /dev/null +++ b/docs/operator-local-tooling.md @@ -0,0 +1,54 @@ +# Operator-local tooling (not for upstream) + +Personal scripts and machine scans must **not** land in upstream PRs. This repo already ignores `localdocs/` and `execplan/` - use those instead of extending `.gitignore`. + +**Agent instructions:** canonical guide is [`docs/operator/AGENTS.md`](operator/AGENTS.md) only. Root `AGENTS.md` is **deleted on this fork** (upstream keeps theirs; we never PR either). + +## Where things live + +| Kind | Location | Committed? | +|------|----------|------------| +| Machine chat index (293 sessions, paths, summaries) | `~/.hapi/operator/reconnectable-agent-chats.{json,txt}` | No - outside repo | +| Personal batch attach presets | `localdocs/operator/attach-existing-agent-sessions.sh` | No - `localdocs/` ignored | +| Regenerate chat index | `localdocs/operator/regenerate-chat-index.sh` | No | +| Generic attach-by-id (future PR F) | `scripts/attach-agent-chat.sh` | Yes, when ready | +| Voice dogfood evidence | `docs/dogfood/*.md` (sanitized) | Yes - product evidence | + +## Commands + +```bash +# Refresh index after new chats +./localdocs/operator/regenerate-chat-index.sh + +# Lookup / attach (reads ~/.hapi/operator/ by default) +./scripts/lookup-agent-chat.sh 12 +./scripts/attach-agent-chat.sh 3054d570 + +# Your hardcoded 8-session batch +./localdocs/operator/attach-existing-agent-sessions.sh +``` + +Override index path: `HAPI_CHAT_INDEX=/path/to.json` + +## Belt-and-suspenders (no repo changes) + +**`.git/info/exclude`** - personal gitignore, never committed. See yours for `PLAN.md` and any scratch paths still in the tree. + +**Global ignore** - `~/.config/git/ignore` applies to all repos on this machine. + +**Local pre-commit hook** - `.git/hooks/pre-commit` can refuse `git add` of operator paths; template in comments below. + +```bash +#!/bin/sh +# .git/hooks/pre-commit (local only) +blocked='localdocs/|~/.hapi/operator|reconnectable-agent-chats|attach-existing-agent-sessions' +if git diff --cached --name-only | grep -Eq "$blocked"; then + echo "Blocked: operator-local paths" >&2 + exit 1 +fi +``` + +## Friction check before `git add -A` + +- `docs/dogfood/` here is for **sanitized voice dogfood**, not full-machine chat inventories. +- `PLAN.md` at repo root is operator scratch unless you explicitly want it upstream. diff --git a/docs/operator/AGENTS.md b/docs/operator/AGENTS.md new file mode 100644 index 00000000000..810b0584080 --- /dev/null +++ b/docs/operator/AGENTS.md @@ -0,0 +1,296 @@ +# AGENTS.md (operator fork) + +Work style: telegraph; noun-phrases ok; drop grammar; + +**Canonical agent guide for `heavygee/hapi`.** Upstream `tiann/hapi` ships root `AGENTS.md` - **this fork deletes that file** and keeps everything here. Never PR this path or a root `AGENTS.md` change to upstream. + +Prefer progressive loading: this file → root `README.md` → package READMEs → `docs/plans/` for voice/integration depth. + +--- + +## Meta: what this fork is + +**HAPI is an agent-corralling platform** - local-first remote control for CLI coding agents (Claude Code, Codex, Cursor Agent, Gemini, OpenCode). Extension of upstream **[tiann/hapi](https://github.com/tiann/hapi)** (AGPL-3). + +| Layer | Role | +|-------|------| +| **Upstream HAPI** | Multi-agent hub, PWA, Telegram, ElevenLabs voice, session sync | +| **Our layer** | Voice-first modality, deterministic mode state, optional `AGENT_NOTIFY_SUMMARY`, multi-agent fleet ops from phone while AFK | +| **Legacy reference** | CursorVox, CursorRemote - mine patterns, do not rebuild parallel stacks | + +**North star:** *Gardening while agents work* - [`docs/plans/2026-05-23-voice-agent-state-integration.md`](../plans/2026-05-23-voice-agent-state-integration.md) §14. + +--- + +## Upstream relationship + +```text +upstream → https://github.com/tiann/hapi.git +origin → https://github.com/heavygee/hapi.git +``` + +- Extend upstream; PR-sized slices; default path unchanged when new code off +- **Never modify maintainer canon** in upstream PRs - see § Upstream file boundaries +- **Upstream PR branches** start from `upstream/main` only - product code diffs, nothing fork-local + +--- + +## Strategic direction: voice-first + +ElevenLabs ConvAI today: handoff OK, readback weak, payment, no mode machine. Target: pluggable voice modality + hub-owned state. Plan: `docs/plans/2026-05-23-voice-agent-state-integration.md`. Do **not** port CursorVox `dispatch_agent.py` as state owner. + +--- + +## Operator docs map + +| Doc | Purpose | +|-----|---------| +| **`docs/operator/AGENTS.md`** | This file | +| `docs/plans/*` | Integration plans, PR A-F | +| `docs/operator-local-tooling.md` | `localdocs/`, machine indexes | +| `docs/dogfood/*.md` | Voice evidence for upstream PR bodies | + +--- + +## Upstream PR series + +| PR | Scope | +|----|-------| +| **A** | Voice readback - `contextFormatters.ts`, `voiceHooks.ts` | +| **B** | ElevenLabs archive - `hub/src/voice/`, `voice.ts` | +| **C** | Optional `AGENT_NOTIFY_SUMMARY` | +| **D** | Mode state + modality wrapper | +| **E** | Local OpenAI backend (after #401) | +| **F** | Web import picker | + +Coordinate **#401**, **#640**. Details §16 in integration plan. + +--- + +## Upstream file boundaries + +### Never touch in upstream-bound PRs + +`AGENTS.md`, `CONTRIBUTING.md`, `LICENSE`, `SECURITY.md`, root `README.md`, `.github/*`, `website/`, `docs/operator/*`, `docs/plans/*` + +PR branch sanity check before push: + +```bash +git fetch upstream +git diff --name-only upstream/main...HEAD | grep -E '^(AGENTS\.md|CONTRIBUTING|docs/operator|docs/plans)' && echo STOP || echo OK +``` + +### Fork-only (stay on `origin/main`, not in upstream PRs) + +- `docs/operator/AGENTS.md` (this file) +- `docs/plans/*`, `docs/operator-local-tooling.md` +- `.cursor/rules/operator-fork.mdc` +- Root `.gitattributes` (`AGENTS.md merge=ours` - fork merge hygiene) +- Absence of root `AGENTS.md` (deleted on fork) + +### Keeping a clean tree after upstream sync + +One-time per clone: + +```bash +git config merge.ours.driver true +``` + +Fork root `.gitattributes` keeps **`AGENTS.md` deleted** when merging `upstream/main` (ours = fork side). + +If `AGENTS.md` reappears after a rebase anyway: + +```bash +git rm -f AGENTS.md +git commit -m "chore(fork): drop upstream AGENTS.md (canonical copy in docs/operator/)" +``` + +**Upstream PR branches:** branched from `upstream/main` - root `AGENTS.md` exists on the branch but **leave it untouched**; your PR diff must not include it. + +--- + +## Upstream PR voice (diffident contributor) + +PR prose = humble first-timer; work = first-class. Silent checklist: rebase, tests, default path note, no fork docs in diff. + +Never in upstream PRs: AI disclosure, fork strategy, internal plans, canon edits. + +See prior skeleton in git history or integration plan §16.9 - Summary / Problem / Approach / Testing / Related / Questions. + +--- + +## Voice mode states (gardening) + +`idle_warm|cold`, `align_intent`, `await_confirm`, `executing_async` (silence), `reporting`, `blocked`, `report_refresh`. Ack only after hub queues. Optional `AGENT_NOTIFY_SUMMARY` - parse when present; `~/coding/agent-notify/ACTUALSPEC.md`. + +--- + +## Git workflow + +### Two branches, two purposes + +| Branch | Base | Purpose | +|--------|------|---------| +| **`main`** on `origin` (fork) | upstream + fork-only commits | Local dev; operator docs; deleted `AGENTS.md` - **never open a PR to tiann from this branch** | +| **`fix/…`, `feat/…`** | **`upstream/main` only** | Upstream PRs - diff must be product code only | + +Committing fork metadata on fork `main` is **fine**. It only leaks into an upstream PR if you branch wrong. + +**Safe (upstream PR):** + +```bash +git fetch upstream +git checkout -b fix/voice-ready-inline-summary upstream/main # NOT fork main +# ... edits in cli/hub/web/shared only ... +git diff --name-only upstream/main...HEAD # must not list AGENTS.md, docs/operator/, docs/plans/ +git push -u origin fix/voice-ready-inline-summary +gh pr create --repo tiann/hapi --head heavygee:fix/voice-ready-inline-summary +``` + +**Unsafe (will PR the deletion + operator docs):** + +```bash +git checkout -b fix/voice main # fork main includes fork-only commits +gh pr create --repo tiann/hapi # BAD - ancestry includes AGENTS.md deletion +``` + +If you started from fork `main` by mistake, re-cut before push: + +```bash +git fetch upstream +git checkout -b fix/voice-ready-inline-summary upstream/main +git cherry-pick # product commits only, not fork config commits +``` + +Or: `git rebase --onto upstream/main upstream/main fix/voice` after ensuring fork-only commits aren't in the chain. + +### Sync fork main with upstream + +```bash +git fetch upstream && git checkout main && git merge upstream/main # AGENTS.md stays deleted (merge=ours) +git rm -f AGENTS.md 2>/dev/null; true +``` + +One-time per clone: `git config merge.ours.driver true` + +Before `git add` on **PR branches**: no `localdocs/`, secrets, `docs/operator/`, `docs/plans/`. + +--- + +## HAPI baseline (from upstream `tiann/hapi` AGENTS.md) + +Inlined here so the fork does not need root `AGENTS.md`. When upstream updates their copy, manually port relevant technical deltas into this section. + +### What is HAPI? + +Local-first platform for running AI coding agents (Claude Code, Codex, Gemini, Cursor Agent, OpenCode) with remote control via web/phone. CLI wraps agents and connects to hub; hub serves web app and handles real-time sync. + +### Repo layout + +``` +cli/ - CLI binary, agent wrappers, runner daemon +hub/ - HTTP API + Socket.IO + SSE + Telegram bot +web/ - React PWA for remote control +shared/ - Common types, schemas, utilities +docs/ - VitePress documentation site +website/ - Marketing site +``` + +Bun workspaces; `shared` consumed by cli, hub, web. + +### Architecture overview + +``` +┌─────────┐ Socket.IO ┌─────────┐ SSE/REST ┌─────────┐ +│ CLI │ ──────────── │ Hub │ ──────────── │ Web │ +│ (agent) │ │ (server)│ │ (PWA) │ +└─────────┘ └─────────┘ └─────────┘ +``` + +**Data flow:** +1. CLI spawns agent, connects to hub via Socket.IO +2. Agent events → CLI → hub → DB + SSE broadcast +3. Web subscribes to SSE `/api/events` +4. User actions → Web → hub REST → RPC → CLI → agent + +**Voice path (ElevenLabs default):** + +```text +Browser WebRTC ↔ ElevenLabs ConvAI → client tools → hub queue → coding agent CLI + ↑ voiceHooks contextual updates +``` + +### Reference docs + +- `README.md`, `cli/README.md`, `hub/README.md`, `web/README.md`, `docs/guide/`, `CONTRIBUTING.md` (read only) + +### Shared rules + +- No backward compatibility required +- Pragmatism; avoid overengineering; tests only when needed +- TypeScript strict; Bun from repo root; `@/*` → `./src/*`; 4-space; Zod in `shared/src/schemas.ts` + +### Common commands + +```bash +bun typecheck +bun run test +bun run dev +bun run build:single-exe +``` + +### Key source dirs + +**CLI (`cli/src/`):** `api/`, `claude/`, `codex/`, `agent/`, `runner/`, `commands/`, `modules/`, `ui/` + +**Hub (`hub/src/`):** `web/routes/`, `socket/handlers/cli/`, `sync/`, `store/`, `sse/`, `telegram/`, `notifications/`, `config/`, `visibility/`, **`voice/`** (operator extensions) + +**Web (`web/src/`):** `routes/`, `components/`, `hooks/`, `api/client.ts`, **`realtime/`** (voice) + +**Shared (`shared/src/`):** `types.ts`, `schemas.ts`, `socket.ts`, `messages.ts`, `modes.ts`, **`voice.ts`** + +### Voice integration seams + +| Concern | Path | +|---------|------| +| Voice prompt + tools | `shared/src/voice.ts` | +| Default transport | `web/src/realtime/RealtimeVoiceSession.tsx` | +| Client tools | `web/src/realtime/realtimeClientTools.ts` | +| Context feed | `voiceHooks.ts`, `contextFormatters.ts` | +| Token API | `hub/src/web/routes/voice.ts` | +| Notify + mode hook | `hub/src/socket/handlers/cli/sessionHandlers.ts` | +| Outbound messages | `hub/src/sync/messageService.ts` | + +### Testing + +Vitest; `*.test.ts` next to source; hub + cli tests; no web tests currently. + +### Common tasks + +| Task | Key files | +|------|-----------| +| Add CLI command | `cli/src/commands/`, `cli/src/index.ts` | +| Add API endpoint | `hub/src/web/routes/`, `hub/src/web/index.ts` | +| Add Socket.IO event | `hub/src/socket/handlers/cli/`, `shared/src/socket.ts` | +| Modify session logic | `sessionCache.ts`, `syncEngine.ts` | +| Modify messages | `messageService.ts` | +| Voice readback / mode | `contextFormatters.ts`, `sessionHandlers.ts`, `hub/src/voice/` | +| Attach agent chat | `machines.ts`, `scripts/attach-agent-chat.sh` | + +### Important patterns + +- **RPC:** `rpc-register` + `rpcGateway.ts` +- **Versioned updates:** stale rejected +- **Session modes:** `local` vs `remote` +- **Permission modes:** `default`, `acceptEdits`, `bypassPermissions`, `plan` +- **Namespaces:** `CLI_API_TOKEN:` + +### Critical thinking + +1. Fix root cause (not band-aid). +2. Unsure: read more code; ask w/ short options. +3. Conflicts: call out; pick safer path. +4. Unrecognized changes: assume other agent; focus your changes. +5. **Upstream first** - general fixes → upstream PR. +6. **Maintainer canon read-only** - never PR edits to `AGENTS.md`, `CONTRIBUTING.md`, root `README.md`. +7. **Fork agent doc is here only** - root `AGENTS.md` must not exist on fork `main`. diff --git a/docs/plans/2026-05-23-upstream-voice-pr-handoff.md b/docs/plans/2026-05-23-upstream-voice-pr-handoff.md new file mode 100644 index 00000000000..0648dd05ea5 --- /dev/null +++ b/docs/plans/2026-05-23-upstream-voice-pr-handoff.md @@ -0,0 +1,9 @@ +# Handoff plan: upstream voice PRs for `tiann/hapi` + +**This document is deprecated as a separate spec.** + +All content - dogfood findings, PR A-E series, #401/#640 coordination, local WIP map, new-agent checklist, and reproduction commands - lives in the main integration plan: + +**[2026-05-23-voice-agent-state-integration.md](./2026-05-23-voice-agent-state-integration.md) §16** + +Start there for a clean-agent handoff. This file remains only as a bookmark for old links. diff --git a/docs/plans/2026-05-23-voice-agent-state-integration.md b/docs/plans/2026-05-23-voice-agent-state-integration.md new file mode 100644 index 00000000000..8790e4597b0 --- /dev/null +++ b/docs/plans/2026-05-23-voice-agent-state-integration.md @@ -0,0 +1,1069 @@ +# Plan: HAPI + Voice Agent State Layer (coexistence with upstream) + +**Status:** Re-reviewed 2026-05-23 after proxmox dogfood start +**Repo:** `/home/heavygee/coding/hapi` (cloned from `https://github.com/tiann/hapi`, upstream `main` @ `04d3d02`) +**Author context:** Architecture conversation May 2026 - pivot from CursorRemote/CursorVox stack to HAPI as primary remote + multi-agent platform +**Goal:** **Coexist with upstream HAPI** - extend, do not replace. Ship additive modules and a **voice-first modality** (local OpenAI-compatible speech stack) while keeping the tree **PR-able** against `tiann/hapi` at all times. +**License note:** Upstream HAPI is **AGPL-3**. Any modified hub exposed on a network must comply with AGPL source-offer requirements (see [why-hapi.md](../guide/why-hapi.md) and root `LICENSE`). + +--- + +## 1. Executive summary + +We spent significant effort on **CursorRemote** (CDP → IDE composer remote control) and **CursorVox** (voice cockpit + deterministic routing → CursorRemote). The strategic direction has shifted: + +| Old assumption | New assumption | +|----------------|----------------| +| Primary agent surface = Cursor IDE composer | Primary agent surface = **CLI agents** (`agent`, `claude`, `gemini`, etc.) | +| Remote = scrape Electron DOM (CursorRemote) | Remote = **wrap CLI sessions** with web/PWA/Telegram | +| Voice = custom FastAPI stack (CursorVox) | Voice = **orchestration layer** on top of remote hub (HAPI today uses ElevenLabs ConvAI) | + +**HAPI** already delivers most of what we built toward: multi-agent remote control, session resume, permissions from phone, PWA, Telegram mini-app, optional Tailscale self-host, voice via ElevenLabs. + +**This plan** is to **extend upstream HAPI in place** with the **differentiated layer we already designed in CursorVox**: + +- Deterministic **voice agent mode state machine** (warm/cold idle, confirm gating, async execution phases) +- **`AGENT_NOTIFY_SUMMARY` contract** for machine-readable completion/status (shared with `agent-notify`) +- A **voice-first modality** backed by **local OpenAI-compatible endpoints** (STT/TTS/optional classifier LLM) - additive to today's ElevenLabs path, not a replacement fork +- **Modality wrapper** on outbound agent messages (voice-originated turns only) + +**Coexistence contract:** Existing HAPI behavior (text UI, Telegram, ElevenLabs ConvAI, default settings) must keep working unchanged when new code is off or env vars unset. Every slice should be merge-shaped: isolated modules, tests, feature flags or config gates, minimal edits to existing call sites. + +**Operator model (full spec):** §14 - *gardening while agents work* - async delegation, hub-owned truth, voice as thin classifier + speaker, responsive only when agents need you. + +CursorRemote and CursorVox become **legacy / reference implementations**, not the primary product path. + +### 2026-05-23 re-review decisions + +After deploying HAPI on proxmox and starting a real Cursor session against `~/coding/jellybot`, the direction is still right, but the first implementation slice should be narrower: + +- **Keep HAPI as primary**. CLR is a good Cursor-only reference, not a parallel production stack. +- **Prove state contract on existing ElevenLabs path first**, then add the **voice-first local modality** as a pluggable provider - not a parallel stack or sidecar. +- **Do not Docker the runner yet**. Hub-only Docker is possible later, but the runner needs host agent CLIs, auth, and workspace writes. Current boot path is systemd. +- **Treat Cursor remote mode separately**. HAPI Cursor remote mode uses `agent -p --output-format stream-json --trust`; it does not provide the same per-tool approval story as Claude/Codex. +- **Hook inbound assistant messages in CLI session handling**, not only `MessageService`. `hub/src/socket/handlers/cli/sessionHandlers.ts` is where CLI-originated messages are persisted and SSE updates are emitted. +- **Prefer session metadata/state over a new API endpoint at first**. Store derived voice mode / notify status in existing session update flow; add `GET /voice-mode` only if the web UI really needs it. + +### CursorVox postmortem: do not port the intermediary agent blindly + +The latest CursorVox run against `Workspaces / Project assessment and role clarification` showed the failure pattern clearly: + +1. User asked, in fragments: "What is this project about?" then "its purpose" / "overall purpose". +2. CursorVox knew the bound target, but the dispatcher still kept asking which project/what context instead of using the selected session. +3. When it finally chose to dispatch, it spoke "I'm starting the workspace check now..." before the handoff was proven. +4. CursorRemote then failed delivery after three CDP attempts: text inserted + Enter pressed, but "Sent message was not observed in chat transcript after submit". +5. The user heard both a false start and an internal transport failure. + +Conclusion: the **stateful voice intermediary agent** is the wrong thing to transplant. It adds a second conversation brain with stale memory, fuzzy target reasoning, and premature acknowledgements. HAPI should instead use: + +- a thin voice tool layer that sends user intent to the already-selected HAPI session; +- deterministic state transitions derived from real HAPI events (`message queued`, `message consumed`, `agent ready/done`, `permission requested`); +- no "execution started" spoken acknowledgement until the hub has accepted/queued the message; +- `AGENT_NOTIFY_SUMMARY` as the completion/status contract, not dispatcher memory as truth; +- LLM voice routing only for lightweight intent classification/wording, never as the owner of task state. + +--- + +## 2. Problem statement + +### What HAPI solves today + +- Run Claude Code, Codex, Cursor Agent CLI, Gemini, OpenCode locally +- Control from browser/PWA/Telegram while AFK +- Session handoff local ↔ remote, permission approval, terminal access +- Voice: ElevenLabs ConvAI → `messageCodingAgent` / `processPermissionRequest` client tools + +Note: permission behavior is agent-flavor specific. Cursor remote mode currently runs with `--trust`, so voice-triggered Cursor tasks need extra guardrails if we want confirmation before destructive work. + +See upstream: `README.md`, `docs/guide/how-it-works.md`, `docs/guide/voice-assistant.md`, `docs/guide/cursor.md`. + +### What HAPI does not solve (our gap) + +- **Voice completion readback** - handoff via `messageCodingAgent` works; summarizing coding-agent output after `thinking` stops is broken on production upstream (see §16) +- **Deterministic voice routing** - HAPI voice delegates intent to ElevenLabs LLM + two tools; CursorVox used dispatcher + explicit mode transitions +- **Optional `AGENT_NOTIFY_SUMMARY` parsing** - not in upstream; useful only for operators who add that tail convention to their own agent rules (see §6.2, §16) +- **Local speech stack** - HAPI is ElevenLabs-centric today; operator runs Speaches/Chatterbox on proxmox (`local-speech-agent` compose) as future `VOICE_BACKEND=local-openai` after upstream PR #401 lands +- **agent-notify integration** - stop-hook TTS/tmux driven by same contract as voice readback (operator-specific) +- **ElevenLabs conversation logging** - transcripts live on ElevenLabs unless hub archives them (WIP PR B, §16) +- **In-app builder surface** (future) - separate concern; shared `BuilderClient` interface may sit above HAPI REST/SSE later + +### What HAPI voice actually is (ElevenLabs path today) + +HAPI voice is **not** dumb STT + TTS. It is **ElevenLabs Conversational AI (ConvAI)**: + +```text +Browser WebRTC ↔ ElevenLabs ConvAI (STT + orchestrator LLM + TTS) + ↓ client tools + messageCodingAgent / processPermissionRequest + ↓ + HAPI hub session queue → coding agent CLI + ↑ contextual updates (voiceHooks) +``` + +- **Orchestrator LLM** (in auto-created agent): `gemini-2.5-flash` per `shared/src/voice.ts` / `buildVoiceAgentConfig()` +- **System prompt + tools:** `VOICE_SYSTEM_PROMPT`, same two client tools as our thin-adapter model +- **Hub role:** mint conversation token, accept queued messages, push session events to ConvAI via web hooks +- **ConvAI conversation logs:** `GET /v1/convai/conversations/{id}` on ElevenLabs (not on hub unless PR B lands) + +This is the same architectural slot CursorVox tried to fill with a stateful Python dispatcher - HAPI already has the ConvAI intermediary; what's missing is **deterministic completion readback** and optional operator notify parsing. + +### What CursorRemote solved (now secondary) + +- IDE composer DOM control via CDP (`--remote-debugging-port=9222`) +- Only relevant when **Cursor IDE is open** with agent panel visible +- Path: `~/coding/CursorRemote/` - see `docs/architecture.md`, `docs/prd.md` + +--- + +## 3. Strategic decision record + +### Why not keep building CursorVox? + +CursorVox proved voice → agent routing against **CursorRemote only**. That is the wrong substrate if the operator lives in **CLI agent mode** (Composer 2.5 Fast, no IDE chrome). HAPI + [cursor-local-remote](https://github.com/Vovch/cursor-local-remote) class tools address CLI remote; HAPI additionally unifies **Claude/Gemini/Codex**. + +### Coexistence with upstream HAPI (primary strategy) + +**We are not building a permanent fork or a second product.** We extend `tiann/hapi` so our work can land as **upstream PRs** (or a small series of PRs) once dogfood passes. + +| Principle | Meaning | +|-----------|---------| +| **Additive modules** | New code lives in `shared/src/*`, `hub/src/voice/*`, optional `web/src/realtime/providers/*` - not scattered rewrites | +| **Default path unchanged** | ElevenLabs + existing web voice session remain the default; local voice-first is opt-in via settings/env | +| **Thin integration seams** | Hook `sessionHandlers.ts`, extend session metadata, wrap outbound sends - avoid replacing `syncEngine`, `messageService`, or auth | +| **PR-sized commits** | Each phase should be reviewable independently: parser + tests, mode engine + tests, modality wrapper, provider interface, local provider impl | +| **Track upstream** | Rebase or merge `tiann/hapi` regularly; resolve conflicts at integration seams, not by duplicating upstream files | +| **No sidecar in production** | CursorVox FastAPI → HAPI API doubles ops and session truth; reference only | + +**Rejected for production:** permanent private fork without upstream path, sidecar voice stack, or changes that break ElevenLabs/text/Telegram when local voice is disabled. + +**Optional extract later:** if upstream wants a smaller first PR, `@hapi/voice-state` or similar package boundary is fine - but integration stays in this repo until accepted upstream. + +### Voice-first modality (local OpenAI-compatible) + +A **modality** is a transport + orchestration path for the same HAPI session store - not a separate agent platform. + +| Modality today | Modality we add | +|----------------|-----------------| +| Text (web/PWA, Telegram) | **Voice-first local** - mic/speaker loop on device or via hub proxy | +| ElevenLabs ConvAI (cloud STT/LLM/TTS, WebRTC) | **Local OpenAI-compatible stack** on tailnet (already operated on proxmox) | + +**Local stack (existing ops, new HAPI adapter):** + +| Role | Service | API shape | +|------|---------|-----------| +| STT | Speaches (`local-speech-agent`) | OpenAI-compatible `/v1/audio/transcriptions` | +| TTS | Chatterbox gateway | OpenAI-compatible `/v1/audio/speech` (HTTP; not WS realtime required for v1) | +| Classifier LLM (optional) | Local OpenAI-compatible chat (Speaches-hosted or separate) | `/v1/chat/completions` with same tool schema as `VOICE_TOOLS` | + +**Shared across modalities (not duplicated per provider):** + +- `VOICE_SYSTEM_PROMPT`, `VOICE_TOOLS`, `realtimeClientTools` → hub message path +- `voiceMode` state + `AGENT_NOTIFY` parsing in hub +- `modalityWrapper` on voice-originated sends +- `voiceHooks` context feed (session history, permissions, ready) + +**Provider interface (PR-able shape):** + +```text +VoiceTransportProvider (interface) + ├─ ElevenLabsConvAIProvider # existing; wrap current RealtimeVoiceSession path + └─ LocalOpenAIVoiceProvider # new; Speaches STT + local LLM tools + Chatterbox TTS +``` + +Selection via hub/web config (e.g. `voice.provider: elevenlabs | local_openai`) with env-backed base URLs for local endpoints. **No hard dependency** on local services in default build; CI runs without them. + +**Voice-first UX (later slice):** optional UI entry that opens mic-first session (large talk control, minimal chrome) - still the same HAPI session underneath; can ship after provider abstraction lands. + +### Decommission candidates (after HAPI slice passes) + +| Service | Tailnet name | Action | +|---------|--------------|--------| +| CursorVox Docker `:7861` | `svc:cursorvox` | Deprecate after voice-state on HAPI | +| CursorRemote Docker `:3000` | `svc:cursor-d` | Keep optional for IDE-only workflows | +| Cursor CDP on teemo-ssd `:9222` | `svc:cursor-cdp` | Only needed if CursorRemote kept | + +Scripts: `~/coding/server-setup/scripts/tailscale/harden-*-cursor*.sh` + +--- + +## 4. Target architecture + +```text +┌─────────────────────────────────────────────────────────────────┐ +│ Phone / PWA / Telegram │ +│ ├─ Text UI (existing, unchanged default) │ +│ ├─ Voice: ElevenLabs ConvAI (existing default) │ +│ └─ Voice-first: LocalOpenAIVoiceProvider (NEW, opt-in) │ +└────────────────────────────┬────────────────────────────────────┘ + │ REST / SSE / Socket.IO +┌────────────────────────────▼────────────────────────────────────┐ +│ HAPI Hub (upstream + additive extensions) │ +│ ├─ syncEngine / messageService (existing, untouched core) │ +│ ├─ VoiceModeEngine (NEW) - per-session state machine │ +│ ├─ AgentNotifyParser (NEW) - AGENT_NOTIFY_SUMMARY on msgs │ +│ ├─ ModalityWrapper (NEW) - voice-originated outbound text │ +│ ├─ VoiceTransportProvider registry (NEW) - pluggable voice │ +│ └─ SQLite session metadata extensions (backward compatible) │ +└────────────────────────────┬────────────────────────────────────┘ + │ Socket.IO +┌────────────────────────────▼────────────────────────────────────┐ +│ HAPI CLI → claude | agent | gemini | codex | opencode │ +└─────────────────────────────────────────────────────────────────┘ + +Optional future: agent-notify stop hook reads same JSONL contract +``` + +--- + +## 5. HAPI integration map (start here in this repo) + +Read **`docs/operator/AGENTS.md`** (canonical on this fork; upstream baseline inlined there). Key seams for voice-state work: + +| Concern | HAPI path | Notes | +|---------|-----------|-------| +| Voice orchestrator prompt + tools | `shared/src/voice.ts` | `VOICE_SYSTEM_PROMPT`, `VOICE_TOOLS`, `buildVoiceAgentConfig()` - shared by all providers | +| Voice transport (default) | `web/src/realtime/RealtimeVoiceSession.tsx` | ElevenLabs ConvAI WebRTC - **unchanged default** | +| Voice transport (voice-first local) | `shared/src/voiceProvider.ts`, `hub/src/voice/providers/localOpenAi.ts`, `web/src/realtime/providers/` | **NEW opt-in** - OpenAI-compatible STT/TTS/chat | +| ElevenLabs token API | `hub/src/web/routes/voice.ts` | `POST /voice/token` | +| Web voice client tools | `web/src/realtime/realtimeClientTools.ts` | `messageCodingAgent`, `processPermissionRequest` - shared hub bridge for all providers | +| Web voice session registry | `web/src/realtime/RealtimeSession.ts` | Provider-agnostic session id + hooks | +| Inbound assistant/agent messages | `hub/src/socket/handlers/cli/sessionHandlers.ts` | **Primary hook for AGENT_NOTIFY + mode transitions** after CLI message normalization and persistence | +| Outbound user messages | `hub/src/sync/messageService.ts` | Web/Telegram queued send path; useful for voice-origin metadata and wrappers | +| Session lifecycle | `hub/src/sync/syncEngine.ts`, `hub/src/sync/sessionCache.ts` | Activity, ready events | +| Persistence | `hub/src/store/sessions.ts`, `hub/src/store/messages.ts` | Extend metadata | +| Permissions (phone approve) | `hub/src/web/routes/permissions.ts` | Already agent-flavor aware | +| Notifications | `hub/src/notifications/` | May drive proactive voice readback | +| Cursor CLI wrapper | `docs/guide/cursor.md`, `cli/src/cursor/` | Remote mode: `agent -p --output-format stream-json --trust --resume`; no per-tool remote approval | + +### Suggested new modules (names tentative) + +``` +shared/src/voiceMode.ts # ModeState enum, transitions, types +shared/src/agentNotify.ts # Parse/strip AGENT_NOTIFY_SUMMARY JSON +shared/src/voiceProvider.ts # VoiceTransportProvider interface + types (PR boundary) +hub/src/voice/modeEngine.ts # Pure transition helper invoked by sessionHandlers +hub/src/voice/modalityWrapper.ts # Outbound prompt wrapping +hub/src/voice/providers/localOpenAi.ts # Speaches STT + OpenAI chat tools + Chatterbox TTS +web/src/realtime/providers/ # Client-side provider wiring; ElevenLabs stays default export +``` + +**PR discipline:** prefer new files + re-exports over editing upstream-heavy files. When editing existing files (`sessionHandlers.ts`, `realtimeClientTools.ts`, `voice.ts`), keep diffs minimal and behind config checks. + +--- + +## 6. Legacy assets to mine (external repos) + +All paths under `~/coding/` unless noted. + +### 6.1 CursorVox - voice agent state + routing (PRIMARY) + +**Repo:** `~/coding/cursorvox/` +**Architecture doc:** `cursorvox/docs/ARCHITECTURE.md` +**Operator guide:** `cursorvox/docs/OPERATOR_GUIDE.md` +**Interface spec:** `cursorvox/docs/plans/2026-04-29-legit-cursorvox-interface-spec.md` + +| File | Port? | What it does | +|------|-------|--------------| +| `src/cursorvox/voice_mode_state.py` | **Yes → TS** | Mode state machine: `idle_warm`, `idle_cold`, `align_intent`, `await_confirm`, `executing_async`, `reporting`, `blocked`; transitions from agent text + user turns | +| `src/cursorvox/modality.py` | **Yes → TS** | Wraps voice user messages; injects `[CursorVox mode context]` + `AGENT_NOTIFY_SUMMARY` output contract | +| `src/cursorvox/voice_speakable.py` | **Yes → TS** | Strip `AGENT_NOTIFY_SUMMARY` tail before TTS | +| `src/cursorvox/command_router.py` | Partial | Target resolution + focus + `send_message` - **replace** with HAPI session targeting; keep confirm/approve routing ideas | +| `src/cursorvox/safety.py` | Partial | High-risk command gating before mutate | +| `src/cursorvox/dispatch_agent.py` | Cautionary reference | Do **not** port as a stateful intermediary agent. Mine only narrow tests/prompts for lightweight classification wording if needed. | +| `src/cursorvox/audio_intent.py` | Reference | Legacy deterministic intents; mostly superseded by dispatcher | +| `src/cursorvox/targets.py` | **No** (IDE) | VoiceTarget from CursorRemote `windowSnapshots` - CLI sessions use HAPI session list instead | +| `src/cursorvox/cursorremote_client.py` | **No** | Socket.io bridge to CursorRemote - obsolete on CLI-first path | +| `src/cursorvox/app.py` | Reference | FastAPI routes, health, voice intent handler wiring | +| `src/cursorvox/proactive.py`, `attention*.py` | Later | Proactive spoken queue from agent state - port after core loop | +| `src/cursorvox/tts/chatterbox_gateway.py` | **Yes** | HTTP TTS to local gateway | +| `src/cursorvox/tts/speaches.py` | **Yes** | STT/TTS HTTP to Speaches | + +**Tests to read before porting:** + +- `cursorvox/tests/test_modality.py` +- `cursorvox/tests/test_voice_speakable.py` +- `cursorvox/tests/test_audio_intent_processor.py` (mode/confirm scenarios) +- `cursorvox/tests/test_targets.py` (skip if not doing IDE targeting) + +**Local speech stack (operational):** + +- CursorVox README documents Speaches `:18001`, Chatterbox gateway `:18008` via `local-speech-agent` compose +- `cursorvox/docker-compose.yml` - env patterns for `CURSORREMOTE_BASE_URL` (will become HAPI hub URL) + +### 6.2 agent-notify / AGENT_NOTIFY_SUMMARY (optional operator convention) + +**Repos:** `~/coding/agent-notify/` (spec), operator `~/coding/AGENTS.md` (optional rule) +**Canonical spec:** `agent-notify/ACTUALSPEC.md` + +**Upstream framing (critical):** `AGENT_NOTIFY_SUMMARY` is **not** a HAPI built-in requirement. Most HAPI users will never emit it. It is an **optional machine-readable tail** some operators add to **their own** agent instructions (`AGENTS.md`, project rules, hooks). HAPI should: + +- Parse it **when present** in assistant messages +- Prefer `summary` for voice readback when parsed +- **Never** require agents to emit it +- **Never** add it to upstream HAPI default prompts + +When present, the JSON tail is source of truth for spoken/read status (`action`, `status`, `summary`, etc.) for that operator's stack. + +Planned HAPI behavior (PR C / Phase 1): + +1. Parse from hub message stream (`shared/src/agentNotify.ts`) +2. Drive mode transitions when combined with mode engine (`done` → `idle_warm`, etc.) +3. Feed speakable text to voice output (strip JSON tail) +4. Optionally share parsed object with agent-notify stop hook (operator deploy only) + +### 6.3 CursorRemote - IDE remote (LEGACY REFERENCE) + +**Repo:** `~/coding/CursorRemote/` (this workspace) + +| Asset | Relevance | +|-------|-----------| +| `docs/architecture.md`, `docs/prd.md` | CDP/DOM model - understand what we're **not** building on | +| `src/server/command-executor.ts` | Send message verification pattern | +| `src/server/activity-derive.ts` | Agent idle/heuristic detection (inferior to AGENT_NOTIFY) | +| `src/server/relay.ts` | socket.io command protocol - different from HAPI | +| Tailscale/Docker setup | **Reuse patterns** for HAPI: `Dockerfile`, `docker-compose.yml`, `DEVELOPMENT.md`, server-setup hardening scripts | + +Do **not** wire new voice-state to CursorRemote unless explicitly maintaining IDE lane. + +### 6.4 cursor-local-remote (alternative CLI remote) + +**Upstream:** https://github.com/Vovch/cursor-local-remote (`clr`) + +Lighter-weight Cursor-only CLI remote. HAPI supersedes for multi-agent; CLR useful as reference for: + +- `agent -p --output-format stream-json` + session transcript paths under `~/.cursor/projects/` +- Cursor-first session browser UX +- Git panel from phone (diff, commit, push, branch) +- Simple webhook completion notifications (for `ntfy` / Discord / Slack style sinks) + +Do not run CLR beside HAPI as a production stack unless explicitly testing a UX gap; two remotes spawning Cursor sessions will create duplicate control surfaces. + +### 6.5 Infrastructure + +| Path | Use | +|------|-----| +| `~/coding/server-setup/scripts/tailscale/harden-*-cursor*.sh` | Template for `harden-hapi-service.sh` | +| `~/coding/server-setup/docs/runbooks/tailscale-internal-services.md` | Runbook pattern | +| `~/coding/cursorvox/docs/plans/2026-04-29-legit-cursorvox-interface-spec.md` | UX requirements that may inform HAPI web voice UI | + +--- + +## 7. Phased implementation plan + +**Upstream alignment:** Phases map to merge-shaped PRs in **§16**. Prefer landing upstream PR **#401** (pluggable backends) before local OpenAI provider work. + +### Phase 0 - Baseline dogfood (partly complete) + +- [x] Run HAPI on proxmox with hub + runner + Tailscale Serve +- [x] Confirm no third-party relay: hub binds `127.0.0.1:3006`; Tailscale Serve publishes `https://hapi.tail9944ee.ts.net/` +- [x] Run one Cursor session from web/PWA against `~/coding/jellybot` +- [x] Remove `specstory run ...` shell alias interference so HAPI resolves real `agent`, `codex`, and `gemini` binaries +- [x] Read `shared/src/voice.ts` + `web/src/realtime/realtimeClientTools.ts` end-to-end +- [x] ElevenLabs voice dogfood: hello test + subtitle-search feature (see §16.3-16.4, `docs/dogfood/`) +- [x] Document upstream PR strategy and ConvAI architecture insight (§16) +- [x] Decide integration shape: **coexist with upstream**; additive modules; PR series to `tiann/hapi` (not permanent fork or sidecar) +- [ ] Verify real non-Cursor agent sessions from web: Claude, Codex, Gemini +- [ ] Document AGPL compliance for `svc:hapi` on tailnet +- [ ] Help rebase/review upstream **PR #401** (pluggable voice backends) - see §16.7 + +**Exit criteria:** Dogfood evidence written; go/no-go in §10; voice handoff proven (messageCodingAgent → hub 200). + +### Phase 1 / PR C - Optional AGENT_NOTIFY parsing + mode state + +- [ ] **PR A first (upstream):** fix ready-event inline assistant text (§16.6) - can ship before this phase +- [ ] **PR B (upstream):** ElevenLabs transcript archive (§16.6) +- [ ] Port `AGENT_NOTIFY_SUMMARY` parser → `shared/src/agentNotify.ts` (**opt-in convention only**) +- [ ] Port mode state types + transitions from `voice_mode_state.py` → `shared/src/voiceMode.ts` +- [ ] Hook `hub/src/socket/handlers/cli/sessionHandlers.ts`: on assistant message, parse notify JSON when present, update session voice mode +- [ ] `voiceHooks.onReady`: prefer parsed notify `summary` over last-message heuristic when available +- [ ] Add unit tests mirroring `cursorvox/tests/test_modality.py`, `test_voice_speakable.py` +- [ ] Publish state through existing session update/SSE path +- [ ] Keep stored chat messages intact; strip contract tail only at voice/TTS boundaries + +**Exit criteria:** When operator agent emits notify line, voice readback uses `summary`; when absent, PR A last-message behavior still works. + +### Phase 2 - Outbound modality wrapper (PR D) + +- [ ] Port `wrap_voice_user_message()` behavior → `hub/src/voice/modalityWrapper.ts` +- [ ] Add explicit `sentFrom: 'voice'` (or equivalent metadata) from `realtimeClientTools.ts` through the hub send path +- [ ] Apply wrapper only when message origin = voice +- [ ] Confirm gating: `await_confirm` blocks `messageCodingAgent` until user confirms (port logic from `command_router.py`; avoid `dispatch_agent.py` as state owner) +- [ ] Ack policy: spoken "sent" only after hub persists/queues message (see §14.6) + +**Exit criteria:** Voice-originated sends include mode context; agent replies with parseable `AGENT_NOTIFY_SUMMARY`; confirm flow works on destructive request; failed queue never produces execution narrative. + +### Phase 3 - Pluggable backends (#401) + local OpenAI (PR E) + +- [ ] Land or rebase upstream **[PR #401](https://github.com/tiann/hapi/pull/401)** (`VOICE_BACKEND=elevenlabs | gemini-live | qwen-realtime`, `GET /api/voice/backend`) - §16.7 +- [ ] Stack PR A/B/C on `VoiceBackendSession` if #401 merges first +- [ ] Extend ElevenLabs/Gemini prompts with mode-aware instructions (backward compatible) +- [ ] Wire proactive readback on mode transition to `reporting` / notify `status: done` +- [ ] **PR E:** `VOICE_BACKEND=local-openai` - Speaches STT + OpenAI-compatible chat tools + Chatterbox TTS (after #401 interface exists; do not parallel-switcher) +- [ ] Optional: voice-first mic-primary UI entry + +**Exit criteria:** Default ElevenLabs unchanged; Gemini Live or local-openai dogfood passes subtitle-search scenario with audible completion summary. + +### Phase 4 - Ops + decommission + +- [x] Tailscale serve `svc:hapi` on proxmox (mirror cursorvox/cursor-d pattern) +- [x] `hapi-runner.service` for remote spawn without terminal babysitter +- [ ] Consider hub-only Docker/Compose after core dogfood; keep runner on host unless a container auth/workspace model proves cleaner +- [ ] Archive CursorVox docker stack; document legacy CursorRemote IDE lane +- [ ] Update `~/coding/AGENTS.md` or homelab runbook with new canonical remote URL + +--- + +## 8. Explicit non-goals (v1) + +- Replacing HAPI's core sync/session architecture +- CDP / Cursor IDE DOM scraping in this integration +- Multi-user tenancy beyond HAPI namespaces +- In-app builder pull-down UI (separate future project; may call HAPI REST) +- Breaking or removing upstream ElevenLabs voice for users who do not opt into local modality +- A permanent private fork that diverges without a PR path to `tiann/hapi` +- Requiring local speech services in default install or CI + +**Not a non-goal:** upstream PRs - dogfood first, then open PR-sized slices once tests and default-path regression pass. + +--- + +## 9. Testing strategy + +| Layer | Approach | +|-------|----------| +| `agentNotify` / `voiceMode` | Port existing CursorVox unit tests to Vitest | +| Hub message hooks | Extend `hub/src/socket/handlers/cli/sessionHandlers` tests/patterns; use `messageService` tests for outbound user-message metadata | +| Voice tools | Mock session + simulate `messageCodingAgent` RPC | +| Provider regression | With default config, ElevenLabs path matches upstream behavior (no local services required in CI) | +| Local provider | Optional integration tests behind env flag; mock OpenAI-compatible HTTP | +| E2E | Manual dogfood matrix from `cursorvox/scripts/dogfood_voice_self_loop.py` (adapt for HAPI) | + +--- + +## 10. Open questions (for cold eval agent) + +**Decided (May 2026 dogfood):** + +| Question | Decision | +|----------|----------| +| Upstream workflow | Coexist with `tiann/hapi`; PR series §16; no permanent fork | +| Voice architecture | ElevenLabs ConvAI is already the thin intermediary; fix readback + logging, not rebuild dispatcher | +| AGENT_NOTIFY | **Opt-in** operator convention only; parse when present (PR C) | +| Pluggable backends | **Track PR #401**; local Speaches/Chatterbox = PR E after #401 | +| No upstream issue | File PR A with dogfood evidence; reference #640 and #401 | + +**Still open:** + +1. **AGPL:** Private tailnet only - is source offer to household devices sufficient via git mirror? +2. **CursorRemote:** Full decommission or keep `cursor-d` for IDE composer indefinitely? +3. **agent-notify:** Hub webhook vs continue relying on Cursor stop hook + JSONL scan (operator deploy)? +4. **Docker:** Hub-only Compose after core dogfood? +5. **Cursor permissions:** Is `--trust` acceptable for remote Cursor sessions, or separate voice guardrails? +6. **AGENT_NOTIFY upstream docs:** Generic JSON shape only vs link to external community spec? +7. **PR #401 default backend:** Confirm `DEFAULT_VOICE_BACKEND='elevenlabs'` on rebased head (early branch flipped to gemini-live; author claims revert) +8. **PR #401 Composer Enter change:** Split out of voice PR or get explicit tiann OK? (HAPI Bot blocker; author claims separate request) +9. **PR #640 ready trigger:** Confirm SSE-only path before stacking PR A + +--- + +## 11. Local environment (ElevenLabs voice) + +Secrets live in **gitignored** env files (not committed): + +| File | Purpose | +|------|---------| +| `~/coding/hapi/.env` | Repo-level reference; same active key | +| `~/coding/hapi/hub/.env` | **Loaded by Bun** when running `cd hub && bun run dev` | +| `~/coding/hapi/.env.example` | Template without secrets | + +**Active key:** `hg` (heavygee). Alternates `justg` and `gc` are commented in both `.env` files - swap by commenting/uncommenting `ELEVENLABS_API_KEY` (one active only). + +For single-binary / CLI outside `hub/`, export before start: + +```bash +set -a && source ~/coding/hapi/.env && set +a +``` + +Voice requires `ELEVENLABS_API_KEY` on the **hub process** (`hub/src/web/routes/voice.ts`). + +**API key permissions:** Auto-create agent + conversation token require ElevenLabs scopes **`convai_read`** and **`convai_write`**. Keys with TTS-only scopes fail with HTTP 500 *"Failed to create ElevenLabs agent automatically"* or missing permission errors on list/create endpoints. + +Optional after first auto-create: set `ELEVENLABS_AGENT_ID=agent_...` in `hub/.env` to skip create step. + +### Tailscale (proxmox, no third-party relay) + +**URL:** `https://hapi.tail9944ee.ts.net/` + +| Item | Path | +|------|------| +| Harden (VIP + ACL + Serve) | `~/coding/server-setup/scripts/tailscale/harden-hapi-service.sh` | +| Boot units | `sudo ~/coding/server-setup/scripts/tailscale/install-hapi-tailnet-services.sh` | +| Verify | `~/coding/server-setup/scripts/verify-hapi-tailnet.sh` | +| Hub systemd | `server-setup/systemd/hapi-hub.service` | +| Runner systemd | `server-setup/systemd/hapi-runner.service` | +| Serve systemd | `server-setup/systemd/tailscale-serve-hapi.service` | + +Do **not** run `hapi hub --relay`. Hub binds `127.0.0.1:3006`; Tailscale Serve proxies HTTPS only on your tailnet. + +After first hub start: **`CLI_API_TOKEN`** in `~/.hapi/settings.json` — use for phone/web login. + +Current proxmox runner workspace roots: + +- `/home/heavygee/coding` +- `/home/heavygee/coding/hapi` + +No official HAPI Docker image exists for this project. `hapiproject/hapi` on Docker Hub is unrelated HAPI FHIR. If Docker is added, start with hub-only Compose; keep the runner host-native until agent CLI auth and workspace mounts have a tested contract. + +--- + +## 12. Quick start for next agent + +```bash +cd ~/coding/hapi +bun install +bun typecheck +bun run test + +# Terminal 1 - hub (loads hub/.env) +bun run dev:hub # or use existing hapi-hub.service on proxmox + +# Terminal 2 - CLI session +npx @twsxtd/hapi cursor # or bun cli after build; verify agent on PATH + +# Production-ish proxmox path +systemctl status hapi-hub.service hapi-runner.service tailscale-serve-hapi.service +hapi runner status + +# Read this plan (§14 operator model, §16 upstream PR handoff + dogfood) +less docs/plans/2026-05-23-voice-agent-state-integration.md + +# Reference repos +ls ~/coding/cursorvox/src/cursorvox/voice_mode_state.py +ls ~/coding/cursorvox/src/cursorvox/modality.py +ls ~/coding/agent-notify/ACTUALSPEC.md +ls ~/coding/CursorRemote/docs/architecture.md +``` + +--- + +## 13. Conversation context (how we got here) + +Condensed arc for the eval agent: + +1. Built **CursorRemote** to remote-control **Cursor IDE composer** via CDP (Tailscale `cursor-d`, Docker on proxmox). +2. Built **CursorVox** as voice cockpit → CursorRemote (`cursorvox` tailnet), local Speaches/Chatterbox, dispatcher-led intents, mode state machine, `AGENT_NOTIFY_SUMMARY`. +3. Identified **inside-out app builder** loop (in-app surface → agent → reload) as separate from voice remote. +4. Recognized **CLI agent** (Composer 2.5 Fast, no IDE) as primary modality - CursorRemote cannot see CLI sessions. +5. Found **HAPI** (and CLR) as existing CLI remote multi-agent solutions. +6. Concluded HAPI subsumes CursorRemote+CursorVox **platform role**; our value is the **voice agent state layer** to graft on. + +--- + +## 14. Operator model: gardening while agents work (full spec) + +This section is the **product and architecture contract** for voice on HAPI. It captures everything worth keeping from the CursorVox attempt, everything we refuse to repeat, and the operator stance: + +> **I am doing the gardening. I want my agents kept busy. I want to be responsive when they actually need me - not nagged, not lied to, not asked which bed I'm standing in when I already picked one.** + +That sentence is the north star. Implementation must optimize for **async delegation + selective interruption**, not for **conversational co-piloting**. + +### 14.1 Roles (who owns what) + +| Actor | Job | Must NOT do | +|-------|-----|-------------| +| **Operator (you)** | Pick session, delegate tasks, approve/deny, unblock, occasionally check status | Babysit tool traces, re-explain context the agent already has | +| **Coding agent (CLI)** | Execute work, emit `AGENT_NOTIFY_SUMMARY`, ask when blocked | Assume voice heard a message that never queued | +| **HAPI hub** | Session truth, message queue, permissions, mode state, SSE/events | Guess intent from stale sidecar memory | +| **Voice layer (ElevenLabs + web tools)** | STT/TTS, classify utterance → HAPI tool, speak hub-backed updates | Own task state, target resolution, or "worker started" fiction | +| **Modality wrapper (hub)** | Inject voice-only execution policy into **outbound** user messages | Pollute desktop/non-voice turns | + +CursorVox collapsed the last three rows into a **dispatch orchestrator** (`dispatch_agent.py`) that tried to be a second agent. That is the spaghetti. HAPI splits them again. + +### 14.2 Gardening metaphor → mode states + +Port the **deterministic mode machine** from `voice_mode_state.py`, but store transitions in **HAPI session metadata**, driven by hub events - not dispatcher memory. + +| Mode | Gardener experience | Voice should | Hub/driver events | +|------|---------------------|--------------|-------------------| +| `idle_warm` | Just finished a task; still in flow | Stay quiet unless spoken to; short acks OK | Agent `status: done` notify; recent report within warm window (~30 min) | +| `idle_cold` | Away for hours; context stale | On next task, **recap first** then confirm intent | Time since last report exceeds warm window; or long gap since user turn (~12 h cold recap) | +| `report_refresh` | "What's going on?" while hands busy | Answer from **session truth**: pending permissions, last notify summary, blocked | User check-in phrases ("what needs me", "where did we leave off"); read-only query | +| `align_intent` | New instruction, not yet sent | Mirror outcome briefly; clarify **task details only** | User message classified as work; before hub accepts queue | +| `await_confirm` | About to do something risky | Hold sends; ask yes/no/revise; **block** `messageCodingAgent` until resolved | High-risk intent or agent asked confirm; safety gate armed | +| `executing_async` | **Gardening** - agent should be busy | **Silence.** No "still working?" No filler. | Message queued + consumed; agent working; until notify or permission | +| `reporting` | Agent finished a beat worth hearing | Speak **notify summary** (stripped JSON tail), 1-3 sentences | Assistant message with parseable `AGENT_NOTIFY_SUMMARY` or ready + substantive reply | +| `blocked` | Agent needs you **now** | Clear blocker + concrete ask ("allow bash?", "pick A or B") | Notify `status: blocked`; permission pending; send failed; transport error | + +**Warm vs cold idle** matters for returning gardeners: cold start should trigger recap + confirm, not "what project?" when the HAPI session is already selected. + +### 14.3 What CursorVox proved worth keeping + +These are **non-negotiable ports** (Phase 1-3): + +1. **`AGENT_NOTIFY_SUMMARY` contract** (`modality.py`, `agent-notify/ACTUALSPEC.md`) - machine-readable completion; voice reads `summary`, mode reads `status`/`action`. +2. **Mode state machine** (`voice_mode_state.py`) - especially `executing_async` silence and `report_refresh` check-ins. +3. **Modality wrapper on voice sends only** (`wrap_voice_user_message`) - desktop CLI sessions stay normal; phone voice gets execution policy + mode context block. +4. **Speakable stripping** (`voice_speakable.py`) - never TTS the JSON tail or raw tool dumps. +5. **Confirm gating for risky work** (`safety.py`, `command_router.py` confirm paths) - two-step approve where needed; **hub-owned** pending confirm, not dispatcher memory. +6. **Read-only status intents** (Vox: `what_needs_me`, `read_last_response`) - answer from cache/state **without** spawning agent work. +7. **Attention semantics** (`ATTENTION_QUEUE_VOX.md`) - sort by "needs me now" (approval, blocked, action required) vs calm idle tabs. +8. **Auditability** (interface spec §8) - every voice turn should be traceable: heard → classified → hub action → spoken result. +9. **Operator guide flow** - arrive → check state → send work → approve in two steps when high risk. + +### 14.4 What CursorVox proved we must NOT repeat + +Documented in postmortem (2026-05-23 jellybot session) and reinforced by `voice-sessions.jsonl`: + +| Failure | Evidence | HAPI rule | +|---------|----------|-----------| +| Second brain re-asks target | Bound session known; dispatcher still "which project?" | **Selected HAPI session is the target.** Voice never resolves windows/tabs. | +| Premature execution narrative | `"I'm starting the workspace check now..."` before transport proof | Speak **only after hub accepts/queues** message. Tool return `"sent"` is not enough if persistence fails - tighten in Phase 2. | +| Transport lies to user | CursorRemote: text inserted, Enter pressed, not in transcript | HAPI path: runner + CLI stream-json; failure surfaces as `blocked`, not fake progress | +| Dispatcher memory drift | `DispatchMemory.short_state/long_state` diverges from IDE | **No rolling dispatcher state.** Session messages + notify JSON are truth. | +| Over-clarification loops | User: "overall purpose" → still aligning | With bound session, clarify **task outcome only**, max N rounds then pass-through (configurable) | +| Chatty async | Filling silence while agent works | `executing_async` = **mandatory silence** in voice prompt + no proactive TTS except permissions/blockers/done | + +`dispatch_agent.py` remains a **cautionary reference** - mine phrasing for lightweight classification if needed, never port as state owner. + +### 14.5 Understanding intent (three layers, not one spaghetti LLM) + +**Layer 0 - Transport interrupts (deterministic, optional port)** + +Vox `intents.py` handles only hard interrupts: "stop talking", "be quiet". No semantic parsing. HAPI may add similar client-side hooks (mute TTS, end voice session) without LLM. + +**Layer 1 - Voice LLM classifier (already in HAPI)** + +`shared/src/voice.ts` + `realtimeClientTools.ts`: + +- `messageCodingAgent(message)` - delegate work to **active session** +- `processPermissionRequest(allow|deny)` - respond to **hub's pending permission** +- Direct answer - meta/voice questions the assistant can answer from injected context + +The LLM **classifies and phrases**. It does not maintain `pending_worker_message`, `short_state`, or choose targets. + +Context for classification arrives via `voiceHooks.ts` → `sendContextualUpdate`: + +- Session focus + history (`formatSessionFull`) +- New agent messages (`onMessages`) +- Permission requests (`onPermissionRequested`) +- Ready/done (`onReady`) + +That is how the voice layer "understands" without owning task memory: **HAPI pushes truth in; LLM maps speech to tools.** + +**Layer 2 - Hub mode gating (deterministic, Phase 2)** + +Even if the LLM calls `messageCodingAgent`, the hub/client may **reject** when: + +- `mode_state === await_confirm` and message is not confirm/revise/cancel +- High-risk mutation without completed confirm flow (port `safety.py` ideas) +- No active session / runner offline → spoken `blocked`, not dispatch + +This is the Vox `command_router` lesson without the CursorRemote target picker. + +**Explicit non-layer:** CursorVox `dispatch_agent.py` JSON (`action: ask_user | dispatch_worker`, rolling memory). **Deleted from architecture.** + +### 14.6 Communicating with the agent on the user's behalf (end-to-end) + +```text +User speech + → STT (ElevenLabs today; Speaches later) + → Voice LLM picks tool OR answers locally + → [Gate] mode + safety check + → realtimeClientTools.messageCodingAgent(msg) + → sessionStore.sendMessage(sessionId, msg) # must include sentFrom: voice (Phase 2) + → hub messageService / sync queue + → [Wrap] modalityWrapper adds mode block + notify contract reminder (voice only) + → runner forwards to agent CLI + → agent works (operator gardens) + → assistant messages → sessionHandlers + → AgentNotifyParser extracts AGENT_NOTIFY_SUMMARY + → modeEngine transitions (e.g. executing_async → reporting → idle_warm) + → SSE + voiceHooks push context + → Voice speaks summary (TTS) when mode allows +``` + +**Acknowledgement policy (fixes Vox false start):** + +1. User finishes speaking. +2. Tool invoked. +3. **Hub persists and queues** user message (exit criterion Phase 2). +4. Only then: brief ack ("Sent." / "Got it.") - optionally **hub-generated**, not LLM improvisation. +5. Transition to `executing_async`. +6. **Silence** until permission, blocker, or notify done. + +**Pass-through wording:** Voice should forward user intent **without rewriting into a different task**. Dispatcher paraphrase caused drift ("workspace check" vs "what is this project about"). Modality wrapper tells the **agent** how to behave; it should not replace the user's words. + +### 14.7 Being responsive to agents (when to interrupt the gardener) + +Interrupt priority (highest first): + +1. **Permission request** - agent blocked on tool approval; speak immediately with allow/deny prompt. +2. **`AGENT_NOTIFY_SUMMARY` with `status: blocked`** - agent needs decision or info. +3. **`AGENT_NOTIFY_SUMMARY` with `status: needs_decision`** - multiple options; speak options briefly. +4. **Send/transport failure** - queue rejected, runner offline; do not claim work started. +5. **`status: done`** - speak summary when operator would want to know work finished (respect DND later). +6. **Agent question in `await_confirm` territory** - agent asked "is that right?"; hold execution. + +Do **not** interrupt for: + +- Routine tool calls mid-flight +- Partial streaming tokens +- Dispatcher "helpful" check-ins +- Low-confidence re-clarification when session + user text are sufficient + +This maps Vox **attention queue** to HAPI: surface sessions with `pending permission`, `blocked notify`, or `failed send` - not every idle session. + +### 14.8 Check-in workflows (gardening-friendly) + +Port Vox check-in detection (`_is_check_in_text` in `voice_mode_state.py`) as shared helpers. These are **read-mostly** - they should query hub state, not spawn agents unless user explicitly adds new work: + +| User says (examples) | Mode transition | Action | +|----------------------|-----------------|--------| +| "What needs me?" | `report_refresh` | Summarize pending permissions + blocked sessions + last notify per focused session | +| "Where did we leave off?" | `report_refresh` | Last agent notify summary + recent user/agent exchange | +| "Read last response" | `report_refresh` | Speakable tail of last assistant message (strip contract JSON) | +| "Status?" / "Catch me up" | `report_refresh` | Same as above; cold idle adds recap preamble | + +After recap, if user adds new work in same utterance, transition `align_intent` → queue send. + +Future tools (Phase 3+): `getSessionStatus`, `listAttentionItems` - only if prompt injection via context updates proves insufficient. + +### 14.9 Modality wrapper content (what agents see vs what user hears) + +User hears: natural speech, summaries, permission prompts. + +Agent sees (voice-originated turns only), adapted from `modality.py`: + +- `[user said]` block with verbatim user text +- `[HAPI voice mode context]` with current `mode_state`, optional `pending_intent_digest` +- Execution policy bullets per mode (e.g. `executing_async`: milestone/blocker/done only) +- Reminder to emit `AGENT_NOTIFY_SUMMARY {"version":1,...}` on completion + +Agent does **not** see dispatcher `short_state`/`long_state` rolls. + +Global `AGENTS.md` rule already requires notify line format; HAPI wrapper reinforces it for voice sessions. + +### 14.10 Permission and destructive work (responsive, not reckless) + +Vox pattern: `approve current` → `confirm approve` (two-step). HAPI already has `processPermissionRequest` against hub permission state. + +Extend for Cursor `--trust` remote mode (Phase 2 guardrails): + +- Voice-triggered **mutating** tasks may require `await_confirm` + spoken playback of intent +- Destructive keywords / high-risk tool patterns port selectively from `safety.py` +- Never auto-approve from voice without explicit allow + +Operator gardening implies **trust but verify**: agent stays busy on safe work; risky work waits for a nod. + +### 14.11 Feedback loop: one truth, three consumers + +When an assistant message lands in `sessionHandlers.ts`: + +1. **Store** full message (unchanged) in SQLite +2. **Parse** `AGENT_NOTIFY_SUMMARY` if present → typed object +3. **Update** session voice mode via `modeEngine` +4. **Broadcast** SSE/session update to web/Telegram +5. **Voice** via hooks: contextual update for LLM; optional proactive TTS on `reporting` / done +6. **agent-notify** (optional): same parsed object for stop-hook TTS/tmux - single contract, multiple outputs (ACTUALSPEC §1) + +Speak **notify.summary**, not dispatcher paraphrase. Strip JSON before TTS. + +### 14.12 UX principles (from legit interface spec, adapted for HAPI) + +Keep from CursorVox product contract: + +- Command-first, not generic chatbot that sometimes sends work +- Mobile-first: large talk control, visible session, clear connection health +- Show what was heard and what happened (audit trail in UI - HAPI web can extend session view) +- Errors speakable: no session, runner offline, permission missing, send failed + +Drop: + +- Cursor target cards from `windowSnapshots` +- Pipecat demo as primary surface (HAPI PWA replaces) +- Dependency on CursorRemote bridge health + +### 14.13 Phase mapping to gardening capabilities + +| Phase | Gardener capability unlocked | +|-------|------------------------------| +| **0** (dogfood) | Can open HAPI, pick session, type/send; voice path read end-to-end | +| **1** | Hub knows mode + notify; "what needs me" can be answered from truth; completion visible in API | +| **2** | Voice send is wrapped + gated; no false "starting"; confirm before risky voice tasks | +| **3** | Full loop: speak task → garden → hear done summary; permissions interrupt reliably | +| **4** | Retire CursorVox stack; HAPI is canonical remote | + +### 14.14 Dogfood acceptance matrix (adapt from CursorVox) + +Each scenario must pass on HAPI before CursorVox decommission: + +| # | Scenario | Pass criteria | +|---|----------|---------------| +| 1 | Cold return | After simulated 12h idle, "where did we leave off" gives recap from session, not "which project?" | +| 2 | Delegate async | Voice sends harmless task; **no speech** until done notify or permission | +| 3 | Permission interrupt | Agent requests bash; voice prompts; allow/deny works; agent continues | +| 4 | Blocked notify | Agent emits `status: blocked`; voice speaks action field; mode = blocked | +| 5 | Done notify | Agent emits `status: done`; voice speaks summary; mode → idle_warm | +| 6 | Confirm gate | Risky task enters await_confirm; spurious send blocked until confirm | +| 7 | Send failure | Runner offline → blocked spoken; **no** "starting now" | +| 8 | Check-in read-only | "What needs me" does not enqueue new agent message | +| 9 | Multi-session | Switch focus in UI; voice respects new session context | +| 10 | Cursor trust path | Document behavior when `--trust` skips per-tool approval | + +Record evidence in hub logs + `~/.hapi/voice-sessions.jsonl` (via `POST /api/voice/sessions/log` on voice disconnect). Example: `docs/dogfood/2026-05-23-elevenlabs-voice-first-hello.md`. + +### 14.15 Open design choices (gardening tuning) + +1. **Max clarification rounds** in `align_intent` before pass-through (Vox had dispatcher loops; suggest cap at 1-2 when session bound). +2. **Proactive done speech** when voice session inactive but notify arrives (Telegram push vs later voice readback). +3. **Attention API** on HAPI: dedicated endpoint vs derive from session list + permission counts. +4. **Upstream PR order:** state contract (Phase 1) → modality wrapper (Phase 2) → `VoiceTransportProvider` + local OpenAI stack (Phase 3) - each slice reviewable without breaking default ElevenLabs path. + +Default stance: **ship deterministic hub behavior first**; tune LLM phrasing second. + +--- + +## 15. Document maintenance + +When phases complete, update: + +- [ ] This file (checkboxes + §10 decisions + §16 PR status) +- [ ] `~/coding/server-setup` runbook if `svc:hapi` deployed +- [ ] `~/coding/cursorvox/README.md` - add deprecation pointer to HAPI voice integration (upstream PR path) +- [ ] `~/coding/CursorRemote/README.md` - clarify IDE-legacy scope +- [ ] `docs/dogfood/*` when new voice sessions are recorded + +**Do not** commit upstream submodule changes without explicit operator request. + +--- + +## 16. Upstream PR strategy, dogfood findings, and new-agent handoff + +**Audience:** New agent taking this forward with a **clean start** (fresh branch, re-implement WIP; do not assume operator's uncommitted diff is deployed). + +**Canonical dogfood artifacts:** + +| File | Content | +|------|---------| +| `docs/dogfood/2026-05-23-elevenlabs-voice-first-hello.md` | Hello test; handoff OK; readback failed | +| `docs/dogfood/2026-05-23-elevenlabs-subtitle-search.md` | Real feature request; handoff OK; summary never delivered | +| `docs/dogfood/*.jsonl` | Exported ElevenLabs conversation JSON (sanitized for repo) | +| `~/.hapi/voice-sessions.jsonl` | Runtime log after PR B (operator machine) | + +### 16.1 Production gaps (May 2026 proxmox dogfood) + +| Symptom | Evidence | +|---------|----------| +| **Handoff works** | `POST .../messages 200` after `messageCodingAgent` | +| **Readback fails** | ConvAI says "finished" but cannot summarize coding-agent output | +| **Ready hook misleads** | `formatReadyEvent` injects *"previous messages ARE the summary"* without embedding text; shows as fake `user` turn in ElevenLabs transcript | +| **Wrong agent label** | Ready text says "Claude Code" on Cursor sessions | +| **ConvAI chattiness** | "Are you still there?" during async work despite `VOICE_SYSTEM_PROMPT` silence rules | +| **No hub transcript** | Voice conversation only on ElevenLabs unless manually fetched | +| **No upstream issue** | No matching open issue on `tiann/hapi` | + +### 16.2 How HAPI readback works today (and why it failed) + +| Mechanism | Role | +|-----------|------| +| `voiceHooks.onMessages` | Push new coding-agent messages to ConvAI as **contextual updates** (includes text) | +| `voiceHooks.onReady` | When `session.thinking` false → `sendUserMessage(formatReadyEvent(...))` | +| `VOICE_SYSTEM_PROMPT` | Tells ConvAI to wait after tool send; summarize on updates | + +**Root bug:** `onReady` asserts the summary already exists in context but **does not paste assistant text**. ConvAI hallucinates progress ("summary in the previous message") when context is empty or thin. + +**Planned fixes (PR A):** `extractLastAssistantSpeakable()` + embed in `formatReadyEvent`. **Planned enhancement (PR C):** prefer optional `AGENT_NOTIFY_SUMMARY.summary` when operator agents emit it. + +### 16.3 Dogfood session 1 - hello test + +- **Conv ID:** `conv_1201ksawpq32evna7dcy4ksaw3eh` · 83s · "Message Coding Agent" +- **Hub session:** `9d04335d-2b90-4941-98a7-eb414823f0e0` (jellybot / Cursor) +- **Hub:** token 18:04:11, message POST 18:04:34 +- **Result:** `messageCodingAgent("hello")` succeeded; user asked for summary; ConvAI had nothing substantive to report +- **Lesson:** Even trivial tasks expose ready-hook gap + +### 16.4 Dogfood session 2 - subtitle search feature + +- **Conv ID:** `conv_8501ksaxzm0tfv98198ar2r2t777` · 291s · "Subtitle Search Feature" +- **Hub:** token 18:26:31, message POST 18:27:35 (real jellybot feature request) +- **Flow:** User described subtitle index/search feature → ConvAI confirmed → `messageCodingAgent` → "sent" (tool obeyed) +- **Failures:** + - ConvAI check-ins at 89s, 130s (violates async silence) + - Ready injection at 176s with empty summary claim + - User "yes please" for summary at 228s → never delivered; ended politely useless at 282s +- **Lesson:** Handoff production-ready; **completion reporting is not** + +### 16.5 Upstream landscape + +| Item | Type | Status | Relevance | +|------|------|--------|-----------| +| **[PR #640](https://github.com/tiann/hapi/pull/640)** | PR | OPEN | Codex messages → voice context; ready on completion messages. **Coordinate with PR A.** Does not fix inline ready text or Cursor. | +| **[PR #401](https://github.com/tiann/hapi/pull/401)** | PR | OPEN, conflicts, changes requested | `VOICE_BACKEND`, Gemini Live, Qwen; runtime `GET /api/voice/backend`. **Enable/track - do not reimplement.** | +| **[#462](https://github.com/tiann/hapi/issues/462)** | Issue | OPEN | Composer dictation - **not** voice-assistant flow | + +### 16.5.1 Maintainer review gate - PR #401 (`tiann`, CHANGES_REQUESTED) + +**tiann (2026-04-06):** *"I believe this is a good feature. Please fix the comments first."* + +That means resolve **HAPI Bot** inline review threads before re-requesting review - not invent a parallel architecture. tiann has no separate inline comments; the actionable list is the bot findings on the PR head (`aa9802d` at last check). + +**Must hold (maintainer coexistence contract):** + +| Requirement | Why | +|-------------|-----| +| `DEFAULT_VOICE_BACKEND = 'elevenlabs'` | Hubs with only `ELEVENLABS_API_KEY` must not route to Gemini/Qwen | +| ElevenLabs code paths untouched | Zero regression on default install | +| ElevenLabs prompt/language unchanged | Chinese prompt block must **not** leak into ElevenLabs config; use backend-specific prompts | +| WebSocket proxies JWT-gated | `/api/voice/gemini-ws` and `/api/voice/qwen-ws` require hub JWT before upgrade | +| No provider secrets to browser | Token endpoints return proxied `wsUrl` only; DashScope/Gemini keys stay server-side | +| Split upstream vs client WS URLs | `*_UPSTREAM_WS_URL` server-only; browser always gets `/api/voice/*-ws` | +| Voice button gated until registered | `onRegistered` after lazy chunk mounts + `registerVoiceSession()` - not just backend discovery | +| `HAPI_PUBLIC_URL` / request origin for proxy URLs | Remote browsers must not get `ws://localhost:...` | +| Sequential Gemini tool calls | No `Promise.all` on shared permission/session state | +| AudioWorklet graph pulls frames | Worklet connected through zero-gain sink to destination | +| Mobile AudioContext in user gesture | Create/resume playback context at start of click handler | +| Cleanup on failed starts | Close leaked `AudioContext` on throw paths | +| No `skipWaiting`/`clientsClaim` in SW | Avoid lazy-chunk hash mismatch mid-session after deploy | +| Debug-guard voice tool logs | `messageCodingAgent` logs behind `VOICE_CONFIG.ENABLE_DEBUG_LOGGING` | + +**Claimed fixed by author (verify on rebase):** Qwen WS auth, default backend revert, proxy URL split, ElevenLabs language split, voice-button readiness, ws URL origin, audio graph, sequential tools, SW revert, debug logging, mic mute on start. + +**Still open per HAPI Bot at last head (must confirm or fix before merge):** + +| Finding | File area | Notes | +|---------|-----------|-------| +| Gemini unmutes user after `turnComplete` | `GeminiLiveVoiceSession.tsx` | Must respect user mute across model speech (barge-in mute ≠ user mute) | +| Failed starts leak `AudioContext` | Gemini + Qwen sessions | `try/catch` + `cleanup()` on all early exits | +| Composer Enter-to-send inverted | `HappyComposer.tsx` | Bot flags as unrelated regression; author claims separate intentional UX change - **needs tiann ruling**, not assumption | +| Gemini setup message dropped under proxy backpressure | `server.ts` / Gemini WS | Queue initial setup if upstream slow | +| Qwen stuck in `connecting` on setup error after `session.created` | `QwenVoiceSession.tsx` | Reject promise + surface error | +| Merge conflicts with current `tiann/main` | whole PR | Rebase required | + +**Our PR A/B/C:** Do not bundle unrelated composer or SW changes. Stack on #401 only after above gate passes. + +### 16.5.2 Maintainer review gate - PR #640 + +**tiann:** No review yet (OPEN, no CHANGES_REQUESTED). + +**HAPI Bot (initial review) - must fix before merge:** + +| Finding | Issue | Required fix | +|---------|-------|--------------| +| Historical ready replay | `SessionChat.tsx` scans `newMessages` including hydrated history | Move ready detection to **live SSE** `message-received` path only; never fire `onReady` for refetched/old `ready` / `task_complete` rows | + +**Overlap with our PR A:** #640 improves Codex message formatting + ready **trigger**; PR A fixes ready **payload** (inline assistant text). Prefer: merge #640 first or one coordinated PR; do not duplicate Codex formatter work in PR A. + +**Does not replace PR A:** #640 does not embed assistant text in `formatReadyEvent` or fix Cursor sessions. + +### 16.6 Upstream PR series (merge-shaped) + +Each PR: **default ElevenLabs behavior unchanged** when env unset. + +#### PR A - Voice completion readback (ship first) + +- `formatReadyEvent(sessionId, lastAssistantText?)` embeds assistant text; agent-neutral wording +- `voiceHooks.onReady` uses `extractLastAssistantSpeakable(messages)` +- Tests: `contextFormatters.test.ts` +- Coordinate with PR #640 + +#### PR B - ElevenLabs conversation archive + +- `hub/src/voice/elevenLabsConversationLog.ts` +- `POST /api/voice/sessions/log` +- Web: store `conversationId` on start, archive on disconnect +- Log path: `{HAPI_HOME}/voice-sessions.jsonl` + +#### PR C - Optional AGENT_NOTIFY parsing + +- `shared/src/agentNotify.ts`; hook `sessionHandlers.ts` +- Voice prefers notify `summary` when present +- **Not** a HAPI default; **not** required for all users +- Upstream docs: "optional convention for custom agent rules" + +#### PR D - Mode state + modality wrapper (later) + +- `voiceMode.ts`, `modalityWrapper.ts`, `await_confirm` gating +- Operator fork or post A-C if maintainer wants scope + +#### PR E - Local OpenAI backend (after #401) + +- `VOICE_BACKEND=local-openai` using #401's switcher +- Speaches STT + local chat tools + Chatterbox TTS +- **Not** a parallel architecture + +### 16.7 PR #401 - enable and extend (do not reinvent) + +PR #401 adds: + +```bash +VOICE_BACKEND=elevenlabs # default, unchanged +VOICE_BACKEND=gemini-live # Google Live API, function calling +VOICE_BACKEND=qwen-realtime +GET /api/voice/backend # runtime discovery, no Vite rebuild +``` + +**Recommendation:** + +1. Rebase `Overbaker:feat/pluggable-voice-backend` onto `tiann/main`; resolve merge conflicts +2. Walk **§16.5.1 checklist** against PR head; fix or verify each HAPI Bot thread; re-request tiann review +3. On Composer Enter change: confirm with tiann whether it stays in #401 or splits to separate PR (bot treats it as blocker) +4. Stack PR A/B/C on `VoiceBackendSession` after #401 merges +5. Use **Gemini Live** for early non-ElevenLabs dogfood (free tier, tools) while local stack waits on PR E +6. Verify ElevenLabs remains sole default when env unset (`DEFAULT_VOICE_BACKEND`) + +### 16.8 Local WIP status (operator clone, May 2026) + +**Not committed. Not running on proxmox** (hub since 15:29 without restart; web not rebuilt). + +| Path | Target PR | +|------|-----------| +| `web/src/realtime/hooks/contextFormatters.ts` | A | +| `web/src/realtime/hooks/voiceHooks.ts` | A, C | +| `hub/src/voice/elevenLabsConversationLog.ts` | B | +| `hub/src/web/routes/voice.ts` | B | +| `web/src/realtime/RealtimeSession.ts` | B | +| `web/src/realtime/RealtimeVoiceSession.tsx` | B | +| `web/src/api/client.ts` | B | + +New agent: **re-implement on fresh branch** from current upstream; use above as reference only. + +### 16.9 New-agent checklist + +- [ ] Read §14 (gardening model) and §16 (this section) +- [ ] Read `docs/dogfood/*` +- [ ] `git pull` on `tiann/hapi/main` +- [ ] Review PR #640 and #401 (**§16.5.1-16.5.2 maintainer gates**) +- [ ] Implement PR A + tests; `bun run test` + `bun typecheck:web` +- [ ] Re-dogfood subtitle-search scenario; verify ElevenLabs transcript shows inline assistant text in ready injection +- [ ] Open upstream PR with conv IDs; note AGENT_NOTIFY is opt-in in PR C description +- [ ] PR B, then PR C, then help on #401, then PR E + +### 16.10 Reproduction commands + +```bash +cd ~/coding/hapi/hub && bun run dev +cd ~/coding/hapi/web && bun run dev +# Voice session → delegate task → wait for agent → ask for summary + +curl -H "xi-api-key: $ELEVENLABS_API_KEY" \ + "https://api.elevenlabs.io/v1/convai/conversations?agent_id=$ELEVENLABS_AGENT_ID" +``` + +Suggested Git workflow: + +```bash +cd ~/coding/hapi +git fetch origin +git checkout main && git pull origin main + +# Option 1: PR A only (smallest) +git checkout -b fix/voice-ready-inline-summary + +# Option 2: help upstream #401 first +gh pr checkout 401 --repo tiann/hapi +# resolve conflicts, address tiann review, then stack PR A on top +``` + +Open PR with: dogfood conv IDs, **"default behavior unchanged"** regression note, PR #640/#401 relationship, and for PR C explicit **AGENT_NOTIFY is opt-in user agent convention**. + +**Explicit non-goals for upstream series:** stateful voice dispatcher; required AGENT_NOTIFY for all users; breaking ElevenLabs default; CursorVox/CursorRemote coupling; Docker/systemd in same PRs. diff --git a/docs/plans/2026-05-23-web-agent-chat-import-picker.md b/docs/plans/2026-05-23-web-agent-chat-import-picker.md new file mode 100644 index 00000000000..9d8d731dde2 --- /dev/null +++ b/docs/plans/2026-05-23-web-agent-chat-import-picker.md @@ -0,0 +1,128 @@ +# Plan: Web-based import picker for existing agent chats + +**Status:** Draft +**Related:** [voice integration plan](./2026-05-23-voice-agent-state-integration.md) +**Operator need:** Attach pre-HAPI agent conversations (Cursor, Claude, Codex, etc.) to the HAPI session list without restarting work or running CLI one-liners per repo. + +--- + +## Problem + +HAPI only lists sessions created through the hub (CLI `hapi *`, web spawn, runner RPC). Chats started outside HAPI (`agent`, `claude`, `codex` in a terminal) are invisible until manually wrapped. + +Today the operator workaround is: + +```bash +# CLI per project (local-first; blocks terminal unless remote spawn) +cd ~/coding/myproject && hapi cursor resume + +# Batch remote attach (May 2026 operator script) +~/coding/hapi/localdocs/operator/attach-existing-agent-sessions.sh +``` + +That script uses `POST /api/machines/:id/spawn` with **`resumeSessionId`** (added to `SpawnSessionRequestSchema` May 2026). Web UI does not expose this yet. + +--- + +## Goal + +**Browse workspace → pick agent flavor → pick discovered local chat → attach to HAPI** (remote runner spawn), with: + +- No duplicate HAPI session if same agent chat already attached +- Clear label (project path + chat title/first message + mtime) +- Optional pin/rename in HAPI metadata after attach + +--- + +## Discovery sources (read-only, machine-local via runner RPC) + +| Agent | Discovery | Resume id field | +|-------|-----------|-----------------| +| **Cursor** | `agent ls` (TTY) or parse `~/.cursor/projects/home-heavygee-coding-*/agent-transcripts/` + optional `store.db` titles | Cursor chat UUID | +| **Claude** | Latest `~/.claude/projects/-home-heavygee-coding-/*.jsonl` | Claude session UUID | +| **Codex** | Scan `~/.codex/sessions/**/rollout-*.jsonl` `session_meta.payload.id` filtered by `cwd` | Codex thread id | +| **Gemini / OpenCode / Kimi** | Existing HAPI scanner patterns in `cli/src/*/utils/*Scanner*` | flavor-specific metadata | + +**Runner constraint:** discovery runs on the machine with workspace roots; hub never reads `~/.cursor` directly. + +--- + +## Proposed UX (web) + +1. **Entry:** Session list empty state or `/browse` → **Import existing chat** +2. **Step 1:** Machine (if multiple) + directory picker (existing browse UI) +3. **Step 2:** Agent flavor tabs (cursor | claude | codex | …) +4. **Step 3:** List discovered chats: + - Title heuristic: first user message / sqlite title / "Untitled" + - Subtitle: `mtime`, message count estimate, agent id prefix + - Badge: **Already in HAPI** if hub metadata matches `cursorSessionId` / etc. +5. **Attach:** `POST /api/machines/:id/spawn` with `{ directory, agent, resumeSessionId }` +6. **Result:** Navigate to new session; show note that **full transcript backfill is not guaranteed** (agent context intact; HAPI history may be sparse until new traffic) + +--- + +## API / hub work (upstream-shaped) + +### PR F1 - Expose resume on spawn (done locally May 2026) + +- `shared/src/apiTypes.ts`: `resumeSessionId?: string` on `SpawnSessionRequestSchema` +- `hub/src/web/routes/machines.ts`: forward to `engine.spawnSession` +- Tests: spawn route passes resume id to RPC + +### PR F2 - Discover local agent chats (new) + +- `GET /api/machines/:id/agent-chats?directory=&agent=cursor|claude|codex` +- Runner RPC: `list-agent-chats` executes flavor-specific discovery in cwd +- Returns `{ chats: [{ id, title, updatedAt, cwd, alreadyAttachedSessionId? }] }` +- Security: path must be under runner workspace roots (same as spawn) + +### PR F3 - Web import wizard + +- `web/src/components/ImportAgentChat/` wizard +- Uses F1 + F2; no new hub session store tables + +--- + +## Edge cases + +| Case | Handling | +|------|----------| +| **Named chat not literal on disk** (e.g. operator says "login2oidc") | Search titles/first-message heuristics; show match confidence; allow manual id paste | +| **`agent ls` needs TTY** | Runner uses transcript mtime fallback; optional `script`/`CI=1` probe | +| **specstory `agent` alias** | Document `command agent` or full cursor-agent path in runner env | +| **Duplicate attach** | Disable Attach if `alreadyAttachedSessionId`; offer Open existing | +| **Wrong cwd** | Warn when discovery cwd ≠ picker directory | + +--- + +## Dogfood attach map (May 2026 operator batch) + +| Project | Agent | Resume id | Notes | +|---------|-------|-----------|-------| +| sparling | cursor | `d2b0370c-3e29-4462-9296-f984f0614aef` | Latest transcript mtime | +| sparling | claude | `12d15516-adb9-49cf-8e7a-9bb18ede3246` | Latest `.jsonl` in claude projects dir | +| meister-export-web | cursor | `c5add90a-2389-48c1-a9d6-10d24195435c` | | +| server-setup | cursor | `3054d570-fe5d-4d0d-8d4e-9f5ac2a45dea` | OIDC/htaccess modernization thread (operator label: login2oidc) | +| ExcuseMe | cursor | `f0f6291f-7ecc-4bf3-9c9d-c09bfb831ff7` | | +| gtxr | codex | `019e4b52-a96d-7283-9098-3a7ff8599a54` | From rollout `session_meta` cwd match | +| local-speech-agent | cursor | `ba02940f-f488-489b-9a2d-c00a0880cfe2` | | +| YourChores | cursor | `9118c502-4253-42a8-8d4d-0ce123c1f519` | | + +Script: `localdocs/operator/attach-existing-agent-sessions.sh` (operator-local; see `docs/operator-local-tooling.md`) + +--- + +## Non-goals + +- Full historical transcript import into HAPI message store (separate backfill project) +- Replacing agent-native session pickers inside Cursor/Claude UIs +- Requiring AGENT_NOTIFY or voice changes + +--- + +## Success criteria + +- Operator attaches 8 chats without CLI one-liners +- All appear in web session list as **remote** runner sessions +- Agent continues prior context (smoke: send "where did we leave off" via web) +- Web picker PR F2+F3 removes need for hardcoded script From b352999f7b2b630966c251fe40e493cd24d8a053 Mon Sep 17 00:00:00 2001 From: HeavyGee <133152184+heavygee@users.noreply.github.com> Date: Tue, 26 May 2026 22:45:05 +0100 Subject: [PATCH 0004/1600] docs: add Teemo Windows runner handoff for agent continuity Captures completed install state, open issues, and next steps so replacement agents can resume without the poisoned Gemini session transcript. Co-authored-by: Cursor --- docs/handoff-teemo-runner.md | 123 +++++++++++++++++++++++++++++++++++ 1 file changed, 123 insertions(+) create mode 100644 docs/handoff-teemo-runner.md diff --git a/docs/handoff-teemo-runner.md b/docs/handoff-teemo-runner.md new file mode 100644 index 00000000000..7bf12009327 --- /dev/null +++ b/docs/handoff-teemo-runner.md @@ -0,0 +1,123 @@ +# Handoff: Windows runner on Teemo (Gemini agent session) + +Handoff for replacing the Gemini agent session **"hapi - gemini windows installer"**. Use this doc to pick up remote-runner work without re-reading the poisoned Gemini transcript. + +Related: [tiann/hapi#711](https://github.com/tiann/hapi/issues/711) (Gemini context overflow / no recovery path; Antigravity migration decision). Operator copy: [heavygee/hapi#3](https://github.com/heavygee/hapi/issues/3). + +## Mission + +Install **HAPI runner only** (not hub) on Windows desktop **Teemo**, connected to the Linux hub. The hub stays on Linux. + +| Role | Host | Machine ID | +|------|------|------------| +| Hub | Linux (`proxmox`) | `f9bb3c9e-43fd-41ca-9e4f-a0b0414b9026` | +| Runner (target) | Windows (`Teemo`) | `teemo` (configured; see duplicate note below) | + +Hub URL: `https://hapi.tail9944ee.ts.net` + +## HAPI session metadata + +| Field | Value | +|-------|--------| +| HAPI session ID | `b0a7208e-f35e-410a-b130-00adbf3dc040` | +| Gemini session ID | `dd9982b5-b3e6-4c1c-a9ab-87e4e7cfdbf3` | +| **Do not resume** | Context exceeded 1M tokens; transcript archived at `~/.gemini/tmp/hapi/chats/archive/` | + +Start a **fresh** agent session for follow-up work. + +## What the previous agent accomplished + +### Windows (Teemo) — installation largely done + +| Item | Status | +|------|--------| +| SSH | Works: `heavygee@100.68.171.36` (Tailscale) | +| Bun | Installed: `C:\Users\HeavyGee\.bun\bin\bun.exe` | +| HAPI clone | `H:\home\heavygee\hapi-clone` (moved from `C:\Users\HeavyGee\hapi-clone` for disk space) | +| Dependencies | `bun install` run in repo | +| Runner settings | `C:\Users\HeavyGee\.hapi\settings.json` — `machineId: teemo`, hub URL, CLI token | +| Workspace root | `h:\Users\HeavyGee\Documents\gavinc` | +| Agent CLIs | Global install attempted: `@anthropic-ai/claude-code`, `@google/gemini-cli`; `bun run tools:unpack` in `cli/` | +| Runner process | Started multiple times; logs at one point showed successful hub connect and workspace registration | +| Boot persistence | Windows scheduled-task attempts (C: then H: paths) — **not verified end-to-end** | + +### Hub-side (Linux) — investigation only + +- Extensive `sqlite3 ~/.hapi/hapi.db` queries on `machines` / `sessions` +- Read runner, hub socket, and install docs under `cli/` and `hub/` +- One manual DB patch: `UPDATE machines SET active=1 ... WHERE id='teemo'` (band-aid, not a fix) +- **No HAPI repo file edits** — zero write/edit operations in source + +## What is still broken (operator-reported) + +1. **Sessions appeared in UI but did not run agents on Windows** — user could create a session; remote execution did not behave as expected. +2. **After H: drive move**, agent reported success; user corrected: runner **missing from hub machine dropdown**, workspaces not listed. +3. **Duplicate machine registrations** in hub DB (same host, different IDs/paths): + - `abd1f588-997a-464a-9586-4845bf3620d7` — old C: path (`C:\Users\HeavyGee\hapi-clone\cli`) + - `teemo` — current H: path (`H:\home\heavygee\hapi-clone\cli`) +4. **Windows agent toolchain not verified** — user asked whether Cursor, Codex, Gemini, Claude are installed and on PATH for runner spawn; investigation incomplete. +5. **Gemini session died** on context overflow before dropdown/connection issues were resolved. + +## Live state at handoff time (2026-05-26) + +Checked after the Gemini session ended: + +- **Windows:** `bun.exe` running (Services session — likely scheduled task) +- **Settings:** `machineId: teemo`, hub URL present in `C:\Users\HeavyGee\.hapi\settings.json` +- **Hub DB:** both `teemo` and `abd1f588-...` show `active=1` with the same workspace root — stale duplicate may confuse UI + +Treat "process is up" as necessary but not sufficient; validate hub socket, dropdown, and spawn end-to-end. + +## Key paths and commands + +``` +Linux hub config: ~/.hapi/settings.json +Hub DB: ~/.hapi/hapi.db + +Windows SSH: heavygee@100.68.171.36 +Windows HAPI tree: H:\home\heavygee\hapi-clone\cli +Windows HAPI home: C:\Users\HeavyGee\.hapi\ +Runner settings: C:\Users\HeavyGee\.hapi\settings.json +Workspace root: h:\Users\HeavyGee\Documents\gavinc +Bun: C:\Users\HeavyGee\.bun\bin\bun.exe +Runner logs: C:\Users\HeavyGee\.hapi\logs\*-runner.log + +Example runner start (from H: install): + cd H:\home\heavygee\hapi-clone\cli + bun src/index.ts runner start --workspace-root h:\Users\HeavyGee\Documents\gavinc +``` + +Environment on Windows (also in settings file): + +- `HAPI_API_URL=https://hapi.tail9944ee.ts.net` +- `CLI_API_TOKEN` — see `C:\Users\HeavyGee\.hapi\settings.json` (do not commit) + +## Recommended next steps + +1. **Verify runner ↔ hub** — tail `*-runner.log` on Windows; confirm hub receives live updates for `teemo`, not just DB `active=1`. +2. **Remove stale machine row** — deactivate or clean up `abd1f588-997a-464a-9586-4845bf3620d7` if it is the obsolete C: registration. +3. **Audit Windows agent toolchain** — `where cursor`, `where codex`, `claude --version`, `gemini --version`; install anything required for flavors you intend to spawn remotely. +4. **End-to-end spawn test** — create a remote session on `teemo` with workspace `h:\Users\HeavyGee\Documents\gavinc`; confirm an agent process starts on Windows and produces output. +5. **Boot persistence** — inspect scheduled task name/state; ensure logon task points at `H:\home\heavygee\hapi-clone\cli` and reconnects to hub after reboot. +6. **Fresh agent session** — do not resume Gemini session `dd9982b5-...`; see [tiann/hapi#711](https://github.com/tiann/hapi/issues/711) for context-limit background. + +## User prompt timeline (abbreviated) + +| # | Intent | +|---|--------| +| 1 | Install runner on LAN Windows box; hub stays on Linux | +| 2 | Configure runner to connect to this hub (Tailscale-aware) | +| 3 | Sessions show in UI but do not run; investigate Windows toolchain | +| 4 | Run `hapi runner start --workspace-root h:\Users\Heavygee\Documents\gavinc` | +| 5 | Confirm runner after H: move; enable restart at boot | +| 6 | Reassess — runner not registered, workspaces missing after move | +| 7–9 | Machine ID `abd1f588` vs display name `teemo`; rename to `teemo` | +| 10 | Runner no longer in dropdowns | +| 11+ | "continue" / retry — blocked by Gemini context/quota errors | + +## What was not done + +- No durable, verified boot + reconnect story +- No proof that remote agent execution works on Teemo +- No HAPI code changes or PR from this workstream +- Dropdown / duplicate-machine issue left unresolved when the Gemini session died From 17f483b5bb56af624152123012807a0e7b547670 Mon Sep 17 00:00:00 2001 From: HeavyGee <133152184+heavygee@users.noreply.github.com> Date: Wed, 27 May 2026 01:58:27 +0100 Subject: [PATCH 0005/1600] docs(plans): voice selection for all backends + personality config specs MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Two new plan documents: - voice-selection-all-backends.md: extending PR #690's ElevenLabs voice picker to Gemini (5 prebuilt voices) and Qwen (55 voices, 6 known). Covers voiceName? in VoiceSessionConfig, per-backend localStorage keys, and backend-aware settings UI. Supersedes rebase-690-onto-692.md §8. - voice-personality-config.md: paralinguistic and personality controls per backend. ElevenLabs exposes stability/style/speed/similarity sliders; Gemini has no audio params (system prompt only); Qwen uses instruction- based control. Covers preset system, custom prompt textarea, and ElevenLabs-only advanced sliders hidden for other backends. via [HAPI](https://hapi.run) Co-Authored-By: HAPI --- docs/plans/voice-personality-config.md | 272 +++++++++++++++++++++ docs/plans/voice-selection-all-backends.md | 227 +++++++++++++++++ 2 files changed, 499 insertions(+) create mode 100644 docs/plans/voice-personality-config.md create mode 100644 docs/plans/voice-selection-all-backends.md diff --git a/docs/plans/voice-personality-config.md b/docs/plans/voice-personality-config.md new file mode 100644 index 00000000000..f8ec53fb628 --- /dev/null +++ b/docs/plans/voice-personality-config.md @@ -0,0 +1,272 @@ +# Plan: Voice personality and paralinguistic configuration + +**Status:** Draft +**Date:** 2026-05-27 +**Related:** `voice-selection-all-backends.md`, `self-bootstrapping-config.md` Phase 3, PR #692 + +--- + +## Goal + +Go beyond which voice is used to configure *how* each voice agent engages: speaking pace, emotional +expressiveness, personality framing, and — where APIs allow — fine-grained paralinguistic controls. +Different backends expose very different levers; the UI should surface what's real and skip what +isn't. + +--- + +## What each backend actually exposes + +### ElevenLabs (richest controls) + +ElevenLabs has the most knobs, set in agent config and overridable per-conversation via +`conversation_config_override.tts`: + +| Parameter | Type | Range | Effect | +|-----------|------|-------|--------| +| `stability` | float | 0.0–1.0 | Lower = more emotional/dynamic; higher = more consistent but can be monotonous. ElevenLabs recommends 0.30–0.50 for expressive delivery | +| `similarity_boost` | float | 0.0–1.0 | How closely output matches the training voice. Higher = cleaner but less flexible | +| `style` | float | 0.0–1.0 | Exaggerates the voice's natural style. 0 = neutral; higher = more dramatic. Costs extra compute at higher values | +| `use_speaker_boost` | bool | — | Further boosts similarity to original speaker | +| `speed` | float | 0.7–1.2 | Speaking rate. 0.9–1.1 recommended for natural conversation; default 1.0 | + +**There is no explicit emotion enum** — emotional affect emerges from the combination of +`stability` and `style`. ElevenLabs' recommended "emotional" preset: stability 0.35, +similarity_boost 0.75, style 0.35, speaker_boost on. + +**System prompt** is the primary lever for personality and engagement style. Controls: +- Role, persona, name +- Tone (formal, casual, warm, direct) +- Engagement pattern (proactive vs reactive, how much it elaborates) +- Response length/conciseness +- When to ask clarifying questions vs just act +- Dynamic variables allow runtime injection (e.g. current session name, user name) without + separate agents + +**Per-conversation override:** all of the above can be overridden when minting the conversation +token, without changing the underlying agent config. Useful for context-specific personality +shifts (e.g. more formal when a permission approval is pending). + +--- + +### Gemini Live (minimal direct controls) + +Gemini Live exposes very few paralinguistic API parameters: + +| Parameter | Where | Notes | +|-----------|-------|-------| +| `voice_name` | `speech_config.voice_config.prebuilt_voice_config.voice_name` | Selects prebuilt voice | +| (none) | — | No speaking rate, pitch, or emotion fields in the Live API | + +**Affective dialog** is available — the model reads the user's emotional tone from audio and adapts +its response style — but you cannot *prescribe* an emotional target via API parameters. It's +responsive, not configurable. + +**System prompt** is the primary (and essentially only) lever for personality. It reliably affects: +- Response tone and register +- Verbosity +- Personality framing ("be warm and encouraging", "be terse and direct") +- Whether the model elaborates or waits to be asked + +The Gemini TTS API (separate from Live) supports SSML-style prosody tags for pace/tone, but these +are **not available in the Live/realtime endpoint** as of 2026-05. + +**Takeaway for UI:** for Gemini, the only exposed controls worth surfacing are voice selection +(see `voice-selection-all-backends.md`) and system prompt customisation. No sliders needed. + +--- + +### Qwen Realtime (instruction-based controls) + +Qwen takes a different approach — paralinguistic control is via natural language instructions +rather than numeric parameters: + +| Control | Mechanism | Example | +|---------|-----------|---------| +| Speaking rate | In-turn instruction | "speak faster", "speak slower" | +| Volume | In-turn instruction | "speak louder" | +| Emotion | In-turn instruction | "speak cheerfully", "speak warmly" | +| Voice | `session.update` → `session.voice` field | "Mia", "Tina", etc. | + +**Emotion recognition:** Qwen recognises 7 input emotions from the user's audio (surprised, neutral, +happy, sad, disgusted, angry, fearful) and can adapt accordingly — similar to Gemini's affective +dialog, but with a named taxonomy. + +**55 voices available** (47 multilingual + 8 dialect), selected via `session.update`. +Known English-suitable voices: Mia (default), Tina, Cherry, Chelsie, Serena, Ethan. + +**System prompt** influences engagement style. Instruction-based emotion/pace control means the +system prompt can include standing instructions: "speak at a relaxed, unhurried pace" or "respond +with warmth and encouragement" — and Qwen will apply this without a per-parameter API call. + +**Takeaway for UI:** for Qwen, surface voice selection and a system prompt editor. Consider a +small set of preset "personality modes" that translate to natural language instructions baked into +the prompt (see Presets section below). + +--- + +## Settings UI design + +### Location + +`Settings → Voice Assistant` — extend the existing section rather than adding a new tab. +Organisation within the section: + +``` +Voice Assistant + ├─ Backend [picker — Phase 1 of self-bootstrapping-config.md] + ├─ Voice [per-backend picker — voice-selection-all-backends.md] + ├─ Personality [new — this plan] + │ ├─ Preset [dropdown] + │ └─ Custom prompt [expandable textarea] + └─ Advanced [collapsible — ElevenLabs-only sliders] + ├─ Stability + ├─ Expressiveness (style) + ├─ Speaking rate + └─ Similarity boost +``` + +--- + +### Personality presets + +A small set of named presets that configure the system prompt additions and (for ElevenLabs) +the paralinguistic parameters together. Presets are backend-aware — they apply what each +backend can actually do. + +Suggested initial set: + +| Preset | Feel | ElevenLabs params | Prompt addition | +|--------|------|-------------------|-----------------| +| **Balanced** (default) | Warm but focused | stability 0.5, style 0.1, speed 1.0 | (none — base prompt only) | +| **Expressive** | Energetic, animated | stability 0.35, style 0.35, speed 1.05 | "Be enthusiastic and expressive. Vary your pace and energy." | +| **Calm** | Measured, reassuring | stability 0.75, style 0.0, speed 0.95 | "Speak in a calm, measured way. Pause thoughtfully." | +| **Direct** | Terse, efficient | stability 0.65, style 0.05, speed 1.1 | "Be concise and direct. Skip pleasantries unless asked." | +| **Custom** | User-defined | user values | user prompt | + +For Gemini and Qwen, presets only affect the prompt addition (no sliders to set). The preset +label still appears — it just means the prompt style, not the audio parameters. + +--- + +### System prompt customisation + +A textarea in Settings lets the operator append to (not replace) the base `VOICE_SYSTEM_PROMPT`: + +``` +[Base VOICE_SYSTEM_PROMPT — not editable] + +[Personality preset addition — auto-filled, editable] + +[Operator notes — free-form] +``` + +**Storage:** localStorage initially (`hapi-voice-custom-prompt`). Phase 3 of +`self-bootstrapping-config.md` moves this to the SQLite config table so it persists across +devices. + +**Scope:** custom prompt applies to all backends equally — it's appended to instructions before +the session starts. Per-backend prompt overrides are a later enhancement if needed. + +--- + +### Advanced controls (ElevenLabs only) + +Show a collapsible "Advanced" section only when ElevenLabs is the active backend. +Hide entirely for Gemini and Qwen — don't show grayed-out sliders that do nothing. + +``` +Advanced (ElevenLabs only) + Stability [slider 0–1] default: 0.5 + Expressiveness [slider 0–1] default: 0.1 (maps to `style`) + Speaking rate [slider 0.7–1.2] default: 1.0 + Similarity boost [slider 0–1] default: 0.75 + [ ] Speaker boost default: off +``` + +Label "Expressiveness" not "Style" — more intuitive. Tooltip explains the tradeoff. +"Similarity boost" and "Speaker boost" grouped together with a note that these are voice-specific +and may sound different with different voices. + +**Storage:** localStorage per-backend (`hapi-voice-el-stability` etc.) or a single JSON object +(`hapi-voice-el-settings`). Phase 3 moves to DB. + +--- + +## Hub changes + +**`hub/src/web/routes/voice.ts`** — ElevenLabs token endpoint + +The existing `POST /voice/token` calls `getOrCreateAgentIdForVoice()`. Extend to accept +paralinguistic overrides and pass them as `conversation_config_override.tts`: + +```typescript +// New optional fields on token request body: +voice_settings?: { + stability?: number + similarity_boost?: number + style?: number + use_speaker_boost?: boolean + speed?: number +} +``` + +Hub passes these through to the ElevenLabs `POST /v1/convai/conversation/token` call. + +For Gemini and Qwen no hub changes needed — voice params go through the frontend session config +and the WebSocket proxy forwards them as-is. + +--- + +## Shared prompt infrastructure + +The custom prompt append should flow through the existing `sendContextualUpdate` / +`updateInstructions` paths — not require new hub endpoints: + +- ElevenLabs: include in `conversation_config_override.agent.prompt.prompt` when minting token +- Gemini: include in `systemInstruction` in `BidiGenerateContentSetup` +- Qwen: include in `instructions` in `session.update` + +`VoiceSessionConfig` gains a `customPrompt?: string` field alongside `voiceName?`. +`VoiceBackendSession` reads from localStorage and passes through. + +--- + +## Files touched + +| File | Change | +|------|--------| +| `shared/src/voice.ts` | `VOICE_SYSTEM_PROMPT` stays as base; `buildGeminiLiveConfig()` accepts `customPrompt?` | +| `web/src/realtime/types.ts` | Add `voiceName?`, `customPrompt?`, `voiceSettings?` to `VoiceSessionConfig` | +| `web/src/realtime/GeminiLiveVoiceSession.tsx` | Pass `customPrompt` into system instruction | +| `web/src/realtime/QwenVoiceSession.tsx` | Pass `customPrompt` into `session.update` instructions | +| `web/src/realtime/RealtimeVoiceSession.tsx` / token call | Pass `voice_settings` override | +| `web/src/realtime/VoiceBackendSession.tsx` | Read all settings from localStorage, pass in config | +| `web/src/routes/settings/index.tsx` | Preset picker, custom prompt textarea, ElevenLabs sliders | +| `hub/src/web/routes/voice.ts` | Accept and forward `voice_settings` in token request | + +--- + +## What the Qwen instruction-based approach means for UI + +For Qwen, "speaking faster" or "cheerfully" is a natural language instruction, not a slider. +The Personality preset system handles this cleanly — the "Expressive" preset for Qwen just +injects "Be enthusiastic and expressive. Vary your pace and energy." into the system prompt, +which Qwen will follow. No need to expose a "send a message saying speak faster" control. + +--- + +## Open questions + +1. **ElevenLabs per-conversation override** — does overriding `agent.prompt.prompt` in the token + request fully replace or append to the agent's configured prompt? Verify before implementing + — may need to fetch the agent's base prompt and concatenate. +2. **Gemini SSML in Live** — Google may add prosody controls to Live API in future. Monitor + release notes; the UI should be easy to extend if sliders become meaningful. +3. **Qwen full voice personality descriptions** — the 55-voice list with personality descriptions + is in Chinese docs. Worth translating/curating before shipping the picker. +4. **Preset persistence** — localStorage for now; Phase 3 of self-bootstrapping-config.md moves + settings to SQLite. Design the storage shape so migration is a copy, not a restructure. +5. **Per-session vs persistent** — should personality settings apply to all future sessions or + be overridable per-session-start? Start with persistent (stored settings always apply); + per-session override is a later enhancement. diff --git a/docs/plans/voice-selection-all-backends.md b/docs/plans/voice-selection-all-backends.md new file mode 100644 index 00000000000..cdf58660962 --- /dev/null +++ b/docs/plans/voice-selection-all-backends.md @@ -0,0 +1,227 @@ +# Plan: Voice selection for all backends (Gemini, Qwen, ElevenLabs) + +**Status:** Draft +**Date:** 2026-05-27 +**Supersedes:** `docs/tooling/rebase-690-onto-692.md` §8 (voice picker backend-awareness section) +**Related:** PR #690 (ElevenLabs voice picker), PR #692 (pluggable backends), `self-bootstrapping-config.md` Phase 1 + +--- + +## Goal + +PR #690 added a voice picker for ElevenLabs voices. That picker should work for all three backends — +each surfacing its own voice list (dynamic for ElevenLabs, static for Gemini and Qwen) — with +selections stored independently so switching backends doesn't clobber each other's choice. + +--- + +## Available voices per backend + +### ElevenLabs + +5,000+ voices fetched dynamically from `GET /api/voice/voices` (already implemented in PR #690). +Selection stored in localStorage as before. No change needed here beyond backend-awareness in the UI. + +### Gemini Live + +5 prebuilt voices available in the Live API (30 HD voices across 24 languages total, but only these +are documented for the Live/realtime endpoint): + +| Voice | Character | +|-------|-----------| +| `Puck` | Conversational, friendly — good default | +| `Charon` | Deep, authoritative | +| `Kore` | Neutral, professional | +| `Fenrir` | Warm, approachable | +| `Aoede` | (documented; affect not specified in Live API docs) | + +Current hardcoded default: `Aoede` (in `buildGeminiLiveConfig()`). Should become user-selectable. + +Voice set via `speech_config.voice_config.prebuilt_voice_config.voice_name` in the session config +sent to Google's BidiGenerateContent endpoint. + +### Qwen Realtime + +55 voices available (47 multilingual + 8 dialect-specific). Known/confirmed English-accessible voices: + +| Voice | Notes | +|-------|-------| +| `Mia` | Current default (`QWEN_REALTIME_VOICE` in `shared/src/voice.ts`) | +| `Tina` | | +| `Cherry` | | +| `Chelsie` | | +| `Serena` | | +| `Ethan` | | + +Full list is in DashScope docs (primarily Chinese). Verify and expand this list before shipping. + +Voice set via `session.voice` field in `session.update` event. + +--- + +## Architecture changes + +### 1. `VoiceSessionConfig` — add `voiceName?` + +In `web/src/realtime/types.ts` (added by PR #692): + +```typescript +export interface VoiceSessionConfig { + language?: string + initialContext?: string + voiceName?: string // NEW — passed through to each backend session +} +``` + +### 2. Session implementations read `voiceName` + +**`GeminiLiveVoiceSession.tsx`** + +Replace hardcoded `'Aoede'` in `buildGeminiLiveConfig()` call: + +```typescript +// Before: +const config = buildGeminiLiveConfig(sessionConfig.language) + +// After: +const config = buildGeminiLiveConfig(sessionConfig.language, sessionConfig.voiceName) +``` + +Update `buildGeminiLiveConfig()` in `shared/src/voice.ts` to accept and use `voiceName`: + +```typescript +export function buildGeminiLiveConfig(language?: string, voiceName?: string): GeminiLiveConfig { + return { + // ...existing config... + speechConfig: { + voiceConfig: { + prebuiltVoiceConfig: { + voiceName: voiceName ?? 'Aoede' + } + } + } + } +} +``` + +**`QwenVoiceSession.tsx`** + +Replace hardcoded `QWEN_REALTIME_VOICE` in `this.currentSessionConfig`: + +```typescript +// In startSession(), when building currentSessionConfig: +voice: config.voiceName ?? QWEN_REALTIME_VOICE, +``` + +**`RealtimeVoiceSession.tsx` (ElevenLabs)** + +Already passes `voiceId` to `fetchVoiceToken()`. Wire `voiceName` through: + +```typescript +// voiceName is the ElevenLabs voice ID for this backend +await fetchVoiceToken(this.api, { voiceId: config.voiceName }) +``` + +### 3. Per-backend localStorage keys + +Store selections independently so switching backends doesn't reset another backend's choice: + +```typescript +const VOICE_STORAGE_KEYS = { + 'elevenlabs': 'hapi-voice-elevenlabs', + 'gemini-live': 'hapi-voice-gemini', + 'qwen-realtime': 'hapi-voice-qwen', +} as const +``` + +Current `hapi-voice-id` key (ElevenLabs-only from PR #690) migrates to `hapi-voice-elevenlabs` +on first load — or read both for backwards compatibility. + +### 4. `VoiceBackendSession` passes selection through + +`VoiceBackendSession.tsx` reads the active backend's localStorage key and includes `voiceName` +when calling `session.startSession(config)`. + +--- + +## Settings UI changes (`web/src/routes/settings/index.tsx`) + +The voice picker section from PR #690 becomes backend-aware: + +**ElevenLabs backend active:** +- Show existing dynamic picker (fetches from `/api/voice/voices`) +- Preview controls remain +- Clone badge remains + +**Gemini Live backend active:** +- Show static picker with 5 voices +- No preview (Google doesn't expose voice preview URLs) +- Show character description next to each voice name + +**Qwen Realtime backend active:** +- Show static picker with known voices +- No preview +- Note if full voice list is unavailable (link to DashScope docs) + +**If only one backend configured (single voice available):** +- Hide picker entirely — no point showing a list of one + +**Backend picker integration:** +- If multiple backends are configured, show backend picker first (Phase 1 of + `self-bootstrapping-config.md`), then voice picker for the selected backend +- Voice picker updates when backend selection changes + +--- + +## Hub changes + +**`hub/src/web/routes/voice.ts`** + +`GET /voice/voices` is currently ElevenLabs-only. When backend is Gemini or Qwen, return 404 or +an empty list rather than attempting to call the ElevenLabs API. Gate by active backend or accept +a `?backend=` query param. + +Alternatively: add `GET /voice/voices/gemini` and `GET /voice/voices/qwen` that return the static +lists server-side (easier to keep up to date without a web rebuild). + +--- + +## Files touched + +| File | Change | +|------|--------| +| `shared/src/voice.ts` | `buildGeminiLiveConfig()` accepts `voiceName?` | +| `web/src/realtime/types.ts` | Add `voiceName?` to `VoiceSessionConfig` | +| `web/src/realtime/GeminiLiveVoiceSession.tsx` | Pass `voiceName` through | +| `web/src/realtime/QwenVoiceSession.tsx` | Pass `voiceName` through | +| `web/src/realtime/RealtimeVoiceSession.tsx` | Wire `voiceName` as `voiceId` | +| `web/src/realtime/VoiceBackendSession.tsx` | Read localStorage, pass `voiceName` in config | +| `web/src/routes/settings/index.tsx` | Backend-aware voice picker UI | +| `hub/src/web/routes/voice.ts` | Guard `/voice/voices` by backend | + +--- + +## PR strategy + +This is a natural follow-on to PR #690. Two options: + +**Option A:** Rebase PR #690 onto post-#692 main and extend in-place. The rebase guide +(`docs/tooling/rebase-690-onto-692.md`) covers the conflict resolution; extend the result with +the Gemini/Qwen picker work described here. + +**Option B:** Merge PR #690 as ElevenLabs-only first, then open a new PR for multi-backend voice +selection. Cleaner review surface but more coordination. + +Option A is preferred if PR #690 hasn't been reviewed yet — less total diff for the reviewer. + +--- + +## Open questions + +1. **Qwen full voice list** — need to verify all 55 voices and which are English-suitable. + Check DashScope console or Chinese docs before hardcoding the static list. +2. **Gemini voice additions** — Google adds voices periodically. Consider fetching from + a Gemini voices endpoint if one exists, rather than hardcoding. +3. **Voice preview for Gemini/Qwen** — not available via API. Could generate a short + hub-side TTS sample on demand if worth the complexity. +4. **Backwards compatibility** — `hapi-voice-id` → `hapi-voice-elevenlabs` migration. From 185d3b39299a32b30ca730fc6cf0f316b1996a4f Mon Sep 17 00:00:00 2001 From: HeavyGee <133152184+heavygee@users.noreply.github.com> Date: Wed, 27 May 2026 02:09:01 +0100 Subject: [PATCH 0006/1600] docs(plans): expand voice personality spec with full expressiveness research Add laughter/gasp/sigh audio tags (ElevenLabs v3 square-bracket syntax), Qwen native backchanneling and full-duplex advantages, Gemini affective dialog flag, 8-voice Gemini Live roster, and ElevenLabs tag density guidance for long-session command-centre UX. Covers: preset system with audio tag instructions per preset, VAD tuning note for Qwen backchanneling, tag prompt engineering guidance, and honest per-backend capability table up front. via [HAPI](https://hapi.run) Co-Authored-By: HAPI --- docs/plans/voice-personality-config.md | 466 ++++++++++++++++--------- 1 file changed, 297 insertions(+), 169 deletions(-) diff --git a/docs/plans/voice-personality-config.md b/docs/plans/voice-personality-config.md index f8ec53fb628..0965c82a316 100644 --- a/docs/plans/voice-personality-config.md +++ b/docs/plans/voice-personality-config.md @@ -2,206 +2,314 @@ **Status:** Draft **Date:** 2026-05-27 +**Goal:** Make long-session AI voice feel as natural, warm, and pleasing as possible — a command +centre experience where listening never becomes fatiguing. **Related:** `voice-selection-all-backends.md`, `self-bootstrapping-config.md` Phase 3, PR #692 --- -## Goal +## TL;DR capability table -Go beyond which voice is used to configure *how* each voice agent engages: speaking pace, emotional -expressiveness, personality framing, and — where APIs allow — fine-grained paralinguistic controls. -Different backends expose very different levers; the UI should surface what's real and skip what -isn't. +| Feature | ElevenLabs v3 | Gemini Live | Qwen Realtime | +|---------|--------------|-------------|---------------| +| Laughter / giggle | ✅ `[laughs]` tag | ⚠️ possible natively, not documented | ✅ instruction-based | +| Sigh / gasp / gulp | ✅ explicit tags | ❌ not documented | ✅ instruction-based | +| Whisper | ✅ `[whispers]` tag | ✅ "whisper" in prompt | ✅ instruction-based | +| Emotional style tags | ✅ rich (see below) | ⚠️ prompt-only | ✅ instruction-based | +| Thinking sounds / backchanneling | ✅ `[hesitates]` | ⚠️ prompt-only | ✅ **native full-duplex** | +| Affective dialog (adapts to user) | ⚠️ via voice params | ✅ `enable_affective_dialog` | ✅ emotion recognition | +| Paralinguistic sliders | ✅ 5 params | ❌ | ❌ | +| SSML prosody | ❌ (v3 uses tags) | ⚠️ prompt-style only | ❌ | --- -## What each backend actually exposes +## ElevenLabs (richest) -### ElevenLabs (richest controls) +### Audio tags — the main lever -ElevenLabs has the most knobs, set in agent config and overridable per-conversation via -`conversation_config_override.tts`: +ElevenLabs v3 Conversational uses square-bracket audio tags embedded in the LLM's text output. +The TTS pipeline renders them as actual audio — the ConvAI orchestrator LLM must be prompted to +emit them, and v3 Conversational honours them without extra config. -| Parameter | Type | Range | Effect | -|-----------|------|-------|--------| -| `stability` | float | 0.0–1.0 | Lower = more emotional/dynamic; higher = more consistent but can be monotonous. ElevenLabs recommends 0.30–0.50 for expressive delivery | -| `similarity_boost` | float | 0.0–1.0 | How closely output matches the training voice. Higher = cleaner but less flexible | -| `style` | float | 0.0–1.0 | Exaggerates the voice's natural style. 0 = neutral; higher = more dramatic. Costs extra compute at higher values | -| `use_speaker_boost` | bool | — | Further boosts similarity to original speaker | -| `speed` | float | 0.7–1.2 | Speaking rate. 0.9–1.1 recommended for natural conversation; default 1.0 | +**Non-verbal vocalizations:** -**There is no explicit emotion enum** — emotional affect emerges from the combination of -`stability` and `style`. ElevenLabs' recommended "emotional" preset: stability 0.35, -similarity_boost 0.75, style 0.35, speaker_boost on. +``` +[laughs] [chuckles] [giggles] +[sighs] [sigh] [gasps] [gulps] +[whispers] [clears throat] +[hesitates] [stammers] [pauses] +[short pause] [long pause] +``` -**System prompt** is the primary lever for personality and engagement style. Controls: -- Role, persona, name -- Tone (formal, casual, warm, direct) -- Engagement pattern (proactive vs reactive, how much it elaborates) -- Response length/conciseness -- When to ask clarifying questions vs just act -- Dynamic variables allow runtime injection (e.g. current session name, user name) without - separate agents +**Emotional delivery tags** (affect the next ~4–5 words then revert): -**Per-conversation override:** all of the above can be overridden when minting the conversation -token, without changing the underlying agent config. Useful for context-specific personality -shifts (e.g. more formal when a permission approval is pending). +``` +[excited] [nervous] [frustrated] [sorrowful] [calm] +[cheerfully] [playfully] [sarcastically] [dramatically] [deadpan] +[flatly] [resigned tone] [confident] [empathetic] [warm tone] +``` ---- +**Character/style tags** (more sustained): -### Gemini Live (minimal direct controls) +``` +[whispers] [pirate voice] [British accent] [French accent] +[evil scientist voice] [storytelling mode] +``` -Gemini Live exposes very few paralinguistic API parameters: +**Sound effects** (can be used sparingly for effect): -| Parameter | Where | Notes | -|-----------|-------|-------| -| `voice_name` | `speech_config.voice_config.prebuilt_voice_config.voice_name` | Selects prebuilt voice | -| (none) | — | No speaking rate, pitch, or emotion fields in the Live API | +``` +[clapping] [gunshot] [explosion] +``` -**Affective dialog** is available — the model reads the user's emotional tone from audio and adapts -its response style — but you cannot *prescribe* an emotional target via API parameters. It's -responsive, not configurable. +**Important:** square brackets only — `*chuckles*`, ``, SSML `` are not v3 syntax. +v3 also does not support SSML `` or `` — use `[slow]`, `[fast]`, `[pauses]`. -**System prompt** is the primary (and essentially only) lever for personality. It reliably affects: -- Response tone and register -- Verbosity -- Personality framing ("be warm and encouraging", "be terse and direct") -- Whether the model elaborates or waits to be asked +### How to get the LLM to emit tags -The Gemini TTS API (separate from Live) supports SSML-style prosody tags for pace/tone, but these -are **not available in the Live/realtime endpoint** as of 2026-05. +Tags must appear in the assistant's text output — the ConvAI orchestrator LLM (Gemini 2.5 Flash +by default) needs to be instructed to use them. System prompt section to add: -**Takeaway for UI:** for Gemini, the only exposed controls worth surfacing are voice selection -(see `voice-selection-all-backends.md`) and system prompt customisation. No sliders needed. +``` +## Expressive delivery +You speak with natural warmth and occasional personality. Use audio cues where appropriate: +- [laughs] or [chuckles] when something is genuinely funny +- [sighs] for moments of mild exasperation or wistfulness +- [hesitates] before uncertain or sensitive statements +- [excited] when sharing something genuinely interesting +- [warm tone] as your default register in casual exchanges +Do not overuse tags — one or two per response maximum. Never perform emotion that isn't earned. +``` ---- +### Paralinguistic sliders -### Qwen Realtime (instruction-based controls) +Set in agent config or overridden per-conversation via `conversation_config_override.tts`: -Qwen takes a different approach — paralinguistic control is via natural language instructions -rather than numeric parameters: +| Parameter | Range | Notes | +|-----------|-------|-------| +| `stability` | 0.0–1.0 | Lower = more dynamic/emotional; higher = consistent but flat | +| `similarity_boost` | 0.0–1.0 | Adherence to training voice | +| `style` | 0.0–1.0 | Exaggerates the voice's natural style; costs compute at high values | +| `use_speaker_boost` | bool | Boosts voice similarity further | +| `speed` | 0.7–1.2 | Speaking rate; 0.9–1.1 recommended for conversation | -| Control | Mechanism | Example | -|---------|-----------|---------| -| Speaking rate | In-turn instruction | "speak faster", "speak slower" | -| Volume | In-turn instruction | "speak louder" | -| Emotion | In-turn instruction | "speak cheerfully", "speak warmly" | -| Voice | `session.update` → `session.voice` field | "Mia", "Tina", etc. | +**ElevenLabs' "emotional" preset**: stability 0.35, similarity 0.75, style 0.35, speaker_boost on. +Good starting point for a warm, expressive long-session voice. -**Emotion recognition:** Qwen recognises 7 input emotions from the user's audio (surprised, neutral, -happy, sad, disgusted, angry, fearful) and can adapt accordingly — similar to Gemini's affective -dialog, but with a named taxonomy. +### Voice model requirement -**55 voices available** (47 multilingual + 8 dialect), selected via `session.update`. -Known English-suitable voices: Mia (default), Tina, Cherry, Chelsie, Serena, Ethan. +Audio tags require **Eleven v3 Conversational** as the TTS model in the agent config. +Turbo v2 / Flash v2 use SSML syntax — different, not compatible. Use v3. -**System prompt** influences engagement style. Instruction-based emotion/pace control means the -system prompt can include standing instructions: "speak at a relaxed, unhurried pace" or "respond -with warmth and encouragement" — and Qwen will apply this without a per-parameter API call. +### Voice selection -**Takeaway for UI:** for Qwen, surface voice selection and a system prompt editor. Consider a -small set of preset "personality modes" that translate to natural language instructions baked into -the prompt (see Presets section below). +5,000+ voices. For long-session warmth, filter the Voice Library by: +- Category: "Conversational" or "Warm" +- Mood tag: "Friendly", "Warm", "Empathetic" +- Avoid: "Narrative" or "Audiobook" voices — optimised for reading, not dialogue --- -## Settings UI design +## Gemini Live (most limited, but improving) -### Location +### What works -`Settings → Voice Assistant` — extend the existing section rather than adding a new tab. -Organisation within the section: +**Affective dialog** (enable via `enable_affective_dialog: true` in session config, requires `v1alpha` API): +- Model detects user's emotional tone from audio and adapts its response style +- Not prescriptive — you can't say "be excited" as an API param, but the model modulates itself +**Natural language style instructions** in system prompt: ``` -Voice Assistant - ├─ Backend [picker — Phase 1 of self-bootstrapping-config.md] - ├─ Voice [per-backend picker — voice-selection-all-backends.md] - ├─ Personality [new — this plan] - │ ├─ Preset [dropdown] - │ └─ Custom prompt [expandable textarea] - └─ Advanced [collapsible — ElevenLabs-only sliders] - ├─ Stability - ├─ Expressiveness (style) - ├─ Speaking rate - └─ Similarity boost +Speak warmly and conversationally. Use natural pacing with brief pauses. +When something is genuinely interesting, let enthusiasm show in your delivery. +Whisper for emphasis on sensitive points. ``` ---- +**Proactivity** (`proactivity: true`): model decides when to respond vs stay silent; filters +background noise and non-directed speech. Useful in a command centre where ambient audio is present. -### Personality presets +### What doesn't work (yet) -A small set of named presets that configure the system prompt additions and (for ElevenLabs) -the paralinguistic parameters together. Presets are backend-aware — they apply what each -backend can actually do. +- No audio tags or SSML in the Live endpoint +- No documented native laughter/gasp generation (the model *may* produce these natively given + its audio training, but it's not a controllable feature) +- No speaking rate, pitch, or emotion API parameters +- Thinking sounds / filler ("uh-huh", "hmm") not documented as produceable -Suggested initial set: +### Voices (8 available in Live half-cascade models) -| Preset | Feel | ElevenLabs params | Prompt addition | -|--------|------|-------------------|-----------------| -| **Balanced** (default) | Warm but focused | stability 0.5, style 0.1, speed 1.0 | (none — base prompt only) | -| **Expressive** | Energetic, animated | stability 0.35, style 0.35, speed 1.05 | "Be enthusiastic and expressive. Vary your pace and energy." | -| **Calm** | Measured, reassuring | stability 0.75, style 0.0, speed 0.95 | "Speak in a calm, measured way. Pause thoughtfully." | -| **Direct** | Terse, efficient | stability 0.65, style 0.05, speed 1.1 | "Be concise and direct. Skip pleasantries unless asked." | -| **Custom** | User-defined | user values | user prompt | +| Voice | Character | +|-------|-----------| +| **Puck** | Upbeat, conversational, lively — best for warm long sessions | +| **Fenrir** | Warm, approachable, excitable | +| **Aoede** | Not fully characterised in docs | +| **Charon** | Deep, authoritative | +| **Kore** | Firm, confident, neutral-professional | +| **Leda** | (HD voice, characterisation TBD) | +| **Orus** | (HD voice, characterisation TBD) | +| **Zephyr** | (HD voice, characterisation TBD) | -For Gemini and Qwen, presets only affect the prompt addition (no sliders to set). The preset -label still appears — it just means the prompt style, not the audio parameters. +For long sessions: **Puck** or **Fenrir** first; Charon for a more serious command-centre feel. + +### Honest assessment for command-centre UX + +Gemini Live is the least expressive of the three for deliberate emotional control. The system +prompt can shape tone but you're relying on the model's judgment, not reliable tags. Best used +when you want Google's reasoning quality and can accept more neutral delivery. --- -### System prompt customisation +## Qwen Realtime (native full-duplex, instruction-based expressiveness) + +### Backchanneling — genuine differentiator -A textarea in Settings lets the operator append to (not replace) the base `VOICE_SYSTEM_PROMPT`: +Qwen3-Omni natively distinguishes backchanneling ("uh-huh", "hmm", "I see", listener feedback) +from semantic interruptions. In a long conversation, the model responds to these naturally without +treating them as commands. This is **significantly better than ElevenLabs or Gemini** for extended +back-and-forth — it makes the conversation feel genuinely mutual rather than turn-based. + +### Expressive vocalizations + +The model has been observed producing laughter natively (GitHub reports of "unwanted laughter" +confirm it *can* — the goal is making it controlled rather than surprising). Instruction-based +approach: ``` -[Base VOICE_SYSTEM_PROMPT — not editable] +When something is genuinely amusing, it's natural to chuckle lightly. +Use warm acknowledgements like "mmm" or "ah" to show you're following along. +A gentle sigh is appropriate for moments of empathy or reflection. +Don't suppress natural conversational sounds — they make dialogue feel more human. +``` + +### Emotion recognition (input → output loop) -[Personality preset addition — auto-filled, editable] +Qwen recognises 7 emotions in the user's voice: surprised, neutral, happy, sad, disgusted, angry, +fearful. This feeds into adaptive response tone — the model's output modulates to match or +complement the user's affect. No API param needed; it's always on. -[Operator notes — free-form] +### Speed and expressiveness via instruction + +``` +speak at a relaxed, unhurried pace — never rushed +speak with warmth and a gentle energy +use natural pauses when considering something +be enthusiastic about ideas without being excitable ``` -**Storage:** localStorage initially (`hapi-voice-custom-prompt`). Phase 3 of -`self-bootstrapping-config.md` moves this to the SQLite config table so it persists across -devices. +These are reliable because Qwen's instruction-following for audio style is strong. + +### Voice selection + +55 voices (47 multilingual + 8 dialect). Known characterised voices: +- **Mia** — current default +- **Tina**, **Cherry**, **Chelsie**, **Serena**, **Ethan**, **Aiden** -**Scope:** custom prompt applies to all backends equally — it's appended to instructions before -the session starts. Per-backend prompt overrides are a later enhancement if needed. +Full personality matrix requires DashScope console access or Chinese docs. Worth testing +each candidate voice with a standard paragraph before committing. --- -### Advanced controls (ElevenLabs only) +## Settings UI design -Show a collapsible "Advanced" section only when ElevenLabs is the active backend. -Hide entirely for Gemini and Qwen — don't show grayed-out sliders that do nothing. +### Structure ``` -Advanced (ElevenLabs only) - Stability [slider 0–1] default: 0.5 - Expressiveness [slider 0–1] default: 0.1 (maps to `style`) - Speaking rate [slider 0.7–1.2] default: 1.0 - Similarity boost [slider 0–1] default: 0.75 - [ ] Speaker boost default: off +Settings → Voice Assistant + ├─ Backend [picker] + ├─ Voice [per-backend picker] + ├─ Character [new] + │ ├─ Preset [dropdown: Balanced / Warm & Expressive / Calm / Direct / Custom] + │ └─ Personality notes [textarea — appended to system prompt] + └─ Voice tuning [collapsible — ElevenLabs only] + ├─ Stability [slider 0–1, default 0.5] + ├─ Expressiveness [slider 0–1, default 0.1] + ├─ Speaking rate [slider 0.7–1.2, default 1.0] + ├─ Similarity boost [slider 0–1, default 0.75] + └─ [ ] Speaker boost ``` -Label "Expressiveness" not "Style" — more intuitive. Tooltip explains the tradeoff. -"Similarity boost" and "Speaker boost" grouped together with a note that these are voice-specific -and may sound different with different voices. +Hide "Voice tuning" entirely for Gemini and Qwen — no grayed-out sliders. + +--- + +### Personality presets + +Presets configure the system prompt addition and (for ElevenLabs) the paralinguistic parameters +together. All presets include an audio tags instruction block for ElevenLabs. + +#### Balanced (default) + +*Warm, focused, professional. Good for task work.* + +- ElevenLabs params: stability 0.50, style 0.10, speed 1.0 +- Prompt addition: *(none — base VOICE_SYSTEM_PROMPT only)* +- Audio tags guidance: minimal — `[hesitates]`, `[warm tone]` only when natural + +#### Warm & Expressive + +*Human-feeling, animated. Best for long exploratory sessions.* + +- ElevenLabs params: stability 0.35, style 0.30, speed 0.97, speaker_boost on +- Prompt addition: + ``` + Speak with natural warmth and personality. Use audio cues where they fit: + [chuckles] or [laughs] when something is genuinely funny, + [excited] when sharing something interesting, + [sighs] for wistful or empathetic moments, + [warm tone] as your default register. + One or two tags per response maximum — never performed, always earned. + Speak at a relaxed pace. Pause before considered answers. + ``` + +#### Calm -**Storage:** localStorage per-backend (`hapi-voice-el-stability` etc.) or a single JSON object -(`hapi-voice-el-settings`). Phase 3 moves to DB. +*Measured, reassuring. Good for late-night sessions or complex problem-solving.* + +- ElevenLabs params: stability 0.75, style 0.0, speed 0.93 +- Prompt addition: + ``` + Speak slowly and deliberately. [pauses] before important points. + Use [sighs] and [hesitates] naturally. Never rush. + Keep energy low and steady. + ``` + +#### Direct + +*Terse, efficient. Good for rapid task execution.* + +- ElevenLabs params: stability 0.65, style 0.05, speed 1.08 +- Prompt addition: + ``` + Be concise. Skip pleasantries unless asked. No filler phrases. + Short answers. Confirm before elaborating. + ``` + +#### Custom + +User-defined values. Shows all sliders and a full textarea. + +--- + +### System prompt customisation + +The personality notes textarea appends to (never replaces) `VOICE_SYSTEM_PROMPT`. +Character limit: ~500 tokens — enough for a full persona description. + +For ElevenLabs, the custom prompt is included in `conversation_config_override.agent.prompt.prompt` +when minting the conversation token (needs hub to fetch the existing agent base prompt and +concatenate — verify ElevenLabs API behaviour before implementing). + +For Gemini and Qwen, it's included in system instructions on session start. --- ## Hub changes -**`hub/src/web/routes/voice.ts`** — ElevenLabs token endpoint +### ElevenLabs token endpoint (`POST /voice/token`) -The existing `POST /voice/token` calls `getOrCreateAgentIdForVoice()`. Extend to accept -paralinguistic overrides and pass them as `conversation_config_override.tts`: +Accept and forward new optional fields: ```typescript -// New optional fields on token request body: voice_settings?: { stability?: number similarity_boost?: number @@ -209,64 +317,84 @@ voice_settings?: { use_speaker_boost?: boolean speed?: number } +custom_prompt?: string ``` -Hub passes these through to the ElevenLabs `POST /v1/convai/conversation/token` call. +Pass as `conversation_config_override.tts` and `conversation_config_override.agent.prompt.prompt`. + +### No hub changes for Gemini / Qwen -For Gemini and Qwen no hub changes needed — voice params go through the frontend session config -and the WebSocket proxy forwards them as-is. +Voice and personality params go through the frontend session config and the WebSocket proxy +forwards them as-is in `session.update`. --- -## Shared prompt infrastructure +## `VoiceSessionConfig` additions + +```typescript +export interface VoiceSessionConfig { + language?: string + initialContext?: string + voiceName?: string // from voice-selection-all-backends.md + customPrompt?: string // personality notes appended to system prompt + voiceSettings?: { // ElevenLabs only; ignored by other backends + stability?: number + similarityBoost?: number + style?: number + useSpeakerBoost?: boolean + speed?: number + } +} +``` + +--- -The custom prompt append should flow through the existing `sendContextualUpdate` / -`updateInstructions` paths — not require new hub endpoints: +## Implementation notes -- ElevenLabs: include in `conversation_config_override.agent.prompt.prompt` when minting token -- Gemini: include in `systemInstruction` in `BidiGenerateContentSetup` -- Qwen: include in `instructions` in `session.update` +### Getting ElevenLabs to emit audio tags reliably -`VoiceSessionConfig` gains a `customPrompt?: string` field alongside `voiceName?`. -`VoiceBackendSession` reads from localStorage and passes through. +The audio tags instruction must be in the **agent system prompt**, not injected as a contextual +update. Contextual updates are conversational turns, not standing instructions. Include in the +`VOICE_SYSTEM_PROMPT` base or in the `conversation_config_override.agent.prompt.prompt` addition. ---- +### Tag density tuning -## Files touched +One or two tags per response is the right ceiling. More than that tips into performance rather +than natural speech. A useful test: read a response aloud and check whether the tags would feel +genuine if a human said them. If not, the LLM is over-tagging — tighten the prompt instruction. -| File | Change | -|------|--------| -| `shared/src/voice.ts` | `VOICE_SYSTEM_PROMPT` stays as base; `buildGeminiLiveConfig()` accepts `customPrompt?` | -| `web/src/realtime/types.ts` | Add `voiceName?`, `customPrompt?`, `voiceSettings?` to `VoiceSessionConfig` | -| `web/src/realtime/GeminiLiveVoiceSession.tsx` | Pass `customPrompt` into system instruction | -| `web/src/realtime/QwenVoiceSession.tsx` | Pass `customPrompt` into `session.update` instructions | -| `web/src/realtime/RealtimeVoiceSession.tsx` / token call | Pass `voice_settings` override | -| `web/src/realtime/VoiceBackendSession.tsx` | Read all settings from localStorage, pass in config | -| `web/src/routes/settings/index.tsx` | Preset picker, custom prompt textarea, ElevenLabs sliders | -| `hub/src/web/routes/voice.ts` | Accept and forward `voice_settings` in token request | +### Qwen "unwanted laughter" risk ---- +Because Qwen can produce laughter natively and instruction-following is strong, a poorly worded +prompt could make it laugh too readily. Include a qualifier: +``` +Natural sounds are appropriate — but only when genuinely fitting. Never perform emotion. +``` -## What the Qwen instruction-based approach means for UI +### Gemini affective dialog API flag -For Qwen, "speaking faster" or "cheerfully" is a natural language instruction, not a slider. -The Personality preset system handles this cleanly — the "Expressive" preset for Qwen just -injects "Be enthusiastic and expressive. Vary your pace and energy." into the system prompt, -which Qwen will follow. No need to expose a "send a message saying speak faster" control. +`enable_affective_dialog: true` is a `v1alpha` API feature — not in the stable endpoint. +Use the alpha API path when enabling it and note it may change. Worth the instability for +long sessions where user mood affects the interaction. --- ## Open questions -1. **ElevenLabs per-conversation override** — does overriding `agent.prompt.prompt` in the token - request fully replace or append to the agent's configured prompt? Verify before implementing - — may need to fetch the agent's base prompt and concatenate. -2. **Gemini SSML in Live** — Google may add prosody controls to Live API in future. Monitor - release notes; the UI should be easy to extend if sliders become meaningful. -3. **Qwen full voice personality descriptions** — the 55-voice list with personality descriptions - is in Chinese docs. Worth translating/curating before shipping the picker. -4. **Preset persistence** — localStorage for now; Phase 3 of self-bootstrapping-config.md moves - settings to SQLite. Design the storage shape so migration is a copy, not a restructure. -5. **Per-session vs persistent** — should personality settings apply to all future sessions or - be overridable per-session-start? Start with persistent (stored settings always apply); - per-session override is a later enhancement. +1. **ElevenLabs base prompt concatenation** — does `conversation_config_override.agent.prompt.prompt` + append or replace the agent's configured prompt? Must verify before implementing custom prompt + pass-through. +2. **Gemini native laughter** — undocumented. Worth a practical test: prompt "laugh warmly when + something is funny" and try a few amusing inputs. Document the result. +3. **Qwen full voice list** — 55 voices, personalities primarily in Chinese docs. Need a test + matrix: run a standard warmth-test paragraph through each available voice, note character. +4. **Audio tag prompt engineering** — the right instruction density for tag emission needs + testing per-voice and per-model. Some ElevenLabs voices interpret tags more naturally than + others. +5. **Per-session vs persistent personality** — start with persistent (stored settings apply to + all sessions). Per-session override (different character for different agent sessions) is a + later enhancement but worth designing the storage shape for. +6. **Qwen backchanneling in HAPI** — Qwen's native full-duplex backchanneling handling means + the VAD (voice activity detection) threshold may need tuning. The hub's current Qwen proxy + uses server VAD with `threshold: 0.5, silence_duration_ms: 800`. These values may suppress + natural "mmm" and "uh-huh" sounds from the user. Worth testing. From 5fc19370486e363acdfd1539e977f5bf4fb69801 Mon Sep 17 00:00:00 2001 From: HeavyGee <133152184+heavygee@users.noreply.github.com> Date: Sat, 30 May 2026 14:40:31 +0100 Subject: [PATCH 0007/1600] docs: canon new functionality intake playbook for agents Add AGENTS.md with mandatory discovery, playback, soup vs clean demo, and pre-operator gates (tests, cold review, Playwright). Detail in docs/tooling/new-feature-intake.md; index in tooling README. Co-authored-by: Cursor --- AGENTS.md | 123 +++++++++++++++++++ docs/tooling/README.md | 11 +- docs/tooling/new-feature-intake.md | 190 +++++++++++++++++++++++++++++ 3 files changed, 320 insertions(+), 4 deletions(-) create mode 100644 AGENTS.md create mode 100644 docs/tooling/new-feature-intake.md diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 00000000000..7f3d05008ec --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,123 @@ +# AGENTS.md + +> Before proceeding, read `~/coding/AGENTS.local.md` and `~/coding/SOUL.md` when present +> (or repo-local copies). They define local operator voice. Never commit or cite them. + +--- + +## Progress Reporting + +Each update is one line: + +``` + | | | +``` + +**STATE:** `moving` · `blocked` · `done` +**DELTA:** What changed. New only. No history. +**NEXT:** What happens next without operator input. +**ASK:** Required operator action, or `none`. + +Rules: +- One line. No logs, no reasoning. +- `moving` → ASK is `none` +- `blocked` → ASK is concrete and actionable +- No meaningful change twice in a row → STATE becomes `blocked` + +``` +moving | tests added | running CI | none +blocked | missing env var | waiting | add STRIPE_KEY +done | deployed to prod | monitoring | none +``` + +--- + +## Decision Contract + +**Ambiguity** — Ask before acting. One focused question, not a list. +**Done** — Tests pass. Fix **deployed** to the environment the operator cares about (usually production). Commit when the repo uses git-triggered deploy; otherwise use the project's documented deploy command. Operator unblocked. +**Scope** — Do exactly what was asked. Flag additions as options; don't implement them. +**Blockers** — Surface immediately. Never work around a blocker silently. + +--- + +## Ship After Fix (mandatory) + +Saving files locally is not shipping. + +When you change application code in a repo with a known deploy path (Vercel, Fly, Docker prod, etc.): + +1. **Deploy** after the fix using that project's documented prod command (e.g. `npx vercel deploy --prod --scope `). Do not wait for the operator to ask. +2. **Do not** treat "I'll deploy when you push" as done unless deploy is impossible (missing credentials, hook failure, operator said local-only). +3. If deploy fails, state **blocked** with the error; do not claim the fix is live. +4. **Preview-only** changes: deploy preview/staging when documented; prod only when the fix targets prod UX or config. + +Exception: docs-only or `.md` with no runtime effect — deploy optional unless the operator expects it live. + +**HAPI new functionality** — "deployed" means the **demo environment** (soup or clean instance) is live and passed pre-operator gates (§6 below). Upstream PR and daily-driver manifest are **later** steps after operator dogfood approval. See [New functionality intake](#new-functionality-intake). + +--- + +## Communication + +No narration. No recaps. No "here's what I did." +Report results, not activity. If nothing changed, say so. + +**GitHub issues and PRs** — When you mention an issue or pull request number, it must be a markdown link, not bare `#NNN`. Use the canonical URL on the repo you mean (upstream HAPI: `https://github.com/tiann/hapi/issues/737`, `https://github.com/tiann/hapi/pull/567`). Example: [issue #737](https://github.com/tiann/hapi/issues/737). + +**New product features (web/hub/cli)** — Follow [New functionality intake](#new-functionality-intake) (mandatory). Worktree discipline and soup mechanics: `AGENTS.local.md` (never upstream) + [`docs/tooling/new-feature-intake.md`](docs/tooling/new-feature-intake.md). + +--- + +## New functionality intake + +When the operator asks for **new behavior**, follow this pipeline. Do not skip to implementation or "please test in your browser." + +### Roles + +| Role | Owns | +|------|------| +| **Orchestrator** | Peer handoff, discovery (§1-3), issue filing, soup vs clean choice, manifest / Proxmox demo | +| **Feature peer** | Worktree implementation, §6 gates, iteration until operator handoff | +| **After operator OK** | Upstream PR + review threads (§8) | + +### Pipeline + +| Step | Gate | +|------|------| +| **0** | Spawn a **feature peer agent** linked to the parent session (id + request + issue link when exists). | +| **1** | **Code search** — prove the behavior does not already exist (cite paths). | +| **2** | **Upstream search** — `tiann/hapi` issues and PRs, **open and closed**. | +| **3** | **Playback** — summarize problem, gap, and scope; wait for operator confirmation. | +| **4** | Operator: **open issue** (you create it) or **worktree spike** without issue. | +| **5** | If implementing: operator chooses **soup** (manifest + `:3006`) or **clean instance** (Proxmox / LAN, `upstream/main` only, **new port**; do not swing `hapi-active`). Add **runner** only if remote spawn is required. | +| **6** | **Before operator test:** `bun typecheck` + `bun run test` → **cold code review** ([rubric](docs/tooling/cold-pr-review-rubric.md)) → **Playwright smoke** (`scripts/dev/read-hapi-web.mjs`; `PLAYWRIGHT_CHROME_PATH=/usr/bin/google-chrome` on Linux). Fix failures; do not hand off early. | +| **7** | Operator **dogfoods** via tailnet + LAN links (deep route when possible). | +| **8** | **After explicit approval:** verification + cold review on PR diff → `gh pr create` vs `upstream/main` → link issue. | + +Full detail, Proxmox notes, and diagram: [`docs/tooling/new-feature-intake.md`](docs/tooling/new-feature-intake.md). + +```mermaid +flowchart LR + subgraph discover + A[Peer agent] --> B[Code + upstream search] + B --> C[Playback] + end + subgraph build + C --> D[Issue or worktree] + D --> E[Soup or clean demo] + E --> F[Tests + cold review + Playwright] + end + subgraph ship + F --> G[Operator dogfood] + G --> H[Upstream PR] + end +``` + +**Never** ask the operator to browser-test until §6 passes. **Never** open an upstream PR until §7 approves. + +--- + +## CursorVox cockpit (visual review) + +For **CursorVox** UI judgments ("go look at the interface"), use the mobile screenshot harness and vision on the PNGs. See **`~/coding/cursorvox/AGENTS.md`** (Visual review section): `cd ~/coding/cursorvox/frontend && npm run capture-ui`, then read `screenshots/mobile-cockpit/*.png`. diff --git a/docs/tooling/README.md b/docs/tooling/README.md index ba33f596d42..6423ee56eb9 100644 --- a/docs/tooling/README.md +++ b/docs/tooling/README.md @@ -26,6 +26,7 @@ Feature agents should **read the relevant doc below at session start**; meta bot | Doc | Purpose | |-----|---------| +| [new-feature-intake.md](./new-feature-intake.md) | **Operator requests new behavior** — discovery, playback, soup vs clean demo, gates before dogfood, PR after approval | | [worktree-testing.md](./worktree-testing.md) | `hapi-active` symlink, `hapi-use-worktree`, service swing | | [driver-soup.md](./driver-soup.md) | Daily driver manifest, merge-train PR worktrees, garden vs soup | | [pr-review-loop.md](./pr-review-loop.md) | Pre-PR verification + cold review; pre-push open-PR gate; post-push PR comment poll | @@ -141,10 +142,12 @@ Then read both tooling docs if anything changed since last session. ## Session-start checklist (feature agents) -1. Read repo `AGENTS.local.md` (or `~/coding/AGENTS.local.md`). -2. Confirm `git branch --show-current` and `pwd` — worktree, not main checkout. -3. Skim [worktree-testing.md](./worktree-testing.md) if touching hub or systemd. -4. Skim [pr-review-loop.md](./pr-review-loop.md) before push/PR. +1. Read repo [`AGENTS.md`](../AGENTS.md) — [New functionality intake](../AGENTS.md#new-functionality-intake) when the operator requests new behavior. +2. Read repo `AGENTS.local.md` (or `~/coding/AGENTS.local.md`). +3. Confirm `git branch --show-current` and `pwd` — worktree, not main checkout. +4. Skim [new-feature-intake.md](./new-feature-intake.md) for soup vs clean demo and §6 gates (tests, cold review, Playwright **before** operator browser test). +5. Skim [worktree-testing.md](./worktree-testing.md) if touching hub or systemd. +6. Skim [pr-review-loop.md](./pr-review-loop.md) before push/PR (after operator dogfood approval). --- diff --git a/docs/tooling/new-feature-intake.md b/docs/tooling/new-feature-intake.md new file mode 100644 index 00000000000..629c97f6298 --- /dev/null +++ b/docs/tooling/new-feature-intake.md @@ -0,0 +1,190 @@ +# New functionality intake + +Canonical process when the operator asks for **new product behavior** (web, hub, cli, shared). Summarized in repo root [`AGENTS.md`](../../AGENTS.md). + +**Orchestrator** (original session / tooling meta) owns steps 0-5 and demo topology. **Feature peer agent** owns implementation and pre-operator gates. **Upstream PR** happens only after operator dogfood approval. + +--- + +## Flow + +```mermaid +flowchart TD + A[Operator request] --> B[Spawn feature peer agent
link to parent session] + B --> C[Code search — exists already?] + C --> D[Upstream search tiann/hapi
issues + PRs open and closed] + D --> E{Novel gap?} + E -->|No| F[Stop: cite code / issue / PR] + E -->|Yes| G[Playback summary → operator] + G --> H{Operator} + H -->|File issue| I[Create issue on tiann/hapi] + H -->|Spike only| J[Worktree, no issue yet] + I --> K{Implement?} + J --> K + K -->|No| L[Wait] + K -->|Yes| M{Demo topology} + M -->|Soup| N[Worktree + manifest layer
hapi-driver-rebuild + hapi-use-driver] + M -->|Clean| O[Proxmox hub upstream/main only
new port + tailnet/LAN links] + N --> P[Peer: typecheck + test] + O --> P + P --> Q[Peer: cold code review on diff] + Q --> R[Peer: Playwright smoke on demo URL] + R --> S{Gates pass?} + S -->|No| T[Fix in worktree — do not ping operator] + T --> P + S -->|Yes| U[Operator links + what to click] + U --> V[Operator dogfoods] + V --> W{Approved?} + W -->|No| T + W -->|Yes| X[Cold review + verification
gh pr create vs upstream/main] + X --> Y[Link PR to issue; resolve review threads] +``` + +--- + +## Step-by-step + +### 0 — Feature peer agent + +When intake starts, spawn (or hand off to) a **dedicated feature peer** that: + +- Records the **parent session id** and operator request verbatim +- Does not edit `~/coding/hapi-driver` by hand +- Reports back to the orchestrator with evidence (search results, demo URL, test output) + +One feature → one worktree → one peer. Do not share worktrees across agents. + +### 1 — Code search (mandatory) + +Search the repo for existing behavior, flags, routes, and UI: + +- Ripgrep / semantic search on keywords from the request +- Read call sites, not just filenames +- **Stop with links** if the feature already exists or is partially implemented + +### 2 — Upstream search (mandatory) + +On `tiann/hapi`, search **open and closed** issues and PRs for the same theme: + +```bash +gh search issues "scroll restoration" --repo tiann/hapi --state open +gh search issues "scroll restoration" --repo tiann/hapi --state closed +gh search prs "voice backend" --repo tiann/hapi --state open +gh search prs "voice backend" --repo tiann/hapi --state closed +``` + +Also check merged PRs that may have landed on `upstream/main` since the operator last synced. + +### 3 — Playback (mandatory) + +Before any implementation, send the operator a short **playback**: + +- What you think they want +- What already exists (code + upstream links) +- Proposed gap / scope +- Risks or trade-offs (one paragraph max) + +Wait for confirmation or correction. + +### 4 — Issue vs worktree-first + +Operator chooses: + +| Choice | Action | +|--------|--------| +| **Open issue** | Create issue on `tiann/hapi` (use `gh api` + jq for bodies with backticks — see github-cli-safety skill) | +| **Spike first** | `hapi-worktree-create --branch feat/...` from `upstream/main`; issue optional until dogfood passes | + +Upstream PR branches stay **`upstream/main...HEAD`** for review. Soup manifest merge order is **local only** — see [driver-soup.md](./driver-soup.md). + +### 5 — Demo topology (operator choice) + +Ask explicitly: **soup** or **clean instance**? + +#### Soup (daily driver) + +- Implement in `~/coding/hapi-` +- Add branch to `~/.config/hapi/driver-manifest.yaml` +- `hapi-driver-rebuild --build-web --verify` +- `hapi-use-driver` when ready (**restarts hub + runner on :3006; kills live sessions**) + +Operator URL: existing tailnet hub (e.g. `https://hapi.tail9944ee.ts.net`) after swing. + +#### Clean (upstream/main only) + +Do **not** swing `hapi-active`. Stand up a **separate** hub on Proxmox (or LAN) from **`upstream/main` only** plus the feature branch: + +| Component | When | +|-----------|------| +| **Hub** | Always — new `HAPI_LISTEN_PORT`, separate `HAPI_HOME` / DB if isolation needed | +| **Web** | Bundled in hub `web/dist` or vite proxy per operator setup | +| **Runner** | Only if the feature needs **remote spawn / live CLI sessions** — second runner must target the **new** hub URL, not `:3006` | + +Give the operator **both**: + +- Tailnet URL with deep path when possible (`/sessions/...`, `/settings`, etc.) +- LAN / Proxmox URL (`http://:/...`) + +Document port, `HAPI_HOME`, and branch in the handoff message. + +### 6 — Gates before operator test (mandatory) + +**Do not** send "please try it" until all pass in the **demo worktree / instance**: + +1. **`bun typecheck`** and **`bun run test`** (and `cd web && bun run test` if web touched) +2. **Cold code review** — full diff vs `upstream/main`; use [cold-pr-review-rubric.md](./cold-pr-review-rubric.md); fix Blocker/Major before handoff +3. **Playwright smoke** — real browser, demo URL, auth token from operator env: + +```bash +# Linux: bundled Chromium may hang; prefer system Chrome +export PLAYWRIGHT_CHROME_PATH=/usr/bin/google-chrome + +node scripts/dev/read-hapi-web.mjs \ + "https:///sessions/?token=" \ + --expect "visible proof string" \ + --screenshot localdocs/playwright-runs/handoff.png \ + --timeout 30000 +``` + +Assert: no `QuotaExceededError` / error-boundary strings in console; `failedRequests` empty unless documented. + +Optional feature-specific repro scripts live under `scripts/dev/*-playwright.mjs`. + +Only after (1)-(3): send operator **links**, **what to click**, and **screenshot path**. + +### 7 — Operator dogfood + +Operator validates in browser. Iterate in the worktree; re-run gates after each round. **Do not** open upstream PR until explicit approval. + +### 8 — Upstream PR (after approval) + +1. `/verification-before-completion` with command output +2. `/requesting-code-review` on `git diff upstream/main...HEAD` +3. `gh pr create` against `tiann/hapi` `main` — link issue (`Fixes #NNN`) +4. Post-push: [pr-review-loop.md](./pr-review-loop.md) + +To land on daily soup after merge: drop layer from manifest if merged, or keep until upstream contains the commit; `hapi-driver-rebuild`. + +--- + +## Ship / done semantics (HAPI) + +For **new functionality intake**, "done" stages: + +| Stage | Meaning | +|-------|---------| +| **Ready for operator** | Gates in §6 passed; links delivered | +| **Operator approved** | Explicit OK to open PR | +| **Shipped upstream** | PR merged on `tiann/hapi` | +| **On soup** | Manifest rebuilt + `hapi-use-driver` (operator choice) | + +Global "Ship After Fix" applies to **production/tailnet daily driver** only after operator chooses soup activation — not before dogfood. + +--- + +## Related + +- [driver-soup.md](./driver-soup.md) — manifest, rebuild, read-only driver tree +- [worktree-testing.md](./worktree-testing.md) — `hapi-use-worktree`, env symlinks +- [pr-review-loop.md](./pr-review-loop.md) — pre-PR and post-push discipline +- [README.md](./README.md) — meta bot charter From cafe0eacc7c09f2fa0720820e0ba68f808617061 Mon Sep 17 00:00:00 2001 From: HeavyGee <133152184+heavygee@users.noreply.github.com> Date: Sat, 30 May 2026 14:45:51 +0100 Subject: [PATCH 0008/1600] docs: peer spawn handoff template and clarify agent instruction roots Require orchestrator to list completed vs owned intake steps when spawning feature peers. Document that rules load from ~/coding/hapi workspace and docs/operator/AGENTS.md, not hapi-driver runtime tree. Root AGENTS.md is a fork redirect only. Co-authored-by: Cursor --- .cursor/rules/operator-fork.mdc | 4 +- AGENTS.md | 127 ++--------------------------- docs/operator/AGENTS.md | 25 +++++- docs/tooling/README.md | 2 +- docs/tooling/new-feature-intake.md | 64 +++++++++++++-- 5 files changed, 94 insertions(+), 128 deletions(-) diff --git a/.cursor/rules/operator-fork.mdc b/.cursor/rules/operator-fork.mdc index d0db8436302..089e75c124f 100644 --- a/.cursor/rules/operator-fork.mdc +++ b/.cursor/rules/operator-fork.mdc @@ -9,5 +9,7 @@ This repo is a **fork** of `tiann/hapi`. Root **`AGENTS.md` is intentionally abs **Read `docs/operator/AGENTS.md`** - single canonical guide (HAPI baseline + fork intent + upstream PR discipline). -- Upstream PR branches: from `upstream/main` only; never include `docs/operator/`, `docs/plans/`, or `AGENTS.md` edits in the PR diff. +- **New functionality requests:** also read `docs/tooling/new-feature-intake.md`. Orchestrator spawns feature peers with explicit **done vs owned** intake steps (§0 handoff block). +- **Workspace** = `~/coding/hapi` (mirror). **`hapi-driver`** = runtime on `:3006` via `hapi-active` — not the default instruction root. +- Upstream PR branches: from `upstream/main` only; never include `docs/operator/`, `docs/plans/`, or root `AGENTS.md` body in the PR diff. - Plans: `docs/plans/`. diff --git a/AGENTS.md b/AGENTS.md index 7f3d05008ec..f17790f4c35 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,123 +1,14 @@ -# AGENTS.md +# AGENTS.md (fork redirect) -> Before proceeding, read `~/coding/AGENTS.local.md` and `~/coding/SOUL.md` when present -> (or repo-local copies). They define local operator voice. Never commit or cite them. +**Do not treat this file as the full agent guide on `heavygee/hapi`.** ---- +| Read first | Purpose | +|------------|---------| +| [`docs/operator/AGENTS.md`](docs/operator/AGENTS.md) | Fork canon — HAPI baseline, upstream PR discipline, voice/XR pointers | +| [`docs/tooling/new-feature-intake.md`](docs/tooling/new-feature-intake.md) | New product behavior — discovery, **peer spawn handoff**, soup vs clean demo, gates before operator test | -## Progress Reporting +**Operator-local (gitignored):** `~/coding/AGENTS.local.md` and optional repo `AGENTS.local.md`. -Each update is one line: +**Runtime vs workspace:** Cursor workspace is usually `~/coding/hapi` (mirror + local docs). **`~/coding/hapi-driver`** is the daily-driver **runtime** via `hapi-active` — not the default place agent rules load from. -``` - | | | -``` - -**STATE:** `moving` · `blocked` · `done` -**DELTA:** What changed. New only. No history. -**NEXT:** What happens next without operator input. -**ASK:** Required operator action, or `none`. - -Rules: -- One line. No logs, no reasoning. -- `moving` → ASK is `none` -- `blocked` → ASK is concrete and actionable -- No meaningful change twice in a row → STATE becomes `blocked` - -``` -moving | tests added | running CI | none -blocked | missing env var | waiting | add STRIPE_KEY -done | deployed to prod | monitoring | none -``` - ---- - -## Decision Contract - -**Ambiguity** — Ask before acting. One focused question, not a list. -**Done** — Tests pass. Fix **deployed** to the environment the operator cares about (usually production). Commit when the repo uses git-triggered deploy; otherwise use the project's documented deploy command. Operator unblocked. -**Scope** — Do exactly what was asked. Flag additions as options; don't implement them. -**Blockers** — Surface immediately. Never work around a blocker silently. - ---- - -## Ship After Fix (mandatory) - -Saving files locally is not shipping. - -When you change application code in a repo with a known deploy path (Vercel, Fly, Docker prod, etc.): - -1. **Deploy** after the fix using that project's documented prod command (e.g. `npx vercel deploy --prod --scope `). Do not wait for the operator to ask. -2. **Do not** treat "I'll deploy when you push" as done unless deploy is impossible (missing credentials, hook failure, operator said local-only). -3. If deploy fails, state **blocked** with the error; do not claim the fix is live. -4. **Preview-only** changes: deploy preview/staging when documented; prod only when the fix targets prod UX or config. - -Exception: docs-only or `.md` with no runtime effect — deploy optional unless the operator expects it live. - -**HAPI new functionality** — "deployed" means the **demo environment** (soup or clean instance) is live and passed pre-operator gates (§6 below). Upstream PR and daily-driver manifest are **later** steps after operator dogfood approval. See [New functionality intake](#new-functionality-intake). - ---- - -## Communication - -No narration. No recaps. No "here's what I did." -Report results, not activity. If nothing changed, say so. - -**GitHub issues and PRs** — When you mention an issue or pull request number, it must be a markdown link, not bare `#NNN`. Use the canonical URL on the repo you mean (upstream HAPI: `https://github.com/tiann/hapi/issues/737`, `https://github.com/tiann/hapi/pull/567`). Example: [issue #737](https://github.com/tiann/hapi/issues/737). - -**New product features (web/hub/cli)** — Follow [New functionality intake](#new-functionality-intake) (mandatory). Worktree discipline and soup mechanics: `AGENTS.local.md` (never upstream) + [`docs/tooling/new-feature-intake.md`](docs/tooling/new-feature-intake.md). - ---- - -## New functionality intake - -When the operator asks for **new behavior**, follow this pipeline. Do not skip to implementation or "please test in your browser." - -### Roles - -| Role | Owns | -|------|------| -| **Orchestrator** | Peer handoff, discovery (§1-3), issue filing, soup vs clean choice, manifest / Proxmox demo | -| **Feature peer** | Worktree implementation, §6 gates, iteration until operator handoff | -| **After operator OK** | Upstream PR + review threads (§8) | - -### Pipeline - -| Step | Gate | -|------|------| -| **0** | Spawn a **feature peer agent** linked to the parent session (id + request + issue link when exists). | -| **1** | **Code search** — prove the behavior does not already exist (cite paths). | -| **2** | **Upstream search** — `tiann/hapi` issues and PRs, **open and closed**. | -| **3** | **Playback** — summarize problem, gap, and scope; wait for operator confirmation. | -| **4** | Operator: **open issue** (you create it) or **worktree spike** without issue. | -| **5** | If implementing: operator chooses **soup** (manifest + `:3006`) or **clean instance** (Proxmox / LAN, `upstream/main` only, **new port**; do not swing `hapi-active`). Add **runner** only if remote spawn is required. | -| **6** | **Before operator test:** `bun typecheck` + `bun run test` → **cold code review** ([rubric](docs/tooling/cold-pr-review-rubric.md)) → **Playwright smoke** (`scripts/dev/read-hapi-web.mjs`; `PLAYWRIGHT_CHROME_PATH=/usr/bin/google-chrome` on Linux). Fix failures; do not hand off early. | -| **7** | Operator **dogfoods** via tailnet + LAN links (deep route when possible). | -| **8** | **After explicit approval:** verification + cold review on PR diff → `gh pr create` vs `upstream/main` → link issue. | - -Full detail, Proxmox notes, and diagram: [`docs/tooling/new-feature-intake.md`](docs/tooling/new-feature-intake.md). - -```mermaid -flowchart LR - subgraph discover - A[Peer agent] --> B[Code + upstream search] - B --> C[Playback] - end - subgraph build - C --> D[Issue or worktree] - D --> E[Soup or clean demo] - E --> F[Tests + cold review + Playwright] - end - subgraph ship - F --> G[Operator dogfood] - G --> H[Upstream PR] - end -``` - -**Never** ask the operator to browser-test until §6 passes. **Never** open an upstream PR until §7 approves. - ---- - -## CursorVox cockpit (visual review) - -For **CursorVox** UI judgments ("go look at the interface"), use the mobile screenshot harness and vision on the PNGs. See **`~/coding/cursorvox/AGENTS.md`** (Visual review section): `cd ~/coding/cursorvox/frontend && npm run capture-ui`, then read `screenshots/mobile-cockpit/*.png`. +**Peer agents:** orchestrator must pass completed vs owned intake steps — template in `new-feature-intake.md` §0. diff --git a/docs/operator/AGENTS.md b/docs/operator/AGENTS.md index 810b0584080..84979299e8c 100644 --- a/docs/operator/AGENTS.md +++ b/docs/operator/AGENTS.md @@ -45,8 +45,11 @@ ElevenLabs ConvAI today: handoff OK, readback weak, payment, no mode machine. Ta | Doc | Purpose | |-----|---------| -| **`docs/operator/AGENTS.md`** | This file | -| `docs/plans/*` | Integration plans, PR A-F | +| **`docs/operator/AGENTS.md`** | This file (fork agent canon) | +| [`docs/tooling/new-feature-intake.md`](../tooling/new-feature-intake.md) | **New behavior requests** — discovery, spawn handoff, soup vs clean, gates before operator test | +| `docs/tooling/driver-soup.md` | Daily driver manifest, `hapi-active`, worktrees | +| `docs/plans/*` | Integration plans, PR A-F; peer agent: `2026-05-30-peer-agent-offering.md` | +| `docs/operator/xr/*` | **XR only (private):** work graph + mindmap visualization epic — start at `xr/work-graph-and-visualization.md` | | `docs/operator-local-tooling.md` | `localdocs/`, machine indexes | | `docs/dogfood/*.md` | Voice evidence for upstream PR bodies | @@ -294,3 +297,21 @@ Vitest; `*.test.ts` next to source; hub + cli tests; no web tests currently. 5. **Upstream first** - general fixes → upstream PR. 6. **Maintainer canon read-only** - never PR edits to `AGENTS.md`, `CONTRIBUTING.md`, root `README.md`. 7. **Fork agent doc is here only** - root `AGENTS.md` must not exist on fork `main`. + +--- + +## New functionality intake + +When the operator asks for **new product behavior**, follow [`docs/tooling/new-feature-intake.md`](../tooling/new-feature-intake.md) end-to-end. + +**Orchestrator** completes steps 1-3 (and usually 4-5), then spawns a **feature peer** with the mandatory handoff block in that doc (completed steps vs peer-owned steps). + +**Feature peer** implements in `~/coding/hapi-` — not in `~/coding/hapi-driver` by hand. Pass §6 (tests, cold review, Playwright) **before** asking the operator to browser-test. Upstream PR only after operator dogfood approval (§8). + +**Instruction roots:** agents read **this file** and tooling docs from the **`~/coding/hapi` workspace**, plus `~/coding/AGENTS.local.md`. The **daily driver** (`~/coding/hapi-driver`) is what **`hapi-active` runs** — not where IDE rules come from unless that tree is the opened workspace. + +--- + +## Peer spawn handoff (required) + +Do not spawn a feature peer without filling the template in [`new-feature-intake.md` §0](../tooling/new-feature-intake.md#0--feature-peer-agent--mandatory-handoff). Minimum: parent session id, playback summary, which steps are **DONE** vs **peer-owned**, worktree path, demo topology (soup vs clean). diff --git a/docs/tooling/README.md b/docs/tooling/README.md index 6423ee56eb9..a265989e267 100644 --- a/docs/tooling/README.md +++ b/docs/tooling/README.md @@ -142,7 +142,7 @@ Then read both tooling docs if anything changed since last session. ## Session-start checklist (feature agents) -1. Read repo [`AGENTS.md`](../AGENTS.md) — [New functionality intake](../AGENTS.md#new-functionality-intake) when the operator requests new behavior. +1. Read [`docs/operator/AGENTS.md`](../operator/AGENTS.md) (fork canon). For new behavior, read [new-feature-intake.md](./new-feature-intake.md) (orchestrator handoff §0). 2. Read repo `AGENTS.local.md` (or `~/coding/AGENTS.local.md`). 3. Confirm `git branch --show-current` and `pwd` — worktree, not main checkout. 4. Skim [new-feature-intake.md](./new-feature-intake.md) for soup vs clean demo and §6 gates (tests, cold review, Playwright **before** operator browser test). diff --git a/docs/tooling/new-feature-intake.md b/docs/tooling/new-feature-intake.md index 629c97f6298..c2cfe088411 100644 --- a/docs/tooling/new-feature-intake.md +++ b/docs/tooling/new-feature-intake.md @@ -44,15 +44,67 @@ flowchart TD ## Step-by-step -### 0 — Feature peer agent +### 0 — Feature peer agent + mandatory handoff + +When intake starts, spawn (or hand off to) a **dedicated feature peer**. The **orchestrator prompt is not optional** — it must list **which steps are already done** and **which steps the peer owns**. + +Copy and fill this block (do not spawn a peer with only "implement X"): + +```markdown +## Parent +- Orchestrator session: +- Operator request: + +## Intake status (orchestrator completed) +- [ ] 1 Code search — DONE: +- [ ] 2 Upstream search — DONE: +- [ ] 3 Playback — DONE: operator confirmed on +- [ ] 4 Issue — OR spike-only (no issue yet) +- [ ] 5 Demo topology — — + +## Your assignment (feature peer) +- Own steps: **** +- Do NOT redo: **** +- Worktree: `~/coding/hapi-` @ branch `` (create if missing) +- Do NOT edit `~/coding/hapi-driver` by hand +- Read: `docs/operator/AGENTS.md` + this file (`docs/tooling/new-feature-intake.md`) +- Before operator browser test: pass §6 (typecheck, test, cold review, Playwright) +- Report back to orchestrator with: demo URLs, screenshot path, test output, diff stat + +## Links +- Issue: ... +- Playback summary: ... +``` -When intake starts, spawn (or hand off to) a **dedicated feature peer** that: +One feature → one worktree → one peer. Do not share worktrees across agents. -- Records the **parent session id** and operator request verbatim -- Does not edit `~/coding/hapi-driver` by hand -- Reports back to the orchestrator with evidence (search results, demo URL, test output) +--- -One feature → one worktree → one peer. Do not share worktrees across agents. +## Where agents read instructions (not the daily driver) + +Confusion is common: **`hapi-active` → `~/coding/hapi-driver` is the running hub/runner**, not where Cursor rules usually live. + +| Source | Path | Applies when | +|--------|------|----------------| +| **Fork agent canon** | [`docs/operator/AGENTS.md`](../operator/AGENTS.md) | Workspace is `~/coding/hapi` (primary mirror). **Start here** on this fork. | +| **Intake playbook** | This file | New product behavior (steps 0-8). | +| **Tooling / soup** | [`driver-soup.md`](./driver-soup.md), [`README.md`](./README.md) | Manifest, rebuild, `hapi-use-driver`, worktrees. | +| **Operator local (gitignored)** | `~/coding/AGENTS.local.md`, optional `AGENTS.local.md` in repo | Machine voice, pre-PR checklist, worktree discipline. Never upstream. | +| **Global persona** | `~/coding/SOUL.md` | User-facing tone (never cite in PRs). | +| **Upstream-style root `AGENTS.md`** | Only on **`upstream/main`** / `tiann/hapi` | Not used on fork `main` (fork deletes or stubs it). Do not treat upstream root copy as fork canon. | +| **`cli/AGENTS.md`** | Package scope | Extra rules when the agent's focus is `cli/` only. | +| **Daily driver tree** | `~/coding/hapi-driver` | **Runtime / served UI** after `hapi-driver-rebuild` + `hapi-use-driver`. **Not** the default instruction root unless you explicitly open that folder as the IDE workspace. | + +**Where to edit code** + +| Goal | Edit in | +|------|---------| +| Upstream PR | `~/coding/hapi-` worktree, branch from `upstream/main` | +| Mirror / docs | `~/coding/hapi` (primary checkout) | +| Soup on `:3006` | Manifest merge only — `hapi-driver-rebuild`, never hand-edit driver | +| Try feature in browser | Whatever `readlink -f ~/coding/hapi-active` points at (usually driver after `hapi-use-driver`) | + +**Peer agents** spawned from an orchestrator inherit **files on disk** in the workspace (`~/coding/hapi`), not the orchestrator's chat memory. They only know completed intake steps if the handoff block above says so. ### 1 — Code search (mandatory) From d3657e90865bc77a249f0d60d5a6e5d42e8e73da Mon Sep 17 00:00:00 2001 From: HeavyGee <133152184+heavygee@users.noreply.github.com> Date: Sat, 30 May 2026 15:41:45 +0100 Subject: [PATCH 0009/1600] docs(tooling): add hapi-sync-fork-main and enforce mirror before driver rebuild Fork main must track upstream/main plus fork-only docs. New sync script; driver rebuild fails when primary main is behind upstream. Document cadence in driver-soup and meta bot README. Co-authored-by: Cursor --- docs/operator/AGENTS.md | 2 + docs/tooling/README.md | 14 +- docs/tooling/driver-manifest.example.yaml | 3 +- docs/tooling/driver-soup.md | 14 +- scripts/tooling/hapi-driver-rebuild.sh | 183 ++++++++++++++++++++++ scripts/tooling/hapi-sync-fork-main.sh | 80 ++++++++++ 6 files changed, 288 insertions(+), 8 deletions(-) create mode 100755 scripts/tooling/hapi-driver-rebuild.sh create mode 100755 scripts/tooling/hapi-sync-fork-main.sh diff --git a/docs/operator/AGENTS.md b/docs/operator/AGENTS.md index 84979299e8c..4b4d99b3a85 100644 --- a/docs/operator/AGENTS.md +++ b/docs/operator/AGENTS.md @@ -29,6 +29,8 @@ upstream → https://github.com/tiann/hapi.git origin → https://github.com/heavygee/hapi.git ``` +**Fork `main` mirror:** after upstream activity run `hapi-sync-fork-main` (in `scripts/tooling/`) and `git push origin main`. Primary checkout `~/coding/hapi` must contain **upstream product code + fork docs** — not docs-only drift. `hapi-driver-rebuild` refuses if `main` is behind `upstream/main`. + - Extend upstream; PR-sized slices; default path unchanged when new code off - **Never modify maintainer canon** in upstream PRs - see § Upstream file boundaries - **Upstream PR branches** start from `upstream/main` only - product code diffs, nothing fork-local diff --git a/docs/tooling/README.md b/docs/tooling/README.md index a265989e267..dda427ca17c 100644 --- a/docs/tooling/README.md +++ b/docs/tooling/README.md @@ -27,6 +27,7 @@ Feature agents should **read the relevant doc below at session start**; meta bot | Doc | Purpose | |-----|---------| | [new-feature-intake.md](./new-feature-intake.md) | **Operator requests new behavior** — discovery, playback, soup vs clean demo, gates before dogfood, PR after approval | +| `scripts/tooling/hapi-sync-fork-main.sh` | Keep `~/coding/hapi` `main` = upstream + fork docs | | [worktree-testing.md](./worktree-testing.md) | `hapi-active` symlink, `hapi-use-worktree`, service swing | | [driver-soup.md](./driver-soup.md) | Daily driver manifest, merge-train PR worktrees, garden vs soup | | [pr-review-loop.md](./pr-review-loop.md) | Pre-PR verification + cold review; pre-push open-PR gate; post-push PR comment poll | @@ -103,7 +104,16 @@ cd web && bun run build # before hub UI test Meta bot does not merge or declare "done" without evidence from these (or the repo's documented subset for a given change). -### 5. Documentation maintenance +### 5. Fork `main` sync (mandatory cadence) + +```bash +hapi-sync-fork-main # after upstream merges +hapi-sync-fork-main --check-only # before driver rebuild / intake (also enforced by hapi-driver-rebuild) +``` + +Push `origin main` after sync. Fork `main` must stay **upstream/main + fork-only docs** — see [driver-soup.md](./driver-soup.md). + +### 6. Documentation maintenance (tooling docs) When tooling behavior changes, meta bot updates **in the same change**: @@ -113,7 +123,7 @@ When tooling behavior changes, meta bot updates **in the same change**: Keep [pr-review-loop.md](./pr-review-loop.md) honest about IDE vs CLI hook support. -### 6. Worktree lifecycle +### 7. Worktree lifecycle After merge: diff --git a/docs/tooling/driver-manifest.example.yaml b/docs/tooling/driver-manifest.example.yaml index 614238d7010..07efd84431c 100644 --- a/docs/tooling/driver-manifest.example.yaml +++ b/docs/tooling/driver-manifest.example.yaml @@ -7,8 +7,7 @@ base: upstream/main layers: - # Current daily-driver soup: pluggable voice + session list attention + # Open upstream PRs / fork branches only (drop when merged to upstream/main) - branch: feat/pluggable-voice-backend - - pr: 699 # Add unmerged PRs / branches below (top merges last): diff --git a/docs/tooling/driver-soup.md b/docs/tooling/driver-soup.md index b51e5d15e15..651e6998527 100644 --- a/docs/tooling/driver-soup.md +++ b/docs/tooling/driver-soup.md @@ -79,10 +79,16 @@ hapi-use-driver # restarts hapi-hub + hapi-runner together ### When upstream moves -1. Edit manifest (drop merged PRs, add new ones) -2. `hapi-driver-rebuild --build-web --verify` -3. Garden smoke: `curl -sf http://127.0.0.1:3006/health` + quick VR/web check -4. Log drift in `~/coding/hapi-garden/GARDEN_LOGBOOK.md` if API changed +1. **Sync fork mirror:** `hapi-sync-fork-main` then `git push origin main` +2. Edit manifest — drop layers merged to `upstream/main` +3. `hapi-driver-rebuild --build-web --verify` (refuses if fork `main` is behind upstream) +4. `hapi-use-driver` when ready +5. Garden smoke: `curl -sf http://127.0.0.1:3006/health` + quick web/VR check +6. Log drift in `~/coding/hapi-garden/GARDEN_LOGBOOK.md` if API changed + +### Keeping fork `main` truthful + +Fork `main` = **`upstream/main` + fork-only docs/plans**. After upstream merges: run `hapi-sync-fork-main`. Meta bot: weekly `--check-only` even if idle. --- diff --git a/scripts/tooling/hapi-driver-rebuild.sh b/scripts/tooling/hapi-driver-rebuild.sh new file mode 100755 index 00000000000..25d6adbd421 --- /dev/null +++ b/scripts/tooling/hapi-driver-rebuild.sh @@ -0,0 +1,183 @@ +#!/usr/bin/env bash +# Rebuild ~/coding/hapi-driver from ~/.config/hapi/driver-manifest.yaml +# +# ~/coding/hapi-driver is READ-ONLY between rebuilds — this script is the only +# supported way to change it. Hand-edits and cp-from-other-worktrees are forbidden. +# +# Usage: +# hapi-driver-rebuild # rebuild only (no hub restart) +# hapi-driver-rebuild --build-web # also rebuild web/dist +# hapi-driver-rebuild --verify # run typecheck + test after merge +# hapi-driver-rebuild --activate # swing hapi-active + restart hub (DESTRUCTIVE to live sessions) +# +set -euo pipefail + +PRIMARY="${HAPI_PRIMARY:-$HOME/coding/hapi}" +DRIVER="${HAPI_DRIVER:-$HOME/coding/hapi-driver}" +MANIFEST="${HAPI_DRIVER_MANIFEST:-$HOME/.config/hapi/driver-manifest.yaml}" +PARSE="$PRIMARY/scripts/tooling/parse-driver-manifest.mjs" +DRIVER_BRANCH="${HAPI_DRIVER_BRANCH:-driver/integration}" +BUN="${BUN:-$HOME/.bun/bin/bun}" + +BUILD_WEB=0 +VERIFY=0 +ACTIVATE=0 + +while [[ $# -gt 0 ]]; do + case "$1" in + --build-web) BUILD_WEB=1; shift ;; + --verify) VERIFY=1; shift ;; + --activate) ACTIVATE=1; shift ;; + -h|--help) + sed -n '2,12p' "$0" + exit 0 + ;; + *) echo "Unknown option: $1" >&2; exit 2 ;; + esac +done + +if [[ ! -f "$MANIFEST" ]]; then + echo "ERROR: manifest not found: $MANIFEST" >&2 + echo "Copy example: mkdir -p ~/.config/hapi && cp $PRIMARY/docs/tooling/driver-manifest.example.yaml $MANIFEST" >&2 + exit 1 +fi + +if [[ ! -x "$PARSE" ]] && [[ ! -f "$PARSE" ]]; then + echo "ERROR: parser missing: $PARSE" >&2 + exit 1 +fi + +mkdir -p "$(dirname "$MANIFEST")" + +echo "Fetching upstream..." +git -C "$PRIMARY" fetch upstream + +SYNC_SCRIPT="$PRIMARY/scripts/tooling/hapi-sync-fork-main.sh" +if [[ -x "$SYNC_SCRIPT" ]]; then + if ! "$SYNC_SCRIPT" --check-only 2>/dev/null; then + echo "ERROR: fork main is behind upstream/main. Run: hapi-sync-fork-main && git push origin main" >&2 + exit 1 + fi +elif git -C "$PRIMARY" show-ref --verify --quiet refs/heads/main; then + behind_main="$(git -C "$PRIMARY" rev-list --count main..upstream/main 2>/dev/null || echo 0)" + if [[ "${behind_main:-0}" -gt 0 ]]; then + echo "ERROR: $PRIMARY main is ${behind_main} commit(s) behind upstream/main" >&2 + echo " Run: hapi-sync-fork-main" >&2 + exit 1 + fi +fi + +if [[ -d "$DRIVER" ]] && [[ -n "$(git -C "$DRIVER" status --porcelain)" ]]; then + echo "WARNING: $DRIVER has local changes — rebuild will reset the tree (stash or commit them elsewhere first)." >&2 + echo " Only manifest-driven rebuilds belong on the driver tree. See docs/tooling/driver-soup.md" >&2 +fi + +if [[ ! -d "$DRIVER" ]]; then + echo "Creating driver worktree at $DRIVER (branch $DRIVER_BRANCH)..." + git -C "$PRIMARY" worktree add -b "$DRIVER_BRANCH" "$DRIVER" upstream/main +fi + +if [[ ! -e "$DRIVER/hub/.env" ]]; then + echo "Linking hub/.env → ~/.hapi/hub.env" + ln -s "$HOME/.hapi/hub.env" "$DRIVER/hub/.env" +fi + +manifest_json="$("$BUN" run "$PARSE" "$MANIFEST")" +base_ref="$(echo "$manifest_json" | jq -r '.base')" +layer_count="$(echo "$manifest_json" | jq '.layers | length')" + +if echo "$manifest_json" | jq -e '.layers[] | select(.ref == "fix/web-scroll-guard-unwrap-race")' >/dev/null; then + pr722_state="$(gh pr view 722 --repo "${HAPI_PR_REPO:-tiann/hapi}" --json state --jq '.state' 2>/dev/null || true)" + if [[ "$pr722_state" == "MERGED" ]]; then + echo "WARNING: upstream PR #722 is merged — drop fix/web-scroll-guard-unwrap-race from $MANIFEST" >&2 + fi +fi + +if [[ -n "$upstream_tip" && "$base_ref" == "upstream/main" ]]; then + echo "Base: upstream/main @ $(git -C "$PRIMARY" log -1 --oneline "$upstream_tip")" +fi + +echo "Resetting $DRIVER to $base_ref ($layer_count layer(s))..." +git -C "$DRIVER" checkout -B "$DRIVER_BRANCH" "$base_ref" + +resolve_merge_ref() { + local type="$1" ref="$2" + case "$type" in + branch|integrate) + if git -C "$PRIMARY" rev-parse --verify "${ref}^{commit}" >/dev/null 2>&1; then + echo "$ref" + else + echo "ERROR: layer ref not found: $ref" >&2 + exit 1 + fi + ;; + pr) + local head_branch pr_repo="${HAPI_PR_REPO:-tiann/hapi}" + head_branch="$(gh pr view "$ref" --repo "$pr_repo" --json headRefName --jq '.headRefName' 2>/dev/null || true)" + if [[ -z "$head_branch" || "$head_branch" == "null" ]]; then + echo "ERROR: could not resolve PR #$ref via gh (repo: $pr_repo)" >&2 + exit 1 + fi + git -C "$PRIMARY" fetch origin "$head_branch" 2>/dev/null || true + echo "origin/$head_branch" + ;; + *) + echo "ERROR: unknown layer type: $type" >&2 + exit 1 + ;; + esac +} + +for i in $(seq 0 $((layer_count - 1))); do + type="$(echo "$manifest_json" | jq -r ".layers[$i].type")" + ref="$(echo "$manifest_json" | jq -r ".layers[$i].ref")" + merge_ref="$(resolve_merge_ref "$type" "$ref")" + + echo "Layer $((i + 1))/$layer_count: merging $merge_ref ..." + if ! git -C "$DRIVER" merge --no-edit "$merge_ref"; then + echo "ERROR: merge conflict merging $merge_ref into $DRIVER_BRANCH" >&2 + echo "Resolve in $DRIVER, commit, or fix manifest order." >&2 + exit 1 + fi +done + +echo "Driver HEAD: $(git -C "$DRIVER" log -1 --oneline)" + +if [[ "$BUILD_WEB" -eq 1 ]] || [[ ! -f "$DRIVER/web/dist/index.html" ]]; then + echo "Building web..." + if [[ ! -d "$DRIVER/node_modules" ]]; then + echo "Installing dependencies (first driver build)..." + (cd "$DRIVER" && "$BUN" install) + fi + (cd "$DRIVER/web" && "$BUN" run build) +fi + +if [[ "$VERIFY" -eq 1 ]]; then + echo "Running typecheck..." + (cd "$DRIVER" && "$BUN" typecheck) + echo "Running tests..." + (cd "$DRIVER" && "$BUN" run test) +fi + +echo "" +echo "Driver rebuild complete: $DRIVER @ $(git -C "$DRIVER" rev-parse --short HEAD)" +echo "Manifest: $MANIFEST" +echo "Active hub: $(readlink -f "$HOME/coding/hapi-active" 2>/dev/null || echo '(no symlink)')" + +if [[ "$ACTIVATE" -eq 1 ]]; then + echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━" + echo " ACTIVATE: restarts hapi-hub + hapi-runner (kills sessions)" + echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━" + if [[ -t 0 ]]; then + read -rp "Proceed with hapi-use-worktree $DRIVER? [y/N] " yn + [[ "${yn,,}" == "y" ]] || { echo "Skipped activate."; exit 0; } + else + echo "Non-interactive: skipping activate (re-run with TTY or use hapi-use-worktree manually)." >&2 + exit 0 + fi + exec hapi-use-worktree "$DRIVER" +fi + +echo "" +echo "To swing live hub (restarts service — kills sessions):" +echo " hapi-use-worktree $DRIVER" diff --git a/scripts/tooling/hapi-sync-fork-main.sh b/scripts/tooling/hapi-sync-fork-main.sh new file mode 100755 index 00000000000..a95f3e4580b --- /dev/null +++ b/scripts/tooling/hapi-sync-fork-main.sh @@ -0,0 +1,80 @@ +#!/usr/bin/env bash +# Sync fork main with upstream/main, keeping fork-only commits on top. +# +# Fork main should always be: upstream/main + operator docs/plans (never product-only drift). +# +# Usage: +# hapi-sync-fork-main # fetch + merge if behind +# hapi-sync-fork-main --check-only # exit 1 if primary main is behind upstream +# hapi-sync-fork-main --rebase # rebase fork-only commits onto upstream (linear history) +# +set -euo pipefail + +PRIMARY="${HAPI_PRIMARY:-$HOME/coding/hapi}" +UPSTREAM_REF="${HAPI_UPSTREAM_REF:-upstream/main}" +MAIN_BRANCH="${HAPI_MAIN_BRANCH:-main}" + +CHECK_ONLY=0 +USE_REBASE=0 + +while [[ $# -gt 0 ]]; do + case "$1" in + --check-only) CHECK_ONLY=1; shift ;; + --rebase) USE_REBASE=1; shift ;; + -h|--help) + sed -n '2,12p' "$0" + exit 0 + ;; + *) echo "Unknown option: $1" >&2; exit 2 ;; + esac +done + +if [[ ! -d "$PRIMARY/.git" ]]; then + echo "ERROR: not a git repo: $PRIMARY" >&2 + exit 1 +fi + +echo "Fetching upstream..." +git -C "$PRIMARY" fetch upstream + +if ! git -C "$PRIMARY" show-ref --verify --quiet "refs/remotes/$UPSTREAM_REF"; then + echo "ERROR: missing $UPSTREAM_REF" >&2 + exit 1 +fi + +behind="$(git -C "$PRIMARY" rev-list --count "$MAIN_BRANCH..$UPSTREAM_REF" 2>/dev/null || echo 0)" +ahead="$(git -C "$PRIMARY" rev-list --count "$UPSTREAM_REF..$MAIN_BRANCH" 2>/dev/null || echo 0)" + +echo "fork $MAIN_BRANCH: ${ahead} ahead, ${behind} behind $UPSTREAM_REF" + +if [[ "$behind" -eq 0 ]]; then + echo "OK: $PRIMARY $MAIN_BRANCH is up to date with $UPSTREAM_REF" + exit 0 +fi + +if [[ "$CHECK_ONLY" -eq 1 ]]; then + echo "FAIL: $PRIMARY $MAIN_BRANCH is $behind commit(s) behind $UPSTREAM_REF" >&2 + echo "Run: hapi-sync-fork-main" >&2 + exit 1 +fi + +if [[ -n "$(git -C "$PRIMARY" status --porcelain)" ]]; then + echo "ERROR: $PRIMARY has uncommitted changes — stash or commit before sync" >&2 + git -C "$PRIMARY" status --short | head -20 + exit 1 +fi + +git -C "$PRIMARY" checkout "$MAIN_BRANCH" + +if [[ "$USE_REBASE" -eq 1 ]]; then + echo "Rebasing $MAIN_BRANCH onto $UPSTREAM_REF..." + git -C "$PRIMARY" rebase "$UPSTREAM_REF" +else + echo "Merging $UPSTREAM_REF into $MAIN_BRANCH..." + git -C "$PRIMARY" merge "$UPSTREAM_REF" -m "merge(upstream): sync tiann/hapi main into fork main ($(git -C "$PRIMARY" rev-parse --short "$UPSTREAM_REF"))" +fi + +echo "" +echo "Synced: $(git -C "$PRIMARY" log -1 --oneline)" +echo "Next: review ~/.config/hapi/driver-manifest.yaml — drop layers now on upstream/main" +echo " hapi-driver-rebuild --build-web --verify (if soup layers changed)" From e059d656d8dcec28a203998127eccff72c8150bd Mon Sep 17 00:00:00 2001 From: HeavyGee <133152184+heavygee@users.noreply.github.com> Date: Sat, 30 May 2026 16:21:32 +0100 Subject: [PATCH 0010/1600] chore(tooling): add full scripts/tooling set and fork commit hooks Track driver/sync/worktree helpers in-repo; install-git-hooks sets core.hooksPath for secrets and operator-only path gates. Fix hapi-driver-rebuild upstream_tip after sync check. Co-authored-by: Cursor --- docs/tooling/README.md | 1 + docs/tooling/commit-hooks.md | 37 ++++++++ scripts/tooling/git-hooks/commit-msg | 18 ++++ scripts/tooling/git-hooks/pre-commit | 105 +++++++++++++++++++++ scripts/tooling/hapi-driver-rebuild.sh | 1 + scripts/tooling/hapi-runner-from-active.sh | 27 ++++++ scripts/tooling/hapi-use-driver.sh | 9 ++ scripts/tooling/hapi-use-worktree.sh | 70 ++++++++++++++ scripts/tooling/hapi-worktree-create.sh | 95 +++++++++++++++++++ scripts/tooling/install-git-hooks.sh | 12 +++ scripts/tooling/parse-driver-manifest.mjs | 46 +++++++++ 11 files changed, 421 insertions(+) create mode 100644 docs/tooling/commit-hooks.md create mode 100755 scripts/tooling/git-hooks/commit-msg create mode 100755 scripts/tooling/git-hooks/pre-commit create mode 100755 scripts/tooling/hapi-runner-from-active.sh create mode 100755 scripts/tooling/hapi-use-driver.sh create mode 100755 scripts/tooling/hapi-use-worktree.sh create mode 100755 scripts/tooling/hapi-worktree-create.sh create mode 100755 scripts/tooling/install-git-hooks.sh create mode 100755 scripts/tooling/parse-driver-manifest.mjs diff --git a/docs/tooling/README.md b/docs/tooling/README.md index dda427ca17c..2cad20298c3 100644 --- a/docs/tooling/README.md +++ b/docs/tooling/README.md @@ -28,6 +28,7 @@ Feature agents should **read the relevant doc below at session start**; meta bot |-----|---------| | [new-feature-intake.md](./new-feature-intake.md) | **Operator requests new behavior** — discovery, playback, soup vs clean demo, gates before dogfood, PR after approval | | `scripts/tooling/hapi-sync-fork-main.sh` | Keep `~/coding/hapi` `main` = upstream + fork docs | +| [commit-hooks.md](./commit-hooks.md) | `install-git-hooks.sh` — secrets + operator path gates | | [worktree-testing.md](./worktree-testing.md) | `hapi-active` symlink, `hapi-use-worktree`, service swing | | [driver-soup.md](./driver-soup.md) | Daily driver manifest, merge-train PR worktrees, garden vs soup | | [pr-review-loop.md](./pr-review-loop.md) | Pre-PR verification + cold review; pre-push open-PR gate; post-push PR comment poll | diff --git a/docs/tooling/commit-hooks.md b/docs/tooling/commit-hooks.md new file mode 100644 index 00000000000..835a04ea43c --- /dev/null +++ b/docs/tooling/commit-hooks.md @@ -0,0 +1,37 @@ +# Git commit hooks (fork) + +Install once per clone: + +```bash +~/coding/hapi/scripts/tooling/install-git-hooks.sh +``` + +Sets `core.hooksPath` → `scripts/tooling/git-hooks/` (no Husky/npm required). + +## What is blocked + +| Gate | Scope | +|------|--------| +| **Paths** | `localdocs/`, `.env*`, `AGENTS.local.md`, `*~` | +| **Operator paths on PR branches** | `docs/operator/`, `docs/plans/` when branch is not `main` / `driver/integration` / `docs/*` | +| **Persona / fork-only strings** | `jessica-mood`, `SOUL_SESSION`, `SOUL.md`, `localdocs/` in staged content | +| **Secrets (heuristic)** | `CLI_API_TOKEN=`, `*_API_KEY=`, `sk-`, `ghp_`, etc. in staged diff | +| **Commit message** | `jessica-mood`, `SOUL.md`, `AGENTS.local`, `Co-authored-by: Cursor` | + +**Allowed:** ElevenLabs voice name `Jessica` in product code (`web/src/lib/voices.ts`) — not the same as fork route `jessica-mood`. + +## Bypass + +```bash +HAPI_SKIP_COMMIT_HOOKS=1 git commit ... +``` + +Use only for emergencies; never on upstream PR branches. + +## Upstream PRs + +Hooks run on every commit in this clone. Upstream PR branches must still pass: + +```bash +git diff --name-only upstream/main...HEAD | grep -E '^(docs/operator|docs/plans)' && echo STOP +``` diff --git a/scripts/tooling/git-hooks/commit-msg b/scripts/tooling/git-hooks/commit-msg new file mode 100755 index 00000000000..2f7ddbc9592 --- /dev/null +++ b/scripts/tooling/git-hooks/commit-msg @@ -0,0 +1,18 @@ +#!/usr/bin/env bash +# Block persona / operator leaks in commit messages. +set -euo pipefail + +MSG_FILE="${1:?}" +MSG="$(cat "$MSG_FILE")" + +if [[ "${HAPI_SKIP_COMMIT_HOOKS:-}" == "1" ]]; then + exit 0 +fi + +if printf '%s' "$MSG" | grep -qiE 'jessica-mood|SOUL\.md|AGENTS\.local|co-authored-by: cursor'; then + echo "commit-msg: message contains forbidden reference (persona/operator leak)" >&2 + echo "Use HAPI_SKIP_COMMIT_HOOKS=1 only for emergencies." >&2 + exit 1 +fi + +exit 0 diff --git a/scripts/tooling/git-hooks/pre-commit b/scripts/tooling/git-hooks/pre-commit new file mode 100755 index 00000000000..892364d102f --- /dev/null +++ b/scripts/tooling/git-hooks/pre-commit @@ -0,0 +1,105 @@ +#!/usr/bin/env bash +# Fork commit gate — secrets + operator-only paths/strings. +# Install: scripts/tooling/install-git-hooks.sh +set -euo pipefail + +ROOT="$(git rev-parse --show-toplevel)" +cd "$ROOT" + +if [[ "${HAPI_SKIP_COMMIT_HOOKS:-}" == "1" ]]; then + exit 0 +fi + +STAGED="$(git diff --cached --name-only --diff-filter=ACMR)" +if [[ -z "$STAGED" ]]; then + exit 0 +fi + +BRANCH="$(git branch --show-current 2>/dev/null || echo '')" +FAIL=0 + +report() { + echo "pre-commit: $1" >&2 + FAIL=1 +} + +# --- forbidden paths (never commit) --- +while IFS= read -r path; do + [[ -z "$path" ]] && continue + case "$path" in + localdocs/*|*/localdocs/*) + report "refusing to commit localdocs/: $path" + ;; + .env|.env.*|*/.env|*/.env.*|hub/.env~|*/hub/.env~) + report "refusing to commit env file: $path" + ;; + AGENTS.local.md|*/AGENTS.local.md) + report "refusing to commit AGENTS.local.md: $path" + ;; + *~) + report "refusing to commit backup file: $path" + ;; + esac +done <<< "$STAGED" + +# --- operator-only paths on upstream PR branches (not fork main / docs branches) --- +if [[ "$BRANCH" != "main" && "$BRANCH" != driver/integration && "$BRANCH" != docs/* ]]; then + while IFS= read -r path; do + [[ -z "$path" ]] && continue + case "$path" in + docs/operator/*|docs/plans/*) + report "operator/plans path on PR branch '$BRANCH': $path (use fork main only)" + ;; + esac + done <<< "$STAGED" +fi + +# --- forbidden substrings in staged content (operator / persona leaks) --- +# Note: ElevenLabs voice name "Jessica" in product code is allowed; block fork-only routes/persona. +PATTERNS=( + 'jessica-mood' + 'SOUL_SESSION' + 'SOUL.md' + 'AGENTS.local.md' + 'localdocs/' +) + +for pattern in "${PATTERNS[@]}"; do + if git diff --cached -G"$pattern" --quiet -- .; then + : + else + report "staged content matches forbidden pattern: $pattern" + git diff --cached -G"$pattern" --name-only -- . >&2 || true + fi +done + +# --- crude secret patterns in staged diff --- +SECRET_PATTERNS=( + 'CLI_API_TOKEN=[^[:space:]]+' + 'ELEVENLABS_API_KEY=[^[:space:]]+' + 'GEMINI_API_KEY=[^[:space:]]+' + 'OPENAI_API_KEY=[^[:space:]]+' + 'sk-[A-Za-z0-9]{20,}' + 'ghp_[A-Za-z0-9]{20,}' + 'xox[baprs]-[A-Za-z0-9-]{10,}' +) + +for pattern in "${SECRET_PATTERNS[@]}"; do + if git diff --cached -G"$pattern" --quiet -- . 2>/dev/null; then + continue + fi + if git diff --cached -G"$pattern" --name-only -- . 2>/dev/null | grep -q .; then + report "possible secret in staged diff (pattern: $pattern)" + git diff --cached -G"$pattern" --name-only -- . >&2 || true + fi +done + +# --- commit message (when using commit-msg hook this is separate; cheap check for -m via env) --- + +if [[ "$FAIL" -ne 0 ]]; then + echo "" >&2 + echo "Bypass only if you know what you are doing: HAPI_SKIP_COMMIT_HOOKS=1 git commit ..." >&2 + exit 1 +fi + +exit 0 diff --git a/scripts/tooling/hapi-driver-rebuild.sh b/scripts/tooling/hapi-driver-rebuild.sh index 25d6adbd421..c30e17ae623 100755 --- a/scripts/tooling/hapi-driver-rebuild.sh +++ b/scripts/tooling/hapi-driver-rebuild.sh @@ -51,6 +51,7 @@ mkdir -p "$(dirname "$MANIFEST")" echo "Fetching upstream..." git -C "$PRIMARY" fetch upstream +upstream_tip="$(git -C "$PRIMARY" rev-parse upstream/main 2>/dev/null || true)" SYNC_SCRIPT="$PRIMARY/scripts/tooling/hapi-sync-fork-main.sh" if [[ -x "$SYNC_SCRIPT" ]]; then diff --git a/scripts/tooling/hapi-runner-from-active.sh b/scripts/tooling/hapi-runner-from-active.sh new file mode 100755 index 00000000000..e641cb4f935 --- /dev/null +++ b/scripts/tooling/hapi-runner-from-active.sh @@ -0,0 +1,27 @@ +#!/usr/bin/env bash +# systemd ExecStart helper: run hapi runner from whatever tree hapi-active points at. +set -euo pipefail + +BUN="${BUN:-$HOME/.bun/bin/bun}" +ACTIVE_LINK="${HAPI_ACTIVE_LINK:-$HOME/coding/hapi-active}" +ACTIVE="$(readlink -f "$ACTIVE_LINK")" +CLI_DIR="$ACTIVE/cli" +CODING_ROOT="${HAPI_CODING_ROOT:-$HOME/coding}" + +if [[ ! -f "$CLI_DIR/src/index.ts" ]]; then + echo "ERROR: active tree missing cli: $CLI_DIR" >&2 + exit 1 +fi + +if [[ ! -d "$ACTIVE/node_modules" ]]; then + echo "ERROR: active tree missing node_modules — run: cd $ACTIVE && bun install" >&2 + exit 1 +fi + +export HAPI_API_URL="${HAPI_API_URL:-http://127.0.0.1:3006}" +export PATH="$HOME/.local/bin:$HOME/.npm-global/bin:/usr/local/bin:/usr/bin:/bin" + +cd "$CLI_DIR" +exec "$BUN" run src/index.ts runner start-sync \ + --workspace-root "$CODING_ROOT" \ + --workspace-root "$ACTIVE" diff --git a/scripts/tooling/hapi-use-driver.sh b/scripts/tooling/hapi-use-driver.sh new file mode 100755 index 00000000000..1605371ef1c --- /dev/null +++ b/scripts/tooling/hapi-use-driver.sh @@ -0,0 +1,9 @@ +#!/usr/bin/env bash +# hapi-use-driver +# Swings hapi-hub.service to the daily-driver soup checkout. +# Same as: hapi-use-worktree ~/coding/hapi-driver + +set -euo pipefail + +DRIVER="${HAPI_DRIVER:-$HOME/coding/hapi-driver}" +exec hapi-use-worktree "$DRIVER" diff --git a/scripts/tooling/hapi-use-worktree.sh b/scripts/tooling/hapi-use-worktree.sh new file mode 100755 index 00000000000..42cf43ea107 --- /dev/null +++ b/scripts/tooling/hapi-use-worktree.sh @@ -0,0 +1,70 @@ +#!/usr/bin/env bash +# hapi-use-worktree +# Swings hapi-active and restarts hub + runner together from that tree. + +set -euo pipefail + +WORKTREE="${1:?Usage: hapi-use-worktree }" +WORKTREE="$(realpath "$WORKTREE")" +ACTIVE_LINK="${HAPI_ACTIVE_LINK:-$HOME/coding/hapi-active}" +HUB_ENV="${HAPI_HUB_ENV:-$HOME/.hapi/hub.env}" +BUN="${BUN:-$HOME/.bun/bin/bun}" +DRIVER="${HAPI_DRIVER:-$HOME/coding/hapi-driver}" + +if [[ ! -d "$WORKTREE/hub" ]] || [[ ! -d "$WORKTREE/cli" ]]; then + echo "ERROR: $WORKTREE must be a full HAPI worktree (hub/ + cli/)" >&2 + exit 1 +fi + +if [[ ! -e "$WORKTREE/hub/.env" ]]; then + echo "Linking $HUB_ENV → $WORKTREE/hub/.env" + ln -sfn "$HUB_ENV" "$WORKTREE/hub/.env" +fi + +if [[ ! -d "$WORKTREE/node_modules" ]]; then + echo "Installing dependencies in $WORKTREE ..." + (cd "$WORKTREE" && "$BUN" install) +fi + +if [[ ! -f "$WORKTREE/web/dist/index.html" ]]; then + echo "WARNING: $WORKTREE/web/dist/index.html missing — hub UI may be stale." >&2 + if [[ -t 0 ]]; then + read -rp "Build web now? [y/N] " yn + if [[ "${yn,,}" == "y" ]]; then + (cd "$WORKTREE/web" && "$BUN" run build) + fi + fi +fi + +echo "" +echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━" +echo " STACK SWITCH — kills live agent sessions" +echo " Restarts: hapi-hub.service + hapi-runner.service" +echo " Target: $WORKTREE" +echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━" +if [[ -t 0 ]]; then + read -rp "Proceed? [y/N] " confirm + [[ "${confirm,,}" == "y" ]] || { echo "Aborted."; exit 1; } +elif [[ "${HAPI_STACK_SWITCH_YES:-}" != "1" ]]; then + echo "Refusing stack switch without TTY. Export HAPI_STACK_SWITCH_YES=1 to confirm." >&2 + exit 1 +fi + +echo "Pointing hapi-active → $WORKTREE" +ln -sfn "$WORKTREE" "$ACTIVE_LINK" + +echo "Restarting hapi-hub.service + hapi-runner.service ..." +sudo systemctl restart hapi-hub.service hapi-runner.service + +echo "" +echo "Active stack:" +echo " hapi-active → $(readlink -f "$ACTIVE_LINK")" +echo " hub: $(systemctl is-active hapi-hub.service)" +echo " runner: $(systemctl is-active hapi-runner.service)" +systemctl show hapi-runner.service -p ExecStart --value | sed 's/^/ runner ExecStart: /' + +if [[ "$WORKTREE" == "$(realpath "$DRIVER")" ]]; then + echo "Daily driver active." +else + echo "Restore daily driver: hapi-use-driver" +fi diff --git a/scripts/tooling/hapi-worktree-create.sh b/scripts/tooling/hapi-worktree-create.sh new file mode 100755 index 00000000000..052df472c29 --- /dev/null +++ b/scripts/tooling/hapi-worktree-create.sh @@ -0,0 +1,95 @@ +#!/usr/bin/env bash +# Create a PR formulation worktree. +# +# Usage: +# hapi-worktree-create --branch [--after branch:foo] [--after pr:692] ... +# hapi-worktree-create pluggable-voice --branch feat/pluggable-voice-backend +# hapi-worktree-create stacked-foo --branch feat/foo --after feat/pluggable-voice-backend +# +set -euo pipefail + +PRIMARY="${HAPI_PRIMARY:-$HOME/coding/hapi}" +BUN="${BUN:-$HOME/.bun/bin/bun}" +BASE="${HAPI_WORKTREE_BASE:-upstream/main}" +NAME="" +BRANCH="" +AFTER=() + +usage() { + sed -n '2,10p' "$0" +} + +while [[ $# -gt 0 ]]; do + case "$1" in + --branch) BRANCH="${2:?}"; shift 2 ;; + --base) BASE="${2:?}"; shift 2 ;; + --after) AFTER+=("${2:?}"); shift 2 ;; + -h|--help) usage; exit 0 ;; + -*) echo "Unknown option: $1" >&2; usage >&2; exit 2 ;; + *) + if [[ -z "$NAME" ]]; then NAME="$1"; shift + else echo "Unexpected arg: $1" >&2; exit 2; fi + ;; + esac +done + +[[ -n "$NAME" ]] || { echo "Usage: hapi-worktree-create --branch [--after ref...]" >&2; exit 2; } +[[ -n "$BRANCH" ]] || { echo "ERROR: --branch required" >&2; exit 2; } + +PATH_DIR="$HOME/coding/hapi-${NAME}" +HUB_ENV="$HOME/.hapi/hub.env" + +if [[ -e "$PATH_DIR" ]]; then + echo "ERROR: path already exists: $PATH_DIR" >&2 + exit 1 +fi + +if git -C "$PRIMARY" show-ref --verify --quiet "refs/heads/$BRANCH"; then + echo "ERROR: branch $BRANCH already exists locally — pick a new branch name or use existing worktree" >&2 + exit 1 +fi + +echo "Fetching upstream..." +git -C "$PRIMARY" fetch upstream + +echo "Creating worktree $PATH_DIR (branch $BRANCH from $BASE)..." +git -C "$PRIMARY" worktree add -b "$BRANCH" "$PATH_DIR" "$BASE" + +ln -sfn "$HUB_ENV" "$PATH_DIR/hub/.env" + +resolve_after_ref() { + local spec="$1" + if [[ "$spec" =~ ^pr:([0-9]+)$ ]]; then + local pr="${BASH_REMATCH[1]}" + local pr_repo="${HAPI_PR_REPO:-tiann/hapi}" + local head + head="$(gh pr view "$pr" --repo "$pr_repo" --json headRefName --jq '.headRefName')" + git -C "$PRIMARY" fetch origin "$head" 2>/dev/null || true + echo "origin/$head" + else + if git -C "$PRIMARY" rev-parse --verify "${spec}^{commit}" >/dev/null 2>&1; then + echo "$spec" + else + echo "ERROR: --after ref not found: $spec" >&2 + exit 1 + fi + fi +} + +for spec in "${AFTER[@]}"; do + ref="$(resolve_after_ref "$spec")" + echo "Merge train: merging $ref into $BRANCH ..." + if ! git -C "$PATH_DIR" merge --no-edit "$ref"; then + echo "ERROR: merge conflict for --after $spec" >&2 + echo "Resolve in $PATH_DIR and commit." >&2 + exit 1 + fi +done + +echo "" +echo "Worktree ready: $PATH_DIR" +echo "Branch: $BRANCH" +echo " cd $PATH_DIR" +echo " git branch --show-current # confirm before commit/PR" +echo "" +echo "Test on live hub (restarts service): hapi-use-worktree $PATH_DIR" diff --git a/scripts/tooling/install-git-hooks.sh b/scripts/tooling/install-git-hooks.sh new file mode 100755 index 00000000000..9bb165ade95 --- /dev/null +++ b/scripts/tooling/install-git-hooks.sh @@ -0,0 +1,12 @@ +#!/usr/bin/env bash +# Point this clone's git hooks at scripts/tooling/git-hooks/ +set -euo pipefail + +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)" +HOOKS="$ROOT/scripts/tooling/git-hooks" + +chmod +x "$HOOKS"/pre-commit "$HOOKS"/commit-msg 2>/dev/null || true +git -C "$ROOT" config core.hooksPath "$HOOKS" +echo "Installed git hooksPath → $HOOKS" +echo "Hooks: pre-commit (secrets + operator paths), commit-msg (persona leaks)" +echo "Bypass: HAPI_SKIP_COMMIT_HOOKS=1 git commit ..." diff --git a/scripts/tooling/parse-driver-manifest.mjs b/scripts/tooling/parse-driver-manifest.mjs new file mode 100755 index 00000000000..80cb925b614 --- /dev/null +++ b/scripts/tooling/parse-driver-manifest.mjs @@ -0,0 +1,46 @@ +#!/usr/bin/env bun +/** + * Minimal YAML subset parser for ~/.config/hapi/driver-manifest.yaml + * Supports: base, layers with branch / pr / integrate keys. + */ +import { readFileSync } from 'node:fs'; + +const path = process.argv[2]; +if (!path) { + console.error('Usage: parse-driver-manifest.mjs '); + process.exit(2); +} + +const text = readFileSync(path, 'utf8'); +const result = { base: 'upstream/main', layers: [] }; + +for (const raw of text.split('\n')) { + const line = raw.replace(/#.*$/, '').trimEnd(); + if (!line.trim() || line.trim().startsWith('#')) continue; + + const baseMatch = line.match(/^base:\s*(.+)$/); + if (baseMatch) { + result.base = baseMatch[1].trim(); + continue; + } + + const branchMatch = line.match(/^\s*-\s*branch:\s*(.+)$/); + if (branchMatch) { + result.layers.push({ type: 'branch', ref: branchMatch[1].trim() }); + continue; + } + + const prMatch = line.match(/^\s*-\s*pr:\s*(\d+)\s*$/); + if (prMatch) { + result.layers.push({ type: 'pr', ref: Number(prMatch[1]) }); + continue; + } + + const integrateMatch = line.match(/^\s*-\s*integrate:\s*(.+)$/); + if (integrateMatch) { + result.layers.push({ type: 'integrate', ref: integrateMatch[1].trim() }); + continue; + } +} + +console.log(JSON.stringify(result)); From 9f3128b2facb0f3d5d0b351538609f1e0c468fab Mon Sep 17 00:00:00 2001 From: HeavyGee <133152184+heavygee@users.noreply.github.com> Date: Sat, 30 May 2026 17:03:33 +0100 Subject: [PATCH 0011/1600] chore(tooling): harvest-resistant hooks and watch-activate-driver Co-authored-by: Cursor --- docs/tooling/commit-hooks.md | 37 +++---- scripts/tooling/git-hooks/commit-msg | 7 +- scripts/tooling/git-hooks/pre-commit | 104 ++++++++++-------- scripts/tooling/git-hooks/pre-push | 55 +++++++++ scripts/tooling/hapi-watch-activate-driver.sh | 61 ++++++++++ scripts/tooling/install-git-hooks.sh | 4 +- 6 files changed, 199 insertions(+), 69 deletions(-) create mode 100755 scripts/tooling/git-hooks/pre-push create mode 100755 scripts/tooling/hapi-watch-activate-driver.sh diff --git a/docs/tooling/commit-hooks.md b/docs/tooling/commit-hooks.md index 835a04ea43c..56470ed527c 100644 --- a/docs/tooling/commit-hooks.md +++ b/docs/tooling/commit-hooks.md @@ -6,32 +6,29 @@ Install once per clone: ~/coding/hapi/scripts/tooling/install-git-hooks.sh ``` -Sets `core.hooksPath` → `scripts/tooling/git-hooks/` (no Husky/npm required). +Sets `core.hooksPath` → `scripts/tooling/git-hooks/` (pre-commit, commit-msg, **pre-push**). -## What is blocked +## Harvest resistance -| Gate | Scope | -|------|--------| -| **Paths** | `localdocs/`, `.env*`, `AGENTS.local.md`, `*~` | -| **Operator paths on PR branches** | `docs/operator/`, `docs/plans/` when branch is not `main` / `driver/integration` / `docs/*` | -| **Persona / fork-only strings** | `jessica-mood`, `SOUL_SESSION`, `SOUL.md`, `localdocs/` in staged content | -| **Secrets (heuristic)** | `CLI_API_TOKEN=`, `*_API_KEY=`, `sk-`, `ghp_`, etc. in staged diff | -| **Commit message** | `jessica-mood`, `SOUL.md`, `AGENTS.local`, `Co-authored-by: Cursor` | +Fork branches on `origin` must not carry **operator canon**, **plans**, **localdocs**, **XR POC**, or **persona routes** — even on `main`. Hooks block **staging** and **push** of that material so clones/remotes are not a harvest target. -**Allowed:** ElevenLabs voice name `Jessica` in product code (`web/src/lib/voices.ts`) — not the same as fork route `jessica-mood`. +| Layer | Blocks | +|-------|--------| +| **pre-commit** | Staging `docs/operator/`, `docs/plans/`, `localdocs/`, `xr-poc`, `.cursor/rules/operator*`, env files, `jessica-mood` paths/content, `SOUL_*` / `SOUL.md`, secrets | +| **pre-push** | Any **outgoing** commit range that touches those paths or adds `jessica-mood` / SOUL content | +| **commit-msg** | Same tokens in message body | -## Bypass +**Allowed in product code:** ElevenLabs voice name `Jessica` in `web/src/lib/voices.ts` (upstream). **Not allowed:** `hub/.../jessica-mood`, interior-note persona wiring, `docs/operator/*`. -```bash -HAPI_SKIP_COMMIT_HOOKS=1 git commit ... -``` +## Overrides -Use only for emergencies; never on upstream PR branches. +| Variable | Use | +|----------|-----| +| `HAPI_ALLOW_OPERATOR_COMMIT=1` | One-off commit that must touch `docs/operator/` or `docs/plans/` (still review before push) | +| `HAPI_SKIP_COMMIT_HOOKS=1` | Emergency only — disables all three hooks | -## Upstream PRs +**Note:** `docs/operator/` already in historical `main` — hooks stop **new** leaks. To strip from remote history use a separate git history rewrite (not automated here). -Hooks run on every commit in this clone. Upstream PR branches must still pass: +## Upstream PR branches -```bash -git diff --name-only upstream/main...HEAD | grep -E '^(docs/operator|docs/plans)' && echo STOP -``` +Product PRs to `tiann/hapi` must not include fork paths regardless — `git diff --name-only upstream/main...HEAD` should never list `docs/operator/` or `docs/plans/`. diff --git a/scripts/tooling/git-hooks/commit-msg b/scripts/tooling/git-hooks/commit-msg index 2f7ddbc9592..86849e9870a 100755 --- a/scripts/tooling/git-hooks/commit-msg +++ b/scripts/tooling/git-hooks/commit-msg @@ -1,5 +1,4 @@ #!/usr/bin/env bash -# Block persona / operator leaks in commit messages. set -euo pipefail MSG_FILE="${1:?}" @@ -9,9 +8,9 @@ if [[ "${HAPI_SKIP_COMMIT_HOOKS:-}" == "1" ]]; then exit 0 fi -if printf '%s' "$MSG" | grep -qiE 'jessica-mood|SOUL\.md|AGENTS\.local|co-authored-by: cursor'; then - echo "commit-msg: message contains forbidden reference (persona/operator leak)" >&2 - echo "Use HAPI_SKIP_COMMIT_HOOKS=1 only for emergencies." >&2 +if printf '%s' "$MSG" | grep -qiE \ + 'jessica-mood|jessica_mood|SOUL\.md|SOUL_SESSION|AGENTS\.local|docs/operator|docs/plans|localdocs/|co-authored-by:[[:space:]]*cursor'; then + echo "commit-msg: forbidden reference in message (persona / fork-private)" >&2 exit 1 fi diff --git a/scripts/tooling/git-hooks/pre-commit b/scripts/tooling/git-hooks/pre-commit index 892364d102f..a3de1571108 100755 --- a/scripts/tooling/git-hooks/pre-commit +++ b/scripts/tooling/git-hooks/pre-commit @@ -1,5 +1,5 @@ #!/usr/bin/env bash -# Fork commit gate — secrets + operator-only paths/strings. +# Fork commit gate — no harvestable operator/persona material in git. # Install: scripts/tooling/install-git-hooks.sh set -euo pipefail @@ -15,7 +15,6 @@ if [[ -z "$STAGED" ]]; then exit 0 fi -BRANCH="$(git branch --show-current 2>/dev/null || echo '')" FAIL=0 report() { @@ -23,57 +22,80 @@ report() { FAIL=1 } -# --- forbidden paths (never commit) --- +# --- forbidden paths: never enter git (any branch) --- +FORBIDDEN_PREFIXES=( + 'docs/operator/' + 'docs/plans/' + 'localdocs/' + 'web/public/xr-poc/' + '.cursor/rules/operator' +) + while IFS= read -r path; do [[ -z "$path" ]] && continue + for prefix in "${FORBIDDEN_PREFIXES[@]}"; do + if [[ "$path" == "$prefix"* ]]; then + if [[ "${HAPI_ALLOW_OPERATOR_COMMIT:-}" == "1" ]]; then + echo "pre-commit: WARN allowing fork-private path (HAPI_ALLOW_OPERATOR_COMMIT=1): $path" >&2 + else + report "fork-private path blocked: $path (override: HAPI_ALLOW_OPERATOR_COMMIT=1)" + fi + fi + done case "$path" in - localdocs/*|*/localdocs/*) - report "refusing to commit localdocs/: $path" - ;; - .env|.env.*|*/.env|*/.env.*|hub/.env~|*/hub/.env~) - report "refusing to commit env file: $path" + .env|.env.*|hub/.env|hub/.env.*|*/.env|*/.env.*|hub/.env~|*/hub/.env~) + report "env file blocked: $path" ;; AGENTS.local.md|*/AGENTS.local.md) - report "refusing to commit AGENTS.local.md: $path" + report "AGENTS.local.md blocked: $path" ;; *~) - report "refusing to commit backup file: $path" + report "backup file blocked: $path" + ;; + *jessica-mood*|*jessica_mood*) + report "fork-only route path blocked: $path" ;; esac done <<< "$STAGED" -# --- operator-only paths on upstream PR branches (not fork main / docs branches) --- -if [[ "$BRANCH" != "main" && "$BRANCH" != driver/integration && "$BRANCH" != docs/* ]]; then - while IFS= read -r path; do - [[ -z "$path" ]] && continue - case "$path" in - docs/operator/*|docs/plans/*) - report "operator/plans path on PR branch '$BRANCH': $path (use fork main only)" - ;; - esac - done <<< "$STAGED" -fi - -# --- forbidden substrings in staged content (operator / persona leaks) --- -# Note: ElevenLabs voice name "Jessica" in product code is allowed; block fork-only routes/persona. -PATTERNS=( +# --- forbidden content in staged diff (any path) --- +CONTENT_PATTERNS=( 'jessica-mood' + 'jessica_mood' 'SOUL_SESSION' - 'SOUL.md' - 'AGENTS.local.md' + 'SOUL\.md' + '~/coding/SOUL' + 'AGENTS\.local' 'localdocs/' + 'docs/operator/' + 'docs/plans/' ) -for pattern in "${PATTERNS[@]}"; do - if git diff --cached -G"$pattern" --quiet -- .; then - : - else - report "staged content matches forbidden pattern: $pattern" - git diff --cached -G"$pattern" --name-only -- . >&2 || true +SCAN_PATHS=(hub web cli shared package.json) +for pattern in "${CONTENT_PATTERNS[@]}"; do + if git diff --cached -G"$pattern" --quiet -- "${SCAN_PATHS[@]}" 2>/dev/null; then + continue + fi + if [[ "${HAPI_ALLOW_OPERATOR_COMMIT:-}" == "1" ]]; then + echo "pre-commit: WARN content match $pattern (HAPI_ALLOW_OPERATOR_COMMIT=1)" >&2 + continue fi + report "staged product content matches: $pattern" + git diff --cached -G"$pattern" --name-only -- "${SCAN_PATHS[@]}" 2>/dev/null | sed 's/^/ /' >&2 || true done -# --- crude secret patterns in staged diff --- +# ElevenLabs voice label "Jessica" in product files is OK; block only in hub route files. +while IFS= read -r path; do + [[ -z "$path" ]] && continue + case "$path" in + hub/*jessica*|web/*jessica-mood*) + if git diff --cached -- "$path" 2>/dev/null | grep -qi 'jessica'; then + report "jessica reference in fork route file: $path" + fi + ;; + esac +done <<< "$STAGED" + SECRET_PATTERNS=( 'CLI_API_TOKEN=[^[:space:]]+' 'ELEVENLABS_API_KEY=[^[:space:]]+' @@ -81,24 +103,20 @@ SECRET_PATTERNS=( 'OPENAI_API_KEY=[^[:space:]]+' 'sk-[A-Za-z0-9]{20,}' 'ghp_[A-Za-z0-9]{20,}' - 'xox[baprs]-[A-Za-z0-9-]{10,}' ) for pattern in "${SECRET_PATTERNS[@]}"; do - if git diff --cached -G"$pattern" --quiet -- . 2>/dev/null; then + if git diff --cached -G"$pattern" --quiet -- "${SCAN_PATHS[@]}" 2>/dev/null; then continue fi - if git diff --cached -G"$pattern" --name-only -- . 2>/dev/null | grep -q .; then - report "possible secret in staged diff (pattern: $pattern)" - git diff --cached -G"$pattern" --name-only -- . >&2 || true - fi + report "possible secret in staged product diff ($pattern)" + git diff --cached -G"$pattern" --name-only -- "${SCAN_PATHS[@]}" 2>/dev/null | sed 's/^/ /' >&2 || true done -# --- commit message (when using commit-msg hook this is separate; cheap check for -m via env) --- - if [[ "$FAIL" -ne 0 ]]; then echo "" >&2 - echo "Bypass only if you know what you are doing: HAPI_SKIP_COMMIT_HOOKS=1 git commit ..." >&2 + echo "Fork-private material must not land in git (harvest risk on push)." >&2 + echo "Emergency: HAPI_SKIP_COMMIT_HOOKS=1 | operator docs only: HAPI_ALLOW_OPERATOR_COMMIT=1" >&2 exit 1 fi diff --git a/scripts/tooling/git-hooks/pre-push b/scripts/tooling/git-hooks/pre-push new file mode 100755 index 00000000000..82e43dba4df --- /dev/null +++ b/scripts/tooling/git-hooks/pre-push @@ -0,0 +1,55 @@ +#!/usr/bin/env bash +# Block pushing fork-private paths to remotes (harvest resistance). +set -euo pipefail + +if [[ "${HAPI_SKIP_COMMIT_HOOKS:-}" == "1" ]]; then + exit 0 +fi + +ROOT="$(git rev-parse --show-toplevel)" +cd "$ROOT" + +FORBIDDEN_PATH_RE='^(docs/operator/|docs/plans/|localdocs/|web/public/xr-poc/|\.cursor/rules/operator|AGENTS\.local\.md)' + +while read -r local_ref local_sha remote_ref remote_sha; do + [[ -z "${local_ref:-}" || "$local_ref" == *'{'* ]] && continue + + if [[ "$remote_sha" =~ ^0+$ ]]; then + range="$local_sha" + files="$(git rev-list --objects "$local_sha" 2>/dev/null | git diff-tree --no-commit-id --name-only -r "$local_sha" 2>/dev/null || git ls-tree -r --name-only "$local_sha")" + else + range="${remote_sha}..${local_sha}" + files="$(git diff --name-only "$remote_sha" "$local_sha" 2>/dev/null || true)" + fi + + [[ -z "$files" ]] && continue + + bad="$(printf '%s\n' "$files" | grep -E "$FORBIDDEN_PATH_RE" || true)" + if [[ -n "$bad" ]]; then + echo "pre-push: refusing to push commits that touch fork-private paths to remote" >&2 + echo " range: $range" >&2 + printf '%s\n' "$bad" | sed 's/^/ /' >&2 + echo " Private docs stay local or use a different remote. Override: HAPI_SKIP_COMMIT_HOOKS=1" >&2 + exit 1 + fi + + # Content scan on outgoing diff (persona / interior routes) + if [[ "$remote_sha" =~ ^0+$ ]]; then + continue + fi + if git diff "$remote_sha" "$local_sha" -G'jessica-mood' --quiet -- . 2>/dev/null; then + : + else + echo "pre-push: outgoing diff contains jessica-mood (fork-only route)" >&2 + git diff "$remote_sha" "$local_sha" -G'jessica-mood' --name-only -- . >&2 || true + exit 1 + fi + for pat in 'SOUL_SESSION' 'SOUL\.md' '~/coding/SOUL'; do + if ! git diff "$remote_sha" "$local_sha" -G"$pat" --quiet -- . 2>/dev/null; then + echo "pre-push: outgoing diff matches forbidden pattern: $pat" >&2 + exit 1 + fi + done +done + +exit 0 diff --git a/scripts/tooling/hapi-watch-activate-driver.sh b/scripts/tooling/hapi-watch-activate-driver.sh new file mode 100755 index 00000000000..11742938f17 --- /dev/null +++ b/scripts/tooling/hapi-watch-activate-driver.sh @@ -0,0 +1,61 @@ +#!/usr/bin/env bash +# Poll session health until no WORKING agents, then swing hapi-active to daily driver. +# +# Usage: +# hapi-watch-activate-driver # foreground, 30s interval +# hapi-watch-activate-driver --once # exit 0 if activated, 2 if still working +# hapi-watch-activate-driver --interval 15 +# +set -euo pipefail + +PRIMARY="${HAPI_PRIMARY:-$HOME/coding/hapi}" +HEALTH="${HAPI_SESSIONS_HEALTH:-$PRIMARY/scripts/hapi-sessions-health.sh}" +INTERVAL="${HAPI_WATCH_INTERVAL:-30}" +ONCE=0 + +while [[ $# -gt 0 ]]; do + case "$1" in + --once) ONCE=1; shift ;; + --interval) INTERVAL="$2"; shift 2 ;; + -h|--help) + sed -n '2,10p' "$0" + exit 0 + ;; + *) echo "Unknown option: $1" >&2; exit 2 ;; + esac +done + +if [[ ! -x "$HEALTH" ]]; then + echo "ERROR: missing $HEALTH" >&2 + exit 1 +fi + +count_working() { + "$HEALTH" --json 2>/dev/null | jq '[.sessions[]? | select(.status == "WORKING")] | length' +} + +working="$(count_working)" +echo "hapi-watch-activate-driver: WORKING=${working} (poll every ${INTERVAL}s)" + +if [[ "$working" -eq 0 ]]; then + echo "No WORKING sessions — activating daily driver..." + export HAPI_STACK_SWITCH_YES=1 + exec hapi-use-driver +fi + +if [[ "$ONCE" -eq 1 ]]; then + echo "Still ${working} WORKING session(s) — not activating" >&2 + exit 2 +fi + +while true; do + sleep "$INTERVAL" + working="$(count_working)" + ts="$(date '+%Y-%m-%d %H:%M:%S')" + if [[ "$working" -eq 0 ]]; then + echo "$ts WORKING=0 — activating daily driver..." + export HAPI_STACK_SWITCH_YES=1 + exec hapi-use-driver + fi + echo "$ts WORKING=${working} — waiting" +done diff --git a/scripts/tooling/install-git-hooks.sh b/scripts/tooling/install-git-hooks.sh index 9bb165ade95..e5e35bdde21 100755 --- a/scripts/tooling/install-git-hooks.sh +++ b/scripts/tooling/install-git-hooks.sh @@ -5,8 +5,8 @@ set -euo pipefail ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)" HOOKS="$ROOT/scripts/tooling/git-hooks" -chmod +x "$HOOKS"/pre-commit "$HOOKS"/commit-msg 2>/dev/null || true +chmod +x "$HOOKS"/pre-commit "$HOOKS"/commit-msg "$HOOKS"/pre-push 2>/dev/null || true git -C "$ROOT" config core.hooksPath "$HOOKS" echo "Installed git hooksPath → $HOOKS" -echo "Hooks: pre-commit (secrets + operator paths), commit-msg (persona leaks)" +echo "Hooks: pre-commit, commit-msg, pre-push (harvest-resistant fork gates)" echo "Bypass: HAPI_SKIP_COMMIT_HOOKS=1 git commit ..." From ef3b2ddd18b07c868f78662380ba95d4ffe4d489 Mon Sep 17 00:00:00 2001 From: HeavyGee <133152184+heavygee@users.noreply.github.com> Date: Sat, 30 May 2026 17:03:45 +0100 Subject: [PATCH 0012/1600] chore(tooling): ignore Co-authored-by trailers in commit-msg hook Co-authored-by: Cursor --- scripts/tooling/git-hooks/commit-msg | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/scripts/tooling/git-hooks/commit-msg b/scripts/tooling/git-hooks/commit-msg index 86849e9870a..a5aecaeb9d0 100755 --- a/scripts/tooling/git-hooks/commit-msg +++ b/scripts/tooling/git-hooks/commit-msg @@ -2,14 +2,15 @@ set -euo pipefail MSG_FILE="${1:?}" -MSG="$(cat "$MSG_FILE")" +# Cursor may append Co-authored-by trailers; do not treat those as operator leaks. +MSG="$(grep -viE '^[[:space:]]*co-authored-by:' "$MSG_FILE" || true)" if [[ "${HAPI_SKIP_COMMIT_HOOKS:-}" == "1" ]]; then exit 0 fi if printf '%s' "$MSG" | grep -qiE \ - 'jessica-mood|jessica_mood|SOUL\.md|SOUL_SESSION|AGENTS\.local|docs/operator|docs/plans|localdocs/|co-authored-by:[[:space:]]*cursor'; then + 'jessica-mood|jessica_mood|SOUL\.md|SOUL_SESSION|AGENTS\.local|docs/operator/|docs/plans/|localdocs/|co-authored-by:[[:space:]]*cursor'; then echo "commit-msg: forbidden reference in message (persona / fork-private)" >&2 exit 1 fi From f58974b72e78d803cbd19461144d2cac3f3f5507 Mon Sep 17 00:00:00 2001 From: HeavyGee <133152184+heavygee@users.noreply.github.com> Date: Sat, 30 May 2026 17:03:56 +0100 Subject: [PATCH 0013/1600] chore(tooling): pre-push content scan product paths only Co-authored-by: Cursor --- scripts/tooling/git-hooks/pre-push | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/scripts/tooling/git-hooks/pre-push b/scripts/tooling/git-hooks/pre-push index 82e43dba4df..60d1175b0ff 100755 --- a/scripts/tooling/git-hooks/pre-push +++ b/scripts/tooling/git-hooks/pre-push @@ -37,16 +37,17 @@ while read -r local_ref local_sha remote_ref remote_sha; do if [[ "$remote_sha" =~ ^0+$ ]]; then continue fi - if git diff "$remote_sha" "$local_sha" -G'jessica-mood' --quiet -- . 2>/dev/null; then + PUSH_SCAN=(hub web cli shared) + if git diff "$remote_sha" "$local_sha" -G'jessica-mood' --quiet -- "${PUSH_SCAN[@]}" 2>/dev/null; then : else - echo "pre-push: outgoing diff contains jessica-mood (fork-only route)" >&2 - git diff "$remote_sha" "$local_sha" -G'jessica-mood' --name-only -- . >&2 || true + echo "pre-push: outgoing product diff contains jessica-mood (fork-only route)" >&2 + git diff "$remote_sha" "$local_sha" -G'jessica-mood' --name-only -- "${PUSH_SCAN[@]}" >&2 || true exit 1 fi for pat in 'SOUL_SESSION' 'SOUL\.md' '~/coding/SOUL'; do - if ! git diff "$remote_sha" "$local_sha" -G"$pat" --quiet -- . 2>/dev/null; then - echo "pre-push: outgoing diff matches forbidden pattern: $pat" >&2 + if ! git diff "$remote_sha" "$local_sha" -G"$pat" --quiet -- "${PUSH_SCAN[@]}" 2>/dev/null; then + echo "pre-push: outgoing product diff matches forbidden pattern: $pat" >&2 exit 1 fi done From 6be22d743c8910cf8e0b71e48c1dc86b7664e6a9 Mon Sep 17 00:00:00 2001 From: HeavyGee <133152184+heavygee@users.noreply.github.com> Date: Sat, 30 May 2026 19:09:28 +0100 Subject: [PATCH 0014/1600] chore(tooling): block operator tailnet URLs in git hooks and gh bodies Add check-operator-leaks.sh and gh-public-body-check.sh. Wire into pre-commit, pre-push, and commit-msg via install-git-hooks.sh. Co-authored-by: Cursor --- docs/tooling/commit-hooks.md | 17 +++- docs/tooling/new-feature-intake.md | 3 +- scripts/tooling/check-operator-leaks.sh | 130 ++++++++++++++++++++++++ scripts/tooling/gh-public-body-check.sh | 23 +++++ scripts/tooling/git-hooks/commit-msg | 6 ++ scripts/tooling/git-hooks/pre-commit | 7 ++ scripts/tooling/git-hooks/pre-push | 5 + scripts/tooling/install-git-hooks.sh | 4 +- 8 files changed, 190 insertions(+), 5 deletions(-) create mode 100755 scripts/tooling/check-operator-leaks.sh create mode 100755 scripts/tooling/gh-public-body-check.sh diff --git a/docs/tooling/commit-hooks.md b/docs/tooling/commit-hooks.md index 56470ed527c..c82cff6bade 100644 --- a/docs/tooling/commit-hooks.md +++ b/docs/tooling/commit-hooks.md @@ -14,9 +14,9 @@ Fork branches on `origin` must not carry **operator canon**, **plans**, **locald | Layer | Blocks | |-------|--------| -| **pre-commit** | Staging `docs/operator/`, `docs/plans/`, `localdocs/`, `xr-poc`, `.cursor/rules/operator*`, env files, `jessica-mood` paths/content, `SOUL_*` / `SOUL.md`, secrets | -| **pre-push** | Any **outgoing** commit range that touches those paths or adds `jessica-mood` / SOUL content | -| **commit-msg** | Same tokens in message body | +| **pre-commit** | Staging `docs/operator/`, `docs/plans/`, `localdocs/`, `xr-poc`, `.cursor/rules/operator*`, env files, `jessica-mood` paths/content, `SOUL_*` / `SOUL.md`, secrets, **operator tailnet hostnames** (`*.tail9944ee.ts.net`) | +| **pre-push** | Any **outgoing** commit range that touches those paths or adds `jessica-mood` / SOUL / tailnet URL content | +| **commit-msg** | Same tokens in message body + tailnet URLs | **Allowed in product code:** ElevenLabs voice name `Jessica` in `web/src/lib/voices.ts` (upstream). **Not allowed:** `hub/.../jessica-mood`, interior-note persona wiring, `docs/operator/*`. @@ -29,6 +29,17 @@ Fork branches on `origin` must not carry **operator canon**, **plans**, **locald **Note:** `docs/operator/` already in historical `main` — hooks stop **new** leaks. To strip from remote history use a separate git history rewrite (not automated here). +## Public GitHub text (issues / PRs) + +Git hooks do **not** run on `gh issue create`. Before filing upstream issues or PRs: + +```bash +scripts/tooling/gh-public-body-check.sh /tmp/issue-body.md +gh issue create --body-file /tmp/issue-body.md ... +``` + +Blocks operator MagicDNS hostnames (e.g. `hapi.tail9944ee.ts.net`). Use generic wording: "operator tailnet hub". + ## Upstream PR branches Product PRs to `tiann/hapi` must not include fork paths regardless — `git diff --name-only upstream/main...HEAD` should never list `docs/operator/` or `docs/plans/`. diff --git a/docs/tooling/new-feature-intake.md b/docs/tooling/new-feature-intake.md index c2cfe088411..bd480942f17 100644 --- a/docs/tooling/new-feature-intake.md +++ b/docs/tooling/new-feature-intake.md @@ -159,8 +159,9 @@ Ask explicitly: **soup** or **clean instance**? - Add branch to `~/.config/hapi/driver-manifest.yaml` - `hapi-driver-rebuild --build-web --verify` - `hapi-use-driver` when ready (**restarts hub + runner on :3006; kills live sessions**) +- **Do not** run `hapi-watch-activate-driver` from this orchestrator/agent turn — it counts this session as WORKING until the turn ends ([watch-activate-driver.md](./watch-activate-driver.md)). Operator runs watch from an external shell, or `HAPI_STACK_SWITCH_YES=1 hapi-use-driver` when health shows WORKING=0. -Operator URL: existing tailnet hub (e.g. `https://hapi.tail9944ee.ts.net`) after swing. +Operator URL: existing tailnet hub (hostname in `~/.hapi/hub.env` / operator docs only — never in upstream issues) after swing. #### Clean (upstream/main only) diff --git a/scripts/tooling/check-operator-leaks.sh b/scripts/tooling/check-operator-leaks.sh new file mode 100755 index 00000000000..55b95bea1d0 --- /dev/null +++ b/scripts/tooling/check-operator-leaks.sh @@ -0,0 +1,130 @@ +#!/usr/bin/env bash +# Scan text for operator-private infrastructure that must not appear in +# upstream PRs, public issues, or commits pushed to tiann/hapi. +# +# Usage: +# check-operator-leaks.sh --stdin # read stdin +# check-operator-leaks.sh --file PATH [..] # read files +# check-operator-leaks.sh --git-staged # staged diff (product paths) +# check-operator-leaks.sh --git-range A B # outgoing commit range +# +# Exit 0 if clean, 1 if leaks found. +# Override: HAPI_ALLOW_OPERATOR_LEAK=1 +set -euo pipefail + +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)" +cd "$ROOT" + +if [[ "${HAPI_ALLOW_OPERATOR_LEAK:-}" == "1" ]]; then + exit 0 +fi + +# Operator tailnet MagicDNS (and similar). Extend via HAPI_OPERATOR_LEAK_PATTERNS_FILE. +LEAK_PATTERNS=( + 'tail9944ee\.ts\.net' + 'hapi\.tail9944ee' +) + +if [[ -n "${HAPI_OPERATOR_LEAK_PATTERNS_FILE:-}" && -f "${HAPI_OPERATOR_LEAK_PATTERNS_FILE}" ]]; then + while IFS= read -r line || [[ -n "$line" ]]; do + [[ -z "$line" || "$line" =~ ^# ]] && continue + LEAK_PATTERNS+=("$line") + done < "${HAPI_OPERATOR_LEAK_PATTERNS_FILE}" +fi + +PRODUCT_SCAN_PATHS=(hub web cli shared package.json) + +FAIL=0 + +report_leak() { + local context="$1" + local pattern="$2" + local sample="$3" + echo "operator-leak: $context matches /$pattern/: $sample" >&2 + FAIL=1 +} + +scan_text_blob() { + local context="$1" + local blob="$2" + local pat sample + for pat in "${LEAK_PATTERNS[@]}"; do + if printf '%s' "$blob" | grep -qiE "$pat"; then + sample="$(printf '%s' "$blob" | grep -oiE ".{0,40}${pat}.{0,40}" | head -1 | tr '\n' ' ')" + report_leak "$context" "$pat" "$sample" + fi + done +} + +scan_file() { + local path="$1" + [[ -f "$path" ]] || return 0 + scan_text_blob "file:$path" "$(cat "$path")" +} + +scan_git_staged() { + local diff + diff="$(git diff --cached -- "${PRODUCT_SCAN_PATHS[@]}" 2>/dev/null || true)" + [[ -z "$diff" ]] && return 0 + scan_text_blob 'git-staged' "$diff" + local pat + for pat in "${LEAK_PATTERNS[@]}"; do + if ! git diff --cached -G"$pat" --quiet -- "${PRODUCT_SCAN_PATHS[@]}" 2>/dev/null; then + git diff --cached -G"$pat" --name-only -- "${PRODUCT_SCAN_PATHS[@]}" 2>/dev/null | sed 's/^/ /' >&2 || true + fi + done +} + +scan_git_range() { + local from="$1" + local to="$2" + local diff + diff="$(git diff "$from" "$to" -- "${PRODUCT_SCAN_PATHS[@]}" 2>/dev/null || true)" + [[ -z "$diff" ]] && return 0 + scan_text_blob "git-range:$from..$to" "$diff" +} + +usage() { + sed -n '2,12p' "$0" + exit 2 +} + +if [[ $# -eq 0 ]]; then + usage +fi + +case "$1" in + --stdin) + scan_text_blob 'stdin' "$(cat)" + ;; + --file) + shift + [[ $# -ge 1 ]] || usage + for f in "$@"; do + scan_file "$f" + done + ;; + --git-staged) + scan_git_staged + ;; + --git-range) + [[ $# -eq 3 ]] || usage + scan_git_range "$2" "$3" + ;; + -h|--help) + usage + ;; + *) + usage + ;; +esac + +if [[ "$FAIL" -ne 0 ]]; then + echo "" >&2 + echo "Operator-private URLs/hostnames must not appear in public upstream artifacts." >&2 + echo "Use generic wording (e.g. \"operator tailnet hub\") in issues/PRs." >&2 + echo "Emergency override: HAPI_ALLOW_OPERATOR_LEAK=1" >&2 + exit 1 +fi + +exit 0 diff --git a/scripts/tooling/gh-public-body-check.sh b/scripts/tooling/gh-public-body-check.sh new file mode 100755 index 00000000000..4ac39e77f49 --- /dev/null +++ b/scripts/tooling/gh-public-body-check.sh @@ -0,0 +1,23 @@ +#!/usr/bin/env bash +# Run before: gh issue create/edit, gh pr create/edit (public repos). +# gh-public-body-check.sh /tmp/issue-body.md +# gh issue create ... --body-file <(gh-public-body-check.sh --filter body.md) +# +# Modes: +# gh-public-body-check.sh PATH [..] check file(s), exit 1 on leak +# gh-public-body-check.sh --filter PATH print PATH to stdout if clean (for --body-file) +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +CHECK="$SCRIPT_DIR/check-operator-leaks.sh" +chmod +x "$CHECK" 2>/dev/null || true + +if [[ "${1:-}" == "--filter" ]]; then + [[ $# -eq 2 ]] || { echo "Usage: $0 --filter PATH" >&2; exit 2; } + "$CHECK" --file "$2" + cat "$2" + exit 0 +fi + +[[ $# -ge 1 ]] || { echo "Usage: $0 PATH [..] | $0 --filter PATH" >&2; exit 2; } +exec "$CHECK" --file "$@" diff --git a/scripts/tooling/git-hooks/commit-msg b/scripts/tooling/git-hooks/commit-msg index a5aecaeb9d0..5373a65024f 100755 --- a/scripts/tooling/git-hooks/commit-msg +++ b/scripts/tooling/git-hooks/commit-msg @@ -2,6 +2,8 @@ set -euo pipefail MSG_FILE="${1:?}" +ROOT="$(git rev-parse --show-toplevel)" +LEAK_CHECK="$ROOT/scripts/tooling/check-operator-leaks.sh" # Cursor may append Co-authored-by trailers; do not treat those as operator leaks. MSG="$(grep -viE '^[[:space:]]*co-authored-by:' "$MSG_FILE" || true)" @@ -15,4 +17,8 @@ if printf '%s' "$MSG" | grep -qiE \ exit 1 fi +if [[ -x "$LEAK_CHECK" ]]; then + printf '%s' "$MSG" | "$LEAK_CHECK" --stdin || exit 1 +fi + exit 0 diff --git a/scripts/tooling/git-hooks/pre-commit b/scripts/tooling/git-hooks/pre-commit index a3de1571108..9677160bf5e 100755 --- a/scripts/tooling/git-hooks/pre-commit +++ b/scripts/tooling/git-hooks/pre-commit @@ -5,6 +5,7 @@ set -euo pipefail ROOT="$(git rev-parse --show-toplevel)" cd "$ROOT" +LEAK_CHECK="$ROOT/scripts/tooling/check-operator-leaks.sh" if [[ "${HAPI_SKIP_COMMIT_HOOKS:-}" == "1" ]]; then exit 0 @@ -113,6 +114,12 @@ for pattern in "${SECRET_PATTERNS[@]}"; do git diff --cached -G"$pattern" --name-only -- "${SCAN_PATHS[@]}" 2>/dev/null | sed 's/^/ /' >&2 || true done +if [[ -x "$LEAK_CHECK" ]]; then + if ! "$LEAK_CHECK" --git-staged; then + FAIL=1 + fi +fi + if [[ "$FAIL" -ne 0 ]]; then echo "" >&2 echo "Fork-private material must not land in git (harvest risk on push)." >&2 diff --git a/scripts/tooling/git-hooks/pre-push b/scripts/tooling/git-hooks/pre-push index 60d1175b0ff..006964e3306 100755 --- a/scripts/tooling/git-hooks/pre-push +++ b/scripts/tooling/git-hooks/pre-push @@ -8,6 +8,7 @@ fi ROOT="$(git rev-parse --show-toplevel)" cd "$ROOT" +LEAK_CHECK="$ROOT/scripts/tooling/check-operator-leaks.sh" FORBIDDEN_PATH_RE='^(docs/operator/|docs/plans/|localdocs/|web/public/xr-poc/|\.cursor/rules/operator|AGENTS\.local\.md)' @@ -51,6 +52,10 @@ while read -r local_ref local_sha remote_ref remote_sha; do exit 1 fi done + + if [[ -x "$LEAK_CHECK" ]]; then + "$LEAK_CHECK" --git-range "$remote_sha" "$local_sha" || exit 1 + fi done exit 0 diff --git a/scripts/tooling/install-git-hooks.sh b/scripts/tooling/install-git-hooks.sh index e5e35bdde21..3ee89d129b5 100755 --- a/scripts/tooling/install-git-hooks.sh +++ b/scripts/tooling/install-git-hooks.sh @@ -6,7 +6,9 @@ ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)" HOOKS="$ROOT/scripts/tooling/git-hooks" chmod +x "$HOOKS"/pre-commit "$HOOKS"/commit-msg "$HOOKS"/pre-push 2>/dev/null || true +chmod +x "$ROOT/scripts/tooling/check-operator-leaks.sh" "$ROOT/scripts/tooling/gh-public-body-check.sh" 2>/dev/null || true git -C "$ROOT" config core.hooksPath "$HOOKS" echo "Installed git hooksPath → $HOOKS" -echo "Hooks: pre-commit, commit-msg, pre-push (harvest-resistant fork gates)" +echo "Hooks: pre-commit, commit-msg, pre-push (fork-private paths, secrets, operator tailnet URLs)" echo "Bypass: HAPI_SKIP_COMMIT_HOOKS=1 git commit ..." +echo "Public gh bodies: scripts/tooling/gh-public-body-check.sh /tmp/issue.md before gh issue create" From 1d65586e55aaad42391d5eb08f8f11da223b393e Mon Sep 17 00:00:00 2001 From: HeavyGee <133152184+heavygee@users.noreply.github.com> Date: Sun, 31 May 2026 16:47:22 +0100 Subject: [PATCH 0015/1600] docs: point session monitor to ~/coding/server-setup/scripts/hapi/ hapi-sessions-health.sh + the C plotter were untracked in scripts/ and kept getting swept into stashes by routine `git stash -u` on HAPI worktrees, vanishing from disk while the watch process kept running stale in-memory code. Moved to server-setup/scripts/hapi/ (committed there); hapi-watch-activate-driver.sh now defaults to the new path. Co-authored-by: Cursor --- docs/tooling/README.md | 4 ++-- scripts/tooling/hapi-watch-activate-driver.sh | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/tooling/README.md b/docs/tooling/README.md index 2cad20298c3..456d0ac7fed 100644 --- a/docs/tooling/README.md +++ b/docs/tooling/README.md @@ -14,7 +14,7 @@ Feature agents should **read the relevant doc below at session start**; meta bot |-------|------|----------------| | **HAPI API / hub** | `~/coding/hapi` (upstream/main mirror), `~/coding/hapi-driver` (daily soup), `~/coding/hapi-*` PR worktrees, `hapi-active` symlink | Driver manifest rebuild, worktree hygiene, live swing | | **Adjacent HAPI repos** | e.g. `hapi-garden`, `hapi-session-attention`, any `~/coding/hapi-*` worktree with an open branch | Same rules; confirm which tree is active before debugging "prod" | -| **Machine helpers** | `~/.local/bin/hapi-use-worktree`, `hapi-use-main`, `gh` wrapper, `pr-post-push-check*`, `hapi-sessions-health.sh` | Installed, executable, match docs | +| **Machine helpers** | `~/.local/bin/hapi-use-worktree`, `hapi-use-main`, `gh` wrapper, `pr-post-push-check*`, `~/.local/bin/hapi-sessions-health.sh` → `server-setup/scripts/hapi/` | Installed, executable, match docs | | **Agent hooks** | `~/.claude/settings.json`, `~/.cursor/hooks.json`, `~/coding/AGENTS.local.md` | Policy text matches docs; note IDE vs CLI hook parity gaps | | **Upstream boundary** | `tiann/hapi` PRs | No operator-local files, no AI attribution (see repo `AGENTS.local.md`) | @@ -91,7 +91,7 @@ hapi-sessions-health.sh jellybot # filter by path/flavor/id Meta bot triages `STUCK?`, `ZOMBIE`, and missing runner PIDs; escalates or kills stale processes per operator policy. -Script: `scripts/hapi-sessions-health.sh` (repo root). +Script: `~/coding/server-setup/scripts/hapi/hapi-sessions-health.sh` (operator tooling; symlinked as `~/.local/bin/hapi-sessions-health.sh`). Used to live in this repo at `scripts/hapi-sessions-health.sh`; relocated 2026-05-31 so `git stash -u` operations on HAPI worktrees don't sweep it away. ### 4. Verification commands (HAPI default) diff --git a/scripts/tooling/hapi-watch-activate-driver.sh b/scripts/tooling/hapi-watch-activate-driver.sh index 11742938f17..14cf189642d 100755 --- a/scripts/tooling/hapi-watch-activate-driver.sh +++ b/scripts/tooling/hapi-watch-activate-driver.sh @@ -9,7 +9,7 @@ set -euo pipefail PRIMARY="${HAPI_PRIMARY:-$HOME/coding/hapi}" -HEALTH="${HAPI_SESSIONS_HEALTH:-$PRIMARY/scripts/hapi-sessions-health.sh}" +HEALTH="${HAPI_SESSIONS_HEALTH:-$HOME/coding/server-setup/scripts/hapi/hapi-sessions-health.sh}" INTERVAL="${HAPI_WATCH_INTERVAL:-30}" ONCE=0 From a5c0fd0fb42f98043e5de37a3507e5e0cb8fc756 Mon Sep 17 00:00:00 2001 From: HeavyGee <133152184+heavygee@users.noreply.github.com> Date: Sun, 31 May 2026 19:46:47 +0100 Subject: [PATCH 0016/1600] chore(tooling): watch-activate-driver ouroboros guard + exclude flags - Refuse to start under Cursor/agent parent without --exclude-sid / --exclude-agent-session / --force-unsafe (walks PPID chain). - Filter WORKING by sid or Cursor agentSessionId (prefix match both directions); auto-drop watch-runner procs. - Print who we are still waiting on; --once exits 2 when still blocked. Without this, running the watch inside the HAPI Cursor turn that launched it deadlocks: the agent child keeps the session WORKING, so filtered count never reaches 0. Recovery used to require killing the agent + watch child by hand. The prior upgrade lived only as an uncommitted working-tree mod and was repeatedly swept into git stashes by peer agents running rebuild / sync flows. Committing so it stops disappearing. Also restore docs/tooling/watch-activate-driver.md (previously also uncommitted) and link from README + driver-soup. Co-authored-by: Cursor --- docs/tooling/README.md | 1 + docs/tooling/driver-soup.md | 2 + docs/tooling/watch-activate-driver.md | 64 ++++++++++ scripts/tooling/hapi-watch-activate-driver.sh | 114 ++++++++++++++++-- 4 files changed, 168 insertions(+), 13 deletions(-) create mode 100644 docs/tooling/watch-activate-driver.md diff --git a/docs/tooling/README.md b/docs/tooling/README.md index 456d0ac7fed..ad8d77e2d98 100644 --- a/docs/tooling/README.md +++ b/docs/tooling/README.md @@ -31,6 +31,7 @@ Feature agents should **read the relevant doc below at session start**; meta bot | [commit-hooks.md](./commit-hooks.md) | `install-git-hooks.sh` — secrets + operator path gates | | [worktree-testing.md](./worktree-testing.md) | `hapi-active` symlink, `hapi-use-worktree`, service swing | | [driver-soup.md](./driver-soup.md) | Daily driver manifest, merge-train PR worktrees, garden vs soup | +| [watch-activate-driver.md](./watch-activate-driver.md) | `hapi-watch-activate-driver` - external-only watch; ouroboros guard + excludes | | [pr-review-loop.md](./pr-review-loop.md) | Pre-PR verification + cold review; pre-push open-PR gate; post-push PR comment poll | | [cold-pr-review-rubric.md](./cold-pr-review-rubric.md) | Open-PR cold review bar (match upstream HAPI Bot severity) | diff --git a/docs/tooling/driver-soup.md b/docs/tooling/driver-soup.md index 651e6998527..ee905fedefe 100644 --- a/docs/tooling/driver-soup.md +++ b/docs/tooling/driver-soup.md @@ -32,6 +32,8 @@ hapi-use-driver # same, daily driver path After `hapi-driver-rebuild`, run `hapi-use-driver` when ready — rebuild alone does not restart services. +**Do not** run `hapi-watch-activate-driver` from inside a Cursor agent turn without `--exclude-agent-session` (ouroboros: this session stays WORKING until the agent exits). See [watch-activate-driver.md](./watch-activate-driver.md). + ## Daily driver (soup) **Manifest:** `~/.config/hapi/driver-manifest.yaml` (operator-local; example in repo) diff --git a/docs/tooling/watch-activate-driver.md b/docs/tooling/watch-activate-driver.md new file mode 100644 index 00000000000..ba9ccf94c5b --- /dev/null +++ b/docs/tooling/watch-activate-driver.md @@ -0,0 +1,64 @@ +# hapi-watch-activate-driver + +Polls `hapi-sessions-health.sh --json` until **no blocking WORKING sessions**, then runs `hapi-use-driver` (restarts hub + runner on `:3006`). + +## Ouroboros rule (mandatory) + +**Do not run this script from inside a HAPI Cursor agent turn** unless you pass an exclude for **this** session. + +While the watch loop runs, the agent child process is still alive -> hub marks this session **WORKING** -> filtered count never reaches 0 -> deadlock. Operator recovery from a real deadlock: kill agent (exit 143) + watch child. + +| Run from | OK? | +|----------|-----| +| External terminal / systemd / cron | Yes | +| Cursor agent turn with **no** exclude | **No** (logic deadlock - script refuses to start) | +| Agent turn with `--exclude-agent-session ` | Yes (will kill this agent on activate) | + +## Usage + +```bash +# Preferred: external shell after you confirm health +hapi-sessions-health.sh --json | jq '[.sessions[]|select(.status=="WORKING")]' +HAPI_STACK_SWITCH_YES=1 hapi-use-driver + +# Watch loop (external shell, foreground) +hapi-watch-activate-driver --interval 20 + +# One-shot check +hapi-watch-activate-driver --once + +# Exclude this hub session or Cursor agent id (prefix ok for sid) +hapi-watch-activate-driver \ + --exclude-sid 17f4a977 \ + --exclude-agent-session 6904d349-f576-489f-bcd7-972f37f3942a + +# Background from inside agent turn, survives agent exit +setsid nohup env HAPI_STACK_SWITCH_YES=1 \ + hapi-watch-activate-driver \ + --exclude-agent-session "$CURSOR_AGENT_SESSION_ID" \ + --interval 15 \ + >> /tmp/hapi-watch-activate-driver.log 2>&1 < /dev/null & +disown +``` + +## Flags + +| Flag / env | Effect | +|-----|--------| +| `--once` | Single check; exit 0 if activated, 2 if still blocked | +| `--interval ` / `HAPI_WATCH_INTERVAL` | Poll interval (default 30) | +| `--exclude-sid ` / `HAPI_WATCH_EXCLUDE_SID` | Drop hub session by sid/sid8 (prefix match both ways) | +| `--exclude-agent-session ` / `HAPI_WATCH_EXCLUDE_AGENT_SESSION` | Drop session by Cursor `agentSessionId` (prefix match) | +| `--force-unsafe` | Bypass agent-parent guard (still deadlocks if **only** this session is WORKING) | + +Auto-exclude: any WORKING row whose `procs[]` includes `hapi-watch-activate-driver` (the watch child itself). + +## Guard + +If launched under a Cursor/agent parent without any exclude or `--force-unsafe`, the script **refuses to start** (exit 3) with instructions. Walks up `PPID` chain looking for `/agent`, `cursor-agent`, or `cursor agent` in cmdline. + +## Agent discipline + +Orchestrator / meta bot must **not** background `hapi-watch-activate-driver` inside the same turn that is waiting for activation **without** the exclude. Tell the operator to run it externally, or run `hapi-use-driver` manually when `WORKING==0`. + +When the watch fires `hapi-use-driver`, it restarts hub + runner -> **kills all live agent sessions including the one that launched the watch**. That's expected; the operator asked for the restart. Background-with-setsid lets the watch survive the agent exit so it can still trigger. diff --git a/scripts/tooling/hapi-watch-activate-driver.sh b/scripts/tooling/hapi-watch-activate-driver.sh index 14cf189642d..229f567ce2e 100755 --- a/scripts/tooling/hapi-watch-activate-driver.sh +++ b/scripts/tooling/hapi-watch-activate-driver.sh @@ -1,24 +1,35 @@ #!/usr/bin/env bash -# Poll session health until no WORKING agents, then swing hapi-active to daily driver. +# Poll session health until no WORKING agents (excluding this turn), then hapi-use-driver. +# +# NEVER run from inside a HAPI Cursor agent turn without --exclude-agent-session: +# this session stays WORKING until the agent exits, so WORKING never hits 0 (ouroboros). # # Usage: -# hapi-watch-activate-driver # foreground, 30s interval -# hapi-watch-activate-driver --once # exit 0 if activated, 2 if still working -# hapi-watch-activate-driver --interval 15 +# hapi-watch-activate-driver # external shell only +# hapi-watch-activate-driver --exclude-sid 17f4a977 +# hapi-watch-activate-driver --exclude-agent-session 6904d349-f576-489f-bcd7-972f37f3942a +# HAPI_WATCH_EXCLUDE_AGENT_SESSION= hapi-watch-activate-driver +# hapi-watch-activate-driver --once --interval 20 # set -euo pipefail PRIMARY="${HAPI_PRIMARY:-$HOME/coding/hapi}" HEALTH="${HAPI_SESSIONS_HEALTH:-$HOME/coding/server-setup/scripts/hapi/hapi-sessions-health.sh}" INTERVAL="${HAPI_WATCH_INTERVAL:-30}" +EXCLUDE_SID="${HAPI_WATCH_EXCLUDE_SID:-}" +EXCLUDE_AGENT="${HAPI_WATCH_EXCLUDE_AGENT_SESSION:-}" ONCE=0 +FORCE_UNSAFE=0 while [[ $# -gt 0 ]]; do case "$1" in --once) ONCE=1; shift ;; --interval) INTERVAL="$2"; shift 2 ;; + --exclude-sid) EXCLUDE_SID="$2"; shift 2 ;; + --exclude-agent-session) EXCLUDE_AGENT="$2"; shift 2 ;; + --force-unsafe) FORCE_UNSAFE=1; shift ;; -h|--help) - sed -n '2,10p' "$0" + sed -n '2,16p' "$0" exit 0 ;; *) echo "Unknown option: $1" >&2; exit 2 ;; @@ -30,32 +41,109 @@ if [[ ! -x "$HEALTH" ]]; then exit 1 fi -count_working() { +launched_under_agent() { + local pid="${PPID:-}" + local depth=0 + while [[ -n "$pid" && "$pid" -gt 1 && "$depth" -lt 12 ]]; do + local cmd + cmd="$(tr '\0' ' ' < "/proc/$pid/cmdline" 2>/dev/null || true)" + if [[ "$cmd" == *"/agent "* ]] || [[ "$cmd" == *"cursor-agent"* ]] || [[ "$cmd" == *"cursor agent"* ]]; then + return 0 + fi + pid="$(ps -o ppid= -p "$pid" 2>/dev/null | tr -d ' ' || true)" + depth=$((depth + 1)) + done + return 1 +} + +# Returns JSON array of WORKING sessions after excludes (auto-drops watch-runner procs). +filter_working_json() { + "$HEALTH" --json 2>/dev/null | jq \ + --arg sid "$EXCLUDE_SID" \ + --arg agent "$EXCLUDE_AGENT" \ + ' + [.sessions[]? + | select(.status == "WORKING") + | select( + ($sid | length) == 0 + or ( + .sid != $sid and .sid8 != $sid + and ((.sid | startswith($sid)) | not) + and (($sid | startswith(.sid8)) | not) + ) + ) + | select( + ($agent | length) == 0 + or ( + (.agentSessionId // "") as $aid + | $aid != $agent + and ($aid | startswith($agent) | not) + and ($agent | startswith($aid) | not) + ) + ) + | select( + any(.procs[]?; .cmd | test("hapi-watch-activate-driver")) | not + ) + ] + ' +} + +count_working_filtered() { + filter_working_json | jq 'length' +} + +list_working_filtered() { + filter_working_json | jq -r '.[] | "\(.sid8) \(.project // "?") agent=\(.agentSessionId // "-") \(.note // "")"' +} + +count_working_raw() { "$HEALTH" --json 2>/dev/null | jq '[.sessions[]? | select(.status == "WORKING")] | length' } -working="$(count_working)" -echo "hapi-watch-activate-driver: WORKING=${working} (poll every ${INTERVAL}s)" +if launched_under_agent && [[ -z "$EXCLUDE_SID" && -z "$EXCLUDE_AGENT" && "$FORCE_UNSAFE" -ne 1 ]]; then + echo "ERROR: hapi-watch-activate-driver started under a Cursor/agent parent (ouroboros risk)." >&2 + echo " This HAPI session stays WORKING until the agent turn ends, so WORKING never reaches 0." >&2 + echo " Fix: run from an external terminal, or pass:" >&2 + echo " --exclude-agent-session " >&2 + echo " --exclude-sid " >&2 + echo " Emergency only: --force-unsafe (will still deadlock if only this session is WORKING)" >&2 + exit 3 +fi + +raw="$(count_working_raw)" +working="$(count_working_filtered)" + +echo "hapi-watch-activate-driver: WORKING=${working} (raw=${raw}, poll every ${INTERVAL}s)" +if [[ -n "$EXCLUDE_SID" ]]; then + echo " exclude sid: $EXCLUDE_SID" +fi +if [[ -n "$EXCLUDE_AGENT" ]]; then + echo " exclude agent session: $EXCLUDE_AGENT" +fi +if [[ "$working" -gt 0 ]]; then + echo " waiting on:" + list_working_filtered | sed 's/^/ /' +fi if [[ "$working" -eq 0 ]]; then - echo "No WORKING sessions — activating daily driver..." + echo "No blocking WORKING sessions — activating daily driver..." export HAPI_STACK_SWITCH_YES=1 exec hapi-use-driver fi if [[ "$ONCE" -eq 1 ]]; then - echo "Still ${working} WORKING session(s) — not activating" >&2 + echo "Still ${working} WORKING session(s) after excludes — not activating" >&2 exit 2 fi while true; do sleep "$INTERVAL" - working="$(count_working)" + working="$(count_working_filtered)" ts="$(date '+%Y-%m-%d %H:%M:%S')" if [[ "$working" -eq 0 ]]; then - echo "$ts WORKING=0 — activating daily driver..." + echo "$ts WORKING=0 (after excludes) — activating daily driver..." export HAPI_STACK_SWITCH_YES=1 exec hapi-use-driver fi - echo "$ts WORKING=${working} — waiting" + echo "$ts WORKING=${working} (raw=$(count_working_raw)) — waiting" done From 0c2bdfbbac6dbbe6b873787551d0c530a25df2d7 Mon Sep 17 00:00:00 2001 From: HeavyGee <133152184+heavygee@users.noreply.github.com> Date: Sun, 31 May 2026 22:53:44 +0100 Subject: [PATCH 0017/1600] chore(tooling): stash advisory + always-applied rule (multi-agent repo) Git has no pre-stash hook, so we cannot intercept the command itself without replacing the git binary. Three layers that do work in this environment: 1. .cursor/rules/no-stash-others-work.mdc (alwaysApply) - In-band warning at decision time. Cursor agents see it every turn. - Rule: never stash files you did not edit this turn; commit your own work in-turn; if you cannot, move to a worktree, do not stash. 2. scripts/tooling/check-stash-advisory.sh - Surfaces stashes >30m old or with WIP-style labels. - Non-blocking advisory (stderr, exit 0). - Smoke test on current tree: 16/16 stashes flagged - exactly the picture that motivated this change. 3. pre-push hook + install-git-hooks.sh - pre-push runs the advisory after path/content gates. - install-git-hooks.sh runs it once on install. Policy doc: docs/tooling/git-stash-policy.md with incident log and canonical alternatives (WIP commit on branch, worktree, labelled stash of last resort). Bypass: HAPI_SKIP_STASH_ADVISORY=1 / HAPI_SKIP_COMMIT_HOOKS=1 Co-authored-by: Cursor --- docs/tooling/README.md | 1 + docs/tooling/git-stash-policy.md | 66 +++++++++++++++ scripts/tooling/check-stash-advisory.sh | 104 ++++++++++++++++++++++++ scripts/tooling/git-hooks/pre-push | 5 ++ scripts/tooling/install-git-hooks.sh | 4 + 5 files changed, 180 insertions(+) create mode 100644 docs/tooling/git-stash-policy.md create mode 100755 scripts/tooling/check-stash-advisory.sh diff --git a/docs/tooling/README.md b/docs/tooling/README.md index ad8d77e2d98..b57032617ab 100644 --- a/docs/tooling/README.md +++ b/docs/tooling/README.md @@ -29,6 +29,7 @@ Feature agents should **read the relevant doc below at session start**; meta bot | [new-feature-intake.md](./new-feature-intake.md) | **Operator requests new behavior** — discovery, playback, soup vs clean demo, gates before dogfood, PR after approval | | `scripts/tooling/hapi-sync-fork-main.sh` | Keep `~/coding/hapi` `main` = upstream + fork docs | | [commit-hooks.md](./commit-hooks.md) | `install-git-hooks.sh` — secrets + operator path gates | +| [git-stash-policy.md](./git-stash-policy.md) | **Multi-agent repo** - do not stash other agents' work; commit instead | | [worktree-testing.md](./worktree-testing.md) | `hapi-active` symlink, `hapi-use-worktree`, service swing | | [driver-soup.md](./driver-soup.md) | Daily driver manifest, merge-train PR worktrees, garden vs soup | | [watch-activate-driver.md](./watch-activate-driver.md) | `hapi-watch-activate-driver` - external-only watch; ouroboros guard + excludes | diff --git a/docs/tooling/git-stash-policy.md b/docs/tooling/git-stash-policy.md new file mode 100644 index 00000000000..1defa71530b --- /dev/null +++ b/docs/tooling/git-stash-policy.md @@ -0,0 +1,66 @@ +# Git stash policy (multi-agent repo) + +`~/coding/hapi` and its worktrees are touched by **multiple peer Cursor agents concurrently**. `git stash` in this environment is a silent way to lose other agents' uncommitted work. + +This doc is the long-form of `.cursor/rules/no-stash-others-work.mdc`. + +## Real incidents this is designed to prevent + +| Date | Loss | +|------|------| +| 2026-05-31 | Watch-script ouroboros guard edit reverted twice between turns (peer ran rebuild -> auto-stashed -> never restored). Eventually committed as `a5c0fd0`. | +| 2026-05-30 | Stash list grew to 16 entries, several with names like `wip-unrelated-before-driver-rebuild` that no agent could claim ownership of. | +| various | `hapi-sync-fork-main` and `hapi-driver-rebuild` warnings prompt agents to `git stash` to proceed - they do, then forget. | + +## The rule, in three lines + +1. **Never stash dirty files that you did not edit this turn.** +2. **Commit your own work in-turn** (WIP commit on a branch is fine - stash is not). +3. **If something is in the way and is not yours, use a worktree** (`hapi-worktree-create`) instead of stashing the primary tree. + +## Why agents stash in this repo (and what to do instead) + +### "The rebuild script asked me to stash" + +`hapi-driver-rebuild` will warn about a dirty driver tree, and `hapi-sync-fork-main` checks primary main. They do **not** auto-stash. If you hit the warning: + +``` +WARNING: /home/heavygee/coding/hapi has local changes - rebuild will reset... +``` + +The correct moves, in order of preference: + +1. `git status` -> recognise the files. If yours, commit them. If not yours, **stop**. +2. If you cannot commit (mid-rebase, conflicting unstaged changes), move your work to a worktree: + ```bash + hapi-worktree-create + git -C ~/coding/hapi checkout -- . + ``` +3. Only stash as a last resort, with a labelled message: + ```bash + git stash push -u -m "wip " + ``` + ...and `git stash apply` (or `pop`) before you end your turn. + +### "I need to rebase a branch but the worktree is dirty" + +Rebase in the **branch's own worktree**, not in the primary `~/coding/hapi`. Every active upstream-PR branch already has a worktree under `~/coding/hapi-` (`git worktree list` to confirm). + +### "I am refactoring and need to checkpoint" + +Make a WIP commit on a branch. Stashes are not checkpoints - they have no parent commit and no name resolution. A WIP commit can be force-pushed, amended, dropped via `git reset` - all auditable. A stash cannot. + +## Backstops + +| Layer | What it does | +|-------|--------------| +| Cursor rule `.cursor/rules/no-stash-others-work.mdc` | Always-applied; agents see this in their context every turn | +| `scripts/tooling/check-stash-advisory.sh` | Lists stashes older than 30 min with WIP-style labels | +| Pre-push hook | Calls the advisory script before each push; warns (does not block) | +| `install-git-hooks.sh` | Runs the advisory once at install time | + +## Why not just intercept `git stash`? + +Git has no `pre-stash` hook. The command path uses plumbing that bypasses commit hooks. The only way to intercept the call itself would be to replace the `git` binary in PATH with a wrapper - too invasive for a workspace-scoped policy. + +So the strategy is: **in-band warning before the call** (Cursor rule) + **detection after** (advisory hook) + **commit canonical** (this doc). diff --git a/scripts/tooling/check-stash-advisory.sh b/scripts/tooling/check-stash-advisory.sh new file mode 100755 index 00000000000..6e29a58a330 --- /dev/null +++ b/scripts/tooling/check-stash-advisory.sh @@ -0,0 +1,104 @@ +#!/usr/bin/env bash +# Surface stashes that look like other-agents' lost work. +# Non-blocking - prints to stderr, always exits 0. +# +# Triggers warning for stash entries that match ANY of: +# - Older than HAPI_STASH_ADVISORY_AGE_MIN (default 30) minutes +# - Message contains: wip, pre-, auto, untitled, dirty +# - Message is empty / generic "WIP on " +# +# Usage: +# scripts/tooling/check-stash-advisory.sh # foreground audit +# scripts/tooling/check-stash-advisory.sh --quiet # only print if findings +# scripts/tooling/check-stash-advisory.sh --count # print count, exit 0 +# +# Bypass: HAPI_SKIP_STASH_ADVISORY=1 +set -euo pipefail + +if [[ "${HAPI_SKIP_STASH_ADVISORY:-}" == "1" ]]; then + exit 0 +fi + +QUIET=0 +COUNT_ONLY=0 +while [[ $# -gt 0 ]]; do + case "$1" in + --quiet) QUIET=1; shift ;; + --count) COUNT_ONLY=1; shift ;; + -h|--help) + sed -n '2,16p' "$0" + exit 0 + ;; + *) echo "Unknown option: $1" >&2; exit 2 ;; + esac +done + +ROOT="$(git rev-parse --show-toplevel 2>/dev/null || true)" +[[ -z "$ROOT" ]] && exit 0 + +AGE_MIN="${HAPI_STASH_ADVISORY_AGE_MIN:-30}" +NOW_EPOCH="$(date +%s)" + +mapfile -t STASHES < <(git -C "$ROOT" stash list --format='%gd|%ct|%gs' 2>/dev/null || true) +total="${#STASHES[@]}" + +if [[ "$COUNT_ONLY" -eq 1 ]]; then + echo "$total" + exit 0 +fi + +if [[ "$total" -eq 0 ]]; then + [[ "$QUIET" -eq 1 ]] || echo "stash-advisory: 0 stashes (clean)" + exit 0 +fi + +SUSPECT_RE='(wip|pre-|auto|untitled|dirty|pre_|preupstream|prerebuild|prerebase|cleanup|backup)' +findings=() + +for line in "${STASHES[@]}"; do + [[ -z "$line" ]] && continue + ref="${line%%|*}" + rest="${line#*|}" + ts="${rest%%|*}" + msg="${rest#*|}" + age_min=$(( (NOW_EPOCH - ts) / 60 )) + age_label="" + if [[ "$age_min" -ge $((60 * 24)) ]]; then + age_label="$((age_min / 60 / 24))d" + elif [[ "$age_min" -ge 60 ]]; then + age_label="$((age_min / 60))h" + else + age_label="${age_min}m" + fi + + suspect=0 + if [[ "$age_min" -ge "$AGE_MIN" ]]; then + suspect=1 + fi + if echo "$msg" | grep -qiE "$SUSPECT_RE"; then + suspect=1 + fi + if [[ "$msg" =~ ^WIP\ on\ ]]; then + suspect=1 + fi + if [[ "$suspect" -eq 1 ]]; then + findings+=(" ${ref} age=${age_label} ${msg}") + fi +done + +if [[ "${#findings[@]}" -eq 0 ]]; then + [[ "$QUIET" -eq 1 ]] || echo "stash-advisory: ${total} stash(es), none suspicious" + exit 0 +fi + +{ + echo "stash-advisory: ${#findings[@]} of ${total} stash(es) look like lost agent work:" + printf '%s\n' "${findings[@]}" + echo "" + echo " Older than ${AGE_MIN}m or WIP-style label. If you do not own one, do NOT drop it." + echo " Policy: docs/tooling/git-stash-policy.md" + echo " Cursor rule: .cursor/rules/no-stash-others-work.mdc" + echo " Bypass once: HAPI_SKIP_STASH_ADVISORY=1" +} >&2 + +exit 0 diff --git a/scripts/tooling/git-hooks/pre-push b/scripts/tooling/git-hooks/pre-push index 006964e3306..e51328f86c0 100755 --- a/scripts/tooling/git-hooks/pre-push +++ b/scripts/tooling/git-hooks/pre-push @@ -58,4 +58,9 @@ while read -r local_ref local_sha remote_ref remote_sha; do fi done +ADVISORY="$ROOT/scripts/tooling/check-stash-advisory.sh" +if [[ -x "$ADVISORY" ]]; then + "$ADVISORY" --quiet || true +fi + exit 0 diff --git a/scripts/tooling/install-git-hooks.sh b/scripts/tooling/install-git-hooks.sh index 3ee89d129b5..5b97504ff34 100755 --- a/scripts/tooling/install-git-hooks.sh +++ b/scripts/tooling/install-git-hooks.sh @@ -7,8 +7,12 @@ HOOKS="$ROOT/scripts/tooling/git-hooks" chmod +x "$HOOKS"/pre-commit "$HOOKS"/commit-msg "$HOOKS"/pre-push 2>/dev/null || true chmod +x "$ROOT/scripts/tooling/check-operator-leaks.sh" "$ROOT/scripts/tooling/gh-public-body-check.sh" 2>/dev/null || true +chmod +x "$ROOT/scripts/tooling/check-stash-advisory.sh" 2>/dev/null || true git -C "$ROOT" config core.hooksPath "$HOOKS" echo "Installed git hooksPath → $HOOKS" echo "Hooks: pre-commit, commit-msg, pre-push (fork-private paths, secrets, operator tailnet URLs)" echo "Bypass: HAPI_SKIP_COMMIT_HOOKS=1 git commit ..." echo "Public gh bodies: scripts/tooling/gh-public-body-check.sh /tmp/issue.md before gh issue create" +echo "" +echo "Stash policy (multi-agent repo): docs/tooling/git-stash-policy.md" +"$ROOT/scripts/tooling/check-stash-advisory.sh" --quiet || true From 41604b80455ffe1d51847420afc43a8933a61d46 Mon Sep 17 00:00:00 2001 From: HeavyGee <133152184+heavygee@users.noreply.github.com> Date: Sun, 31 May 2026 22:54:24 +0100 Subject: [PATCH 0018/1600] chore(tooling): track .cursor/rules/ + add no-stash-others-work rule Global ~/.config/git/ignore ignores .cursor/, but rules under .cursor/rules/ are meant to be shared across the repo (Cursor agents on any machine should see them). Override the global ignore for that subdir only - per-user .cursor/ state still ignored. The no-stash-others-work rule was supposed to land in the previous commit (0c2bdfb) but was silently dropped by the global ignore. That commit's pre-push hook + advisory script work without it, but the rule is the layer that fires BEFORE the agent stashes - the most important of the three. alwaysApply: true so Cursor agents see it every turn in this workspace. Co-authored-by: Cursor --- .cursor/rules/no-stash-others-work.mdc | 49 ++++++++++++++++++++++++++ .gitignore | 8 +++++ 2 files changed, 57 insertions(+) create mode 100644 .cursor/rules/no-stash-others-work.mdc diff --git a/.cursor/rules/no-stash-others-work.mdc b/.cursor/rules/no-stash-others-work.mdc new file mode 100644 index 00000000000..30bda7676e4 --- /dev/null +++ b/.cursor/rules/no-stash-others-work.mdc @@ -0,0 +1,49 @@ +--- +description: Multi-agent repo - never `git stash` work that is not yours; commit instead +alwaysApply: true +--- + +# Do not `git stash` in this repo without thinking + +This is a **multi-agent monorepo**. Peer agents frequently leave **uncommitted changes** in `~/coding/hapi` (and worktrees) between turns. A blind `git stash` here will sweep their work into the stash list where it is easy to lose - and where rebuild / sync flows will silently leave it. + +This is not theoretical - it has happened multiple times. The watch-script ouroboros guard was wiped twice this way before being committed (`a5c0fd0`). + +## The rule + +Before you run `git stash` (or any command that invokes it - `git rebase`, `git pull --rebase`, `hapi-sync-fork-main`, `hapi-driver-rebuild`): + +1. Run `git status` and `git diff --stat`. +2. If the dirty files are **yours** (you edited them this turn) - **commit them**, do not stash. +3. If the dirty files are **not yours** - stop. Either: + - Search the agent transcripts for who owns them (`grep -l ~/.cursor/projects/*/agent-transcripts/*.jsonl`), or + - Move to a fresh **worktree** for your work (`hapi-worktree-create` / `git worktree add`), or + - Ask the operator before you touch them. + +## Why not stash? + +- `git stash` makes work invisible. The next agent does not see it in `git status`. +- Stashes accumulate without owners (this repo had **16 lingering stashes** at last audit). +- Rebuild / sync scripts that auto-stash before resetting can lose work permanently if the stash is later dropped. +- Stashed WIP that lived only as a working-tree mod is **not version controlled** - it can be lost in a `reset --hard` or `clean -fd` you do not own. + +## Canonical alternatives + +| You want to ... | Do this | +|------------------|--------| +| Pause your own work | `git commit -am 'wip: '` on a feature branch (your worktree or a temp branch) | +| Work without disturbing dirty primary | `hapi-worktree-create ` then work there | +| Rebuild driver soup with dirty primary | `git stash push -m 'wip ' -u` **then immediately** `git stash apply` after rebuild, OR commit to WIP branch first | +| Rebase a branch with dirty other work | Switch to a worktree of that branch and rebase there | + +If you absolutely must stash, **label your stash** with your agent id / Cursor session id so the next agent can find it: + +```bash +git stash push -m "wip " -u +``` + +## Backstop + +`pre-push` hook + `scripts/tooling/check-stash-advisory.sh` surface stashes older than 30 minutes with WIP-style messages. If you see one and do not own it, do not drop it - leave it for the operator. + +See [docs/tooling/git-stash-policy.md](../../docs/tooling/git-stash-policy.md). diff --git a/.gitignore b/.gitignore index dc3c3d28a15..c30933a310a 100644 --- a/.gitignore +++ b/.gitignore @@ -42,3 +42,11 @@ execplan/ # Generated npm bundle output (local) cli/npm/main/ .ace-tool/ + +# Cursor: ignored by global ~/.config/git/ignore but we want shared rules tracked +# in this repo. Negate the global rule for .cursor/rules/ only (per-user state +# under .cursor/ stays ignored). +!.cursor/ +.cursor/* +!.cursor/rules/ +!.cursor/rules/** From 7a2b19cc12c919599899bb90ab61820dcf947746 Mon Sep 17 00:00:00 2001 From: HeavyGee <133152184+heavygee@users.noreply.github.com> Date: Sun, 31 May 2026 23:34:23 +0100 Subject: [PATCH 0019/1600] docs(operator): runner-systemd resilience stack + 22:40 BST retrospective - runner-systemd operator guide: rewritten for the combined fix/runner-handoff-systemd-resilience branch (replaces the two prior soup layers). New install block covers the resilience drop-in (Restart=always + StartLimit*), watchdog timer, NOPASSWD sudoers, and persisted settings.json fallback. Verification matrix expanded with start-lock race + Restart=always scenarios. - runner-self-restart-bluedeploy-fix plan: Definition of done ticked + 22:40 BST incident retrospective with the three structural gaps Fix A+B did not close (env leak, race, on-failure-vs-clean-exit) and the matching resilience-stack fixes. Includes friction-mode post-mortem (Restart=always alone was the cheap proof) and known pre-existing test failure (integration test vs new waitForRunnerHandoff timing). Live verification at 23:30 BST: drop-in active, watchdog firing, settings.json fallback in place, MainPID 32517 unchanged across deploy. Co-authored-by: Cursor --- docs/operator/runner-systemd.md | 140 +++++++++ ...5-31-runner-self-restart-bluedeploy-fix.md | 294 ++++++++++++++++++ 2 files changed, 434 insertions(+) create mode 100644 docs/operator/runner-systemd.md create mode 100644 docs/plans/2026-05-31-runner-self-restart-bluedeploy-fix.md diff --git a/docs/operator/runner-systemd.md b/docs/operator/runner-systemd.md new file mode 100644 index 00000000000..8b7d9aa96ed --- /dev/null +++ b/docs/operator/runner-systemd.md @@ -0,0 +1,140 @@ +# Runner systemd integration (operator-local) + +Daily-driver HAPI here runs as **two systemd services**: + +``` +hapi-hub.service → bun run hub from $ACTIVE/hub +hapi-runner.service → bun run cli from $ACTIVE/cli (start-sync) +``` + +Both follow `~/coding/hapi-active` (symlinked by `hapi-use-driver` / `hapi-use-worktree`). + +The runner's CLI ships an mtime-driven self-restart - when source files change underneath it, the runner spawns a replacement and `process.exit(0)`'s. Under systemd, **`Restart=on-failure` does not restart on clean exits**, so the runner stays dead until manual intervention. Soup rebuilds (`hapi-driver-rebuild`) trip this every time they touch the active tree. + +The 2026-05-31 22:40 BST incident proved the env-var-only mitigation was insufficient: a terminal-launched `hapi runner start-sync` from `/home/heavygee/coding/hapi` (without the env var exported) saw mtime drift, killed the live systemd-owned runner via HTTP /stop, then took its own SIGTERM ~200ms later and exited cleanly - leaving the machine offline for 3 minutes until manual `systemctl start`. The runner-systemd-resilience layer (see below) makes this class of incident structurally impossible: even if every CLI-level check regresses, `Restart=always` + the watchdog timer bring the machine back within seconds. + +## Local mitigation - resilience stack + +Single combined soup branch (`fix/runner-handoff-systemd-resilience`) carries: + +1. The two prior soup commits (env-var opt-out + argv preservation/handoff verification). +2. A **persisted** `runnerDisableVersionHandoff:true` in `~/.hapi/settings.json` so the opt-out survives env-var leaks. +3. A **start-lock** in `cli/src/runner/run.ts` (`~/.hapi/runner.start.lock`) that serialises concurrent `runner start-sync` invocations. +4. Systemd templates under `cli/systemd/*` (drop-in with `Restart=always` + watchdog timer). + +### Drop-in (replaces the older `10-disable-version-handoff.conf`) + +```ini +# /etc/systemd/system/hapi-runner.service.d/10-resilience.conf +[Unit] +StartLimitBurst=10 +StartLimitIntervalSec=300 + +[Service] +Environment=HAPI_DISABLE_VERSION_HANDOFF=1 +ExecStartPre=/bin/bash -lc '/home/heavygee/.bun/bin/bun run --cwd /home/heavygee/coding/hapi-active/cli /home/heavygee/coding/hapi-active/cli/src/index.ts runner stop || true' +Restart=always +RestartSec=5 +RestartPreventExitStatus=2 +``` + +`Restart=always` is the big lever - any future clean exit gets restarted by systemd within 5s, regardless of cause. `StartLimitBurst=10 / StartLimitIntervalSec=300` prevents a genuinely broken runner from pinning CPU (note: must be in `[Unit]`, systemd ignores them in `[Service]`). `RestartPreventExitStatus=2` skips restart on fatal config errors. + +The env var + `ExecStartPre` are unchanged from the prior drop-in. The env var is honored by `cli/src/runner/run.ts` heartbeat and `cli/src/runner/controlClient.ts:isRunnerRunningCurrentlyInstalledHappyVersion`; both ALSO check the persisted setting now so the env var leaking out of any future spawn is no longer fatal. + +### Watchdog timer (belt-and-braces) + +Polls `/cli/machines/` every 60s. If the hub reports the machine inactive or `runnerState.status != "running"` AND the runner's local heartbeat is older than 30s, restarts the unit. + +### Setup (one-time) + +```bash +# 1. Install resilience drop-in (replaces 10-disable-version-handoff.conf) +sudo cp ~/coding/hapi-active/cli/systemd/hapi-runner-resilience.conf \ + /etc/systemd/system/hapi-runner.service.d/10-resilience.conf +sudo rm -f /etc/systemd/system/hapi-runner.service.d/10-disable-version-handoff.conf + +# 2. Install watchdog units +sudo cp ~/coding/hapi-active/cli/systemd/hapi-runner-watchdog.service \ + /etc/systemd/system/hapi-runner-watchdog.service +sudo cp ~/coding/hapi-active/cli/systemd/hapi-runner-watchdog.timer \ + /etc/systemd/system/hapi-runner-watchdog.timer + +# 3. Allow the unit user to restart the runner without password. +sudo tee /etc/sudoers.d/hapi-watchdog <<'EOF' +heavygee ALL=(root) NOPASSWD: /bin/systemctl restart hapi-runner.service +EOF +sudo chmod 0440 /etc/sudoers.d/hapi-watchdog +sudo visudo -c -f /etc/sudoers.d/hapi-watchdog # must report "parsed OK" + +# 4. Persist the env var as a settings.json key (env-leak hardening). +jq '.runnerDisableVersionHandoff = true' ~/.hapi/settings.json > /tmp/s.json && \ + mv /tmp/s.json ~/.hapi/settings.json + +# 5. Activate +sudo systemctl daemon-reload +sudo systemctl restart hapi-runner.service # picks up new drop-in +sudo systemctl enable --now hapi-runner-watchdog.timer +``` + +### Verify + +```bash +systemctl show hapi-runner.service -p Restart -p RestartUSec \ + -p StartLimitBurst -p StartLimitIntervalUSec -p RestartPreventExitStatus -p Environment +# Expect: +# Restart=always +# RestartUSec=5s +# StartLimitBurst=10 +# StartLimitIntervalUSec=5min +# RestartPreventExitStatus=2 +# Environment=... HAPI_DISABLE_VERSION_HANDOFF=1 ... + +systemctl list-timers hapi-runner-watchdog.timer +# Expect: NEXT fires in <60s window, LAST recent + +journalctl -u hapi-runner-watchdog.service --since '5 min ago' --no-pager | tail -3 +# Expect: "[watchdog] machine active + runner=running on http://...; no action" +``` + +## Required soup layer + +Single layer in `~/.config/hapi/driver-manifest.yaml`: + +| Branch | Effect | +|--------|--------| +| `fix/runner-handoff-systemd-resilience` | Cherry-picks the two prior soup commits; adds persisted opt-out, start-lock, systemd templates | + +The older `feat/runner-skip-version-handoff-flag` + `fix/runner-handoff-preserves-argv` are now superseded by this branch (they're cherry-picked into it). Drop them from the manifest when adopting this layer. + +## Verification matrix + +| Scenario | Expected | +|----------|----------| +| `hapi-driver-rebuild` + soup changes mtime on `cli/package.json` | Runner log shows no `outdated` / `self-restart` entries; `systemctl is-active hapi-runner.service` stays `active`; `MainPID` does not change across heartbeat ticks. With `DEBUG=1` the runner also logs `Version-handoff disabled (env=true, setting=true); skipping mtime/version drift self-restart` | +| Terminal `hapi runner start-sync` without env var exported | persisted `runnerDisableVersionHandoff:true` honored; "Runner already running with matching version" -> exit 0; live runner unaffected | +| Two concurrent `hapi runner start-sync` invocations (race) | Second invocation waits up to 6s on `runner.start.lock`; by then first has taken over; second sees "Runner already running with matching version" -> exit 0; no kill of either | +| Manual `systemctl kill -s KILL hapi-runner.service` | systemd restarts within 5s (`Restart=always`); watchdog timer's next tick sees healthy state | +| Hub reports machine offline + heartbeat > 30s | Watchdog runs `sudo systemctl restart hapi-runner.service`; journal entry in `hapi-runner-watchdog.service` | +| `hapi-use-driver` swing | systemd restarts the unit; `ExecStartPre` stops any orphaned runner; new runner reads the same drop-in env; machine reappears within ~5s | + +### Live verification 2026-05-31 (post-incident) + +After installing the resilience drop-in via `daemon-reload` (no service restart): + +- `systemctl show hapi-runner.service -p Restart` -> `Restart=always` (was `on-failure`). +- `StartLimitIntervalUSec=5min`, `StartLimitBurst=10` (was 10s default + 5). +- `RestartUSec=5s`, `RestartPreventExitStatus=2`, `HAPI_DISABLE_VERSION_HANDOFF=1` all present in unit env. +- Watchdog timer enabled, fires every 60s, dry-run + live-run both correctly identify the live runner as healthy: `machine f9bb3c9e-... active + runner=running on http://127.0.0.1:3006; no action`. +- `~/.hapi/settings.json` has `runnerDisableVersionHandoff: true` so the next start-sync from any terminal context inherits the opt-out without env var. + +Earlier (Fix A + B only) verification, retained for context: +- `runner.state.json` shows `startedWithArgv: ["runner","start-sync","--workspace-root","/home/heavygee/coding","--workspace-root","/home/heavygee/coding/hapi-driver"]` - Fix B persistence confirmed. +- Touched `~/coding/hapi-driver/cli/package.json` (mtime drift simulation). 70 seconds later (one heartbeat past): `MainPID` unchanged at 33332, `ActiveState=active`. Pre-fix behavior would have been a new pid or `inactive`. Fix A flag confirmed in production. + +## Related + +- `docs/plans/2026-05-31-runner-self-restart-bluedeploy-fix.md` - problem statement, evidence, design, 22:40 incident retrospective +- `cli/systemd/README.md` (in soup) - template inventory + install instructions +- `docs/tooling/driver-soup.md` - manifest workflow +- `scripts/tooling/hapi-runner-from-active.sh` - the `ExecStart` helper diff --git a/docs/plans/2026-05-31-runner-self-restart-bluedeploy-fix.md b/docs/plans/2026-05-31-runner-self-restart-bluedeploy-fix.md new file mode 100644 index 00000000000..1a60052206d --- /dev/null +++ b/docs/plans/2026-05-31-runner-self-restart-bluedeploy-fix.md @@ -0,0 +1,294 @@ +# Plan: Stop runner self-restart from breaking soup rebuilds + +**Status:** DONE (2026-05-31 23:30 BST) - Fix A + B + resilience stack live in soup; live drop-in verified, watchdog timer enabled +**Owner:** any soup-aware HAPI agent +**Scope:** local fork (`heavygee/hapi`) soup stack only - **not** an upstream PR +**Related:** `~/coding/hapi-driver`, `hapi-driver-rebuild`, `hapi-use-driver`, daily soup workflow + +--- + +## Problem + +Running `hapi-driver-rebuild` while a `hapi runner start-sync` is live can knock the runner offline silently. Hub keeps serving the web UI; sessions queue messages; **nothing executes** because there is no machine. + +### Evidence (2026-05-31 incident) + +From `~/.hapi/logs/2026-05-31-15-36-51-pid-46645-runner.log` and the test-runner logs that landed alongside it: + +1. Live runner PID 46645 was happy, sessions registered. +2. `hapi-driver-rebuild --verify` ran integration tests that briefly registered as the same machine with version `0.0.0-integration-test-should-be-auto-cleaned-up-28876`. Source-file mtimes changed. +3. Live runner's heartbeat saw `installedCliMtimeMs !== startedWithCliMtimeMs` and logged: + ``` + Runner is outdated, triggering self-restart with latest version, clearing heartbeat interval + ``` +4. It called `spawnHappyCLI(['runner', 'start'], { detached: true, stdio: 'ignore' })` and exited. +5. The new `hapi runner start` invocation **stopped the old runner** and exited - it does **not** spawn a `start-sync`. No replacement runner came up. +6. `GET /api/machines` returned `[]` for ~8 minutes. All sessions appeared frozen. + +### Code today + +Trigger: `cli/src/runner/run.ts` lines 798-826 (heartbeat interval `restartOnStaleVersionAndHeartbeat`). + +The misleading comment at lines 810-813 says: +> "It will first check if runner is running... Next it will start a new runner with the latest version with runner-sync :D" + +That is **not what `hapi runner start` does**. `runner start` is a "kill old, then exit" command (see lines 100-111). There is no auto-spawn of `start-sync`, and the original `--workspace-root` argv is lost regardless. + +### Why this is a local problem, not upstream + +| Audience | Hits this bug? | +|----------|----------------| +| End users on published npm `@twsxtd/hapi` | No. CLI binary mtime never changes mid-session unless they `npm install`. | +| Driver/soup operator (heavygee) running `bun cli/src/index.ts ... start-sync` | **Yes, every rebuild.** Source mtimes change constantly. | + +So the auto-update mtime watcher is **dead code for everyone except us**. We are the only consumer of the broken self-restart path. **Carry fixes locally; do not PR upstream unless asked.** + +### Shape of the problem + +It is a **malformed blue-green deployment**: the runner detects "green build exists on disk", kills itself (blue), then assumes a new blue magically appears. No green ever started. Blue dies. Machine offline. + +--- + +## Fix A - DO - Disable auto-update during rebuild + +**Goal:** rebuild and `hapi-use-driver` without the live runner committing suicide. + +**Approach:** runner respects `HAPI_DISABLE_VERSION_HANDOFF=1`. Operator scripts set it before touching source, unset after activation. + +### Code changes + +**File:** `cli/src/runner/run.ts`, around line 798 (inside `restartOnStaleVersionAndHeartbeat`). + +```ts +if (process.env.HAPI_DISABLE_VERSION_HANDOFF === '1') { + if (process.env.DEBUG) { + logger.debug('[RUNNER RUN] HAPI_DISABLE_VERSION_HANDOFF set, skipping mtime/version drift check'); + } +} else { + // existing block: getInstalledCliMtimeMs() comparison + spawnHappyCLI(['runner', 'start']) +} +``` + +Also: same flag should be checked in `cli/src/runner/run.ts` line ~103 (`isRunnerRunningCurrentlyInstalledHappyVersion`) so a fresh `start-sync` invocation against a flagged-live runner does not still kill it. Keep the version-mismatch log at debug level. + +**File:** new soup branch `feat/runner-skip-version-handoff-flag`. Single small commit, easy rebase. + +**Operator script changes (in `~/coding/hapi-driver` and `~/.local/bin`):** + +| Script | Change | +|--------|--------| +| `hapi-driver-rebuild` | `export HAPI_DISABLE_VERSION_HANDOFF=1` at start; `unset` at end (trap on exit). | +| `hapi-use-driver` | Same: set before symlink swap, unset after. | +| `hapi runner start-sync` invocation in tmux startup | Pass through `HAPI_DISABLE_VERSION_HANDOFF` from environment if exported by operator session. | + +These scripts live outside `~/coding/hapi`, so document the contract here and link from `docs/operator-local-tooling.md`. + +### Test plan + +1. Start `hapi runner start-sync ...` with `HAPI_DISABLE_VERSION_HANDOFF=1`. +2. Touch `cli/src/index.ts` to bump mtime. +3. Wait > `HAPI_RUNNER_HEARTBEAT_INTERVAL` (60s default). +4. Confirm runner log says "skipping mtime/version drift check" and process is still alive. +5. Confirm `GET /api/machines` still lists the machine. +6. Run without the flag: confirm old behaviour (runner exits, log shows "Runner is outdated"). + +### Branch name + +`feat/runner-skip-version-handoff-flag` (top of soup stack; merge order doesn't matter). + +--- + +## Fix B - DO - Make self-restart actually work + +**Goal:** if the auto-update path ever fires (operator forgot the flag, or some other trigger), the new runner should **come up with the same workspace roots and same args** the operator started with. + +### Code changes + +**File:** `cli/src/runner/run.ts` lines 814-826. + +Today: +```ts +spawnHappyCLI(['runner', 'start'], { detached: true, stdio: 'ignore' }); +``` + +Replacement: +```ts +const state = await readRunnerState(); +const argv = state?.startedWithArgv ?? ['runner', 'start-sync']; + +const child = spawnHappyCLI(argv, { detached: true, stdio: 'ignore' }); + +const handoffOk = await waitForMachineRegistered(machineId, { + hub: process.env.HAPI_API_URL, + timeoutMs: 30_000, +}); + +if (!handoffOk) { + logger.debug('[RUNNER RUN] Replacement runner did not register within 30s; staying alive'); + // do NOT exit - we are still the only runner the hub knows about + return; +} + +// child is up and registered, safe to exit +process.exit(0); +``` + +This requires: + +1. **Persist original argv** in `runner.state.json`. Add `startedWithArgv: string[]` to `RunnerLocallyPersistedState` (already saving `startedWithCliVersion`, etc.). Capture `process.argv.slice(2)` at runner start. +2. **`waitForMachineRegistered` helper.** Poll hub `/api/machines`, return true when the new runner has registered with the same `machineId` AND a different PID than ours. +3. **Don't `process.exit(0)` blindly** if handoff failed. Today the parent exits after a 10s sleep regardless. + +### Test plan + +1. With `HAPI_DISABLE_VERSION_HANDOFF` unset, start `hapi runner start-sync --workspace-root A --workspace-root B`. +2. Touch source mtime. +3. Wait for heartbeat trigger. +4. Confirm new runner process exists with **same `--workspace-root` args** (check `ps`, `runner.state.json`). +5. Confirm hub `GET /api/machines` shows machine continuously, no gap. +6. Negative test: `chmod -x` the hapi binary or otherwise force handoff failure - confirm parent runner does **not** exit. + +### Branch name + +`fix/runner-handoff-preserves-argv` (depends on Fix A only by file proximity, no logical dependency). + +--- + +## Fix C - WON'T DO - True blue-green + +**Status: explicitly out of scope. Do not implement.** + +Real blue-green would mean: + +- Hub gains two-runner-version routing (active green vs draining blue). +- Protocol negotiates which runner version handles each new spawn. +- Drain logic waits for blue's sessions to finish before retiring blue. +- Schema additions in `shared/protocol`. + +**Why not:** + +1. Touches hub, CLI, and protocol - hundreds of lines, schema migration, tests across the whole stack. +2. Soup stack would need to rebase a giant invasive branch every week against upstream churn. +3. Fixes A + B already solve the actual operator pain (rebuild without breaking; if you forget the flag, handoff still works). +4. Upstream maintainer hasn't asked for this. Carrying it speculatively is a tax on every soup rebuild for years. + +Revisit only if upstream signals interest in multi-version runner support, or if hosted/multi-tenant HAPI deployments become a use case for us. + +--- + +## Verification matrix + +| Scenario | A applied | B applied | Expected | +|----------|-----------|-----------|----------| +| Operator runs `hapi-driver-rebuild` with flag set by script | yes | yes | Runner stays up; sessions stay live; rebuild completes; flag unset; verify all green | +| Operator forgets flag; manual source edit | no | yes | Auto-update fires; new runner registers with same args; brief overlap acceptable | +| Operator forgets flag; B not yet applied | no | no | **Today's incident reproduces.** | +| Replacement runner crashes | no | yes | Old runner stays alive (no `process.exit(0)`); operator notified via existing logs/health | +| Two simultaneous rebuilds | yes | yes | Idempotent; flag on both, no double-handoff | + +--- + +## Friction mode notes + +**Steelman of "don't fix, just remember the flag":** the bug only fires for one user (us), the workaround is `unset HAPI_DISABLE_VERSION_HANDOFF` in `.bashrc`-equivalent, no code touched, no rebase tax. Counter: we already lost ~15 minutes today; the cost of forgetting compounds. + +**Risk of Fix B:** introduces a new wait loop in the runner's heartbeat path. If `waitForMachineRegistered` itself misbehaves, we've made the auto-update path slower without fixing it. Mitigation: hard 30s timeout, default-safe (don't exit on failure). + +**Risk of carrying these in soup forever:** if upstream refactors `runner/run.ts`, both branches need touch. Acceptable - they're small. + +**Cheapest falsification of this whole plan:** disable the auto-update watcher entirely by setting `HAPI_RUNNER_HEARTBEAT_INTERVAL=0` (if the runner respects `0` as "never"; if not, that's a one-line patch). If that solves operator pain without Fix A or Fix B, the watcher is just unused dead weight for our use case. Worth a 30-second probe before implementing A+B. + +--- + +## Definition of done + +- [x] Fix A merged into soup stack as `feat/runner-skip-version-handoff-flag` (2026-05-31 16:24) +- [x] Fix B merged into soup stack as `fix/runner-handoff-preserves-argv` (2026-05-31 16:26) +- [x] 2026-05-31 22:40 incident retrospective + resilience stack: `fix/runner-handoff-systemd-resilience` (see below) +- [x] Manifest updated to single combined branch +- [x] `docs/operator/runner-systemd.md` rewritten with resilience-stack install + verify +- [x] Live drop-in installed: `Restart=always`, `RestartSec=5s`, `StartLimitBurst=10`, `StartLimitIntervalSec=5min`, `HAPI_DISABLE_VERSION_HANDOFF=1` +- [x] Watchdog timer enabled, dry-run + first live fire correctly identified machine as healthy +- [x] `~/.hapi/settings.json` has `runnerDisableVersionHandoff:true` for env-leak safety +- [x] C section of this doc remains marked **WON'T DO** + +--- + +## 2026-05-31 22:40 BST incident retrospective + +### What we got wrong in the original Fix A + B design + +Fix A wired `HAPI_DISABLE_VERSION_HANDOFF=1` into both runtime paths (heartbeat + `isRunnerRunningCurrentlyInstalledHappyVersion`). Fix B preserved argv and added `waitForRunnerHandoff` so the old runner doesn't exit until the new one registers. Both correct, both deployed. Verification matrix from 17:00 BST signed off. + +At 22:40 BST the runner died anyway: + +``` +[22:40:47.254] Starting hapi CLI with args: ["bun","/$bunfs/root/hapi","runner","start-sync"] +[22:40:47.263] [RUNNER RUN] Environment + { "PWD": "/home/heavygee/coding/hapi", + "HAPI_API_URL": "http://127.0.0.1:3006", + "CLI_API_TOKEN_SET": false, + ... + // no HAPI_DISABLE_VERSION_HANDOFF in env dump + } +[22:40:47.265] [RUNNER CONTROL] Current CLI mtime: 1779549472629, Runner started with mtime: 1780242730153 +[22:40:47.265] [RUNNER RUN] Runner version mismatch detected, restarting runner with current CLI version +[22:40:47.265] Stopping runner with PID 24935 <-- killed the systemd-owned live runner +[22:40:47.456] [RUNNER RUN] Received SIGTERM <-- 200ms later took its own SIGTERM +[22:40:47.643] [RUNNER RUN] Process exiting with code: 0 +``` + +Machine offline for 3 minutes until manual `systemctl start hapi-runner.service`. + +### Three structural gaps Fix A+B did not close + +1. **Env var leak.** Fix A relied on every CLI invocation having `HAPI_DISABLE_VERSION_HANDOFF=1` in its environment. The systemd unit's drop-in set it correctly. But a TERMINAL-launched `bun /$bunfs/root/hapi runner start-sync` (operator script, single-binary, run from `/home/heavygee/coding/hapi`) inherited the operator shell's env - which never exported it. The flag worked exactly as designed; the contract that "everybody remembers to export it" is what failed. + +2. **Concurrent invocation race.** Even with proper flag propagation, two `start-sync` invocations within the same setup window could each see the other's runner as stale (or not stale) and race past each other into kill-old / start-new. The 22:40 log shows the replacement runner (PID 65341) receiving SIGTERM 200ms after starting, suggesting a parallel `runner stop` or systemd-level intervention. + +3. **`Restart=on-failure` doesn't recover from clean exits.** This is the proximate cause. The runner's `process.exit(0)` is by design - the auto-restart path was supposed to spawn a replacement first. But ANY path that exits 0 (forgotten flag, handoff failure, race-driven SIGTERM during cleanup) leaves systemd thinking "service exited successfully, nothing to do". The unit policy fundamentally cannot recover from this without `Restart=always`. + +### Resilience stack (this branch: `fix/runner-handoff-systemd-resilience`) + +| Gap | Fix | +|-----|-----| +| Env var leak | Persisted `settings.runnerDisableVersionHandoff:true` in `~/.hapi/settings.json` (`cli/src/persistence.ts` + both check sites). Once written, every CLI invocation from any context inherits the opt-out. Env var still wins when set. | +| Concurrent race | New `~/.hapi/runner.start.lock` held by `startRunner()` for the setup window only (kill-old + acquire-runtime-lock + write-state). Stale-cleaned after 15s. Second invocation waits ~6s, then sees the now-correct version and bows out cleanly. | +| `Restart=on-failure` | New drop-in `cli/systemd/hapi-runner-resilience.conf` upgrades to `Restart=always` + `RestartSec=5` + `StartLimitBurst=10` + `StartLimitIntervalSec=300` (5 min). `RestartPreventExitStatus=2` for fatal config errors. | +| All of the above regress | New `hapi-runner-watchdog.{service,timer,sh}`: probes `/cli/machines/` every 60s; if active=false or `runnerState.status != "running"` and heartbeat is older than 30s, restarts the unit via NOPASSWD sudo. | + +### Friction-mode falsification (post-mortem) + +The original plan's friction-mode note ("cheapest falsification: just set `Restart=always`") was correct. The single line `Restart=always` would have ended operator UI pain at 22:40 BST regardless of every other code path being broken - systemd would have restarted within 5s of the clean exit. Everything else in this branch (persisted setting, start-lock, watchdog) is defense-in-depth against the underlying CLI-level bugs; `Restart=always` is the cheap proof that the system is resilient. + +The persisted setting + start-lock + watchdog still earn their keep: they prevent the same bug from CAUSING a restart in the first place, which is healthier than letting it churn the service. But anyone reviewing this stack should understand the deployment is structurally safe even if every CLI-level fix regresses. + +### Verification (post-deploy, 23:30 BST) + +``` +$ systemctl show hapi-runner.service -p Restart -p RestartUSec \ + -p StartLimitBurst -p StartLimitIntervalUSec -p RestartPreventExitStatus -p Environment +Restart=always +RestartUSec=5s +StartLimitIntervalUSec=5min +StartLimitBurst=10 +RestartPreventExitStatus=2 +Environment=... HAPI_DISABLE_VERSION_HANDOFF=1 ... + +$ systemctl list-timers hapi-runner-watchdog.timer +NEXT LEFT LAST PASSED UNIT +Sun 2026-05-31 23:32:55 BST 51s left Sun 2026-05-31 23:31:55 BST 8s ago hapi-runner-watchdog.timer + +$ journalctl -u hapi-runner-watchdog.service --since '5 min ago' | tail -1 +... [watchdog] machine f9bb3c9e-... active + runner=running on http://127.0.0.1:3006; no action + +$ cat ~/.hapi/settings.json | jq '.runnerDisableVersionHandoff, .machineId' +true +"f9bb3c9e-43fd-41ca-9e4f-a0b0414b9026" +``` + +Live `hapi-runner.service` MainPID 32517 unchanged across the deploy - no service restart needed for the policy change (daemon-reload sufficed). + +### Known pre-existing test failure + +`cli/src/runner/runner.integration.test.ts > ... should detect version mismatch and kill old runner` fails on the cherry-picked branches (verified by reverting to upstream/main where it passes). Root cause: the new `waitForRunnerHandoff` blocking-poll pattern (up to 30s) + the test's 40s wait window can race - the heartbeat fires at T+30, handoff polling extends past T+40 when the test asserts. NOT introduced by this branch's new commits; documented here for future cleanup. Fix is likely a one-line bump of the test's wait window from `heartbeat + 10s` to `heartbeat + handoff_timeout + 10s`. From ee209ea6f304df27eeaf781b1e5920471095adda Mon Sep 17 00:00:00 2001 From: HeavyGee <133152184+heavygee@users.noreply.github.com> Date: Mon, 1 Jun 2026 07:39:51 +0100 Subject: [PATCH 0020/1600] chore(tooling): Phase 1 of hapi folder reorg - canonical worktrees layout New worktrees default to ~/coding/hapi/worktrees/ instead of polluting ~/coding/ with hapi-/ siblings. Existing 22 legacy worktrees stay where they are and drain naturally over Phase 2. Changes: - hapi-worktree-create: default path now ${HAPI_PRIMARY}/worktrees/${NAME}; legacy ~/coding/hapi-/ still available via --at top (deprecated, warns) - worktrees/.gitkeep: pre-create the canonical bucket - .gitignore: mask /active /driver /upstream /worktrees/* with negation for the .gitkeep so the bucket stays committed - .cursor/rules/worktree-layout.mdc: alwaysApply rule so agents pick the new convention automatically (matches the no-stash-others-work rule pattern) - scripts/tooling/check-worktree-layout.sh: audit script that flags worktrees outside the canonical layout (carrot+stick: hapi-worktree-create is the carrot, this audit is the stick since git does not allow aliasing built-in subcommands like 'worktree add') - scripts/tooling/git-hooks/pre-push: wire the audit as advisory (non-blocking), HAPI_SKIP_WORKTREE_AUDIT=1 to bypass - AGENTS canon: feature peer instructions point at the new canonical worktree location - plan doc: full reorg writeup, operator decisions captured, Phase 1 done, Phase 2 (drain) + Phase 3 (physical move with hub downtime) pending Co-authored-by: Cursor --- .cursor/rules/worktree-layout.mdc | 40 +++ .gitignore | 10 + docs/operator/AGENTS.md | 6 +- .../2026-06-01-hapi-folders-reorganization.md | 281 ++++++++++++++++++ scripts/tooling/check-worktree-layout.sh | 103 +++++++ scripts/tooling/git-hooks/pre-push | 5 + scripts/tooling/hapi-worktree-create.sh | 36 ++- worktrees/.gitkeep | 0 8 files changed, 476 insertions(+), 5 deletions(-) create mode 100644 .cursor/rules/worktree-layout.mdc create mode 100644 docs/plans/2026-06-01-hapi-folders-reorganization.md create mode 100755 scripts/tooling/check-worktree-layout.sh create mode 100644 worktrees/.gitkeep diff --git a/.cursor/rules/worktree-layout.mdc b/.cursor/rules/worktree-layout.mdc new file mode 100644 index 00000000000..22667525e03 --- /dev/null +++ b/.cursor/rules/worktree-layout.mdc @@ -0,0 +1,40 @@ +--- +description: New git worktrees on this repo must live under ~/coding/hapi/worktrees/ +alwaysApply: true +--- + +# Canonical worktree layout (2026-06-01 onward) + +This repo uses **one** canonical place for new git worktrees: **`~/coding/hapi/worktrees/`**. + +| Path | What it is | Created how | +|------|------------|-------------| +| `~/coding/hapi/` | Main mirror, branch=`main` | clone | +| `~/coding/hapi/driver` | Daily-driver soup worktree | one-shot, lives forever | +| `~/coding/hapi/upstream` | Clean `upstream/main` worktree | one-shot, lives forever | +| `~/coding/hapi/active` | Symlink at runtime - points at driver or upstream | runtime, not a worktree | +| `~/coding/hapi/worktrees/` | **All new feature/PR worktrees** | `hapi-worktree-create --branch ` | + +Pre-2026-06-01 worktrees still exist under `~/coding/hapi-/` and a sibling `~/coding/hapi-worktrees//`. Those are legacy and being drained, do not add to them. + +## The rule + +When you create a new worktree: + +1. **Default tool:** `hapi-worktree-create --branch ` - it places the worktree in `~/coding/hapi/worktrees/` automatically. +2. **Manual `git worktree add`:** the path argument must start with `~/coding/hapi/worktrees/` (or be one of the three reserved names `driver`, `upstream` - but those already exist). +3. **Never** create a worktree at `~/coding/hapi-/` or `~/coding/hapi-worktrees//` - those are legacy locations that the next agent will not find without `git worktree list`. +4. **Never** create a worktree from inside another worktree without an explicit path under `~/coding/hapi/worktrees/`. Nested or doubly-nested worktrees (e.g. `hapi-X/hapi-Y-worktrees/Z`) are the bug we are trying to stop. + +## Why + +- One predictable place per agent / per `ls` to find work in flight. +- `git worktree list` mirrors filesystem layout - no surprise paths. +- The mirror dir (`~/coding/hapi`) stays clean of sibling clutter; the gitignore at root masks `/worktrees/`, `/driver`, `/upstream`, `/active`. +- Cursor project ids are path-hashed - moving worktrees breaks agent resume continuity. The canonical layout puts new work in stable paths that will not move again. + +## Backstop + +`scripts/tooling/check-worktree-layout.sh` runs in the `pre-push` hook (advisory). It warns when worktrees live outside the canonical layout. Drift is expected during Phase 2 of the reorg; new drift after that is a bug. + +See [docs/plans/2026-06-01-hapi-folders-reorganization.md](../../docs/plans/2026-06-01-hapi-folders-reorganization.md) for the full reorganization plan and migration phases. diff --git a/.gitignore b/.gitignore index c30933a310a..4da83dd1fa8 100644 --- a/.gitignore +++ b/.gitignore @@ -43,6 +43,16 @@ execplan/ cli/npm/main/ .ace-tool/ +# Canonical worktree layout (2026-06-01 onward, Phase 1 / Option B). +# These subdirs are git worktrees of this same .git or operator-only shells. +# Tracked: this gitignore + worktrees/.gitkeep. Everything else under them = worktree contents. +# See docs/plans/2026-06-01-hapi-folders-reorganization.md. +/active +/driver +/upstream +/worktrees/* +!/worktrees/.gitkeep + # Cursor: ignored by global ~/.config/git/ignore but we want shared rules tracked # in this repo. Negate the global rule for .cursor/rules/ only (per-user state # under .cursor/ stays ignored). diff --git a/docs/operator/AGENTS.md b/docs/operator/AGENTS.md index 4b4d99b3a85..9f3777bd9af 100644 --- a/docs/operator/AGENTS.md +++ b/docs/operator/AGENTS.md @@ -308,9 +308,11 @@ When the operator asks for **new product behavior**, follow [`docs/tooling/new-f **Orchestrator** completes steps 1-3 (and usually 4-5), then spawns a **feature peer** with the mandatory handoff block in that doc (completed steps vs peer-owned steps). -**Feature peer** implements in `~/coding/hapi-` — not in `~/coding/hapi-driver` by hand. Pass §6 (tests, cold review, Playwright) **before** asking the operator to browser-test. Upstream PR only after operator dogfood approval (§8). +**Feature peer** implements in **`~/coding/hapi/worktrees/`** (created via `hapi-worktree-create --branch `) — not in `~/coding/hapi/driver` by hand. Pass §6 (tests, cold review, Playwright) **before** asking the operator to browser-test. Upstream PR only after operator dogfood approval (§8). -**Instruction roots:** agents read **this file** and tooling docs from the **`~/coding/hapi` workspace**, plus `~/coding/AGENTS.local.md`. The **daily driver** (`~/coding/hapi-driver`) is what **`hapi-active` runs** — not where IDE rules come from unless that tree is the opened workspace. +**Instruction roots:** agents read **this file** and tooling docs from the **`~/coding/hapi` workspace**, plus `~/coding/AGENTS.local.md`. The **daily driver** (`~/coding/hapi/driver`) is what **`hapi-active` runs** — not where IDE rules come from unless that tree is the opened workspace. + +**Canonical worktree layout (2026-06-01 onward):** see [`.cursor/rules/worktree-layout.mdc`](../../.cursor/rules/worktree-layout.mdc) and [`docs/plans/2026-06-01-hapi-folders-reorganization.md`](../plans/2026-06-01-hapi-folders-reorganization.md). Summary: `~/coding/hapi/{driver,upstream,worktrees/}` — never create new worktrees at `~/coding/hapi-/` or `~/coding/hapi-worktrees//` (those are pre-reorg legacy locations being drained). --- diff --git a/docs/plans/2026-06-01-hapi-folders-reorganization.md b/docs/plans/2026-06-01-hapi-folders-reorganization.md new file mode 100644 index 00000000000..dda4058f9e3 --- /dev/null +++ b/docs/plans/2026-06-01-hapi-folders-reorganization.md @@ -0,0 +1,281 @@ +# `~/coding/hapi*` reorganization plan + +Status: **Phase 1 (Option B) DONE 2026-06-01.** Phase 2 (drain) in progress, Phase 3 (Option C) pending low-agent-count maintenance window. + +Author note: this is a multi-agent repo. ~31 active agents have CWDs that may be inside dirs this plan moves. Coordination is the dominant cost, not the file moves. + +## Operator decisions (2026-06-01) + +| Question | Answer | +|----------|--------| +| Phase 1 today, low-risk Option B? | **Yes** - executed this session | +| Rename `~/coding/hapi-companion/`? | **No** - stays as-is, it's the independent Android companion product repo | +| Keep backward-compat symlinks (`~/coding/hapi-driver` -> `~/coding/hapi/driver`) after Phase 3? | **No** - hard-cut. Switch happens once, agents adapt. | +| Communication channel for the 31 agents about the new convention? | Per-directory awareness: when a worktree gets removed or moved, message the session in it before action. Bulk announcement not needed because the Cursor rule + audit warning catch new drift. | +| Can we PREVENT wrong-place worktree creation? | Git does not support aliasing built-in subcommands so we can't intercept `git worktree add`. Instead: carrot (`hapi-worktree-create` defaults to canonical path) + stick (Cursor rule `worktree-layout.mdc` + `check-worktree-layout.sh` audit in pre-push hook). | + +--- + +## 1. Current state (what's actually there) + +### 1.1 At `~/coding/` root - the mess + +```text +hapi/ real fork mirror, branch=main (Cursor proj: home-heavygee-coding-hapi, 19 transcripts) +hapi-active -> hapi-driver symlink (used by all systemd) +hapi-main -> hapi symlink (backward-compat shortcut) +hapi-companion/ INDEPENDENT REPO (heavygee/hapi-companion.git, not a worktree) + +hapi-driver/ worktree of hapi [driver/integration] - the active soup +hapi-upstream/ worktree of hapi [upstream-main-test] - the upstream baseline we just built +hapi-garden/ worktree of hapi [garden/r3f-poc] +hapi-interior-life/ worktree of hapi [feat/hub-interior-life-notes] + +hapi-cursor-resume-fix/ worktree of hapi [fix/cursor-resume-id-early-persist] +hapi-cursor-summarize/ worktree of hapi [feat/cursor-summarize-738] +hapi-mermaid-lightbox-737/ worktree of hapi [feat/mermaid-lightbox-737] +hapi-pwa-push-actions/ worktree of hapi [feat/pwa-notification-actions] +hapi-queued-sse-fix/ worktree of hapi [fix/global-sse-messages-consumed] +hapi-runner-handoff/ worktree of hapi [fix/runner-handoff-systemd-resilience] +hapi-session-attention/ worktree of hapi [feat/session-list-attention] +hapi-voice-advanced-controls/ worktree of hapi [feat/voice-advanced-controls] + +hapi-worktrees/ a partial-convention bucket (not all worktrees ended up in here) + issue708/ worktree of hapi [fix/web-scroll-guard-unwrap-race] + issue-709/ worktree of hapi [fix/hub-persist-permission-mode-709] + issue-732-phase1-import-spawn/ worktree of hapi [feat/issue-732-phase1-import-spawn] + issue-resume-race-fix/ worktree of hapi [fix/hub-resume-config-race-728] + pluggable-voice/ worktree of hapi [feat/pluggable-voice-backend] + pre-707-scroll/ worktree of hapi (detached) + styling-issue/ worktree of hapi [hapi-styling-issue] + upstream-main-ab/ worktree of hapi (detached, has dirty bun.lock) + voice-selection-all-backends/ worktree of hapi [feat/voice-selection-all-backends] + voice-selection-all-backends-worktrees/ + 0531-4033/ worktree of hapi [feat/voice-selection-all-backends] (DOUBLY-NESTED, agent-spawned) +``` + +**Counts:** 1 main mirror + 12 top-level peer worktrees + 10 nested worktrees + 1 doubly-nested worktree + 1 independent repo + 2 symlinks = **27 directories** under `~/coding/hapi*`. + +### 1.2 Path dependencies (anything that hard-codes `~/coding/hapi-*`) + +**systemd units** (require `sudo` + `daemon-reload` + service restart to change): +- `/etc/systemd/system/hapi-hub.service` -> `WorkingDirectory=/home/heavygee/coding/hapi-active/hub` +- `/etc/systemd/system/hapi-runner.service` -> calls `/home/heavygee/.local/bin/hapi-runner-from-active` +- `/etc/systemd/system/hapi-runner-watchdog.service` -> `/home/heavygee/coding/hapi-active/cli/systemd/hapi-runner-watchdog.sh` +- `/etc/systemd/system/garden-web.service` -> `WorkingDirectory=/home/heavygee/coding/hapi-garden` + +**`~/.local/bin/` tools** with `~/coding/hapi*` literals: +- `hapi-runner-from-active` (reads `HAPI_ACTIVE_LINK`, default `$HOME/coding/hapi-active`) +- `hapi-use-driver` (`HAPI_DRIVER`, default `$HOME/coding/hapi-driver`) +- `hapi-use-main` (same default) +- `hapi-use-worktree` (`HAPI_ACTIVE_LINK`, `HAPI_DRIVER`) +- `hapi-worktree-create` (`HAPI_PRIMARY=$HOME/coding/hapi`, creates new at `$HOME/coding/hapi-${NAME}` - this is the script that **caused** the top-level sprawl) +- `hapi-driver-rebuild` +- `hapi-watch-activate-driver` + +**`~/.config/hapi/driver-manifest.yaml`** - references branches not paths, no change needed. + +**State dirs (not in scope):** `~/.hapi/`, `~/.hapi-upstream/` - data live elsewhere, no path coupling. + +**Cursor agent project keys** (path -> hash): +- `home-heavygee-coding-hapi` (19 transcripts) - the root mirror +- `home-heavygee-coding-hapi-queued-sse-fix`, `-runner-handoff`, `-worktrees-issue708`, `-worktrees-issue-709`, `-worktrees-issue-resume-race-fix`, `-worktrees-voice-selection--a1de796`, `-worktrees-voice-selection-all-backends-worktrees-0531-4033`, `-worktrees-gemini-investigation` (~9 known) +- **Changing any of these CWDs renames the Cursor project.** Existing transcripts stay where they are. Future resumes go to the new project ID. + +--- + +## 2. Constraints driving the plan + +| Constraint | Impact | +|------------|--------| +| ~31 active agents, many with CWD inside `~/coding/hapi-*` | Moving any peer dir kills the agent in it. Must coordinate stop -> move -> restart. | +| `~/coding/hapi/` IS the canonical fork mirror checkout | Cannot become a pure parent dir without moving `.git`. Moving `.git` invalidates every worktree's anchor pointer. | +| systemd hub + runner serve THIS chat session right now | Their `hapi-active` symlink target change is online. Their `WorkingDirectory` change requires sudo + daemon-reload + restart -> chat blackout window. | +| Cursor project key = path hash | Renaming dir = new Cursor project = lost resume continuity for agents in that dir. Root `~/coding/hapi/` agents are safe ONLY IF we leave that path untouched. | +| `git worktree move` rewrites both ends | But fails if the worktree is currently locked, dirty in incompatible ways, or has running processes (npm dev servers, etc) | +| `hapi-worktree-create` script is the root cause of new top-level dirs | If we don't change it, the next agent re-creates the mess in a day | + +--- + +## 3. Target end-state (operator's request, refined) + +```text +~/coding/hapi/ the fork mirror checkout (branch=main) - UNCHANGED LOCATION + .git/ shared git dir for all worktrees + .gitignore gains: /active, /driver, /upstream, /worktrees, /companion (where applicable) + hub/ cli/ web/ shared/ docs/ existing source tree + + active -> driver symlink (was ~/coding/hapi-active -> ~/coding/hapi-driver) + driver/ worktree [driver/integration] (was ~/coding/hapi-driver) + upstream/ worktree [upstream-main-test or upstream/main] (was ~/coding/hapi-upstream) + worktrees/ bucket for everything else (was ~/coding/hapi-worktrees + scattered top-level) + garden/ worktree [garden/r3f-poc] (was ~/coding/hapi-garden) + interior-life/ worktree (was ~/coding/hapi-interior-life) + cursor-resume-fix/ worktree (was ~/coding/hapi-cursor-resume-fix) + cursor-summarize/ worktree (was ~/coding/hapi-cursor-summarize) + mermaid-lightbox-737/ worktree (was ~/coding/hapi-mermaid-lightbox-737) + pwa-push-actions/ worktree (was ~/coding/hapi-pwa-push-actions) + queued-sse-fix/ worktree (was ~/coding/hapi-queued-sse-fix) + runner-handoff/ worktree (was ~/coding/hapi-runner-handoff) + session-attention/ worktree (was ~/coding/hapi-session-attention) + voice-advanced-controls/ worktree (was ~/coding/hapi-voice-advanced-controls) + issue708/ issue-709/ ... existing nested worktrees stay where they are + pluggable-voice/ etc + +~/coding/hapi-companion/ STAYS where it is (independent product repo, not a worktree of hapi) +``` + +`~/coding/hapi-*` siblings disappear entirely once migration completes. `~/coding/hapi-main` symlink can be deleted (redundant since `~/coding/hapi` IS main). + +--- + +## 4. Three options to get there + +### Option A: Symlink overlay only (cosmetic, zero agent coordination) + +**Move:** nothing. **Add:** + +```bash +ln -s ../hapi-driver ~/coding/hapi/driver +ln -s ../hapi-upstream ~/coding/hapi/upstream +ln -s ../hapi-worktrees ~/coding/hapi/worktrees +ln -s ../hapi-active ~/coding/hapi/active +# (12 more for each top-level worktree, OR consolidate top-level ones manually first) +``` + +Then update docs + tooling to PREFER `~/coding/hapi/` paths going forward. Existing tools, systemd, agents keep working off old paths. New agents/scripts use new paths. + +**Pros:** +- Zero downtime, zero agent disruption +- Reversible: `rm` the symlinks +- Can do today during this session + +**Cons:** +- Underlying filesystem stays messy +- Adds a second naming convention layered on top of the old one (worse, not better, until cleanup) +- `git status` in `~/coding/hapi/` will show the new symlinks as untracked (gitignore them) +- The `hapi-worktree-create` script still creates at `~/coding/hapi-${NAME}` and we have to update it anyway + +**Verdict:** **Not recommended** as the end-state. Useful as a transitional Phase 0 while doing B or C. + +### Option B: Hybrid - move only NEW work to hapi/worktrees, leave running peers alone + +**Move:** nothing existing. **Change:** + +1. Update `hapi-worktree-create` to default to `${HAPI_PRIMARY}/worktrees/${NAME}` instead of `${HAPI_PRIMARY}/../hapi-${NAME}`. +2. Update `hapi-worktree-create` to also accept an `--at top` flag for the rare case someone wants the old layout. +3. Add `.gitignore` entries in `~/coding/hapi/` for `/worktrees/`, `/active`, `/driver`, `/upstream`, `/companion`. +4. Pre-create `~/coding/hapi/worktrees/` (empty dir) so the new default path exists. +5. Document the new convention in `docs/operator/AGENTS.md` so future agents pick it up. +6. Existing 22 worktrees stay where they are. Over time as they merge & get cleaned up, the sprawl naturally drains. + +**Pros:** +- Zero downtime, zero agent disruption now +- Stops the bleeding (new worktrees no longer pollute `~/coding/`) +- Existing worktrees migrate on their own merge/cleanup cycle +- Tooling and docs converge on one convention + +**Cons:** +- Mixed layout persists for weeks until peer worktrees merge out +- `hapi-active` and `hapi-driver` stay at top level (because moving them = systemd outage) +- Cleanup never "finishes" without a deliberate sweep + +**Verdict:** **Recommended as the realistic first move.** Low cost, high payoff, no coordination. + +### Option C: Full physical reorganization (the real cleanup) + +**Move:** everything. Requires a maintenance window. + +**Sequence:** + +1. **Communicate ahead** - announce in operator chat / HAPI session messages: "All hapi peer agents must pause work and commit/push their state by HH:MM. Hub + runner will be offline for ~15 minutes during reorg." +2. **Snapshot baseline** - `git -C ~/coding/hapi worktree list > /tmp/hapi-worktrees-pre-reorg.txt` +3. **Stop services** - `sudo systemctl stop hapi-hub hapi-runner garden-web` +4. **Kill all peer agents** - whatever orchestrator owns them. Identify by `pgrep -af 'coding/hapi-'`. Each agent's terminal CWD becomes invalid after the move. +5. **Move worktrees with git** (preserves the worktree -> .git linkage): + ```bash + git -C ~/coding/hapi worktree move /home/heavygee/coding/hapi-driver /home/heavygee/coding/hapi/driver + git -C ~/coding/hapi worktree move /home/heavygee/coding/hapi-upstream /home/heavygee/coding/hapi/upstream + git -C ~/coding/hapi worktree move /home/heavygee/coding/hapi-garden /home/heavygee/coding/hapi/worktrees/garden + # ... ~22 more moves, all explicit + git -C ~/coding/hapi worktree move /home/heavygee/coding/hapi-worktrees/issue708 /home/heavygee/coding/hapi/worktrees/issue708 + # etc - flattening hapi-worktrees/* up one level into hapi/worktrees/* + # (or keep them, but then there's an intermediate hapi-worktrees that needs to go away too) + ``` +6. **Rebuild active symlink** - `rm ~/coding/hapi-active; ln -s ../hapi/driver ~/coding/hapi/active` +7. **Update systemd unit paths** in-place (4 units), `daemon-reload`, restart: + - `hapi-hub.service`: `WorkingDirectory=/home/heavygee/coding/hapi/active/hub` (or `/home/heavygee/coding/hapi/driver/hub` directly) + - `hapi-runner-watchdog.service`: `ExecStart=/home/heavygee/coding/hapi/active/cli/systemd/hapi-runner-watchdog.sh` + - `garden-web.service`: `WorkingDirectory=/home/heavygee/coding/hapi/worktrees/garden` +8. **Update `~/.local/bin/` scripts** - rewrite `HAPI_PRIMARY`, `HAPI_DRIVER`, `HAPI_ACTIVE_LINK` defaults; `hapi-worktree-create` default location. +9. **Update workspace rules** - `~/coding/hapi/.cursor/rules/operator-fork.mdc`, `AGENTS.md`, `docs/operator/AGENTS.md` to document the new layout. +10. **Restart services** - `sudo systemctl start hapi-hub hapi-runner garden-web` +11. **Verify** - `git -C ~/coding/hapi worktree list` matches expectation; `/health` on hub responds; runner re-registers. +12. **Resume agent work** - operator restarts peer agents with their new CWDs. + +**Pros:** +- Genuinely clean end-state +- Future tooling/docs have one canonical path +- Eliminates the doubly-nested-worktrees absurdity + +**Cons:** +- ~15-30 min hub/runner downtime +- ALL 31 peer agents must pause and resume (each loses Cursor resume continuity unless we leave the SOURCE worktree path's transcripts in place AND new agents get spawned) +- High-touch: ~22 `git worktree move` operations, 4 systemd edits, 5+ script edits +- If any worktree has running dev servers / npm processes when moved, `git worktree move` fails -> partial state +- Cursor project IDs change for every moved worktree -> new transcript dirs, old transcripts orphaned (they stay at the old hash-keyed dir, just no longer get appended to) + +**Verdict:** **Right end-state, wrong week.** Worth doing once 31 agents -> ~5 agents, or batched with another planned downtime (e.g. a major upstream merge). + +--- + +## 5. Recommended path + +**Phase 1 (DONE 2026-06-01):** Option B + drift guards +- [x] Updated `hapi-worktree-create` default to `~/coding/hapi/worktrees/${NAME}` (with deprecated `--at top` fallback) +- [x] Created `~/coding/hapi/worktrees/` empty dir + `.gitkeep` +- [x] Added `.gitignore` entries in `~/coding/hapi/.gitignore`: `/active`, `/driver`, `/upstream`, `/worktrees/*` (negated `!/worktrees/.gitkeep`) +- [x] Created `.cursor/rules/worktree-layout.mdc` (alwaysApply rule) so future agents pick new convention by default +- [x] Created `scripts/tooling/check-worktree-layout.sh` (mirrors `check-stash-advisory.sh` pattern) +- [x] Wired audit into `scripts/tooling/git-hooks/pre-push` (advisory, non-blocking, `HAPI_SKIP_WORKTREE_AUDIT=1` to bypass) +- [x] Documented new convention in `docs/operator/AGENTS.md` +- Awareness for already-running agents: handled per-directory when their worktree gets drained in Phase 2 (no bulk broadcast needed - audit + rule catch new drift) + +**Phase 2 (opportunistic, over the next 1-2 weeks):** drain +- Each worktree that finishes its branch's lifecycle (merged or abandoned): `git worktree remove`. Don't recreate at old path. +- Naturally consolidates without coordinated action. + +**Phase 3 (one-shot maintenance window, when agent count is low):** Option C +- Physically move the few remaining stragglers + `hapi-driver`, `hapi-upstream`, `hapi-active` +- Update systemd + scripts +- ~10-15 min hub downtime +- Done. + +--- + +## 6. Open questions for operator before any execution + +ALL ANSWERED 2026-06-01 - see "Operator decisions" at top of file. Summary: + +1. `~/coding/hapi-companion/` stays - independent repo, prefix is brand-link. +2. Phase 1 (Option B) executed this session. +3. No backward-compat symlinks after Phase 3 - hard-cut. +4. No bulk agent broadcast - per-directory awareness as each worktree drains. + +--- + +## 7. Risks I'm watching even for Option B + +- `hapi-worktree-create` change: needs careful test that existing `HAPI_PRIMARY` override still works for someone who's customized it. +- `.gitignore` for `worktrees/` etc - if any of those subdirs ever contain something we DO want tracked (a top-level README or symlinks list), we need explicit negation patterns. Currently nothing planned to live there as tracked files. +- The fact that `~/coding/hapi-worktrees/voice-selection-all-backends-worktrees/0531-4033` is **doubly nested** is itself a bug - some agent already misuses worktree creation. Worth a separate audit of that. + +--- + +## 8. What I am NOT planning to do without explicit go + +- Touch `~/coding/hapi-companion/` (independent product) +- Move `~/coding/hapi-driver/` while hub serves this session +- Stop / restart hub or runner systemd +- Send messages to other agents +- Delete any `hapi-*` directory anywhere diff --git a/scripts/tooling/check-worktree-layout.sh b/scripts/tooling/check-worktree-layout.sh new file mode 100755 index 00000000000..5f748ff6485 --- /dev/null +++ b/scripts/tooling/check-worktree-layout.sh @@ -0,0 +1,103 @@ +#!/usr/bin/env bash +# Surface git worktrees that live outside the canonical layout. +# Non-blocking - prints to stderr, always exits 0. +# +# Canonical layout (2026-06-01 onward): +# ~/coding/hapi/ main mirror, branch=main +# ~/coding/hapi/driver daily-driver soup +# ~/coding/hapi/upstream clean upstream baseline +# ~/coding/hapi/active symlink at runtime, not a worktree per se +# ~/coding/hapi/worktrees/ everything else +# +# Anything outside these is legacy (pre-2026-06-01) or a wrong-place creation. +# Legacy is OK during Phase 2 drain; wrong-place creations should be flagged. +# +# See: docs/plans/2026-06-01-hapi-folders-reorganization.md +# +# Usage: +# scripts/tooling/check-worktree-layout.sh # foreground audit +# scripts/tooling/check-worktree-layout.sh --quiet # only print if findings +# scripts/tooling/check-worktree-layout.sh --count # just print drift count +# +# Bypass: HAPI_SKIP_WORKTREE_AUDIT=1 +set -euo pipefail + +if [[ "${HAPI_SKIP_WORKTREE_AUDIT:-}" == "1" ]]; then + exit 0 +fi + +QUIET=0 +COUNT_ONLY=0 +while [[ $# -gt 0 ]]; do + case "$1" in + --quiet) QUIET=1; shift ;; + --count) COUNT_ONLY=1; shift ;; + -h|--help) sed -n '2,24p' "$0"; exit 0 ;; + *) echo "Unknown option: $1" >&2; exit 2 ;; + esac +done + +# Use the shared .git dir; works from any worktree. +COMMON_DIR="$(git rev-parse --git-common-dir 2>/dev/null || true)" +[[ -z "$COMMON_DIR" ]] && exit 0 + +# Anchor on the main mirror dir (parent of .git, or whatever common-dir resolves into). +COMMON_ABS="$(cd "$COMMON_DIR" && pwd)" +PRIMARY_ABS="${HAPI_PRIMARY:-$(dirname "$COMMON_ABS")}" +PRIMARY_ABS="$(cd "$PRIMARY_ABS" && pwd)" + +CANONICAL_PREFIXES=( + "${PRIMARY_ABS}" + "${PRIMARY_ABS}/driver" + "${PRIMARY_ABS}/upstream" + "${PRIMARY_ABS}/worktrees/" +) + +is_canonical() { + local path="$1" + if [[ "$path" == "$PRIMARY_ABS" ]]; then return 0; fi + for pfx in "$PRIMARY_ABS/driver" "$PRIMARY_ABS/upstream"; do + if [[ "$path" == "$pfx" ]]; then return 0; fi + done + if [[ "$path" == "$PRIMARY_ABS/worktrees/"* ]]; then return 0; fi + return 1 +} + +mapfile -t WORKTREES < <(git -C "$PRIMARY_ABS" worktree list --porcelain 2>/dev/null \ + | awk '/^worktree / { print $2 }') + +total="${#WORKTREES[@]}" +drift=() +for wt in "${WORKTREES[@]}"; do + if ! is_canonical "$wt"; then + drift+=("$wt") + fi +done + +if [[ "$COUNT_ONLY" -eq 1 ]]; then + echo "${#drift[@]}" + exit 0 +fi + +if [[ "${#drift[@]}" -eq 0 ]]; then + [[ "$QUIET" -eq 1 ]] || echo "worktree-layout: ${total} worktree(s), all in canonical layout" + exit 0 +fi + +{ + echo "worktree-layout: ${#drift[@]} of ${total} worktree(s) live outside canonical layout:" + for path in "${drift[@]}"; do + echo " $path" + done + echo "" + echo " Canonical layout (since 2026-06-01):" + echo " ${PRIMARY_ABS}/{driver,upstream,worktrees/}" + echo "" + echo " These may be legacy (pre-reorg) or accidental wrong-place creation." + echo " Plan: docs/plans/2026-06-01-hapi-folders-reorganization.md" + echo " Use 'hapi-worktree-create' (defaults to canonical path) for new worktrees." + echo " To move a legacy one: git worktree move ${PRIMARY_ABS}/worktrees/" + echo " Bypass once: HAPI_SKIP_WORKTREE_AUDIT=1" +} >&2 + +exit 0 diff --git a/scripts/tooling/git-hooks/pre-push b/scripts/tooling/git-hooks/pre-push index e51328f86c0..4bcceb12413 100755 --- a/scripts/tooling/git-hooks/pre-push +++ b/scripts/tooling/git-hooks/pre-push @@ -63,4 +63,9 @@ if [[ -x "$ADVISORY" ]]; then "$ADVISORY" --quiet || true fi +WT_AUDIT="$ROOT/scripts/tooling/check-worktree-layout.sh" +if [[ -x "$WT_AUDIT" ]]; then + "$WT_AUDIT" --quiet || true +fi + exit 0 diff --git a/scripts/tooling/hapi-worktree-create.sh b/scripts/tooling/hapi-worktree-create.sh index 052df472c29..33d988d1ff7 100755 --- a/scripts/tooling/hapi-worktree-create.sh +++ b/scripts/tooling/hapi-worktree-create.sh @@ -1,22 +1,38 @@ #!/usr/bin/env bash -# Create a PR formulation worktree. +# Create a PR formulation worktree, in the canonical location. +# +# CANONICAL LAYOUT (2026-06-01 onward): +# ~/coding/hapi/ main mirror, branch=main +# ~/coding/hapi/worktrees/ NEW worktrees go here (default) +# ~/coding/hapi/driver the daily-driver soup worktree (already exists) +# ~/coding/hapi/upstream clean upstream-main worktree (already exists) +# ~/coding/hapi/active symlink, points at one of the above +# +# Pre-2026-06-01 worktrees still live at ~/coding/hapi-/ during Phase 2 drain. +# See docs/plans/2026-06-01-hapi-folders-reorganization.md. # # Usage: # hapi-worktree-create --branch [--after branch:foo] [--after pr:692] ... # hapi-worktree-create pluggable-voice --branch feat/pluggable-voice-backend # hapi-worktree-create stacked-foo --branch feat/foo --after feat/pluggable-voice-backend # +# Flags: +# --at top (DEPRECATED) Create at ~/coding/hapi-/ legacy location. +# Will warn loudly. Do not use for new work. +# set -euo pipefail PRIMARY="${HAPI_PRIMARY:-$HOME/coding/hapi}" BUN="${BUN:-$HOME/.bun/bin/bun}" BASE="${HAPI_WORKTREE_BASE:-upstream/main}" +WORKTREE_ROOT="${HAPI_WORKTREE_ROOT:-$PRIMARY/worktrees}" NAME="" BRANCH="" +AT_TOP=0 AFTER=() usage() { - sed -n '2,10p' "$0" + sed -n '2,22p' "$0" } while [[ $# -gt 0 ]]; do @@ -24,6 +40,13 @@ while [[ $# -gt 0 ]]; do --branch) BRANCH="${2:?}"; shift 2 ;; --base) BASE="${2:?}"; shift 2 ;; --after) AFTER+=("${2:?}"); shift 2 ;; + --at) + case "${2:?}" in + top) AT_TOP=1; shift 2 ;; + canonical|worktrees) AT_TOP=0; shift 2 ;; + *) echo "ERROR: --at takes 'top' (deprecated) or 'canonical'" >&2; exit 2 ;; + esac + ;; -h|--help) usage; exit 0 ;; -*) echo "Unknown option: $1" >&2; usage >&2; exit 2 ;; *) @@ -36,7 +59,14 @@ done [[ -n "$NAME" ]] || { echo "Usage: hapi-worktree-create --branch [--after ref...]" >&2; exit 2; } [[ -n "$BRANCH" ]] || { echo "ERROR: --branch required" >&2; exit 2; } -PATH_DIR="$HOME/coding/hapi-${NAME}" +if [[ "$AT_TOP" == "1" ]]; then + PATH_DIR="$HOME/coding/hapi-${NAME}" + echo "WARN: --at top is deprecated; new worktrees should live in $WORKTREE_ROOT/" >&2 + echo "WARN: see docs/plans/2026-06-01-hapi-folders-reorganization.md" >&2 +else + mkdir -p "$WORKTREE_ROOT" + PATH_DIR="$WORKTREE_ROOT/${NAME}" +fi HUB_ENV="$HOME/.hapi/hub.env" if [[ -e "$PATH_DIR" ]]; then diff --git a/worktrees/.gitkeep b/worktrees/.gitkeep new file mode 100644 index 00000000000..e69de29bb2d From 2de6126430d754a0e607dac73a35553b9e3401a8 Mon Sep 17 00:00:00 2001 From: HeavyGee <133152184+heavygee@users.noreply.github.com> Date: Mon, 1 Jun 2026 08:15:46 +0100 Subject: [PATCH 0021/1600] chore(tooling): canonical-worktree guard via ~/.local/bin/git PATH shim Closes the gap left by the prior Phase 1 commit: 'git won't let us alias built-in subcommands' was a lazy answer. The right answer is to wrap `git` itself at the PATH layer (~/.local/bin/git already exists as a push cold-review wrapper; just extend it). Now every `git worktree add` inside the hapi clone is rejected if the target path is not under the canonical ~/coding/hapi/worktrees/ (or the reserved driver/upstream slots). Layers (defense in depth): 1. Carrot: hapi-worktree-create defaults to canonical bucket 2. Shim: ~/.local/bin/git wrapper -> scripts/tooling/git-shim-worktree-guard.sh hard-blocks non-canonical 'git worktree add' inside the clone 3. Audit: scripts/tooling/check-worktree-layout.sh in pre-push hook reports drift across the whole clone (catches anything that bypassed the shim) Bypass for one-off: HAPI_SKIP_WORKTREE_GUARD=1 git worktree add ... Tested: - 13 unit tests against the guard script (good paths, bad paths, -b/-B, --detach, reserved slots, /tmp allow, ~/coding allow-list, bypass env) - 4 E2E tests via the wrapper (bad path blocked, -b blocked, -C global flag handled, bypass works) - Non-hapi repo (~/coding/server-setup) unaffected - guard exits 0 when not invoked inside the hapi clone - Pass-through overhead: ~2.4ms per git invocation (100 git --version in 0.243s) vs ~0.2ms direct - acceptable The shim is installed at ~/.local/bin/git (operator-machine-local, not tracked) but the GUARD logic it calls lives in this commit as a tracked script - so any operator-machine recreating the wrapper just needs the one-line invocation pointing at the tracked script. Co-authored-by: Cursor --- .cursor/rules/worktree-layout.mdc | 8 +- .../2026-06-01-hapi-folders-reorganization.md | 3 +- scripts/tooling/check-worktree-layout.sh | 5 + scripts/tooling/git-shim-worktree-guard.sh | 128 ++++++++++++++++++ 4 files changed, 141 insertions(+), 3 deletions(-) create mode 100755 scripts/tooling/git-shim-worktree-guard.sh diff --git a/.cursor/rules/worktree-layout.mdc b/.cursor/rules/worktree-layout.mdc index 22667525e03..053d3476d02 100644 --- a/.cursor/rules/worktree-layout.mdc +++ b/.cursor/rules/worktree-layout.mdc @@ -33,8 +33,12 @@ When you create a new worktree: - The mirror dir (`~/coding/hapi`) stays clean of sibling clutter; the gitignore at root masks `/worktrees/`, `/driver`, `/upstream`, `/active`. - Cursor project ids are path-hashed - moving worktrees breaks agent resume continuity. The canonical layout puts new work in stable paths that will not move again. -## Backstop +## Backstops (three of them) -`scripts/tooling/check-worktree-layout.sh` runs in the `pre-push` hook (advisory). It warns when worktrees live outside the canonical layout. Drift is expected during Phase 2 of the reorg; new drift after that is a bug. +1. **Carrot:** `hapi-worktree-create --branch ` defaults to the canonical bucket. Use it. +2. **Hard stop at `git` invocation:** `~/.local/bin/git` is a wrapper that intercepts `git worktree add` inside the hapi clone and refuses non-canonical targets (source: `scripts/tooling/git-shim-worktree-guard.sh`). This catches direct `git worktree add` calls from agents, scripts, and IDE integrations. Bypass once with `HAPI_SKIP_WORKTREE_GUARD=1 git worktree add ...`. +3. **Drift audit on push:** `scripts/tooling/check-worktree-layout.sh` runs in the `pre-push` hook (advisory). It warns when ANY worktree of this clone lives outside the canonical layout — catches legacy drift and anything that snuck past the shim. + +Drift is expected during Phase 2 of the reorg; new drift after that is a bug. See [docs/plans/2026-06-01-hapi-folders-reorganization.md](../../docs/plans/2026-06-01-hapi-folders-reorganization.md) for the full reorganization plan and migration phases. diff --git a/docs/plans/2026-06-01-hapi-folders-reorganization.md b/docs/plans/2026-06-01-hapi-folders-reorganization.md index dda4058f9e3..7d52633b1b7 100644 --- a/docs/plans/2026-06-01-hapi-folders-reorganization.md +++ b/docs/plans/2026-06-01-hapi-folders-reorganization.md @@ -12,7 +12,7 @@ Author note: this is a multi-agent repo. ~31 active agents have CWDs that may be | Rename `~/coding/hapi-companion/`? | **No** - stays as-is, it's the independent Android companion product repo | | Keep backward-compat symlinks (`~/coding/hapi-driver` -> `~/coding/hapi/driver`) after Phase 3? | **No** - hard-cut. Switch happens once, agents adapt. | | Communication channel for the 31 agents about the new convention? | Per-directory awareness: when a worktree gets removed or moved, message the session in it before action. Bulk announcement not needed because the Cursor rule + audit warning catch new drift. | -| Can we PREVENT wrong-place worktree creation? | Git does not support aliasing built-in subcommands so we can't intercept `git worktree add`. Instead: carrot (`hapi-worktree-create` defaults to canonical path) + stick (Cursor rule `worktree-layout.mdc` + `check-worktree-layout.sh` audit in pre-push hook). | +| Can we PREVENT wrong-place worktree creation? | **Yes** - via PATH-precedence wrapper at `~/.local/bin/git` that intercepts `git worktree add` inside the hapi clone and refuses non-canonical targets (source tracked at `scripts/tooling/git-shim-worktree-guard.sh`). Wrapper passes through everything else; ~2.4ms overhead per git call. Bypass with `HAPI_SKIP_WORKTREE_GUARD=1`. Original answer ("git won't let us alias built-in subcommands") was lazy - the right answer is to wrap `git` itself at the PATH layer, not alias the subcommand. Carrot (`hapi-worktree-create`) and audit (`check-worktree-layout.sh` in pre-push) remain as additional layers. | --- @@ -238,6 +238,7 @@ Then update docs + tooling to PREFER `~/coding/hapi/` paths going forward. - [x] Created `.cursor/rules/worktree-layout.mdc` (alwaysApply rule) so future agents pick new convention by default - [x] Created `scripts/tooling/check-worktree-layout.sh` (mirrors `check-stash-advisory.sh` pattern) - [x] Wired audit into `scripts/tooling/git-hooks/pre-push` (advisory, non-blocking, `HAPI_SKIP_WORKTREE_AUDIT=1` to bypass) +- [x] Created `scripts/tooling/git-shim-worktree-guard.sh` and patched `~/.local/bin/git` wrapper to call it before `git worktree add`. Hard block on non-canonical paths inside the hapi clone (bypass: `HAPI_SKIP_WORKTREE_GUARD=1`). 13 unit + 4 E2E tests pass. Non-hapi repos unaffected. ~2.4ms overhead per git invocation. - [x] Documented new convention in `docs/operator/AGENTS.md` - Awareness for already-running agents: handled per-directory when their worktree gets drained in Phase 2 (no bulk broadcast needed - audit + rule catch new drift) diff --git a/scripts/tooling/check-worktree-layout.sh b/scripts/tooling/check-worktree-layout.sh index 5f748ff6485..91169cbd36b 100755 --- a/scripts/tooling/check-worktree-layout.sh +++ b/scripts/tooling/check-worktree-layout.sh @@ -94,6 +94,11 @@ fi echo " ${PRIMARY_ABS}/{driver,upstream,worktrees/}" echo "" echo " These may be legacy (pre-reorg) or accidental wrong-place creation." + echo " New 'git worktree add' is now blocked at the PATH-shim layer (~/.local/bin/git)" + echo " via scripts/tooling/git-shim-worktree-guard.sh - if any of the above were created" + echo " AFTER 2026-06-01, someone bypassed the shim (HAPI_SKIP_WORKTREE_GUARD=1) or used" + echo " /usr/bin/git directly. Investigate." + echo "" echo " Plan: docs/plans/2026-06-01-hapi-folders-reorganization.md" echo " Use 'hapi-worktree-create' (defaults to canonical path) for new worktrees." echo " To move a legacy one: git worktree move ${PRIMARY_ABS}/worktrees/" diff --git a/scripts/tooling/git-shim-worktree-guard.sh b/scripts/tooling/git-shim-worktree-guard.sh new file mode 100755 index 00000000000..3c6ad463d34 --- /dev/null +++ b/scripts/tooling/git-shim-worktree-guard.sh @@ -0,0 +1,128 @@ +#!/usr/bin/env bash +# Worktree-add guard for the ~/coding/hapi clone (canonical layout enforcer). +# +# Standalone script invoked by the ~/.local/bin/git wrapper BEFORE running +# `git worktree add`. Exits 0 = OK to proceed; exits 1 (after printing) = block. +# +# Receives `git worktree add ...` args with global flags already stripped by the +# wrapper. Args here begin with "worktree" "add" ... +# +# Bypass: HAPI_SKIP_WORKTREE_GUARD=1 +# +# Tested invocation patterns the wrapper forwards here: +# git worktree add +# git worktree add -b [] +# git worktree add -B [] +# git worktree add --detach +# git worktree add --force --no-checkout +# git -C worktree add (wrapper chdirs first; -C stripped) +# +# Repo context: enforced only when invoked inside the hapi clone (detected via +# `git rev-parse --git-common-dir`). For non-hapi repos this exits 0 immediately. +# Allow-listed targets: +# - ${HAPI_PRIMARY}/worktrees/ (canonical bucket) +# - ${HAPI_PRIMARY}/driver (reserved, already exists) +# - ${HAPI_PRIMARY}/upstream (reserved, already exists) +# - paths under /tmp/ or ~/tmp/ (ephemeral fixtures) +# - paths outside ~/coding/ (warned but allowed) +# Block: +# - any other path under ~/coding/ (i.e. legacy ~/coding/hapi-/ pattern) + +set -uo pipefail + +[[ "${HAPI_SKIP_WORKTREE_GUARD:-}" == "1" ]] && exit 0 + +[[ "${1:-}" == "worktree" && "${2:-}" == "add" ]] || exit 0 + +REAL_GIT="${REAL_GIT_BIN:-/usr/bin/git}" +[[ -x "$REAL_GIT" ]] || exit 0 + +TOP="$("$REAL_GIT" rev-parse --show-toplevel 2>/dev/null || true)" +COMMON="$("$REAL_GIT" rev-parse --git-common-dir 2>/dev/null || true)" +[[ -z "$TOP" && -z "$COMMON" ]] && exit 0 + +HAPI_ROOT="${HAPI_PRIMARY:-$HOME/coding/hapi}" +HAPI_ROOT="$(cd "$HAPI_ROOT" 2>/dev/null && pwd -P || echo "$HAPI_ROOT")" + +COMMON_ABS="" +if [[ -n "$COMMON" ]]; then + COMMON_ABS="$(cd "$COMMON" 2>/dev/null && pwd -P || echo "$COMMON")" +fi + +is_hapi=0 +if [[ -n "$COMMON_ABS" && "$COMMON_ABS" == "$HAPI_ROOT/.git" ]]; then + is_hapi=1 +fi +if [[ "$is_hapi" -ne 1 && -n "$TOP" ]]; then + case "$TOP" in + "$HAPI_ROOT"|"$HAPI_ROOT"/*|"$HOME/coding/hapi-"*) is_hapi=1 ;; + esac +fi +[[ "$is_hapi" -eq 1 ]] || exit 0 + +shift 2 +path_arg="" +while [[ "$#" -gt 0 ]]; do + a="$1" + case "$a" in + -b|-B|--reason) + shift 2 2>/dev/null || break ;; + --reason=*|--lock|--lock=*|--checkout|--no-checkout|--detach|--force|-f|\ + --quiet|-q|--track|--no-track|--guess-remote|--no-guess-remote|--orphan|\ + --relative-paths|--no-relative-paths|--expire|--expire=*) + shift ;; + --*=*|-*) + shift ;; + *) + path_arg="$a" + break ;; + esac +done + +[[ -n "$path_arg" ]] || exit 0 + +case "$path_arg" in + /*) abs="$path_arg" ;; + "~"|"~/"*) abs="${path_arg/#~/$HOME}" ;; + *) abs="$(pwd -P)/$path_arg" ;; +esac +abs="$(realpath -m "$abs" 2>/dev/null || echo "$abs")" + +CANON_ROOT="$HAPI_ROOT/worktrees" +CANON_DRIVER="$HAPI_ROOT/driver" +CANON_UPSTREAM="$HAPI_ROOT/upstream" + +case "$abs" in + "$CANON_ROOT"/*|"$CANON_DRIVER"|"$CANON_UPSTREAM") exit 0 ;; + /tmp/*|"$HOME/tmp/"*) exit 0 ;; +esac + +case "$abs" in + "$HOME/coding/"*) + cat <&2 + +git: BLOCKED -- git worktree add at non-canonical path inside hapi area + + Requested: $abs + Canonical: $CANON_ROOT/ + $CANON_DRIVER, $CANON_UPSTREAM (reserved) + + Why: hapi worktrees must live in one predictable place so all agents and + tooling can find them. Pre-2026-06-01 worktrees in ~/coding/hapi-/ + and ~/coding/hapi-worktrees// are LEGACY and being drained. + + Use: hapi-worktree-create --branch + Or: git worktree add $CANON_ROOT/ [] + Bypass: HAPI_SKIP_WORKTREE_GUARD=1 git worktree add ... + + See: .cursor/rules/worktree-layout.mdc + docs/plans/2026-06-01-hapi-folders-reorganization.md + +EOF + exit 1 + ;; + *) + echo "git-shim: warn -- worktree add target is outside ~/coding/: $abs" >&2 + exit 0 + ;; +esac From 33095ad213741910304f833c23c708b0d1d38c6e Mon Sep 17 00:00:00 2001 From: HeavyGee <133152184+heavygee@users.noreply.github.com> Date: Mon, 1 Jun 2026 16:46:07 +0100 Subject: [PATCH 0022/1600] chore(tooling): auto DB prep on stack switch (forward + reverse migrations) The hub's SQLite store has forward step-migrations only (v1 -> v2 -> ... -> N). Going backward (e.g. swinging active from a v10 soup back to a v9 upstream/main) crashed the hub at boot with "schema version mismatch ... does not run compatibility migrations" - which exactly bit us this morning when the manifest was cleaned to pure-upstream while the live DB was still at v10 from feat/android-wear-companion's fcm_devices table. New helper scripts/tooling/hapi-driver-db-prep.sh: - Reads target SCHEMA_VERSION from /hub/src/store/index.ts - Reads live PRAGMA user_version from ~/.hapi/hapi.db - Always backs up DB to ~/.hapi/hapi.db.bak.pre-activate- (skip with HAPI_DB_PREP_NO_BACKUP=1, not recommended) - live == target -> no-op - live < target -> no-op (hub auto-migrates forward on boot) - live > target -> walks downgrade table one step at a time; aborts on unknown transition without touching the DB - --dry-run flag for inspection without side effects - Refuses to run while hub is active (must be stopped first) Wired into hapi-use-worktree.sh: it now stops hub, runs prep, then starts hub (was: blind systemctl restart). Bypass via HAPI_SKIP_DB_PREP=1 if you need the old behavior for some reason. Known downgrade table (extend apply_downgrade_step() as new layers bump schema): - v10 -> v9: DROP fcm_devices + 2 indexes (introduced by android-wear-companion) Tested end-to-end this session: - Started: live v9, layers=[], hub on pure upstream/main - Re-added all 9 layers, rebuilt driver -> target v10 - hapi-use-worktree saw live(9) < target(10) -> forward decision, backed up DB, started hub - Hub booted, stepMigrations[9] ran, DB now at v10, fcm_devices table back - All 9 layers live: voice stack, interior-life, pwa-push, android-wear, mermaid, queued-sse, voice-advanced-controls, runner-handoff resilience - Hub + runner active, serving normal session traffic docs/tooling/driver-soup.md: added DB jiu-jitsu section + scripts table entry. The downgrade path (v10 -> v9) was exercised earlier this session by the manual SQL block; the helper just wraps that SQL in detection + backup logic. Co-authored-by: Cursor --- docs/tooling/driver-soup.md | 18 ++- scripts/tooling/hapi-driver-db-prep.sh | 156 +++++++++++++++++++++++++ scripts/tooling/hapi-use-worktree.sh | 28 ++++- 3 files changed, 199 insertions(+), 3 deletions(-) create mode 100755 scripts/tooling/hapi-driver-db-prep.sh diff --git a/docs/tooling/driver-soup.md b/docs/tooling/driver-soup.md index ee905fedefe..159f89db3d2 100644 --- a/docs/tooling/driver-soup.md +++ b/docs/tooling/driver-soup.md @@ -136,13 +136,29 @@ Garden shared mode (`garden-web.service` → `:5174` → API `:3006`) always tal |---------|---------| | `hapi-driver-rebuild` | Rebuild soup from manifest | | `hapi-worktree-create` | New PR worktree (+ merge train) | -| `hapi-use-worktree ` | Swing `hapi-active` + restart **hub + runner** | +| `hapi-use-worktree ` | Swing `hapi-active` + **prep DB** + restart hub + runner | | `hapi-use-driver` | Swing to daily driver soup | +| `hapi-driver-db-prep ` | Backup DB + auto-downgrade schema to match ``'s SCHEMA_VERSION; called automatically by `hapi-use-worktree` | | `hapi-runner-from-active` | systemd helper — runner CLI from `hapi-active/cli` | | `hapi-sessions-health.sh` | Session monitor | Sources: `scripts/tooling/` in repo; installed to `~/.local/bin/`. +### DB schema jiu-jitsu (auto-handled, 2026-06-01) + +The hub's SQLite store has **forward step-migrations only** (v1 -> v2 -> ... -> N). When the manifest changes the effective SCHEMA_VERSION, the live DB at `~/.hapi/hapi.db` must match the target tree before hub boot: + +- **Adding a schema-bumping layer (e.g. `feat/android-wear-companion` v9 -> v10):** automatic. Hub boots, `stepMigrations[N]` runs, DB ratchets forward. Nothing to do. +- **Removing one (rolling back to upstream/main; v10 -> v9):** the hub code has no down-migrations. `hapi-driver-db-prep.sh` auto-invokes from `hapi-use-worktree`, backs up the DB (timestamped `~/.hapi/hapi.db.bak.pre-activate-`), and applies known reverse SQL. + +**Known reverse transitions** (extend `apply_downgrade_step()` in `scripts/tooling/hapi-driver-db-prep.sh` when a new bump lands): + +| Direction | Effect | Data loss | +|-----------|--------|-----------| +| v10 -> v9 | DROP TABLE `fcm_devices` + 2 indexes (introduced by `feat/android-wear-companion`) | FCM device registrations gone from live DB; preserved in backup; Android companion re-registers on next launch | + +**Bypass** (not recommended): `HAPI_SKIP_DB_PREP=1 hapi-use-worktree ...`. This restores the old behavior (raw `systemctl restart`) and you eat the hub-crash-on-schema-mismatch if you're going backward. + --- ## First-time setup diff --git a/scripts/tooling/hapi-driver-db-prep.sh b/scripts/tooling/hapi-driver-db-prep.sh new file mode 100755 index 00000000000..b5dfae50db3 --- /dev/null +++ b/scripts/tooling/hapi-driver-db-prep.sh @@ -0,0 +1,156 @@ +#!/usr/bin/env bash +# Prepare ~/.hapi/hapi.db for activation of . +# +# Why this exists: +# The hub's SQLite store has forward step-migrations only (v1 -> v2 -> ... -> N). +# Reverse migrations (e.g. v10 -> v9 when rolling back to upstream/main) are NOT +# in the hub code. If the live DB is at v10 and the target hub code expects v9, +# the hub aborts at boot with a schema-mismatch fatal. This script bridges that +# gap, atomically and with a backup. +# +# What it does: +# 1. Resolves three schema versions: +# target_schema = SCHEMA_VERSION read from /hub/src/store/index.ts +# live_schema = PRAGMA user_version of ~/.hapi/hapi.db +# base_schema = SCHEMA_VERSION read from upstream/main (informational only) +# 2. Always backs up ~/.hapi/hapi.db to ~/.hapi/hapi.db.bak.pre-activate- +# (unless HAPI_DB_PREP_NO_BACKUP=1; not recommended) +# 3. If live_schema == target_schema: nothing else to do (hub will boot cleanly) +# If live_schema < target_schema: nothing else to do (hub will auto-migrate +# forward via stepMigrations on boot) +# If live_schema > target_schema: apply known downgrade SQL to step DB back +# from live_schema down to target_schema. +# Aborts if any step is unknown. +# +# Hub MUST be stopped before running this. Caller is responsible. Verified here. +# +# Known downgrade transitions (extend as new schema-bumping layers are added): +# v10 -> v9 : DROP TABLE fcm_devices + its 2 indexes +# (introduced by feat/android-wear-companion; data loss = fcm_devices +# rows; restore from backup if needed; Android companion re-registers +# on next launch) +# +# Usage: +# hapi-driver-db-prep.sh +# hapi-driver-db-prep.sh --dry-run +# +# Env: +# HAPI_DB_PATH (default: $HOME/.hapi/hapi.db) +# HAPI_PRIMARY (default: $HOME/coding/hapi - used for git lookups) +# HAPI_DB_PREP_NO_BACKUP=1 skip the safety backup (not recommended) + +set -euo pipefail + +DRY_RUN=0 +TARGET="" + +while [[ $# -gt 0 ]]; do + case "$1" in + --dry-run) DRY_RUN=1; shift ;; + -h|--help) sed -n '2,40p' "$0"; exit 0 ;; + *) + if [[ -z "$TARGET" ]]; then TARGET="$1"; shift + else echo "Unexpected arg: $1" >&2; exit 2; fi + ;; + esac +done + +[[ -n "$TARGET" ]] || { echo "Usage: hapi-driver-db-prep.sh " >&2; exit 2; } +TARGET="$(realpath "$TARGET")" + +PRIMARY="${HAPI_PRIMARY:-$HOME/coding/hapi}" +DB_PATH="${HAPI_DB_PATH:-$HOME/.hapi/hapi.db}" + +[[ -f "$DB_PATH" ]] || { echo "ERROR: DB not found at $DB_PATH" >&2; exit 1; } +[[ -f "$TARGET/hub/src/store/index.ts" ]] || { + echo "ERROR: target $TARGET missing hub/src/store/index.ts" >&2 + exit 1 +} + +extract_schema_version() { + grep -E "^const SCHEMA_VERSION:\s*number\s*=\s*[0-9]+" "$1" \ + | head -1 \ + | grep -oE "[0-9]+$" +} + +target_schema="$(extract_schema_version "$TARGET/hub/src/store/index.ts" || true)" +[[ -n "$target_schema" ]] || { echo "ERROR: could not parse SCHEMA_VERSION in $TARGET" >&2; exit 1; } + +base_schema="$(git -C "$PRIMARY" show upstream/main:hub/src/store/index.ts 2>/dev/null \ + | grep -E "^const SCHEMA_VERSION:\s*number\s*=\s*[0-9]+" | head -1 | grep -oE "[0-9]+$" || true)" +base_schema="${base_schema:-?}" + +live_schema="$(sqlite3 "$DB_PATH" "PRAGMA user_version;" 2>/dev/null || true)" +[[ -n "$live_schema" ]] || { echo "ERROR: could not read PRAGMA user_version from $DB_PATH" >&2; exit 1; } + +echo "hapi-driver-db-prep:" +echo " target_schema = $target_schema (from $TARGET/hub/src/store/index.ts)" +echo " base_schema = $base_schema (from upstream/main)" +echo " live_schema = $live_schema (from $DB_PATH)" + +if [[ "$live_schema" -eq "$target_schema" ]]; then + decision="match -- no migration needed" +elif [[ "$live_schema" -lt "$target_schema" ]]; then + decision="forward -- hub will auto-migrate $live_schema -> $target_schema via stepMigrations on boot" +else + decision="downgrade -- need to step DB back from $live_schema down to $target_schema" +fi +echo " decision: $decision" + +if [[ "$DRY_RUN" -eq 1 ]]; then + echo " (dry-run; exiting)" + exit 0 +fi + +if systemctl is-active --quiet hapi-hub.service; then + echo "ERROR: hapi-hub.service is active. Stop it first:" >&2 + echo " sudo systemctl stop hapi-hub.service" >&2 + exit 1 +fi + +if [[ "${HAPI_DB_PREP_NO_BACKUP:-}" != "1" ]]; then + BACKUP="${DB_PATH}.bak.pre-activate-$(date -u +%Y%m%d-%H%M%SZ)" + echo " backup: $DB_PATH -> $BACKUP" + cp -a "$DB_PATH" "$BACKUP" +fi + +apply_downgrade_step() { + local from="$1" to="$2" + case "${from}_to_${to}" in + 10_to_9) + echo " applying v10 -> v9 downgrade: DROP fcm_devices + indexes" + sqlite3 "$DB_PATH" <<'SQL' +BEGIN IMMEDIATE; +DROP INDEX IF EXISTS idx_fcm_devices_token; +DROP INDEX IF EXISTS idx_fcm_devices_namespace; +DROP TABLE IF EXISTS fcm_devices; +PRAGMA user_version = 9; +COMMIT; +SQL + ;; + *) + echo "ERROR: no known downgrade for v${from} -> v${to}" >&2 + echo " Add a case to apply_downgrade_step() in $0" >&2 + echo " OR restore from a v${to} backup manually" >&2 + return 1 + ;; + esac +} + +if [[ "$live_schema" -gt "$target_schema" ]]; then + cur="$live_schema" + while [[ "$cur" -gt "$target_schema" ]]; do + prev=$((cur - 1)) + apply_downgrade_step "$cur" "$prev" || exit 1 + cur="$prev" + done + new_live="$(sqlite3 "$DB_PATH" "PRAGMA user_version;")" + if [[ "$new_live" -ne "$target_schema" ]]; then + echo "ERROR: downgrade left DB at v${new_live}, expected v${target_schema}" >&2 + exit 1 + fi + echo " downgrade done: DB now at v${new_live}" + sqlite3 "$DB_PATH" "VACUUM;" +fi + +echo " db-prep complete; safe to start hub on $TARGET" diff --git a/scripts/tooling/hapi-use-worktree.sh b/scripts/tooling/hapi-use-worktree.sh index 42cf43ea107..04f2ecc5e00 100755 --- a/scripts/tooling/hapi-use-worktree.sh +++ b/scripts/tooling/hapi-use-worktree.sh @@ -53,8 +53,32 @@ fi echo "Pointing hapi-active → $WORKTREE" ln -sfn "$WORKTREE" "$ACTIVE_LINK" -echo "Restarting hapi-hub.service + hapi-runner.service ..." -sudo systemctl restart hapi-hub.service hapi-runner.service +# DB jiu-jitsu: ensure ~/.hapi/hapi.db schema matches the target tree before the +# hub starts. Skip with HAPI_SKIP_DB_PREP=1 (not recommended). +DB_PREP="$(dirname "$(readlink -f "$0")")/hapi-driver-db-prep.sh" +if [[ "${HAPI_SKIP_DB_PREP:-}" != "1" && -x "$DB_PREP" ]]; then + echo "" + echo "Stopping hub to prep DB ..." + sudo systemctl stop hapi-hub.service || true + if ! "$DB_PREP" "$WORKTREE"; then + echo "ERROR: DB prep failed; refusing to restart hub on incompatible schema" >&2 + echo " Live DB and backup are untouched if downgrade aborted." >&2 + echo " Restart hub manually after resolving: sudo systemctl start hapi-hub.service" >&2 + exit 1 + fi + echo "" + echo "Starting hub + restarting runner ..." + sudo systemctl start hapi-hub.service + sudo systemctl restart hapi-runner.service +else + if [[ "${HAPI_SKIP_DB_PREP:-}" == "1" ]]; then + echo "WARN: HAPI_SKIP_DB_PREP=1 -- skipping DB schema check + backup" >&2 + else + echo "WARN: hapi-driver-db-prep.sh not found at $DB_PREP -- skipping" >&2 + fi + echo "Restarting hapi-hub.service + hapi-runner.service ..." + sudo systemctl restart hapi-hub.service hapi-runner.service +fi echo "" echo "Active stack:" From 5d5a8bd6edc62aa6572430130d6b41c683ced570 Mon Sep 17 00:00:00 2001 From: HeavyGee <133152184+heavygee@users.noreply.github.com> Date: Mon, 1 Jun 2026 21:22:02 +0100 Subject: [PATCH 0023/1600] docs: surface DB schema discipline in manifest template + intake gates Two follow-ups to commit 33095ad (auto DB prep on stack switch): - driver-manifest.example.yaml: header comment now explains that schema bumps in this list trigger the reverse-SQL contract; points at hapi-driver-db-prep.sh and driver-soup.md for the full flow. - new-feature-intake.md gate 3 (renumbered): new "DB schema check" item - if a peer's branch bumps SCHEMA_VERSION, they must also extend apply_downgrade_step() before handoff. Without this rule, every new schema-bumping layer would silently install a future activation trap. Playwright smoke renumbers to gate 4. Co-authored-by: Cursor --- docs/tooling/driver-manifest.example.yaml | 14 ++++++++++++++ docs/tooling/new-feature-intake.md | 5 +++-- 2 files changed, 17 insertions(+), 2 deletions(-) diff --git a/docs/tooling/driver-manifest.example.yaml b/docs/tooling/driver-manifest.example.yaml index 07efd84431c..2dfee79b2dc 100644 --- a/docs/tooling/driver-manifest.example.yaml +++ b/docs/tooling/driver-manifest.example.yaml @@ -3,6 +3,20 @@ # # ~/coding/hapi-driver is READ-ONLY between rebuilds — only hapi-driver-rebuild may change it. # Layer order matters. Each layer merges into driver/integration on top of base. +# +# DB schema: +# Hub's SQLite store has FORWARD step-migrations only. Layers that bump +# SCHEMA_VERSION (in hub/src/store/index.ts) auto-migrate the live DB at hub +# boot. Removing them later requires reverse SQL, which the hub code does NOT +# carry — `hapi-use-worktree` auto-invokes `hapi-driver-db-prep.sh` to back up +# the DB and apply known reverse transitions when going backward. +# +# If you add a layer here that bumps SCHEMA_VERSION, ALSO add the reverse SQL +# case to `apply_downgrade_step()` in scripts/tooling/hapi-driver-db-prep.sh +# in this repo. Without that, swinging active away from this layer later will +# abort the activation cleanly but block until you write the SQL. +# +# See docs/tooling/driver-soup.md "DB schema jiu-jitsu" for the full flow. base: upstream/main diff --git a/docs/tooling/new-feature-intake.md b/docs/tooling/new-feature-intake.md index bd480942f17..34532729288 100644 --- a/docs/tooling/new-feature-intake.md +++ b/docs/tooling/new-feature-intake.md @@ -186,7 +186,8 @@ Document port, `HAPI_HOME`, and branch in the handoff message. 1. **`bun typecheck`** and **`bun run test`** (and `cd web && bun run test` if web touched) 2. **Cold code review** — full diff vs `upstream/main`; use [cold-pr-review-rubric.md](./cold-pr-review-rubric.md); fix Blocker/Major before handoff -3. **Playwright smoke** — real browser, demo URL, auth token from operator env: +3. **DB schema check** — if your branch bumps `SCHEMA_VERSION` in `hub/src/store/index.ts` (i.e. adds a `migrateFromVxToVy()` step), you MUST also add the reverse-SQL case to `apply_downgrade_step()` in [`scripts/tooling/hapi-driver-db-prep.sh`](../../scripts/tooling/hapi-driver-db-prep.sh). Without this, swinging `hapi-active` away from your layer later (back to upstream, or to a soup without it) aborts the activation cleanly but blocks until someone writes the SQL. See [driver-soup.md "DB schema jiu-jitsu"](./driver-soup.md#db-schema-jiu-jitsu-auto-handled-2026-06-01). +4. **Playwright smoke** — real browser, demo URL, auth token from operator env: ```bash # Linux: bundled Chromium may hang; prefer system Chrome @@ -203,7 +204,7 @@ Assert: no `QuotaExceededError` / error-boundary strings in console; `failedRequ Optional feature-specific repro scripts live under `scripts/dev/*-playwright.mjs`. -Only after (1)-(3): send operator **links**, **what to click**, and **screenshot path**. +Only after (1)-(4): send operator **links**, **what to click**, and **screenshot path**. ### 7 — Operator dogfood From 5f261a11ec2cac71319a54528e1001802f8df775 Mon Sep 17 00:00:00 2001 From: HeavyGee <133152184+heavygee@users.noreply.github.com> Date: Mon, 1 Jun 2026 21:51:56 +0100 Subject: [PATCH 0024/1600] tooling: driver-stack coordination - flock + status file + read CLI Problem ~30 agents on this repo can race on hapi-driver-rebuild or hapi-use-worktree. The driver tree is documented READ-ONLY between rebuilds with no enforcement, the active symlink can be swung while another switch is mid-restart, and agents had no way to ask "is someone already doing this?" beyond pgrep + stat. Observed live: one agent pinging another via session-id message to coordinate a rebuild by hand. What changed - lib/driver-status.sh (new): sourceable bash lib. flock-based mutual exclusion per operation (rebuild | switch), atomic-rewrite JSON status at ~/.hapi/driver-status.json (schema v1), begin/end/set helpers, stale-pid detection. EX_TEMPFAIL=75 when contended. - hapi-driver-rebuild.sh: acquires rebuild lock, writes start/exit status (incl. head_sha, head_subject, manifest_layer_count). On --activate, hands off cleanly to hapi-use-worktree (closes lock FD before exec so the switch script owns its own lock). - hapi-use-worktree.sh: acquires switch lock, records from/to + exit code. - hapi-driver-status.sh + ~/.local/bin symlink (new): read CLI. Human summary, --json, --quiet (exit 0/75/2 for idle/busy/stale), --watch. Surfaces age, pid liveness, head sha, layer count, what hapi-active points at, and how long since it was last swung. Discoverability Cursor alwaysApply rule + tooling doc updated with the precheck recipe and a note on why this lives in a file (the hub may be down precisely when status matters most). Escape hatches HAPI_SKIP_DRIVER_LOCK=1 bypass (testing only) Stale pid: CLI prints exact rm + auto-heals on next run. Tested Idle baseline / running detected / collision exits 75 / completion records head sha + subject / stale pid detected and reported. Co-authored-by: Cursor --- .cursor/rules/operator-fork.mdc | 1 + docs/operator/AGENTS.md | 2 +- docs/tooling/driver-soup.md | 32 ++++ scripts/tooling/hapi-driver-rebuild.sh | 28 +++ scripts/tooling/hapi-driver-status.sh | 166 +++++++++++++++++ scripts/tooling/hapi-use-worktree.sh | 14 ++ scripts/tooling/lib/driver-status.sh | 237 +++++++++++++++++++++++++ 7 files changed, 479 insertions(+), 1 deletion(-) create mode 100755 scripts/tooling/hapi-driver-status.sh create mode 100755 scripts/tooling/lib/driver-status.sh diff --git a/.cursor/rules/operator-fork.mdc b/.cursor/rules/operator-fork.mdc index 089e75c124f..b8bfd549a6d 100644 --- a/.cursor/rules/operator-fork.mdc +++ b/.cursor/rules/operator-fork.mdc @@ -11,5 +11,6 @@ This repo is a **fork** of `tiann/hapi`. Root **`AGENTS.md` is intentionally abs - **New functionality requests:** also read `docs/tooling/new-feature-intake.md`. Orchestrator spawns feature peers with explicit **done vs owned** intake steps (§0 handoff block). - **Workspace** = `~/coding/hapi` (mirror). **`hapi-driver`** = runtime on `:3006` via `hapi-active` — not the default instruction root. +- **Before any `hapi-driver-rebuild` or `hapi-use-worktree`:** run `hapi-driver-status --quiet` (exit 0 idle, 75 busy, 2 stale). The scripts auto-flock, but the precheck avoids 30-agent collisions on the stack. See `docs/tooling/driver-soup.md#coordination-avoid-stack-switch-contention`. - Upstream PR branches: from `upstream/main` only; never include `docs/operator/`, `docs/plans/`, or root `AGENTS.md` body in the PR diff. - Plans: `docs/plans/`. diff --git a/docs/operator/AGENTS.md b/docs/operator/AGENTS.md index 9f3777bd9af..f4c48043686 100644 --- a/docs/operator/AGENTS.md +++ b/docs/operator/AGENTS.md @@ -49,7 +49,7 @@ ElevenLabs ConvAI today: handoff OK, readback weak, payment, no mode machine. Ta |-----|---------| | **`docs/operator/AGENTS.md`** | This file (fork agent canon) | | [`docs/tooling/new-feature-intake.md`](../tooling/new-feature-intake.md) | **New behavior requests** — discovery, spawn handoff, soup vs clean, gates before operator test | -| `docs/tooling/driver-soup.md` | Daily driver manifest, `hapi-active`, worktrees | +| `docs/tooling/driver-soup.md` | Daily driver manifest, `hapi-active`, worktrees, **coordination (`hapi-driver-status`) and DB jiu-jitsu** | | `docs/plans/*` | Integration plans, PR A-F; peer agent: `2026-05-30-peer-agent-offering.md` | | `docs/operator/xr/*` | **XR only (private):** work graph + mindmap visualization epic — start at `xr/work-graph-and-visualization.md` | | `docs/operator-local-tooling.md` | `localdocs/`, machine indexes | diff --git a/docs/tooling/driver-soup.md b/docs/tooling/driver-soup.md index 159f89db3d2..7dc2c392337 100644 --- a/docs/tooling/driver-soup.md +++ b/docs/tooling/driver-soup.md @@ -139,11 +139,43 @@ Garden shared mode (`garden-web.service` → `:5174` → API `:3006`) always tal | `hapi-use-worktree ` | Swing `hapi-active` + **prep DB** + restart hub + runner | | `hapi-use-driver` | Swing to daily driver soup | | `hapi-driver-db-prep ` | Backup DB + auto-downgrade schema to match ``'s SCHEMA_VERSION; called automatically by `hapi-use-worktree` | +| `hapi-driver-status [--json\|--quiet\|--watch]` | Read coordination state — is a rebuild/switch in flight, when did the last one finish, what is `hapi-active` pointing at | | `hapi-runner-from-active` | systemd helper — runner CLI from `hapi-active/cli` | | `hapi-sessions-health.sh` | Session monitor | Sources: `scripts/tooling/` in repo; installed to `~/.local/bin/`. +### Coordination (avoid stack-switch contention) + +With ~30 agents on this repo, two callers can land on `hapi-driver-rebuild` or `hapi-use-worktree` simultaneously — one rewrites the driver tree mid-merge while the other reads it, or two stack switches race on the symlink and hub restart. + +Both scripts now take a `flock` on `~/.hapi/locks/{rebuild,switch}.lock` and publish state to `~/.hapi/driver-status.json` (atomic rewrite, schema v1). A second concurrent invocation exits **75** (`EX_TEMPFAIL`) with a pointer at the first. + +**Before kicking off a rebuild or switch** (especially from a peer agent), run: + +```bash +hapi-driver-status # human summary +hapi-driver-status --quiet # exit 0 idle, 75 busy, 2 stale-pid +``` + +`--quiet` is the right thing for an agent precheck: + +```bash +if ! hapi-driver-status --quiet; then + echo "driver stack busy or stale -- inspect with hapi-driver-status" + exit 1 +fi +hapi-driver-rebuild --build-web --verify +``` + +**Stale state** (process died without releasing): `hapi-driver-status` prints `STALE pid=N (dead)` and the exact `rm` to clear the lock. The status file self-heals on the next successful run. + +**Bypass** (testing only): `HAPI_SKIP_DRIVER_LOCK=1`. Skips both flock and status writes; collisions corrupt the driver tree. + +**Why no hub API route?** The hub may be down *during* a switch — exactly when status is most wanted. File-backed status is readable when the hub is dead. + +--- + ### DB schema jiu-jitsu (auto-handled, 2026-06-01) The hub's SQLite store has **forward step-migrations only** (v1 -> v2 -> ... -> N). When the manifest changes the effective SCHEMA_VERSION, the live DB at `~/.hapi/hapi.db` must match the target tree before hub boot: diff --git a/scripts/tooling/hapi-driver-rebuild.sh b/scripts/tooling/hapi-driver-rebuild.sh index c30e17ae623..61c8c377052 100755 --- a/scripts/tooling/hapi-driver-rebuild.sh +++ b/scripts/tooling/hapi-driver-rebuild.sh @@ -19,6 +19,7 @@ PARSE="$PRIMARY/scripts/tooling/parse-driver-manifest.mjs" DRIVER_BRANCH="${HAPI_DRIVER_BRANCH:-driver/integration}" BUN="${BUN:-$HOME/.bun/bin/bun}" +ORIG_ARGS=("$@") BUILD_WEB=0 VERIFY=0 ACTIVATE=0 @@ -36,6 +37,19 @@ while [[ $# -gt 0 ]]; do esac done +# Concurrency guard + status reporting (see lib/driver-status.sh). +# Bypassable: HAPI_SKIP_DRIVER_LOCK=1 (testing only -- corrupts driver tree +# if two rebuilds collide). +LIB_DIR="$(dirname "$(readlink -f "$0")")/lib" +# shellcheck source=lib/driver-status.sh +source "$LIB_DIR/driver-status.sh" +if [[ "${HAPI_SKIP_DRIVER_LOCK:-}" != "1" ]]; then + driver_status_init + driver_status_acquire rebuild + driver_status_begin rebuild "${ORIG_ARGS[@]}" + trap 'driver_status_end rebuild "$?" head_sha="$(git -C "$DRIVER" rev-parse --short HEAD 2>/dev/null || echo unknown)" head_subject="$(git -C "$DRIVER" log -1 --format=%s 2>/dev/null || echo unknown)"' EXIT +fi + if [[ ! -f "$MANIFEST" ]]; then echo "ERROR: manifest not found: $MANIFEST" >&2 echo "Copy example: mkdir -p ~/.config/hapi && cp $PRIMARY/docs/tooling/driver-manifest.example.yaml $MANIFEST" >&2 @@ -87,6 +101,10 @@ manifest_json="$("$BUN" run "$PARSE" "$MANIFEST")" base_ref="$(echo "$manifest_json" | jq -r '.base')" layer_count="$(echo "$manifest_json" | jq '.layers | length')" +if [[ "${HAPI_SKIP_DRIVER_LOCK:-}" != "1" ]]; then + driver_status_set rebuild "manifest_layer_count=$layer_count" +fi + if echo "$manifest_json" | jq -e '.layers[] | select(.ref == "fix/web-scroll-guard-unwrap-race")' >/dev/null; then pr722_state="$(gh pr view 722 --repo "${HAPI_PR_REPO:-tiann/hapi}" --json state --jq '.state' 2>/dev/null || true)" if [[ "$pr722_state" == "MERGED" ]]; then @@ -176,6 +194,16 @@ if [[ "$ACTIVATE" -eq 1 ]]; then echo "Non-interactive: skipping activate (re-run with TTY or use hapi-use-worktree manually)." >&2 exit 0 fi + # Hand off to the switch script. The EXIT trap won't fire under exec, so + # close the rebuild as successful here (head_sha is known good) and let + # use-worktree own the switch lock + status from here on. + if [[ "${HAPI_SKIP_DRIVER_LOCK:-}" != "1" ]]; then + driver_status_end rebuild 0 \ + head_sha="$(git -C "$DRIVER" rev-parse --short HEAD 2>/dev/null || echo unknown)" \ + head_subject="$(git -C "$DRIVER" log -1 --format=%s 2>/dev/null || echo unknown)" + trap - EXIT + eval "exec ${_HAPI_LOCK_FD_REBUILD}>&-" + fi exec hapi-use-worktree "$DRIVER" fi diff --git a/scripts/tooling/hapi-driver-status.sh b/scripts/tooling/hapi-driver-status.sh new file mode 100755 index 00000000000..72690d3b3c2 --- /dev/null +++ b/scripts/tooling/hapi-driver-status.sh @@ -0,0 +1,166 @@ +#!/usr/bin/env bash +# hapi-driver-status -- read the driver-stack coordination state. +# +# Pretty-prints ~/.hapi/driver-status.json (written by hapi-driver-rebuild +# and hapi-use-worktree) so agents can answer: +# - is a rebuild or switch in progress right now? +# - if yes: by whom, since when, with what args? +# - if no: when did the last one finish, and what landed? +# - what is hapi-active pointing at, and when was it last swung? +# +# Usage: +# hapi-driver-status # human-readable summary +# hapi-driver-status --json # raw JSON for scripts +# hapi-driver-status --quiet # exit code only: 0 idle, 75 busy, 2 stale +# hapi-driver-status --watch # poll every 2s (Ctrl-C to stop) +# +# Exit codes +# 0 both rebuild + switch are idle +# 75 at least one operation is running (matches lib EX_TEMPFAIL convention) +# 2 one or more pids look stale (process dead, status not reset) +# 1 status file missing or unreadable + +set -euo pipefail + +STATUS_FILE="${HAPI_STATUS_FILE:-$HOME/.hapi/driver-status.json}" +MODE=human + +while [[ $# -gt 0 ]]; do + case "$1" in + --json) MODE=json; shift ;; + --quiet|-q) MODE=quiet; shift ;; + --watch|-w) MODE=watch; shift ;; + -h|--help) sed -n '2,20p' "$0"; exit 0 ;; + *) echo "Unknown flag: $1" >&2; exit 2 ;; + esac +done + +if [[ ! -f "$STATUS_FILE" ]]; then + echo "no driver-status file yet at $STATUS_FILE" >&2 + echo "(it appears after the first hapi-driver-rebuild or hapi-use-worktree)" >&2 + exit 1 +fi +command -v jq >/dev/null 2>&1 || { echo "jq required" >&2; exit 1; } + +humanize_age() { + local ts="$1" + [[ -z "$ts" || "$ts" == "null" ]] && { echo "(never)"; return; } + local epoch now diff + epoch="$(date -u -d "$ts" +%s 2>/dev/null || echo 0)" + now="$(date -u +%s)" + diff=$((now - epoch)) + (( diff < 0 )) && diff=0 + if (( diff < 60 )); then echo "${diff}s ago" + elif (( diff < 3600 )); then echo "$((diff/60))m $((diff%60))s ago" + elif (( diff < 86400)); then echo "$((diff/3600))h $((diff%3600/60))m ago" + else echo "$((diff/86400))d $((diff%86400/3600))h ago" + fi +} + +pid_alive() { + local pid="$1" + [[ "$pid" =~ ^[0-9]+$ ]] || return 1 + kill -0 "$pid" 2>/dev/null +} + +render_op() { + local op="$1" out + out="$(jq -r ".${op}" "$STATUS_FILE")" + local state pid started_at started_by completed_at exit_code args + state="$(echo "$out" | jq -r '.state // "?"')" + pid="$(echo "$out" | jq -r '.pid // "null"')" + started_at="$(echo "$out" | jq -r '.started_at // "null"')" + started_by="$(echo "$out" | jq -r '.started_by // "?"')" + completed_at="$(echo "$out" | jq -r '.completed_at // "null"')" + exit_code="$(echo "$out" | jq -r '.exit_code // "?"')" + args="$(echo "$out" | jq -r '.args // [] | join(" ")')" + + local label color reset + if [[ -t 1 ]]; then color="\033[1m"; reset="\033[0m"; else color=""; reset=""; fi + printf '%b%-8s%b ' "$color" "$op" "$reset" + + if [[ "$state" == "running" ]]; then + if pid_alive "$pid"; then + printf 'RUNNING pid=%s by=%s since=%s (%s)\n' \ + "$pid" "$started_by" "$started_at" "$(humanize_age "$started_at")" + [[ "$op" == "rebuild" && -n "$args" ]] && printf ' args: %s\n' "$args" + if [[ "$op" == "switch" ]]; then + local from to + from="$(echo "$out" | jq -r '.from // "?"')" + to="$(echo "$out" | jq -r '.to // "?"')" + printf ' %s -> %s\n' "$from" "$to" + fi + return 1 + else + printf 'STALE pid=%s (dead) recorded-start=%s by=%s\n' \ + "$pid" "$started_at" "$started_by" + printf ' crashed without releasing status. To clear:\n' + printf ' rm %s/locks/%s.lock\n' "${HAPI_STATE_DIR:-$HOME/.hapi}" "$op" + printf ' (status auto-resets on next run)\n' + return 2 + fi + fi + + printf 'idle last=%s (%s) exit=%s by=%s\n' \ + "$completed_at" "$(humanize_age "$completed_at")" "$exit_code" "$started_by" + if [[ "$op" == "rebuild" ]]; then + local sha subject layers + sha="$(echo "$out" | jq -r '.head_sha // "?"')" + subject="$(echo "$out" | jq -r '.head_subject // "?"')" + layers="$(echo "$out" | jq -r '.manifest_layer_count // "?"')" + printf ' head=%s "%s" layers=%s\n' "$sha" "$subject" "$layers" + elif [[ "$op" == "switch" ]]; then + local from to + from="$(echo "$out" | jq -r '.from // "?"')" + to="$(echo "$out" | jq -r '.to // "?"')" + printf ' last switch: %s -> %s\n' "$from" "$to" + fi + return 0 +} + +render_human() { + echo "=== hapi-driver-status ($STATUS_FILE) ===" + echo "" + + local rebuild_rc=0 switch_rc=0 + render_op rebuild || rebuild_rc=$? + echo "" + render_op switch || switch_rc=$? + echo "" + + local active_target is_driver mtime + active_target="$(jq -r '.active.target // "(no symlink)"' "$STATUS_FILE")" + is_driver="$(jq -r '.active.is_driver // false' "$STATUS_FILE")" + mtime="$(jq -r '.active.symlink_mtime // "null"' "$STATUS_FILE")" + local tag="DAILY DRIVER" + [[ "$is_driver" == "true" ]] || tag="FEATURE WORKTREE" + echo "active -> $active_target" + echo " [$tag] last swung $mtime ($(humanize_age "$mtime"))" + + # Aggregate exit code: 75 busy > 2 stale > 0 idle. + (( rebuild_rc == 1 || switch_rc == 1 )) && return 75 + (( rebuild_rc == 2 || switch_rc == 2 )) && return 2 + return 0 +} + +case "$MODE" in + json) + cat "$STATUS_FILE" + ;; + quiet) + render_human >/dev/null + exit $? + ;; + watch) + while true; do + clear + render_human || true + echo "" + echo "(refresh 2s, Ctrl-C to stop)" + sleep 2 + done + ;; + human) + render_human + ;; +esac diff --git a/scripts/tooling/hapi-use-worktree.sh b/scripts/tooling/hapi-use-worktree.sh index 04f2ecc5e00..cbbc06062cb 100755 --- a/scripts/tooling/hapi-use-worktree.sh +++ b/scripts/tooling/hapi-use-worktree.sh @@ -16,6 +16,20 @@ if [[ ! -d "$WORKTREE/hub" ]] || [[ ! -d "$WORKTREE/cli" ]]; then exit 1 fi +# Concurrency guard + status reporting (see lib/driver-status.sh). +# Bypassable: HAPI_SKIP_DRIVER_LOCK=1 (testing only). +LIB_DIR="$(dirname "$(readlink -f "$0")")/lib" +# shellcheck source=lib/driver-status.sh +source "$LIB_DIR/driver-status.sh" +if [[ "${HAPI_SKIP_DRIVER_LOCK:-}" != "1" ]]; then + driver_status_init + driver_status_acquire switch + PREV_ACTIVE="$(readlink -f "$ACTIVE_LINK" 2>/dev/null || echo unknown)" + driver_status_begin switch "$WORKTREE" + driver_status_set switch "from=$PREV_ACTIVE" "to=$WORKTREE" + trap 'driver_status_end switch "$?"' EXIT +fi + if [[ ! -e "$WORKTREE/hub/.env" ]]; then echo "Linking $HUB_ENV → $WORKTREE/hub/.env" ln -sfn "$HUB_ENV" "$WORKTREE/hub/.env" diff --git a/scripts/tooling/lib/driver-status.sh b/scripts/tooling/lib/driver-status.sh new file mode 100755 index 00000000000..60645dc7ea6 --- /dev/null +++ b/scripts/tooling/lib/driver-status.sh @@ -0,0 +1,237 @@ +#!/usr/bin/env bash +# driver-status.sh -- sourceable helpers for HAPI driver-stack coordination. +# +# Purpose +# Two scripts mutate the daily-driver stack: +# - hapi-driver-rebuild (rewrites ~/coding/hapi-driver from the manifest) +# - hapi-use-worktree (swings hapi-active + restarts hub + runner) +# With ~30 agents on this repo at once, parallel invocations corrupt the +# driver tree mid-merge or restart the hub mid-build. This lib gives both +# scripts: +# 1. flock-based mutual exclusion (per-operation lock) +# 2. a single JSON status file consumers can poll +# 3. start / end hooks that record state automatically +# +# Status file: ~/.hapi/driver-status.json (atomic rewrite, schema v1) +# { +# "schema": 1, +# "updated_at": "2026-06-01T20:45:00Z", +# "rebuild": { +# "state": "idle" | "running", +# "pid": null | , +# "started_at": "...Z" | null, +# "started_by": "operator" | "", +# "args": ["--build-web", ...], +# "completed_at": "...Z" | null, +# "exit_code": | null, +# "head_sha": "" | null, +# "head_subject": "" | null, +# "manifest_layer_count": | null +# }, +# "switch": { +# "state": "idle" | "running", +# "pid": null | , +# "started_at": "...Z" | null, +# "started_by": "operator" | "", +# "from": "/path" | null, +# "to": "/path" | null, +# "completed_at": "...Z" | null, +# "exit_code": | null +# }, +# "active": { +# "target": "/home/heavygee/coding/hapi-driver", +# "is_driver": true, +# "symlink_mtime": "...Z" +# } +# } +# +# Usage (from a wrapper script) +# source "$(dirname "$0")/lib/driver-status.sh" +# driver_status_init # ensure dirs + jq present +# driver_status_acquire rebuild # flock or fail loud +# driver_status_begin rebuild "$@" # write state=running +# trap 'driver_status_end rebuild "$?"' EXIT # record exit code +# ... rebuild work ... +# +# Override env (test-only) +# HAPI_STATE_DIR default ~/.hapi +# HAPI_LOCK_DIR default $HAPI_STATE_DIR/locks +# HAPI_STATUS_FILE default $HAPI_STATE_DIR/driver-status.json +# HAPI_AGENT_LABEL identifier written into started_by (default "operator") + +HAPI_STATE_DIR="${HAPI_STATE_DIR:-$HOME/.hapi}" +HAPI_LOCK_DIR="${HAPI_LOCK_DIR:-$HAPI_STATE_DIR/locks}" +HAPI_STATUS_FILE="${HAPI_STATUS_FILE:-$HAPI_STATE_DIR/driver-status.json}" +HAPI_AGENT_LABEL="${HAPI_AGENT_LABEL:-operator}" + +# FD numbers for the two operation locks. High enough to avoid stomping on +# anything the caller is using. +_HAPI_LOCK_FD_REBUILD=201 +_HAPI_LOCK_FD_SWITCH=202 + +driver_status_init() { + mkdir -p "$HAPI_STATE_DIR" "$HAPI_LOCK_DIR" + if ! command -v jq >/dev/null 2>&1; then + echo "ERROR: jq required for driver-status (apt install jq)" >&2 + return 1 + fi + if [[ ! -f "$HAPI_STATUS_FILE" ]]; then + _driver_status_write_initial + fi +} + +_driver_status_now() { date -u +%Y-%m-%dT%H:%M:%SZ; } + +_driver_status_active_block() { + local active_link="$HOME/coding/hapi-active" + local target="null" is_driver=false mtime="null" mtime_epoch + if [[ -L "$active_link" ]]; then + target="\"$(readlink -f "$active_link")\"" + if [[ "$(readlink -f "$active_link")" == "$(readlink -f "$HOME/coding/hapi-driver" 2>/dev/null || echo /nope)" ]]; then + is_driver=true + fi + # stat the symlink itself (not the target) -- this is the swing time. + mtime_epoch="$(stat -c '%Y' "$active_link" 2>/dev/null || echo 0)" + if [[ "$mtime_epoch" =~ ^[0-9]+$ ]] && (( mtime_epoch > 0 )); then + mtime="\"$(date -u -d "@$mtime_epoch" +%Y-%m-%dT%H:%M:%SZ)\"" + fi + fi + printf '{"target":%s,"is_driver":%s,"symlink_mtime":%s}' \ + "$target" "$is_driver" "$mtime" +} + +_driver_status_write_initial() { + local tmp + tmp="$(mktemp -p "$HAPI_STATE_DIR" .driver-status.XXXXXX.json)" + cat > "$tmp" < +# Hard-fails (exits caller with code 75 EX_TEMPFAIL) if the lock is held. +# We use exit 75 rather than 1 so callers/CI can distinguish "busy" from +# "real failure". +driver_status_acquire() { + local op="$1" fd lockfile other_pid other_started other_who + case "$op" in + rebuild) fd=$_HAPI_LOCK_FD_REBUILD; lockfile="$HAPI_LOCK_DIR/rebuild.lock" ;; + switch) fd=$_HAPI_LOCK_FD_SWITCH; lockfile="$HAPI_LOCK_DIR/switch.lock" ;; + *) echo "driver_status_acquire: unknown op '$op'" >&2; exit 2 ;; + esac + eval "exec $fd>\"$lockfile\"" + if ! flock -n "$fd"; then + echo "ERROR: hapi-$op already in progress. Inspect: hapi-driver-status" >&2 + if [[ -f "$HAPI_STATUS_FILE" ]] && command -v jq >/dev/null 2>&1; then + other_pid="$(jq -r ".${op}.pid // \"?\"" "$HAPI_STATUS_FILE")" + other_started="$(jq -r ".${op}.started_at // \"?\"" "$HAPI_STATUS_FILE")" + other_who="$(jq -r ".${op}.started_by // \"?\"" "$HAPI_STATUS_FILE")" + echo " pid=$other_pid started_at=$other_started by=$other_who" >&2 + if [[ "$other_pid" =~ ^[0-9]+$ ]] && ! kill -0 "$other_pid" 2>/dev/null; then + echo " NOTE: pid $other_pid is dead -- prior run crashed without releasing status." >&2 + echo " Remove stale lock: rm $lockfile (status will self-heal on next run)" >&2 + fi + fi + exit 75 + fi +} + +# driver_status_begin [args...] +driver_status_begin() { + local op="$1"; shift + local args_json now + now="$(_driver_status_now)" + if (( $# == 0 )); then + args_json='[]' + else + args_json="$(printf '%s\n' "$@" | jq -R . | jq -s .)" + fi + _driver_status_jq_update " + .updated_at = \"$now\" | + .${op}.state = \"running\" | + .${op}.pid = $$ | + .${op}.started_at = \"$now\" | + .${op}.started_by = \"$HAPI_AGENT_LABEL\" | + .${op}.completed_at = null | + .${op}.exit_code = null | + .${op}.args = $args_json | + .active = $(_driver_status_active_block) + " +} + +# driver_status_end [key=value ...] +# Extra k=v pairs are merged as strings into the op block (e.g. head_sha=abc123). +driver_status_end() { + local op="$1" exit_code="$2"; shift 2 || true + local now extra="" k v + now="$(_driver_status_now)" + for kv in "$@"; do + k="${kv%%=*}" + v="${kv#*=}" + if [[ "$v" =~ ^[0-9]+$ ]]; then + extra+=" | .${op}.${k} = ${v}" + else + extra+=" | .${op}.${k} = \"$(printf '%s' "$v" | sed 's/\\/\\\\/g;s/"/\\"/g')\"" + fi + done + _driver_status_jq_update " + .updated_at = \"$now\" | + .${op}.state = \"idle\" | + .${op}.pid = null | + .${op}.completed_at = \"$now\" | + .${op}.exit_code = ${exit_code} + ${extra} | + .active = $(_driver_status_active_block) + " || true +} + +# driver_status_set key=value [key=value ...] (mid-run mutation) +driver_status_set() { + local op="$1"; shift + local extra="" k v + for kv in "$@"; do + k="${kv%%=*}" + v="${kv#*=}" + if [[ "$v" =~ ^[0-9]+$ ]]; then + extra+=" | .${op}.${k} = ${v}" + else + extra+=" | .${op}.${k} = \"$(printf '%s' "$v" | sed 's/\\/\\\\/g;s/"/\\"/g')\"" + fi + done + _driver_status_jq_update " + .updated_at = \"$(_driver_status_now)\" + ${extra} | + .active = $(_driver_status_active_block) + " || true +} + +_driver_status_jq_update() { + local expr="$1" tmp + [[ -f "$HAPI_STATUS_FILE" ]] || _driver_status_write_initial + tmp="$(mktemp -p "$HAPI_STATE_DIR" .driver-status.XXXXXX.json)" + if jq "$expr" "$HAPI_STATUS_FILE" > "$tmp" 2>/dev/null; then + mv "$tmp" "$HAPI_STATUS_FILE" + else + rm -f "$tmp" + echo "WARN: driver-status JSON update failed (jq)" >&2 + return 1 + fi +} From 212ce0ef2aff4d6e4bd07403ab4822143bb5374c Mon Sep 17 00:00:00 2001 From: HeavyGee <133152184+heavygee@users.noreply.github.com> Date: Mon, 1 Jun 2026 22:06:01 +0100 Subject: [PATCH 0025/1600] tooling: patient hub restart - wire orphan drain into the switch path Problem Operator hit a session mid-turn that got yanked. Investigation: 1. hapi-patient-stack-restart.sh exists (added today by another agent) but has ZERO callers - pure orphan. 2. hapi-use-worktree.sh does naive systemctl stop -> DB prep -> start with no drain. 3. The interruption-causing restarts were raw `sudo systemctl restart hapi-hub.service` bypassing even the canonical path. Two such events in the last hour while the prior coordination commit was being written. What changed - hapi-use-worktree.sh: patient by default. After acquiring the switch lock and before stopping the hub, polls hapi-sessions-health.sh for WORKING sessions. Waits up to HAPI_PATIENT_TIMEOUT (600s default), poll cadence HAPI_PATIENT_INTERVAL (30s). Times out cleanly and logs who's still WORKING before proceeding (not a silent yank). Opt-out: --impatient or HAPI_IMPATIENT=1 for hung-hub emergencies. - hapi-restart-hub.sh + ~/.local/bin symlink (new): bare hub bounce with the same patient drain. For "I need to restart the hub but not switch stacks" cases - the path that has historically been served by raw systemctl. Same lock as hapi-use-worktree (switch lock) so the two can't race. --no-runner to skip the runner. - hapi-driver-status: new "working" line showing WORKING session count + warning to use hapi-restart-hub when >0. - Cursor alwaysApply rule: explicit "NEVER systemctl restart hapi-hub directly, use hapi-restart-hub" line. - driver-soup.md: "Patient restarts" section with the bypass matrix and the "never do / always do" pair. The orphan hapi-patient-stack-restart.sh is left in place as documentation / reference implementation but is not on the path. The wrappers above inline the same drain logic so the patient behavior is colocated with the operation that needs it. Known limitation hapi-sessions-health --json returns id:null/tag:null for WORKING entries (count is correct, used by drain). Filed as plan doc 2026-06-01-sessions-health-null-id-tag.md. Until fixed, the drain timeout log line will name offenders as "id=? tag=?". Functional drain works regardless. Tested --impatient skips drain / lint clean / live render shows WORKING=2 with the warning line / wrappers don't race (same lock). Co-authored-by: Cursor --- .cursor/rules/operator-fork.mdc | 1 + .../2026-06-01-sessions-health-null-id-tag.md | 51 +++++++++ docs/tooling/driver-soup.md | 39 ++++++- scripts/tooling/hapi-driver-status.sh | 20 ++++ scripts/tooling/hapi-restart-hub.sh | 106 ++++++++++++++++++ scripts/tooling/hapi-use-worktree.sh | 74 +++++++++++- 6 files changed, 284 insertions(+), 7 deletions(-) create mode 100644 docs/plans/2026-06-01-sessions-health-null-id-tag.md create mode 100755 scripts/tooling/hapi-restart-hub.sh diff --git a/.cursor/rules/operator-fork.mdc b/.cursor/rules/operator-fork.mdc index b8bfd549a6d..1733d614b76 100644 --- a/.cursor/rules/operator-fork.mdc +++ b/.cursor/rules/operator-fork.mdc @@ -12,5 +12,6 @@ This repo is a **fork** of `tiann/hapi`. Root **`AGENTS.md` is intentionally abs - **New functionality requests:** also read `docs/tooling/new-feature-intake.md`. Orchestrator spawns feature peers with explicit **done vs owned** intake steps (§0 handoff block). - **Workspace** = `~/coding/hapi` (mirror). **`hapi-driver`** = runtime on `:3006` via `hapi-active` — not the default instruction root. - **Before any `hapi-driver-rebuild` or `hapi-use-worktree`:** run `hapi-driver-status --quiet` (exit 0 idle, 75 busy, 2 stale). The scripts auto-flock, but the precheck avoids 30-agent collisions on the stack. See `docs/tooling/driver-soup.md#coordination-avoid-stack-switch-contention`. +- **NEVER `sudo systemctl restart hapi-hub.service`** (or `... hapi-hub.service hapi-runner.service`). It yanks WORKING agents mid-turn. Use **`hapi-restart-hub`** (patient drain, 10min timeout, `--impatient` for hung-hub emergencies). For stack switches use `hapi-use-worktree` (same patient default). See `docs/tooling/driver-soup.md#patient-restarts-dont-yank-live-agents`. - Upstream PR branches: from `upstream/main` only; never include `docs/operator/`, `docs/plans/`, or root `AGENTS.md` body in the PR diff. - Plans: `docs/plans/`. diff --git a/docs/plans/2026-06-01-sessions-health-null-id-tag.md b/docs/plans/2026-06-01-sessions-health-null-id-tag.md new file mode 100644 index 00000000000..d5f69194987 --- /dev/null +++ b/docs/plans/2026-06-01-sessions-health-null-id-tag.md @@ -0,0 +1,51 @@ +# Plan: hapi-sessions-health --json returns null id/tag for WORKING entries + +**Status:** open, low priority +**Filed:** 2026-06-01 22:00 UTC +**Found by:** patient-restart wiring (commit pending) + +## Symptom + +```bash +$ scripts/hapi-sessions-health.sh --json \ + | jq '.sessions[] | select(.status == "WORKING")' +{ "id": null, "tag": null, "status": "WORKING", "last_seen_ms_ago": null } +{ "id": null, "tag": null, "status": "WORKING", "last_seen_ms_ago": null } +``` + +Count is correct (2 WORKING sessions exist), but every `WORKING` entry comes +back with `id: null`, `tag: null`, `last_seen_ms_ago: null`. Non-WORKING +entries presumably (untested) come back populated. + +## Why it matters + +`hapi-restart-hub` and `hapi-use-worktree` patient-drain block on the count +which is correct, so functionality is intact. But when the drain timeout +fires, they want to log *who* is still WORKING — that log line is currently +useless ("still WORKING: id=? tag=?"). Same with `hapi-driver-status`'s +WORKING summary. + +## Where to look + +- `scripts/hapi-sessions-health.sh` (51KB bash) — see whatever JSON-shaping + block emits the `.sessions[]` array. The status branch likely strips + identifying fields for the WORKING case (cargo-culted ETag privacy? + short-circuit on hub poll timeout?). +- Hub API: confirm `GET /api/sessions` actually returns id+tag for sessions + it considers WORKING. If hub omits them server-side that's the real bug. + +## Fix sketch (not yet) + +1. Decide: are id/tag deliberately omitted (privacy/auth-token leakage + risk) or accidentally dropped? If deliberate, surface a redacted hash + instead so operators still know *who* (matched against `hapi-driver-status`). +2. If accidental: probably one missing field assignment in the WORKING + branch of the JSON shaper. +3. Test by triggering a patient drain timeout and confirming the log line + names the offenders. + +## Workaround until then + +Cross-reference `hapi-driver-status` WORKING count against the hub UI at +`https://hapi.tail9944ee.ts.net/sessions` — anything marked WORKING in the +UI matches the count from the health script. diff --git a/docs/tooling/driver-soup.md b/docs/tooling/driver-soup.md index 7dc2c392337..a6e89453c13 100644 --- a/docs/tooling/driver-soup.md +++ b/docs/tooling/driver-soup.md @@ -136,10 +136,11 @@ Garden shared mode (`garden-web.service` → `:5174` → API `:3006`) always tal |---------|---------| | `hapi-driver-rebuild` | Rebuild soup from manifest | | `hapi-worktree-create` | New PR worktree (+ merge train) | -| `hapi-use-worktree ` | Swing `hapi-active` + **prep DB** + restart hub + runner | -| `hapi-use-driver` | Swing to daily driver soup | +| `hapi-use-worktree [--impatient]` | **Patient by default** — drain WORKING sessions, swing `hapi-active`, prep DB, restart hub + runner | +| `hapi-use-driver` | Swing to daily driver soup (inherits patient default) | +| `hapi-restart-hub [--impatient] [--no-runner]` | **Patient hub bounce** — drain WORKING sessions, then `systemctl restart`. Use INSTEAD of raw `sudo systemctl restart hapi-hub.service` | | `hapi-driver-db-prep ` | Backup DB + auto-downgrade schema to match ``'s SCHEMA_VERSION; called automatically by `hapi-use-worktree` | -| `hapi-driver-status [--json\|--quiet\|--watch]` | Read coordination state — is a rebuild/switch in flight, when did the last one finish, what is `hapi-active` pointing at | +| `hapi-driver-status [--json\|--quiet\|--watch]` | Read coordination state — is a rebuild/switch in flight, when did the last one finish, how many WORKING sessions right now | | `hapi-runner-from-active` | systemd helper — runner CLI from `hapi-active/cli` | | `hapi-sessions-health.sh` | Session monitor | @@ -174,6 +175,38 @@ hapi-driver-rebuild --build-web --verify **Why no hub API route?** The hub may be down *during* a switch — exactly when status is most wanted. File-backed status is readable when the hub is dead. +### Patient restarts (don't yank live agents) + +`hapi-use-worktree` and `hapi-restart-hub` are **patient by default**: they poll `hapi-sessions-health.sh` for `WORKING` sessions and wait (default 30s poll, 10min timeout) before tearing the hub down. The timeout is a safety valve — a stuck agent that never finishes WORKING shouldn't deadlock the whole stack — but normal turns will complete and the restart proceeds cleanly. + +**Never do this:** + +```bash +sudo systemctl restart hapi-hub.service # kills mid-turn agents +sudo systemctl restart hapi-hub.service hapi-runner.service +``` + +**Always do this:** + +```bash +hapi-restart-hub # bounce hub + runner, patient +hapi-restart-hub --no-runner # bounce hub only +hapi-use-worktree # stack switch, patient +``` + +**Tuning:** + +| Env / flag | Default | Effect | +|-----------|---------|--------| +| `--impatient` | off | Skip drain. Restart now. Use when the hub is hung. | +| `HAPI_IMPATIENT=1` | off | Same, via env. For non-interactive watchdogs. | +| `HAPI_PATIENT_TIMEOUT=` | 600 | Max drain wait before proceeding with WORKING>0. `0` = wait forever (deadlock risk). | +| `HAPI_PATIENT_INTERVAL=` | 30 | Poll cadence. | + +If the timeout fires, both wrappers log which sessions were still WORKING before proceeding — that's the signal an operator wants to see, not a silent yank. + +**Known gap:** the underlying `hapi-sessions-health.sh --json` returns `id: null, tag: null` for WORKING entries (only the count is right). The drain still works (it acts on count), and `hapi-driver-status` shows the count, but identifying *who* is still working requires a separate read against the hub. Filed as a follow-up. + --- ### DB schema jiu-jitsu (auto-handled, 2026-06-01) diff --git a/scripts/tooling/hapi-driver-status.sh b/scripts/tooling/hapi-driver-status.sh index 72690d3b3c2..9d4e0324dcd 100755 --- a/scripts/tooling/hapi-driver-status.sh +++ b/scripts/tooling/hapi-driver-status.sh @@ -118,6 +118,24 @@ render_op() { return 0 } +render_working() { + local health="${HAPI_SESSIONS_HEALTH:-$HOME/coding/hapi/scripts/hapi-sessions-health.sh}" + if [[ ! -x "$health" ]]; then + echo "working (health script not available)" + return 0 + fi + local count + count="$("$health" --json 2>/dev/null | jq -r '[.sessions[]? | select(.status == "WORKING")] | length' 2>/dev/null || echo 0)" + if [[ "$count" == "0" ]]; then + echo "working WORKING=0 (safe to restart hub without --impatient)" + else + echo "working WORKING=$count (a restart will yank these unless you wait or use hapi-restart-hub)" + local color="" reset="" + [[ -t 1 ]] && { color="\033[33m"; reset="\033[0m"; } + printf ' %busage: hapi-restart-hub (patient by default, 10min timeout)%b\n' "$color" "$reset" + fi +} + render_human() { echo "=== hapi-driver-status ($STATUS_FILE) ===" echo "" @@ -136,6 +154,8 @@ render_human() { [[ "$is_driver" == "true" ]] || tag="FEATURE WORKTREE" echo "active -> $active_target" echo " [$tag] last swung $mtime ($(humanize_age "$mtime"))" + echo "" + render_working # Aggregate exit code: 75 busy > 2 stale > 0 idle. (( rebuild_rc == 1 || switch_rc == 1 )) && return 75 diff --git a/scripts/tooling/hapi-restart-hub.sh b/scripts/tooling/hapi-restart-hub.sh new file mode 100755 index 00000000000..d114d42d25d --- /dev/null +++ b/scripts/tooling/hapi-restart-hub.sh @@ -0,0 +1,106 @@ +#!/usr/bin/env bash +# hapi-restart-hub [--impatient] [--no-runner] +# +# Patient restart of hapi-hub.service (and hapi-runner.service unless +# --no-runner). Does NOT change hapi-active, does NOT touch the DB, does +# NOT rebuild the driver. Use this when you need to bounce the hub +# (env change, hung process, stuck websocket) but stay on the current +# stack. +# +# Why this exists +# Raw `sudo systemctl restart hapi-hub.service` yanks the hub +# regardless of who's mid-turn. That has been the dominant interruption +# pattern. This wrapper polls WORKING sessions, waits up to +# HAPI_PATIENT_TIMEOUT seconds (default 600s = 10 min), then restarts. +# +# Bypass +# --impatient restart immediately, kill live sessions +# HAPI_IMPATIENT=1 same, via env (for scripts / watchdogs) +# +# Coordination +# Takes the same "switch" flock as hapi-use-worktree so a stack switch +# and a hub bounce don't race. Exits 75 if another switch is in flight. +# Inspect: hapi-driver-status + +set -euo pipefail + +IMPATIENT=0 +RUNNER=1 + +while [[ $# -gt 0 ]]; do + case "$1" in + --impatient) IMPATIENT=1; shift ;; + --no-runner) RUNNER=0; shift ;; + -h|--help) sed -n '2,24p' "$0"; exit 0 ;; + *) echo "Unknown flag: $1" >&2; exit 2 ;; + esac +done +[[ "${HAPI_IMPATIENT:-}" == "1" ]] && IMPATIENT=1 + +PRIMARY="${HAPI_PRIMARY:-$HOME/coding/hapi}" +PATIENT_TIMEOUT="${HAPI_PATIENT_TIMEOUT:-600}" +PATIENT_INTERVAL="${HAPI_PATIENT_INTERVAL:-30}" +HEALTH_SCRIPT="${HAPI_SESSIONS_HEALTH:-$PRIMARY/scripts/hapi-sessions-health.sh}" + +SCRIPT_DIR="$(dirname "$(readlink -f "$0")")" +# shellcheck source=lib/driver-status.sh +source "$SCRIPT_DIR/lib/driver-status.sh" + +if [[ "${HAPI_SKIP_DRIVER_LOCK:-}" != "1" ]]; then + driver_status_init + driver_status_acquire switch + ACTIVE_NOW="$(readlink -f "$HOME/coding/hapi-active" 2>/dev/null || echo unknown)" + driver_status_begin switch "$ACTIVE_NOW" + driver_status_set switch "from=$ACTIVE_NOW" "to=$ACTIVE_NOW" + trap 'driver_status_end switch "$?"' EXIT +fi + +patient_drain() { + [[ "$IMPATIENT" -eq 1 ]] && { echo "patient: skipped (--impatient)"; return 0; } + if [[ ! -x "$HEALTH_SCRIPT" ]]; then + echo "patient: WARN $HEALTH_SCRIPT not executable -- skipping drain" >&2 + return 0 + fi + local working start elapsed + working="$("$HEALTH_SCRIPT" --json 2>/dev/null | jq -r '[.sessions[]? | select(.status == "WORKING")] | length' 2>/dev/null || echo 0)" + [[ "$working" -eq 0 ]] && { echo "patient: WORKING=0, no drain needed"; return 0; } + echo "patient: WORKING=$working sessions in flight; waiting up to ${PATIENT_TIMEOUT}s (poll ${PATIENT_INTERVAL}s)" + echo "patient: bypass with --impatient or HAPI_IMPATIENT=1" + start=$SECONDS + while [[ "$working" -gt 0 ]]; do + elapsed=$((SECONDS - start)) + if [[ "$PATIENT_TIMEOUT" -gt 0 && "$elapsed" -ge "$PATIENT_TIMEOUT" ]]; then + echo "patient: TIMEOUT after ${elapsed}s with WORKING=$working -- proceeding anyway" >&2 + "$HEALTH_SCRIPT" --json 2>/dev/null | jq -r '.sessions[]? | select(.status == "WORKING") | " still WORKING: id=\(.id // "?") tag=\(.tag // "?")"' >&2 || true + return 0 + fi + echo " $(date '+%H:%M:%S') WORKING=$working elapsed=${elapsed}s budget=${PATIENT_TIMEOUT}s" + sleep "$PATIENT_INTERVAL" + working="$("$HEALTH_SCRIPT" --json 2>/dev/null | jq -r '[.sessions[]? | select(.status == "WORKING")] | length' 2>/dev/null || echo 0)" + done + echo "patient: WORKING=0 after $((SECONDS - start))s -- proceeding" +} + +echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━" +if [[ "$IMPATIENT" -eq 1 ]]; then + echo " HUB RESTART (IMPATIENT) — kills live agent sessions NOW" +else + echo " HUB RESTART — patient drain, then restart" +fi +echo " Stack: $(readlink -f "$HOME/coding/hapi-active" 2>/dev/null || echo unknown)" +echo " Services: hapi-hub.service$([[ "$RUNNER" -eq 1 ]] && echo ' + hapi-runner.service')" +echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━" + +patient_drain + +if [[ "$RUNNER" -eq 1 ]]; then + echo "Restarting hapi-hub + hapi-runner ..." + sudo systemctl restart hapi-hub.service hapi-runner.service +else + echo "Restarting hapi-hub ..." + sudo systemctl restart hapi-hub.service +fi + +echo "" +echo " hub: $(systemctl is-active hapi-hub.service)" +[[ "$RUNNER" -eq 1 ]] && echo " runner: $(systemctl is-active hapi-runner.service)" diff --git a/scripts/tooling/hapi-use-worktree.sh b/scripts/tooling/hapi-use-worktree.sh index cbbc06062cb..bdbf8297a2a 100755 --- a/scripts/tooling/hapi-use-worktree.sh +++ b/scripts/tooling/hapi-use-worktree.sh @@ -1,21 +1,80 @@ #!/usr/bin/env bash -# hapi-use-worktree +# hapi-use-worktree [--impatient] # Swings hapi-active and restarts hub + runner together from that tree. +# +# Patient by default: waits for WORKING sessions to finish (poll every 30s) +# before tearing the hub down. Times out after HAPI_PATIENT_TIMEOUT seconds +# (default 600 = 10 min) and logs who's still WORKING before proceeding. +# +# Bypass: +# --impatient yank the hub immediately, kill live sessions +# HAPI_IMPATIENT=1 same, via env (for non-interactive callers) set -euo pipefail -WORKTREE="${1:?Usage: hapi-use-worktree }" +IMPATIENT=0 +WORKTREE="" + +while [[ $# -gt 0 ]]; do + case "$1" in + --impatient) IMPATIENT=1; shift ;; + -h|--help) sed -n '2,12p' "$0"; exit 0 ;; + -*) echo "Unknown flag: $1" >&2; exit 2 ;; + *) + if [[ -z "$WORKTREE" ]]; then WORKTREE="$1"; shift + else echo "Unexpected arg: $1" >&2; exit 2; fi + ;; + esac +done + +[[ -n "$WORKTREE" ]] || { echo "Usage: hapi-use-worktree [--impatient]" >&2; exit 2; } +[[ "${HAPI_IMPATIENT:-}" == "1" ]] && IMPATIENT=1 + WORKTREE="$(realpath "$WORKTREE")" ACTIVE_LINK="${HAPI_ACTIVE_LINK:-$HOME/coding/hapi-active}" HUB_ENV="${HAPI_HUB_ENV:-$HOME/.hapi/hub.env}" BUN="${BUN:-$HOME/.bun/bin/bun}" DRIVER="${HAPI_DRIVER:-$HOME/coding/hapi-driver}" +PATIENT_TIMEOUT="${HAPI_PATIENT_TIMEOUT:-600}" +PATIENT_INTERVAL="${HAPI_PATIENT_INTERVAL:-30}" +SCRIPT_DIR="$(dirname "$(readlink -f "$0")")" +HEALTH_SCRIPT="${HAPI_SESSIONS_HEALTH:-$SCRIPT_DIR/../hapi-sessions-health.sh}" if [[ ! -d "$WORKTREE/hub" ]] || [[ ! -d "$WORKTREE/cli" ]]; then echo "ERROR: $WORKTREE must be a full HAPI worktree (hub/ + cli/)" >&2 exit 1 fi +# Patient drain: poll WORKING session count and wait until it reaches 0 (or +# we hit the timeout). The drain happens AFTER lock acquire (below) but +# BEFORE the systemctl stop, so a second patient caller is held by flock at +# the gate rather than draining in parallel. +patient_drain() { + [[ "$IMPATIENT" -eq 1 ]] && { echo "patient: skipped (--impatient)"; return 0; } + if [[ ! -x "$HEALTH_SCRIPT" ]]; then + echo "patient: WARN $HEALTH_SCRIPT not executable -- skipping drain" >&2 + return 0 + fi + local working start now elapsed + working="$("$HEALTH_SCRIPT" --json 2>/dev/null | jq -r '[.sessions[]? | select(.status == "WORKING")] | length' 2>/dev/null || echo 0)" + [[ "$working" -eq 0 ]] && { echo "patient: WORKING=0, no drain needed"; return 0; } + echo "patient: WORKING=$working sessions in flight; waiting up to ${PATIENT_TIMEOUT}s (poll ${PATIENT_INTERVAL}s)" + echo "patient: bypass next time with --impatient or HAPI_IMPATIENT=1" + start=$SECONDS + while [[ "$working" -gt 0 ]]; do + elapsed=$((SECONDS - start)) + if [[ "$PATIENT_TIMEOUT" -gt 0 && "$elapsed" -ge "$PATIENT_TIMEOUT" ]]; then + echo "patient: TIMEOUT after ${elapsed}s with WORKING=$working -- proceeding anyway" >&2 + "$HEALTH_SCRIPT" --json 2>/dev/null | jq -r '.sessions[]? | select(.status == "WORKING") | " still WORKING: id=\(.id // "?") tag=\(.tag // "?")"' >&2 || true + return 0 + fi + echo " $(date '+%H:%M:%S') WORKING=$working elapsed=${elapsed}s budget=${PATIENT_TIMEOUT}s" + sleep "$PATIENT_INTERVAL" + working="$("$HEALTH_SCRIPT" --json 2>/dev/null | jq -r '[.sessions[]? | select(.status == "WORKING")] | length' 2>/dev/null || echo 0)" + done + echo "patient: WORKING=0 after $((SECONDS - start))s -- proceeding" +} + # Concurrency guard + status reporting (see lib/driver-status.sh). # Bypassable: HAPI_SKIP_DRIVER_LOCK=1 (testing only). LIB_DIR="$(dirname "$(readlink -f "$0")")/lib" @@ -52,8 +111,11 @@ fi echo "" echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━" -echo " STACK SWITCH — kills live agent sessions" -echo " Restarts: hapi-hub.service + hapi-runner.service" +if [[ "$IMPATIENT" -eq 1 ]]; then + echo " STACK SWITCH (IMPATIENT) — kills live agent sessions NOW" +else + echo " STACK SWITCH — patient drain, then restart hub + runner" +fi echo " Target: $WORKTREE" echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━" if [[ -t 0 ]]; then @@ -64,6 +126,10 @@ elif [[ "${HAPI_STACK_SWITCH_YES:-}" != "1" ]]; then exit 1 fi +# Drain BEFORE we touch the symlink or stop the hub. We're inside the switch +# lock; second concurrent caller is blocked at the gate, not racing the drain. +patient_drain + echo "Pointing hapi-active → $WORKTREE" ln -sfn "$WORKTREE" "$ACTIVE_LINK" From b0cc7390c4e1b14a041439a9f50d644509e60b29 Mon Sep 17 00:00:00 2001 From: HeavyGee <133152184+heavygee@users.noreply.github.com> Date: Mon, 1 Jun 2026 23:47:35 +0100 Subject: [PATCH 0026/1600] tooling(operator): commit legacy chat attach + transcript backfill scripts These fork-only operator scripts have been recovered twice now from stash@{4} (wip-unrelated-before-driver-rebuild) after living as untracked files in scripts/. Promote them so git clean / driver-rebuild stops eating them. - scripts/attach-agent-chat.{sh,ts}: resolve a legacy Cursor/Claude/ Codex chat UUID (or index# from ~/.hapi/operator/reconnectable-agent- chats.json), spawn a hub session with resumeSessionId or merge into an existing inactive HAPI row, optionally backfill historical messages, and PATCH the session display name (topic-only; the sidebar already groups by project path). - scripts/backfill-agent-transcript.{ts,test.ts}: read a Cursor/Claude/ Codex jsonl transcript and insert HAPI message envelopes via the current Store; markMessagesInvoked so backfilled rows do not pile up as "queued" in the web UI. Two passing tests cover the cursor map + dedupe-by-local_id path. - scripts/lookup-agent-chat.sh: index# / UUID-prefix lookup against ~/.hapi/operator/reconnectable-agent-chats.json. Pairs with the hapi-find-and-attach-legacy-chat skill at ~/coding/skills/hapi-find-and-attach-legacy-chat/. Caveat: backfill opens hapi.db through the in-repo Store, which is pinned to SCHEMA_VERSION=9. Live hub DB is currently v10 (fcm_devices added in hapi-driver). Until upstream takes v10, backfill against a v10 DB still needs the temporary user_version bounce trick. The new scripts/tooling/hapi-driver-db-prep.sh (commit 33095ad) handles the downgrade path on stack switches but does not help in-process bun runs of this Store yet. Fork-only; not for upstream PR. Co-authored-by: Cursor --- scripts/attach-agent-chat.sh | 6 + scripts/attach-agent-chat.ts | 417 ++++++++++++++++++++++ scripts/backfill-agent-transcript.test.ts | 82 +++++ scripts/backfill-agent-transcript.ts | 378 ++++++++++++++++++++ scripts/lookup-agent-chat.sh | 40 +++ 5 files changed, 923 insertions(+) create mode 100755 scripts/attach-agent-chat.sh create mode 100644 scripts/attach-agent-chat.ts create mode 100644 scripts/backfill-agent-transcript.test.ts create mode 100644 scripts/backfill-agent-transcript.ts create mode 100755 scripts/lookup-agent-chat.sh diff --git a/scripts/attach-agent-chat.sh b/scripts/attach-agent-chat.sh new file mode 100755 index 00000000000..f64b9b40de6 --- /dev/null +++ b/scripts/attach-agent-chat.sh @@ -0,0 +1,6 @@ +#!/usr/bin/env bash +# Attach a legacy agent chat UUID to HAPI (spawn, reconnect merge, optional transcript backfill). +# resumeagent-tui auto mode invokes this when present under the resolved hapi repo root. +set -euo pipefail +ROOT="$(cd "$(dirname "$0")/.." && pwd)" +exec bun run "$ROOT/scripts/attach-agent-chat.ts" "$@" diff --git a/scripts/attach-agent-chat.ts b/scripts/attach-agent-chat.ts new file mode 100644 index 00000000000..c0c1e99f869 --- /dev/null +++ b/scripts/attach-agent-chat.ts @@ -0,0 +1,417 @@ +#!/usr/bin/env bun +/** + * Find a legacy agent chat UUID and attach it to HAPI (spawn or reconnect merge). + * Optional transcript backfill into ~/.hapi/hapi.db for empty HAPI scrollback. + */ +import { readFileSync, existsSync } from 'node:fs' +import { homedir } from 'node:os' +import { join } from 'node:path' +import { spawnSync } from 'node:child_process' +import { Database } from 'bun:sqlite' + +import { backfillSessionMessages, resolveTranscriptPath } from './backfill-agent-transcript' + +type AgentFlavor = 'cursor' | 'claude' | 'codex' + +type IndexRow = { + n?: number + agent?: string + id: string + project?: string +} + +type HapiSessionRow = { + id: string + active: number + metadata: string | null + messageCount: number +} + +function argValue(name: string): string | undefined { + const i = process.argv.indexOf(name) + if (i >= 0) return process.argv[i + 1] + const prefix = `${name}=` + const hit = process.argv.find((a) => a.startsWith(prefix)) + return hit ? hit.slice(prefix.length) : undefined +} + +function hasFlag(flag: string): boolean { + return process.argv.includes(flag) +} + +function expandHome(path: string): string { + return path.startsWith('~/') ? join(homedir(), path.slice(2)) : path +} + +function usage(): never { + console.error(`Usage: attach-agent-chat.sh [options] + +Options: + --dry-run Plan only; no hub spawn/resume or sqlite writes + --no-backfill Skip transcript import into HAPI messages + --backfill-only Only backfill (requires --session) + --local Use \`hapi resume\` in project dir instead of hub spawn + --session Target HAPI session (backfill-only or force reconnect row) + --name