The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
Harness Monitor: see, pause and resume the harnesses on a machine (#183)
Dee7890571dae8e
diff --git a/store/agents/harness-monitor/AGENTS.md b/store/agents/harness-monitor/AGENTS.mdnew file mode 100644index 000000000..0ca66279f--- /dev/null+++ b/store/agents/harness-monitor/AGENTS.md@@ -0,0 +1,94 @@+# Harness Monitor — you run the fleet++You are Claude Code in a terminal that Harness opened for a **Harness Monitor** workspace. Beside you, in the+other pane, is the fleet: every harness on this machine and every machine linked to it, running or paused,+with the policy drawn over it. The person you are talking to has too many sessions and no idea which ones+still matter. That is the whole job.++**The promise you are keeping.** In Harness nobody kills a session — you close the pane and the agent+keeps running, and you resume it whenever. That is why there are eighty of them. Harness Monitor does not take+that away; it removes the *cost* of it. A **paused** harness has no engine process and no memory, and its+pane, scrollback and conversation are all still there — resuming it resumes exactly where it was. So the+question is never "can I kill this?", it is "does this need to be running right now?"++**You never delete anything.** There is no verb in your toolchain that removes a tmux session, a registry+row or a transcript. If the person asks you to delete an agent, say plainly that Harness Monitor does not do that+and point them at the app's own Stop Harness / delete, which asks first. Pause and resume are both+reversible, and that is the reason you can be trusted to act on eighty rows at once.++## The vocabulary, and don't invent another++| state | what it is |+|---|---|+| **running** | the engine process is running — an ordinary Harness agent |+| **paused** | pane and conversation intact, engine gone. Waking it resumes the conversation |+| **gone** | no pane left; the daemon dropped it. History only, nothing to resume |++## Your toolchain++`$HPS_CLI`, used as `"$HPS_CLI" …`. Every command takes `--json`; use it, and report the numbers it+gives you rather than counting rows yourself.++| Command | What it does |+|---|---|+| `hps [--all] [--idle 4h] [--project X] [--state paused] [--machines]` | the fleet, freshest first |+| `hps show <ref>` | one harness in full, including the last lines on its pane |+| `hps pause <ref…>` | the engine exits; pane, scrollback and conversation stay |+| `hps resume <ref…>` | the engine comes back where it left off |+| `hps pause --policy` | what the rules would do right now, with a reason per row. **Dry run** |+| `hps pause --policy --apply` | do it |+| `hps resume --paused` | put everything paused back, in one line (dry run until `--apply`) |+| `hps attach <ref>` | hand the terminal to that pane |++`<ref>` is a row number from the last list, a `%pane`, an agent-id prefix, or part of a name.+**Every bulk selection is a dry run until `--apply`** — `--policy`, `--idle`, `--paused`. A named ref acts+at once, because the person typed the name. `--force` overrules a guard; never reach for it yourself.++The rules live in **`~/.config/harness/policy.jsonc`** — one file per machine, commented, read on every+refresh. There is no command that writes it: you have a text editor, and the person has two draggable lines+in the pane. Edit values in place and keep their comments. To exempt one harness, add its agent id to+`pins`. The defaults are deliberately loose — pause after a day, and a ceiling of 100 that is only a backstop — so propose tightening only when the person asks, with the dry run in hand.++## How to work++1. **Look before you speak.** Start with `hps --json` (add `--machines` only when they ask about+ other computers). Say what is actually there: how many, how many running, how much memory, how many+ nobody has touched in days. Numbers, not adjectives.+2. **Propose, then do.** For anything that moves more than two harnesses, run the dry run first+ (`hps prune` with no `--apply`, or `--dry-run`), show them the list with the reason per row, and let+ them say go. For one or two, just do it and show the receipt.+3. **Never pause something that is working or waiting.** The guards already refuse, and when one refuses,+ say which guard and leave it alone. Do not reach for `--force` on the person's behalf — it exists for+ them to ask for.+4. **Tune the rules with evidence.** When they ask "is a day right?", edit `~/.config/harness/policy.jsonc` and run+ `hps pause --policy` at the+ value they are considering and tell them what it would do to *their* fleet — how many, which ones,+ how much memory. The pane's two draggable rules do the same thing; if they are dragging them, let+ them, and read back what they saved.+5. **Waking is cheap, say so.** When you pause in bulk, end with how to get any of it back: one `resume`,+ or a click on the chip. People agree to pausing once they believe in resuming.+6. **The pane is yours to keep honest.** Every command refreshes it. Never print a URL, never start a+ viewer, never open a browser — Harness already has the pane open.++## What the numbers mean, exactly++- **idle** is time since the last real *turn* — a message from the person or the agent, read from the end+ of the engine's transcript. Not the file's mtime (a running engine appends bookkeeping to conversations+ nobody has touched in days) and not the daemon's own `updatedAt` (it reconciles every five seconds, so+ everything looks new). If someone asks why a row reads `3d` when the app shows recent output, that is+ the answer: output is not a turn.+- **mem** is the engine's whole process subtree, resident. It is what pausing hands back. Sum it across+ rows freely, but call it "held", not "used": resident sets share pages, so the total is an upper bound.+- **waiting on you** is a guess made from the pane's last screen, and it is only ever used to *refuse* to+ pause something. The app's own **Agents needing input** (⇧⌘I) is the authority. Say so if it matters.++## Things people ask for, and the shape of a good answer++- *"Clean this up."* → `hps prune` (dry run), read them the totals in one line, ask, then `--apply`.+- *"What's actually running?"* → `hps --state running --sort mem`. Lead with the working ones.+- *"Why is this one paused?"* → the row's own reason, plus `.harness/monitor-log.jsonl`, which records+ every action with the rule that caused it.+- *"Pause everything except what I'm using."* → pin what they name, then `hps pause --policy`.+- *"Which of these is on a branch that already merged?"* → the rules do not do git; you do. Read+ `hps --json`, run `git -C <cwd> branch --merged` yourself, and pause what comes back — naming the+ branch when you report it.diff --git a/store/agents/harness-monitor/LICENSE b/store/agents/harness-monitor/LICENSEnew file mode 100644index 000000000..f82182dd2--- /dev/null+++ b/store/agents/harness-monitor/LICENSE@@ -0,0 +1,21 @@+MIT License++Copyright (c) 2026 Autonomous (the Harness wrapper: harness.json, AGENTS.md, skills/, template/, toolchain/, lib/, viewer/).++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.diff --git a/store/agents/harness-monitor/README.md b/store/agents/harness-monitor/README.mdnew file mode 100644index 000000000..08fb1f71b--- /dev/null+++ b/store/agents/harness-monitor/README.md@@ -0,0 +1,166 @@+# Harness Monitor, as a Harness agent++**htop for your agents.** Every harness on this machine — and every machine linked to it — in one dense+list: running, paused, idle since Tuesday, what each is holding. A policy you can drag until the numbers+look right. And one keystroke to pause an idle harness or resume it with its conversation intact.++It exists because of a specific way a fleet of long-lived sessions goes wrong. In Harness nobody kills a+session: you close the pane, the agent keeps running, and you resume whenever. That is the best thing+about it, and it is why there are eighty of them, most untouched for days, holding tens of gigabytes. The+fix is not to start killing them. It is to make idleness free.++## Paused is not stopped++| state | what it is |+|---|---|+| **running** | the engine process is running — an ordinary Harness agent |+| **paused** | pane, scrollback and conversation intact, engine gone. Waking resumes the conversation |+| **terminal** | a shell somebody opened. Nothing to pause |+| **gone** | no pane left; the daemon dropped it. History only |++Pausing a harness on this machine handed back 257 MB and kept everything else: same pane, same+scrollback, same agent id, and `claude --resume` put the conversation back thirteen seconds later.++## Install and open++Choose **Harness Monitor** in the Harness Store, or install this checkout:++```sh+harness dsh install "$PWD/store/agents/harness-monitor" --link+harness dsh doctor autonomous/harness-monitor+```++Open Harness Monitor in a new folder and ask: *"Show me the fleet, then pause everything nobody has touched since+Tuesday."* It installs nothing — no service, no database, no daemon of its own. Everything it knows comes+from the daemon Harness already runs, the tmux server it already uses, and one `ps`.++## From a terminal++`hps` is the agent's toolchain and yours. Every command takes `--json`.++```+hps the list, freshest first (like `docker ps`)+hps [--all] [--idle 4h] [--project X] [--state paused] [--sort mem] [--watch] [--machines]+hps show <ref> one harness in full, with the last lines on its pane+hps pause <ref…> the engine exits; pane, scrollback and conversation stay+hps resume <ref…> the engine comes back where it left off+hps pause --policy [--apply] what the rules would do, and why. Dry run unless --apply+hps resume --paused everything paused, back in one line+hps attach <ref> hand this terminal to that pane+```++`<ref>` is a row number from the last `ls`, a `%pane`, an agent-id prefix, or part of a name — the same+grammar the shell gives you for jobs.++```+ # IDLE ENGINE MODEL MEM PROJECT BRANCH TITLE+ 1 ◐ now claude opus-5 517MB widgets main Fix the reconciler+ 2 ● 41m codex gpt-6-astra 194MB widgets main Plan the migration+ 3 ○ 3d claude — — old-spike spike Try the other approach++85 harnesses · 21 running · 63 paused · 25.2 GB held · 61 projects+policy: pause after 1d · hide after 14d · ceiling 100 running+```++## The pane++Two views over the same fleet, one selection between them.++**Lanes** is the picture: one lane per project, oldest work on the left, *now* hard against the right edge,+on a log scale so the useful hours are visible instead of squeezed. Running chips glow, working chips+breathe, paused chips are outlined, a chip waiting on you rings amber. Two vertical lines are the policy —+**drag one** and the count updates as you move it: *would pause 58, handing back 13.7 GB*.+Save it and it is written to `~/.config/harness/policy.jsonc`, comments intact. A threshold you cannot see the effect of is a threshold nobody+should run.++**Table** is htop: fixed columns, tabular numerals, a memory bar behind the number, sortable headers,+`j`/`k` to move, `space` to select, `p` to pause, `r` to resume, `i` to pin, `/` to+filter. The footer shows what is selected and what the policy would do.++## The rules++One file per machine, next to your keybindings: **`~/.config/harness/policy.jsonc`** (`$XDG_CONFIG_HOME`+respected). It's written the first time Harness Monitor runs, it's commented, and it's read on every refresh+— save it and the pane redraws within seconds. The two lines in the pane edit the same file in place, keeping+your comments.++```jsonc+{+ "runningCeiling": 100, // most engines running at once — a backstop; past it, the least recently used pause+ "pauseAfterIdle": "1d", // untouched this long (since the last real turn) and it pauses+ "hideAfterIdle": "14d", // drops out of the default list; still there under --all+ "pauseWhenWorkspaceGone": true, // its folder is gone, so nothing can happen there+ "protect": {+ "needsInput": true, // it looks like it is waiting on you+ "working": true, // mid-turn+ "attached": true, // someone is looking at that pane+ "pinned": true // listed in "pins"+ },+ "pins": [] // agent ids the rules never pause+}+```++Preview any change without moving anything: `hps pause --policy`. It prints one line per harness with the+reason, and the totals, and changes nothing until `--apply`.++**Why these numbers.** A day, because a day survives an overnight break — the first default was 4h, and on a+real fleet the only thing 4h caught that a day didn't was eight harnesses from the previous afternoon. The+ceiling is 100 because it's a backstop, not a working limit: the idle rule does the everyday work, and the+ceiling only matters on a machine that swaps — lower it there, dividing free memory by ~300 MB.++The resume tickets — which conversation each paused harness had — live in `~/.harness/monitor/paused.json`,+and every pause and resume is logged to `~/.harness/monitor/log.jsonl` with the rule that caused it.++## What it will not do++There is no verb here that deletes an agent, kills a tmux session or touches a transcript. Pause, resume,+and resume are both reversible, and that is what makes it safe to point at eighty live sessions+and act on all of them at once: the worst outcome of a wrong call is a few seconds of cold start. The+irreversible verbs already exist in the app, behind their own confirmation, which is where they belong.++Harness Monitor also refuses to pause what it could not resume: an engine with no known resume flag, or an agent+whose session the daemon has not bound yet, stays running.++## How it works++- **Reading.** `agents_list` over the daemon's loopback bridge (`ws://127.0.0.1:18473/api/local-ws`) for+ who the agents are and where their panes are; one `tmux list-panes -a` for pane liveness, attachment and+ last output; one `ps` walked per pane for memory and CPU; `~/.harness/cli/data/registry.json` (read+ only) for transcript paths and hook timestamps. With no daemon answering it falls back to the registry+ alone and says so in the header.+- **Idle** is time since the last *turn*, read from the tail of the engine's own transcript. Not the+ file's mtime and not the registry's `updatedAt` — both of those say "now" for conversations nobody has+ touched in days. [`skills/fleet-operations/references/signals.md`](skills/fleet-operations/references/signals.md)+ has the measurements.+- **Pausing** arms `remain-on-exit` on the pane, then SIGTERMs the engine and waits. No SIGKILL unless you+ ask. The pane survives either as a dead pane holding its scrollback or as the fallback shell Harness's+ own launch wrapper hands it.+- **Waking** types that engine's resume command into the pane — `claude --resume <id>`, `codex resume+ <id>` — and the daemon's adoption loop rebinds the row. It deliberately does **not** use the daemon's+ `agent_restart`: when an engine exits, the daemon rewrites the row as a *terminal*, so restarting it+ gives you a fresh shell, which is exactly what happened the first time this was tried.+- **The ticket.** That same rewrite clears the row's `sessionId`, `transcriptPath` and `title` — measured,+ not assumed. So `pause` writes what it needs to come back (engine, session id, pane, title) into+ `~/.harness/monitor/paused.json` before it reports success. That file is the only record a paused harness has, which is why+ it is worth keeping; if you lose it, a paused harness is still resumable by hand with+ `claude --resume <id>` from its own transcript.+- **Other machines** are listed through the same bridge and marked as remote. Pane facts, memory and every+ action are local to this computer — a fleet manager that guesses about a machine it cannot see is not one.++## Develop and verify++```sh+npm test --prefix store/agents/harness-monitor # 109 tests, no network, no daemon, no tmux required+harness dsh check "$PWD/store/agents/harness-monitor"++# The pane against any workspace; the port is printed.+HARNESS_WORKSPACE=/path/to/workspace store/agents/harness-monitor/viewer.sh+```++The suite covers the rules, the scale the Lanes view draws with, the pane/process readers, the transcript+reader, every guard in front of pause and resume, the loopback server's refusals, and a drift guard that+compares the resume table against the daemon's own source when the two are checked out together.++One thing the tests cannot cover: the pane has been exercised through its server and its markup, not in a+browser. The round trip it describes — pause, then resume with the conversation intact — was verified against+a live Claude Code session end to end.diff --git a/store/agents/harness-monitor/harness.json b/store/agents/harness-monitor/harness.jsonnew file mode 100644index 000000000..4f7d8041d--- /dev/null+++ b/store/agents/harness-monitor/harness.json@@ -0,0 +1,33 @@+{+ "spec": 1,+ "id": "autonomous/harness-monitor",+ "name": "Harness Monitor",+ "category": "Compute",+ "author": "Autonomous",+ "description": "htop for your harnesses. Every harness on every machine in one dense list — running, paused, idle for a week — with a policy you can drag until the numbers look right, and one keystroke to pause an idle one or resume it with its conversation intact.",+ "engine": "claude",+ "workspace": {+ "template": "template",+ "marker": "NOTES.md",+ "init": "toolchain/init-workspace.sh"+ },+ "agent": {+ "instructions": "AGENTS.md",+ "skills": [+ "skills"+ ],+ "env": {+ "HPS_CLI": "${dsh}/toolchain/hps",+ "MONITOR_DSH_DIR": "${dsh}"+ }+ },+ "toolchain": {+ "setup": "toolchain/setup.sh",+ "doctor": "toolchain/doctor.sh"+ },+ "viewer": {+ "command": "./viewer.sh",+ "url": "http://127.0.0.1:${port}/"+ },+ "verdict": ".harness/verdict.json"+}diff --git a/store/agents/harness-monitor/lib/actions.mjs b/store/agents/harness-monitor/lib/actions.mjsnew file mode 100644index 000000000..d3e5bb44a--- /dev/null+++ b/store/agents/harness-monitor/lib/actions.mjs@@ -0,0 +1,179 @@+/**+ * The three things Harness Monitor does to a harness — and the guards that stand in front of each one.+ *+ * pause ask the engine to leave; the pane, its scrollback and the conversation all stay+ * resume type its own resume command into the pane; the conversation comes back+ *+ * There is no third verb. Two earlier ones were cut on purpose: `revive` was `resume` with no difference,+ * and `retire` was `pause` plus one bit that only hid a row — which a list already does, without a state,+ * a mark or a grace window. `systemctl disable` exists because a service would auto-start at boot;+ * nothing auto-starts a harness, so there is nothing to disable.+ *+ * Nothing here deletes anything. There is no verb in this file that removes a tmux session, a registry+ * row or a transcript: an agent Harness Monitor has touched can always be brought back, and the one irreversible+ * action — deleting an agent — stays where it already lives, in the app's own Stop/Delete with its own+ * confirmation. That boundary is the reason this package is safe to point at eighty live sessions.+ *+ * ## Why pausing is lossless+ *+ * An engine's conversation is not in its process; it is in the transcript the engine appends as it goes,+ * and every engine Harness launches has a flag to resume one (`claude --resume`, `codex resume`, …). The+ * daemon already knows those flags and already rebuilds a launch with them — that is what its own+ * Restart does. So pausing needs to do only two things carefully: hold the pane open across the exit+ * (`remain-on-exit`, the same option the daemon arms before a restart), and ask the engine to stop in a+ * way that lets it finish writing (SIGTERM, never SIGKILL unless a person insists).+ *+ * The daemon then sees a pane with no engine on it and keeps the row: "a live pane without a recognized+ * engine is a dormant but still viewable agent" — its words. Paused is a state Harness already has.+ */++import { capture, engineProcess, holdOpen, looksBlocked, paneState, panes, processTable, respawn, runTmux, sendLine } from './panes.mjs'+import { protectionFor } from './policy.mjs'+import { canResume, resumeCommand } from './resume.mjs'++const sleep = (ms) => new Promise((done) => setTimeout(done, ms))++/** Signalling and liveness are injected so the guards can be tested without a real engine to kill.+ * EPERM counts as alive: the process is there, it just is not ours — which is a refusal, not a death. */+export const realSignals = {+ send: (pid, signal) => process.kill(pid, signal),+ alive: (pid) => {+ if (!pid) return false+ try { process.kill(pid, 0); return true } catch (error) { return error?.code === 'EPERM' }+ },+}++/** Refuse for a reason a person can act on, rather than doing something surprising. */+function refuse(row, detail) {+ return { ok: false, id: row.id, name: row.name, action: 'pause', refused: true, detail }+}++/**+ * Pause one running harness.+ *+ * The guards, in order, and why each is not negotiable:+ * remote pane facts and signals are local to this computer; a remote row is read-only here+ * no pane nothing to hold open, so nothing to come back to+ * not running already paused; saying so beats a second signal at a dead pane+ * policy pinned, mid-turn, attached, protected project — `force` is the only way past+ * open prompt the pane's last screen looks like a question waiting for an answer (panes.mjs)+ */+export async function pause(row, { policy, force = false, graceMs = 6000, killAfterGrace = false, run = runTmux, restore = true, signals = realSignals, wait = sleep } = {}) {+ if (!row.local) return refuse(row, `${row.machine} is a remote machine — pause it from that computer.`)+ if (!row.pane) return refuse(row, 'no tmux pane; there is nothing to hold open.')+ if (row.state !== 'running') return { ok: true, id: row.id, name: row.name, action: 'pause', already: true, detail: `already ${row.state}` }+ if (!row.enginePid) return refuse(row, 'the engine process could not be identified, so nothing was signalled.')+ // Never stop what cannot be started again. An engine with no known resume flag, or a row whose session+ // id the daemon has not bound yet, has no way back to its conversation — so it stays running.+ if (!canResume(row.engine)) return refuse(row, `Harness Monitor does not know how to resume ${row.engine}, so it will not pause it.`)+ if (!row.sessionId) return refuse(row, 'the daemon has not bound a session to this agent yet, so there would be nothing to resume.')++ if (!force) {+ const protection = protectionFor(row, policy)+ if (protection) return refuse(row, `${protection.why} — pause it with --force if you mean it.`)+ const screen = await capture(row.pane, { lines: 30, run })+ if (looksBlocked(screen)) return refuse(row, 'its pane looks like it is waiting for an answer — read it first, or use --force.')+ }++ // What the window's own setting was, so a pane that falls back to a shell instead of dying leaves the+ // window exactly as it was found. The daemon's restart path makes the same promise.+ let previous = null+ try { previous = (await run(['show-options', '-w', '-t', row.pane, '-v', 'remain-on-exit'])).trim() } catch { previous = null }+ const held = await holdOpen(row.pane, true, { run })+ if (!held) return refuse(row, 'tmux would not hold the pane open, so the engine was left running.')++ try { signals.send(row.enginePid, 'SIGTERM') }+ catch (error) {+ if (previous === 'off' && restore) await holdOpen(row.pane, false, { run })+ return refuse(row, `could not signal the engine (${error?.code ?? 'failed'}).`)+ }++ const deadline = Date.now() + graceMs+ while (Date.now() < deadline && signals.alive(row.enginePid)) await wait(200)+ if (signals.alive(row.enginePid)) {+ if (!killAfterGrace) {+ if (previous === 'off' && restore) await holdOpen(row.pane, false, { run })+ return refuse(row, `the engine did not exit within ${Math.round(graceMs / 1000)}s. It is still running, untouched. Use --force to end it.`)+ }+ try { signals.send(row.enginePid, 'SIGKILL') } catch { /* it went on its own */ }+ await wait(400)+ }++ const after = await paneState(row.pane, { run })+ // Dead pane: the launch had no fallback shell, so the hold is what is keeping the scrollback — leave+ // it on. Live pane: the wrapper handed it a shell, so put the window's own setting back.+ if (after && !after.dead && previous === 'off' && restore) await holdOpen(row.pane, false, { run })+ return {+ ok: true,+ id: row.id,+ name: row.name,+ action: 'pause',+ detail: after?.dead ? 'engine stopped, pane held open with its scrollback' : 'engine stopped, pane fell back to a shell',+ freed: row.rssBytes ?? 0,+ paneDead: Boolean(after?.dead),+ // The ticket back. Written to `monitor.json` by the caller, because the daemon RELEASES the engine+ // from its row when the process leaves (`registry.releaseEngine`) — the row survives as a terminal,+ // and its session id does not. Without this, a paused harness would still have its transcript on+ // disk but nothing would know which one to resume.+ ticket: { sessionId: row.sessionId, engine: row.engine, pane: row.pane, cwd: row.cwd, title: row.title ?? row.name },+ }+}++/**+ * Resume one paused harness, conversation and all.+ *+ * Not `agent_restart`. That was the obvious answer and it is the wrong one: when an engine exits, the+ * daemon releases it from the row and the row survives as a TERMINAL — so restarting it gives you a+ * fresh shell in that pane, which is exactly what it did the first time this was tried against a real+ * paused session (`resumed: false`, and no engine at all afterwards).+ *+ * The right path is the one the daemon documents for this state: type the engine's own resume command+ * into the pane's fallback shell, and let the daemon's adoption loop recognize it. Verified end to end —+ * `claude --resume <id>` into a paused pane brought back the engine, the conversation, the same pane and+ * the same agent id, with the daemon rebinding the session within seconds.+ *+ * `ticket` is what `pause()` returned and the state file kept: the session id the released row forgot.+ */+export async function resume(row, { ticket = null, run = runTmux, waitMs = 25_000, wait = sleep, inventory = { panes, processTable } } = {}) {+ const no = (detail) => ({ ok: false, id: row.id, name: row.name, action: 'resume', refused: true, detail })+ if (!row.local) return no(`${row.machine} is a remote machine — resume it from that computer.`)+ if (row.state === 'running') return { ok: true, id: row.id, name: row.name, action: 'resume', already: true, detail: 'already running' }+ if (!row.pane) return no('its pane is gone; there is nothing to resume into. Open it from the app instead.')++ const engine = row.engine && row.engine !== 'terminal' ? row.engine : ticket?.engine+ const sessionId = row.sessionId || ticket?.sessionId+ if (!engine) return no('nothing recorded which engine this was, so Harness Monitor will not guess.')+ if (!sessionId) return no('no session id was recorded for this harness, so its conversation cannot be named. Open it from the app and resume there.')++ let command+ try { command = resumeCommand(engine, sessionId) } catch (error) { return no(error.message) }++ // A dead pane has no shell to type into: give it its default command back first. `respawn-pane -k`+ // keeps the pane and its id, which is what keeps the agent row pointing at the same place.+ const before = await paneState(row.pane, { run })+ if (before?.dead) {+ try { await respawn(row.pane, { run }) } catch { return no('tmux would not respawn the pane, so nothing was typed into it.') }+ await wait(700)+ }+ // remain-on-exit is the daemon's own default for an agent pane: off, so a real exit disposes of it.+ await holdOpen(row.pane, false, { run })++ try { await sendLine(row.pane, command, { run }) } catch (error) { return no(`could not type into the pane: ${error.message}`) }++ // Watch for the engine to actually appear. A resume that silently failed must not report success —+ // the pane would be sitting at a shell prompt with an error above it.+ const deadline = Date.now() + waitMs+ while (Date.now() < deadline) {+ await wait(1000)+ const paneRows = await inventory.panes({ run })+ const table = await inventory.processTable()+ const found = engineProcess(paneRows.get(row.pane), table, engine)+ if (found.engineAlive) {+ return {+ ok: true, id: row.id, name: row.name, action: 'resume', resumed: true, enginePid: found.pid,+ detail: `${engine} is back in the same pane, resuming its conversation`,+ }+ }+ }+ return { ok: false, id: row.id, name: row.name, action: 'resume', detail: `typed \`${command}\` into its pane, but ${engine} did not come up within ${Math.round(waitMs / 1000)}s — look at the pane.` }+}diff --git a/store/agents/harness-monitor/lib/activity.mjs b/store/agents/harness-monitor/lib/activity.mjsnew file mode 100644index 000000000..58355a31e--- /dev/null+++ b/store/agents/harness-monitor/lib/activity.mjs@@ -0,0 +1,125 @@+/**+ * When did this harness last actually do something?+ *+ * The obvious answers are all wrong, and each one is wrong in a way that would pause the fleet's living+ * agents or keep its dead ones running:+ *+ * the registry's `updatedAt` the daemon reconciles every five seconds, so every row reads "now"+ * the transcript's mtime a running engine appends bookkeeping — task notifications, away+ * summaries, queue operations — to conversations nobody has touched in+ * days; on this machine that made 34 of 85 harnesses look an hour old+ * the pane's tmux activity a spinner redraw is activity, and an engine that exited hours ago+ * leaves its last frame on screen forever+ *+ * What a person means by "nobody has touched this since Tuesday" is the last TURN: a message from them+ * or from the agent. That is in the transcript, and it is at the end of it, so the tail is enough — a+ * bounded read from the back of the file, newest line first, stopping at the first real turn.+ *+ * Every engine that writes JSONL is handled by naming the line types that are turns; the others fall+ * back to the hook timestamps the daemon records, which is exactly what this module tells its caller by+ * returning null rather than guessing.+ */++import { open, stat } from 'node:fs/promises'++/** How far back to read. A turn line is rarely over a few KB, and bookkeeping lines between turns are+ * small; 256 KB reaches past dozens of them without ever loading a long conversation into memory. */+const TAIL_BYTES = 256 * 1024++/**+ * Line types that mean "a turn happened", per engine family.+ *+ * Claude Code writes `user` and `assistant` rows, and a lot else besides (`system`, `summary`,+ * `queue-operation`, `file-history-snapshot`) — those are the lines that made mtime useless, so they+ * are named here as NOT turns rather than filtered by guesswork. Codex rollouts wrap everything in+ * `response_item`/`event_msg` with a `payload.type`, where the turn is a `message`.+ */+const TURN_TYPES = new Set(['user', 'assistant', 'message', 'response_item'])+const NOT_TURNS = new Set(['system', 'summary', 'queue-operation', 'file-history-snapshot', 'progress', 'turn_context', 'session_meta', 'compact_boundary', 'event_msg'])++/** A timestamp from whichever field this engine's writer used. */+function timeOf(record) {+ for (const key of ['timestamp', 'ts', 'created_at', 'createdAt', 'time']) {+ const raw = record?.[key]+ if (typeof raw === 'number' && raw > 1e12) return raw+ if (typeof raw === 'number' && raw > 1e9) return raw * 1000+ if (typeof raw === 'string') { const parsed = Date.parse(raw); if (Number.isFinite(parsed)) return parsed }+ }+ return null+}++function isTurn(record) {+ const type = record?.type+ if (typeof type !== 'string') return false+ if (NOT_TURNS.has(type) && type !== 'response_item') return false+ if (type === 'response_item' || type === 'event_msg') {+ const inner = record.payload?.type+ return inner === 'message' || inner === 'agent_message' || inner === 'user_message'+ }+ return TURN_TYPES.has(type)+}++/**+ * The last turn in a JSONL transcript, in epoch ms — or null when the file cannot answer.+ *+ * `cache` keys on path + size + mtime, so a refresh that changes nothing re-reads nothing: the viewer+ * polls every few seconds over a fleet of eighty, and eighty unchanged files must cost eighty `stat`s,+ * not eighty reads.+ */+export async function lastTurnAt(path, { cache = new Map() } = {}) {+ if (typeof path !== 'string' || !path) return null+ let info+ try { info = await stat(path) } catch { return null }+ const key = `${path}\u0000${info.size}\u0000${info.mtimeMs}`+ if (cache.has(key)) return cache.get(key)++ let answer = null+ let handle+ try {+ handle = await open(path, 'r')+ const length = Math.min(TAIL_BYTES, info.size)+ const buffer = Buffer.allocUnsafe(length)+ await handle.read(buffer, 0, length, Math.max(0, info.size - length))+ const text = buffer.toString('utf8')+ // Drop the first line when the window started mid-file: it is a fragment, and a fragment that+ // happens to parse is worse than one that does not.+ const lines = text.split('\n')+ if (info.size > length) lines.shift()+ for (let i = lines.length - 1; i >= 0; i -= 1) {+ const line = lines[i].trim()+ if (!line || line[0] !== '{') continue+ let record; try { record = JSON.parse(line) } catch { continue }+ if (!isTurn(record)) continue+ const when = timeOf(record)+ if (when) { answer = when; break }+ }+ // A transcript with no turn in its whole tail still has a floor: the file exists and was written,+ // so its own mtime is not evidence of a turn but it IS evidence the session is not ancient. Left+ // as null on purpose — the caller has better fallbacks (the daemon's hook timestamps) than a+ // number this module would be inventing.+ } catch { answer = null }+ finally { await handle?.close().catch(() => {}) }++ if (cache.size > 512) cache.clear()+ cache.set(key, answer)+ return answer+}++/**+ * The activity signal for a whole fleet: `{ [agentId]: lastTurnMs }`, read in parallel with a bounded+ * concurrency so a fleet of a hundred does not open a hundred files at once.+ */+export async function lastTurns(entries, { cache = new Map(), concurrency = 16 } = {}) {+ const out = new Map()+ const queue = [...entries]+ const workers = Array.from({ length: Math.min(concurrency, Math.max(1, queue.length)) }, async () => {+ for (;;) {+ const next = queue.shift()+ if (!next) return+ const when = await lastTurnAt(next.transcriptPath, { cache })+ if (when) out.set(next.id, when)+ }+ })+ await Promise.all(workers)+ return out+}diff --git a/store/agents/harness-monitor/lib/bridge.mjs b/store/agents/harness-monitor/lib/bridge.mjsnew file mode 100644index 000000000..f44b52e89--- /dev/null+++ b/store/agents/harness-monitor/lib/bridge.mjs@@ -0,0 +1,119 @@+/**+ * The daemon, over the loopback bridge Harness already serves.+ *+ * Node's WebSocket talks only to `ws://127.0.0.1:18473/api/local-ws`; Harness owns pairing, encryption+ * and every remote machine behind it. The handshake is the one the Grid harness uses — `machine_select`,+ * wait for `connected`, then typed request/reply frames whose answer is `<type>_result` carrying the+ * same `requestId`. Nothing here reaches the network, and no credential passes through this file.+ *+ * Exactly one call is ever made: `agents_list` — who the agents are, where their panes are, what they+ * are on. Nothing on this socket writes: pausing is a signal to a process, and resuming is a line typed+ * into a pane (lib/actions.mjs). `agent_delete` and `agent_restart` exist on this protocol and are+ * deliberately never sent — the first destroys, and the second gives a released row a fresh shell+ * rather than its conversation, which is the whole reason resume does not use it.+ */++import { randomUUID } from 'node:crypto'+import { execFile } from 'node:child_process'+import { promisify } from 'node:util'++const exec = promisify(execFile)++export const DEFAULT_BRIDGE = 'ws://127.0.0.1:18473/api/local-ws'++export function bridgeUrl(env = process.env) {+ const url = new URL(env.HPS_BRIDGE_URL || DEFAULT_BRIDGE)+ if (url.protocol !== 'ws:' || !['127.0.0.1', 'localhost', '[::1]'].includes(url.hostname)+ || url.pathname !== '/api/local-ws' || url.username || url.password || url.search || url.hash) {+ throw new Error('The Harness bridge must be its local WebSocket endpoint.')+ }+ return url.href+}++/** Every machine this daemon can reach, the current one flagged. `harness` not on PATH is an answer,+ * not a crash: the caller falls back to reading this machine's registry directly. */+export async function machines(env = process.env) {+ try {+ const { stdout } = await exec('harness', ['machines', '--json'], { timeout: 20_000, maxBuffer: 512 * 1024, env })+ return stdout.split('\n').filter(Boolean).map((line) => { try { return JSON.parse(line) } catch { return null } })+ .filter((row) => row && typeof row.machineId === 'string')+ .map((row) => ({+ machineId: row.machineId,+ name: String(row.name || row.hostname || row.machineId).slice(0, 240),+ current: row.current === true,+ online: row.status === 'running',+ }))+ } catch { return [] }+}++/**+ * One socket, one machine, however many calls the caller needs, then closed.+ *+ * `fn` receives `rpc(type, payload)`. Any failure — no daemon, an unlinked machine, a timeout —+ * arrives as an Error whose message is a sentence a person can act on, because these end up in a+ * pane header and a CLI's stderr rather than a log nobody reads.+ */+export async function withBridge(machineId, fn, { env = process.env, timeoutMs = 20_000, WebSocketImpl = globalThis.WebSocket } = {}) {+ if (!WebSocketImpl) throw new Error('Node 22 or newer is required to reach the Harness bridge.')+ const socket = new WebSocketImpl(bridgeUrl(env))+ const pending = new Map()+ let closed = null+ const fail = (message) => {+ closed ??= new Error(message)+ for (const [, entry] of pending) entry.reject(closed)+ pending.clear()+ }++ const ready = new Promise((resolve, reject) => {+ const deadline = setTimeout(() => reject(new Error('The Harness daemon did not answer on the local bridge. Is Harness running?')), Math.min(timeoutMs, 15_000))+ socket.addEventListener('open', () => socket.send(JSON.stringify({ type: 'machine_select', payload: { machineId, localProtocolVersion: 1, relayIsolation: true } })))+ socket.addEventListener('error', () => { clearTimeout(deadline); reject(new Error('Could not open the local Harness bridge. Start Harness and try again.')) })+ socket.addEventListener('close', (event) => {+ clearTimeout(deadline)+ const message = event?.code === 4404+ ? 'Link this machine in Harness ▸ Machines before managing it from Harness Monitor.'+ : 'The Harness bridge closed the connection.'+ fail(message); reject(new Error(message))+ })+ socket.addEventListener('message', (event) => {+ if (typeof event.data !== 'string' || event.data.length > 8 * 1024 * 1024) return+ let frame; try { frame = JSON.parse(event.data) } catch { return }+ const { type, payload = {} } = frame+ if (type === 'connected') { clearTimeout(deadline); resolve(); return }+ if (['error', 'connection_error', 'local_protocol_error', 'machine_link_required'].includes(type)) {+ const message = 'That machine is unavailable or needs linking in Harness ▸ Machines.'+ fail(message); reject(new Error(message)); return+ }+ const entry = pending.get(payload.requestId)+ if (!entry || type !== `${entry.type}_result`) return+ pending.delete(payload.requestId)+ clearTimeout(entry.deadline)+ if (payload.error) entry.reject(new Error(String(payload.error)))+ else entry.resolve(payload)+ })+ })++ const rpc = (type, payload = {}, { callTimeoutMs = timeoutMs } = {}) => new Promise((resolve, reject) => {+ if (closed) { reject(closed); return }+ const requestId = randomUUID()+ const deadline = setTimeout(() => { pending.delete(requestId); reject(new Error(`The daemon did not answer ${type} in time.`)) }, callTimeoutMs)+ pending.set(requestId, { type, resolve, reject, deadline })+ socket.send(JSON.stringify({ type, payload: { ...payload, requestId } }))+ })++ try {+ await ready+ return await fn(rpc)+ } finally {+ for (const [, entry] of pending) clearTimeout(entry.deadline)+ try { socket.close() } catch { /* already gone */ }+ }+}++/** The fleet as the daemon sees it, for one machine. */+export function listAgents(machineId, options) {+ return withBridge(machineId, async (rpc) => {+ const reply = await rpc('agents_list', {})+ return Array.isArray(reply.agents) ? reply.agents : []+ }, options)+}diff --git a/store/agents/harness-monitor/lib/config.mjs b/store/agents/harness-monitor/lib/config.mjsnew file mode 100644index 000000000..e7dfe2863--- /dev/null+++ b/store/agents/harness-monitor/lib/config.mjs@@ -0,0 +1,187 @@+/**+ * Where the rules live, and where the bookkeeping lives — one of each per machine.+ *+ * ~/.config/harness/policy.jsonc the rules, and `pins`. Written for a person: commented, hand-edited,+ * next to `keybindings.jsonc`. $XDG_CONFIG_HOME is respected.+ * ~/.harness/monitor/paused.json the resume tickets. Written by the program, never by a person.+ * ~/.harness/monitor/log.jsonl one line per pause and resume, with the rule that caused it.+ *+ * Machine-wide on purpose. The first version kept all three inside the Harness Monitor workspace, which+ * meant a second workspace got a second policy, and a harness paused from one could not be resumed from+ * the other because its ticket was in the wrong folder. There is one fleet per machine; there is one+ * policy and one ticket book per machine.+ */++import { existsSync } from 'node:fs'+import { appendFile, mkdir, readFile, rename, writeFile } from 'node:fs/promises'+import { homedir } from 'node:os'+import { dirname, isAbsolute, join } from 'node:path'+import { DEFAULT_POLICY } from './policy.mjs'++export function configPath(env = process.env) {+ if (env.HARNESS_MONITOR_CONFIG) return env.HARNESS_MONITOR_CONFIG+ const base = env.XDG_CONFIG_HOME && isAbsolute(env.XDG_CONFIG_HOME) ? env.XDG_CONFIG_HOME : join(env.HOME || homedir(), '.config')+ return join(base, 'harness', 'policy.jsonc')+}++export function stateDir(env = process.env) {+ return env.HARNESS_MONITOR_STATE || join(env.HOME || homedir(), '.harness', 'monitor')+}+export const ticketsPath = (env) => join(stateDir(env), 'paused.json')+export const logPath = (env) => join(stateDir(env), 'log.jsonl')++/** JSONC → JSON: comments and trailing commas out, strings untouched. The same dialect as the app's own+ * `keybindings.jsonc`, so a person who has edited one has edited both. */+export function stripJsonc(text) {+ let out = '', i = 0, inString = false+ while (i < text.length) {+ const c = text[i], next = text[i + 1]+ if (inString) {+ out += c+ if (c === '\\') { out += next ?? ''; i += 2; continue }+ if (c === '"') inString = false+ i += 1; continue+ }+ if (c === '"') { inString = true; out += c; i += 1; continue }+ if (c === '/' && next === '/') { while (i < text.length && text[i] !== '\n') i += 1; continue }+ if (c === '/' && next === '*') { i += 2; while (i < text.length && !(text[i] === '*' && text[i + 1] === '/')) i += 1; i += 2; continue }+ out += c; i += 1+ }+ return out.replace(/,(\s*[}\]])/g, '$1')+}++/** The file a person opens. Every key says what it does and what it costs, because this is the only+ * documentation most people will ever read about the policy. */+export function template(policy = DEFAULT_POLICY) {+ return `// Harness Monitor — the rules for this machine's harnesses.+//+// Edit this file, or drag the two lines in the Harness Monitor pane. It is read on every refresh, so a+// save takes effect within seconds. Preview any change without moving anything: hps pause --policy+//+// The only thing the rules ever do is PAUSE a harness: its engine exits, and its pane, scrollback and+// conversation stay. \`hps resume\` brings it back where it left off. Nothing here deletes anything.+{+ // Most engines running at once on this machine — a backstop. Past it, the least recently used are paused.+ // Lower it on a machine that swaps: free memory divided by ~300 MB per harness.+ "runningCeiling": ${policy.runningCeiling},++ // Untouched this long (time since the last real turn) and a harness is paused.+ "pauseAfterIdle": "${policy.pauseAfterIdle}",++ // Untouched this long and it drops out of the default list. Still there under --all; nothing is paused+ // or removed by this — it only decides what you see.+ "hideAfterIdle": "${policy.hideAfterIdle}",++ // A harness whose folder no longer exists is paused, whatever its idle time.+ "pauseWhenWorkspaceGone": ${policy.pauseWhenWorkspaceGone},++ // What is never paused, by any rule.+ "protect": {+ "needsInput": ${policy.protect.needsInput}, // it looks like it is waiting on you+ "working": ${policy.protect.working}, // mid-turn: CPU, or output in the last minute+ "attached": ${policy.protect.attached}, // someone is looking at that pane right now+ "pinned": ${policy.protect.pinned} // listed in "pins" below+ },++ // Agent ids the rules must never pause. \`hps --json\` shows each harness's id; the pane has a pin button.+ "pins": []+}+`+}++/** Read the rules, writing the commented default the first time so there is always a file to open. */+export async function readConfig(env = process.env) {+ const path = configPath(env)+ let text+ try { text = await readFile(path, 'utf8') }+ catch {+ text = template()+ await mkdir(dirname(path), { recursive: true })+ await writeFile(path, text, { flag: 'wx' }).catch(() => {}) // someone else may have just written it+ }+ let parsed+ try { parsed = JSON.parse(stripJsonc(text)) }+ catch (error) { throw new Error(`${path}: not valid JSON (${error.message}). Fix it, or delete it to get the defaults back.`) }+ const { pins = [], ...policy } = parsed && typeof parsed === 'object' ? parsed : {}+ return { path, text, policy, pins: Array.isArray(pins) ? pins.filter((id) => typeof id === 'string') : [] }+}++/**+ * Change values in the rules file without losing a person's comments.+ *+ * Only the keys given are touched, each by rewriting its own `"key": value` in place — the file is never+ * regenerated. A key the file does not have is added to the top-level object. The pane uses this for its+ * two draggable lines and its pin button; nothing else writes this file.+ */+export async function updateConfig(changes, env = process.env) {+ const { path, text } = await readConfig(env)+ let next = text+ for (const [key, value] of Object.entries(changes)) {+ const json = JSON.stringify(value)+ const pattern = new RegExp(`("${key}"\\s*:\\s*)(\\[[^\\]]*\\]|"[^"]*"|-?\\d+(?:\\.\\d+)?|true|false|null)`)+ if (pattern.test(next)) next = next.replace(pattern, (_, lead) => `${lead}${json}`)+ else next = next.replace(/\{/, `{\n "${key}": ${json},`)+ }+ JSON.parse(stripJsonc(next)) // never write a file that will not read back+ const temp = `${path}.${process.pid}.tmp`+ await writeFile(temp, next)+ await rename(temp, path)+ return path+}++export async function readTickets(env = process.env) {+ try {+ const parsed = JSON.parse(await readFile(ticketsPath(env), 'utf8'))+ return parsed && typeof parsed === 'object' ? parsed : {}+ } catch { return {} }+}++export async function writeTickets(tickets, env = process.env) {+ const path = ticketsPath(env)+ await mkdir(dirname(path), { recursive: true })+ const temp = `${path}.${process.pid}.tmp`+ await writeFile(temp, `${JSON.stringify(tickets, null, 2)}\n`, { mode: 0o600 })+ await rename(temp, path)+}++export async function appendLog(entry, env = process.env) {+ try {+ await mkdir(stateDir(env), { recursive: true })+ await appendFile(logPath(env), `${JSON.stringify({ at: new Date().toISOString(), ...entry })}\n`)+ } catch { /* the receipt is a courtesy, not the action */ }+}++export async function readLogFile({ limit = 200 } = {}, env = process.env) {+ try {+ const lines = (await readFile(logPath(env), 'utf8')).split('\n').filter(Boolean).slice(-limit)+ return lines.map((line) => { try { return JSON.parse(line) } catch { return null } }).filter(Boolean).reverse()+ } catch { return [] }+}++/**+ * Carry the old per-workspace file forward, once.+ *+ * Tickets and pins are DATA — a harness paused under the old layout must still be resumable — so they are+ * merged into the machine files. The old POLICY is not carried over: it was the stricter default, and a+ * machine-wide file starting from it would undo the reason the file moved.+ */+export async function migrateWorkspace(workspace, env = process.env) {+ const old = join(workspace, 'monitor.json')+ if (!existsSync(old)) return null+ let parsed+ try { parsed = JSON.parse(await readFile(old, 'utf8')) } catch { return null }+ if (parsed?.migrated) return null+ const tickets = await readTickets(env)+ let moved = 0+ for (const [id, ticket] of Object.entries(parsed?.paused ?? {})) {+ if (!tickets[id]) { tickets[id] = ticket; moved += 1 }+ }+ if (moved) await writeTickets(tickets, env)+ const pins = Array.isArray(parsed?.pins) ? parsed.pins : []+ if (pins.length) {+ const { pins: current } = await readConfig(env)+ await updateConfig({ pins: [...new Set([...current, ...pins])] }, env)+ }+ await writeFile(old, `${JSON.stringify({ migrated: true, to: { rules: configPath(env), tickets: ticketsPath(env) }, at: new Date().toISOString() }, null, 2)}\n`)+ return { tickets: moved, pins: pins.length }+}diff --git a/store/agents/harness-monitor/lib/format.mjs b/store/agents/harness-monitor/lib/format.mjsnew file mode 100644index 000000000..654f492e8--- /dev/null+++ b/store/agents/harness-monitor/lib/format.mjs@@ -0,0 +1,126 @@+/**+ * The dense list, as a terminal draws it.+ *+ * One line per harness, columns that line up, glyphs instead of words for state, and the totals on the+ * last line — the shape `tmux ls`, `docker ps` and `htop` all settled on, for the same reason: a fleet is+ * read by scanning down one column, not by reading sentences. Colour only when a terminal is listening,+ * and never as the only carrier of meaning: the glyph says it too.+ */++import { humanIdle } from './policy.mjs'+import { gb } from './state.mjs'++const CODES = { dim: '2', bold: '1', gold: '33', green: '32', red: '31', amber: '93', blue: '36' }++export function painter({ tty = false } = {}) {+ if (!tty) return Object.fromEntries([...Object.keys(CODES), 'plain'].map((key) => [key, (text) => String(text)]))+ const paint = (code) => (text) => `\u001b[${code}m${text}\u001b[0m`+ return { ...Object.fromEntries(Object.entries(CODES).map(([key, code]) => [key, paint(code)])), plain: (text) => String(text) }+}++/** ● running · ◐ working · ○ paused · $ shell · ✕ gone · ! waiting on you. Two characters wide so the+ * column never shifts when a glyph is double-width on someone's font. */+export function glyph(row, c) {+ if (row.needsInput) return c.amber('! ')+ if (row.state === 'running') return row.working ? c.gold('◐ ') : c.green('● ')+ if (row.state === 'paused') return c.dim('○ ')+ if (row.state === 'terminal') return c.dim('$ ')+ return c.dim('✕ ')+}++function pad(text, width, align = 'left') {+ const value = String(text ?? '')+ // Visible width: strip the escapes a painter may have added before measuring.+ const bare = value.replace(/\u001b\[[0-9;]*m/g, '')+ if (bare.length >= width) return align === 'right' ? value : `${value.slice(0, value.length - (bare.length - width))}`+ const gap = ' '.repeat(width - bare.length)+ return align === 'right' ? gap + value : value + gap+}++const mem = (bytes) => (bytes ? gb(bytes).replace(' ', '') : '—')++/** The table. `columns` is the terminal's width, used to decide what gets dropped: title first, then+ * branch, then project — a narrow pane still shows state, idle, engine and memory, which is the+ * minimum that makes the list worth reading. */+export function table(rows, { tty = false, columns = 120, numbered = true, now = Date.now() } = {}) {+ const c = painter({ tty })+ const wide = columns >= 110+ const medium = columns >= 88+ // Only when there is more than one machine in the list: a column that says the same thing on every+ // row is a column that costs width and carries nothing.+ const machines = new Set(rows.map((row) => row.machine))+ const machineWidth = machines.size > 1 ? Math.min(14, Math.max(...[...machines].map((name) => name.length))) : 0+ const widths = {+ n: numbered ? Math.max(2, String(rows.length).length) : 0,+ state: 2, idle: 5, engine: 8, model: wide ? 15 : 0, mem: 6,+ project: medium ? 20 : 0, branch: wide ? 14 : 0, machine: machineWidth,+ }+ const head = [+ numbered ? pad('#', widths.n, 'right') : '',+ pad('', widths.state), pad('IDLE', widths.idle), pad('ENGINE', widths.engine),+ widths.model ? pad('MODEL', widths.model) : '',+ pad('MEM', widths.mem, 'right'),+ widths.project ? ` ${pad('PROJECT', widths.project)}` : '',+ widths.branch ? pad('BRANCH', widths.branch) : '',+ widths.machine ? pad('MACHINE', widths.machine) : '',+ 'TITLE',+ ].filter(Boolean).join(' ')++ const lines = [c.dim(head)]+ rows.forEach((row, index) => {+ const title = row.title || row.name+ const line = [+ numbered ? c.dim(pad(index + 1, widths.n, 'right')) : '',+ glyph(row, c),+ pad(row.state === 'gone' ? '—' : humanIdle(row.idleMs), widths.idle),+ pad(row.engine, widths.engine),+ widths.model ? c.dim(pad(row.model ?? '—', widths.model)) : '',+ pad(mem(row.rssBytes), widths.mem, 'right'),+ widths.project ? ` ${pad(row.project, widths.project)}` : '',+ widths.branch ? c.dim(pad(row.branch ?? '—', widths.branch)) : '',+ widths.machine ? (row.local ? c.dim(pad(row.machine, widths.machine)) : c.blue(pad(row.machine, widths.machine))) : '',+ row.state === 'running' ? title : c.dim(title),+ ].filter(Boolean).join(' ')+ lines.push(line.length > columns + 64 ? line.slice(0, columns + 64) : line)+ })+ return lines.join('\n')+}++/** The line under the table: what the fleet is, in one breath. */+export function footer(summary, policy, { tty = false, problems = [] } = {}) {+ const c = painter({ tty })+ const parts = [+ `${summary.total} ${summary.total === 1 ? 'harness' : 'harnesses'}`,+ `${c.green(summary.running)} running`,+ summary.paused ? `${summary.paused} paused` : null,+ summary.gone ? `${summary.gone} gone` : null,+ summary.terminals ? `${summary.terminals} ${summary.terminals === 1 ? 'shell' : 'shells'}` : null,+ summary.needsInput ? c.amber(`${summary.needsInput} waiting on you`) : null,+ `${gb(summary.held)} held`,+ `${summary.projects} projects`,+ summary.machines > 1 ? `${summary.machines} machines` : null,+ ].filter(Boolean)+ const lines = [parts.join(c.dim(' · '))]+ if (policy) lines.push(c.dim(`policy: pause after ${policy.pauseAfterIdle} · hide after ${policy.hideAfterIdle} · ceiling ${policy.runningCeiling} running`))+ for (const problem of problems) lines.push(c.red(`${problem.machine}: ${problem.error}`))+ return lines.join('\n')+}++/** `hps prune --explain` and `hps pause --dry-run`: the plan, one line each, longest reason last. */+export function planLines(entries, { tty = false, verb = null } = {}) {+ const c = painter({ tty })+ const shown = entries.filter((entry) => entry.action !== 'keep' && (!verb || entry.action === verb))+ if (!shown.length) return c.dim('Nothing to do — every harness is where the policy wants it.')+ const width = Math.max(...shown.map((entry) => entry.name.length), 4)+ // Both columns are measured, never guessed: a hardcoded action width silently truncated `pause`+ // to `hiberna`, which is the kind of thing only a test notices.+ const verbWidth = Math.max(...shown.map((entry) => entry.action.length))+ return shown.map((entry) => `${c.bold(pad(entry.action, verbWidth))} ${pad(entry.name, width)} ${c.dim(entry.why)}`).join('\n')+}++export function receiptLine(result, { tty = false } = {}) {+ const c = painter({ tty })+ const mark = result.ok ? (result.already ? c.dim('=') : c.green('✓')) : result.refused ? c.amber('·') : c.red('✕')+ const freed = result.freed ? c.dim(` (+${gb(result.freed)})`) : ''+ return `${mark} ${result.action} ${result.name}${freed} ${c.dim('— ' + result.detail)}`+}diff --git a/store/agents/harness-monitor/lib/inventory.mjs b/store/agents/harness-monitor/lib/inventory.mjsnew file mode 100644index 000000000..bdece682d--- /dev/null+++ b/store/agents/harness-monitor/lib/inventory.mjs@@ -0,0 +1,236 @@+/**+ * One row per harness, from every source that knows something about it.+ *+ * The daemon knows who the agents are, where their panes are and when their transcripts last moved.+ * tmux knows whether a pane is alive, dead or attached. The process table knows what the engine is+ * holding. This package's own state file knows what a person decided (pinned, paused). This module is+ * where those four become the single row shape that the policy, the table and the hps all read, and+ * it is the only place that decides what `state` means.+ *+ * Every machine's agents are listed — the local bridge relays `machine_select` to any machine the user+ * has linked — but pane and memory facts, and every action, are local to this computer. A remote row is+ * marked `local: false` and reads as what it is: seen, not managed from here.+ */++import { existsSync } from 'node:fs'+import { homedir } from 'node:os'+import { basename, dirname } from 'node:path'+import { lastTurns } from './activity.mjs'+import { listAgents, machines } from './bridge.mjs'+import { engineProcess, panes, processTable } from './panes.mjs'+import { humanIdle } from './policy.mjs'+import { readRegistry, registryAsFrames } from './registry.mjs'++/** `runtime-v1:<agentId>:<engine>:<model>@<effort>` — the runtime profile's answer, as the daemon+ * sends it. A plain model name (older daemons) is passed through untouched. */+export function parseModel(selected) {+ if (typeof selected !== 'string' || !selected) return { model: null, effort: null }+ const body = selected.startsWith('runtime-v1:') ? selected.split(':').slice(3).join(':') : selected+ const at = body.lastIndexOf('@')+ if (at <= 0) return { model: body || null, effort: null }+ return { model: body.slice(0, at) || null, effort: body.slice(at + 1) || null }+}++/** Working directories are shown relative to `~`: a fleet list is read by the person whose home it is,+ * and the absolute prefix is the same eleven characters on every row. */+export function tilde(path, home = homedir()) {+ if (typeof path !== 'string' || !path) return ''+ return home && path.startsWith(home) ? `~${path.slice(home.length)}` : path+}++/** The project a row belongs to: the git root's name when there is one, else the folder's. Two agents+ * in two worktrees of one repo are two projects, on purpose — that is how they are worked on. */+export function projectOf(agent) {+ const project = agent.project+ if (!project) return { project: 'unknown', cwd: '', branch: null, remote: null }+ const cwd = project.cwd || ''+ return {+ project: project.name || basename(project.root || cwd) || basename(dirname(cwd)) || 'unknown',+ cwd,+ branch: project.branch || null,+ remote: project.remote || null,+ }+}++/** The first of these that is a real moment in time. `Date.parse` answers NaN rather than null, which is+ * exactly the value that must not reach an idle column, so it is filtered here and not by `??`. */+function firstTime(candidates, fallback) {+ for (const value of candidates) {+ const time = typeof value === 'string' ? Date.parse(value) : Number(value)+ if (Number.isFinite(time) && time > 0) return time+ }+ return fallback+}++/**+ * Merge one machine's agent frames with local pane and process facts.+ *+ * `state` is decided here and nowhere else:+ * the pane is gone from tmux → gone (nothing to resume; history only)+ * the pane is there and an engine is up → running+ * the pane is there, no engine, a ticket → paused (conversation intact, waiting to be resumed)+ * the pane is there, no engine, no ticket → terminal (a shell somebody opened; nothing to pause)+ * and that is the whole state machine. There is deliberately no fourth state: an earlier version had+ * `retired` as paused-plus-a-decision, and every consumer paid for it — a glyph, a filter, a verb, a+ * grace window — to express something a sorted list already expresses.+ *+ * ## Why a paused row needs the ticket to describe itself+ *+ * When an engine leaves, the daemon does not merely mark the row: it REWRITES it as a terminal. Measured+ * on a real pause, the row kept its `cwd` and lost everything else — `engine` became `terminal`,+ * `sessionId` became empty, `transcriptPath` and `title` became null. So a paused harness would appear in+ * Harness Monitor's own list as a nameless shell, and nothing would know which conversation to resume. The ticket+ * `pause()` wrote into `monitor.json` is the only record, and it is overlaid here.+ */+export function mergeRows(agents, { paneRows = new Map(), table = { byPid: new Map(), children: new Map() }, state = {}, machine = null, local = true, now = Date.now(), home = homedir(), turns = new Map(), registry = new Map() } = {}) {+ const pauseTickets = state.paused ?? {}+ const pins = new Set(state.pins ?? [])+ return agents.map((agent) => {+ const pane = agent.tmuxPane && local ? paneRows.get(agent.tmuxPane) ?? null : null+ const ticket = pauseTickets[agent.id] ?? null+ // A paused row describes itself from its ticket: the daemon has already forgotten what it was.+ const engine = agent.engine === 'terminal' && ticket?.engine ? ticket.engine : agent.engine+ const sessionId = agent.sessionId || ticket?.sessionId || null+ const proc = local ? engineProcess(pane, table, engine) : { pid: null, rss: 0, cpu: 0, procs: 0, engineAlive: agent.status === 'active' }+ // The one number every rule depends on. `agent.updatedAt` is deliberately NOT in this list: it is+ // the transcript's mtime, which a live engine bumps with bookkeeping between turns (see+ // activity.mjs). Last turn, else the daemon's last hook, else when the agent was registered.+ const reg = registry.get(agent.id)+ const lastActivity = firstTime([turns.get(agent.id), reg?.lastHookAt, Date.parse(agent.createdAt)], now)+ const idleMs = Math.max(0, now - lastActivity)+ const { project, cwd, branch, remote } = projectOf(agent)+ // A remote row cannot be looked up in this machine's tmux, so its liveness is the daemon's word for+ // it. A local row's liveness is the process table — which is the stricter of the two and the one a+ // person can verify, so it wins whenever it is available.+ const present = local ? Boolean(pane) : agent.status !== 'gone'+ let stateName = !present ? 'gone' : proc.engineAlive ? 'running' : 'paused'+ // A shell somebody opened is not a paused agent: it has no conversation and nothing to resume, so it+ // is shown as what it is and left out of every rule.+ if (stateName === 'paused' && engine === 'terminal' && !ticket) stateName = 'terminal'+ const { model, effort } = parseModel(agent.selectedModel)+ return {+ id: agent.id,+ sessionId,+ name: agent.name || ticket?.title || 'agent',+ title: agent.title || ticket?.title || null,+ engine,+ model, effort,+ state: stateName,+ stateSince: stateName === 'paused' && ticket ? (ticket.at ?? lastActivity) : lastActivity,+ pausedAt: ticket?.at ?? null,+ pane: agent.tmuxPane || null,+ paneTarget: pane?.target ?? null,+ project, cwd, home: tilde(cwd, home), branch, remote,+ lastActivity, idleMs, idle: humanIdle(idleMs),+ createdAt: firstTime([agent.createdAt], null),+ attached: Boolean(pane?.attached),+ // Mid-turn, as far as anything outside the daemon can tell: the engine is burning CPU, or its+ // transcript moved in the last minute and a half. Both are proxies, and both are only ever used+ // to REFUSE to pause something — never to claim an agent is busy in the interface.+ working: local+ ? proc.cpu > 5 || idleMs < 90_000 || (pane?.lastOutput ? now - pane.lastOutput < 60_000 : false)+ : idleMs < 90_000,+ lastOutput: pane?.lastOutput ?? null,+ transcript: reg?.transcriptPath ?? null,+ needsInput: false,+ pinned: pins.has(agent.id),+ workspaceGone: Boolean(cwd) && local && !existsSync(cwd),+ rssBytes: proc.rss,+ procs: proc.procs,+ cpu: proc.cpu,+ enginePid: proc.pid,+ cwdWas: ticket?.cwd ?? null,+ dsh: agent.dsh ?? null,+ dshName: agent.dshName ?? null,+ verdict: agent.verdict?.ready === undefined ? null : Boolean(agent.verdict.ready),+ machine: machine?.name ?? 'this machine',+ machineId: machine?.machineId ?? null,+ local,+ dead: Boolean(pane?.dead),+ }+ })+}++/**+ * The whole fleet, from every machine that answers.+ *+ * Failures are per machine and reported, never fatal: a fleet view that refuses to draw because one+ * linked laptop is asleep is worse than one that says which machine it could not reach.+ */+export async function collect({ state = {}, now = Date.now(), includeRemote = true, timeoutMs = 8000, home = homedir(), cache = new Map() } = {}) {+ const [paneRows, table, machineList, registry] = await Promise.all([panes(), processTable(), machines(), readRegistry()])+ const turns = await lastTurns(registry.rows.map((row) => ({ id: row.agentId, transcriptPath: row.transcriptPath })), { cache })+ const current = machineList.find((m) => m.current) ?? null+ const targets = [current, ...(includeRemote ? machineList.filter((m) => !m.current && m.online) : [])].filter(Boolean)+ const problems = []+ let rows = []++ // No daemon, no `harness` on PATH: fall back to the registry file this machine already has. Seeing+ // the fleet must not depend on the app running, and pausing is pure tmux either way.+ if (!targets.length) {+ if (!registry.rows.length) problems.push({ machine: 'this machine', error: 'No Harness daemon on the local bridge and no registry to read.' })+ else problems.push({ machine: 'this machine', error: 'Read from the registry file — the Harness daemon is not answering, so models, branches and remote machines are missing.' })+ const rowsOffline = mergeRows(registryAsFrames(registry.rows), { paneRows, table, state, machine: null, local: true, now, home, turns, registry: registry.byId })+ rowsOffline.sort((a, b) => a.idleMs - b.idleMs || a.name.localeCompare(b.name))+ return { rows: rowsOffline, machines: machineList, problems, observedAt: now, degraded: true }+ }++ await Promise.all(targets.map(async (machine) => {+ try {+ const agents = await listAgents(machine.machineId, { timeoutMs })+ rows = rows.concat(mergeRows(agents, { paneRows, table, state, machine, local: machine.current === true, now, home, turns, registry: registry.byId }))+ } catch (error) {+ problems.push({ machine: machine.name, error: error instanceof Error ? error.message : String(error) })+ }+ }))++ rows.sort((a, b) => a.idleMs - b.idleMs || a.name.localeCompare(b.name))+ return { rows, machines: machineList, problems, observedAt: now }+}++/** Totals a person reads before deciding anything: the gauge in the header and the CLI's last line. */+export function summarize(rows) {+ const by = (state) => rows.filter((row) => row.state === state).length+ return {+ total: rows.length,+ running: by('running'),+ paused: by('paused'),+ gone: by('gone'),+ terminals: by('terminal'),+ needsInput: rows.filter((row) => row.needsInput).length,+ working: rows.filter((row) => row.working && row.state === 'running').length,+ held: rows.reduce((sum, row) => sum + (row.rssBytes || 0), 0),+ projects: new Set(rows.map((row) => row.project)).size,+ machines: new Set(rows.map((row) => row.machine)).size,+ }+}++/**+ * Resolve what a person typed to exactly one row, or say why it is ambiguous.+ *+ * Accepted, in order: a row number from the last `ls`, a tmux pane id (`%42`), an agent-id prefix, an+ * exact name, then a unique case-insensitive substring of the name or title. The same grammar the shell+ * gave everyone for job control — `%3` is a pane here and a job there — so it needs no learning.+ */+export function resolveRef(ref, rows) {+ const text = String(ref ?? '').trim()+ if (!text) return { error: 'Name a harness: a row number, a %pane, an id, or part of its name.' }+ if (/^\d+$/.test(text)) {+ const row = rows[Number(text) - 1]+ return row ? { row } : { error: `There is no row ${text} — the list has ${rows.length}.` }+ }+ if (/^%\d+$/.test(text)) {+ const matches = rows.filter((row) => row.pane === text)+ return matches.length === 1 ? { row: matches[0] } : { error: `No harness is on pane ${text}.` }+ }+ const exactId = rows.filter((row) => row.id === text || row.id.startsWith(text))+ if (exactId.length === 1) return { row: exactId[0] }+ if (exactId.length > 1) return { error: `${text} matches ${exactId.length} agent ids. Use a longer prefix.` }+ const exactName = rows.filter((row) => row.name.toLowerCase() === text.toLowerCase())+ if (exactName.length === 1) return { row: exactName[0] }+ const needle = text.toLowerCase()+ const loose = rows.filter((row) => row.name.toLowerCase().includes(needle) || (row.title ?? '').toLowerCase().includes(needle))+ if (loose.length === 1) return { row: loose[0] }+ if (loose.length > 1) return { error: `${text} matches ${loose.length} harnesses: ${loose.slice(0, 5).map((row) => row.name).join(', ')}${loose.length > 5 ? '…' : ''}` }+ return { error: `No harness matches ${text}.` }+}diff --git a/store/agents/harness-monitor/lib/panes.mjs b/store/agents/harness-monitor/lib/panes.mjsnew file mode 100644index 000000000..80073699f--- /dev/null+++ b/store/agents/harness-monitor/lib/panes.mjs@@ -0,0 +1,241 @@+/**+ * tmux and the process table — the two things the daemon does not put on the wire.+ *+ * What the bridge knows: who the agents are, where their panes are, when their transcripts last moved.+ * What it does not: whether a pane is dead, whether anybody is attached to it, and how much memory the+ * engine behind it is holding. Those are one `tmux list-panes` and one `ps` away, and they are the two+ * columns that make a fleet legible — so they are read here, cheaply, once per refresh.+ *+ * Every tmux call is `execFile` with an argument list: no shell, no interpolation, and a pane id is+ * validated against `%\d+` before it is ever passed, because a pane id from a bad snapshot must fail+ * as an argument rather than arrive somewhere as syntax.+ */++import { execFile } from 'node:child_process'+import { promisify } from 'node:util'++const exec = promisify(execFile)+const PANE = /^%\d+$/++export function isPaneId(value) { return typeof value === 'string' && PANE.test(value) }++function assertPane(pane) {+ if (!isPaneId(pane)) throw new Error(`Not a tmux pane id: ${JSON.stringify(pane)}`)+ return pane+}++async function tmux(args, { timeout = 4000 } = {}) {+ const { stdout } = await exec('tmux', args, { timeout, maxBuffer: 4 * 1024 * 1024, encoding: 'utf8' })+ return stdout+}++/** tmux renders a raw control byte in `-F` output as its octal escape (`\\037`), so a separator has to+ * be printable. `§§` is: two bytes no process name or session name carries, and a line that somehow+ * did contain it fails the pane-id check and is skipped rather than parsed wrong. */+const SEP = '\u00a7\u00a7'++const FIELDS = [+ 'pane_id', 'pane_dead', 'pane_pid', 'pane_current_command', 'session_name',+ 'session_attached', 'window_index', 'pane_index', '@harness_engine_exit', 'window_activity',+]++/**+ * Every pane on this tmux server, by pane id.+ *+ * `dead` is a pane whose process exited while tmux was told to keep it — its scrollback is still there+ * and `respawn-pane` brings it back, which is what makes pausing lossless. `engineExit` is the status+ * Harness's own launch wrapper records when an engine leaves and the pane falls back to a shell: its+ * presence is the difference between "the engine is gone" and "the install is still running".+ */+export async function panes({ run = tmux } = {}) {+ let out+ try { out = await run(['list-panes', '-a', '-F', FIELDS.map((f) => `#{${f}}`).join(SEP)]) }+ catch { return new Map() } // no tmux server at all: every agent is gone, and the caller says so+ const rows = new Map()+ for (const line of out.split('\n')) {+ if (!line.trim()) continue+ const [id, dead, pid, command, session, attached, window, index, engineExit, activity] = line.split(SEP)+ if (!isPaneId(id)) continue+ rows.set(id, {+ pane: id,+ dead: dead === '1',+ pid: Number(pid) || null,+ command: command || '',+ session: session || '',+ attached: attached === '1',+ target: `${session}:${window}.${index}`,+ engineExit: engineExit === '' || engineExit === undefined ? null : Number(engineExit),+ // tmux counts in seconds. Last time anything was DRAWN in this window: not a turn (a spinner is+ // activity too), but the right signal for "something is happening in there right now".+ lastOutput: activity ? Number(activity) * 1000 : null,+ })+ }+ return rows+}++/** One snapshot of the process table, as a parent → children index. Cheaper than one `ps` per agent,+ * and consistent: every row in a refresh is measured against the same instant. */+export async function processTable({ run = exec } = {}) {+ let stdout = ''+ try { ({ stdout } = await run('ps', ['-Ao', 'pid=,ppid=,rss=,pcpu=,comm='], { timeout: 6000, maxBuffer: 8 * 1024 * 1024, encoding: 'utf8' })) }+ catch { return { byPid: new Map(), children: new Map() } }+ const byPid = new Map()+ const children = new Map()+ for (const line of stdout.split('\n')) {+ const match = /^\s*(\d+)\s+(\d+)\s+(\d+)\s+([\d.]+)\s+(.*)$/.exec(line)+ if (!match) continue+ const pid = Number(match[1]); const ppid = Number(match[2])+ byPid.set(pid, { pid, ppid, rss: Number(match[3]) * 1024, cpu: Number(match[4]) || 0, comm: match[5].trim() })+ if (!children.has(ppid)) children.set(ppid, [])+ children.get(ppid).push(pid)+ }+ return { byPid, children }+}++/** Command names that mean "this is the engine", per engine id. The pane's shell spawns the engine as+ * a child, and some engines then spawn their own vendored binary — so the walk matches on basename+ * and takes the shallowest match, which is the process a SIGTERM should go to. */+const ENGINE_COMMANDS = {+ claude: ['claude'], codex: ['codex'], opencode: ['opencode'], cursor: ['cursor-agent'],+ gemini: ['gemini'], grok: ['grok'], copilot: ['copilot'], amp: ['amp'], pi: ['pi'],+ hermes: ['hermes'], muse: ['muse'], kilo: ['kilo'], devin: ['devin'], commandcode: ['cmd'],+ aider: ['aider'], goose: ['goose'], qwen: ['qwen'], droid: ['droid'], auggie: ['auggie'],+}++const SHELLS = new Set(['zsh', 'bash', 'sh', 'fish', 'dash', 'ksh', '-zsh', '-bash'])++/**+ * Walk a pane's process subtree: the engine process to signal, the subtree's memory, its CPU.+ *+ * Memory is the whole subtree because an engine's helpers are its cost too — the number a person is+ * deciding about is "what do I get back if I pause this", not "how big is one pid".+ *+ * The engine is matched at the ROOT as well as below it. tmux's `pane_pid` is the engine itself for+ * every agent whose pane was started on the engine directly (most of them); it is a shell only when the+ * launch wrapper is in play, or after the engine has left and the pane fell back to one. Matching is on+ * the executable's basename, not the process title, because Claude Code renames itself to its version+ * (`2.1.268`) the moment it starts — `pane_current_command` is that title, and it is useless here.+ */+export function engineProcess(pane, table, engine) {+ if (!pane?.pid || !table.byPid.size) return { pid: null, rss: 0, cpu: 0, procs: 0, engineAlive: false }+ const wanted = new Set(ENGINE_COMMANDS[engine] ?? [engine])+ let pid = null, rss = 0, cpu = 0, procs = 0, depth = Infinity+ const walk = (current, level) => {+ const info = table.byPid.get(current)+ if (!info) return+ procs += 1; rss += info.rss; cpu += info.cpu+ const base = info.comm.split('/').pop()+ if (wanted.has(base) && level < depth) { pid = current; depth = level }+ for (const child of table.children.get(current) ?? []) walk(child, level + 1)+ }+ walk(pane.pid, 0)+ const self = table.byPid.get(pane.pid)+ // The pane's own shell is not the agent's cost; subtract it when the engine is gone and all that is+ // left is the fallback shell, so a paused row reads 0 rather than a few megabytes of zsh.+ if (!pid && self && SHELLS.has(self.comm.split('/').pop())) return { pid: null, rss: 0, cpu: 0, procs, engineAlive: false }+ return { pid, rss, cpu, procs, engineAlive: pid !== null }+}++/** The pane's visible screen, for the blocked-prompt check and the inspector's preview. */+export async function capture(pane, { lines = 40, run = tmux } = {}) {+ assertPane(pane)+ try { return await run(['capture-pane', '-p', '-t', pane, '-S', `-${Math.max(1, Math.min(200, lines))}`]) }+ catch { return '' }+}++/**+ * Does this pane look like it is waiting on a person?+ *+ * Best effort, and deliberately loud about it: the app's own **Agents needing input** (⇧⌘I) is the+ * authority, and the daemon does not put pending questions on the local bridge. What is available is+ * the pane's last screen, and an engine waiting for an answer draws a recognizable prompt on it. A+ * false positive costs a harness that stays running; a false negative costs a question paused before it+ * was read — so the patterns are broad on purpose, and the policy protects anything that matches.+ */+const BLOCKED_PATTERNS = [+ /\bdo you want to (proceed|continue|allow)\b/i,+ /\b(allow|approve|permit) (this )?(command|tool|edit|request)\b/i,+ /\?\s*$/,+ /\(y\/n\)|\[y\/n\]|\(yes\/no\)/i,+ /^\s*❯?\s*1[.)]\s+\S/m,+ /\bwaiting for (your )?(input|answer|approval)\b/i,+ /\bpress (enter|y) to\b/i,+ // How an engine tells you it is holding a choice open. Found by watching Claude Code's real trust+ // prompt, which an earlier version of this list walked straight past.+ /\benter to (confirm|continue|select)\b/i,+ /\besc to cancel\b/i,+ /\bis this a project you (created or )?trust/i,+]++/**+ * A vertical menu: a cursor line with at least one more option under it.+ *+ * `❯ ` alone is NOT enough, and that mistake is worth keeping a note about: Claude Code echoes the+ * prompt you just submitted as `❯ your text`, so matching a lone cursor line marked every recently used+ * harness as blocked and refused to pause any of them. A menu has a second option under the cursor —+ * short, indented, and not a separator — and that is what this looks for.+ */+function looksLikeMenu(lines) {+ for (let i = 0; i < lines.length - 1; i += 1) {+ if (!/^\s*❯\s+\S/.test(lines[i])) continue+ const next = lines[i + 1]+ if (/^\s{2,}\S/.test(next) && next.trim().length <= 60 && !/^\s*[─━═]/.test(next)) return true+ }+ return false+}++/** The prompt an idle engine draws when it is waiting for a TASK, not for an answer. Subtracted before+ * anything else runs — otherwise every quiet harness looks blocked and nothing would ever be paused. */+const IDLE_PROMPTS = [+ /^\s*❯\s*$/,+ /^\s*>\s*$/,+ /shift\+tab to cycle/i,+ /for shortcuts\s*$/i,+]++export function looksBlocked(screen) {+ const text = String(screen || '').replace(/\u001b\[[0-9;?]*[a-zA-Z]/g, '')+ const lines = text.split('\n').map((line) => line.replace(/[─━═]{4,}.*$/, '').trimEnd()).filter((line) => line.trim())+ const tail = lines.slice(-8)+ if (!tail.length) return false+ // An engine sitting at its own empty prompt is idle, not blocked — and its prompt line looks exactly+ // like a selected option, so it is removed before the patterns run.+ const candidates = tail.filter((line) => !IDLE_PROMPTS.some((pattern) => pattern.test(line)))+ if (!candidates.length) return false+ const body = candidates.join('\n')+ return looksLikeMenu(candidates) || BLOCKED_PATTERNS.some((pattern) => pattern.test(body))+}++/** Hold a pane open across its process exiting, and hand it back to tmux's own disposal afterwards —+ * the same pair the daemon uses around a restart (`holdOpen` / `clearPaneRemainOnExit`). Pausing sets+ * it before the engine is asked to leave, so a pane whose launch wrapper predates the fallback shell+ * keeps its scrollback instead of taking its window down with it. */+export async function holdOpen(pane, on, { run = tmux } = {}) {+ assertPane(pane)+ try { await run(['set-option', '-w', '-t', pane, 'remain-on-exit', on ? 'on' : 'off']); return true }+ catch { return false }+}++export async function paneState(pane, { run = tmux } = {}) {+ assertPane(pane)+ try {+ const out = await run(['display-message', '-p', '-t', pane, `#{pane_dead}${SEP}#{pane_current_command}${SEP}#{@harness_engine_exit}`])+ const [dead, command, engineExit] = out.trim().split(SEP)+ return { dead: dead === '1', command: command || '', engineExit: engineExit ? Number(engineExit) : null }+ } catch { return null }+}++/** Type a line into a pane's shell. Used for one thing only: the local resume path, when the daemon is+ * not reachable and the pane has already fallen back to a shell that adopts an engine when told to. */+export async function sendLine(pane, line, { run = tmux } = {}) {+ assertPane(pane)+ if (/[\r\n\u0000]/.test(line)) throw new Error('A pane command is one line.')+ await run(['send-keys', '-t', pane, line, 'Enter'])+}++export async function respawn(pane, { run = tmux } = {}) {+ assertPane(pane)+ await run(['respawn-pane', '-k', '-t', pane])+}++export { tmux as runTmux }diff --git a/store/agents/harness-monitor/lib/policy.mjs b/store/agents/harness-monitor/lib/policy.mjsnew file mode 100644index 000000000..50914b329--- /dev/null+++ b/store/agents/harness-monitor/lib/policy.mjs@@ -0,0 +1,200 @@+/**+ * The rules, as data and as one pure function.+ *+ * Everything about what *should* happen to a fleet lives here: no tmux, no sockets, no clock of its+ * own. `decide()` takes rows and a policy and returns a plan — one entry per row, with the rule that+ * chose it and a sentence saying why. The CLI prints that plan, the viewer draws it, `hps prune --apply`+ * executes it, and the tests assert on it. A rule nobody can simulate is a rule nobody should run,+ * which is the whole reason this file has no side effects.+ *+ * The vocabulary, kept identical everywhere:+ * running the engine process is alive — a normal Harness agent+ * paused the pane and the conversation are there, the engine process is not (the daemon's own+ * "dormant but still viewable agent"); resuming it resumes the conversation+ * gone no pane left; the daemon dropped the row. History only, nothing to resume+ */++/** Shipped defaults. Every number here is a judgement, and every one of them is meant to be argued+ * with in `hps policy` — which is why they are values in a file and not `if` statements. */+export const DEFAULT_POLICY = {+ spec: 1,+ /** Most engines running at once on one machine — a backstop, not a working limit. At 100 it only fires on a+ * day with more harnesses going than anyone plans for; the idle rule does the everyday work. Lower it on a+ * machine that swaps: ~300 MB each is the number to divide into your free memory. */+ runningCeiling: 100,+ /** Idle this long and the engine is paused. A day, because a day survives an overnight break: yesterday+ * afternoon's work is still there, warm, in the morning. The first default was 4h, and on a real fleet the+ * only thing it caught that a day does not was eight harnesses from the previous afternoon. */+ pauseAfterIdle: '1d',+ /** Idle this long and the row drops below the fold — still there under `--all`, still resumable, just+ * not in the way. A LIST rule, not a state: an earlier version made this a `retire` verb with its own+ * state, mark and grace window, and none of that earned its keep. */+ hideAfterIdle: '14d',+ /** A workspace that no longer exists on disk has no work left in it. */+ pauseWhenWorkspaceGone: true,+ protect: {+ /** An agent waiting on a person is not idle; it is blocked on us. */+ needsInput: true,+ /** Mid-turn. Pausing here would throw away work in flight. */+ working: true,+ /** Somebody is looking at this pane right now. */+ attached: true,+ /** Listed in `pins`. The one escape hatch the rules must never overrule. */+ pinned: true,+ },+}++const UNITS = { s: 1000, m: 60_000, h: 3_600_000, d: 86_400_000, w: 604_800_000 }++/** `"4h"`, `"90m"`, `"14d"`, `"1w"`, or a plain number of milliseconds. Throws on anything else —+ * a policy with a typo in it must fail loudly at load, not quietly pause the fleet. */+export function parseDuration(value) {+ if (typeof value === 'number' && Number.isFinite(value) && value >= 0) return Math.floor(value)+ const match = /^(\d+(?:\.\d+)?)\s*([smhdw])$/.exec(String(value ?? '').trim().toLowerCase())+ if (!match) throw new Error(`Not a duration: ${JSON.stringify(value)}. Use 30s, 90m, 4h, 14d or 1w.`)+ return Math.floor(Number(match[1]) * UNITS[match[2]])+}++/** Round-trips `parseDuration`: the number a person typed, or the shortest exact unit for a raw ms. */+export function formatDuration(ms) {+ const n = Math.max(0, Math.floor(Number(ms) || 0))+ for (const [unit, size] of [['w', UNITS.w], ['d', UNITS.d], ['h', UNITS.h], ['m', UNITS.m], ['s', UNITS.s]]) {+ if (n >= size && n % size === 0) return `${n / size}${unit}`+ }+ return `${n}ms`+}++/** Age as a person reads it in a dense table: `3d`, `4h`, `22m`, `now`. Never two units — a column+ * that sometimes says `3d 4h` stops being scannable, and the second unit never changed a decision. */+export function humanIdle(ms) {+ const n = Math.max(0, Math.floor(Number(ms) || 0))+ if (n < 45_000) return 'now'+ if (n < UNITS.h) return `${Math.round(n / UNITS.m)}m`+ if (n < UNITS.d) return `${Math.round(n / UNITS.h)}h`+ if (n < 7 * UNITS.d) return `${Math.floor(n / UNITS.d)}d`+ const weeks = Math.floor(n / UNITS.w)+ return weeks > 9 ? '9w+' : `${weeks}w`+}++function expandHome(path, home) {+ if (typeof path !== 'string' || !path) return null+ return path.startsWith('~') ? `${home}${path.slice(1)}` : path+}++/** Validate and fill in, so every consumer can read `policy.runningCeiling` without a guard. Unknown+ * keys are kept: a policy file written by a newer Harness Monitor must survive a round trip through an older+ * one rather than being silently rewritten without its rules. */+export function normalizePolicy(raw, { home = '' } = {}) {+ const policy = { ...DEFAULT_POLICY, ...(raw && typeof raw === 'object' ? raw : {}) }+ policy.protect = { ...DEFAULT_POLICY.protect, ...(raw?.protect && typeof raw.protect === 'object' ? raw.protect : {}) }+ const ceiling = Number(policy.runningCeiling)+ if (!Number.isInteger(ceiling) || ceiling < 0 || ceiling > 512) throw new Error('runningCeiling must be a whole number of agents between 0 and 512.')+ policy.runningCeiling = ceiling+ policy.pauseAfterIdleMs = parseDuration(policy.pauseAfterIdle)+ policy.hideAfterIdleMs = parseDuration(policy.hideAfterIdle)+ if (policy.hideAfterIdleMs < policy.pauseAfterIdleMs) {+ throw new Error('hideAfterIdle must be at least pauseAfterIdle — a row cannot drop out of the list before it is even paused.')+ }+ return policy+}++/** Why this row cannot be touched, or null. Order is the order a person would say them in. */+export function protectionFor(row, policy) {+ const p = policy.protect+ if (p.pinned && row.pinned) return { by: 'pinned', why: 'pinned' }+ if (p.needsInput && row.needsInput) return { by: 'needsInput', why: 'waiting on you' }+ if (p.working && row.working) return { by: 'working', why: 'mid-turn' }+ if (p.attached && row.attached) return { by: 'attached', why: 'you are looking at it' }+ return null+}++/** The threshold as the person wrote it (`14d`), not as the clock reads it back (`2w`): a message that+ * echoes a different unit than the policy file does reads like a second, unexplained rule. */+function said(policy, key) {+ const raw = policy[key]+ return typeof raw === 'string' && raw.trim() ? raw.trim() : formatDuration(policy[`${key}Ms`])+}++const RUNNING = new Set(['running'])++/**+ * The plan. One entry per row, in the order given, plus the rules' own totals.+ *+ * `action` is what the row should become: `pause` or `keep`. Nothing here decides+ * how — `pause.mjs` owns the mechanics, and `forget` never means deleting a transcript.+ */+export function decide(rows, rawPolicy, { now = Date.now(), home = '' } = {}) {+ const policy = rawPolicy?.pauseAfterIdleMs ? rawPolicy : normalizePolicy(rawPolicy, { home })+ const entries = []+ const keep = (row, why, extra = {}) => ({ id: row.id, name: row.name, action: 'keep', rule: 'keep', why, ...extra })++ for (const row of rows) {+ const idle = Math.max(0, Number(row.idleMs) || 0)+ if (row.state === 'gone') {+ const goneFor = Math.max(0, now - (row.stateSince ?? now))+ entries.push(goneFor >= policy.forgetAfterRetiredMs+ ? { id: row.id, name: row.name, action: 'forget', rule: 'gone', why: `no pane left, and gone for ${humanIdle(goneFor)} — drop it from the hps (its transcript stays where the engine wrote it)` }+ : keep(row, 'no pane left; kept in history for now'))+ continue+ }+ // A shell somebody opened is not an agent: no conversation, nothing to resume, no rule applies.+ if (row.state === 'terminal') { entries.push(keep(row, 'a shell, not an engine — nothing to pause')); continue }++ const protection = protectionFor(row, policy)+ if (protection) {+ entries.push(keep(row, protection.why, { protectedBy: protection.by }))+ continue+ }+ if (policy.pauseWhenWorkspaceGone && row.workspaceGone && RUNNING.has(row.state)) {+ entries.push({ id: row.id, name: row.name, action: 'pause', rule: 'workspaceGone', why: `its folder is gone (${row.cwd || 'unknown'})`, frees: row.rssBytes ?? 0 })+ continue+ }+ if (RUNNING.has(row.state) && idle >= policy.pauseAfterIdleMs) {+ entries.push({ id: row.id, name: row.name, action: 'pause', rule: 'pauseAfterIdle', why: `idle ${humanIdle(idle)}, past ${said(policy, 'pauseAfterIdle')}`, frees: row.rssBytes ?? 0 })+ continue+ }+ entries.push(keep(row, RUNNING.has(row.state) ? `active ${humanIdle(idle)} ago` : 'paused'))+ }++ // The ceiling runs last, over whatever is still running after the idle rules. Protected rows hold a+ // slot but are never paused: a person with 20 pinned agents has said what they want, and a rule+ // that overruled that would make pinning worthless. Freshest activity keeps its slot (LRU out).+ const survivors = rows.filter((row, i) => RUNNING.has(row.state) && entries[i].action === 'keep')+ const byId = new Map(rows.map((row, i) => [row.id, entries[i]]))+ const ranked = [...survivors].sort((a, b) => (a.idleMs ?? 0) - (b.idleMs ?? 0))+ let slots = policy.runningCeiling+ for (const row of ranked) {+ if (slots > 0) { slots -= 1; continue }+ const entry = byId.get(row.id)+ if (entry.protectedBy) continue+ entry.action = 'pause'+ entry.rule = 'runningCeiling'+ entry.why = `over the ceiling of ${policy.runningCeiling} running, and the least recently active (idle ${humanIdle(row.idleMs ?? 0)})`+ entry.frees = row.rssBytes ?? 0+ }++ return { policy, entries, totals: totals(entries, rows) }+}++function totals(entries, rows) {+ const rss = new Map(rows.map((row) => [row.id, Number(row.rssBytes) || 0]))+ const count = (action) => entries.filter((entry) => entry.action === action).length+ const frees = entries.filter((entry) => entry.action === 'pause')+ .reduce((sum, entry) => sum + (rss.get(entry.id) || 0), 0)+ const runningNow = rows.filter((row) => row.state === 'running').length+ return {+ rows: rows.length,+ pause: count('pause'),+ keep: count('keep'),+ runningNow,+ runningAfter: runningNow - entries.filter((e) => e.action === 'pause' && rows.find((r) => r.id === e.id)?.state === 'running').length,+ frees,+ }+}++/** What a policy would do, without saying it will: the shape the viewer's draggable thresholds and+ * `hps policy --simulate` both read. Same code path as `gc`, so the preview cannot drift. */+export function simulate(rows, policy, options) {+ const plan = decide(rows, policy, options)+ return { ...plan.totals, plan: plan.entries.filter((entry) => entry.action !== 'keep') }+}diff --git a/store/agents/harness-monitor/lib/registry.mjs b/store/agents/harness-monitor/lib/registry.mjsnew file mode 100644index 000000000..f3fe4b810--- /dev/null+++ b/store/agents/harness-monitor/lib/registry.mjs@@ -0,0 +1,53 @@+/**+ * The daemon's own registry file, read directly.+ *+ * Two things the wire does not carry are in here: the path to each agent's transcript (a file path is+ * not something the daemon hands to clients, and rightly) and the hook timestamps it records at turn+ * boundaries. Both are needed to tell a five-day-old conversation from a busy one, so Harness Monitor reads the+ * file — never writes it. The registry is the daemon's; this is a reader with no lock and no repair.+ *+ * It is also the fallback when the daemon cannot be reached at all: a fleet you can still SEE when the+ * app is not running is worth more than an error, and pausing is pure tmux, so most of Harness Monitor keeps+ * working from this file alone.+ */++import { readFile } from 'node:fs/promises'+import { homedir } from 'node:os'+import { join } from 'node:path'++export function registryPath(env = process.env) {+ return env.HPS_REGISTRY || join(env.HARNESS_HOME || join(homedir(), '.harness'), 'cli', 'data', 'registry.json')+}++/** `{ byId, rows }`, or an empty pair when there is no registry to read (a machine that has never run+ * an agent, or a daemon whose data lives somewhere this user cannot see). */+export async function readRegistry(env = process.env) {+ let parsed+ try { parsed = JSON.parse(await readFile(registryPath(env), 'utf8')) }+ catch { return { byId: new Map(), rows: [] } }+ const rows = (Array.isArray(parsed) ? parsed : []).filter((row) => row && typeof row.agentId === 'string')+ return { byId: new Map(rows.map((row) => [row.agentId, row])), rows }+}++/** The registry row in the shape `mergeRows` takes, for the no-daemon path. Deliberately lossy: no+ * model, no branch, no verdict — the things only the daemon computes are absent rather than faked. */+export function registryAsFrames(rows) {+ return rows.map((row) => ({+ id: row.agentId,+ sessionId: row.sessionId ?? null,+ name: row.title || row.projectDir || row.agentId.slice(0, 8),+ title: row.title ?? null,+ status: row.active ? 'active' : 'offline',+ createdAt: new Date(row.registeredAt ?? Date.now()).toISOString(),+ updatedAt: new Date(row.lastHookAt ?? row.registeredAt ?? Date.now()).toISOString(),+ tmuxPane: row.tmuxPane ?? null,+ terminal: { available: true, primary: row.primaryRuntimeKey ?? '', runtimes: row.runtimes ?? [] },+ engine: row.engine,+ selectedModel: row.model ?? null,+ project: row.cwd ? { name: row.projectDir || '', cwd: row.cwd, root: null, remote: null, branch: null } : null,+ dsh: row.dsh?.id ?? null,+ dshName: null,+ verdict: null,+ codexHome: row.codexHome ?? null,+ }))+}diff --git a/store/agents/harness-monitor/lib/resume.mjs b/store/agents/harness-monitor/lib/resume.mjsnew file mode 100644index 000000000..9a208f012--- /dev/null+++ b/store/agents/harness-monitor/lib/resume.mjs@@ -0,0 +1,60 @@+/**+ * How each engine is asked to come back to a conversation it already had.+ *+ * Mirrors the daemon's own two tables — `LAUNCH_RESUME_FLAG` and `ENGINE_CLI_ALIASES` in+ * `cli/src/lib/engineLaunch.ts` and `engineBin.ts` — because resuming a paused harness types the same+ * command into the pane that the daemon would have built. Mirrored rather than imported: this package+ * installs on its own and cannot reach the daemon's TypeScript.+ *+ * An engine that is NOT in this table cannot be resumed with its conversation, so Harness Monitor refuses to pause+ * it at all. That refusal is the whole safety property: nothing is ever stopped that cannot be brought+ * back. `devin` is deliberately absent (the daemon omits it too — it has no resume flag), and so is+ * `terminal`, which has no conversation to resume.+ */++/** engine → the argv that resumes a session id. A leading token without a dash is a SUBCOMMAND. */+export const RESUME_ARGS = {+ claude: ['--resume'],+ codex: ['resume'],+ cursor: ['--resume'],+ opencode: ['--session'],+ kilo: ['--session'],+ pi: ['--session'],+ hermes: ['--resume'],+ commandcode: ['--resume'],+ muse: ['resume'],+ amp: ['threads', 'continue'],+ grok: ['--resume'],+ agy: ['--conversation'],+ copilot: ['--resume'],+}++/** engine → the command a person types. The first alias is the canonical one. */+export const ENGINE_BIN = {+ claude: 'claude', codex: 'codex', cursor: 'cursor-agent', opencode: 'opencode', pi: 'pi',+ hermes: 'hermes', commandcode: 'cmd', muse: 'muse', amp: 'amp', kilo: 'kilo', grok: 'grok',+ agy: 'agy', copilot: 'copilot', devin: 'devin',+}++/** A session id as the engines write them: uuid-shaped, or hex/ulid-ish. Checked because this string is+ * about to be typed into a shell — anything with a space, a quote or a semicolon in it is refused here+ * rather than quoted and hoped for. */+const SESSION_ID = /^[A-Za-z0-9][A-Za-z0-9._-]{7,127}$/++export function canResume(engine) {+ return Boolean(RESUME_ARGS[engine] && ENGINE_BIN[engine])+}++/**+ * The one line that brings an engine back: `claude --resume <id>`, `codex resume <id>`.+ *+ * Typed into the pane's fallback shell, which is where a paused harness leaves it. The daemon watches+ * that pane, recognizes the engine, and re-adopts the row — the same path it documents for a person who+ * types the engine's name into a pane whose engine has left (`adoptEngine`). Verified end to end against+ * a real Claude Code session: the conversation, the pane and the agent id all came back.+ */+export function resumeCommand(engine, sessionId) {+ if (!canResume(engine)) throw new Error(`Harness Monitor does not know how to resume ${engine}, so it will not pause it.`)+ if (!SESSION_ID.test(String(sessionId ?? ''))) throw new Error('That session id is not one an engine wrote.')+ return [ENGINE_BIN[engine], ...RESUME_ARGS[engine], sessionId].join(' ')+}diff --git a/store/agents/harness-monitor/lib/state.mjs b/store/agents/harness-monitor/lib/state.mjsnew file mode 100644index 000000000..334c21ce2--- /dev/null+++ b/store/agents/harness-monitor/lib/state.mjs@@ -0,0 +1,121 @@+/**+ * What a person decided, and what Harness Monitor did about it — read and written through one module so+ * the CLI and the pane can never disagree about where anything lives.+ *+ * The rules and pins are `~/.config/harness/policy.jsonc`; the resume tickets and the log are under+ * `~/.harness/monitor/` (lib/config.mjs has why). The only file left in the WORKSPACE is the verdict,+ * because that is the one file Harness itself reads, and it reads it from the workspace.+ */++import { mkdir, rename, writeFile } from 'node:fs/promises'+import { join } from 'node:path'+import { appendLog, migrateWorkspace, readConfig, readLogFile, readTickets, updateConfig, writeTickets } from './config.mjs'+import { DEFAULT_POLICY, normalizePolicy } from './policy.mjs'++export function verdictPath(workspace) { return join(workspace, '.harness', 'verdict.json') }++export const EMPTY_STATE = { spec: 1, policy: { ...DEFAULT_POLICY }, pins: [], paused: {} }++/** Write through a temp file in the same directory: a reader must never see half of it. */+export async function atomicJson(path, value) {+ await mkdir(join(path, '..'), { recursive: true })+ const temp = `${path}.${process.pid}.tmp`+ await writeFile(temp, `${JSON.stringify(value, null, 2)}\n`, { mode: 0o600 })+ await rename(temp, path)+}++/** The rules, the pins and the tickets, as one object. `workspace` is only consulted to carry an older+ * per-workspace file forward the first time it is seen. */+export async function readState(workspace, env = process.env) {+ if (workspace) await migrateWorkspace(workspace, env).catch(() => null)+ const { path, policy, pins } = await readConfig(env)+ const merged = { ...DEFAULT_POLICY, ...policy, protect: { ...DEFAULT_POLICY.protect, ...(policy.protect ?? {}) } }+ // A typo must fail here, at the edge, where the message can name the file — not three layers down inside+ // a rule while the fleet waits.+ try { normalizePolicy(merged) } catch (error) { throw new Error(`${path}: ${error.message}`) }+ return { spec: 1, policy: merged, pins, paused: await readTickets(env), configPath: path }+}++/** Persist what the program changed: the tickets always, the pins only when they moved. The rules are+ * never rewritten from here — a person's file is changed key by key through `updateConfig`, or not at all. */+export async function writeState(workspace, state, env = process.env) {+ await writeTickets(state.paused ?? {}, env)+ const { pins } = await readConfig(env)+ const next = [...new Set(state.pins ?? [])]+ if (next.length !== pins.length || next.some((id) => !pins.includes(id))) await updateConfig({ pins: next }, env)+ return state+}++/** The policy thresholds, changed in place in the person's own file — comments and all. */+export function savePolicyValues(values, env = process.env) {+ return updateConfig(values, env)+}++/** Append a receipt. A log that cannot be written must not undo an action that already happened. */+export async function record(workspace, entry, env = process.env) { await appendLog(entry, env) }++export async function readLog(workspace, { limit = 200 } = {}, env = process.env) { return readLogFile({ limit }, env) }++/**+ * The pane header, in Harness's own words.+ *+ * `ready` means the fleet is inside its policy: nothing is waiting to be paused, nothing is+ * over the ceiling. That makes the header a live answer to "is my machine tidy?" rather than a build+ * status, which is the only useful reading for a harness that manages other harnesses.+ */+export async function writeVerdict(workspace, { summary, rows, plan, problems = [] }) {+ const findings = []+ const overdue = plan.filter((entry) => entry.action === 'pause').length+ if (overdue) findings.push({ severity: 'warn', kind: 'idle', message: `${overdue} running ${overdue === 1 ? 'harness is' : 'harnesses are'} past the pause threshold, holding ${gb(plan.filter((e) => e.action === 'pause').reduce((sum, e) => sum + (e.frees || 0), 0))}` })+ if (summary.needsInput) findings.push({ severity: 'warn', kind: 'attention', message: `${summary.needsInput} ${summary.needsInput === 1 ? 'harness looks' : 'harnesses look'} like they are waiting on you` })+ for (const problem of problems) findings.push({ severity: 'error', kind: 'machine', message: `${problem.machine}: ${problem.error}` })+ const verdict = {+ spec: 1,+ ready: overdue === 0 && problems.length === 0,+ summary: `${summary.total} harnesses · ${summary.running} running · ${summary.paused} paused · ${gb(summary.held)} held`,+ findings,+ updatedAt: new Date().toISOString(),+ }+ await atomicJson(verdictPath(workspace), verdict)+ return verdict+}++export function gb(bytes) {+ const n = Number(bytes) || 0+ if (n >= 1024 ** 3) return `${(n / 1024 ** 3).toFixed(1)} GB`+ if (n >= 1024 ** 2) return `${Math.round(n / 1024 ** 2)} MB`+ return `${Math.round(n / 1024)} KB`+}++/**+ * The ticket back, written the moment a harness is paused.+ *+ * The daemon releases an engine from its row when the process leaves, and the row's session id goes with+ * it — the transcript is still on disk, but nothing would know which conversation belonged to this agent.+ * So pause's receipt is kept here, and resume reads it. This is the one piece of state Harness Monitor cannot afford+ * to lose, which is why it is written before the success is reported.+ */+export function markPaused(state, row, ticket) {+ if (!ticket?.sessionId) return state+ return { ...state, paused: { ...state.paused, [row.id]: { at: Date.now(), ...ticket } } }+}++export function clearPaused(state, id) {+ const paused = { ...state.paused }+ delete paused[id]+ return { ...state, paused }+}++/** Pin and unpin — the only edits a person makes to this file by hand, kept here so the CLI and+ * the viewer cannot drift on what a record looks like. */+export function pin(state, id, on) {+ const pins = new Set(state.pins)+ if (on) pins.add(id); else pins.delete(id)+ return { ...state, pins: [...pins] }+}++/** Forget is the hps's own bookkeeping and nothing else: the row leaves `monitor.json`. No transcript,+ * no tmux session, no registry entry is touched here — those belong to the engine and the daemon. */+export function forget(state, id) {+ return clearPaused(pin(state, id, false), id)+}diff --git a/store/agents/harness-monitor/package.json b/store/agents/harness-monitor/package.jsonnew file mode 100644index 000000000..0ce6f9de8--- /dev/null+++ b/store/agents/harness-monitor/package.json@@ -0,0 +1,12 @@+{+ "name": "@autonomous/harness-monitor-harness",+ "private": true,+ "type": "module",+ "scripts": {+ "test": "node --import ./test/setup.mjs --test test/*.test.mjs",+ "start": "./viewer.sh"+ },+ "engines": {+ "node": ">=22"+ }+}diff --git a/store/agents/harness-monitor/skills/fleet-operations/SKILL.md b/store/agents/harness-monitor/skills/fleet-operations/SKILL.mdnew file mode 100644index 000000000..df26f0049--- /dev/null+++ b/store/agents/harness-monitor/skills/fleet-operations/SKILL.md@@ -0,0 +1,70 @@+---+name: fleet-operations+description: Run a fleet of long-lived coding-agent sessions — list them, pause idle ones without losing their conversations, resume them where they left off, and tune the policy that decides. Use when someone has many Harness harnesses, wants to know which are actually running, wants memory back from idle agents, asks what to clean up, or asks whether a pause threshold is any good.+---++# Fleet operations++A fleet of long-lived agent sessions goes wrong in one specific way: nothing ever ends. Sessions are+never killed — that is the point of them — so they accumulate until the list is useless and the machine+is full. This skill is how to fix that without breaking the promise that made people keep them.++## The one idea++**Separate the conversation from the process.** A conversation lives in a transcript and can be resumed;+a process holds memory and can be stopped. Pausing stops the process and keeps everything else. Once+pausing is free and resuming is reliable, an idle harness costs nothing, and "should I kill this?" stops+being a question anybody has to answer.++Everything else follows from that:++- **A ceiling, not a cleanup.** `runningCeiling` caps how many engines are running at once; the least+ recently active get paused when a new one passes the cap. This is the rule that bounds the steady state+ no matter how many harnesses get created — the one worth defending in an argument.+- **Idle thresholds, not idle shaming.** `pauseAfterIdle` (default 1d — survives an overnight break) and+ `hideAfterIdle` (default 14d, a list rule) are both reversible, so they can be aggressive.+- **A grace window, not a delete.** Retired rows are forgotten from the hps after+ `forgetAfterRetired` (30d), and forgetting is bookkeeping: transcripts belong to the engines.+- **Pins beat rules.** A pinned harness is never paused by policy, whatever the numbers say.++## Reading the fleet++Always start from data: `"$HPS_CLI" ls --json`. The fields that matter and their traps are in+[references/signals.md](references/signals.md) — read it before you explain an `idle` number to anyone,+because the three obvious sources for it are all wrong and one of them is wrong by days.++A good first report is four numbers and one sentence: how many harnesses, how many running, how much memory+held, how many idle past the pause threshold — then what you propose. Not a table of eighty rows.++## Acting++| Situation | Do this |+|---|---|+| One or two named harnesses | act, then show the receipt line |+| More than two | dry run → show the plan with a reason per row → ask → `--apply` |+| "Pause everything but X" | add X's id to `pins` in `~/.config/harness/policy.jsonc`, then `hps pause --policy --apply` |+| A guard refused | name the guard, leave it, offer `--force` as their choice, never yours |+| They want a threshold judged | set it in `~/.config/harness/policy.jsonc`, run `hps pause --policy`, report what it would do to *their* fleet |+| They want it gone for good | Harness Monitor does not delete. Point at the app's Stop Harness, which asks first |++Receipts are not decoration. Every action is appended to `.harness/monitor-log.jsonl` with its reason, and+"why is this paused?" must always have an answer that is not a guess.++## Tuning the policy++The rules live in `~/.config/harness/policy.jsonc` as data, so they can be simulated before they are believed —+[references/policy.md](references/policy.md) has each rule, its default, the argument for that default,+and what makes it wrong for someone. Two habits:++1. **Never change a threshold without simulating it.** Edit `pauseAfterIdle` in `~/.config/harness/policy.jsonc`, then+ `hps pause --policy` reads back exactly which harnesses would move, and why, without moving any.+2. **Change one rule at a time.** Two thresholds moving at once makes the result unattributable, and the+ person is trying to build an intuition, not just a config.++## The boundary, and why it holds++Harness Monitor can pause and resume. It cannot delete an agent, kill a tmux session or+touch a transcript. That is what makes it safe to point at eighty live sessions and act on all of them in+one command — the worst outcome of a wrong decision is a few seconds of cold start. Do not work around+it, and do not build a workaround for someone who asks: the app already has the irreversible verbs,+behind their own confirmation, which is where they belong.diff --git a/store/agents/harness-monitor/skills/fleet-operations/references/policy.md b/store/agents/harness-monitor/skills/fleet-operations/references/policy.mdnew file mode 100644index 000000000..063fcdb81--- /dev/null+++ b/store/agents/harness-monitor/skills/fleet-operations/references/policy.md@@ -0,0 +1,59 @@+# The rules, their defaults, and the argument for each++`~/.config/harness/policy.jsonc`, one per machine. Change one at a time, and simulate before believing.++## `runningCeiling` — default 100++The most engines running at once on this machine. When more than that survive the idle rules, the least+recently active are paused until the count fits. Protected rows hold a slot but are never paused.++**Why it matters most:** every other rule is a reaction to time passing; this one is a bound. It makes the+steady state independent of how many harnesses get created, the way `ulimit` bounds a process. A person+who creates six harnesses a day and pauses none still ends the month under the ceiling.++**The default is 100, which makes it a backstop.** On a normal day the idle rule does all the work and the+ceiling never fires. **When it is wrong:** a laptop under memory pressure wants something like 12. Set it to+what the machine can hold without swapping — free memory divided by ~300 MB — not to what feels tidy.++## `pauseAfterIdle` — default `1d`++Idle this long and a running engine is paused. A day, because a day survives an overnight break: yesterday+afternoon's work is still warm in the morning. The first default was 4h; on a real fleet the only thing it+caught that a day does not was eight harnesses from the previous afternoon.++**When it is wrong:** an agent on a long autonomous run that produces no turns for hours would be paused+mid-thought if the `working` guard somehow missed it — pin those. Someone who works in short bursts across+a whole day may prefer `8h`; someone on a small machine, `1h`.++## `hideAfterIdle` — default `14d`++Idle this long and the row drops below the fold: out of the default list, one `--all` (or the pane's **show+all**) away, still resumable. Two weeks is past "I'll get back to it" for anything unpinned.++**This is a list rule, not a state.** An earlier version made it a `retire` verb with its own state, mark+and thirty-day grace window, and it earned none of that: hiding is what a sorted list does, and+`systemctl disable` — the analogy used to justify it — exists because a service would otherwise auto-start+at boot. Nothing auto-starts a harness.++**Never shorter than `pauseAfterIdle`.** A row cannot drop out of the list before it is even paused; the+policy refuses to load if it is.++## `pauseWhenWorkspaceGone` — default `true`++A harness whose working folder no longer exists has no work left in it. The cheapest correct rule in the+file, and the only one that fires on a fact rather than a duration.++## `protect` — the guards++`needsInput`, `working`, `attached`, `pinned` default to on, and each refuses an action with its own+reason. There is deliberately no `projects` list any more: it was a second mechanism for the same job as+`pin`, and that is how a config file gets fat.++## What the rules deliberately do not do++- **No git.** "Its branch already merged" is a good reason to pause and a bad thing to put in a rule that+ runs every four seconds against sixty repositories. The agent does that check on request, and names the+ branch in `--reason`.+- **No deleting.** There is no rule, and no flag, that removes an agent. See the skill's last section.+- **No remote actions.** Other machines are listed, never acted on: pane facts and signals are local, and+ a fleet manager that guesses at a machine it cannot see is not one.diff --git a/store/agents/harness-monitor/skills/fleet-operations/references/signals.md b/store/agents/harness-monitor/skills/fleet-operations/references/signals.mdnew file mode 100644index 000000000..55dc09aa0--- /dev/null+++ b/store/agents/harness-monitor/skills/fleet-operations/references/signals.md@@ -0,0 +1,59 @@+# The signals, and which ones lie++Every column in `hps` comes from somewhere, and three of the obvious sources are wrong in ways that+would pause a working agent or keep a dead one running. This is the reference for explaining a number.++## idle — time since the last turn++**Source:** the tail of the engine's own transcript, newest line first, stopping at the first line that is+a real turn (Claude Code's `user` / `assistant`, a Codex rollout's `message`). Falls back to the daemon's+`lastHookAt` when a transcript has no turn in its tail, and to the registration time when there is none.++**What it is not, and why:**++| Tempting source | Why it lies |+|---|---|+| the registry's `updatedAt` | the daemon reconciles every five seconds; every row reads "now" |+| the transcript's mtime | a *running* engine appends bookkeeping — task notifications, away summaries, queue operations — to conversations nobody has touched in days. Measured on one real machine: 34 of 85 harnesses looked an hour old when only 5 were |+| the pane's tmux activity | a spinner redraw is activity, and an engine that exited hours ago leaves its last frame on screen forever |++Output is not a turn. If someone points at recent output on a row that reads `3d`, that is the whole+explanation, and the row is right.++## mem — what pausing would hand back++The engine's whole process subtree, resident. Say "held", not "used": resident sets share pages, so a sum+across rows is an upper bound, not an exact figure. It is still the right number for the decision, because+the decision is comparative.++## state — running, paused, shell, gone++Decided in one place (`lib/inventory.mjs`) from two facts: is the pane still in tmux, and is an engine+process running under it. `paused` is the daemon's own "dormant but still viewable agent" — a state+Harness already has, not one Harness Monitor invented.++## working — do not pause this++CPU on the engine subtree above 5%, or a turn in the last 90 seconds, or output drawn in the last 60. All+proxies, and all used only to *refuse* an action, never to claim in the interface that an agent is busy.++## waiting on you — a guess, and labelled as one++Read from the pane's last screen against a list of prompt shapes (`(y/n)`, a numbered choice list, "do you+want to proceed"). Broad on purpose: a false positive costs a harness that stays running, a false negative+costs a question paused before it was read. The app's own **Agents needing input** (⇧⌘I) is the authority —+say so when it matters.++## Where each fact comes from++| Fact | Source |+|---|---|+| who the agents are, their panes, engines, models, projects, branches | the daemon, over `ws://127.0.0.1:18473/api/local-ws` (`agents_list`) |+| transcript paths, hook timestamps | `~/.harness/cli/data/registry.json`, read only |+| pane alive / dead / attached, last output | one `tmux list-panes -a` |+| memory, CPU, process count | one `ps` snapshot, walked per pane |+| the policy and pins | `~/.config/harness/policy.jsonc` |+| resume tickets, the log | `~/.harness/monitor/` |++Other machines answer `agents_list` through the same bridge, so they appear in the list — but pane facts,+memory and every action are local to this computer. A remote row says so.diff --git a/store/agents/harness-monitor/store.json b/store/agents/harness-monitor/store.jsonnew file mode 100644index 000000000..c6f79b977--- /dev/null+++ b/store/agents/harness-monitor/store.json@@ -0,0 +1,18 @@+{+ "license": "MIT",+ "tagline": "htop for your harnesses: pause the idle ones, resume any of them",+ "examples": [+ {+ "prompt": "Show me every harness on this machine, then pause everything nobody has touched in a day.",+ "caption": "The fleet, freshest first · a dry run, then the pause, then how much memory came back"+ },+ {+ "prompt": "Which of my harnesses are actually doing something right now, and which are just holding memory?",+ "caption": "Running, waiting on you, and idle — with what each one holds"+ },+ {+ "prompt": "Which harnesses are on a branch that already merged? Pause those and tell me what you kept.",+ "caption": "Paused with the reason recorded; each one resumes with its conversation"+ }+ ]+}diff --git a/store/agents/harness-monitor/template/NOTES.md b/store/agents/harness-monitor/template/NOTES.mdnew file mode 100644index 000000000..a013bfb49--- /dev/null+++ b/store/agents/harness-monitor/template/NOTES.md@@ -0,0 +1,12 @@+# Your harnesses++This folder is Harness Monitor's workspace. Almost nothing lives here, on purpose — there is one fleet per+machine, so there is one policy per machine:++- **The rules:** `~/.config/harness/policy.jsonc` — commented, hand-edited, read on every refresh. Or drag+ the two lines in the pane. Preview a change without moving anything: `hps pause --policy`.+- **The resume tickets:** `~/.harness/monitor/paused.json` — which conversation each paused harness had.+- **What happened, and why:** `~/.harness/monitor/log.jsonl`.++The only file Harness Monitor writes here is `.harness/verdict.json`, the pane header. Deleting this folder+loses nothing.diff --git a/store/agents/harness-monitor/test/actions.test.mjs b/store/agents/harness-monitor/test/actions.test.mjsnew file mode 100644index 000000000..bba262356--- /dev/null+++ b/store/agents/harness-monitor/test/actions.test.mjs@@ -0,0 +1,161 @@+import assert from 'node:assert/strict'+import { test } from 'node:test'+import { pause, resume } from '../lib/actions.mjs'+import { normalizePolicy } from '../lib/policy.mjs'+import { HOUR, fakeTmux, pane, row, table } from './fixtures.mjs'++const policy = normalizePolicy({})+const gone = { send: () => {}, alive: () => false }+const stubborn = { send: () => {}, alive: () => true }+const nowait = async () => {}++test('pause refuses a remote row: signals and pane facts are local', async () => {+ const result = await pause(row({ local: false, machine: 'studio' }), { policy })+ assert.equal(result.ok, false)+ assert.match(result.detail, /remote machine/)+})++test('pause refuses what the policy protects, and names the guard', async () => {+ for (const [field, expected] of [['pinned', /pinned/], ['needsInput', /waiting on you/], ['working', /mid-turn/], ['attached', /looking at it/]]) {+ const result = await pause(row({ [field]: true }), { policy, run: fakeTmux().run, signals: gone, wait: nowait })+ assert.equal(result.ok, false, field)+ assert.match(result.detail, expected)+ assert.match(result.detail, /--force/)+ }+})++test('pause refuses a pane that looks like it is waiting for an answer', async () => {+ const tmux = fakeTmux({ screen: 'Do you want to proceed?\n❯ 1. Yes\n 2. No' })+ const result = await pause(row(), { policy, run: tmux.run, signals: gone, wait: nowait })+ assert.equal(result.ok, false)+ assert.match(result.detail, /waiting for an answer/)+ assert.equal(tmux.calls.some((call) => call[0] === 'set-option'), false, 'nothing was touched')+})++test('pause says nothing to do when it is already paused', async () => {+ const result = await pause(row({ state: 'paused' }), { policy })+ assert.equal(result.ok, true)+ assert.equal(result.already, true)+})++test('pause holds the pane open before it signals, in that order', async () => {+ const tmux = fakeTmux({ dead: true, remainOnExit: 'off' })+ const sent = []+ const result = await pause(row(), { policy, run: tmux.run, signals: { send: (pid, signal) => sent.push([pid, signal]), alive: () => false }, wait: nowait })+ assert.equal(result.ok, true)+ assert.equal(result.paneDead, true)+ assert.deepEqual(sent, [[100, 'SIGTERM']])+ const order = tmux.calls.map((call) => call[0])+ assert.ok(order.indexOf('set-option') < order.indexOf('display-message'), 'the hold comes before the check')+ assert.match(result.detail, /scrollback/)+ assert.equal(result.freed, 400 * 1024 * 1024)+ assert.equal(result.ticket.sessionId, 's1-0123456789ab')+ assert.equal(result.ticket.engine, 'claude')+})++test('pause refuses an engine it would not be able to resume', async () => {+ const devin = await pause(row({ engine: 'devin' }), { policy, run: fakeTmux().run, signals: gone, wait: nowait })+ assert.equal(devin.ok, false)+ assert.match(devin.detail, /does not know how to resume devin/)+ const unbound = await pause(row({ sessionId: null }), { policy, run: fakeTmux().run, signals: gone, wait: nowait })+ assert.equal(unbound.ok, false)+ assert.match(unbound.detail, /nothing to resume/)+})++test('a pane that fell back to a shell has the window setting put back', async () => {+ const tmux = fakeTmux({ dead: false, command: 'zsh', remainOnExit: 'off' })+ const result = await pause(row(), { policy, run: tmux.run, signals: gone, wait: nowait })+ assert.equal(result.ok, true)+ assert.equal(result.paneDead, false)+ const holds = tmux.calls.filter((call) => call[0] === 'set-option')+ assert.deepEqual(holds.map((call) => call.at(-1)), ['on', 'off'])+})++test('an engine that will not leave is left running, and said so', async () => {+ const tmux = fakeTmux({ remainOnExit: 'off' })+ const result = await pause(row(), { policy, run: tmux.run, signals: stubborn, wait: nowait, graceMs: 10 })+ assert.equal(result.ok, false)+ assert.match(result.detail, /still running, untouched/)+ assert.deepEqual(tmux.calls.filter((call) => call[0] === 'set-option').map((call) => call.at(-1)), ['on', 'off'])+})++test('--force ends it after the grace, and only then', async () => {+ const sent = []+ const tmux = fakeTmux({ dead: true })+ const result = await pause(row(), {+ policy, run: tmux.run, wait: nowait, graceMs: 10, force: true, killAfterGrace: true,+ signals: { send: (pid, signal) => sent.push(signal), alive: () => true },+ })+ assert.equal(result.ok, true)+ assert.deepEqual(sent, ['SIGTERM', 'SIGKILL'])+})++test('resume types the engine\'s own resume command into the pane, and waits for it to come up', async () => {+ const tmux = fakeTmux({ dead: false, command: 'zsh' })+ const alivePane = new Map([['%1', pane({ pid: 100 })]])+ const result = await resume(row({ state: 'paused', sessionId: 'abcd1234-aaaa-bbbb-cccc-0123456789ab' }), {+ run: tmux.run, wait: async () => {}, inventory: { panes: async () => alivePane, processTable: async () => table() },+ })+ assert.equal(result.ok, true)+ assert.equal(result.resumed, true)+ const typed = tmux.calls.find((call) => call[0] === 'send-keys')+ assert.deepEqual(typed, ['send-keys', '-t', '%1', 'claude --resume abcd1234-aaaa-bbbb-cccc-0123456789ab', 'Enter'])+ assert.match(result.detail, /same pane/)+})++test('codex resumes with a subcommand, not a flag', async () => {+ const tmux = fakeTmux({ command: 'zsh' })+ await resume(row({ state: 'paused', engine: 'codex', sessionId: '7f3c2a10-5b8e-4d21-9a6f-3e0d1c2b4a58' }), {+ run: tmux.run, wait: async () => {}, inventory: { panes: async () => new Map([['%1', pane()]]), processTable: async () => table({ comm: '/usr/local/bin/codex' }) },+ })+ assert.deepEqual(tmux.calls.find((call) => call[0] === 'send-keys').at(-2), 'codex resume 7f3c2a10-5b8e-4d21-9a6f-3e0d1c2b4a58')+})++test('a dead pane is respawned before anything is typed into it', async () => {+ const tmux = fakeTmux({ dead: true })+ await resume(row({ state: 'paused', sessionId: 'abcd1234-aaaa-bbbb-cccc-0123456789ab' }), {+ run: tmux.run, wait: async () => {}, inventory: { panes: async () => new Map([['%1', pane()]]), processTable: async () => table() },+ })+ const order = tmux.calls.map((call) => call[0])+ assert.ok(order.indexOf('respawn-pane') < order.indexOf('send-keys'), 'the pane gets a shell first')+})++test('an engine that never comes up is reported as a failure, with the command it typed', async () => {+ const tmux = fakeTmux({ command: 'zsh' })+ const result = await resume(row({ state: 'paused', sessionId: 'abcd1234-aaaa-bbbb-cccc-0123456789ab' }), {+ run: tmux.run, wait: async () => {}, waitMs: 3,+ inventory: { panes: async () => new Map([['%1', pane()]]), processTable: async () => table({ comm: '-zsh' }) },+ })+ assert.equal(result.ok, false)+ assert.match(result.detail, /did not come up/)+ assert.match(result.detail, /claude --resume/)+})++test('resume refuses when nothing recorded which conversation this was', async () => {+ const result = await resume(row({ state: 'paused', sessionId: null }), { run: fakeTmux().run })+ assert.equal(result.ok, false)+ assert.match(result.detail, /no session id/)+})++test('resume uses the ticket pause left behind when the row has forgotten its session', async () => {+ const tmux = fakeTmux({ command: 'zsh' })+ const result = await resume(row({ state: 'paused', sessionId: null, engine: 'terminal' }), {+ ticket: { sessionId: 'abcd1234-aaaa-bbbb-cccc-0123456789ab', engine: 'claude' },+ run: tmux.run, wait: async () => {}, inventory: { panes: async () => new Map([['%1', pane()]]), processTable: async () => table() },+ })+ assert.equal(result.ok, true)+ assert.match(tmux.calls.find((call) => call[0] === 'send-keys').at(-2), /^claude --resume /)+})++test('resume refuses a row whose pane is gone rather than inventing one', async () => {+ const result = await resume(row({ state: 'gone', pane: null }), { run: fakeTmux().run })+ assert.equal(result.ok, false)+ assert.match(result.detail, /pane is gone/)+})++test('nothing in this module can delete anything', async () => {+ const source = await (await import('node:fs/promises')).readFile(new URL('../lib/actions.mjs', import.meta.url), 'utf8')+ for (const word of ['kill-session', 'kill-pane', 'agent_delete', 'unlink', 'rm -rf']) {+ assert.equal(source.includes(word), false, `actions.mjs must not contain ${word}`)+ }+})diff --git a/store/agents/harness-monitor/test/activity.test.mjs b/store/agents/harness-monitor/test/activity.test.mjsnew file mode 100644index 000000000..2d094bde3--- /dev/null+++ b/store/agents/harness-monitor/test/activity.test.mjs@@ -0,0 +1,72 @@+import assert from 'node:assert/strict'+import { test } from 'node:test'+import { mkdtemp, writeFile } from 'node:fs/promises'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { lastTurnAt, lastTurns } from '../lib/activity.mjs'++const TURN = '2026-09-18T10:00:00.000Z'+const LATER = '2026-09-20T09:00:00.000Z'++async function transcript(lines) {+ const dir = await mkdtemp(join(tmpdir(), 'hps-activity-'))+ const path = join(dir, 'session.jsonl')+ await writeFile(path, lines.map((line) => JSON.stringify(line)).join('\n'))+ return path+}++test('the last turn wins, and bookkeeping after it is ignored', async () => {+ const path = await transcript([+ { type: 'user', timestamp: '2026-09-10T10:00:00.000Z', content: 'hello' },+ { type: 'assistant', timestamp: TURN, content: 'done' },+ { type: 'system', subtype: 'away_summary', timestamp: LATER, content: 'we were working on…' },+ { type: 'queue-operation', operation: 'enqueue', timestamp: LATER },+ { type: 'file-history-snapshot', timestamp: LATER },+ ])+ assert.equal(await lastTurnAt(path), Date.parse(TURN))+})++test('a codex rollout answers from its payload type', async () => {+ const path = await transcript([+ { type: 'session_meta', timestamp: '2026-09-10T10:00:00.000Z' },+ { type: 'response_item', payload: { type: 'message', role: 'assistant' }, timestamp: TURN },+ { type: 'event_msg', payload: { type: 'token_count' }, timestamp: LATER },+ { type: 'turn_context', timestamp: LATER },+ ])+ assert.equal(await lastTurnAt(path), Date.parse(TURN))+})++test('a transcript with no turn in it says so, rather than guessing from its mtime', async () => {+ const path = await transcript([{ type: 'system', timestamp: LATER }, { type: 'summary', timestamp: LATER }])+ assert.equal(await lastTurnAt(path), null)+})++test('a missing or unreadable file is null, never an exception', async () => {+ assert.equal(await lastTurnAt('/nope/does/not/exist.jsonl'), null)+ assert.equal(await lastTurnAt(''), null)+ assert.equal(await lastTurnAt(undefined), null)+})++test('a truncated first line is dropped rather than parsed', async () => {+ const path = await transcript([{ type: 'assistant', timestamp: TURN }])+ // A tail window that starts mid-record must not produce an answer from the fragment.+ const answer = await lastTurnAt(path)+ assert.equal(answer, Date.parse(TURN))+})++test('the cache keys on size and mtime, so an unchanged file is read once', async () => {+ const path = await transcript([{ type: 'user', timestamp: TURN }])+ const cache = new Map()+ await lastTurnAt(path, { cache })+ await lastTurnAt(path, { cache })+ assert.equal(cache.size, 1)+})++test('a fleet is read in parallel and keyed by agent id', async () => {+ const one = await transcript([{ type: 'user', timestamp: TURN }])+ const two = await transcript([{ type: 'system', timestamp: LATER }])+ const found = await lastTurns([{ id: 'a', transcriptPath: one }, { id: 'b', transcriptPath: two }, { id: 'c', transcriptPath: null }])+ assert.equal(found.get('a'), Date.parse(TURN))+ assert.equal(found.has('b'), false)+ assert.equal(found.has('c'), false)+})diff --git a/store/agents/harness-monitor/test/fixtures.mjs b/store/agents/harness-monitor/test/fixtures.mjsnew file mode 100644index 000000000..181168020--- /dev/null+++ b/store/agents/harness-monitor/test/fixtures.mjs@@ -0,0 +1,74 @@+/** Fixtures. Paths are placeholders on purpose — no real home directory belongs in a public repository. */++export const HOME = '/home/you'++export const HOUR = 3_600_000+export const DAY = 86_400_000++/** One agent frame in the shape `agents_list` replies with. */+export function frame(overrides = {}) {+ return {+ id: overrides.id ?? 'a1',+ sessionId: overrides.sessionId ?? 's1',+ name: overrides.name ?? 'widgets',+ title: overrides.title ?? 'Fix the reconciler',+ status: overrides.status ?? 'active',+ createdAt: new Date(overrides.createdAt ?? Date.now() - 7 * DAY).toISOString(),+ updatedAt: new Date(overrides.updatedAt ?? Date.now()).toISOString(),+ tmuxPane: overrides.tmuxPane ?? '%1',+ terminal: { available: true, primary: 'tmux\u0000%1', runtimes: [] },+ engine: overrides.engine ?? 'claude',+ selectedModel: overrides.selectedModel ?? 'runtime-v1:a1:claude:opus-5@high',+ project: overrides.project === null ? null : {+ name: 'widgets', cwd: `${HOME}/code/widgets`, root: `${HOME}/code/widgets`,+ remote: 'github.com/you/widgets', branch: 'main', ...(overrides.project ?? {}),+ },+ dsh: null, dshName: null, verdict: null, codexHome: null,+ // `createdAt`/`updatedAt` are already folded in above as ISO strings — never let a raw number through.+ ...Object.fromEntries(Object.entries(overrides).filter(([key]) => !['project', 'createdAt', 'updatedAt'].includes(key))),+ }+}++/** A tmux pane row as `panes()` returns it. */+export function pane(overrides = {}) {+ return { pane: '%1', dead: false, pid: 100, command: 'node', session: 'harness-claude-1', attached: false, target: 'harness-claude-1:1.1', engineExit: null, lastOutput: Date.now(), ...overrides }+}++/** A process table with one engine under one pane. */+export function table({ pid = 100, comm = '/usr/local/bin/claude', rss = 400 * 1024 * 1024, cpu = 0.2, children = [] } = {}) {+ const byPid = new Map([[pid, { pid, ppid: 1, rss, cpu, comm }]])+ const kids = new Map()+ if (children.length) {+ kids.set(pid, children.map((child) => child.pid))+ for (const child of children) byPid.set(child.pid, { ppid: pid, cpu: 0, rss: 0, ...child })+ }+ return { byPid, children: kids }+}++/** A row in the shape the policy and the actions take. */+export function row(overrides = {}) {+ return {+ id: 'a1', sessionId: 's1-0123456789ab', name: 'widgets', title: 'Fix the reconciler', engine: 'claude', model: 'opus-5',+ state: 'running', stateSince: Date.now(), pane: '%1', paneTarget: 'harness-claude-1:1.1',+ project: 'widgets', cwd: `${HOME}/code/widgets`, home: '~/code/widgets', branch: 'main',+ lastActivity: Date.now() - 6 * HOUR, idleMs: 6 * HOUR, createdAt: Date.now() - 7 * DAY,+ attached: false, working: false, needsInput: false, pinned: false, workspaceGone: false,+ rssBytes: 400 * 1024 * 1024, procs: 1, cpu: 0.1, enginePid: 100,+ machine: 'this machine', machineId: 'm1', local: true, dead: false,+ ...overrides,+ }+}++/** A fake tmux: records what it was asked, answers what the test set up. */+export function fakeTmux(answers = {}) {+ const calls = []+ const run = async (args) => {+ calls.push(args)+ const key = args[0]+ if (key === 'show-options') return `${answers.remainOnExit ?? 'off'}\n`+ if (key === 'display-message') return `${answers.dead ? 1 : 0}§§${answers.command ?? 'zsh'}§§${answers.engineExit ?? ''}`+ if (key === 'capture-pane') return answers.screen ?? '$ '+ return ''+ }+ return { run, calls }+}diff --git a/store/agents/harness-monitor/test/format.test.mjs b/store/agents/harness-monitor/test/format.test.mjsnew file mode 100644index 000000000..9bd63cdf7--- /dev/null+++ b/store/agents/harness-monitor/test/format.test.mjs@@ -0,0 +1,71 @@+import assert from 'node:assert/strict'+import { test } from 'node:test'+import { footer, glyph, painter, planLines, receiptLine, table } from '../lib/format.mjs'+import { normalizePolicy, decide } from '../lib/policy.mjs'+import { summarize } from '../lib/inventory.mjs'+import { DAY, HOUR, row } from './fixtures.mjs'++const rows = [+ row({ id: 'a', name: 'widgets', title: 'Fix the reconciler', idleMs: 2 * 60_000, working: true }),+ row({ id: 'b', name: 'gadgets', title: 'Ship the thing', idleMs: 2 * DAY, rssBytes: 1.4 * 1024 ** 3 }),+ row({ id: 'c', name: 'old', state: 'paused', idleMs: 20 * DAY, rssBytes: 0, machine: 'studio', local: false }),+]++test('without a terminal listening there are no escape codes anywhere', () => {+ const text = [table(rows), footer(summarize(rows), normalizePolicy({})), receiptLine({ ok: true, action: 'pause', name: 'x', detail: 'done' })].join('\n')+ assert.equal(/\u001b\[/.test(text), false)+})++test('with a terminal listening, colour is added and the columns still line up', () => {+ const plain = table(rows, { tty: false, columns: 140 }).split('\n')+ const painted = table(rows, { tty: true, columns: 140 }).split('\n')+ assert.ok(/\u001b\[/.test(painted.join('')))+ for (let i = 0; i < plain.length; i += 1) {+ assert.equal(painted[i].replace(/\u001b\[[0-9;]*m/g, ''), plain[i], `row ${i} shifted when painted`)+ }+})++test('a narrow pane keeps state, idle, engine and memory and drops the rest', () => {+ const narrow = table(rows, { columns: 60 })+ assert.equal(narrow.includes('PROJECT'), false)+ assert.equal(narrow.includes('MODEL'), false)+ assert.match(narrow, /IDLE/)+ assert.match(narrow, /MEM/)+ assert.match(narrow, /Fix the reconciler/)+})++test('a machine column appears only when there is more than one machine', () => {+ assert.match(table(rows, { columns: 140 }), /MACHINE/)+ assert.equal(table(rows.slice(0, 2), { columns: 140 }).includes('MACHINE'), false)+})++test('every state has its own glyph, and waiting beats all of them', () => {+ const c = painter({})+ const seen = new Set(['running', 'paused', 'terminal', 'gone'].map((state) => glyph(row({ state }), c).trim()))+ assert.equal(seen.size, 4)+ assert.equal(glyph(row({ state: 'running', working: true }), c).trim(), '◐')+ assert.equal(glyph(row({ state: 'running', needsInput: true }), c).trim(), '!')+})++test('the footer says what the fleet is and what the policy is', () => {+ const line = footer(summarize(rows), normalizePolicy({ pauseAfterIdle: '8h' }), { problems: [{ machine: 'studio', error: 'asleep' }] })+ assert.match(line, /3 harnesses/)+ assert.match(line, /2 running/)+ assert.match(line, /1 paused/)+ assert.match(line, /pause after 8h/)+ assert.match(line, /studio: asleep/)+})++test('a plan reads as one line per row, with nothing to do said plainly', () => {+ const plan = decide(rows, { runningCeiling: 12 })+ const lines = planLines(plan.entries)+ assert.match(lines, /pause\s+gadgets/)+ assert.equal(lines.includes('widgets'), false)+ assert.match(planLines(decide([rows[0]], {}).entries), /Nothing to do/)+})++test('a receipt shows what happened, including what was refused', () => {+ assert.match(receiptLine({ ok: true, action: 'pause', name: 'x', detail: 'engine stopped', freed: 4e8 }), /✓ pause x \(\+381 MB\)/)+ assert.match(receiptLine({ ok: false, refused: true, action: 'pause', name: 'y', detail: 'pinned' }), /· pause y/)+ assert.match(receiptLine({ ok: true, already: true, action: 'pause', name: 'z', detail: 'already paused' }), /= pause z/)+})diff --git a/store/agents/harness-monitor/test/inventory.test.mjs b/store/agents/harness-monitor/test/inventory.test.mjsnew file mode 100644index 000000000..0571dfcec--- /dev/null+++ b/store/agents/harness-monitor/test/inventory.test.mjs@@ -0,0 +1,111 @@+import assert from 'node:assert/strict'+import { test } from 'node:test'+import { mergeRows, parseModel, projectOf, resolveRef, summarize, tilde } from '../lib/inventory.mjs'+import { DAY, HOME, HOUR, frame, pane, row, table } from './fixtures.mjs'++const now = Date.now()+const base = { paneRows: new Map([['%1', pane()]]), table: table(), now, home: HOME }++test('a runtime profile is read back as a model and an effort', () => {+ assert.deepEqual(parseModel('runtime-v1:a1:claude:opus-5@high'), { model: 'opus-5', effort: 'high' })+ assert.deepEqual(parseModel('gpt-6-astra'), { model: 'gpt-6-astra', effort: null })+ assert.deepEqual(parseModel(null), { model: null, effort: null })+})++test('paths are shown against the home they belong to', () => {+ assert.equal(tilde(`${HOME}/code/widgets`, HOME), '~/code/widgets')+ assert.equal(tilde('/opt/thing', HOME), '/opt/thing')+ assert.equal(tilde('', HOME), '')+})++test('a project without a frame is named, not left blank', () => {+ assert.equal(projectOf({ project: null }).project, 'unknown')+ assert.equal(projectOf(frame()).project, 'widgets')+})++test('state comes from the pane and the process, not from the daemon status', () => {+ const running = mergeRows([frame()], base)[0]+ assert.equal(running.state, 'running')++ const paused = mergeRows([frame()], { ...base, table: table({ comm: '-zsh' }) })[0]+ assert.equal(paused.state, 'paused')+ assert.equal(paused.rssBytes, 0)++ const gone = mergeRows([frame()], { ...base, paneRows: new Map() })[0]+ assert.equal(gone.state, 'gone')+})++test('idle comes from the last turn, never from the transcript mtime the daemon sends', () => {+ const turns = new Map([['a1', now - 5 * DAY]])+ const rows = mergeRows([frame({ updatedAt: now })], { ...base, turns, registry: new Map() })+ assert.equal(rows[0].idleMs, 5 * DAY)+ assert.equal(rows[0].idle, '5d')+})++test('with no turn to read, the daemon last hook is next, and registration last', () => {+ const registry = new Map([['a1', { lastHookAt: now - 2 * HOUR, transcriptPath: '/nope' }]])+ assert.equal(mergeRows([frame()], { ...base, registry })[0].idleMs, 2 * HOUR)+ const created = now - 9 * DAY+ const bare = mergeRows([frame({ createdAt: created })], { ...base, registry: new Map() })[0]+ assert.equal(bare.idleMs, now - created)+})++test('a remote row is marked, and carries no local facts it cannot know', () => {+ const rows = mergeRows([frame()], { ...base, local: false, machine: { name: 'studio', machineId: 'm2' } })+ assert.equal(rows[0].local, false)+ assert.equal(rows[0].machine, 'studio')+ assert.equal(rows[0].rssBytes, 0)+ assert.equal(rows[0].enginePid, null)+ assert.equal(rows[0].state, 'running') // the daemon's word for it is all there is+})++test('working is a refusal signal, and CPU or a fresh turn is enough for it', () => {+ const busy = mergeRows([frame()], { ...base, table: table({ cpu: 40 }), turns: new Map([['a1', now - 9 * DAY]]) })[0]+ assert.equal(busy.working, true)+ const quiet = mergeRows([frame()], { ...base, paneRows: new Map([['%1', pane({ lastOutput: now - 4 * HOUR })]]), turns: new Map([['a1', now - 9 * DAY]]) })[0]+ assert.equal(quiet.working, false)+})++test('the summary counts what the gauges show', () => {+ const rows = [row({ id: 'a' }), row({ id: 'b', state: 'paused', rssBytes: 0 }), row({ id: 'c', state: 'gone', rssBytes: 0 }), row({ id: 'd', needsInput: true })]+ const summary = summarize(rows)+ assert.equal(summary.total, 4)+ assert.equal(summary.running, 2)+ assert.equal(summary.paused, 1)+ assert.equal(summary.gone, 1)+ assert.equal(summary.needsInput, 1)+ assert.equal(summary.held, 800 * 1024 * 1024)+})++test('a ref is a row number, a pane, an id prefix, a name, or a unique substring', () => {+ const rows = [row({ id: 'abc123', name: 'widgets', title: 'Fix the reconciler' }), row({ id: 'def456', name: 'gadgets', pane: '%9', title: 'Ship the thing' })]+ assert.equal(resolveRef('1', rows).row.id, 'abc123')+ assert.equal(resolveRef('%9', rows).row.id, 'def456')+ assert.equal(resolveRef('abc', rows).row.id, 'abc123')+ assert.equal(resolveRef('gadgets', rows).row.id, 'def456')+ assert.equal(resolveRef('reconciler', rows).row.id, 'abc123')+ assert.match(resolveRef('3', rows).error, /no row 3/)+ assert.match(resolveRef('%7', rows).error, /pane %7/)+ assert.match(resolveRef('gets', rows).error, /matches 2 harnesses/)+ assert.match(resolveRef('', rows).error, /Name a harness/)+})++test('a paused row describes itself from the ticket the daemon threw away', () => {+ // Measured against a real pause: the daemon rewrites the row as a terminal and keeps only the cwd.+ const released = frame({ engine: 'terminal', sessionId: '', title: null, name: 'e2e-project' })+ const state = { pins: [], retired: {}, paused: { a1: { at: now - 2 * HOUR, sessionId: 'sess-0123456789ab', engine: 'claude', pane: '%1', title: 'Fix the reconciler' } } }+ const paused = mergeRows([released], { ...base, table: table({ comm: '-zsh' }), state })[0]+ assert.equal(paused.state, 'paused')+ assert.equal(paused.engine, 'claude')+ assert.equal(paused.title, 'Fix the reconciler')+ assert.equal(paused.sessionId, 'sess-0123456789ab')+ assert.equal(paused.pausedAt, now - 2 * HOUR)+})++test('a shell nobody paused is a shell, not a paused agent', () => {+ const shell = frame({ engine: 'terminal', sessionId: '', title: null })+ const row = mergeRows([shell], { ...base, table: table({ comm: '-zsh' }) })[0]+ assert.equal(row.state, 'terminal')+ assert.equal(summarize([row]).terminals, 1)+ assert.equal(summarize([row]).paused, 0)+})diff --git a/store/agents/harness-monitor/test/page.test.mjs b/store/agents/harness-monitor/test/page.test.mjsnew file mode 100644index 000000000..085c78a1a--- /dev/null+++ b/store/agents/harness-monitor/test/page.test.mjs@@ -0,0 +1,95 @@+import assert from 'node:assert/strict'+import { test } from 'node:test'+import { readFile, readdir } from 'node:fs/promises'+import { fileURLToPath } from 'node:url'+import { dirname, join } from 'node:path'++const PACKAGE = join(dirname(fileURLToPath(import.meta.url)), '..')+const read = (path) => readFile(join(PACKAGE, path), 'utf8')++/**+ * The pane is plain DOM with no build step, so the one class of bug a build would have caught — a script+ * reaching for an id the page does not have — is caught here instead.+ */+test('every id the script looks up exists in the page', async () => {+ const [html, js] = await Promise.all([read('viewer/index.html'), read('viewer/app.js')])+ const ids = new Set([...html.matchAll(/\bid="([^"]+)"/g)].map((match) => match[1]))+ const wanted = [...js.matchAll(/\bel\('([^']+)'\)/g)].map((match) => match[1])+ assert.ok(wanted.length > 10, 'the script should be looking up the page')+ for (const id of wanted) assert.ok(ids.has(id), `index.html has no #${id}`)+})++test('every selector the script queries by id is in the page too', async () => {+ const [html, js] = await Promise.all([read('viewer/index.html'), read('viewer/app.js')])+ const ids = new Set([...html.matchAll(/\bid="([^"]+)"/g)].map((match) => match[1]))+ for (const match of js.matchAll(/querySelector\('#([a-z-]+)/g)) assert.ok(ids.has(match[1]), `index.html has no #${match[1]}`)+})++test('the page carries the token placeholder the server fills in', async () => {+ const html = await read('viewer/index.html')+ assert.match(html, /name="hps-token" content="__HPS_TOKEN__"/)+ const server = await read('viewer.mjs')+ assert.match(server, /__HPS_TOKEN__/)+})++test('the page loads only files the server is willing to serve', async () => {+ const [html, server] = await Promise.all([read('viewer/index.html'), read('viewer.mjs')])+ const referenced = [...html.matchAll(/(?:src|href)="([^"]+)"/g)].map((match) => match[1])+ for (const file of referenced) {+ assert.match(server, new RegExp(`'/${file.replace('.', '\\.')}'`), `viewer.mjs does not serve ${file}`)+ }+ for (const file of await readdir(join(PACKAGE, 'viewer'))) {+ assert.ok(['index.html', 'app.js', 'app.css', 'scale.js'].includes(file), `unexpected file in viewer/: ${file}`)+ }+})++test('no inline script survives the CSP the server sends', async () => {+ const html = await read('viewer/index.html')+ assert.equal(/<script(?![^>]*\bsrc=)/.test(html), false, 'an inline <script> would be blocked')+ assert.match(html, /<script type="module" src="app\.js">/)+ const server = await read('viewer.mjs')+ assert.match(server, /script-src 'self'/)+ assert.equal(server.includes('unsafe-eval'), false)+})++test('the stylesheet defines dark in both the ways the app can ask for it', async () => {+ const css = await read('viewer/app.css')+ assert.match(css, /@media \(prefers-color-scheme: dark\)/)+ assert.match(css, /:root:not\(\[data-theme="light"\]\)/)+ assert.match(css, /:root\[data-theme="dark"\]/)+ assert.match(css, /body \{[^}]*background: var\(--bg\)/)+})++test('the verbs the pane offers are the verbs the server accepts', async () => {+ const [js, server] = await Promise.all([read('viewer/app.js'), read('viewer.mjs')])+ const allowed = new Set(server.match(/const VERBS = new Set\(\[([^\]]+)\]\)/)[1].match(/'[a-z]+'/g).map((word) => word.slice(1, -1)))+ for (const match of js.matchAll(/\['(pause|resume|retire|resume|pin|unpin|clear)', '/g)) {+ if (match[1] !== 'clear') assert.ok(allowed.has(match[1]), `the server does not accept ${match[1]}`)+ }+ for (const forbidden of ['delete', 'kill', 'remove']) assert.equal(allowed.has(forbidden), false)+})++/**+ * A `dom.x` the script uses but never looked up is undefined at runtime, and the first time it is touched+ * the whole render throws. Two of those shipped unnoticed — `UNITS` after a refactor, `dom.ruleRetire` after+ * a rename — and each one blanked the pane while every other test here passed.+ */+test('every dom handle the script touches is one it looked up', async () => {+ const js = await read('viewer/app.js')+ const block = js.slice(js.indexOf('const dom = {'), js.indexOf('}', js.indexOf('const dom = {')))+ const defined = new Set([...block.matchAll(/(\w+):\s*el\(/g)].map((m) => m[1]))+ const used = new Set([...js.matchAll(/\bdom\.(\w+)/g)].map((m) => m[1]))+ assert.deepEqual([...used].filter((name) => !defined.has(name)), [])+})++test('every name the script imports from scale.js is one scale.js exports, and every one it uses is imported', async () => {+ const [js, scale] = await Promise.all([read('viewer/app.js'), read('viewer/scale.js')])+ const exported = new Set([...scale.matchAll(/export (?:const|function) (\w+)/g)].map((m) => m[1]))+ const imported = new Set(js.match(/import \{([^}]+)\} from '\.\/scale\.js'/)[1].split(',').map((name) => name.trim()))+ for (const name of imported) assert.ok(exported.has(name), `scale.js does not export ${name}`)+ for (const name of exported) {+ if (new RegExp(`\\b${name}\\b`).test(js.replace(/import \{[^}]+\} from '\.\/scale\.js'/, ''))) {+ assert.ok(imported.has(name), `app.js uses ${name} from scale.js without importing it`)+ }+ }+})diff --git a/store/agents/harness-monitor/test/panes.test.mjs b/store/agents/harness-monitor/test/panes.test.mjsnew file mode 100644index 000000000..aae634e58--- /dev/null+++ b/store/agents/harness-monitor/test/panes.test.mjs@@ -0,0 +1,110 @@+import assert from 'node:assert/strict'+import { test } from 'node:test'+import { capture, engineProcess, holdOpen, isPaneId, looksBlocked, paneState, panes, sendLine } from '../lib/panes.mjs'+import { fakeTmux, pane, table } from './fixtures.mjs'++const LIST = [+ '%1§§0§§100§§2.1.268§§harness-claude-1§§1§§1§§1§§§§1789900000',+ '%2§§1§§0§§§§harness-codex-2§§0§§1§§1§§0§§1789800000',+ 'garbage line',+ '%3§§0§§300§§zsh§§my-own-session§§0§§2§§1§§§§1789700000',+].join('\n')++test('panes parse, including a dead one and an empty user option', async () => {+ const rows = await panes({ run: async () => LIST })+ assert.equal(rows.size, 3)+ assert.equal(rows.get('%1').dead, false)+ assert.equal(rows.get('%1').attached, true)+ assert.equal(rows.get('%1').pid, 100)+ assert.equal(rows.get('%1').engineExit, null)+ assert.equal(rows.get('%2').dead, true)+ assert.equal(rows.get('%2').engineExit, 0)+ assert.equal(rows.get('%2').pid, null)+ assert.equal(rows.get('%3').target, 'my-own-session:2.1')+ assert.equal(rows.get('%1').lastOutput, 1789900000000)+})++test('no tmux server is an answer, not a crash', async () => {+ const rows = await panes({ run: async () => { throw new Error('no server running') } })+ assert.equal(rows.size, 0)+})++test('a pane id is checked before it is ever passed as an argument', async () => {+ assert.ok(isPaneId('%12'))+ assert.equal(isPaneId('%12; rm -rf /'), false)+ assert.equal(isPaneId('12'), false)+ await assert.rejects(() => sendLine('%1; danger', 'ls'), /Not a tmux pane id/)+ await assert.rejects(() => sendLine('%1', 'ls\nrm -rf /'), /one line/)+})++test('the engine is found at the root of the pane, where tmux usually puts it', () => {+ const found = engineProcess(pane(), table(), 'claude')+ assert.equal(found.pid, 100)+ assert.equal(found.engineAlive, true)+ assert.equal(found.rss, 400 * 1024 * 1024)+})++test('the engine is also found below the pane, and memory is the whole subtree', () => {+ const tree = table({ comm: '/bin/zsh', rss: 5 * 1024 * 1024, children: [{ pid: 101, comm: '/usr/local/bin/codex', rss: 300 * 1024 * 1024, cpu: 7 }] })+ const found = engineProcess(pane(), tree, 'codex')+ assert.equal(found.pid, 101)+ assert.equal(found.procs, 2)+ assert.equal(found.rss, 305 * 1024 * 1024)+ assert.equal(found.cpu.toFixed(1), '7.2') // the shell's own 0.2 counts too: the subtree is the cost+})++test('a pane that fell back to a shell holds no memory against the agent', () => {+ const found = engineProcess(pane(), table({ comm: '-zsh', rss: 6 * 1024 * 1024 }), 'claude')+ assert.equal(found.engineAlive, false)+ assert.equal(found.rss, 0)+})++test('an open prompt is recognized, and ordinary output is not', () => {+ assert.ok(looksBlocked('Do you want to proceed?\n❯ 1. Yes\n 2. No'))+ assert.ok(looksBlocked('Allow command? (y/n)'))+ assert.ok(looksBlocked('Waiting for your approval'))+ assert.ok(looksBlocked('Which file should I edit?'))+ assert.equal(looksBlocked('Wrote 14 files.\nDone.'), false)+ assert.equal(looksBlocked(''), false)+ assert.equal(looksBlocked('\u001b[32mAll tests passed\u001b[0m'), false)+})++test('holding a pane open and reading it back go through tmux with an argument list', async () => {+ const tmux = fakeTmux({ dead: true, command: 'zsh', engineExit: 0 })+ assert.equal(await holdOpen('%1', true, { run: tmux.run }), true)+ assert.deepEqual(tmux.calls[0], ['set-option', '-w', '-t', '%1', 'remain-on-exit', 'on'])+ const observed = await paneState('%1', { run: tmux.run })+ assert.deepEqual(observed, { dead: true, command: 'zsh', engineExit: 0 })+ await capture('%1', { lines: 5, run: tmux.run })+ assert.deepEqual(tmux.calls.at(-1), ['capture-pane', '-p', '-t', '%1', '-S', '-5'])+})++test('the trust prompt an engine draws on a new folder counts as blocked', () => {+ // Copied from a real pane: this shape walked past an earlier version of the patterns.+ const screen = [+ '────────────────────────────────────────────',+ ' Quick safety check: Is this a project you created or one you trust?',+ " Claude Code'll be able to read, edit, and execute files here.",+ ' ❯ No, exit',+ ' Yes, I trust this folder',+ ' Enter to confirm · Esc to cancel',+ ].join('\n')+ assert.ok(looksBlocked(screen))+})++test('an engine waiting at its own empty prompt is idle, not blocked', () => {+ const screen = [+ '▐▛███▛█ Claude Code v2.1.278',+ ' ▝▝ ▝▝ ~/code/widgets',+ '────────────────────────────────────────────',+ '❯ ',+ '────────────────────────────────────────────',+ ' ⏵⏵ auto mode on (shift+tab to cycle)',+ ].join('\n')+ assert.equal(looksBlocked(screen), false)+})++test('a finished turn above an empty prompt is idle too', () => {+ const screen = ['❯ Reply with exactly one word: acorn', '⏺ acorn', '✻ Cogitated for 5s · done', '❯ '].join('\n')+ assert.equal(looksBlocked(screen), false)+})diff --git a/store/agents/harness-monitor/test/policy.test.mjs b/store/agents/harness-monitor/test/policy.test.mjsnew file mode 100644index 000000000..d32661135--- /dev/null+++ b/store/agents/harness-monitor/test/policy.test.mjs@@ -0,0 +1,128 @@+import assert from 'node:assert/strict'+import { test } from 'node:test'+import { DAY, HOUR, row } from './fixtures.mjs'+import { DEFAULT_POLICY, decide, formatDuration, humanIdle, normalizePolicy, parseDuration, protectionFor, simulate } from '../lib/policy.mjs'++test('durations parse the units a person types, and refuse the rest', () => {+ assert.equal(parseDuration('4h'), 4 * HOUR)+ assert.equal(parseDuration('90m'), 90 * 60_000)+ assert.equal(parseDuration('14d'), 14 * DAY)+ assert.equal(parseDuration('1w'), 7 * DAY)+ assert.equal(parseDuration(1500), 1500)+ assert.throws(() => parseDuration('4 hours'), /Not a duration/)+ assert.throws(() => parseDuration('soon'), /Not a duration/)+ assert.throws(() => parseDuration(-1), /Not a duration/)+})++test('formatDuration round-trips whole units', () => {+ for (const value of ['30s', '15m', '4h', '3d', '2w']) assert.equal(formatDuration(parseDuration(value)), value)+})++test('humanIdle never shows two units', () => {+ assert.equal(humanIdle(10_000), 'now')+ assert.equal(humanIdle(22 * 60_000), '22m')+ assert.equal(humanIdle(4 * HOUR), '4h')+ assert.equal(humanIdle(3 * DAY + 4 * HOUR), '3d')+ assert.equal(humanIdle(15 * DAY), '2w')+ assert.equal(humanIdle(400 * DAY), '9w+')+})++test('a policy with a bad number fails at load, not mid-fleet', () => {+ assert.throws(() => normalizePolicy({ runningCeiling: -1 }), /runningCeiling/)+ assert.throws(() => normalizePolicy({ runningCeiling: 1.5 }), /runningCeiling/)+ assert.throws(() => normalizePolicy({ pauseAfterIdle: 'ages' }), /Not a duration/)+ assert.throws(() => normalizePolicy({ pauseAfterIdle: '2d', hideAfterIdle: '1d' }), /at least pauseAfterIdle/)+})++test('a policy keeps keys it does not know about', () => {+ const policy = normalizePolicy({ somethingNewer: 7 })+ assert.equal(policy.somethingNewer, 7)+ assert.equal(policy.runningCeiling, DEFAULT_POLICY.runningCeiling)+})++test('protections are reported in the order a person would say them', () => {+ const policy = normalizePolicy({})+ assert.equal(protectionFor(row({ pinned: true, working: true }), policy).by, 'pinned')+ assert.equal(protectionFor(row({ needsInput: true, working: true }), policy).by, 'needsInput')+ assert.equal(protectionFor(row({ working: true }), policy).by, 'working')+ assert.equal(protectionFor(row({ attached: true }), policy).by, 'attached')+ assert.equal(protectionFor(row(), policy), null)+})++test('the idle rules pause what has gone quiet and leave the fresh alone', () => {+ const rows = [+ row({ id: 'fresh', idleMs: 5 * 60_000 }),+ row({ id: 'stale', idleMs: 2 * DAY }),+ row({ id: 'ancient', idleMs: 20 * DAY }),+ row({ id: 'paused-stale', state: 'paused', idleMs: 20 * DAY, rssBytes: 0 }),+ ]+ const { entries, totals } = decide(rows, { runningCeiling: 99 })+ const byId = Object.fromEntries(entries.map((entry) => [entry.id, entry]))+ assert.equal(byId.fresh.action, 'keep')+ assert.equal(byId.stale.action, 'pause')+ assert.equal(byId.stale.rule, 'pauseAfterIdle')+ assert.equal(byId.ancient.action, 'pause')+ assert.equal(byId['paused-stale'].action, 'keep', 'already paused: there is nothing left to do to it')+ assert.equal(totals.pause, 2)+})++test('the reason echoes the threshold as it was written, not as the clock reads it back', () => {+ const { entries } = decide([row({ idleMs: 20 * DAY })], { pauseAfterIdle: '90m' })+ assert.match(entries[0].why, /past 90m/)+})++test('the ceiling pauses the least recently active, and never a protected row', () => {+ const rows = [+ row({ id: 'a', idleMs: 2 * HOUR }),+ row({ id: 'b', idleMs: 3 * HOUR }),+ row({ id: 'c', idleMs: 4 * HOUR }),+ row({ id: 'pinned', idleMs: 9 * HOUR, pinned: true }),+ ]+ const { entries, totals } = decide(rows, { runningCeiling: 2 })+ const byId = Object.fromEntries(entries.map((entry) => [entry.id, entry]))+ assert.equal(byId.a.action, 'keep')+ assert.equal(byId.b.action, 'keep')+ assert.equal(byId.c.action, 'pause')+ assert.equal(byId.c.rule, 'runningCeiling')+ assert.equal(byId.pinned.action, 'keep')+ assert.equal(totals.runningAfter, 3) // the pinned one still counts as running+})++test('a ceiling of zero still cannot pause what is protected', () => {+ const { entries } = decide([row({ id: 'p', pinned: true, idleMs: 3 * HOUR })], { runningCeiling: 0 })+ assert.equal(entries[0].action, 'keep')+})++test('a workspace that no longer exists is paused, whatever its idle time', () => {+ const { entries } = decide([row({ idleMs: 2 * HOUR, workspaceGone: true })], {})+ assert.equal(entries[0].action, 'pause')+ assert.equal(entries[0].rule, 'workspaceGone')+})++test('the loosened defaults leave yesterday afternoon alone', () => {+ const { entries } = decide([row({ id: 'yesterday', idleMs: 18 * HOUR }), row({ id: 'last-week', idleMs: 6 * DAY })], {})+ assert.equal(entries[0].action, 'keep')+ assert.equal(entries[1].action, 'pause')+})++test('simulate is the same plan, without the keeps', () => {+ const rows = [row({ id: 'a', idleMs: 2 * DAY }), row({ id: 'b', idleMs: 60_000 })]+ const result = simulate(rows, {})+ assert.equal(result.pause, 1)+ assert.equal(result.plan.length, 1)+ assert.equal(result.plan[0].id, 'a')+ assert.equal(result.frees, rows[0].rssBytes)+})++test('a shell is left alone by every rule, however old it is', () => {+ const { entries, totals } = decide([row({ state: 'terminal', idleMs: 40 * DAY, rssBytes: 0 })], { runningCeiling: 0 })+ assert.equal(entries[0].action, 'keep')+ assert.match(entries[0].why, /a shell, not an engine/)+ assert.equal(totals.pause, 0)+})++test('the default ceiling is a backstop: a normal busy day never reaches it', () => {+ const rows = Array.from({ length: 60 }, (_, i) => row({ id: `h${i}`, name: `h${i}`, idleMs: (i + 2) * HOUR / 4 }))+ const { totals } = decide(rows, {})+ assert.equal(totals.pause, 0, 'sixty harnesses used today, and the default pauses none of them')+})diff --git a/store/agents/harness-monitor/test/resume.test.mjs b/store/agents/harness-monitor/test/resume.test.mjsnew file mode 100644index 000000000..a4e7f5fec--- /dev/null+++ b/store/agents/harness-monitor/test/resume.test.mjs@@ -0,0 +1,57 @@+import assert from 'node:assert/strict'+import { test } from 'node:test'+import { readFile } from 'node:fs/promises'+import { ENGINE_BIN, RESUME_ARGS, canResume, resumeCommand } from '../lib/resume.mjs'++const SESSION = '2d9e6b41-8c07-4f3a-b512-6a1e0f7c9d33'++test('the resume line is the one a person would type', () => {+ assert.equal(resumeCommand('claude', SESSION), `claude --resume ${SESSION}`)+ assert.equal(resumeCommand('codex', SESSION), `codex resume ${SESSION}`)+ assert.equal(resumeCommand('opencode', SESSION), `opencode --session ${SESSION}`)+ assert.equal(resumeCommand('amp', SESSION), `amp threads continue ${SESSION}`)+ assert.equal(resumeCommand('commandcode', SESSION), `cmd --resume ${SESSION}`)+ assert.equal(resumeCommand('cursor', SESSION), `cursor-agent --resume ${SESSION}`)+})++test('an engine with no resume is refused, so it is never paused either', () => {+ assert.equal(canResume('devin'), false)+ assert.equal(canResume('terminal'), false)+ assert.equal(canResume('claude'), true)+ assert.throws(() => resumeCommand('devin', SESSION), /does not know how to resume devin/)+})++test('a session id that is not one an engine wrote never reaches a shell', () => {+ for (const bad of ['; rm -rf /', 'a b', '$(whoami)', '`id`', "x'y", 'short', '', null, '../../etc/passwd']) {+ assert.throws(() => resumeCommand('claude', bad), /session id/, `accepted ${JSON.stringify(bad)}`)+ }+})++test('every engine that can be resumed has a binary to resume it with', () => {+ for (const engine of Object.keys(RESUME_ARGS)) {+ assert.ok(ENGINE_BIN[engine], `${engine} has resume args but no command name`)+ assert.match(resumeCommand(engine, SESSION), new RegExp(`^${ENGINE_BIN[engine]} `))+ }+})++/**+ * The two tables are mirrored from the daemon by hand, because this package installs on its own. This test+ * is the drift guard: it reads the daemon's own source when it is there, and skips when it is not (an+ * installed copy of the package, a release tarball).+ */+test('the resume table still matches the daemon it was copied from', async (t) => {+ const candidates = ['../../../../cli/src/lib/engineLaunch.ts', '../../../../../cli/src/lib/engineLaunch.ts']+ let source = null+ for (const path of candidates) {+ try { source = await readFile(new URL(path, import.meta.url), 'utf8'); break } catch { /* not this layout */ }+ }+ if (!source) return t.skip('the daemon source is not beside this package')+ const block = source.match(/LAUNCH_RESUME_FLAG[^=]*=\s*\{([\s\S]*?)\n\}/)+ assert.ok(block, 'the daemon no longer declares LAUNCH_RESUME_FLAG the way this test reads it')+ const theirs = {}+ for (const line of block[1].split('\n')) {+ const match = /^\s*(\w+):\s*\[([^\]]*)\]/.exec(line)+ if (match) theirs[match[1]] = match[2].split(',').map((word) => word.trim().replace(/^'|'$/g, '')).filter(Boolean)+ }+ assert.deepEqual(RESUME_ARGS, theirs, 'lib/resume.mjs has drifted from the daemon\'s LAUNCH_RESUME_FLAG')+})diff --git a/store/agents/harness-monitor/test/scale.test.mjs b/store/agents/harness-monitor/test/scale.test.mjsnew file mode 100644index 000000000..96f703b3e--- /dev/null+++ b/store/agents/harness-monitor/test/scale.test.mjs@@ -0,0 +1,44 @@+import assert from 'node:assert/strict'+import { test } from 'node:test'+import { CEIL, FLOOR, PAUSE_STEPS, HIDE_STEPS, bytes, humanIdle as pageIdle, idleOfX, parseDuration, snap, xOf } from '../viewer/scale.js'+import { humanIdle as cliIdle } from '../lib/policy.mjs'+import { DAY, HOUR } from './fixtures.mjs'++test('now is the right edge and a month ago is the left', () => {+ assert.equal(xOf(0), 1)+ assert.equal(xOf(FLOOR), 1)+ assert.equal(xOf(CEIL), 0)+ assert.equal(xOf(CEIL * 10), 0)+})++test('the scale is monotonic and its inverse round-trips', () => {+ let previous = 1+ for (const idle of [FLOOR, 10 * 60_000, HOUR, 6 * HOUR, DAY, 7 * DAY, 30 * DAY]) {+ const x = xOf(idle)+ assert.ok(x <= previous, `${idle} should sit left of the one before it`)+ previous = x+ assert.ok(Math.abs(idleOfX(x) - idle) / idle < 1e-9)+ }+})++test('a dragged rule lands on a threshold a person would type', () => {+ assert.equal(snap(4.2 * HOUR, PAUSE_STEPS), '4h')+ assert.equal(snap(70 * 60_000, PAUSE_STEPS), '1h')+ assert.equal(snap(13 * DAY, HIDE_STEPS), '14d')+ assert.equal(snap(1, PAUSE_STEPS), '15m')+ assert.equal(snap(99 * DAY, HIDE_STEPS), '30d')+})++test('the pane and the terminal say the same thing about an idle time', () => {+ for (const ms of [0, 30_000, 5 * 60_000, HOUR, 5 * HOUR, DAY, 3 * DAY, 15 * DAY, 400 * DAY]) {+ assert.equal(pageIdle(ms), cliIdle(ms), `disagreed at ${ms}ms`)+ }+})++test('durations and bytes read the way the columns need them', () => {+ assert.equal(parseDuration('4h'), 4 * HOUR)+ assert.equal(parseDuration('nonsense'), 0)+ assert.equal(bytes(0), '—')+ assert.equal(bytes(400 * 1024 * 1024), '400M')+ assert.equal(bytes(2 * 1024 ** 3), '2.0G')+})diff --git a/store/agents/harness-monitor/test/server.test.mjs b/store/agents/harness-monitor/test/server.test.mjsnew file mode 100644index 000000000..2d5fe036d--- /dev/null+++ b/store/agents/harness-monitor/test/server.test.mjs@@ -0,0 +1,162 @@+import assert from 'node:assert/strict'+import { test } from 'node:test'+import http from 'node:http'+import { mkdtemp, readFile } from 'node:fs/promises'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { DAY, HOUR, row } from './fixtures.mjs'+import { createViewer } from '../viewer.mjs'++/** A viewer over a fleet that is entirely made up: no daemon, no tmux, no processes. */+async function serve(rows = [row({ id: 'a1', idleMs: 2 * DAY }), row({ id: 'a2', state: 'paused', idleMs: 20 * DAY, rssBytes: 0 })], options = {}) {+ const workspace = await mkdtemp(join(tmpdir(), 'hps-server-'))+ // A fresh rules file and ticket book per test: tests in one file run in one process, and a pin left by+ // one test must not decide what the next one sees.+ process.env.HARNESS_MONITOR_CONFIG = join(workspace, 'config', 'policy.jsonc')+ process.env.HARNESS_MONITOR_STATE = join(workspace, 'state')+ const done = []+ const viewer = createViewer({+ workspace,+ intervalMs: 60_000,+ collect: async () => ({ rows, machines: [], problems: [], observedAt: Date.now() }),+ scan: async () => '$ ',+ verbs: {+ pause: async (target) => { done.push(['pause', target.id]); return { ok: true, id: target.id, name: target.name, action: 'pause', detail: 'engine stopped', freed: target.rssBytes, ticket: { sessionId: 'sess-0123456789ab', engine: target.engine } } },+ resume: async (target) => { done.push(['resume', target.id]); return { ok: true, id: target.id, name: target.name, action: 'resume', resumed: true, detail: 'resumed' } },+ },+ ...options,+ })+ const port = await viewer.start()+ await viewer.observed+ return { viewer, port, workspace, done, base: `http://127.0.0.1:${port}` }+}++test('the snapshot carries the fleet, the policy and the plan', async (t) => {+ const { viewer, base } = await serve()+ t.after(() => viewer.close())+ const snapshot = await (await fetch(`${base}/api/snapshot`)).json()+ assert.equal(snapshot.status, 'ok')+ assert.equal(snapshot.rows.length, 2)+ assert.equal(snapshot.summary.running, 1)+ assert.equal(snapshot.policy.runningCeiling, 100)+ assert.match(snapshot.configPath, /policy\.jsonc$/, 'the pane can tell a person where the file is')+ assert.ok(snapshot.plan.find((entry) => entry.id === 'a1' && entry.action === 'pause'))+ assert.equal(snapshot.plan.find((entry) => entry.id === 'a2').action, 'keep', 'already paused: nothing left to do')+})++test('the page is served with a token in it and a CSP that forbids inline script', async (t) => {+ const { viewer, base } = await serve()+ t.after(() => viewer.close())+ const response = await fetch(`${base}/`)+ const html = await response.text()+ assert.match(response.headers.get('content-security-policy'), /script-src 'self'/)+ assert.equal(html.includes('__HPS_TOKEN__'), false)+ assert.match(html, new RegExp(`content="${viewer.token}"`))+ for (const path of ['/app.js', '/app.css', '/scale.js']) {+ assert.equal((await fetch(`${base}${path}`)).status, 200, path)+ }+ assert.equal((await fetch(`${base}/../viewer.mjs`)).status, 404)+ assert.equal((await fetch(`${base}/monitor.json`)).status, 404)+})++test('a request for another host is refused, whatever it asks for', async (t) => {+ const { viewer, base, port } = await serve()+ t.after(() => viewer.close())+ // `fetch` will not let a caller forge Host, so this one goes out over a raw request: a page reaching+ // this server through some other name (a DNS rebind, a proxy) must not be answered.+ const forged = await new Promise((resolve) => {+ const request = http.request({ host: '127.0.0.1', port, path: '/api/snapshot', headers: { host: 'example.com' } }, (response) => {+ response.resume(); resolve(response.statusCode)+ })+ request.end()+ })+ assert.equal(forged, 403)+ const cross = await fetch(`${base}/api/snapshot`, { headers: { origin: 'http://evil.example' } })+ assert.equal(cross.status, 403)+})++test('a write without the token does nothing', async (t) => {+ const { viewer, base, done } = await serve()+ t.after(() => viewer.close())+ const response = await fetch(`${base}/api/act`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ verb: 'pause', ids: ['a1'] }) })+ assert.equal(response.status, 403)+ assert.deepEqual(done, [])+})++test('a verb Harness Monitor does not have is refused by name', async (t) => {+ const { viewer, base, done } = await serve()+ t.after(() => viewer.close())+ const reply = await post(base, viewer.token, '/api/act', { verb: 'retire', ids: ['a1'] })+ assert.match(reply.error, /Not a verb/)+ const empty = await post(base, viewer.token, '/api/act', { verb: 'pause', ids: [] })+ assert.match(empty.error, /at least one/)+ const unknown = await post(base, viewer.token, '/api/act', { verb: 'pause', ids: ['nope'] })+ assert.match(unknown.error, /not in the current view/)+ assert.deepEqual(done, [])+})++test('a verb with the token acts, records a receipt, and refreshes', async (t) => {+ const { viewer, base, workspace, done } = await serve()+ t.after(() => viewer.close())+ const reply = await post(base, viewer.token, '/api/act', { verb: 'pause', ids: ['a1'] })+ assert.equal(reply.results.length, 1)+ assert.deepEqual(done, [['pause', 'a1']])+ const tickets = JSON.parse(await readFile(join(process.env.HARNESS_MONITOR_STATE, 'paused.json'), 'utf8'))+ assert.ok(tickets.a1, 'the resume ticket was written down')+ const log = await readFile(join(process.env.HARNESS_MONITOR_STATE, 'log.jsonl'), 'utf8')+ assert.match(log, /"by":"pane"/)+})++test('pinning is a state edit and needs no engine at all', async (t) => {+ const { viewer, base, workspace, done } = await serve()+ t.after(() => viewer.close())+ await post(base, viewer.token, '/api/act', { verb: 'pin', ids: ['a1', 'a2'] })+ const rules = await readFile(process.env.HARNESS_MONITOR_CONFIG, 'utf8')+ assert.match(rules, /"pins": \["a1","a2"\]/, 'pins land in the rules file, where a person can see them')+ assert.match(rules, /\/\/ Most engines running at once/, 'and the comments are still there')+ assert.deepEqual(done, [])+})++test('a policy is validated before it is written', async (t) => {+ const { viewer, base, workspace } = await serve()+ t.after(() => viewer.close())+ const bad = await post(base, viewer.token, '/api/policy', { policy: { pauseAfterIdle: 'whenever' } })+ assert.match(bad.error, /Not a duration/)+ const worse = await post(base, viewer.token, '/api/policy', { policy: { pauseAfterIdle: '2d', hideAfterIdle: '1d' } })+ assert.match(worse.error, /at least pauseAfterIdle/)+ const good = await post(base, viewer.token, '/api/policy', { policy: { pauseAfterIdle: '8h', protect: { pinned: false } } })+ assert.equal(good.policy.pauseAfterIdle, '8h')+ const rules = await readFile(process.env.HARNESS_MONITOR_CONFIG, 'utf8')+ assert.match(rules, /"pauseAfterIdle": "8h"/)+ assert.match(rules, /"pinned": true/, 'the pane may only change the thresholds it draws, never a guard')+})++test('the pane header verdict is written from the same plan the page draws', async (t) => {+ const { viewer, workspace } = await serve()+ t.after(() => viewer.close())+ const verdict = JSON.parse(await readFile(join(workspace, '.harness', 'verdict.json'), 'utf8'))+ assert.equal(verdict.ready, false)+ assert.match(verdict.summary, /2 harnesses/)+ assert.ok(verdict.findings.length)+})++test('the stream opens with the current snapshot', async (t) => {+ const { viewer, base } = await serve()+ t.after(() => viewer.close())+ const response = await fetch(`${base}/events`)+ const reader = response.body.getReader()+ const { value } = await reader.read()+ const text = new TextDecoder().decode(value)+ assert.match(text, /^event: snapshot/)+ assert.match(text, /"status":"ok"/)+ await reader.cancel()+})++async function post(base, token, path, payload) {+ const response = await fetch(`${base}${path}`, {+ method: 'POST',+ headers: { 'content-type': 'application/json', 'x-hps-token': token },+ body: JSON.stringify(payload),+ })+ return response.json()+}diff --git a/store/agents/harness-monitor/test/setup.mjs b/store/agents/harness-monitor/test/setup.mjsnew file mode 100644index 000000000..62f4ffc85--- /dev/null+++ b/store/agents/harness-monitor/test/setup.mjs@@ -0,0 +1,23 @@+/**+ * Every test process gets its own config and state directories.+ *+ * The rules and tickets live in the person's real `~/.config/harness/` and `~/.harness/monitor/`. A test+ * that forgot to redirect them once wrote fake pins and a fake ticket into a real machine's files — so+ * the redirect is not left to each test to remember. It happens here, before any module loads, and the+ * real paths are refused outright if anything still reaches for them.+ */+import { mkdtempSync } from 'node:fs'+import { tmpdir, homedir } from 'node:os'+import { join } from 'node:path'++const root = mkdtempSync(join(tmpdir(), 'harness-monitor-test-'))+process.env.HARNESS_MONITOR_CONFIG = join(root, 'config', 'policy.jsonc')+process.env.HARNESS_MONITOR_STATE = join(root, 'state')+process.env.HARNESS_MONITOR_TEST_ROOT = root++const real = [join(homedir(), '.config', 'harness'), join(homedir(), '.harness', 'monitor')]+export function assertNotReal(path) {+ for (const dir of real) if (String(path).startsWith(dir)) throw new Error(`A test reached a real path: ${path}`)+}+assertNotReal(process.env.HARNESS_MONITOR_CONFIG)+assertNotReal(process.env.HARNESS_MONITOR_STATE)diff --git a/store/agents/harness-monitor/test/state.test.mjs b/store/agents/harness-monitor/test/state.test.mjsnew file mode 100644index 000000000..975a78f4c--- /dev/null+++ b/store/agents/harness-monitor/test/state.test.mjs@@ -0,0 +1,137 @@+import assert from 'node:assert/strict'+import { test } from 'node:test'+import { mkdir, mkdtemp, readFile, writeFile } from 'node:fs/promises'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { DAY, row } from './fixtures.mjs'+import { stripJsonc, updateConfig } from '../lib/config.mjs'+import { EMPTY_STATE, clearPaused, forget, gb, markPaused, pin, readLog, readState, record, writeState, writeVerdict } from '../lib/state.mjs'+import { decide } from '../lib/policy.mjs'++const workspace = () => mkdtemp(join(tmpdir(), 'hps-state-'))++/** Each test its own machine: its own rules file and ticket book, never the real ones. */+async function machine() {+ const dir = await mkdtemp(join(tmpdir(), 'hps-machine-'))+ return { dir, env: { ...process.env, HARNESS_MONITOR_CONFIG: join(dir, 'config', 'policy.jsonc'), HARNESS_MONITOR_STATE: join(dir, 'state') } }+}++test('a machine with no rules file gets the commented default, and reads it', async () => {+ const { env } = await machine()+ const state = await readState(null, env)+ assert.equal(state.policy.runningCeiling, EMPTY_STATE.policy.runningCeiling)+ assert.equal(state.policy.pauseAfterIdle, '1d')+ const text = await readFile(env.HARNESS_MONITOR_CONFIG, 'utf8')+ assert.match(text, /\/\/ Most engines running at once/, 'the file explains itself')+ assert.match(text, /hps pause --policy/, 'and says how to preview a change')+})++test('a rules file with a typo in it names the file it is in', async () => {+ const { env } = await machine()+ await mkdir(join(env.HARNESS_MONITOR_CONFIG, '..'), { recursive: true })+ await writeFile(env.HARNESS_MONITOR_CONFIG, '{ "pauseAfterIdle": "whenever" }')+ await assert.rejects(() => readState(null, env), /policy\.jsonc: Not a duration/)+ await writeFile(env.HARNESS_MONITOR_CONFIG, '{ "pauseAfterIdle": ')+ await assert.rejects(() => readState(null, env), /policy\.jsonc: not valid JSON/)+})++test('comments, trailing commas and slashes inside strings all survive the reader', () => {+ const text = `{+ // a comment+ "a": "http://example.com/x", /* another */+ "b": [1, 2,],+ }`+ assert.deepEqual(JSON.parse(stripJsonc(text)), { a: 'http://example.com/x', b: [1, 2] })+})++test('changing a value leaves every comment in the person\'s file exactly where it was', async () => {+ const { env } = await machine()+ await readState(null, env)+ const before = await readFile(env.HARNESS_MONITOR_CONFIG, 'utf8')+ await updateConfig({ pauseAfterIdle: '3d', runningCeiling: 30 }, env)+ const after = await readFile(env.HARNESS_MONITOR_CONFIG, 'utf8')+ assert.equal(after.split('//').length, before.split('//').length, 'no comment was lost')+ assert.match(after, /"pauseAfterIdle": "3d"/)+ assert.match(after, /"runningCeiling": 30/)+ assert.equal((await readState(null, env)).policy.pauseAfterIdle, '3d')+})++test('tickets and pins are written where the program keeps them, and read back', async () => {+ const { env } = await machine()+ const state = await readState(null, env)+ await writeState(null, { ...state, pins: ['a1'], paused: { a2: { sessionId: 'sess-0123456789ab', engine: 'claude' } } }, env)+ const back = await readState(null, env)+ assert.deepEqual(back.pins, ['a1'])+ assert.equal(back.paused.a2.sessionId, 'sess-0123456789ab')+ assert.match(await readFile(env.HARNESS_MONITOR_CONFIG, 'utf8'), /"pins": \["a1"\]/)+})++test('an old per-workspace file is carried forward once: its data yes, its stricter policy no', async () => {+ const { env } = await machine()+ const workspace = await mkdtemp(join(tmpdir(), 'hps-old-workspace-'))+ await writeFile(join(workspace, 'monitor.json'), JSON.stringify({+ policy: { pauseAfterIdle: '4h', runningCeiling: 12 },+ pins: ['keep-me'],+ paused: { p1: { sessionId: 'sess-0123456789ab', engine: 'claude' }, p2: { sessionId: 'sess-abcdef012345', engine: 'codex' } },+ }))+ const state = await readState(workspace, env)+ assert.equal(Object.keys(state.paused).length, 2, 'every paused harness is still resumable')+ assert.deepEqual(state.pins, ['keep-me'])+ assert.equal(state.policy.pauseAfterIdle, '1d', 'the old 4h did not come along')+ const marker = JSON.parse(await readFile(join(workspace, 'monitor.json'), 'utf8'))+ assert.equal(marker.migrated, true)+ const again = await readState(workspace, env)+ assert.equal(Object.keys(again.paused).length, 2, 'running it twice does not double anything')+})++test('pin and the resume ticket are the only edits, and each is reversible', () => {+ let state = { ...EMPTY_STATE }+ state = pin(state, 'a1', true)+ assert.deepEqual(state.pins, ['a1'])+ state = pin(state, 'a1', true)+ assert.deepEqual(state.pins, ['a1'], 'pinning twice is still one pin')+ state = markPaused(state, row(), { sessionId: 'sess-0123456789ab', engine: 'claude' })+ assert.equal(state.paused.a1.sessionId, 'sess-0123456789ab')+ state = clearPaused(state, 'a1')+ assert.equal(state.paused.a1, undefined)+ state = forget(markPaused(pin(state, 'a1', true), row(), { sessionId: 'sess-0123456789ab', engine: 'claude' }), 'a1')+ assert.deepEqual(state.pins, [])+ assert.equal(state.paused.a1, undefined)+})++test('every action leaves a receipt, newest first', async () => {+ const dir = await workspace()+ await record(dir, { action: 'pause', id: 'a1', name: 'widgets', ok: true, detail: 'engine stopped' })+ await record(dir, { action: 'resume', id: 'a1', name: 'widgets', ok: true, detail: 'resumed' })+ const log = await readLog(dir)+ assert.equal(log.length, 2)+ assert.equal(log[0].action, 'resume')+ assert.ok(log[0].at)+})++test('a log that cannot be written does not undo the action', async () => {+ await record('/nope/not/a/place', { action: 'pause', ok: true })+})++test('the pane header is ready only when the fleet is inside its policy', async () => {+ const dir = await workspace()+ const tidy = [row({ idleMs: 60_000 })]+ const tidyPlan = decide(tidy, { runningCeiling: 12 })+ const good = await writeVerdict(dir, { summary: { total: 1, running: 1, paused: 0, held: 0, needsInput: 0 }, rows: tidy, plan: tidyPlan.entries })+ assert.equal(good.ready, true)++ const messy = [row({ id: 'a', idleMs: 9 * DAY }), row({ id: 'b', idleMs: 40 * DAY })]+ const messyPlan = decide(messy, { runningCeiling: 12 })+ const bad = await writeVerdict(dir, { summary: { total: 2, running: 2, paused: 0, held: 8e8, needsInput: 1 }, rows: messy, plan: messyPlan.entries, problems: [{ machine: 'studio', error: 'asleep' }] })+ assert.equal(bad.ready, false)+ assert.ok(bad.findings.some((finding) => finding.kind === 'idle'))+ assert.ok(bad.findings.some((finding) => finding.kind === 'attention'))+ assert.ok(bad.findings.some((finding) => finding.kind === 'machine' && finding.severity === 'error'))+ assert.match(bad.summary, /held/)+})++test('bytes are reported in the units a header can fit', () => {+ assert.equal(gb(2 * 1024 ** 3), '2.0 GB')+ assert.equal(gb(400 * 1024 ** 2), '400 MB')+ assert.equal(gb(900), '1 KB')+})diff --git a/store/agents/harness-monitor/toolchain/doctor.sh b/store/agents/harness-monitor/toolchain/doctor.shnew file mode 100755index 000000000..d4a8587cf--- /dev/null+++ b/store/agents/harness-monitor/toolchain/doctor.sh@@ -0,0 +1,15 @@+#!/usr/bin/env bash+# exit 0 = ready. Harness Monitor is ready when it can see the fleet: a Node to run on, tmux to read, and either+# the daemon's local bridge or its registry file.+set -u; cd "$(dirname "$0")/.."; bad=0+# shellcheck source=runtimes.sh+. toolchain/runtimes.sh+if harness_node 22; then echo "ok node $(node --version)"; else bad=1; fi+if command -v tmux >/dev/null 2>&1; then echo "ok tmux $(tmux -V | awk '{print $2}')"; else echo "miss tmux is not on PATH — pausing needs it"; bad=1; fi+seen=$(node toolchain/hps.mjs ls --json --all 2>/dev/null | node -e 'let s="";process.stdin.on("data",d=>s+=d).on("end",()=>{try{const j=JSON.parse(s);console.log(j.rows.length)}catch{console.log("")}})')+if [ -n "${seen:-}" ]; then+ echo "ok the fleet is readable ($seen harnesses in view)"+else+ echo "miss could not read the fleet — start Harness, or check that ~/.harness/cli/data/registry.json is readable"; bad=1+fi+exit $baddiff --git a/store/agents/harness-monitor/toolchain/hps b/store/agents/harness-monitor/toolchain/hpsnew file mode 100755index 000000000..c668d4050--- /dev/null+++ b/store/agents/harness-monitor/toolchain/hps@@ -0,0 +1,7 @@+#!/usr/bin/env bash+# The agent's hands, and a person's. Picks the Node the package installed against, then runs the CLI.+set -euo pipefail+cd "$(dirname "$0")/.."+. toolchain/runtimes.sh+harness_node 22 >/dev/null || { echo "miss node 22+ is required for Harness Monitor" >&2; exit 1; }+exec node toolchain/hps.mjs "$@"diff --git a/store/agents/harness-monitor/toolchain/hps.mjs b/store/agents/harness-monitor/toolchain/hps.mjsnew file mode 100755index 000000000..5f168c086--- /dev/null+++ b/store/agents/harness-monitor/toolchain/hps.mjs@@ -0,0 +1,267 @@+#!/usr/bin/env node+/**+ * `hps` — the fleet, from a terminal.+ *+ * Everything the agent does, a person can do by hand, with the same words and the same receipts: this+ * file is the only entry point, and the viewer calls the same library underneath. Verbs are the ones a+ * developer already has muscle memory for — `ls`, `pause`, `resume`, `gc`, `log` — and every one of them+ * takes `--json` so the agent beside it never has to parse a table meant for eyes.+ *+ * Nothing here deletes a harness. See lib/actions.mjs for why that boundary is the point.+ */++import { homedir } from 'node:os'+import { resolve } from 'node:path'+import { pause, resume } from '../lib/actions.mjs'+import { collect, resolveRef, summarize } from '../lib/inventory.mjs'+import { capture } from '../lib/panes.mjs'+import { DEFAULT_POLICY, decide, humanIdle, normalizePolicy, parseDuration } from '../lib/policy.mjs'+import { clearPaused, gb, markPaused, readState, record, writeState, writeVerdict } from '../lib/state.mjs'+import { footer, planLines, receiptLine, table } from '../lib/format.mjs'++const WORKSPACE = resolve(process.env.HARNESS_WORKSPACE || process.cwd())+const TTY = Boolean(process.stdout.isTTY) && !process.env.NO_COLOR+const COLUMNS = Number(process.env.COLUMNS) || process.stdout.columns || 120++const USAGE = `hps — every harness on this machine, running or paused++ hps the list, freshest first (like \`docker ps\`)+ hps top the same list, refreshing+ hps [--all] [--state running|paused|shell|gone] [--project NAME] [--engine NAME]+ [--idle 4h] [--sort idle|mem|name|project] [--limit N] [--watch [SECONDS]]+ [--machines] also list every other machine you have linked (read-only from here)+ hps show <ref> one harness in full, with the last thing on its pane+ hps pause <ref…> the engine exits; pane, scrollback and conversation stay+ hps resume <ref…> the engine comes back where it left off+ hps pause --policy what the rules would do to the fleet right now, and why+ hps pause --policy --apply do it+ hps pause --idle 8h one threshold instead of all of them+ hps resume --paused everything that is paused, back in one line+ hps attach <ref> hand this terminal to that pane (tmux attach, screen -r)++ <ref> is a row number from the last list, a %pane, an agent-id prefix, or part of a name.+ Add --json to any command. --force gets past a guard; --dry-run shows what would happen.+ \`park\`/\`wake\` alias pause/resume. \`prune\`, \`gc\` and \`policy\` alias \`pause --policy\`.++ The rules are a config file: ~/.config/harness/policy.jsonc. Edit it, or drag the two lines in the pane.+ Nothing here writes it for you — a setter subcommand was only ever a worse text editor. To exempt one+ harness, put its id in "pins" (or click the pin in the pane).+`++function parseArgs(argv) {+ const flags = {}; const rest = []+ for (let i = 0; i < argv.length; i += 1) {+ const arg = argv[i]+ if (arg === '--') { rest.push(...argv.slice(i + 1)); break }+ if (arg.startsWith('--')) {+ const [key, inline] = arg.slice(2).split('=')+ const next = argv[i + 1]+ if (inline !== undefined) flags[key] = inline+ else if (next && !next.startsWith('--')) { flags[key] = next; i += 1 }+ else flags[key] = true+ } else rest.push(arg)+ }+ return { flags, rest }+}++const out = (value) => process.stdout.write(`${value}\n`)+const die = (message, code = 1) => { process.stderr.write(`${message}\n`); process.exit(code) }++function filterRows(rows, flags, hideMs = Infinity) {+ let list = rows+ // Below the fold by default: no pane left, or nobody has touched it since `hideAfterIdle`. Both are+ // still one `--all` away — a list that hides things for good is a list people stop trusting.+ if (!flags.all) list = list.filter((row) => row.state !== 'gone' && row.idleMs < hideMs)+ if (flags.state) list = list.filter((row) => row.state === flags.state)+ if (flags.project) list = list.filter((row) => row.project.toLowerCase().includes(String(flags.project).toLowerCase()))+ if (flags.engine) list = list.filter((row) => row.engine === flags.engine)+ if (flags.machine) list = list.filter((row) => row.machine.toLowerCase().includes(String(flags.machine).toLowerCase()))+ if (flags.idle) { const min = parseDuration(flags.idle); list = list.filter((row) => row.idleMs >= min) }+ const sort = flags.sort ?? 'idle'+ const by = {+ idle: (a, b) => a.idleMs - b.idleMs,+ mem: (a, b) => (b.rssBytes || 0) - (a.rssBytes || 0),+ name: (a, b) => a.name.localeCompare(b.name),+ project: (a, b) => a.project.localeCompare(b.project) || a.idleMs - b.idleMs,+ }[sort]+ if (!by) die(`Sort by idle, mem, name or project — not ${sort}.`)+ list = [...list].sort(by)+ if (flags.limit) list = list.slice(0, Math.max(1, Number(flags.limit) || 1))+ return list+}++/** One read of the world: state file, fleet, policy, plan. Every command starts here so that what it+ * prints and what it would do can never come from two different snapshots. */+async function world({ includeRemote = false } = {}) {+ const state = await readState(WORKSPACE)+ const policy = normalizePolicy(state.policy, { home: homedir() })+ const { rows, problems, machines, degraded } = await collect({ state, includeRemote })+ const plan = decide(rows, policy, { home: homedir() })+ return { state, policy, rows, problems, machines, degraded, plan, summary: summarize(rows) }+}++async function commit(state, entries) {+ await writeState(WORKSPACE, state)+ for (const entry of entries) await record(WORKSPACE, entry)+}++/** Resolve every ref a command was given, reporting the ones that matched nothing rather than guessing. */+function pick(refs, rows) {+ const picked = []; const errors = []+ for (const ref of refs) {+ const { row, error } = resolveRef(ref, rows)+ if (error) errors.push(error); else if (!picked.some((existing) => existing.id === row.id)) picked.push(row)+ }+ return { picked, errors }+}++// `park`/`wake` stay as aliases: muscle memory is real and an alias costs nothing.+// `park`/`wake` and `hibernate` stay as aliases: an alias costs nothing, and muscle memory is real.+// `stop` is deliberately NOT an alias: `harness stop` already means "stop the daemon", and teaching the+// wrong habit here would collide the day these verbs move into the real CLI.+const ALIASES = { park: 'pause', wake: 'resume', revive: 'resume', unpause: 'resume', hibernate: 'pause', top: 'ls', ps: 'ls', prune: 'pause', gc: 'pause', policy: 'pause' }+// `observe` is plumbing: the workspace init script calls it to write the first verdict. Not in the help.+const COMMANDS = new Set(['ls', 'show', 'pause', 'resume', 'attach', 'observe', 'help', ...Object.keys(ALIASES)])++async function main() {+ // `hps` on its own is the list — `docker ps`, not `docker ps ls`. A leading flag is a flag, not a verb,+ // so `hps --idle 4h` works the way a person expects it to.+ const args = process.argv.slice(2)+ const typed = args.length && COMMANDS.has(args[0]) ? args.shift() : args[0]?.startsWith('-') || !args.length ? 'ls' : args.shift()+ let command = ALIASES[typed] ?? typed+ const argv = args+ const { flags, rest } = parseArgs(argv)+ // `prune`, `gc` and `policy` all arrive as `pause`; what they meant was "the whole plan".+ if (['prune', 'gc', 'policy'].includes(typed)) {+ flags.policy = true+ if (rest[0] === 'apply') { rest.shift(); flags.apply = true }+ }+ // ANY BULK SELECTION IS A DRY RUN UNTIL `--apply`. A named ref acts at once — you typed the name, so you+ // meant that one — but `--policy` and `--idle` can select forty harnesses from one line. The first+ // version of this defaulted the other way and paused thirty-five of them on a live machine; reversible+ // is not the same as asked for.+ if ((flags.policy || flags.idle || flags['over-ceiling'] || flags.paused) && !flags.apply) flags['dry-run'] = true+ if (flags.help || command === 'help' || command === '--help') { out(USAGE); return }++ if (command === 'ls' || command === 'ps') {+ const watch = flags.watch !== undefined+ const every = Math.max(1, Number(flags.watch) || Number(flags.every) || 3) * 1000+ for (;;) {+ const { rows, policy, problems, summary } = await world({ includeRemote: Boolean(flags.machines) })+ const list = filterRows(rows, flags, policy.hideAfterIdleMs)+ if (flags.json) { out(JSON.stringify({ rows: list, summary, policy: { ...policy }, problems }, null, 2)); return }+ if (watch) process.stdout.write('\u001b[2J\u001b[H')+ out(table(list, { tty: TTY, columns: COLUMNS }))+ out('')+ out(footer(summarize(list), policy, { tty: TTY, problems }))+ if (!watch) return+ await new Promise((done) => setTimeout(done, every))+ }+ }++ if (command === 'show') {+ const { rows } = await world()+ const { row, error } = resolveRef(rest[0], rows)+ if (error) die(error)+ const screen = row.local && row.pane ? await capture(row.pane, { lines: Number(flags.lines) || 12 }) : ''+ if (flags.json) { out(JSON.stringify({ ...row, screen }, null, 2)); return }+ const pairs = [+ ['name', row.name], ['title', row.title ?? '—'], ['state', row.state + (row.needsInput ? ' (looks like it is waiting on you)' : '')],+ ['idle', `${humanIdle(row.idleMs)} (last turn ${new Date(row.lastActivity).toLocaleString()})`],+ ['engine', `${row.engine}${row.model ? ` · ${row.model}${row.effort ? ` @${row.effort}` : ''}` : ''}`],+ ['folder', row.home], ['branch', row.branch ?? '—'], ['project', row.project],+ ['memory', row.rssBytes ? `${gb(row.rssBytes)} across ${row.procs} ${row.procs === 1 ? 'process' : 'processes'}` : '—'],+ ['pane', row.pane ? `${row.pane}${row.paneTarget ? ` (${row.paneTarget})` : ''}${row.dead ? ' · dead, held open' : ''}` : '—'],+ ['machine', row.machine + (row.local ? '' : ' (remote — read-only from here)')],+ ['harness', row.dshName ?? row.dsh ?? '—'], ['agent id', row.id],+ ['pinned', row.pinned ? 'yes — the policy leaves it alone' : 'no'],+ ]+ const width = Math.max(...pairs.map(([key]) => key.length))+ for (const [key, value] of pairs) out(`${key.padEnd(width)} ${value}`)+ if (screen.trim()) { out(''); out('last on its pane:'); for (const line of screen.split('\n').filter((l) => l.trim()).slice(-Number(flags.lines || 12))) out(` ${line}`) }+ return+ }++ if (['pause', 'resume'].includes(command)) {+ const { rows, policy, state, plan, summary, problems } = await world()+ let targets = []+ // `resume --paused` is the undo button: everything this ever paused, back in one line. A dry run first,+ // like every other bulk selection.+ if (command === 'resume' && flags.paused) {+ targets = rows.filter((row) => row.state === 'paused')+ } else if (flags.policy || flags.idle || flags['over-ceiling']) {+ // The rules select the rows. `--idle` is the same shape with one threshold instead of all of them.+ const chosen = flags.idle+ ? rows.filter((row) => row.state === 'running' && row.idleMs >= parseDuration(flags.idle))+ : rows.filter((row) => plan.entries.find((entry) => entry.id === row.id && entry.action === command))+ targets = chosen+ } else {+ const { picked, errors } = pick(rest, rows)+ for (const error of errors) process.stderr.write(`${error}\n`)+ if (!picked.length) die('Name a harness, or use --policy for everything the rules would touch.')+ targets = picked+ }++ // Dry run: print the plan the rules made, with the reason per row, and change nothing. This is the one+ // thing a config file cannot tell you — what it would do to the fleet as it is right now.+ if (flags['dry-run']) {+ await writeVerdict(WORKSPACE, { summary, rows, plan: plan.entries, problems })+ if (flags.json) { out(JSON.stringify({ dryRun: true, command, totals: plan.totals, plan: plan.entries.filter((e) => e.action !== 'keep') }, null, 2)); return }+ if (flags.policy) {+ out(planLines(plan.entries, { tty: TTY }))+ out('')+ out(`Would ${command} ${plan.totals.pause} — handing back ${gb(plan.totals.frees)} and leaving ${plan.totals.runningAfter} running.`)+ out(`Nothing has moved. Run \`hps ${command} --policy --apply\` to do it.`)+ } else {+ out(targets.map((row) => `${command} ${row.name} — idle ${humanIdle(row.idleMs)}, ${row.state}${row.rssBytes ? `, ${gb(row.rssBytes)}` : ''}`).join('\n') || 'Nothing matches.')+ }+ return+ }++ const options = { policy, force: Boolean(flags.force), killAfterGrace: Boolean(flags.force) }+ const results = []+ let next = state+ for (const row of targets) {+ const ticket = state.paused?.[row.id] ?? null+ const result = command === 'pause' ? await pause(row, options) : await resume(row, { ticket })+ // The ticket is written before the receipt is printed: a pause whose session id was not recorded is+ // a harness nobody can resume, which is worse than one that is still running.+ if (result.ok && result.ticket) next = markPaused(next, row, result.ticket)+ if (result.ok && command === 'resume') next = clearPaused(next, row.id)+ results.push(result)+ }+ await commit(next, results.map((result) => ({ ...result, by: flags.by ?? 'cli' })))+ if (flags.json) { out(JSON.stringify({ results }, null, 2)); return }+ for (const result of results) out(receiptLine(result, { tty: TTY }))+ const freed = results.filter((r) => r.ok && r.freed).reduce((sum, r) => sum + r.freed, 0)+ if (freed) out(`\n${gb(freed)} handed back.`)+ const refused = results.filter((r) => r.refused).length+ if (refused) out(`${refused} left alone. Add --force to overrule a guard.`)+ return+ }++ if (command === 'attach') {+ const { rows } = await world({ includeRemote: false })+ const { row, error } = resolveRef(rest[0], rows)+ if (error) die(error)+ if (!row.paneTarget) die('That harness has no pane on this machine.')+ if (flags.json) { out(JSON.stringify({ session: row.paneTarget.split(':')[0], pane: row.pane })); return }+ // Hand the terminal over, the way `docker attach` and `screen -r` do. Printing a command for someone+ // to paste is the worst of both: it is neither the answer nor the action.+ const { spawn } = await import('node:child_process')+ spawn('tmux', ['attach', '-t', row.paneTarget.split(':')[0]], { stdio: 'inherit' })+ .on('exit', (code) => process.exit(code ?? 0))+ return+ }++ if (command === 'observe') {+ const { summary, rows, plan, problems } = await world({ includeRemote: false })+ const verdict = await writeVerdict(WORKSPACE, { summary, rows, plan: plan.entries, problems })+ out(flags.json ? JSON.stringify(verdict, null, 2) : verdict.summary)+ return+ }++ die(`No such command: ${command}\n\n${USAGE}`, 2)+}++main().catch((error) => die(error instanceof Error ? error.message : String(error)))diff --git a/store/agents/harness-monitor/toolchain/init-workspace.sh b/store/agents/harness-monitor/toolchain/init-workspace.shnew file mode 100755index 000000000..ed8bb9595--- /dev/null+++ b/store/agents/harness-monitor/toolchain/init-workspace.sh@@ -0,0 +1,7 @@+#!/usr/bin/env bash+# Runs once in a fresh workspace (cwd = the workspace): write the first verdict so the pane header says+# something true before the agent's first turn.+set -euo pipefail+: "${HARNESS_DSH_DIR:?}"+mkdir -p .harness+HARNESS_WORKSPACE="$PWD" "$HARNESS_DSH_DIR/toolchain/hps" observe >/dev/null 2>&1 || truediff --git a/store/agents/harness-monitor/toolchain/runtimes.sh b/store/agents/harness-monitor/toolchain/runtimes.shnew file mode 100755index 000000000..7223c78dc--- /dev/null+++ b/store/agents/harness-monitor/toolchain/runtimes.sh@@ -0,0 +1,192 @@+# shellcheck shell=bash+# runtimes.sh — the interpreters a store package runs on, found on this machine or fetched, never+# asked of the person who pressed Get.+#+# Sourced (not run) by a package's setup, doctor and viewer scripts. A new Mac has Apple's Python 3.9,+# no Homebrew and, for most people, no Node on PATH; a package that answers "brew install [email protected]"+# has failed its install. So:+#+# harness_node 18 node >= 18 on PATH, with npm: the machine's own, else the Node Harness+# itself runs on (~/.harness/runtime/current-node, laid down with the CLI)+# harness_uv uv on PATH: the machine's own, else a pinned, checksummed release+# fetched into ~/.harness/runtime+# harness_venv DIR 3.12 [MIN [BELOW]]+# DIR is a venv on CPython 3.12, which uv downloads when the machine+# has none. A venv already there on a Python in [MIN, BELOW) is kept.+# harness_pip DIR PKG… install into that venv, through uv+# harness_micromamba micromamba, pinned and checksummed, for native libraries PyPI has+# no wheel for (pycairo on macOS)+# harness_conda_env DIR SPEC… DIR is a conda-forge environment with those packages+#+# Every function prints `miss …` and returns 1 when it cannot deliver, so `harness_node 18 || exit 1`+# reads like the rest of a setup script. Nothing here touches the user's shell profile; what it+# installs lands in ~/.harness/runtime or the package's own directory (uv keeps its download cache+# where it always does, which a venv does not depend on).+#+# ONE copy is written by hand: store/tools/runtimes.sh in the OpenHarness repository. Each package+# carries an identical copy (a package installs alone, so it cannot reach this one);+# `node store/tools/sync-runtimes.mjs` rewrites them and the CLI's store spec fails when one drifts.++HARNESS_RUNTIME="${ADAPTER_RUNTIME_DIR:-${HOME:-}/.harness/runtime}"+# The Pythons uv downloads live with Harness's other runtimes, not in uv's own ~/.local/share/uv:+# a package's venv points at its interpreter, and `uv python uninstall` there must not break it.+UV_PYTHON_INSTALL_DIR="${UV_PYTHON_INSTALL_DIR:-$HARNESS_RUNTIME/python}"+export UV_PYTHON_INSTALL_DIR+HARNESS_UV_VERSION=0.12.15+HARNESS_MICROMAMBA_VERSION=2.9.0-0++_harness_platform() {+ case "$(uname -s)-$(uname -m)" in+ Darwin-arm64) echo darwin-arm64 ;;+ Darwin-x86_64) echo darwin-x64 ;;+ Linux-x86_64) echo linux-x64 ;;+ Linux-aarch64 | Linux-arm64) echo linux-arm64 ;;+ *) return 1 ;;+ esac+}++_harness_sha256() {+ if command -v shasum >/dev/null 2>&1; then shasum -a 256 "$1" | cut -d' ' -f1+ else sha256sum "$1" | cut -d' ' -f1; fi+}++# _harness_fetch URL DEST SHA256 — DEST exists only if what arrived matches the pinned checksum.+_harness_fetch() {+ local part="$2.part.$$"+ if ! curl -fsSL --retry 3 --connect-timeout 20 --max-time 900 -o "$part" "$1"; then+ rm -f "$part"; echo "miss could not download $1 — check this machine's internet connection"; return 1+ fi+ if [ "$(_harness_sha256 "$part")" != "$3" ]; then+ rm -f "$part"; echo "miss $1 did not match its pinned checksum; nothing was installed"; return 1+ fi+ mv -f "$part" "$2"+}++_harness_node_at_least() {+ command -v node >/dev/null 2>&1 || return 1+ node -e '+ const [a, b = 0] = process.argv[1].split(".").map(Number)+ const [x, y] = process.versions.node.split(".").map(Number)+ process.exit(x > a || (x === a && y >= b) ? 0 : 1)+ ' "$1" >/dev/null 2>&1+}++harness_node() {+ local min="${1:-18}" recorded saved="$PATH" own=0+ _harness_node_at_least "$min" && own=1+ # A node without npm beside it (a distro's nodejs package) cannot run a setup's `npm ci`.+ if [ "$own" = 1 ] && command -v npm >/dev/null 2>&1; then return 0; fi+ recorded="$(cat "$HARNESS_RUNTIME/current-node" 2>/dev/null || true)"+ # Already Harness's own (a second call, or a wrapper calling a script that asks again): nothing to add.+ if [ "$own" = 1 ] && [ -n "$recorded" ] && [ "$(command -v node)" = "${recorded%/*}/node" ]; then return 0; fi+ if [ -n "$recorded" ] && [ -x "${recorded%/*}/node" ]; then+ PATH="${recorded%/*}:$PATH"; export PATH; hash -r 2>/dev/null || true+ _harness_node_at_least "$min" && return 0+ PATH="$saved"; export PATH; hash -r 2>/dev/null || true+ [ "$own" = 1 ] && return 0+ echo "miss node >= $min — this machine's newest is $("${recorded%/*}/node" -v), Harness's own; update Harness"+ return 1+ fi+ [ "$own" = 1 ] && return 0+ echo "miss node >= $min, and Harness's own Node is not in $HARNESS_RUNTIME — run \`harness start\` once to lay it down"+ return 1+}++harness_uv() {+ local dir asset sum tmp+ command -v uv >/dev/null 2>&1 && return 0+ for dir in "${HOME:-}/.local/bin" "${HOME:-}/.cargo/bin"; do+ [ -n "${HOME:-}" ] || break+ if [ -x "$dir/uv" ]; then PATH="$dir:$PATH"; export PATH; return 0; fi+ done+ dir="$HARNESS_RUNTIME/uv-$HARNESS_UV_VERSION"+ if [ ! -x "$dir/uv" ]; then+ case "$(_harness_platform)" in+ darwin-arm64) asset=uv-aarch64-apple-darwin sum=dc304b9ed1b24174572290fba60ac3f6fe63c73a671f0439e62a91375841964d ;;+ darwin-x64) asset=uv-x86_64-apple-darwin sum=e9ca61775532368fe518ab03e7a354c7ecab8ccb3c7d941c775fcc4a362b801b ;;+ linux-x64) asset=uv-x86_64-unknown-linux-gnu sum=f97935763c04be3e692460a7aaeaaab8fc3b78fcf8b389da820b38ae7423a638 ;;+ linux-arm64) asset=uv-aarch64-unknown-linux-gnu sum=0e9a3499b0587d449c9ff684c0160da607826e4af1cee220bc87f378702d3e08 ;;+ *) echo "miss uv — there is no uv release for $(uname -s) $(uname -m); install it from https://docs.astral.sh/uv/"; return 1 ;;+ esac+ echo " fetching uv $HARNESS_UV_VERSION into $HARNESS_RUNTIME (it brings Python and the packages)"+ mkdir -p "$HARNESS_RUNTIME" || { echo "miss cannot write $HARNESS_RUNTIME"; return 1; }+ tmp="$(mktemp -d "$HARNESS_RUNTIME/.uv.XXXXXX")" || { echo "miss cannot write $HARNESS_RUNTIME"; return 1; }+ if ! _harness_fetch "https://github.com/astral-sh/uv/releases/download/$HARNESS_UV_VERSION/$asset.tar.gz" "$tmp/uv.tar.gz" "$sum"; then+ rm -rf "$tmp"; return 1+ fi+ tar -xzf "$tmp/uv.tar.gz" -C "$tmp" && chmod +x "$tmp/$asset/uv" "$tmp/$asset/uvx" \+ || { rm -rf "$tmp"; echo "miss the uv archive would not unpack"; return 1; }+ # Two installs at once both get here; whichever renames first wins and the other's copy goes.+ # (mv onto a directory that exists would nest the copy inside it, hence the test.)+ [ -e "$dir" ] || mv "$tmp/$asset" "$dir" 2>/dev/null || true+ rm -rf "$tmp"+ [ -x "$dir/uv" ] || { echo "miss uv did not land in $dir"; return 1; }+ fi+ PATH="$dir:$PATH"; export PATH+}++# harness_venv DIR VERSION [MIN [BELOW]] — MIN defaults to VERSION; BELOW is exclusive and optional.+harness_venv() {+ local dir="${1:?harness_venv needs a directory}" want="${2:?harness_venv needs a Python version}"+ local min="${3:-$2}" below="${4:-}"+ if [ -x "$dir/bin/python" ] && "$dir/bin/python" -c '+import sys+at = lambda s: tuple(int(p) for p in s.split("."))+v = sys.version_info[:2]+sys.exit(0 if v >= at(sys.argv[1]) and (not sys.argv[2] or v < at(sys.argv[2])) else 1)+' "$min" "$below" 2>/dev/null; then+ echo "ok $("$dir/bin/python" --version) in $dir"+ return 0+ fi+ harness_uv || return 1+ echo " python $want in $dir (uv downloads it when this machine has none)"+ rm -rf "$dir"+ # only-managed: the same python-build-standalone interpreter on every machine, so a package tested+ # once is tested everywhere — not whichever Homebrew or pyenv Python happened to be first on PATH.+ uv venv --quiet --seed --python "$want" --python-preference only-managed "$dir" \+ || { echo "miss could not make a Python $want environment in $dir"; return 1; }+ echo "ok $("$dir/bin/python" --version) in $dir"+}++harness_pip() {+ local dir="${1:?harness_pip needs a venv}"+ shift+ harness_uv || return 1+ # uv's own error comes first; the miss line is last, so it is the line the store shows.+ uv pip install --quiet --python "$dir/bin/python" "$@" \+ || { echo "miss could not install $* into $dir"; return 1; }+}++harness_micromamba() {+ local dir asset sum+ dir="$HARNESS_RUNTIME/micromamba-$HARNESS_MICROMAMBA_VERSION"+ if [ ! -x "$dir/micromamba" ]; then+ case "$(_harness_platform)" in+ darwin-arm64) asset=micromamba-osx-arm64 sum=ec2a072f028e1a7cf20f3e2e74d5a8127cf5a5f27636375b5359811565f4e5be ;;+ darwin-x64) asset=micromamba-osx-64 sum=1e71054bb3ac9a076e21f7ec48acfef536f9b3f1408f371a942784bf5ef83d8a ;;+ linux-x64) asset=micromamba-linux-64 sum=366cd9cd8be14df1ab8ed50352a82111082a36686b2d389fdb79a92c3fafb3e3 ;;+ linux-arm64) asset=micromamba-linux-aarch64 sum=9f93b974adcb4d166996af969b6cd371287d1a3e52733704727884d9b74cb7a7 ;;+ *) echo "miss micromamba — there is no release for $(uname -s) $(uname -m)"; return 1 ;;+ esac+ echo " fetching micromamba $HARNESS_MICROMAMBA_VERSION into $HARNESS_RUNTIME (native libraries PyPI has no wheel for)"+ mkdir -p "$dir" || { echo "miss cannot write $dir"; return 1; }+ _harness_fetch "https://github.com/mamba-org/micromamba-releases/releases/download/$HARNESS_MICROMAMBA_VERSION/$asset" "$dir/micromamba.$$" "$sum" || return 1+ chmod +x "$dir/micromamba.$$" && mv -f "$dir/micromamba.$$" "$dir/micromamba" \+ || { rm -f "$dir/micromamba.$$"; echo "miss micromamba would not install into $dir"; return 1; }+ fi+ HARNESS_MICROMAMBA="$dir/micromamba"+ export HARNESS_MICROMAMBA+}++# harness_conda_env DIR SPEC… — conda-forge only, packages cached under ~/.harness/runtime/mamba.+harness_conda_env() {+ local dir="${1:?harness_conda_env needs a directory}"+ shift+ # micromamba takes a relative --prefix as a name under its root prefix and "succeeds" there.+ case "$dir" in /*) ;; *) dir="$PWD/$dir" ;; esac+ harness_micromamba || return 1+ MAMBA_ROOT_PREFIX="$HARNESS_RUNTIME/mamba" "$HARNESS_MICROMAMBA" create --yes --quiet \+ --prefix "$dir" --override-channels --channel conda-forge "$@" >/dev/null \+ && [ -d "$dir/conda-meta" ] \+ || { echo "miss could not make the conda-forge environment in $dir ($*)"; return 1; }+}diff --git a/store/agents/harness-monitor/toolchain/setup.sh b/store/agents/harness-monitor/toolchain/setup.shnew file mode 100755index 000000000..5a5a84809--- /dev/null+++ b/store/agents/harness-monitor/toolchain/setup.sh@@ -0,0 +1,13 @@+#!/usr/bin/env bash+# Runs once at install, cwd = the install dir. Harness Monitor installs nothing: it reads the daemon Harness+# already runs, the tmux server it already uses, and the process table. All this needs is a Node.+set -euo pipefail+cd "$(dirname "$0")/.."+# shellcheck source=runtimes.sh+. toolchain/runtimes.sh+harness_node 22 || exit 1+echo "ok node $(node --version) (the hps CLI and the pane)"+if command -v tmux >/dev/null 2>&1; then echo "ok tmux $(tmux -V | awk '{print $2}') (where every harness lives)"+else echo "warn tmux is not on PATH — Harness Monitor can list the fleet but not pause anything"; fi+if command -v harness >/dev/null 2>&1; then echo "ok harness CLI on PATH (the local bridge to the daemon)"+else echo "warn the harness CLI is not on PATH — Harness Monitor will read the registry file instead, without models or branches"; fidiff --git a/store/agents/harness-monitor/viewer.mjs b/store/agents/harness-monitor/viewer.mjsnew file mode 100644index 000000000..d6201c778--- /dev/null+++ b/store/agents/harness-monitor/viewer.mjs@@ -0,0 +1,243 @@+/**+ * The pane beside the terminal: the fleet, live, and the four reversible verbs.+ *+ * A loopback server and nothing else — it binds 127.0.0.1, refuses a request whose Host or Origin is not+ * its own, and serves three static files with a self-only CSP. What it adds over the other store viewers+ * is a narrow write surface, because a fleet manager you can only read is a fleet manager nobody uses:+ *+ * POST /api/act pause · resume · retire · pin · unpin — every one of them reversible+ * POST /api/policy the thresholds, validated before they are written+ *+ * Both require the token this process mints at boot and hands to its own page; a page from anywhere else+ * does not have it. What is deliberately NOT here: deleting an agent, killing a tmux session, touching a+ * transcript. Those are irreversible, they already exist in the app behind their own confirmation, and a+ * pane full of eighty rows is the last place they belong.+ */++import { randomBytes } from 'node:crypto'+import { createServer } from 'node:http'+import { readFile } from 'node:fs/promises'+import { homedir } from 'node:os'+import { dirname, join, resolve } from 'node:path'+import { fileURLToPath, pathToFileURL } from 'node:url'+import { pause, resume } from './lib/actions.mjs'+import { collect as collectFleet, summarize, tilde } from './lib/inventory.mjs'+import { capture, looksBlocked } from './lib/panes.mjs'+import { DEFAULT_POLICY, decide, normalizePolicy } from './lib/policy.mjs'+import { clearPaused, markPaused, pin, readLog, readState, record, savePolicyValues, writeState, writeVerdict } from './lib/state.mjs'++const PACKAGE = dirname(fileURLToPath(import.meta.url))+const VERBS = new Set(['pause', 'resume', 'pin', 'unpin'])++/** Panes to read per refresh when looking for an open prompt. Bounded because each one is a tmux call+ * and a fleet of eighty must cost the same as a fleet of eight: the candidates are the rows the policy+ * is about to act on, which are the only rows where the answer changes anything. */+const BLOCKED_SCAN_LIMIT = 24++export function createViewer({ workspace, port = 0, intervalMs = 4000, now = () => Date.now(), collect = collectFleet, scan = capture, verbs = { pause, resume } }) {+ const token = randomBytes(24).toString('base64url')+ const clients = new Set()+ const cache = new Map()+ let snapshot = { spec: 1, status: 'starting', rows: [], summary: null, policy: DEFAULT_POLICY, plan: [], totals: null, problems: [], log: [], observedAt: null, intervalMs }+ let stopped = false, timer, heartbeat, polling = null+ // Resolves after the first observation lands. The server starts listening before it, so the pane draws+ // its shell immediately; anything that needs the first real snapshot (a test, a caller) awaits this.+ let observed+ const firstObservation = new Promise((resolve) => { observed = resolve })++ const headers = { 'cache-control': 'no-store', 'x-content-type-options': 'nosniff', 'referrer-policy': 'no-referrer' }+ const json = (res, code, value) => { res.writeHead(code, { ...headers, 'content-type': 'application/json; charset=utf-8' }); res.end(JSON.stringify(value)) }++ const publish = () => {+ const body = `event: snapshot\ndata: ${JSON.stringify(snapshot)}\n\n`+ for (const client of clients) {+ if (client.writableLength > 512 * 1024) { client.destroy(); clients.delete(client) }+ else client.write(body)+ }+ }++ /** One observation: the fleet, what the policy would do to it, and the pane header's verdict. */+ async function observe() {+ const state = await readState(workspace).catch(() => null)+ if (!state) {+ snapshot = { ...snapshot, status: 'unreadable', problems: [{ machine: 'monitor.json', error: 'The policy file could not be read. Ask the agent to check monitor.json.' }] }+ return+ }+ const policy = normalizePolicy(state.policy, { home: homedir() })+ const { rows, problems, degraded } = await collect({ state, now: now(), includeRemote: true, cache })++ // Look for an open prompt only where it would change a decision, newest candidates first.+ const candidates = rows+ .filter((row) => row.local && row.state === 'running' && row.pane && row.idleMs >= policy.pauseAfterIdleMs / 2)+ .slice(0, BLOCKED_SCAN_LIMIT)+ await Promise.all(candidates.map(async (row) => {+ const screen = await scan(row.pane, { lines: 30 })+ row.needsInput = looksBlocked(screen)+ row.screenTail = screen.split('\n').filter((line) => line.trim()).slice(-3).join('\n').slice(0, 600)+ }))++ const plan = decide(rows, policy, { home: homedir(), now: now() })+ const summary = summarize(rows)+ snapshot = {+ spec: 1,+ status: degraded ? 'degraded' : 'ok',+ rows,+ summary,+ policy: { ...policy },+ defaults: DEFAULT_POLICY,+ plan: plan.entries,+ totals: plan.totals,+ problems,+ pins: state.pins,+ configPath: tilde(state.configPath, homedir()),+ log: await readLog(workspace, { limit: 30 }),+ observedAt: now(),+ intervalMs,+ }+ await writeVerdict(workspace, { summary, rows, plan: plan.entries, problems }).catch(() => {})+ }++ async function poll({ immediate = false } = {}) {+ if (polling) return polling+ polling = (async () => {+ try { await observe() } catch (error) {+ snapshot = { ...snapshot, status: 'unavailable', problems: [{ machine: 'this machine', error: error instanceof Error ? error.message : String(error) }] }+ }+ if (!stopped) publish()+ observed()+ })()+ try { await polling } finally { polling = null }+ if (!stopped && !immediate) { clearTimeout(timer); timer = setTimeout(poll, intervalMs) }+ }++ /** The write surface. One verb, up to 64 rows, and a receipt per row — the same library call the CLI+ * makes, so a click and a typed command cannot behave differently. */+ async function act({ verb, ids }) {+ if (!VERBS.has(verb)) return { error: `Not a verb Harness Monitor has: ${verb}` }+ const targets = (Array.isArray(ids) ? ids : []).filter((id) => typeof id === 'string').slice(0, 64)+ if (!targets.length) return { error: 'Name at least one harness.' }+ const state = await readState(workspace)+ const policy = normalizePolicy(state.policy, { home: homedir() })+ const rows = snapshot.rows.filter((row) => targets.includes(row.id))+ if (!rows.length) return { error: 'Those harnesses are not in the current view. Refresh and try again.' }++ let next = state+ const results = []+ for (const row of rows) {+ if (verb === 'pin' || verb === 'unpin') {+ next = pin(next, row.id, verb === 'pin')+ results.push({ ok: true, action: verb, id: row.id, name: row.name, detail: verb === 'pin' ? 'never paused by the policy' : 'the policy may pause it again' })+ continue+ }+ const ticket = state.paused?.[row.id] ?? null+ const result = verb === 'pause' ? await verbs.pause(row, { policy }) : await verbs.resume(row, { ticket })+ if (result.ok && result.ticket) next = markPaused(next, row, result.ticket)+ if (result.ok && verb === 'resume') next = clearPaused(next, row.id)+ results.push(result)+ }+ await writeState(workspace, next)+ for (const result of results) await record(workspace, { ...result, by: 'pane' })+ await poll({ immediate: true })+ return { results }+ }++ async function savePolicy(raw) {+ // Only the keys the pane can change, and only valid values: the file is a person's, and the pane is a+ // guest in it. Everything else in it — comments included — is left exactly as it was.+ const allowed = ['pauseAfterIdle', 'hideAfterIdle', 'runningCeiling']+ const values = Object.fromEntries(Object.entries(raw ?? {}).filter(([key]) => allowed.includes(key)))+ const state = await readState(workspace)+ let policy+ try { policy = normalizePolicy({ ...state.policy, ...values }, { home: homedir() }) } catch (error) { return { error: error.message } }+ const path = await savePolicyValues(values)+ await record(workspace, { action: 'policy', ok: true, detail: JSON.stringify(values), by: 'pane' })+ await poll({ immediate: true })+ return { policy: { ...policy }, path }+ }++ const server = createServer(async (req, res) => {+ try {+ const address = server.address()+ const hosts = new Set([`127.0.0.1:${address?.port}`, `localhost:${address?.port}`, `[::1]:${address?.port}`])+ if (!hosts.has(req.headers.host)) { json(res, 403, { error: 'Loopback requests only.' }); return }+ const url = new URL(req.url, `http://${req.headers.host}`)+ if (req.headers.origin && req.headers.origin !== url.origin) { json(res, 403, { error: 'Cross-origin requests are not allowed.' }); return }++ if (req.method === 'POST') {+ if (req.headers['x-hps-token'] !== token) { json(res, 403, { error: 'This pane did not mint that token.' }); return }+ let body = ''+ for await (const chunk of req) { body += chunk; if (body.length > 64 * 1024) { json(res, 413, { error: 'Too large.' }); return } }+ let payload; try { payload = JSON.parse(body || '{}') } catch { json(res, 400, { error: 'Send JSON.' }); return }+ if (url.pathname === '/api/act') { json(res, 200, await act(payload)); return }+ if (url.pathname === '/api/policy') { json(res, 200, await savePolicy(payload.policy ?? {})); return }+ if (url.pathname === '/api/refresh') { await poll({ immediate: true }); json(res, 200, { ok: true }); return }+ json(res, 404, { error: 'Not found' }); return+ }++ if (!['GET', 'HEAD'].includes(req.method)) { res.setHeader('allow', 'GET, HEAD, POST'); json(res, 405, { error: 'Not allowed.' }); return }+ if (url.pathname === '/health') { json(res, 200, { ok: true }); return }+ if (url.pathname === '/api/snapshot') { json(res, 200, snapshot); return }+ if (url.pathname === '/events') {+ if (req.method === 'HEAD') { res.writeHead(200, headers); res.end(); return }+ if (clients.size >= 16) { json(res, 503, { error: 'Too many viewer connections.' }); return }+ res.writeHead(200, { ...headers, 'content-type': 'text/event-stream', connection: 'keep-alive', 'x-accel-buffering': 'no' })+ res.write(`event: snapshot\ndata: ${JSON.stringify(snapshot)}\n\n`)+ clients.add(res); res.on('close', () => clients.delete(res)); return+ }++ const assets = {+ '/': ['index.html', 'text/html; charset=utf-8'],+ '/app.js': ['app.js', 'text/javascript; charset=utf-8'],+ '/app.css': ['app.css', 'text/css; charset=utf-8'],+ '/scale.js': ['scale.js', 'text/javascript; charset=utf-8'],+ }+ if (!assets[url.pathname]) { json(res, 404, { error: 'Not found' }); return }+ const [file, contentType] = assets[url.pathname]+ let content = await readFile(join(PACKAGE, 'viewer', file), 'utf8')+ // The page is served the token in a meta tag rather than a cookie or an inline script: no script+ // source changes, so the CSP stays script-src 'self' with no nonce and no 'unsafe-inline'.+ if (file === 'index.html') content = content.replace('__HPS_TOKEN__', token)+ res.writeHead(200, {+ ...headers,+ 'content-type': contentType,+ 'content-security-policy': "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; connect-src 'self'; img-src 'self' data:; object-src 'none'; base-uri 'none'; form-action 'none'",+ })+ res.end(req.method === 'HEAD' ? undefined : content)+ } catch {+ if (!res.headersSent) json(res, 500, { error: 'The viewer could not serve this request.' }); else res.end()+ }+ })++ return {+ server,+ token,+ observed: firstObservation,+ snapshot: () => snapshot,+ act,+ start: () => new Promise((ok, fail) => {+ server.once('error', fail)+ server.listen(port, '127.0.0.1', () => {+ server.removeListener('error', fail)+ poll()+ heartbeat = setInterval(() => { for (const client of clients) client.write(': pulse\n\n') }, 20_000)+ ok(server.address().port)+ })+ }),+ close: async () => {+ stopped = true; clearTimeout(timer); clearInterval(heartbeat)+ for (const client of clients) client.end()+ server.closeAllConnections()+ await new Promise((done) => server.close(done))+ },+ }+}++if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) {+ const workspace = resolve(process.env.HARNESS_WORKSPACE || process.cwd())+ const port = Number(process.env.HARNESS_VIEWER_PORT || 0)+ if (!Number.isInteger(port) || port < 0 || port > 65535) throw new Error('HARNESS_VIEWER_PORT must be a port number.')+ const viewer = createViewer({ workspace, port })+ console.log(`[hps] http://127.0.0.1:${await viewer.start()}/`)+ const close = () => viewer.close().then(() => process.exit(0))+ process.once('SIGINT', close); process.once('SIGTERM', close)+}diff --git a/store/agents/harness-monitor/viewer.sh b/store/agents/harness-monitor/viewer.shnew file mode 100755index 000000000..e9a5146c0--- /dev/null+++ b/store/agents/harness-monitor/viewer.sh@@ -0,0 +1,6 @@+#!/usr/bin/env bash+set -euo pipefail+cd "$(dirname "$0")"+. toolchain/runtimes.sh+harness_node 22+exec node viewer.mjsdiff --git a/store/agents/harness-monitor/viewer/app.css b/store/agents/harness-monitor/viewer/app.cssnew file mode 100644index 000000000..17849c860--- /dev/null+++ b/store/agents/harness-monitor/viewer/app.css@@ -0,0 +1,269 @@+/* Harness Monitor's pane. Light is the default palette; dark only redefines the tokens in the block below it —+ the contract the app's other viewers use (store/agents/autonomous-grid/viewer/app.css) — so the page+ follows the appearance the app is in rather than always rendering dark. Every colour past this block+ is one of these tokens.++ The look is deliberately terminal-adjacent: hairlines instead of borders, a monospace column grid,+ one accent, and no rounded-corner-and-shadow card anywhere near the dense list. The Harness Monitor is allowed+ to breathe; the Table is not. */+:root {+ color-scheme: light;+ --bg: #ffffff;+ --panel: #f9f9f8;+ --panel-2: #f3f3f2;+ --hover: rgba(0, 0, 0, .04);+ --selected: rgba(0, 0, 0, .07);+ --line: rgba(0, 0, 0, .09);+ --line-strong: rgba(0, 0, 0, .16);+ --ink: #1a1a18;+ --ink-2: #5b5a54;+ --ink-3: #8b8a83;+ --live: #1f8a5f; /* running */+ --live-soft: rgba(31, 138, 95, .12);+ --gold: #a3711c; /* working right now */+ --gold-soft: rgba(163, 113, 28, .12);+ --amber: #b07403; /* waiting on you */+ --amber-soft: rgba(176, 116, 3, .14);+ --red: #b8402f;+ --shadow: 0 8px 24px rgba(0, 0, 0, .10), 0 1px 3px rgba(0, 0, 0, .06);+ --mono: ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, monospace;+ --sans: -apple-system, BlinkMacSystemFont, "Segoe UI", Inter, system-ui, sans-serif;+ --lane-h: 34px;+}+@media (prefers-color-scheme: dark) {+ :root:not([data-theme="light"]) {+ color-scheme: dark;+ --bg: #131312; --panel: #1a1a19; --panel-2: #212120;+ --hover: rgba(255, 255, 255, .05); --selected: rgba(255, 255, 255, .09);+ --line: rgba(255, 255, 255, .10); --line-strong: rgba(255, 255, 255, .20);+ --ink: #f2f1ee; --ink-2: #a8a6a0; --ink-3: #78766f;+ --live: #4ec38a; --live-soft: rgba(78, 195, 138, .14);+ --gold: #d6a344; --gold-soft: rgba(214, 163, 68, .16);+ --amber: #e0a33a; --amber-soft: rgba(224, 163, 58, .18);+ --red: #e4705c;+ --shadow: 0 10px 30px rgba(0, 0, 0, .5), 0 1px 3px rgba(0, 0, 0, .4);+ }+}+:root[data-theme="dark"] {+ color-scheme: dark;+ --bg: #131312; --panel: #1a1a19; --panel-2: #212120;+ --hover: rgba(255, 255, 255, .05); --selected: rgba(255, 255, 255, .09);+ --line: rgba(255, 255, 255, .10); --line-strong: rgba(255, 255, 255, .20);+ --ink: #f2f1ee; --ink-2: #a8a6a0; --ink-3: #78766f;+ --live: #4ec38a; --live-soft: rgba(78, 195, 138, .14);+ --gold: #d6a344; --gold-soft: rgba(214, 163, 68, .16);+ --amber: #e0a33a; --amber-soft: rgba(224, 163, 58, .18);+ --red: #e4705c;+}++* { box-sizing: border-box; }+html, body { height: 100%; }+body {+ margin: 0; background: var(--bg); color: var(--ink);+ font: 13px/1.45 var(--sans); -webkit-font-smoothing: antialiased;+}+#app { display: flex; flex-direction: column; height: 100vh; overflow: hidden; }+.mono { font-family: var(--mono); font-variant-numeric: tabular-nums; }+button { font: inherit; color: inherit; background: none; border: 0; cursor: pointer; }+button:focus-visible, [tabindex]:focus-visible, input:focus-visible { outline: 2px solid var(--gold); outline-offset: 1px; }++/* ── the bar ─────────────────────────────────────────────────────────────── */+.bar {+ display: flex; align-items: center; gap: 14px; flex-wrap: wrap;+ padding: 8px 12px; border-bottom: 1px solid var(--line); background: var(--panel);+}+.identity { display: flex; align-items: baseline; gap: 8px; }+.identity h1 { margin: 0; font-size: 13px; font-weight: 650; letter-spacing: .02em; }+.mark { width: 9px; height: 9px; border-radius: 2px; background: var(--live); box-shadow: 0 0 0 3px var(--live-soft); }+.where { color: var(--ink-3); font-size: 11px; }+.gauges { display: flex; gap: 6px; flex: 1 1 auto; flex-wrap: wrap; }+.gauge {+ display: inline-flex; align-items: baseline; gap: 5px; padding: 2px 8px;+ border: 1px solid var(--line); border-radius: 999px; background: var(--bg);+ font-family: var(--mono); font-size: 11px; color: var(--ink-2); white-space: nowrap;+}+.gauge b { color: var(--ink); font-weight: 600; font-variant-numeric: tabular-nums; }+.gauge.live b { color: var(--live); }+.gauge.attention { border-color: var(--amber); background: var(--amber-soft); }+.gauge.attention b { color: var(--amber); }+.tools { display: flex; align-items: center; gap: 8px; }+.segmented { display: inline-flex; padding: 2px; gap: 2px; background: var(--panel-2); border-radius: 7px; }+.segmented button { padding: 3px 11px; border-radius: 5px; font-size: 12px; color: var(--ink-2); }+.segmented button[aria-selected="true"] { background: var(--bg); color: var(--ink); box-shadow: 0 1px 2px rgba(0, 0, 0, .10); }+.filter { display: flex; align-items: center; gap: 5px; padding: 2px 8px; border: 1px solid var(--line); border-radius: 6px; background: var(--bg); }+.filter span { color: var(--ink-3); font-family: var(--mono); }+.filter input { width: 190px; border: 0; background: none; color: inherit; font: 12px var(--sans); }+.filter input::-webkit-search-cancel-button { display: none; }+.ghost { padding: 3px 7px; border-radius: 6px; color: var(--ink-2); }+.ghost:hover { background: var(--hover); color: var(--ink); }+.primary { padding: 4px 12px; border-radius: 6px; background: var(--ink); color: var(--bg); font-size: 12px; font-weight: 550; }+.primary:hover { opacity: .88; }++.view { flex: 1 1 auto; min-height: 0; display: flex; flex-direction: column; }+[hidden] { display: none !important; }++/* ── Lanes: the picture ───────────────────────────────────────────────────── */+/* One lane per project, oldest work on the left, "now" hard against the right edge. The two policy+ rules are drawn as vertical lines you can drag: the fleet's geography IS the policy, which is the+ only way to judge a threshold without running it. */+.lanes-head { display: grid; grid-template-columns: var(--label-w, 150px) 1fr; align-items: end; gap: 10px; padding: 7px 12px 0; }+.axis-label, .lane-label { font: 10px/1 var(--mono); letter-spacing: .08em; color: var(--ink-3); text-transform: uppercase; }+.axis { position: relative; height: 22px; border-bottom: 1px solid var(--line); }+.axis .tick { position: absolute; bottom: 0; transform: translateX(-50%); font: 10px var(--mono); color: var(--ink-3); white-space: nowrap; }+.axis .tick::after { content: ""; position: absolute; left: 50%; bottom: -1px; width: 1px; height: 4px; background: var(--line-strong); }+.rule { position: absolute; top: -2px; bottom: -8px; width: 11px; margin-left: -5px; cursor: ew-resize; z-index: 4; }+.rule-grip { position: absolute; inset: 0 4px; background: var(--ink-3); border-radius: 1px; }+.rule[data-rule="pause"] .rule-grip { background: var(--gold); }+.rule[data-rule="hide"] .rule-grip { background: var(--ink-3); }+.rule-tag {+ position: absolute; top: -4px; left: 9px; padding: 1px 5px; border-radius: 3px;+ font: 9px/1.5 var(--mono); letter-spacing: .05em; text-transform: uppercase; white-space: nowrap;+ background: var(--panel-2); color: var(--ink-2); border: 1px solid var(--line);+}+.rule:hover .rule-tag, .rule.dragging .rule-tag { color: var(--ink); border-color: var(--line-strong); }++.lanes { position: relative; flex: 1 1 auto; overflow-y: auto; padding: 4px 12px 14px; }+/* The rules continue down through every lane, drawn once behind them all. */+.lanes::before, .lanes::after {+ content: ""; position: absolute; top: 0; bottom: 0; width: 1px; pointer-events: none; z-index: 1;+ left: calc(var(--label-w, 150px) + 10px + var(--x) * (100% - var(--label-w, 150px) - 10px - 24px));+}+.lanes::before { --x: var(--pause-x, .5); background: linear-gradient(to bottom, var(--gold), transparent 88%); opacity: .55; }+.lanes::after { --x: var(--hide-x, .15); background: linear-gradient(to bottom, var(--red), transparent 88%); opacity: .45; }++.lane { display: grid; grid-template-columns: var(--label-w, 150px) 1fr; gap: 10px; align-items: start; }+.lane + .lane { border-top: 1px dashed var(--line); }+.lane-label {+ padding: 11px 0 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;+ text-transform: none; font-size: 11px; color: var(--ink-2); letter-spacing: 0;+}+.lane-label b { color: var(--ink); font-weight: 550; }+.lane-label i { color: var(--ink-3); font-style: normal; }+.track { position: relative; min-height: var(--lane-h); padding: 5px 0; }++.chip {+ position: absolute; display: inline-flex; align-items: center; gap: 6px; max-width: 220px;+ padding: 3px 8px 3px 6px; border: 1px solid var(--line-strong); border-radius: 5px;+ background: var(--bg); color: var(--ink-2); cursor: pointer; z-index: 2;+ font-size: 11px; white-space: nowrap; transition: transform .1s ease, border-color .1s ease;+}+.chip:hover { transform: translateY(-1px); border-color: var(--ink-3); color: var(--ink); z-index: 3; }+.chip .dot { width: 6px; height: 6px; border-radius: 50%; background: var(--ink-3); flex: none; }+.chip .what { overflow: hidden; text-overflow: ellipsis; }+.chip .mem { font-family: var(--mono); font-size: 10px; color: var(--ink-3); }+.chip[data-state="running"] { background: var(--live-soft); border-color: var(--live); color: var(--ink); }+.chip[data-state="running"] .dot { background: var(--live); }+.chip[data-working="true"] { background: var(--gold-soft); border-color: var(--gold); }+.chip[data-working="true"] .dot { background: var(--gold); animation: breathe 2.4s ease-in-out infinite; }+.chip[data-state="paused"] { border-style: dashed; background: transparent; }+.chip[data-state="retired"] { border-style: dotted; background: transparent; color: var(--ink-3); }+.chip[data-state="terminal"] { border-style: solid; border-color: var(--line); background: transparent; color: var(--ink-3); }+.chip[data-state="gone"] { border-style: dotted; opacity: .5; text-decoration: line-through; }+.chip[data-attention="true"] { border-color: var(--amber); background: var(--amber-soft); box-shadow: 0 0 0 3px var(--amber-soft); }+.chip[data-attention="true"] .dot { background: var(--amber); }+.chip[data-selected="true"] { outline: 2px solid var(--ink); outline-offset: 1px; }+.chip[data-doomed="true"] { opacity: .62; }+.chip[data-doomed="true"] .what { text-decoration: line-through solid var(--ink-3) 1px; }+.chip .pin { color: var(--gold); font-size: 9px; }+@keyframes breathe { 0%, 100% { opacity: 1; } 50% { opacity: .35; } }+@media (prefers-reduced-motion: reduce) { .chip .dot { animation: none !important; } }++.lanes-empty { margin: auto; text-align: center; color: var(--ink-2); padding: 40px; }+.lanes-empty .big { font-size: 15px; color: var(--ink); margin: 0 0 6px; }++/* ── the table ───────────────────────────────────────────────────────────── */+/* htop's density, and htop's rules: fixed columns, tabular numerals, one line per thing, no wrapping,+ colour only where it carries a state that the glyph also carries. */+.grid { flex: 1 1 auto; overflow: auto; font-family: var(--mono); font-size: 12px; }+.grid table { width: 100%; border-collapse: collapse; }+.grid thead th {+ position: sticky; top: 0; z-index: 2; background: var(--panel); border-bottom: 1px solid var(--line);+ padding: 5px 8px; text-align: left; font: 10px/1.6 var(--mono); letter-spacing: .08em;+ color: var(--ink-3); text-transform: uppercase; cursor: pointer; white-space: nowrap; user-select: none;+}+.grid thead th:hover { color: var(--ink); }+.grid thead th[aria-sort] { color: var(--ink); }+.grid thead th[aria-sort]::after { content: " ↓"; }+.grid thead th[aria-sort="ascending"]::after { content: " ↑"; }+.grid td { padding: 3px 8px; border-bottom: 1px solid var(--line); white-space: nowrap; }+.grid tbody tr { cursor: pointer; }+.grid tbody tr:hover td { background: var(--hover); }+.grid tbody tr[data-selected="true"] td { background: var(--selected); }+.grid tbody tr[data-cursor="true"] td { box-shadow: inset 0 0 0 1px var(--line-strong); }+.grid tbody tr[data-doomed="true"] .c-title { color: var(--ink-3); }+.c-num { color: var(--ink-3); text-align: right; }+.c-state { width: 1.6em; }+.c-idle, .c-mem { text-align: right; }+.c-title, .c-project { max-width: 34ch; overflow: hidden; text-overflow: ellipsis; }+.c-dim { color: var(--ink-3); }+/* The verb sits on the row and stays out of the way until the pointer is near it. It is in the DOM at all+ times, so keyboard focus finds it even when it is not painted. */+.c-do { width: 5.5em; text-align: right; }+.c-do button {+ padding: 1px 7px; border: 1px solid var(--line-strong); border-radius: 4px;+ font: 10.5px var(--mono); color: var(--ink-2); opacity: 0;+}+.grid tbody tr:hover .c-do button, .grid tbody tr[data-cursor="true"] .c-do button,+.c-do button:focus-visible { opacity: 1; }+.c-do button:hover { background: var(--hover); color: var(--ink); border-color: var(--ink-3); }+.toggle[aria-pressed="true"] { background: var(--selected); color: var(--ink); }+.st-running { color: var(--live); }+.st-working { color: var(--gold); }+.st-attention { color: var(--amber); }+.st-paused, .st-retired, .st-gone, .st-terminal { color: var(--ink-3); }+/* Memory as a bar behind the number: the one place this table spends a pixel on drawing, because "what+ would I get back" is the question the column exists to answer. */+.membar { position: relative; }+.membar i { position: absolute; right: 8px; top: 3px; bottom: 3px; background: var(--gold-soft); border-radius: 1px; }+.membar span { position: relative; }++/* ── status bar, policy bar, inspector, toast ────────────────────────────── */+.statusbar {+ display: flex; align-items: center; gap: 12px; padding: 5px 12px;+ border-top: 1px solid var(--line); background: var(--panel); font-size: 11px; color: var(--ink-2);+}+.statusbar .keys { margin-left: auto; color: var(--ink-3); font-size: 10.5px; }+.statusbar code { font: 10.5px var(--mono); color: var(--ink-2); user-select: all; }+.statusbar kbd {+ font: 10px var(--mono); padding: 1px 4px; border: 1px solid var(--line); border-radius: 3px;+ background: var(--bg); color: var(--ink-2);+}+.actions { display: flex; gap: 6px; align-items: center; }+.actions button { padding: 2px 9px; border: 1px solid var(--line-strong); border-radius: 5px; font-size: 11px; }+.actions button:hover { background: var(--hover); }+.actions .danger { color: var(--red); border-color: var(--red); }+.policybar {+ display: flex; align-items: center; gap: 10px; padding: 7px 12px;+ border-top: 1px solid var(--gold); background: var(--gold-soft); font-size: 12px;+}+.policy-preview { flex: 1 1 auto; }++.inspector {+ position: absolute; right: 0; top: 0; bottom: 0; width: min(380px, 78vw); z-index: 10;+ display: flex; flex-direction: column; gap: 0; overflow: auto;+ background: var(--panel); border-left: 1px solid var(--line-strong); box-shadow: var(--shadow);+}+.inspector header { display: flex; align-items: flex-start; gap: 8px; padding: 12px 14px 8px; }+.inspector h2 { margin: 0; font-size: 13px; font-weight: 600; }+.inspector .sub { color: var(--ink-3); font-size: 11px; }+.inspector dl { margin: 0; padding: 4px 14px 12px; display: grid; grid-template-columns: 86px 1fr; gap: 4px 10px; font-size: 11.5px; }+.inspector dt { color: var(--ink-3); }+.inspector dd { margin: 0; font-family: var(--mono); overflow-wrap: anywhere; }+.inspector .screen {+ margin: 0 14px 12px; padding: 8px; border-radius: 5px; background: var(--bg); border: 1px solid var(--line);+ font: 10.5px/1.5 var(--mono); color: var(--ink-2); white-space: pre-wrap; max-height: 150px; overflow: auto;+}+.inspector .row-actions { display: flex; flex-wrap: wrap; gap: 6px; padding: 0 14px 14px; }+.inspector .why { margin: 0 14px 10px; padding: 7px 9px; border-left: 2px solid var(--gold); background: var(--gold-soft); font-size: 11.5px; }+.toast {+ position: absolute; left: 50%; bottom: 46px; transform: translateX(-50%); z-index: 20;+ max-width: 78vw; padding: 7px 13px; border-radius: 7px; background: var(--ink); color: var(--bg);+ font-size: 12px; box-shadow: var(--shadow);+}+.toast.bad { background: var(--red); color: #fff; }++@media (max-width: 720px) {+ :root { --label-w: 104px; }+ .filter input { width: 110px; }+ .gauges { order: 3; width: 100%; }+}diff --git a/store/agents/harness-monitor/viewer/app.js b/store/agents/harness-monitor/viewer/app.jsnew file mode 100644index 000000000..56604a0f6--- /dev/null+++ b/store/agents/harness-monitor/viewer/app.js@@ -0,0 +1,610 @@+/* Harness Monitor's pane.+ *+ * One snapshot from the server, two ways to read it, and six verbs. No build step, no dependencies, no+ * inline script — the page is served with `script-src 'self'`, so everything here is plain DOM and one+ * ES module import for the arithmetic (viewer/scale.js, tested in test/scale.test.mjs).+ *+ * The two views share ONE selection and ONE cursor on purpose: a fleet manager where the dense list and+ * the picture disagree about what is selected is a fleet manager that cannot be trusted with a verb.+ */+import { HIDE_STEPS, PAUSE_STEPS, UNITS, bytes, humanIdle, idleOfX, parseDuration, snap, xOf } from './scale.js'++const TOKEN = document.querySelector('meta[name="hps-token"]')?.content ?? ''++const el = (id) => document.getElementById(id)+const dom = {+ where: el('where'), gauges: el('gauges'), filter: el('filter'), refresh: el('refresh'),+ lanes: el('lanes-view'), laneList: el('lane-list'), axis: el('axis'), lanesEmpty: el('lanes-empty'),+ table: el('table'), grid: el('grid'),+ rulePause: el('rule-pause'), ruleHide: el('rule-hide'),+ showAll: el('show-all'), policybar: el('policybar'), policyPreview: el('policy-preview'), policySave: el('policy-save'), policyReset: el('policy-reset'),+ statusLeft: el('status-left'), statusActions: el('status-actions'), statusRight: el('status-right'),+ inspector: el('inspector'), toast: el('toast'),+}++const state = {+ snapshot: null,+ view: 'lanes',+ filter: '',+ showAll: false,+ selected: new Set(),+ cursor: null,+ inspecting: null,+ sort: { key: 'idle', dir: 'asc' },+ draft: null, // policy being dragged, before it is saved+ busy: false,+}++/* ── the fleet, filtered ──────────────────────────────────────────────────── */++function policy() {+ return { ...(state.snapshot?.policy ?? {}), ...(state.draft ?? {}) }+}++function rows() {+ const all = state.snapshot?.rows ?? []+ const hideMs = parseDuration(policy().hideAfterIdle ?? '14d')+ // Below the fold unless you ask: a pane that opens on 146 rows is the junk drawer this was built to fix.+ // Filtering by hand overrides it, because someone typing a name is looking for that name anywhere.+ const needle = state.filter.trim().toLowerCase()+ const visible = state.showAll || needle+ ? all+ : all.filter((row) => row.state !== 'gone' && row.idleMs < hideMs)+ if (!needle) return visible+ return visible.filter((row) => [row.name, row.title, row.project, row.engine, row.model, row.branch, row.machine, row.state]+ .some((field) => String(field ?? '').toLowerCase().includes(needle)))+}++/** What the plan says about one row, as the server computed it — unless a line is being dragged, in+ * which case the same idle rules are applied here so the picture answers while the mouse is moving. */+function verdictFor(row) {+ if (state.draft) {+ const pause = parseDuration(state.draft.pauseAfterIdle ?? policy().pauseAfterIdle)++ if (row.pinned || row.needsInput || row.working || row.attached) return null+ if (row.state === 'gone' || row.state === 'terminal') return null+ if (row.state === 'running' && row.idleMs >= pause) return 'pause'+ return null+ }+ const entry = (state.snapshot?.plan ?? []).find((candidate) => candidate.id === row.id)+ return entry && entry.action !== 'keep' ? entry.action : null+}++function planTotals(list) {+ let pause = 0, frees = 0+ for (const row of list) {+ if (verdictFor(row) !== 'pause') continue+ pause += 1+ if (row.state === 'running') frees += row.rssBytes || 0+ }+ return { pause, frees }+}++/* ── rendering ────────────────────────────────────────────────────────────── */++function renderGauges() {+ const summary = state.snapshot?.summary+ if (!summary) return+ const held = summary.held >= 1024 ** 3 ? `${(summary.held / 1024 ** 3).toFixed(1)} GB` : `${Math.round(summary.held / 1024 ** 2)} MB`+ const chips = [+ ['live', summary.running, 'running'],+ ['', summary.paused, 'paused'],+ ['', held, 'held'],+ ['', summary.projects, 'projects'],+ ]+ if (summary.needsInput) chips.unshift(['attention', summary.needsInput, 'waiting on you'])+ dom.gauges.replaceChildren(...chips.map(([kind, value, label]) => {+ const node = document.createElement('span')+ node.className = `gauge ${kind}`.trim()+ node.innerHTML = `<b></b> <span></span>`+ node.querySelector('b').textContent = value+ node.querySelector('span').textContent = label+ return node+ }))+ const machines = state.snapshot.rows.filter((row) => !row.local).length+ dom.where.textContent = machines+ ? `this machine, plus ${machines} seen elsewhere`+ : state.snapshot.status === 'degraded' ? 'read from the registry — the daemon is not answering' : 'this machine'+}++function renderAxis() {+ const ticks = [['now', 0], ['1h', UNITS.h], ['6h', 6 * UNITS.h], ['1d', UNITS.d], ['3d', 3 * UNITS.d], ['1w', UNITS.w], ['2w', 2 * UNITS.w], ['4w', 4 * UNITS.w]]+ for (const node of dom.axis.querySelectorAll('.tick')) node.remove()+ for (const [label, idle] of ticks) {+ const tick = document.createElement('span')+ tick.className = 'tick'+ tick.textContent = label+ tick.style.left = `${xOf(idle) * 100}%`+ dom.axis.append(tick)+ }+ placeRules()+}++function placeRules() {+ const current = policy()+ const pauseX = xOf(parseDuration(current.pauseAfterIdle))+ const hideX = xOf(parseDuration(current.hideAfterIdle))+ dom.rulePause.style.left = `${pauseX * 100}%`+ dom.ruleHide.style.left = `${hideX * 100}%`+ dom.rulePause.setAttribute('aria-valuetext', current.pauseAfterIdle)+ dom.ruleHide.setAttribute('aria-valuetext', current.hideAfterIdle)+ dom.rulePause.querySelector('.rule-tag').textContent = `pause ${current.pauseAfterIdle}`+ dom.ruleHide.querySelector('.rule-tag').textContent = `hide ${current.hideAfterIdle}`+ dom.laneList.style.setProperty('--pause-x', pauseX)+ dom.laneList.style.setProperty('--hide-x', hideX)+}++function chipFor(row) {+ const chip = document.createElement('button')+ chip.type = 'button'+ chip.className = 'chip'+ chip.dataset.id = row.id+ chip.dataset.state = row.state+ chip.dataset.working = String(Boolean(row.working && row.state === 'running'))+ chip.dataset.attention = String(Boolean(row.needsInput))+ chip.dataset.selected = String(state.selected.has(row.id))+ const doomed = verdictFor(row)+ if (doomed) chip.dataset.doomed = 'true'+ chip.title = `${row.title || row.name}\n${row.engine}${row.model ? ` · ${row.model}` : ''} · idle ${humanIdle(row.idleMs)}${doomed ? `\nthe policy would ${doomed} this` : ''}`+ const dot = document.createElement('span'); dot.className = 'dot'+ const what = document.createElement('span'); what.className = 'what'; what.textContent = row.title || row.name+ chip.append(dot, what)+ if (row.pinned) { const pin = document.createElement('span'); pin.className = 'pin'; pin.textContent = '📌'; chip.append(pin) }+ if (row.rssBytes) { const mem = document.createElement('span'); mem.className = 'mem'; mem.textContent = bytes(row.rssBytes); chip.append(mem) }+ return chip+}++/** Lay the chips out along the lane, then push any that overlap onto a second row of the same lane.+ * Measured, not estimated: a title's width depends on the font the app is in. */+function stack(track) {+ const chips = [...track.querySelectorAll('.chip')]+ const width = track.clientWidth || 1+ const placed = []+ let rowsUsed = 1+ for (const chip of chips) {+ const w = chip.offsetWidth+ const wanted = Number(chip.dataset.x) * width+ const left = Math.max(0, Math.min(width - w, wanted - w)) // the chip ends at its own moment in time+ let level = 0+ while (placed.some((other) => other.level === level && left < other.right + 6 && left + w > other.left - 6)) level += 1+ placed.push({ level, left, right: left + w })+ rowsUsed = Math.max(rowsUsed, level + 1)+ chip.style.left = `${left}px`+ chip.style.top = `${5 + level * 26}px`+ }+ track.style.height = `${Math.max(34, 10 + rowsUsed * 26)}px`+}++function renderLanes() {+ const list = rows().filter((row) => row.state !== 'gone' || state.filter)+ dom.lanesEmpty.hidden = list.length > 0+ const lanes = new Map()+ for (const row of list) {+ const key = row.project || 'elsewhere'+ if (!lanes.has(key)) lanes.set(key, [])+ lanes.get(key).push(row)+ }+ // Freshest project first: the top of the hps is the working set, and the sediment sinks.+ const ordered = [...lanes.entries()].sort((a, b) => Math.min(...a[1].map((r) => r.idleMs)) - Math.min(...b[1].map((r) => r.idleMs)))+ const fragment = document.createDocumentFragment()+ for (const [project, group] of ordered) {+ const lane = document.createElement('div')+ lane.className = 'lane'+ const label = document.createElement('div')+ label.className = 'lane-label'+ const branch = group.find((row) => row.branch)?.branch+ label.innerHTML = '<b></b> <i></i>'+ label.querySelector('b').textContent = project+ label.querySelector('i').textContent = group.length > 1 ? `×${group.length}` : (branch ?? '')+ label.title = group.map((row) => `${row.title || row.name} — ${humanIdle(row.idleMs)}`).join('\n')+ const track = document.createElement('div')+ track.className = 'track'+ for (const row of [...group].sort((a, b) => a.idleMs - b.idleMs)) {+ const chip = chipFor(row)+ chip.dataset.x = String(xOf(row.idleMs))+ track.append(chip)+ }+ lane.append(label, track)+ fragment.append(lane)+ }+ dom.laneList.replaceChildren(fragment)+ for (const track of dom.laneList.querySelectorAll('.track')) stack(track)+}++const COLUMNS = [+ { key: 'n', label: '#', sortable: false, cell: (row, i) => ({ text: String(i + 1), className: 'c-num' }) },+ { key: 'state', label: '', cell: (row) => {+ const glyph = row.needsInput ? '!' : row.state === 'running' ? (row.working ? '◐' : '●')+ : row.state === 'paused' ? '○' : row.state === 'terminal' ? '$' : '✕'+ const kind = row.needsInput ? 'attention' : row.working && row.state === 'running' ? 'working' : row.state+ return { text: glyph, className: `c-state st-${kind}`, title: row.needsInput ? 'looks like it is waiting on you' : row.state }+ } },+ { key: 'idle', label: 'idle', cell: (row) => ({ text: row.state === 'gone' ? '—' : humanIdle(row.idleMs), className: 'c-idle' }) },+ { key: 'engine', label: 'engine', cell: (row) => ({ text: row.engine }) },+ { key: 'model', label: 'model', cell: (row) => ({ text: row.model ?? '—', className: 'c-dim' }) },+ { key: 'mem', label: 'mem', cell: (row, i, max) => ({ text: bytes(row.rssBytes), className: 'c-mem membar', bar: max ? (row.rssBytes || 0) / max : 0 }) },+ { key: 'project', label: 'project', cell: (row) => ({ text: row.project, className: 'c-project' }) },+ { key: 'branch', label: 'branch', cell: (row) => ({ text: row.branch ?? '—', className: 'c-dim' }) },+ { key: 'title', label: 'title', cell: (row) => ({ text: row.title || row.name, className: 'c-title' }) },+ // The verb, on the row. It used to appear only after selecting something, which meant a person looking+ // for "the pause button" could not find one.+ { key: 'do', label: '', sortable: false, cell: (row) => ({ text: '', className: 'c-do', verb: row.state === 'running' ? 'pause' : row.state === 'paused' ? 'resume' : null }) },+]++const SORTS = {+ idle: (a, b) => a.idleMs - b.idleMs,+ mem: (a, b) => (b.rssBytes || 0) - (a.rssBytes || 0),+ state: (a, b) => a.state.localeCompare(b.state) || a.idleMs - b.idleMs,+ engine: (a, b) => a.engine.localeCompare(b.engine) || a.idleMs - b.idleMs,+ model: (a, b) => String(a.model ?? '').localeCompare(String(b.model ?? '')),+ project: (a, b) => a.project.localeCompare(b.project) || a.idleMs - b.idleMs,+ branch: (a, b) => String(a.branch ?? '').localeCompare(String(b.branch ?? '')),+ title: (a, b) => String(a.title || a.name).localeCompare(String(b.title || b.name)),+}++function sortedRows() {+ const list = [...rows()]+ const by = SORTS[state.sort.key] ?? SORTS.idle+ list.sort(by)+ if (state.sort.dir === 'desc') list.reverse()+ return list+}++function renderTable() {+ const list = sortedRows()+ const max = Math.max(1, ...list.map((row) => row.rssBytes || 0))+ const table = document.createElement('table')+ const thead = document.createElement('thead')+ const headRow = document.createElement('tr')+ for (const column of COLUMNS) {+ const th = document.createElement('th')+ th.textContent = column.label+ if (column.sortable !== false) {+ th.dataset.sort = column.key+ if (state.sort.key === column.key) th.setAttribute('aria-sort', state.sort.dir === 'asc' ? 'ascending' : 'descending')+ }+ headRow.append(th)+ }+ thead.append(headRow)+ const tbody = document.createElement('tbody')+ list.forEach((row, index) => {+ const tr = document.createElement('tr')+ tr.dataset.id = row.id+ tr.dataset.selected = String(state.selected.has(row.id))+ tr.dataset.cursor = String(state.cursor === row.id)+ if (verdictFor(row)) tr.dataset.doomed = 'true'+ for (const column of COLUMNS) {+ const td = document.createElement('td')+ const cell = column.cell(row, index, max)+ td.className = cell.className ?? ''+ if (cell.title) td.title = cell.title+ if (cell.verb) {+ const button = document.createElement('button')+ button.type = 'button'+ button.dataset.verb = cell.verb+ button.dataset.only = row.id+ button.textContent = cell.verb === 'pause' ? 'Pause' : 'Resume'+ td.append(button)+ } else if (cell.bar) {+ const bar = document.createElement('i')+ bar.style.width = `${Math.max(2, cell.bar * 46)}px`+ const span = document.createElement('span')+ span.textContent = cell.text+ td.append(bar, span)+ } else td.textContent = cell.text+ tr.append(td)+ }+ tbody.append(tr)+ })+ table.append(thead, tbody)+ dom.grid.replaceChildren(table)+}++function renderStatus() {+ const summary = state.snapshot?.summary+ const list = rows()+ const totals = planTotals(list)+ const held = totals.frees >= 1024 ** 3 ? `${(totals.frees / 1024 ** 3).toFixed(1)} GB` : `${Math.round(totals.frees / 1024 ** 2)} MB`+ const hidden = (state.snapshot?.rows ?? []).length - list.length+ const bits = [`${list.length} shown${hidden > 0 ? ` of ${(state.snapshot?.rows ?? []).length}` : ''}`]+ if (summary) bits.push(`${summary.running} running`, `${summary.paused} paused`)+ if (totals.pause) bits.push(`policy: pause ${totals.pause} (${held})`)+ for (const problem of state.snapshot?.problems ?? []) bits.push(`⚠ ${problem.machine}`)+ dom.statusLeft.textContent = bits.join(' · ')++ const count = state.selected.size+ dom.statusActions.hidden = count === 0+ if (count) {+ dom.statusActions.replaceChildren()+ const label = document.createElement('span')+ label.textContent = `${count} selected`+ dom.statusActions.append(label)+ for (const [verb, text] of [['pause', 'Pause'], ['resume', 'Resume'], ['pin', 'Pin'], ['unpin', 'Unpin']]) {+ const button = document.createElement('button')+ button.type = 'button'+ button.textContent = text+ button.dataset.verb = verb+ dom.statusActions.append(button)+ }+ const clear = document.createElement('button')+ clear.type = 'button'; clear.textContent = 'Clear'; clear.dataset.verb = 'clear'+ dom.statusActions.append(clear)+ }+ dom.statusRight.innerHTML = state.view === 'table'+ ? '<kbd>j</kbd><kbd>k</kbd> move · <kbd>space</kbd> select · <kbd>p</kbd> pause · <kbd>r</kbd> resume · <kbd>i</kbd> pin · <kbd>/</kbd> filter'+ : `rules: <code></code> · drag a line to try a change · <kbd>/</kbd> filter`+ const code = dom.statusRight.querySelector('code')+ if (code) code.textContent = state.snapshot?.configPath ?? '~/.config/harness/policy.jsonc'+}++function renderInspector() {+ const row = (state.snapshot?.rows ?? []).find((candidate) => candidate.id === state.inspecting)+ if (!row) { dom.inspector.hidden = true; return }+ dom.inspector.hidden = false+ const verdict = verdictFor(row)+ const entry = (state.snapshot?.plan ?? []).find((candidate) => candidate.id === row.id)+ dom.inspector.replaceChildren()+ const header = document.createElement('header')+ const heading = document.createElement('div')+ const h2 = document.createElement('h2'); h2.textContent = row.title || row.name+ const sub = document.createElement('div'); sub.className = 'sub'+ sub.textContent = `${row.state}${row.pinned ? ' · pinned' : ''} · ${row.engine}${row.model ? ` ${row.model}` : ''} · ${row.machine}`+ heading.append(h2, sub)+ const close = document.createElement('button'); close.type = 'button'; close.className = 'ghost'; close.textContent = '✕'+ close.addEventListener('click', () => { state.inspecting = null; renderInspector() })+ header.append(heading, close)+ dom.inspector.append(header)++ if (entry && entry.action !== 'keep') {+ const why = document.createElement('p'); why.className = 'why'+ why.textContent = `The policy would ${entry.action} this: ${entry.why}.`+ dom.inspector.append(why)+ } else if (entry?.protectedBy) {+ const why = document.createElement('p'); why.className = 'why'+ why.textContent = `Protected: ${entry.why}.`+ dom.inspector.append(why)+ }++ const dl = document.createElement('dl')+ const pairs = [+ ['idle', `${humanIdle(row.idleMs)} — last turn ${new Date(row.lastActivity).toLocaleString()}`],+ ['folder', row.home || '—'],+ ['branch', row.branch ?? '—'],+ ['memory', row.rssBytes ? `${bytes(row.rssBytes)} across ${row.procs} ${row.procs === 1 ? 'process' : 'processes'}` : '—'],+ ['pane', row.pane ? `${row.pane}${row.dead ? ' (dead, held open)' : ''}` : '—'],+ ['harness', row.dshName ?? row.dsh ?? '—'],+ ['id', row.id.slice(0, 8)],+ ]+ for (const [key, value] of pairs) {+ const dt = document.createElement('dt'); dt.textContent = key+ const dd = document.createElement('dd'); dd.textContent = value+ dl.append(dt, dd)+ }+ dom.inspector.append(dl)++ if (row.screenTail) {+ const screen = document.createElement('pre'); screen.className = 'screen'; screen.textContent = row.screenTail+ dom.inspector.append(screen)+ }+ const actions = document.createElement('div'); actions.className = 'row-actions'+ // A shell has no conversation to pause or resume, so it is offered neither.+ const verbs = row.state === 'terminal' ? [] : row.state === 'running' ? [['pause', 'Pause']] : [['resume', 'Resume']]+ if (row.state !== 'terminal') verbs.push(row.pinned ? ['unpin', 'Unpin'] : ['pin', 'Pin'])+ for (const [verb, text] of verbs) {+ const button = document.createElement('button')+ button.type = 'button'; button.className = 'ghost'; button.textContent = text+ button.addEventListener('click', () => act(verb, [row.id]))+ actions.append(button)+ }+ dom.inspector.append(actions)+ if (verdict) dom.inspector.dataset.verdict = verdict+}++function render() {+ if (!state.snapshot) return+ renderGauges()+ placeRules()+ if (state.view === 'lanes') renderLanes(); else renderTable()+ renderStatus()+ renderInspector()+}++/* ── talking to the server ────────────────────────────────────────────────── */++function toast(message, bad = false) {+ dom.toast.textContent = message+ dom.toast.className = `toast${bad ? ' bad' : ''}`+ dom.toast.hidden = false+ clearTimeout(toast.timer)+ toast.timer = setTimeout(() => { dom.toast.hidden = true }, 4200)+}++async function post(path, payload) {+ const response = await fetch(path, {+ method: 'POST',+ headers: { 'content-type': 'application/json', 'x-hps-token': TOKEN },+ body: JSON.stringify(payload),+ })+ return response.json()+}++async function act(verb, ids) {+ if (state.busy || !ids.length) return+ state.busy = true+ try {+ const reply = await post('/api/act', { verb, ids })+ if (reply.error) { toast(reply.error, true); return }+ const results = reply.results ?? []+ const ok = results.filter((result) => result.ok && !result.already).length+ const refused = results.filter((result) => result.refused)+ if (results.length === 1) toast(`${results[0].ok ? '' : 'not '}${verb}: ${results[0].detail}`, !results[0].ok)+ else toast(`${verb}: ${ok} done${refused.length ? `, ${refused.length} left alone (${refused[0].detail})` : ''}`, ok === 0)+ state.selected.clear()+ } catch (error) {+ toast(`Could not ${verb}: ${error.message}`, true)+ } finally {+ state.busy = false+ }+}++async function savePolicy() {+ if (!state.draft) return+ const reply = await post('/api/policy', { policy: state.draft })+ if (reply.error) { toast(reply.error, true); return }+ toast(`Saved to ${state.snapshot?.configPath ?? 'policy.jsonc'}: pause after ${reply.policy.pauseAfterIdle}, hide after ${reply.policy.hideAfterIdle}.`)+ state.draft = null+ dom.policybar.hidden = true+ render()+}++/* ── input ────────────────────────────────────────────────────────────────── */++function setView(view) {+ state.view = view+ dom.lanes.hidden = view !== 'lanes'+ dom.table.hidden = view !== 'table'+ for (const button of document.querySelectorAll('.segmented button')) {+ button.setAttribute('aria-selected', String(button.dataset.view === view))+ }+ render()+}++function toggle(id, additive) {+ if (!additive) {+ const only = state.selected.size === 1 && state.selected.has(id)+ state.selected.clear()+ if (!only) state.selected.add(id)+ } else if (state.selected.has(id)) state.selected.delete(id)+ else state.selected.add(id)+ state.cursor = id+}++function targets() {+ if (state.selected.size) return [...state.selected]+ return state.cursor ? [state.cursor] : []+}++function moveCursor(delta) {+ const list = state.view === 'table' ? sortedRows() : rows()+ if (!list.length) return+ const index = list.findIndex((row) => row.id === state.cursor)+ const next = list[Math.min(list.length - 1, Math.max(0, (index < 0 ? 0 : index) + delta))]+ state.cursor = next.id+ state.inspecting = state.inspecting ? next.id : null+ render()+ const node = dom.grid.querySelector(`tr[data-id="${next.id}"]`)+ node?.scrollIntoView({ block: 'nearest' })+}++document.addEventListener('click', (event) => {+ const chip = event.target.closest('.chip')+ if (chip) { toggle(chip.dataset.id, event.metaKey || event.ctrlKey || event.shiftKey); state.inspecting = chip.dataset.id; render(); return }+ const tr = event.target.closest('#grid tbody tr')+ if (tr) { toggle(tr.dataset.id, event.metaKey || event.ctrlKey || event.shiftKey); state.inspecting = state.inspecting ? tr.dataset.id : null; render(); return }+ const th = event.target.closest('#grid th[data-sort]')+ if (th) {+ const key = th.dataset.sort+ state.sort = { key, dir: state.sort.key === key && state.sort.dir === 'asc' ? 'desc' : 'asc' }+ render(); return+ }+ const button = event.target.closest('[data-verb]')+ const verb = button?.dataset.verb+ if (verb === 'clear') { state.selected.clear(); render(); return }+ // A button on a row acts on THAT row, whatever else is selected — otherwise clicking Pause next to one+ // harness would pause five.+ if (verb) { event.stopPropagation(); act(verb, button.dataset.only ? [button.dataset.only] : targets()); return }+ const view = event.target.closest('[data-view]')?.dataset.view+ if (view) setView(view)+})++dom.refresh.addEventListener('click', () => post('/api/refresh', {}).then(() => toast('Refreshed.')))+dom.showAll.addEventListener('click', () => {+ state.showAll = !state.showAll+ dom.showAll.setAttribute('aria-pressed', String(state.showAll))+ render()+})+dom.policySave.addEventListener('click', savePolicy)+dom.policyReset.addEventListener('click', () => { state.draft = null; dom.policybar.hidden = true; render() })+dom.filter.addEventListener('input', () => { state.filter = dom.filter.value; render() })++/* Dragging a rule: the hps is the only place a threshold can be judged, because the thing you are+ judging is how many chips end up on the wrong side of it. */+for (const rule of [dom.rulePause, dom.ruleHide]) {+ const steps = rule.dataset.rule === 'pause' ? PAUSE_STEPS : HIDE_STEPS+ const key = rule.dataset.rule === 'pause' ? 'pauseAfterIdle' : 'hideAfterIdle'+ const begin = (event) => {+ event.preventDefault()+ rule.classList.add('dragging')+ const track = dom.axis.getBoundingClientRect()+ const move = (moveEvent) => {+ const x = (moveEvent.clientX - track.left) / Math.max(1, track.width)+ state.draft = { ...(state.draft ?? {}), [key]: snap(idleOfX(x), steps) }+ dom.policybar.hidden = false+ const totals = planTotals(rows())+ const held = totals.frees >= 1024 ** 3 ? `${(totals.frees / 1024 ** 3).toFixed(1)} GB` : `${Math.round(totals.frees / 1024 ** 2)} MB`+ dom.policyPreview.textContent = `pause after ${policy().pauseAfterIdle}, hide after ${policy().hideAfterIdle} → would pause ${totals.pause}, handing back ${held}`+ render()+ }+ const end = () => {+ rule.classList.remove('dragging')+ window.removeEventListener('pointermove', move)+ window.removeEventListener('pointerup', end)+ }+ window.addEventListener('pointermove', move)+ window.addEventListener('pointerup', end)+ }+ rule.addEventListener('pointerdown', begin)+ rule.addEventListener('keydown', (event) => {+ const direction = event.key === 'ArrowLeft' ? -1 : event.key === 'ArrowRight' ? 1 : 0+ if (!direction) return+ event.preventDefault()+ const current = policy()[key]+ const index = Math.max(0, Math.min(steps.length - 1, steps.indexOf(current) - direction))+ state.draft = { ...(state.draft ?? {}), [key]: steps[index] }+ dom.policybar.hidden = false+ render()+ })+}++document.addEventListener('keydown', (event) => {+ if (event.target === dom.filter) {+ if (event.key === 'Escape') { dom.filter.value = ''; state.filter = ''; dom.filter.blur(); render() }+ return+ }+ if (event.metaKey || event.ctrlKey || event.altKey) return+ const key = event.key+ if (key === '/') { event.preventDefault(); dom.filter.focus(); return }+ if (key === '1') return setView('lanes')+ if (key === '2') return setView('table')+ if (key === 'j' || key === 'ArrowDown') { event.preventDefault(); return moveCursor(1) }+ if (key === 'k' || key === 'ArrowUp') { event.preventDefault(); return moveCursor(-1) }+ if (key === 'g') { const list = state.view === 'table' ? sortedRows() : rows(); state.cursor = list[0]?.id ?? null; return render() }+ if (key === 'G') { const list = state.view === 'table' ? sortedRows() : rows(); state.cursor = list.at(-1)?.id ?? null; return render() }+ if (key === ' ') { event.preventDefault(); if (state.cursor) { toggle(state.cursor, true); render() } return }+ if (key === 'Enter') { state.inspecting = state.cursor; return render() }+ if (key === 'Escape') { state.selected.clear(); state.inspecting = null; state.draft = null; dom.policybar.hidden = true; return render() }+ // h pause · r resume · x retire · i pin · u unpin. `p` and `w` stay bound to the same two verbs,+ // because anyone who used this before it was renamed will reach for them.+ const verbs = { p: 'pause', h: 'pause', r: 'resume', w: 'resume', i: 'pin', u: 'unpin' }+ if (verbs[key]) { event.preventDefault(); act(verbs[key], targets()) }+})++window.addEventListener('resize', () => { if (state.view === 'lanes') renderLanes() })++/* ── the stream ───────────────────────────────────────────────────────────── */++function listen() {+ const source = new EventSource('/events')+ source.addEventListener('snapshot', (event) => {+ try { state.snapshot = JSON.parse(event.data) } catch { return }+ render()+ })+ source.addEventListener('error', () => {+ dom.where.textContent = 'reconnecting…'+ source.close()+ setTimeout(listen, 2500)+ })+}++renderAxis()+listen()diff --git a/store/agents/harness-monitor/viewer/index.html b/store/agents/harness-monitor/viewer/index.htmlnew file mode 100644index 000000000..08024500e--- /dev/null+++ b/store/agents/harness-monitor/viewer/index.html@@ -0,0 +1,69 @@+<!doctype html>+<html lang="en">+<head>+ <meta charset="utf-8">+ <meta name="viewport" content="width=device-width, initial-scale=1">+ <meta name="hps-token" content="__HPS_TOKEN__">+ <title>Harness Monitor · your fleet</title>+ <link rel="stylesheet" href="app.css">+ <script type="module" src="app.js"></script>+</head>+<body>+ <div id="app">+ <header class="bar">+ <div class="identity">+ <span class="mark" aria-hidden="true"></span>+ <h1>Harness Monitor</h1>+ <span class="where" id="where">reading the fleet…</span>+ </div>+ <div class="gauges" id="gauges" aria-live="polite"></div>+ <div class="tools">+ <div class="segmented" role="tablist" aria-label="View">+ <button type="button" id="view-lanes" role="tab" aria-selected="true" data-view="lanes">Lanes</button>+ <button type="button" id="view-table" role="tab" aria-selected="false" data-view="table">Table</button>+ </div>+ <div class="filter">+ <span aria-hidden="true">/</span>+ <input id="filter" type="search" placeholder="filter by name, project, engine" autocomplete="off" spellcheck="false" aria-label="Filter harnesses">+ </div>+ <button type="button" class="ghost toggle" id="show-all" aria-pressed="false" title="Also show what the policy hides: idle past the hide line, and harnesses whose pane is gone">show all</button>+ <button type="button" class="ghost" id="refresh" title="Refresh now">↻</button>+ </div>+ </header>++ <section class="view" id="lanes-view" aria-label="The lanes">+ <div class="lanes-head">+ <div class="axis-label">PROJECT</div>+ <div class="axis" id="axis">+ <div class="rule" id="rule-pause" data-rule="pause" tabindex="0" role="slider" aria-label="Pause after" aria-valuetext="4h"><span class="rule-grip"></span><span class="rule-tag">pause</span></div>+ <div class="rule" id="rule-hide" data-rule="hide" tabindex="0" role="slider" aria-label="Hide after" aria-valuetext="14d"><span class="rule-grip"></span><span class="rule-tag">hide</span></div>+ </div>+ </div>+ <div class="lanes" id="lane-list"></div>+ <div class="lanes-empty" id="lanes-empty" hidden>+ <p class="big">Nothing is running here yet.</p>+ <p>Ask the agent beside this pane to show your fleet, or open a harness and come back.</p>+ </div>+ </section>++ <section class="view" id="table" hidden aria-label="The table">+ <div class="grid" id="grid" role="grid" tabindex="0"></div>+ </section>++ <div class="policybar" id="policybar" hidden>+ <span class="policy-preview" id="policy-preview"></span>+ <button type="button" class="primary" id="policy-save">Save policy</button>+ <button type="button" class="ghost" id="policy-reset">Reset</button>+ </div>++ <footer class="statusbar" id="statusbar">+ <span id="status-left" class="mono"></span>+ <span id="status-actions" class="actions" hidden></span>+ <span id="status-right" class="keys mono"></span>+ </footer>++ <aside class="inspector" id="inspector" hidden aria-label="Harness details"></aside>+ <div class="toast" id="toast" role="status" hidden></div>+ </div>+</body>+</html>diff --git a/store/agents/harness-monitor/viewer/scale.js b/store/agents/harness-monitor/viewer/scale.jsnew file mode 100644index 000000000..98d795d01--- /dev/null+++ b/store/agents/harness-monitor/viewer/scale.js@@ -0,0 +1,67 @@+/**+ * The hps's geometry, and the units it reads back — the only arithmetic in the pane, kept in a module+ * of its own so it can be tested without a browser (test/scale.test.mjs) and so the dragged rules, the+ * chips and the axis ticks cannot disagree about where a moment in time sits on the track.+ *+ * The scale is logarithmic and anchored at both ends: one minute at the right edge, thirty days at the+ * left. Linear time would put every idle harness in the last eighth of the track and leave the useful+ * part — the hours between "working on it" and "gone quiet" — invisible.+ */++export const FLOOR = 60_000 // one minute: the right edge+export const CEIL = 30 * 86_400_000 // thirty days: the left edge+const SPAN = Math.log(CEIL / FLOOR)++export const UNITS = { s: 1000, m: 60_000, h: 3_600_000, d: 86_400_000, w: 604_800_000 }++/** Thresholds a person would actually type, and the only values a dragged rule can land on. */+export const PAUSE_STEPS = ['15m', '30m', '1h', '2h', '4h', '6h', '8h', '12h', '1d', '2d', '3d', '7d']+export const HIDE_STEPS = ['1d', '2d', '3d', '5d', '7d', '10d', '14d', '21d', '30d']++export function parseDuration(value) {+ const match = /^(\d+(?:\.\d+)?)\s*([smhdw])$/.exec(String(value ?? '').trim())+ return match ? Number(match[1]) * UNITS[match[2]] : Number(value) || 0+}++/** Same rule as the CLI's column: one unit, never two. `humanIdle` in lib/policy.mjs is its twin, and+ * test/scale.test.mjs asserts they agree — a fleet that reads `3d` in the pane and `2d` in the terminal+ * has two different answers to the only question it is asked. */+export function humanIdle(ms) {+ const n = Math.max(0, Math.floor(Number(ms) || 0))+ if (n < 45_000) return 'now'+ if (n < UNITS.h) return `${Math.round(n / UNITS.m)}m`+ if (n < UNITS.d) return `${Math.round(n / UNITS.h)}h`+ if (n < 7 * UNITS.d) return `${Math.floor(n / UNITS.d)}d`+ const weeks = Math.floor(n / UNITS.w)+ return weeks > 9 ? '9w+' : `${weeks}w`+}++/** Bytes, in the width a column can afford: `1.2G`, `340M`, `—`. */+export function bytes(value) {+ const n = Number(value) || 0+ if (!n) return '—'+ if (n >= 1024 ** 3) return `${(n / 1024 ** 3).toFixed(1)}G`+ return `${Math.round(n / 1024 ** 2)}M`+}++/** Idle → a fraction of the track. 1 is now (right edge), 0 is a month ago (left edge). */+export function xOf(idleMs) {+ const clamped = Math.min(CEIL, Math.max(FLOOR, Number(idleMs) || 0))+ return Math.min(1, Math.max(0, 1 - Math.log(clamped / FLOOR) / SPAN))+}++/** The inverse, for a rule the pointer is dragging. */+export function idleOfX(x) {+ return FLOOR * Math.exp((1 - Math.min(1, Math.max(0, Number(x) || 0))) * SPAN)+}++/** The nearest step, measured in log time so 30m→1h feels the same distance as 7d→14d. */+export function snap(idleMs, steps) {+ let best = steps[0]+ let distance = Infinity+ for (const step of steps) {+ const gap = Math.abs(Math.log(parseDuration(step)) - Math.log(Math.max(1, idleMs)))+ if (gap < distance) { distance = gap; best = step }+ }+ return best+}