tasks: the Tasks app, as the template has it
Misha Kaletsky, 2026-11-24 18:16 UTC · 5317767e82196635244ca06b97b63451ce42b8c7 · the first commit
7 files changed
- A app.ts
- A index.html
- A public/app.css
- A public/app.js
- A public/manifest.webmanifest
- A public/tasks-model.js
- A tasks-model.test.mjs
A app.ts
@@ -0,0 +1,54 @@ +// app.ts — THE TASKS APP, as worker.ts mounts it on tasks.<domain>: a board over the markdown +// files under tasks/ in the repo that worker.ts points it at (`tasksApp({ repo })`; /repos/config +// while the mind has no such repo), or in the repo of the mind that `?repo=` names. public/app.js says what the page does, and +// public/tasks-model.js how a file is read as a card. This file only serves the page: the board +// reads and commits through the member's own itx, so there is no backend class and no state here. +// The task sheet edits a file as the Docs app does, through the Docs app's processors +// (../docs/processors/): /processors.json says where they are, in the Docs app's own words. +import { type AppDescription, serveFiles, type IterateConfigEntrypoint } from "iterate/sdk"; +import theme from "../theme.css"; +// oxlint-disable-next-line import/extensions -- a folder: the loader hands over every file under it, by path +import liveReload from "../live-reload/"; +import { processorsAnswer } from "../docs/app.ts"; +import { openFile } from "../open-files.ts"; +import index from "./index.html"; +// oxlint-disable-next-line import/extensions -- a folder: the loader hands over every file under it, by path +import files from "./public/"; + +/** What Tasks says of itself to anyone: the mind's sign-in pages show its name and icon. */ +const TASKS: AppDescription = { name: "Tasks", icon: "/icon.svg", for: "members" }; + +/** The repo the board points at when worker.ts names none. A commit to a repo other than + * `/repos/config` publishes nothing, so a card that moves does not load the mind's code again. */ +const TASKS_REPO = "/repos/tasks"; + +/** `repo`: THE REPO THE BOARD POINTS AT, a path of this mind (`/repos/<name>`). The page shows + * the markdown files under `tasks/` of it. While the mind has no such repo, the page shows the + * config repo's `tasks/`; `?repo=<name>` shows any other repo for one visit. */ +export function tasksApp({ repo = TASKS_REPO }: { repo?: string } = {}) { + return { + /** The app's description and icon, for anyone: worker.ts asks this before its guard + * (../open-files.ts). */ + open: (request: Request) => openFile(request, TASKS), + /** Every request on the app's host. worker.ts guards it, so a member alone gets here. */ + async fetch(request: Request, host: Pick<IterateConfigEntrypoint, "auth">) { + const url = new URL(request.url); + // Where the Docs processors' classes are and which version of them this commit holds: the + // answer apps/docs/app.ts gives, so the task sheet and Docs start one doc's processors + // under one name and never as two copies. + if (url.pathname === "/processors.json") return Response.json(await processorsAnswer()); + // the repo worker.ts points the board at: the page asks once, when it loads + if (url.pathname === "/board.json") + return Response.json({ repo }, { headers: { "cache-control": "no-store" } }); + // The page's own socket (/itx) and what @iterate-com/ui's shell asks of its host + // (/.auth/session.json, /.auth/minds.json, /.auth/logout). + const page = host.auth.memberPage(request); + if (page) return page; + // the app's own files, and the one theme file that every app of this mind shares + return serveFiles(request, { + index, + files: { ...files, ...liveReload, "theme.css": theme }, + }); + }, + }; +}
A index.html
@@ -0,0 +1,63 @@ +<!doctype html> +<html lang="en"> + <head> + <meta charset="utf-8" /> + <meta name="viewport" content="width=device-width, initial-scale=1" /> + <title>Tasks</title> + <!-- The components' modules and stylesheet come from one other host: the connection to it + starts now, while the rest of this head is read. --> + <link rel="preconnect" href="https://esm.iterate.com" crossorigin /> + <!-- What the app is called and its icon: the mind's sign-in pages show both. --> + <link rel="manifest" href="/manifest.webmanifest" /> + <link rel="icon" href="/icon.svg" type="image/svg+xml" /> + <!-- iterate's components, pinned to one build: the one the Dash and Docs pin. To upgrade, + change the version here. --> + <script type="importmap"> + { + "imports": { + "@iterate-com/ui/": "https://esm.iterate.com/@iterate-com/ui@0.1.0-main.20261124T154040Z-83b4390/", + "react": "https://esm.iterate.com/@iterate-com/ui@0.1.0-main.20261124T154040Z-83b4390/react", + "react/": "https://esm.iterate.com/@iterate-com/ui@0.1.0-main.20261124T154040Z-83b4390/react/", + "react-dom": "https://esm.iterate.com/@iterate-com/ui@0.1.0-main.20261124T154040Z-83b4390/react-dom", + "react-dom/": "https://esm.iterate.com/@iterate-com/ui@0.1.0-main.20261124T154040Z-83b4390/react-dom/", + "lucide-react": "https://esm.iterate.com/lucide-react@1.48.0?external=react,react-dom" + } + } + </script> + <!-- The page's socket, asked for here and not when the app's modules have loaded: `memberItx` + (@iterate-com/ui/live, in app.js) takes it for its first session. It stands before the + stylesheets, because a script after a stylesheet waits for it. --> + <script> + try { + window.__itxSocket = new WebSocket(new URL("/itx", location.href.replace(/^http/, "ws"))); + // time to itx: when the socket opens (page-events.md, "Speed") + window.__itxSocket.addEventListener("open", () => performance.mark("iterate:itx-open"), { + once: true, + }); + } catch {} + </script> + <!-- The kit's stylesheet for a page with the docs editor (the task sheet has one): everything + styles.css holds, and the editor's own classes and its live preview's look. It takes the + place of styles.css: a page links one of the two, never both. --> + <link + rel="stylesheet" + href="https://esm.iterate.com/@iterate-com/ui@0.1.0-main.20261124T154040Z-83b4390/docs-editor.css" + /> + <!-- The look of this mind's apps: apps/theme.css, one file for every app. One line there + makes them all dark. shadcn's components also ask for the class `dark`, so the script + puts it on <html> when the file says dark. --> + <link rel="stylesheet" href="/theme.css" /> + <script> + if (getComputedStyle(document.documentElement).colorScheme === "dark") + document.documentElement.classList.add("dark"); + </script> + <link rel="stylesheet" href="/app.css" /> + <!-- The page takes a new commit by itself: apps/live-reload/live-reload.js says how. A commit + that changes a task changes no file of this page, so it reloads nothing. --> + <script type="module" src="/live-reload.js" blocking="render"></script> + </head> + <body> + <div id="root"><p class="tasks-note">Connecting…</p></div> + <script type="module" src="/app.js"></script> + </body> +</html>
A public/app.css
@@ -0,0 +1,939 @@ +/* app.css — the board's own layout. @iterate-com/ui's stylesheet holds the classes its own + components use and no others, so what this page adds is written here as plain CSS, on the + theme's variables (apps/theme.css): a change of theme changes the board with every other app. */ +html, +body, +#root { + height: 100%; +} + +/* a line in place of the board: it is being read, it could not be read, nothing matches */ +.tasks-note { + padding: 1rem; + color: var(--muted-foreground); + font-size: 0.875rem; +} + +.tasks-link { + border: 0; + padding: 0; + background: none; + color: var(--foreground); + font: inherit; + text-decoration: underline; + text-underline-offset: 3px; + cursor: pointer; +} + +.tasks-empty { + height: 100%; +} + +/* ── the bar in the shell's header: the filter, the rows, what is saved, "New task" ── */ +.tasks-bar { + display: flex; + flex: 1; + min-width: 0; + align-items: center; + gap: 0.5rem; +} + +.tasks-search { + position: relative; + display: flex; + flex: 0 1 18rem; + min-width: 7rem; + align-items: center; +} + +.tasks-search > svg { + position: absolute; + left: 0.6rem; + width: 0.9rem; + height: 0.9rem; + color: var(--muted-foreground); + pointer-events: none; +} + +.tasks-search > input { + height: 1.875rem; + padding-left: 1.9rem; +} + +/* what filters the board now, in a line above the board: one chip for each, and a press lets go + of it. The line scrolls sideways when it is longer than the page. */ +.tasks-picked { + display: flex; + flex: none; + align-items: center; + gap: 0.375rem; + overflow-x: auto; + padding: 0.625rem 1rem 0; + scrollbar-width: none; +} + +.tasks-picked > .tasks-link { + flex: none; + margin-left: 0.25rem; + font-size: 0.75rem; +} + +/* the board fills what the line of chips leaves */ +.tasks-picked + .board { + height: calc(100% - 2.125rem); +} + +.tasks-chip { + display: inline-flex; + flex: none; + align-items: center; + gap: 0.3rem; + height: 1.5rem; + border: 1px solid var(--border); + border-radius: 999px; + padding: 0 0.4rem 0 0.6rem; + background: var(--background); + color: var(--foreground); + font-size: 0.75rem; + white-space: nowrap; + cursor: pointer; +} + +.tasks-chip:hover { + background: var(--accent); +} + +.tasks-chip-of { + color: var(--muted-foreground); +} + +.tasks-chip > svg { + width: 0.75rem; + height: 0.75rem; + color: var(--muted-foreground); +} + +.tasks-bar-end { + display: flex; + align-items: center; + gap: 0.75rem; + margin-left: auto; +} + +.tasks-save { + display: inline-flex; + align-items: center; + gap: 0.35rem; + color: var(--muted-foreground); + font-size: 0.75rem; + white-space: nowrap; +} + +.tasks-save > svg { + width: 0.8rem; + height: 0.8rem; +} + +.tasks-save[data-failed] { + color: var(--destructive); +} + +/* a long value (an agent's name) is cut before the row's count, which stands over the button's end */ +.tasks-nav-label { + min-width: 0; + max-width: calc(100% - 1.5rem); + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +/* ── the board: one grid of columns, scrolled both ways, with the columns' names kept on top ── */ +.board { + --column: minmax(13.5rem, 1fr); + height: 100%; + overflow: auto; + padding: 0 1rem 2rem; + overscroll-behavior-x: contain; +} + +.board-head, +.board-cells { + display: grid; + grid-template-columns: repeat(var(--columns), var(--column)); + gap: 0.75rem; + min-width: min-content; +} + +.board-head { + position: sticky; + top: 0; + z-index: 2; + padding: 0.75rem 0 0.5rem; + background: var(--background); +} + +.board-column-head { + display: flex; + align-items: center; + gap: 0.5rem; + min-width: 0; + padding: 0 0.25rem 0 0.5rem; + font-size: 0.8125rem; + font-weight: 500; +} + +.board-column-name { + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.board-column-count { + color: var(--muted-foreground); + font-weight: 400; + font-variant-numeric: tabular-nums; +} + +.board-column-add { + margin-left: auto; + color: var(--muted-foreground); +} + +.board-row + .board-row { + margin-top: 1.25rem; +} + +/* a row's name, when the board is in rows by a dimension: it stays at the left while the row + scrolls sideways */ +.board-row-name { + position: sticky; + left: 0; + display: inline-flex; + align-items: baseline; + gap: 0.4rem; + margin: 0 0 0.5rem; + padding: 0 0.5rem; + font-size: 0.8125rem; + font-weight: 600; +} + +.board-row-of { + color: var(--muted-foreground); + font-weight: 400; +} + +.board-cell { + display: flex; + flex-direction: column; + gap: 0.5rem; + min-height: 5rem; + padding: 0.5rem; + border-radius: calc(var(--radius) + 2px); + background: color-mix(in oklab, var(--muted) 60%, transparent); + transition: + background-color 120ms, + box-shadow 120ms; +} + +.board-cell[data-over] { + background: color-mix(in oklab, var(--primary) 9%, var(--muted)); + box-shadow: inset 0 0 0 1.5px color-mix(in oklab, var(--primary) 45%, transparent); +} + +/* the faint plus under a cell's cards: there when the pointer is in the cell, or it has focus */ +.board-cell-add { + display: flex; + align-items: center; + justify-content: center; + height: 1.75rem; + border: 0; + border-radius: calc(var(--radius) - 2px); + background: none; + color: var(--muted-foreground); + opacity: 0; + cursor: pointer; + transition: + opacity 120ms, + background-color 120ms; +} + +.board-cell-add > svg { + width: 0.9rem; + height: 0.9rem; +} + +.board-cell:hover > .board-cell-add, +.board-cell-add:focus-visible { + opacity: 1; +} + +.board-cell-add:hover { + background: color-mix(in oklab, var(--foreground) 6%, transparent); + color: var(--foreground); +} + +.board-more { + align-self: flex-start; + padding: 0.25rem 0.5rem; + color: var(--muted-foreground); + font-size: 0.75rem; +} + +/* ── a card ── */ +.task { + display: flex; + flex-direction: column; + gap: 0.5rem; + padding: 0.625rem 0.75rem; + border: 1px solid var(--border); + border-radius: var(--radius); + background: var(--card); + color: var(--card-foreground); + box-shadow: 0 1px 2px rgb(0 0 0 / 4%); + cursor: grab; + transition: + border-color 120ms, + box-shadow 120ms, + opacity 120ms; + position: relative; +} + +.task:hover { + border-color: color-mix(in oklab, var(--foreground) 22%, var(--border)); + box-shadow: 0 2px 6px rgb(0 0 0 / 7%); +} + +.task[data-dragging] { + opacity: 0.4; +} + +.task-top { + display: flex; + align-items: flex-start; + gap: 0.25rem; +} + +.task-title { + flex: 1; + min-width: 0; + color: inherit; + font-size: 0.8125rem; + font-weight: 500; + line-height: 1.35; + text-decoration: none; + overflow-wrap: anywhere; + display: -webkit-box; + -webkit-box-orient: vertical; + -webkit-line-clamp: 3; + overflow: hidden; +} + +.task-title:hover { + text-decoration: underline; + text-underline-offset: 3px; +} + +/* the card's menu: over the card's corner when the pointer is on the card or the menu is open, so + the title has the card's whole width. On a screen that is touched nothing hovers: there it is + always shown, and the title leaves it room. */ +.task-menu { + position: absolute; + top: 0.35rem; + right: 0.35rem; + background: var(--card); + color: var(--muted-foreground); + opacity: 0; +} + +.task:hover .task-menu, +.task-menu:focus-visible, +.task-menu[aria-expanded="true"], +.task-menu[data-popup-open] { + opacity: 1; +} + +/* wide enough for "In progress" on one line */ +.task-menu-popup { + min-width: 11rem; +} + +@media (hover: none) { + .task-menu, + .board-cell-add { + opacity: 1; + } + + .task-title { + padding-right: 1.75rem; + } +} + +.task-meta { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 0.3rem; + min-height: 1.25rem; + color: var(--muted-foreground); + font-size: 0.6875rem; +} + +.task-meta:empty { + display: none; +} + +.task-folder { + overflow: hidden; + max-width: 100%; + text-overflow: ellipsis; + white-space: nowrap; +} + +.task-tag { + height: 1.125rem; + padding: 0 0.4rem; + font-size: 0.6875rem; + font-weight: 400; +} + +/* a value of a dimension on a card is a button: a press filters the board by it */ +.task-value { + display: inline-flex; + align-items: center; + border: 0; + border-radius: 999px; + padding: 0; + background: none; + color: inherit; + font: inherit; + cursor: pointer; +} + +.task-value:hover > [data-slot="badge"], +.task-value.task-owner:hover, +.task-value.task-agent:hover { + box-shadow: 0 0 0 1px var(--ring); +} + +.task-value[aria-pressed="true"] > [data-slot="badge"], +.task-value.task-owner[aria-pressed="true"], +.task-value.task-agent[aria-pressed="true"] { + box-shadow: 0 0 0 1.5px var(--primary); +} + +.task-value:focus-visible { + outline: 2px solid var(--ring); + outline-offset: 1px; +} + +/* a priority's dot: red for the top ones, amber for high, grey for the rest */ +.task-priority > i { + width: 0.4rem; + height: 0.4rem; + margin-right: 0.3rem; + border-radius: 999px; + background: var(--muted-foreground); +} + +.task-value:is( + [data-value="urgent"], + [data-value="critical"], + [data-value="p0"], + [data-value="highest"] + ) + > .task-priority + > i { + background: oklch(0.63 0.21 25); +} + +.task-value:is([data-value="high"], [data-value="p1"]) > .task-priority > i { + background: oklch(0.75 0.15 75); +} + +/* who has the task: its agent and its owner, at the card's right edge */ +.task-people { + display: inline-flex; + align-items: center; + gap: 0.25rem; + margin-left: auto; +} + +.task-agent { + justify-content: center; + width: 1.25rem; + height: 1.25rem; + background: var(--secondary); + color: var(--secondary-foreground); +} + +.task-agent > svg { + width: 0.75rem; + height: 0.75rem; +} + +.task-owner { + display: inline-flex; + align-items: center; + justify-content: center; + width: 1.25rem; + height: 1.25rem; + border-radius: 999px; + background: var(--secondary); + color: var(--secondary-foreground); + font-size: 0.5625rem; + font-weight: 600; +} + +/* a change that is not in the repo yet */ +.task-unsaved { + width: 0.4rem; + height: 0.4rem; + margin-left: auto; + border-radius: 999px; + background: oklch(0.75 0.15 75); +} + +.task-people + .task-unsaved { + margin-left: 0; +} + +/* ── the box for a new task ── */ +.task-composer { + cursor: auto; + border-color: var(--ring); + box-shadow: 0 0 0 3px color-mix(in oklab, var(--ring) 30%, transparent); +} + +.task-composer > textarea { + width: 100%; + border: 0; + padding: 0; + outline: none; + resize: none; + background: none; + color: inherit; + font: inherit; + font-size: 0.8125rem; + font-weight: 500; + line-height: 1.35; +} + +.task-composer-foot { + display: flex; + align-items: center; + justify-content: space-between; + gap: 0.5rem; + color: var(--muted-foreground); + font-size: 0.6875rem; +} + +/* ── a status's mark: one colour a status, the same in a column's head and in a card's menu ── */ +.status-mark { + flex: none; + width: 0.9rem; + height: 0.9rem; +} + +.status-mark[data-status="backlog"] { + color: var(--muted-foreground); +} + +.status-mark[data-status="todo"] { + color: light-dark(oklch(0.55 0 0), oklch(0.75 0 0)); +} + +.status-mark[data-status="in-progress"] { + color: light-dark(oklch(0.72 0.16 80), oklch(0.82 0.15 85)); +} + +.status-mark[data-status="in-review"] { + color: light-dark(oklch(0.62 0.15 150), oklch(0.75 0.16 150)); +} + +.status-mark[data-status="done"] { + color: light-dark(oklch(0.55 0.2 275), oklch(0.7 0.16 275)); +} + +.status-mark[data-status="own"] { + color: light-dark(oklch(0.6 0.19 25), oklch(0.72 0.17 25)); +} + +/* ── a phone: a column is most of the screen wide, and the board snaps to one ── */ +@media (max-width: 640px) { + .board { + --column: 82vw; + padding: 0 0.75rem 2rem; + scroll-snap-type: x proximity; + } + + .board-column-head, + .board-cell { + scroll-snap-align: center; + } + + .tasks-search { + flex: 1 1 auto; + } + + /* the bar has room for the buttons, not for their words: "Group" without its value, and "New + task" as its plus alone */ + .tasks-wide { + display: none; + } + + .tasks-picked { + padding-inline: 0.75rem; + } +} + +/* ── the task sheet: a task open at the right of the board ── */ +/* The kit's sheet is a narrow panel; a task wants room for its text and the comments beside it. + These rules are not in a layer, so they stand over the kit's utilities, which are. */ +.task-sheet { + gap: 0; + width: min(100vw, 60rem); + max-width: none; + background: var(--background); + color: var(--foreground); +} + +.task-sheet-top { + display: flex; + flex: none; + align-items: baseline; + gap: 0.5rem; + min-height: 2.75rem; + padding: 0.75rem 3.25rem 0.5rem 1.5rem; + outline: none; +} + +.task-sheet-kind { + font-size: 0.75rem; + font-weight: 500; +} + +.task-sheet-path { + overflow: hidden; + color: var(--muted-foreground); + font-family: var(--font-mono, ui-monospace, monospace); + font-size: 0.75rem; + text-overflow: ellipsis; + white-space: nowrap; +} + +/* the head, the saving line and the text scroll as one page under the sheet's top */ +.task-sheet-body { + display: flex; + flex: 1; + flex-direction: column; + min-height: 0; + overflow-y: auto; + overscroll-behavior: contain; +} + +.task-head { + display: flex; + flex: none; + flex-direction: column; + align-items: flex-start; + gap: 0.75rem; + padding: 0.25rem 1.5rem 0.75rem; +} + +/* a text edited in place: it looks like text until it is pointed at or typed in */ +.task-box { + min-width: 0; + border: 1px solid transparent; + border-radius: calc(var(--radius) - 2px); + padding: 0.2rem 0.4rem; + background: none; + color: inherit; + font: inherit; + outline: none; +} + +.task-box:hover { + border-color: var(--border); +} + +.task-box:focus-visible { + border-color: var(--ring); + box-shadow: 0 0 0 3px color-mix(in oklab, var(--ring) 30%, transparent); +} + +.task-box::placeholder { + color: var(--muted-foreground); +} + +.task-title-box { + width: calc(100% + 0.8rem); + margin: 0 -0.4rem; + resize: none; + font-size: 1.375rem; + font-weight: 600; + line-height: 1.25; + /* as tall as its text: a long title is two lines, not a scrolling box */ + field-sizing: content; +} + +.task-properties { + display: grid; + grid-template-columns: max-content minmax(0, 1fr); + gap: 0.375rem 1rem; + width: 100%; + margin: 0; + font-size: 0.8125rem; +} + +.task-property { + display: grid; + grid-column: 1 / -1; + grid-template-columns: subgrid; + align-items: center; + min-height: 1.75rem; +} + +.task-property > dt { + color: var(--muted-foreground); +} + +.task-property > dd { + display: flex; + min-width: 0; + align-items: center; + margin: 0; +} + +.task-property > dd > [data-slot="native-select-wrapper"] { + width: auto; + min-width: 9rem; +} + +.task-property .task-box { + width: min(100%, 16rem); +} + +.task-property-text { + padding-left: 0.4rem; + color: var(--muted-foreground); + font-family: var(--font-mono, ui-monospace, monospace); + font-size: 0.75rem; +} + +/* the task's agent in the sheet: a link to its chat in the Dash */ +.task-agent-link { + color: inherit; + text-decoration: underline; + text-decoration-color: var(--border); + text-underline-offset: 2px; + overflow-wrap: anywhere; +} + +.task-agent-link:hover { + color: var(--foreground); + text-decoration-color: currentColor; +} + +.task-add-property { + margin-left: -0.4rem; + color: var(--muted-foreground); +} + +/* tags: a chip for each, and a box that adds one */ +.task-chips { + display: flex; + flex-wrap: wrap; + min-width: 0; + align-items: center; + gap: 0.3rem; +} + +.task-chip { + display: inline-flex; + align-items: center; + gap: 0.2rem; + height: 1.375rem; + border-radius: 999px; + padding: 0 0.25rem 0 0.55rem; + background: var(--secondary); + color: var(--secondary-foreground); + font-size: 0.75rem; +} + +.task-chip > button { + display: inline-flex; + align-items: center; + justify-content: center; + width: 1rem; + height: 1rem; + border: 0; + border-radius: 999px; + padding: 0; + background: none; + color: var(--muted-foreground); + cursor: pointer; +} + +.task-chip > button:hover, +.task-chip > button:focus-visible { + background: color-mix(in oklab, var(--foreground) 12%, transparent); + color: var(--foreground); + outline: none; +} + +.task-chip > button > svg { + width: 0.7rem; + height: 0.7rem; +} + +.task-property .task-chips-box { + width: 7rem; +} + +/* where the two kinds of change stand: the title and properties, and the text */ +.task-saving { + display: flex; + flex: none; + flex-wrap: wrap; + gap: 0.25rem 1.25rem; + margin: 0; + border-top: 1px solid var(--border); + padding: 0.5rem 1.5rem; + color: var(--muted-foreground); + font-size: 0.75rem; +} + +.task-saving-part { + display: inline-flex; + align-items: center; + gap: 0.35rem; +} + +.task-saving-part > svg { + flex: none; + width: 0.8rem; + height: 0.8rem; +} + +.task-saving-part[data-pending] { + color: var(--foreground); +} + +.task-saving-part[data-failed] { + color: var(--destructive); +} + +/* the Docs editor fills the rest; its own bar stays at the top of the sheet's page as it scrolls */ +.task-text { + display: flex; + flex: 1 0 auto; + flex-direction: column; + min-width: 0; + border-top: 1px solid var(--border); +} + +/* In its Rich view the editor draws the frontmatter as a list of properties. The sheet's head is + that list here, with controls, so the editor's is not drawn twice. Its Markdown view still shows + the frontmatter as it is written, and there it can be typed in. */ +.task-text .docs-properties { + display: none; +} + +@media (max-width: 640px) { + .task-sheet { + width: 100vw; + border-left: 0; + } + + .task-sheet-top, + .task-head, + .task-saving { + padding-inline: 1rem; + } + + .task-sheet-top { + padding-right: 3.25rem; + } + + .task-title-box { + font-size: 1.1875rem; + } +} + +/* ── "Needs a person": a list in place of the board (app.js `NeedsPage`) ── */ +.needs { + display: flex; + flex-direction: column; + gap: 0.5rem; + max-width: 48rem; + margin: 0; + padding: 1rem; + list-style: none; +} + +.needs-row { + display: flex; + flex-direction: column; + gap: 0.375rem; + padding: 0.75rem; + border: 1px solid var(--border); + border-radius: var(--radius); + background: var(--card); +} + +.needs-top { + display: flex; + align-items: center; + gap: 0.5rem; +} + +.needs-asks { + display: flex; + flex-direction: column; + gap: 0.5rem; + margin: 0; + padding-inline-start: 1.5rem; + font-size: 0.8125rem; +} + +/* an ask's answer box (app.js `Ask`): the field takes the row, the button keeps its own width */ +/* under an ask: who asked it, a link to that agent's chat in the Dash */ +.needs-asker { + display: flex; + align-items: center; + gap: 0.25rem; + width: fit-content; + margin-top: 0.125rem; + color: var(--muted-foreground); + font-size: 0.75rem; + text-decoration: none; +} + +a.needs-asker:hover { + color: var(--foreground); + text-decoration: underline; + text-underline-offset: 2px; +} + +.needs-asker > svg { + width: 0.75rem; + height: 0.75rem; +} + +.needs-answer { + display: flex; + align-items: center; + gap: 0.5rem; + margin-top: 0.25rem; +} + +.needs-answer > :first-child { + flex: 1; + min-width: 0; +} + +.needs-blocked { + margin: 0; + color: var(--muted-foreground); + font-size: 0.8125rem; +}
A public/app.js
@@ -0,0 +1,2090 @@ +// app.js — THE TASKS APP'S PAGE: the markdown files under tasks/ in one repo of this mind, as a +// board. The repo is the one worker.ts points the app at (app.ts `tasksApp({ repo })`, which +// /board.json answers; the tasks repo, tasks-model.js `TASKS_REPO`, when it names none), or the +// one that `?repo=<name>` names (/repos/<name>): the bar's "Repo" menu lists the mind's repos, +// and the page loads again for the one chosen. +// A column is a status, a card is a file (tasks-model.js says how a file is read). A person +// makes a task, moves a card to another column (by drag, or from the card's menu), and filters the +// board by words, by folder and by each dimension that the files hold (tags, priority, size, owner, +// agent: tasks-model.js `DIMENSIONS`). "Group by" breaks the board into rows by one of them. A +// card's title opens the task in a sheet at the right of the board, where its title, its properties +// and its text are edited and commented on ("the task sheet", below). +// +// EVERY CHANGE IS A COMMIT TO THAT REPO. The board shows a change at once and commits a moment +// later, with whatever else was changed meanwhile: several cards moved in a row are ONE commit +// (`Board`, below). The board reads the repo again at every commit to it, whoever made it, so each +// open board shows what the others did. A commit to a repo of tasks publishes nothing: only +// /repos/config is the mind's code. (`?repo=config` is a board like any other, and there a commit +// does publish the mind.) +// +// Everything it draws is a component of @iterate-com/ui, loaded through the import map in +// index.html. The page's own layout is app.css. +// oxlint-disable unicorn-js/template-indent -- the formatter indents a template that starts in a branch of a ternary or in an argument, and this rule then asks for another indent: its own fix and the formatter never agree on this file +import { + html, + render, + useEffect, + useMemo, + useRef, + useState, + useSyncExternalStore, +} from "@iterate-com/ui/page"; +import { AppShell, AppShellPageHeader } from "@iterate-com/ui/components/app-shell"; +import { ReconnectingMark } from "@iterate-com/ui/components/reconnecting-mark"; +import { Badge } from "@iterate-com/ui/components/ui/badge"; +import { Button } from "@iterate-com/ui/components/ui/button"; +import { + DropdownMenu, + DropdownMenuContent, + DropdownMenuGroup, + DropdownMenuItem, + DropdownMenuLabel, + DropdownMenuRadioGroup, + DropdownMenuRadioItem, + DropdownMenuSeparator, + DropdownMenuTrigger, +} from "@iterate-com/ui/components/ui/dropdown-menu"; +import { + Empty, + EmptyContent, + EmptyDescription, + EmptyHeader, + EmptyTitle, +} from "@iterate-com/ui/components/ui/empty"; +import { Input } from "@iterate-com/ui/components/ui/input"; +import { NativeSelect, NativeSelectOption } from "@iterate-com/ui/components/ui/native-select"; +import { + Sheet, + SheetContent, + SheetDescription, + SheetTitle, +} from "@iterate-com/ui/components/ui/sheet"; +import { + SidebarGroup, + SidebarGroupContent, + SidebarGroupLabel, + SidebarMenu, + SidebarMenuBadge, + SidebarMenuButton, + SidebarMenuItem, +} from "@iterate-com/ui/components/ui/sidebar"; +import { Spinner } from "@iterate-com/ui/components/ui/spinner"; +import { + BotIcon, + CheckIcon, + ChevronDownIcon, + EllipsisIcon, + ExternalLinkIcon, + PlusIcon, + SearchIcon, + TriangleAlertIcon, + XIcon, +} from "@iterate-com/ui/icons"; +import { itxSessionOf, memberItx } from "@iterate-com/ui/live"; +import { + agentChatPath, + applyChange, + columnOf, + columnsOf, + commitOf, + DIMENSIONS, + dimensionsOf, + filterTasks, + messageOf, + needsAPerson, + newTask, + rowsOf, + TASKS_DIR, + TASKS_REPO, + tasksOf, + valuesOf, +} from "./tasks-model.js"; + +// ── the member's itx ── +// @iterate-com/ui's `memberItx`: one WebSocket to this host's /itx, whose root is the mind's itx as +// the member the platform signed in here. A publication cuts the socket for a few seconds; the +// same `itx` then calls through a new session, and the board opens its subscription again +// (`pageSession`'s epoch, in `App`). +const itx = memberItx(); +const pageSession = itxSessionOf(itx); +const [{ principal }, initialRepos, pointed] = await Promise.all([ + itx.whoami(), + itx.repos.list().catch(() => []), + // the repo worker.ts points the board at (app.ts, `tasksApp({ repo })`); an answer that is no + // JSON, or names no repo path, leaves the tasks repo + fetch("/board.json") + .then((answer) => answer.json()) + .catch(() => ({})), +]); +/** The repo the board points at: a path `/repos/<name>` from app.ts, else the tasks repo. */ +const BOARD_REPO = /^\/repos\/[A-Za-z0-9][A-Za-z0-9._-]*$/.test(pointed?.repo) + ? pointed.repo + : TASKS_REPO; +/** Who a commit made here is by: the person's email as both name and address. */ +const author = principal?.email ? { name: principal.email, email: principal.email } : undefined; + +// The mind is its domain, and this host is one label under it. +const domain = location.hostname.split(".").slice(1).join(".") || location.hostname; +/** THE REPO WHOSE TASKS THE BOARD SHOWS, by its name: the one `?repo=` names, else the repo the + * board points at (`BOARD_REPO`) when the mind has it, else `config` (so a new mind's + * onboarding cards under `tasks/` in `/repos/config` appear before the tasks repo is made). + * Read once when the page loads; the bar's "Repo" menu loads the page again for another + * (`showRepo`). */ +const DEFAULT_REPO_NAME = initialRepos.some((repo) => repo.path === BOARD_REPO) + ? BOARD_REPO.split("/").at(-1) + : "config"; +const REPO_NAME = (() => { + const named = new URLSearchParams(location.search).get("repo"); + return named && /^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(named) ? named : DEFAULT_REPO_NAME; +})(); +const REPO = `/repos/${REPO_NAME}`; +/** The repo with this mind's code: the editor's processors and their package pins are there. */ +const CODE_REPO = "/repos/config"; +/** A task's file in the Docs app, where it is written and commented on. */ +const docsHref = (path) => + `https://docs.${domain}/?repo=${encodeURIComponent(REPO_NAME)}&doc=${encodeURIComponent(path)}`; +/** An agent's chat in the Dash (tasks-model.js `agentChatPath`), or null when the card names no + * context path. */ +const agentHref = (agent) => { + const path = agentChatPath(agent); + return path && `https://dash.${domain}${path}`; +}; +/** The board of another repo: the page again, with no filter of this one. */ +const showRepo = (name) => { + if (name === REPO_NAME) return; + location.assign( + name === DEFAULT_REPO_NAME + ? location.pathname + : `${location.pathname}?repo=${encodeURIComponent(name)}`, + ); +}; + +const wordsOf = (error) => (error instanceof Error ? error.message : String(error)); + +// ── the board's store ── + +/** How long the board waits after a change before it commits, and how long at most after the + * first change that is not committed yet: several changes in that time are one commit. */ +const COMMIT_AFTER_MS = 1500; + +/** THE TASKS OF THE REPO, AND THE CHANGES NOT COMMITTED YET. The page reads `get()` through + * React's useSyncExternalStore. + * + * - What it shows is the repo's files with the waiting changes applied, so a moved card is in its + * new column at once. + * - A change is kept as what the person did ("this file's status is done"), and is applied to the + * file as the repo has it when the commit is made. So a commit somebody else made meanwhile + * (an edit in Docs, an agent's) is never written over: only the status line is ours. + * - A commit names the tip it was decided on (`parent`). When the tip has moved, the repo refuses + * it, and the board reads again and tries again. + * - A commit whose answer was lost (the publication it starts can cut the socket) is tried + * again, and then changes nothing: the files already say what it wanted. + * - Reads and commits run one at a time. */ +class Board { + #listeners = new Set(); + #view; + /** The repo's task files at `#tip`, by path; null before the first read. */ + #files = null; + #tip = null; + #loadError = null; + /** The changes not committed yet, oldest first. */ + #pending = []; + /** The tasks made on this page, newest first: they head their column, where their maker looks. */ + #made = []; + /** `state`: "idle", "waiting" (a commit is due), "saving", "saved" or "failed". */ + #save = { state: "idle", error: null }; + #timer = null; + #firstChangeAt = 0; + #savedTimer = null; + #serial = Promise.resolve(); + + constructor() { + this.#publish(); + } + + subscribe = (listener) => { + this.#listeners.add(listener); + return () => this.#listeners.delete(listener); + }; + + get = () => this.#view; + + #publish() { + const files = this.#files ? this.#pending.reduce(applyChange, this.#files) : {}; + this.#view = { + loaded: Boolean(this.#files), + loadError: this.#loadError, + tasks: madeFirst(tasksOf(files), this.#made), + paths: Object.keys(files), + /** the paths with a change that is not committed yet */ + unsaved: new Set(this.#pending.map((change) => change.path)), + save: this.#save, + }; + for (const listener of this.#listeners) listener(); + } + + #exclusive(work) { + const run = this.#serial.then(work); + this.#serial = run.catch(() => {}); + return run; + } + + /** The task files at the repo's tip. `modules` answers the paths under the folder without the + * folder's name; a repo with no tasks/ answers none. */ + async #readTip() { + const repo = itx.repos.get(REPO); + try { + const tip = await repo.tip(); + if (tip === this.#tip && this.#files) return { tip, files: this.#files }; + const under = tip ? await repo.modules({ commitOid: tip, dir: TASKS_DIR }) : {}; + const files = Object.fromEntries( + Object.entries(under).map(([path, text]) => [`${TASKS_DIR}/${path}`, text]), + ); + return { tip, files }; + } finally { + repo[Symbol.dispose]?.(); + } + } + + /** Read the repo again: at the page's start, and after each commit to it. */ + read() { + return this.#exclusive(async () => { + try { + const { tip, files } = await this.#readTip(); + if (files === this.#files) return; + this.#tip = tip; + this.#files = files; + this.#loadError = null; + } catch (error) { + // a board that has drawn keeps what it drew: the next commit's event reads again + if (this.#files) return; + this.#loadError = wordsOf(error); + } + this.#publish(); + }); + } + + /** Hear of each commit to the repo, and read once now. Answers what lets go of it. A session of + * the member's itx ends with its socket, so the page opens this again at each new session. */ + open() { + const { epoch } = pageSession.get(); + let closed = false; + let subscription = null; + void (async () => { + // subscribed before the read: a commit between the two is read again, never missed + const opened = await itx.subscribe({ + consumes: ["events.iterate.com/repo/commit-completed"], + target: (events) => { + // capnweb hands each event as a proxy, which structuredClone refuses: a plain copy to read + // react-doctor-disable-next-line react-doctor/no-json-parse-stringify-clone -- a structured clone refuses a proxy; JSON reads one through its properties (the UI kit's DocList does the same) + const commits = JSON.parse(JSON.stringify(events)); + const moved = commits.some( + (event) => event?.payload?.path === REPO && event.payload.commitOid !== this.#tip, + ); + if (moved && !closed) void this.read(); + }, + }); + if (closed) return opened[Symbol.dispose]?.(); + subscription = opened; + await this.read(); + // what waited through a cut connection is committed now + if (this.#pending.length > 0) this.#schedule(0); + })().catch((error) => { + if (closed || this.#files) return; + this.#loadError = wordsOf(error); + this.#publish(); + }); + return () => { + closed = true; + // a session that is gone took its subscriptions with it: there is nothing to let go of + const now = pageSession.get(); + if (now.epoch === epoch && now.state === "open") subscription?.[Symbol.dispose]?.(); + }; + } + + /** A person changed something: shown at once, committed a moment later. */ + change(change) { + this.#pending = [...this.#pending, change]; + if (change.kind === "create") this.#made = [change.path, ...this.#made]; + this.#firstChangeAt ||= Date.now(); + this.#save = { state: "waiting", error: null }; + this.#publish(); + this.#schedule( + Math.max( + 0, + // 6000: at most that long after the first change that is not committed yet + Math.min(COMMIT_AFTER_MS, this.#firstChangeAt + 6000 - Date.now()), + ), + ); + } + + /** Commit what waits now: "Try again" after a commit failed, and the page being left. */ + commitNow() { + if (this.#pending.length > 0) this.#schedule(0); + } + + #schedule(ms) { + clearTimeout(this.#timer); + this.#timer = setTimeout(() => void this.#commit(), ms); + } + + #commit() { + return this.#exclusive(async () => { + const sending = this.#pending; + if (sending.length === 0) return; + clearTimeout(this.#savedTimer); + this.#firstChangeAt = 0; + this.#save = { state: "saving", error: null }; + this.#publish(); + try { + await this.#send(sending); + // what a person changed while this commit ran waits for the next one + this.#pending = this.#pending.slice(sending.length); + this.#save = { state: this.#pending.length > 0 ? "waiting" : "saved", error: null }; + if (this.#pending.length > 0) { + this.#firstChangeAt = Date.now(); + this.#schedule(COMMIT_AFTER_MS); + } else { + this.#savedTimer = setTimeout(() => { + if (this.#save.state !== "saved") return; + this.#save = { state: "idle", error: null }; + this.#publish(); + }, 2500); + } + } catch (error) { + // the changes stay on the board and wait: "Try again", or the next change, commits them + this.#save = { state: "failed", error: wordsOf(error) }; + } + this.#publish(); + }); + } + + /** One commit of `changes` on the repo's tip. Tried again when the repo refuses it (its tip + * moved) or the answer is lost: each try reads the tip first, and a try that finds nothing + * left to write is done. */ + async #send(changes) { + const waits = [400, 1500, 4000]; + for (let attempt = 0; ; attempt += 1) { + try { + const { tip, files } = await this.#readTip(); + this.#tip = tip; + this.#files = files; + const written = commitOf(files, changes); + if (written.length === 0) return; + const repo = itx.repos.get(REPO); + try { + const { commitOid } = await repo.commitFiles({ + message: messageOf(changes), + changes: written, + parent: tip, + author, + }); + this.#files = { + ...files, + ...Object.fromEntries(written.map((each) => [each.path, each.content])), + }; + this.#tip = commitOid || tip; + return; + } finally { + repo[Symbol.dispose]?.(); + } + } catch (error) { + if (attempt >= waits.length) throw error; + await new Promise((done) => setTimeout(done, waits[attempt])); + } + } + } +} + +/** `tasks` with those of `made` first, in its order; the others stay as they were. */ +function madeFirst(tasks, made) { + if (made.length === 0) return tasks; + const place = new Map(made.map((path, at) => [path, at])); + const first = tasks + .filter((task) => place.has(task.path)) + .sort((a, b) => place.get(a.path) - place.get(b.path)); + return [...first, ...tasks.filter((task) => !place.has(task.path))]; +} + +const board = new Board(); + +// a page that is left commits what waits; a commit that cannot finish is said first +addEventListener("pagehide", () => board.commitNow()); +addEventListener("beforeunload", (event) => { + if (board.get().unsaved.size === 0) return; + board.commitNow(); + event.preventDefault(); +}); + +// ── the URL ── +// THE VIEW IS A LINK: `?q=` the words, `?folder=` a folder under tasks/ ("." for the top), +// `?status=` one or more columns (`?status=in-progress&status=todo`), one parameter for each value +// of a dimension that filters (`?tag=onboarding&size=large`: one of the tags AND that size), +// `?group=priority` the dimension that breaks the board into rows, and `?task=<path>` the task +// whose sheet is open. The board is ONE board over every file under tasks/, however deep: a folder +// narrows it, and no row is a folder. +const subscribeToUrl = (listener) => { + addEventListener("popstate", listener); + return () => removeEventListener("popstate", listener); +}; + +function setView(change) { + const next = new URLSearchParams(location.search); + for (const [key, value] of Object.entries(change)) { + next.delete(key); + // a list is one parameter for each element + for (const each of [value].flat()) + if (each !== undefined && each !== "" && each !== null) next.append(key, each); + } + const query = next.toString(); + // a filter typed letter by letter is one entry of the history, not one a letter + history.replaceState(null, "", query ? `?${query}` : location.pathname); + dispatchEvent(new PopStateEvent("popstate")); +} + +function useView() { + const search = useSyncExternalStore(subscribeToUrl, () => location.search); + return useMemo(() => { + const params = new URLSearchParams(search); + const folder = params.get("folder"); + return { + query: params.get("q") || "", + // oxlint-disable-next-line iterate/simple-truthiness-check -- no `folder` in the address (null) is no folder asked for; "." is the top of tasks/, which is "" + folder: folder === null ? null : folder === "." ? "" : folder, + /** the columns that filter, normalized (`?status=in-progress&status=todo`) */ + statuses: [...new Set(params.getAll("status").filter(Boolean).map(columnOf))], + /** the values that filter, by dimension: { tags: ["ui"], size: [], … } */ + where: Object.fromEntries( + DIMENSIONS.map(({ id, param }) => [id, params.getAll(param).filter(Boolean)]), + ), + /** the dimension that breaks the board into rows, by its id, or null */ + group: DIMENSIONS.find(({ id }) => id === params.get("group"))?.id ?? null, + /** the path of the task whose sheet is open, or null */ + task: params.get("task"), + /** `?needs=person`: the list of what waits for a person in place of the board */ + needs: params.get("needs") === "person", + }; + }, [search]); +} + +/** Filter by a value of a dimension, or let go of it when it filters already. */ +function pick(view, dimension, value) { + const now = view.where[dimension.id]; + setView({ + [dimension.param]: now.includes(value) ? now.filter((each) => each !== value) : [...now, value], + }); +} + +/** The board with no filter: the words, the folder, the statuses and every dimension's values let go. */ +const showEverything = () => + setView({ + q: undefined, + folder: undefined, + status: undefined, + ...Object.fromEntries(DIMENSIONS.map(({ param }) => [param, undefined])), + }); + +/** A value as a person reads it: an agent is its path's last part. */ +const valueLabel = (dimension, value) => + dimension.id === "agent" ? value.split("/").filter(Boolean).at(-1) || value : value; + +// ── a status's mark ── +// A ring that fills as the work goes on, as issue trackers draw it: dashed for the backlog, open +// for todo, half and three quarters for the two states of work, and a check for done. A status of +// its own is a plain dot. +function StatusMark({ column }) { + const share = { todo: 0, "in-progress": 0.5, "in-review": 0.75 }[column]; + if (column === "done") + return html` + <svg class="status-mark" data-status="done" viewBox="0 0 16 16" aria-hidden="true"> + <circle cx="8" cy="8" r="7" fill="currentColor" /> + <path + d="M5 8.2l2.1 2.1L11.2 6" + fill="none" + stroke="var(--background)" + stroke-width="1.6" + stroke-linecap="round" + stroke-linejoin="round" + /> + </svg> + `; + if (column === "backlog") + return html` + <svg class="status-mark" data-status="backlog" viewBox="0 0 16 16" aria-hidden="true"> + <circle + cx="8" + cy="8" + r="6.25" + fill="none" + stroke="currentColor" + stroke-width="1.5" + stroke-dasharray="2.2 2.2" + /> + </svg> + `; + if (share === undefined) + return html` + <svg class="status-mark" data-status="own" viewBox="0 0 16 16" aria-hidden="true"> + <circle cx="8" cy="8" r="6.25" fill="none" stroke="currentColor" stroke-width="1.5" /> + <circle cx="8" cy="8" r="2.5" fill="currentColor" /> + </svg> + `; + // the filled part is a circle of radius 2 drawn with a stroke 4 wide: a pie of `share` + const round = 2 * Math.PI * 2; + return html` + <svg class="status-mark" data-status=${column} viewBox="0 0 16 16" aria-hidden="true"> + <circle cx="8" cy="8" r="6.25" fill="none" stroke="currentColor" stroke-width="1.5" /> + ${ + share > 0 && + html`<circle + cx="8" + cy="8" + r="2" + fill="none" + stroke="currentColor" + stroke-width="4" + stroke-dasharray=${`${round * share} ${round}`} + transform="rotate(-90 8 8)" + />` + } + </svg> + `; +} + +/** The status a card gets in a column: the column's id, or for a status of its own the words the + * files use for it. */ +const statusOf = (column) => (column.own ? column.label : column.id); + +// ── the page ── + +function App() { + const { epoch } = useSyncExternalStore(pageSession.subscribe, pageSession.get, pageSession.get); + // the board's subscription is of one session: opened again at each new one + useEffect(() => board.open(), [epoch]); + const state = useSyncExternalStore(board.subscribe, board.get); + const view = useView(); + const [composer, setComposer] = useState(null); + const searchRef = useRef(null); + // the mind's repos by name, for the bar's "Repo" menu: the one shown is always among them + const [repos, setRepos] = useState([REPO_NAME]); + useEffect(() => { + let current = true; + itx.repos.list().then( + (listed) => { + const names = listed + .map((repo) => /^\/repos\/([^/]+)$/.exec(repo.path)?.[1]) + .filter(Boolean); + if (current) setRepos([...new Set([REPO_NAME, ...names])].sort()); + }, + // the menu then holds this repo alone + () => {}, + ); + return () => { + current = false; + }; + }, [epoch]); + + const shown = useMemo(() => filterTasks(state.tasks, view), [state.tasks, view]); + const allColumns = useMemo(() => columnsOf(state.tasks), [state.tasks]); + const columns = useMemo( + () => + view.statuses.length > 0 + ? allColumns.filter((column) => view.statuses.includes(column.id)) + : allColumns, + [allColumns, view.statuses], + ); + /** the dimensions that the files hold: no file with a priority, no priority on the page */ + const dimensions = useMemo(() => dimensionsOf(state.tasks), [state.tasks]); + // iterate DIMENSIONS (not `dimensions`) so a deep-linked filter chip is always visible and removable + const picked = DIMENSIONS.flatMap((dimension) => + view.where[dimension.id].map((value) => ({ dimension, value })), + ); + const filtered = Boolean( + view.query || + view.folder !== null || + view.statuses.length > 0 || + DIMENSIONS.some(({ id }) => view.where[id].length > 0), + ); + /** the dimension of the rows, when the link names one that the files hold */ + const group = dimensions.find((dimension) => dimension.id === view.group) ?? null; + // the rows: one for each value of that dimension that has a task shown, or one row with every + // task. `value` is the row's value, null for the tasks that have none, undefined with no rows. + const rows = useMemo(() => { + if (!group) return [{ value: undefined, tasks: shown }]; + const found = rowsOf(shown, group); + return found.length > 0 ? found : [{ value: null, label: group.none, tasks: [] }]; + }, [group, shown]); + + /** Open the box for a new task in a column, in the folder the board shows, and in a row when the + * board has rows (the first one, when the bar's button or "c" asks). */ + const compose = (column, row = rows[0].value) => + setComposer({ column: column.id, status: statusOf(column), folder: view.folder ?? "", row }); + const create = (title) => { + if (!composer || !title.trim()) return; + // a task made in a filtered view or row inherits its active filter values so it stays visible + const fields = {}; + for (const dimension of DIMENSIONS) { + const active = view.where[dimension.id]; + if (active.length === 0) continue; + fields[dimension.id] = dimension.many ? [...active] : active[0]; + } + if (group && composer.row) { + fields[group.id] = group.many + ? [...new Set([...(fields[group.id] || []), composer.row])] + : composer.row; + } + const made = newTask({ + title, + status: composer.status, + folder: composer.folder, + taken: state.paths, + fields, + }); + board.change({ kind: "create", ...made }); + }; + const move = (task, column) => { + if (task.column !== column.id) + board.change({ kind: "status", path: task.path, status: statusOf(column) }); + }; + + // "/" goes to the search, "c" makes a task: only when nobody is typing + useEffect(() => { + const onKey = (event) => { + if (event.metaKey || event.ctrlKey || event.altKey) return; + const at = document.activeElement; + if (at && (/^(?:INPUT|TEXTAREA|SELECT)$/.test(at.tagName) || at.isContentEditable)) return; + if (event.key === "/") { + event.preventDefault(); + searchRef.current?.focus(); + } else if (event.key === "c" && state.loaded) { + event.preventDefault(); + compose(columns.find((column) => column.id === "todo") || columns[0] || allColumns[0]); + } + }; + addEventListener("keydown", onKey); + return () => removeEventListener("keydown", onKey); + }); + + return html` + <${AppShell} + app="Tasks" + mind=${domain} + mindHref=${() => "./"} + nav=${html`<${Nav} tasks=${state.tasks} dimensions=${dimensions} view=${view} />`} + account=${principal} + locationKey=${location.pathname + location.search} + > + <${AppShellPageHeader}> + <div class="tasks-bar"> + <label class="tasks-search"> + <${SearchIcon} /> + <${Input} + ref=${searchRef} + type="search" + placeholder="Filter tasks" + aria-label="Filter tasks" + value=${view.query} + onChange=${(event) => setView({ q: event.target.value })} + onKeyDown=${(event) => event.key === "Escape" && event.target.blur()} + /> + </label> + <${DropdownMenu}> + <${DropdownMenuTrigger} + render=${html`<${Button} variant="ghost" size="sm" className="tasks-group" />`} + > + <span>Repo<span class="tasks-wide">: ${REPO_NAME}</span></span> + <${ChevronDownIcon} data-icon="inline-end" /> + <//> + <${DropdownMenuContent} align="start" className="task-menu-popup"> + <${DropdownMenuGroup}> + <${DropdownMenuLabel}>Tasks of the repo<//> + <${DropdownMenuRadioGroup} value=${REPO_NAME} onValueChange=${showRepo}> + ${repos.map( + (name) => + html`<${DropdownMenuRadioItem} key=${name} value=${name} closeOnClick=${true} + >${name}<// + >`, + )} + <//> + <//> + <//> + <//> + ${ + dimensions.length > 0 && + html` + <${DropdownMenu}> + <${DropdownMenuTrigger} + render=${html`<${Button} variant=${group ? "secondary" : "ghost"} size="sm" className="tasks-group" />`} + > + <span>Group${group && html`<span class="tasks-wide">: ${group.one}</span>`}</span> + <${ChevronDownIcon} data-icon="inline-end" /> + <//> + <${DropdownMenuContent} align="start" className="task-menu-popup"> + <${DropdownMenuGroup}> + <${DropdownMenuLabel}>Rows by<//> + <${DropdownMenuRadioGroup} + value=${group?.id ?? "none"} + onValueChange=${(id) => setView({ group: id === "none" ? undefined : id })} + > + <${DropdownMenuRadioItem} value="none" closeOnClick=${true}>Nothing<//> + ${dimensions.map( + (dimension) => html` + <${DropdownMenuRadioItem} + key=${dimension.id} + value=${dimension.id} + closeOnClick=${true} + > + ${dimension.one} + <//> + `, + )} + <//> + <//> + <//> + <//> + ` + } + <span class="tasks-bar-end"> + <${SaveMark} save=${state.save} /> + <${Button} + size="sm" + disabled=${!state.loaded} + aria-label="New task" + onClick=${() => compose(columns.find((column) => column.id === "todo") || columns[0] || allColumns[0])} + > + <${PlusIcon} data-icon="inline-start" /><span class="tasks-wide">New task</span> + <//> + </span> + </div> + <//> + ${ + view.needs + ? html`<${NeedsPage} state=${state} tasks=${needsAPerson(shown)} filtered=${filtered} />` + : html`<${Page} + state=${state} + shown=${shown} + columns=${columns} + allColumns=${allColumns} + view=${view} + picked=${picked} + group=${group} + rows=${rows} + filtered=${filtered} + composer=${composer} + compose=${compose} + closeComposer=${() => setComposer(null)} + create=${create} + move=${move} + />` + } + <//> + <${TaskSheet} + path=${view.task} + state=${state} + columns=${allColumns} + dimensions=${dimensions} + move=${move} + /> + <${ReconnectingMark} itx=${itx} /> + `; +} + +/** Beside the title: whether what the person changed is in the repo yet. */ +function SaveMark({ save }) { + if (save.state === "waiting" || save.state === "saving") + return html`<span class="tasks-save" role="status"><${Spinner} />Saving…</span>`; + if (save.state === "saved") + return html`<span class="tasks-save" role="status"><${CheckIcon} />Saved</span>`; + if (save.state === "failed") + return html` + <span class="tasks-save" data-failed role="alert" title=${save.error}> + <${TriangleAlertIcon} />Not saved + <${Button} variant="outline" size="xs" onClick=${() => board.commitNow()}>Try again<//> + </span> + `; + return null; +} + +/** The sidebar: the folders under tasks/, then each dimension that the files hold with its values, + * each with how many tasks it has. A press on one filters the board; a press on one that filters + * lets go of it. */ +function Nav({ tasks, dimensions, view }) { + const folders = useMemo(() => { + // a folder counts what is in it and beneath it, as the filter does + const names = new Set(); + for (const task of tasks) { + const parts = task.folder ? task.folder.split("/") : []; + for (let depth = 1; depth <= parts.length; depth += 1) + names.add(parts.slice(0, depth).join("/")); + } + return [...names] + .sort() + .map((name) => [ + name, + tasks.filter((task) => task.folder === name || task.folder.startsWith(`${name}/`)).length, + ]); + }, [tasks]); + const row = (key, label, count, active, onClick, depth = 0) => html` + <${SidebarMenuItem} key=${key}> + <${SidebarMenuButton} isActive=${active} onClick=${onClick} tooltip=${label}> + <span class="tasks-nav-label" style=${{ paddingInlineStart: `${depth * 0.75}rem` }} + >${label}</span + > + <//> + <${SidebarMenuBadge}>${count}<//> + <//> + `; + return html` + <${SidebarGroup}> + <${SidebarGroupLabel}>Tasks<//> + <${SidebarGroupContent}> + <${SidebarMenu}> + ${row( + "all", + "All tasks", + tasks.length, + !view.needs && + !view.query && + view.folder === null && + view.statuses.length === 0 && + DIMENSIONS.every(({ id }) => view.where[id].length === 0), + () => + setView({ + q: undefined, + folder: undefined, + status: undefined, + needs: undefined, + ...Object.fromEntries(DIMENSIONS.map(({ param }) => [param, undefined])), + }), + )} + ${row("needs", "Needs a person", needsAPerson(tasks).length, view.needs, () => + setView({ needs: view.needs ? undefined : "person" }), + )} + ${folders.map(([name, count]) => + row( + `folder:${name}`, + name.split("/").at(-1), + count, + view.folder === name, + () => setView({ folder: view.folder === name ? undefined : name }), + name.split("/").length, + ), + )} + <//> + <//> + <//> + ${dimensions.map( + (dimension) => html` + <${SidebarGroup} key=${dimension.id}> + <${SidebarGroupLabel}>${dimension.label}<//> + <${SidebarGroupContent}> + <${SidebarMenu}> + ${dimension.values.map(([value, count]) => + row( + `${dimension.id}:${value}`, + valueLabel(dimension, value), + count, + view.where[dimension.id].includes(value), + () => pick(view, dimension, value), + ), + )} + <//> + <//> + <//> + `, + )} + `; +} + +/** WHO ASKED EACH OPEN ASK OF THE BOARD: `itx.config.taskAskers` (apps/tasks/askers.js), which + * reads it from the change feed, as a map from `<file>\n<ask>` to its row. Null until the first + * answer; "unread" when the call fails, so that the page then says what it does know (the + * task's agent) and that the asker could not be read. It is asked again when the board's asks change, and once more a moment later + * when an ask has no asker yet: the feed hears of a commit a moment after the board does. */ +function useAskers(tasks) { + const asked = tasks + .flatMap((task) => task.humanAsk.map((ask) => `${task.path}\n${ask}`)) + .join("\n\n"); + const [askers, setAskers] = useState(null); + useEffect(() => { + if (!asked) return undefined; + let live = true; + let timer; + const read = (again) => + itx.config.taskAskers({ repo: REPO_NAME }).then( + (answer) => { + if (!live) return; + setAskers(new Map(answer.asks.map((row) => [`${row.file}\n${row.ask}`, row]))); + if (again && answer.asks.some((row) => !row.at)) + timer = setTimeout(() => read(false), 4000); + }, + () => live && setAskers((now) => now ?? "unread"), + ); + read(true); + return () => { + live = false; + clearTimeout(timer); + }; + }, [asked]); + return askers; +} + +/** WHO ASKED, UNDER AN ASK: the agent that added the ask, as a link to its chat in the Dash, where + * a person asks it why before they answer. `asker` is the ask's row of `useAskers`. When nothing + * says who asked (an ask older than the change feed, or one written by hand), the line names the + * task's own agent and SAYS that it is the task's agent: that one may not be the asker. A person + * who asked on the board is named with no link. */ +function Asker({ task, asker }) { + const when = asker?.at ? ` on ${asker.at.slice(0, 16).replace("T", " ")} UTC` : ""; + if (asker?.agent && agentHref(asker.agent)) + return html` + <a + class="needs-asker" + data-asker="agent" + href=${agentHref(asker.agent)} + target="_blank" + rel="noreferrer" + title=${`${asker.agent} asked this${when}. Opens its chat in the Dash.`} + > + Asked by ${valueLabel(DIMENSION.agent, asker.agent)}<${ExternalLinkIcon} /> + </a> + `; + if (asker?.by && !asker.by.startsWith("/")) + return html`<span + class="needs-asker" + data-asker="person" + title=${`${asker.by} asked this${when}${asker.page ? ` on ${asker.page}` : ""}.`} + >Asked by ${asker.by}</span + >`; + // the first answer is not here yet: say nothing, not the wrong agent + if (!asker || !agentHref(task.agent)) return null; + return html` + <a + class="needs-asker" + data-asker="assignee" + href=${agentHref(task.agent)} + target="_blank" + rel="noreferrer" + title=${`${asker.unread ? "Who asked this could not be read" : "Who asked this is not recorded"}. ${task.agent} is the agent that has the task. Opens its chat in the Dash.`} + > + ${asker.unread ? "Asker not read" : "Asker not recorded"}. The task's agent: + ${valueLabel(DIMENSION.agent, task.agent)}<${ExternalLinkIcon} /> + </a> + `; +} + +/** ONE ASK OF A TASK, WITH THE BOX THAT ANSWERS IT. An answer is a change like a moved card: the + * ask leaves the list at once, and a commit a moment later takes its line out of the file's + * `human-ask:` and keeps the ask with the answer, who gave it and when under `## Answers` in the + * task's text (tasks-model.js `answerAsk`). The agent that follows the task hears of that commit + * (apps/tasks/feed.js), so nobody has to tell it. */ +function Ask({ task, ask, asker }) { + const [answer, setAnswer] = useState(""); + return html` + <li> + <span>${ask}</span> + <${Asker} task=${task} asker=${asker} /> + <form + class="needs-answer" + onSubmit=${(event) => { + event.preventDefault(); + if (!answer.trim()) return; + board.change({ + kind: "answer", + path: task.path, + ask, + answer, + by: principal?.email || principal?.actor || "someone", + at: new Date().toISOString(), + }); + }} + > + <${Input} + placeholder="Your answer, then Enter" + aria-label=${`Your answer to: ${ask}`} + value=${answer} + onChange=${(event) => setAnswer(event.target.value)} + onKeyDown=${(event) => { + // Enter sends it, with Cmd or Ctrl too: a browser sends a form on the bare key alone + if (event.key !== "Enter" || event.isComposing || event.nativeEvent?.isComposing) + return; + event.preventDefault(); + event.currentTarget.form.requestSubmit(); + }} + /> + <${Button} type="submit" variant="outline" size="sm" disabled=${!answer.trim()}>Answer<//> + </form> + </li> + `; +} + +/** "Needs a person" (`?needs=person`), in place of the board: each task that is not done and asks a + * person something (`human-ask:`) or says what holds it (`blocked-on:`), as a row. A person + * answers an ask here (`Ask`), and each ask names the agent that asked it, as a link to its chat + * (`Asker`); what holds a task is only read. The board's other filters still narrow it. */ +function NeedsPage({ state, tasks, filtered }) { + const askers = useAskers(tasks); + if (!state.loaded) + return state.loadError + ? html`<p class="tasks-note" role="alert">Couldn't read the tasks: ${state.loadError}</p>` + : html`<p class="tasks-note">Reading the tasks…</p>`; + if (tasks.length === 0 && filtered) + return html` + <p class="tasks-note"> + No task that needs a person matches.${" "} + <button class="tasks-link" onClick=${showEverything}>Show every task</button> + </p> + `; + if (tasks.length === 0) + return html` + <${Empty} className="tasks-empty"> + <${EmptyHeader}> + <${EmptyTitle}>Nothing waits for a person<//> + <${EmptyDescription}> + A task asks a person with <code>human-ask:</code> in its frontmatter, and says what + holds it with <code>blocked-on:</code>. An ask is answered here. A done task is not + listed. + <//> + <//> + <//> + `; + return html` + <ul class="needs" aria-label="Tasks that need a person"> + ${tasks.map( + (task) => html` + <li class="needs-row" key=${task.path}> + <div class="needs-top"> + <${StatusMark} column=${task.column} /> + <a + class="task-title" + href=${taskHref(task.path)} + onClick=${(event) => { + if ( + event.button !== 0 || + event.metaKey || + event.ctrlKey || + event.shiftKey || + event.altKey + ) + return; + event.preventDefault(); + openTask(task.path); + }} + > + ${task.title} + </a> + ${task.owner && html`<${Badge} variant="outline">${task.owner}<//>`} + </div> + ${ + task.humanAsk.length > 0 && + html` + <ul class="needs-asks" aria-label="Asks"> + ${task.humanAsk.map( + (ask) => + html`<${Ask} + key=${ask} + task=${task} + ask=${ask} + asker=${ + // a row with no asker for an ask that the answer does not have (a new one): the task's agent then + askers && + (askers === "unread" + ? { unread: true } + : (askers.get(`${task.path}\n${ask}`) ?? {})) + } + />`, + )} + </ul> + ` + } + ${task.blockedOn && html`<p class="needs-blocked">Blocked on: ${task.blockedOn}</p>`} + </li> + `, + )} + </ul> + `; +} + +/** Beside the sidebar: the board, or the line that says why there is none. */ +function Page({ + state, + shown, + columns, + allColumns, + view, + picked, + group, + rows, + filtered, + composer, + compose, + closeComposer, + create, + move, +}) { + if (!state.loaded) + return state.loadError + ? html`<p class="tasks-note" role="alert">Couldn't read the tasks: ${state.loadError}</p>` + : html`<p class="tasks-note">Reading the tasks…</p>`; + if (state.tasks.length === 0 && !composer) + return html` + <${Empty} className="tasks-empty"> + <${EmptyHeader}> + <${EmptyTitle}>No tasks yet<//> + <${EmptyDescription}> + A task is a markdown file under <code>${TASKS_DIR}/</code> in the repo + <code>${REPO}</code>. Make the first one here, or commit one. + <//> + <//> + <${EmptyContent}> + <${Button} onClick=${() => compose(columns.find((column) => column.id === "todo"))}> + <${PlusIcon} data-icon="inline-start" />New task + <//> + <//> + <//> + `; + return html` + ${ + (view.folder !== null || view.statuses.length > 0 || picked.length > 0) && + html` + <div class="tasks-picked" role="group" aria-label="What filters the board"> + ${ + view.folder !== null && + html` + <button class="tasks-chip" onClick=${() => setView({ folder: undefined })}> + <span class="tasks-chip-of">Folder</span>${view.folder || TASKS_DIR}<${XIcon} + aria-label="Remove this filter" + /> + </button> + ` + } + ${view.statuses.map( + (status) => html` + <button + class="tasks-chip" + key=${`status:${status}`} + onClick=${() => setView({ status: view.statuses.filter((each) => each !== status) })} + > + <span class="tasks-chip-of">Status</span + >${columns.find((column) => column.id === status)?.label || status} + <${XIcon} aria-label="Remove this filter" /> + </button> + `, + )} + ${picked.map( + ({ dimension, value }) => html` + <button + class="tasks-chip" + key=${`${dimension.id}:${value}`} + onClick=${() => pick(view, dimension, value)} + > + <span class="tasks-chip-of">${dimension.one}</span>${valueLabel(dimension, value)} + <${XIcon} aria-label="Remove this filter" /> + </button> + `, + )} + <button class="tasks-link" onClick=${showEverything}>Clear</button> + </div> + ` + } + <div class="board" style=${{ "--columns": columns.length }}> + <div class="board-head"> + ${columns.map( + (column) => html` + <div class="board-column-head" key=${column.id}> + <${StatusMark} column=${column.id} /> + <span class="board-column-name">${column.label}</span> + <span class="board-column-count"> + ${shown.filter((task) => task.column === column.id).length} + </span> + <${Button} + variant="ghost" + size="icon-xs" + className="board-column-add" + aria-label=${`New task in ${column.label}`} + onClick=${() => compose(column)} + > + <${PlusIcon} /> + <//> + </div> + `, + )} + </div> + ${ + filtered && shown.length === 0 && !composer + ? html` + <p class="tasks-note"> + No task matches.${" "} + <button class="tasks-link" onClick=${showEverything}>Show every task</button> + </p> + ` + : rows.map( + (row) => html` + <section class="board-row" key=${String(row.value)}> + ${ + group && + html` + <h2 class="board-row-name"> + <span class="board-row-of">${group.one}</span> + ${row.value === null ? row.label : valueLabel(group, row.value)} + <span class="board-column-count">${row.tasks.length}</span> + </h2> + ` + } + <div class="board-cells"> + ${columns.map( + (column) => html` + <${Cell} + key=${column.id} + column=${column} + columns=${allColumns} + tasks=${row.tasks.filter((task) => task.column === column.id)} + all=${state.tasks} + unsaved=${state.unsaved} + view=${view} + group=${group} + composing=${composer?.column === column.id && composer.row === row.value} + compose=${() => compose(column, row.value)} + closeComposer=${closeComposer} + create=${create} + move=${move} + /> + `, + )} + </div> + </section> + `, + ) + } + </div> + `; +} + +/** How many cards a cell shows before "Show more": a long Done column costs nothing to draw. */ +const CELL_PAGE = 40; + +/** One column of one row: its cards, the box for a new one, and where a dragged card is dropped. + * A drop changes the card's STATUS and nothing else: a card dropped in another row stays in its + * own row, because the board writes no dimension of a file that exists. */ +function Cell({ + column, + columns, + tasks, + all, + unsaved, + view, + group, + composing, + compose, + closeComposer, + create, + move, +}) { + const [over, setOver] = useState(false); + const [limit, setLimit] = useState(CELL_PAGE); + return html` + <div + class="board-cell" + data-over=${over || undefined} + data-column=${column.id} + onDragOver=${(event) => { + if (!event.dataTransfer.types.includes("application/x-task")) return; + event.preventDefault(); + event.dataTransfer.dropEffect = "move"; + if (!over) setOver(true); + }} + onDragLeave=${(event) => { + if (!event.currentTarget.contains(event.relatedTarget)) setOver(false); + }} + onDrop=${(event) => { + setOver(false); + const path = event.dataTransfer.getData("application/x-task"); + const task = all.find((each) => each.path === path); + if (!task) return; + event.preventDefault(); + move(task, column); + }} + > + ${composing && html`<${Composer} create=${create} close=${closeComposer} />`} + ${tasks + .slice(0, limit) + .map( + (task) => html` + <${Card} + key=${task.path} + task=${task} + columns=${columns} + unsaved=${unsaved.has(task.path)} + view=${view} + group=${group} + move=${move} + /> + `, + )} + ${ + tasks.length > limit && + html` + <button class="tasks-link board-more" onClick=${() => setLimit(limit + CELL_PAGE)}> + Show ${Math.min(CELL_PAGE, tasks.length - limit)} more of ${tasks.length - limit} + </button> + ` + } + ${ + !composing && + html` + <button + class="board-cell-add" + aria-label=${`New task in ${column.label}`} + onClick=${compose} + > + <${PlusIcon} /> + </button> + ` + } + </div> + `; +} + +/** The box a new task's title is written in. Enter makes the task and leaves the box open for the + * next one; Escape, or leaving it empty, closes it. */ +function Composer({ create, close }) { + const [title, setTitle] = useState(""); + const ref = useRef(null); + useEffect(() => ref.current?.focus(), []); + return html` + <form + class="task task-composer" + onSubmit=${(event) => { + event.preventDefault(); + if (!title.trim()) return close(); + create(title); + setTitle(""); + }} + > + <textarea + ref=${ref} + rows="2" + placeholder="Task title" + aria-label="Task title" + value=${title} + onChange=${(event) => setTitle(event.target.value.replace(/\n/g, " "))} + onKeyDown=${(event) => { + if (event.key === "Escape") close(); + if (event.key === "Enter" && !event.shiftKey) { + event.preventDefault(); + event.currentTarget.form.requestSubmit(); + } + }} + onBlur=${() => !title.trim() && close()} + ></textarea> + <div class="task-composer-foot"> + <span>Enter to add · Esc to close</span> + <${Button} type="submit" size="xs" disabled=${!title.trim()}>Add<//> + </div> + </form> + `; +} + +/** A value of a dimension on a card: a press filters the board by it, and a second press lets go. */ +function Value({ view, dimension, value, className, title, children }) { + const on = view.where[dimension.id].includes(value); + return html` + <button + type="button" + class=${`task-value ${className || ""}`} + data-dimension=${dimension.id} + data-value=${String(value).toLowerCase()} + aria-pressed=${on} + title=${title || `${dimension.one}: ${value}${on ? " (filters the board)" : ""}`} + onClick=${() => pick(view, dimension, value)} + > + ${children ?? value} + </button> + `; +} + +const DIMENSION = Object.fromEntries(DIMENSIONS.map((dimension) => [dimension.id, dimension])); +/** The first letters of a name's first two words: "jonas templestein" is JT, "jonas" is JO. */ +const initialsOf = (name) => { + const words = name.split(/[\s._@-]+/).filter(Boolean); + return (words.length > 1 ? words[0][0] + words[1][0] : name.slice(0, 2)).toUpperCase(); +}; + +/** One task. Its title opens the task's sheet (a plain click; the link itself is the board with + * that sheet open, for a new tab); the card is dragged to another column, and + * its menu does the same for a finger or a keyboard. Under the title: the folder, and each + * dimension that the file holds (the one the board's rows are by is left out: the row says it). */ +function Card({ task, columns, unsaved, view, group, move }) { + const has = (id) => (group?.id === id && !DIMENSION[id].many ? [] : valuesOf(task, id)); + const [dragging, setDragging] = useState(false); + return html` + <article + class="task" + draggable="true" + data-dragging=${dragging || undefined} + data-unsaved=${unsaved || undefined} + onDragStart=${(event) => { + event.dataTransfer.setData("application/x-task", task.path); + event.dataTransfer.setData("text/plain", task.title); + event.dataTransfer.effectAllowed = "move"; + setDragging(true); + }} + onDragEnd=${() => setDragging(false)} + > + <div class="task-top"> + <a + class="task-title" + href=${taskHref(task.path)} + draggable="false" + onClick=${(event) => { + if ( + event.button !== 0 || + event.metaKey || + event.ctrlKey || + event.shiftKey || + event.altKey + ) + return; + event.preventDefault(); + openTask(task.path); + }} + > + ${task.title} + </a> + <${DropdownMenu}> + <${DropdownMenuTrigger} + render=${html`<${Button} + variant="ghost" + size="icon-xs" + className="task-menu" + aria-label=${`Actions for ${task.title}`} + />`} + > + <${EllipsisIcon} /> + <//> + <${DropdownMenuContent} align="end" className="task-menu-popup"> + <${DropdownMenuGroup}> + <${DropdownMenuLabel}>Status<//> + <${DropdownMenuRadioGroup} + value=${task.column} + onValueChange=${(id) => + move( + task, + columns.find((column) => column.id === id), + )} + > + ${columns.map( + (column) => html` + <${DropdownMenuRadioItem} key=${column.id} value=${column.id}> + <${StatusMark} column=${column.id} />${column.label} + <//> + `, + )} + <//> + <//> + <${DropdownMenuSeparator} /> + <${DropdownMenuItem} + onClick=${() => window.open(docsHref(task.path), "_blank", "noreferrer")} + > + <${ExternalLinkIcon} />Open in Docs + <//> + <//> + <//> + </div> + <div class="task-meta"> + ${task.folder && html`<span class="task-folder">${task.folder}</span>`} + ${has("priority").map( + (value) => html` + <${Value} key=${value} view=${view} dimension=${DIMENSION.priority} value=${value}> + <${Badge} variant="outline" className="task-tag task-priority"><i></i>${value}<//> + <//> + `, + )} + ${has("tags").map( + (value) => html` + <${Value} key=${value} view=${view} dimension=${DIMENSION.tags} value=${value}> + <${Badge} variant="secondary" className="task-tag">${value}<//> + <//> + `, + )} + ${has("size").map( + (value) => html` + <${Value} key=${value} view=${view} dimension=${DIMENSION.size} value=${value}> + <${Badge} variant="outline" className="task-tag">${value}<//> + <//> + `, + )} + ${ + has("agent").length + has("owner").length > 0 && + html`<span class="task-people"> + ${has("agent").map((value) => + // the agent's mark is a link to its chat in the Dash; a name that is no path filters, as the other values do + agentHref(value) + ? html` + <a + key=${value} + class="task-value task-agent" + data-dimension="agent" + href=${agentHref(value)} + target="_blank" + rel="noreferrer" + title=${`Agent: ${value} (opens its chat in the Dash)`} + aria-label=${`Chat with the agent ${valueLabel(DIMENSION.agent, value)}`} + draggable=${false} + > + <${BotIcon} /> + </a> + ` + : html` + <${Value} + key=${value} + view=${view} + dimension=${DIMENSION.agent} + value=${value} + className="task-agent" + > + <${BotIcon} /> + <//> + `, + )} + ${has("owner").map( + (value) => html` + <${Value} + key=${value} + view=${view} + dimension=${DIMENSION.owner} + value=${value} + className="task-owner" + > + ${initialsOf(value)} + <//> + `, + )} + </span>` + } + ${unsaved && html`<span class="task-unsaved" title="Not in the repo yet"></span>`} + </div> + </article> + `; +} + +// ── the task sheet ── +// A TASK OPENS IN A SHEET AT THE RIGHT OF THE BOARD (`?task=<path>`), and is edited there: +// +// - its TEXT in the Docs app's live editor (@iterate-com/ui's `DocEditor` on a `DocSession`): +// several people type at once, comment on the text, and the doc's processor saves what they +// type as a commit, a minute after the first unsaved edit or when the last one leaves; +// - its TITLE AND PROPERTIES through the board's own changes (`board.change`), as a card's move: +// shown at once on the card and on every open board, and one commit a moment later. The open +// editors get that commit merged into their text by the doc's processor. +// +// So the sheet has two things that can be waiting, and its saving line names both. A changed +// title renames nothing: the file's path is the task's identity. +// +// The editor is the Docs app's, with the Docs app's processors (apps/docs/processors/): the page +// names them exactly as the Docs page does (/processors.json, apps/tasks/app.ts), so a file open +// in both is one doc. Its code is loaded when the first sheet opens, not with the board. + +const PROCESSOR_PACKAGES = ["yjs", "diff", "node-diff3"]; +let editorAsked; +/** The editor's module and the processors' facet spec, asked for once. A failure is asked again + * at the next sheet. */ +function editorOf() { + editorAsked ||= (async () => { + const [kit, answer, manifestText] = await Promise.all([ + import("@iterate-com/ui/components/docs-editor/docs-editor"), + fetch("/processors.json"), + itx.repos.get(CODE_REPO).readFile("package.json"), + ]); + if (!answer.ok) throw new Error(`/processors.json answered ${answer.status}`); + const processors = await answer.json(); + const manifest = JSON.parse(manifestText || "{}"); + const pins = PROCESSOR_PACKAGES.map( + (name) => `${name}@${manifest.dependencies?.[name] || "none"}`, + ); + const me = principal?.email || principal?.actor || "someone"; + return { + DocEditor: kit.DocEditor, + DocSession: kit.DocSession, + user: { name: me, email: me, color: kit.cursorColor(me) }, + // the same spec and the same name as the Docs page's (apps/docs/public/app.js) + facetSpec: (className) => ({ + className, + mainModule: processors.mainModule, + source: ["itx", ["cd", "/"], "repos", ["get", CODE_REPO], ["modules"]], + cacheKey: `docs-processors:${processors.version}:${pins.join(",")}`, + }), + }; + })(); + editorAsked.catch(() => { + editorAsked = undefined; + }); + return editorAsked; +} + +/** The board's link with one task open, and the same link with none. */ +const taskHref = (path) => { + const next = new URLSearchParams(location.search); + if (path) next.set("task", path); + else next.delete("task"); + const query = next.toString(); + return query ? `?${query}` : location.pathname; +}; +/** Open a task's sheet: a new entry of the history, so Back closes it. */ +function openTask(path) { + history.pushState(null, "", taskHref(path)); + dispatchEvent(new PopStateEvent("popstate")); +} + +/** The sheet: the kit's `Sheet` (a dialog: it keeps the focus inside while it is open, gives it + * back to the card when it closes, and Escape closes it). The focus goes to the sheet's top at + * the opening, not into a text box: on a phone that would raise the keyboard over the task. */ +function TaskSheet({ path, state, columns, dimensions, move }) { + // the task last opened: the sheet keeps showing it while it slides away + const [last, setLast] = useState(path); + if (path && path !== last) setLast(path); + const top = useRef(null); + const task = last ? state.tasks.find((each) => each.path === last) : undefined; + return html` + <${Sheet} open=${Boolean(path)} onOpenChange=${(open) => !open && setView({ task: undefined })}> + <${SheetContent} className="task-sheet" initialFocus=${top}> + <div class="task-sheet-top" ref=${top} tabindex="-1"> + <${SheetTitle} className="task-sheet-kind">Task<//> + <${SheetDescription} className="task-sheet-path">${last}<//> + </div> + ${ + task + ? html`<${TaskBody} + key=${task.path} + task=${task} + columns=${columns} + dimensions=${dimensions} + save=${state.save} + move=${move} + />` + : html` + <p class="tasks-note" role=${state.loaded ? "alert" : undefined}> + ${state.loaded ? html`There is no task at <code>${last}</code>.` : "Reading the tasks…"} + </p> + ` + } + <//> + <//> + `; +} + +/** One open task: its head (the title and the properties), its saving line, and its text. */ +function TaskBody({ task, columns, dimensions, save, move }) { + // A DOC'S SESSION IS OF ONE SESSION OF THE PAGE'S ITX: its context and its subscriptions end + // with that socket, and the kit's "Try again" syncs through the context it has. A publish of the + // mind, or a deploy, cuts the socket for a few seconds. So the sheet makes a new DocSession at + // each new session of the page (`epoch`), which opens the doc again by itself. WHAT THAT COSTS: + // keys typed after the cut and before the new session is live were never sent, and are lost + // (the editor is read-only while it opens, so the loss is the cut's own second or two). + // `text` is what the editor shows until it is live: the file as the board has it at that moment. + const { epoch } = useSyncExternalStore(pageSession.subscribe, pageSession.get, pageSession.get); + const [opened, setOpened] = useState({ epoch, text: task.source }); + if (opened.epoch !== epoch) setOpened({ epoch, text: task.source }); + const [editor, setEditor] = useState(null); + const [attempt, setAttempt] = useState(0); + useEffect(() => { + let current = true; + editorOf().then( + (kit) => current && setEditor({ kit }), + (error) => current && setEditor({ error: wordsOf(error) }), + ); + return () => { + current = false; + }; + }, [attempt]); + const session = useMemo( + () => + editor?.kit + ? new editor.kit.DocSession({ + itx, + repo: REPO, + path: task.path, + kind: "markdown", + text: opened.text, + user: editor.kit.user, + facetSpec: editor.kit.facetSpec, + commentOnly: false, + }) + : null, + [editor, task.path, opened], + ); + return html` + <div class="task-sheet-body"> + <${TaskHead} task=${task} columns=${columns} dimensions=${dimensions} move=${move} /> + <p class="task-saving" role="status"> + <${PropertiesSaving} save=${save} /> + ${session && html`<${TextSaving} session=${session} />`} + </p> + ${ + session + ? html`<${TaskText} session=${session} DocEditor=${editor.kit.DocEditor} />` + : editor?.error + ? html` + <p class="tasks-note" role="alert"> + Couldn't open the editor: ${editor.error}${" "} + <button + class="tasks-link" + onClick=${() => { + setEditor(null); + setAttempt(attempt + 1); + }} + > + Try again + </button> + </p> + ` + : html`<p class="tasks-note">Opening the editor…</p>` + } + </div> + `; +} + +/** Where the title and the properties stand: they are the board's changes. */ +function PropertiesSaving({ save }) { + if (save.state === "waiting" || save.state === "saving") + return html`<span class="task-saving-part" data-pending + ><${Spinner} />Title and properties: saving…</span + >`; + if (save.state === "failed") + return html` + <span class="task-saving-part" data-failed title=${save.error}> + <${TriangleAlertIcon} />Title and properties: not saved + <${Button} variant="outline" size="xs" onClick=${() => board.commitNow()}>Try again<//> + </span> + `; + return html`<span class="task-saving-part"><${CheckIcon} />Title and properties: saved</span>`; +} + +/** Where the text stands: it is the doc's, saved by the doc's processor. */ +function TextSaving({ session }) { + const { status } = useSyncExternalStore(session.subscribe, session.state, session.state); + const words = { + opening: "Text: opening…", + editing: + "Text: typed, not in the repo yet (it is saved within a minute, or when the sheet closes)", + saved: "Text: saved", + "save-failed": `Text: not saved: ${status.message}`, + disconnected: "Text: the connection was lost; opening again…", + unavailable: "Text: cannot be edited now", + }[status.kind]; + const pending = status.kind === "editing" || status.kind === "opening"; + const failed = status.kind === "save-failed" || status.kind === "unavailable"; + return html` + <span + class="task-saving-part" + data-pending=${pending || undefined} + data-failed=${failed || undefined} + > + ${pending ? html`<${Spinner} />` : failed ? html`<${TriangleAlertIcon} />` : html`<${CheckIcon} />`}${words} + </span> + `; +} + +/** The task's text in the Docs editor. */ +function TaskText({ session, DocEditor }) { + // TAB IN THE EDITOR. The editor takes Tab for itself (it indents the line), as a text editor + // does. For a person who goes through the sheet with Tab that is a trap, and a harmful one: the + // cursor of an editor just entered is on the file's first line, which is the frontmatter's + // fence. So Tab passes THROUGH an editor that the keyboard brought the focus to, until the + // person types or clicks in it: from then on Tab is the editor's. The handlers are on the way + // down to the editor (capture), so the editor never sees a Tab that passes. + const passing = useRef(false); + const byPointer = useRef(false); + const inEditor = (event) => + event.target instanceof Element && Boolean(event.target.closest(".cm-content")); + return html` + <div + class="task-text" + onPointerDownCapture=${() => { + byPointer.current = true; + passing.current = false; + }} + onFocusCapture=${(event) => { + if (!inEditor(event)) return; + passing.current = !byPointer.current; + byPointer.current = false; + }} + onKeyDownCapture=${(event) => { + byPointer.current = false; + if (!inEditor(event)) return; + // not prevented: the browser moves the focus on, which is what Tab does elsewhere + if (event.key === "Tab" && passing.current) event.stopPropagation(); + else if (!["Shift", "Control", "Alt", "Meta"].includes(event.key)) passing.current = false; + }} + > + <${DocEditor} + session=${session} + listHref=${taskHref(null)} + listLabel="tasks" + editHref=${taskHref(session.options.path)} + onNavigate=${(href) => { + history.pushState(null, "", href); + dispatchEvent(new PopStateEvent("popstate")); + }} + unavailable=${html` + <p> + The task's text is edited through the Docs app's processors in this mind's config repo + (<code>apps/docs/processors/</code>). The title and the properties above do not need + them. + </p> + `} + /> + </div> + `; +} + +/** The task's title and properties, each edited in place. A change is a change of the board: on + * the card at once, and in the file with the next commit. */ +function TaskHead({ task, columns, dimensions, move }) { + // a dimension the file does not hold, asked for with "Add property": shown empty until it has a value + const [added, setAdded] = useState([]); + // the agent is the task's own business (who has it is written by that agent): shown, not edited + const editable = DIMENSIONS.filter((dimension) => dimension.id !== "agent"); + const asked = new Set(added); + const shown = editable.filter( + (dimension) => valuesOf(task, dimension.id).length > 0 || asked.has(dimension.id), + ); + const isShown = new Set(shown); + const hidden = editable.filter((dimension) => !isShown.has(dimension)); + return html` + <div class="task-head"> + <${TextBox} + className="task-title-box" + label="Title" + value=${task.title} + multiline + onCommit=${(title) => title && board.change({ kind: "title", path: task.path, title })} + /> + <dl class="task-properties"> + <div class="task-property"> + <dt><label htmlFor="task-status">Status</label></dt> + <dd> + <${NativeSelect} + id="task-status" + size="sm" + value=${task.column} + onChange=${(event) => + move( + task, + columns.find((column) => column.id === event.target.value), + )} + > + ${columns.map((column) => html`<${NativeSelectOption} key=${column.id} value=${column.id}>${column.label}<//>`)} + <//> + </dd> + </div> + ${shown.map( + (dimension) => html` + <div class="task-property" key=${dimension.id}> + <dt><label htmlFor=${`task-${dimension.id}`}>${dimension.one}</label></dt> + <dd> + <${Property} + id=${`task-${dimension.id}`} + dimension=${dimension} + values=${valuesOf(task, dimension.id)} + inUse=${ + dimensions + .find((each) => each.id === dimension.id) + ?.values.map(([value]) => value) ?? [] + } + set=${(value) => board.change({ kind: "field", path: task.path, field: dimension.id, value })} + /> + </dd> + </div> + `, + )} + ${ + task.agent && + html` + <div class="task-property"> + <dt>Agent</dt> + <dd class="task-property-text"> + ${ + agentHref(task.agent) + ? html`<a + class="task-agent-link" + href=${agentHref(task.agent)} + target="_blank" + rel="noreferrer" + title="Opens the agent's chat in the Dash" + >${task.agent}</a + >` + : task.agent + } + </dd> + </div> + ` + } + </dl> + ${ + hidden.length > 0 && + html` + <${DropdownMenu}> + <${DropdownMenuTrigger} + render=${html`<${Button} variant="ghost" size="xs" className="task-add-property" />`} + > + <${PlusIcon} data-icon="inline-start" />Add property + <//> + <${DropdownMenuContent} align="start" className="task-menu-popup"> + ${hidden.map( + (dimension) => html` + <${DropdownMenuItem} + key=${dimension.id} + onClick=${() => setAdded([...added, dimension.id])} + > + ${dimension.one} + <//> + `, + )} + <//> + <//> + ` + } + </div> + `; +} + +/** One dimension's control: a list of chips for tags, a choice for a dimension that has choices + * (priority, size), a text box for the rest (owner). */ +function Property({ id, dimension, values, inUse, set }) { + if (dimension.many) + return html`<${ChipsBox} + id=${id} + dimension=${dimension} + values=${values} + inUse=${inUse} + set=${set} + />`; + const value = values[0] || ""; + if (dimension.choices) { + // the dimension's own choices, then what the board's files use, then what this file says + const choices = [...new Set([...dimension.choices, ...inUse, ...values])]; + return html` + <${NativeSelect} + id=${id} + size="sm" + value=${value} + onChange=${(event) => set(event.target.value)} + > + <${NativeSelectOption} value="">None<//> + ${choices.map((choice) => html`<${NativeSelectOption} key=${choice} value=${choice}>${choice}<//>`)} + <//> + `; + } + return html`<${TextBox} + id=${id} + label=${dimension.one} + value=${value} + suggestions=${inUse} + placeholder="None" + onCommit=${set} + />`; +} + +/** A text edited in place: what is typed is the box's own until Enter or until the box is left, + * then it is handed over once (`onCommit`), so a title typed letter by letter is one change. + * Escape gives the typing up. While nobody types, the box shows the value as it is now. */ +function TextBox({ id, className, label, value, multiline, suggestions, placeholder, onCommit }) { + const [draft, setDraft] = useState(null); + const commit = () => { + if (draft === null) return; + const next = draft.replace(/\s+/g, " ").trim(); + setDraft(null); + if (next !== value) onCommit(next); + }; + const props = { + id, + className: `task-box ${className || ""}`, + "aria-label": label, + placeholder, + value: draft ?? value, + onChange: (event) => setDraft(event.target.value), + onBlur: commit, + onKeyDown: (event) => { + if (event.key === "Enter" && !event.shiftKey) { + event.preventDefault(); + event.currentTarget.blur(); + } else if (event.key === "Escape" && draft !== null) { + // the first Escape gives up what was typed; the sheet stays open + event.stopPropagation(); + setDraft(null); + } + }, + }; + if (multiline) return html`<textarea rows="1" ...${props}></textarea>`; + const list = suggestions?.length > 0 ? `${id}-list` : undefined; + return html` + <input type="text" list=${list} autocomplete="off" ...${props} /> + ${list && html`<datalist id=${list}>${suggestions.map((each) => html`<option key=${each} value=${each}></option>`)}</datalist>`} + `; +} + +/** A dimension with several values (tags): a chip for each, taken away by its cross, and a box + * that adds one at Enter or at a comma. Backspace in the empty box takes the last one away. */ +function ChipsBox({ id, dimension, values, inUse, set }) { + const [draft, setDraft] = useState(""); + const has = new Set(values); + const add = (text) => { + const more = text + .split(",") + .map((each) => each.trim()) + .filter((each) => each && !has.has(each)); + setDraft(""); + if (more.length > 0) set([...values, ...more]); + }; + const others = inUse.filter((each) => !has.has(each)); + return html` + <span class="task-chips"> + ${values.map( + (value) => html` + <span class="task-chip" key=${value}> + ${value} + <button + type="button" + aria-label=${`Remove ${dimension.one.toLowerCase()} ${value}`} + onClick=${() => set(values.filter((each) => each !== value))} + > + <${XIcon} /> + </button> + </span> + `, + )} + <input + id=${id} + class="task-box task-chips-box" + type="text" + list=${others.length > 0 ? `${id}-list` : undefined} + autocomplete="off" + placeholder=${values.length > 0 ? "Add…" : "None"} + aria-label=${`Add a ${dimension.one.toLowerCase()}`} + value=${draft} + onChange=${(event) => (event.target.value.endsWith(",") ? add(event.target.value) : setDraft(event.target.value))} + onBlur=${() => add(draft)} + onKeyDown=${(event) => { + if (event.key === "Enter") { + event.preventDefault(); + add(draft); + } else if (event.key === "Backspace" && !draft && values.length > 0) + set(values.slice(0, -1)); + else if (event.key === "Escape" && draft) { + event.stopPropagation(); + setDraft(""); + } + }} + /> + ${ + others.length > 0 && + html`<datalist id=${`${id}-list`}> + ${others.map((each) => html`<option key=${each} value=${each}></option>`)} + </datalist>` + } + </span> + `; +} + +render(html`<${App} />`, document.getElementById("root"));
A public/manifest.webmanifest
@@ -0,0 +1,17 @@ +{ + "name": "Tasks", + "short_name": "Tasks", + "description": "The mind's tasks as a board: the markdown files under tasks/ in its config repo.", + "start_url": "/", + "display": "browser", + "icons": [ + { + "src": "/icon.svg", + "sizes": "any", + "type": "image/svg+xml" + } + ], + "iterate": { + "for": "members" + } +}
A public/tasks-model.js
@@ -0,0 +1,879 @@ +// tasks-model.js — A TASK FILE AS A CARD, text in and text out: no network, no page. A task is a +// markdown file under tasks/ in a repo of the mind (the tasks repo, `TASKS_REPO` below, unless a +// board or a caller names another), and what the board knows of it is in the file's frontmatter +// and its first heading: +// +// --- +// status: in-progress the column (below); `state:` is read too, as the first board wrote it +// tags: [board, ui] also read: `labels:`, a block list, or words with commas between +// size: small shown on the card as it is written +// priority: high shown on the card as it is written +// owner: jonas also read: `assignee:` +// agent: /agents/... the agent that has the task, as the first board wrote it +// blocked-on: PR #12 what holds the task (one line); the board only reads it +// human-ask: what the task waits for from a person, one `- ` line for each ask +// - Sign the grant? (also read: one line after the key, or `[a, b]`). The board lists +// - Merge #12, or wait? them ("Needs a person", `needsAPerson`), and a person answers one +// there: the ask's line goes, and the ask with its answer is kept +// under `## Answers` in the text (`answerAsk`). These two keys are +// read whole: a `#` in them is a word, never a comment +// --- +// +// Tags, priority, size, owner and agent are the task's DIMENSIONS (below): the board shows one, +// filters by it and breaks into rows by it only when some file holds it. It invents none. +// +// # The title else `title:` in the frontmatter, else the file's name +// +// A file with no frontmatter is a task too, in Todo. The board changes ONE thing of a file at a +// time (its status, its title, one dimension, or one ask answered: `setStatus`, `setTitle`, +// `setField`, `answerAsk`) and leaves every other byte as it was, so a hand-written file stays +// hand-written, and a key the board does not know stays where it is. +// The page (app.js) and the test (../tasks-model.test.mjs) both load this file as it is. + +/** THE TASKS REPO, AND THE FOLDER OF A REPO WHOSE MARKDOWN FILES ARE ITS TASKS. The tasks repo is + * the one that the board shows and `itx.config.followTasks` follows when nobody names a repo. It + * lives in the mind alone (no GitHub mirror), and a commit to it publishes nothing. Any other + * repo of the mind is a board too, by its name: `tasks.<domain>/?repo=<name>` (app.js), and the + * change feed tells of every repo's tasks (../feed.js). Nothing else names these two. */ +export const TASKS_REPO = "/repos/tasks"; +export const TASKS_DIR = "tasks"; + +/** The board's columns, in order. A task whose status is none of these (or of their other + * spellings below) gets a column of its own after them. */ +export const COLUMNS = [ + { id: "backlog", label: "Backlog" }, + { id: "todo", label: "Todo" }, + { id: "in-progress", label: "In progress" }, + { id: "in-review", label: "In review" }, + { id: "done", label: "Done" }, +]; + +/** Other spellings of a column, as task files written by hand have them. They are read, never + * rewritten: a file changes only when a person moves its card. */ +const SPELLINGS = { + backlog: ["idea", "ideas", "later", "someday", "icebox"], + todo: ["to-do", "ready", "open", "next", "planned", "new"], + "in-progress": ["doing", "building", "wip", "started", "active", "in-flight"], + "in-review": [ + "review", + "needs-review", + "needs-decision", + "done-pending-merge", + "done-awaiting-review", + "awaiting-review", + ], + done: ["complete", "completed", "closed", "shipped", "merged", "finished"], +}; +const COLUMN_OF = new Map( + COLUMNS.flatMap(({ id }) => [id, ...(SPELLINGS[id] || [])].map((spelling) => [spelling, id])), +); + +/** The column a written status belongs to: one of COLUMNS' ids, or for a status of its own the + * status as a slug. None written is Todo. */ +export function columnOf(status) { + const slug = slugify(status || ""); + if (!slug) return "todo"; + return COLUMN_OF.get(slug) || slug; +} + +/** Lower-case words with hyphens between: "Done, awaiting review" is done-awaiting-review. One + * longer than `max` is cut at the end of a word, never inside one (unless its first word alone + * is too long). */ +export function slugify(text, max = 64) { + const slug = String(text) + .normalize("NFKD") + .replace(/[̀-ͯ]/g, "") + .toLowerCase() + .replace(/[^a-z0-9]+/g, "-") + .replace(/^-+|-+$/g, ""); + if (slug.length <= max) return slug; + const cut = slug.slice(0, max); + // the cut fell at a word's end when the next character is a hyphen + const whole = slug[max] === "-" ? cut : cut.slice(0, Math.max(cut.lastIndexOf("-"), 0)) || cut; + return whole.replace(/-+$/g, ""); +} + +/** Whether the board shows this file of the repo: markdown under the tasks folder. */ +export function isTaskPath(path) { + return path.startsWith(`${TASKS_DIR}/`) && /\.(?:md|markdown)$/i.test(path); +} + +// ── the frontmatter ── +// Read line by line, for the few keys the board shows: no YAML library, so nothing to load and +// nothing that can rewrite a file's other lines. A key is a line that starts at the left edge. + +const FRONTMATTER = /^---[ \t]*\r?\n(?:([\s\S]*?)\r?\n)?---[ \t]*(?:\r?\n|$)/; + +/** The file's frontmatter: its lines, where the body begins, and the file's line ending. */ +function frontmatterOf(source) { + const eol = /\r\n/.test(source) ? "\r\n" : "\n"; + const match = FRONTMATTER.exec(source); + if (!match) return { exists: false, lines: [], bodyAt: 0, eol }; + return { + exists: true, + lines: match[1] === undefined || match[1] === "" ? [] : match[1].split(/\r?\n/), + bodyAt: match[0].length, + eol, + }; +} + +const keyOf = (line) => /^([A-Za-z][\w-]*)[ \t]*:(?:[ \t]|$)/.exec(line)?.[1]; + +/** A written value without its quotes, or its comment when it has no quotes. `whole` keeps what + * follows a `#`: in a line that a person reads, "#12" is a word. */ +function scalar(text, whole = false) { + const value = text.trim(); + const quoted = /^(["'])([\s\S]*)\1$/.exec(value); + if (quoted) return quoted[2]; + return whole ? value : value.replace(/\s+#.*$/, "").trim(); +} + +/** The items of an inline list: split at each comma that is outside quotes, so `["a, b", c]` is two. */ +function itemsOf(text) { + const items = [""]; + let quote = null; + for (const char of text) { + if (char === "," && !quote) items.push(""); + else items[items.length - 1] += char; + if (quote) quote = char === quote ? null : quote; + // a quote opens an item only as its first character: the one in `it's` is a letter + else if ((char === `"` || char === "'") && items.at(-1).trim() === char) quote = char; + } + return items; +} + +/** One key's value: a string, or a list for `[a, b]` and for `- a` lines under the key. Undefined + * when the frontmatter has no such key. `whole`: no part of the value is a comment (`scalar`). */ +function valueOf(lines, key, whole = false) { + const at = lines.findIndex((line) => keyOf(line) === key); + if (at < 0) return undefined; + const rest = lines[at].slice(lines[at].indexOf(":") + 1).trim(); + const inline = /^\[([\s\S]*)\]$/.exec(rest); + if (inline) + return itemsOf(inline[1]) + .map((item) => scalar(item, whole)) + .filter(Boolean); + if (rest) return scalar(rest, whole); + const items = []; + for (const line of lines.slice(at + 1)) { + const item = /^\s*-\s+(.*)$/.exec(line); + if (!item) break; + items.push(scalar(item[1], whole)); + } + return items.length > 0 ? items.filter(Boolean) : ""; +} + +const listOf = (value) => + value === undefined + ? [] + : (Array.isArray(value) ? value : String(value).split(",")) + .map((each) => each.trim()) + .filter(Boolean); +const textOf = (value) => (Array.isArray(value) ? value.join(", ") : value || ""); + +/** The first `# ` heading outside the frontmatter and outside a code fence: its words, and which + * line of `body` it is. */ +function headingIn(body) { + let fenced = false; + const lines = body.split(/\r?\n/); + for (let at = 0; at < lines.length; at += 1) { + if (/^\s*(```|~~~)/.test(lines[at])) fenced = !fenced; + if (fenced) continue; + const heading = /^#\s+(.+?)\s*#*\s*$/.exec(lines[at]); + if (heading) return { title: heading[1].trim(), at }; + } +} + +/** The file's name as a title: "2026-11-19-board-filters.md" is "Board filters". */ +function titleOfPath(path) { + const name = path + .split("/") + .at(-1) + .replace(/\.(?:md|markdown)$/i, ""); + const words = + name + .replace(/^\d{4}-\d{2}-\d{2}-/, "") + .replace(/[-_]+/g, " ") + .trim() || name; + return words.charAt(0).toUpperCase() + words.slice(1); +} + +/** One task file as the board's card. `path` is its path in the repo and its identity. */ +export function parseTask(path, source) { + const { lines, bodyAt } = frontmatterOf(source); + const status = textOf(valueOf(lines, "status") ?? valueOf(lines, "state")); + const folder = path.split("/").slice(1, -1).join("/"); + return { + path, + title: + textOf(valueOf(lines, "title")) || + headingIn(source.slice(bodyAt))?.title || + titleOfPath(path), + /** as the file writes it; "" when it writes none */ + status, + column: columnOf(status), + tags: [...new Set([...listOf(valueOf(lines, "tags")), ...listOf(valueOf(lines, "labels"))])], + priority: textOf(valueOf(lines, "priority")), + size: textOf(valueOf(lines, "size")), + owner: textOf(valueOf(lines, "owner") ?? valueOf(lines, "assignee")), + agent: textOf(valueOf(lines, "agent")), + /** the model and the effort that the task's agent was started with, when the card says so */ + model: textOf(valueOf(lines, "model")), + effort: textOf(valueOf(lines, "effort")), + /** what holds the task, as one line; "" when the file says nothing */ + blockedOn: textOf(valueOf(lines, "blocked-on", true) ?? valueOf(lines, "blocked_on", true)), + /** paths of tasks that this task depends on (`depends-on:` / `depends_on:`) */ + dependsOn: [ + ...new Set([ + ...listOf(valueOf(lines, "depends-on")), + ...listOf(valueOf(lines, "depends_on")), + ]), + ], + /** what it waits for from a person, each item whole (a comma inside one line splits nothing) */ + humanAsk: [valueOf(lines, "human-ask", true) ?? valueOf(lines, "human_ask", true) ?? []] + .flat() + .filter(Boolean), + /** the folders between tasks/ and the file: "" for a task at the top */ + folder, + source, + }; +} + +/** A value as one line of YAML: quoted only when YAML would read it as something else. */ +function written(value) { + return /^[\w][\w .\-/]*$/.test(value) && !/\s$/.test(value) ? value : JSON.stringify(value); +} + +/** The file with its status changed and every other byte as it was. It writes the key the file + * has (`status:`, or the older `state:`), adds `status:` to a frontmatter without one, and gives + * a file with no frontmatter one of that single line. */ +export function setStatus(source, status) { + return setKey(source, ["status", "state"], written(status)); +} + +/** The file with ONE key of its frontmatter written and every other byte as it was. `keys` are the + * key's spellings: the one the file has is written, else the first is added at the frontmatter's + * end, and a file with no frontmatter gets one of that single line. `value` is the text after + * the colon; undefined takes the key's line away (and, when that leaves nothing between the + * fences, the frontmatter stays as two fences: the board never deletes a file's frontmatter). + * A value written as a block list (`- a` lines under the key) goes with its key's line. With `one`, a + * second spelling of the key in the same file goes too, so that the file says one thing. */ +function setKey(source, keys, value, { one = false } = {}) { + const { exists, lines, bodyAt, eol } = frontmatterOf(source); + if (!exists) + return value === undefined + ? source + : `---${eol}${keys[0]}: ${value}${eol}---${eol}${eol}${source}`; + const key = keys.find((each) => lines.some((has) => keyOf(has) === each)); + if (!key && value === undefined) return source; + const spellings = new Set(keys); + const next = []; + let dropping = false; + let done = false; + for (const line of lines) { + const at = keyOf(line); + // the lines of a block value belong to the key above them + if (dropping && !at && /^(?:\s+\S|\s*-\s|\s*$)/.test(line) && line.trim() !== "") continue; + dropping = false; + if (at && (at === key || (one && spellings.has(at)))) { + dropping = true; + if (at === key && !done && value !== undefined) next.push(`${key}: ${value}`); + done = true; + continue; + } + next.push(line); + } + if (!key) next.push(`${keys[0]}: ${value}`); + const between = next.length > 0 ? `${next.join(eol)}${eol}` : ""; + return `---${eol}${between}---${eol}${source.slice(bodyAt)}`; +} + +/** The file with one DIMENSION written (an id of `DIMENSIONS`) and every other byte as it was. + * `value` is a text, or for tags a list; an empty one takes the key's line away. A file's own + * spelling of the key stays (`labels:`, `assignee:`). An id that is no dimension changes + * nothing. */ +export function setField(source, id, value) { + const dimension = DIMENSIONS.find((each) => each.id === id); + if (!dimension) return source; + const values = [value] + .flat() + .map((each) => String(each ?? "").trim()) + .filter(Boolean); + if (values.length === 0) return setKey(source, dimension.keys, undefined, { one: true }); + const unique = [...new Set(values)]; + return setKey( + source, + dimension.keys, + dimension.many ? `[${unique.map(written).join(", ")}]` : written(unique[0]), + { one: true }, + ); +} + +/** The file with its TITLE changed and every other byte as it was: the `title:` of its + * frontmatter when it has one, else its first `# ` heading, else a new heading as the body's + * first line. The file's path does not change: a title renames nothing. An empty title changes + * nothing. */ +export function setTitle(source, title) { + const name = String(title).replace(/\s+/g, " ").trim(); + if (!name) return source; + const { lines, bodyAt, eol } = frontmatterOf(source); + if (lines.some((line) => keyOf(line) === "title")) + return setKey(source, ["title"], written(name)); + const head = source.slice(0, bodyAt); + const body = source.slice(bodyAt); + const heading = headingIn(body); + if (!heading) return insertHeading(head, body, name, eol); + const bodyLines = body.split(/(\r?\n)/); + // split keeps each line ending as its own element: line n is element 2n + bodyLines[heading.at * 2] = `# ${name}`; + return head + bodyLines.join(""); +} + +/** A body with a new first heading: after the blank lines that follow the frontmatter, and with a + * blank line before the text that was first. */ +function insertHeading(head, body, name, eol) { + const blank = /^(?:[ \t]*\r?\n)*/.exec(body)[0]; + const rest = body.slice(blank.length); + return `${head}${blank}# ${name}${eol}${rest ? eol + rest : ""}`; +} + +/** A new task's file: where it goes and what it holds. `taken` is the paths the repo has, so two + * tasks with one title get two files (`-2`, `-3`). */ +export function newTask({ title, status = "todo", folder = "", taken = [], fields = {} }) { + const name = title.trim() || "New task"; + const dir = [ + TASKS_DIR, + ...folder + .split("/") + .map((part) => slugify(part)) + .filter(Boolean), + ].join("/"); + const slug = slugify(name) || "task"; + const used = new Set(taken); + let path = `${dir}/${slug}.md`; + for (let n = 2; used.has(path); n += 1) path = `${dir}/${slug}-${n}.md`; + // a task made in a row or filtered view is born with its values: `fields` is + // { <dimension's id>: value | value[] }, written under the dimension's first key + const more = DIMENSIONS.flatMap(({ id, keys, many }) => { + const values = [ + ...new Set( + [fields[id]] + .flat() + .map((each) => String(each ?? "").trim()) + .filter(Boolean), + ), + ]; + if (values.length === 0) return []; + return [ + many + ? `${keys[0]}: [${values.map(written).join(", ")}]` + : `${keys[0]}: ${written(values[0])}`, + ]; + }); + return { + path, + content: [`---`, `status: ${written(status)}`, ...more, `---`, ``, `# ${name}`, ``].join("\n"), + }; +} + +// ── the dimensions ── + +/** WHAT A TASK CAN BE SHOWN, FILTERED AND BROKEN DOWN BY, besides its status (the columns) and its + * folder. Each is read from the frontmatter keys in `keys`, and a board has a dimension only when + * one of its files holds it (`dimensionsOf`): the board invents no field. `param` is its name in + * the page's URL, `many` says that a task can have several values, `choices` are the values the + * task sheet offers beside those in use, and `order` is the order of + * the values that have one (any other value comes after them, the most used first). */ +export const DIMENSIONS = [ + { + id: "tags", + param: "tag", + label: "Tags", + one: "Tag", + none: "No tag", + keys: ["tags", "labels"], + many: true, + }, + { + id: "priority", + param: "priority", + label: "Priority", + one: "Priority", + none: "No priority", + keys: ["priority"], + choices: ["urgent", "high", "medium", "low"], + order: [ + "urgent", + "critical", + "p0", + "highest", + "high", + "p1", + "medium", + "normal", + "p2", + "low", + "p3", + "lowest", + "p4", + ], + }, + { + id: "size", + param: "size", + label: "Size", + one: "Size", + none: "No size", + keys: ["size"], + choices: ["small", "medium", "large"], + order: ["xs", "tiny", "s", "small", "m", "medium", "l", "large", "xl", "huge"], + }, + { + id: "owner", + param: "owner", + label: "Owner", + one: "Owner", + none: "No owner", + keys: ["owner", "assignee"], + }, + { id: "agent", param: "agent", label: "Agent", one: "Agent", none: "No agent", keys: ["agent"] }, +]; + +/** WHERE AN AGENT'S CHAT IS IN THE DASH: the Dash's own address of the agent at this context path, + * with no origin ("/agents/agents/claude/x"), or null when the value is no context path (a card + * whose `agent:` is a plain name has no chat to open). The encoding is that of + * apps/dash/links.ts `dashLinks(apex).agent`, which is what `itx.config.dashLink` answers: a path + * that a URL's pathname can carry goes in the pathname, any other in `?contextPath=`. */ +export function agentChatPath(agent) { + const path = String(agent ?? "").trim(); + if (!path.startsWith("/") || path === "/") return null; + const sayable = path + .slice(1) + .split("/") + .every((part) => part && part !== "." && part !== ".."); + const href = sayable + ? `/agents${path + .split("/") + .map(encodeURIComponent) + .join("/") + .replace(/%(?:40|3A|24|26|2B|2C|3B|3D)/g, decodeURIComponent)}` + : `/agents?${new URLSearchParams({ contextPath: path }) + .toString() + .replaceAll("+", "%20") + .replace(/%(?:2F|40|3A|2C)/g, decodeURIComponent)}`; + // a last "." "," ":" is encoded, so that a chat or a mail that makes the address a link keeps it + return href.replace(/[.,:]$/, (last) => ({ ".": "%2E", ",": "%2C", ":": "%3A" })[last]); +} + +/** A task's values in one dimension: none, one, or for tags several. */ +export const valuesOf = (task, id) => [task[id]].flat().filter(Boolean); + +/** The dimensions that these tasks hold, each with its values and how many tasks have each + * (`values`: `[value, count]`, in the dimension's order) and how many tasks have none + * (`without`). */ +export function dimensionsOf(tasks) { + return DIMENSIONS.map((dimension) => { + const place = (value) => { + const at = (dimension.order || []).indexOf(String(value).toLowerCase()); + return at < 0 ? (dimension.order || []).length : at; + }; + const values = counts(tasks, (task) => valuesOf(task, dimension.id)); + values.sort(([a], [b]) => place(a) - place(b)); + return { + ...dimension, + values, + without: tasks.filter((task) => valuesOf(task, dimension.id).length === 0).length, + }; + }).filter((dimension) => dimension.values.length > 0); +} + +/** The board's rows by one dimension (an element of `dimensionsOf`): a row for each value, in the + * dimension's order, then a row for the tasks that have none. A row with no task is left out, + * and a task with two tags is in two rows. */ +export function rowsOf(tasks, dimension) { + const byValue = new Map(dimension.values.map(([value]) => [value, []])); + const without = []; + for (const task of tasks) { + const values = valuesOf(task, dimension.id); + if (values.length === 0) without.push(task); + for (const value of values) byValue.get(value)?.push(task); + } + const rows = [...byValue].map(([value, has]) => ({ value, label: value, tasks: has })); + return [...rows, { value: null, label: dimension.none, tasks: without }].filter( + (row) => row.tasks.length > 0, + ); +} + +// ── what waits for a person ── + +/** The tasks that are not done and ask a person something or say what holds them: those that ask + * first, then the blocked ones, each by title. The board never writes `blocked-on:`, and it + * writes `human-ask:` in one way: an ask that a person answers leaves it (`answerAsk`). */ +export function needsAPerson(tasks) { + return tasks + .filter((task) => task.column !== "done" && (task.humanAsk.length > 0 || task.blockedOn)) + .sort( + (a, b) => + Number(b.humanAsk.length > 0) - Number(a.humanAsk.length > 0) || + a.title.localeCompare(b.title, undefined, { numeric: true }) || + a.path.localeCompare(b.path), + ); +} + +const ASK_KEYS = ["human-ask", "human_ask"]; +/** The heading in a task's text under which the answers to its asks are kept. */ +export const ANSWERS_HEADING = "## Answers"; + +/** THE FILE WITH ONE ASK ANSWERED, and every other byte as it was. This is the whole format of an + * answer: + * - the ask's line leaves `human-ask:` in the frontmatter (the key too, when it was the last + * ask), so the frontmatter says what is still asked; + * - `- **<the ask>** <the answer> (<who>, <YYYY-MM-DD HH:MM> UTC)` becomes the last line under + * `## Answers` in the text, a heading that is made at the text's end when the file has none. + * `by` is who answered, as they are known (an address); `at` is an ISO time. The answer is kept + * as one line. An ask that the file does not have changes nothing. */ +export function answerAsk(source, { ask, answer, by, at }) { + const { exists, lines, bodyAt, eol } = frontmatterOf(source); + const keyAt = lines.findIndex((line) => ASK_KEYS.includes(keyOf(line))); + if (!exists || keyAt < 0) return source; + const front = [...lines]; + const rest = front[keyAt].slice(front[keyAt].indexOf(":") + 1).trim(); + const inline = /^\[([\s\S]*)\]$/.exec(rest); + if (inline) { + // `human-ask: [a, b]`: the line again without the item, each other item as it was written + const items = itemsOf(inline[1]) + .map((item) => item.trim()) + .filter(Boolean); + const found = items.findIndex((item) => scalar(item, true) === ask); + if (found < 0) return source; + items.splice(found, 1); + if (items.length > 0) front[keyAt] = `${keyOf(front[keyAt])}: [${items.join(", ")}]`; + else front.splice(keyAt, 1); + } else if (rest) { + // `human-ask: one ask` + if (scalar(rest, true) !== ask) return source; + front.splice(keyAt, 1); + } else { + // the `- ` lines under the key + let end = keyAt + 1; + while (end < front.length && /^\s*-\s+/.test(front[end])) end += 1; + const found = front + .slice(keyAt + 1, end) + .findIndex((line) => scalar(/^\s*-\s+(.*)$/.exec(line)[1], true) === ask); + if (found < 0) return source; + // the last ask takes its key with it + if (end - keyAt === 2) front.splice(keyAt, 2); + else front.splice(keyAt + 1 + found, 1); + } + const said = String(answer ?? "") + .replace(/\s+/g, " ") + .trim(); + const when = `${String(at).slice(0, 10)} ${String(at).slice(11, 16)} UTC`; + const line = `- **${ask}** ${said ? `${said} ` : ""}(${by}, ${when})`; + const between = front.length > 0 ? `${front.join(eol)}${eol}` : ""; + return `---${eol}${between}---${eol}${withLineUnder(source.slice(bodyAt), ANSWERS_HEADING, line, eol)}`; +} + +/** A task's text with one more line under a `## ` heading (`heading`, with its marks): after that + * section's last line, or under a new heading at the text's end. A heading inside a code fence is + * no heading. */ +function withLineUnder(body, heading, line, eol) { + const lines = body.split(/\r?\n/); + const words = heading.replace(/^#+\s*/, ""); + let fenced = false; + let found = -1; + let end = lines.length; + for (let at = 0; at < lines.length; at += 1) { + if (/^\s*(```|~~~)/.test(lines[at])) fenced = !fenced; + if (fenced) continue; + if (found < 0) { + if (/^##\s/.test(lines[at]) && lines[at].replace(/^##\s+/, "").trim() === words) found = at; + } else if (/^#{1,6}\s/.test(lines[at])) { + end = at; + break; + } + } + if (found < 0) { + const text = body.replace(/\s*$/, ""); + return `${text}${text ? eol + eol : ""}${heading}${eol}${eol}${line}${eol}`; + } + // the section's last line that is not blank: the new line goes after it + let last = end - 1; + while (last > found && lines[last].trim() === "") last -= 1; + const after = lines.slice(last + 1); + const next = [...lines.slice(0, last + 1), ...(last === found ? [""] : []), line, ...after].join( + eol, + ); + // a text that ended with no line end gets one: the line is a whole line + return after.length > 0 ? next : `${next}${eol}`; +} + +/** A text as ONE line of a frontmatter value that the reader gives back as it is (`scalar` with + * `whole`): in quotes when its own first and last characters would be read as quotes, or as the + * brackets of a list. */ +function asWritten(text) { + if (/^\[[\s\S]*\]$/.test(text)) return `"${text}"`; + const quoted = /^(["'])[\s\S]*\1$/.exec(text); + return quoted ? (quoted[1] === '"' ? `'${text}'` : `"${text}"`) : text; +} + +/** THE FILE WITH ONE MORE ASK, and every other byte as it was: a `- ` line at the end of + * `human-ask:`. The key becomes a list of such lines when the file wrote it another way (one + * line, or `[a, b]`), is made at the frontmatter's end when the file has none, and a file with no + * frontmatter gets one. The ask is kept as one line. An ask that the file has already, or an + * empty one, changes nothing. */ +export function addAsk(source, ask) { + const said = String(ask ?? "") + .replace(/\s+/g, " ") + .trim(); + const { exists, lines, bodyAt, eol } = frontmatterOf(source); + const asked = [valueOf(lines, "human-ask", true) ?? valueOf(lines, "human_ask", true) ?? []] + .flat() + .filter(Boolean); + if (!said || asked.includes(said)) return source; + const item = ` - ${asWritten(said)}`; + if (!exists) return `---${eol}human-ask:${eol}${item}${eol}---${eol}${eol}${source}`; + const front = [...lines]; + const keyAt = front.findIndex((line) => ASK_KEYS.includes(keyOf(line))); + if (keyAt < 0) front.push("human-ask:", item); + else { + const key = keyOf(front[keyAt]); + const rest = front[keyAt].slice(front[keyAt].indexOf(":") + 1).trim(); + const inline = /^\[([\s\S]*)\]$/.exec(rest); + // what the key held on its own line, as items of a list: each as it was written + const held = inline + ? itemsOf(inline[1]) + .map((each) => each.trim()) + .filter(Boolean) + : rest + ? [rest] + : []; + let end = keyAt + 1; + while (end < front.length && /^\s*-\s+/.test(front[end])) end += 1; + front.splice(keyAt, 1, `${key}:`, ...held.map((each) => ` - ${each}`)); + front.splice(end + held.length, 0, item); + } + return `---${eol}${front.join(eol)}${eol}---${eol}${source.slice(bodyAt)}`; +} + +/** THE FILE WITH WHAT HOLDS THE TASK WRITTEN (`blocked-on:`, one line), or with the key taken + * away for an empty text; every other byte as it was. */ +export function setBlockedOn(source, text) { + const said = String(text ?? "") + .replace(/\s+/g, " ") + .trim(); + return setKey(source, ["blocked-on", "blocked_on"], said ? asWritten(said) : undefined, { + one: true, + }); +} + +/** THE FILE WITH ONE PLAIN KEY OF ITS FRONTMATTER WRITTEN (`model: claude-fable-5-2`), or taken + * away for an empty text; every other byte as it was. For a key that is no dimension of the + * board: the board keeps it and shows it nowhere. A key that is no plain word changes nothing. */ +export function setPlainKey(source, key, text) { + if (!/^[a-z][a-z0-9-]*$/.test(String(key))) return source; + const said = String(text ?? "") + .replace(/\s+/g, " ") + .trim(); + return setKey(source, [key], said ? written(said) : undefined); +} + +/** The heading in a task's text under which notes are kept. */ +export const LOG_HEADING = "## Log"; + +/** THE FILE WITH ONE MORE NOTE: `- <YYYY-MM-DD HH:MM> UTC, <who>: <the note>` as the last line + * under `## Log` in the text, a heading that is made at the text's end when the file has none. + * For a line of progress or of what was found; longer reasoning is written into the text itself. + * `at` is an ISO time. The note is kept as one line. An empty note changes nothing. */ +export function addNote(source, { note, by, at }) { + const said = String(note ?? "") + .replace(/\s+/g, " ") + .trim(); + if (!said) return source; + const { bodyAt, eol } = frontmatterOf(source); + const when = `${String(at).slice(0, 10)} ${String(at).slice(11, 16)} UTC`; + return ( + source.slice(0, bodyAt) + + withLineUnder(source.slice(bodyAt), LOG_HEADING, `- ${when}, ${by}: ${said}`, eol) + ); +} + +/** THE ANSWERS THAT A TASK'S TEXT KEEPS (`answerAsk` wrote them): each line under `## Answers` of + * the form `- **<ask>** <answer> (<who>, <YYYY-MM-DD HH:MM> UTC)`, oldest first, as + * `{ ask, answer, by, at }`. A line of another form is left out, and so is a heading inside a + * code fence. The change feed says with it what an ask was answered with, and the board as data + * (../board.js) lists them. */ +export function answersOf(source) { + const answers = []; + let fenced = false; + let inside = false; + for (const line of source.slice(frontmatterOf(source).bodyAt).split(/\r?\n/)) { + if (/^\s*(```|~~~)/.test(line)) fenced = !fenced; + if (fenced) continue; + if (/^#{1,6}\s/.test(line)) { + inside = /^##\s+Answers\s*$/.test(line); + continue; + } + const found = + inside && + /^- \*\*(.+?)\*\* (?:(.*) )?\(([^()]+), (\d{4}-\d{2}-\d{2} \d{2}:\d{2}) UTC\)$/.exec(line); + if (found) answers.push({ ask: found[1], answer: found[2] || "", by: found[3], at: found[4] }); + } + return answers; +} + +// ── the board ── + +/** Every task of a folder read (`{ path: text }`), by title. */ +export function tasksOf(files) { + return Object.entries(files) + .filter(([path, source]) => isTaskPath(path) && typeof source === "string") + .map(([path, source]) => parseTask(path, source)) + .sort( + (a, b) => + a.title.localeCompare(b.title, undefined, { numeric: true }) || + a.path.localeCompare(b.path), + ); +} + +/** The columns for these tasks: the five, then one for each status of its own, by name. The label + * of such a column is the status as the first file writes it. */ +export function columnsOf(tasks) { + const own = new Map(); + for (const task of tasks) + if (!COLUMNS.some((column) => column.id === task.column) && !own.has(task.column)) + own.set(task.column, task.status); + return [ + ...COLUMNS, + ...[...own] + .sort(([a], [b]) => a.localeCompare(b)) + .map(([id, label]) => ({ id, label, own: true })), + ]; +} + +/** The tasks a filter leaves: every word of `query` in the title, the path, the status or a value + * of a dimension; for each dimension that `where` names (`{ tags: ["ui"], size: ["large"] }`), + * one of its values; one of `statuses` (by column id, when given); and the folder or one beneath + * it. */ +export function filterTasks(tasks, { query = "", where = {}, folder = null, statuses = [] } = {}) { + const words = query.toLowerCase().split(/\s+/).filter(Boolean); + const named = DIMENSIONS.filter(({ id }) => where[id]?.length > 0); + const wantedColumns = statuses.length > 0 ? new Set(statuses.map(columnOf)) : null; + return tasks.filter((task) => { + if (wantedColumns && !wantedColumns.has(task.column)) return false; + // oxlint-disable-next-line iterate/simple-truthiness-check -- "" is the folder at the top of tasks/, null is no folder asked for + if (folder !== null && task.folder !== folder && !task.folder.startsWith(`${folder}/`)) + return false; + for (const { id } of named) + if (!valuesOf(task, id).some((value) => where[id].includes(value))) return false; + if (words.length === 0) return true; + const text = [ + task.title, + task.path, + task.status, + ...DIMENSIONS.flatMap(({ id }) => valuesOf(task, id)), + ] + .join("\n") + .toLowerCase(); + return words.every((word) => text.includes(word)); + }); +} + +/** How many tasks each value has, most first: `counts(tasks, (task) => task.tags)`. */ +export function counts(tasks, valuesOf) { + const count = new Map(); + for (const task of tasks) + for (const value of [valuesOf(task)].flat()) count.set(value, (count.get(value) || 0) + 1); + return [...count].sort(([a, n], [b, m]) => m - n || String(a).localeCompare(String(b))); +} + +// ── a change, and the files after it ── +// The page keeps what a person did as CHANGES, not as new files: a change is applied to the file +// as the repo has it at the moment of the commit, so a line somebody else wrote meanwhile stays. + +/** What each kind of change does to a file's text. The board makes the first four; an agent's + * calls (../cards.js, ../asks.js) make them all. */ +const CHANGES = { + status: (source, change) => setStatus(source, change.status), + title: (source, change) => setTitle(source, change.title), + field: (source, change) => setField(source, change.field, change.value), + answer: (source, change) => answerAsk(source, change), + ask: (source, change) => addAsk(source, change.ask), + blocked: (source, change) => setBlockedOn(source, change.blockedOn), + note: (source, change) => addNote(source, change), + key: (source, change) => setPlainKey(source, change.key, change.value), +}; + +/** `files` after `change`: `{ kind: "status", path, status }`, `{ kind: "title", path, title }`, + * `{ kind: "field", path, field, value }` (a dimension's id and its value), `{ kind: "answer", + * path, ask, answer, by, at }` (`answerAsk`), `{ kind: "ask", path, ask }` (`addAsk`), + * `{ kind: "blocked", path, blockedOn }` (`setBlockedOn`), `{ kind: "note", path, note, by, at }` + * (`addNote`), `{ kind: "key", path, key, value }` (`setPlainKey`) or `{ kind: "create", path, + * content }`. A change of a file that is gone changes nothing, and neither does a kind that is + * none of these. */ +export function applyChange(files, change) { + if (change.kind === "create") + return change.path in files ? files : { ...files, [change.path]: change.content }; + const source = files[change.path]; + if (typeof source !== "string" || !Object.hasOwn(CHANGES, change.kind)) return files; + const next = CHANGES[change.kind](source, change); + return next === source ? files : { ...files, [change.path]: next }; +} + +/** What a commit of `changes` writes over `files`: each changed path once, with its last content. + * Empty when the changes change nothing (a card moved and moved back). */ +export function commitOf(files, changes) { + const after = changes.reduce(applyChange, files); + return Object.keys(after) + .filter((path) => after[path] !== files[path]) + .map((path) => ({ path, content: after[path] })); +} + +const shortOf = (text) => (text.length > 80 ? `${text.slice(0, 79)}…` : text); + +/** The commit's message: what one change did, or how many there are with a line for each. A path + * whose status changed twice is named once, with where it ended; so is a title, and each + * dimension. */ +export function messageOf(changes) { + const last = new Map(); + for (const change of changes) { + if (change.kind === "create") last.set(change.path, `new ${change.path}`); + else if (change.kind === "title") + last.set(`${change.path}\0title`, `${change.path}: the title`); + else if (change.kind === "answer") + last.set( + `${change.path}\0answer\0${change.ask}`, + `${change.path}: answered "${shortOf(change.ask)}"`, + ); + else if (change.kind === "ask") + last.set( + `${change.path}\0ask\0${change.ask}`, + `${change.path}: asks "${shortOf(String(change.ask))}"`, + ); + else if (change.kind === "blocked") + last.set( + `${change.path}\0blocked`, + `${change.path}: ${change.blockedOn ? `blocked on ${shortOf(String(change.blockedOn))}` : "no longer blocked"}`, + ); + else if (change.kind === "note") last.set(`${change.path}\0note`, `${change.path}: a note`); + else if (change.kind === "key") + last.set( + `${change.path}\0key\0${change.key}`, + `${change.path}: ${change.value ? `${change.key} is ${shortOf(String(change.value))}` : `no ${change.key}`}`, + ); + else if (change.kind === "field") { + const value = [change.value].flat().filter(Boolean).join(", "); + last.set( + `${change.path}\0${change.field}`, + `${change.path}: ${value ? `${change.field} is ${value}` : `no ${change.field}`}`, + ); + } else + last.set( + change.path, + `${last.get(change.path)?.startsWith("new ") ? "new " : ""}${change.path} is ${change.status}`, + ); + } + const said = [...last.values()]; + if (said.length === 1) return `tasks: ${said[0]}`; + return [`tasks: ${said.length} changes`, "", ...said.map((line) => `- ${line}`)].join("\n"); +}
A tasks-model.test.mjs
@@ -0,0 +1,896 @@ +// tasks-model.test.mjs — the board's reading and writing of a task file (public/tasks-model.js). +// Run it with `node --test apps/tasks/`. +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { + addAsk, + agentChatPath, + addNote, + answerAsk, + answersOf, + applyChange, + columnOf, + columnsOf, + commitOf, + counts, + DIMENSIONS, + dimensionsOf, + filterTasks, + isTaskPath, + messageOf, + needsAPerson, + newTask, + parseTask, + rowsOf, + setBlockedOn, + setField, + setStatus, + setTitle, + slugify, + tasksOf, + valuesOf, +} from "./public/tasks-model.js"; + +test("a file with frontmatter is a card with its status, tags, size and owner", () => { + const task = parseTask( + "tasks/cloud/board-filters.md", + "---\nstatus: in-progress\nsize: large\ntags: [board, ui]\nowner: jonas\n---\n\n# Board filters\n\nText.\n", + ); + assert.equal(task.title, "Board filters"); + assert.equal(task.status, "in-progress"); + assert.equal(task.column, "in-progress"); + assert.deepEqual(task.tags, ["board", "ui"]); + assert.equal(task.size, "large"); + assert.equal(task.owner, "jonas"); + assert.equal(task.folder, "cloud"); +}); + +test("a file with no frontmatter is a task in Todo, titled by its heading or its name", () => { + assert.equal(parseTask("tasks/a.md", "# Ship it\n").column, "todo"); + assert.equal(parseTask("tasks/a.md", "# Ship it\n").title, "Ship it"); + assert.equal( + parseTask("tasks/2026-11-19-board-filters.md", "No heading.\n").title, + "Board filters", + ); + assert.equal(parseTask("tasks/a.md", "").folder, ""); +}); + +test("the title is the frontmatter's, before the heading; a heading in a code fence is no title", () => { + assert.equal( + parseTask("tasks/a.md", '---\ntitle: "From: the top"\n---\n# Heading\n').title, + "From: the top", + ); + assert.equal(parseTask("tasks/a.md", "```\n# not this\n```\n\n# This\n").title, "This"); +}); + +test("the older key `state:` and a block list of labels are read", () => { + const task = parseTask("tasks/a.md", "---\nstate: in-review\nlabels:\n - one\n - two\n---\n"); + assert.equal(task.column, "in-review"); + assert.deepEqual(task.tags, ["one", "two"]); +}); + +test("the spellings that hand-written task files use land in the five columns", () => { + const column = Object.fromEntries( + [ + "idea", + "later", + "ready", + "building", + "in review", + "needs-decision", + "done-pending-merge", + "done, awaiting review", + "complete", + "Done", + "", + ].map((status) => [status, columnOf(status)]), + ); + assert.deepEqual(column, { + idea: "backlog", + later: "backlog", + ready: "todo", + building: "in-progress", + "in review": "in-review", + "needs-decision": "in-review", + "done-pending-merge": "in-review", + "done, awaiting review": "in-review", + complete: "done", + Done: "done", + "": "todo", + }); +}); + +test("a status of its own gets a column of its own, after the five", () => { + const tasks = tasksOf({ + "tasks/a.md": "---\nstatus: blocked\n---\n# A\n", + "tasks/b.md": "---\nstatus: done\n---\n# B\n", + }); + assert.deepEqual( + columnsOf(tasks).map((column) => column.id), + ["backlog", "todo", "in-progress", "in-review", "done", "blocked"], + ); +}); + +test("a status change rewrites one line and leaves every other byte", () => { + const source = + "---\nsize: small\nstatus: todo \n# a comment line\ntags:\n - x\n---\n\n# T\n\n---\nnot frontmatter\n"; + assert.equal( + setStatus(source, "done"), + "---\nsize: small\nstatus: done\n# a comment line\ntags:\n - x\n---\n\n# T\n\n---\nnot frontmatter\n", + ); +}); + +test("a status change keeps the key the file has, and adds `status:` where there is none", () => { + assert.equal(setStatus("---\nstate: todo\n---\nBody\n", "done"), "---\nstate: done\n---\nBody\n"); + assert.equal( + setStatus("---\nsize: small\n---\nBody\n", "done"), + "---\nsize: small\nstatus: done\n---\nBody\n", + ); + assert.equal(setStatus("---\n---\nBody\n", "done"), "---\nstatus: done\n---\nBody\n"); + assert.equal( + setStatus("# Only a body\n", "in-progress"), + "---\nstatus: in-progress\n---\n\n# Only a body\n", + ); +}); + +test("a status change keeps Windows line endings, and quotes a status YAML would misread", () => { + assert.equal( + setStatus("---\r\nstatus: todo\r\n---\r\nBody\r\n", "done"), + "---\r\nstatus: done\r\n---\r\nBody\r\n", + ); + assert.equal( + parseTask("tasks/a.md", setStatus("# T\n", "waiting: on Misha")).status, + "waiting: on Misha", + ); +}); + +test("what was set is what is read", () => { + for (const status of ["backlog", "todo", "in-progress", "in-review", "done", "blocked"]) + assert.equal( + parseTask("tasks/a.md", setStatus("---\ntags: [a]\n---\n# T\n", status)).column, + status, + ); +}); + +test("a new task is a file under tasks/ named by its title, never over another", () => { + assert.deepEqual(newTask({ title: "Ship the Tour!" }), { + path: "tasks/ship-the-tour.md", + content: "---\nstatus: todo\n---\n\n# Ship the Tour!\n", + }); + const taken = ["tasks/cloud/ship.md", "tasks/cloud/ship-2.md"]; + assert.equal( + newTask({ title: "Ship", folder: "cloud", status: "done", taken }).path, + "tasks/cloud/ship-3.md", + ); + assert.equal(newTask({ title: " " }).path, "tasks/new-task.md"); + assert.equal(newTask({ title: "x", folder: "../../Etc" }).path, "tasks/etc/x.md"); +}); + +test("only markdown under tasks/ is a task", () => { + assert.equal(isTaskPath("tasks/a.md"), true); + assert.equal(isTaskPath("tasks/deep/er/a.markdown"), true); + assert.equal(isTaskPath("tasks/proof.cjs"), false); + assert.equal(isTaskPath("backlog/a.md"), false); + assert.equal(isTaskPath("apps/tasks/README.md"), false); +}); + +test("the filter is every word, any of the tags, and a folder with those beneath it", () => { + const tasks = tasksOf({ + "tasks/a.md": "---\ntags: [ui]\n---\n# Board filters\n", + "tasks/cloud/b.md": "---\ntags: [cloud]\nowner: misha\n---\n# Cloud arcs\n", + "tasks/cloud/designs/c.md": "# Wizard design\n", + }); + const paths = (filter) => filterTasks(tasks, filter).map((task) => task.path); + assert.deepEqual(paths({ query: "board FILT" }), ["tasks/a.md"]); + assert.deepEqual(paths({ query: "misha" }), ["tasks/cloud/b.md"]); + assert.deepEqual(paths({ where: { tags: ["ui", "cloud"] } }), ["tasks/a.md", "tasks/cloud/b.md"]); + assert.deepEqual(paths({ folder: "cloud" }), ["tasks/cloud/b.md", "tasks/cloud/designs/c.md"]); + assert.deepEqual(paths({ folder: "" }), ["tasks/a.md"]); + assert.deepEqual( + counts(tasks, (task) => task.tags), + [ + ["cloud", 1], + ["ui", 1], + ], + ); +}); + +const DIMENSIONED = { + "tasks/a.md": + "---\nstatus: todo\ntags: [ui, board]\nsize: large\npriority: high\nowner: jonas\n---\n# A\n", + "tasks/b.md": + "---\nstatus: done\nlabels: [ui]\nsize: small\nassignee: misha\nagent: /agents/tasks/b\n---\n# B\n", + "tasks/c.md": "---\nstatus: todo\nsize: large\npriority: urgent\nmood: fine\n---\n# C\n", + "tasks/deep/d.md": "# D\n", +}; + +test("a card has the dimensions its frontmatter holds, and no other", () => { + const [a, b, c, d] = tasksOf(DIMENSIONED); + assert.deepEqual( + [a, b].map((task) => [task.tags, task.priority, task.size, task.owner, task.agent]), + [ + [["ui", "board"], "high", "large", "jonas", ""], + [["ui"], "", "small", "misha", "/agents/tasks/b"], + ], + ); + assert.deepEqual(valuesOf(a, "tags"), ["ui", "board"]); + assert.deepEqual(valuesOf(c, "owner"), []); + assert.equal("mood" in c, false); + assert.deepEqual( + DIMENSIONS.flatMap(({ id }) => valuesOf(d, id)), + [], + ); +}); + +test("a board has a dimension only when a file holds it, with its values in order and their counts", () => { + const dimensions = dimensionsOf(tasksOf(DIMENSIONED)); + assert.deepEqual( + dimensions.map(({ id, values, without }) => [id, values, without]), + [ + [ + "tags", + [ + ["ui", 2], + ["board", 1], + ], + 2, + ], + [ + "priority", + [ + ["urgent", 1], + ["high", 1], + ], + 2, + ], + [ + "size", + [ + ["small", 1], + ["large", 2], + ], + 1, + ], + [ + "owner", + [ + ["jonas", 1], + ["misha", 1], + ], + 2, + ], + ["agent", [["/agents/tasks/b", 1]], 3], + ], + ); + // no file with a priority: the board has no priority + assert.deepEqual( + dimensionsOf( + tasksOf({ "tasks/a.md": "---\nsize: small\n---\n# A\n", "tasks/b.md": "# B\n" }), + ).map(({ id }) => id), + ["size"], + ); + assert.deepEqual(dimensionsOf(tasksOf({ "tasks/b.md": "# B\n" })), []); + // a value with no place in the order comes after those that have one + const sizes = dimensionsOf( + tasksOf({ "tasks/a.md": "---\nsize: epic\n---\n", "tasks/b.md": "---\nsize: Small\n---\n" }), + ); + assert.deepEqual( + sizes[0].values.map(([value]) => value), + ["Small", "epic"], + ); +}); + +test("the filter is one value of each dimension named", () => { + const tasks = tasksOf(DIMENSIONED); + const paths = (where) => filterTasks(tasks, { where }).map((task) => task.path); + assert.deepEqual(paths({ size: ["large"] }), ["tasks/a.md", "tasks/c.md"]); + assert.deepEqual(paths({ size: ["large"], priority: ["urgent"] }), ["tasks/c.md"]); + assert.deepEqual(paths({ size: ["large", "small"], tags: ["ui"] }), ["tasks/a.md", "tasks/b.md"]); + assert.deepEqual(paths({ owner: ["misha"] }), ["tasks/b.md"]); + assert.deepEqual(paths({ owner: [] }).length, 4); + // the words reach every dimension's values + assert.deepEqual( + filterTasks(tasks, { query: "urgent" }).map((task) => task.path), + ["tasks/c.md"], + ); + assert.deepEqual( + filterTasks(tasks, { query: "agents/tasks" }).map((task) => task.path), + ["tasks/b.md"], + ); +}); + +test("the rows by a dimension: one a value in order, then the tasks with none; a task with two tags is in two", () => { + const tasks = tasksOf(DIMENSIONED); + const rows = (id, of = tasks) => + rowsOf( + of, + dimensionsOf(tasks).find((each) => each.id === id), + ).map((row) => [row.value, row.label, row.tasks.map((task) => task.path)]); + assert.deepEqual(rows("size"), [ + ["small", "small", ["tasks/b.md"]], + ["large", "large", ["tasks/a.md", "tasks/c.md"]], + [null, "No size", ["tasks/deep/d.md"]], + ]); + assert.deepEqual(rows("tags"), [ + ["ui", "ui", ["tasks/a.md", "tasks/b.md"]], + ["board", "board", ["tasks/a.md"]], + [null, "No tag", ["tasks/c.md", "tasks/deep/d.md"]], + ]); + // a row with no task shown (a filter took them) is left out + assert.deepEqual(rows("size", filterTasks(tasks, { where: { owner: ["jonas"] } })), [ + ["large", "large", ["tasks/a.md"]], + ]); +}); + +test("a task made in a row is born with the row's value, and the board never writes a dimension else", () => { + assert.equal( + newTask({ title: "Big one", fields: { size: "large" } }).content, + "---\nstatus: todo\nsize: large\n---\n\n# Big one\n", + ); + assert.equal( + newTask({ title: "T", fields: { tags: "ui, really" } }).content, + '---\nstatus: todo\ntags: ["ui, really"]\n---\n\n# T\n', + ); + assert.equal( + parseTask("tasks/t.md", newTask({ title: "T", fields: { tags: "ui" } }).content).tags[0], + "ui", + ); + assert.equal( + newTask({ title: "T", fields: { mood: "fine" } }).content, + "---\nstatus: todo\n---\n\n# T\n", + ); + // a status change keeps every dimension's line, and a line the board does not know, byte for byte + const source = DIMENSIONED["tasks/c.md"]; + assert.equal(setStatus(source, "done"), source.replace("status: todo", "status: done")); +}); + +test("changes are applied to the files as they are at the commit, and a commit names each path once", () => { + const files = { "tasks/a.md": "---\nstatus: todo\nsize: small\n---\n# A\n" }; + const changes = [ + { kind: "status", path: "tasks/a.md", status: "in-progress" }, + { kind: "create", path: "tasks/b.md", content: "---\nstatus: todo\n---\n\n# B\n" }, + { kind: "status", path: "tasks/b.md", status: "done" }, + { kind: "status", path: "tasks/gone.md", status: "done" }, + ]; + assert.deepEqual(commitOf(files, changes), [ + { path: "tasks/a.md", content: "---\nstatus: in-progress\nsize: small\n---\n# A\n" }, + { path: "tasks/b.md", content: "---\nstatus: done\n---\n\n# B\n" }, + ]); + assert.equal( + messageOf(changes.slice(0, 3)), + "tasks: 2 changes\n\n- tasks/a.md is in-progress\n- new tasks/b.md is done", + ); + assert.equal(messageOf(changes.slice(0, 1)), "tasks: tasks/a.md is in-progress"); + // a card moved and moved back writes nothing + assert.deepEqual( + commitOf(files, [changes[0], { kind: "status", path: "tasks/a.md", status: "todo" }]), + [], + ); + // a file somebody else made first is not written over + assert.equal(applyChange({ "tasks/b.md": "theirs" }, changes[1])["tasks/b.md"], "theirs"); +}); + +// ── what the task sheet writes: a title, a dimension ── + +const WRITTEN = + "---\nstatus: todo\ntags: [ui, billing]\npriority: high\nmood: fine\nowner: jonas\n---\n\n# Billing page\n\nThe page a member pays on.\n"; + +test("a dimension is written into its own line, and every other byte stays", () => { + assert.equal( + setField(WRITTEN, "priority", "low"), + WRITTEN.replace("priority: high", "priority: low"), + ); + assert.equal( + setField(WRITTEN, "owner", "misha t"), + WRITTEN.replace("owner: jonas", "owner: misha t"), + ); + assert.equal( + setField(WRITTEN, "tags", ["ui", "cloud"]), + WRITTEN.replace("tags: [ui, billing]", "tags: [ui, cloud]"), + ); + // a dimension the file does not hold yet is added at the frontmatter's end + assert.equal( + setField(WRITTEN, "size", "large"), + WRITTEN.replace("owner: jonas\n", "owner: jonas\nsize: large\n"), + ); + // an empty value takes the line away, and nothing else + assert.equal(setField(WRITTEN, "priority", ""), WRITTEN.replace("priority: high\n", "")); + assert.equal(setField(WRITTEN, "tags", []), WRITTEN.replace("tags: [ui, billing]\n", "")); + assert.equal(setField(WRITTEN, "size", ""), WRITTEN); + // a key the board does not know is never written, and no id but a dimension's is + assert.equal(setField(WRITTEN, "mood", "bad"), WRITTEN); + assert.equal(setField(WRITTEN, "status", "done"), WRITTEN); + // what was written is what is read + assert.deepEqual(parseTask("tasks/a.md", setField(WRITTEN, "tags", ["a b", "c, d", "ui"])).tags, [ + "a b", + "c, d", + "ui", + ]); + assert.equal( + parseTask("tasks/a.md", setField(WRITTEN, "owner", "Ada: the first")).owner, + "Ada: the first", + ); + assert.deepEqual(parseTask("tasks/a.md", "---\ntags: [it's, other]\n---\n").tags, [ + "it's", + "other", + ]); +}); + +test("a dimension keeps the file's own spelling of its key, its line endings, and a file with no frontmatter gets one", () => { + assert.equal( + setField("---\nassignee: jonas\n---\n# T\n", "owner", "misha"), + "---\nassignee: misha\n---\n# T\n", + ); + assert.equal( + setField("---\nlabels: [a]\n---\n# T\n", "tags", ["a", "b"]), + "---\nlabels: [a, b]\n---\n# T\n", + ); + // a block list goes with its key, and the key after it stays + assert.equal( + setField("---\ntags:\n - a\n - b\nsize: small\n---\n# T\n", "tags", ["c"]), + "---\ntags: [c]\nsize: small\n---\n# T\n", + ); + // two spellings in one file become one line: the file says one thing + assert.equal( + setField("---\ntags: [a]\nlabels: [b]\nsize: small\n---\n", "tags", ["a", "b", "c"]), + "---\ntags: [a, b, c]\nsize: small\n---\n", + ); + assert.equal( + setField("---\r\nstatus: todo\r\n---\r\nBody\r\n", "size", "small"), + "---\r\nstatus: todo\r\nsize: small\r\n---\r\nBody\r\n", + ); + assert.equal(setField("# T\n", "size", "small"), "---\nsize: small\n---\n\n# T\n"); + assert.equal(setField("# T\n", "size", ""), "# T\n"); + // the last key taken away leaves the two fences: the board deletes no frontmatter + assert.equal(setField("---\nsize: small\n---\n# T\n", "size", ""), "---\n---\n# T\n"); + // a status change still leaves a second spelling of its key alone + assert.equal( + setStatus("---\nstatus: todo\nstate: old\n---\n", "done"), + "---\nstatus: done\nstate: old\n---\n", + ); +}); + +test("a title is written where the file keeps it, and renames nothing", () => { + // the first heading + assert.equal( + setTitle(WRITTEN, "Billing, the page"), + WRITTEN.replace("# Billing page", "# Billing, the page"), + ); + assert.equal(parseTask("tasks/billing-page.md", setTitle(WRITTEN, "New name")).title, "New name"); + assert.equal( + parseTask("tasks/billing-page.md", setTitle(WRITTEN, "New name")).path, + "tasks/billing-page.md", + ); + // `title:` in the frontmatter, when the file has it; the heading below it stays + assert.equal( + setTitle("---\ntitle: Old\n---\n# A heading\n", "New: one"), + '---\ntitle: "New: one"\n---\n# A heading\n', + ); + // a heading in a code fence is no title; the real one after it is + assert.equal( + setTitle("```\n# not this\n```\n# This\n", "That"), + "```\n# not this\n```\n# That\n", + ); + // no heading: a new one, as the body's first line + assert.equal( + setTitle("---\nstatus: todo\n---\n\nJust text.\n", "Named"), + "---\nstatus: todo\n---\n\n# Named\n\nJust text.\n", + ); + assert.equal(setTitle("Just text.\n", "Named"), "# Named\n\nJust text.\n"); + assert.equal(setTitle("", "Named"), "# Named\n"); + assert.equal(setTitle("---\nstatus: todo\n---\n", "Named"), "---\nstatus: todo\n---\n# Named\n"); + // line endings stay, and so does every line but the title's + assert.equal( + setTitle("---\r\nsize: s\r\n---\r\n\r\n# Old\r\n\r\nText\r\n", "New"), + "---\r\nsize: s\r\n---\r\n\r\n# New\r\n\r\nText\r\n", + ); + // new lines in a title are spaces, and an empty title changes nothing + assert.equal(setTitle("# Old\n", " Two\nlines "), "# Two lines\n"); + assert.equal(setTitle(WRITTEN, " "), WRITTEN); +}); + +test("a title and a dimension are changes like a status: applied to the file as it is at the commit", () => { + const files = { "tasks/a.md": "---\nstatus: todo\n---\n\n# A\n" }; + const changes = [ + { kind: "title", path: "tasks/a.md", title: "A, renamed" }, + { kind: "field", path: "tasks/a.md", field: "priority", value: "high" }, + { kind: "field", path: "tasks/a.md", field: "tags", value: ["ui"] }, + { kind: "status", path: "tasks/a.md", status: "done" }, + { kind: "field", path: "tasks/gone.md", field: "size", value: "small" }, + ]; + assert.deepEqual(commitOf(files, changes), [ + { + path: "tasks/a.md", + content: "---\nstatus: done\npriority: high\ntags: [ui]\n---\n\n# A, renamed\n", + }, + ]); + // somebody edited the text meanwhile: their line stays, ours are applied to their file + const theirs = { + "tasks/a.md": "---\nstatus: todo\nsize: large\n---\n\n# A\n\nTheir new paragraph.\n", + }; + assert.equal( + commitOf(theirs, changes)[0].content, + "---\nstatus: done\nsize: large\npriority: high\ntags: [ui]\n---\n\n# A, renamed\n\nTheir new paragraph.\n", + ); + assert.equal( + messageOf(changes.slice(0, 4)), + "tasks: 4 changes\n\n- tasks/a.md: the title\n- tasks/a.md: priority is high\n- tasks/a.md: tags is ui\n- tasks/a.md is done", + ); + assert.equal( + messageOf([{ kind: "field", path: "tasks/a.md", field: "size", value: "" }]), + "tasks: tasks/a.md: no size", + ); + // a property set and set back writes nothing + assert.deepEqual( + commitOf({ "tasks/a.md": WRITTEN }, [ + { kind: "field", path: "tasks/a.md", field: "priority", value: "low" }, + { kind: "field", path: "tasks/a.md", field: "priority", value: "high" }, + ]), + [], + ); +}); + +test("a long title's file name is cut at a word", () => { + const path = newTask({ + title: "The task sheet: a card opens in the board, with the Docs editor and comments", + }).path; + assert.equal(path, "tasks/the-task-sheet-a-card-opens-in-the-board-with-the-docs-editor.md"); + assert.equal(slugify("one two three", 9), "one-two"); + assert.equal(slugify("one two three", 7), "one-two"); + assert.equal(slugify("one two three", 8), "one-two"); + // a first word that is too long alone is cut where it must be + assert.equal(slugify("supercalifragilistic", 5), "super"); + assert.equal(slugify("short"), "short"); +}); + +test("blocked-on and human-ask are read whole, and only an open task that has one needs a person", () => { + const asks = parseTask( + "tasks/a.md", + "---\nstatus: todo\nhuman-ask: [sign the grant, read it]\nblocked-on: a review, then a deploy\n---\n# A\n", + ); + assert.deepEqual(asks.humanAsk, ["sign the grant", "read it"]); + assert.equal(asks.blockedOn, "a review, then a deploy"); + const oneLine = parseTask("tasks/b.md", "---\nhuman-ask: say yes, or no\n---\n# B\n"); + assert.deepEqual(oneLine.humanAsk, ["say yes, or no"]); + const block = parseTask( + "tasks/c.md", + "---\nblocked_on: CI\nhuman-ask:\n - one\n - two\n---\n# C\n", + ); + assert.deepEqual([block.blockedOn, block.humanAsk], ["CI", ["one", "two"]]); + const none = parseTask("tasks/d.md", "---\nstatus: todo\nhuman-ask:\n---\n# D\n"); + assert.deepEqual([none.blockedOn, none.humanAsk], ["", []]); + const done = parseTask("tasks/e.md", "---\nstatus: done\nhuman-ask: [late]\n---\n# E\n"); + const blocked = parseTask("tasks/f.md", "---\nblocked-on: CI\n---\n# Aa blocked\n"); + assert.deepEqual( + needsAPerson([none, done, blocked, oneLine, asks]).map((task) => task.title), + ["A", "B", "Aa blocked"], + ); +}); + +test("a # in blocked-on or human-ask is a word; after any other key it starts a comment", () => { + const task = parseTask( + "tasks/a.md", + '---\nstatus: todo # soon\nblocked-on: PR #12 review\nhuman-ask:\n - Merge #99, or wait?\n - "quoted # too"\n---\n# A\n', + ); + assert.equal(task.status, "todo"); + assert.equal(task.blockedOn, "PR #12 review"); + assert.deepEqual(task.humanAsk, ["Merge #99, or wait?", "quoted # too"]); + assert.deepEqual(parseTask("tasks/b.md", "---\nhuman-ask: [Sign #7?, read it]\n---\n").humanAsk, [ + "Sign #7?", + "read it", + ]); +}); + +const answered = { + answer: " Wait for\nthe deploy. ", + by: "misha@nustom.com", + at: "2026-11-20T14:50:31.000Z", +}; + +test("an answer takes the ask's line out of the frontmatter and keeps both under ## Answers", () => { + const file = + "---\nstatus: todo\nhuman-ask:\n - Merge #12 now, or wait?\n - Sign the grant?\nowner: jonas\n---\n\n# A\n\nText.\n"; + const one = answerAsk(file, { ask: "Merge #12 now, or wait?", ...answered }); + assert.equal( + one, + "---\nstatus: todo\nhuman-ask:\n - Sign the grant?\nowner: jonas\n---\n\n# A\n\nText.\n\n## Answers\n\n- **Merge #12 now, or wait?** Wait for the deploy. (misha@nustom.com, 2026-11-20 14:50 UTC)\n", + ); + // the last ask takes its key with it, and the second answer goes under the same heading + const two = answerAsk(one, { + ask: "Sign the grant?", + answer: "", + by: "jonas@nustom.com", + at: "2026-11-21T09:05:00.000Z", + }); + assert.equal( + two, + "---\nstatus: todo\nowner: jonas\n---\n\n# A\n\nText.\n\n## Answers\n\n- **Merge #12 now, or wait?** Wait for the deploy. (misha@nustom.com, 2026-11-20 14:50 UTC)\n- **Sign the grant?** (jonas@nustom.com, 2026-11-21 09:05 UTC)\n", + ); + assert.deepEqual( + [parseTask("tasks/a.md", one).humanAsk, parseTask("tasks/a.md", two).humanAsk], + [["Sign the grant?"], []], + ); + // an ask that the file does not have changes nothing + assert.equal(answerAsk(file, { ask: "Another ask?", ...answered }), file); + assert.equal(answerAsk("# No frontmatter\n", { ask: "x", ...answered }), "# No frontmatter\n"); +}); + +test("an answer finds an ask however the file writes it, and its heading wherever it is", () => { + const inline = answerAsk('---\nhuman-ask: [Sign #7?, "read it, all"]\n---\n# A', { + ask: "read it, all", + ...answered, + }); + assert.equal( + inline, + "---\nhuman-ask: [Sign #7?]\n---\n# A\n\n## Answers\n\n- **read it, all** Wait for the deploy. (misha@nustom.com, 2026-11-20 14:50 UTC)\n", + ); + const line = answerAsk("---\nhuman_ask: say yes, or no\n---\n", { + ask: "say yes, or no", + ...answered, + }); + assert.equal( + line, + "---\n---\n## Answers\n\n- **say yes, or no** Wait for the deploy. (misha@nustom.com, 2026-11-20 14:50 UTC)\n", + ); + // a heading with a section after it, and one inside a code fence that is no heading + const between = + "---\nhuman-ask: [x]\n---\n# A\n\n```\n## Answers\n```\n\n## Answers\n\n- **old** yes (a@x, 2026-11-19 10:00 UTC)\n\n## Later\n\nMore.\n"; + assert.equal( + answerAsk(between, { ask: "x", ...answered }), + "---\n---\n# A\n\n```\n## Answers\n```\n\n## Answers\n\n- **old** yes (a@x, 2026-11-19 10:00 UTC)\n- **x** Wait for the deploy. (misha@nustom.com, 2026-11-20 14:50 UTC)\n\n## Later\n\nMore.\n", + ); + // an empty section, and a file with Windows line ends + assert.equal( + answerAsk("---\nhuman-ask: [x]\n---\n## Answers\n", { ask: "x", ...answered }), + "---\n---\n## Answers\n\n- **x** Wait for the deploy. (misha@nustom.com, 2026-11-20 14:50 UTC)\n", + ); + assert.equal( + answerAsk("---\r\nhuman-ask: [x]\r\n---\r\n# A\r\n", { ask: "x", ...answered }), + "---\r\n---\r\n# A\r\n\r\n## Answers\r\n\r\n- **x** Wait for the deploy. (misha@nustom.com, 2026-11-20 14:50 UTC)\r\n", + ); +}); + +test("an answer is a change like any other: applied to the file as it is at the commit, and named in the message", () => { + const files = { "tasks/a.md": "---\nstatus: todo\nhuman-ask:\n - Sign the grant?\n---\n# A\n" }; + const change = { kind: "answer", path: "tasks/a.md", ask: "Sign the grant?", ...answered }; + const [written] = commitOf(files, [ + { kind: "status", path: "tasks/a.md", status: "in-progress" }, + change, + ]); + assert.equal( + written.content, + "---\nstatus: in-progress\n---\n# A\n\n## Answers\n\n- **Sign the grant?** Wait for the deploy. (misha@nustom.com, 2026-11-20 14:50 UTC)\n", + ); + assert.equal(messageOf([change]), 'tasks: tasks/a.md: answered "Sign the grant?"'); + // an ask that somebody else answered meanwhile is gone from the file: the change writes nothing + assert.deepEqual(commitOf({ "tasks/a.md": "---\nstatus: todo\n---\n# A\n" }, [change]), []); + assert.equal(applyChange({}, change)["tasks/a.md"], undefined); +}); + +test("the answers that a task's text keeps are read back as they were written", () => { + const file = + "---\nstatus: todo\nhuman-ask:\n - Merge #12 now, or wait?\n - Sign the grant?\n---\n# A\n"; + const one = answerAsk(file, { + ask: "Merge #12 now, or wait?", + answer: "Wait (until Monday).", + by: "misha@nustom.com", + at: "2026-11-20T14:50:31.000Z", + }); + const two = answerAsk(one, { + ask: "Sign the grant?", + answer: "", + by: "a test of the pilot", + at: "2026-11-21T09:05:00.000Z", + }); + assert.deepEqual(answersOf(two), [ + { + ask: "Merge #12 now, or wait?", + answer: "Wait (until Monday).", + by: "misha@nustom.com", + at: "2026-11-20 14:50", + }, + { ask: "Sign the grant?", answer: "", by: "a test of the pilot", at: "2026-11-21 09:05" }, + ]); + // only the lines of that form under that heading: not a list elsewhere, not one in a code fence + const other = + "# A\n\n- **bold** words (a@x, 2026-11-20 14:50 UTC)\n\n```\n## Answers\n- **x** y (a@x, 2026-11-20 14:50 UTC)\n```\n\n## Answers\n\nA line of prose.\n- **x** y (a@x, 2026-11-20 14:50 UTC)\n\n## Later\n\n- **z** no (a@x, 2026-11-20 14:50 UTC)\n"; + assert.deepEqual(answersOf(other), [ + { ask: "x", answer: "y", by: "a@x", at: "2026-11-20 14:50" }, + ]); + assert.deepEqual(answersOf(file), []); +}); + +const asksOf = (source) => parseTask("tasks/a.md", source).humanAsk; + +test("an ask is one more line under human-ask, however the file wrote the key, and is read back as it was", () => { + const plain = "---\nstatus: todo\n---\n# A\n"; + const one = addAsk(plain, " Merge #12 now,\n or wait? "); + assert.equal(one, "---\nstatus: todo\nhuman-ask:\n - Merge #12 now, or wait?\n---\n# A\n"); + // a second ask goes after the first, and a key in the middle keeps its place + const two = addAsk( + "---\nhuman-ask:\n - Merge #12 now, or wait?\nowner: jonas\n---\n# A\n", + "Sign the grant?", + ); + assert.equal( + two, + "---\nhuman-ask:\n - Merge #12 now, or wait?\n - Sign the grant?\nowner: jonas\n---\n# A\n", + ); + // one line after the key, and an inline list, become lines of a list with their items as written + assert.equal( + addAsk("---\nhuman_ask: say yes, or no\n---\n", "And why?"), + "---\nhuman_ask:\n - say yes, or no\n - And why?\n---\n", + ); + assert.equal( + addAsk('---\nhuman-ask: [Sign #7?, "read it, all"]\n---\n', "And why?"), + '---\nhuman-ask:\n - Sign #7?\n - "read it, all"\n - And why?\n---\n', + ); + assert.deepEqual( + asksOf(addAsk('---\nhuman-ask: [Sign #7?, "read it, all"]\n---\n', "And why?")), + ["Sign #7?", "read it, all", "And why?"], + ); + // a file with no frontmatter gets one; an ask that is there already, or an empty one, changes nothing + assert.equal(addAsk("# A\n", "Why?"), "---\nhuman-ask:\n - Why?\n---\n\n# A\n"); + assert.equal(addAsk(one, "Merge #12 now, or wait?"), one); + assert.equal(addAsk(plain, " "), plain); + // words that the reader would take for quotes or for a list come back as they were + for (const odd of [ + '"Ship it" or "wait"', + "'quoted'", + "[x] tick this", + "[all of it]", + "- a dash first", + "a # b", + ]) + assert.deepEqual(asksOf(addAsk(plain, odd)), [odd], odd); + // and an ask that was added can be answered + assert.deepEqual( + asksOf( + answerAsk(addAsk(plain, "[all of it]"), { + ask: "[all of it]", + answer: "yes", + by: "a@x", + at: "2026-11-20T14:50:00.000Z", + }), + ), + [], + ); +}); + +test("blocked-on is one line, set and taken away, and read back as it was", () => { + const plain = "---\nstatus: todo\n---\n# A\n"; + const blocked = setBlockedOn(plain, " PR #12\n review "); + assert.equal(blocked, "---\nstatus: todo\nblocked-on: PR #12 review\n---\n# A\n"); + assert.equal( + setBlockedOn(blocked, "the deploy"), + "---\nstatus: todo\nblocked-on: the deploy\n---\n# A\n", + ); + assert.equal(setBlockedOn(blocked, ""), plain); + assert.equal(setBlockedOn(plain, null), plain); + // the file's own spelling of the key stays + assert.equal( + setBlockedOn("---\nblocked_on: CI\n---\n", "a review"), + "---\nblocked_on: a review\n---\n", + ); + for (const odd of ["[CI] is red", "[all of it]", '"the deploy"', "'x'"]) + assert.equal(parseTask("tasks/a.md", setBlockedOn(plain, odd)).blockedOn, odd, odd); +}); + +test("a note is one line under ## Log, after the notes before it", () => { + const file = "---\nstatus: todo\n---\n\n# A\n\nText.\n"; + const at = "2026-11-20T15:40:31.000Z"; + const one = addNote(file, { + note: " Found the cause:\n the hint races. ", + by: "/agents/worker", + at, + }); + assert.equal( + one, + "---\nstatus: todo\n---\n\n# A\n\nText.\n\n## Log\n\n- 2026-11-20 15:40 UTC, /agents/worker: Found the cause: the hint races.\n", + ); + const two = addNote(one, { + note: "Fixed.", + by: "/agents/worker", + at: "2026-11-20T16:05:00.000Z", + }); + assert.equal(two, `${one}- 2026-11-20 16:05 UTC, /agents/worker: Fixed.\n`); + assert.equal(addNote(file, { note: " ", by: "x", at }), file); + // the log and the answers are two sections: each line goes under its own heading, wherever that is + const answered = answerAsk(addAsk(two, "Ship it?"), { + ask: "Ship it?", + answer: "Yes.", + by: "a@x", + at, + }); + const noted = addNote(answered, { + note: "Shipped.", + by: "/agents/worker", + at: "2026-11-20T16:30:00.000Z", + }); + assert.equal( + noted, + "---\nstatus: todo\n---\n\n# A\n\nText.\n\n## Log\n\n- 2026-11-20 15:40 UTC, /agents/worker: Found the cause: the hint races.\n- 2026-11-20 16:05 UTC, /agents/worker: Fixed.\n- 2026-11-20 16:30 UTC, /agents/worker: Shipped.\n\n## Answers\n\n- **Ship it?** Yes. (a@x, 2026-11-20 15:40 UTC)\n", + ); +}); + +test("an ask, what holds a task and a note are changes like the others, each named in the message", () => { + const files = { "tasks/a.md": "---\nstatus: todo\n---\n# A\n" }; + const changes = [ + { kind: "status", path: "tasks/a.md", status: "in-progress" }, + { kind: "blocked", path: "tasks/a.md", blockedOn: "PR #12" }, + { kind: "ask", path: "tasks/a.md", ask: "Ship it?" }, + { + kind: "note", + path: "tasks/a.md", + note: "Started.", + by: "/agents/worker", + at: "2026-11-20T15:40:31.000Z", + }, + ]; + const [written] = commitOf(files, changes); + assert.equal( + written.content, + "---\nstatus: in-progress\nblocked-on: PR #12\nhuman-ask:\n - Ship it?\n---\n# A\n\n## Log\n\n- 2026-11-20 15:40 UTC, /agents/worker: Started.\n", + ); + assert.equal( + messageOf(changes), + 'tasks: 4 changes\n\n- tasks/a.md is in-progress\n- tasks/a.md: blocked on PR #12\n- tasks/a.md: asks "Ship it?"\n- tasks/a.md: a note', + ); + assert.equal( + messageOf([{ kind: "blocked", path: "tasks/a.md", blockedOn: "" }]), + "tasks: tasks/a.md: no longer blocked", + ); + // a kind that the model does not know changes nothing + assert.deepEqual(commitOf(files, [{ kind: "explode", path: "tasks/a.md" }]), []); +}); + +test("an agent's chat in the Dash: the address that itx.config.dashLink answers, and none for a plain name", () => { + // each address is what the live mind's itx.config.dashLink({ view: "agent", contextPath }) answered on 20 Nov 2026 + assert.equal( + agentChatPath("/agents/claude/tasks-agent-chat-link-mwp6c8m4-852f95"), + "/agents/agents/claude/tasks-agent-chat-link-mwp6c8m4-852f95", + ); + assert.equal(agentChatPath("/agents/voice/a b:c."), "/agents/agents/voice/a%20b:c%2E"); + assert.equal(agentChatPath("/agents/é@x,y+z"), "/agents/agents/%C3%A9@x,y+z"); + assert.equal(agentChatPath("/agents//x"), "/agents?contextPath=/agents//x"); + // a card whose agent is no context path has no chat to open + for (const none of ["claude", "", undefined, null, "/", "https://evil.example/x"]) + assert.equal(agentChatPath(none), null); +}); + +test("filterTasks filters by statuses (normalized column ids)", () => { + const tasks = tasksOf({ + "tasks/a.md": "---\nstatus: in-progress\ntags: [onboarding]\n---\n\n# Active\n", + "tasks/b.md": "---\nstatus: todo\ntags: [onboarding]\n---\n\n# Next\n", + "tasks/c.md": "---\nstatus: done\ntags: [onboarding]\n---\n\n# Finished\n", + "tasks/d.md": "---\nstatus: backlog\ntags: [other]\n---\n\n# Later\n", + }); + assert.deepEqual( + filterTasks(tasks, { where: { tags: ["onboarding"] }, statuses: ["in-progress", "todo"] }).map( + (t) => t.path, + ), + ["tasks/a.md", "tasks/b.md"], + ); + assert.deepEqual( + filterTasks(tasks, { statuses: ["completed"] }).map((t) => t.path), + ["tasks/c.md"], + ); +}); + +test("newTask writes multiple values for a multi-value dimension like tags", () => { + const created = newTask({ + title: "Follow up with Andy", + status: "todo", + fields: { tags: ["onboarding", "first-sitting"], priority: "high" }, + }); + assert.equal(created.path, "tasks/follow-up-with-andy.md"); + assert.match(created.content, /^tags: \[onboarding, first-sitting\]$/m); + assert.match(created.content, /^priority: high$/m); +}); + +test("parseTask reads depends-on and depends_on frontmatter", () => { + const card = parseTask( + "tasks/onboarding-telemetry.md", + "---\nstatus: todo\ntags: [onboarding]\ndepends-on: [tasks/onboarding-website.md, tasks/onboarding-look.md]\n---\n\n# Telemetry\n", + ); + assert.deepEqual(card.dependsOn, ["tasks/onboarding-website.md", "tasks/onboarding-look.md"]); +});