diff --git a/.agents-docs/AGENTS-architecture.md b/.agents-docs/AGENTS-architecture.md index 9bfec1e..b15e49f 100644 --- a/.agents-docs/AGENTS-architecture.md +++ b/.agents-docs/AGENTS-architecture.md @@ -15,10 +15,13 @@ plan2code/ │ │ ├── resolve.md # Per-type resolution + graduating the fog │ │ ├── handoff.md # Clearing gate + PLAN-DRAFT handoff │ │ └── trail.md # Every-response map visual + pathed resume command +│ ├── shared-references/ # Reference files shared across skills +│ │ └── building-habits.md # Find the cause, test first, pin behaviour (quick-task, implement, implement-review) │ ├── plan2code-review-references/ # Reference files for review skill │ │ ├── verification-protocol.md # Deep verification + confidence calibration │ │ ├── dimensions.md # 11 dimensions with detailed checklists │ │ ├── false-positives.md # Known false-positive patterns +│ │ ├── reviewer-brief.md # Fill-in brief for the one fresh helper that runs the analysis │ │ └── session-end.md # Next-step routing at review session end │ ├── plan2code-init-update-references/ # Reference files for init-update skill │ │ └── ai-agent-file-sync.md # Step 7: replace AI configs with AGENTS.md refs @@ -102,9 +105,11 @@ plan2code/ | `plan2code-2-document.md` | 2 | Create implementation specs | | `plan2code-3-implement.md` | 3 | Execute implementation (phase by phase) | | `plan2code-3-implement-review.md` | 3 | Execute one phase, run focused review and fixes, then request approval | -| `plan2code-review.md` | review | Post-implementation comprehensive review | +| `plan2code-review.md` | review | Post-implementation comprehensive review, analysed by one fresh helper when the tool has one (verified in session; the report says who reviewed) | | `plan2code-4-finalize.md` | 4 | Validate, summarize, feedback, archive (steps 1–7, +optional 6.5) | | `plan2code-handoff.md` | handoff | Compact the conversation into a self-contained handoff document for a fresh session | +| `plan2code-xray.md` | xray | Explain how and why an area works (files, commits, PRs via `gh` when present), or rank the rough spots worth fixing into `ARCHITECTURE-BRIEF-.md` for Pathfinder or Plan; never edits code | +| `plan2code-diagnose.md` | diagnose | Find a bug's cause under the find-the-cause-first habit (`references/building-habits.md`) and write it up as `specs//DIAGNOSIS-.md` without fixing it, then offer Quick Task to fix it, or Plan when the fix is big. The dashboard scan reports such a folder as spec state `diagnosed` ("Bug diagnosed"), which lights Quick Task (suggested) and Plan. Once Quick Task marks the diagnosis `Fixed` (nothing past it in the folder) the state is `fixed` ("Bug fixed"): no pipeline card lights, the picker never pre-selects it, and Quick Task offers to archive it with `specs.mjs archive` | | `plan2code-changelog.md` | changelog | Check the CHANGELOG version against the default branch, suggest editable entries for new work, keep `package.json` aligned, offer to commit the result through Git | | `plan2code-git.md` | git | Branches, pull (with conflict help), push, publish and commits (clear message, suggested splits) on the web console's git board, or plain instructions in the terminal (`switch to main`, `commit and push`); asks before every push, publish and delete | @@ -124,7 +129,7 @@ Examples: Some workflows use companion reference files for depth that does not need to load on every invocation. The orchestrator (main workflow file) loads them via `Read` directives during execution. -**Pattern:** `src/-references/` (e.g., `plan2code-review-references/`) +**Pattern:** `src/-references/` (e.g., `plan2code-review-references/`). A file several skills read lives in `src/shared-references/` instead and ships to each through `additionalReferences` (e.g., `building-habits.md` into Quick Task, Implement and Implement + Review). **How the installer handles them:** the directory is copied verbatim to `skills//references/`, so `Read references/.md` resolves consistently for every agent. There is one output format, with no flat-file sibling directory or path rewrite. @@ -151,6 +156,7 @@ Anything a workflow step decides with one correct answer (parsing a spec's check | `pathfinder.mjs` (own) | 0-pathfinder | `reconcile`, `frontier`, `claim`, `resolve`, `rule-out`, `trail`, `gate`, `lint`, `brief-data` | | `feedback-payload.mjs` (own) | 4-finalize | STEP 6.5's payload (real sha256 prompt hashes) and the gh / browser / print submission tiers | | `handoff-path.mjs` (own) | handoff | Timestamped path, OS temp dir, git ignore check | +| `xray.mjs` (own) | xray | `hotspots` (churn, files changed together, often-changed files with no test, from `git log` over a capped window) and `history ` (commits following renames, a blame summary, PR titles and first paragraphs through `gh` when signed in, and which sources were used). Read-only | | `changelog-state.mjs` (own) | changelog | `state`, `bump`, `set-package-version`: the default branch's version, whether the branch's entry can be extended (not released, not on another branch), the file's heading style, the gap since the entry was last touched; only `set-package-version` writes, and only the version field | | `git.mjs` (own) | git | `state`, `plan`, `branch-check`, `init-check`, `delete-check`, `cleanup-list`, `conflicts`, `pr-url`, `classify-error`: the repo snapshot, each action's exact command and confirm text (shared by the terminal and the board), branch-name, delete, cleanup and git init checks, a stopped rebase's conflicts, the pull-request link and git's errors sorted into kinds with a next step. Read-only: the agent runs every command it prints, and `guard()` refuses force push, hook skipping, amend, remote delete and blanket add | @@ -190,7 +196,7 @@ Optional local browser UI shipped with **every** skill. Source lives in `src/web | `public/favicon.js` | The tab icon's status bar. `faviconState({ mood, spin, finished })` (PURE) maps the call `renderStatus()` makes for Planny's line to `busy` (the spinning ring), `ready` (`point`), `attention` (`adrift`, `gone`, or `work` without the ring — the stale line) or `plain` (finished, `happy`); `faviconSvg()` is `FAVICON_BODY` (kept equal to `favicon.svg` by a test) plus a bar along the bottom edge in the `FAVICON_COLORS` color (busy dashed on a white strip, so the states differ by pattern; the rest solid); `setFavicon()` swaps both `` hrefs only on a change — the SVG as a data URL, the PNG link drawn through a canvas. Called from `say()` in `renderStatus()`, which runs every second | | `public/subagents.js` | PURE, no imports: the Subagents switch. `SUBAGENT_WORKFLOWS` / `offered()` (the opt-in table: `implement`, `implement-review`, `quick-task`, `review`, `pathfinder`, each with its default instruction), `cleanSetting()` (`{ on, instruction, max }` or `{ error }`: `bad`, `too-long` past 2,000 characters, `max` outside 1-20), `FRAME_LINES`, `blockFor(setting, told)` (the `Subagents:` lines and `subagents` field an agent is owed, given the session setting and its cursor; never says "off" to an agent not told "on"), `checkHelper()` / `checkHelpers()` (the `helpers` house rule) and the page's view rules `showSwitch()`, `switchLabel()`, `helperRows()`, `showTab()`, `CHECKIN_LINE`. Imported by the server, `console.mjs`, `lib.mjs`, the page and the tests; in `SERVABLE` and preloaded | | `picker.mjs` | the per-OS native folder picker behind **Browse…** (`pickerCommand()` → `{ command, args, env }` or `null`; `pickFolder()` runs it with async `spawn`, so the server keeps serving while the dialog is open). Copied from `src/launcher/plan2code.js` (self-contained CommonJS, so it cannot be shared) with the prompt as a parameter; a drift test keeps the two in step | -| `update-check.mjs` | the dashboard's release check, server-only (never in `SERVABLE`): `compareVersions()` (numeric X.Y.Z, `null` otherwise), `latestTag()` (the highest `refs/tags/vX.Y.Z`, peeled `^{}` and pre-release tags skipped), `checkForUpdate({ installed, cacheFile, now, run })` (never throws) and `runLsRemote()` (`git ls-remote --tags` on the repo: no shell, `GIT_TERMINAL_PROMPT=0`, `GCM_INTERACTIVE=never`, SSH `BatchMode` when `GIT_SSH_COMMAND` is unset, `windowsHide`, killed at 10 s; git authenticates itself, the console never touches a credential). The answer, failures included, is cached for an hour in `~/.plan2code/console/update-check.json` (`UPDATE_CHECK_FILE`, in `PROTECTED_CONSOLE_FILES` so no sweep removes it). `server.mjs` starts it after the ready line and never awaits it; `stateFrame()` carries `update: { installed, latest }` only when a newer release exists (its `latest` is part of `haveKey()`, so a page that connected first still gets it), and `GET /version` returns `{ version, latest }`. Tests seed a fresh cached failure in every console home, so no test server reaches the network | +| `update-check.mjs` | the dashboard's release check, server-only (never in `SERVABLE`): `compareVersions()` (numeric X.Y.Z, `null` otherwise), `latestTag()` (the highest `refs/tags/vX.Y.Z`, peeled `^{}` and pre-release tags skipped), `checkForUpdate({ installed, cacheFile, now, run })` (never throws) and `runLsRemote()` (`git ls-remote --tags` on the repo: no shell, `GIT_TERMINAL_PROMPT=0`, `GCM_INTERACTIVE=never`, SSH `BatchMode` when `GIT_SSH_COMMAND` is unset, `windowsHide`, killed at 10 s; git authenticates itself, the console never touches a credential). The answer, failures included, is cached for an hour in `~/.plan2code/console/update-check.json` (`UPDATE_CHECK_FILE`, in `PROTECTED_CONSOLE_FILES` so no sweep removes it). `server.mjs` starts it after the ready line and never awaits it; `stateFrame()` carries `update: { installed, latest }` only when a newer release exists (its `latest` is part of `haveKey()`, so a page that connected first still gets it), and `GET /version` returns `{ version, latest }`. Tests seed a fresh cached failure in every console home, so no test server reaches the network. The `plan2code` launcher reads the same cache for its terminal release notice (a copy of this module sits in `~/.plan2code/bin/`) | | `public/chat.js` | the Quick question chat's PURE rules, shared by the server and the page: `CHAT_LIMIT` / `CHAT_MAX_CHARS` / `CHAT_MAX_ATTACHMENTS` (the combined image + document cap; `CHAT_MAX_IMAGES` is kept as an alias of it), `chatOffline()` (the server's `409 offline` guard), and the page's view model (`chatView`, `sendState`, `nextAbout`, `contextOptions`, `unreadDot` / `shouldChime`). Ask context is the `{ history, about }` model: `nextAbout()` records the last 3 places visited in `history` and sets `about` only when the person picks one from **+ Add context** (`contextOptions()` lists that history plus *This spec*); dropping it or a successful send clears it, so the page never attaches context on its own. Imports only `answers.js`, no module-scope DOM, so `node --test` covers it | | `public/starters.js` | PURE, no imports: the Role list (`ROLES`, `ROLE_NOT_SET`, `normalizeRole()`, `needsRoleNudge()`: the dashboard banner shows until `looks.json` carries any `role`), the 19 starter templates (Markdown `## heading` sections, shape pinned by a test) and their per-role orders (`TEMPLATES`, `TEMPLATE_ORDERS`, `templatesFor()`, `templateSwap()` for the replace prompt), and the Ask starter sets (`STARTER_SETS`, `STARTER_SET_FOR`, `startersFor()`). Imported by `app.js` and the tests; in `SERVABLE`, preloaded by `index.html` and parse-checked. The page owns the wording; a skill only flags its fresh-idea `text` card with `"templates": "idea"` | | `public/answers.js` | the page's PURE answer-shaping logic (what an answer reads as, what a placeholder offers, whether a send carries an answer at all). Split out of `app.js` because `app.js` cannot be imported outside a browser, so anything left in it is untestable. The `scripts/test-web-console-*.mjs` tests import it directly. | @@ -198,7 +204,7 @@ Optional local browser UI shipped with **every** skill. Source lives in `src/web | `public/boot.js` | `playWake()`: the dashboard's first-open wake-up. Self-contained (it owns its timers, the listeners that swallow input mid-run and the one measured glide transform; the page's `stir()` callback times the nudge between the click and the boot, which `app.js` fills with one snore; `skipEl` — the muted Skip button, and Escape — ends the run early with `onSkip` as the cue to silence queued sounds) and free of module-scope DOM access, so it can be imported by the tests and kept out of `app.js`'s render paths; `GLIDE_AT_MS` / `DONE_AT_MS` are its timings | | `console.md` | the core of the agent-facing contract, read once per conversation (every skill ships the same copy, so a dashboard hop never re-reads it): starting, the turn (`post --wait`, the exit codes, handling a send, `settle`), posting, the payload and its kinds, documents (including `file` blocks), the house rules, and an index of the topic files below with the moment each is read. A test caps it at 24,000 characters | | `console-finish.md` · `console-stop.md` · `console-chat.md` · `console-workspace.md` · `console-subagents.md` · `console-launches.md` · `console-meter.md` · `console-attachments.md` · `console-trouble.md` | topic files, each read only when its moment first comes: finishing (the finish and its buttons), stop requests (the way home mid-workflow, `stopWarning`, resuming a pause), Quick questions, the Workspace, standing instructions and helper reports, dashboard launches and the menu payload, the session meter's `run` events (read only when a `run` is refused: the notes inline every `run`), keeping a cited note attachment, and recovery | -| `notes/.md` | per-workflow notes (`init` for both inits, `pathfinder` with Briefs, `plan`, `revise-plan`, `document`, `implement` for both builds, `quick-task`, `review`, `finalize`, `handoff`, `changelog`, `git`). Each skill's Interface line reads `/console.md` and its own notes file right after `open`; a test checks every skill names one that exists | +| `notes/.md` | per-workflow notes (`init` for both inits, `pathfinder` with Briefs, `plan`, `revise-plan`, `document`, `implement` for both builds, `quick-task`, `review`, `finalize`, `handoff`, `changelog`, `git`, `xray`, `diagnose`). Each skill's Interface line reads `/console.md` and its own notes file right after `open`; a test checks every skill names one that exists | | `building.md` · `building-review.md` | the build half of the contract, for `implement`, `implement-review` and `quick-task`: progress posts (`agent.activity`, `agent.quietMinutes`, `file` blocks re-read with `refresh`), the chat check between tasks, questions mid-build and stop requests; `building-review.md` is the review run on the page (the sign-off's `review` verdict, **Review it now**, Implement + Review's Stage 2), read only when asked for | Key design points: @@ -214,7 +220,7 @@ Key design points: - **`looks.width` is a person-level preference** alongside theme, accent and sounds in `looks.json`. `CARD_WIDTHS` in `public/palette.js` (`narrow` 720, `comfortable` 880 — default — `wide` 1080) is read by the page (`cardWidth()` validates a saved value) and by `server.mjs`, which paints `data-width` on first load; `app.css` maps `data-width` onto the single `--card-width` variable that every column rule uses. - **`GET /overview` is the one route that reads a project file.** It serves `/overview.md` as `text/markdown` with `cache-control: no-store` (so the Overview tab is always fresh), or `404 { "error": "no overview" }`. A dashboard session honours `?spec=` only when it equals a `dir` in `state.scan.specs`; every other workflow uses `state.specDir` and ignores the query. The root is `state.worktree` (fallback `state.project`), and `readOverview()` resolves and `realpath`s the file and refuses anything outside the root's realpath, so `../`, absolute paths and outward symlinks all 404. - **Month-old sessions are deleted whole.** `open` lists `staleSessions()` (directories matching the session-id pattern whose `state.json` mtime is older than 30 days, never the sid being opened — no exceptions for paused sessions or unread sends) and `staleScratch()` (top-level regular `.json` / `.mjs` files in the console folder older than 30 days, never `looks.json` or `console-dir` — `PROTECTED_CONSOLE_FILES` — never a directory or symlink) before it prints, and removes them after; `removeSessions()` / `removeScratch()` re-check every name against the session-id pattern / the scratch-name rule before deleting — not the age, the skipped sid or the file type, which the `stale*` listing already decided, so never hand them names that did not come from it. `console.md` tells agents to write temporary payload files into the session's own folder so they go with it. -- **User Preferences → Cleanup deletes on demand, from a list the server makes.** `POST /cleanup` (origin-checked) with `{ scan: true }` returns `cleanupFindings()`: `{ items: [{ id, where, name, kind, bytes }], bytes }`, ids `session:` (the `staleSessions()` rule, and every file in the folder that old too, never the serving sid), `console:` (anything at the top of the console home but `PROTECTED_CONSOLE_FILES`, `sessions` and `runtime`, directories too) and `root:` (anything at the top of `~/.plan2code` but `KEPT_PLAN2CODE_ENTRIES`: `console`, `bin`, `launcher.json`, `models.json`) and `completed:` (each folder or link directly under the session worktree's `specs--completed/` whose newest mtime is older than the session age, 30 days; loose files there stay; the server passes `project: sessionWorktree() || PROJECT`, and without a `project` the archive is never scanned). Both stray kinds must be untouched for `STRAY_GRACE_MS` (an hour, by the newest `lstat` mtime anywhere inside, since rewriting a file never moves its folder's mtime; unreadable reads as fresh): the same folders hold `workspaces.json.lock` and `writeJsonAtomic()`'s `..tmp`, which live for milliseconds. `root:` is only scanned when the console home is `/console`, so a test or dev home never reaches the real folder. Paths never go to the page. `{ delete: [id] }` runs `removeCleanup()`, which re-scans and removes only ids still on the fresh list (symlinks unlinked, never followed), returning `{ removed, bytes, failed }`. The page always shows the list before **Delete these**. +- **User Preferences → Cleanup deletes on demand, from a list the server makes.** `POST /cleanup` (origin-checked) with `{ scan: true }` returns `cleanupFindings()`: `{ items: [{ id, where, name, kind, bytes }], bytes }`, ids `session:` (the `staleSessions()` rule, and every file in the folder that old too, never the serving sid), `console:` (anything at the top of the console home but `PROTECTED_CONSOLE_FILES`, `sessions` and `runtime`, directories too) and `root:` (anything at the top of `~/.plan2code` but `KEPT_PLAN2CODE_ENTRIES`: `console`, `bin`, `launcher.json`, `install.json`, `models.json`) and `completed:` (each folder or link directly under the session worktree's `specs--completed/` whose newest mtime is older than the session age, 30 days; loose files there stay; the server passes `project: sessionWorktree() || PROJECT`, and without a `project` the archive is never scanned). Both stray kinds must be untouched for `STRAY_GRACE_MS` (an hour, by the newest `lstat` mtime anywhere inside, since rewriting a file never moves its folder's mtime; unreadable reads as fresh): the same folders hold `workspaces.json.lock` and `writeJsonAtomic()`'s `..tmp`, which live for milliseconds. `root:` is only scanned when the console home is `/console`, so a test or dev home never reaches the real folder. Paths never go to the page. `{ delete: [id] }` runs `removeCleanup()`, which re-scans and removes only ids still on the fresh list (symlinks unlinked, never followed), returning `{ removed, bytes, failed }`. The page always shows the list before **Delete these**. - **The console's path is stated, not searched for.** Each Interface line names `references/web-console/` beside the SKILL.md and the `~/.plan2code/console/console-dir` fallback; the prompts with room (all but pathfinder, plan, document and finalize, which sit near the char limit) also name the canonical global install path `~/.agents/skills//references/web-console/` (the skills CLI's real store; every agent dir links into it), and every `console.mjs open` writes `HERE` to `~/.plan2code/console/console-dir` (only `open`, so a `help` or dev run from `src/` never repoints it) so a later session can read the path from a fixed place. Without these the agent hunts the skill install dirs on every session. - **`open` needs no payload, and runs first.** `--file` and `--title` are optional (the title defaults to the folder name). Every skill's Interface line puts `node "/console.mjs" open --workflow ` BEFORE reading console.md or the project, and a test (`every skill opens the console before it reads anything`) keeps it that way; a blank session renders a starting screen ("Starting Pathfinder", Planny in flight) until the first post. Every skill replaces the flight with its own animated pose (init — init-update borrows it — pathfinder, plan — revise-plan borrows it — document, implement — implement-review borrows it — finalize, quick-task, review, handoff; only the dashboard keeps the flight), cloned by `startStage()` in `app.js` from ` + +

