docs: add specification, agent rules and project notes

This commit is contained in:
Florian Schmidt
2026-11-15 23:51:05 +01:00
commit a5fea2f82f
8 changed files with 288 additions and 0 deletions
+8
View File
@@ -0,0 +1,8 @@
# Architecture
- [2026-11-15] **Custom app instead of marimo/Atuin/Runme.** Need: literal, copyable shell + SSH run + checks + params + dynamic downloads + Claude Code CLI next to the notebook. No existing tool covers all; marimo hid commands behind Python.
- [2026-11-15] **TypeScript monorepo** (core / server / web). One language; node-pty + xterm.js is the proven path for the embedded Claude terminal.
- [2026-11-15] **AI = real `claude` CLI in a tmux-backed terminal panel.** Uses the user's subscription legitimately; marimo's ACP panel was deprecated and API-key chat is not wanted.
- [2026-11-15] **Workspace (notebooks, hosts.yaml) is a separate git repo** from the app code; the app ships a `CLAUDE.md` format guide into it.
## Archive
+6
View File
@@ -0,0 +1,6 @@
# Attempts
- [2026-11-15] **Approach:** marimo in LXC 501 + Fabric/asyncssh helpers, Claude via marimo's ACP agent panel. **Outcome:** ACP panel superseded by marimo pair; sidebar chat is API-key only. **Now:** dropped.
- [2026-11-15] **Approach:** marimo pair (Claude Code CLI in terminal) writing Python notebooks. **Outcome:** worked technically, but notebooks became Python wrappers; commands not readable/copyable, chat only in bottom terminal. **Now:** custom app (ShellBook) with shell-first format.
## Archive
+19
View File
@@ -0,0 +1,19 @@
# Project Mind — Index
> Always-loaded. Everything else is on-demand. Update TOC when files change.
## Current Focus
- [2026-11-15] Spec draft `docs/spec.md` v0.1 — awaiting review of the notebook format (§3).
- [2026-11-15] Next: M0 — monorepo skeleton + `packages/core` parser/params/shellQuote with tests.
## Invariants
- Displayed script == executed script (one substitution path).
- All shell quoting via `core/shellQuote`.
- Secrets only as env vars; never rendered/logged.
- Strict SSH host key checking with explicit TOFU.
- `check` steps are side-effect free.
- Notebooks stay plain, readable Markdown.
## Table of Contents
- `architecture.md` — 4 entries — why custom app, stack, AI integration, workspace split
- `attempts.md` — 2 entries — marimo + marimo-pair trial and why it was dropped
- `open.md` — 3 entries — open design questions
+7
View File
@@ -0,0 +1,7 @@
# Open Questions
- [2026-11-15] Optional chat-style UI (stream-json headless `claude`) in addition to the terminal? Would bill to the Agent SDK credit on subscriptions — decide after M4.
- [2026-11-15] sudo with password (`type: secret` + `sudo -S`) or require NOPASSWD sudo only? Spec v0.1: `sudo -n` only.
- [2026-11-15] Node 22 on Debian 13: NodeSource repo vs. official tarball in the deploy script; node-pty prebuilds vs. build-essential.
## Archive
+42
View File
@@ -0,0 +1,42 @@
# ShellBook — Agent Rules
Project rules on top of the global rules. These win on conflict.
## What this is
Self-hosted web app for notebook-style server runbooks: Markdown notebooks whose
shell blocks are shown literally (params filled in, copyable) and can be run on
hosts over SSH. Spec: `docs/spec.md` — read it before any design change.
## Invariants
- **The displayed script is the executed script.** Rendering and execution use the same
substitution result; never build a second, hidden command string.
- **All shell quoting goes through `packages/core` `shellQuote`.** No ad-hoc escaping anywhere.
- **Secrets** (`type: secret` params) are passed as env vars only; never rendered, logged,
stored in audit records or artifacts metadata.
- **Strict SSH host key checking.** Unknown keys require explicit user confirmation (TOFU).
- **`check` steps must be side-effect free**; only `run` steps change hosts.
- Notebooks stay valid, readable Markdown in any renderer (Gitea/GitHub).
- AI integration uses the real Claude Code CLI in a terminal (user's own login). No
embedding of subscription credentials, no SDK-based chat on subscription auth.
## Stack and layout
TypeScript, Node 22 LTS, pnpm workspaces. `packages/core` (pure, no I/O),
`apps/server` (Fastify, ws, ssh2, node-pty), `apps/web` (Vite + React, CodeMirror,
xterm.js), `deploy/`. Tests with Vitest; `core` changes need unit tests.
- `@shellbook/core` is consumed **as TypeScript source** (`exports: ./src/index.ts`); the
server bundles it for production, the web app via Vite.
- **Contracts:** `packages/core/src/types.ts` (notebook model), `protocol.ts` (HTTP/WS API),
and the function signatures in `index.ts`. Change them only deliberately and update all
consumers in the same change.
- Commands (pnpm via corepack or `npx [email protected]`): `pnpm install`, `pnpm typecheck`,
`pnpm test`, `pnpm dev`. All three must pass before a commit.
## Workflow
- Issue-first: work items are Gitea issues on `FinalFactory/ShellBook`; reference them in commits.
- Conventional commit subjects (`feat(core): …`, `fix(server): …`).
- New dependencies must be well-known and justified in the PR/commit message.
+1
View File
@@ -0,0 +1 @@
@AGENTS.md
+11
View File
@@ -0,0 +1,11 @@
# ShellBook
Notebook-style runbooks for Linux servers.
- Notebooks are Markdown: prose plus `sh` blocks.
- Commands are always shown literally, with parameters filled in, so you can copy them.
- Steps run on a chosen host over SSH (`run`) or verify state with ✅/❌ (`check`).
- Steps can produce files that appear as downloads, and reveal follow-up notes.
- Claude Code (the real CLI) runs in a built-in terminal panel and edits notebooks live.
Status: design phase. See [docs/spec.md](docs/spec.md).
+194
View File
@@ -0,0 +1,194 @@
# ShellBook — Specification (draft v0.1)
ShellBook is a self-hosted web app for **notebook-style runbooks for Linux servers**.
A notebook is a Markdown file: prose plus shell blocks. The shell is the primary
artifact — always shown literally, with parameter values filled in, copyable into
any terminal. ShellBook adds buttons around it: run on a host over SSH, check a
condition, download a produced file. Claude Code (the real CLI, subscription
login) runs in a built-in terminal and edits the notebooks.
## 1. Goals
| # | Requirement | Where |
|---|---|---|
| G1 | Notebooks with prose and code, written by hand or by AI | §3 format, §6 AI |
| G2 | Run a code block on a chosen machine over SSH | §4 execution |
| G3 | Check blocks that do real checks on the machine (dir/package/config present) and show ✅/❌ | §3.3 |
| G4 | Parameters in the text: editable, optionally required, substituted into the scripts | §3.2 |
| G5 | Dynamic flows: a step produces files → download buttons + follow-up notes appear | §3.4, §3.5 |
| G6 | **Commands are readable and copyable** without running anything | §3.1, §5 |
| G7 | Web UI, reachable over LAN/Tailscale behind Traefik; logins survive restarts | §7 |
| G8 | Claude Code CLI with subscription login, as a chat-like panel next to the notebook | §6 |
Non-goals (v1): multi-user roles, scheduling/cron, Windows targets, interactive TTY
programs inside run blocks (use the terminal panel for those).
## 2. Concepts
- **Workspace**: a git repo with the user's data, separate from the app code:
`notebooks/*.md`, `hosts.yaml`, `CLAUDE.md` (format guide for Claude, shipped by ShellBook).
- **Host**: an entry in `hosts.yaml` (`name`, `address`, `user`, `port`, optional `tags`).
ShellBook connects with its own SSH key.
- **Step**: a fenced block with a ShellBook attribute set. Kinds: `run`, `check`.
- **Run record**: one execution of a step (host, rendered script, output, exit code,
artifacts, timestamp). Appended to the audit log.
## 3. Notebook format
Plain Markdown that renders sensibly in Gitea/GitHub too (blocks show as normal
`sh` code with an info string).
### 3.1 Example
````markdown
---
title: New server SSH key
params:
host: { type: host, required: true, label: Target server }
user: { type: name, required: true, default: admin, label: Login user }
keyname: { type: name, default: "id_ed25519_{{host}}" }
---
# New server SSH key
Creates a key pair for **{{user}}** on **{{host}}** and authorizes it.
```sh {check host="{{host}}" title="User exists"}
id {{user}}
```
```sh {check host="{{host}}" title="Password login disabled"}
sshd -T | grep -qx 'passwordauthentication no'
```
```sh {run on=local id=keygen title="Generate key pair" artifacts="{{keyname}},{{keyname}}.pub"}
ssh-keygen -q -t ed25519 -N '' -C {{user}}@{{host}} -f {{keyname}}
```
```sh {run host="{{host}}" id=authorize title="Authorize key" confirm upload="{{keyname}}.pub:/tmp/new_key.pub"}
install -d -m 700 -o {{user}} -g {{user}} ~{{user}}/.ssh
cat /tmp/new_key.pub >> ~{{user}}/.ssh/authorized_keys
rm /tmp/new_key.pub
```
:::after{step=keygen}
Download the private key above, then save it:
- **Linux:** `~/.ssh/{{keyname}}`, then `chmod 600 ~/.ssh/{{keyname}}`
- **Windows:** `C:\Users\<you>\.ssh\{{keyname}}`
:::
````
### 3.2 Parameters
- Declared in frontmatter `params`. Fields: `type`, `required`, `default`, `label`, `options` (for `type: choice`).
- Types and validation (validated before any run):
- `host` — dropdown from `hosts.yaml`; substitutes the host **name** in attributes, the connection uses the inventory entry.
- `name` — `[A-Za-z0-9._-]+` (users, files, packages, services).
- `path` — absolute or relative path, no NUL/newline.
- `string` — free text.
- `choice` — one of `options`.
- `secret` — never rendered, never logged; passed to the script as an environment variable only (`$NAME`), not via `{{ }}`.
- `{{name}}` works in prose, in block attributes and in scripts.
- **Substitution in scripts is shell-safe**: the value is inserted shell-quoted when it
contains anything outside `[A-Za-z0-9._/@:=+-]`. The displayed script and the executed
script are the same string. One function does this (`core/shellQuote`), nowhere else.
- A step with a missing required param shows the script with `{{name}}` highlighted and a disabled Run button.
### 3.3 Step attributes
Info string: `sh {<kind> key=value key="value with spaces" flag}`. Language `sh`/`bash` keeps syntax highlighting in other renderers.
| Attribute | Kinds | Meaning |
|---|---|---|
| `run` / `check` | — | Step kind. `check` = read-only, ✅ if exit code 0, may run without confirmation ("Run all checks"). |
| `host="…"` | both | Target host (usually `{{host}}`). |
| `on=local` | both | Run on the ShellBook server instead (key generation, etc.). |
| `id=…` | both | Stable id, referenced by `:::after` and `capture`. Default: slug of title. |
| `title="…"` | both | Shown as step heading. |
| `sudo` | both | Wrap in `sudo -n` (passwordless sudo required; fails clearly otherwise). |
| `confirm` | run | Ask before running (default on for `run` against hosts tagged `prod`). |
| `capture=var` | both | Store trimmed stdout as a runtime param `var` for later steps. |
| `artifacts="a,b"` | run | Files (relative to the run's workdir) offered as downloads after success. Remote: fetched via SFTP. |
| `upload="src:dst"` | run | Copy an artifact from a previous step to the host before the script runs. |
| `timeout=60` | both | Seconds; default 300 for run, 30 for check. |
### 3.4 Conditional sections
`:::after{step=<id>}` … `:::` — rendered only after that step succeeded in the
current session. `:::after{step=<id> failed}` for the failure case. (remark-directive syntax.)
### 3.5 Artifacts
Each `on=local` run gets a fresh workdir under `data/runs/<run-id>/`. Artifacts are kept
for 24 h (configurable), then deleted. Private keys are flagged sensitive: one download
only, then removed.
## 4. Execution
- Scripts run as `bash -euo pipefail -s` with the script on stdin; no TTY.
- SSH via `ssh2`, ShellBook's own key, **strict host key checking**. Unknown host key →
UI shows the fingerprint and asks once (TOFU), then stored in the workspace's `known_hosts`.
- Output is streamed to the browser over WebSocket (stdout/stderr interleaved, with exit code).
- Every run is appended to `data/audit.jsonl`: time, notebook, step id, host, rendered script, exit code, duration. Secrets never appear.
- One step per host at a time (queue); different hosts in parallel.
## 5. UI
- **Notebook list** (left), **notebook view** (center), **AI/terminal panel** (right, collapsible).
- Notebook view: params form at the top (sticky); prose rendered; each step is a card:
title, target host, **the literal script with values filled in**, buttons
`Copy` · `Copy as ssh one-liner` · `Run`/`Check`; output below.
- "Run all checks" button per notebook → ✅/❌ summary.
- Edit mode: raw Markdown in CodeMirror with live preview. Files changed on disk
(by Claude or git pull) reload live.
## 6. AI: Claude Code
- The right panel is a real terminal (xterm.js ↔ node-pty) running `claude` in the
workspace, inside `tmux` so the session survives closed tabs and app restarts.
This is the genuine CLI with the user's own subscription login — no API key, no SDK.
- The workspace ships a `CLAUDE.md` describing this notebook format, so Claude writes
shell-first notebooks (literal commands, no wrapper code).
- Live reload (§5) makes Claude's edits appear immediately.
- Later option: `ANTHROPIC_BASE_URL` / token for a custom endpoint, set in the
panel's environment.
## 7. Security
- The app can run commands on every host → treat access as root-equivalent.
- Built-in login: one password (scrypt hash in config), session cookie signed with a
secret persisted on disk → **logins survive restarts**. Optional: trust a
forward-auth header from Traefik instead.
- Listens on `127.0.0.1` or LAN; intended behind Traefik + firewall (LAN/Tailscale only).
- Terminal panel = shell as the service user: same trust level as the app itself.
- No secrets in notebooks, audit log or artifacts metadata.
## 8. Architecture
pnpm monorepo, TypeScript throughout, Node 22 LTS.
```
packages/core format parser (frontmatter, steps, directives), param validation,
substitution + shellQuote. Pure, no I/O. Shared by server and web.
apps/server Fastify + WebSocket. Workspace files, hosts.yaml, SSH (ssh2),
run queue, artifacts, audit log, auth, terminal (node-pty + tmux),
file watcher.
apps/web Vite + React. Notebook view, params form, step cards, CodeMirror,
xterm.js panel.
deploy/ LXC/systemd install script, Traefik example.
```
Tests: Vitest. `core` is unit-tested exhaustively (parser, quoting, validation);
server has integration tests against a throwaway SSH server container.
## 9. Milestones
| M | Scope | Done when |
|---|---|---|
| M0 | Repo skeleton, `core`: parser, params, shellQuote + tests | Example §3.1 parses; quoting fuzz tests pass |
| M1 | Read-only viewer: list, params form, rendered steps, copy buttons | Example notebook readable/copyable in browser |
| M2 | Execution: hosts.yaml, SSH run/check, streaming, TOFU, audit log | Checks + run against a test VM |
| M3 | Artifacts, uploads, `:::after`, `capture` | SSH-key example works end to end |
| M4 | Terminal panel with Claude in tmux, live reload, shipped CLAUDE.md | Claude edits a notebook, view updates live |
| M5 | Auth, deploy script for LXC 501, Traefik example; replaces marimo | Running in CT 501 behind Traefik |