diff --git a/.agents-docs/AGENTS-architecture.md b/.agents-docs/AGENTS-architecture.md index f3411f6..5d69020 100644 --- a/.agents-docs/AGENTS-architecture.md +++ b/.agents-docs/AGENTS-architecture.md @@ -63,7 +63,7 @@ plan2code/ │ ├── node-test.mjs, page-test-helpers.mjs # `npm test`'s `node --test`, files at once capped at one per spare core; the page tests' browser sessions and their redraw-safe `styleOf()`, `stylesOf()`, `scrollCard()` │ ├── test-launcher.mjs, test-getting-started.mjs # Launcher suite; newcomer docs kept in step │ ├── test-skill-scripts.mjs, test-script-.mjs, test-git-repo.mjs, skill-script-helpers.mjs, fixture-helpers.mjs # Skill script suites and fixtures -│ ├── check-versions.mjs, fix-line-endings.mjs, play.mjs # Six-file version sync; restores LF everywhere (also pretest + pre-commit); tries the games from src/ +│ ├── check-versions.mjs, fix-line-endings.mjs, play.mjs # Version sync across every file that carries it (twelve places, also run by npm test); restores LF everywhere (also pretest + pre-commit); tries the games from src/ │ ├── measure-console-wire.mjs, css-helpers.mjs, ghoul-test-helpers.mjs, fixtures/, console-wire-runs/ # Wire-size probe and its captured runs; shared CSS and Ghoul Rush test helpers; skill-script fixtures │ └── validate-char-count.js # Pre-commit character count validator ├── skills/ # Generated, gitignored build output — one Agent Skill per src/ prompt @@ -546,7 +546,8 @@ Key design points: - **The CLI hands the agent its terminal line.** `open`, `post` and `wait` (exits `0` and `10`) print `terminalLine: "→ Look at the web console: "` (`terminalLine()` in `sessions.mjs`), and `console.md` asks the agent to end every terminal message with the latest one verbatim, so the tool builds the line rather than the model. In `wait` it is added to the printed result only; the collected `result.json` on disk never carries it. `open` also prints `swept: { sessions, scratch, handoffs }` when it found anything to clean. - **State fields written by `open`, not the agent.** Every `open` (fresh or resume) records `state.worktree` and `state.branch` from `repoRoots()` — the branch is read off `/HEAD` on the walk that already finds the gitdir (`""` on a detached HEAD or outside git; env-relocated repos ask git, as before) — and the page shows them in the footer as the workspace label (`footerLabel()`: `folder · branch`, or `folder + N folders · branch` once folders are added, stepping down through narrower tiers); a click opens the Workspace dialog. `state.wake = true` is set only by a fresh `open --workflow dashboard` and deleted by every resume (server restart, launch, Back to the dashboard); the page also keeps a per-sid `sessionStorage` guard so a reload never replays it. - **`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 `routes.mjs`, which paints `data-width` on first load; `styles/tokens.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 with `?file=map` / `?file=draft` the spec's `pathfinder/map.md` / live `PLAN-DRAFT-*.md` (the dashboard's Map and Plan draft tabs, shown only while the spec has no overview; `readSpecFile()` picks the file and names it in `x-spec-file`), or an empty `204` when there is no such file (normal for most specs, and no failed request in the browser console). A dashboard session honors `?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 `readSpecFile()` (which `readOverview()` wraps) resolves and `realpath`s the file and refuses anything outside the root's realpath, so `../`, absolute paths and outward symlinks all get the same 204, as do an unscanned `?spec=` and an unknown `?file=`. +- **`GET /agents-doc` is the other route that reads a project file** (the dashboard's AGENTS.md tab, right after Dashboard, shown while the project has an `AGENTS.md`). A dashboard session only; it serves `AGENTS.md` or one markdown file directly under `.agents-docs/` (`?file=`, default `AGENTS.md`; `readAgentsDoc()` in `sessions.mjs` allows exactly those two shapes and `realpath`s the file inside the root), as `text/markdown` with `no-store`, or a `204` for anything else. The page links `.agents-docs/` files in place through `md()`'s `link` option (`renderAgentsDoc()` in `screens/docs.js`). +- **`GET /overview` reads a project file too.** It serves `/overview.md` as `text/markdown` with `cache-control: no-store` (so the Overview tab is always fresh), or with `?file=map` / `?file=draft` the spec's `pathfinder/map.md` / live `PLAN-DRAFT-*.md` (the dashboard's Map and Plan draft tabs, shown only while the spec has no overview; `readSpecFile()` picks the file and names it in `x-spec-file`), or an empty `204` when there is no such file (normal for most specs, and no failed request in the browser console). A dashboard session honors `?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 `readSpecFile()` (which `readOverview()` wraps) resolves and `realpath`s the file and refuses anything outside the root's realpath, so `../`, absolute paths and outward symlinks all get the same 204, as do an unscanned `?spec=` and an unknown `?file=`. - **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 → System → 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, folder? }], bytes }` (`folder` on `notepad:` items only), 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`, `handoffs`, `notepads`, `app`, `app.json`, `agents.json`), `notepad:` (a month-old notepad, whole; see Notebook below) 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. diff --git a/.readme/web-console.md b/.readme/web-console.md index 0206f72..24bac70 100644 --- a/.readme/web-console.md +++ b/.readme/web-console.md @@ -1955,6 +1955,7 @@ origin. | `POST /chat` | A Quick question `{ text, about?, images?, files?, conversation }`, or `{ reset: true, conversation }` for New conversation. Appended to the session's `chat.ndjson`. 400 `too-long` (over 4,000 characters), `image`, `file` or `bad`; 409 `offline`, `stale` or `limit` (10 per conversation). Never refused because a card send is still uncollected. | | `POST /chat/decision` | Approve or Decline on an edit the agent proposed: `{ re, decision, text?, conversation }`. Once per proposal; does not count toward the 10. | | `GET /overview?spec=specs/[&file=map\|draft]` | The Overview tab's read of `/overview.md` (or, with `file=`, the Map tab's `pathfinder/map.md` or the Plan draft tab's live `PLAN-DRAFT-*.md`), as `text/markdown` with `cache-control: no-store` and the file's spec-relative name, URL-encoded, in `x-spec-file`. A missing file is a 204. On the dashboard `spec` must be one of the scanned specs; elsewhere the session's own spec is used. The file's real path must stay inside the project, so `../`, absolute paths and symlinks pointing out all get the same 204 as a missing file, as does an unscanned `spec` or an unknown `file`. | +| `GET /agents-doc[?file=]` | The Dashboard's AGENTS.md tab: `AGENTS.md` (the default) or one `.agents-docs/.md`, as `text/markdown` with `cache-control: no-store`. A dashboard only; any other file name, a missing file or a path that leaves the project is a 204. | | `GET /handoff?id=` | *Read it all*: the handoff's `.md` from `~/.plan2code/handoffs/`, as `text/markdown` with `cache-control: no-store`. A dashboard only, and only an id its own scan listed: a used, unknown or malformed id is 404. | | `GET /workspace` | The Workspace dialog's list: folders, `missing`, `remote` and the agent's folder `issues`. `?check=1` re-checks every folder on disk first. | | `POST /workspace/add` | `{ path, name?, description? }`. The path is resolved against the folder the session started in (`~` expanded) and must be a folder: 400 `not-a-folder`, `duplicate` (with its `name`; compared case-insensitively on Windows and macOS), `bad-name`, or `name-taken` with a `suggest`. Answers the new entry, `nested: true` when it sits inside another folder in the list. | diff --git a/CHANGELOG.md b/CHANGELOG.md index e0930ce..8a1f9c9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,10 @@ All notable changes to Plan2Code will be documented in this file. - **desktop app**: the terminal now starts docked on the right on a fresh install, as intended, instead of at the bottom. The app always reported a saved `bottom` dock, so the page's right-dock default never ran; it now reports nothing until a dock is saved. A dock you already chose is kept. +### ✨ Added + +- **web console**: the dashboard has an **AGENTS.md** tab right after Dashboard, shown while the project has an `AGENTS.md`. It reads the file fresh from disk, read-only, and links into `.agents-docs/` open in place with a way back. + ## v3.0.2 ### ✨ Added diff --git a/scripts/test-web-console-agents-doc.mjs b/scripts/test-web-console-agents-doc.mjs new file mode 100644 index 0000000..f325e85 --- /dev/null +++ b/scripts/test-web-console-agents-doc.mjs @@ -0,0 +1,71 @@ +// The Dashboard's AGENTS.md tab: which files the server will read for it. +// Run with: node --test scripts/test-web-console-agents-doc.mjs + +import test from "node:test"; +import assert from "node:assert/strict"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { readAgentsDoc } from "../src/web-console/sessions.mjs"; + +function project(files) { + const base = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-agents-doc-")); + const root = path.join(base, "project"); + for (const [rel, text] of Object.entries(files)) { + fs.mkdirSync(path.dirname(path.join(root, rel)), { recursive: true }); + fs.writeFileSync(path.join(root, rel), text); + } + fs.mkdirSync(root, { recursive: true }); + fs.writeFileSync(path.join(base, "secret.md"), "outside\n"); + return { base, root }; +} + +test("readAgentsDoc reads AGENTS.md and one markdown file under .agents-docs", async () => { + const { base, root } = project({ "AGENTS.md": "# Guide\n", ".agents-docs/AGENTS-x.md": "# X\n" }); + try { + assert.deepEqual(await readAgentsDoc(root, "AGENTS.md"), { file: "AGENTS.md", text: "# Guide\n" }); + assert.deepEqual(await readAgentsDoc(root, ".agents-docs/AGENTS-x.md"), { file: ".agents-docs/AGENTS-x.md", text: "# X\n" }); + } finally { + fs.rmSync(base, { recursive: true, force: true }); + } +}); + +test("readAgentsDoc is null for a missing file and for any other path", async () => { + const { base, root } = project({ "AGENTS.md": "# Guide\n", "README.md": "readme\n", ".agents-docs/sub/deep.md": "deep\n", ".agents-docs/notes.txt": "t\n" }); + try { + const refused = [ + "README.md", + "agents.md", + "../secret.md", + ".agents-docs/../secret.md", + ".agents-docs/sub/deep.md", + ".agents-docs/notes.txt", + ".agents-docs/missing.md", + ".agents-docs\AGENTS-x.md", + path.join(base, "secret.md"), + "", + null, + ]; + for (const rel of refused) assert.equal(await readAgentsDoc(root, rel), null, String(rel)); + assert.equal(await readAgentsDoc("", "AGENTS.md"), null); + fs.rmSync(path.join(root, "AGENTS.md")); + assert.equal(await readAgentsDoc(root, "AGENTS.md"), null); + } finally { + fs.rmSync(base, { recursive: true, force: true }); + } +}); + +test("readAgentsDoc does not follow a link out of the project root", async (t) => { + const { base, root } = project({ "AGENTS.md": "# Guide\n" }); + try { + fs.mkdirSync(path.join(root, ".agents-docs"), { recursive: true }); + try { + fs.symlinkSync(path.join(base, "secret.md"), path.join(root, ".agents-docs", "leak.md")); + } catch { + return t.skip("symlinks are not allowed here"); + } + assert.equal(await readAgentsDoc(root, ".agents-docs/leak.md"), null); + } finally { + fs.rmSync(base, { recursive: true, force: true }); + } +}); diff --git a/scripts/test-web-console-shape.mjs b/scripts/test-web-console-shape.mjs index c639e9f..4d13e5a 100644 --- a/scripts/test-web-console-shape.mjs +++ b/scripts/test-web-console-shape.mjs @@ -187,7 +187,7 @@ test("shape: no page module sets a style attribute from script", () => { // and WORKSPACE_EDITS for /workspace/add, /edit and /remove. The git board has // no routes of its own: its buttons are sends (`__git`), through /submit. const ROUTE_ORDER = [ - "/health", "/s/", "/handover", "/", "SERVABLE", "/overview", "/handoff", "/version", "/state", "/events", "/draft", + "/health", "/s/", "/handover", "/", "SERVABLE", "/overview", "/agents-doc", "/handoff", "/version", "/state", "/events", "/draft", "/looks", "/looks", "/subagents", "/pr-host", "/models", "/models", "/agents", "/agents", "/agents/test", "/agents/use-path", "/cleanup", "/upload", "/notepad", "/notepad/text", "/notepad/image", "/notepad/thumb", "/notepad/image/delete", "/notepad/tab", "/notepad/tab/rename", "/notepad/tab/delete", "/notepad/tab/order", "/notepad/tab/last", "/notepad/tab/sent", "/notepad/images/", diff --git a/src/web-console/public/render.js b/src/web-console/public/render.js index 4530270..a2ad233 100644 --- a/src/web-console/public/render.js +++ b/src/web-console/public/render.js @@ -64,6 +64,11 @@ function takeMarker(item) { return TASK_MARKERS[m[1]]; } +// While md() runs with a `link` option: a function that takes a link's href and +// returns a click handler to make it an in-page link, or null to leave it to the +// usual rules. Set only for the duration of one md() call. +let linkHook = null; + function safeHref(href) { if (!href) return null; const trimmed = String(href).trim(); @@ -117,6 +122,19 @@ function inlineInto(parent, tokens) { parent.appendChild(document.createElement("br")); break; case "link": { + const onOpen = linkHook && linkHook(String(t.href || "").trim()); + if (onOpen) { + const a = el("a"); + a.href = "#"; + a.addEventListener("click", (e) => { + e.preventDefault(); + onOpen(); + }); + if (t.title) a.title = t.title; + inlineInto(a, t.tokens); + parent.appendChild(a); + break; + } const href = safeHref(t.href); if (!href) { inlineInto(parent, t.tokens); @@ -288,7 +306,7 @@ function blockInto(parent, tokens) { } /** Render markdown into a fresh element. Returns the element. */ -export function md(source, className = "md") { +export function md(source, className = "md", options = {}) { const host = el("div", className); if (!source) return host; let tokens; @@ -298,7 +316,13 @@ export function md(source, className = "md") { host.appendChild(el("p", "md-p", String(source))); return host; } - blockInto(host, tokens); + // `options.link`: see linkHook above. + linkHook = typeof options.link === "function" ? options.link : null; + try { + blockInto(host, tokens); + } finally { + linkHook = null; + } return host; } diff --git a/src/web-console/public/screens/core.js b/src/web-console/public/screens/core.js index e1790bc..a55895a 100644 --- a/src/web-console/public/screens/core.js +++ b/src/web-console/public/screens/core.js @@ -54,7 +54,7 @@ import { helperRows, showTab } from "../subagents.js"; import { FOOTER_TIERS, footerLabel } from "../workspace.js"; import { activity, agentAdrift, agentWorking, askBusy, loopDriving, loopWaiting, loopWaitingKey, asked, awaitingReply, byId, dashboardLive, docs, doingNow, - finish, gitAwaiting, isDashboard, isGitBoard, isOpen, isSpecFileView, items, loadOverview, myTurn, openItems, + AGENTS_VIEW, agentsTabShown, finish, gitAwaiting, isDashboard, isGitBoard, isOpen, isSpecFileView, items, loadAgentsDoc, loadOverview, myTurn, openItems, patience, pressStranded, reviewPending, scan, selSpec, sendCollected, specFileTabs, stagedCount, stranded, topics, workingMs, WORKING_GRACE_MS, workspaceFolders, @@ -67,7 +67,7 @@ import { attachFiles, heldNotes, noteImages, pendingNotes, removeImage } from ". import { closeMentions } from "../mention-box.js"; import { buildPager, fitGrowBox, markFor, markMore, renderCard, renderEndItem, renderNotice } from "./cards.js"; import { sendState, suggestState } from "../send-state.js"; -import { renderBriefButton, renderDoc, renderOverview } from "./docs.js"; +import { renderAgentsDoc, renderBriefButton, renderDoc, renderOverview } from "./docs.js"; import { board, renderGitBoard, resetBoard } from "./git-host.js"; import { renderWorkspace, tellFolderIssues } from "./workspace.js"; import { openHelpOn } from "./help-dialog.js"; @@ -535,6 +535,8 @@ export function adopt(body) { // A spec file tab's file changes under a build, so a tab you are watching // refetches on every new frame too, not only on the click that opened it. if (firstLoad || page.S.specDir !== prevSpecDir || page.S.workflow !== prevWorkflow || isSpecFileView(page.view)) loadOverview(); + // The Dashboard's AGENTS.md tab: found on arrival, re-read while it is open. + if (firstLoad || page.S.workflow !== prevWorkflow || page.view === AGENTS_VIEW) loadAgentsDoc(); if (announce) showArrival(announce); // New entries land at the bottom of the rail. Gliding down to them beats // leaving the list parked where it was while it grew underneath. @@ -991,7 +993,7 @@ function withFocus(fn) { // (the dashboard menu, the end page). function currentScroller() { if (!drawnView) return null; - if (drawnView.startsWith("doc:") || isSpecFileView(drawnView)) return $("main"); + if (drawnView.startsWith("doc:") || isSpecFileView(drawnView) || drawnView === AGENTS_VIEW) return $("main"); if (drawnView === "questions") return $("main").querySelector(":scope > .card.question"); if (drawnView === "ask") return $("main").querySelector(".ask-list"); return null; @@ -1430,6 +1432,10 @@ function renderViews() { const fileTabs = specFileTabs(); for (const f of fileTabs) tabs.push({ id: f.id, label: f.label, count: 0 }); if (isSpecFileView(page.view) && !fileTabs.some((f) => f.id === page.view)) page.view = "questions"; + // Right after Dashboard: the project's AGENTS.md, present while the file is. + // Like a spec file tab, it sends the person home if the file goes away. + if (agentsTabShown()) tabs.splice(1, 0, { id: AGENTS_VIEW, label: "AGENTS.md", count: 0 }); + else if (page.view === AGENTS_VIEW) page.view = "questions"; for (const d of docs()) tabs.push({ id: "doc:" + d.id, label: d.title || "Document", count: 0 }); // The helpers the agent reported, from the first one on; cleared by a // dashboard hop, which sends the person home like the Overview tab does. @@ -1482,6 +1488,10 @@ function renderViews() { // changed on disk since. render(); if (isSpecFileView(t.id)) loadOverview(); + if (t.id === AGENTS_VIEW) { + page.agentsDoc.open = "AGENTS.md"; + loadAgentsDoc(); + } }); nav.appendChild(b); } @@ -1616,7 +1626,7 @@ function renderMain() { } function paintMain(main) { - main.classList.toggle("is-doc", page.view.startsWith("doc:") || isSpecFileView(page.view)); + main.classList.toggle("is-doc", page.view.startsWith("doc:") || isSpecFileView(page.view) || page.view === AGENTS_VIEW); main.classList.toggle("is-ask", page.view === "ask"); // An agent-less session has no questions, docs or board to draw: its whole @@ -1625,6 +1635,7 @@ function paintMain(main) { if (page.view.startsWith("doc:")) return renderDoc(main, page.view.slice(4)); if (isSpecFileView(page.view)) return renderOverview(main, page.view); + if (page.view === AGENTS_VIEW) return renderAgentsDoc(main); if (page.view === "ask") return renderAsk(main); if (page.view === "subagents") return renderSubagents(main); diff --git a/src/web-console/public/screens/docs.js b/src/web-console/public/screens/docs.js index 7e29f3e..1167970 100644 --- a/src/web-console/public/screens/docs.js +++ b/src/web-console/public/screens/docs.js @@ -1,6 +1,6 @@ // Plan2Code Web Console - documents: tabs, blocks, print and download, and the brief button; defines only. -import { docs, agentWorking, workingMs, patience, WORKING_GRACE_MS, finish, SPEC_FILES } from "../selectors.js"; +import { docs, agentWorking, workingMs, patience, WORKING_GRACE_MS, finish, SPEC_FILES, loadAgentsDoc } from "../selectors.js"; import { el, md } from "../render.js"; import { downloadDocHtml, docSavedNote, downloadDoc, blockBody } from "../doc-files.js"; import { hooks, page, redraw } from "../state.js"; @@ -239,6 +239,64 @@ export function renderOverview(main, kind = "overview") { main.appendChild(box); } +// The files the AGENTS.md tab may show: the same two shapes the server serves. +const AGENTS_FILE = /^(?:AGENTS\.md|\.agents-docs\/[A-Za-z0-9._-]+\.md)$/; + +// A link in an agent-guide file, resolved against the file it sits in: the +// guide's own name when it points at another agent-guide file, else null (an +// outside link keeps the usual rules). +export function agentsLinkTarget(from, href) { + if (!href || /^[a-z][a-z0-9+.-]*:/i.test(href) || href.startsWith("#") || href.startsWith("/")) return null; + try { + const u = new URL(href, "http://guide.invalid/" + from); + const rel = decodeURIComponent(u.pathname.slice(1)); + return AGENTS_FILE.test(rel) ? rel : null; + } catch { + return null; + } +} + +// The Dashboard's AGENTS.md tab: the project's agent guide, read-only, straight +// from disk. A link to another guide file (.agents-docs/...) opens in place, +// with a way back to AGENTS.md. +export function renderAgentsDoc(main) { + const { open, texts } = page.agentsDoc; + const head = el("div", "doc-head"); + head.appendChild(el("h2", null, open === "AGENTS.md" ? "AGENTS.md" : open)); + const tools = el("div", "doc-tools"); + if (open !== "AGENTS.md") { + const guide = el("button", "btn small", "Back to AGENTS.md"); + guide.type = "button"; + guide.addEventListener("click", () => { + page.agentsDoc.open = "AGENTS.md"; + redraw(); + main.scrollTop = 0; + }); + tools.appendChild(guide); + } + tools.appendChild(backButton()); + tools.appendChild(printButton()); + head.appendChild(tools); + main.appendChild(head); + main.appendChild(el("p", "help", open + " · read-only, straight from disk")); + const box = el("div", "block settled"); + box.appendChild( + md(texts[open] || "", "md", { + link: (href) => { + const rel = agentsLinkTarget(open, href); + if (!rel) return null; + return () => { + page.agentsDoc.open = rel; + redraw(); + main.scrollTop = 0; + loadAgentsDoc(); + }; + }, + }) + ); + main.appendChild(box); +} + // The brief dialog's buttons, wired once at start-up. export function wireDocs() { $("btn-brief").addEventListener("click", openBrief); diff --git a/src/web-console/public/selectors.js b/src/web-console/public/selectors.js index bc3d03e..273d17e 100644 --- a/src/web-console/public/selectors.js +++ b/src/web-console/public/selectors.js @@ -333,5 +333,46 @@ export async function loadOverview() { if (changed) redraw(); } +// The Dashboard's AGENTS.md tab: its view id, and whether it is on now (the +// dashboard, with an AGENTS.md the last read found). +export const AGENTS_VIEW = "agents-md"; +export const agentsTabShown = () => isDashboard() && typeof page.agentsDoc.texts["AGENTS.md"] === "string"; + +// Read one agent-guide file fresh from disk (`rel` as the server names it) and +// keep its text; null when it is not there. Off the dashboard nothing is read. +async function fetchAgentsDoc(rel) { + try { + const res = await fetch("/agents-doc?file=" + encodeURIComponent(rel), { cache: "no-store" }); + return res.status === 200 ? await res.text() : null; + } catch { + return null; + } +} + +// Fresh from disk every time, like the spec file tabs: AGENTS.md changes under +// init-update, and the tab is only worth having if it shows what is there now. +// Reads AGENTS.md (does the tab exist?) and, when a linked file is open, that +// file too. Repaints only when a tab would appear or vanish or a text changed. +export async function loadAgentsDoc() { + if (!isDashboard()) { + if (Object.keys(page.agentsDoc.texts).length) page.agentsDoc = { open: "AGENTS.md", texts: {} }; + return; + } + const open = page.agentsDoc.open; + const rels = open === "AGENTS.md" ? ["AGENTS.md"] : ["AGENTS.md", open]; + const found = await Promise.all(rels.map(fetchAgentsDoc)); + // The person moved on (Back to AGENTS.md) while this was in flight. + if (!isDashboard() || page.agentsDoc.open !== open) return; + const texts = {}; + rels.forEach((rel, i) => { + if (typeof found[i] === "string") texts[rel] = found[i]; + }); + // A linked file that went missing: back to AGENTS.md itself. + const next = { open: texts[open] === undefined ? "AGENTS.md" : open, texts }; + const changed = JSON.stringify(next) !== JSON.stringify(page.agentsDoc); + page.agentsDoc = next; + if (changed) redraw(); +} + // The workspace's folders, original first, or none before a frame has them. export const workspaceFolders = () => (page.wsFrame && Array.isArray(page.wsFrame.folders) ? page.wsFrame.folders : []); diff --git a/src/web-console/public/state.js b/src/web-console/public/state.js index 3170bba..eae47ac 100644 --- a/src/web-console/public/state.js +++ b/src/web-console/public/state.js @@ -136,6 +136,10 @@ export const page = { // for, `files` maps each SPEC_FILES kind (overview, map, draft) that exists // to `{ file, text }`. See loadOverview(). overview: { key: null, files: {} }, + // The Dashboard's AGENTS.md tab: `texts` maps each agent-guide file read so + // far (AGENTS.md, .agents-docs/.md) to its text, `open` is the one in + // view. The tab exists while texts["AGENTS.md"] does. See loadAgentsDoc(). + agentsDoc: { open: "AGENTS.md", texts: {} }, // The dashboard's first-open wake-up (boot.js), while it runs. `cards` turns // true at the glide, which lets the menu in; `entered` once its entrance has // played; `typed` is how many characters of the note show, or null once all diff --git a/src/web-console/routes.mjs b/src/web-console/routes.mjs index b03d475..61d249a 100644 --- a/src/web-console/routes.mjs +++ b/src/web-console/routes.mjs @@ -30,7 +30,7 @@ import { } from "./files.mjs"; import { AGENTS_SCHEMA, makeId, normalizeAgents, resolveCommand, validateForSave } from "./agents.mjs"; import { findAgent, loadAgentList } from "./agent-lookup.mjs"; -import { checkDocument, cleanupFindings, readSpecFile, removeCleanup } from "./sessions.mjs"; +import { checkDocument, cleanupFindings, readAgentsDoc, readSpecFile, removeCleanup } from "./sessions.mjs"; import { SHOTS_DIR_NAME, SHOT_NAME, shotType } from "./patches.mjs"; import { appendChat, currentConversation, pendingChatCount, typedCount } from "./inbox.mjs"; import { specKey } from "./workspace.mjs"; @@ -85,6 +85,7 @@ const ROUTES = [ { path: "/", method: "GET", run: page }, { match: (p, req) => req.method === "GET" && SERVABLE.has(p.slice(1)), run: publicFile }, { path: "/overview", method: "GET", run: overview }, + { path: "/agents-doc", method: "GET", run: agentsDoc }, { path: "/handoff", method: "GET", run: handoffDoc }, { path: "/version", method: "GET", run: version }, { path: "/state", method: "GET", run: stateGet }, @@ -419,6 +420,29 @@ function overview(req, res, ctx, url) { .catch(noOverview); } +// The project's AGENTS.md (or one file under .agents-docs/), read-only, for the +// dashboard's AGENTS.md tab. Only a dashboard serves it, and only the two +// shapes readAgentsDoc() allows; anything else, or a missing file, is a 204 +// (no tab) so the browser console stays free of a failed request. +function agentsDoc(req, res, ctx, url) { + const state = ctx.readState() || {}; + const none = () => { + res.writeHead(204, baseHeaders({ "cache-control": "no-store" })); + res.end(); + }; + if (state.workflow !== "dashboard") return none(); + readAgentsDoc(state.worktree || state.project, url.searchParams.get("file") || "AGENTS.md") + .then((found) => + found + ? send(res, 200, found.text, "text/markdown; charset=utf-8", { + "cache-control": "no-store", + "x-spec-file": encodeURIComponent(found.file), + }) + : none() + ) + .catch(none); +} + // A handoff's document, read-only, for the dashboard's "Read it all". Only a // dashboard serves it, and only an id its own scan listed: a used or unknown // id, or anything that is not a bare handoff id, is a 404. diff --git a/src/web-console/sessions.mjs b/src/web-console/sessions.mjs index 1c064e3..ffeb1ae 100644 --- a/src/web-console/sessions.mjs +++ b/src/web-console/sessions.mjs @@ -540,6 +540,28 @@ export async function readSpecFile(root, specDir, kind) { } } +// The project's agent guide as the Dashboard's AGENTS.md tab shows it: only +// AGENTS.md itself or one markdown file directly under .agents-docs/, never any +// other path. Kept inside the root by realpath, like readSpecFile(). +const AGENTS_DOC_RE = /^(?:AGENTS\.md|\.agents-docs\/[A-Za-z0-9._-]+\.md)$/; + +/** + * `{ file, text }` for an allowed agent-guide file (`rel` as written, with `/` + * separators), or null when it is not allowed, missing or outside the root. + */ +export async function readAgentsDoc(root, rel) { + if (!root || typeof rel !== "string" || !AGENTS_DOC_RE.test(rel)) return null; + try { + const file = path.resolve(root, ...rel.split("/")); + const [realFile, realRoot] = await Promise.all([fs.promises.realpath(file), fs.promises.realpath(root)]); + const inside = path.relative(realRoot, realFile); + if (!inside || inside === ".." || inside.startsWith(".." + path.sep) || path.isAbsolute(inside)) return null; + return { file: rel, text: await fs.promises.readFile(realFile, "utf8") }; + } catch { + return null; + } +} + // The line every CLI command hands the agent to end its terminal messages with. // Under the desktop app the page is already in the window beside the terminal, // so the address would only be noise there: the line points at the window.