Delete this spec?

+ +
+ + + +
+

Leave this workflow?

@@ -2570,7 +2659,7 @@

A new Plan2Code is available

@@ -2579,7 +2668,11 @@
  • Run this in your terminal (not in this page or your agent):
    - It opens the installer's menu. Back at your prompt with no output at all? npm + It updates everything that was installed (the skills, the plan2code + command and any extras you added), with no menu. If the plan2code + command is not installed, run this instead: +
    + Back at your prompt with no output at all? npm could not reach the repository and hid the reason: run git ls-remote https://github.com/jparkerweb/plan2code.git to see it.
  • diff --git a/src/web-console/public/meter.js b/src/web-console/public/meter.js index c20ada7..5a9a211 100644 --- a/src/web-console/public/meter.js +++ b/src/web-console/public/meter.js @@ -30,14 +30,16 @@ export const WEIGHTS = Object.freeze({ "git-commits": 0, "git-conflict": 1, changelog: 1, + xray: 1, + diagnose: 1, }); // Workflows whose launch itself scores WEIGHTS[workflow]. Pathfinder, // implement and implement-review score only through the agent's `run` -// reports; dashboard and handoff never score; git and changelog score 1 on +// reports; dashboard and handoff never score; git, changelog, xray and diagnose score 1 on // launch (Git then adds its commit tally and conflict help). export const LAUNCH_COUNTED = Object.freeze( - new Set(["plan", "revise-plan", "document", "review", "quick-task", "init", "init-update", "finalize", "git", "changelog"]) + new Set(["plan", "revise-plan", "document", "review", "quick-task", "init", "init-update", "finalize", "git", "changelog", "xray", "diagnose"]) ); // Git's commits weigh what they add up to: each `git-commits` run carries @@ -140,6 +142,8 @@ const WORKFLOW_NAMES = Object.freeze({ handoff: "Handoff", git: "Git", changelog: "Changelog", + xray: "X-ray", + diagnose: "Diagnose", }); // The skill run an entry belongs to, from its ledger id ("L3:..." -> "L3"). @@ -157,6 +161,8 @@ const LAUNCH_LABELS = Object.freeze({ finalize: "Finalize started", git: "Git started", changelog: "Changelog started", + xray: "X-ray started", + diagnose: "Diagnose started", }); const RUN_LABELS = Object.freeze({ "pathfinder-chart": "Pathfinder map written", @@ -177,6 +183,8 @@ const RUN_LABELS = Object.freeze({ "git-commits": "Commits in Git", "git-conflict": "Git conflict help", changelog: "Changelog run", + xray: "X-ray run", + diagnose: "Diagnose run", }); // The unit a run names, from its ledger id ("L3:phase-2" -> "phase-2"). diff --git a/src/web-console/public/subagents.js b/src/web-console/public/subagents.js index 43786a9..8d1e8b2 100644 --- a/src/web-console/public/subagents.js +++ b/src/web-console/public/subagents.js @@ -24,7 +24,7 @@ export const SUBAGENT_WORKFLOWS = Object.freeze({ }), review: Object.freeze({ instruction: - "Split the review across helpers by area (for example correctness, tests and security), then merge and de-duplicate their findings yourself before you report.", + "Run the review's analysis in one fresh helper briefed only with the spec and the change set (references/reviewer-brief.md); verify every finding yourself before you report.", }), pathfinder: Object.freeze({ instruction: diff --git a/src/web-console/server.mjs b/src/web-console/server.mjs index b6a153d..d184420 100644 --- a/src/web-console/server.mjs +++ b/src/web-console/server.mjs @@ -54,6 +54,9 @@ import { rememberedWorkspace, removeCleanup, remoteWarning, + SHOTS_DIR_NAME, + SHOT_NAME, + shotType, saveSubagentStoreEntry, PR_HOST_KINDS, savePrHost, @@ -131,6 +134,25 @@ const EXT_ALT = UPLOAD_EXTS.join("|"); const UPLOAD_ANY_ROUTE = new RegExp(`^/uploads/([0-9a-f-]{36})\\.(${EXT_ALT})$`); const UPLOAD_NAME = new RegExp(`^[0-9a-f-]{36}\\.(${EXT_ALT})$`); +// Screenshots the agent saved for a doc's image block (Show me it working), +// only ever directly inside /shots/ under SHOT_NAME's plain shape. +const SHOTS_DIR = path.join(DIR, SHOTS_DIR_NAME); +const SHOT_TYPES = { png: "image/png", jpeg: "image/jpeg", webp: "image/webp" }; + +function shotPath(name) { + if (!SHOT_NAME.test(name)) return null; + const file = path.resolve(SHOTS_DIR, name); + if (!file.startsWith(path.resolve(SHOTS_DIR) + path.sep)) return null; + try { + const real = fs.realpathSync.native(file); + const fold = (p) => (process.platform === "win32" || process.platform === "darwin" ? p.toLowerCase() : p); + if (fold(path.dirname(real)) !== fold(fs.realpathSync.native(SHOTS_DIR))) return null; + return fs.statSync(real).isFile() ? real : null; + } catch { + return null; + } +} + // A kept attachment's name, as attachmentName() in lib.mjs writes it: // -.. const KEPT_ROUTE = new RegExp(`^/attachments/([a-z0-9-]{1,40}-[0-9a-f-]{8}\\.(${EXT_ALT}))$`); @@ -1468,6 +1490,25 @@ const server = http.createServer((req, res) => { }); } + // A screenshot for a doc's image block. Matched on the raw request line too, + // like uploads: anything URL parsing had to fold (`..`) is not a shot. + if (pathname.startsWith("/shots/") || req.url.startsWith("/shots/")) { + if (req.method !== "GET") return json(res, 405, { error: "method" }); + const name = pathname.slice("/shots/".length); + const file = req.url === pathname ? shotPath(name) : null; + if (!file) return json(res, 404, { error: "not found" }); + let buf; + try { + buf = fs.readFileSync(file); + } catch { + return json(res, 404, { error: "not found" }); + } + // The bytes, not the name, pick the type: the file may have changed since it was posted. + const type = SHOT_TYPES[shotType(buf)]; + if (!type) return json(res, 404, { error: "not found" }); + return send(res, 200, buf, type, { "cache-control": "no-store" }); + } + // Matched on the raw request line as well as the parsed path: URL parsing // folds `..` segments away, and nothing that needed folding is an upload. // GET and DELETE take images and documents alike.