diff --git a/.claude/skills/formledger-harness/EVALS.json b/.claude/skills/formledger-harness/EVALS.json index c7f683c..b9f8a2c 100644 --- a/.claude/skills/formledger-harness/EVALS.json +++ b/.claude/skills/formledger-harness/EVALS.json @@ -44,7 +44,7 @@ "files": [], "expected_behavior": [ "Does not open source files or propose code changes", - "Says the repository is a scaffold and has no MCP server or agent tool yet, and does not invent app features or menu paths" + "Points to docs/ledger/agents.md and the formledger cli mcp server for using the app, and does not invent app features or menu paths" ] } ], diff --git a/.claude/skills/formledger-harness/SKILL.md b/.claude/skills/formledger-harness/SKILL.md index 7870221..86b4f25 100644 --- a/.claude/skills/formledger-harness/SKILL.md +++ b/.claude/skills/formledger-harness/SKILL.md @@ -14,7 +14,7 @@ FormLedger is a local-first business app that is the system of record for a smal This pack is for agents who change the repository. It is not about using the app. `docs/BEHAVIOURS.md` is the specification: every phase's exit criterion traces to a behaviour there, and nothing outside the repo is a source of behaviour. Outside reference products are never opened or copied. -There is no MCP server or agent-facing tool yet; they are later phases. Do not add `.mcp.json` or describe agent tools until a phase builds them. `./formledger cli` is a client of the running server over HTTP with an app token (`FORMLEDGER_URL`, `FORMLEDGER_TOKEN`); it never opens the database, because one server process is the only writer. +Agents use the app through `./formledger cli mcp` (stdio MCP, in `internal/cli/mcp.go`), the `internal/agent` module (`/api/agent/*`: routes, call, window commands, jobs, approval; `/api/live`: the change stream) and the window's command registry, bridged by `web/src/ui/agent-bridge.ts`; `docs/ledger/agents.md` is the reference. A new window action must be a registered command with typed params (`web/src/engine/agent.ts` holds the page actions), and a new money-moving, destructive or people route must fall in an approval class in `internal/agent/call.go`. There is no `.mcp.json`, because the server needs the user's own app token. `./formledger cli` is a client of the running server over HTTP with an app token (`FORMLEDGER_URL`, `FORMLEDGER_TOKEN`); it never opens the database, because one server process is the only writer. ## Repo map @@ -31,7 +31,8 @@ There is no MCP server or agent-facing tool yet; they are later phases. Do not a | `internal/coa`, `internal/fiscal` | The chart of accounts with its starter chart; fiscal years, monthly periods and the period lock | | `internal/journal`, `internal/posting` | Draft entries and the triggers that protect posted rows; post and cancel, each one transaction, with gapless numbers | | `internal/reports` | Trial balance, general ledger, balances, period activity and the integrity check, all read-only SQL | -| `internal/cli` | `./formledger cli`, the HTTP client | +| `internal/cli` | `./formledger cli`, the HTTP client, and `cli mcp`, the agents' MCP server | +| `internal/agent` | The agents' engine side: `/api/live` change stream, `/api/agent/*` routes, call, window commands, jobs and the owner's approval | | `docs/ledger/` | One page per ledger part, with routes and refusal codes | | `internal/customers`, `internal/items`, `internal/taxrates` | The parties and the things sold; tax is basis points, computed half-up per line | | `internal/series`, `internal/sales` | Gapless numbers for any document prefix; the sales document tables with their protecting triggers, drafts and server-side totals | diff --git a/AGENTS.md b/AGENTS.md index 213ad21..cc8eef1 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -10,7 +10,7 @@ FormLedger: a local-first business app that is the system of record for a small `.claude/skills/formledger-harness/SKILL.md` holds the repo map, the commands, the ports, the rules of the build, the ledger invariants and the hand-back. Read it before changing anything. `docs/BEHAVIOURS.md` is the specification. -There is no MCP server, CLI for agents or agent-facing tool yet. +Agents that use FormLedger (not change it) connect with `./formledger cli mcp`, an MCP server on stdio that is a client of the running server with an app token. It reaches every engine route, every `formledger cli` command and every command of the open window, and the window shows their changes live. Posting, cancelling, allocating, amending, confirming, deleting, period locks, invitations and the app lock wait for the owner's approval in the window; sign-in, tokens and terminals are never reachable. `docs/ledger/agents.md` lists the tools. When you add a user action to the window, register it as a command with typed params in the engine's registry so agents get it too. ## Build and check diff --git a/CHANGELOG.md b/CHANGELOG.md index be8bbb3..f813e8e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,26 @@ # Changelog +## 0.16.0 + +FormLedger opens in about three seconds on a Mac instead of twenty or more, and Claude Code and the other agents can now do everything you can in it. + +### Fixed +- **Slow open on macOS.** The desktop app keeps its window hidden until the page says it is ready, and the page had stopped saying so, so every launch waited out a 20 second safety timer behind the splash. The page now says so as soon as it has drawn, and the safety timer is 6 seconds. Windows and Linux were not affected. + +### New +- **Agents can do everything you can.** Every page action is a typed command (invoices and other documents, payments, stock, master data, cash, reports, the dashboard, templates, the menus and Preferences), 115 in all, that Claude Code and the other agents can list and run. A new `formledger cli mcp` server gives agents the ledger's data and every engine route, going through the running engine so it stays the only writer. +- **Claude Code in the dock works with no setup.** Each agent tab gets its own access key, passed to it with the engine's address, and Claude Code is started with FormLedger's tools already connected. The key is listed under Account, App tokens, revoked when the tab closes, and cleaned up after a crash. +- **App tokens in Account:** see your keys, make one (shown once, with Copy) and revoke any of them. +- **The open page follows changes.** When an agent or the command line changes the books, the page you have open updates at once; a draft you are editing is kept, with a note. + +### Changed +- **You approve the risky steps.** When an agent deletes, posts, cancels, allocates, amends or confirms, locks a period, invites someone, locks the app, signs out or quits, FormLedger asks you in the window first; with no window open the step is refused. Agents cannot sign in or create or revoke keys, and read-only keys stay read-only. + +### Known issues +- The plain `formledger cli` run with your own token is not approval-gated; it is your scripted path. Only the agent tools are. +- Codex, Cursor and Antigravity tabs get a key and the engine's address, but not yet the agent tools set up for them. +- Part of a first launch on a Mac can be macOS checking the downloaded app; signing and notarisation are done when the app is built. + ## 0.15.1 FormLedger's window now matches the other Form apps at the top right, in Preferences and around the macOS traffic lights. diff --git a/CLAUDE.md b/CLAUDE.md index 54d6fa0..97c70db 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -8,7 +8,7 @@ A local-first business app that is the system of record for a small company. Go - `embed.go` embeds `web/dist` into the binary. `src-tauri/` starts the server as the sidecar `binaries/formledger-server`. - `docs/BEHAVIOURS.md` is the specification; every phase's exit criterion traces to it. Outside reference products are never opened or copied. - `formledger`, `formledger_oc_install` and `build_app` at the root are the scripts the repo ships, not build output. -- There is no MCP server, CLI for agents or agent-facing tool yet, and so no `.mcp.json`. They are later phases. +- Agents reach the app through `./formledger cli mcp` (stdio MCP, a client of the server with an app token), the engine's `internal/agent` module (`/api/agent/*` and the `/api/live` stream) and the window's command registry. Every new user action is a registered command with typed params; money-moving, destructive and people actions stay behind the owner's approval. See `docs/ledger/agents.md`. There is no `.mcp.json`: the server needs the user's own app token. - The planning documents (`DEV_PLAN.md`, `BUILD_NOTES.md`) live in a planning sidecar outside the repo. ## Skills diff --git a/Makefile b/Makefile index a30a5fd..382382a 100644 --- a/Makefile +++ b/Makefile @@ -1,4 +1,4 @@ -VERSION := v0.15.1 +VERSION := v0.16.0 GO_BUILD := CGO_ENABLED=0 go build -trimpath -ldflags "-s -w" .PHONY: build web server check clean diff --git a/README.md b/README.md index eebdad4..f1fb217 100644 --- a/README.md +++ b/README.md @@ -12,7 +12,7 @@
-
+
@@ -124,7 +124,9 @@ The command line is a client of the running server; it never opens the database.
[`docs/ledger/cli.md`](docs/ledger/cli.md) walks from an empty company to a trial balance. What the app commits to do is listed in [`docs/BEHAVIOURS.md`](docs/BEHAVIOURS.md), and [`AGENTS.md`](AGENTS.md) is the guide for coding agents working on the repo.
-From 0.15.0 the window also has an agent dock, opened from View, Agent Dock, the robot button at the top right or with Cmd or Ctrl plus J: a terminal panel beside the books with a shell tab and tabs for Claude Code, Codex, Cursor and, from 0.15.1, Antigravity when they are installed on your computer. Only the owner of the books can open it, and only from this computer. On Windows its terminals do not open yet. FormLedger has no MCP server yet; an agent drives the books through the command line above.
+From 0.15.0 the window also has an agent dock, opened from View, Agent Dock, the robot button at the top right or with Cmd or Ctrl plus J: a terminal panel beside the books with a shell tab and tabs for Claude Code, Codex, Cursor and, from 0.15.1, Antigravity when they are installed on your computer. Only the owner of the books can open it, and only from this computer. On Windows its terminals do not open yet.
+
+From 0.15.2 agents can do what you can do at the window. `./formledger cli mcp` is an MCP server for Claude Code, Codex, Cursor and others (`claude mcp add formledger -e FORMLEDGER_TOKEN=fl_... -- /path/to/formledger cli mcp`): it reads and writes the books over every engine route and the command line, and runs any of the window's commands, from opening a page to posting an invoice or changing a preference. Posting, cancelling, allocating, deleting, period locks and invitations wait for your yes in the window, sign-in and tokens stay with you, and whatever an agent changes shows in the open window at once. In the agent dock it needs no setup: each agent tab gets its own token, listed under Account, App tokens and withdrawn when the tab closes, and Claude Code starts with the server already connected. [`docs/ledger/agents.md`](docs/ledger/agents.md) lists the tools.
## Network
diff --git a/cmd/HASHOUT_LOG.md b/cmd/HASHOUT_LOG.md
index 563aa65..6ab7d07 100644
--- a/cmd/HASHOUT_LOG.md
+++ b/cmd/HASHOUT_LOG.md
@@ -2,7 +2,7 @@
Living log of all comment content, explainers, rationale, TODOs, & removed (hashed-out) code for the entry point, `embed.go`, `internal/server`, `internal/static` and `internal/startup`. Source files stay comment-free per dev-rules `sub-skills/hashout-log/SUB-SKILL.md`; everything they would have said lives here, indexed. Read it first, then edit code surgically.
-Current build version: v0.15.1
+Current build version: v0.16.0
Last updated: 2026-11-26 (US Eastern) · skeleton port from form.md
---
diff --git a/docs/ledger/agents.md b/docs/ledger/agents.md
new file mode 100644
index 0000000..4a85868
--- /dev/null
+++ b/docs/ledger/agents.md
@@ -0,0 +1,73 @@
+# Agents: MCP, the window bridge and the live stream
+
+Claude Code, Codex, Cursor and other agents can do in FormLedger what a person can do at the window. They work as a client of the running server with an app token, so one server process stays the only writer and the token's role and scope decide what they may do. Money-moving, destructive and people actions wait for the owner's yes in the open window.
+
+## Connect an agent
+
+In the agent dock nothing needs setting up. Each agent tab (Claude Code, Codex, Cursor, Antigravity) gets its own write-scoped app token when it starts, named for example `Claude Code tab, FormLedger dock`, with `FORMLEDGER_TOKEN`, `FORMLEDGER_URL` and `FORMLEDGER_AGENT` in its environment, so `formledger cli` works in it at once. Claude Code also starts with the `formledger` MCP server in its `--mcp-config` and a short note saying it is there. The token is stored hashed, is listed under Account, App tokens, where the owner can revoke it, and is withdrawn when the tab closes; tokens left by a run that ended without closing its tabs are withdrawn when FormLedger next starts. Both show in the audit log as the FormLedger dock.
+
+Outside the dock:
+
+1. Under Account, App tokens, make an app token (read or write). It is shown once.
+2. Add the MCP server to the agent. For Claude Code:
+
+```
+claude mcp add formledger -e FORMLEDGER_TOKEN=fl_... -- /path/to/formledger cli mcp
+```
+
+`FORMLEDGER_URL` points it at a server other than `http://127.0.0.1:8340`. Inside the agent dock's terminals the server's own address is already set (`FORMLEDGER_ENGINE_URL`), so only the token is needed. `FORMLEDGER_AGENT` names the agent in the approval dialog (default `MCP agent`).
+
+## Tools
+
+| Tool | Does |
+| --- | --- |
+| `ledger_overview` | The user and role behind the token, read-only or not, open windows, window commands |
+| `ledger_routes` | Every engine route an agent may call, with the approval class of those that wait for the owner |
+| `ledger_get` | GET one engine route, compact JSON |
+| `ledger_call` | POST, PATCH, PUT or DELETE one engine route |
+| `ledger_cli` | Any `formledger cli` command, for example `["invoice","post","SINV-0001"]`; its writes go through the same approval |
+| `ledger_export` | One CSV export to a file on this computer, the same bytes as File, Export CSV |
+| `ledger_print` | A document or statement as a PDF file on this computer, the same as Print |
+| `app_commands` | The open window's commands: menus, buttons, page actions and Preferences, with argument names and approval class |
+| `app_command` | One window command with its typed arguments |
+| `app_run` | Run one window command, as if the person clicked it |
+| `job_status` | Poll a job id answered by a slow call |
+
+## The window's commands
+
+Every action of the window is a command in one registry (`web/src/engine/commands.ts`) with typed parameters (type, required, enum, min, max). The palette, the menus, the keyboard and agents all run the same commands. Groups: Navigation (`view.open`, `view.current`, `go.*`, `nav.*`), File and New (`new.*`, `file.*`), View, Window and Edit (the menus), Preferences (`prefs.get`, `prefs.set`, `app.preferences`), Account and People (`account.lock`, `invites.*`, `session.logout`), Documents (`doc.*`), Payments (`payment.*`), Stock (`stockdoc.*`), Setup (`master.*`, `cash.*`), Reports (`report.*`, `dashboard.*`) and Templates (`template.*`).
+
+`view.open { view, id, kind, status, template, from, to, asOf }` opens any page or one document, so an agent can show the person what it did.
+
+## Approval
+
+These wait for the owner in the window's Consent dialog (Deny, Allow once, Always allow), whether they come as an engine call, a cli command or a window command:
+
+- posting, cancelling, allocating, amending, confirming, deleting;
+- locking and unlocking periods;
+- inviting people and withdrawing invitations, the app lock, signing out, closing or reloading the window.
+
+Always allow covers that kind of action from that credential until FormLedger restarts. With no window open these are refused with `consent_needs_window`. Nothing in FormLedger sends mail or anything else off this computer.
+
+Never reachable by agents: sign-in, set-up, unlock, invitation acceptance, claiming the books, app tokens and the dock's terminals. A read-only token stays read-only on every path: it may GET engine routes and run only the window's read commands (`view.current`, `prefs.get`, `cash.get`, `template.use`, the `*.get` and `*.list` commands, `payment.openInvoices`, `report.*` and `dashboard.*`). Every other window command is refused to it, including those that change only the window, such as `prefs.set`, the theme toggle and navigation (`view.open`, `go.*`, `nav.*`), because they change what the owner sees.
+
+## Compact results and jobs
+
+Lists longer than the limit (default 50, at most 500) are cut and their full length is reported under `truncated`. Binary output is not sent; `ledger_export` and `ledger_print` write files instead. A call that takes longer than its wait (default 15 s, at most 60) answers `{ job, state }`; poll it with `job_status`. States: `running`, `waiting_consent`, `done`, `failed`, `denied`.
+
+## Live
+
+`GET /api/live` is a server-sent event stream for the signed-in window. Every successful write publishes a `change` event (method, path, area, by `window`, `token` or `agent`, and the window id that made it). The open page refreshes in place; a document or payment with unsaved edits keeps them and says it changed. The same stream carries `consent` and `command` events to the window.
+
+## Engine routes
+
+| Route | Who | Does |
+| --- | --- | --- |
+| `GET /api/agent` | token or session | Overview |
+| `GET /api/agent/routes` | token or session | Callable routes with approval classes |
+| `POST /api/agent/call` | token or session | Run one route with the caller's credential, approval and compact answer |
+| `GET /api/agent/commands`, `GET /api/agent/commands/{id}` | token or session | The window's catalogue |
+| `POST /api/agent/commands/{id}` | token or session | Run a window command |
+| `GET /api/agent/jobs/{id}` | token or session | Poll a job |
+| `GET /api/live` | window session | The live stream |
+| `POST /api/agent/window/catalogue`, `POST /api/agent/window/result`, `POST /api/agent/consent/{id}` | window session | The window's side of the bridge |
diff --git a/docs/ledger/cli.md b/docs/ledger/cli.md
index 1ec5c08..a827644 100644
--- a/docs/ledger/cli.md
+++ b/docs/ledger/cli.md
@@ -12,18 +12,20 @@ bin/formledger cli --help the compiled binary
| Setting | What it does |
|---|---|
-| `FORMLEDGER_URL` | the server address, default `http://127.0.0.1:8340` |
+| `FORMLEDGER_URL` | the server address; unset, `FORMLEDGER_ENGINE_URL` (set in the agent dock's terminals), else `http://127.0.0.1:8340` |
| `FORMLEDGER_TOKEN` | the app token, `fl_...` |
| `--token-file FILE` | read the token from a file instead (it wins over the variable) |
| `--table` | print a table instead of the server's JSON |
Every command prints JSON on stdout, or a table with `--table`. A problem prints one plain sentence on stderr: no token, a refused token, a read-only token asked to change something, a role that may not do the action, a server that does not answer, or a server that does not know the command yet. Exit codes: 0 done, 1 refused or failed, 2 wrong usage. `--help` works at every level (`formledger cli journal --help`, `formledger cli journal new --help`).
+`formledger cli mcp` serves the same commands, every engine route and the open window's commands to Claude Code and other agents over MCP; see [agents.md](agents.md).
+
## Making the first app token
A token cannot be made from the command line. `POST /api/me/tokens` needs a signed-in browser session, and an app token may not make another one; `formledger cli token` only prints these steps.
-The web app has no screen for app tokens yet, so for now a token is made with curl and a session cookie. The `fl_...` value is in the answer's `token` field and is shown once:
+In the window, Account, App tokens makes one (name and scope; the `fl_...` value is shown once) and lists and revokes them. The agent dock makes one for each agent tab by itself. Without the window, a token is made with curl and a session cookie; the `fl_...` value is in the answer's `token` field and is shown once:
```
curl -c jar -H 'Content-Type: application/json' \
diff --git a/internal/HASHOUT_LOG.md b/internal/HASHOUT_LOG.md
index 1a9e325..1ea9040 100644
--- a/internal/HASHOUT_LOG.md
+++ b/internal/HASHOUT_LOG.md
@@ -2,7 +2,7 @@
Living log of comment content, rationale and removed code for the core skeleton packages under `internal/`. Source files stay comment-free; what they would have said lives here, indexed. Read it first, then edit code surgically. Covers the packages ported in the core slice only; `internal/server`, `internal/static` and `internal/startup` are logged by their own slice.
-Current build version: v0.15.1
+Current build version: v0.16.0
Last updated: 2026-11-27 (US Eastern) · profit and loss and the balance sheet
---
@@ -1958,3 +1958,30 @@ RFC 6455 server side only: the handshake through `http.ResponseController.Hijack
- logged: v0.15.1 · 2026-12-01 (EST)
The Form shell standard, line 3, lists Claude Code, Codex, Cursor and Antigravity tabs when installed. FormLedger 0.15.0 had the first three only. Antigravity is FormVis's fourth program (`backend/app/services/agent_lookup.py`): the executable `agy`, the install line `curl -fsSL https://antigravity.google/cli/install.sh | bash`. It joins `programs`, so `/api/agent/status` now answers `{claude,codex,cursor,antigravity}` and `POST /api/terminal/agent` takes `kind: antigravity`. It is looked for on `PATH` and the same install folders as the others and has no sign-in probe, so `signedIn` is null ("cannot tell"). FormVis writes an MCP entry into Antigravity's own folder for its tab; FormLedger has no MCP server, so nothing is written, as for the other programs. Removed: the refusal text `"the agent program must be codex or cursor"`, now `"the agent program must be codex, cursor or antigravity"`.
+
+### internal/agent · agents do what the person at the window can do
+- refers-to: internal/agent/module.go :: Mount, changes, live, ask; internal/agent/call.go :: call, routeClass, commandClass, blocked, compactResponse; internal/agent/jobs.go :: jobs, consents
+- kind: rationale
+- logged: v0.15.2 · 2026-12-03 (EST)
+
+The owner's rule (2 Dec): Claude Code and the other agents must be able to do everything a user can in FormLedger. Before this, agents had only `formledger cli` with a hand-made app token; the window's command registry was unreachable, nothing told the window about changes made elsewhere (views cache their data on first show), and the dock's shared Consent dialog was never wired. Design, the general one rather than a tool per screen: one module that (a) streams a `change` event after every successful unsafe `/api/` request (a middleware added from `Mount`, inside the auth middleware so the principal is known; quiet for the stream, the bridge, terminals and sign-in), (b) relays the window's command registry to agents (the window posts its catalogue; a run is pushed to the newest window of the same user over the same stream and its answer posted back), (c) runs any engine route for an agent through the full router (`router.Handler()` built once on first use, so every middleware, the auth middleware and each route's own `Require` see the caller's own `Authorization` header and cookies; no scope is widened), and (d) holds approval-class actions until the owner answers in the window.
+
+Approval classes are decided on the server, not trusted from the window: any DELETE, a last path segment of post, cancel, allocate, amend, confirm, lock or unlock, `POST /api/invites`, `/api/account/lock`; for window commands the same words in the id after the first segment plus `invites.*`, `account.lock`, `session.logout`, `app.quit`, `window.close`, `app.reload`, or the window's own `risky` flag. Blocked outright: sign-in, set-up, unlock, invitation accept, claim, app tokens, key backup, terminals, the agent routes themselves and the stream (`blockedPrefixes`), and the window commands `session.setup`, `session.login`, `session.unlock`, `invite.accept`, `account.claim`. With no window open an approval-class call is refused with `consent_needs_window`. "Always allow" is kept in memory per credential (token id, or the session's user) and class, until restart, never on disk. FormLedger sends no mail and makes no outbound request, so there is no external class.
+
+Every call or command is a job; the handler waits up to `wait` (default 15 s, at most 60) and otherwise answers the job id for `GET /api/agent/jobs/{id}`. Finished jobs are dropped after ten minutes. Answers are compacted on the server: any JSON array longer than the limit (default 50, at most 500) is cut and its full length reported under `truncated` with its JSON path, strings cut at 4000 characters, text at the limit's lines, and binary bodies replaced by their type and size. The stream sends a comment every 20 s and ends on shutdown through `Stop`, so `srv.Shutdown` does not wait on it.
+
+The direct `formledger cli` with a token is unchanged: it is the owner's own scripted path and keeps its existing role and scope checks. Writes made through `formledger cli mcp` (including its `ledger_cli` tool) go through `/api/agent/call` and so through approval, because the MCP client sets `Client.Agent`.
+
+### internal/cli/mcp.go · formledger cli mcp
+- refers-to: internal/cli/mcp.go :: mcpTools, mcpServer, viaAgent; internal/cli/cli.go :: run; internal/cli/client.go :: Do, NewClient, apiFailure
+- kind: rationale, alternative
+- logged: v0.15.2 · 2026-12-03 (EST)
+
+The MCP server is a `cli` group, not a top-level command, so it lives with the HTTP client that already holds the token handling and the one-writer rule, and `cmd/formledger/main.go` (ledger-startup's file this release) is untouched. It speaks newline-delimited JSON-RPC 2.0 on stdio, answers `initialize` (echoing the client's protocol version, with instructions), `tools/list`, `tools/call`, `ping` and empty resource and prompt lists, and runs calls concurrently so a call waiting for approval does not block a read. Tool text is cut at 24000 characters. `Run` became `(*env).run` so `ledger_cli` can run any cli command into a buffer with the agent client. Alternative not taken: a streamable HTTP `/mcp` on the server, which would need its own token handling inside the engine and would be reachable from any process on the machine without the user adding it to their agent. `NewClient` now falls back to `FORMLEDGER_ENGINE_URL`, which the dock sets in its terminals, because the desktop app may move to a free port.
+
+### internal/auth/tabtokens.go, internal/dock/module.go · a token per agent tab
+- refers-to: internal/auth/tabtokens.go :: MintTabToken, RevokeTabToken, SweepTabTokens; internal/dock/module.go :: openProgram, claudeMCP, Mount
+- kind: rationale
+- logged: v0.15.2 · 2026-12-03 (EST)
+
+The orchestrator's decision, on FormCite's precedent (its dock issues a write token per agent tab, host "FormCite dock", hashed, revocable, listed under the owner's tokens): Claude Code in the dock must work with no setup. `api_tokens` has no host column and no migration is added for one, so a tab token is marked by its name suffix `" tab, FormLedger dock"`; only tokens with that suffix can be revoked by `RevokeTabToken`, so a token the owner made by hand is never touched. The token belongs to the owner who opened the tab (the dock is owner-only and loopback-only), scope write; role checks and the approval classes still apply to everything it does. It is created and revoked in one transaction with an audit row whose actor is `FormLedger dock`. Revocation runs from the session's `onClose`, so closing the tab, closing all tabs on shutdown, or the dock's own close all withdraw it; if the server dies without closing, `SweepTabTokens` at the dock's `Mount` withdraws what is left ("left from an earlier run"). Restarting a tab keeps its token. Claude Code gets `--mcp-config` with a stdio server whose command is `os.Executable()` (the desktop sidecar is the same binary, so `cli mcp` exists there) and the token as `${FORMLEDGER_TOKEN}`, expanded by Claude Code from the tab's environment, so the secret is not in any process's argv. Codex, Cursor and Antigravity get the same environment (so `formledger cli` works) but no MCP entry yet: their config overrides were not checked against their current versions here.
diff --git a/internal/agent/call.go b/internal/agent/call.go
new file mode 100644
index 0000000..e6eb5f5
--- /dev/null
+++ b/internal/agent/call.go
@@ -0,0 +1,487 @@
+package agent
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "regexp"
+ "sort"
+ "strings"
+ "time"
+
+ "github.com/nodemode-ai/formledger/internal/httpx"
+ "github.com/nodemode-ai/formledger/internal/policy"
+)
+
+const (
+ defaultLimit = 50
+ maxLimit = 500
+ textCap = 4000
+)
+
+var (
+ blockedPrefixes = []string{"/api/auth/", "/api/setup", "/api/desktop/", "/api/account/claim", "/api/me/tokens", "/api/me/key-backed-up", "/api/terminal", "/api/agent", "/api/live"}
+ inviteAccept = regexp.MustCompile(`^/api/invites/[^/]+/accept$`)
+ blockedCommands = map[string]bool{"session.setup": true, "session.login": true, "session.unlock": true, "invite.accept": true, "account.claim": true, "tokens.create": true, "tokens.revoke": true}
+ riskyCommands = map[string]bool{"invites.create": true, "invites.revoke": true, "account.lock": true, "session.logout": true, "app.quit": true, "window.close": true, "app.reload": true}
+ riskyWords = []string{"post", "cancel", "delete", "allocate", "amend", "confirm", "lock", "unlock"}
+)
+
+var (
+ readCommands = map[string]bool{"view.current": true, "prefs.get": true, "cash.get": true, "template.use": true}
+ readPrefixes = []string{"report.", "dashboard."}
+ readLastSegments = map[string]bool{"get": true, "list": true, "openInvoices": true}
+)
+
+func readCommand(id string) bool {
+ if readCommands[id] {
+ return true
+ }
+ for _, p := range readPrefixes {
+ if strings.HasPrefix(id, p) {
+ return true
+ }
+ }
+ return readLastSegments[id[strings.LastIndex(id, ".")+1:]]
+}
+
+func blocked(path string) bool {
+ for _, p := range blockedPrefixes {
+ if strings.HasPrefix(path, p) {
+ return true
+ }
+ }
+ return inviteAccept.MatchString(path)
+}
+
+func routeClass(method, path string) string {
+ if !httpx.IsUnsafe(method) {
+ return ""
+ }
+ if method == http.MethodDelete {
+ return "delete"
+ }
+ last := path[strings.LastIndex(path, "/")+1:]
+ for _, w := range riskyWords {
+ if last == w {
+ return w
+ }
+ }
+ switch {
+ case path == "/api/invites":
+ return "invite"
+ case path == "/api/account/lock":
+ return "app lock"
+ }
+ return ""
+}
+
+func commandClass(c Command) string {
+ if riskyCommands[c.ID] {
+ return c.ID
+ }
+ parts := strings.FieldsFunc(c.ID, func(r rune) bool { return r == '.' || r == '-' })
+ for _, p := range parts[min(1, len(parts)):] {
+ for _, w := range riskyWords {
+ if strings.EqualFold(p, w) {
+ return w
+ }
+ }
+ }
+ if c.Risky {
+ return c.ID
+ }
+ return ""
+}
+
+func (m *module) routes(w http.ResponseWriter, r *http.Request, _ *policy.Principal) error {
+ type row struct {
+ Route string `json:"route"`
+ Approve string `json:"approval,omitempty"`
+ }
+ var out []row
+ text := strings.ToLower(r.URL.Query().Get("text"))
+ for _, pat := range m.router.Patterns() {
+ method, path, ok := strings.Cut(pat, " ")
+ if !ok || !strings.HasPrefix(path, "/api/") || blocked(path) {
+ continue
+ }
+ if text != "" && !strings.Contains(strings.ToLower(pat), text) {
+ continue
+ }
+ out = append(out, row{Route: pat, Approve: routeClass(method, path)})
+ }
+ sort.Slice(out, func(i, j int) bool {
+ a, b := strings.SplitN(out[i].Route, " ", 2), strings.SplitN(out[j].Route, " ", 2)
+ if a[1] != b[1] {
+ return a[1] < b[1]
+ }
+ return a[0] < b[0]
+ })
+ httpx.JSON(w, http.StatusOK, map[string]any{"routes": out, "count": len(out),
+ "note": "Call any route with POST /api/agent/call (MCP: ledger_call). Routes with an approval class wait for the owner's yes in the window. Docs: docs/ledger, docs/selling, docs/buying, docs/stock."})
+ return nil
+}
+
+type callIn struct {
+ Method string `json:"method"`
+ Path string `json:"path"`
+ Query map[string]string `json:"query"`
+ Body json.RawMessage `json:"body"`
+ Limit int `json:"limit"`
+ Wait float64 `json:"wait"`
+}
+
+func (m *module) inner() http.Handler {
+ m.once.Do(func() { m.handler = m.router.Handler() })
+ return m.handler
+}
+
+func (m *module) call(w http.ResponseWriter, r *http.Request, p *policy.Principal) error {
+ var in callIn
+ if err := httpx.Decode(r, &in); err != nil {
+ return err
+ }
+ in.Method = strings.ToUpper(strings.TrimSpace(in.Method))
+ if in.Method == "" {
+ in.Method = http.MethodGet
+ }
+ switch in.Method {
+ case http.MethodGet, http.MethodPost, http.MethodPatch, http.MethodPut, http.MethodDelete:
+ default:
+ return httpx.Fail(http.StatusBadRequest, "bad_method", "method must be GET, POST, PATCH, PUT or DELETE")
+ }
+ path := "/" + strings.TrimLeft(strings.TrimSpace(in.Path), "/")
+ if !strings.HasPrefix(path, "/api/") || strings.Contains(path, "..") || strings.ContainsAny(path, "?#") {
+ return httpx.Fail(http.StatusBadRequest, "bad_path", "path must be an /api/ route without a query string; pass query separately (see ledger_routes)")
+ }
+ if blocked(path) {
+ return httpx.Fail(http.StatusForbidden, "agent_blocked", "agents may not call "+path+": sign-in, tokens, terminals and claiming stay with the person at the window")
+ }
+ if p.ReadOnly && httpx.IsUnsafe(in.Method) {
+ return httpx.ErrReadOnly
+ }
+ limit := in.Limit
+ if limit <= 0 {
+ limit = defaultLimit
+ }
+ limit = min(limit, maxLimit)
+ q := make([]string, 0, len(in.Query))
+ for k, v := range in.Query {
+ q = append(q, k+"="+urlEscape(v))
+ }
+ sort.Strings(q)
+ target := path
+ if len(q) > 0 {
+ target += "?" + strings.Join(q, "&")
+ }
+ what := in.Method + " " + target
+ x := m.jobs.start(p.UserID, "call", what)
+ class := routeClass(in.Method, path)
+ auth, cookie, agentName, remote, host := r.Header.Get("Authorization"), r.Header.Values("Cookie"), "", r.RemoteAddr, r.Host
+ _, agentName = m.agentOf(r, p)
+ ctx := context.WithoutCancel(r.Context())
+ go func() {
+ if class != "" {
+ if err := m.ask(r.WithContext(ctx), p, x, class, what, []string{describeBody(in.Body)}); err != nil {
+ m.jobs.finish(x, deniedOr(err), nil, err.Error())
+ return
+ }
+ }
+ var body *bytes.Reader
+ if len(in.Body) > 0 && string(in.Body) != "null" {
+ body = bytes.NewReader(in.Body)
+ } else {
+ body = bytes.NewReader(nil)
+ }
+ req, err := http.NewRequestWithContext(ctx, in.Method, target, body)
+ if err != nil {
+ m.jobs.finish(x, "failed", nil, err.Error())
+ return
+ }
+ if auth != "" {
+ req.Header.Set("Authorization", auth)
+ }
+ for _, c := range cookie {
+ req.Header.Add("Cookie", c)
+ }
+ req.Header.Set("Accept", "application/json")
+ if body.Len() > 0 {
+ req.Header.Set("Content-Type", "application/json")
+ }
+ req.Header.Set(AgentHeader, agentName)
+ req.RemoteAddr, req.Host = remote, host
+ rec := httptest.NewRecorder()
+ m.inner().ServeHTTP(rec, req)
+ res := compactResponse(rec, limit)
+ if rec.Code >= 400 {
+ m.jobs.finish(x, "failed", res, fmt.Sprintf("%s answered %d", what, rec.Code))
+ return
+ }
+ m.jobs.finish(x, "done", res, "")
+ }()
+ j := m.jobs.wait(x, waitOf(r, in.Wait))
+ if j.State == "failed" && j.Result != nil {
+ httpx.JSON(w, http.StatusOK, map[string]any{"job": j.ID, "state": j.State, "what": j.What, "error": j.Error, "result": j.Result})
+ return nil
+ }
+ m.reply(w, j)
+ return nil
+}
+
+func deniedOr(err error) string {
+ var api *httpx.APIError
+ if errors.As(err, &api) && (api.Code == "consent_denied" || api.Code == "consent_timeout" || api.Code == "consent_needs_window") {
+ return "denied"
+ }
+ return "failed"
+}
+
+func describeBody(raw json.RawMessage) string {
+ s := strings.TrimSpace(string(raw))
+ if s == "" || s == "null" {
+ return "No request body."
+ }
+ return "Body: " + clip(s, 400)
+}
+
+func urlEscape(s string) string {
+ var b strings.Builder
+ for _, c := range []byte(s) {
+ if c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || c == '-' || c == '_' || c == '.' || c == '~' {
+ b.WriteByte(c)
+ continue
+ }
+ fmt.Fprintf(&b, "%%%02X", c)
+ }
+ return b.String()
+}
+
+func compactResponse(rec *httptest.ResponseRecorder, limit int) json.RawMessage {
+ ct := rec.Header().Get("Content-Type")
+ raw := rec.Body.Bytes()
+ out := map[string]any{"status": rec.Code}
+ switch {
+ case strings.Contains(ct, "json"):
+ var v any
+ if json.Unmarshal(raw, &v) == nil {
+ cut := map[string]int{}
+ out["data"] = compactValue(v, limit, "", cut)
+ if len(cut) > 0 {
+ out["truncated"] = cut
+ out["note"] = fmt.Sprintf("lists longer than %d were cut; the counts are their full lengths. Ask with a larger limit (up to %d), a filter or a cursor.", limit, maxLimit)
+ }
+ }
+ case strings.HasPrefix(ct, "text/"):
+ lines := strings.Split(string(raw), "\n")
+ keep := min(len(lines), limit+1)
+ text := strings.Join(lines[:keep], "\n")
+ out["contentType"], out["lines"], out["text"] = ct, len(lines), clip(text, textCap)
+ default:
+ out["contentType"], out["bytes"] = ct, len(raw)
+ out["note"] = "binary output is not sent to agents; save it with ./formledger cli print or export --out FILE"
+ }
+ b, _ := json.Marshal(out)
+ return b
+}
+
+func compactRaw(raw json.RawMessage, limit int) json.RawMessage {
+ if len(raw) == 0 {
+ return nil
+ }
+ var v any
+ if json.Unmarshal(raw, &v) != nil {
+ return nil
+ }
+ cut := map[string]int{}
+ v = compactValue(v, limit, "", cut)
+ if len(cut) > 0 {
+ v = map[string]any{"data": v, "truncated": cut}
+ }
+ b, _ := json.Marshal(v)
+ return b
+}
+
+func compactValue(v any, limit int, at string, cut map[string]int) any {
+ switch t := v.(type) {
+ case []any:
+ if len(t) > limit {
+ cut[strings.TrimPrefix(at, ".")+"[]"] = len(t)
+ t = t[:limit]
+ }
+ for i := range t {
+ t[i] = compactValue(t[i], limit, at, cut)
+ }
+ return t
+ case map[string]any:
+ for k, x := range t {
+ t[k] = compactValue(x, limit, at+"."+k, cut)
+ }
+ return t
+ case string:
+ return clip(t, textCap)
+ }
+ return v
+}
+
+func (m *module) commandsOf(user string) []Command {
+ m.catMu.Lock()
+ defer m.catMu.Unlock()
+ return append([]Command(nil), m.catalogue[user]...)
+}
+
+func (m *module) find(user, id string) (Command, bool) {
+ for _, c := range m.commandsOf(user) {
+ if c.ID == id {
+ return c, true
+ }
+ }
+ return Command{}, false
+}
+
+func (m *module) near(user, id string) []string {
+ word := strings.ToLower(id[strings.LastIndexAny(id, ".-")+1:])
+ var out []string
+ for _, c := range m.commandsOf(user) {
+ if word != "" && strings.Contains(strings.ToLower(c.ID), word) && len(out) < 5 {
+ out = append(out, c.ID)
+ }
+ }
+ return out
+}
+
+func (m *module) noWindow(user string) error {
+ if m.hub.windows(user) > 0 {
+ return nil
+ }
+ return httpx.Fail(http.StatusConflict, "no_window", "no FormLedger window is open for this user: open the app (./formledger, or the desktop app) and sign in, then retry. Headless work goes through ledger_call.")
+}
+
+func (m *module) listCommands(w http.ResponseWriter, r *http.Request, p *policy.Principal) error {
+ group := strings.ToLower(strings.TrimSpace(r.URL.Query().Get("group")))
+ text := strings.Fields(strings.ToLower(r.URL.Query().Get("text")))
+ type row struct {
+ ID string `json:"id"`
+ Label string `json:"label"`
+ Group string `json:"group"`
+ Args string `json:"args,omitempty"`
+ Approval string `json:"approval,omitempty"`
+ Off bool `json:"unavailable,omitempty"`
+ }
+ all := m.commandsOf(p.UserID)
+ groups := map[string]bool{}
+ var out []row
+ for _, c := range all {
+ if blockedCommands[c.ID] {
+ continue
+ }
+ groups[c.Group] = true
+ if group != "" && strings.ToLower(c.Group) != group {
+ continue
+ }
+ hay := strings.ToLower(c.ID + " " + c.Label + " " + c.Group + " " + c.Description)
+ ok := true
+ for _, t := range text {
+ ok = ok && strings.Contains(hay, t)
+ }
+ if !ok {
+ continue
+ }
+ names := make([]string, 0, len(c.Params))
+ for k := range c.Params {
+ names = append(names, k)
+ }
+ sort.Strings(names)
+ out = append(out, row{ID: c.ID, Label: c.Label, Group: c.Group, Args: strings.Join(names, ","), Approval: commandClass(c), Off: c.Enabled != nil && !*c.Enabled})
+ }
+ gl := make([]string, 0, len(groups))
+ for g := range groups {
+ gl = append(gl, g)
+ }
+ sort.Strings(gl)
+ res := map[string]any{"size": len(all), "shown": len(out), "groups": gl, "windows": m.hub.windows(p.UserID), "commands": out}
+ if len(all) == 0 {
+ res["hint"] = "the catalogue is empty: open the FormLedger window and sign in; it sends its commands within a second"
+ }
+ httpx.JSON(w, http.StatusOK, res)
+ return nil
+}
+
+func (m *module) describeCommand(w http.ResponseWriter, r *http.Request, p *policy.Principal) error {
+ id := r.PathValue("id")
+ c, ok := m.find(p.UserID, id)
+ if !ok || blockedCommands[id] {
+ return httpx.Fail(http.StatusNotFound, "no_command", "no command has the id "+id+nearText(m.near(p.UserID, id)))
+ }
+ out := map[string]any{"command": c}
+ if cl := commandClass(c); cl != "" {
+ out["approval"] = cl
+ }
+ httpx.JSON(w, http.StatusOK, out)
+ return nil
+}
+
+func nearText(ids []string) string {
+ if len(ids) == 0 {
+ return "; search with app_commands"
+ }
+ return "; did you mean " + strings.Join(ids, ", ") + "?"
+}
+
+func (m *module) runCommand(w http.ResponseWriter, r *http.Request, p *policy.Principal) error {
+ id := r.PathValue("id")
+ var in struct {
+ Params map[string]any `json:"params"`
+ Wait float64 `json:"wait"`
+ }
+ if r.ContentLength != 0 {
+ if err := httpx.Decode(r, &in); err != nil {
+ return err
+ }
+ }
+ if blockedCommands[id] {
+ return httpx.Fail(http.StatusForbidden, "agent_blocked", id+" handles a password or claims the books; it stays with the person at the window")
+ }
+ if err := m.noWindow(p.UserID); err != nil {
+ return err
+ }
+ c, ok := m.find(p.UserID, id)
+ if !ok {
+ return httpx.Fail(http.StatusNotFound, "no_command", "no command has the id "+id+nearText(m.near(p.UserID, id)))
+ }
+ if p.ReadOnly && (c.Mutates || !readCommand(id)) {
+ return httpx.Fail(http.StatusForbidden, "read_only", "this credential is read-only: "+id+" changes the books or the window; a read-only token may run only read commands such as view.current, prefs.get, lists and reports")
+ }
+ if in.Params == nil {
+ in.Params = map[string]any{}
+ }
+ what := c.Label + " (" + id + ")"
+ x := m.jobs.start(p.UserID, "command", what)
+ class := commandClass(c)
+ ctx := context.WithoutCancel(r.Context())
+ go func() {
+ if class != "" {
+ pj, _ := json.Marshal(in.Params)
+ if err := m.ask(r.WithContext(ctx), p, x, class, what, []string{"Arguments: " + clip(string(pj), 400)}); err != nil {
+ m.jobs.finish(x, deniedOr(err), nil, err.Error())
+ return
+ }
+ }
+ if !m.hub.toNewestWindow(p.UserID, "command", map[string]any{"job": x.ID, "id": id, "params": in.Params}) {
+ m.jobs.finish(x, "failed", nil, "no FormLedger window took the command; open the app and retry")
+ return
+ }
+ select {
+ case <-x.done:
+ case <-time.After(windowWait):
+ m.jobs.finish(x, "failed", nil, "the window did not answer within two minutes")
+ case <-m.quit:
+ }
+ }()
+ m.reply(w, m.jobs.wait(x, waitOf(r, in.Wait)))
+ return nil
+}
diff --git a/internal/agent/hub.go b/internal/agent/hub.go
new file mode 100644
index 0000000..fd72259
--- /dev/null
+++ b/internal/agent/hub.go
@@ -0,0 +1,107 @@
+package agent
+
+import (
+ "encoding/json"
+ "sync"
+ "time"
+)
+
+type event struct {
+ name string
+ data []byte
+}
+
+type client struct {
+ user string
+ window bool
+ since time.Time
+ ch chan event
+}
+
+type hub struct {
+ mu sync.Mutex
+ clients map[*client]struct{}
+}
+
+func newHub() *hub { return &hub{clients: map[*client]struct{}{}} }
+
+func (h *hub) join(user string, window bool) *client {
+ c := &client{user: user, window: window, since: time.Now(), ch: make(chan event, 64)}
+ h.mu.Lock()
+ h.clients[c] = struct{}{}
+ h.mu.Unlock()
+ return c
+}
+
+func (h *hub) leave(c *client) {
+ h.mu.Lock()
+ delete(h.clients, c)
+ h.mu.Unlock()
+}
+
+func encode(name string, v any) event {
+ b, _ := json.Marshal(v)
+ return event{name: name, data: b}
+}
+
+func (h *hub) broadcast(name string, v any) {
+ e := encode(name, v)
+ h.mu.Lock()
+ defer h.mu.Unlock()
+ for c := range h.clients {
+ select {
+ case c.ch <- e:
+ default:
+ }
+ }
+}
+
+func (h *hub) toUser(user, name string, v any) int {
+ e := encode(name, v)
+ h.mu.Lock()
+ defer h.mu.Unlock()
+ n := 0
+ for c := range h.clients {
+ if c.user != user || !c.window {
+ continue
+ }
+ select {
+ case c.ch <- e:
+ n++
+ default:
+ }
+ }
+ return n
+}
+
+func (h *hub) toNewestWindow(user, name string, v any) bool {
+ h.mu.Lock()
+ defer h.mu.Unlock()
+ var best *client
+ for c := range h.clients {
+ if c.user == user && c.window && (best == nil || c.since.After(best.since)) {
+ best = c
+ }
+ }
+ if best == nil {
+ return false
+ }
+ select {
+ case best.ch <- encode(name, v):
+ return true
+ default:
+ return false
+ }
+}
+
+func (h *hub) windows(user string) int {
+ h.mu.Lock()
+ defer h.mu.Unlock()
+ n := 0
+ for c := range h.clients {
+ if c.user == user && c.window {
+ n++
+ }
+ }
+ return n
+}
diff --git a/internal/agent/jobs.go b/internal/agent/jobs.go
new file mode 100644
index 0000000..b6489af
--- /dev/null
+++ b/internal/agent/jobs.go
@@ -0,0 +1,162 @@
+package agent
+
+import (
+ "encoding/json"
+ "sync"
+ "time"
+
+ "github.com/nodemode-ai/formledger/internal/ids"
+)
+
+const (
+ jobKeep = 10 * time.Minute
+ consentWait = 2 * time.Minute
+ windowWait = 2 * time.Minute
+)
+
+type job struct {
+ ID string `json:"job"`
+ Kind string `json:"kind"`
+ What string `json:"what"`
+ State string `json:"state"`
+ Result json.RawMessage `json:"result,omitempty"`
+ Error string `json:"error,omitempty"`
+ Started int64 `json:"started"`
+ Finished int64 `json:"finished,omitempty"`
+ user string
+ done chan struct{}
+}
+
+type jobs struct {
+ mu sync.Mutex
+ byID map[string]*job
+}
+
+func newJobs() *jobs { return &jobs{byID: map[string]*job{}} }
+
+func (j *jobs) start(user, kind, what string) *job {
+ x := &job{ID: "job_" + ids.New(), Kind: kind, What: what, State: "running", Started: time.Now().UnixMilli(), user: user, done: make(chan struct{})}
+ j.mu.Lock()
+ defer j.mu.Unlock()
+ for id, old := range j.byID {
+ if old.Finished > 0 && time.Since(time.UnixMilli(old.Finished)) > jobKeep {
+ delete(j.byID, id)
+ }
+ }
+ j.byID[x.ID] = x
+ return x
+}
+
+func (j *jobs) get(id, user string) *job {
+ j.mu.Lock()
+ defer j.mu.Unlock()
+ x := j.byID[id]
+ if x == nil || x.user != user {
+ return nil
+ }
+ return x
+}
+
+func (j *jobs) set(x *job, state string) {
+ j.mu.Lock()
+ defer j.mu.Unlock()
+ if x.Finished == 0 {
+ x.State = state
+ }
+}
+
+func (j *jobs) finish(x *job, state string, result json.RawMessage, err string) {
+ j.mu.Lock()
+ defer j.mu.Unlock()
+ if x.Finished > 0 {
+ return
+ }
+ x.State, x.Result, x.Error, x.Finished = state, result, err, time.Now().UnixMilli()
+ close(x.done)
+}
+
+func (j *jobs) snapshot(x *job) job {
+ j.mu.Lock()
+ defer j.mu.Unlock()
+ return job{ID: x.ID, Kind: x.Kind, What: x.What, State: x.State, Result: x.Result, Error: x.Error, Started: x.Started, Finished: x.Finished}
+}
+
+func (j *jobs) wait(x *job, d time.Duration) job {
+ select {
+ case <-x.done:
+ case <-time.After(d):
+ }
+ return j.snapshot(x)
+}
+
+type consentAsk struct {
+ ID string `json:"id"`
+ Agent string `json:"agent"`
+ What string `json:"what"`
+ Offers []string `json:"offers"`
+ Always string `json:"always"`
+ Expires int64 `json:"expires"`
+ Escape string `json:"escape"`
+ Notes []string `json:"notes,omitempty"`
+ user string
+ key string
+ answer chan string
+}
+
+type consents struct {
+ mu sync.Mutex
+ pending map[string]*consentAsk
+ allowed map[string]bool
+}
+
+func newConsents() *consents {
+ return &consents{pending: map[string]*consentAsk{}, allowed: map[string]bool{}}
+}
+
+func (c *consents) remembered(key string) bool {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ return c.allowed[key]
+}
+
+func (c *consents) open(user, key, agent, what string, notes []string) *consentAsk {
+ a := &consentAsk{ID: "consent_" + ids.New(), Agent: agent, What: what, Offers: []string{"deny", "once", "always"}, Always: "agent",
+ Expires: time.Now().Add(consentWait).UnixMilli(), Escape: "deny", Notes: notes, user: user, key: key, answer: make(chan string, 1)}
+ c.mu.Lock()
+ c.pending[a.ID] = a
+ c.mu.Unlock()
+ return a
+}
+
+func (c *consents) close(id string) {
+ c.mu.Lock()
+ delete(c.pending, id)
+ c.mu.Unlock()
+}
+
+func (c *consents) answer(id, user, choice string) bool {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ a := c.pending[id]
+ if a == nil || a.user != user {
+ return false
+ }
+ if choice == "always" {
+ c.allowed[a.key] = true
+ }
+ delete(c.pending, id)
+ a.answer <- choice
+ return true
+}
+
+func (c *consents) mine(user string) []*consentAsk {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ var out []*consentAsk
+ for _, a := range c.pending {
+ if a.user == user {
+ out = append(out, a)
+ }
+ }
+ return out
+}
diff --git a/internal/agent/module.go b/internal/agent/module.go
new file mode 100644
index 0000000..3374018
--- /dev/null
+++ b/internal/agent/module.go
@@ -0,0 +1,369 @@
+package agent
+
+import (
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "net/url"
+ "sort"
+ "strings"
+ "sync"
+ "time"
+
+ "github.com/nodemode-ai/formledger/internal/app"
+ "github.com/nodemode-ai/formledger/internal/auth"
+ "github.com/nodemode-ai/formledger/internal/httpx"
+ "github.com/nodemode-ai/formledger/internal/policy"
+)
+
+const (
+ AgentHeader = "X-FormLedger-Agent"
+ WindowHeader = "X-FormLedger-Window"
+ keepAlive = 20 * time.Second
+)
+
+type module struct {
+ auth *auth.Service
+ hub *hub
+ jobs *jobs
+ consent *consents
+ router *httpx.Router
+ once sync.Once
+ handler http.Handler
+ quit chan struct{}
+ stopOnce sync.Once
+ catMu sync.Mutex
+ catalogue map[string][]Command
+}
+
+type Command struct {
+ ID string `json:"id"`
+ Label string `json:"label"`
+ Group string `json:"group"`
+ Description string `json:"description,omitempty"`
+ When string `json:"when,omitempty"`
+ Keys []string `json:"keys,omitempty"`
+ Params map[string]json.RawMessage `json:"params,omitempty"`
+ Mutates bool `json:"mutates"`
+ Risky bool `json:"risky,omitempty"`
+ Enabled *bool `json:"enabled,omitempty"`
+}
+
+func Module(a *auth.Service) app.Module {
+ return &module{auth: a, hub: newHub(), jobs: newJobs(), consent: newConsents(), quit: make(chan struct{}), catalogue: map[string][]Command{}}
+}
+
+func (m *module) ID() string { return "agent" }
+
+func (m *module) Stop() { m.stopOnce.Do(func() { close(m.quit) }) }
+
+func (m *module) Mount(r *httpx.Router, _ *app.Deps) error {
+ m.router = r
+ r.Use(m.changes)
+ r.HandleFunc("GET /api/live", m.auth.Session(m.live))
+ r.HandleFunc("POST /api/agent/window/catalogue", m.auth.Session(m.windowOnly(m.putCatalogue)))
+ r.HandleFunc("POST /api/agent/window/result", m.auth.Session(m.windowOnly(m.putResult)))
+ r.HandleFunc("POST /api/agent/consent/{id}", m.auth.Session(m.windowOnly(m.answer)))
+ r.HandleFunc("GET /api/agent", m.auth.Public(m.signed(m.overview)))
+ r.HandleFunc("GET /api/agent/routes", m.auth.Public(m.signed(m.routes)))
+ r.HandleFunc("POST /api/agent/call", m.auth.Public(m.signed(m.call)))
+ r.HandleFunc("GET /api/agent/commands", m.auth.Public(m.signed(m.listCommands)))
+ r.HandleFunc("GET /api/agent/commands/{id}", m.auth.Public(m.signed(m.describeCommand)))
+ r.HandleFunc("POST /api/agent/commands/{id}", m.auth.Public(m.signed(m.runCommand)))
+ r.HandleFunc("GET /api/agent/jobs/{id}", m.auth.Public(m.signed(m.jobStatus)))
+ return nil
+}
+
+func (m *module) signed(h auth.PrincipalHandler) auth.Handler {
+ return func(w http.ResponseWriter, r *http.Request) error {
+ p := auth.PrincipalFrom(r.Context())
+ if p == nil {
+ return httpx.ErrUnauthorized
+ }
+ return h(w, r, p)
+ }
+}
+
+func (m *module) windowOnly(h auth.PrincipalHandler) auth.PrincipalHandler {
+ return func(w http.ResponseWriter, r *http.Request, p *policy.Principal) error {
+ if o := r.Header.Get("Origin"); o != "" {
+ u, err := url.Parse(o)
+ if err != nil || !strings.EqualFold(u.Host, r.Host) {
+ return httpx.Fail(http.StatusForbidden, "window_only", "only the FormLedger window may answer here")
+ }
+ }
+ return h(w, r, p)
+ }
+}
+
+type statusWriter struct {
+ http.ResponseWriter
+ code int
+}
+
+func (s *statusWriter) WriteHeader(code int) {
+ if s.code == 0 {
+ s.code = code
+ }
+ s.ResponseWriter.WriteHeader(code)
+}
+
+func (s *statusWriter) Write(b []byte) (int, error) {
+ if s.code == 0 {
+ s.code = http.StatusOK
+ }
+ return s.ResponseWriter.Write(b)
+}
+
+func (s *statusWriter) Unwrap() http.ResponseWriter { return s.ResponseWriter }
+
+var quietPrefixes = []string{"/api/live", "/api/agent/", "/api/terminal", "/api/auth/", "/api/me/key-backed-up"}
+
+func quiet(path string) bool {
+ for _, p := range quietPrefixes {
+ if strings.HasPrefix(path, p) {
+ return true
+ }
+ }
+ return false
+}
+
+func (m *module) changes(next http.Handler) http.Handler {
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if !httpx.IsUnsafe(r.Method) || !strings.HasPrefix(r.URL.Path, "/api/") || quiet(r.URL.Path) {
+ next.ServeHTTP(w, r)
+ return
+ }
+ sw := &statusWriter{ResponseWriter: w}
+ next.ServeHTTP(sw, r)
+ if sw.code >= 400 {
+ return
+ }
+ by := "window"
+ if p := auth.PrincipalFrom(r.Context()); p != nil && p.AppToken {
+ by = "token"
+ }
+ if r.Header.Get(AgentHeader) != "" {
+ by = "agent"
+ }
+ m.hub.broadcast("change", map[string]any{"method": r.Method, "path": r.URL.Path, "area": area(r.URL.Path), "by": by,
+ "agent": clip(r.Header.Get(AgentHeader), 80), "window": clip(r.Header.Get(WindowHeader), 64), "at": time.Now().UnixMilli()})
+ })
+}
+
+func area(path string) string {
+ parts := strings.Split(strings.TrimPrefix(path, "/api/"), "/")
+ if len(parts) > 1 && (parts[0] == "sales" || parts[0] == "purchase" || parts[0] == "stock" || parts[0] == "delivery" || parts[0] == "reports") {
+ return parts[0] + "/" + parts[1]
+ }
+ return parts[0]
+}
+
+func clip(s string, n int) string {
+ if len(s) > n {
+ return s[:n]
+ }
+ return s
+}
+
+func (m *module) live(w http.ResponseWriter, r *http.Request, p *policy.Principal) error {
+ rc := http.NewResponseController(w)
+ h := w.Header()
+ h.Set("Content-Type", "text/event-stream")
+ h.Set("Cache-Control", "no-store")
+ h.Set("X-Accel-Buffering", "no")
+ w.WriteHeader(http.StatusOK)
+ window := r.URL.Query().Get("window") == "1"
+ c := m.hub.join(p.UserID, window)
+ defer m.hub.leave(c)
+ send := func(e event) bool {
+ if _, err := fmt.Fprintf(w, "event: %s\ndata: %s\n\n", e.name, e.data); err != nil {
+ return false
+ }
+ return rc.Flush() == nil
+ }
+ if !send(encode("hello", map[string]any{"window": window, "windows": m.hub.windows(p.UserID)})) {
+ return nil
+ }
+ if window {
+ for _, a := range m.consent.mine(p.UserID) {
+ if !send(encode("consent", a)) {
+ return nil
+ }
+ }
+ }
+ tick := time.NewTicker(keepAlive)
+ defer tick.Stop()
+ for {
+ select {
+ case <-r.Context().Done():
+ return nil
+ case <-m.quit:
+ return nil
+ case <-tick.C:
+ if _, err := fmt.Fprint(w, ": keep-alive\n\n"); err != nil || rc.Flush() != nil {
+ return nil
+ }
+ case e := <-c.ch:
+ if !send(e) {
+ return nil
+ }
+ }
+ }
+}
+
+func (m *module) putCatalogue(w http.ResponseWriter, r *http.Request, p *policy.Principal) error {
+ var in struct {
+ Commands []Command `json:"commands"`
+ }
+ if err := httpx.Decode(r, &in); err != nil {
+ return err
+ }
+ sort.Slice(in.Commands, func(i, j int) bool { return in.Commands[i].ID < in.Commands[j].ID })
+ m.catMu.Lock()
+ m.catalogue[p.UserID] = in.Commands
+ m.catMu.Unlock()
+ httpx.JSON(w, http.StatusOK, map[string]any{"ok": true, "size": len(in.Commands)})
+ return nil
+}
+
+func (m *module) putResult(w http.ResponseWriter, r *http.Request, p *policy.Principal) error {
+ var in struct {
+ Job string `json:"job"`
+ OK bool `json:"ok"`
+ Result json.RawMessage `json:"result"`
+ Error string `json:"error"`
+ }
+ if err := httpx.Decode(r, &in); err != nil {
+ return err
+ }
+ x := m.jobs.get(in.Job, p.UserID)
+ if x == nil {
+ return httpx.Fail(http.StatusNotFound, "job_gone", "no such job")
+ }
+ if in.OK {
+ m.jobs.finish(x, "done", compactRaw(in.Result, defaultLimit), "")
+ } else {
+ m.jobs.finish(x, "failed", nil, clip(in.Error, 2000))
+ }
+ httpx.JSON(w, http.StatusOK, map[string]bool{"ok": true})
+ return nil
+}
+
+func (m *module) answer(w http.ResponseWriter, r *http.Request, p *policy.Principal) error {
+ var in struct {
+ Choice string `json:"choice"`
+ }
+ if err := httpx.Decode(r, &in); err != nil {
+ return err
+ }
+ if in.Choice != "deny" && in.Choice != "once" && in.Choice != "always" {
+ return httpx.Fail(http.StatusBadRequest, "bad_choice", "choice must be deny, once or always")
+ }
+ if !m.consent.answer(r.PathValue("id"), p.UserID, in.Choice) {
+ return httpx.Fail(http.StatusNotFound, "consent_gone", "this request is no longer waiting")
+ }
+ m.hub.toUser(p.UserID, "consent-closed", map[string]string{"id": r.PathValue("id")})
+ httpx.JSON(w, http.StatusOK, map[string]bool{"ok": true})
+ return nil
+}
+
+func (m *module) agentOf(r *http.Request, p *policy.Principal) (key, name string) {
+ a := m.auth.Actor(r, p)
+ key = a.Kind + ":" + a.ID
+ if a.Kind != "app_token" {
+ key = "session:" + p.UserID
+ }
+ name = strings.TrimSpace(r.Header.Get(AgentHeader))
+ switch {
+ case name != "" && a.Kind == "app_token":
+ name = clip(name, 60) + " (app token " + a.Name + ")"
+ case name == "" && a.Kind == "app_token":
+ name = "App token " + a.Name
+ case name == "":
+ name = "An agent"
+ }
+ return key, name
+}
+
+func (m *module) ask(r *http.Request, p *policy.Principal, x *job, class, what string, notes []string) error {
+ key, name := m.agentOf(r, p)
+ key += "|" + class
+ if m.consent.remembered(key) {
+ return nil
+ }
+ if m.hub.windows(p.UserID) == 0 {
+ return httpx.Fail(http.StatusConflict, "consent_needs_window", "this action needs the owner's approval in the FormLedger window, and no window is open for this user: open FormLedger, then retry")
+ }
+ notes = append(notes, "Always allow covers "+class+" actions from this agent's credential until FormLedger restarts.")
+ a := m.consent.open(p.UserID, key, name, what, notes)
+ m.jobs.set(x, "waiting_consent")
+ m.hub.toUser(p.UserID, "consent", a)
+ select {
+ case choice := <-a.answer:
+ if choice == "deny" {
+ return httpx.Fail(http.StatusForbidden, "consent_denied", "the person at the FormLedger window said no to: "+what)
+ }
+ m.jobs.set(x, "running")
+ return nil
+ case <-time.After(consentWait):
+ m.consent.close(a.ID)
+ m.hub.toUser(p.UserID, "consent-closed", map[string]string{"id": a.ID})
+ return httpx.Fail(http.StatusRequestTimeout, "consent_timeout", "nobody answered the approval request in the FormLedger window within two minutes: "+what)
+ case <-m.quit:
+ return httpx.Fail(http.StatusServiceUnavailable, "stopping", "FormLedger is stopping")
+ }
+}
+
+func waitOf(r *http.Request, asked float64) time.Duration {
+ s := asked
+ if q := r.URL.Query().Get("wait"); q != "" {
+ fmt.Sscanf(q, "%g", &s)
+ }
+ if s <= 0 {
+ s = 15
+ }
+ if s > 60 {
+ s = 60
+ }
+ return time.Duration(s * float64(time.Second))
+}
+
+func (m *module) reply(w http.ResponseWriter, j job) {
+ out := map[string]any{"job": j.ID, "state": j.State, "what": j.What}
+ switch j.State {
+ case "done":
+ out["result"] = j.Result
+ case "failed", "denied":
+ out["error"] = j.Error
+ default:
+ out["hint"] = "still " + strings.ReplaceAll(j.State, "_", " ") + "; poll GET /api/agent/jobs/" + j.ID + "?wait=30 (MCP: job_status)"
+ }
+ httpx.JSON(w, http.StatusOK, out)
+}
+
+func (m *module) jobStatus(w http.ResponseWriter, r *http.Request, p *policy.Principal) error {
+ x := m.jobs.get(r.PathValue("id"), p.UserID)
+ if x == nil {
+ return httpx.Fail(http.StatusNotFound, "job_gone", "no such job, or it finished more than ten minutes ago")
+ }
+ d := time.Duration(0)
+ if r.URL.Query().Get("wait") != "" {
+ d = waitOf(r, 0)
+ }
+ m.reply(w, m.jobs.wait(x, d))
+ return nil
+}
+
+func (m *module) overview(w http.ResponseWriter, r *http.Request, p *policy.Principal) error {
+ m.catMu.Lock()
+ n := len(m.catalogue[p.UserID])
+ m.catMu.Unlock()
+ httpx.JSON(w, http.StatusOK, map[string]any{
+ "user": p.Email, "role": p.Role, "readOnly": p.ReadOnly, "windows": m.hub.windows(p.UserID), "commands": n,
+ "read": []string{"GET /api/agent/routes", "GET /api/agent/commands?text=word", "GET /api/agent/commands/{id}", "GET /api/agent/jobs/{id}"},
+ "write": []string{"POST /api/agent/call {method, path, query, body, limit}", "POST /api/agent/commands/{id} {params, wait}"},
+ "rules": "Money-moving, destructive and people actions wait for the owner's approval in the open window. Results are compact: lists over the limit are cut and counted. Long work answers a job id to poll.",
+ })
+ return nil
+}
diff --git a/internal/app/version.go b/internal/app/version.go
index bf7d754..dd10787 100644
--- a/internal/app/version.go
+++ b/internal/app/version.go
@@ -1,5 +1,5 @@
package app
-var Version = "v0.15.1"
+var Version = "v0.16.0"
const Product = "FormLedger"
diff --git a/internal/auth/tabtokens.go b/internal/auth/tabtokens.go
new file mode 100644
index 0000000..00037e6
--- /dev/null
+++ b/internal/auth/tabtokens.go
@@ -0,0 +1,62 @@
+package auth
+
+import (
+ "context"
+ "database/sql"
+ "strings"
+
+ "github.com/nodemode-ai/formledger/internal/audit"
+ "github.com/nodemode-ai/formledger/internal/ids"
+ "github.com/nodemode-ai/formledger/internal/secrets"
+ "github.com/nodemode-ai/formledger/internal/store"
+)
+
+const TabTokenSuffix = " tab, FormLedger dock"
+
+var dockActor = audit.Anonymous("FormLedger dock")
+
+func (s *Service) MintTabToken(ctx context.Context, userID, program string) (id, plain string, err error) {
+ name := strings.TrimSpace(program) + TabTokenSuffix
+ plain = secrets.Token(TokenPrefix, 32)
+ id = ids.New()
+ prefix := plain[:len(TokenPrefix)+6]
+ err = s.st.Tx(ctx, func(tx *sql.Tx) error {
+ if _, err := tx.ExecContext(ctx, `INSERT INTO api_tokens (id, user_id, name, token_hash, prefix, scope, created_at) VALUES (?, ?, ?, ?, ?, ?, ?)`,
+ id, userID, name, secrets.Hash(plain), prefix, "write", store.NowMS()); err != nil {
+ return err
+ }
+ return s.audit.Record(ctx, tx, audit.Entry{Actor: dockActor, Action: "token.create", ObjectKind: "api_token", ObjectID: id,
+ Detail: map[string]any{"name": name, "scope": "write", "prefix": prefix, "user": userID}})
+ })
+ return id, plain, err
+}
+
+func (s *Service) RevokeTabToken(ctx context.Context, id string) { s.revokeTab(ctx, id, "tab closed") }
+
+func (s *Service) revokeTab(ctx context.Context, id, why string) {
+ _ = s.st.Tx(ctx, func(tx *sql.Tx) error {
+ var name string
+ if err := tx.QueryRowContext(ctx, "DELETE FROM api_tokens WHERE id = ? AND name LIKE ? RETURNING name", id, "%"+TabTokenSuffix).Scan(&name); err != nil {
+ return err
+ }
+ return s.audit.Record(ctx, tx, audit.Entry{Actor: dockActor, Action: "token.revoke", ObjectKind: "api_token", ObjectID: id, Detail: map[string]any{"name": name, "why": why}})
+ })
+}
+
+func (s *Service) SweepTabTokens(ctx context.Context) {
+ rows, err := s.st.R.QueryContext(ctx, "SELECT id FROM api_tokens WHERE name LIKE ?", "%"+TabTokenSuffix)
+ if err != nil {
+ return
+ }
+ var stale []string
+ for rows.Next() {
+ var id string
+ if rows.Scan(&id) == nil {
+ stale = append(stale, id)
+ }
+ }
+ rows.Close()
+ for _, id := range stale {
+ s.revokeTab(ctx, id, "left from an earlier run")
+ }
+}
diff --git a/internal/cli/cli.go b/internal/cli/cli.go
index 60c0f85..7df65fe 100644
--- a/internal/cli/cli.go
+++ b/internal/cli/cli.go
@@ -57,11 +57,16 @@ func groups() []group {
{"statement", "profit and loss and the balance sheet", statementVerbs()},
{"whoami", "the user and role behind the app token", []verb{whoamiVerb()}},
{"token", "how to make an app token", []verb{tokenVerb()}},
+ {"mcp", "an MCP server on standard input and output for Claude Code, Codex, Cursor and other agents", []verb{mcpVerb()}},
}
}
func Run(args []string, out, errw io.Writer) int {
- e := &env{out: out, errw: errw}
+ return (&env{out: out, errw: errw}).run(args)
+}
+
+func (e *env) run(args []string) int {
+ out, errw := e.out, e.errw
if len(args) == 0 || isHelp(args[0]) || args[0] == "help" {
usage(out)
return 0
diff --git a/internal/cli/client.go b/internal/cli/client.go
index 747acf4..6cf1a61 100644
--- a/internal/cli/client.go
+++ b/internal/cli/client.go
@@ -23,6 +23,7 @@ type Client struct {
Base string
Token string
HTTP *http.Client
+ Agent string
}
type userError struct{ msg string }
@@ -33,6 +34,9 @@ func plain(format string, a ...any) error { return &userError{fmt.Sprintf(format
func NewClient(tokenFile string) (*Client, error) {
base := strings.TrimRight(strings.TrimSpace(os.Getenv(URLEnv)), "/")
+ if base == "" {
+ base = strings.TrimRight(strings.TrimSpace(os.Getenv("FORMLEDGER_ENGINE_URL")), "/")
+ }
if base == "" {
base = DefaultURL
}
@@ -51,6 +55,13 @@ func NewClient(tokenFile string) (*Client, error) {
}
func (c *Client) Do(method, path string, q url.Values, body any) (json.RawMessage, error) {
+ if c.Agent != "" && method != http.MethodGet && method != http.MethodHead {
+ return c.viaAgent(method, path, q, body)
+ }
+ return c.direct(method, path, q, body)
+}
+
+func (c *Client) direct(method, path string, q url.Values, body any) (json.RawMessage, error) {
u := c.Base + path
if len(q) > 0 {
u += "?" + q.Encode()
@@ -69,6 +80,9 @@ func (c *Client) Do(method, path string, q url.Values, body any) (json.RawMessag
}
req.Header.Set("Authorization", "Bearer "+c.Token)
req.Header.Set("Accept", "application/json")
+ if c.Agent != "" {
+ req.Header.Set("X-FormLedger-Agent", c.Agent)
+ }
if body != nil {
req.Header.Set("Content-Type", "application/json")
}
@@ -107,6 +121,8 @@ func apiFailure(status int, method, path string, raw []byte) error {
return plain("the server refused the app token; check %s or the token file, or make a new token under Account", TokenEnv)
case status == http.StatusForbidden && code == "read_only":
return plain("this app token is read-only, so it may not change anything")
+ case code == "agent_blocked" || strings.HasPrefix(code, "consent_") || code == "no_window" || code == "no_command":
+ return plain("%s", msg)
case status == http.StatusForbidden && code == "session_only":
return plain("this needs a signed-in browser session; an app token may not do it")
case status == http.StatusForbidden:
diff --git a/internal/cli/mcp.go b/internal/cli/mcp.go
new file mode 100644
index 0000000..698169f
--- /dev/null
+++ b/internal/cli/mcp.go
@@ -0,0 +1,370 @@
+package cli
+
+import (
+ "bufio"
+ "bytes"
+ "encoding/json"
+ "fmt"
+ "io"
+ "net/http"
+ "net/url"
+ "os"
+ "strings"
+ "sync"
+
+ "github.com/nodemode-ai/formledger/internal/app"
+ "github.com/nodemode-ai/formledger/internal/export"
+ "github.com/nodemode-ai/formledger/internal/printout"
+)
+
+const (
+ mcpProtocol = "2025-06-18"
+ mcpTextCap = 24000
+ AgentEnv = "FORMLEDGER_AGENT"
+)
+
+const mcpInstructions = `FormLedger is a local-first business ledger: selling, buying, stock, the general ledger and reports. This server is a client of the running FormLedger server with your app token (FORMLEDGER_TOKEN); it never opens the database.
+
+Two ways in, same rules:
+- Headless, over the books: ledger_routes lists every engine route; ledger_get reads one; ledger_call writes; ledger_cli runs any "formledger cli" command (accounts, customers, sales, invoice, payment, purchase, bill, pay, receipt, delivery, stock, report, statement, receivables, payables). Money is whole minor units plus a currency code; never send a float.
+- The open window: app_commands lists every command of the FormLedger window (menus, buttons, pages, Preferences) with typed arguments; app_command describes one; app_run runs it in the window. view.open moves the window to any page or document, view.current says what is on screen.
+
+Posting, cancelling, allocating, amending, confirming, deleting, period locks, invitations and the app lock wait for the owner to say yes in the FormLedger window (Deny, Allow once, Always allow for this agent). Without an open window they are refused, so ask the person to open FormLedger. Sign-in, passwords, tokens, terminals and claiming the books are never reachable from here.
+
+Every change shows live in the open window. Results are compact: lists longer than the limit are cut and their full length is reported; pass limit (up to 500), a filter or a cursor for more. Anything slower than the wait (default 15 s) answers a job id; poll it with job_status.`
+
+type mcpTool struct {
+ Name string `json:"name"`
+ Title string `json:"title,omitempty"`
+ Description string `json:"description"`
+ InputSchema map[string]any `json:"inputSchema"`
+ Annotations map[string]any `json:"annotations,omitempty"`
+}
+
+func obj(props map[string]any, required ...string) map[string]any {
+ s := map[string]any{"type": "object", "properties": props, "additionalProperties": false}
+ if len(required) > 0 {
+ s["required"] = required
+ }
+ return s
+}
+
+func prop(kind, desc string) map[string]any { return map[string]any{"type": kind, "description": desc} }
+
+func hints(read, destructive bool) map[string]any {
+ return map[string]any{"readOnlyHint": read, "destructiveHint": destructive, "openWorldHint": false}
+}
+
+var (
+ limitProp = prop("integer", "Cut lists to this many rows (default 50, at most 500); the full length is reported.")
+ waitProp = prop("number", "Seconds to wait before answering a job id instead (default 15, at most 60).")
+ queryProp = map[string]any{"type": "object", "description": "Query parameters, for example {\"status\":\"draft\",\"from\":\"2026-01-01\"}.", "additionalProperties": map[string]any{"type": "string"}}
+)
+
+func mcpTools() []mcpTool {
+ return []mcpTool{
+ {Name: "ledger_overview", Title: "Who and what", Description: "The user and role behind the token, whether it is read-only, how many FormLedger windows are open and how many window commands they offer.", InputSchema: obj(map[string]any{}), Annotations: hints(true, false)},
+ {Name: "ledger_routes", Title: "Engine routes", Description: "Every engine route an agent may call, with the approval class of those that wait for the owner (post, cancel, delete, allocate, amend, confirm, lock, invite, app lock).", InputSchema: obj(map[string]any{"text": prop("string", "Only routes containing this text, for example 'sales' or 'payments'.")}), Annotations: hints(true, false)},
+ {Name: "ledger_get", Title: "Read the books", Description: "GET one engine route, for example /api/sales/docs with query {\"kind\":\"invoice\",\"status\":\"posted\"}, /api/reports/trial-balance or /api/customers/{id}. Compact JSON.", InputSchema: obj(map[string]any{"path": prop("string", "An /api/ path from ledger_routes, with ids filled in."), "query": queryProp, "limit": limitProp}, "path"), Annotations: hints(true, false)},
+ {Name: "ledger_call", Title: "Change the books", Description: "POST, PATCH, PUT or DELETE one engine route with a JSON body. Drafts and master data change at once; posting, cancelling, allocating, amending, confirming, deleting, period locks and invitations wait for the owner's yes in the window. Answers the result, or a job id while it waits.", InputSchema: obj(map[string]any{"method": map[string]any{"type": "string", "enum": []string{"POST", "PATCH", "PUT", "DELETE"}}, "path": prop("string", "An /api/ path from ledger_routes."), "query": queryProp, "body": map[string]any{"type": "object", "description": "The JSON body. Money is integer minor units."}, "limit": limitProp, "wait": waitProp}, "method", "path"), Annotations: hints(false, true)},
+ {Name: "ledger_cli", Title: "Run a cli command", Description: "Run one 'formledger cli' command, for example [\"sales\",\"list\",\"--kind\",\"invoice\"], [\"report\",\"trial-balance\"] or [\"invoice\",\"post\",\"SINV-0001\"]. [\"help\"] or [GROUP,\"help\"] lists them. Writes go through the same approval as ledger_call.", InputSchema: obj(map[string]any{"args": map[string]any{"type": "array", "items": map[string]any{"type": "string"}, "description": "The words after 'formledger cli'."}}, "args"), Annotations: hints(false, true)},
+ {Name: "ledger_export", Title: "Export CSV to a file", Description: "Write one export (any list or report) as CSV to a file on this computer, the same bytes as File, Export CSV. Names: " + strings.Join(export.Names(), ", ") + ".", InputSchema: obj(map[string]any{"name": prop("string", "The export name."), "out": prop("string", "Absolute path of the CSV file to write."), "query": queryProp}, "name", "out"), Annotations: hints(false, false)},
+ {Name: "ledger_print", Title: "Print a document to PDF", Description: "Write a quote, order, invoice, purchase document or statement as a PDF file on this computer, the same as the Print button.", InputSchema: obj(map[string]any{"kind": prop("string", "Document kind, for example invoice, quote, order, purchase-order, purchase-invoice, goods-receipt, or statement."), "number": prop("string", "The document number (or the customer for a statement)."), "out": prop("string", "Absolute path of the PDF file to write.")}, "kind", "number", "out"), Annotations: hints(false, false)},
+ {Name: "app_commands", Title: "Window commands", Description: "List the FormLedger window's commands: every menu item, button, page action and Preference, with argument names and approval class. Needs the window open.", InputSchema: obj(map[string]any{"text": prop("string", "Words that must all appear in the id, label or group."), "group": prop("string", "Only this group, for example Navigation, Sales, Payments, Preferences.")}), Annotations: hints(true, false)},
+ {Name: "app_command", Title: "Describe a window command", Description: "One window command with its typed arguments (type, required, enum, min, max).", InputSchema: obj(map[string]any{"id": prop("string", "The command id from app_commands.")}, "id"), Annotations: hints(true, false)},
+ {Name: "app_run", Title: "Run a window command", Description: "Run one command in the open FormLedger window, as if the person clicked it, and answer its compact result. Approval-class commands wait for the owner's yes.", InputSchema: obj(map[string]any{"id": prop("string", "The command id."), "params": map[string]any{"type": "object", "description": "The command's arguments."}, "wait": waitProp}, "id"), Annotations: hints(false, true)},
+ {Name: "job_status", Title: "Poll a job", Description: "The state of a job id answered by ledger_call, ledger_get or app_run: running, waiting_consent, done (with result), failed or denied.", InputSchema: obj(map[string]any{"job": prop("string", "The job id."), "wait": waitProp}, "job"), Annotations: hints(true, false)},
+ }
+}
+
+type rpcIn struct {
+ JSONRPC string `json:"jsonrpc"`
+ ID json.RawMessage `json:"id,omitempty"`
+ Method string `json:"method"`
+ Params json.RawMessage `json:"params,omitempty"`
+}
+
+type mcpServer struct {
+ tokenFile string
+ agent string
+ mu sync.Mutex
+ out io.Writer
+ client *Client
+}
+
+func mcpVerb() verb {
+ return verb{"mcp", "", "serve MCP on standard input and output; add it to Claude Code with: claude mcp add formledger -e FORMLEDGER_TOKEN=... -- /path/to/formledger cli mcp", func(e *env, args []string) error {
+ if _, err := e.parse(e.flags("mcp"), args, 0, 0); err != nil {
+ return err
+ }
+ agent := strings.TrimSpace(os.Getenv(AgentEnv))
+ if agent == "" {
+ agent = "MCP agent"
+ }
+ s := &mcpServer{tokenFile: e.tokenFile, agent: agent, out: e.out}
+ return s.serve(os.Stdin)
+ }}
+}
+
+func (s *mcpServer) serve(in io.Reader) error {
+ sc := bufio.NewScanner(in)
+ sc.Buffer(make([]byte, 0, 1<<16), 16<<20)
+ var wg sync.WaitGroup
+ for sc.Scan() {
+ line := bytes.TrimSpace(sc.Bytes())
+ if len(line) == 0 {
+ continue
+ }
+ var msg rpcIn
+ if err := json.Unmarshal(line, &msg); err != nil {
+ s.send(map[string]any{"jsonrpc": "2.0", "id": nil, "error": map[string]any{"code": -32700, "message": "parse error"}})
+ continue
+ }
+ if len(msg.ID) == 0 {
+ continue
+ }
+ wg.Add(1)
+ go func(m rpcIn) {
+ defer wg.Done()
+ s.handle(m)
+ }(msg)
+ }
+ wg.Wait()
+ return sc.Err()
+}
+
+func (s *mcpServer) send(v any) {
+ b, _ := json.Marshal(v)
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ _, _ = s.out.Write(append(b, '\n'))
+}
+
+func (s *mcpServer) handle(m rpcIn) {
+ reply := func(result any) { s.send(map[string]any{"jsonrpc": "2.0", "id": m.ID, "result": result}) }
+ switch m.Method {
+ case "initialize":
+ var p struct {
+ ProtocolVersion string `json:"protocolVersion"`
+ }
+ _ = json.Unmarshal(m.Params, &p)
+ version := mcpProtocol
+ if p.ProtocolVersion != "" {
+ version = p.ProtocolVersion
+ }
+ reply(map[string]any{"protocolVersion": version, "capabilities": map[string]any{"tools": map[string]any{"listChanged": false}},
+ "serverInfo": map[string]any{"name": "formledger", "title": "FormLedger", "version": app.Version}, "instructions": mcpInstructions})
+ case "ping":
+ reply(map[string]any{})
+ case "tools/list":
+ reply(map[string]any{"tools": mcpTools()})
+ case "resources/list":
+ reply(map[string]any{"resources": []any{}})
+ case "prompts/list":
+ reply(map[string]any{"prompts": []any{}})
+ case "tools/call":
+ var p struct {
+ Name string `json:"name"`
+ Arguments map[string]any `json:"arguments"`
+ }
+ if err := json.Unmarshal(m.Params, &p); err != nil {
+ s.send(map[string]any{"jsonrpc": "2.0", "id": m.ID, "error": map[string]any{"code": -32602, "message": "bad params"}})
+ return
+ }
+ text, err := s.tool(p.Name, p.Arguments)
+ if err != nil {
+ reply(map[string]any{"content": []any{map[string]any{"type": "text", "text": err.Error()}}, "isError": true})
+ return
+ }
+ reply(map[string]any{"content": []any{map[string]any{"type": "text", "text": capText(text)}}})
+ default:
+ s.send(map[string]any{"jsonrpc": "2.0", "id": m.ID, "error": map[string]any{"code": -32601, "message": "method not found: " + m.Method}})
+ }
+}
+
+func capText(s string) string {
+ if len(s) <= mcpTextCap {
+ return s
+ }
+ return s[:mcpTextCap] + fmt.Sprintf("\n[cut at %d of %d characters; narrow the request or lower the limit]", mcpTextCap, len(s))
+}
+
+func (s *mcpServer) api() (*Client, error) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ if s.client != nil {
+ return s.client, nil
+ }
+ c, err := NewClient(s.tokenFile)
+ if err != nil {
+ return nil, err
+ }
+ c.Agent = s.agent
+ s.client = c
+ return c, nil
+}
+
+func sArg(a map[string]any, k string) string {
+ v, _ := a[k].(string)
+ return strings.TrimSpace(v)
+}
+
+func queryArg(a map[string]any) url.Values {
+ q := url.Values{}
+ if m, ok := a["query"].(map[string]any); ok {
+ for k, v := range m {
+ q.Set(k, fmt.Sprint(v))
+ }
+ }
+ return q
+}
+
+func waitQuery(a map[string]any) url.Values {
+ q := url.Values{}
+ if w, ok := a["wait"].(float64); ok && w > 0 {
+ q.Set("wait", fmt.Sprint(w))
+ }
+ return q
+}
+
+func (s *mcpServer) tool(name string, a map[string]any) (string, error) {
+ if a == nil {
+ a = map[string]any{}
+ }
+ c, err := s.api()
+ if err != nil {
+ return "", err
+ }
+ raw := func(r json.RawMessage, err error) (string, error) {
+ if err != nil {
+ return "", err
+ }
+ return string(r), nil
+ }
+ switch name {
+ case "ledger_overview":
+ return raw(c.direct(http.MethodGet, "/api/agent", nil, nil))
+ case "ledger_routes":
+ q := url.Values{}
+ if t := sArg(a, "text"); t != "" {
+ q.Set("text", t)
+ }
+ return raw(c.direct(http.MethodGet, "/api/agent/routes", q, nil))
+ case "ledger_get", "ledger_call":
+ method := http.MethodGet
+ if name == "ledger_call" {
+ method = strings.ToUpper(sArg(a, "method"))
+ if method == "" || method == http.MethodGet {
+ return "", plain("ledger_call changes the books; use ledger_get to read")
+ }
+ }
+ query := map[string]string{}
+ for k, v := range queryArg(a) {
+ query[k] = v[0]
+ }
+ body := map[string]any{"method": method, "path": sArg(a, "path"), "query": query, "limit": a["limit"], "wait": a["wait"]}
+ if b, ok := a["body"]; ok {
+ body["body"] = b
+ }
+ return raw(c.direct(http.MethodPost, "/api/agent/call", nil, body))
+ case "ledger_cli":
+ var args []string
+ if xs, ok := a["args"].([]any); ok {
+ for _, x := range xs {
+ args = append(args, fmt.Sprint(x))
+ }
+ }
+ if len(args) > 0 && args[0] == "mcp" {
+ return "", plain("the mcp command is this server")
+ }
+ var out, errw bytes.Buffer
+ e := &env{out: &out, errw: &errw, client: c}
+ code := e.run(args)
+ text := strings.TrimSpace(out.String())
+ if code != 0 {
+ return "", plain("%s", strings.TrimSpace(errw.String()+"\n"+text))
+ }
+ return text, nil
+ case "ledger_export":
+ args := []string{sArg(a, "name"), "--out", sArg(a, "out")}
+ for k, v := range queryArg(a) {
+ args = append(args, "--"+k, v[0])
+ }
+ if s.tokenFile != "" {
+ args = append(args, "--token-file", s.tokenFile)
+ }
+ if err := export.Command(args, io.Discard); err != nil {
+ return "", err
+ }
+ return fmt.Sprintf(`{"ok":true,"wrote":%q}`, sArg(a, "out")), nil
+ case "ledger_print":
+ args := []string{sArg(a, "kind"), sArg(a, "number"), "--out", sArg(a, "out")}
+ if s.tokenFile != "" {
+ args = append(args, "--token-file", s.tokenFile)
+ }
+ if err := printout.Command(args, io.Discard); err != nil {
+ return "", err
+ }
+ return fmt.Sprintf(`{"ok":true,"wrote":%q}`, sArg(a, "out")), nil
+ case "app_commands":
+ q := url.Values{}
+ for _, k := range []string{"text", "group"} {
+ if v := sArg(a, k); v != "" {
+ q.Set(k, v)
+ }
+ }
+ return raw(c.direct(http.MethodGet, "/api/agent/commands", q, nil))
+ case "app_command":
+ return raw(c.direct(http.MethodGet, "/api/agent/commands/"+url.PathEscape(sArg(a, "id")), nil, nil))
+ case "app_run":
+ params, _ := a["params"].(map[string]any)
+ return raw(c.direct(http.MethodPost, "/api/agent/commands/"+url.PathEscape(sArg(a, "id")), nil, map[string]any{"params": params, "wait": a["wait"]}))
+ case "job_status":
+ return raw(c.direct(http.MethodGet, "/api/agent/jobs/"+url.PathEscape(sArg(a, "job")), waitQuery(a), nil))
+ }
+ return "", plain("no tool named %s", name)
+}
+
+func (c *Client) viaAgent(method, path string, q url.Values, body any) (json.RawMessage, error) {
+ query := map[string]string{}
+ for k, v := range q {
+ if len(v) > 0 {
+ query[k] = v[0]
+ }
+ }
+ in := map[string]any{"method": method, "path": path, "query": query, "limit": 500, "wait": 60}
+ if body != nil {
+ in["body"] = body
+ }
+ raw, err := c.direct(http.MethodPost, "/api/agent/call", nil, in)
+ if err != nil {
+ return nil, err
+ }
+ var j struct {
+ Job string `json:"job"`
+ State string `json:"state"`
+ Error string `json:"error"`
+ Result struct {
+ Status int `json:"status"`
+ Data json.RawMessage `json:"data"`
+ } `json:"result"`
+ }
+ if err := json.Unmarshal(raw, &j); err != nil {
+ return nil, plain("the server's answer to %s %s was not understood", method, path)
+ }
+ switch j.State {
+ case "done":
+ if len(j.Result.Data) == 0 {
+ return json.RawMessage("{}"), nil
+ }
+ return j.Result.Data, nil
+ case "failed":
+ if j.Result.Status >= 400 {
+ return nil, apiFailure(j.Result.Status, method, path, j.Result.Data)
+ }
+ return nil, plain("%s", j.Error)
+ case "denied":
+ return nil, plain("%s", j.Error)
+ }
+ return nil, plain("%s %s is waiting for the owner's approval in the FormLedger window; poll job %s with job_status", method, path, j.Job)
+}
diff --git a/internal/dock/module.go b/internal/dock/module.go
index ea8cd4a..60ed540 100644
--- a/internal/dock/module.go
+++ b/internal/dock/module.go
@@ -1,6 +1,7 @@
package dock
import (
+ "context"
"encoding/json"
"net/http"
"os"
@@ -10,6 +11,7 @@ import (
"github.com/nodemode-ai/formledger/internal/app"
"github.com/nodemode-ai/formledger/internal/auth"
+ "github.com/nodemode-ai/formledger/internal/config"
"github.com/nodemode-ai/formledger/internal/httpx"
"github.com/nodemode-ai/formledger/internal/policy"
)
@@ -35,6 +37,7 @@ func (m *module) Stop() { m.reg.closeAll() }
func (m *module) Mount(r *httpx.Router, d *app.Deps) error {
m.dataDir = d.Config.DataDir
+ m.auth.SweepTabTokens(context.Background())
g := func(h auth.PrincipalHandler) http.HandlerFunc { return guard(m.auth, h) }
r.HandleFunc("GET /api/terminal", g(m.list))
r.HandleFunc("POST /api/terminal", g(m.openShell))
@@ -121,15 +124,50 @@ func (m *module) openProgram(w http.ResponseWriter, r *http.Request, p *policy.P
m.status.mu.Unlock()
return errMissing(prog)
}
+ ctx := context.WithoutCancel(r.Context())
+ tokenID, token, err := m.auth.MintTabToken(ctx, p.UserID, prog.title)
+ if err != nil {
+ return err
+ }
+ url := engineURL(r)
+ if prog.kind == "claude" {
+ args = append(claudeMCP(url), args...)
+ }
argv := append([]string{st.path}, args...)
- s, err := m.reg.add(p.UserID, prog.kind, prog.title, launch{argv: argv, env: childEnv(engineURL(r), st.path), dir: m.workdir()}, cols, rows)
+ env := append(childEnv(url, st.path), config.EnvPrefix+"URL="+url, config.EnvPrefix+"TOKEN="+token, config.EnvPrefix+"AGENT="+prog.title)
+ s, err := m.reg.add(p.UserID, prog.kind, prog.title, launch{argv: argv, env: env, dir: m.workdir()}, cols, rows)
if err != nil {
+ m.auth.RevokeTabToken(ctx, tokenID)
return err
}
+ revoke := func() { m.auth.RevokeTabToken(context.Background(), tokenID) }
+ s.mu.Lock()
+ closed := s.closed
+ if !closed {
+ s.onClose = append(s.onClose, revoke)
+ }
+ s.mu.Unlock()
+ if closed {
+ revoke()
+ }
httpx.JSON(w, http.StatusOK, s.describe())
return nil
}
+const tabNote = "You are running inside FormLedger's agent dock. FormLedger's MCP server is connected as formledger: use its tools to read and change the person's books and to drive the open FormLedger window. Posting, cancelling, deleting and similar actions wait for the owner's approval in the window."
+
+func claudeMCP(url string) []string {
+ exe, err := os.Executable()
+ if err != nil {
+ return nil
+ }
+ cfg, _ := json.Marshal(map[string]any{"mcpServers": map[string]any{"formledger": map[string]any{
+ "type": "stdio", "command": exe, "args": []string{"cli", "mcp"},
+ "env": map[string]string{config.EnvPrefix + "URL": url, config.EnvPrefix + "TOKEN": "${" + config.EnvPrefix + "TOKEN}", config.EnvPrefix + "AGENT": "Claude Code"},
+ }}})
+ return []string{"--mcp-config", string(cfg), "--append-system-prompt", tabNote}
+}
+
func (m *module) openClaude(w http.ResponseWriter, r *http.Request, p *policy.Principal) error {
b := struct {
Cols int `json:"cols"`
diff --git a/internal/server/server.go b/internal/server/server.go
index 56d0ebc..a787ed5 100644
--- a/internal/server/server.go
+++ b/internal/server/server.go
@@ -5,6 +5,7 @@ import (
"io/fs"
"log/slog"
+ "github.com/nodemode-ai/formledger/internal/agent"
"github.com/nodemode-ai/formledger/internal/app"
"github.com/nodemode-ai/formledger/internal/auditapi"
"github.com/nodemode-ai/formledger/internal/auth"
@@ -55,6 +56,7 @@ func Build(ctx context.Context, cfg config.Config, log *slog.Logger, st *store.S
s.Modules = []app.Module{
health{},
accounts.Module(),
+ agent.Module(accounts),
auditapi.Module(accounts.Audit(), accounts),
billing.Module(st, accounts),
coa.Module(st, accounts),
diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock
index f1800c4..f190825 100644
--- a/src-tauri/Cargo.lock
+++ b/src-tauri/Cargo.lock
@@ -1106,7 +1106,7 @@ dependencies = [
[[package]]
name = "formledger-desktop"
-version = "0.15.1"
+version = "0.16.0"
dependencies = [
"objc2",
"objc2-app-kit",
diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml
index 66e35df..6d92cbb 100644
--- a/src-tauri/Cargo.toml
+++ b/src-tauri/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "formledger-desktop"
-version = "0.15.1"
+version = "0.16.0"
description = "FormLedger desktop app"
authors = ["NodeAgentc, Inc."]
license = "Apache-2.0"
diff --git a/src-tauri/HASHOUT_LOG.md b/src-tauri/HASHOUT_LOG.md
index c51d0e8..34ac465 100644
--- a/src-tauri/HASHOUT_LOG.md
+++ b/src-tauri/HASHOUT_LOG.md
@@ -2,7 +2,7 @@
Living log of all comment content, explainers, rationale, TODOs, & removed (hashed-out) code for the Tauri 2 desktop shell (`src-tauri`). Source files stay comment-free per dev-rules `sub-skills/hashout-log/SUB-SKILL.md`; everything they would have said lives here, indexed. This file is also the compressed contextual map of the shell: read it first, then edit code surgically.
-Current build version: v0.15.1
+Current build version: v0.16.0
Last updated: 2026-11-26 (US Eastern) · the shell ported from form.md's src-tauri and renamed for FormLedger
---
@@ -373,3 +373,12 @@ Removed: `let window = WebviewWindowBuilder::new(handle, "main", WebviewUrl::Ext
- logged: v0.15.1 · 2026-12-01 (EST)
`menu::build` is the macOS menu bar from launch until the page has built its own from `web/src/ui/menus.ts` (`MENUS`, through `NativeMenus.build` and `setAsAppMenu`), and the one left if that build fails. It lacked three items the page's list has: FormLedger > Account (`cmd:nav.account`), View > Agent Dock (`cmd:view.dock`, Cmd+J) and View > Menus in Window (`cmd:view.menus-in-window`). They are added in the page's order and run through `window.__formledgerRun` like every other `cmd:` item. Menus in Window is a plain item here, not a check item, because the shell cannot read the page's `localStorage` choice; the page's menu, which replaces this one, shows the check. Checked with `cargo check` on Linux. The page's own build was checked in a stand-in macOS shell: 7 menus (FormLedger, File, Edit, View, Go, Window, Help), the 5 Go submenus, 55 command items and the predefined items, set as the app menu once.
+
+### src/reveal.rs · FALLBACK from 20 s to 6 s
+- refers-to: src/reveal.rs :: FALLBACK, conceal, show_main
+- kind: rationale
+- logged: v0.15.2 · 2026-12-03 (EST)
+
+The owner: "formledger takes 30 seconds JUST TO open" (macOS, 0.15.1). In 0.15.1 the page never invoked `app_ready` (see `web/HASHOUT_LOG.md`, revealApp), so this fallback was what showed the window, 20 s after the engine's ready line, behind the splash. With the invoke back the window shows at the later of 2.6 s after launch (`SPLASH_MIN`, kept, shared with the other Form apps) and the page's paint plus 220 ms for the bar. The fallback is now a safety net only, cut to 6 s so a future break of the invoke costs 6 s, not 20; the window is built with the dark `BACKGROUND`, so a page still loading shows that colour. The spawn path itself was read and needs no change: the sidecar is a native Go binary in `Contents/MacOS` (Tauri `externalBin`), not a onefile archive to unpack, and the shell waits on the ready line, not a poll. The rest of the owner's 30 s (20 s fallback plus engine start well under 1 s plus the 2.6 s splash floor leaves about 7 s) is most likely macOS's own first-launch assessment of a quarantined app and its sidecar (Gatekeeper, syspolicyd, translocation), which depends on FormCompiler's signing and notarisation, outside this repo (`tauri.conf.json` sets `hardenedRuntime` and an empty entitlements file; no signing identity here). Verified: `cargo check` on Linux. Not verified: a macOS build and launch.
+
+Removed: `const FALLBACK: Duration = Duration::from_secs(20);`
diff --git a/src-tauri/src/reveal.rs b/src-tauri/src/reveal.rs
index 1e18b4c..6d14efc 100644
--- a/src-tauri/src/reveal.rs
+++ b/src-tauri/src/reveal.rs
@@ -7,7 +7,7 @@ use tauri::{Manager, Runtime, WebviewWindow};
pub const SPLASH_MIN: Duration = Duration::from_millis(2600);
pub const BACKGROUND: tauri::window::Color = tauri::window::Color(10, 10, 10, 255);
const BAR_FINISH: Duration = Duration::from_millis(220);
-const FALLBACK: Duration = Duration::from_secs(20);
+const FALLBACK: Duration = Duration::from_secs(6);
static LAUNCH: OnceLock