diff --git a/AGENTS.md b/AGENTS.md index 6df4302..18de76f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -20,8 +20,8 @@ Node 22 (`/opt/studio/bin/node`; `node:sqlite` needs 22.13 or later). The server export PATH=/opt/studio/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin unset NODE_ENV # with NODE_ENV=production npm skips esbuild npm --prefix extension ci && npm --prefix extension run build # release.build (writes extension/dist and the two ZIPs) -npm test # release.test: server 154, runner 139, extension 78, e2e helpers 12 -npm run harness # extension UI harness: 53 groups in Chromium, 53 in Firefox +npm test # release.test: server 166, runner 143, extension 84, e2e helpers 12 +npm run harness # extension UI harness: 59 groups in Chromium, 59 in Firefox node deploy/caddy.check.mjs # the proxy rules with a real Caddy ``` diff --git a/CHANGELOG.md b/CHANGELOG.md index a63a375..abf0287 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,23 @@ The headings are versions of the contract (`docs/protocol.md`). The extension ha ## [Unreleased] +## [3.5] - 2026-11-14 + +Extension 0.6.0. + +### Added + +- Go back: a closed pin with a live fix has a "Go back" button in its card. You choose the version: the page before the pin, or the page after an earlier fix. `POST /api/pins/:id/revert { commit }` (users only) queues the pin with `revert`; the runner starts one revert run (lean, the project card, effort high with one retry counted from the request) that undoes the commits newest first, ships the old version and closes the pin. +- The pin JSON has `versions` (the live fix commits, oldest first), `revert` and `revertedAt`. The first open of an older database reads the versions from the `Done: ()` replies. +- `pins show` and `pins_get` print `versions:`, `go back:` and `reverted:`; `pins list` marks a go back. The element verdict has a revert rule: the element came back, went away or changed. +- Extension: the card shows "Going back" and "Reverted"; the run toast says "Going back #12"; the done toast says "Back to the earlier version · #12"; the Log chip says "Going back" or "Reverted". + +### Fixed + +- A resolve or a dismiss with a 4000-character summary or reason failed with 400, because its reply went over 4000 characters. The reply text is now cut; the commit stays. +- `pins ship` stopped at `git add` when a listed file was deleted and the deletion was staged already (`git revert`, `git rm`). +- Extension: a clipped text in the UI no longer ends with half an emoji. + ## [3.4] - 2026-11-14 Extension 0.5.0. The first public release. diff --git a/PLAN.md b/PLAN.md index 0df42b8..3962e88 100644 --- a/PLAN.md +++ b/PLAN.md @@ -1,5 +1,5 @@ # Plan -Current version: v3.4.0 (2026-11-14, the first public release; the units run `/srv/hub/pins`) +Current version: v3.5.0 (2026-11-14, Go back on each pin; the units run `/srv/hub/pins`) Goal: not recorded ## Next release: v1.0.0 @@ -21,4 +21,5 @@ Goal: not recorded - Adopt the project contract release (`proj release kog-pins prod`): back up `pins.db`, move the data to the release folder, give the service user what the runner needs, point the `pins` wrapper at the release, create the env file, then release and check. Until then the command must not run (source: `AGENTS.md` "Release"; the unit template headers in `deploy/units`) ## Done +- v3.5.0 (2026-11-14): Go back. A closed pin with a live fix returns the page to the version before the pin or after an earlier fix (order: "add a reverse button to the previous version on each pin ... full solid"). - v3.4.0 (2026-11-14): OnSpot (was Kog Pins), first public release at https://github.com/jstadev/onspot. diff --git a/README.md b/README.md index 9ebe4a9..7d28a56 100644 --- a/README.md +++ b/README.md @@ -30,6 +30,8 @@ The contract between all parts is [`docs/protocol.md`](docs/protocol.md). If the +--------------------------------------------------+ ``` +Each closed pin keeps the commits of its fixes. **Go back** in the pin card starts a revert run: you choose the version (the page before the pin, or after an earlier fix), the session undoes the later commits, ships the old version and closes the pin. + | Part | Path | What it does | |---|---|---| | Extension | `extension/` | MV3 extension for Chrome and Firefox. The content script draws the picker, the note popup, the markers and the cards. The background script does all network and reads the live stream. | @@ -65,7 +67,7 @@ In a second shell: export PINS_PORT=4751 PINS_AGENT=demo curl -s http://127.0.0.1:4751/api/health -# {"ok":true,"version":"0.1.0","extension":"0.5.0","open":{"queued":0,"working":0,"waiting":0}} +# {"ok":true,"version":"0.1.0","extension":"0.6.0","open":{"queued":0,"working":0,"waiting":0}} # Create a pin as a user (no X-Pins-Agent header). The extension does this for you. curl -s -X POST http://127.0.0.1:4751/api/pins -H 'Content-Type: application/json' \ @@ -171,9 +173,9 @@ To report a problem, read [`SECURITY.md`](SECURITY.md). ```sh npm --prefix extension ci # one time: the extension tests run the build -npm test # server 154, runner 139, extension 78, e2e helpers 12 tests +npm test # server 166, runner 143, extension 84, e2e helpers 12 tests node deploy/caddy.check.mjs # the proxy rules against a real Caddy (needs the caddy binary) -npm run harness # the extension UI: 53 groups in Chromium and 53 in Firefox +npm run harness # the extension UI: 59 groups in Chromium and 59 in Firefox ``` - The tests use an in-memory store, ports that the system picks and temp folders. They send nothing to a running server. @@ -211,7 +213,7 @@ OnSpot runs in one deployment today. These parts are tied to it. - **Prompt text.** The prompt names tools and paths of the current host: `maestro session`, `/root/triad/bin/triad delegate`, worktrees under `/srv/work`, `https://ai.koglabs.com/dev` (`runner/src/prompt.js`). - **`pins ship`.** It needs `deploy/project.json` in the target project and the command `proj release staging`. `proj` is not in this repo. Without them the command says "ship by hand". - **The "before" shot.** The runner starts it with `/usr/bin/systemd-run` (`runner/src/index.js`). -- **Versions.** The contract is at v3.4 and the extension at 0.5.0. The server and the runner report 0.1.0. +- **Versions.** The contract is at v3.5 and the extension at 0.6.0. The server and the runner report 0.1.0. - **Firefox.** The add-on is not signed. ## Licence diff --git a/docs/protocol.md b/docs/protocol.md index 1c013ac..eecc408 100644 --- a/docs/protocol.md +++ b/docs/protocol.md @@ -1,4 +1,4 @@ -# OnSpot: contract v3.4 +# OnSpot: contract v3.5 OnSpot puts feedback pins on any `koglabs.com` page. A pin names an element and holds a note. Agents read the queue, take a pin, fix it, and resolve it with the commit. This file is @@ -37,6 +37,13 @@ The storage keys `kog-pins:*`, the deep link `#kog-pin=` and both extension installed extension keeps its data and old links still work. A pin that names Fable or Haiku runs its session on that model. The e2e SSO cookie code is not in the repository (`E2E_LOGIN`). +v3.5 (2026-11-14, order of the Chairman: *"add a reverse button to the previous version on each pin. make it +full solid. ill click the pin and ill choose to go back to the previous version i had on that pin"*): each +pin keeps the list of its live fix commits (`versions`). **Go back** on a closed pin with a live fix queues a +revert run (`POST /api/pins/:id/revert { commit }`, users only). He chooses the version: before the pin, or +after an earlier fix. The runner starts one session that undoes the chosen commits, newest first, ships the +old version and closes the pin. Extension 0.6.0 has the Go back button and the version choice in the card. + 2026-11-12 (order of the Chairman, on the model limit of Triad: *"remove it now from everywhere"*): Triad accepts every model name (triad #46), so a pin that names Fable or Haiku runs its session on that model. The detour through an Opus session and `maestro session` (`delegateTo`) is gone. @@ -88,6 +95,9 @@ The extension has one dev dependency, `esbuild`. Do not add dependencies. "shots": { "before": "2026-10-17T14:01:10.000Z", "after": null }, "acceptedAt": null, "reopens": 0, + "versions": [{ "commit": "a1b2c3d4e5f6", "summary": "Title margin 48px to 24px", "at": "2026-10-17T14:05:00.000Z" }], + "revert": null, + "revertedAt": null, "replyCount": 0, "createdAt": "2026-10-17T14:00:00.000Z", "updatedAt": "2026-10-17T14:00:00.000Z", @@ -123,6 +133,20 @@ The extension has one dev dependency, `esbuild`. Do not add dependencies. - `reopens` counts how many times **he** sent the pin back: a user reply with `reopen: true`, a user reply on a `waiting` pin, or `reopen` by a user. A reopen by an agent (the runner's retry) does not count. Pins created before the v3.1 schema hold `null` (unknown); new pins start at 0. +- `versions` (v3.5) holds the live fix commits of this pin, oldest first: `{ commit, summary, at }` + (`at` is the time of the resolve; `summary` clipped to 300 characters). Each `resolve` with a `commit` of + 7 to 40 hex characters (a git sha) adds one entry, except the resolve of a revert run and a commit that + is in the list already. Another `commit` (a PR link, "n/a") is kept on the pin but is no version. A completed revert removes the entries that it undid. The list keeps the newest 30. + Version 0 is the page before the pin; version k is the page after `versions[k-1]`; the last entry is + the version that is live now. A pin with no entry has nothing to go back to. On the first open of a + v3.5 store, each pin gets its entries from its own `Done: ()` replies (the commit is + 7 to 40 hex characters), oldest first. +- `revert` (v3.5) is the go back that he asked for and that is not complete, else `null`: + `{ commits: ["", ...], at, attempts }`. `commits` holds the commits to undo, newest first (always + the newest entries of `versions`). `at` is the time of the request. `attempts` is the `attempts` of the + pin at the request, so `attempts` minus this value is the number of revert runs. +- `revertedAt` (v3.5) is the time when the latest revert run closed the pin, else `null`. A requeue + clears it, so a `done` pin with `revertedAt` shows the result of a go back. - `url` has no fragment. `host` is `URL.host` in lower case. `path` is `URL.pathname`. - `targets` holds 1 to 10 elements. The first one is the primary element. - `quote` is the text the user selected on the page, or `null`. @@ -185,6 +209,16 @@ They belong to the current run: `start` deletes the steps of the earlier run. | ask | queued, working | waiting | adds reply `` (kind of the actor); keeps `agent` and `run` | | reopen | working, waiting, done, dismissed | queued | clears `agent`, `summary`, `commit`, `run`, `startedAt`, `closedAt`, `acceptedAt`; `reopens` + 1 when the actor is a user (and `reopens` is not `null`) | | accept | done | done | users only (an agent gets 403); sets `acceptedAt` once; a second accept returns 200 and changes nothing; emits `pin` `updated` | +| revert | done, dismissed | queued | users only (an agent gets 403); `commit` (required, 400 when missing) must be the `commit` of an entry of `versions` (else 409; 409 also when `versions` is empty); sets `revert` to that entry and every later entry, newest first; same clearing as reopen, also `revertedAt`; `reopens` + 1; adds the user reply `Go back to : undo .` (`` is `the version before this pin` or `fix ()`) | + +`resolve` of a pin with `revert` (the revert run) removes the `revert.commits` from `versions`, clears +`revert`, sets `revertedAt` and adds the reply `Reverted: ()` instead of `Done: ...`; its +commit is not a new version. `resolve` of any other pin adds its `commit` to `versions`. `dismiss` clears +`revert` (the go back is cancelled; the fix stays live). A reopen and a user reply that requeues keep +`revert`: the next run is a revert run again. + +The reply that `resolve` and `dismiss` write fits 4000 characters: a long summary or reason is cut, the +commit stays (v3.5; a summary of 4000 characters gave 400 before). `resolve` and `dismiss` also accept `waiting`. A **user** reply on a `waiting` pin reopens it (status `queued`, same clearing as reopen) in the same transaction, so the auto-fix runner @@ -242,8 +276,9 @@ store.setShot(id, kind, { type, bytes }) // -> Pin | null; kind "before"| store.getShot(id, kind) // -> { type, bytes } | null store.pruneShots({ olderThanDays: 30 }) // -> number of files removed store.updateNote(id, note) // -> Pin | null -store.transition(id, "start"|"resolve"|"dismiss"|"ask"|"reopen"|"accept", { agent, summary, commit, reason, question, run, model, kind, author }) // -> Pin | null, throws ConflictError / ValidationError - // kind "user"|"agent" decides the reopens count and the accept guard +store.transition(id, "start"|"resolve"|"dismiss"|"ask"|"reopen"|"accept"|"revert", { agent, summary, commit, reason, question, run, model, kind, author }) // -> Pin | null, throws ConflictError / ValidationError / ForbiddenError + // kind "user"|"agent" decides the reopens count and the accept and revert guards + // revert: commit = the first fix to undo (it and every later fix) store.deletePin(id) // -> boolean store.addReply(id, { kind, author, body, reopen }) // -> Reply | null store.listReplies(id) // -> Reply[] oldest first @@ -311,6 +346,7 @@ Every browser request passes the hub SSO (admin) in Caddy first. Caddy adds `X-S | POST | `/api/pins/:id/ask` | `{ question }` | 200 `{ pin }` | | POST | `/api/pins/:id/reopen` | `{}` | 200 `{ pin }` | | POST | `/api/pins/:id/accept` | `{}` (users only, else 403; pin `done`, else 409) | 200 `{ pin }` | +| POST | `/api/pins/:id/revert` | `{ commit }` (users only, else 403; pin `done` or `dismissed` and `commit` in `versions`, else 409) | 200 `{ pin }` | | POST | `/api/pins/:id/replies` | `{ body, reopen? }` | 201 `{ reply, pin }` | | GET | `/api/settings` | | 200 Settings | | PATCH | `/api/settings` | `{ autofix?, bulk?: { on?, delegate?, agents? } }` | 200 Settings | @@ -404,8 +440,12 @@ shots: before 14:01 url: https://crete.koglabs.com/pricing?x=1 ``` -The `about`, `presets`, `steps` and `shots` lines appear only when they have content. The list -format adds ` · ` after the label when `intent` is set. In the list and detail formats +The detail format also has, after `batch`: `versions: · ...` (oldest first), +`go back: undo , ` while `revert` is set and `reverted: ` when `revertedAt` +is set. +The `about`, `presets`, `steps`, `shots`, `versions`, `go back` and `reverted` lines appear only when they +have content. The list format adds ` · ` after the label when `intent` is set, and ` · go back` +while `revert` is set. In the list and detail formats every run of whitespace or control characters in a value is one space. ## CLI `pins` (`server/bin/pins.js`) @@ -460,8 +500,11 @@ verdict of `judge(intent, before, after)` (`server/src/facts.js`): | `style` | a style or the size changed | `check: the look did not change` | | `layout` | size, position, display, margin, padding or gap changed | `check: position and size did not change` | | none, `behaviour`, `task` | the element is gone, or text, style or size changed | `check: nothing changed on the pinned element` | +| revert (v3.5: the pin has `revert` or `revertedAt`) | the element came back, went away, or its text, style or size changed | `check: the element did not change back` | -A pass reads `#12 check: changed style, size (color, font)` or `#12 check: the element is gone`. +A pass reads `#12 check: changed style, size (color, font)` or `#12 check: the element is gone`. In a +revert, an element that the "before" shot did not find and the "after" shot finds passes as +`check: the element is back`. With no "before" facts, or when only the position moved and the pin has no intent, the verdict is open (`ok: null`): `check: no before facts (...)`, `check: only the position moved`. The verdict text holds kinds and property names only, never a value from the page. `pins done` prints a negative @@ -494,6 +537,9 @@ squash-merge the PR; `proj release staging`; take the "after" shot and jud stale when the process ends. A wait over 4 minutes ends with exit code 3. - It is safe to run again: a merged PR resumes at the release, and a gate that passed for the same commit does not run twice. +- A listed path whose deletion is staged already (after `git revert --no-commit` or `git rm`: it is in no + worktree and no index) is not given to `git add`; the commit takes it. A listed path that is in no + worktree, no index and no commit stops the commit step with the git error (v3.5). - It refuses the paths `.env*`, `*.key`, `*.pem`, `*secret*`, `.git`, `.github/workflows/**` and `infra/**` in any letter case, a path through a link, a folder, a branch named `main` or `master`, and a tracked file that changed but is not in the list. @@ -550,7 +596,8 @@ One-shot, `ext.runtime.sendMessage(msg)` returns a promise: 401 -> `{ ok: false, status: 401, ... }` and the background state becomes `login`. The background accepts only paths that match `API_PATH_RE`, at most 2048 characters, and for each path only the methods of its route: `health` and `stats` GET; `batches` POST; `settings` GET and - PATCH; `pins` GET and POST; `pins/` GET, PATCH and DELETE; `pins//` POST. A GET + PATCH; `pins` GET and POST; `pins/` GET, PATCH and DELETE; `pins//` POST (the actions +`start`, `resolve`, `dismiss`, `reopen`, `replies`, `accept` and, since 0.6.0, `revert`). A GET with a body is `{ ok: false, status: 400, error: "invalid body" }`. A body over 512 KiB as JSON text is `{ ok: false, status: 413, data: null, error: "body too large" }`. A redirect counts as a 401. On a status 0 answer the content script does not set the connection state by itself. It @@ -688,7 +735,9 @@ them in one request; the fix run starts at once. comes back from the page cache. A change in another tab of the host arrives through `storage.onChanged`. 8. **Toasts** (bottom-left; top on narrow screens; at most 3) for live changes only: a run - starts ("Fixing #12 · Opus 5.5 high", then its latest progress step, updated live), a pin is done (summary, **See it**, Open), a + starts ("Fixing #12 · Opus 5.5 high", then its latest progress step, updated live; a revert run says + "Going back #12 · Opus 5.5 high"), a pin is done (summary, **See it**, Open; after a revert run the + title is "Back to the earlier version · #12"), a question arrives (the question, Answer), a pin is dismissed. A toast closes when its pin changes status or is deleted, its card opens, or the pin is marked seen. After a refetch a toast closes when its pin is gone or has another status. @@ -703,13 +752,30 @@ them in one request; the fix run starts at once. or waiting: Dismiss, Reopen, Delete; a reply on a waiting pin requeues it. Done: See it, **Looks good** (sends `POST /api/pins/:id/accept`, then marks the pin seen; it marks it seen also when the call fails), **Not right** (opens "What is still wrong?"; sending posts the reply - with `reopen: true`, so the pin is fixed again at the next effort) and Delete. Delete has an - inline confirm. A done card of an accepted pin shows "Accepted" next to the status. + with `reopen: true`, so the pin is fixed again at the next effort), **Go back** (below) and Delete. + Delete has an inline confirm. A done card of an accepted pin shows "Accepted" next to the status. + **Go back** (0.6.0) shows on a `done` or `dismissed` card whose pin has at least one entry in + `versions` and no `revert`; title "Go back to an earlier version of this element". It opens an inline + panel (it closes the "Not right" box and the Delete confirm, and they close it): the line "Now: fix + · · " (only when `versions` holds 2 or more entries; summary clipped to 80 + characters), then the question "Go back to which version?" with one radio button per earlier version, + newest first: "After fix · · " for each entry but the last, and last "Before this + pin (the page before any fix)". With one entry there is no choice: the panel says "Go back to the page + before this pin? An agent undoes and ships the old version." The default choice is "Before + this pin". The buttons are **Go back** (it sends `POST /api/pins/:id/revert { commit }`, `commit` = the + entry right after the chosen version: `versions[0]` for "Before this pin", `versions[k]` for "After fix + k") and **Keep** (closes the panel). Esc closes the panel and keeps the card. While the call runs the + Go back button is disabled; an error shows in the card and keeps the panel open. On success the card + shows the new state (queued). + A card whose pin has `revert` shows "Going back" next to the status and hides Edit; its other buttons + follow the status (Dismiss cancels the go back; the fix stays live). A `done` card with `revertedAt` + shows "Reverted" next to the status. The short sha is the first 7 characters of the commit. A card whose pin does not load shows the reason and the status "Not loaded". 11. **Log.** A panel at the top right (full width on narrow screens): "Not sent" with Submit all, then the sent pins of this host grouped by batch, newest first, with "2/3 done", a status chip, the note, element and path, and the summary and short commit, the question, or the - latest progress step of a working pin. Rows open their pin (or their page). It loads `GET /api/pins?host=&status=all&limit=100` + latest progress step of a working pin. A pin with `revert` has the chip text "Going back"; a done + pin with `revertedAt` has "Reverted". Rows open their pin (or their page). It loads `GET /api/pins?host=&status=all&limit=100` and updates live. The footer links to the Triad Pins tab. A screen reader reads each row itself (status, number, note, element, detail); the title of the row is "Open pin 12". When the Log closes by Esc, its close button or the shortcut, the focus goes to the Log button if the menu is @@ -1014,10 +1080,29 @@ code, writes git state or deploys. A Claude session does that, under the standin say that it closes the pin and that its output is the live check (no second look at the live page). The lean line follows the model line. Without brief, shot and profile the prompt is the v3.1 text. +16. **Revert run** (v3.5). A queued pin with `revert` starts its own run, also with bulk mode on (it never + joins a bulk run). Label `Pin #12 · Go back: · Opus 5.5 high`. The model rule of item 6 holds, + but the runs count from the request: the effort uses `attempts - revert.attempts` in place of + `attempts`, and so does the retry of item 10 (one retry at the next effort, then `ask`). The start is + lean (`profile: "pin"`; with `PINS_RUNNER_LEAN=0` the full start). The runner reads no history and no + siblings; the brief gives the project card only (no source hints). The harness takes the "before" + shot (item 13): it shows the page with the fix. The prompt (`buildRevertPrompt`) holds, in this order: + who he is and that he pressed Go back on the pin; the model and lean lines; the commits to undo, + newest first (short sha, fix number, date, summary, fenced as agent text); the version he goes back + to ("the page before this pin" or "the page after fix <k> (<short sha>)"); his words (note, About, + thread) as context; the `<page-data>` block and its rule; the project line and card; how to work: own + worktree `/srv/work/<repo>-pin<id>` from origin/main, `git revert --no-commit <sha>` for each commit + newest first (fetch first when git does not know it; a commit that is undone already is skipped; when + a later commit changed the same lines, keep the later work and remove only the change of this pin), + 2 to 4 progress steps, the ship (with `ship` true: `pins ship <id> --dir <worktree> --message "Revert + pin #<id>: ..." --summary "..." <every changed file, also deleted ones>`; else the project ship and + `pins done <id> --summary ... --commit <sha>`), ask only when a commit cannot be found or the undo + would remove other work, never dismiss (if the old version is live already, `pins done` without a + commit), and the hard end state. ### Bulk mode (runner, while `settings.bulk.on` is `true`) -1. **Grouping.** The queued pins of one `batch` form one bulk run, due at once (the server writes a whole +1. **Grouping.** The queued pins of one `batch` form one bulk run (a pin with `revert` never: item 16), due at once (the server writes a whole batch before it sends an event; the runner lists `?batch=<id>&status=queued` before it starts, as v2 did). A pin without a batch still gets its own run (item 3). The setting is read when the run starts; a change never touches a run that already runs. A bulk run holds at most 30 pins (the batch limit). diff --git a/extension/package-lock.json b/extension/package-lock.json index effbe3e..7624452 100644 --- a/extension/package-lock.json +++ b/extension/package-lock.json @@ -1,12 +1,12 @@ { "name": "onspot-extension", - "version": "0.5.0", + "version": "0.6.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "onspot-extension", - "version": "0.5.0", + "version": "0.6.0", "devDependencies": { "esbuild": "0.28.2" } diff --git a/extension/package.json b/extension/package.json index 2e3c642..e02ca94 100644 --- a/extension/package.json +++ b/extension/package.json @@ -1,6 +1,6 @@ { "name": "onspot-extension", - "version": "0.5.0", + "version": "0.6.0", "private": true, "license": "MIT", "type": "module", diff --git a/extension/src/content/card.js b/extension/src/content/card.js index f934bb6..5e5d904 100644 --- a/extension/src/content/card.js +++ b/extension/src/content/card.js @@ -3,7 +3,7 @@ import { ext, MSG, RUN_URL, SHOT_KINDS } from '../shared/protocol.js'; import { HOST, SHOT_CACHE, SHOT_WIDTH } from './env.js'; import { resolveTarget } from './target.js'; import { ABOUT, SCOPE } from './prefs.js'; -import { elapsed, isOpen, modelName, statusText, when } from './format.js'; +import { elapsed, goBack, isOpen, modelName, revertTag, statusText, when } from './format.js'; import { announce, button, el, errorNode, link, panelShell, setTitle, textarea } from './dom.js'; import { schedule, setError, showFlash, syncWatchers } from './layout.js'; import { api } from './live.js'; @@ -77,6 +77,7 @@ export function refreshCard(instance, pin) { instance.status.dataset.status = pin.status; instance.accepted.hidden = pin.status !== 'done' || !pin.acceptedAt; instance.accepted.title = pin.acceptedAt ? `You accepted it ${when(pin.acceptedAt)}` : ''; + instance.tag.textContent = revertTag(pin); instance.tag.hidden = !instance.tag.textContent; instance.note.textContent = pin.note; const tags = [ABOUT[pin.intent]?.[0], SCOPE[pin.scope]?.[0]].filter(Boolean).map(text => el('span', 'chip', text)); for (const preset of Array.isArray(pin.presets) ? pin.presets : []) { @@ -110,11 +111,14 @@ export function refreshCard(instance, pin) { instance.commit.textContent = pin.commit ? `Commit ${pin.commit}` : ''; instance.commit.hidden = !pin.commit; if (!instance.busy) instance.panel.querySelectorAll('button').forEach(node => { node.disabled = false; }); const closed = pin.status === 'done' || pin.status === 'dismissed'; - instance.edit.hidden = pin.status !== 'queued'; + instance.edit.hidden = pin.status !== 'queued' || Boolean(pin.revert); instance.dismiss.hidden = !isOpen(pin); instance.reopen.hidden = pin.status !== 'working' && pin.status !== 'waiting'; instance.see.hidden = pin.status !== 'done'; instance.good.hidden = pin.status !== 'done' || Boolean(pin.acceptedAt); + const back = Boolean(goBack(pin)); + instance.backOpen &&= back; + instance.back.hidden = !back || instance.backOpen; instance.backBox.hidden = !instance.backOpen; // Open pins take replies. A closed pin shows "Not right", which opens the reply box. instance.replyForm.hidden = closed && !instance.wrongOpen; instance.wrong.hidden = !closed || instance.wrongOpen; @@ -186,15 +190,45 @@ async function cardAction(instance, method, suffix = '', body) { } catch (error) { if (card === instance) setError(instance.error, error.message); return false; } finally { instance.busy = false; buttons.forEach(node => { node.disabled = false; }); } } +// Go back (v3.5): an inline panel. Opening it closes the Not right box and the Delete confirm. +export function setBack(instance, open) { + instance.backOpen = open; + if (open) { instance.wrongOpen = false; instance.confirm.hidden = true; renderBack(instance); } + refreshCard(instance, instance.pin); + (open ? instance.backBox.querySelector(':checked') || instance.backBox.querySelector('.primary') : instance.back).focus(); +} +function renderBack(instance) { + const { now, ask, choices } = goBack(instance.pin); + let question = el('p', '', ask); + if (choices.length > 1) { + question = el('fieldset'); + question.append(el('legend', '', ask)); + choices.forEach((choice, index) => { + const label = el('label'), input = el('input'); + Object.assign(input, { type: 'radio', name: 'go-back', value: choice.commit, checked: index === choices.length - 1 }); + label.append(input, el('span', '', choice.label)); + question.append(label); + }); + } + const footer = el('div', 'panel-footer'); + footer.append(button('Keep the version that is live now', 'Keep', () => setBack(instance, false)), button('Start a run that ships the chosen version', 'Go back', async () => { + const commit = instance.backBox.querySelector(':checked')?.value ?? choices.at(-1).commit; + if (await cardAction(instance, 'POST', '/revert', { commit }) && card === instance) { + announce(`Pin ${instance.id} goes back to the chosen version.`); + instance.panel.focus({ preventScroll: true }); + } + }, 'primary')); + instance.backBox.replaceChildren(...(now ? [el('p', 'detail', now)] : []), question, footer); +} export async function openCard(id, scroll = false) { closePopup(); closeCard(false); closeLog(); closeSettings(false); dropToast(`pin:${id}`); const instance = panelShell('thread', `Pin ${id}`, () => closeCard()); - Object.assign(instance, { id, replies: new Map(), busy: false, wrongOpen: false, steps: [], count: pins.get(id)?.progress?.count || 0, timer: 0 }); + Object.assign(instance, { id, replies: new Map(), busy: false, wrongOpen: false, backOpen: false, steps: [], count: pins.get(id)?.progress?.count || 0, timer: 0 }); instance.status = el('span', 'status', 'Loading…'); instance.accepted = el('span', 'accepted', 'Accepted'); instance.accepted.hidden = true; - instance.head.insertBefore(instance.status, instance.close); - instance.head.insertBefore(instance.accepted, instance.close); + instance.tag = el('span', 'revert-tag'); instance.tag.hidden = true; + for (const node of [instance.status, instance.accepted, instance.tag]) instance.head.insertBefore(node, instance.close); const body = el('div', 'panel-body'); instance.note = el('p', 'note'); instance.question = el('p', 'question'); instance.question.hidden = true; @@ -257,7 +291,7 @@ export async function openCard(id, scroll = false) { if (ok) closeCard(); }); instance.wrong = button('Send this pin back for another fix', 'Not right', () => { - instance.wrongOpen = true; instance.replyForm.hidden = false; + instance.wrongOpen = true; instance.backOpen = false; instance.replyForm.hidden = false; if (instance.pin) refreshCard(instance, instance.pin); instance.reply.focus(); }); @@ -267,14 +301,19 @@ export async function openCard(id, scroll = false) { }); instance.dismiss = button('Dismiss this pin', 'Dismiss', () => cardAction(instance, 'POST', '/dismiss', {})); instance.reopen = button('Reopen this pin', 'Reopen', () => cardAction(instance, 'POST', '/reopen', {})); - for (const node of [instance.see, instance.good, instance.wrong, instance.edit, instance.dismiss, instance.reopen]) node.hidden = true; - const confirm = el('div', 'confirm'); confirm.hidden = true; - const deleteButton = button('Delete this pin', 'Delete', () => { confirm.hidden = false; confirmDelete.focus(); schedule(); }, 'danger'); + instance.back = button('Go back to an earlier version of this element', 'Go back', () => setBack(instance, true)); + instance.backBox = el('div', 'go-back'); + for (const node of [instance.see, instance.good, instance.wrong, instance.back, instance.backBox, instance.edit, instance.dismiss, instance.reopen]) node.hidden = true; + const confirm = instance.confirm = el('div', 'confirm'); confirm.hidden = true; + const deleteButton = button('Delete this pin', 'Delete', () => { + if (instance.backOpen) setBack(instance, false); + confirm.hidden = false; confirmDelete.focus(); schedule(); + }, 'danger'); instance.delete = deleteButton; const confirmDelete = button('Confirm deletion of this pin', 'Delete pin', () => cardAction(instance, 'DELETE'), 'danger'); confirm.append(el('span', '', 'Delete this pin?'), button('Keep this pin', 'Cancel', () => { confirm.hidden = true; deleteButton.focus(); schedule(); }), confirmDelete); - actions.append(instance.see, instance.good, instance.wrong, instance.edit, instance.dismiss, instance.reopen, deleteButton); - instance.panel.append(body, actions, confirm); + actions.append(instance.see, instance.good, instance.wrong, instance.back, instance.edit, instance.dismiss, instance.reopen, deleteButton); + instance.panel.append(body, actions, instance.backBox, confirm); card = instance; instance.panel.querySelectorAll('button').forEach(node => { if (node !== instance.close) node.disabled = true; }); if (pins.has(id)) refreshCard(instance, pins.get(id)); diff --git a/extension/src/content/format.js b/extension/src/content/format.js index b8422d1..e556274 100644 --- a/extension/src/content/format.js +++ b/extension/src/content/format.js @@ -1,7 +1,11 @@ // Words and numbers as he reads them: the pure part. No DOM and no storage, so node tests it. export const plural = (n, word) => `${n} ${word}${n === 1 ? '' : 's'}`; -export const clip = (text, max) => { const s = String(text ?? '').replace(/\s+/g, ' ').trim(); return s.length > max ? `${s.slice(0, max - 1)}…` : s; }; +// One line of at most `max` characters. The cut never keeps half a character (a lone first unit of a surrogate pair). +export const clip = (text, max) => { + const s = String(text ?? '').replace(/\s+/g, ' ').trim(), end = max - 1 - /[\uD800-\uDBFF]/.test(s[max - 2]); + return s.length > max ? `${s.slice(0, end)}…` : s; +}; export function when(iso) { const date = new Date(iso); if (Number.isNaN(date.getTime())) return ''; @@ -34,3 +38,23 @@ export function elapsed(pin) { const minutes = Math.floor(seconds / 60), two = n => String(n % 60).padStart(2, '0'); return `Fixing for ${minutes < 60 ? minutes : `${Math.floor(minutes / 60)}:${two(minutes)}`}:${two(seconds)}`; } +// Go back (v3.5). The short sha is the first 7 characters of the commit. +export const sha7 = commit => String(commit ?? '').slice(0, 7); +// The tag next to the status: a go back that is not complete, or the result of one. +export const revertTag = pin => pin.revert ? 'Going back' : pin.status === 'done' && pin.revertedAt ? 'Reverted' : ''; +const fixLine = (k, version) => [`fix ${k}`, sha7(version?.commit), clip(version?.summary, 80)].filter(Boolean).join(' · '); +// What the Go back panel shows, or null when the card has no Go back. Version k is the page after +// fix k (versions[k - 1]); going back to it undoes versions[k] and every later fix, so the commit +// to send is versions[k].commit. The choices are newest first; the last one is the default. +export function goBack(pin) { + const list = Array.isArray(pin.versions) ? pin.versions : [], n = list.length; + if (!n || pin.revert || (pin.status !== 'done' && pin.status !== 'dismissed')) return null; + const choices = []; + for (let k = n - 1; k > 0; k--) choices.push({ label: `After ${fixLine(k, list[k - 1])}`, commit: list[k]?.commit }); + choices.push({ label: 'Before this pin (the page before any fix)', commit: list[0]?.commit }); + return { + now: n > 1 ? `Now: ${fixLine(n, list[n - 1])}` : '', + ask: n > 1 ? 'Go back to which version?' : `Go back to the page before this pin? An agent undoes ${sha7(list[0]?.commit)} and ships the old version.`, + choices, + }; +} diff --git a/extension/src/content/keys.js b/extension/src/content/keys.js index ca5681f..f566b8b 100644 --- a/extension/src/content/keys.js +++ b/extension/src/content/keys.js @@ -12,7 +12,7 @@ import { discardButton, discardConfirm, drafts, renderTray, submitAll } from './ import { closeLog, log, toggleLog } from './log.js'; import { closeSettings, renderSettings, settings, toggleSettings } from './settings.js'; import { closeKeyForm } from './settings-keys.js'; -import { card, closeCard } from './card.js'; +import { card, closeCard, setBack } from './card.js'; // What each shortcut action does (the list is in shortcuts.js). const actions = { @@ -38,6 +38,7 @@ export function onKey(event) { event.preventDefault(); event.stopPropagation(); if (!discardConfirm.hidden) { discardConfirm.hidden = true; renderTray(); discardButton.focus({ preventScroll: true }); } else if (popup) closePopup(); + else if (card?.backOpen) setBack(card, false); else if (card) closeCard(); else if (settings?.keyForm) closeKeyForm(); else if (settings?.reset) { settings.reset = false; renderSettings('key-reset'); } diff --git a/extension/src/content/log.js b/extension/src/content/log.js index 850af39..93ef68e 100644 --- a/extension/src/content/log.js +++ b/extension/src/content/log.js @@ -1,7 +1,7 @@ // The Log: the unsent pins and the sent pins of this host, grouped by batch. import { HOST, SUBMIT_KEYS } from './env.js'; import { resolveTarget } from './target.js'; -import { clip, plural, statusText, when } from './format.js'; +import { clip, plural, revertTag, statusText, when } from './format.js'; import { button, el, link, panelShell, root, setPressed } from './dom.js'; import { schedule, syncWatchers } from './layout.js'; import { api } from './live.js'; @@ -105,7 +105,7 @@ export function renderLog() { : pin.status === 'waiting' ? clip(questions.get(pin.id) || 'Open it to answer.', 200) : pin.status === 'dismissed' ? clip(pin.summary || '', 160) : pin.status === 'working' ? clip(pin.progress?.text, 200) || `Started ${when(pin.startedAt)}` : ''; - section.append(logRow(String(pin.id), { key: pin.status, text: statusText(pin) }, `#${pin.id}`, pin.note, + section.append(logRow(String(pin.id), { key: pin.status, text: revertTag(pin) || statusText(pin) }, `#${pin.id}`, pin.note, `${clip(pin.targets[0]?.label, 60)} · ${pin.path}`, detail, () => openPin(pin), `Open pin ${pin.id}`)); } list.append(section); diff --git a/extension/src/content/pins.js b/extension/src/content/pins.js index e529786..3033652 100644 --- a/extension/src/content/pins.js +++ b/extension/src/content/pins.js @@ -52,7 +52,7 @@ export function acceptPin(pin, action = 'updated') { function notify(previous, pin) { const key = `pin:${pin.id}`; // The run toast stays while the run works and shows its newest step. Closed by hand, it stays closed. - const working = () => toast({ key, pin: pin.id, kind: 'working', title: `Fixing #${pin.id}${modelName(pin) ? ` · ${modelName(pin)}` : ''}`, text: pin.progress?.text, ms: 0 }); + const working = () => toast({ key, pin: pin.id, kind: 'working', title: `${pin.revert ? 'Going back' : 'Fixing'} #${pin.id}${modelName(pin) ? ` · ${modelName(pin)}` : ''}`, text: pin.progress?.text, ms: 0 }); if (previous.status === pin.status) { if (pin.status === 'working' && toasts.has(key) && previous.progress?.count !== pin.progress?.count) working(); return; @@ -60,7 +60,7 @@ function notify(previous, pin) { dropToast(key); // a toast about the old status is stale now if (pin.status === 'working') working(); else if (pin.status === 'done') { - toast({ key, pin: pin.id, kind: 'done', title: `#${pin.id} done`, text: pin.summary || pin.note, ms: 16000, actions: [ + toast({ key, pin: pin.id, kind: 'done', title: pin.revertedAt ? `Back to the earlier version · #${pin.id}` : `#${pin.id} done`, text: pin.summary || pin.note, ms: 16000, actions: [ ['See the change on the page', 'See it', () => seeIt(pin)], ['Open this pin', 'Open', () => openPin(pin)], ] }); } else if (pin.status === 'dismissed') { diff --git a/extension/src/content/styles.js b/extension/src/content/styles.js index 48df5df..7713501 100644 --- a/extension/src/content/styles.js +++ b/extension/src/content/styles.js @@ -136,7 +136,7 @@ textarea::placeholder, input::placeholder { color: var(--muted); } .status[data-status='waiting'] { color: #c4b5fd; } .status[data-status='done'] { color: var(--done); } .status[data-status='dismissed'] { color: var(--muted); } -.accepted { color: var(--done); font-size: 11px; font-weight: 600; white-space: nowrap; } +.accepted, .revert-tag { color: var(--done); font-size: 11px; font-weight: 600; white-space: nowrap; } .note { margin: 0 0 12px; white-space: pre-wrap; overflow-wrap: anywhere; } .summary { margin: 0 0 10px; color: #bbf7d0; white-space: pre-wrap; overflow-wrap: anywhere; } .question { margin: -6px 0 12px; color: #ddd6fe; white-space: pre-wrap; overflow-wrap: anywhere; } @@ -164,6 +164,13 @@ textarea::placeholder, input::placeholder { color: var(--muted); } .reply-form { margin-top: 12px; } .confirm { display: flex; flex-wrap: wrap; align-items: center; gap: 5px; padding: 0 12px 10px; } .confirm span { flex: 1; font-size: 12px; } +.go-back { padding: 0 12px 10px; display: grid; gap: 6px; } +.go-back p, .go-back fieldset { margin: 0; font-size: 12px; overflow-wrap: anywhere; } +.go-back fieldset { border: 0; padding: 0; min-width: 0; display: grid; gap: 2px; } +.go-back legend { padding: 0 0 4px; font-size: 12px; font-weight: 600; } +.go-back label { display: flex; align-items: flex-start; gap: 8px; min-height: 32px; padding: 6px 4px; border-radius: 6px; cursor: pointer; font-size: 12px; } +@media (hover: hover) { .go-back label:hover { background: var(--raised); } } +.go-back input { flex: none; width: 16px; height: 16px; margin: 1px 0 0; padding: 0; accent-color: var(--accent); cursor: pointer; } .sheet-title { display: flex; justify-content: space-between; margin: 16px 0 6px; font-size: 11px; font-weight: 600; color: var(--muted); } .sheet-title:first-child { margin-top: 0; } .row { display: flex; align-items: center; gap: 2px; min-height: 40px; border-top: 1px solid var(--line); } diff --git a/extension/src/shared/protocol.js b/extension/src/shared/protocol.js index 1d34a3a..47eaf6d 100644 --- a/extension/src/shared/protocol.js +++ b/extension/src/shared/protocol.js @@ -14,7 +14,7 @@ export const PORT_NAME = "pins-live"; export const PING_MS = 25000; // Paths the background script forwards; anything else is refused. `/api/settings` takes only SETTINGS_METHODS. -export const API_PATH_RE = /^\/api\/(health|stats|batches|settings|pins(\/[1-9][0-9]{0,11}(\/(start|resolve|dismiss|reopen|replies|accept))?)?)(\?[^#]*)?$/; +export const API_PATH_RE = /^\/api\/(health|stats|batches|settings|pins(\/[1-9][0-9]{0,11}(\/(start|resolve|dismiss|reopen|replies|accept|revert))?)?)(\?[^#]*)?$/; export const API_METHODS = ["GET", "POST", "PATCH", "DELETE"]; export const SETTINGS_METHODS = ["GET", "PATCH"]; diff --git a/extension/test/background.test.js b/extension/test/background.test.js index a54801c..2d959cd 100644 --- a/extension/test/background.test.js +++ b/extension/test/background.test.js @@ -139,7 +139,7 @@ test("API takes each path only with the methods of its route", async () => { const api = createAPI({ fetch: async (url, options) => { calls.push(`${options.method} ${url.slice(API.length)}`); return Response.json({}); } }); const routes = { "/api/health": ["GET"], "/api/stats": ["GET"], "/api/batches": ["POST"], "/api/settings": ["GET", "PATCH"], "/api/pins": ["GET", "POST"], - "/api/pins/12": ["GET", "PATCH", "DELETE"], "/api/pins/12/replies": ["POST"], "/api/pins/12/accept?x=1": ["POST"], "/api/pins?host=a.koglabs.com": ["GET", "POST"], + "/api/pins/12": ["GET", "PATCH", "DELETE"], "/api/pins/12/replies": ["POST"], "/api/pins/12/accept?x=1": ["POST"], "/api/pins/12/revert": ["POST"], "/api/pins?host=a.koglabs.com": ["GET", "POST"], }; const expected = []; for (const [path, methods] of Object.entries(routes)) { @@ -154,9 +154,9 @@ test("API takes each path only with the methods of its route", async () => { test("the path allowlist holds what the content script calls and nothing that only an agent may call", async () => { const allowed = ["/api/health", "/api/pins", "/api/pins?host=a.koglabs.com&status=all&limit=50", "/api/pins/12", "/api/batches", - "/api/pins/12/dismiss", "/api/pins/12/reopen", "/api/pins/12/replies", "/api/pins/12/accept", "/api/settings"]; + "/api/pins/12/dismiss", "/api/pins/12/reopen", "/api/pins/12/replies", "/api/pins/12/accept", "/api/pins/12/revert", "/api/settings"]; const refused = ["/api/pins/12/shots/before", "/api/pins/12/shots/after", "/api/pins/12/progress", "/api/pins/12/ask", "/api/settings/bulk", - "/api/settingsx", "/api/pins/12/accept/1", "/api/pins/0/accept", "/api/events", "/mcp", "/download/onspot-chrome.zip", "/api/pins/12/replies/3", "/api/pins/12?x#y", "/pins/api/health"]; + "/api/settingsx", "/api/pins/12/accept/1", "/api/pins/0/accept", "/api/pins/12/revert/1", "/api/pins/12/reverts", "/api/events", "/mcp", "/download/onspot-chrome.zip", "/api/pins/12/replies/3", "/api/pins/12?x#y", "/pins/api/health"]; for (const path of allowed) assert.equal(API_PATH_RE.test(path), true, path); let count = 0; const api = createAPI({ fetch: () => { count++; throw new Error("must not fetch"); } }); diff --git a/extension/test/content-format.test.js b/extension/test/content-format.test.js index 48f2607..eb45ac5 100644 --- a/extension/test/content-format.test.js +++ b/extension/test/content-format.test.js @@ -1,6 +1,6 @@ import test from "node:test"; import assert from "node:assert/strict"; -import { clip, elapsed, isOpen, modelName, newer, plural, statusText, when } from "../src/content/format.js"; +import { clip, elapsed, goBack, isOpen, modelName, newer, plural, revertTag, sha7, statusText, when } from "../src/content/format.js"; test("plural adds an s for every count but one", () => { assert.equal(plural(1, "pin"), "1 pin"); @@ -75,3 +75,76 @@ test("when shows the time for today and the date for another day", (t) => { assert.notEqual(when(other.toISOString()), time(other)); for (const bad of ["", "not a date", undefined, {}]) assert.equal(when(bad), "", String(bad)); }); + +const lone = /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/; +test("clip never ends with half a character", () => { + const face = "\u{1F600}"; // two UTF-16 units + for (let pad = 0; pad < 6; pad++) { + for (const max of [5, 6, 7, 80]) { + const out = clip("x".repeat(pad) + face.repeat(50), max); + assert.ok(out.length <= max, `${pad} ${max}`); + assert.equal(lone.test(out), false, `${pad} ${max}: ${JSON.stringify(out)}`); + assert.ok(out.endsWith("\u2026")); + } + } + assert.equal(clip(`${"x".repeat(78)}${face}tail`, 80), `${"x".repeat(78)}\u2026`, "the pair goes whole"); + assert.equal(clip(`${"x".repeat(77)}${face}tail`, 80), `${"x".repeat(77)}${face}\u2026`, "a whole pair stays"); +}); + +const C = ["a1b2c3d4e5f60718", "b2c3d4e5f6071829", "c3d4e5f60718293a"]; +const versions = (n, summaries = ["Title margin 48px to 24px", "Title colour green", "Title font 600"]) => + C.slice(0, n).map((commit, i) => ({ commit, summary: summaries[i], at: "2026-11-14T10:00:00.000Z" })); + +test("goBack: no Go back without a version, with a go back running, or on an open pin", () => { + assert.equal(goBack({ status: "done", versions: [], revert: null }), null); + for (const v of [undefined, null, "x", {}]) assert.equal(goBack({ status: "done", versions: v, revert: null }), null, String(v)); + assert.equal(goBack({ status: "done", versions: versions(1), revert: { commits: [C[0]], at: "x", attempts: 1 } }), null); + for (const status of ["queued", "working", "waiting"]) assert.equal(goBack({ status, versions: versions(2), revert: null }), null, status); + assert.notEqual(goBack({ status: "done", versions: versions(1), revert: null }), null); + assert.notEqual(goBack({ status: "dismissed", versions: versions(1), revert: null }), null); + assert.notEqual(goBack({ status: "done", versions: versions(1) }), null, "an older server sends no revert"); +}); + +test("goBack with one version asks one question and undoes that fix", () => { + assert.deepEqual(goBack({ status: "done", versions: versions(1), revert: null }), { + now: "", + ask: "Go back to the page before this pin? An agent undoes a1b2c3d and ships the old version.", + choices: [{ label: "Before this pin (the page before any fix)", commit: C[0] }], + }); +}); + +test("goBack with three versions lists the earlier versions newest first; each choice undoes the fix after it", () => { + assert.deepEqual(goBack({ status: "done", versions: versions(3), revert: null }), { + now: "Now: fix 3 · c3d4e5f · Title font 600", + ask: "Go back to which version?", + choices: [ + { label: "After fix 2 · b2c3d4e · Title colour green", commit: C[2] }, + { label: "After fix 1 · a1b2c3d · Title margin 48px to 24px", commit: C[1] }, + { label: "Before this pin (the page before any fix)", commit: C[0] }, + ], + }); +}); + +test("goBack clips each summary to 80 characters and leaves out a missing one", () => { + const long = `${"word ".repeat(15)}abc\u{1F600}${"z".repeat(30)}`; // units 78 and 79 are the pair: the cut falls inside it + const back = goBack({ status: "dismissed", versions: versions(2, [long, null]), revert: null }); + assert.equal(back.now, "Now: fix 2 · b2c3d4e"); + const label = back.choices[0].label, summary = label.split(" · ")[2]; + assert.ok(summary.length <= 80 && summary.endsWith("\u2026"), summary); + assert.equal(lone.test(label), false, label); + assert.equal(summary, clip(long, 80)); + assert.equal(summary, `${"word ".repeat(15)}abc\u2026`); + assert.equal(goBack({ status: "done", versions: [{ commit: C[0], summary: " \n " }, { commit: C[1] }], revert: null }).choices[0].label, "After fix 1 · a1b2c3d"); +}); + +test("sha7 and revertTag", () => { + assert.equal(sha7(C[0]), "a1b2c3d"); + assert.equal(sha7("abc"), "abc"); + for (const bad of [null, undefined, ""]) assert.equal(sha7(bad), ""); + const revert = { commits: [C[0]], at: "2026-11-14T10:00:00.000Z", attempts: 1 }; + for (const status of ["queued", "working", "waiting"]) assert.equal(revertTag({ status, revert, revertedAt: null }), "Going back", status); + assert.equal(revertTag({ status: "done", revert: null, revertedAt: "2026-11-14T10:05:00.000Z" }), "Reverted"); + assert.equal(revertTag({ status: "queued", revert: null, revertedAt: "2026-11-14T10:05:00.000Z" }), "", "a requeue clears it; an old value shows nothing"); + assert.equal(revertTag({ status: "done", revert: null, revertedAt: null }), ""); + assert.equal(revertTag({ status: "done" }), ""); +}); diff --git a/extension/test/harness/fake-ext.js b/extension/test/harness/fake-ext.js index d4be1f9..ee2f24d 100644 --- a/extension/test/harness/fake-ext.js +++ b/extension/test/harness/fake-ext.js @@ -49,7 +49,7 @@ function create(body, batch = null) { id: db.nextPin++, status: 'queued', url: url.href, host: url.host.toLowerCase(), path: url.pathname, title: (body.title || '').slice(0, 300), note: body.note.trim(), quote: body.quote?.slice(0, 2000) || null, targets: copy(body.targets), viewport: body.viewport || null, author: 'tester', agent: null, - summary: null, commit: null, run: null, batch, model: null, attempts: 0, acceptedAt: null, reopens: 0, + summary: null, commit: null, run: null, batch, model: null, attempts: 0, acceptedAt: null, reopens: 0, versions: [], revert: null, revertedAt: null, intent: body.intent ?? null, scope: body.scope ?? null, presets: copy(body.presets ?? []), progress: null, shots: { before: null, after: null }, replyCount: 0, createdAt: now(), updatedAt: now(), startedAt: null, closedAt: null, }; db.pins.push(pin); save(); return pin; @@ -70,9 +70,9 @@ function reply(pin, body, kind = 'user') { const item = { id: db.nextReply++, pinId: pin.id, kind, author: kind === 'agent' ? 'test-agent' : 'tester', body: text(body, 'body'), createdAt: now() }; db.replies.push(item); pin.replyCount++; pin.updatedAt = now(); save(); return item; } -// A user reopen, as the store does it: clears the run and the acceptance, counts the reopen. +// A user reopen, as the store does it: clears the run, the acceptance and the go back result, counts the reopen. function reopenPin(pin) { - Object.assign(pin, { status: 'queued', agent: null, summary: null, commit: null, run: null, startedAt: null, closedAt: null, acceptedAt: null }); + Object.assign(pin, { status: 'queued', agent: null, summary: null, commit: null, run: null, startedAt: null, closedAt: null, acceptedAt: null, revertedAt: null }); pin.reopens++; } // PATCH /api/settings merges. An unknown key, a wrong type or agents outside 1 to 8 is 400 and changes nothing. @@ -100,7 +100,7 @@ function handle({ method, path, body }) { if (lostResponses > 0) { lostResponses--; return { ok: false, status: 0, data: null, error: 'offline' }; } return success(data, status); } - const match = /^\/api\/pins(?:\/([1-9][0-9]{0,11})(?:\/(start|resolve|dismiss|ask|reopen|replies|accept))?)?$/.exec(url.pathname); + const match = /^\/api\/pins(?:\/([1-9][0-9]{0,11})(?:\/(start|resolve|dismiss|ask|reopen|replies|accept|revert))?)?$/.exec(url.pathname); if (!match) return failure('Not found', 404); if (!match[1]) { if (method === 'GET') { @@ -137,7 +137,7 @@ function handle({ method, path, body }) { save(); return success({ reply: copy(item), pin: copy(pin) }, 201); } - const allowed = { start: ['queued'], resolve: ['queued', 'working', 'waiting'], dismiss: ['queued', 'working', 'waiting'], ask: ['queued', 'working'], reopen: ['working', 'waiting', 'done', 'dismissed'], accept: ['done'] }; + const allowed = { start: ['queued'], resolve: ['queued', 'working', 'waiting'], dismiss: ['queued', 'working', 'waiting'], ask: ['queued', 'working'], reopen: ['working', 'waiting', 'done', 'dismissed'], accept: ['done'], revert: ['done', 'dismissed'] }; if (!allowed[action]?.includes(pin.status)) return failure('Status conflict', 409); pin.updatedAt = now(); if (action === 'start') { @@ -146,9 +146,23 @@ function handle({ method, path, body }) { } if (action === 'resolve') { pin.summary = text(body?.summary, 'summary'); pin.commit = body?.commit || null; pin.status = 'done'; pin.closedAt = now(); - reply(pin, `Done: ${pin.summary}${pin.commit ? ` (${pin.commit})` : ''}`, 'agent'); + // The revert run removes the fixes that it undid; any other resolve adds a version. + const reverted = Boolean(pin.revert); + if (reverted) { pin.versions = pin.versions.filter(item => !pin.revert.commits.includes(item.commit)); pin.revert = null; pin.revertedAt = now(); } + else if (pin.commit) pin.versions = [...pin.versions, { commit: pin.commit, summary: pin.summary, at: now() }].slice(-30); + reply(pin, `${reverted ? 'Reverted' : 'Done'}: ${pin.summary}${pin.commit ? ` (${pin.commit})` : ''}`, 'agent'); + } + if (action === 'dismiss') { pin.status = 'dismissed'; pin.summary = body?.reason || null; pin.closedAt = now(); pin.revert = null; } + // Go back: the chosen commit and every later fix are undone, newest first. + if (action === 'revert') { + if (typeof body?.commit !== 'string' || !body.commit) return failure('commit is required'); + const at = pin.versions.findIndex(item => item.commit === body.commit); + if (at < 0) return failure('That commit is not a version of this pin.', 409); + const commits = pin.versions.slice(at).map(item => item.commit).reverse(); + pin.revert = { commits, at: now(), attempts: pin.attempts }; + reopenPin(pin); + reply(pin, `Go back to ${at ? `fix ${at} (${pin.versions[at - 1].commit.slice(0, 7)})` : 'the version before this pin'}: undo ${commits.map(commit => commit.slice(0, 7)).join(', ')}.`); } - if (action === 'dismiss') { pin.status = 'dismissed'; pin.summary = body?.reason || null; pin.closedAt = now(); } if (action === 'ask') { pin.status = 'waiting'; reply(pin, text(body?.question, 'question'), 'agent'); } if (action === 'reopen') reopenPin(pin); if (action === 'accept') pin.acceptedAt ??= now(); // once; a second accept changes nothing diff --git a/extension/test/harness/run.mjs b/extension/test/harness/run.mjs index 936ce8c..0fc9a70 100644 --- a/extension/test/harness/run.mjs +++ b/extension/test/harness/run.mjs @@ -1160,6 +1160,130 @@ try { await clean(hp, shotsPage.issues); await hp.close(); pass('a failed accept shows the reason, keeps Looks good for a retry and still marks the pin seen'); + // Go back (0.6.0): the version choice in the card of a closed pin, and the labels of a go back. + const backPage = await freshPage(context, '/back'); activePage = backPage.page; + const gp = backPage.page; + const V = ['a1b2c3d4e5f60718', 'b2c3d4e5f6071829', 'c3d4e5f60718293a']; + await gp.evaluate(V => { + __fake.reset(); localStorage.removeItem('onspot-harness-storage'); + const target = { selector: '#target', label: 'h1 "Make room"', rect: { x: 100, y: 100, w: 500, h: 50 } }; + const at = new Date().toISOString(), v = (i, summary) => ({ commit: V[i], summary, at }), first = v(0, 'Title margin 48px to 24px'); + for (const [note, fields] of [ + ['No fix commit.', { status: 'done', summary: 'Nothing to ship.', closedAt: at }], + ['One fix.', { status: 'done', summary: first.summary, commit: V[0], versions: [first], closedAt: at }], + ['Three fixes.', { status: 'done', summary: 'Title font 600', commit: V[2], versions: [first, v(1, 'Title colour green'), v(2, 'Title font 600')], closedAt: at }], + ['Dismissed after a fix.', { status: 'dismissed', summary: 'Not needed.', versions: [first], closedAt: at }], + ['Go back, please.', { status: 'queued', versions: [first], revert: { commits: [V[0]], at, attempts: 1 } }], + ['Went back.', { status: 'done', summary: 'Undid a1b2c3d.', commit: 'd4e5f60', revertedAt: at, closedAt: at }], + ]) __fake.update(__fake.seed({ url: `${location.origin}/back`, note, targets: [target] }).id, { agent: 'claude', model: 'opus 5.5 high', attempts: 1, ...fields }); + }, V); + await gp.reload(); await visible(gp, '.capsule'); await marker(gp, 5); + const openBy = async id => { + await gp.evaluate(id => { location.hash = `#kog-pin=${id}`; }, id); + await waitFor(gp, id => location.hash === '' && document.querySelector('on-spot').shadowRoot.querySelector('.thread .panel-title')?.textContent === `Pin ${id}`, id); + }; + const backView = () => gp.evaluate(() => { + const card = document.querySelector('on-spot').shadowRoot.querySelector('.thread'); + const shown = sel => { const node = card.querySelector(sel); return node && !node.closest('[hidden]') ? node : null; }; + const box = shown('.go-back'); + return { button: Boolean(shown('button[title="Go back to an earlier version of this element"]')), tag: shown('.revert-tag')?.textContent ?? null, edit: Boolean(shown('button[title="Edit this note"]')), + panel: box && { now: box.querySelector('.detail')?.textContent ?? null, ask: box.querySelector('legend, p:not(.detail)').textContent, options: [...box.querySelectorAll('label')].map(node => [node.textContent, node.querySelector('input').checked]) } }; + }); + const activeIn = () => gp.evaluate(() => { const node = document.querySelector('on-spot').shadowRoot.activeElement; return node ? node.title || `${node.type}:${node.value}:${node.checked}` : ''; }); + const opener = gp.locator(ui('button[title="Go back to an earlier version of this element"]')), submitBack = gp.locator(ui('button[title="Start a run that ships the chosen version"]')); + const revertCalls = id => gp.evaluate(id => __fake.calls.filter(call => call.path === `/api/pins/${id}/revert`).map(({ method, body }) => [method, body]), id); + const none = { button: false, tag: null, edit: false, panel: null }; + for (const [id, expected] of [[1, none], [2, { ...none, button: true }], [4, { ...none, button: true }], [5, { ...none, tag: 'Going back' }], [6, { ...none, tag: 'Reverted' }]]) { + await openBy(id); assert.deepEqual(await backView(), expected, `pin ${id}`); + } + assert.equal(await shadowText(gp, '.thread .status'), 'Done'); + await openBy(5); + assert.equal(await shadowText(gp, '.thread .status'), 'Queued again'); + assert.equal(await gp.locator(ui('button[title="Dismiss this pin"]')).isVisible(), true, 'Dismiss cancels the go back'); + await gp.evaluate(() => __fake.update(5, { revert: null })); + await waitFor(gp, () => !document.querySelector('on-spot').shadowRoot.querySelector('.thread button[title="Edit this note"]').hidden); + assert.deepEqual(await backView(), { ...none, edit: true }, 'without the go back the queued card has Edit again'); + await gp.evaluate(V => __fake.update(5, { revert: { commits: [V[0]], at: new Date().toISOString(), attempts: 1 } }), V); + await waitFor(gp, () => document.querySelector('on-spot').shadowRoot.querySelector('.thread button[title="Edit this note"]').hidden); + pass('Go back shows only on a done or dismissed card with a version and no go back; "Going back" hides Edit; a done card after a go back says "Reverted"'); + + await openBy(2); await opener.click(); + assert.deepEqual(await backView(), { ...none, panel: { now: null, ask: 'Go back to the page before this pin? An agent undoes a1b2c3d and ships the old version.', options: [] } }); + assert.equal(await activeIn(), 'Start a run that ships the chosen version'); + await screenshot(gp, name, 'go-back-one'); + await gp.locator(ui('button[title="Keep the version that is live now"]')).click(); + assert.deepEqual(await backView(), { ...none, button: true }); assert.equal(await activeIn(), 'Go back to an earlier version of this element'); + await opener.click(); await gp.keyboard.press('Escape'); + assert.deepEqual(await backView(), { ...none, button: true }, 'Esc closes the panel'); assert.equal(await gp.locator(ui('.thread')).isVisible(), true, 'and keeps the card'); + const reply = gp.locator(ui('textarea[name="pin-reply"]')), confirmDelete = gp.locator(ui('button[title="Confirm deletion of this pin"]')); + await opener.click(); await gp.locator(ui('button[title="Send this pin back for another fix"]')).click(); + assert.deepEqual([(await backView()).panel, await reply.isVisible()], [null, true], 'Not right closes the panel'); + await opener.click(); + assert.deepEqual([Boolean((await backView()).panel), await reply.isVisible()], [true, false], 'Go back closes the Not right box'); + await gp.locator(ui('button[title="Delete this pin"]')).click(); + assert.deepEqual([(await backView()).panel, await confirmDelete.isVisible()], [null, true], 'the Delete confirm closes the panel'); + await opener.click(); + assert.deepEqual([Boolean((await backView()).panel), await confirmDelete.isVisible()], [true, false], 'Go back closes the Delete confirm'); + assert.deepEqual(await revertCalls(2), [], 'nothing is sent before Go back'); + pass('Go back with one version: one question names the fix; Keep and Esc close the panel, not the card; it, the Not right box and the Delete confirm close each other'); + + await gp.evaluate(() => { __fake.delay = 300; }); + await submitBack.click(); + assert.equal(await submitBack.isDisabled(), true, 'Go back is disabled while the call runs'); + await waitFor(gp, () => document.querySelector('on-spot').shadowRoot.querySelector('.thread .status')?.textContent === 'Queued again'); + await gp.evaluate(() => { __fake.delay = 30; }); + assert.deepEqual(await revertCalls(2), [['POST', { commit: V[0] }]]); + assert.deepEqual(await backView(), { ...none, tag: 'Going back' }); + assert.deepEqual(await gp.evaluate(() => { const pin = __fake.db.pins.find(item => item.id === 2); return [pin.status, pin.revert.commits]; }), ['queued', [V[0]]]); + await marker(gp, 2, 'queued'); + pass('"Before this pin" sends POST /api/pins/2/revert { commit: versions[0] }; Go back is disabled while it runs; the card shows the queued pin with "Going back"'); + + await openBy(3); await opener.click(); + assert.deepEqual((await backView()).panel, { now: 'Now: fix 3 · c3d4e5f · Title font 600', ask: 'Go back to which version?', options: [ + ['After fix 2 · b2c3d4e · Title colour green', false], ['After fix 1 · a1b2c3d · Title margin 48px to 24px', false], ['Before this pin (the page before any fix)', true]] }); + assert.equal(await activeIn(), `radio:${V[0]}:true`, 'the focus is on the default choice'); + for (const label of ['After fix 2 · b2c3d4e · Title colour green', 'After fix 1 · a1b2c3d · Title margin 48px to 24px', 'Before this pin (the page before any fix)']) { + assert.equal(await gp.getByRole('radio', { name: label, exact: true }).count(), 1, `a screen reader reads "${label}"`); + } + await gp.keyboard.press('ArrowUp'); + assert.equal(await activeIn(), `radio:${V[1]}:true`, 'an arrow key picks the next newer version'); + assert.deepEqual((await backView()).panel.options.map(([, checked]) => checked), [false, true, false]); + await gp.keyboard.press('Tab'); await gp.keyboard.press('Tab'); + assert.equal(await activeIn(), 'Start a run that ships the chosen version', 'Tab goes on to Keep, then Go back'); + await screenshot(gp, name, 'go-back-three'); + pass('Go back with three versions: the "Now:" line, the choices newest first, "Before this pin" as the default; each radio has its name and the keys reach it'); + + await gp.evaluate(() => __fake.failNext('POST', '/api/pins/3/revert', 409, 'That commit is not a version of this pin.')); + await submitBack.click(); + await waitFor(gp, () => document.querySelector('on-spot').shadowRoot.querySelector('#onspot-card-error')?.textContent === 'That commit is not a version of this pin.'); + assert.equal(await shadowText(gp, '.thread .status'), 'Done'); + assert.deepEqual((await backView()).panel?.options.map(([, checked]) => checked), [false, true, false], 'the panel stays open with the choice'); + assert.equal(await submitBack.isDisabled(), false, 'Go back can be tried again'); + await submitBack.click(); + await waitFor(gp, () => document.querySelector('on-spot').shadowRoot.querySelector('.thread .status')?.textContent === 'Queued again'); + assert.deepEqual(await revertCalls(3), [['POST', { commit: V[1] }], ['POST', { commit: V[1] }]], '"After fix 1" undoes versions[1] and every later fix'); + assert.deepEqual(await backView(), { ...none, tag: 'Going back' }); + assert.equal(await gp.locator(ui('#onspot-card-error')).isVisible(), false); + assert.deepEqual(await gp.evaluate(() => __fake.db.pins.find(item => item.id === 3).revert.commits), [V[2], V[1]]); + await gp.keyboard.press('Escape'); await gone(gp, '.thread'); + pass('a failed go back shows the reason in the card and keeps the panel open; "After fix 1" sends POST /api/pins/3/revert { commit: versions[1] }'); + + const toastTitle = kind => gp.evaluate(kind => document.querySelector('on-spot').shadowRoot.querySelector(`.toast[data-kind="${kind}"] .toast-title`)?.textContent ?? null, kind); + await gp.evaluate(() => __fake.update(5, { status: 'working', run: 'triad:77', startedAt: new Date().toISOString() })); + await waitFor(gp, () => document.querySelector('on-spot').shadowRoot.querySelector('.toast[data-kind="working"]')); + assert.equal(await toastTitle('working'), 'Going back #5 · Opus 5.5 high'); + await gp.evaluate(() => { const at = new Date().toISOString(); __fake.update(5, { status: 'done', summary: 'Undid a1b2c3d.', commit: 'e5f6071', revert: null, revertedAt: at, versions: [], closedAt: at }); }); + await waitFor(gp, () => document.querySelector('on-spot').shadowRoot.querySelector('.toast[data-kind="done"]')); + assert.equal(await toastTitle('done'), 'Back to the earlier version · #5'); + await openMenu(gp); await gp.locator(ui('.log-button')).click(); await visible(gp, '.log'); + await waitFor(gp, () => document.querySelector('on-spot').shadowRoot.querySelectorAll('.log .log-row').length === 6); + assert.deepEqual(await gp.evaluate(() => [...document.querySelector('on-spot').shadowRoot.querySelectorAll('.log-row')].map(row => `${row.dataset.key} ${row.querySelector('.chip').textContent}`)), + ['6 Reverted', '5 Reverted', '4 Dismissed', '3 Going back', '2 Going back', '1 Done']); + await screenshot(gp, name, 'go-back-log'); + await gp.keyboard.press('Escape'); await gone(gp, '.log'); + await clean(gp, backPage.issues); await gp.close(); + pass('a revert run toast says "Going back #5 · Opus 5.5 high" and its done toast "Back to the earlier version · #5"; the Log chips say "Going back" and "Reverted"'); + // Bulk mode: server settings in the Settings sheet, and a chip in the tray. const bulkPage = await freshPage(context, '/bulk'); activePage = bulkPage.page; const bp = bulkPage.page; diff --git a/runner/src/prompt.js b/runner/src/prompt.js index 3dcb73e..d662317 100644 --- a/runner/src/prompt.js +++ b/runner/src/prompt.js @@ -125,6 +125,66 @@ export function buildPrompt({ pin, project, choice, replies = [], history = [], ]); } +/** + * The prompt of a revert run (docs/protocol.md, Auto-fix runner, item 16): he pressed Go back on a + * closed pin. The session undoes the commits of pin.revert, newest first, ships the old version and + * closes the pin. A summary is agent text: it goes in fenced, like a reply. + * @param {{ pin: object, project: object, choice: { label: string }, replies?: object[], + * brief?: { card: string[], ship: boolean }|null, shot?: boolean, lean?: boolean }} run + */ +export function buildRevertPrompt({ pin, project, choice, replies = [], brief = null, shot = false, lean = false }) { + const id = pin.id, card = list(brief?.card), ship = brief?.ship === true; + const versions = Array.isArray(pin.versions) ? pin.versions : []; + const commits = Array.isArray(pin.revert?.commits) ? pin.revert.commits.map(String) : []; + const short = (sha) => fenced(sha, 40).slice(0, 7); + const kept = versions.length - commits.length; + const target = kept > 0 ? `the page after fix ${kept} (${short(versions[kept - 1].commit)})` : "the page before this pin"; + const worktree = `/srv/work/<repo>-pin${id}`; + const summary = '--summary "<what he now sees, one line, English>"'; + return lines([ + `You are the OnSpot session for pin #${id} on ${pin.host}. The Chairman pressed "Go back" on this pin: he wants an earlier version of the page back. Undo the commits below, ship the old version and close the pin.`, + `Model: ${choice.label}.`, + lean && LEAN, + "", + "Undo these commits, newest first:", + ...commits.map((sha) => { + const index = versions.findIndex((v) => v.commit === sha), v = versions[index]; + return ` ${fenced(sha, 40)} · fix ${index + 1}${v ? ` · ${fenced(String(v.at ?? "").slice(0, 10), 10)} · ${fenced(v.summary, 160)}` : ""}`; + }), + `He goes back to ${target}.${kept > 0 ? ` Fix ${kept} and the fixes before it stay.` : ""}`, + "", + "His words on the pin, for context (the order now is the go back):", + ...words(pin, replies).filter((line) => !/^Earlier runs:/.test(line)), + "", + ...fence(pin), + FENCE_RULE, + "", + where(pin.host, project), + "", + ...block(card), + "How to work:", + `1. ${card.length ? CARD : MEMORY}`, + `2. Make your own worktree ${worktree} from origin/main. Other sessions can change the same project at the same time.`, + "3. For each commit above, newest first: git revert --no-commit <sha>. If git does not know a commit, fetch origin first; if it is in another repository, work there. If a commit is undone already, skip it. If a later commit changed the same lines, keep the later work and remove only the change of this pin. Build and look at the result before you ship.", + `4. Progress: ${PINS} progress ${id} "<step>". Send 2 to 4 steps of at most 120 characters, in English: commits found, undo made, ship.`, + shot + ? `5. Shots: the harness took the "before" shot (the page with the fix).${ship ? "" : ` Run \`${PINS} snap ${id} after\` ${AFTER}`}` + : `5. Shots: run \`${PINS} snap ${id} before\` before the undo and \`${PINS} snap ${id} after\` after the live deploy. ${SHOTS}`, + `6. Ask only when a commit cannot be found or the undo would remove other work: ${PINS} ask ${id} "<one short question>".`, + ...(ship ? [ + `7. Ship with one command: ${PINS} ship ${id} --dir ${worktree} --message "Revert pin #${id}: <short what>" ${summary} <every changed file, also deleted ones>`, + " git status --short lists the files. The command commits them, runs the gate one time, pushes, merges the PR, releases to staging, takes the \"after\" shot, checks the element, closes the pin and removes the worktree. Give the call a timeout of 10 minutes. Do not run the tests, git push, gh or proj yourself.", + ` If it stops, fix what it names and run the same command again. Exit code 3: a lane is busy, run it again. Exit code 4: the old version is live but the element did not change back; look at the live page, then fix it and ship again, or close with ${PINS} done ${id} ${DONE}.`, + ] : [ + `7. ${SHIP} Then close: ${PINS} done ${id} ${DONE}`, + ]), + `8. Never dismiss this pin. If the old version is live already, close it with ${PINS} done ${id} ${summary} and no commit.`, + "", + `Hard end state: when you stop, pin #${id} is not "working". It is done (with the commit of the undo) or waiting (you asked).`, + "Report at the end, one line: result, commit, live check.", + ]); +} + /** * One prompt for all pins of a bulk run, in id order (Bulk mode, item 5). If it is longer than * PROMPT_BYTES, the history of every pin goes first, then the hints; his words and the page data diff --git a/runner/src/runner.js b/runner/src/runner.js index 7f304dc..4250ae5 100644 --- a/runner/src/runner.js +++ b/runner/src/runner.js @@ -4,7 +4,7 @@ // It is a harness: it never edits code, writes git state or deploys. import { readEvents } from "./sse.js"; import { chooseModel, chooseBulkModel } from "./model.js"; -import { buildBulkPrompt, pinTitle, PROMPT_BYTES } from "./prompt.js"; +import { buildBulkPrompt, buildRevertPrompt, pinTitle, PROMPT_BYTES } from "./prompt.js"; import { chooseProfile } from "./profile.js"; import { readConfig } from "./config.js"; import { createShots } from "./shots.js"; @@ -38,6 +38,9 @@ const errorCode = (error) => Number.isInteger(error.status) ? `http=${error.stat // than when the run took the pin says that he did it. A reopen by an agent (a session on its own // pin) leaves the count as it is, and so does a pin from before the count (null). const sentBack = (pin, taken) => Number.isInteger(pin.reopens) && Number.isInteger(taken) && pin.reopens > taken; +// The runs of a go back count from his request (docs/protocol.md, item 16): the first revert run +// has effort high and one retry, also when the pin had fix runs before. +const runsOf = (pin) => (pin.revert ? { ...pin, attempts: Math.max(0, Number(pin.attempts) - (Number(pin.revert.attempts) || 0)) } : pin); /** clock supplies now(), setTimeout(fn, ms), clearTimeout(id). start/stop are async. * brief({ pin, project, earlier }) builds the pin brief; shoot(pinId) takes the "before" shot. @@ -70,6 +73,8 @@ export function createRunner({ fetch, clock, triad, resolveProject, buildPrompt, const endedRuns = new Set(); let enabled = false, started = false, stopping = false, bootstrapped = false, queue = Promise.resolve(); let bulk = { on: false, delegate: false, agents: 3 }; + // A pin of a batch waits for the bulk run of its batch while bulk mode is on. A go back never does. + const inBulk = (pin) => bulk.on && Boolean(pin.batch) && !pin.revert; let budget = { day: null, used: 0 }; let startAfter = 0, owedAfter = 0; let streamController, streamJob, retry = 3000; @@ -223,7 +228,8 @@ export function createRunner({ fetch, clock, triad, resolveProject, buildPrompt, // search; it never stops the run. The log line holds numbers only. async function briefOf(pin, project) { if (!makeBrief) return null; - const earlier = await read(pin, { host: pin.host, status: "done", limit: 200 }, () => true); + // A revert run uses the project card only: the earlier pins teach no source hint it needs. + const earlier = pin.revert ? [] : await read(pin, { host: pin.host, status: "done", limit: 200 }, () => true); let timeout; try { const facts = await Promise.race([ @@ -258,9 +264,17 @@ export function createRunner({ fetch, clock, triad, resolveProject, buildPrompt, if (!current || stopping || limit(current.key)) return; await settings(); // The mode counts at the start: with bulk now on, the pin waits for the run of its batch. - if (!enabled || options.disabled || stopping || (bulk.on && current.pin.batch)) return; + if (!enabled || options.disabled || stopping || inBulk(current.pin)) return; const { pin, project, key } = current; - const choice = chooseModel(pin); + const choice = chooseModel(runsOf(pin)); + if (pin.revert) { + // A go back (item 16): the lean start, the project card, no history and no siblings. + const profile = options.lean ? "pin" : null; + const facts = await briefOf(pin, project); + const prompt = buildRevertPrompt({ pin, project, choice, replies, brief: facts, shot: Boolean(shots), lean: profile === "pin" }); + await begin([pin], key, project, choice, `Pin #${pin.id} · Go back: ${pinTitle(pin)} · ${choice.label}`, prompt, profile); + return; + } // The lean start, unless the pin needs the full one (runner/src/profile.js). const profile = options.lean ? chooseProfile(pin) : null; const known = await context(pin); @@ -276,7 +290,7 @@ export function createRunner({ fetch, clock, triad, resolveProject, buildPrompt, const { pins: listed } = await api(`/api/pins?${new URLSearchParams({ batch, status: "queued", limit: 500 })}`); if (!Array.isArray(listed)) throw new Error("Invalid pins list"); for (const pin of listed) await ingest(pin); - const members = () => [...pending.values()].filter((other) => other.pin.batch === batch).sort((a, b) => a.pin.id - b.pin.id); + const members = () => [...pending.values()].filter((other) => other.pin.batch === batch && !other.pin.revert).sort((a, b) => a.pin.id - b.pin.id); const replies = new Map(); for (const { pin } of members()) replies.set(pin.id, await reread(pin.id)); const group = members().slice(0, BULK_MAX); @@ -498,10 +512,10 @@ export function createRunner({ fetch, clock, triad, resolveProject, buildPrompt, // session reopened it) gets the question: a new run for it could repeat without end. if (!back && !(pin.status === "working" && pin.run === `triad:${run.id}`)) return; try { - if (run.end !== GONE && enabled && !options.disabled && pin.status === "working" && Number(pin.attempts) < MAX_ATTEMPTS) { + if (run.end !== GONE && enabled && !options.disabled && pin.status === "working" && Number(runsOf(pin).attempts) < MAX_ATTEMPTS) { // One more run, one effort step higher. It starts at once. With auto-fix off nothing // would pick it up, so the pin goes to the Chairman instead. - const next = bulk.on && pin.batch ? chooseBulkModel([pin]) : chooseModel(pin); + const next = inBulk(pin) ? chooseBulkModel([pin]) : chooseModel(runsOf(pin)); await api(`/api/pins/${id}/replies`, { body: `${ended} Trying again at effort ${next.effort}.` }); await api(`/api/pins/${id}/reopen`, {}); } else await api(`/api/pins/${id}/ask`, { question: `${ended} Reply to retry, or dismiss it.` }); @@ -519,7 +533,7 @@ export function createRunner({ fetch, clock, triad, resolveProject, buildPrompt, for (const entry of units()) { if (stopping) return; const reason = limit(entry.key); - if (!reason) await (bulk.on && entry.pin.batch ? launchBulk(entry) : launch(entry)); + if (!reason) await (inBulk(entry.pin) ? launchBulk(entry) : launch(entry)); else if (entry.limit !== reason) { entry.limit = reason; log(`limit reached ${reason} pin=${entry.pin.id}`); @@ -533,7 +547,7 @@ export function createRunner({ fetch, clock, triad, resolveProject, buildPrompt, function units() { const batches = new Set(); return [...pending.values()].sort((a, b) => a.pin.id - b.pin.id).filter(({ pin }) => { - if (!bulk.on || !pin.batch) return true; + if (!inBulk(pin)) return true; if (batches.has(pin.batch)) return false; batches.add(pin.batch); return true; diff --git a/runner/test/revert.test.js b/runner/test/revert.test.js new file mode 100644 index 0000000..2527bd2 --- /dev/null +++ b/runner/test/revert.test.js @@ -0,0 +1,98 @@ +// v3.5, item 16: a queued pin with `revert` (he pressed Go back) starts its own revert run. +import test from "node:test"; +import assert from "node:assert/strict"; +import { buildRevertPrompt } from "../src/prompt.js"; +import { chooseModel } from "../src/model.js"; +import { harness } from "./helpers.js"; + +const A = "a1b2c3d4e5f60718293a4b5c6d7e8f9012345678", B = "b2c3d4e"; +const VERSIONS = [ + { commit: A, summary: "Margin 48px to 24px", at: "2026-11-13T10:00:00.000Z" }, + { commit: B, summary: "Margin <24px> to 16px", at: "2026-11-14T09:00:00.000Z" }, +]; +// A pin with two fix runs behind it; he asks to go back to the page before the pin. +const back = (extra = {}) => ({ batch: 7, attempts: 2, versions: VERSIONS, revert: { commits: [B, A], at: "2026-11-14T10:00:00.000Z", attempts: 2 }, ...extra }); +const BRIEF = { card: ["Project card: one"], hints: ["Source hints:", " 1. src/a.js:3"], ship: true, gate: "npm test", stats: {} }; +const ON = { on: true, delegate: false, agents: 3 }; + +test("a go back starts its own lean run at effort high, also in bulk mode, with the card and no history, siblings or earlier pins", async (t) => { + const inputs = []; + const h = harness(t, { bulk: ON, brief: async (input) => { inputs.push(input); return BRIEF; } }); + await h.start(); + h.add(1, undefined, back()); + h.add(2, undefined, { batch: 7 }); h.add(3, undefined, { batch: 7 }); + await h.settle(); + const labels = h.delegates.map(({ body }) => body.label).sort(); + assert.deepEqual(labels, ["Pin #1 · Go back: Private pin note · Opus 5.5 high", "Pins #2 #3 · Private pin note +1 · Opus 5.5 xhigh · bulk"]); + const run = h.delegates.find(({ body }) => body.label.startsWith("Pin #1")).body; + assert.deepEqual([run.model, run.effort, run.profile], ["claude-opus-5-5", "high", "pin"]); + assert.ok(run.prompt.startsWith('You are the OnSpot session for pin #1 on one.koglabs.com. The Chairman pressed "Go back" on this pin')); + assert.ok(run.prompt.includes(`Undo these commits, newest first:\n ${B} · fix 2 · 2026-11-14 · Margin ‹24px› to 16px\n ${A} · fix 1 · 2026-11-13 · Margin 48px to 24px\nHe goes back to the page before this pin.\n`)); + assert.ok(run.prompt.includes("\n\nProject card: one\n\nHow to work:\n")); + assert.ok(!run.prompt.includes("Source hints"), "a revert needs no source hints"); + assert.deepEqual(inputs.find((input) => input.pin.id === 1).earlier, [], "no read of the earlier pins"); + assert.ok(!h.requests.some((request) => request.path === "/api/pins" && request.query.has("selector")), "no history read"); + const listed = h.requests.filter((request) => request.query?.get("batch") === "7" && request.query.get("status") === "all"); + assert.deepEqual(listed, [], "no siblings read"); + const claims = h.requests.filter((request) => request.path === "/api/pins/1/start"); + assert.deepEqual(claims.map((request) => request.body.model), ["opus 5.5 high"]); +}); + +test("the runs of a go back count from his request: one retry at the next effort, then the Chairman", async (t) => { + const h = harness(t); + await h.start(); + h.add(1, undefined, back({ batch: null })); + await h.settle(); + assert.equal(h.delegates[0].body.effort, "high"); + h.tasks.set("101", { status: "failed", exitCode: 1, lastLine: "Quota" }); + await h.clock.tick(15_000); + await h.settle(); + const replies = h.requests.filter((request) => request.path === "/api/pins/1/replies"); + assert.deepEqual(replies.map((request) => request.body.body), ["The run ended without a result (failed, exit 1): Quota. Trying again at effort xhigh."]); + assert.equal(h.delegates.length, 2); + assert.deepEqual([h.delegates[1].body.effort, h.delegates[1].body.label], ["xhigh", "Pin #1 · Go back: Private pin note · Opus 5.5 xhigh"]); + assert.deepEqual(h.pins.get(1).revert.commits, [B, A], "the retry is a go back again"); + h.tasks.set("102", { status: "failed", exitCode: 1, lastLine: "Quota" }); + await h.clock.tick(15_000); + await h.settle(); + assert.equal(h.pins.get(1).status, "waiting"); + assert.match(h.pins.get(1).question, /Reply to retry, or dismiss it\.$/); + assert.equal(h.delegates.length, 2); +}); + +test("the full start stays off for a go back only when the lean switch is off", async (t) => { + const h = harness(t, { config: { lean: false } }); + await h.start(); + h.add(1, undefined, back({ batch: null, intent: "task", note: "Use the design kit skill" })); + await h.settle(); + assert.equal(h.delegates[0].body.profile, null); + assert.ok(!h.delegates[0].body.prompt.includes("This session starts lean")); + const lean = harness(t); + await lean.start(); + lean.add(1, undefined, back({ batch: null, intent: "task", note: "Use the design kit skill" })); + await lean.settle(); + assert.equal(lean.delegates[0].body.profile, "pin", "a go back needs no skill, also when the note named one"); +}); + +test("buildRevertPrompt: the version he keeps, the ship command or the manual ship, the before shot, no Earlier runs line", () => { + const pin = { id: 9, host: "one.koglabs.com", path: "/", url: "https://one.koglabs.com/", note: "Smaller title", attempts: 2, + targets: [{ selector: "h1", label: "h1 <Title>" }], versions: VERSIONS, revert: { commits: [B], attempts: 2 } }; + const project = { name: "one", dir: "/srv/one", candidates: ["one"] }; + const choice = chooseModel({ ...pin, attempts: 0 }); + const shipped = buildRevertPrompt({ pin, project, choice, brief: BRIEF, shot: true, lean: true }); + assert.ok(shipped.includes(`Undo these commits, newest first:\n ${B} · fix 2 · 2026-11-14 · Margin ‹24px› to 16px\nHe goes back to the page after fix 1 (${A.slice(0, 7)}). Fix 1 and the fixes before it stay.\n`)); + assert.ok(shipped.includes("Model: Opus 5.5 high.\nThis session starts lean:")); + assert.ok(shipped.includes('PINS_AGENT=claude pins ship 9 --dir /srv/work/<repo>-pin9 --message "Revert pin #9: <short what>" --summary "<what he now sees, one line, English>" <every changed file, also deleted ones>')); + assert.ok(shipped.includes('5. Shots: the harness took the "before" shot (the page with the fix).\n')); + assert.ok(shipped.includes("element: h1 ‹Title›")); + assert.ok(shipped.includes("Note: Smaller title")); + assert.ok(!shipped.includes("Earlier runs:"), "the fix runs are not runs of this go back"); + assert.ok(shipped.includes("8. Never dismiss this pin.")); + const manual = buildRevertPrompt({ pin: { ...pin, revert: { commits: [B, A] } }, project, choice }); + assert.ok(manual.includes("He goes back to the page before this pin.\n")); + assert.ok(manual.includes("7. Ship: build and tests pass, commit (explicit paths), push, merge, deploy the way this project deploys, then check the live page. Then close: PINS_AGENT=claude pins done 9")); + assert.ok(manual.includes("PINS_AGENT=claude pins snap 9 before` before the undo")); + assert.ok(!manual.includes("pins ship")); + assert.ok(manual.includes("How to work:\n1. Read the project memory first"), "no card: the memory"); + assert.ok(!/\u0000/.test(manual)); +}); diff --git a/server/bin/pins.js b/server/bin/pins.js index 5a9a5d3..a5a78d0 100755 --- a/server/bin/pins.js +++ b/server/bin/pins.js @@ -2,7 +2,7 @@ import { readFileSync, rmSync, statSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; -import { clearFacts, judge, loadFacts, saveFacts } from "../src/facts.js"; +import { clearFacts, judge, loadFacts, saveFacts, verdictIntent } from "../src/facts.js"; import { formatDetail, formatLine, formatList } from "../src/format.js"; import { ID_RE } from "../src/id.js"; import { ship } from "../src/ship.js"; @@ -125,7 +125,7 @@ function saveImage(id, bytes) { // A done pin whose before and after facts show no change gets a warning. It never blocks the command. function warnIfUnchanged(id, pin) { const [before, after] = ["before", "after"].map((kind) => loadFacts(id, kind)); - const result = before && after && judge(pin.intent, before, after); + const result = before && after && judge(verdictIntent(pin), before, after); if (result?.ok === false) console.error(`warning: ${result.text}`); } @@ -217,7 +217,7 @@ async function main() { const shot = await snapPin(pin, {}); await upload(id, "after", shot.bytes); saveFacts(id, "after", shot.facts); - const verdict = judge(pin.intent, loadFacts(id, "before"), shot.facts); + const verdict = judge(verdictIntent(pin), loadFacts(id, "before"), shot.facts); return { ok: verdict.ok, text: `#${id} after: ${shot.text} · ${verdict.text}` }; }; process.exitCode = await ship( @@ -236,7 +236,7 @@ async function main() { saveFacts(id, kind, shot.facts); if (kind === "before") clearFacts(id, ["after", "check"]); console.log(`#${id} ${kind}: ${shot.text}${image}`); - if (kind !== "before") console.log(`#${id} ${judge(pin.intent, loadFacts(id, "before"), shot.facts).text}`); + if (kind !== "before") console.log(`#${id} ${judge(verdictIntent(pin), loadFacts(id, "before"), shot.facts).text}`); return; } if (command === "list") { diff --git a/server/src/api.js b/server/src/api.js index b720903..7beb4c9 100644 --- a/server/src/api.js +++ b/server/src/api.js @@ -8,7 +8,7 @@ export function apiRoute(path) { if (path === "/api/settings") return { name: "settings", methods: ["GET", "PATCH"] }; if (path === "/api/pins") return { name: "pins", methods: ["GET", "POST"] }; if (path === "/api/batches") return { name: "batches", methods: ["POST"] }; - const match = /^\/api\/pins\/([^/]+)(?:\/(start|resolve|dismiss|ask|reopen|accept|replies|progress|shots\/(before|after)))?$/.exec(path); + const match = /^\/api\/pins\/([^/]+)(?:\/(start|resolve|dismiss|ask|reopen|accept|revert|replies|progress|shots\/(before|after)))?$/.exec(path); const id = match && parseId(match[1]); if (!id) return null; if (match[3]) return { name: "shot", id, kind: match[3], methods: ["GET", "PUT"] }; diff --git a/server/src/facts.js b/server/src/facts.js index 81bcb38..7c13636 100644 --- a/server/src/facts.js +++ b/server/src/facts.js @@ -106,11 +106,26 @@ const WANTED = { layout: { kinds: ["size", "position"], none: "position and size did not change" }, }; +/** The intent that judges a pin: a revert run, or the result of one, wants the element back as it was. */ +export const verdictIntent = (pin) => (pin?.revert || pin?.revertedAt ? "revert" : pin?.intent ?? null); + +// A revert passes when the element changed in any way, also when it came back or went away. +function judgeRevert(before, after) { + if (!before || !after) return { ok: null, text: `check: no ${before ? "after" : "before"} facts` }; + if (!before.found) return after.found ? { ok: true, text: "check: the element is back" } : { ok: null, text: "check: no before facts (a signed-out visitor did not see the element)" }; + const { kinds, props } = changes(before, after); + if (kinds.includes("gone")) return { ok: true, text: "check: the element is gone" }; + if (!kinds.length) return { ok: false, text: "check: the element did not change back" }; + if (kinds.length === 1 && kinds[0] === "position") return { ok: null, text: "check: only the position moved" }; + return { ok: true, text: `check: changed ${kinds.join(", ")}${props.length ? ` (${props.slice(0, 3).join(", ")})` : ""}` }; +} + /** * Did the pinned element change the way the pin asks? A pure function. * Returns { ok: true | false | null, text }; null means that the facts cannot say. */ export function judge(intent, before, after) { + if (intent === "revert") return judgeRevert(before, after); if (!before?.found) return { ok: null, text: "check: no before facts (a signed-out visitor did not see the element)" }; if (!after) return { ok: null, text: "check: no after facts" }; const { kinds, props } = changes(before, after); diff --git a/server/src/format.js b/server/src/format.js index 37ed91b..8b33e9f 100644 --- a/server/src/format.js +++ b/server/src/format.js @@ -4,6 +4,7 @@ const text = oneLine; const quoted = (value) => JSON.stringify(text(value)); const entries = (value) => Object.entries(value ?? {}).filter(([, v]) => text(v)); const clock = (iso) => iso?.slice(11, 16); +const short = (sha) => text(sha).slice(0, 7); export function formatAge(iso, now = Date.now()) { const age = new Date(now).getTime() - new Date(iso).getTime(); @@ -26,6 +27,7 @@ export function formatList(pins, { now = Date.now() } = {}) { `${formatLine(pin)} ${pin.host}${pin.path}`, text(pin.targets?.[0]?.label), text(pin.intent), + pin.revert ? "go back" : "", formatAge(pin.createdAt, now), pin.replyCount > 0 ? `${pin.replyCount} ${pin.replyCount === 1 ? "reply" : "replies"}` : "", ]; @@ -43,6 +45,9 @@ export function formatDetail(pin, replies = [], steps = []) { for (const key of ["agent", "model", "summary", "commit", "run", "batch"]) { if (text(pin[key])) lines.push(`${key}: ${text(pin[key])}`); } + if (pin.versions?.length) lines.push(`versions: ${pin.versions.map((v) => `${short(v.commit)} ${text(v.summary).slice(0, 80)}`).join(" · ")}`); + if (pin.revert?.commits?.length) lines.push(`go back: undo ${pin.revert.commits.map(short).join(", ")}`); + if (pin.revertedAt) lines.push(`reverted: ${clock(pin.revertedAt)}`); for (const [index, target] of (pin.targets ?? []).entries()) { lines.push(`target ${index + 1}: ${text(target.label)}`); if (text(target.selector)) lines.push(` selector: ${text(target.selector)}`); diff --git a/server/src/ship.js b/server/src/ship.js index 2e78863..f810882 100644 --- a/server/src/ship.js +++ b/server/src/ship.js @@ -311,7 +311,10 @@ export async function ship(input, deps) { // 4. Commit only the listed paths; other staged or changed files stop the ship. step = "commit"; - await git(["add", "--", ...files]); + // A deletion that is staged already (git revert, git rm) is in no worktree and no index: git add refuses its path. + const indexed = new Set((await git(["ls-files", "-z", "--", ...files])).stdout.split("\0")); + const present = files.filter((rel) => indexed.has(rel) || lstatSync(join(root, rel), { throwIfNoEntry: false })); + if (present.length) await git(["add", "--", ...present]); const staged = (await git(["diff", "--cached", "--quiet", "--", ...files], { check: false })).code === 1; if (staged) await git(["commit", "-q", "-m", message, "--", ...files]); else if ((await git(["rev-list", "--count", "origin/main..HEAD"])).stdout.trim() === "0") throw failure("nothing to ship"); diff --git a/server/src/store.js b/server/src/store.js index 54c8ca7..62d0f37 100644 --- a/server/src/store.js +++ b/server/src/store.js @@ -26,7 +26,15 @@ const TRANSITIONS = { ask: { from: ["queued", "working"], to: "waiting" }, reopen: { from: ["working", "waiting", "done", "dismissed"], to: "queued" }, accept: { from: ["done"], to: "done" }, + revert: { from: ["done", "dismissed"], to: "queued" }, }; +// Only he can accept a result or go back to an earlier version. +const USER_ONLY = { accept: "accept a pin", revert: "go back to an earlier version" }; +// A version is one live fix commit; a git sha of 7 to 40 hex characters. The list keeps the newest. +const COMMIT_RE = /^[0-9a-f]{7,40}$/i; +const VERSIONS_MAX = 30; +// The reply that a resolve writes: "Done: <summary> (<commit>)". The first open of a v3.5 file reads the versions from it. +const DONE_REPLY_RE = /^Done: ([\s\S]*) \(([0-9a-f]{7,40})\)$/i; export const BATCH_MAX = 30; const KEY_RE = /^[A-Za-z0-9_-]{8,80}$/; const ATTR_KEYS = ["id", "class", "role", "aria-label", "href", "src", "alt", "name", "type", "placeholder", "data-testid", "data-slot", "data-component", "title"]; @@ -38,7 +46,7 @@ const SHOT_FILE_RE = new RegExp(`^(${ID})-(?:${SHOT_KINDS.join("|")})(?:\\.tmp)? // Columns that newer versions added; an older file gets them on open. const ADDED_COLUMNS = [["run", "TEXT"], ["batch", "INTEGER"], ["model", "TEXT"], ["attempts", "INTEGER NOT NULL DEFAULT 0"], ["intent", "TEXT"], ["scope", "TEXT"], ["presets", "TEXT"], ["shot_before", "TEXT"], ["shot_after", "TEXT"], - ["accepted_at", "TEXT"], ["reopens", "INTEGER"]]; + ["accepted_at", "TEXT"], ["reopens", "INTEGER"], ["versions", "TEXT"], ["revert", "TEXT"], ["reverted_at", "TEXT"]]; const BULK_DEFAULT = { on: false, delegate: false, agents: 3 }; const isFlag = (v) => typeof v === "boolean"; const BULK_CHECKS = { on: isFlag, delegate: isFlag, agents: (v) => Number.isInteger(v) && v >= 1 && v <= 8 }; @@ -71,6 +79,9 @@ CREATE TABLE IF NOT EXISTS pins ( shot_after TEXT, accepted_at TEXT, reopens INTEGER, + versions TEXT, + revert TEXT, + reverted_at TEXT, created_at TEXT NOT NULL, updated_at TEXT NOT NULL, started_at TEXT, @@ -124,6 +135,7 @@ function migrate(db) { try { db.exec(PINS_SCHEMA); const existing = new Set(db.prepare("PRAGMA table_info(pins)").all().map(({ name }) => name)); + const backfill = !existing.has("versions"); for (const [name, type] of ADDED_COLUMNS) { if (!existing.has(name)) db.exec(`ALTER TABLE pins ADD COLUMN ${name} ${type};`); } @@ -141,6 +153,7 @@ function migrate(db) { } } db.exec(SCHEMA); + if (backfill) backfillVersions(db); if (db.prepare("PRAGMA foreign_key_check").all().length) throw new Error("database has invalid foreign keys"); db.exec("COMMIT;"); } catch (error) { @@ -152,6 +165,20 @@ function migrate(db) { } } +// Before v3.5 a pin kept only its latest commit. Its own "Done: <summary> (<commit>)" replies hold every fix, oldest first. +function backfillVersions(db) { + const found = new Map(); + for (const { pin_id: id, body, created_at: at } of db.prepare("SELECT pin_id, body, created_at FROM replies WHERE body LIKE 'Done: %' ORDER BY id").all()) { + const match = DONE_REPLY_RE.exec(body); + if (!match) continue; + const list = found.get(id) ?? []; + if (!list.some((v) => v.commit === match[2])) list.push({ commit: match[2], summary: clip(match[1].trim(), 300), at }); + found.set(id, list); + } + const write = db.prepare("UPDATE pins SET versions = ? WHERE id = ?"); + for (const [id, list] of found) write.run(JSON.stringify(list.slice(-VERSIONS_MAX)), id); +} + /** "open" (default), "all", or a comma list of statuses. */ export function parseStatuses(value) { const s = String(value ?? "open").trim().toLowerCase() || "open"; @@ -172,6 +199,12 @@ function clip(v, max) { return /[\ud800-\udbff]$/.test(cut) ? cut.slice(0, -1) : cut; } +// The reply that a resolve or a dismiss writes. The summary may use all 4000 characters: its text is cut, the commit stays. +function closing(verb, text, ref) { + const tail = ref ? ` (${ref})` : ""; + return `${verb}: ${clip(text, 4000 - verb.length - 2 - tail.length)}${tail}`; +} + function required(v, max, name) { if (typeof v !== "string" || !v.trim()) throw new ValidationError(`${name} is required`); const s = v.trim(); @@ -277,6 +310,9 @@ function toPin(row) { shots: { before: row.shot_before ?? null, after: row.shot_after ?? null }, acceptedAt: row.accepted_at ?? null, reopens: row.reopens === null || row.reopens === undefined ? null : Number(row.reopens), + versions: row.versions ? JSON.parse(row.versions) : [], + revert: row.revert ? JSON.parse(row.revert) : null, + revertedAt: row.reverted_at ?? null, replyCount: Number(row.reply_count ?? 0), createdAt: row.created_at, updatedAt: row.updated_at, @@ -312,7 +348,10 @@ export function openStore({ file, rootDomain = "koglabs.com", shotsDir = file && start: db.prepare(`UPDATE pins SET status = 'working', agent = ?, summary = NULL, commit_ref = NULL, run = ?, model = ?, attempts = attempts + 1, shot_before = NULL, shot_after = NULL, started_at = ?, closed_at = NULL, updated_at = ? WHERE id = ?`), note: db.prepare(`UPDATE pins SET note = ?, updated_at = ? WHERE id = ?`), status: db.prepare(`UPDATE pins SET status = ?, agent = ?, summary = ?, commit_ref = ?, run = ?, started_at = ?, closed_at = ?, updated_at = ? WHERE id = ?`), - requeue: db.prepare(`UPDATE pins SET status = 'queued', agent = NULL, summary = NULL, commit_ref = NULL, run = NULL, started_at = NULL, closed_at = NULL, accepted_at = NULL, reopens = reopens + ?, updated_at = ? WHERE id = ?`), + requeue: db.prepare(`UPDATE pins SET status = 'queued', agent = NULL, summary = NULL, commit_ref = NULL, run = NULL, started_at = NULL, closed_at = NULL, accepted_at = NULL, reverted_at = NULL, reopens = reopens + ?, updated_at = ? WHERE id = ?`), + resolve: db.prepare(`UPDATE pins SET status = 'done', agent = ?, summary = ?, commit_ref = ?, versions = ?, revert = NULL, reverted_at = ?, closed_at = ?, updated_at = ? WHERE id = ?`), + revert: db.prepare(`UPDATE pins SET status = 'queued', agent = NULL, summary = NULL, commit_ref = NULL, run = NULL, started_at = NULL, closed_at = NULL, accepted_at = NULL, reverted_at = NULL, revert = ?, reopens = reopens + 1, updated_at = ? WHERE id = ?`), + dropRevert: db.prepare(`UPDATE pins SET revert = NULL WHERE id = ?`), accept: db.prepare(`UPDATE pins SET accepted_at = ?, updated_at = ? WHERE id = ?`), touch: db.prepare(`UPDATE pins SET updated_at = ? WHERE id = ?`), del: db.prepare(`DELETE FROM pins WHERE id = ?`), @@ -467,7 +506,7 @@ export function openStore({ file, rootDomain = "koglabs.com", shotsDir = file && transition(id, action, { agent, summary, commit, reason, question, run, model, kind = "agent", author } = {}) { const rule = TRANSITIONS[action]; if (!rule) throw new ValidationError(`unknown action "${action}"`); - if (action === "accept" && kind !== "user") throw new ForbiddenError("only a user can accept a pin"); + if (USER_ONLY[action] && kind !== "user") throw new ForbiddenError(`only a user can ${USER_ONLY[action]}`); let reply = null; db.exec("BEGIN IMMEDIATE"); try { @@ -482,12 +521,19 @@ export function openStore({ file, rootDomain = "koglabs.com", shotsDir = file && } else if (action === "resolve") { const text = required(summary, 4000, "summary"); const ref = optional(commit, 200, "commit"); - q.status.run("done", who, text, ref, pin.run, pin.startedAt, t, t, id); - reply = insertReply(id, kind, author ?? who, `Done: ${text}${ref ? ` (${ref})` : ""}`); + // A revert run takes its commits out of the live versions; its own commit is no new version. + let versions = pin.versions; + if (pin.revert) versions = versions.filter((v) => !pin.revert.commits.includes(v.commit)); + else if (ref && COMMIT_RE.test(ref) && !versions.some((v) => v.commit === ref)) { + versions = [...versions, { commit: ref, summary: clip(text, 300), at: t }].slice(-VERSIONS_MAX); + } + q.resolve.run(who, text, ref, JSON.stringify(versions), pin.revert ? t : null, t, t, id); + reply = insertReply(id, kind, author ?? who, closing(pin.revert ? "Reverted" : "Done", text, ref)); } else if (action === "dismiss") { const why = optional(reason, 4000, "reason"); q.status.run("dismissed", pin.agent, why, null, pin.run, pin.startedAt, t, t, id); - if (why) reply = insertReply(id, kind, author ?? who, `Dismissed: ${why}`); + q.dropRevert.run(id); + if (why) reply = insertReply(id, kind, author ?? who, closing("Dismissed", why)); } else if (action === "ask") { const text = required(question, 4000, "question"); q.status.run("waiting", pin.agent, pin.summary, pin.commit, pin.run, pin.startedAt, pin.closedAt, t, id); @@ -496,6 +542,16 @@ export function openStore({ file, rootDomain = "koglabs.com", shotsDir = file && // A second accept changes nothing and sends no event. if (pin.acceptedAt) { db.exec("COMMIT"); return pin; } q.accept.run(t, t, id); + } else if (action === "revert") { + // commit is the first fix to undo; every later fix goes too, so the page is the version before it. + const ref = required(commit, 200, "commit"); + const index = pin.versions.findIndex((v) => v.commit === ref); + if (index < 0) throw new ConflictError(pin.versions.length ? `pin #${id} has no live fix ${ref}` : `pin #${id} has no version to go back to`); + const undo = pin.versions.slice(index).reverse().map((v) => v.commit); + q.revert.run(JSON.stringify({ commits: undo, at: t, attempts: pin.attempts }), t, id); + const short = (sha) => sha.slice(0, 7); + const target = index ? `fix ${index} (${short(pin.versions[index - 1].commit)})` : "the version before this pin"; + reply = insertReply(id, "user", author, `Go back to ${target}: undo ${undo.map(short).join(", ")}.`); } else { q.requeue.run(kind === "user" ? 1 : 0, t, id); } diff --git a/server/test/revert.test.js b/server/test/revert.test.js new file mode 100644 index 0000000..ea13814 --- /dev/null +++ b/server/test/revert.test.js @@ -0,0 +1,251 @@ +// v3.5: the live fix commits of a pin (versions), Go back (revert) and the revert run's resolve. +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { createServer } from "node:http"; +import { once } from "node:events"; +import { mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { DatabaseSync } from "node:sqlite"; +import { createApp } from "../src/app.js"; +import { openStore, ConflictError, ForbiddenError, ValidationError } from "../src/store.js"; +import { formatDetail, formatList } from "../src/format.js"; +import { judge, verdictIntent } from "../src/facts.js"; + +const input = (extra = {}) => ({ url: "https://crete.koglabs.com/pricing", note: "Cut the space", targets: [{ selector: "main > h1", label: "h1" }], ...extra }); +const USER = { kind: "user", author: "sam" }; +const AGENT = { kind: "agent", agent: "claude", author: "claude" }; +const A = "a1b2c3d4e5f60718293a4b5c6d7e8f9012345678"; +const B = "b2c3d4e"; +const R = "f00dfacecafe"; + +// A pin with two live fixes: A, then "Not right", then B. +function twoFixes(store = openStore({ file: ":memory:" })) { + const { id } = store.createPin(input()); + store.transition(id, "start", AGENT); + store.transition(id, "resolve", { ...AGENT, summary: "Margin 48px to 24px", commit: A }); + store.addReply(id, { ...USER, body: "Smaller", reopen: true }); + store.transition(id, "start", AGENT); + store.transition(id, "resolve", { ...AGENT, summary: "Margin 24px to 16px", commit: B }); + return { store, id }; +} + +test("resolve adds a hex commit to versions once; no commit, a non-hex commit or a repeat adds none; the list keeps the newest 30", () => { + const { store, id } = twoFixes(); + const pin = store.getPin(id); + assert.deepEqual(pin.versions.map((v) => [v.commit, v.summary]), [[A, "Margin 48px to 24px"], [B, "Margin 24px to 16px"]]); + assert.match(pin.versions[0].at, /^\d{4}-\d\d-\d\dT/); + assert.equal(pin.commit, B); + assert.deepEqual([pin.revert, pin.revertedAt], [null, null]); + for (const commit of [undefined, "n/a", "jstadev/x#12", "abc12", B]) { + store.transition(id, "reopen", AGENT); + store.transition(id, "start", AGENT); + store.transition(id, "resolve", { ...AGENT, summary: "Again", commit }); + } + assert.equal(store.getPin(id).versions.length, 2, "no new version"); + const { id: many } = store.createPin(input()); + for (let i = 0; i < 32; i++) { + store.transition(many, "start", AGENT); + store.transition(many, "resolve", { ...AGENT, summary: `Fix ${i}`, commit: i.toString(16).padStart(7, "0") }); + store.transition(many, "reopen", USER); + } + const kept = store.getPin(many).versions; + assert.equal(kept.length, 30); + assert.equal(kept[0].summary, "Fix 2"); + assert.equal(kept.at(-1).summary, "Fix 31"); + const { id: long } = store.createPin(input()); + store.transition(long, "resolve", { ...AGENT, summary: "x".repeat(4000), commit: A }); + assert.equal(store.getPin(long).versions[0].summary.length, 300, "the summary of a version is clipped"); + const closing = store.listReplies(long).at(-1).body; + assert.ok(closing.length === 4000 && closing.startsWith("Done: xxx") && closing.endsWith(` (${A})`), "a 4000-character summary fits: its text is cut, the commit stays"); + store.transition(long, "reopen", USER); + assert.equal(store.transition(long, "dismiss", { ...USER, reason: "y".repeat(4000) }).status, "dismissed"); + assert.equal(store.listReplies(long).at(-1).body.length, 4000); + store.close(); +}); + +test("revert: users only (guard before the lookup), closed pins only, a commit of a live version only", () => { + const { store, id } = twoFixes(); + const seen = []; + store.on("change", (event) => seen.push(event)); + assert.throws(() => store.transition(id, "revert", { ...AGENT, commit: A }), ForbiddenError); + assert.throws(() => store.transition(id, "revert", { commit: A }), (error) => error instanceof ForbiddenError && error.status === 403, "no kind means no user"); + assert.throws(() => store.transition(999, "revert", { ...AGENT, commit: A }), ForbiddenError); + assert.equal(store.transition(999, "revert", { ...USER, commit: A }), null); + assert.throws(() => store.transition(id, "revert", USER), (error) => error instanceof ValidationError && /commit is required/.test(error.message)); + assert.throws(() => store.transition(id, "revert", { ...USER, commit: 42 }), ValidationError); + assert.throws(() => store.transition(id, "revert", { ...USER, commit: "c0ffee1" }), (error) => error instanceof ConflictError && /no live fix c0ffee1/.test(error.message)); + assert.throws(() => store.transition(id, "revert", { ...USER, commit: A.slice(0, 7) }), ConflictError, "the exact commit, not a prefix"); + assert.deepEqual(seen, [], "a refused revert sends nothing"); + assert.equal(store.getPin(id).status, "done"); + + const { id: none } = store.createPin(input()); + store.transition(none, "resolve", { ...AGENT, summary: "Asked for no code" }); + assert.throws(() => store.transition(none, "revert", { ...USER, commit: A }), (error) => error instanceof ConflictError && /no version to go back to/.test(error.message)); + for (const status of ["queued", "working", "waiting"]) { + const { id: open } = twoFixes(store); + store.transition(open, "reopen", USER); + if (status !== "queued") store.transition(open, "start", AGENT); + if (status === "waiting") store.transition(open, "ask", { ...AGENT, question: "Which?" }); + assert.equal(store.getPin(open).status, status); + assert.throws(() => store.transition(open, "revert", { ...USER, commit: A }), (error) => error.status === 409 && error.message.endsWith(`is ${status}`)); + } + store.close(); +}); + +test("revert to the version before the pin: queued with every fix newest first, cleared like a reopen, one user reply, one update", () => { + const { store, id } = twoFixes(); + store.transition(id, "accept", USER); + const before = store.getPin(id); + const seen = []; + store.on("change", (event) => seen.push(event)); + const pin = store.transition(id, "revert", { ...USER, commit: A }); + assert.equal(pin.status, "queued"); + assert.deepEqual(pin.revert, { commits: [B, A], at: pin.revert.at, attempts: 2 }); + assert.match(pin.revert.at, /^\d{4}-\d\d-\d\dT/); + assert.deepEqual([pin.agent, pin.summary, pin.commit, pin.run, pin.startedAt, pin.closedAt, pin.acceptedAt, pin.revertedAt], [null, null, null, null, null, null, null, null]); + assert.equal(pin.reopens, before.reopens + 1, "he sent it back"); + assert.deepEqual(pin.versions, before.versions, "the versions stay until the revert run closes the pin"); + assert.deepEqual([pin.model, pin.attempts], [before.model, before.attempts]); + assert.deepEqual(seen.map((event) => event.type), ["pin", "reply"]); + assert.deepEqual(store.listReplies(id).at(-1), { ...store.listReplies(id).at(-1), kind: "user", author: "sam", body: `Go back to the version before this pin: undo ${B}, ${A.slice(0, 7)}.` }); + store.close(); +}); + +test("revert to an earlier fix undoes only the later fixes; it works from dismissed too", () => { + const { store, id } = twoFixes(); + store.transition(id, "reopen", USER); + store.transition(id, "dismiss", { ...USER, reason: "Leave it" }); + const pin = store.transition(id, "revert", { ...USER, commit: B }); + assert.deepEqual(pin.revert.commits, [B]); + assert.equal(store.listReplies(id).at(-1).body, `Go back to fix 1 (${A.slice(0, 7)}): undo ${B}.`); + store.close(); +}); + +test("the revert survives start, ask, a user answer and the runner's reopen; its resolve trims versions and sets revertedAt", () => { + const { store, id } = twoFixes(); + store.transition(id, "revert", { ...USER, commit: A }); + const commits = [B, A]; + assert.deepEqual(store.transition(id, "start", { ...AGENT, run: "triad:9" }).revert.commits, commits); + assert.deepEqual(store.transition(id, "ask", { ...AGENT, question: "The commit is in which repo?" }).revert.commits, commits); + store.addReply(id, { ...USER, body: "dropship" }); + assert.equal(store.getPin(id).status, "queued"); + assert.deepEqual(store.getPin(id).revert.commits, commits, "his answer keeps the go back"); + store.transition(id, "start", AGENT); + assert.deepEqual(store.transition(id, "reopen", AGENT).revert.commits, commits, "the retry is a revert run again"); + store.transition(id, "start", AGENT); + + const seen = []; + store.on("change", (event) => seen.push(event)); + const done = store.transition(id, "resolve", { ...AGENT, summary: "The title has its old margin again", commit: R }); + assert.equal(done.status, "done"); + assert.deepEqual([done.versions, done.revert, done.commit], [[], null, R]); + assert.match(done.revertedAt, /^\d{4}-\d\d-\d\dT/); + assert.equal(store.listReplies(id).at(-1).body, `Reverted: The title has its old margin again (${R})`); + assert.deepEqual(seen.map((event) => event.type), ["pin", "reply"]); + assert.throws(() => store.transition(id, "revert", { ...USER, commit: A }), /no version to go back to/); + + // "Not right" on the reverted pin starts a normal fix run: revertedAt goes, the next commit is a version. + store.addReply(id, { ...USER, body: "Try once more", reopen: true }); + assert.deepEqual([store.getPin(id).revertedAt, store.getPin(id).revert], [null, null]); + store.transition(id, "start", AGENT); + assert.deepEqual(store.transition(id, "resolve", { ...AGENT, summary: "New fix", commit: "c0ffee1" }).versions.map((v) => v.commit), ["c0ffee1"]); + store.close(); +}); + +test("a revert to fix 1 keeps fix 1; a revert run closed without a commit still trims; dismiss cancels the go back", () => { + const { store, id } = twoFixes(); + store.transition(id, "revert", { ...USER, commit: B }); + store.transition(id, "start", AGENT); + const done = store.transition(id, "resolve", { ...AGENT, summary: "Fix 1 is live again" }); + assert.deepEqual([done.versions.map((v) => v.commit), done.commit, done.revert], [[A], null, null]); + assert.equal(store.listReplies(id).at(-1).body, "Reverted: Fix 1 is live again"); + + store.transition(id, "revert", { ...USER, commit: A }); + store.transition(id, "start", AGENT); + const cancelled = store.transition(id, "dismiss", { ...USER, reason: "Keep it" }); + assert.deepEqual([cancelled.status, cancelled.revert, cancelled.versions.map((v) => v.commit)], ["dismissed", null, [A]]); + store.close(); +}); + +test("the first open of a v3.4 file reads the versions from the Done replies, oldest first", (t) => { + const dir = mkdtempSync(join(tmpdir(), "pins-v34-")); + t.after(() => rmSync(dir, { recursive: true, force: true })); + const file = join(dir, "pins.db"); + let store = openStore({ file }); + const { id } = twoFixes(store); + store.addReply(id, { ...USER, body: "Done: not his words (abc1234) though", reopen: false }); + const { id: plain } = store.createPin(input()); + store.transition(plain, "resolve", { ...AGENT, summary: "No code (mobile)" }); + store.transition(plain, "reopen", USER); + store.transition(plain, "resolve", { ...AGENT, summary: "Fixed (header)", commit: "jstadev/x#3" }); + const { id: fresh } = store.createPin(input()); + store.close(); + const old = new DatabaseSync(file); + old.exec("ALTER TABLE pins DROP COLUMN versions; ALTER TABLE pins DROP COLUMN revert; ALTER TABLE pins DROP COLUMN reverted_at;"); + old.close(); + store = openStore({ file }); + t.after(() => store.close()); + assert.deepEqual(store.getPin(id).versions.map((v) => [v.commit, v.summary]), [[A, "Margin 48px to 24px"], [B, "Margin 24px to 16px"]]); + assert.deepEqual(store.getPin(plain).versions, []); + assert.deepEqual([store.getPin(fresh).versions, store.getPin(fresh).revert, store.getPin(fresh).revertedAt], [[], null, null]); + assert.equal(store.transition(id, "revert", { ...USER, commit: A }).revert.commits.length, 2); +}); + +test("HTTP: POST /api/pins/:id/revert is 403 for an agent, 400 without a commit, 409 for an unknown commit, 200 for him", async (t) => { + const store = openStore({ file: ":memory:" }); + const app = createApp({ store, version: "test" }); + const server = createServer(app); + server.listen(0, "127.0.0.1"); + await once(server, "listening"); + t.after(async () => { + app.close(); + await new Promise((resolve) => { server.close(resolve); server.closeAllConnections(); }); + store.close(); + }); + const call = async (path, body, headers = {}) => { + const response = await fetch(`http://127.0.0.1:${server.address().port}${path}`, { method: "POST", headers: { "Content-Type": "application/json", ...headers }, body: JSON.stringify(body) }); + return { status: response.status, data: await response.json() }; + }; + const { id } = twoFixes(store); + assert.equal((await call(`/api/pins/${id}/revert`, { commit: A }, { "X-Pins-Agent": "claude" })).status, 403); + assert.equal((await call(`/api/pins/${id}/revert`, {})).status, 400); + assert.equal((await call(`/api/pins/${id}/revert`, { commit: "c0ffee1" })).status, 409); + assert.equal((await call("/api/pins/999/revert", { commit: A })).status, 404); + const ok = await call(`/api/pins/${id}/revert`, { commit: A }, { "X-SSO-User": "sam" }); + assert.equal(ok.status, 200); + assert.deepEqual([ok.data.pin.status, ok.data.pin.revert.commits], ["queued", [B, A]]); + assert.equal(store.listReplies(id).at(-1).author, "sam"); + assert.equal((await call(`/api/pins/${id}/revert`, { commit: A })).status, 409, "already queued"); +}); + +test("the list and detail formats show versions, the go back and the revert time", () => { + const { store, id } = twoFixes(); + assert.match(formatDetail(store.getPin(id)), new RegExp(`\\nversions: ${A.slice(0, 7)} Margin 48px to 24px · ${B} Margin 24px to 16px\\n`)); + const pin = store.transition(id, "revert", { ...USER, commit: A }); + assert.match(formatDetail(pin), new RegExp(`\\ngo back: undo ${B}, ${A.slice(0, 7)}\\n`)); + assert.match(formatList([pin]), / · go back · /); + store.transition(id, "start", AGENT); + const done = store.transition(id, "resolve", { ...AGENT, summary: "Old margin", commit: R }); + assert.match(formatDetail(done), /\nreverted: \d\d:\d\d\n/); + assert.doesNotMatch(formatDetail(done), /versions:|go back:/); + assert.doesNotMatch(formatList([done]), /go back/); + store.close(); +}); + +test("verdictIntent and the revert verdict", () => { + const facts = (extra = {}) => ({ found: true, text: "Title", rect: { x: 0, y: 0, w: 100, h: 20 }, styles: { color: "red", margin: "48px" }, ...extra }); + assert.equal(verdictIntent({ intent: "remove" }), "remove"); + assert.equal(verdictIntent({ intent: "remove", revert: { commits: [A] } }), "revert"); + assert.equal(verdictIntent({ intent: null, revertedAt: "2026-11-14T10:00:00.000Z" }), "revert"); + assert.equal(verdictIntent({}), null); + assert.deepEqual(judge("revert", { found: false }, facts()), { ok: true, text: "check: the element is back" }); + assert.equal(judge("revert", { found: false }, { found: false }).ok, null); + assert.deepEqual(judge("revert", facts(), { found: false }), { ok: true, text: "check: the element is gone" }); + assert.deepEqual(judge("revert", facts(), facts()), { ok: false, text: "check: the element did not change back" }); + assert.deepEqual(judge("revert", facts(), facts({ styles: { color: "red", margin: "24px" } })), { ok: true, text: "check: changed style (margin)" }); + assert.equal(judge("revert", facts(), facts({ rect: { x: 0, y: 50, w: 100, h: 20 } })).ok, null); + assert.equal(judge("revert", null, facts()).ok, null); + assert.equal(judge("revert", facts(), null).ok, null); + assert.equal(judge("remove", facts(), facts()).ok, false, "the other intents keep their rule"); +}); diff --git a/server/test/ship.test.js b/server/test/ship.test.js index b925afe..20efde2 100644 --- a/server/test/ship.test.js +++ b/server/test/ship.test.js @@ -175,6 +175,36 @@ test("(a) happy path: commit, gate, merge, staging, check, close and clean up", assert.deepEqual(f.projCalls().map((c) => c.args), [["release", "demo", "staging"]]); }); +test("(a2) a revert that deletes a file and its folder ships: git revert stages the deletion, ship commits it", async (t) => { + const f = await fixture(t); + // An earlier pin added a file in a new folder and changed app.txt; it is on main. + mkdirSync(join(f.main, "parts")); + writeFileSync(join(f.main, "parts/badge.txt"), "badge\n"); + writeFileSync(join(f.main, "app.txt"), "one\nTWO\nthree\n"); + await git(f.main, "add", "."); + await git(f.main, "commit", "-q", "-m", "Pin #11: badge"); + const fix = await git(f.main, "rev-parse", "HEAD"); + await git(f.main, "push", "-q", "origin", "main"); + await git(f.wt, "fetch", "-q", "origin"); + await git(f.wt, "reset", "-q", "--hard", "origin/main"); + await git(f.wt, "revert", "--no-commit", fix); + assert.equal(existsSync(join(f.wt, "parts")), false, "the folder is gone with its only file"); + assert.equal(await f.go({ summary: "Back to the page before pin #11", message: "Revert pin #12: badge", paths: ["app.txt", "parts/badge.txt"] }), 0, f.text()); + const [pr] = f.prs; + assert.equal(pr.title, "Revert pin #12: badge"); + assert.equal(await f.originFile("app.txt"), "one\ntwo\nthree"); + assert.notEqual((await run("git", ["-C", f.origin, "cat-file", "-e", "main:parts/badge.txt"])).code, 0, "the file is gone on main"); + assert.deepEqual(f.resolved().map((p) => p.body), [{ summary: "Back to the page before pin #11", commit: pr.mergeCommit }]); +}); + +test("(a3) a path that is in no worktree, no index and no commit stops the commit step with the git error", async (t) => { + const f = await fixture(t); + f.write("app.txt", "one\nTWO\nthree\n"); + assert.equal(await f.go({ paths: ["app.txt", "missing.txt"] }), 1); + assert.match(f.text(), /ship stopped at commit: git commit exited/); + assert.equal(f.prs.length, 0); +}); + test("(b) a failing release.test stops at the gate: nothing pushed, no release, no resolve", async (t) => { const f = await fixture(t); writeFileSync(f.failFlag, ""); diff --git a/server/test/store.test.js b/server/test/store.test.js index 2c373cd..ab302b0 100644 --- a/server/test/store.test.js +++ b/server/test/store.test.js @@ -262,7 +262,7 @@ for (const existingRun of [false, true]) { const file = join(dir, "pins.db"); const old = createOldDatabase(file); if (existingRun) old.exec("ALTER TABLE pins ADD COLUMN run TEXT; UPDATE pins SET run = 'triad:old' WHERE id = 13;"); - const rows = old.prepare("SELECT * FROM pins ORDER BY id").all().map((row) => ({ ...row, run: row.run ?? null, batch: null, model: null, attempts: 0, intent: null, scope: null, presets: null, shot_before: null, shot_after: null, accepted_at: null, reopens: null })); + const rows = old.prepare("SELECT * FROM pins ORDER BY id").all().map((row) => ({ ...row, run: row.run ?? null, batch: null, model: null, attempts: 0, intent: null, scope: null, presets: null, shot_before: null, shot_after: null, accepted_at: null, reopens: null, versions: null, revert: null, reverted_at: null })); const replies = old.prepare("SELECT * FROM replies ORDER BY id").all(); const sequences = old.prepare("SELECT * FROM sqlite_sequence ORDER BY name").all(); assert.doesNotMatch(old.prepare("SELECT sql FROM sqlite_schema WHERE name = 'pins'").get().sql, /'waiting'/); diff --git a/server/test/v3-store.test.js b/server/test/v3-store.test.js index e1b5f3b..c20518a 100644 --- a/server/test/v3-store.test.js +++ b/server/test/v3-store.test.js @@ -228,7 +228,7 @@ test("a v2 file opens as v3: every pin, reply, batch and setting stays; the new t.after(() => rmSync(dir, { recursive: true, force: true })); const file = join(dir, "pins.db"); const old = createV2Database(file); - const rows = old.prepare("SELECT * FROM pins ORDER BY id").all().map((row) => ({ ...row, intent: null, scope: null, presets: null, shot_before: null, shot_after: null, accepted_at: null, reopens: null })); + const rows = old.prepare("SELECT * FROM pins ORDER BY id").all().map((row) => ({ ...row, intent: null, scope: null, presets: null, shot_before: null, shot_after: null, accepted_at: null, reopens: null, versions: null, revert: null, reverted_at: null })); const replies = old.prepare("SELECT * FROM replies ORDER BY id").all(); const batches = old.prepare("SELECT * FROM batches ORDER BY id").all(); const rootpage = old.prepare("SELECT rootpage FROM sqlite_schema WHERE name = 'pins'").get().rootpage;