Tasks as iterate.com runs it: the repo switcher at the top, the Docs editor in the sheet, who asked, and the calls behind the board
Jonas Templestein, 2026-11-27 14:40 UTC · 90c6edb846b7a7795b17f0b052691de752033260 · parent d7aeba1
19 files changed
- A README.md
- M app.ts
- A askers.js
- A asks.js
- A board.js
- A cards.js
- A feed.js
- M index.html
- M package.json
- M pnpm-lock.yaml
- M public/app.css
- M public/app.js
- M public/tasks-model.js
- A tests/askers.test.mjs
- A tests/asks.test.mjs
- A tests/board.test.mjs
- A tests/cards.test.mjs
- A tests/feed.test.mjs
- M tests/tasks-model.test.mjs
A README.md
@@ -0,0 +1,174 @@ +# tasks + +The Tasks app of a mind, on `tasks.<domain>` for members: a board over the markdown files of a +repo. This file says how an agent makes, moves, gives out, follows and answers a task, and how it +reads the board. The files: + +- `app.ts` serves the page. `config/worker.ts` mounts it: `tasksApp({ repo, icon })`. +- `public/app.js` is the page, and `public/tasks-model.js` says how a file is read as a card. + The switcher at the top of the sidebar chooses the repo. +- `cards.js`, `feed.js`, `asks.js`, `askers.js` and `board.js` are the calls below. The + mind's config gives each a method of its API (`api.ts` of `/repos/config`), and hands + `feed.js` every event (`worker.ts`). +- The task sheet edits a task's file with the Docs app's editor (`/repos/docs`). + +Check the repo with `pnpm install`, `pnpm typecheck` and `pnpm test`, with `docs`, `stdlib` and +`kernel` in the folders beside this one. + +## Where the tasks are + +- Each Markdown file under `todo/` of the mind's tasks repo is a card. `status:` in its + frontmatter is its column: `backlog`, `todo`, `in-progress`, `in-review`, `done`. The + folder is `todo`, not `tasks`: on a laptop the folder `tasks/` beside the other repos is this + app's own repo. +- The tasks repo is `/repos/task-board` (`TASKS_REPO` in `public/tasks-model.js`, and + `TASKS_REPO` in `worker.ts` of `/repos/config`): the board shows it and the calls below use + it when they name no repo. It holds the task files and nothing else, no code is loaded from it, + and a commit to it publishes nothing. +- Any repo of the mind is a board: `tasks.<domain>/?repo=<name>` shows the files under its + `todo/`, and the switcher at the top of the sidebar lists the repos. The calls below take + `repo: "<name>"`. +- For a trial, make a throwaway repo (`await itx.repos.create("/repos/<name>")`, then + `itx.repos.delete`), never a trial card on the real board. +- A card opens the task in a sheet, where a member edits its title, its properties and its text, + and comments on it. The text and the comments are the Docs app's doc of that file. +- A done task stays where it is: its status says that it is done. A file's path is the task's + identity, so do not rename one. + +## What a card holds + +A status is enough to start. The frontmatter MAY also hold `tags:`, `owner:` (the person who +asked), `agent:` (the path of the agent that has the task), `priority:`, `blocked-on:` (one line: +what holds it) and `human-ask:` (what it waits for from a person: one `- ` line for each ask). +Keep reasoning, research and follow-up in the Markdown text. `public/tasks-model.js` says what +the board reads. + +## An agent keeps a card with three calls + +Write no frontmatter by hand (`cards.js`): + +```ts +// a new card. `text`: the ask in the person's own words, and where it came from. `owner`: who asked +const { file, link } = await itx.config.taskOpen({ title, text, owner, tags }); +// one commit that moves a card. Name only what changes +await itx.config.taskUpdate({ + file, + status: "in-review", + blockedOn: "the review", + note: "Found the cause.", +}); +// an ask that is a choice brings its options and your recommendation ("Asks and answers") +await itx.config.taskUpdate({ + file, + ask: "Ship on Friday or on Monday?", + decision: { + options: [ + { name: "Friday", tradeoff: "Live two days sooner; nobody watches it over the weekend." }, + { name: "Monday", tradeoff: "Two days later; the team is there." }, + ], + recommend: "Monday", + why: "The change touches sign-in.", + }, +}); +// give a card to an agent that runs +await itx.config.taskAssign({ file, agent: "/agents/…" }); +``` + +- `taskUpdate`: `blockedOn: ""` takes the blocker away. `ask` is one more question for a person, + with `decision` or `noChoice` ("Asks and answers"). `note` is one line under `## Log`, with your + path and the time. It also takes `title`, `owner`, `agent`, `tags`. +- `taskAssign`: the card then names the agent and is in progress, and the agent gets ONE message + that makes the card its brief: where the card is and how to keep it true. `message: "…"` adds + your own words. The call refuses an agent that would not read the card: one that ended, and any + agent but an iterate agent that had no turn for 12 hours. +- From the MCP `run` tool or a member's script add `by: "<your agent path>"` to each call. A + commit through a person's sign-in is stamped as that person, and by this the change feed tells + the others that it was you. +- To change a task's text, commit the file: + `await itx.repos.get("/repos/task-board").commitFiles({ message, changes: [{ path: "todo/<name>.md", content }], parent })` + (`parent`: the tip you read). End `message` with a line `Via: <your agent path>`. +- Close out your own card: `done` with what is done and how you proved it. What is left of the + card's work keeps it open. A fault or a job that you found and that is no part of your card + gets a card of its own before you close. + +A mind adds its own rules to the brief, its own start of a new agent for a card and its own way +with a note by overriding `taskDeps` in the class of its `worker.ts` (`api.ts` of +`/repos/config`; `cards.js` lists the parts). + +## Asks and answers + +- A human ask belongs to its parent task: add it with `taskUpdate({ file, ask })`, never as a new + card. An ask is ONE plain sentence: who it is for, and the answer that you need ("Ada: delete + the 5 old sign-ins, yes or no?"). The name before the colon is whom the board asks. No id and + no offset in it: those belong in the card's text. +- An ask that is a choice brings its options and your recommendation. Before you ask, work the + options out: what each one costs and gives. Then add + `decision: { options: [{ name, tradeoff }, …at least two], recommend: "<one name>", why }` to the + call that adds the ask. "Yes" and "no" are two options, each with what follows from it. The + card keeps them under `## Decisions`, and the page shows them under the ask: a click on an + option writes it into the answer box. An ask that is no choice (a thing that only the person + can do or see) takes `noChoice: "<why>"`. An ask with neither is taken, and the call's answer + holds `warning`: read it. One call adds one ask with a decision. +- An ask whose answer another agent acts on names that agent. Never write an ask that tells a + person to go and write somewhere else: where a person answers makes no difference. Add + `tell: { agent: "/agents/…", words: "<the answer that you wait for>" }` to the call that adds + the ask (`words` may be left out). The person answers in the one box, which starts with those + words; a line above it says where the answer goes; and the page sends the answer to that agent + as the person's own message, beside the card's commit. Whether such a message releases a step + is that agent's own rule. An ask has a `decision` or a `tell`, not both. +- When a person answers your ask somewhere else (your chat, a call), record it at once with + `answerTask`: the ask then leaves the board, and nobody asks them twice. +- Which model recommended is never yours to write. The page reads it from your own log, at the + turn that asked (`itx.config.taskAskers`, `model`), and says "model unrecorded" when no event + says. So add each ask with `taskUpdate` from your own turn, never by a hand-made commit. +- The board's "Needs a person" (`tasks.<domain>/?needs=person`) lists every task that is not done + and has a `human-ask:`, in the order of what presses: a task's `priority:`, then the tasks + whose work is held, then the longest wait. A person answers an ask there, or in the task's + sheet, in the box beside it. A task that is held and asks nothing is not listed. +- Keep your asks true. When events overtake an ask, take it off, write it again, or record the + answer: + `await itx.config.taskUpdate({ file, withdraw: { ask: "<its beginning>", why: "…" } })`, + `await itx.config.taskUpdate({ file, reword: { ask: "<its beginning>", to: "<the new sentence>" } })`, + `await itx.config.answerTask({ file, ask, answer, by: "<the person's address>" })`. + An ask of three days or more is marked "May be outdated", and "Still needed?" sends you a + message from the person: check the ask then. +- Link what an ask names: write a thing that has an address as `[its name](https://…)`. Open + each address before you write it. NEVER put an + address that holds a secret into an ask (a token, a signed or one-time link, an OAuth link with + its `state`): every member and every agent reads an ask, and it stays in the repo's history. +- The format of an answer, whoever writes it: the ask's line leaves `human-ask:`, and + `- **<the ask>** <the answer> (<who>, <YYYY-MM-DD HH:MM> UTC)` is added under `## Answers` at + the end of the task's text. +- Who asked: "Needs a person" shows under each ask the agent that asked it, as a link to its chat + in the Dash, with "the message" in which it asked and "Chat with …", which opens that chat in a + sheet. `await itx.config.taskAskers()` answers the same as data: + `{ file, ask, agent, by, page, at, message, model, assignee }` for each open ask. It is read + from the change feed: the commit that added the ask, by its `Via:` line. +- Clear `blocked-on:` yourself when the thing that held the task is done. + +## Follow a task; never poll one + +```ts +await itx.config.followTasks({ file: "todo/<name>.md" }); // no `file`: every task +``` + +- Each commit that changes the file then reaches you as a message, with what changed and a small + diff. So a person's answer to your ask comes to you. +- From the MCP `run` tool or a member's script add `agent: "<your agent path>"`. +- `only: ["status", "blocked-on", "human-ask"]`: the changes that moved one of those fields and no + other, so that no note wakes you. The names: `added`, `deleted`, `status`, `title`, `owner`, + `agent`, `tags`, `blocked-on`, `human-ask`, `text`. +- You are not told of a commit that you made yourself: one of your own turn, or one whose message + ends with `Via: <your agent path>` (the three calls write that line). +- `itx.config.unfollowTasks(…)` ends it. `itx.config.taskFollowers()` lists who follows what. +- The events are `events.iterate.com/tasks/task-changed` on the repo's log, + `/task-files/<repo name>`. `feed.js` says what one holds. + +## The whole board in one call + +`await itx.config.taskBoard()` (`{ repo: "<name>" }` for another repo) answers every task as its +card, with the answers people gave to its asks, its last change and whether the agent it names +has work now (`agentSeen`) and follows the card (`agentFollows`). An agent that is given a card +follows it first, so a card in progress with `agentFollows: false` was not taken. Then the tasks +that need a person, the board's newest changes and who follows what. It does not hold the rest +of a task's text (read the file) or work that nobody wrote into a task.
M app.ts
@@ -3,7 +3,14 @@ // 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 +// (/repos/docs, processors/): /processors.json says where they are, in the Docs app's own words. +// +// The calls that an agent keeps a card with (`itx.config.taskOpen`, `taskUpdate`, `followTasks`, +// …) are the files beside this one (cards.js, feed.js, asks.js, askers.js, board.js): the mind's +// config gives each a method of its API (api.ts of /repos/config) and hands feed.js every event. import { type AppDescription, serveFiles, type IterateConfigEntrypoint } from "iterate/sdk"; +import { processorsAnswer } from "@repos/docs/app.ts"; import { openFile } from "@repos/stdlib/open-files.ts"; import theme from "@repos/stdlib/theme.css"; import index from "./index.html"; @@ -15,16 +22,31 @@ /** `repo`: THE REPO THE BOARD POINTS AT, a path of this mind (`/repos/<name>`). The page shows * the markdown files under `todo/` of it; `?repo=<name>` shows any other repo for one visit. * `icon`: the answer for the mind's icon, which every app serves as its own - * (open-files.ts of /repos/stdlib). */ -export function tasksApp({ repo, icon }: { repo: string; icon: () => Response }) { + * (open-files.ts of /repos/stdlib). + * `retiredAgents`: the paths of agents that the mind retired. "Needs a person" marks an ask of + * one as maybe outdated, and asks the task's agent about it in its place. */ +export function tasksApp({ + repo, + icon, + retiredAgents = [], +}: { + repo: string; + icon: () => Response; + retiredAgents?: string[]; +}) { return { /** The app's description and icon, for anyone: worker.ts asks this before its guard. */ open: (request: Request) => openFile(request, TASKS, icon), /** Every request on the app's host. worker.ts guards it, so a member alone gets here. */ - fetch(request: Request, host: Pick<IterateConfigEntrypoint, "auth">) { + 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 the Docs app 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 (new URL(request.url).pathname === "/board.json") - return Response.json({ repo }, { headers: { "cache-control": "no-store" } }); + if (url.pathname === "/board.json") + return Response.json({ repo, retiredAgents }, { 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);
A askers.js
@@ -0,0 +1,449 @@ +// askers.js — WHO ASKED: `itx.config.taskAskers({ repo? })` (api.ts) answers, for each ask that a +// task still has (a line of its `human-ask:`), the agent that added it. The board's "Needs a +// person" shows that agent beside the ask as a link to its chat in the Dash (public/app.js `Ask`), +// so that a person can ask it why before they answer. Misha asked for this on 20 Nov 2026 +// (todo/link-human-asks-to-the-agent-that-asked.md). +// +// WHERE THE ANSWER COMES FROM: THE CHANGE FEED, not git's author. Each commit to a repo of tasks +// is one `todo/task-changed` event for each file on the repo's feed log (feed.js), with the card +// before and after it and who made the commit: `via`, the commit message's own `Via:` line (the +// three card calls write it: cards.js), and `by`, the platform's stamp (an agent's path for an +// agent's own turn, a person's address for a commit through their sign-in). The newest event in +// which an ask is in the card after and not in the card before is the commit that asked it: what +// `git blame` of the ask's line would say, with no blame call (the repo has none) and with the +// agent named even when the commit was made through a person's sign-in. Git's author is not used: +// an agent has no address to be an author with, and the platform stamps a commit's person itself. +// +// WHAT IT CANNOT SAY. An ask that is older than the feed's log (the log of /repos/task-board begins on +// 20 Nov 2026), that a person wrote by hand, or whose commit named no agent has `agent: null`. +// `by` then still names the person, when the feed has the commit. The page shows the task's own +// agent for such an ask, and says that it is the task's agent and not the asker. +// +// THE MESSAGE THAT ASKED (Jonas, 25 Nov 2026: link "the exact ask where available"). A row's +// `message` is `{ path, offset, words }`: the event of the asker's own log in which it asked, which the +// Dash's raw view of a context opens (public/tasks-model.js `eventPath`). It is found in two ways +// (`locateAsk`): +// - an agent's own turn: the commit's fact on the repo's log names the event that caused it +// (`source.cause.parent`, "/agents/x@123"). That is exact. It is the turn that wrote the ask +// when the event holds the ask's words (`words: true`). When it does not, the ask was +// written by code that an event set off (a request to be let in), and the event is what led +// to the ask (`words: false`): the page says so, and does not call it the message; +// - a coding session through a person's sign-in (the MCP `run` tool): the commit names no +// event. The session's hooks land on the agent's log, and the tool call that made the commit +// holds the ask's words: the LAST event of the two minutes before the commit whose payload +// has the ask's beginning AND a call that writes an ask (`WRITES`). So an event that only +// quotes the ask (a person's prompt, a message about the card) is not taken, and an ask that +// the session wrote twice is the later call's. Nothing such: no message, and the page shows +// the conversation alone. A match of words is never called more than "the message". +// A lookup reads the asker's log (a search by time, then one page), so its answer is kept: one +// `todo/ask-located` event on the feed's log for each ask, read back with the changes. At most +// MAX_LOCATE asks are looked up in one call; the rest at the next. An ask with no message keeps +// `message: null`, and the page then links the asker's chat alone, as before. +// +// WHICH MODEL ASKED (Jonas, 25 Nov 2026: "it is mentioned which model has recommended this"). A +// row's `model` is `{ name, from }`, read from the asker's own log at the message that asked +// (`modelOf`), and from nothing else: +// - `from: "llm-request"`: the turn is an LLM request of an iterate agent, and the request's +// own event names the model that the platform called. That is the model of that turn; +// - `from: "session-start"`: the turn is a Claude Code session's, and the newest SessionStart +// hook before it names the model that the session started with. A person can change a +// session's model later, and no event says so: the page says "at its session's start". +// A card's `model:` key is what a worker was ASKED to run on, and an agent's own words about its +// model are a claim: neither is read. With no such event, `model` is null and the page says +// "model unrecorded". ACP and Codex sessions have no such event today. +// +// THE AGENT'S BLOCKING MESSAGE (Jonas, 25 Nov 2026: "showing the last agent message is far more +// useful now than showing some tiny summary question"; the design and his yes are on the card +// todo/link-tasks-asks-to-the-exact-message-in-dash.md). A row's `blocking` is `{ path, offset, +// text }`: the agent's own last words of the turn in which it asked, which the page shows under +// the question with no chat opened (`blockingOf`): +// - an iterate agent: the text of the LLM request's result at the message that asked, without +// its scripts; +// - a Claude Code session: `last_assistant_message` of the first Stop hook AFTER the message +// that asked. That event lands when the turn ends, so a read before then finds none yet +// and the next read looks again. A new prompt before any Stop, or a day with neither, ends +// the search: the ask then has no blocking message. +// The summary line in `human-ask:` stays the ask's identity: answers and decisions name an ask by +// its text. The text is a copy of at most BLOCKING_MAX characters, kept with the pointer on the +// feed's log. ACP and Codex sessions have no such event: `blocking` is null, and the page shows +// the summary alone. +import { boardPathOf, feedOf, repoOf, TASK_CHANGED } from "./feed.js"; +import { tasksOf, TASKS_DIR } from "./public/tasks-model.js"; + +/** How many offsets of the feed's log one read takes. */ +const PAGE = 200; + +/** The feed's event that keeps where an ask's message is: `{ file, ask, commitOid, path, offset }`, + * `offset: null` when a lookup found none. */ +export const ASK_LOCATED = "events.iterate.com/tasks/ask-located"; +/** How many asks one call looks up, how near the commit (ms) the message must be. "No message" is + * kept once its commit is 5 minutes old (a session's hook can land after its commit). */ +const MAX_LOCATE = 8; +const NEAR = 120_000; +/** A commit's time is the mind's, an event's is its own arrival: an event this much (ms) after the + * commit still counts as before it. */ +const SLACK = 2_000; +/** What an event of a session must hold beside the ask's words: a call that writes an ask. */ +const WRITES = /taskUpdate|taskOpen|commitFiles|human-ask/; +/** The rule that a kept answer was found by. A kept answer of an older rule is looked up again. */ +const RULE = 4; +/** How many pages back from the message a session's start is looked for. */ +const START_PAGES = 15; + +/** The most of a blocking message that is kept. A session's Stop is looked for 3 pages after the + * ask, and after a day with no Stop the search ends. */ +const BLOCKING_MAX = 4000; + +const cutOf = (text) => { + const said = String(text ?? "") + .replace(/<codemode>[\s\S]*?(?:<\/codemode>|$)/g, "") + .replace(/\n{3,}/g, "\n\n") + .trim(); + return said.length > BLOCKING_MAX + ? `${said.slice(0, BLOCKING_MAX).replace(/\s+\S*$/, "")} …` + : said; +}; + +/** THE AGENT'S BLOCKING MESSAGE for the ask whose turn is at `message` (`{ path, offset }`): + * `{ path, offset, text }`; null when there is none and none will come; undefined when it may + * still come (the turn has not ended). `askedAt`: when the ask was filed, an ISO time. */ +export async function blockingOf(itx, message, askedAt, now = Date.now()) { + if (!message || !Number.isInteger(message.offset)) return null; + const log = itx.cd(message.path); + const at = (await log.readEvents(message.offset - 1, 1)).events[0]; + if (at?.offset !== message.offset) return null; + if (endsWith(at, "/llm-request/settled")) { + const text = cutOf(at.payload?.result?.text); + return text ? { path: message.path, offset: at.offset, text } : null; + } + if (!endsWith(at, "/claude-code/hook-received")) return null; + for (let after = message.offset, pages = 0; pages < 3; pages += 1) { + const { events } = await log.readEvents(after, PAGE); + for (const event of events) { + if (!endsWith(event, "/claude-code/hook-received")) continue; + if (event.payload?.hook_event_name === "Stop") { + const text = cutOf(event.payload.last_assistant_message); + return text ? { path: message.path, offset: event.offset, text } : null; + } + // the person spoke again before the turn ended: the turn's last words never came + if (event.payload?.hook_event_name === "UserPromptSubmit") return null; + } + if (events.length < PAGE) break; + after = events.at(-1).offset; + } + return now - Date.parse(askedAt ?? "") > 86_400_000 ? null : undefined; +} + +const endsWith = (event, name) => typeof event?.type === "string" && event.type.endsWith(name); +const nameOf = (value) => + typeof value === "string" && value.trim() ? value.trim().slice(0, 80) : null; + +/** WHICH MODEL MADE THE TURN AT `message` (`{ path, offset }`): `{ name, from }`, or null when the + * asker's log has no event that says (the head of this file). */ +export async function modelOf(itx, message) { + if (!message || !Number.isInteger(message.offset)) return null; + const log = itx.cd(message.path); + const at = (await log.readEvents(message.offset - 1, 1)).events[0]; + if (at?.offset !== message.offset) return null; + // an iterate agent's turn: the settled request names its request, which names the model + if (endsWith(at, "/llm-request/settled") || endsWith(at, "/llm-request/requested")) { + const asked = endsWith(at, "/llm-request/requested") + ? at + : (await log.readEvents(at.payload?.llmRequestOffset - 1, 1)).events[0]; + const name = + endsWith(asked, "/llm-request/requested") && + (endsWith(at, "/llm-request/requested") || asked.offset === at.payload?.llmRequestOffset) + ? nameOf(asked.payload?.model) + : null; + return name ? { name, from: "llm-request" } : null; + } + // a Claude Code session's turn: the newest SessionStart hook before it + if (endsWith(at, "/claude-code/hook-received")) { + for ( + let end = message.offset, pages = 0; + end > 0 && pages < START_PAGES; + end -= PAGE, pages += 1 + ) { + const { events } = await log.readEvents(Math.max(0, end - PAGE), PAGE); + const start = events.findLast( + (event) => + event.offset <= message.offset && + endsWith(event, "/claude-code/hook-received") && + event.payload?.hook_event_name === "SessionStart" && + nameOf(event.payload?.model), + ); + if (start) return { name: nameOf(start.payload.model), from: "session-start" }; + } + } + return null; +} + +const isPath = (value) => typeof value === "string" && value.startsWith("/"); +const locatedKey = ({ file, ask, commitOid }) => `${file}\n${ask}\n${commitOid}`; + +/** The words of an ask that a search looks for: its first stretch (12 to 60 characters) with no + * quote and no backslash, which a script's text and a JSON payload hold as they are. */ +export function needleOf(ask) { + return /[^"'\\`’‘“”\n]{12,60}/.exec(String(ask ?? ""))?.[0].trim() || null; +} + +/** The first event of `log` at or after the time `from` (ms): a search by halves over the offsets, + * one event a read. It answers an offset to read from (`readEvents(offset - 1, …)`). */ +async function offsetAt(log, head, from) { + let low = 1; + let high = head; + while (low < high) { + const middle = (low + high) >> 1; + const event = (await log.readEvents(middle - 1, 1)).events[0]; + if (!event || Date.parse(event.createdAt) >= from) high = middle; + else low = Math.max(middle, event.offset) + 1; + } + return low; +} + +/** WHERE THE MESSAGE THAT ASKED IS: `{ path, offset }`, or null when nothing says. `row` is the + * ask's row of `askersOf` (`agent`, `at`, `commitOffset`), `repo` the tasks' repo. */ +export async function locateAsk(itx, repo, ask, row) { + if (!row.agent) return null; + // an agent's own turn: the commit's fact names its cause + if (Number.isInteger(row.commitOffset)) { + const fact = (await itx.cd(repo).readEvents(row.commitOffset - 1, 1)).events[0]; + const cause = + fact?.offset === row.commitOffset && /^(\/.+)@(\d+)$/.exec(fact.source?.cause?.parent ?? ""); + if (cause && cause[1] === row.agent) { + const offset = Number(cause[2]); + const event = (await itx.cd(cause[1]).readEvents(offset - 1, 1)).events[0]; + const needle = needleOf(ask); + const words = + Boolean(needle) && + event?.offset === offset && + JSON.stringify(event.payload ?? null).includes(needle); + return { path: cause[1], offset, words }; + } + } + // a session through a person's sign-in: the event of its log that holds the ask's words + const needle = needleOf(ask); + const at = Date.parse(row.at ?? ""); + if (!needle || !Number.isFinite(at)) return null; + const log = itx.cd(row.agent); + const head = (await log.readEvents(Number.MAX_SAFE_INTEGER, 1)).scannedThroughOffset ?? 0; + if (head === 0) return null; + const start = await offsetAt(log, head, at - NEAR); + const { events } = await log.readEvents(start - 1, PAGE); + const found = events.findLast((event) => { + const before = at + SLACK - Date.parse(event.createdAt); + if (!(before >= 0 && before <= NEAR + SLACK)) return false; + const text = JSON.stringify(event.payload ?? null); + return text.includes(needle) && WRITES.test(text); + }); + return found ? { path: row.agent, offset: found.offset, words: true } : null; +} + +/** WHO ADDED EACH OPEN ASK, from the feed's changes. `open`: `{ [file]: [ask, …] }`, the asks that + * the files have now. `changes`: the payloads of `todo/task-changed` events, NEWEST FIRST. + * `found` holds what earlier (newer) changes said already, and is added to: `{ [file]: { [ask]: + * { agent, by, page, at, commitOid } } }`. The newest change that added an ask wins, so an ask + * that was answered and asked again is its last asker's. `agent` is the commit's `Via:` line when + * that is a path, else the platform's `by` when that is one (an agent's own turn), else null. */ +export function askersOf(open, changes, found = {}) { + for (const change of changes) { + const asks = open[change.file]; + if (!asks) continue; + const before = change.before?.humanAsk || []; + for (const ask of change.after?.humanAsk || []) { + if (before.includes(ask) || !asks.includes(ask) || found[change.file]?.[ask]) continue; + (found[change.file] ??= {})[ask] = { + agent: isPath(change.via) ? change.via : isPath(change.by) ? change.by : null, + by: change.by ?? null, + page: change.page ?? null, + at: change.committedAt ?? null, + commitOid: change.commitOid ?? null, + commitOffset: change.commitOffset ?? null, + }; + } + } + return found; +} + +/** `itx.config.taskAskers({ repo? })`: who asked each ask that a task of the tasks repo (or of the + * repo `repo` names) still has. It answers `{ repo, asks, readFrom }`. `asks` has one row for each + * ask, in the board's order: `{ file, ask, agent, by, page, at, assignee }`. `agent`: the path of + * the agent that added the ask, or null when nothing says (an ask older than the feed, or a + * person's own). `by`, `page`: who made that commit and on which page, by the platform's stamp. + * `at`: when; null for an ask that the feed does not have. `message`: `{ path, offset, words }`, + * the event of the asker's log in which it asked (`words: false`: the event that led to the + * ask, which does not hold its words), or null (the head of this file). `model`: `{ name, + * from }`, the model that made that turn by the asker's own log, or null: unrecorded. + * `blocking`: `{ path, offset, text }`, the agent's own last words of that turn, or null. `assignee`: the + * task's own `agent:`, which is NOT the asker. `readFrom`: the offset of the feed's log that the read went back to. */ +export async function taskAskers(itx, input) { + if (input !== undefined && (input === null || typeof input !== "object" || Array.isArray(input))) + throw new Error("taskAskers takes { repo? }, or nothing for the tasks repo."); + const repo = await repoOf("taskAskers", itx, input?.repo); + const handle = itx.repos.get(repo); + const commitOid = await handle.tip(); + const under = commitOid ? await handle.modules({ commitOid, dir: TASKS_DIR }) : {}; + const tasks = tasksOf( + Object.fromEntries(Object.entries(under).map(([path, text]) => [`${TASKS_DIR}/${path}`, text])), + ).filter((task) => task.humanAsk.length > 0); + const open = Object.fromEntries(tasks.map((task) => [task.path, task.humanAsk])); + const found = {}; + const located = new Map(); + let log = null; + let readFrom = null; + // the feed's log, from its end back: a read of a log that does not exist would make it, so the + // catalog is asked first (as board.js does) + const feed = feedOf(repo); + const path = boardPathOf(feed); + if ( + tasks.length > 0 && + (await itx.contexts.list({ under: feed.root, limit: 200 })).some( + (context) => context.path === path, + ) + ) { + log = itx.cd(path); + const head = (await log.readEvents(Number.MAX_SAFE_INTEGER, 1)).scannedThroughOffset ?? 0; + // back from the log's end, 4,000 offsets at most, until every open ask has its asker + for (let end = head; end > 0 && end > head - 4000; end -= PAGE) { + if (Object.entries(open).every(([file, asks]) => asks.every((ask) => found[file]?.[ask]))) + break; + const start = Math.max(0, end - PAGE); + const { events } = await log.readEvents(start, PAGE); + const changes = events + .filter((event) => event.type === TASK_CHANGED && event.offset <= end) + .map((event) => event.payload) + .reverse(); + // newest first, so the newest word on an ask's message is the one kept + for (const event of events.toReversed()) + if ( + event.type === ASK_LOCATED && + event.payload.rule === RULE && + event.offset <= end && + !located.has(locatedKey(event.payload)) + ) + located.set( + locatedKey(event.payload), + Number.isInteger(event.payload.offset) + ? { + path: event.payload.path, + offset: event.payload.offset, + words: event.payload.words === true, + model: event.payload.model ?? null, + blocking: event.payload.blocking, + } + : null, + ); + askersOf(open, changes, found); + readFrom = start; + } + } + // the asks whose message nobody looked up yet: some of them now, and the answer kept on the feed + const unknown = Object.entries(found) + .flatMap(([file, asks]) => Object.entries(asks).map(([ask, row]) => ({ file, ask, row }))) + .filter( + ({ file, ask, row }) => + row.agent && + row.commitOid && + !located.has(locatedKey({ file, ask, commitOid: row.commitOid })), + ) + .slice(0, MAX_LOCATE); + await Promise.all( + unknown.map(async ({ file, ask, row }) => { + const key = locatedKey({ file, ask, commitOid: row.commitOid }); + // a lookup that fails says nothing, and is made again at the next call + const message = await locateAsk(itx, repo, ask, row).catch(() => undefined); + // oxlint-disable-next-line iterate/simple-truthiness-check -- undefined: the lookup failed, and is made again; null: it found no message, which is kept + if (message === undefined) return; + // the model of that turn, when it holds the ask's words: a failed read is "unrecorded" for now + if (message) + message.model = message.words ? await modelOf(itx, message).catch(() => null) : null; + located.set(key, message); + if (!message && !(Date.now() - Date.parse(row.at ?? "") > 300_000)) return; + // kept when it can be: a feed that takes no event costs the next call one more lookup + await Promise.resolve() + .then(() => + log.append({ + type: ASK_LOCATED, + idempotencyKey: `todo/ask-located:${RULE}:${key}`, + payload: { + rule: RULE, + file, + ask, + commitOid: row.commitOid, + path: message?.path ?? row.agent, + offset: message?.offset ?? null, + words: message?.words ?? null, + model: message?.model ?? null, + }, + }), + ) + .catch(() => {}); + }), + ); + // the blocking message of each located ask that has none yet: found when the turn has ended, + // and kept as one more event on the feed, which then is the newest word on that ask + const waiting = Object.entries(found) + .flatMap(([file, asks]) => + Object.entries(asks).map(([ask, row]) => ({ + file, + ask, + row, + key: locatedKey({ file, ask, commitOid: row.commitOid }), + })), + ) + .filter(({ key }) => located.get(key)?.words && located.get(key).blocking === undefined) + .slice(0, MAX_LOCATE); + await Promise.all( + waiting.map(async ({ file, ask, row, key }) => { + const where = located.get(key); + const blocking = await blockingOf(itx, where, row.at).catch(() => undefined); + // oxlint-disable-next-line iterate/simple-truthiness-check -- undefined: not known yet, and looked for again; null: there is none, which is kept + if (blocking === undefined) return; + where.blocking = blocking; + await Promise.resolve() + .then(() => + log.append({ + type: ASK_LOCATED, + idempotencyKey: `todo/ask-located:${RULE}:${key}:blocking`, + payload: { + rule: RULE, + file, + ask, + commitOid: row.commitOid, + path: where.path, + offset: where.offset, + words: where.words, + model: where.model ?? null, + blocking, + }, + }), + ) + .catch(() => {}); + }), + ); + const none = { agent: null, by: null, page: null, at: null }; + return { + repo, + asks: tasks.flatMap((task) => + task.humanAsk.map((ask) => { + const { agent, by, page, at, commitOid } = found[task.path]?.[ask] ?? none; + const where = + (commitOid && located.get(locatedKey({ file: task.path, ask, commitOid }))) || null; + const message = where && { path: where.path, offset: where.offset, words: where.words }; + return { + file: task.path, + ask, + agent, + by, + page, + at, + message, + model: where?.model ?? null, + blocking: where?.blocking ?? null, + assignee: task.agent || null, + }; + }), + ), + readFrom, + }; +}
A asks.js
@@ -0,0 +1,52 @@ +// asks.js — AN ASK OF A TASK, ANSWERED BY AN AGENT: `itx.config.answerTask(…)` (api.ts). A +// person answers an ask on the board ("Needs a person", public/app.js `Ask`). An agent uses this +// call for an answer that a person gave it somewhere else: in a chat, on a call, in Slack. Both +// write one format, public/tasks-model.js `answerAsk`: the ask's line leaves `human-ask:`, and +// `- **<the ask>** <the answer> (<who>, <when>)` is added under `## Answers` in the task's text. +// The commit is the news: the agent that follows the task hears of it (feed.js). +import { repoOf } from "./feed.js"; +import { answerAsk, isTaskPath, messageOf, parseTask } from "./public/tasks-model.js"; + +const asksOf = (file, source) => parseTask(file, source).humanAsk; + +/** `itx.config.answerTask({ file, ask, answer, by, repo? })`: one commit to the task file `file` + * of the tasks repo (or of the repo `repo` names). `ask` is the ask's whole text, as the file has + * it; `by` is the person who answered, as they are known (an address). It answers + * `{ repo, file, commitOid, stillAsked }`. An ask that the file does not have is refused, with + * the asks it does have. A commit that another one overtook is made again on the new tip, once. */ +export async function answerTask(itx, input, now = new Date()) { + if (!input || typeof input !== "object" || Array.isArray(input)) + throw new Error("answerTask takes { file, ask, answer, by, repo? }."); + const { file, ask, answer, by } = input; + for (const [name, value] of Object.entries({ file, ask, answer, by })) + if (typeof value !== "string" || !value.trim()) + throw new Error(`answerTask: ${name} is a text, and it is not empty.`); + if (!isTaskPath(file)) + throw new Error('answerTask: file is a task\'s path, like "todo/a-task.md".'); + const repo = await repoOf("answerTask", itx, input.repo); + const handle = itx.repos.get(repo); + const change = { kind: "answer", path: file, ask, answer, by, at: now.toISOString() }; + for (let attempt = 0; ; attempt += 1) { + const tip = await handle.tip(); + const source = tip ? await handle.readFile(file, { commitOid: tip }) : null; + if (source === null) throw new Error(`answerTask: ${repo} has no ${file}.`); + const next = answerAsk(source, change); + if (next === source) { + const asks = asksOf(file, source); + throw new Error( + `answerTask: ${file} does not ask that. It asks: ${asks.length > 0 ? asks.map((each) => JSON.stringify(each)).join(", ") : "nothing"}.`, + ); + } + try { + const { commitOid } = await handle.commitFiles({ + message: messageOf([change]), + changes: [{ path: file, content: next }], + parent: tip, + }); + return { repo, file, commitOid, stillAsked: asksOf(file, next) }; + } catch (error) { + // main moved between the read and the commit: read again, once + if (attempt > 0) throw error; + } + } +}
A board.js
@@ -0,0 +1,137 @@ +// board.js — THE BOARD AS DATA, for an agent: `itx.config.taskBoard({ repo? })` (api.ts). One +// call answers what the board shows a person and what the change feed remembers, so that an agent +// with no history (a manager that starts cold, a worker that takes work over) can say what runs, +// what is stuck and what waits for a person, and then follow what it cares about (feed.js). +// +// WHAT IT HOLDS. Every task of the repo as its card (public/tasks-model.js `parseTask`: file, +// title, status, column, tags, priority, size, owner, agent, blockedOn, humanAsk), each with the +// newest answers that people gave to its asks (`answersOf`: the decisions made), its last change +// as the feed has it (when, by whom, one line), and, for a task that names an agent, that agent's +// row in the mind's catalog (`agentSeen`: whether it has work now, and when it last had) and +// whether that agent follows the card (`agentFollows`: false means that the agent never took the +// card); the files that need a person, in the page's order; the newest changes of the whole +// board; and who follows what. +// +// WHAT IT DOES NOT HOLD, so say so when you answer from it: the rest of a task's text (read the +// file); what a task's agent is doing (read its log, or ask it); work that nobody wrote into a +// task (open pull requests, the merge and deploy queue); and a change older than the feed's +// reach (`lastChange: null`). +import { boardPathOf, feedOf, repoOf, TASK_CHANGED, taskFollowers } from "./feed.js"; +import { answersOf, needsAPerson, tasksOf, TASKS_DIR } from "./public/tasks-model.js"; + +/** How many of the board's newest changes are answered. */ +const RECENT_CHANGES = 30; +/** How many of a task's newest answers are answered, each cut to this many characters. */ +const ANSWERS = 5; +const ANSWER_CHARS = 500; +/** How far back the feed's log is read for the newest changes: its newest offsets. */ +const LOG_REACH = 400; +/** How many of the catalog's most active agents are asked for. */ +const CATALOG_ROWS = 500; + +/** The feed's log of `repo`, read from its end: the changes, newest first; and who follows. None + * for a repo whose log does not exist yet: a read of it would make it (the catalog says so, and + * the catalog's rows lag, so a log that was made a moment ago reads as none). */ +async function rememberedOf(itx, repo) { + const path = boardPathOf(feedOf(repo)); + const listed = await itx.contexts.list({ under: feedOf(repo).root, limit: 200 }); + if (!listed.some((context) => context.path === path)) return { changes: [], followers: [] }; + const log = itx.cd(path); + const head = (await log.readEvents(Number.MAX_SAFE_INTEGER, 1)).scannedThroughOffset ?? 0; + const { events } = await log.readEvents(Math.max(0, head - LOG_REACH), LOG_REACH); + const changes = events + .filter((event) => event.type === TASK_CHANGED) + .map(({ payload }) => ({ + at: payload.committedAt, + by: payload.by, + file: payload.file, + change: payload.change, + summary: payload.summary, + })) + .reverse(); + return { changes, followers: await taskFollowers(itx, { repo }) }; +} + +/** `itx.config.taskBoard({ repo? })`: the board of the tasks repo, or of the repo `repo` names, as + * data. It answers `{ repo, commitOid, board, tasks, needsAPerson, recentChanges, followers }`. */ +export async function taskBoard(itx, input) { + if (input !== undefined && (input === null || typeof input !== "object" || Array.isArray(input))) + throw new Error("taskBoard takes { repo? }, or nothing for the tasks repo."); + const repo = await repoOf("taskBoard", itx, input?.repo); + const handle = itx.repos.get(repo); + const commitOid = await handle.tip(); + const under = commitOid ? await handle.modules({ commitOid, dir: TASKS_DIR }) : {}; + const tasks = tasksOf( + Object.fromEntries(Object.entries(under).map(([path, text]) => [`${TASKS_DIR}/${path}`, text])), + ); + const { changes, followers } = await rememberedOf(itx, repo); + const lastChangeOf = (file) => { + const last = changes.find((change) => change.file === file); + return last ? { at: last.at, by: last.by, summary: last.summary } : null; + }; + // the agents that tasks name, as the mind's catalog has them: one call, and it wakes none. The + // catalog answers its most active rows, so an agent that is long idle may not be among them. + const named = tasks.some((task) => task.agent.startsWith("/agents/")); + const catalog = new Map( + (named ? await itx.contexts.list({ under: "/agents", limit: CATALOG_ROWS }) : []).map((row) => [ + row.path, + row, + ]), + ); + const agentSeenOf = (agent) => { + const row = catalog.get(agent); + return row ? { awake: Boolean(row.awake), lastActivityAt: row.lastActivityAt ?? null } : null; + }; + const name = repo.split("/").at(-1); + return { + repo, + commitOid, + /** the same board for a person */ + board: `https://tasks.${new URL(await itx.url()).hostname}/?repo=${encodeURIComponent(name)}`, + tasks: tasks.map((task) => ({ + file: task.path, + title: task.title, + status: task.status, + column: task.column, + tags: task.tags, + priority: task.priority, + size: task.size, + owner: task.owner, + agent: task.agent, + /** that agent in the mind's catalog: has it work now, when did it last; null: not among the catalog's rows (or no agent) */ + agentSeen: agentSeenOf(task.agent), + /** whether that agent follows this card (or every card); null: no agent. An agent that is + * given a card follows it as its first act (cards.js `briefOf`), so a card in progress + * whose agent does not follow it was not taken: the agent may be gone. The catalog cannot + * say that (a session whose workspace was closed stays "idle" there). */ + agentFollows: task.agent + ? followers.some( + (each) => + each.agent === task.agent && + (each.follows === task.path || each.follows === "every task"), + ) + : null, + blockedOn: task.blockedOn || null, + humanAsk: task.humanAsk, + /** what people answered to its earlier asks, oldest first: the newest few */ + answers: answersOf(task.source) + .slice(-ANSWERS) + .map((each) => ({ + ...each, + answer: + each.answer.length > ANSWER_CHARS + ? `${each.answer.slice(0, ANSWER_CHARS - 1)}…` + : each.answer, + })), + lastChange: lastChangeOf(task.path), + })), + /** the files of the tasks that are not done and ask a person something */ + needsAPerson: needsAPerson(tasks).map((task) => task.path), + recentChanges: changes.slice(0, RECENT_CHANGES), + followers: followers.map(({ agent, follows, only }) => ({ + agent, + follows, + only, + })), + }; +}
A cards.js
@@ -0,0 +1,516 @@ +// cards.js — A TASK'S CARD, KEPT BY AN AGENT: three calls of `itx.config` (api.ts) that do what +// a person does on the board, so that an agent never writes a task's frontmatter by hand. +// +// taskOpen a new card: its title, its text (the ask in the person's own words), who asked +// taskUpdate one commit that moves a card: status, who has it, what holds it, a new ask, a note +// taskAssign gives a card to an agent. The card is the brief: the agent gets ONE message that +// says where the card is and how to keep it true (`briefOf`) +// +// Each writes through the board's own functions (public/tasks-model.js), on the tip it read, and +// ends its commit's message with `Via: <the calling agent>`, so the change feed (feed.js) says +// whose work a change is. With these and `answerTask` (asks.js), `followTasks` (feed.js) and +// `taskBoard` (board.js), an agent does everything on the board that a person does. +// +// AN AGENT THAT IS NAMED FOR A CARD: one that ended takes no card. The call refuses the agent +// that it can prove gone, and the one with no turn for half a day that it cannot prove alive +// (`goneOf`); for the rest the board says whether the agent took its card (board.js +// `agentFollows`: an agent follows its card as its first act, `briefOf` step 2). +// +// WHAT A MIND ADDS OF ITS OWN, through `deps` (api.ts `taskDeps`). Each is optional, and a mind +// that names none has the plain calls: +// - `linkNote(itx, note)`: the note as the card keeps it (a mind that mirrors its code to +// GitHub makes a link of each commit id); +// - `briefRules({ repo, file, agent, worker })`: the mind's own rules for an agent that gets a +// card, as lines after `briefOf`'s own steps (who merges, who deploys, who reviews); +// - `startWorker(itx, { worker, by, file, repo })`: starts a NEW agent for `taskAssign({ file, +// worker })` and answers `{ agent, model?, effort?, running? }`. A mind without it starts none; +// - `sessionState(itx, agent, row)`: what the mind can prove of a coding session that is named: +// `"runs"`, or why it is gone, in words; undefined when it cannot tell. +import { repoOf } from "./feed.js"; +import { + commitOf, + decisionFault, + isTaskPath, + messageOf, + newTask, + parseTask, + TASKS_DIR, + tellFault, +} from "./public/tasks-model.js"; + +const oneLine = (value) => + String(value ?? "") + .replace(/\s+/g, " ") + .trim(); +const isObject = (value) => Boolean(value) && typeof value === "object" && !Array.isArray(value); +const nameOf = (repo) => repo.split("/").at(-1); +/** `, repo: "<name>"` for a call's example: always named, since a mind chooses which repo a call + * with none means (api.ts `TASKS_BOARD_REPO`). */ +const repoArg = (repo) => `, repo: ${JSON.stringify(nameOf(repo))}`; +const wordsOf = (error) => String(error?.message || error).slice(0, 300); + +/** The card on the board, for a person. */ +async function linkOf(itx, repo, file) { + const query = `repo=${encodeURIComponent(nameOf(repo))}&task=${encodeURIComponent(file)}`; + return `https://tasks.${new URL(await itx.url()).hostname}/?${query}`; +} + +/** Who makes a change: the agent that the call names (`by`), else the agent whose context the + * call came from; null for neither (a member's own script). */ +function callerOf(input, { callerPath }) { + if (oneLine(input.by)) return oneLine(input.by); + let caller; + try { + caller = callerPath(); + } catch { + caller = undefined; + } + return typeof caller === "string" && caller.startsWith("/agents/") ? caller : null; +} + +/** What a caller wants to see of a card after its change. */ +function cardOf(file, source) { + const { title, status, owner, agent, model, effort, tags, blockedOn, humanAsk } = parseTask( + file, + source, + ); + return { + title, + status, + owner, + agent, + model, + effort, + tags, + blockedOn: blockedOn || null, + humanAsk, + }; +} + +/** ONE COMMIT OF `changes` TO A TASK FILE, as the repo has it now (tasks-model.js `applyChange`). + * Made again on the new tip, once, when another commit overtook it. It answers the commit, whether + * the file changed, and the file's text after it. A file that the repo does not have is refused. */ +async function writeTask(itx, tool, { repo, file, changes, via }) { + const handle = itx.repos.get(repo); + for (let attempt = 0; ; attempt += 1) { + const tip = await handle.tip(); + const source = tip ? await handle.readFile(file, { commitOid: tip }) : null; + if (source === null) throw new Error(`${tool}: ${repo} has no ${file}.`); + // changes that depend on what the file holds now (which ask a caller means) are made from it + const list = typeof changes === "function" ? changes(source) : changes; + const [written] = commitOf({ [file]: source }, list); + if (!written) return { commitOid: tip, changed: false, source }; + try { + const message = `${messageOf(list)}${via ? `\n\nVia: ${via}` : ""}`; + const { commitOid } = await handle.commitFiles({ message, changes: [written], parent: tip }); + return { commitOid, changed: true, source: written.content }; + } catch (error) { + // main moved between the read and the commit: read again, once + if (attempt > 0) throw error; + } + } +} + +/** WHAT AN ASK MUST BRING (Jonas, 25 Nov 2026: "we need to make absolutely sure that when we are + * presented with a choice, the different options are explored and a recommendation is given"). + * A call that adds an ask names `decision: { options: [{ name, tradeoff }, …], recommend, why }` + * for it, or `noChoice: "<why>"` for an ask that is no choice between options (a thing only the + * person can do or see: "open the link and say whether the page shows"). With neither, the ask + * is TAKEN and the call's answer holds `warning`, these words (`ASK_WARNING`): for three quarters + * of an hour on 25 Nov 2026 such a call was refused, and Jonas chose "Only warn" on the card + * (todo/decision-asks-options-recommendation-and-model-provenance.md, 11:28 UTC). A decision + * that is given and is not whole is still refused: the agent meant one, and reads what it lacks. + * One call, one ask with a decision. `askRuleOf` answers the decisions to write; `askWarningOf` + * the warning, or undefined. + * AN ASK WHOSE ANSWER ANOTHER AGENT ACTS ON names it: `tell: { agent, words? }`, the agent that + * must hear the person's answer (one that acts only on a member's own message) and the words + * that you wait for. The person answers in the one box, which starts with those words, and the + * page sends the answer to that agent as the person's own message. Never write an ask that + * sends a person to another chat. It is no choice, so it takes no decision and gets no warning. */ +const ASK_WARNING = + 'This ask has no options. An ask that is a choice names them: add decision: { options: [{ name: "…", tradeoff: "what it costs or gives" }, …at least two], recommend: "<the name of one>", why: "<why that one>" } to the call that adds the ask. The person then sees the options, your recommendation and, from your own log, which model made it. For an ask that is no choice between options (a thing that only the person can do or see), add noChoice: "<why>" instead. To add them to this ask now: take it off (withdraw) and add it again with its decision. tasks.md of /repos/config, "Asks and answers".'; +const askWarningOf = (input) => + [input.ask ?? []].flat().map(oneLine).some(Boolean) && + input.decision === undefined && + input.tell === undefined && + !oneLine(input.noChoice) + ? ASK_WARNING + : undefined; +function askRuleOf(tool, input) { + const asks = [input.ask ?? []].flat().map(oneLine).filter(Boolean); + const decided = Object.hasOwn(input, "decision") && input.decision !== undefined; + const told = Object.hasOwn(input, "tell") && input.tell !== undefined; + if (asks.length === 0) { + if (decided || told || oneLine(input.noChoice)) + throw new Error( + `${tool}: decision, tell and noChoice go with an ask, and this call adds none.`, + ); + return []; + } + if (told) { + if (decided) + throw new Error( + `${tool}: an ask has a decision or a tell, not both: the person answers a choice on the card.`, + ); + if (asks.length !== 1) + throw new Error(`${tool}: a tell is of ONE ask. Add each such ask in a call of its own.`); + const fault = tellFault(input.tell); + if (fault) throw new Error(`${tool}: ${fault}`); + if (asks[0].includes("**")) throw new Error(`${tool}: an ask with a tell holds no "**".`); + return [ + { + kind: "tell", + ask: asks[0], + agent: input.tell.agent.trim(), + words: oneLine(input.tell.words), + }, + ]; + } + if (decided) { + if (asks.length !== 1) + throw new Error( + `${tool}: a decision is of ONE ask. Add each ask that is a choice in a call of its own.`, + ); + const fault = decisionFault(input.decision); + if (fault) throw new Error(`${tool}: ${fault}`); + if (asks[0].includes("**")) throw new Error(`${tool}: an ask with a decision holds no "**".`); + return [{ kind: "decision", ask: asks[0], ...input.decision }]; + } + return []; +} + +/** `itx.config.taskOpen({ title, text?, status?, owner?, agent?, tags?, ask?, decision?, noChoice?, + * repo?, by? })`: a new card in the tasks repo (or in the repo `repo` names). `text` is the task's text under its + * title: the ask in the person's own words, and where it came from. `owner` is the person who + * asked; `ask` is one question for a person, or a list of them, with `decision` or `noChoice` + * (`askRuleOf`). Its file is named by the title. + * It answers `{ repo, file, commitOid, link }`. */ +export async function taskOpen(itx, input, deps) { + if (!isObject(input)) + throw new Error( + "taskOpen takes { title, text?, status?, owner?, agent?, tags?, ask?, repo?, by? }.", + ); + const title = oneLine(input.title); + if (!title) throw new Error("taskOpen: title is a text, and it is not empty."); + const decisions = askRuleOf("taskOpen", input); + const repo = await repoOf("taskOpen", itx, input.repo); + const by = callerOf(input, deps); + const text = String(input.text ?? "").trim(); + const handle = itx.repos.get(repo); + for (let attempt = 0; ; attempt += 1) { + const tip = await handle.tip(); + const under = tip ? await handle.modules({ commitOid: tip, dir: TASKS_DIR }) : {}; + const made = newTask({ + title, + status: oneLine(input.status) || "todo", + taken: Object.keys(under).map((path) => `${TASKS_DIR}/${path}`), + }); + const path = made.path; + const [written] = commitOf({}, [ + { kind: "create", path, content: text ? `${made.content}\n${text}\n` : made.content }, + { kind: "field", path, field: "tags", value: [input.tags ?? []].flat() }, + { kind: "field", path, field: "owner", value: oneLine(input.owner) }, + { kind: "field", path, field: "agent", value: oneLine(input.agent) }, + ...[input.ask ?? []].flat().map((ask) => ({ kind: "ask", path, ask })), + ...decisions.map((decision) => ({ path, ...decision })), + ]); + try { + const { commitOid } = await handle.commitFiles({ + message: `tasks: new ${path}${by ? `\n\nVia: ${by}` : ""}`, + changes: [written], + parent: tip, + }); + const warning = askWarningOf(input); + return { + repo, + file: path, + commitOid, + link: await linkOf(itx, repo, path), + warning, + }; + } catch (error) { + // another commit took the tip, or the name: read again, once + if (attempt > 0) throw error; + } + } +} + +/** The changes that a call names, in the order they are written. */ +function changesOf(path, input, by, now) { + const named = (key) => Object.hasOwn(input, key) && input[key] !== undefined; + return [ + ...(named("title") ? [{ kind: "title", path, title: input.title }] : []), + ...(named("status") ? [{ kind: "status", path, status: oneLine(input.status) }] : []), + ...(named("owner") + ? [{ kind: "field", path, field: "owner", value: oneLine(input.owner) }] + : []), + ...(named("agent") + ? [{ kind: "field", path, field: "agent", value: oneLine(input.agent) }] + : []), + ...(named("tags") + ? [{ kind: "field", path, field: "tags", value: [input.tags ?? []].flat() }] + : []), + ...(named("model") ? [{ kind: "key", path, key: "model", value: input.model }] : []), + ...(named("effort") ? [{ kind: "key", path, key: "effort", value: input.effort }] : []), + ...(named("blockedOn") ? [{ kind: "blocked", path, blockedOn: input.blockedOn }] : []), + ...[input.ask ?? []].flat().map((ask) => ({ kind: "ask", path, ask })), + ...askRuleOf("taskUpdate", input).map((decision) => ({ path, ...decision })), + ...(oneLine(input.note) + ? [{ kind: "note", path, note: input.note, by: by || "someone", at: now.toISOString() }] + : []), + ]; +} + +/** How much of an ask a note quotes. */ +const beginOf = (ask) => (ask.length > 100 ? `${ask.slice(0, 99)}…` : ask); + +/** The changes that keep a card's ASKS true, made from the file as it is now. `withdraw` takes an + * ask off that events overtook; `reword` writes one again in plain words. Each names its ask by + * the whole text or by its beginning, which must fit ONE ask of the card. Each leaves a line + * under `## Log` that says what happened to the ask, and why. */ +function askChangesOf(path, source, { withdraw, reword }, by, now) { + const asked = parseTask(path, source).humanAsk; + const whole = (given) => { + const found = asked.filter((ask) => ask === given || ask.startsWith(given)); + if (found.length === 1) return found[0]; + const has = + asked.length > 0 ? asked.map((ask) => JSON.stringify(beginOf(ask))).join(", ") : "nothing"; + throw new Error( + `taskUpdate: ${found.length === 0 ? "no ask" : `${found.length} asks`} of ${path} ${found.length === 0 ? "begins" : "begin"} with ${JSON.stringify(beginOf(given))}. It asks: ${has}.`, + ); + }; + const note = (words) => ({ + kind: "note", + path, + note: words, + by: by || "someone", + at: now.toISOString(), + }); + return [ + ...withdraw.flatMap(({ ask, why }) => { + const text = whole(ask); + return [ + { kind: "withdraw", path, ask: text }, + note( + `An ask was taken off, with no answer: ${oneLine(why)} It began: ${JSON.stringify(beginOf(text))}`, + ), + ]; + }), + ...reword.flatMap(({ ask, to }) => { + const text = whole(ask); + return [ + { kind: "reword", path, ask: text, to: oneLine(to) }, + note(`An ask was written again in plain words. It began: ${JSON.stringify(beginOf(text))}`), + ]; + }), + ]; +} + +/** `itx.config.taskUpdate({ file, status?, title?, owner?, agent?, tags?, model?, effort?, + * blockedOn?, ask?, withdraw?, reword?, note?, repo?, by? })`: one commit that changes what the + * call names, and leaves every other byte of the file. `blockedOn`: what holds the task, one + * line; `""` takes it away. `ask`: one more question for a person (they answer on the board), + * with `decision: { options, recommend, why }`, or `noChoice: "<why>"` for an ask that is no + * choice (`askRuleOf`: an ask with neither is taken, and the answer holds `warning`). + * `withdraw: { ask, why }` takes an ask off that nobody has to answer any more (the pull request + * it asked about is merged), and `reword: { ask, to }` writes an ask again in plain words; each + * may be a list, and `ask` there is the ask's whole text or its beginning. `note`: one line under + * `## Log`, with who wrote it and when. `by`: the agent that makes the change, when the call + * comes from no agent's context (the MCP `run` tool). It answers + * `{ repo, file, commitOid, changed, card }`. */ +export async function taskUpdate(itx, input, deps, now = new Date()) { + if (!isObject(input)) + throw new Error( + "taskUpdate takes { file, status?, title?, owner?, agent?, tags?, model?, effort?, blockedOn?, ask?, withdraw?, reword?, note?, repo?, by? }.", + ); + const { file } = input; + if (typeof file !== "string" || !isTaskPath(file)) + throw new Error('taskUpdate: file is a task\'s path, like "todo/a-task.md".'); + if (Object.hasOwn(input, "status") && input.status !== undefined && !oneLine(input.status)) + throw new Error('taskUpdate: status is a word, like "in-progress" or "done".'); + const withdraw = [input.withdraw ?? []].flat(); + const reword = [input.reword ?? []].flat(); + if (!withdraw.every((one) => isObject(one) && oneLine(one.ask) && oneLine(one.why))) + throw new Error( + "taskUpdate: withdraw is { ask, why }, or a list of them: the ask (its beginning is enough) and why nobody has to answer it any more.", + ); + if (!reword.every((one) => isObject(one) && oneLine(one.ask) && oneLine(one.to))) + throw new Error( + "taskUpdate: reword is { ask, to }, or a list of them: the ask (its beginning is enough) and its new words.", + ); + const by = callerOf(input, deps); + // the note as the card keeps it: a mind may make links in it (`deps.linkNote`) + const plain = changesOf( + file, + oneLine(input.note) && deps.linkNote + ? { ...input, note: await deps.linkNote(itx, input.note) } + : input, + by, + now, + ); + if (plain.length + withdraw.length + reword.length === 0) + throw new Error( + "taskUpdate: name what changes: status, title, owner, agent, tags, model, effort, blockedOn, ask, withdraw, reword or note.", + ); + const repo = await repoOf("taskUpdate", itx, input.repo); + // the asks first, then the rest: the call's own note is the last line of the log + const changes = (source) => [ + ...askChangesOf(file, source, { withdraw, reword }, by, now), + ...plain, + ]; + const done = await writeTask(itx, "taskUpdate", { repo, file, changes, via: by }); + const warning = askWarningOf(input); + return { + repo, + file, + commitOid: done.commitOid, + changed: done.changed, + card: cardOf(file, done.source), + warning, + }; +} + +/** THE FIRST MESSAGE TO THE AGENT THAT GETS A CARD: where its brief is, and how it keeps the card + * true. The same words for every agent, so that every card is kept the same way. `rules`: the + * mind's own lines after these steps (`deps.briefRules`). */ +export function briefOf({ repo, file, agent, by, words, rules = [] }) { + const also = repoArg(repo); + const from = by && by !== agent ? ` from ${by}` : ""; + return [ + `You have a task${from}. The card is your brief: ${file} in the repo ${repo} of this mind.`, + "", + `1. Read it with your \`run\` tool (in a Claude Code or Codex session: the iterate MCP tool \`run\`): async (itx) => await itx.repos.get(${JSON.stringify(repo)}).readFile(${JSON.stringify(file)}). Read tasks.md of /repos/config first: it has the rules for a card.`, + `2. Follow your card, so that a person's answer reaches you as a message: async (itx) => await itx.config.followTasks({ file: ${JSON.stringify(file)}, agent: ${JSON.stringify(agent)}${also} }).`, + `3. Keep the card true while you work, with one call: async (itx) => await itx.config.taskUpdate({ file: ${JSON.stringify(file)}, by: ${JSON.stringify(agent)}, note: "…"${also} }). The same call takes status ("in-progress", "in-review", "done"), blockedOn (what holds you; "" when it is gone) and ask (one question that a person answers in one line: they answer on the board, and the answer comes to you by your follow; name a thing as a Markdown link, [its name](https://…), when it has an address that is safe to share: tasks.md, "Asks and answers"). An ask that is a choice goes with decision: { options: [{ name, tradeoff }, …], recommend, why }: explore the options first, and recommend one. An ask that is no choice goes with noChoice: "<why>". The call takes an ask with neither, and its answer then holds a warning: read it. Never ask a person to write to another agent: when another agent must hear the answer, add tell: { agent: "/agents/…", words: "<the answer that you wait for>" }, and the board sends the person's answer on to it. When the person answers you anywhere else (your chat, Slack), record it at once with itx.config.answerTask.`, + "4. Send no status messages: whoever needs your state reads the card or follows it.", + '5. Close out your own card: ONE call with status "done" (or "in-review" when a person must look first) and a note that says what is done and how you proved it. What is left of THIS card\'s work keeps the card open: write it on the card. A fault or a job that you found and that is no part of this card gets a card of its own (taskOpen) BEFORE you close, and your last note names it.', + ...rules, + ...(words ? ["", `In the words of the agent that gives you the card: ${words}`] : []), + ].join("\n"); +} + +/** An agent with no turn for longer than this is asked nothing, when the mind cannot prove that it + * runs: a new agent gets the card, with the old agent's path in the card's text. */ +const IDLE_TOO_LONG_MS = 12 * 3_600_000; + +/** WHY AN AGENT CANNOT TAKE A CARD NOW, in words, or null. `row` is its row in the mind's catalog + * on /agents (`kind`, `host`, `status`, `lastActivityAt`: the time of its last turn). + * WHAT IS PROVEN: + * - A row that says "ended" is gone. + * - An iterate agent runs: it is the mind's own loop, and a message wakes it. + * - What the mind itself can prove of a coding session (`deps.sessionState`): that it runs, or + * why it is gone. The catalog cannot say this: a session whose window a person closed sends + * no end, and its row stays "idle" for good. + * WHAT IS NOT PROVEN is decided by the time of the agent's last turn (`IDLE_TOO_LONG_MS`). A row + * with no time passes: for it, and for an agent that goes after it got the card, the board says + * whether the agent took the card (board.js `agentFollows`). */ +async function goneOf(itx, agent, row, now, deps) { + if (!row) return null; + if (row.status === "ended") return "has ended"; + if (row.kind === "iterate") return null; + const state = await deps.sessionState?.(itx, agent, row); + if (state === "runs") return null; + if (typeof state === "string" && state) return state; + const last = Date.parse(row.lastActivityAt ?? ""); + if (!Number.isFinite(last) || now - last <= IDLE_TOO_LONG_MS) return null; + return `has had no turn since ${new Date(last).toISOString().slice(0, 16).replace("T", " ")} UTC (more than ${IDLE_TOO_LONG_MS / 3_600_000} hours), and the mind cannot tell whether it still runs`; +} + +/** `itx.config.taskAssign({ file, agent?, worker?, message?, repo?, by? })`: gives the card to an + * agent. `agent`: the path of an agent that runs (one that provably does not is refused: + * `goneOf`). `worker`: what the mind's own `deps.startWorker` takes to start a NEW agent for the + * card; a mind without one refuses it. The card then names the agent (and for a new one its + * model and effort, when the start names them), is in progress, and has a note of it; and the + * agent gets ONE message, `briefOf`, with `message` added as the caller's own words. + * It answers `{ repo, file, agent, model, effort, starting, running, card }`. `starting`: a new + * agent was asked for; `running`: what the start said of how many run beside it, or null. */ +export async function taskAssign(itx, input, deps, now = new Date()) { + if (!isObject(input) || (input.agent === undefined) === (input.worker === undefined)) + throw new Error( + "taskAssign takes { file, agent } for an agent that runs, or { file, worker } for a new one; and message?, repo?, by?.", + ); + const { file, worker } = input; + if (typeof file !== "string" || !isTaskPath(file)) + throw new Error('taskAssign: file is a task\'s path, like "todo/a-task.md".'); + if (worker !== undefined && !isObject(worker)) + throw new Error( + "taskAssign: worker is what this mind's start of a new agent takes, as an object.", + ); + if (worker !== undefined && !deps.startWorker) + throw new Error( + "taskAssign: this mind starts no new agent for a card. Give the card to an agent that runs: { file, agent }.", + ); + const repo = await repoOf("taskAssign", itx, input.repo); + const by = callerOf(input, deps); + const handle = itx.repos.get(repo); + const tip = await handle.tip(); + const before = tip ? await handle.readFile(file, { commitOid: tip }) : null; + if (before === null) + throw new Error(`taskAssign: ${repo} has no ${file}. Open the card first (taskOpen).`); + + let agent = oneLine(input.agent); + let model = ""; + let effort = ""; + let running = null; + if (worker) { + const started = await deps.startWorker(itx, { worker, by, file, repo }); + agent = started.agent; + model = oneLine(started.model); + effort = oneLine(started.effort); + running = started.running ?? null; + } else if (!agent.startsWith("/agents/") || !(await deps.isAgent(agent))) { + throw new Error( + `taskAssign: ${agent || "that"} is no agent, or it has not said what it is yet.`, + ); + } else { + const gone = await goneOf(itx, agent, await deps.agentRow?.(agent), now.getTime(), deps); + if (gone) + throw new Error( + `taskAssign: ${agent} ${gone}. Nobody would read the card. Give it to an agent that runs; name ${agent} in the card's text when its log helps the new one.`, + ); + } + + // the card first: the message points to it + const open = ["backlog", "todo"].includes(parseTask(file, before).column); + // for a new agent the note says what is true now: it was asked for, and is not yet up + const note = worker + ? `A new worker was asked for: ${agent}${model ? ` (${[model, effort].filter(Boolean).join(", ")})` : ""}.` + : `Given to ${agent}.`; + const change = { + agent, + model: model || undefined, + effort: effort || undefined, + ...(open && { status: "in-progress" }), + note, + }; + const again = `call taskAssign again with { file: ${JSON.stringify(file)}, agent: ${JSON.stringify(agent)} }`; + const done = await writeTask(itx, "taskAssign", { + repo, + file, + via: by, + changes: changesOf(file, change, by, now), + }).catch((error) => { + throw new Error( + `taskAssign: the card was not written (${wordsOf(error)}).${worker ? ` The worker ${agent} was asked for: ${again}.` : ""}`, + ); + }); + const rules = (await deps.briefRules?.({ repo, file, agent, worker: Boolean(worker) })) ?? []; + await itx.agents + .get(agent) + .message(briefOf({ repo, file, agent, by, words: oneLine(input.message), rules })) + .catch((error) => { + throw new Error( + `taskAssign: the card names ${agent}, and the message to it failed (${wordsOf(error)}): ${again}.`, + ); + }); + return { + repo, + file, + agent, + model: model || null, + effort: effort || null, + starting: Boolean(worker), + running, + card: cardOf(file, done.source), + }; +}
A feed.js
@@ -0,0 +1,626 @@ +// feed.js — THE TASK CHANGE FEED: one event for each task file that a commit to a repo of the mind +// changed, on ONE log for each repo, so an agent or a page follows a task, or a whole board, +// without polling and without any worker sending updates. Pure data: no agent and no context for a +// file, no model call, and no state of its own. config/worker.ts hands `taskChangesEvent` every event of +// the mind. +// +// WHICH REPOS. Every repo of the mind, /repos/<name>: its task files are the Markdown files under +// todo/ (tasks-model.js `TASKS_DIR`), as the board reads them. The tasks repo, /repos/task-board +// (`TASKS_REPO`), is the one that a call follows when it names no repo. A repo with no todo/ +// costs nothing here: a commit that names its files and no task file is not read. +// +// THE LOG of a repo is `/task-files/<repo name>`: `/task-files/task-board` for /repos/task-board. (`/tasks/` +// was taken: /tasks/native-indexing means something else.) Each event there is +// `events.iterate.com/tasks/task-changed`: +// { repo, file, change: "added" | "modified" | "deleted", moved, commitOid, beforeOid, +// commitOffset, committedAt, message, by, page, via, before, after, summary, diff, +// diffOmitted? } +// `before` and `after` are the card (`cardOf`: title, status, tags, owner, agent, blockedOn, +// humanAsk), null when there is no such file. `moved` names what the change moved (`MOVES`: the +// card's fields, or "text" when it moved none). `summary` is one line that says what changed: each +// field of the card that moved, and an ask that was answered with its answer. `diff` +// is a line diff of at most MAX_DIFF_BYTES, else null with `diffOmitted`. `by` is who made the +// commit, by the platform's stamp on its fact: the person who asked (an address), else the agent +// whose turn caused it (its path), else null. `page` is where that person acted, by the same +// stamp: an app's page ("tasks.iterate.com": the person's own act on the board), or null for a +// script through the person's sign-in. `via` is the commit message's own `Via:` line, or +// null: an agent's session that commits through a person's sign-in is stamped as that person, and +// this line is where it says who it is. +// +// HOW AN AGENT FOLLOWS (`followTasks`, below). From its own script: +// await itx.config.followTasks({ file: "todo/a-task.md" }) // or no `file`: every task +// From a member's script or the MCP `run` tool, name the agent: `{ file, agent: "/agents/…" }`. +// For a task of another repo, name it: `{ file, repo: "<name>" }`. For some changes and no other: +// `{ only: ["status", "blocked-on", "human-ask"] }` (a manager's follow: no note wakes it). +// Each change then reaches the agent as a message, with the summary and the diff. +// `itx.config.unfollowTasks(…)` ends it and `itx.config.taskFollowers()` lists who follows what. +// A follower is one durable row on the log (`followRowOf`): the platform copies each event the row +// takes to the agent as `agent/message-received`, with the row's own retries. A page listens to +// the log for as long as its session lives: +// itx.cd("/task-files/task-board").subscribe({ consumes: [TASK_CHANGED], target: (events) => … }) +// +// WHAT "BEFORE" IS. The repo's own log holds one `repo/commit-completed` for each update of main, +// in order. "Before" is the commit of the fact before this one on that log. So an event says +// exactly what one update of main changed, whether that was one commit or a pull of several, and +// two commits that arrive here at once, or the wrong way round, cannot mix. The files that changed +// are read from the folder at the two commits, never from the fact's `changedPaths`: a `git push` +// to the repo lands a fact that names no file. +// +// ORDER. The hook gets events in no order, so two commits a second apart can be told the other +// way round. Each event is exact by itself, and `commitOffset` (the fact's offset on the repo's +// log) says which is newer. +// +// BOUNDS. At most MAX_FILES events for one fact; past it one `todo/feed-truncated` names the rest. +// A diff over MAX_DIFF_BYTES, or of a file over MAX_FILE_BYTES, is left out with a flag. +// +// WHY IT CANNOT LOOP. It reads the repo and appends to /task-files/…; it never commits, and no code +// acts on the types it appends. A fact that is delivered twice adds nothing: an event's key is the +// fact's place in the repo's log and the file. +import { answersOf, parseTask, TASKS_DIR, TASKS_REPO } from "./public/tasks-model.js"; + +/** A repo's feed: the repo, the folder whose Markdown files are its tasks (tasks-model.js names it, + * for the board too), and the context that the feeds' logs are under. */ +export const feedOf = (repo) => ({ repo, dir: TASKS_DIR, root: "/task-files" }); +/** The feed of the tasks repo: what a call follows when it names no repo. */ +export const TASK_FEED = feedOf(TASKS_REPO); +/** A repo of the mind, by its path. */ +const REPO_PATH = /^\/repos\/[A-Za-z0-9][A-Za-z0-9._-]*$/; +export const TASK_CHANGED = "events.iterate.com/tasks/task-changed"; +export const FEED_TRUNCATED = "events.iterate.com/tasks/feed-truncated"; +const COMMIT_COMPLETED = "events.iterate.com/repo/commit-completed"; +const ROW_CONFIGURED = "events.iterate.com/itx/subscription-configured"; +export const MAX_FILES = 20; +export const MAX_DIFF_BYTES = 4096; +export const MAX_FILE_BYTES = 65536; +/** A line diff compares at most this many pairs of lines; past it the changed middle is one block. */ +const MAX_DIFF_CELLS = 250_000; +/** How many unchanged lines a diff shows around a change. */ +const DIFF_CONTEXT = 2; +/** The platform's bound on a row's expression (core/itx/src/stream/event-expressions.ts). */ +const MAX_EXPRESSION_CHARS = 1024; +/** The names of the rows that make an agent a follower begin with this. */ +const FOLLOW_ROW = "task-follow-"; + +const bytes = (text) => new TextEncoder().encode(text).length; +const isMarkdown = (path) => /\.(?:md|markdown)$/i.test(path); + +/** Whether `path` of the repo is a task file of this feed. */ +export const isTaskFile = (feed, path) => + (!feed.dir || path.startsWith(`${feed.dir}/`)) && isMarkdown(path); + +/** The feed's log: `/task-files/task-board` for /repos/task-board. */ +export const boardPathOf = (feed) => `${feed.root}/${feed.repo.split("/").at(-1)}`; + +/** What a reader of the feed wants of one version of a task file; null when there is none. */ +function cardOf(file, source) { + if (source === null || source === undefined) return null; + const task = parseTask(file, source); + return { + title: task.title, + status: task.status, + tags: task.tags, + owner: task.owner, + agent: task.agent, + blockedOn: task.blockedOn || null, + humanAsk: task.humanAsk.length > 0 ? task.humanAsk : null, + }; +} + +// ── the diff ── + +/** The changed middle of two lists of lines as steps: " " kept, "-" removed, "+" added. The + * longest common run of lines is kept; two lists too long to compare are one block each. */ +function stepsOf(a, b) { + if (a.length * b.length > MAX_DIFF_CELLS) + return [...a.map((line) => ["-", line]), ...b.map((line) => ["+", line])]; + const width = b.length + 1; + // common[i * width + j]: how many lines the longest common run of a[i..] and b[j..] has + const common = new Uint32Array((a.length + 1) * width); + for (let i = a.length - 1; i >= 0; i -= 1) + for (let j = b.length - 1; j >= 0; j -= 1) + common[i * width + j] = + a[i] === b[j] + ? common[(i + 1) * width + j + 1] + 1 + : Math.max(common[(i + 1) * width + j], common[i * width + j + 1]); + const steps = []; + let i = 0; + let j = 0; + while (i < a.length || j < b.length) { + if (i < a.length && j < b.length && a[i] === b[j]) { + steps.push([" ", a[i]]); + i += 1; + j += 1; + } else if ( + j >= b.length || + (i < a.length && common[(i + 1) * width + j] >= common[i * width + j + 1]) + ) { + steps.push(["-", a[i]]); + i += 1; + } else { + steps.push(["+", b[j]]); + j += 1; + } + } + return steps; +} + +/** A small unified diff of two texts: each changed stretch with DIFF_CONTEXT lines around it, under + * a `@@ -line,count +line,count @@` header. Empty when the texts are equal. */ +export function lineDiff(before, after) { + if (before === after) return ""; + // the line end of the last line is no line of its own, unless only one of the texts has it + const sameEnd = before === "" || after === "" || before.endsWith("\n") === after.endsWith("\n"); + const linesOf = (text) => + text === "" ? [] : (sameEnd ? text.replace(/\n$/, "") : text).split("\n"); + const a = linesOf(before); + const b = linesOf(after); + let head = 0; + while (head < a.length && head < b.length && a[head] === b[head]) head += 1; + let tail = 0; + while ( + tail < a.length - head && + tail < b.length - head && + a[a.length - 1 - tail] === b[b.length - 1 - tail] + ) + tail += 1; + const steps = [ + ...a.slice(0, head).map((line) => [" ", line]), + ...stepsOf(a.slice(head, a.length - tail), b.slice(head, b.length - tail)), + ...a.slice(a.length - tail).map((line) => [" ", line]), + ]; + // each step's line number in the two texts + const lineOfA = []; + const lineOfB = []; + let atA = 1; + let atB = 1; + for (const [kind] of steps) { + lineOfA.push(atA); + lineOfB.push(atB); + if (kind !== "+") atA += 1; + if (kind !== "-") atB += 1; + } + // the stretches to show: each change with its context, two that touch as one + const stretches = []; + steps.forEach(([kind], at) => { + if (kind === " ") return; + const from = Math.max(0, at - DIFF_CONTEXT); + const to = Math.min(steps.length, at + 1 + DIFF_CONTEXT); + const last = stretches.at(-1); + if (last && from <= last.to) last.to = to; + else stretches.push({ from, to }); + }); + return stretches + .map(({ from, to }) => { + const shown = steps.slice(from, to); + const countA = shown.filter(([kind]) => kind !== "+").length; + const countB = shown.filter(([kind]) => kind !== "-").length; + // as `diff -u` writes a side with no line: the line before it + const header = `@@ -${countA ? lineOfA[from] : lineOfA[from] - 1},${countA} +${countB ? lineOfB[from] : lineOfB[from] - 1},${countB} @@`; + return [header, ...shown.map(([kind, line]) => kind + line)].join("\n"); + }) + .join("\n"); +} + +// ── one file's change ── + +const cut = (text, most) => (text.length > most ? `${text.slice(0, most - 1)}…` : text); + +/** One line that says what changed, for a follower: who (on which page, when the person acted on + * one, and through which agent's session, when the commit says so), and each field of the card + * that moved. An ask that left `human-ask:` with + * an answer in the text (`answers`: the text's `## Answers`, tasks-model.js `answersOf`) is told + * with its answer, since that is the news. */ +function summaryOf(file, change, before, after, { by, page, via }, answers) { + const who = `${by ? ` by ${by}${page ? ` on ${page}` : ""}` : ""}${via ? ` via ${via}` : ""}`; + if (change === "added") + return `${file} added${who}: "${after.title}", status ${after.status || "none"}`; + if (change === "deleted") return `${file} deleted${who}: "${before.title}"`; + const said = []; + const tell = (label, was, is) => { + if (was !== is) said.push(`${label} ${was || "none"} → ${is || "none"}`); + }; + tell("status", before.status, after.status); + if (before.title !== after.title) said.push(`title "${before.title}" → "${after.title}"`); + tell("owner", before.owner, after.owner); + tell("agent", before.agent, after.agent); + tell("tags", before.tags.join(", "), after.tags.join(", ")); + tell("blocked-on", before.blockedOn, after.blockedOn); + const asked = before.humanAsk || []; + const asks = after.humanAsk || []; + const added = asks.filter((ask) => !asked.includes(ask)).length; + const gone = asked.filter((ask) => !asks.includes(ask)); + const answered = gone.map((ask) => answers.findLast((each) => each.ask === ask)).filter(Boolean); + for (const each of answered) + said.push( + `answered "${cut(each.ask, 70)}": ${cut(each.answer || "(no words)", 160)}${each.by === by ? "" : ` (${each.by})`}`, + ); + const removed = gone.length - answered.length; + if (added || removed) said.push(`human-ask +${added} -${removed} (now ${asks.length})`); + // none of the card's fields moved: the text below the frontmatter did + if (said.length === 0) said.push("its text"); + return `${file} changed${who}: ${said.join("; ")}`; +} + +/** WHAT A CHANGE CAN MOVE, by name: a file that came or went; for a file that changed, each field + * of its card; and "text" for a change that moved no field (a note, an edit of the body). An + * event's `moved` lists them, and a follower that asks for some (`followTasks({ only })`) is told + * of those changes alone: a manager hears of a status, a blocker or an ask, and not of each note. */ +export const MOVES = [ + "added", + "deleted", + "status", + "title", + "owner", + "agent", + "tags", + "blocked-on", + "human-ask", + "text", +]; + +function movedOf(change, before, after) { + if (change !== "modified") return [change]; + const differ = (a, b) => JSON.stringify(a) !== JSON.stringify(b); + const moved = [ + before.status !== after.status && "status", + before.title !== after.title && "title", + before.owner !== after.owner && "owner", + before.agent !== after.agent && "agent", + differ(before.tags, after.tags) && "tags", + before.blockedOn !== after.blockedOn && "blocked-on", + differ(before.humanAsk, after.humanAsk) && "human-ask", + ].filter(Boolean); + return moved.length > 0 ? moved : ["text"]; +} + +/** One file's change in one update of main, as the event's payload. `fact` says which update + * (`{ commitOid, beforeOid, commitOffset, committedAt, message, by, page, via }`); `before` and `after` are + * the file's text at its two commits (null: no such file). */ +export function taskChangeOf({ feed, fact, file, before, after }) { + const change = after === null ? "deleted" : before === null ? "added" : "modified"; + const cards = { before: cardOf(file, before), after: cardOf(file, after) }; + const payload = { + repo: feed.repo, + file, + change, + moved: movedOf(change, cards.before, cards.after), + ...fact, + ...cards, + summary: summaryOf( + file, + change, + cards.before, + cards.after, + fact, + after === null ? [] : answersOf(after), + ).slice(0, 400), + diff: null, + }; + if (bytes(before || "") > MAX_FILE_BYTES || bytes(after || "") > MAX_FILE_BYTES) + return { ...payload, diffOmitted: "file-too-large" }; + const diff = lineDiff(before || "", after || ""); + return bytes(diff) > MAX_DIFF_BYTES + ? { ...payload, diffOmitted: "diff-too-large" } + : { ...payload, diff }; +} + +// ── a commit, told ── + +const isFactOf = (feed, event) => + event?.type === COMMIT_COMPLETED && + event.path === feed.repo && + event.payload?.path === feed.repo && + Boolean(event.payload.commitOid); + +/** Who made the commit, by the platform's stamp on its fact: the person who asked (an address), + * else the context whose event caused it (an agent's path, without the event's offset), else null. */ +function byOf(source) { + const who = source?.principal || source?.onBehalfOf?.principal; + if (who?.email || who?.actor) return who.email || who.actor; + const cause = source?.cause?.parent; + return typeof cause === "string" && cause.startsWith("/") ? cause.replace(/@\d+$/, "") : null; +} + +/** Where the person acted, by the platform's stamp: the page of an app ("tasks.iterate.com" for + * an edit or an answer on the board). Null for a script through a person's sign-in (the MCP `run` + * tool, the CLI: an agent's session, or the person's own script) and for an agent's own turn. So + * a change `by` an address with a page is that person's own act, and one with no page is not + * proven to be. */ +function pageOf(source) { + const page = source?.onBehalfOf?.via?.appPage; + return typeof page === "string" && page ? page.slice(0, 120) : null; +} + +/** Whose session made the commit for that person, in the commit's own words: its `Via:` line (the + * mind's rule for a commit that an agent makes through a person's sign-in, where the platform's + * stamp names the person alone). The agent's word, not the platform's. Null when it has none. */ +const viaOf = (message) => + /^Via: (.+)$/m + .exec(message || "")?.[1] + .trim() + .slice(0, 120) || null; + +/** The commit that main was at before the fact at `offset` of the repo's log: the commit of the + * newest earlier fact there. Null when the log has none (the repo's first commit). It reads the + * log just below `offset`, and further back only when that stretch holds no fact. */ +async function tipBefore(log, feed, offset) { + for (let reach = 64; ; reach *= 8) { + const start = Math.max(0, offset - 1 - reach); + let found = null; + for (let after = start; after < offset - 1;) { + const page = await log.readEvents(after, 200); + for (const event of page.events) + if (event.offset < offset && isFactOf(feed, event)) found = event; + const through = Math.max(page.scannedThroughOffset ?? 0, page.events.at(-1)?.offset ?? 0); + if (through <= after) break; + after = through; + } + if (found) return found.payload.commitOid; + if (start === 0) return null; + } +} + +/** The task files at a commit, by their path in the repo; none for no commit. A file that is not + * text is left out (`repo.modules`). */ +async function folderAt(repo, feed, commitOid) { + if (!commitOid) return {}; + const under = await repo.modules({ commitOid, dir: feed.dir || undefined }); + const prefix = feed.dir ? `${feed.dir}/` : ""; + return Object.fromEntries( + Object.entries(under) + .filter(([path]) => isMarkdown(path)) + .map(([path, text]) => [prefix + path, text]), + ); +} + +/** Append, and take a second landing of the same key as done. */ +async function appendOnce(log, event) { + await log.append(event).catch((error) => { + if ( + (error?.code ?? error?.data?.code) !== "IDEMPOTENCY_CONFLICT" && + !/IDEMPOTENCY_CONFLICT/.test(String(error)) + ) + throw error; + }); +} + +async function tellChanges(itx, event, feed) { + const commit = event.payload; + const beforeOid = await tipBefore(itx.cd(feed.repo), feed, event.offset); + // the same tip, announced again (`repo.announceTip`) + if (beforeOid === commit.commitOid) return; + const repo = itx.repos.get(feed.repo); + const [was, now] = await Promise.all([ + folderAt(repo, feed, beforeOid), + folderAt(repo, feed, commit.commitOid), + ]); + const changed = [...new Set([...Object.keys(was), ...Object.keys(now)])] + .filter((file) => was[file] !== now[file]) + .sort(); + if (changed.length === 0) return; + const fact = { + commitOid: commit.commitOid, + beforeOid, + commitOffset: event.offset, + committedAt: event.createdAt ?? null, + message: (commit.message || "").split("\n")[0].slice(0, 200), + by: byOf(event.source), + page: pageOf(event.source), + via: viaOf(commit.message), + }; + const at = `${feed.repo}@${event.offset}`; + const events = changed.slice(0, MAX_FILES).map((file) => ({ + type: TASK_CHANGED, + idempotencyKey: `todo/task-changed:${at}:${file}`, + payload: taskChangeOf({ + feed, + fact, + file, + before: was[file] ?? null, + after: now[file] ?? null, + }), + })); + const skipped = changed.slice(MAX_FILES); + if (skipped.length > 0) + events.push({ + type: FEED_TRUNCATED, + idempotencyKey: `todo/feed-truncated:${at}`, + payload: { + repo: feed.repo, + commitOid: commit.commitOid, + commitOffset: event.offset, + total: changed.length, + sent: MAX_FILES, + skipped: skipped.slice(0, 100), + }, + }); + // one after the other, so the log has them in the files' order; a file that fails holds no other + const log = itx.cd(boardPathOf(feed)); + let failure; + for (const each of events) await appendOnce(log, each).catch((error) => (failure ??= error)); + if (failure) throw failure; +} + +/** config/worker.ts's hook: an update of a repo's main, as the repo's own copy of its fact (the root has + * a copy too, at an offset of the root's log). The feed is the repo's own, by the event's path. + * One more try after a failure: a run that is repeated adds nothing twice. */ +export async function taskChangesEvent(itx, event) { + if (event?.type !== COMMIT_COMPLETED || !REPO_PATH.test(event.path || "")) return; + const feed = feedOf(event.path); + if (!isFactOf(feed, event)) return; + // a commit that names its files and names no task file: nothing to read + const named = event.payload.changedPaths || []; + if (named.length > 0 && !named.some((path) => isTaskFile(feed, path))) return; + await tellChanges(itx, event, feed).catch(() => + new Promise((done) => setTimeout(done, 300)).then(() => tellChanges(itx, event, feed)), + ); +} + +// ── followers ── + +/** A short hash of a string (FNV-1a, 32 bits): a row's name only has to differ when its row does. */ +function fnv1a(text) { + let hash = 0x811c9dc5; + for (let index = 0; index < text.length; index += 1) { + hash ^= text.charCodeAt(index); + hash = Math.imul(hash, 0x01000193); + } + return (hash >>> 0).toString(16).padStart(8, "0"); +} + +/** THE ROW THAT MAKES `agent` A FOLLOWER of one task file, or with no `file` of every task: a copy + * row on the feed's log. The platform copies each `task-changed` the row takes to the agent's own + * context as `agent/message-received`, the one input every kind of agent reads, so the agent is + * told as if someone wrote to it. `wake: false`: the words are context only (`trigger: false`). + * The agent is not told of a commit that it made itself: one that its own turn caused (`by` is + * then its path), or one whose message names it (`via`, a session's `Via: <its path>`). + * `only`: some of MOVES; the row then takes the changes that moved one of them, and no other. + * One row for each (agent, file): following again writes the same row, with the new `only`. */ +export function followRowOf(feed, { agent, file, wake = true, only = [] }) { + const what = `${file || "every task"}${only.length > 0 ? ` (only a change of: ${only.join(", ")})` : ""}`; + const moves = + only.length > 0 + ? ` and (${only.map((move) => `${JSON.stringify(move)} in payload.moved`).join(" or ")})` + : ""; + // the call that ends it, with the repo's name: a mind chooses which repo a call with none means + const named = { + agent, + file: file || undefined, + repo: feed.repo.split("/").at(-1), + }; + const stop = `await itx.config.unfollowTasks(${JSON.stringify(named)})`; + const words = [ + `{ "message": "A task changed: " & payload.summary`, + ` & (payload.diff ? "\\n\\n" & payload.diff : " (no diff here: " & payload.diffOmitted & "; read the file)")`, + ` & ${JSON.stringify(`\n\nYou follow ${what} of ${feed.repo}. To stop: ${stop}`)}`, + wake ? " }" : `, "trigger": false }`, + ].join(""); + if (words.length > MAX_EXPRESSION_CHARS) + throw new Error( + `followTasks: the agent's path and the file's are too long together for one row (${words.length} of ${MAX_EXPRESSION_CHARS} characters).`, + ); + return { + name: `${FOLLOW_ROW}${fnv1a(`${agent}\n${file || ""}`)}`, + consumes: [TASK_CHANGED], + filter: `${file ? `payload.file = ${JSON.stringify(file)} and ` : ""}payload.by != ${JSON.stringify(agent)} and payload.via != ${JSON.stringify(agent)}${moves}`, + target: { path: agent, type: "events.iterate.com/agent/message-received", payload: words }, + }; +} + +/** The repo a call is about, by its path: the one it names (`"tasks"` or `"/repos/task-board"`), else + * the tasks repo. A repo that the mind does not have is refused: a row on its log would wait for + * ever, and a read of it would fail with other words. (asks.js uses it too.) */ +export async function repoOf(tool, itx, named) { + const repo = + named === undefined + ? TASKS_REPO + : typeof named === "string" && named.startsWith("/") + ? named + : `/repos/${named}`; + if (!REPO_PATH.test(repo)) + throw new Error(`${tool}: repo is a repo's name or its path, like "tasks" or "/repos/task-board".`); + const repos = await itx.repos.list(); + if (!repos.some((each) => each.path === repo)) + throw new Error(`${tool}: the mind has no repo ${repo}.`); + return repo; +} +const feedFor = async (tool, itx, named) => feedOf(await repoOf(tool, itx, named)); + +/** What a follower's row follows, read from its filter (`followRowOf` wrote it): the file that it + * names first, or every task. */ +function followedOf(filter) { + const named = /^payload\.file = ("(?:[^"\\]|\\.)*")/.exec(filter || ""); + return named ? JSON.parse(named[1]) : "every task"; +} +/** The moves that a follower's row is for, read from its filter; null: every change. */ +function onlyOf(filter) { + const moves = [...(filter || "").matchAll(/"([a-z-]+)" in payload\.moved/g)].map( + (found) => found[1], + ); + return moves.length > 0 ? moves : null; +} + +/** Who a call is for: the agent it names, else the agent whose context it came from. */ +async function followerOf(tool, input, { callerPath, isAgent }) { + if (input !== undefined && (input === null || typeof input !== "object" || Array.isArray(input))) + throw new Error(`${tool} takes { file?, agent?, repo? }.`); + const asked = input ?? {}; + const only = asked.only === undefined ? [] : [asked.only].flat(); + if (only.some((move) => !MOVES.includes(move)) || (asked.only !== undefined && only.length === 0)) + throw new Error(`${tool}: only is a list of what a change moved, from: ${MOVES.join(", ")}.`); + let caller; + try { + caller = callerPath(); + } catch { + caller = undefined; + } + const agent = + asked.agent ?? + (typeof caller === "string" && caller.startsWith("/agents/") ? caller : undefined); + if (typeof agent !== "string" || !agent.startsWith("/agents/")) + throw new Error( + `${tool}: this call came from no agent's context: name the agent, { agent: "/agents/…" }.`, + ); + // the one gate that says a path is an agent: a row for any other path would write to it + if (!(await isAgent(agent))) + throw new Error(`${tool}: ${agent} is no agent, or it has not said what it is yet.`); + return { agent, file: asked.file, wake: asked.wake !== false, only: [...new Set(only)] }; +} + +/** `itx.config.followTasks({ file?, agent?, wake?, only?, repo? })`: from now on `agent` (the + * calling agent when not named) is told of each change of the task file `file`, or of every task, + * of the tasks repo or of the repo `repo` names. `only`: some of MOVES, for the changes that + * moved one of them and no other (`only: ["status", "blocked-on", "human-ask"]` leaves out each + * note and each edit of a text). It answers what is followed. A task that the repo does not have + * is refused: its row would wait for ever. */ +export async function followTasks(itx, input, deps) { + const { agent, file, wake, only } = await followerOf("followTasks", input, deps); + const feed = await feedFor("followTasks", itx, input?.repo); + if (file !== undefined) { + if (typeof file !== "string" || !isTaskFile(feed, file)) + throw new Error( + `followTasks: file is a task's path in ${feed.repo}, like "${feed.dir ? `${feed.dir}/` : ""}a-task.md".`, + ); + if ((await itx.repos.get(feed.repo).readFile(file)) === null) + throw new Error(`followTasks: ${feed.repo} has no ${file}.`); + } + const row = followRowOf(feed, { agent, file, wake, only }); + const log = boardPathOf(feed); + await itx.cd(log).append({ type: ROW_CONFIGURED, payload: row }); + return { + agent, + follows: file ?? "every task", + only: only.length > 0 ? only : null, + repo: feed.repo, + log, + row: row.name, + }; +} + +/** `itx.config.unfollowTasks({ file?, agent?, repo? })`: ends what `followTasks` with the same + * `file` (or with none) and the same repo began. It answers whether there was such a row. */ +export async function unfollowTasks(itx, input, deps) { + const { agent, file } = await followerOf("unfollowTasks", input, deps); + const feed = await feedFor("unfollowTasks", itx, input?.repo); + const { name } = followRowOf(feed, { agent, file }); + const log = itx.cd(boardPathOf(feed)); + const followed = (await log.subscriptions.list()).some((row) => row.name === name); + if (followed) await log.append({ type: ROW_CONFIGURED, payload: { name, target: null } }); + return { agent, follows: file ?? "every task", repo: feed.repo, ended: followed }; +} + +/** `itx.config.taskFollowers({ repo? })`: who follows what in the tasks repo, or in the repo that + * `repo` names, read from the rows of its log. */ +export async function taskFollowers(itx, input) { + const feed = await feedFor("taskFollowers", itx, input?.repo); + const rows = await itx.cd(boardPathOf(feed)).subscriptions.list(); + return rows + .filter((row) => row.name.startsWith(FOLLOW_ROW) && row.copy) + .map((row) => ({ + agent: row.copy.path, + follows: followedOf(row.filter), + only: onlyOf(row.filter), + repo: feed.repo, + row: row.name, + })); +}
M index.html
@@ -2,24 +2,32 @@ <html lang="en"> <head> <meta charset="utf-8" /> - <meta name="viewport" content="width=device-width, initial-scale=1" /> + <!-- interactive-widget: where a browser knows it (Chrome on Android), the keyboard makes the + page shorter, so what stands at the bottom stays above it. iOS reads it not: app.js + `useSeenScreen` does that work there. --> + <meta + name="viewport" + content="width=device-width, initial-scale=1, interactive-widget=resizes-content" + /> <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://ui.iterate.com" crossorigin /> <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 pins. To upgrade, change - the version here. --> + <!-- iterate's components, pinned to one release of iterate's UI host (the version is a + commit of the branch `dist` of git.iterate.com/repos/ui): the one that the Docs app pins. + To upgrade, change the commit here, in every line that names it. --> <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/", + "@iterate-com/ui/": "https://ui.iterate.com/@iterate-com/ui@113924454d6ae84a3194625bd4c88892430fb678/", + "react": "https://ui.iterate.com/@iterate-com/ui@113924454d6ae84a3194625bd4c88892430fb678/react", + "react/": "https://ui.iterate.com/@iterate-com/ui@113924454d6ae84a3194625bd4c88892430fb678/react/", + "react-dom": "https://ui.iterate.com/@iterate-com/ui@113924454d6ae84a3194625bd4c88892430fb678/react-dom", + "react-dom/": "https://ui.iterate.com/@iterate-com/ui@113924454d6ae84a3194625bd4c88892430fb678/react-dom/", "lucide-react": "https://esm.iterate.com/lucide-react@1.48.0?external=react,react-dom" } } @@ -32,20 +40,27 @@ window.__itxSocket = new WebSocket(new URL("/itx", location.href.replace(/^http/, "ws"))); } catch {} </script> - <!-- The stylesheet at the address the build serves it from: the shorter one answers with a - redirect to this one. `crossorigin`, so it comes over the connection the modules use. --> + <!-- 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" - crossorigin - href="https://esm.iterate.com/@iterate-com/ui@0.1.0-main.20261124T154040Z-83b4390/dist/styles.css" + href="https://ui.iterate.com/@iterate-com/ui@113924454d6ae84a3194625bd4c88892430fb678/docs-editor.css" /> <!-- The look of this mind's apps: theme.css of /repos/stdlib, 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. --> + 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> + <script> + // `?embed=1`: the page is shown in a frame of another app of the mind (the Dash's panel + // "Needs a person"). A frame is narrow: app.css draws no sidebar and no bar there, and + // app.js shows the asks one at a time at any width. The same Tasks app, for the same member. + if (new URLSearchParams(location.search).get("embed") === "1") + document.documentElement.dataset.embed = ""; </script> <link rel="stylesheet" href="/app.css" /> </head>
M package.json
@@ -7,6 +7,7 @@ "test": "node --test tests/*.test.mjs" }, "dependencies": { + "@repos/docs": "../docs", "@repos/stdlib": "../stdlib" }, "devDependencies": {
M pnpm-lock.yaml
@@ -8,6 +8,9 @@ .: dependencies: + '@repos/docs': + specifier: ../docs + version: link:../docs '@repos/stdlib': specifier: ../stdlib version: link:../stdlib
M public/app.css
@@ -823,20 +823,22 @@ color: var(--destructive); } -/* the file's text as it is written, under the head: read here, written with git */ +/* 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; - margin: 0; - padding: 1rem 1.5rem; border-top: 1px solid var(--border); - font-family: ui-monospace, SFMono-Regular, Menlo, monospace; - font-size: 0.8125rem; - line-height: 1.6; - white-space: pre-wrap; - overflow-wrap: anywhere; } +/* 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; @@ -894,7 +896,64 @@ font-size: 0.8125rem; } +/* a link in an ask or in what holds a task (app.js `Linked`) */ +.needs-link { + color: var(--primary); + text-decoration: underline; + text-underline-offset: 2px; + overflow-wrap: anywhere; +} + +.needs-link:hover { + text-decoration-thickness: 2px; +} + /* 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; +} + +/* who asked, then "huh?" (app.js `Huh`): one line under the ask */ +.needs-who { + display: flex; + flex-wrap: wrap; + align-items: center; + column-gap: 0.5rem; +} + +.needs-huh { + margin-top: 0.125rem; + color: var(--muted-foreground); + font-size: 0.75rem; + text-decoration: underline; + text-decoration-style: dotted; + text-underline-offset: 2px; +} + +.needs-huh:hover { + color: var(--foreground); + text-decoration-style: solid; +} + +.needs-asker > svg { + width: 0.75rem; + height: 0.75rem; +} + .needs-answer { display: flex; align-items: center; @@ -911,4 +970,959 @@ margin: 0; color: var(--muted-foreground); font-size: 0.8125rem; +} + +/* ── a card that waits for a person (app.js `NeedsMark`): amber, as the dot of a high priority ── */ +.task[data-needs] { + border-left: 3px solid oklch(0.75 0.15 75); +} + +.task-needs { + display: flex; + align-items: center; + gap: 0.375rem; + padding: 0.2rem 0.45rem; + border: 1px solid color-mix(in oklab, oklch(0.75 0.15 75) 60%, var(--border)); + border-radius: calc(var(--radius) - 2px); + background: color-mix(in oklab, oklch(0.75 0.15 75) 20%, var(--card)); + color: var(--foreground); + font-size: 0.75rem; + font-weight: 600; + line-height: 1.3; + text-decoration: none; + cursor: pointer; +} + +.task-needs:hover { + background: color-mix(in oklab, oklch(0.75 0.15 75) 32%, var(--card)); +} + +.task-needs:focus-visible { + outline: 2px solid var(--ring); + outline-offset: 1px; +} + +.task-needs > i, +.task-asks-title > i { + flex: none; + width: 0.5rem; + height: 0.5rem; + border-radius: 999px; + background: oklch(0.75 0.15 75); +} + +.task-needs-who { + min-width: 0; + overflow-wrap: anywhere; +} + +.task-needs-count { + flex: none; + margin-left: auto; + color: var(--muted-foreground); + font-weight: 500; +} + +/* ── the same in the task's sheet, before the title (app.js `TaskAsks`) ── */ +.task-asks { + display: flex; + flex: none; + flex-direction: column; + gap: 0.5rem; + margin: 0.25rem 1.5rem 0.75rem; + padding: 0.75rem; + border: 1px solid var(--border); + border-radius: var(--radius); + background: var(--card); +} + +.task-asks[data-waits] { + border-color: color-mix(in oklab, oklch(0.75 0.15 75) 60%, var(--border)); + border-left: 3px solid oklch(0.75 0.15 75); + background: color-mix(in oklab, oklch(0.75 0.15 75) 10%, var(--card)); +} + +.task-asks-title { + display: flex; + align-items: center; + gap: 0.5rem; + margin: 0; + font-size: 0.875rem; + font-weight: 600; +} + +.task-asks .needs-asks { + padding-inline-start: 1.25rem; + font-size: 0.875rem; +} + +@media (max-width: 640px) { + .task-asks { + margin-inline: 1rem; + } + + .task-asks .needs-answer { + flex-wrap: wrap; + } +} + +/* ── "Needs a person": for whom, the order, "Talk these through" (app.js `NeedsPage`) ── */ +.needs-bar { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 0.5rem; + max-width: 48rem; + padding: 1rem 1rem 0; +} + +.needs-for { + display: flex; + flex-wrap: wrap; + gap: 0.375rem; +} + +.needs-chip { + display: inline-flex; + align-items: center; + gap: 0.375rem; + padding: 0.25rem 0.625rem; + border: 1px solid var(--border); + border-radius: 999px; + background: var(--card); + color: var(--foreground); + font-size: 0.8125rem; + cursor: pointer; +} + +.needs-chip > i { + color: var(--muted-foreground); + font-style: normal; + font-size: 0.75rem; +} + +.needs-chip[aria-pressed="true"] { + border-color: var(--foreground); + background: var(--foreground); + color: var(--background); +} + +.needs-chip[aria-pressed="true"] > i { + color: inherit; + opacity: 0.7; +} + +.needs-chip:focus-visible, +.needs-talk:focus-visible { + outline: 2px solid var(--ring); + outline-offset: 1px; +} + +.needs-bar-end { + display: flex; + align-items: center; + gap: 0.75rem; + margin-left: auto; +} + +.needs-talk { + display: inline-flex; + align-items: center; + gap: 0.375rem; + color: var(--foreground); + font-size: 0.8125rem; + text-decoration: underline; + text-decoration-style: dotted; + text-underline-offset: 2px; + white-space: nowrap; +} + +.needs-talk > svg { + width: 0.875rem; + height: 0.875rem; +} + +.needs-ago { + margin-top: 0.125rem; + color: var(--muted-foreground); + font-size: 0.75rem; +} + +/* what a person reads before they answer (app.js `Context`) */ +.needs-context, +.needs-others { + color: var(--muted-foreground); + font-size: 0.8125rem; +} + +.needs-context summary, +.needs-others summary { + display: flex; + flex-wrap: wrap; + align-items: center; + column-gap: 0.75rem; + width: fit-content; + cursor: pointer; + list-style: none; + text-decoration: underline; + text-decoration-style: dotted; + text-underline-offset: 2px; +} + +.needs-context summary::-webkit-details-marker, +.needs-others summary::-webkit-details-marker { + display: none; +} + +.needs-context summary > .needs-asker { + margin-top: 0; +} + +.needs-note, +.needs-about { + margin: 0.25rem 0; + overflow-wrap: anywhere; +} + +.needs-note { + display: -webkit-box; + overflow: hidden; + -webkit-box-orient: vertical; + -webkit-line-clamp: 3; +} + +.needs-context details .needs-note { + display: block; +} + +.needs-about { + color: var(--foreground); + white-space: pre-wrap; +} + +.needs-others > .needs-asks { + margin-top: 0.375rem; + color: var(--foreground); +} + +@media (max-width: 640px) { + .needs-bar-end { + width: 100%; + margin-left: 0; + justify-content: space-between; + } +} + +/* ── an answer: the box that grows, who hears it, and what you answered (app.js `Ask`, `Answered`) ── */ +.needs-answer { + align-items: flex-end; +} + +.needs-box { + flex: 1; + min-width: 0; + min-height: 2.25rem; + max-height: 20rem; + padding: 0.4rem 0.625rem; + border: 1px solid var(--border); + border-radius: calc(var(--radius) - 2px); + background: var(--background); + color: var(--foreground); + font: inherit; + font-size: 0.875rem; + line-height: 1.4; + resize: none; + overflow-y: auto; +} + +.needs-box:focus-visible { + border-color: var(--ring); + outline: 2px solid color-mix(in oklab, var(--ring) 40%, transparent); +} + +.needs-goes { + display: block; + margin-top: 0.25rem; + color: var(--muted-foreground); + font-size: 0.75rem; +} + +.needs-answered { + max-width: 48rem; + padding: 0 1rem 1rem; + color: var(--muted-foreground); + font-size: 0.8125rem; +} + +.task-asks .needs-answered { + padding: 0; +} + +.needs-answered > summary { + width: fit-content; + margin: 0.5rem 0 0.375rem; + font-size: 0.75rem; + cursor: pointer; + text-decoration: underline; + text-decoration-style: dotted; + text-underline-offset: 2px; +} + +.needs-answered > ul { + display: flex; + flex-direction: column; + gap: 0.5rem; + margin: 0; + padding: 0; + list-style: none; +} + +.needs-answered li { + display: flex; + flex-direction: column; + gap: 0.125rem; + padding: 0.5rem 0.75rem; + border: 1px dashed var(--border); + border-radius: var(--radius); +} + +.needs-answered-task { + color: var(--foreground); + font-weight: 500; + text-decoration: none; +} + +.needs-answered-task:hover { + text-decoration: underline; +} + +.needs-answered-said { + color: var(--foreground); + overflow-wrap: anywhere; +} + +.needs-answered-said::before { + content: "→ "; + color: var(--muted-foreground); +} + +/* ── the button that opens an agent's chat (app.js `ChatButton`) ── */ +.needs-chat-toggle { + display: inline-flex; + align-items: center; + gap: 0.25rem; + margin-top: 0.125rem; + padding: 0; + border: 0; + background: none; + color: var(--foreground); + font-size: 0.75rem; + text-decoration: underline; + text-underline-offset: 2px; + cursor: pointer; +} + +.needs-chat-toggle > svg { + width: 0.75rem; + height: 0.75rem; +} + +.needs-chat-toggle:focus-visible { + outline: 2px solid var(--ring); + outline-offset: 1px; +} + +/* ── the sheet with an agent's chat (app.js `ChatButton`): the Dash's page of the agent in a frame ── */ +.chat-sheet { + gap: 0; + width: min(100vw, 46rem); + max-width: none; + background: var(--background); + color: var(--foreground); +} + +.chat-sheet-top { + display: flex; + flex: none; + flex-direction: column; + gap: 0.125rem; + padding: 0.75rem 3.25rem 0.5rem 1rem; + border-bottom: 1px solid var(--border); +} + +.chat-sheet-about { + color: var(--muted-foreground); + font-size: 0.75rem; +} + +.chat-sheet-frame { + flex: 1; + width: 100%; + min-height: 0; + border: 0; +} + +/* ── a decision's options under its ask, and the model that asked (app.js `Decision`) ── */ +.needs-decision { + margin-top: 0.25rem; + padding: 0.5rem 0.625rem; + border: 1px solid var(--border); + border-radius: calc(var(--radius) - 2px); + background: var(--background); + font-size: 0.8125rem; +} + +.needs-decision[data-bare] { + padding: 0; + border: 0; + background: none; + color: var(--muted-foreground); + font-size: 0.75rem; +} + +.needs-decision > ul { + display: flex; + flex-direction: column; + gap: 0.375rem; + margin: 0; + padding: 0; + list-style: none; +} + +.needs-decision li { + display: flex; + align-items: baseline; + gap: 0.5rem; +} + +.needs-option { + flex: none; + padding: 0.1rem 0.5rem; + border: 1px solid var(--border); + border-radius: 999px; + background: var(--card); + color: var(--foreground); + font: inherit; + font-weight: 600; + cursor: pointer; +} + +.needs-option:hover, +.needs-option:focus-visible { + border-color: var(--foreground); + outline: none; +} + +.needs-decision li[data-recommended] > .needs-option { + border-color: oklch(0.6 0.13 150); + background: color-mix(in oklab, oklch(0.6 0.13 150) 16%, var(--card)); +} + +.needs-recommend { + margin: 0.5rem 0 0; +} + +.needs-by { + display: block; + margin-top: 0.125rem; + color: var(--muted-foreground); + font-size: 0.75rem; +} + +.needs-model { + font-family: var(--font-mono, ui-monospace, monospace); + font-size: 0.6875rem; +} + +.needs-model[data-unrecorded] { + font-family: inherit; + font-style: italic; +} + +/* an ask that may be outdated (app.js `Stale`), and a task's priority in place (`Press`) */ +.needs-stale { + display: block; + margin-top: 0.125rem; + color: oklch(0.55 0.13 60); + font-size: 0.75rem; +} + +.needs-press { + display: inline-flex; + align-items: center; + gap: 0.5rem; + margin-left: auto; +} + +.needs-top { + flex-wrap: wrap; +} + +/* a row's title keeps room for its words: on a narrow screen the chips go under it (at 390 px a + title beside the owner's chip was one letter a line). A chip is never wider than its row: a + long owner ends in an ellipsis, and the row does not scroll sideways. */ +.needs-top > .task-title { + flex: 1 1 11rem; + min-width: min(11rem, 100%); +} + +.needs-top > [data-slot="badge"] { + display: inline-block; + flex-shrink: 1; + min-width: 0; + max-width: 100%; + overflow: hidden; + text-overflow: ellipsis; + line-height: 1.125rem; +} + +.needs-press [data-priority="urgent"], +.needs-press [data-priority="high"] { + border-color: oklch(0.63 0.21 25); + font-weight: 600; +} + +/* ── an ask's own question, set apart from what is around it (app.js `Ask`) ── + Jonas, 25 Nov 2026: "the formatting of all of these questions is horrible. You have to like + bold the question". The question is the largest and the only bold text of its ask; who asked, + the model, the options and the chat are smaller and grey, under it. Each ask of a task has a + rule above it, and the list has no indent on a narrow screen. */ +.needs-question { + display: block; + color: var(--foreground); + font-size: 0.9375rem; + font-weight: 600; + line-height: 1.4; + overflow-wrap: anywhere; +} + +.needs-question .needs-link { + font-weight: 600; +} + +.needs-asks > li + li { + margin-top: 0.25rem; + padding-top: 0.75rem; + border-top: 1px solid var(--border); +} + +.needs-asks > li { + display: flex; + flex-direction: column; + gap: 0.25rem; +} + +.needs-asks > li > .needs-who, +.needs-asks > li > .needs-answer { + margin-top: 0; +} + +@media (max-width: 640px) { + .needs-asks, + .task-asks .needs-asks { + padding-inline-start: 0; + } + + .chat-sheet { + width: 100vw; + border-left: 0; + } +} + +/* ── the agent's own last message, under an ask's question (app.js `Blocking`) ── */ +.needs-said { + padding: 0.5rem 0.625rem; + border-left: 3px solid var(--border); + background: color-mix(in oklab, var(--muted) 50%, transparent); + font-size: 0.8125rem; +} + +.needs-said-label { + display: flex; + align-items: baseline; + gap: 0.5rem; + color: var(--muted-foreground); + font-size: 0.75rem; +} + +.needs-said > p { + display: -webkit-box; + margin: 0.125rem 0 0; + overflow: hidden; + color: var(--foreground); + white-space: pre-wrap; + overflow-wrap: anywhere; + -webkit-box-orient: vertical; + -webkit-line-clamp: 4; +} + +.needs-said[data-whole] > p { + display: block; +} + +.needs-said > .tasks-link { + font-size: 0.75rem; +} + +.needs-said code { + padding: 0 0.2rem; + border-radius: 3px; + background: var(--muted); + font-family: var(--font-mono, ui-monospace, monospace); + font-size: 0.75rem; +} + +/* Above the box of an ask whose answer another agent acts on (app.js `Ask`): where it goes. */ +.needs-tell { + margin: 0.25rem 0 0; + font-size: 0.8125rem; +} + +/* ── "Needs a person" on a phone: one ask at a time (app.js `NeedsDeck`, `DeckCard`) ── + Jonas, 27 Nov 2026: "Entering Text on mobile is v hard", "The page is impossible to parse", + "Most info on that screen is not needed at all by default". One card fills the page: the + question, the options as buttons that a thumb hits (48 px and more), and the box. */ +.deck { + display: flex; + flex-direction: column; + gap: 0.75rem; + padding: 0.75rem 1rem 1.5rem; +} + +.deck-head { + display: flex; + align-items: center; + gap: 0.5rem; +} + +/* for whom: one line that scrolls sideways, never a second line */ +.deck-for { + display: flex; + flex: 1; + gap: 0.375rem; + min-width: 0; + overflow-x: auto; + scrollbar-width: none; +} + +.deck-for > .needs-chip { + flex: none; + min-height: 2.25rem; + white-space: nowrap; +} + +.deck-step { + display: flex; + flex: none; + align-items: center; + color: var(--muted-foreground); + font-size: 0.8125rem; + font-variant-numeric: tabular-nums; + white-space: nowrap; +} + +.deck-plain { + min-height: 2.75rem; + padding: 0 0.625rem; + border: 0; + background: none; + color: var(--foreground); + font: inherit; + font-size: 0.875rem; + cursor: pointer; +} + +.deck-plain:disabled { + opacity: 0.35; +} + +.deck-status { + display: flex; + align-items: center; + justify-content: space-between; + gap: 0.5rem; + margin: 0; + padding: 0.5rem 0.75rem; + border-radius: var(--radius); + background: var(--muted); + font-size: 0.875rem; + overflow-wrap: anywhere; +} + +.deck-status svg { + display: inline; + width: 1rem; + height: 1rem; + margin-right: 0.375rem; + vertical-align: -0.15em; +} + +.deck-status[data-failed] { + color: var(--destructive); +} + +.deck-undo { + flex: none; + min-height: 2.25rem; + padding: 0 0.875rem; + border: 1px solid var(--border); + border-radius: 999px; + background: var(--card); + color: var(--foreground); + font: inherit; + font-weight: 600; + cursor: pointer; +} + +.deck-card { + display: flex; + flex-direction: column; + gap: 0.75rem; + padding: 1rem; + border: 1px solid var(--border); + border-radius: var(--radius); + background: var(--card); +} + +.deck-read { + display: flex; + flex-direction: column; + gap: 0.375rem; +} + +.deck-task { + display: flex; + align-items: center; + gap: 0.5rem; +} + +.deck-task-title { + min-width: 0; + overflow: hidden; + color: var(--muted-foreground); + font-size: 0.8125rem; + text-overflow: ellipsis; + white-space: nowrap; +} + +.deck-question { + margin: 0; + color: var(--foreground); + font-size: 1.125rem; + font-weight: 600; + line-height: 1.35; + overflow-wrap: anywhere; +} + +.deck-options { + display: flex; + flex-direction: column; + gap: 0.5rem; + margin: 0; + padding: 0; + list-style: none; +} + +.deck-option { + display: flex; + flex-direction: column; + gap: 0.25rem; + width: 100%; + min-height: 3rem; + padding: 0.75rem 0.875rem; + border: 1px solid var(--border); + border-radius: var(--radius); + background: var(--background); + color: var(--foreground); + font: inherit; + font-size: 1rem; + text-align: left; + cursor: pointer; +} + +.deck-option:active { + border-color: var(--foreground); +} + +.deck-option[data-recommended] { + border-color: oklch(0.6 0.13 150); + background: color-mix(in oklab, oklch(0.6 0.13 150) 14%, var(--background)); +} + +.deck-option-name { + display: flex; + align-items: baseline; + justify-content: space-between; + gap: 0.5rem; + font-weight: 600; + overflow-wrap: anywhere; +} + +.deck-option-name > i { + flex: none; + color: var(--muted-foreground); + font-size: 0.75rem; + font-style: normal; + font-weight: 500; +} + +.deck-option-why { + color: var(--muted-foreground); + font-size: 0.8125rem; + line-height: 1.4; + overflow-wrap: anywhere; +} + +.deck-tell { + margin: 0; +} + +.deck-answer { + display: flex; + flex-direction: column; + gap: 0.5rem; +} + +/* 16 px: under that, iOS zooms the page in when the box takes the focus */ +.deck-box { + width: 100%; + min-height: 3rem; + padding: 0.75rem; + border: 1px solid var(--border); + border-radius: var(--radius); + background: var(--background); + color: var(--foreground); + font: inherit; + font-size: 1rem; + line-height: 1.4; + resize: none; + overflow-y: auto; +} + +.deck-box:focus-visible { + border-color: var(--ring); + outline: 2px solid color-mix(in oklab, var(--ring) 40%, transparent); +} + +.deck-answer-row { + display: flex; + gap: 0.5rem; +} + +/* nothing written and the box not in use: no button stands there greyed out */ +.deck-answer[data-idle] > .deck-answer-row { + display: none; +} + +.deck-answer-row > .deck-send { + flex: 1; + min-height: 2.75rem; + font-size: 1rem; +} + +.deck-more-toggle { + align-self: center; + color: var(--muted-foreground); + text-decoration: underline; + text-decoration-style: dotted; + text-underline-offset: 3px; +} + +.deck-more { + display: flex; + flex-direction: column; + gap: 0.625rem; + padding-top: 0.75rem; + border-top: 1px solid var(--border); + font-size: 0.875rem; +} + +.deck-more > .needs-recommend, +.deck-more > .needs-blocked { + margin: 0; +} + +.deck-more-end { + display: flex; + flex-wrap: wrap; + align-items: center; + justify-content: space-between; + gap: 0.5rem; +} + +.deck-done { + margin: 2rem 0; + color: var(--muted-foreground); + text-align: center; +} + +/* WRITING: the card is what is seen of the screen above the keyboard (app.js `useSeenScreen` + sets its top and height). The question scrolls; the box and "Send" stay at the bottom. */ +.deck-card[data-writing] { + position: fixed; + z-index: 100; + top: 0; + right: 0; + left: 0; + height: 100dvh; + border: 0; + border-radius: 0; + overflow: hidden; +} + +.deck-card[data-writing] > .deck-read { + flex: 1; + min-height: 0; + overflow-y: auto; +} + +.deck-card[data-writing] > .deck-options, +.deck-card[data-writing] > .deck-more-toggle, +.deck-card[data-writing] > .deck-more { + display: none; +} + +/* an ask in a task's sheet, on a phone (app.js `Ask`): each option above what it costs, the box + over its button, and 16 px in the box (iOS zooms in under that) */ +@media (max-width: 640px) { + .needs-decision li { + flex-direction: column; + align-items: flex-start; + gap: 0.25rem; + } + + .needs-option { + padding: 0.375rem 0.75rem; + text-align: left; + } + + .needs-answer, + .task-asks .needs-answer { + flex-direction: column; + flex-wrap: nowrap; + align-items: stretch; + } + + .needs-answer > :first-child { + flex: none; + } + + .needs-box { + font-size: 1rem; + } + + .needs-answer > button { + min-height: 2.75rem; + } +} + +/* ── In a frame of another app (index.html, `?embed=1`: the Dash's panel "Needs a person") ── + No sidebar, no button for it and no bar: the frame holds the asks, one at a time, and what + became of an answer stands over the card (`DeckStatus`). */ +[data-embed] [data-slot="sidebar-trigger"], +[data-embed] [data-slot="sidebar"], +[data-embed] [data-slot="sidebar-gap"], +[data-embed] .frame-sidebar, +[data-embed] header:has([data-page-header]) { + display: none; }
M public/app.js
@@ -1,1536 +1,3232 @@ // app.js — THE TASKS APP'S PAGE: the markdown files under todo/ in one repo of this mind, as a // board. The repo is the one config/worker.ts points the app at (app.ts `tasksApp({ repo })`, -// which /board.json answers), 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 and its -// properties are edited, and its text is read ("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 that the mind's code is not loaded -// from publishes nothing: /repos/task-board is such a repo. -// -// 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, - 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, - 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, - 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 }, pointed] = await Promise.all([ - itx.whoami(), - // the repo config/worker.ts points the board at (app.ts, `tasksApp({ repo })`) - fetch("/board.json").then((answer) => answer.json()), -]); -/** 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. Read once when the page loads; the bar's "Repo" menu loads the page again for - * another (`showRepo`). */ -const DEFAULT_REPO_NAME = pointed.repo.split("/").at(-1); -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}`; -/** 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 pushed with git, 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), - ), - )} - <//> - <//> - <//> - `, - )} - `; -} - -/** 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`). */ -function Ask({ task, ask }) { - const [answer, setAnswer] = useState(""); - return html` - <li> - <span>${ask}</span> - <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`); what holds a task is only read. The board's other filters still - * narrow it. */ -function NeedsPage({ state, tasks, filtered }) { - 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} />`, - )} - </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} - <//> - `, - )} - <//> - <//> - <//> - <//> - </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>`). Its TITLE AND PROPERTIES are -// edited there 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. A changed title renames -// nothing: the file's path is the task's identity. Its TEXT is shown as the file has it. The -// board has no editor for it: write it with git, or ask an agent. - -/** 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 file's text. */ -function TaskBody({ task, columns, dimensions, save, move }) { - 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} /></p> - <pre class="task-text">${task.source}</pre> - </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>`; +// 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 sidebar header's repo switcher 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, AppShellBrand, 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, + useSidebar, +} 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, + agoOf, + answerMessage, + decisionsOf, + tellMessage, + tellsOf, + keeperOf, + PRIORITIES, + pressOf, + staleOf, + stillNeededMessage, + receiversOf, + askIsFor, + contextOf, + deckAt, + deckOf, + NEEDS_ORDERS, + needsFor, + orderNeeds, + peopleAsked, + talkDraft, + huhDraft, + huhHref, + applyChange, + columnOf, + columnsOf, + commitOf, + DIMENSIONS, + dimensionsOf, + eventPath, + filterTasks, + linkedParts, + messageOf, + needsAPerson, + newTask, + rowsOf, + TASKS_DIR, + TASKS_REPO, + tasksOf, + valuesOf, + waitsForAPerson, +} 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; +/** The agents that the mind retired (app.ts `tasksApp({ retiredAgents })`): an ask of one may be + * outdated, and "Still needed?" goes to the task's agent in its place. */ +const RETIRED_AGENTS = Array.isArray(pointed?.retiredAgents) + ? pointed.retiredAgents.filter((path) => typeof path === "string") + : []; +/** 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 sidebar's head: the mind's icon, which the app answers at /icon.svg (../app.ts). +const MIND_ICON = html`<img src="/icon.svg" alt="" className="size-8 rounded-md" />`; +/** 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 `todo/` 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}`; +/** 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)}`; +/** The Dash of this mind: the host `dash` beside this one, on this page's own scheme and port. */ +const DASH = `${location.protocol}//dash.${location.host.split(".").slice(1).join(".") || location.host}`; +/** 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 && `${DASH}${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 todo/ 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 +// (an answer that still waits for "Undo" is sent first: `heldAnswer`, below) +const leave = () => { + heldAnswer.flush(); + board.commitNow(); +}; +addEventListener("pagehide", leave); +// a phone often ends a page with no pagehide: hidden is the last moment that is sure to come +document.addEventListener( + "visibilitychange", + () => document.visibilityState === "hidden" && leave(), +); +addEventListener("beforeunload", (event) => { + heldAnswer.flush(); + 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 todo/ ("." 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 todo/, 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 todo/, 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", + /** "Needs a person" for one person (`?for=Jonas`; `?for=-`: the asks that name nobody), or null */ + needsFor: + params.get("for") === null ? null : params.get("for") === "-" ? "" : params.get("for"), + /** the order of "Needs a person" (`?order=`): tasks-model.js `NEEDS_ORDERS` */ + order: NEEDS_ORDERS.find(({ id }) => id === params.get("order"))?.id ?? NEEDS_ORDERS[0].id, + }; + }, [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) => { + if (dimension.id !== "agent") return value; + const last = value.split("/").filter(Boolean).at(-1) || value; + // a coding session that a person started is named by its id alone: its first eight characters + // tell it from the others, and the whole path is in each link's title + return /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(last) + ? `session ${last.slice(0, 8)}` + : last; +}; + +// ── 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} + switcher=${html`<${RepoSwitcher} repos=${repos} />`} + 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> + ${ + 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} + view=${view} + />` + : 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 todo/, 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), + ), + )} + <//> + <//> + <//> + `, + )} + `; +} + +/** The sidebar's head: Tasks + the active repo, with a dropdown to switch repos when the mind has + * more than one, or a plain brand when it has one. */ +function RepoSwitcher({ repos }) { + const { isMobile, setOpenMobile } = useSidebar(); + if (repos.length <= 1) { + return html` + <${AppShellBrand} + app="Tasks" + line=${html`<span className="font-mono">${REPO}</span>`} + logo=${MIND_ICON} + href="./" + /> + `; + } + return html` + <${SidebarMenu}> + <${SidebarMenuItem}> + <${DropdownMenu}> + <${DropdownMenuTrigger} + render=${html` + <${SidebarMenuButton} + size="lg" + className="data-popup-open:bg-sidebar-accent data-popup-open:text-sidebar-accent-foreground" + aria-label=${`Repo: ${REPO}`} + > + <span + className="flex aspect-square size-8 items-center justify-center rounded-md bg-black" + > + ${MIND_ICON} + </span> + <span className="grid flex-1 text-left text-sm leading-tight"> + <span className="truncate font-medium">Tasks</span> + <span className="truncate font-mono text-xs text-muted-foreground">${REPO}</span> + </span> + <${ChevronDownIcon} className="ml-auto" /> + <//> + `} + /> + <${DropdownMenuContent} + align="start" + side=${isMobile ? "bottom" : "right"} + sideOffset=${4} + className="min-w-56 rounded-lg" + > + <${DropdownMenuGroup}> + <${DropdownMenuLabel}>Tasks of the repo<//> + ${repos.map( + (name) => html` + <${DropdownMenuItem} + key=${name} + className="gap-2" + onClick=${() => { + if (isMobile) setOpenMobile(false); + showRepo(name); + }} + > + <span className="truncate font-mono">${`/repos/${name}`}</span> + ${name === REPO_NAME ? html`<${CheckIcon} className="ml-auto" />` : null} + <//> + `, + )} + <//> + <//> + <//> + <//> + <//> + `; +} + +/** 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; +} +/** One ask's row of `useAskers`: null until the first answer, `{ unread }` when the call failed, + * and `{}` for an ask that the answer does not have (a new one): the page then names the task's agent. */ +const askerOf = (askers, task, ask) => + askers && (askers === "unread" ? { unread: true } : (askers.get(`${task.path}\n${ask}`) ?? {})); + +/** 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> + `; +} + +/** THE MESSAGE THAT ASKED, AFTER WHO ASKED (Jonas, 25 Nov 2026): a link to the one event of the + * asker's log in which it asked, open in the Dash's raw view of that context (tasks-model.js + * `eventPath`), when `itx.config.taskAskers` knows it (`message`: apps/tasks/askers.js says how + * it is found). An event that led to the ask and does not hold its words is called that, not + * "the message". The link opens the raw view of a context, never the agent's chat, and its title + * says so. With none, there is no link here, and "Asked by" opens the chat as before. */ +function AskMessage({ asker }) { + const path = asker?.message && eventPath(asker.message.path, asker.message.offset); + if (!path) return null; + return html` + <a + class="needs-huh" + data-ask-message + href=${`${DASH}${path}`} + target="_blank" + rel="noreferrer" + data-words=${asker.message.words || undefined} + title=${ + asker.message.words + ? `Opens event ${asker.message.offset} of ${asker.message.path} in the Dash's view of that context (not the agent's chat): the turn in which this was asked.` + : `Opens event ${asker.message.offset} of ${asker.message.path} in the Dash's view of that context (not the agent's chat): the event that led to this ask. It does not hold the ask's words.` + } + > + ${asker.message.words ? "the message" : "what led to it"} + </a> + `; +} + +/** "huh?", AFTER WHO ASKED (Misha, 23 Nov 2026): a new tab with the Agents app's home, where the + * box that starts a NEW agent holds a draft that asks it to explain this ask (tasks-model.js + * `huhDraft`, `huhHref`). Nothing is sent: the person reads the draft, changes it and starts the + * agent, or closes the tab. The asker is not told. No link before the askers are read: the draft + * names who asked. */ +function Huh({ task, ask, asker }) { + if (!asker) return null; + const draft = huhDraft({ + domain, + repo: REPO_NAME, + path: task.path, + title: task.title, + ask, + asker, + taskAgent: task.agent, + }); + return html` + <a + class="needs-huh" + href=${huhHref(domain, draft)} + target="_blank" + rel="noreferrer" + title="Opens a new agent's message box with a draft that asks it to explain this question. Nothing is sent until you send it, and the agent that asked is not told." + > + huh? + </a> + `; +} + +/** A LINE WITH ITS LINKS: an ask or what holds a task, where `[words](https://…)` and a bare + * `https://…` are links (tasks-model.js `linkedParts`). A link opens in a new tab, so that the + * answer a person is writing stays. */ +function Linked({ text }) { + return linkedParts(text).map((part, index) => + part.href + ? html`<a + key=${index} + class="needs-link" + href=${part.href} + target="_blank" + rel="noreferrer" + title=${part.href} + >${part.text}</a + >` + : part.text, + ); +} + +/** "3 d ago", or "just now". */ +const agoWords = (at) => (agoOf(at) === "now" ? "just now" : `${agoOf(at)} ago`); + +/** WHO FOLLOWS WHICH TASK (`itx.config.taskFollowers`), for the line that says who hears an + * answer: null until the first answer, [] when the call fails (the line then names the asker as + * one that gets a message, which is what the page then does). Asked once for a page, and again + * after an answer. */ +let followersAsked; +const followersOf = (fresh) => + (followersAsked = + (!fresh && followersAsked) || + itx.config.taskFollowers({ repo: REPO_NAME }).then( + (rows) => [...rows], + () => [], + )); +function useFollowers() { + const [followers, setFollowers] = useState(null); + useEffect(() => { + let live = true; + followersOf().then((rows) => live && setFollowers(rows)); + return () => { + live = false; + }; + }, []); + return followers; +} + +// WHAT THIS PERSON ANSWERED HERE, kept in this browser alone (localStorage, for a week, the +// newest 40): the ask, the answer and the agents that heard it, so that the page can say what +// happened to an answer and where the agent's reply will be (its chat). The card's own text +// keeps every answer for everybody (`## Answers`); this list is only the way back to the chats. +const ANSWERED_KEY = `tasks:answered:${REPO_NAME}`; +const answeredStore = (() => { + const listeners = new Set(); + const read = () => { + try { + const rows = JSON.parse(localStorage.getItem(ANSWERED_KEY) || "[]"); + return Array.isArray(rows) + ? rows.filter((row) => Date.now() - Date.parse(row.at) < 7 * 86_400_000) + : []; + } catch { + return []; + } + }; + let rows = read(); + return { + get: () => rows, + subscribe: (listener) => { + listeners.add(listener); + return () => listeners.delete(listener); + }, + add(row) { + rows = [row, ...rows].slice(0, 40); + try { + localStorage.setItem(ANSWERED_KEY, JSON.stringify(rows)); + } catch { + // a browser that keeps nothing: the list lives as long as the page + } + for (const listener of listeners) listener(); + }, + /** One row's receiver, told or not: `told` true, or the words of why not. */ + told(at, agent, told) { + rows = rows.map((row) => + row.at === at + ? { + ...row, + receivers: row.receivers.map((each) => + each.agent === agent ? { ...each, told } : each, + ), + } + : row, + ); + try { + localStorage.setItem(ANSWERED_KEY, JSON.stringify(rows)); + } catch { + // as above + } + for (const listener of listeners) listener(); + }, + }; +})(); +const useAnswered = () => + useSyncExternalStore(answeredStore.subscribe, answeredStore.get, answeredStore.get); + +/** AN ANSWER, SENT: the board's change (one commit a moment later, `answerAsk`), a row of what this + * person answered, and for an asker that does not follow the card a message to it + * (tasks-model.js `receiversOf`, `answerMessage`). The message goes from this person's own + * session to the agent that asked, and through no other agent. */ +function sendAnswer({ task, ask, answer, asker, followers, tell }) { + const by = principal?.email || principal?.actor || "someone"; + const at = new Date().toISOString(); + const receivers = receiversOf({ task, asker, followers: followers ?? [], tell }); + board.change({ kind: "answer", path: task.path, ask, answer, by, at }); + answeredStore.add({ + at, + path: task.path, + title: task.title, + ask, + answer: answer.replace(/\s+/g, " ").trim(), + receivers, + }); + for (const { agent, hears, why } of receivers) { + if (hears !== "message") continue; + itx.agents + .get(agent) + .message( + (why === "acts on it" ? tellMessage : answerMessage)({ + domain, + repo: REPO_NAME, + path: task.path, + title: task.title, + ask, + answer, + by, + why, + asker: asker?.agent, + }), + ) + .then( + () => answeredStore.told(at, agent, true), + (error) => answeredStore.told(at, agent, wordsOf(error)), + ); + } + followersOf(true); +} + +// ── an agent's chat, in a sheet ── +// "Chat with <agent>" OPENS THAT AGENT'S CHAT IN A SHEET at the right of the page, over the list. +// It is the DASH'S OWN PAGE OF THE AGENT in a frame (`dash.<domain>/agents/<path>?embed=1`: +// apps/dash/index.html hides the Dash's sidebar button there). The Dash draws every kind of agent +// with that kind's own view (a Claude Code session's turns, an iterate agent's chat) and its +// composer. The frame is the member's own Dash, signed in by the same cookie on the same site: it +// grants nothing that the Dash's link does not. +// +// HOW IT CAME TO THIS (Jonas, 25 Nov 2026). He asked for "an embedded agent component that slides +// open and shows it inline, and then shows when your answer has gone in". A first try drew the +// kit's plain `AgentChat` in a box under the ask: it shows "Nothing said yet" for a coding session. +// A second drew the Dash's page under each ask as soon as the ask came into view: "yes but i hate +// it. should be optional and probably open in a sheet or something when opened", and: "it's +// overwhelming". So NOTHING OPENS A CHAT BUT THE PERSON'S CLICK on its button: not a task's +// sheet, not another ask, not an answer. One chat is open at a time, and the answer box needs none. + +/** The button that opens an agent's chat, and the sheet with the chat. The sheet is this + * button's own child, so that it opens over a task's sheet too, which is a dialog itself. Its + * frame is made when the sheet first opens, and is gone when it closes. */ +function ChatButton({ agent, about }) { + const [open, setOpen] = useState(false); + const path = agentChatPath(agent); + return html` + <button + type="button" + class="needs-chat-toggle" + aria-haspopup="dialog" + title=${`Opens the chat with ${agent} in a sheet, live. You can write to it.`} + onClick=${() => setOpen(true)} + > + <${BotIcon} />Chat with ${valueLabel(DIMENSION.agent, agent)} + </button> + <${Sheet} open=${open} onOpenChange=${setOpen}> + <${SheetContent} + className="chat-sheet" + onKeyDown=${(event) => { + // Escape closes this sheet alone: the key goes no further up, where a task's sheet, + // which this one is a child of, would close too + if (event.key !== "Escape") return; + event.stopPropagation(); + setOpen(false); + }} + onPointerDown=${(event) => event.stopPropagation()} + > + <div class="chat-sheet-top"> + <${SheetTitle} className="task-sheet-kind" + >Chat with ${valueLabel(DIMENSION.agent, agent)}<// + > + <${SheetDescription} className="chat-sheet-about"> + ${about ? html`About: ${about}.${" "}` : ""}What you write here goes to the agent and is + no answer on the card.${" "} + <a class="needs-link" href=${agentHref(agent)} target="_blank" rel="noreferrer" + >Open in the Dash</a + > + <//> + </div> + ${open && html`<iframe class="chat-sheet-frame" src=${`${DASH}${path}${path.includes("?") ? "&" : "?"}embed=1`} title=${`The chat of ${agent}, in the Dash`} allow="clipboard-write"></iframe>`} + <//> + <//> + `; +} + +/** AN AGENT'S WORDS, WITH THE LITTLE MARKDOWN THAT AGENTS WRITE MOST: `**bold**` is bold and + * a span in backticks is code; links are links (`Linked`). Everything else is text as it is, with + * its line breaks: a list's dashes and a heading's hashes stay. */ +function Said({ text }) { + return String(text) + .split(/(\*\*[^*\n]+\*\*|`[^`\n]+`)/) + .map((part, index) => + /^\*\*[^*\n]+\*\*$/.test(part) + ? html`<strong key=${index}><${Linked} text=${part.slice(2, -2)} /></strong>` + : /^`[^`\n]+`$/.test(part) + ? html`<code key=${index}>${part.slice(1, -1)}</code>` + : html`<${Linked} key=${index} text=${part} />`, + ); +} + +/** UNDER AN ASK'S QUESTION: THE AGENT'S OWN LAST MESSAGE of the turn in which it asked + * (`itx.config.taskAskers`, `blocking`: apps/tasks/askers.js says how it is found), so that a + * person reads what the agent said with no chat opened. Its first lines show; "more" shows all + * of it (at most 4,000 characters are kept). Its links, bold words and code are drawn (`Said`), + * and no other Markdown. With none (the turn still runs, or a kind of agent whose log has no such event), + * nothing is here and the question stands alone. */ +function Blocking({ asker }) { + const said = asker?.blocking; + const [whole, setWhole] = useState(false); + if (!said?.text) return null; + const long = said.text.length > 320 || said.text.split("\n").length > 4; + const href = eventPath(said.path, said.offset); + return html` + <div class="needs-said" data-whole=${whole || !long || undefined}> + <span class="needs-said-label"> + ${valueLabel(DIMENSION.agent, said.path)} said${" "} + ${href && html`<a class="needs-huh" href=${`${DASH}${href}`} target="_blank" rel="noreferrer" title=${`Opens event ${said.offset} of ${said.path} in the Dash's view of that context.`}>where</a>`} + </span> + <p><${Said} text=${said.text} /></p> + ${long && html`<button type="button" class="tasks-link" aria-expanded=${whole} onClick=${() => setWhole(!whole)}>${whole ? "less" : "more"}</button>`} + </div> + `; +} + +/** UNDER AN ASK THAT IS A CHOICE: the options with what each costs or gives, the one that the + * asker recommends and why (the card's text keeps them: tasks-model.js `decisionsOf`), and WHICH + * MODEL made the turn that asked, by the asker's own log (`itx.config.taskAskers`, `model`), or + * "model unrecorded" when no event says. A click on an option writes its name into the answer + * box; the person still sends it. An ask with no options shows the model's line alone. */ +function Decision({ decision, asker, onPick, bare = false }) { + const model = asker?.model; + const by = !asker + ? null + : model + ? html`<span + class="needs-model" + title=${model.from === "llm-request" ? "From the LLM request of the turn that asked, on the agent's own log." : "From the start of the coding session that asked, on its own log. A model changed later in the session is not recorded."} + > + model ${model.name}${model.from === "session-start" ? " (at its session's start)" : ""} + </span>` + : html`<span + class="needs-model" + data-unrecorded + title="No event of the asker's own log says which model made this turn. The card's model key and an agent's own words are not read as evidence." + >model unrecorded</span + >`; + if (!decision) return bare ? by : null; + return html` + <div class="needs-decision"> + <ul aria-label="Options"> + ${decision.options.map( + ({ name, tradeoff }) => html` + <li key=${name} data-recommended=${name === decision.recommend || undefined}> + <button + type="button" + class="needs-option" + title="Writes this option into the answer box. You still send it." + onClick=${() => onPick(name)} + > + ${name} + </button> + <span><${Linked} text=${tradeoff} /></span> + </li> + `, + )} + </ul> + <p class="needs-recommend"> + <strong>Recommended: ${decision.recommend}.</strong> + <${Linked} text=${decision.why} /> + ${by && html`<span class="needs-by">Recommended by ${by}</span>`} + </p> + </div> + `; +} + +/** BESIDE AN ASK THAT MAY BE OUTDATED (tasks-model.js `staleOf`): why, and "Still needed?", which + * sends the ask's keeper (the agent that asked, else the one that has the task) a message from + * this person: check the ask, and take it off, write it again or say that it stands. */ +function Stale({ task, ask, asker }) { + const [told, setTold] = useState(null); + const why = asker && staleOf({ asker, retired: RETIRED_AGENTS }); + if (!why) return null; + const keeper = keeperOf({ task, asker, retired: RETIRED_AGENTS }); + return html` + <span class="needs-stale"> + May be outdated: ${why}. + ${ + keeper && + (told === null + ? html`<button + type="button" + class="tasks-link" + title=${`Sends ${keeper} a message from you: check this ask, and take it off, write it again, or say that it stands.`} + onClick=${() => { + setTold("sending"); + itx.agents + .get(keeper) + .message( + stillNeededMessage({ + domain, + repo: REPO_NAME, + path: task.path, + title: task.title, + ask, + by: principal?.email || principal?.actor || "someone", + why, + }), + ) + .then( + () => setTold("sent"), + (error) => setTold(wordsOf(error)), + ); + }} + > + Still needed? + </button>` + : html`<span role="status" + >${told === "sending" ? "Asking…" : told === "sent" ? `Asked ${valueLabel(DIMENSION.agent, keeper)}.` : `Not sent: ${told}`}</span + >`) + } + </span> + `; +} + +/** ON A TASK OF "Needs a person": a mark when work stands still for the answer (tasks-model.js + * `pressOf`), beside the task's title, and its priority, set in place (a change of the board, as + * in the sheet). THE PRIORITY IS BEHIND "Context" (`select` alone there), not beside the title: + * Jonas, 27 Nov 2026, in Slack: "Why is the first thing on the decision cards a mutable priority + * deopsown for example?". The question and what answers it come first. */ +function Press({ task, held = true, select = true }) { + const known = PRIORITIES.includes(task.priority) + ? PRIORITIES + : [...new Set([task.priority, ...PRIORITIES])].filter(Boolean); + return html` + <span class="needs-press"> + ${held && pressOf(task).held && html`<${Badge} variant="secondary" title=${task.blockedOn ? `Blocked on: ${task.blockedOn}` : "The task is in progress or in review, and waits for this answer."}>Work is held<//>`} + ${ + select && + html`<${NativeSelect} + size="sm" + aria-label=${`Priority of ${task.title}`} + data-priority=${task.priority || undefined} + value=${task.priority || ""} + onChange=${(event) => board.change({ kind: "field", path: task.path, field: "priority", value: event.target.value })} + > + <${NativeSelectOption} value="">No priority<//> + ${known.map((value) => html`<${NativeSelectOption} key=${value} value=${value}>${value}<//>`)} + <//>` + } + </span> + `; +} + +/** UNDER AN ANSWER BOX: which agents hear the answer, each a link to its chat, where its reply + * will be. Nothing until the askers and the followers are read. */ +function Receivers({ receivers }) { + if (receivers.length === 0) + return html`<span class="needs-goes">Goes on the card. No agent is known to hear it.</span>`; + return html` + <span class="needs-goes"> + Goes to${" "} + ${receivers.map( + ({ agent, why, hears }, index) => html` + ${index > 0 && " and "} + <a + key=${agent} + class="needs-link" + href=${agentHref(agent)} + target="_blank" + rel="noreferrer" + title=${`${agent} ${why}. It hears your answer ${hears === "card" ? "by the card, which it follows" : "by a message from you: it does not follow the card"}. Its reply will be in its chat.`} + > + ${valueLabel(DIMENSION.agent, agent)} + </a> + ${" "}(${why}) + `, + )} + </span> + `; +} + +/** WHAT YOU ANSWERED (in this browser, this week), CLOSED UNTIL THE PERSON OPENS IT: one line + * that says how many. The list was open at first, under the asks, and read as cards that still + * wait (Jonas, 25 Nov 2026: "this page currently shows loads of cards i have responded to. no + * bueno"). An answered ask is off "Needs a person" at once; a task stays on it only while it has + * another ask. Open, the list is each answer with the agents that heard it as + * links to their chats, where a reply will be. `path`: one task's answers only (its sheet). A + * message that could not be sent says so, with the reason. */ +function Answered({ path }) { + const rows = useAnswered().filter((row) => !path || row.path === path); + if (rows.length === 0) return null; + return html` + <details class="needs-answered" aria-label="What you answered"> + <summary> + You answered + ${rows.length === 1 ? "one ask" : `${rows.length} asks`}${path ? " of this task" : ""} this + week: where each went, and the chats for the replies + </summary> + <ul> + ${rows.map((row) => html`<${AnsweredRow} key=${row.at} row=${row} path=${path} />`)} + </ul> + </details> + `; +} + +/** One answer of "You answered". The chat of an agent that heard it opens under it: there the + * person sees that the answer went in, and the agent's reply when it comes. */ +function AnsweredRow({ row, path }) { + return html` + <li> + ${ + !path && + html`<a + class="needs-answered-task" + href=${taskHref(row.path)} + onClick=${(event) => { + if ( + event.button !== 0 || + event.metaKey || + event.ctrlKey || + event.shiftKey || + event.altKey + ) + return; + event.preventDefault(); + openTask(row.path); + }} + >${row.title}</a + >` + } + <span class="needs-answered-ask"><${Linked} text=${row.ask} /></span> + <span class="needs-answered-said">${row.answer}</span> + <span class="needs-who"> + <span class="needs-ago" title=${`${row.at.slice(0, 16).replace("T", " ")} UTC`} + >${agoWords(row.at)}</span + > + ${row.receivers.length === 0 && html`<span class="needs-ago">On the card. No agent is known to hear it.</span>`} + ${row.receivers.map( + ({ agent, hears, told }) => html` + <a + key=${agent} + class="needs-asker" + href=${agentHref(agent)} + target="_blank" + rel="noreferrer" + title=${`${agent}: its reply will be in its chat.`} + > + ${hears === "card" ? "Heard by" : told === true ? "Sent to" : typeof told === "string" ? "NOT sent to" : "Sending to"}${" "} + ${valueLabel(DIMENSION.agent, agent)}: see its reply<${ExternalLinkIcon} /> + </a> + ${typeof told === "string" && html`<span class="needs-ago" role="alert">The message failed: ${told}. The answer is on the card.</span>`} + <${ChatButton} agent=${agent} about=${row.title} /> + `, + )} + </span> + </li> + `; +} + +/** THE DRAFT OF ONE ASK'S ANSWER, and where the answer goes. `kept`: a draft from before (the + * phone's deck keeps one for each card that the person left). */ +function useDraft(task, ask, kept) { + // an ask whose answer ANOTHER AGENT acts on (the card's text says so: tasks-model.js `tellsOf`): + // the answer given here goes to that agent too, as the person's own message, and the box + // starts with the words that the asker waits for. Jonas, 25 Nov 2026, of an ask that sent him + // to another agent's chat: "i am the same person with the same level of authentication in both + // places. it should make zero difference where i post" + const tell = useMemo(() => tellsOf(task.source).get(ask), [task.source, ask]); + const [answer, setAnswer] = useState(() => kept ?? tell?.words ?? ""); + // A DRAFT IS OF ONE ROUTE. When the card changes where the answer goes, or the words that it + // waits for, what stands in the box was written for the route before: it is dropped, and the + // box starts again with the new words, under the line that names the new agent. + const route = tell ? `${tell.agent}\n${tell.words}` : ""; + const routed = useRef(route); + useEffect(() => { + if (routed.current === route) return; + routed.current = route; + setAnswer(tell?.words || ""); + }, [route]); + return { tell, answer, setAnswer }; +} + +/** 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, followers }) { + const { tell, answer, setAnswer } = useDraft(task, ask); + // the box grows with what is typed: a long answer is read whole before it is sent + const box = useRef(null); + useEffect(() => { + if (!box.current) return; + box.current.style.height = "auto"; + box.current.style.height = `${Math.min(box.current.scrollHeight + 2, 320)}px`; + }, [answer]); + // the agent whose chat opens here: the one that asked, else the one that has the task + const chatAgent = [asker?.agent, task.agent].find((each) => agentHref(each)); + const decision = useMemo(() => decisionsOf(task.source).get(ask), [task.source, ask]); + return html` + <li> + <span class="needs-question"><${Linked} text=${ask} /></span> + <${Decision} + decision=${decision} + asker=${asker} + onPick=${(name) => { + setAnswer(name); + box.current?.focus(); + }} + /> + ${ + // WHERE THE ANSWER GOES IS SAID BEFORE IT CAN BE SENT: from the card's own text, so it + // stands here while the asker and the followers are still being read + tell && + html`<p class="needs-tell"> + Your answer goes to${" "} + <a + class="needs-link" + href=${agentHref(tell.agent)} + target="_blank" + rel="noreferrer" + title=${`${tell.agent} acts on your answer. Opens its chat in the Dash.`} + >${tell.agent}</a + > + ${" "}as a message from you, and onto the card. + </p>` + } + <form + class="needs-answer" + onSubmit=${(event) => { + event.preventDefault(); + if (!answer.trim()) return; + sendAnswer({ task, ask, answer, asker, followers, tell }); + }} + > + <textarea + ref=${box} + class="needs-box" + rows="1" + placeholder="Your answer. Enter sends it; Shift+Enter is a new line" + aria-label=${`Your answer to: ${ask}`} + value=${answer} + onInput=${(event) => setAnswer(event.target.value)} + onKeyDown=${(event) => { + // Enter sends it, with Cmd or Ctrl too; Shift+Enter is a new line in the box + if ( + event.key !== "Enter" || + event.shiftKey || + event.isComposing || + event.nativeEvent?.isComposing + ) + return; + event.preventDefault(); + event.currentTarget.form.requestSubmit(); + }} + ></textarea> + <${Button} type="submit" variant="outline" size="sm" disabled=${!answer.trim()} + >${tell ? `Send to ${valueLabel(DIMENSION.agent, tell.agent)}` : "Answer"}<// + > + </form> + ${asker && followers && html`<${Receivers} receivers=${receiversOf({ task, asker, followers, tell })} />`} + <div class="needs-who"> + <${Asker} task=${task} asker=${asker} /> + ${!decision && html`<${Decision} asker=${asker} bare />`} + <${AskMessage} asker=${asker} /> + ${asker?.at && html`<span class="needs-ago" title=${`Asked on ${asker.at.slice(0, 16).replace("T", " ")} UTC`}>${agoWords(asker.at)}</span>`} + <${Huh} task=${task} ask=${ask} asker=${asker} /> + ${chatAgent && html`<${ChatButton} agent=${chatAgent} about=${task.title} />`} + </div> + <${Stale} task=${task} ask=${ask} asker=${asker} /> + <${Blocking} asker=${asker} /> + </li> + `; +} + +/** UNDER A TASK OF "Needs a person": what a person reads before they answer, from the task's own + * file (tasks-model.js `contextOf`), all behind "Context": what holds the task (`blocked-on:`), + * the notes of its log, the newest first, and the text under its title. The agent that has the + * task is a link to its chat. Closed until the person opens it: beside an ask stands the one + * act that answers it, and what explains the task does not compete with it (Jonas, 25 Nov 2026: + * "what is all this?! what am i meant to take from it"). */ +function ContextText({ task, about, notes }) { + return html` + ${task.blockedOn && html`<p class="needs-blocked">Blocked on: <${Linked} text=${task.blockedOn} /></p>`} + ${notes.map((note) => html`<p key=${note} class="needs-note"><${Linked} text=${note} /></p>`)} + ${about ? html`<p class="needs-about"><${Linked} text=${about} /></p>` : html`<p class="needs-about">The task has no text under its title.</p>`} + `; +} +function Context({ task }) { + const { about, notes } = useMemo(() => contextOf(task.source), [task.source]); + return html` + <div class="needs-context"> + <details> + <summary> + Context + ${ + agentHref(task.agent) && + html`<a + class="needs-asker" + href=${agentHref(task.agent)} + target="_blank" + rel="noreferrer" + title=${`${task.agent} has the task. Opens its chat in the Dash.`} + > + The task's agent: ${valueLabel(DIMENSION.agent, task.agent)}<${ExternalLinkIcon} /> + </a>` + } + </summary> + <${ContextText} task=${task} about=${about} notes=${notes} /> + <${Press} task=${task} held=${false} /> + </details> + </div> + `; +} + +// ── "Needs a person" on a phone: one ask at a time ── +// Jonas, 27 Nov 2026, in Slack, of the list at a phone's width: "Entering Text on mobile is v +// hard", "The page is impossible to parse", "Maybe a more \"one at a time\" tinder esque mobile +// interface where after one card is done the next comes", "Most info on that screen is not needed +// at all by default", "Most of the time I just want to either tap once to select an option or +// write something in or see more context and then do one of those things". +// +// So at a phone's width (`PHONE`) the list is a DECK (`NeedsDeck`): ONE ask fills the page. It +// shows the question, the offered options as buttons (ONE TAP ANSWERS), and a box to write in. +// Everything else (what each option costs, who asked, the agent's message, the task's notes) is +// behind "More context". An answer takes the card away and THE NEXT CARD COMES. The answer itself +// waits a few seconds first, under "Undo" (`heldAnswer`): one tap is easy to make by mistake. Then +// it goes the one way that every answer goes (`sendAnswer`). + +/** The width under which "Needs a person" is the deck: the width at which app.css stacks the page. */ +const PHONE = matchMedia("(max-width: 640px)"); +/** IN A FRAME OF ANOTHER APP OF THE MIND (`?embed=1`, index.html): the Dash's panel "Needs a + * person" shows this page so (Jonas, 27 Nov 2026, of that panel: "make it so we can give input + * there - it should be like the mobile view we have for this in the tasks app"). The page is the + * same Tasks app for the same member, with their own session: an answer goes the one way that + * every answer goes (`sendAnswer`). It is the deck at any width, since a panel can be dragged + * wider than a phone, and app.css takes the app's sidebar and bar away. */ +const EMBED = new URLSearchParams(location.search).get("embed") === "1"; +const usePhone = () => + useSyncExternalStore( + (listener) => { + PHONE.addEventListener("change", listener); + return () => PHONE.removeEventListener("change", listener); + }, + () => EMBED || PHONE.matches, + ); + +/** How long an answer given in the deck waits for "Undo" before it is sent. */ +const UNDO_MS = 5000; + +/** THE ONE ANSWER THAT WAITS FOR "Undo": what `sendAnswer` takes, with `key` (tasks-model.js + * `deckOf`) and `typed` (written in the box, not a tapped option). It is sent when its time is + * up, when the next answer is given, and when the page is left or hidden (`leave`, above): it is + * never dropped but by "Undo". It lives outside the deck's component, so that a turned phone or + * a look at the board does not lose it. */ +const heldAnswer = (() => { + const listeners = new Set(); + let held = null; + let timer = null; + const tell = () => { + for (const listener of listeners) listener(); + }; + const flush = () => { + if (!held) return; + const now = held; + held = null; + clearTimeout(timer); + sendAnswer(now); + tell(); + }; + return { + get: () => held, + subscribe: (listener) => (listeners.add(listener), () => listeners.delete(listener)), + flush, + hold(answer) { + flush(); + held = answer; + timer = setTimeout(flush, UNDO_MS); + tell(); + }, + /** Take the waiting answer back: nothing was written and nothing was sent. Answers it. */ + undo() { + const was = held; + held = null; + clearTimeout(timer); + tell(); + return was; + }, + }; +})(); + +/** THE PART OF THE SCREEN THAT IS SEEN, while `active`: `{ top, height }` in CSS pixels, from + * `visualViewport`. A phone's keyboard covers the bottom of the page and (on iOS) changes no + * layout: a box "at the bottom" is then under the keyboard. Only this says what is left. */ +function useSeenScreen(active) { + const [seen, setSeen] = useState(null); + useEffect(() => { + if (!active) return undefined; + const viewport = window.visualViewport; + const read = () => + setSeen( + viewport + ? { top: Math.max(0, viewport.offsetTop), height: viewport.height } + : { top: 0, height: innerHeight }, + ); + read(); + viewport?.addEventListener("resize", read); + viewport?.addEventListener("scroll", read); + addEventListener("resize", read); + return () => { + viewport?.removeEventListener("resize", read); + viewport?.removeEventListener("scroll", read); + removeEventListener("resize", read); + setSeen(null); + }; + }, [active]); + return seen; +} + +/** ABOVE THE DECK'S CARD: what became of the answer just given. While it waits: the answer and + * "Undo". Then the board's own word on its commit (`Board`: saving, saved, or not saved with + * "Try again"). */ +function DeckStatus({ held, save, onUndo }) { + if (held) + return html` + <p class="deck-status" role="status"> + <span>Answered: <strong>${held.answer.replace(/\s+/g, " ").trim()}</strong></span> + <button type="button" class="deck-undo" onClick=${onUndo}>Undo</button> + </p> + `; + if (save.state === "waiting" || save.state === "saving") + return html`<p class="deck-status" role="status"><${Spinner} />Saving your answer…</p>`; + if (save.state === "saved") + return html`<p class="deck-status" role="status"><${CheckIcon} />Saved</p>`; + if (save.state === "failed") + return html` + <p class="deck-status" data-failed role="alert"> + <span><${TriangleAlertIcon} />Not saved: ${save.error}</span> + <button type="button" class="deck-undo" onClick=${() => board.commitNow()}> + Try again + </button> + </p> + `; + return null; +} + +/** ONE CARD OF THE DECK: one ask of one task. + * + * - By default: the task's title (it opens the task), the question, the options of a choice as + * buttons, where the answer goes when another agent acts on it, and the box. + * - A TAP ON AN OPTION ANSWERS with that option. "More context" shows under each option what it + * costs and gives; a tap still answers. + * - WRITING: a tap in the box makes the card fill what is seen of the screen above the keyboard + * (`useSeenScreen`): the question, the box and "Send", and nothing else. So the box and the + * button are seen before the first key, and stay seen. The box's text is 16 px: under that, + * iOS zooms the page in at each focus. + * - `onAnswer(answer, typed)` takes the card away (`NeedsDeck`). */ +function DeckCard({ item, asker, followers, draft, onDraft, onAnswer, order }) { + const { task, ask } = item; + const { tell, answer, setAnswer } = useDraft(task, ask, draft); + const [more, setMore] = useState(false); + const [writing, setWriting] = useState(false); + const seen = useSeenScreen(writing); + const box = useRef(null); + const form = useRef(null); + const leaving = useRef(null); + const decision = useMemo(() => decisionsOf(task.source).get(ask), [task.source, ask]); + const { about, notes } = useMemo(() => contextOf(task.source), [task.source]); + const chatAgent = [asker?.agent, task.agent].find((each) => agentHref(each)); + useEffect(() => { + onDraft(answer); + }, [answer]); + useEffect(() => () => clearTimeout(leaving.current), []); + // the box grows with what is typed, up to a third of what is seen + useEffect(() => { + if (!box.current) return; + box.current.style.height = "auto"; + box.current.style.height = `${Math.min(box.current.scrollHeight + 2, writing && seen ? Math.max(72, seen.height / 3) : 160)}px`; + }, [answer, writing, seen?.height]); + const send = (words, typed) => { + if (!words.trim()) return; + clearTimeout(leaving.current); + box.current?.blur(); + setWriting(false); + onAnswer({ task, ask, answer: words, asker, followers, tell, typed }); + }; + return html` + <article + class="deck-card" + data-writing=${writing || undefined} + style=${writing && seen ? { top: `${seen.top}px`, height: `${seen.height}px` } : undefined} + aria-label=${`An ask of the task ${task.title}`} + > + <div class="deck-read"> + <div class="deck-task"> + <a + class="deck-task-title" + href=${EMBED ? boardTaskHref(task.path) : taskHref(task.path)} + target=${EMBED ? "_blank" : undefined} + rel=${EMBED ? "noreferrer" : undefined} + onClick=${(event) => { + // in a frame the task opens on the board, in a tab of its own: a panel has no + // room for the task's sheet + if (EMBED) return; + event.preventDefault(); + openTask(task.path); + }} + >${task.title}</a + > + ${pressOf(task).held && html`<${Badge} variant="secondary">Work is held<//>`} + </div> + <p class="deck-question"><${Linked} text=${ask} /></p> + <${Stale} task=${task} ask=${ask} asker=${asker} /> + </div> + ${ + decision && + html` + <ul class="deck-options" aria-label="Options: a tap answers"> + ${decision.options.map( + ({ name, tradeoff }) => html` + <li key=${name}> + <button + type="button" + class="deck-option" + data-recommended=${name === decision.recommend || undefined} + onClick=${() => send(name, false)} + > + <span class="deck-option-name" + >${name}${name === decision.recommend && html`<i>Recommended</i>`}</span + > + ${ + // a link's words alone: a link in a button would be a second thing to tap + more && + html`<span class="deck-option-why" + >${linkedParts(tradeoff) + .map((part) => part.text) + .join("")}</span + >` + } + </button> + </li> + `, + )} + </ul> + ` + } + ${ + tell && + html`<p class="needs-tell deck-tell"> + Your answer goes to${" "} + <a class="needs-link" href=${agentHref(tell.agent)} target="_blank" rel="noreferrer" + >${tell.agent}</a + > + ${" "}as a message from you, and onto the card. + </p>` + } + <form + ref=${form} + class="deck-answer" + data-idle=${(!writing && !answer.trim()) || undefined} + onSubmit=${(event) => { + event.preventDefault(); + send(answer, true); + }} + > + <textarea + ref=${box} + class="deck-box" + rows="1" + enterkeyhint="send" + placeholder=${decision ? "Or write an answer" : "Write your answer"} + aria-label=${`Your answer to: ${ask}`} + value=${answer} + onInput=${(event) => setAnswer(event.target.value)} + onFocus=${() => { + clearTimeout(leaving.current); + setWriting(true); + }} + onBlur=${() => { + // a tap on "Send" takes the focus first: the card keeps its place until the tap landed + clearTimeout(leaving.current); + leaving.current = setTimeout( + () => !form.current?.contains(document.activeElement) && setWriting(false), + 250, + ); + }} + onKeyDown=${(event) => { + if ( + event.key !== "Enter" || + event.shiftKey || + event.isComposing || + event.nativeEvent?.isComposing + ) + return; + event.preventDefault(); + event.currentTarget.form.requestSubmit(); + }} + ></textarea> + <div class="deck-answer-row"> + ${writing && html`<button type="button" class="deck-plain" onMouseDown=${(event) => event.preventDefault()} onClick=${() => box.current?.blur()}>Done</button>`} + <${Button} + type="submit" + className="deck-send" + disabled=${!answer.trim()} + onMouseDown=${(event) => event.preventDefault()} + > + ${tell ? `Send to ${valueLabel(DIMENSION.agent, tell.agent)}` : "Send"} + <//> + </div> + </form> + <button + type="button" + class="deck-plain deck-more-toggle" + aria-expanded=${more} + onClick=${() => setMore(!more)} + > + ${more ? "Less context" : "More context"} + </button> + ${ + more && + html` + <div class="deck-more"> + ${decision && html`<p class="needs-recommend"><strong>Recommended: ${decision.recommend}.</strong> <${Linked} text=${decision.why} /></p>`} + <${Blocking} asker=${asker} /> + <div class="needs-who"> + <${Asker} task=${task} asker=${asker} /> + <${Decision} asker=${asker} bare /> + <${AskMessage} asker=${asker} /> + ${asker?.at && html`<span class="needs-ago" title=${`Asked on ${asker.at.slice(0, 16).replace("T", " ")} UTC`}>${agoWords(asker.at)}</span>`} + <${Huh} task=${task} ask=${ask} asker=${asker} /> + ${ + // not in a frame of the Dash: the chat's sheet is the Dash in a frame itself + chatAgent && + !EMBED && + html`<${ChatButton} agent=${chatAgent} about=${task.title} />` + } + </div> + ${asker && followers && html`<${Receivers} receivers=${receiversOf({ task, asker, followers, tell })} />`} + <${ContextText} task=${task} about=${about} notes=${notes} /> + <div class="deck-more-end"><${Press} task=${task} held=${false} />${order}</div> + </div> + ` + } + </article> + `; +} + +/** THE DECK: "Needs a person" at a phone's width. `tasks` are in the page's order and `who` is the + * person whose asks are shown (null: everybody's), as in the list. Above the card: for whom, and + * which card of how many, with "back" and "Skip" (a swipe to the left skips too, and one to the + * right goes back). A card that is answered leaves, and the one after it is shown + * (tasks-model.js `deckAt`). */ +function NeedsDeck({ tasks, every, people, who, askers, followers, save, view }) { + const held = useSyncExternalStore(heldAnswer.subscribe, heldAnswer.get, heldAnswer.get); + const items = deckOf(tasks, who).filter((item) => item.key !== held?.key); + const [at, setAt] = useState({ key: null, index: 0 }); + const index = deckAt(items, at); + const item = items[index]; + const drafts = useRef(new Map()); + // the card that is shown is remembered, so that it stays while the list around it changes + useEffect(() => { + if (item && (item.key !== at.key || index !== at.index)) setAt({ key: item.key, index }); + }, [item?.key, index]); + const go = (step) => + items.length > 1 && setAt({ key: null, index: (index + step + items.length) % items.length }); + const swipe = useRef(null); + const order = html` + <${NativeSelect} + size="sm" + aria-label="Order" + value=${view.order} + onChange=${(event) => setView({ order: event.target.value === NEEDS_ORDERS[0].id ? undefined : event.target.value })} + > + ${NEEDS_ORDERS.map(({ id, label }) => html`<${NativeSelectOption} key=${id} value=${id}>${label}<//>`)} + <//> + `; + return html` + <section class="deck" aria-label="Asks that need a person, one at a time"> + <div class="deck-head"> + <div class="deck-for" role="group" aria-label="Whom the asks are for"> + <button + class="needs-chip" + aria-pressed=${who === null} + onClick=${() => setView({ for: undefined })} + > + Everyone <i>${every.length}</i> + </button> + ${people.map( + ([name, count]) => html` + <button + key=${name} + class="needs-chip" + aria-pressed=${who === name} + onClick=${() => setView({ for: who === name ? undefined : name || "-" })} + > + ${name || "Nobody named"} <i>${count}</i> + </button> + `, + )} + </div> + ${ + item && + html` + <div class="deck-step"> + <button + type="button" + class="deck-plain" + aria-label="The card before" + disabled=${items.length < 2} + onClick=${() => go(-1)} + > + ‹ + </button> + <span aria-live="polite">${index + 1} of ${items.length}</span> + <button + type="button" + class="deck-plain" + disabled=${items.length < 2} + onClick=${() => go(1)} + > + Skip › + </button> + </div> + ` + } + </div> + <${DeckStatus} + held=${held} + save=${save} + onUndo=${() => { + const was = heldAnswer.undo(); + if (!was) return; + if (was.typed) drafts.current.set(was.key, was.answer); + setAt({ key: was.key, index }); + }} + /> + ${ + item + ? html` + <div + class="deck-swipe" + onTouchStart=${(event) => { + const touch = event.touches.length === 1 && event.touches[0]; + // a swipe in the box moves its caret, and one over the chips scrolls them + swipe.current = + touch && !event.target.closest("textarea, select, .deck-more") + ? { x: touch.clientX, y: touch.clientY } + : null; + }} + onTouchEnd=${(event) => { + const from = swipe.current; + const touch = event.changedTouches[0]; + swipe.current = null; + if (!from || !touch) return; + const [dx, dy] = [touch.clientX - from.x, touch.clientY - from.y]; + if (Math.abs(dx) > 70 && Math.abs(dx) > 2 * Math.abs(dy)) go(dx < 0 ? 1 : -1); + }} + > + <${DeckCard} + key=${item.key} + item=${item} + asker=${askerOf(askers, item.task, item.ask)} + followers=${followers} + draft=${drafts.current.get(item.key)} + onDraft=${(words) => drafts.current.set(item.key, words)} + onAnswer=${(answer) => { + drafts.current.delete(item.key); + heldAnswer.hold({ ...answer, key: item.key }); + }} + order=${order} + /> + </div> + ` + : html`<p class="deck-done">Nothing else waits${who ? ` for ${who}` : ""}.</p>` + } + <${Answered} /> + </section> + `; +} + +/** "Needs a person" (`?needs=person`), in place of the board: each task that is not done and asks a + * person something (`human-ask:`), 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 also holds the task + * (`blocked-on:`) is only read. A task that is held and asks nothing is not listed: it waits for + * no person. The board's other filters still narrow it. */ +function NeedsPage({ state, tasks: every, filtered, view }) { + const askers = useAskers(every); + const followers = useFollowers(); + const phone = usePhone(); + const people = peopleAsked(every); + // a name in the address that no ask has (the last ask for that person was answered): every task + const who = people.some(([name]) => name === view.needsFor) ? view.needsFor : null; + const tasks = orderNeeds( + needsFor(every, who), + view.order, + (task, ask) => askerOf(askers, task, ask)?.at, + ); + // which of a task's asks are for somebody else: shown, and marked so + const others = (task) => (who === null ? [] : task.humanAsk.filter((ask) => !askIsFor(ask, who))); + 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` + <${Answered} /> + <${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. An ask is answered + here. A done task is not listed, and neither is a task that is held and asks nothing. + <//> + <//> + <//> + `; + // at a phone's width: one ask at a time (`NeedsDeck`) + if (phone) + return html`<${NeedsDeck} + tasks=${tasks} + every=${every} + people=${people} + who=${who} + askers=${askers} + followers=${followers} + save=${state.save} + view=${view} + />`; + return html` + <div class="needs-bar"> + <div class="needs-for" role="group" aria-label="Whom the asks are for"> + <button + class="needs-chip" + aria-pressed=${who === null} + onClick=${() => setView({ for: undefined })} + > + Everyone <i>${every.length}</i> + </button> + ${people.map( + ([name, count]) => html` + <button + key=${name} + class="needs-chip" + aria-pressed=${who === name} + onClick=${() => setView({ for: who === name ? undefined : name || "-" })} + > + ${name || "Nobody named"} <i>${count}</i> + </button> + `, + )} + </div> + <div class="needs-bar-end"> + <${NativeSelect} + size="sm" + aria-label="Order" + value=${view.order} + onChange=${(event) => setView({ order: event.target.value === NEEDS_ORDERS[0].id ? undefined : event.target.value })} + > + ${NEEDS_ORDERS.map(({ id, label }) => html`<${NativeSelectOption} key=${id} value=${id}>${label}<//>`)} + <//> + <a + class="needs-talk" + href=${huhHref(domain, talkDraft({ domain, repo: REPO_NAME, tasks, who }))} + target="_blank" + rel="noreferrer" + title="Opens a new agent's message box with a draft that asks it to go through these asks with you. Nothing is sent until you send it. The draft tells the agent to answer and approve nothing: you answer here." + > + <${BotIcon} />Talk these through + </a> + </div> + </div> + <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}<//>`} + <${Press} task=${task} select=${false} /> + </div> + <ul class="needs-asks" aria-label="Asks"> + ${task.humanAsk + .filter((ask) => !others(task).includes(ask)) + .map( + (ask) => + html`<${Ask} + key=${ask} + task=${task} + ask=${ask} + asker=${askerOf(askers, task, ask)} + followers=${followers} + />`, + )} + </ul> + ${ + others(task).length > 0 && + html` + <details class="needs-others"> + <summary> + ${others(task).length === 1 ? "One more ask, for somebody else" : `${others(task).length} more asks, for somebody else`} + </summary> + <ul class="needs-asks" aria-label="Asks for somebody else"> + ${others(task).map((ask) => html`<${Ask} key=${ask} task=${task} ask=${ask} asker=${askerOf(askers, task, ask)} followers=${followers} />`)} + </ul> + </details> + ` + } + <${Context} task=${task} /> + </li> + `, + )} + </ul> + <${Answered} /> + `; +} + +/** ON A CARD THAT WAITS FOR A PERSON: the mark (tasks-model.js `waitsForAPerson`), always shown, + * under the title. It says who is asked when the asks name someone ("Needs Jonas"), and how many + * asks there are when there are several. It opens the task's sheet, where the asks are answered. */ +function NeedsMark({ task }) { + const waits = waitsForAPerson(task); + if (!waits) return null; + return html` + <a + class="task-needs" + href=${taskHref(task.path)} + draggable="false" + title=${`${task.humanAsk.join("\n")}\n\nOpens the task, where you answer.`} + onClick=${(event) => { + if (event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) + return; + event.preventDefault(); + openTask(task.path); + }} + > + <i aria-hidden="true"></i> + <span class="task-needs-who">${waits.label}</span> + ${waits.asks > 1 && html`<span class="task-needs-count">${waits.asks} asks</span>`} + </a> + `; +} + +/** IN A TASK'S SHEET, BEFORE ITS TITLE AND PROPERTIES: what the task asks a person, each ask whole + * with who asked it and the answer box of "Needs a person" (`Ask`: the one format, `answerAsk`), + * and what holds the task (`blocked-on:`). A link to a card (`?task=<path>`) so opens on the ask. + * A task with neither shows nothing here. */ +function TaskAsks({ task }) { + const askers = useAskers(task.humanAsk.length > 0 ? [task] : []); + const followers = useFollowers(); + const answered = useAnswered().some((row) => row.path === task.path); + const waits = waitsForAPerson(task); + const count = task.humanAsk.length; + if (count === 0 && !task.blockedOn && !answered) return null; + return html` + <section + class="task-asks" + data-waits=${Boolean(waits) || undefined} + aria-label="What this task waits for" + > + ${ + count > 0 && + html` + <h3 class="task-asks-title"> + <i aria-hidden="true"></i> + ${waits ? `${waits.label}: ${count === 1 ? "one answer" : `${count} answers`}` : "Still asked, though the task is done"} + </h3> + <ul class="needs-asks" aria-label="Asks"> + ${task.humanAsk.map((ask) => html`<${Ask} key=${ask} task=${task} ask=${ask} asker=${askerOf(askers, task, ask)} followers=${followers} />`)} + </ul> + ` + } + ${task.blockedOn && html`<p class="needs-blocked">Blocked on: <${Linked} text=${task.blockedOn} /></p>`} + <${Answered} path=${task.path} /> + </section> + `; +} + +/** 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} + closed=${column.id === "done" && !filtered} + 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. + * `closed`: the cell shows no card until a person asks for them. That is the Done column with no + * search and no filter on (Misha, 23 Nov 2026: done cards off the default view): the head keeps + * its count, one press shows the cards, and a card can still be dropped here. */ +function Cell({ + column, + columns, + tasks, + all, + unsaved, + view, + group, + composing, + compose, + closeComposer, + create, + move, + closed, +}) { + const [over, setOver] = useState(false); + const [more, setMore] = useState(CELL_PAGE); + const [opened, setOpened] = useState(false); + const limit = closed && !opened ? 0 : more; + const setLimit = (next) => { + setOpened(true); + setMore(next); + }; + 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 === 0 ? CELL_PAGE : limit + CELL_PAGE)} + > + ${ + limit === 0 + ? `Show ${tasks.length === 1 ? "the 1 task" : `the ${tasks.length} tasks`} in ${column.label}` + : `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} + data-needs=${Boolean(waitsForAPerson(task)) || 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> + <${NeedsMark} task=${task} /> + <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 (processors/ of /repos/docs): the +// page names them exactly as the Docs page does (/processors.json, ../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] = await Promise.all([ + import("@iterate-com/ui/components/docs-editor/docs-editor"), + fetch("/processors.json"), + ]); + if (!answer.ok) throw new Error(`/processors.json answered ${answer.status}`); + // where the processors' code is (a repo of this mind), and the package pins of that repo + const processors = await answer.json(); + const manifestText = await itx.repos.get(processors.repo).readFile("package.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", processors.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; +}; +/** The board with one task open and nothing else of this view: the link out of a frame. */ +const boardTaskHref = (path) => { + const next = new URLSearchParams(); + if (REPO_NAME !== DEFAULT_REPO_NAME) next.set("repo", REPO_NAME); + next.set("task", path); + return `${location.pathname}?${next}`; +}; +/** 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"> + <${TaskAsks} task=${task} /> + <${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
M public/tasks-model.js
@@ -1,6 +1,7 @@ // 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 todo/ in a repo of the mind (`TASKS_DIR` below), and what the board knows of -// it is in the file's frontmatter and its first heading: +// markdown file under todo/ 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 @@ -27,11 +28,14 @@ // 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 (../tests/tasks-model.test.mjs) both load this file as it is. +// The page (app.js) and the test (../tasks-model.test.mjs) both load this file as it is. -/** THE FOLDER OF A REPO WHOSE MARKDOWN FILES ARE ITS TASKS. The board shows this folder of the - * repo it is pointed at, /repos/task-board for a mind's own board, and of any other repo that - * `?repo=` names, so a repo may keep tasks beside its code. */ +/** 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/task-board"; export const TASKS_DIR = "todo"; /** The board's columns, in order. A task whose status is none of these (or of their other @@ -89,14 +93,9 @@ return whole.replace(/-+$/g, ""); } -/** Whether the board shows this file of the repo: markdown under the tasks folder. A README.md - * there says how the folder is used, so it is no task. */ +/** 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) && - path.split("/").at(-1) !== "README.md" - ); + return path.startsWith(`${TASKS_DIR}/`) && /\.(?:md|markdown)$/i.test(path); } // ── the frontmatter ── @@ -442,23 +441,26 @@ /** 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 the Dash's own - * (@iterate-com/ui `dashPaths`): a path that a URL's pathname can carry goes in the pathname, any - * other in `?contextPath=`. */ + * 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(); + return dashPath("agents", agent); +} +function dashPath(page, context) { + const path = String(context ?? "").trim(); if (!path.startsWith("/") || path === "/") return null; const sayable = path .slice(1) .split("/") .every((part) => part && part !== "." && part !== ".."); const href = sayable - ? `/agents${path + ? `/${page}${path .split("/") .map(encodeURIComponent) .join("/") .replace(/%(?:40|3A|24|26|2B|2C|3B|3D)/g, decodeURIComponent)}` - : `/agents?${new URLSearchParams({ contextPath: path }) + : `/${page}?${new URLSearchParams({ contextPath: path }) .toString() .replaceAll("+", "%20") .replace(/%(?:2F|40|3A|2C)/g, decodeURIComponent)}`; @@ -466,6 +468,65 @@ return href.replace(/[.,:]$/, (last) => ({ ".": "%2E", ",": "%2C", ":": "%3A" })[last]); } +/** WHERE ONE EVENT OF A CONTEXT IS IN THE DASH: the raw view of the context (`/contexts/<path>`) + * with that event open in its inspector, which the view takes from `?view={"event":<offset>}` + * (@iterate-com/ui `ContextViewState`). With no origin; null when `path` is no context path or + * `offset` is no offset. The agent's chat has no address for one message: this is the nearest + * thing that has one. Like any address of the Dash it grants nothing: the Dash is for members. */ +export function eventPath(path, offset) { + const href = dashPath("contexts", path); + if (!href || !Number.isInteger(offset) || offset < 0) return null; + return `${href}${href.includes("?") ? "&" : "?"}${new URLSearchParams({ view: JSON.stringify({ event: offset }) })}`; +} + +/** THE DRAFT BEHIND "huh?": the words that ask a NEW agent to explain one ask of a task, for a + * person who wants the background and does not want to take the asker off its work. It names the + * ask, the task (its link on the board, and its file and repo, which an agent reads with `itx`) + * and who asked. `asker` is the ask's row of `itx.config.taskAskers` (`agent`, or `by` for a + * person, and `at`); with none, the draft says so and names the task's own agent. The draft is + * never sent by the page: the person reads it, changes it and sends it. */ +export function huhDraft({ + domain, + repo = TASKS_REPO.split("/").at(-1), + path, + title, + ask, + asker, + taskAgent, +}) { + const query = new URLSearchParams( + repo === TASKS_REPO.split("/").at(-1) ? { task: path } : { repo, task: path }, + ); + const when = asker?.at ? ` (on ${asker.at.slice(0, 16).replace("T", " ")} UTC)` : ""; + const asked = asker?.agent + ? `The agent that asked: ${asker.agent}${when}` + : asker?.by && !asker.by.startsWith("/") + ? `Asked by the person ${asker.by}${when}, on the task board` + : `Who asked is not recorded.${taskAgent ? ` The agent that has the task: ${taskAgent}` : ""}`; + return [ + "Explain this question to me. A task on the task board asks a person to decide it, and I want the background before I answer.", + "", + `The question: "${ask}"`, + `The task: ${title ? `"${title}", ` : ""}https://tasks.${domain}/?${query} (the file ${path} of the repo /repos/${repo})`, + asked, + "", + "Read the task's file and what it points to. Then tell me in a few lines what is being decided, why it is asked, and what each answer would lead to.", + "Do not answer the question on the board, do not change the task, and do not message the agent that asked: I do not want to take it off its work.", + ].join("\n"); +} + +/** Longest draft that an address carries to the Dash's home, where the box that starts a new agent + * takes it. */ +export const HUH_DRAFT_MAX = 4000; + +/** WHERE "huh?" GOES: the Dash's home, where the box that starts a new agent holds the draft, + * unsent. The new agent is the mind's own, which reads the task with `itx`. The draft is in the + * address's HASH: a browser sends a hash to no server and in no Referer, so the ask's words stay + * in the browser of the member who clicked. */ +export function huhHref(domain, draft) { + return `https://dash.${domain}/#draft=${encodeURIComponent(String(draft).slice(0, HUH_DRAFT_MAX))}`; +} + /** A task's values in one dimension: none, one, or for tags several. */ export const valuesOf = (task, id) => [task[id]].flat().filter(Boolean); @@ -507,20 +568,108 @@ // ── 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`). */ +/** The tasks that are not done and ask a person something, by title. A task that is held and + * asks nothing (`blocked-on:` a deploy, a review, another task) waits for no person: it is not + * here (Misha, 23 Nov 2026, could not tell which rows of the list still mattered). What a + * person must decide is an ask. 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)) + .filter((task) => waitsForAPerson(task)) .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), ); } +// a word that can start an ask before a colon and is no person's name +const NOT_A_NAME = new Set([ + "note", + "question", + "ask", + "decision", + "todo", + "fyi", + "update", + "blocked", + "option", + "options", + "context", + "warning", + "important", + "action", + "yes", + "no", +]); +const NAME = "\\p{Lu}\\p{Ll}[\\p{L}'’-]{0,22}"; +const BETWEEN_NAMES = "\\s*[,/&]\\s*|\\s+(?:and|or)\\s+"; +const ADDRESSED = new RegExp(`^\\s*(${NAME}(?:(?:${BETWEEN_NAMES})${NAME}){0,3})\\s*:\\s`, "u"); + +/** WHO AN ASK IS FOR, when it says so: an ask is written "Jonas: delete the 5 kept sign-ins, yes + * or no?" (tasks.md, "Asks and answers"), so the names before its first colon are the people it + * asks: ["Jonas"], or ["Jonas", "Misha"] for "Jonas or Misha: …". An ask that starts with no + * name answers []. This only reads the ask: who MAY answer it is every member, as before. */ +export function askedOf(ask) { + const names = ADDRESSED.exec(String(ask ?? ""))?.[1].split(new RegExp(BETWEEN_NAMES, "u")) ?? []; + return names.some((name) => NOT_A_NAME.has(name.toLowerCase())) ? [] : names; +} + +/** THE MARK OF A CARD THAT WAITS FOR A PERSON, or null for a card that has none. The rule is + * `needsAPerson`'s: the task is not done and has an ask. `people` are the names that its asks + * give (`askedOf`), each once, in the asks' order; `label` is the mark's words, "Needs Jonas", or + * "Needs a person" when no ask names one; `asks` is how many asks are open. A task that is held + * and asks nothing (`blocked-on:`) has no mark: it waits for no person. */ +export function waitsForAPerson(task) { + if (task.column === "done" || task.humanAsk.length === 0) return null; + const people = [...new Set(task.humanAsk.flatMap(askedOf))]; + return { asks: task.humanAsk.length, people, label: `Needs ${people.join(", ") || "a person"}` }; +} + +// a Markdown link `[words](https://…)` (its address may hold one pair of brackets), or a bare address +const LINK = + /\[([^[\]]+)\]\((https?:\/\/[^\s()]+(?:\([^\s()]*\)[^\s()]*)*)\)|https?:\/\/[^\s<>"`]+/g; + +/** Whether the page may make a link of this address: http or https, and no user name or password + * in it. Any other scheme (`javascript:`) stays text. */ +function linkable(href) { + try { + const url = new URL(href); + return ( + (url.protocol === "https:" || url.protocol === "http:") && !url.username && !url.password + ); + } catch { + return false; + } +} + +/** ONE LINE THAT A PERSON READS (an ask, what holds a task), AS TEXT AND LINKS: a list of + * `{ text }` and `{ text, href }`. A Markdown link `[words](https://…)` is its words; a bare + * `https://…` is itself, without the full stop or the bracket that ends the sentence around it. + * No other Markdown is read. The line itself is never changed: an ask is named by its whole text + * (`answerAsk`), and the page only shows it this way. */ +export function linkedParts(line) { + const text = String(line ?? ""); + const parts = []; + let at = 0; + for (const match of text.matchAll(LINK)) { + let [whole, words, href] = match; + if (!href) { + href = whole.replace(/[.,;:!?'*_]+$/, ""); + // a closing bracket that the address does not open belongs to the sentence + while (/[)\]]$/.test(href) && href.split(/[)\]]/).length > href.split(/[([]/).length) + href = href.slice(0, -1).replace(/[.,;:!?'*_]+$/, ""); + whole = words = href; + } + if (!linkable(href)) continue; + if (match.index > at) parts.push({ text: text.slice(at, match.index) }); + parts.push({ text: words, href }); + at = match.index + whole.length; + } + if (at < text.length) parts.push({ text: text.slice(at) }); + return parts; +} + 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"; @@ -534,9 +683,39 @@ * `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 cut = frontWithoutAsk(source, ask); + if (!cut) return source; + 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})`; + return withFront(cut, withLineUnder(source.slice(cut.bodyAt), ANSWERS_HEADING, line, cut.eol)); +} + +/** THE FILE WITH ONE ASK TAKEN OFF, and every other byte as it was: the ask's line leaves + * `human-ask:` (the key too, when it was the last ask), and nothing is written under + * `## Answers`, because nobody answered. For an ask that events overtook (the pull request it + * asked about is merged). The caller says why in a note. An ask that the file does not have + * changes nothing. */ +export function withdrawAsk(source, ask) { + const cut = frontWithoutAsk(source, ask); + return cut ? withFront(cut, source.slice(cut.bodyAt)) : source; +} + +/** THE FILE WITH ONE ASK WRITTEN AGAIN in other words (`to`), as the last ask; every other byte + * as it was. An ask that the file does not have, and an empty `to`, change nothing. */ +export function rewordAsk(source, ask, to) { + const next = withdrawAsk(source, ask); + return next === source || !String(to ?? "").trim() ? source : addAsk(next, to); +} + +/** The frontmatter's lines without one ask (`{ front, bodyAt, eol }`), or null when the file does + * not have that ask. */ +function frontWithoutAsk(source, ask) { const { exists, lines, bodyAt, eol } = frontmatterOf(source); const keyAt = lines.findIndex((line) => ASK_KEYS.includes(keyOf(line))); - if (!exists || keyAt < 0) return source; + if (!exists || keyAt < 0) return null; const front = [...lines]; const rest = front[keyAt].slice(front[keyAt].indexOf(":") + 1).trim(); const inline = /^\[([\s\S]*)\]$/.exec(rest); @@ -546,13 +725,13 @@ .map((item) => item.trim()) .filter(Boolean); const found = items.findIndex((item) => scalar(item, true) === ask); - if (found < 0) return source; + if (found < 0) return null; 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; + if (scalar(rest, true) !== ask) return null; front.splice(keyAt, 1); } else { // the `- ` lines under the key @@ -561,20 +740,18 @@ const found = front .slice(keyAt + 1, end) .findIndex((line) => scalar(/^\s*-\s+(.*)$/.exec(line)[1], true) === ask); - if (found < 0) return source; + if (found < 0) return null; // 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)}`; + return { front, bodyAt, eol }; } +/** A file from its frontmatter's lines and its text. */ +const withFront = ({ front, eol }, body) => + `---${eol}${front.length > 0 ? `${front.join(eol)}${eol}` : ""}---${eol}${body}`; + /** 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. */ @@ -762,7 +939,7 @@ const wantedColumns = statuses.length > 0 ? new Set(statuses.map(columnOf)) : null; return tasks.filter((task) => { if (wantedColumns && !wantedColumns.has(task.column)) return false; - // "" is the folder at the top of todo/, null is no folder asked for + // oxlint-disable-next-line iterate/simple-truthiness-check -- "" is the folder at the top of todo/, null is no folder asked for if (folder !== null && task.folder !== folder && !task.folder.startsWith(`${folder}/`)) return false; for (const { id } of named) @@ -795,11 +972,15 @@ /** 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 = { + decision: (source, change) => addDecision(source, change), + tell: (source, change) => addTell(source, change), 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), + withdraw: (source, change) => withdrawAsk(source, change.ask), + reword: (source, change) => rewordAsk(source, change.ask, change.to), blocked: (source, change) => setBlockedOn(source, change.blockedOn), note: (source, change) => addNote(source, change), key: (source, change) => setPlainKey(source, change.key, change.value), @@ -808,6 +989,8 @@ /** `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: "withdraw", path, ask }` (`withdrawAsk`), `{ kind: "reword", path, ask, to }` + * (`rewordAsk`), * `{ 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 @@ -846,11 +1029,31 @@ `${change.path}\0answer\0${change.ask}`, `${change.path}: answered "${shortOf(change.ask)}"`, ); + else if (change.kind === "tell") + last.set( + `${change.path}\0tell\0${change.ask}`, + `${change.path}: "${shortOf(String(change.ask))}" is answered by a message to ${change.agent}`, + ); + else if (change.kind === "decision") + last.set( + `${change.path}\0decision\0${change.ask}`, + `${change.path}: the options of "${shortOf(String(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 === "withdraw") + last.set( + `${change.path}\0withdraw\0${change.ask}`, + `${change.path}: no longer asks "${shortOf(String(change.ask))}"`, + ); + else if (change.kind === "reword") + last.set( + `${change.path}\0reword\0${change.ask}`, + `${change.path}: asks again, as "${shortOf(String(change.to))}"`, + ); else if (change.kind === "blocked") last.set( `${change.path}\0blocked`, @@ -877,4 +1080,494 @@ const said = [...last.values()]; if (said.length === 1) return `tasks: ${said[0]}`; return [`tasks: ${said.length} changes`, "", ...said.map((line) => `- ${line}`)].join("\n"); +} + +// ── "Needs a person": its order, whom it asks, and what a person reads before they answer ── + +/** The orders of "Needs a person" (`?order=`), the first one when the address names none. */ +export const NEEDS_ORDERS = [ + { id: "pressing", label: "Most pressing first" }, + { id: "oldest", label: "Longest waiting first" }, + { id: "newest", label: "Newest ask first" }, + { id: "title", label: "By title" }, +]; + +/** WHOM THE OPEN ASKS NAME, for the filter of "Needs a person": `[[name, tasks], …]` by how many + * tasks ask that person, then `["", tasks]` last for the tasks with an ask that names nobody (left + * out when there is none). `tasks` are those that wait for a person (`needsAPerson`). */ +export function peopleAsked(tasks) { + const count = new Map(); + let unnamed = 0; + for (const task of tasks) { + for (const name of new Set(task.humanAsk.flatMap(askedOf))) + count.set(name, (count.get(name) ?? 0) + 1); + if (task.humanAsk.some((ask) => askedOf(ask).length === 0)) unnamed += 1; + } + const named = [...count].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0])); + return unnamed > 0 ? [...named, ["", unnamed]] : named; +} + +/** Whether an ask is for this person: it names them, or, for "" (nobody), it names no one. */ +export const askIsFor = (ask, who) => + who === "" ? askedOf(ask).length === 0 : askedOf(ask).includes(who); + +/** "Needs a person" FOR ONE PERSON: the tasks with an ask for `who` (`askIsFor`), each as it is, + * with all its asks. `who` null or undefined: every task. */ +export function needsFor(tasks, who) { + return who === null || who === undefined + ? tasks + : tasks.filter((task) => task.humanAsk.some((ask) => askIsFor(ask, who))); +} + +/** "Needs a person" IN AN ORDER (`NEEDS_ORDERS`). `askedAt(task, ask)` answers when the ask was + * asked, as an ISO time, or nothing when no one knows. A task's time is that of its oldest ask + * ("oldest") or of its newest ("newest"); a task with no known time comes last, and equal tasks + * keep the order they came in (by title: `needsAPerson`). "pressing" is by `pressOf`: the + * priority, then the tasks whose work is held, then the longest wait. Any other order changes + * nothing. */ +export function orderNeeds(tasks, order, askedAt) { + if (order === "pressing") { + // by priority, then the tasks whose work is held, then the longest wait + const waited = orderNeeds(tasks, "oldest", askedAt); + return waited + .map((task, index) => ({ task, index, press: pressOf(task) })) + .sort( + (a, b) => a.press.rank - b.press.rank || b.press.held - a.press.held || a.index - b.index, + ) + .map(({ task }) => task); + } + if (order !== "oldest" && order !== "newest") return tasks; + const timeOf = (task) => { + const times = task.humanAsk + .map((ask) => Date.parse(askedAt(task, ask) ?? "")) + .filter(Number.isFinite); + return times.length === 0 ? null : order === "oldest" ? Math.min(...times) : Math.max(...times); + }; + return tasks + .map((task, index) => ({ task, index, time: timeOf(task) })) + .sort( + (a, b) => + (a.time === null) - (b.time === null) || + (order === "oldest" ? a.time - b.time : b.time - a.time) || + a.index - b.index, + ) + .map(({ task }) => task); +} + +/** "Needs a person" ONE ASK AT A TIME, for a phone (app.js `NeedsDeck`): `[{ key, task, ask }, …]`, + * the tasks in the order they came in, and each task's asks in the card's own order. With `who`, + * only the asks for that person (`askIsFor`); null or undefined: every ask. `key` names one ask + * of one task, and stays the same while the list around it changes. */ +export function deckOf(tasks, who) { + const all = who === null || who === undefined; + return tasks.flatMap((task) => + task.humanAsk + .filter((ask) => all || askIsFor(ask, who)) + .map((ask) => ({ key: `${task.path}\n${ask}`, task, ask })), + ); +} + +/** WHICH CARD THE DECK SHOWS: an index into `items` (`deckOf`), or -1 for an empty deck. `at` is + * the card shown before, `{ key, index }`. That card, wherever it is now. When it is gone (it was + * answered, or an agent took it off), the card that took its place: the same index, so THE NEXT + * CARD COMES; after the last card, the first one again (what was skipped). */ +export function deckAt(items, at) { + if (items.length === 0) return -1; + const found = items.findIndex((item) => item.key === at?.key); + if (found !== -1) return found; + const index = Number.isInteger(at?.index) ? at.index : 0; + return index < 0 || index >= items.length ? 0 : index; +} + +/** How long ago, in a few letters: "now", "5 min", "3 h", "2 d", "3 wk". "" for no time. */ +export function agoOf(at, now = Date.now()) { + const then = Date.parse(at ?? ""); + if (!Number.isFinite(then)) return ""; + const minutes = Math.max(0, Math.floor((now - then) / 60_000)); + if (minutes < 1) return "now"; + if (minutes < 60) return `${minutes} min`; + if (minutes < 60 * 24) return `${Math.floor(minutes / 60)} h`; + if (minutes < 60 * 24 * 14) return `${Math.floor(minutes / (60 * 24))} d`; + return `${Math.floor(minutes / (60 * 24 * 7))} wk`; +} + +/** WHAT A PERSON READS BEFORE THEY ANSWER, from the task's own text: `about`, the text between its + * title and its first `## ` heading, cut at `max` characters at a word; and `notes`, the newest + * lines under `## Log`, newest first, each without its `- `. Both are plain text as the file has + * it (the page shows them with `linkedParts`, and reads no other Markdown). */ +export function contextOf(source, { max = 900, notes: most = 3 } = {}) { + const { bodyAt } = frontmatterOf(String(source ?? "")); + const lines = String(source ?? "") + .slice(bodyAt) + .split(/\r?\n/); + const title = headingIn(lines.join("\n"))?.at ?? -1; + const next = lines.findIndex((line, at) => at > title && /^##\s/.test(line)); + const text = lines + .slice(title + 1, next < 0 ? undefined : next) + .join("\n") + .replace(/\n{3,}/g, "\n\n") + .trim(); + const cut = text.length > max ? `${text.slice(0, max).replace(/\s+\S*$/, "")} …` : text; + const log = lines.findIndex((line) => line.trim() === LOG_HEADING); + const noted = []; + for (const line of log < 0 ? [] : lines.slice(log + 1)) { + if (/^##?\s/.test(line)) break; + const item = /^-\s+(.*)$/.exec(line); + if (item) noted.push(item[1].trim()); + } + return { about: cut, notes: noted.slice(-most).reverse() }; +} + +/** THE DRAFT BEHIND "Talk these through": the words that ask a NEW agent to go through the open + * asks with the person, one at a time. It names the tasks (at most `most`), and how the agent + * reads the asks itself. It tells the agent to answer nothing and to approve nothing: the person + * answers on the board. That is an instruction in a draft, and no guard: the new agent is a + * member's own, with the mind's reach. The page never sends the draft. */ +export function talkDraft({ domain, repo = TASKS_REPO.split("/").at(-1), tasks, who, most = 12 }) { + const call = repo === TASKS_REPO.split("/").at(-1) ? "" : `{ repo: "${repo}" }`; + const asks = tasks.reduce((sum, task) => sum + task.humanAsk.length, 0); + return [ + `Go through the open questions of the task board with me${who ? ` (those for ${who})` : ""}. ${asks === 1 ? "One question waits" : `${asks} questions wait`} for a person's answer, on ${tasks.length === 1 ? "one task" : `${tasks.length} tasks`}.`, + "", + `Read them with itx.config.taskAskers(${call}) (each open ask and who asked it) and itx.config.taskBoard(${call}) (each task, and "needsAPerson"). Read a task's file in /repos/${repo} for its background.`, + `The page where I answer: https://tasks.${domain}/?${new URLSearchParams(repo === TASKS_REPO.split("/").at(-1) ? { needs: "person" } : { repo, needs: "person" })}`, + "", + "The tasks:", + ...tasks.slice(0, most).map((task) => `- ${task.path}: ${task.title}`), + ...(tasks.length > most ? [`- and ${tasks.length - most} more`] : []), + "", + "Start with a short list, the ones that hold the most work first. Then take them one at a time: what is being decided, why it is asked, what each answer leads to, and what you would answer.", + "Do not answer a question on the board, do not approve anything for me, do not change a task, and do not message the agents that asked. I answer on the board myself.", + ].join("\n"); +} + +// ── an answer: who hears it, and what the asker is told ── + +/** WHICH AGENTS HEAR AN ANSWER TO AN ASK, and how: `[{ agent, why, hears }]`, the asker first. + * `asker` is the ask's row of `itx.config.taskAskers`; `followers` are the rows of + * `itx.config.taskFollowers` (`{ agent, follows, only }`: `follows` is a file or "every task"). + * - the agent that asked (`why: "asked"`): by the card's commit when it follows the card + * (`hears: "card"`), else by a message that the page sends it (`hears: "message"`); + * - the agent that has the task, when it is another one and follows the card + * (`why: "has the task"`, `hears: "card"`). When no agent is known to have asked, it is + * listed also when it does not follow the card, and then gets the message. + * - the agent that ACTS on the answer, when the ask names one (`tell`, tasks-model.js + * `tellsOf`; `why: "acts on it"`): first, and always by a message that the page sends it + * from the person (`tellMessage`), whether it follows the card or not. + * An agent that follows every task (a manager) is not listed for that alone: an answer goes to + * the agent that asked, and through nobody. */ +export function receiversOf({ task, asker, followers = [], tell }) { + const follows = (agent, wide) => + followers.some( + (row) => + row.agent === agent && + (row.follows === task.path || + (wide && row.follows === "every task" && (!row.only || row.only.includes("human-ask")))), + ); + const isPath = (value) => typeof value === "string" && value.startsWith("/"); + const out = []; + // the agent that acts on the answer gets the person's own words, from the person: a line of a + // card's diff is no member's message + if (tell && !tellFault(tell)) + out.push({ agent: tell.agent, why: "acts on it", hears: "message" }); + if (isPath(asker?.agent) && asker.agent !== tell?.agent) + out.push({ + agent: asker.agent, + why: "asked", + hears: follows(asker.agent, true) ? "card" : "message", + }); + if (isPath(task.agent) && task.agent !== asker?.agent && task.agent !== tell?.agent) { + if (follows(task.agent, false)) + out.push({ agent: task.agent, why: "has the task", hears: "card" }); + // nobody is known to have asked: the agent that has the task is told, so that an answer is heard + else if (!isPath(asker?.agent)) + out.push({ agent: task.agent, why: "has the task", hears: "message" }); + } + return out; +} + +/** WHAT THE PAGE TELLS AN ASKER THAT DOES NOT FOLLOW THE CARD, after a person answered its ask: + * who answered, the task, the ask and the answer. The card's commit holds the same. */ +export function answerMessage({ + domain, + repo = TASKS_REPO.split("/").at(-1), + path, + title, + ask, + answer, + by, + why = "asked", +}) { + const query = new URLSearchParams( + repo === TASKS_REPO.split("/").at(-1) ? { task: path } : { repo, task: path }, + ); + return [ + why === "asked" + ? `${by} answered a question that you asked on the task board.` + : `${by} answered a question on a task that you have, on the task board.`, + "", + `The task: ${title ? `"${title}", ` : ""}https://tasks.${domain}/?${query} (the file ${path} of the repo /repos/${repo})`, + `The question: "${ask}"`, + `The answer: ${ + String(answer ?? "") + .replace(/\s+/g, " ") + .trim() || "(no words)" + }`, + "", + "The answer is in the card's text under ## Answers, and the ask is off the card. You get this message because you do not follow the card. Reply here if something is unclear: the person reads this chat.", + ].join("\n"); +} + +/** WHAT THE PAGE SENDS THE AGENT THAT ACTS ON AN ANSWER (`receiversOf`, "acts on it"): THE + * PERSON'S OWN WORDS FIRST, as they would write them in that agent's chat, then where they were + * given. It comes from the person's own session on the task board, so the platform stamps it as + * that person's message. Whether those words release anything is the agent's own rule. */ +export function tellMessage({ + domain, + repo = TASKS_REPO.split("/").at(-1), + path, + title, + ask, + answer, + by, + asker, +}) { + const query = new URLSearchParams( + repo === TASKS_REPO.split("/").at(-1) ? { task: path } : { repo, task: path }, + ); + return [ + String(answer ?? "") + .replace(/\s+/g, " ") + .trim() || "(no words)", + "", + `(${by} wrote this on the task board, in answer to: "${ask}"${asker ? `, which ${asker} asked` : ""}. The task: ${title ? `"${title}", ` : ""}https://tasks.${domain}/?${query}. The answer is on the card too, under ## Answers.)`, + ].join("\n"); +} + +// ── a decision ask: its options, and what the asker recommends ── + +/** The heading in a task's text under which the options of its asks are kept. */ +export const DECISIONS_HEADING = "## Decisions"; + +const lineOf = (value) => + String(value ?? "") + .replace(/\s+/g, " ") + .trim(); + +/** WHAT IS WRONG WITH A DECISION, as words, or "" for one that is whole: at least two options, + * each with a name and what it costs or gives (`tradeoff`); `recommend`, the name of one of them; + * and `why`. Jonas, 25 Nov 2026: "when we are presented with a choice, the different options are + * explored and a recommendation is given". */ +export function decisionFault(decision) { + if (!decision || typeof decision !== "object" || Array.isArray(decision)) + return "decision is { options: [{ name, tradeoff }, …], recommend, why }."; + const options = Array.isArray(decision.options) ? decision.options : []; + if (options.length < 2) + return "decision.options holds at least two options: a choice with one option is no choice."; + if ( + !options.every( + (option) => + option && typeof option === "object" && lineOf(option.name) && lineOf(option.tradeoff), + ) + ) + return "each of decision.options is { name, tradeoff }: its name, and what it costs or gives."; + const names = options.map((option) => lineOf(option.name)); + if (new Set(names).size !== names.length) + return "the names of decision.options differ from each other."; + if (!names.includes(lineOf(decision.recommend))) + return `decision.recommend is the name of one option: ${names.map((name) => JSON.stringify(name)).join(", ")}.`; + if (!lineOf(decision.why)) return "decision.why says why you recommend that option."; + return ""; +} + +/** THE FILE WITH THE OPTIONS OF ONE ASK WRITTEN DOWN, and every other byte as it was. Under + * `## Decisions` at the text's end: + * - **<the ask>** + * - Option: <name>: <tradeoff> + * - Recommended: <name>: <why> + * The block stays when the ask is answered: the text then holds what was weighed. Which MODEL + * recommended is never written here: a model's own word is no evidence, and + * `itx.config.taskAskers` reads it from the asker's own log. A decision that is not whole + * (`decisionFault`), or an ask that has a block already, changes nothing. */ +export function addDecision(source, { ask, options, recommend, why }) { + const said = lineOf(ask); + if (!said || decisionFault({ options, recommend, why }) || blocksOf(source).has(said)) + return source; + const { bodyAt, eol } = frontmatterOf(source); + const block = [ + `- **${said}**`, + ...options.map((option) => ` - Option: ${lineOf(option.name)}: ${lineOf(option.tradeoff)}`), + ` - Recommended: ${lineOf(recommend)}: ${lineOf(why)}`, + ].join(eol); + return ( + source.slice(0, bodyAt) + withLineUnder(source.slice(bodyAt), DECISIONS_HEADING, block, eol) + ); +} + +/** THE OPTIONS THAT A TASK'S TEXT KEEPS (`addDecision` wrote them): a Map from an ask's whole text + * to `{ options: [{ name, tradeoff }], recommend, why }`. A block with no "Recommended" line is + * left out. */ +export function decisionsOf(source) { + return new Map( + [...blocksOf(source)] + .filter(([, block]) => block.recommend) + .map(([ask, { options, recommend, why }]) => [ask, { options, recommend, why }]), + ); +} + +// ── an ask that a person answers by a message to another agent ── + +/** WHAT IS WRONG WITH `tell`, as words, or "" for one that is whole: `agent`, the path of the + * agent that acts on the person's answer, and `words` (it may be left out): the answer that the + * asker waits for, as one line, which the answer box starts with. */ +export function tellFault(tell) { + if (!tell || typeof tell !== "object" || Array.isArray(tell)) + return 'tell is { agent: "/agents/…", words?: "the answer that you wait for" }.'; + if (typeof tell.agent !== "string" || !/^\/agents\/\S+$/.test(tell.agent.trim())) + return 'tell.agent is the path of the agent that acts on the answer, like "/agents/sysadmin".'; + if (tell.words !== undefined && typeof tell.words !== "string") + return "tell.words is a text: the words that you wait for, which the answer box starts with."; + return ""; +} + +/** THE FILE WITH WHICH AGENT ACTS ON ONE ASK'S ANSWER WRITTEN DOWN, and every other byte as it + * was. Under `## Decisions`, as an ask's options are: + * - **<the ask>** + * - Tell: <the agent's path>: <the words that the asker waits for> + * Jonas, 25 Nov 2026, of an ask that told him to write in another agent's chat and stood above + * an answer box: "what is all this?! what am i meant to take from it", and then: "it should make + * zero difference where i post". So the person answers in the one box, and the page sends the + * answer on to that agent as the person's own message (`receiversOf`, `tellMessage`). A `tell` + * that is not whole, or an ask that has a block already, changes nothing. */ +export function addTell(source, { ask, agent, words }) { + const said = lineOf(ask); + if (!said || tellFault({ agent, words }) || blocksOf(source).has(said)) return source; + const { bodyAt, eol } = frontmatterOf(source); + const block = [ + `- **${said}**`, + ` - Tell: ${agent.trim()}${lineOf(words) ? `: ${lineOf(words)}` : ""}`, + ].join(eol); + return ( + source.slice(0, bodyAt) + withLineUnder(source.slice(bodyAt), DECISIONS_HEADING, block, eol) + ); +} + +/** WHICH AGENT ACTS ON THE ANSWER OF EACH ASK THAT NAMES ONE (`addTell` wrote it): a Map from an + * ask's whole text to `{ agent, words }`; `words` is "" when the asker named none. */ +export function tellsOf(source) { + return new Map( + [...blocksOf(source)] + .filter(([, block]) => block.tell) + .map(([ask, block]) => [ask, block.tell]), + ); +} + +/** Every block under `## Decisions`, by its ask: `{ options, recommend, why, tell }`. */ +function blocksOf(source) { + const found = new Map(); + let fenced = false; + let inside = false; + let now = null; + const close = () => { + if (now && (now.recommend || now.tell)) found.set(now.ask, now); + now = null; + }; + for (const line of String(source ?? "") + .slice(frontmatterOf(String(source ?? "")).bodyAt) + .split(/\r?\n/)) { + if (/^\s*(```|~~~)/.test(line)) fenced = !fenced; + if (fenced) continue; + if (/^#{1,6}\s/.test(line)) { + close(); + inside = /^##\s+Decisions\s*$/.test(line); + continue; + } + if (!inside) continue; + const head = /^- \*\*(.+)\*\*\s*$/.exec(line); + if (head) { + close(); + now = { ask: head[1], options: [], recommend: "", why: "", tell: null }; + continue; + } + const part = now && /^\s+- (Option|Recommended|Tell): (.*)$/.exec(line); + if (!part) continue; + // a name holds no ": " (a link's "https://" has none): the first one ends it + const cut = part[2].indexOf(": "); + const [name, rest] = + cut < 0 + ? [part[2].trim(), ""] + : [part[2].slice(0, cut).trim(), part[2].slice(cut + 2).trim()]; + // a path that `taskUpdate` would refuse is no route, whoever wrote the line (`tellFault`) + if (part[1] === "Tell") + now.tell = tellFault({ agent: name, words: rest }) ? null : { agent: name, words: rest }; + else if (part[1] === "Option") now.options.push({ name, tradeoff: rest }); + else [now.recommend, now.why] = [name, rest]; + } + close(); + return found; +} + +// ── "Needs a person": what presses, and what may be outdated ── + +/** The priorities that the page offers, the most pressing first. */ +export const PRIORITIES = ["urgent", "high", "medium", "low"]; + +/** HOW MUCH A TASK THAT WAITS FOR A PERSON PRESSES (Jonas, 25 Nov 2026: age alone is not + * priority): `rank`, lower is more pressing, from the task's `priority:` in the board's own order + * of priorities (a task with none ranks as "medium"); and `held`, whether work stands still for + * the answer: the task is in progress or in review, or says what holds it (`blocked-on:`). */ +export function pressOf(task) { + const order = DIMENSIONS.find(({ id }) => id === "priority").order; + const at = order.indexOf(String(task.priority ?? "").toLowerCase()); + return { + rank: at < 0 ? order.indexOf("medium") : at, + held: task.column === "in-progress" || task.column === "in-review" || Boolean(task.blockedOn), + }; +} + +/** After how many days an ask may be outdated. */ +export const STALE_DAYS = 3; + +/** WHY AN ASK MAY BE OUTDATED, as words, or "" (Jonas, 25 Nov 2026: "quite often stuff is + * outdated"). `asker` is the ask's row of `itx.config.taskAskers`. It may be: the agent that + * asked is retired, or the ask is `STALE_DAYS` days old or more. This is a hint to look, never a + * fact: only the agent or a person takes an ask off. `retired`: the paths of the agents that the + * mind retired (app.ts `tasksApp({ retiredAgents })`); a mind that names none has none. */ +export function staleOf({ asker, now = Date.now(), retired = [] }) { + if (retired.includes(asker?.agent)) return "the agent that asked is retired"; + const days = Math.floor((now - Date.parse(asker?.at ?? "")) / 86_400_000); + return days >= STALE_DAYS ? `asked ${days} days ago` : ""; +} + +/** WHOM THE PAGE ASKS WHETHER AN ASK IS STILL NEEDED: the agent that asked; when that one is + * retired or unknown, the agent that has the task; else nobody (null). */ +export function keeperOf({ task, asker, retired = [] }) { + return ( + [asker?.agent, task.agent].find( + (value) => typeof value === "string" && value.startsWith("/") && !retired.includes(value), + ) ?? null + ); +} + +/** THE WORDS BEHIND "Still needed?": a person asks the ask's keeper to keep the ask true. */ +export function stillNeededMessage({ + domain, + repo = TASKS_REPO.split("/").at(-1), + path, + title, + ask, + by, + why, +}) { + const query = new URLSearchParams( + repo === TASKS_REPO.split("/").at(-1) ? { task: path } : { repo, task: path }, + ); + return [ + `${by} asks whether a question on the task board is still needed${why ? ` (${why})` : ""}.`, + "", + `The task: ${title ? `"${title}", ` : ""}https://tasks.${domain}/?${query} (the file ${path} of the repo /repos/${repo})`, + `The question: "${ask}"`, + "", + 'Check it against what is true now. When events overtook it, take it off: itx.config.taskUpdate({ file, withdraw: { ask: "<its beginning>", why: "…" } }). When it is still needed and its words are old, write it again: reword: { ask: "<its beginning>", to: "<the new sentence>" }. When it stands as it is, say so here in one line. tasks.md of /repos/config, "Asks and answers".', + ].join("\n"); }
A tests/askers.test.mjs
@@ -0,0 +1,692 @@ +// askers.test.mjs — who asked each open ask of a task (askers.js). Run it with `node --test apps/tasks/`. +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { + ASK_LOCATED, + askersOf, + blockingOf, + locateAsk, + modelOf, + needleOf, + taskAskers, +} from "../askers.js"; + +const card = (...humanAsk) => ({ humanAsk: humanAsk.length > 0 ? humanAsk : null }); +const change = (offset, file, before, after, who) => ({ + type: "events.iterate.com/tasks/task-changed", + offset, + payload: { + file, + before, + after, + by: null, + via: null, + page: null, + committedAt: `2026-11-20T16:00:${String(offset % 60).padStart(2, "0")}.000Z`, + commitOid: `c${offset}`, + ...who, + }, +}); + +test("the asker of an ask is the agent of the newest commit that added it", () => { + const open = { "todo/a.md": ["Ship it?", "On a Friday?"], "todo/b.md": ["Pay?"] }; + const changes = [ + // newest first: a note that moved no ask says nothing + { + file: "todo/a.md", + before: card("Ship it?", "On a Friday?"), + after: card("Ship it?", "On a Friday?"), + by: "/agents/noter", + via: null, + }, + // an agent's session through a person's sign-in: the commit's Via line is the agent + { + file: "todo/a.md", + before: card("Ship it?"), + after: card("Ship it?", "On a Friday?"), + by: "jonas@x", + via: "/agents/manager", + committedAt: "t2", + commitOid: "c2", + }, + // an ask that is not open any more is no row + { + file: "todo/a.md", + before: card("Ship it?"), + after: card("Ship it?", "Gone?"), + by: "/agents/other", + via: null, + }, + // an agent's own turn: the platform's stamp is the agent + { + file: "todo/a.md", + before: null, + after: card("Ship it?"), + by: "/agents/worker", + via: null, + committedAt: "t1", + commitOid: "c1", + }, + // a person on the board: no agent + { + file: "todo/b.md", + before: card(), + after: card("Pay?"), + by: "misha@x", + page: "tasks.iterate.com", + via: null, + committedAt: "t0", + commitOid: "c0", + }, + // a file that asks nothing now + { file: "todo/c.md", before: card(), after: card("Old?"), by: "/agents/worker", via: null }, + ]; + assert.deepEqual(askersOf(open, changes), { + "todo/a.md": { + "On a Friday?": { + agent: "/agents/manager", + by: "jonas@x", + page: null, + at: "t2", + commitOid: "c2", + commitOffset: null, + }, + "Ship it?": { + agent: "/agents/worker", + by: "/agents/worker", + page: null, + at: "t1", + commitOid: "c1", + commitOffset: null, + }, + }, + "todo/b.md": { + "Pay?": { + agent: null, + by: "misha@x", + page: "tasks.iterate.com", + at: "t0", + commitOid: "c0", + commitOffset: null, + }, + }, + }); + // an ask that was answered and asked again is its last asker's; a Via line that is no path names no agent + const again = [ + { file: "todo/b.md", before: card(), after: card("Pay?"), by: "jonas@x", via: "Claude Code" }, + { file: "todo/b.md", before: card(), after: card("Pay?"), by: "/agents/first", via: null }, + ]; + assert.equal(askersOf(open, again)["todo/b.md"]["Pay?"].agent, null); + assert.equal(askersOf(open, again.toReversed())["todo/b.md"]["Pay?"].agent, "/agents/first"); +}); + +// A fake mind: one repo with a tasks folder, the feed's log and the catalog. +// `logs`: the events of any other context, by its path. `reads` are those of the feed's log alone. +function fakeMind({ files, events, listed = true, logs = {} }) { + const reads = []; + const appended = []; + const itx = { + repos: { + list: async () => [{ path: "/repos/task-board" }], + get: () => ({ tip: async () => "t1", modules: async () => files }), + }, + contexts: { list: async () => (listed ? [{ path: "/task-files/task-board" }] : []) }, + cd: (path) => ({ + readEvents: async (after, limit) => { + const all = path === "/task-files/task-board" ? events : (logs[path] ?? []); + if (path === "/task-files/task-board") reads.push([path, after, limit]); + return { + events: all.filter((event) => event.offset > after).slice(0, limit), + scannedThroughOffset: all.at(-1)?.offset ?? 0, + }; + }, + append: async (event) => { + appended.push([path, event]); + if (path === "/task-files/task-board") + events.push({ ...event, offset: (events.at(-1)?.offset ?? 0) + 1 }); + }, + }), + }; + return { itx, reads, appended }; +} + +test("taskAskers: each open ask with its asker, which is not the task's assignee; an ask the feed does not have has none", async () => { + const files = { + "a.md": + "---\nstatus: in-progress\nagent: /agents/worker\nhuman-ask:\n - Ship it?\n - An old one?\n---\n# A\n", + "b.md": "---\nstatus: todo\nhuman-ask:\n - Pay?\n---\n# B\n", + "c.md": "---\nstatus: todo\n---\n# C\n", + }; + const events = [ + change(1, "todo/b.md", null, card("Pay?"), { by: "misha@x", page: "tasks.iterate.com" }), + { type: "events.iterate.com/itx/woken", offset: 2, payload: {} }, + change(3, "todo/a.md", card("An old one?"), card("Ship it?", "An old one?"), { + by: "jonas@x", + via: "/agents/manager", + }), + ]; + const { itx, reads } = fakeMind({ files, events }); + const answer = await taskAskers(itx); + assert.deepEqual(answer, { + repo: "/repos/task-board", + asks: [ + { + file: "todo/a.md", + ask: "Ship it?", + agent: "/agents/manager", + by: "jonas@x", + page: null, + at: "2026-11-20T16:00:03.000Z", + message: null, + model: null, + blocking: null, + assignee: "/agents/worker", + }, + { + file: "todo/a.md", + ask: "An old one?", + agent: null, + by: null, + page: null, + at: null, + message: null, + model: null, + blocking: null, + assignee: "/agents/worker", + }, + { + file: "todo/b.md", + ask: "Pay?", + agent: null, + by: "misha@x", + page: "tasks.iterate.com", + at: "2026-11-20T16:00:01.000Z", + message: null, + model: null, + blocking: null, + assignee: null, + }, + ], + readFrom: 0, + }); + assert.deepEqual(reads.slice(1), [["/task-files/task-board", 0, 200]]); +}); + +test("taskAskers reads the feed from its end back, and stops when every ask has its asker", async () => { + const files = { "a.md": "---\nstatus: todo\nhuman-ask:\n - New?\n---\n# A\n" }; + const events = []; + for (let offset = 1; offset <= 450; offset += 1) + events.push(change(offset, "todo/z.md", card(), card(), {})); + events[429] = change(430, "todo/a.md", card(), card("New?"), { by: "/agents/late" }); + events[9] = change(10, "todo/a.md", card(), card("New?"), { by: "/agents/early" }); + const { itx, reads } = fakeMind({ files, events: [...events] }); // a copy: a call keeps what it looked up on the feed; + const answer = await taskAskers(itx); + assert.equal(answer.asks[0].agent, "/agents/late"); + assert.equal(answer.readFrom, 250); + assert.deepEqual(reads.slice(1), [["/task-files/task-board", 250, 200]]); + // an ask that only the log's start has is found by going back + events[429] = change(430, "todo/z.md", card(), card(), {}); + const far = fakeMind({ files, events }); + assert.equal((await taskAskers(far.itx)).asks[0].agent, "/agents/early"); + assert.deepEqual( + far.reads.slice(1).map(([, after]) => after), + [250, 50, 0], + ); +}); + +test("taskAskers reads no log that does not exist, and none for a board that asks nothing", async () => { + const asking = { + "a.md": "---\nstatus: todo\nagent: /agents/worker\nhuman-ask:\n - New?\n---\n# A\n", + }; + const unborn = fakeMind({ files: asking, events: [], listed: false }); + assert.deepEqual(await taskAskers(unborn.itx), { + repo: "/repos/task-board", + asks: [ + { + file: "todo/a.md", + ask: "New?", + agent: null, + by: null, + page: null, + at: null, + message: null, + model: null, + blocking: null, + assignee: "/agents/worker", + }, + ], + readFrom: null, + }); + assert.deepEqual(unborn.reads, []); + const quiet = fakeMind({ + files: { "c.md": "# C\n" }, + events: [change(1, "todo/c.md", null, card(), {})], + }); + assert.deepEqual(await taskAskers(quiet.itx), { repo: "/repos/task-board", asks: [], readFrom: null }); + assert.deepEqual(quiet.reads, []); + await assert.rejects(taskAskers(quiet.itx, "tasks"), /takes \{ repo\? \}/); + await assert.rejects( + taskAskers(quiet.itx, { repo: "none" }), + /the mind has no repo \/repos\/none/, + ); +}); + +test("the message that asked: the commit's cause for an agent's own turn, else the session's event that holds the ask's words", async () => { + assert.equal( + needleOf("Jonas: for Xero, pay for [Xero's Core plan](https://x) or not?"), + "Jonas: for Xero, pay for [Xero", + ); + assert.equal(needleOf("Ship it?"), null); + const at = "2026-11-20T16:00:00.000Z"; + const hook = (offset, seconds, words, call = "taskUpdate") => ({ + offset, + createdAt: new Date(Date.parse(at) + seconds * 1000).toISOString(), + payload: { tool_input: { script: `${call}({ ask: "${words}" })` } }, + }); + const logs = { + // the repo's log: the fact of an agent's own commit names its cause; a session's names none + "/repos/task-board": [ + { offset: 7, source: { cause: { parent: "/agents/worker@41" } } }, + { offset: 8, source: { onBehalfOf: { principal: { email: "jonas@x" } } } }, + { offset: 9, source: { cause: { parent: "/agents/other@5" } } }, + ], + "/agents/worker": [ + { + offset: 41, + createdAt: at, + payload: { text: 'taskUpdate({ ask: "Ship it or wait a day?" })' }, + }, + ], + "/agents/claude/session": [ + ...Array.from({ length: 30 }, (_, n) => + hook(n + 1, -4000 + n, "Jonas: may the demo be erased on 27 Nov?"), + ), + hook(31, -200, "Jonas: may the demo be erased on 27 Nov?"), + hook(32, -40, "Jonas: may the demo be erased on 27 Nov?"), + hook(33, -3, "Jonas: may the demo be erased on 27 Nov?"), + // an event that only quotes the ask writes nothing; one after the commit is another call + hook(34, -1, "Jonas: may the demo be erased on 27 Nov?", "said"), + hook(35, 9, "Jonas: may the demo be erased on 27 Nov?"), + hook(36, 500, "Jonas: may the demo be erased on 27 Nov?"), + ], + }; + const { itx } = fakeMind({ files: {}, events: [], logs }); + assert.deepEqual( + await locateAsk(itx, "/repos/task-board", "Ship it or wait a day?", { + agent: "/agents/worker", + at, + commitOffset: 7, + }), + { path: "/agents/worker", offset: 41, words: true }, + ); + // code that an event set off wrote the ask: the event led to it, and does not hold its words + assert.deepEqual( + await locateAsk(itx, "/repos/task-board", "Should this mind be let in?", { + agent: "/agents/worker", + at, + commitOffset: 7, + }), + { path: "/agents/worker", offset: 41, words: false }, + ); + // the words in a call that writes an ask: the last such event of the two minutes before the commit + assert.deepEqual( + await locateAsk(itx, "/repos/task-board", "Jonas: may the demo be erased on 27 Nov?", { + agent: "/agents/claude/session", + at, + commitOffset: 8, + }), + { path: "/agents/claude/session", offset: 33, words: true }, + ); + assert.equal( + await locateAsk(itx, "/repos/task-board", "Jonas: another question entirely?", { + agent: "/agents/claude/session", + at, + commitOffset: 8, + }), + null, + ); + // a cause that is another context's is not the asker's message; no agent, no log, no time: none + assert.equal( + await locateAsk(itx, "/repos/task-board", "Jonas: may the demo be erased on 27 Nov?", { + agent: "/agents/gone", + at, + commitOffset: 9, + }), + null, + ); + assert.equal( + await locateAsk(itx, "/repos/task-board", "Jonas: may the demo be erased on 27 Nov?", { + agent: null, + at, + commitOffset: 7, + }), + null, + ); + assert.equal( + await locateAsk(itx, "/repos/task-board", "Jonas: may the demo be erased on 27 Nov?", { + agent: "/agents/claude/session", + at: null, + commitOffset: null, + }), + null, + ); +}); + +test("taskAskers answers each ask's message, looks one up once and keeps the answer on the feed", async () => { + const files = { + "a.md": + "---\nstatus: todo\nhuman-ask:\n - Ship it or wait a day?\n - Jonas, is this one found?\n---\n# A\n", + }; + const events = [ + change(1, "todo/a.md", card(), card("Ship it or wait a day?"), { + by: "/agents/worker", + commitOffset: 7, + }), + change( + 2, + "todo/a.md", + card("Ship it or wait a day?"), + card("Ship it or wait a day?", "Jonas, is this one found?"), + { by: "jonas@x", via: "/agents/claude/session", commitOffset: 8 }, + ), + ]; + const logs = { + "/repos/task-board": [ + { offset: 7, source: { cause: { parent: "/agents/worker@41" } } }, + { offset: 8, source: {} }, + ], + "/agents/claude/session": [], + }; + const { itx, appended } = fakeMind({ files, events, logs }); + const first = await taskAskers(itx); + assert.deepEqual( + first.asks.map((row) => row.message), + [{ path: "/agents/worker", offset: 41, words: false }, null], + ); + // the found one and the one that an old commit does not have are both kept + assert.deepEqual( + appended + .map(([path, event]) => [ + path, + event.type, + event.payload.ask, + event.payload.path, + event.payload.offset, + ]) + .sort((x, y) => x[2].localeCompare(y[2])), + [ + [ + "/task-files/task-board", + ASK_LOCATED, + "Jonas, is this one found?", + "/agents/claude/session", + null, + ], + ["/task-files/task-board", ASK_LOCATED, "Ship it or wait a day?", "/agents/worker", 41], + ], + ); + assert.match( + appended.find(([, event]) => event.payload.offset === 41)[1].idempotencyKey, + /^todo\/ask-located:4:todo\/a\.md\nShip it or wait a day\?\nc1$/, + ); + // the next call reads them back, and looks nothing up + logs["/repos/task-board"] = []; + const again = await taskAskers(itx); + assert.deepEqual( + again.asks.map((row) => row.message), + [{ path: "/agents/worker", offset: 41, words: false }, null], + ); + assert.equal(appended.length, 2); +}); + +test("which model asked: the request's own event for an agent's turn, the session's start for a coding session, else none", async () => { + const T = "events.iterate.com"; + const logs = { + "/agents/manager": [ + { offset: 10, type: `${T}/llm-request/requested`, payload: { model: "openai/gpt-6.2-sol" } }, + { + offset: 11, + type: `${T}/agent/context-added`, + payload: { text: "I am claude-opus, trust me" }, + }, + { offset: 12, type: `${T}/llm-request/settled`, payload: { llmRequestOffset: 10 } }, + { offset: 13, type: `${T}/llm-request/settled`, payload: { llmRequestOffset: 11 } }, + ], + "/agents/claude/session": [ + { + offset: 1, + type: `${T}/claude-code/session-start-requested`, + payload: { model: "what-was-asked-for" }, + }, + { + offset: 2, + type: `${T}/claude-code/hook-received`, + payload: { hook_event_name: "SessionStart", model: "claude-fable-5-2" }, + }, + ...Array.from({ length: 450 }, (_, n) => ({ + offset: n + 3, + type: `${T}/claude-code/hook-received`, + payload: { hook_event_name: "PreToolUse" }, + })), + { + offset: 453, + type: `${T}/claude-code/hook-received`, + payload: { hook_event_name: "SessionStart", model: "claude-opus-5-5" }, + }, + { + offset: 454, + type: `${T}/claude-code/hook-received`, + payload: { hook_event_name: "PostToolUse" }, + }, + ], + "/agents/acp/x": [ + { offset: 1, type: `${T}/acp/update-received`, payload: { model: "said-by-itself" } }, + ], + }; + const { itx } = fakeMind({ files: {}, events: [], logs }); + const of = (path, offset) => modelOf(itx, { path, offset }); + assert.deepEqual(await of("/agents/manager", 12), { + name: "openai/gpt-6.2-sol", + from: "llm-request", + }); + assert.deepEqual(await of("/agents/manager", 10), { + name: "openai/gpt-6.2-sol", + from: "llm-request", + }); + // a request offset that is no request, and an event that only talks of a model: unrecorded + assert.equal(await of("/agents/manager", 13), null); + assert.equal(await of("/agents/manager", 11), null); + // the newest start BEFORE the turn; what was asked for at the start is not read + assert.deepEqual(await of("/agents/claude/session", 454), { + name: "claude-opus-5-5", + from: "session-start", + }); + assert.deepEqual(await of("/agents/claude/session", 400), { + name: "claude-fable-5-2", + from: "session-start", + }); + assert.equal(await of("/agents/acp/x", 1), null); + assert.equal(await of("/agents/gone", 5), null); + assert.equal(await modelOf(itx, null), null); +}); + +test("taskAskers answers the model of each ask's turn, and keeps it with the message", async () => { + const files = { "a.md": "---\nstatus: todo\nhuman-ask:\n - Ship it or wait a day?\n---\n# A\n" }; + const events = [ + change(1, "todo/a.md", card(), card("Ship it or wait a day?"), { + by: "/agents/worker", + commitOffset: 7, + }), + ]; + const logs = { + "/repos/task-board": [{ offset: 7, source: { cause: { parent: "/agents/worker@41" } } }], + "/agents/worker": [ + { + offset: 40, + type: "events.iterate.com/llm-request/requested", + payload: { model: "openai/gpt-6.2-sol" }, + }, + { + offset: 41, + type: "events.iterate.com/llm-request/settled", + payload: { + llmRequestOffset: 40, + result: { text: 'taskUpdate({ ask: "Ship it or wait a day?" })' }, + }, + }, + ], + }; + const { itx, appended } = fakeMind({ files, events, logs }); + const row = (await taskAskers(itx)).asks[0]; + assert.deepEqual( + [row.message, row.model], + [ + { path: "/agents/worker", offset: 41, words: true }, + { name: "openai/gpt-6.2-sol", from: "llm-request" }, + ], + ); + assert.deepEqual(appended[0][1].payload.model, { + name: "openai/gpt-6.2-sol", + from: "llm-request", + }); + logs["/agents/worker"] = []; + assert.deepEqual((await taskAskers(itx)).asks[0].model, { + name: "openai/gpt-6.2-sol", + from: "llm-request", + }); +}); + +test("the agent's blocking message: the request's own text, or a session's first Stop after the ask", async () => { + const T = "events.iterate.com"; + const hook = (offset, name, more = {}) => ({ + offset, + type: `${T}/claude-code/hook-received`, + payload: { hook_event_name: name, ...more }, + }); + const logs = { + "/agents/manager": [ + { + offset: 12, + type: `${T}/llm-request/settled`, + payload: { + result: { + text: "I need a yes.\n<codemode>\nitx.config.taskUpdate({ ask: 'x' })\n</codemode>\n\n\n\nThen I go on.", + }, + }, + }, + { + offset: 13, + type: `${T}/llm-request/settled`, + payload: { result: { text: "<codemode>only a script</codemode>" } }, + }, + ], + "/agents/claude/done": [ + hook(5, "PreToolUse"), + hook(6, "PostToolUse"), + hook(7, "PreToolUse"), + hook(8, "Stop", { last_assistant_message: "The link is ready.\n\nSay yes or no." }), + hook(9, "Stop", { last_assistant_message: "a later turn" }), + ], + "/agents/claude/working": [hook(5, "PreToolUse"), hook(6, "PostToolUse")], + "/agents/claude/interrupted": [ + hook(5, "PreToolUse"), + hook(6, "UserPromptSubmit", { prompt: "stop" }), + hook(7, "Stop", { last_assistant_message: "of the next turn" }), + ], + "/agents/acp/x": [{ offset: 1, type: `${T}/acp/update-received`, payload: {} }], + }; + const { itx } = fakeMind({ files: {}, events: [], logs }); + const now = Date.parse("2026-11-25T12:00:00Z"); + const of = (path, offset, askedAt = "2026-11-25T11:00:00Z") => + blockingOf(itx, { path, offset }, askedAt, now); + assert.deepEqual(await of("/agents/manager", 12), { + path: "/agents/manager", + offset: 12, + text: "I need a yes.\n\nThen I go on.", + }); + assert.equal(await of("/agents/manager", 13), null); + assert.deepEqual(await of("/agents/claude/done", 5), { + path: "/agents/claude/done", + offset: 8, + text: "The link is ready.\n\nSay yes or no.", + }); + // the turn has not ended: it may still come; a day later it will not + assert.equal(await of("/agents/claude/working", 5), undefined); + assert.equal(await of("/agents/claude/working", 5, "2026-11-23T11:00:00Z"), null); + // the person spoke before the turn ended; a kind with no such event; no event there + assert.equal(await of("/agents/claude/interrupted", 5), null); + assert.equal(await of("/agents/acp/x", 1), null); + assert.equal(await of("/agents/gone", 3), null); + // a long message is cut at a word + logs["/agents/long"] = [ + { + offset: 1, + type: `${T}/llm-request/settled`, + payload: { result: { text: "word ".repeat(2000) } }, + }, + ]; + const long = await of("/agents/long", 1); + assert.ok(long.text.length <= 4002 && long.text.endsWith(" …")); +}); + +test("taskAskers answers the blocking message when the turn has ended, and keeps it", async () => { + const T = "events.iterate.com"; + const files = { + "a.md": "---\nstatus: todo\nhuman-ask:\n - Jonas, may the demo be erased?\n---\n# A\n", + }; + const events = [ + change(1, "todo/a.md", card(), card("Jonas, may the demo be erased?"), { + by: "jonas@x", + via: "/agents/claude/s", + commitOffset: 8, + committedAt: new Date().toISOString(), + }), + ]; + // the ask is of this minute: an ask of a day ago with no Stop has no blocking message for good + const at = events[0].payload.committedAt; + const hook = (offset, name, more = {}) => ({ + offset, + createdAt: at, + type: `${T}/claude-code/hook-received`, + payload: { hook_event_name: name, ...more }, + }); + const logs = { + "/repos/task-board": [{ offset: 8, source: {} }], + "/agents/claude/s": [ + hook(1, "SessionStart", { model: "claude-fable-5-2" }), + hook(2, "PreToolUse", { + tool_input: { script: 'taskUpdate({ ask: "Jonas, may the demo be erased?" })' }, + }), + ], + }; + const { itx, appended } = fakeMind({ files, events, logs }); + // the turn still runs: a message, a model, and no blocking message yet + const first = (await taskAskers(itx)).asks[0]; + assert.deepEqual( + [first.message, first.model, first.blocking], + [ + { path: "/agents/claude/s", offset: 2, words: true }, + { name: "claude-fable-5-2", from: "session-start" }, + null, + ], + ); + assert.equal(appended.length, 1); + // the turn ended: the next read finds it and keeps it + logs["/agents/claude/s"].push( + hook(3, "Stop", { last_assistant_message: "The demo holds nothing of yours. Erase it?" }), + ); + const second = (await taskAskers(itx)).asks[0]; + assert.deepEqual(second.blocking, { + path: "/agents/claude/s", + offset: 3, + text: "The demo holds nothing of yours. Erase it?", + }); + assert.deepEqual(second.model, { name: "claude-fable-5-2", from: "session-start" }); + assert.equal(appended.length, 2); + assert.match(appended[1][1].idempotencyKey, /:blocking$/); + // and the read after that looks nothing up + logs["/agents/claude/s"] = []; + const third = (await taskAskers(itx)).asks[0]; + assert.deepEqual([third.blocking.offset, third.message.offset], [3, 2]); + assert.equal(appended.length, 2); +});
A tests/asks.test.mjs
@@ -0,0 +1,128 @@ +// asks.test.mjs — an agent's answer to an ask of a task (asks.js). Run it with +// `node --test apps/tasks/`. +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { answerTask } from "../asks.js"; + +const NOW = new Date("2026-11-20T14:50:31.000Z"); + +// A fake mind: repos that hold files at a tip, and a commit that names the tip it was decided on. +function fakeMind( + files = { + "todo/a.md": + "---\nstatus: todo\nhuman-ask:\n - Merge #12 now, or wait?\n - Sign the grant?\n---\n\n# A\n", + }, +) { + const repos = { + "/repos/task-board": { tip: "t1", files: { ...files } }, + "/repos/other": { tip: "o1", files: { "todo/z.md": "---\nhuman-ask: one ask\n---\n" } }, + }; + const commits = []; + const itx = { + repos: { + list: async () => Object.keys(repos).map((path) => ({ path })), + get: (path) => ({ + tip: async () => repos[path].tip, + readFile: async (file) => repos[path].files[file] ?? null, + commitFiles: async ({ message, changes, parent }) => { + if (parent !== repos[path].tip) + throw new Error(`repo ${path}: the commit was refused: main is at ${repos[path].tip}`); + for (const change of changes) repos[path].files[change.path] = change.content; + repos[path].tip = `${parent}+`; + commits.push({ repo: path, message, parent }); + return { commitOid: repos[path].tip }; + }, + }), + }, + }; + return { itx, repos, commits }; +} + +test("an agent's answer is one commit in the board's own format, and says what is still asked", async () => { + const mind = fakeMind(); + const done = await answerTask( + mind.itx, + { + file: "todo/a.md", + ask: "Merge #12 now, or wait?", + answer: "Wait for the deploy.", + by: "misha@nustom.com", + }, + NOW, + ); + assert.deepEqual(done, { + repo: "/repos/task-board", + file: "todo/a.md", + commitOid: "t1+", + stillAsked: ["Sign the grant?"], + }); + assert.equal( + mind.repos["/repos/task-board"].files["todo/a.md"], + "---\nstatus: todo\nhuman-ask:\n - Sign the grant?\n---\n\n# A\n\n## Answers\n\n- **Merge #12 now, or wait?** Wait for the deploy. (misha@nustom.com, 2026-11-20 14:50 UTC)\n", + ); + assert.deepEqual(mind.commits, [ + { + repo: "/repos/task-board", + message: 'tasks: todo/a.md: answered "Merge #12 now, or wait?"', + parent: "t1", + }, + ]); + // a task of another repo + const far = await answerTask( + mind.itx, + { file: "todo/z.md", ask: "one ask", answer: "yes", by: "a@x", repo: "other" }, + NOW, + ); + assert.deepEqual([far.repo, far.stillAsked], ["/repos/other", []]); +}); + +test("a commit that another one overtook is made again on the new tip", async () => { + const mind = fakeMind(); + const { get } = mind.itx.repos; + let stale = true; + // the first read sees a tip that has moved by the time of the commit + mind.itx.repos.get = (path) => ({ + ...get(path), + tip: async () => (stale ? ((stale = false), "t0") : get(path).tip()), + }); + const done = await answerTask( + mind.itx, + { file: "todo/a.md", ask: "Sign the grant?", answer: "Signed.", by: "a@x" }, + NOW, + ); + assert.deepEqual( + [done.commitOid, done.stillAsked, mind.commits.length], + ["t1+", ["Merge #12 now, or wait?"], 1], + ); +}); + +test("an answer to nothing is refused, in words", async () => { + const mind = fakeMind(); + const ask = { file: "todo/a.md", ask: "Sign the grant?", answer: "Yes.", by: "a@x" }; + await assert.rejects( + answerTask(mind.itx, { ...ask, ask: "Another ask?" }, NOW), + /todo\/a\.md does not ask that\. It asks: "Merge #12 now, or wait\?", "Sign the grant\?"\./, + ); + await assert.rejects( + answerTask(mind.itx, { ...ask, file: "todo/none.md" }, NOW), + /\/repos\/task-board has no todo\/none\.md/, + ); + await assert.rejects( + answerTask(mind.itx, { ...ask, file: "worker.ts" }, NOW), + /file is a task's path/, + ); + await assert.rejects( + answerTask(mind.itx, { ...ask, answer: " " }, NOW), + /answer is a text, and it is not empty/, + ); + await assert.rejects(answerTask(mind.itx, { ...ask, by: undefined }, NOW), /by is a text/); + await assert.rejects( + answerTask(mind.itx, { ...ask, repo: "none" }, NOW), + /the mind has no repo \/repos\/none/, + ); + await assert.rejects( + answerTask(mind.itx, "todo/a.md", NOW), + /takes \{ file, ask, answer, by, repo\? \}/, + ); + assert.equal(mind.commits.length, 0); +});
A tests/board.test.mjs
@@ -0,0 +1,208 @@ +// board.test.mjs — the board as data for an agent (board.js). Run it with `node --test apps/tasks/`. +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { taskBoard } from "../board.js"; + +const changed = (offset, file, change, summary, by = "a@x") => ({ + type: "events.iterate.com/tasks/task-changed", + offset, + payload: { file, change, summary, by, committedAt: `2026-11-20T14:0${offset}:00.000Z` }, +}); +const follower = { + name: "task-follow-1", + filter: 'payload.file = "todo/a.md"', + copy: { path: "/agents/em" }, +}; + +// A fake mind: repos with a tasks folder at a tip, the feeds' logs, their rows, and the catalog. +function fakeMind({ + logs = { + "/task-files/task-board": [ + changed(1, "todo/a.md", "added", "a added"), + changed(2, "todo/b.md", "added", "b added"), + { type: "events.iterate.com/itx/woken", offset: 3, payload: {} }, + changed(4, "todo/a.md", "modified", "a: status todo → in-progress", "/agents/worker"), + ], + }, + rows = [follower, { name: "config" }], +} = {}) { + const repos = { + "/repos/task-board": { + tip: "t1", + files: { + "a.md": `---\nstatus: in-progress\nowner: jonas\nagent: /agents/worker\nhuman-ask:\n - Sign the grant?\n---\n# A\n\n## Answers\n\n- **Merge #12 now, or wait?** Wait for the deploy. (misha@nustom.com, 2026-11-20 14:50 UTC)\n- **A long one?** ${"y".repeat(600)} (a@x, 2026-11-20 14:55 UTC)\n`, + "b.md": "---\nstatus: todo\nblocked-on: PR #12\n---\n# B\n", + "c.md": "---\nstatus: done\nhuman-ask: [late]\n---\n# C\n", + "notes.txt": "no task", + }, + }, + "/repos/other": { tip: "o1", files: { "z.md": "# Z\n" } }, + "/repos/unborn": { tip: null, files: {} }, + }; + const read = []; + const itx = { + url: async () => "https://iterate.com/", + repos: { + list: async () => Object.keys(repos).map((path) => ({ path })), + get: (path) => ({ tip: async () => repos[path].tip, modules: async () => repos[path].files }), + }, + // the catalog: the feeds' logs, and the agents it has a row for (a long idle one has none) + contexts: { + list: async ({ under }) => + under === "/agents" + ? [ + { path: "/agents/worker", awake: true, lastActivityAt: "2026-11-20T14:03:30.000Z" }, + { path: "/agents/em", awake: false }, + ] + : Object.keys(logs).map((path) => ({ path })), + }, + cd: (path) => { + read.push(path); + const events = logs[path] ?? []; + return { + readEvents: async (after, limit) => ({ + events: events.filter((event) => event.offset > after).slice(0, limit), + scannedThroughOffset: events.at(-1)?.offset ?? 0, + }), + subscriptions: { list: async () => (path === "/task-files/task-board" ? rows : []) }, + }; + }, + }; + return { itx, read }; +} + +test("the board as data: every card, what needs a person, the newest changes and who follows", async () => { + const { itx } = fakeMind(); + const board = await taskBoard(itx); + assert.deepEqual( + [board.repo, board.commitOid, board.board], + ["/repos/task-board", "t1", "https://tasks.iterate.com/?repo=task-board"], + ); + // the answers that people gave are with the card: the decisions made, a long one cut + const answers = [ + { + ask: "Merge #12 now, or wait?", + answer: "Wait for the deploy.", + by: "misha@nustom.com", + at: "2026-11-20 14:50", + }, + { ask: "A long one?", answer: `${"y".repeat(499)}…`, by: "a@x", at: "2026-11-20 14:55" }, + ]; + assert.deepEqual(board.tasks, [ + { + file: "todo/a.md", + title: "A", + status: "in-progress", + column: "in-progress", + tags: [], + priority: "", + size: "", + owner: "jonas", + agent: "/agents/worker", + agentSeen: { awake: true, lastActivityAt: "2026-11-20T14:03:30.000Z" }, + agentFollows: false, + blockedOn: null, + humanAsk: ["Sign the grant?"], + answers, + lastChange: { + at: "2026-11-20T14:04:00.000Z", + by: "/agents/worker", + summary: "a: status todo → in-progress", + }, + }, + { + file: "todo/b.md", + title: "B", + status: "todo", + column: "todo", + tags: [], + priority: "", + size: "", + owner: "", + agent: "", + agentSeen: null, + agentFollows: null, + blockedOn: "PR #12", + humanAsk: [], + answers: [], + lastChange: { at: "2026-11-20T14:02:00.000Z", by: "a@x", summary: "b added" }, + }, + { + file: "todo/c.md", + title: "C", + status: "done", + column: "done", + tags: [], + priority: "", + size: "", + owner: "", + agent: "", + agentSeen: null, + agentFollows: null, + blockedOn: null, + humanAsk: ["late"], + answers: [], + lastChange: null, + }, + ]); + // a done task needs nobody, and neither does one that is held and asks nothing + assert.deepEqual(board.needsAPerson, ["todo/a.md"]); + assert.deepEqual( + board.recentChanges.map((change) => [change.file, change.change]), + [ + ["todo/a.md", "modified"], + ["todo/b.md", "added"], + ["todo/a.md", "added"], + ], + ); + assert.deepEqual(board.followers, [{ agent: "/agents/em", follows: "todo/a.md", only: null }]); +}); + +test("a card says whether its agent follows it: one that does not was not taken", async () => { + // todo/a.md names /agents/worker. Another agent's follow of the card is not the worker's + assert.equal((await taskBoard(fakeMind().itx)).tasks[0].agentFollows, false); + // the worker follows its card, as an agent that is given one does first + const own = { + name: "task-follow-2", + filter: + 'payload.file = "todo/a.md" and payload.by != "/agents/worker" and payload.via != "/agents/worker"', + copy: { path: "/agents/worker" }, + }; + assert.equal( + (await taskBoard(fakeMind({ rows: [follower, own] }).itx)).tasks[0].agentFollows, + true, + ); + // or it follows every card + const all = { + name: "task-follow-3", + filter: 'payload.by != "/agents/worker" and payload.via != "/agents/worker"', + copy: { path: "/agents/worker" }, + }; + const board = await taskBoard(fakeMind({ rows: [all] }).itx); + assert.deepEqual( + board.tasks.map((task) => task.agentFollows), + [true, null, null], + ); +}); + +test("another repo by its name; a repo with no feed log yet is not read into being", async () => { + const { itx, read } = fakeMind(); + const other = await taskBoard(itx, { repo: "other" }); + assert.deepEqual( + [other.repo, other.board, other.tasks.map((task) => task.title)], + ["/repos/other", "https://tasks.iterate.com/?repo=other", ["Z"]], + ); + assert.deepEqual( + [other.recentChanges, other.followers, other.tasks[0].lastChange], + [[], [], null], + ); + assert.deepEqual(read, []); + const unborn = await taskBoard(itx, { repo: "/repos/unborn" }); + assert.deepEqual([unborn.commitOid, unborn.tasks, unborn.needsAPerson], [null, [], []]); +}); + +test("a board of nothing is refused, in words", async () => { + const { itx } = fakeMind(); + await assert.rejects(taskBoard(itx, { repo: "none" }), /the mind has no repo \/repos\/none/); + await assert.rejects(taskBoard(itx, "tasks"), /takes \{ repo\? \}/); +});
A tests/cards.test.mjs
@@ -0,0 +1,868 @@ +// cards.test.mjs — an agent's three calls that keep a card (cards.js). Run it with +// `node --test apps/tasks/`. +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { briefOf, taskAssign, taskOpen, taskUpdate } from "../cards.js"; +import { parseTask } from "../public/tasks-model.js"; + +const NOW = new Date("2026-11-20T16:05:31.000Z"); +const CARD = + "---\nstatus: todo\nowner: misha@nustom.com\n---\n\n# Fix the bar\n\nIn Misha's words: the bar overlaps.\n"; +const EM = "/agents/engineering-manager"; +const SYSADMIN = "/agents/sysadmin"; + +// A fake mind: repos that hold files at a tip, agents that take messages, and logs that keep what +// is appended. `own`: what a mind adds of its own to the calls (cards.js, `deps`). +function fakeMind({ + files = { "todo/fix-the-bar.md": CARD }, + agents = [EM, "/agents/claude/owner-1"], + caller, + machine = {}, + rows, + own = {}, +} = {}) { + const repos = { + "/repos/task-board": { tip: "t1", files: { ...files } }, + "/repos/other": { tip: "o1", files: {} }, + }; + const commits = []; + const messages = []; + const appended = []; + const itx = { + url: async () => "https://iterate.com/", + repos: { + list: async () => Object.keys(repos).map((path) => ({ path })), + get: (path) => ({ + tip: async () => repos[path].tip, + readFile: async (file) => repos[path].files[file] ?? null, + modules: async ({ dir }) => + Object.fromEntries( + Object.entries(repos[path].files) + .filter(([file]) => file.startsWith(`${dir}/`)) + .map(([file, text]) => [file.slice(dir.length + 1), text]), + ), + commitFiles: async ({ message, changes, parent }) => { + if (parent !== repos[path].tip) + throw new Error(`repo ${path}: the commit was refused: main is at ${repos[path].tip}`); + for (const change of changes) repos[path].files[change.path] = change.content; + repos[path].tip = `${parent}+`; + commits.push({ + repo: path, + message, + parent, + paths: changes.map((change) => change.path), + }); + return { commitOid: repos[path].tip }; + }, + }), + }, + agents: { + get: (path) => ({ + message: async (text) => { + if (machine.deaf === path) throw new Error("no such agent"); + messages.push({ to: path, text }); + return { offset: messages.length }; + }, + }), + }, + cd: (path) => ({ + append: async (...events) => + void appended.push(...events.map((event) => ({ path, ...event }))), + }), + }; + const deps = { + callerPath: () => { + if (!caller) throw new Error("no caller"); + return caller; + }, + isAgent: async (path) => agents.includes(path) || Boolean(rows && Object.hasOwn(rows, path)), + // the catalog's row of an agent, when the test gives rows: a mind's api.ts always does + ...(rows && { agentRow: async (path) => rows[path] ?? null }), + ...own, + }; + return { + itx, + deps, + repos, + commits, + messages, + appended, + file: (path, repo = "/repos/task-board") => repos[repo].files[path], + }; +} + +test("a new card holds the ask in the person's words, who asked, and its asks; its file is named by the title", async () => { + const mind = fakeMind({ caller: EM }); + const made = await taskOpen( + mind.itx, + { + title: " The answer box:\n Cmd-Enter ", + text: 'Misha, 20 Nov 2026, in the pilot\'s card: "i tried to use cmd-enter".\n', + owner: "misha@nustom.com", + tags: ["tasks-app"], + ask: ["Ctrl-Enter too?"], + noChoice: "Only Misha knows which key his hand goes to.", + }, + mind.deps, + ); + assert.deepEqual(made, { + repo: "/repos/task-board", + file: "todo/the-answer-box-cmd-enter.md", + commitOid: "t1+", + link: "https://tasks.iterate.com/?repo=task-board&task=todo%2Fthe-answer-box-cmd-enter.md", + warning: undefined, + }); + assert.equal( + mind.file(made.file), + '---\nstatus: todo\ntags: [tasks-app]\nowner: "misha@nustom.com"\nhuman-ask:\n - Ctrl-Enter too?\n---\n\n# The answer box: Cmd-Enter\n\nMisha, 20 Nov 2026, in the pilot\'s card: "i tried to use cmd-enter".\n', + ); + assert.deepEqual(mind.commits, [ + { + repo: "/repos/task-board", + message: `tasks: new todo/the-answer-box-cmd-enter.md\n\nVia: ${EM}`, + parent: "t1", + paths: [made.file], + }, + ]); + // the same title again is a second file; a card of another repo; a member's script names no agent + const again = await taskOpen(mind.itx, { title: "The answer box: Cmd-Enter" }, mind.deps); + assert.equal(again.file, "todo/the-answer-box-cmd-enter-2.md"); + assert.equal(mind.file(again.file), "---\nstatus: todo\n---\n\n# The answer box: Cmd-Enter\n"); + const member = fakeMind(); + const far = await taskOpen( + member.itx, + { title: "A", status: "backlog", repo: "other" }, + member.deps, + ); + assert.deepEqual( + [far.repo, far.link], + ["/repos/other", "https://tasks.iterate.com/?repo=other&task=todo%2Fa.md"], + ); + assert.equal(member.commits[0].message, "tasks: new todo/a.md"); + await assert.rejects( + taskOpen(mind.itx, { title: " " }, mind.deps), + /title is a text, and it is not empty/, + ); + await assert.rejects(taskOpen(mind.itx, "A", mind.deps), /taskOpen takes \{ title, text\?/); + await assert.rejects( + taskOpen(mind.itx, { title: "A", repo: "none" }, mind.deps), + /the mind has no repo \/repos\/none/, + ); +}); + +test("an update is one commit of what the call names, and says whose it is", async () => { + const mind = fakeMind(); + const worker = "/agents/claude/fix-bar-abc123"; + const done = await taskUpdate( + mind.itx, + { + file: "todo/fix-the-bar.md", + by: worker, + status: "in-progress", + blockedOn: "PR #12 review", + ask: "Ship it on a Friday?", + noChoice: "A test of one commit.", + note: "Found the cause:\n the label has no width.", + }, + mind.deps, + NOW, + ); + assert.deepEqual( + [done.repo, done.file, done.commitOid, done.changed], + ["/repos/task-board", "todo/fix-the-bar.md", "t1+", true], + ); + assert.deepEqual(done.card, { + title: "Fix the bar", + status: "in-progress", + owner: "misha@nustom.com", + agent: "", + model: "", + effort: "", + tags: [], + blockedOn: "PR #12 review", + humanAsk: ["Ship it on a Friday?"], + }); + assert.equal( + mind.file("todo/fix-the-bar.md"), + `---\nstatus: in-progress\nowner: misha@nustom.com\nblocked-on: PR #12 review\nhuman-ask:\n - Ship it on a Friday?\n---\n\n# Fix the bar\n\nIn Misha's words: the bar overlaps.\n\n## Log\n\n- 2026-11-20 16:05 UTC, ${worker}: Found the cause: the label has no width.\n`, + ); + assert.equal( + mind.commits[0].message, + `tasks: 4 changes\n\n- todo/fix-the-bar.md is in-progress\n- todo/fix-the-bar.md: blocked on PR #12 review\n- todo/fix-the-bar.md: asks "Ship it on a Friday?"\n- todo/fix-the-bar.md: a note\n\nVia: ${worker}`, + ); + // the blocker goes; a call that changes nothing makes no commit + const freed = await taskUpdate( + mind.itx, + { file: "todo/fix-the-bar.md", by: worker, blockedOn: "" }, + mind.deps, + NOW, + ); + assert.deepEqual( + [freed.changed, freed.card.blockedOn, mind.commits[1].message], + [true, null, `tasks: todo/fix-the-bar.md: no longer blocked\n\nVia: ${worker}`], + ); + const same = await taskUpdate( + mind.itx, + { file: "todo/fix-the-bar.md", by: worker, status: "in-progress" }, + mind.deps, + NOW, + ); + assert.deepEqual([same.changed, same.commitOid, mind.commits.length], [false, "t1++", 2]); + // from an agent's own context the caller is the agent + const own = fakeMind({ caller: EM }); + await taskUpdate( + own.itx, + { file: "todo/fix-the-bar.md", note: "Asked Misha in the room." }, + own.deps, + NOW, + ); + assert.match( + own.file("todo/fix-the-bar.md"), + /- 2026-11-20 16:05 UTC, \/agents\/engineering-manager: Asked Misha in the room\.\n$/, + ); + assert.match(own.commits[0].message, /\n\nVia: \/agents\/engineering-manager$/); +}); + +test("an update keeps a card's asks true: one is taken off with its reason, one is written again, each named by its beginning", async () => { + const long = + "Jonas: ONE DECISION, on the final pinned head of PR-55: 98c082d71 (green; mergeable). DONE as you asked on 20 Nov, and a hundred more words of ids and offsets."; + const asking = CARD.replace( + "owner: misha@nustom.com\n", + `owner: misha@nustom.com\nhuman-ask:\n - "${long}"\n - Turn the agent tools on? Yes or no.\n - Xero's plan, or our own adapter?\n`, + ); + const mind = fakeMind({ files: { "todo/fix-the-bar.md": asking } }); + const done = await taskUpdate( + mind.itx, + { + file: "todo/fix-the-bar.md", + by: EM, + withdraw: { + ask: "Jonas: ONE DECISION", + why: "PR-55 merged on 21 Nov 2026 at 21:36 UTC.", + }, + reword: [ + { + ask: "Turn the agent tools on?", + to: "Jonas: turn on the agent tools in the Dash, yes or no?", + }, + ], + note: "The asks were checked on 23 Nov.", + }, + mind.deps, + NOW, + ); + assert.deepEqual(done.card.humanAsk, [ + "Xero's plan, or our own adapter?", + "Jonas: turn on the agent tools in the Dash, yes or no?", + ]); + const text = mind.file("todo/fix-the-bar.md"); + assert.match( + text, + /\n## Log\n\n- 2026-11-20 16:05 UTC, \/agents\/engineering-manager: An ask was taken off, with no answer: PR-55 merged on 21 Nov 2026 at 21:36 UTC\. It began: "Jonas: ONE DECISION, on the final pinned head of PR-55: 98c082d71 \(green; mergeable\)\. DONE as you a…"\n/, + ); + assert.match( + text, + /\n- 2026-11-20 16:05 UTC, \/agents\/engineering-manager: An ask was written again in plain words\. It began: "Turn the agent tools on\? Yes or no\."\n- 2026-11-20 16:05 UTC, \/agents\/engineering-manager: The asks were checked on 23 Nov\.\n$/, + ); + assert.doesNotMatch(text, /## Answers/); + // the message names each ask's change, and the three notes once + assert.match( + mind.commits[0].message, + /^tasks: 3 changes\n\n- todo\/fix-the-bar\.md: no longer asks "Jonas: ONE DECISION[^\n]*\n- todo\/fix-the-bar\.md: a note\n- todo\/fix-the-bar\.md: asks again, as "Jonas: turn on the agent tools in the Dash, yes or no\?"\n\nVia: \/agents\/engineering-manager$/, + ); + // a beginning that fits no ask, or two, is refused with what the card asks; nothing is written + await assert.rejects( + taskUpdate( + mind.itx, + { file: "todo/fix-the-bar.md", withdraw: { ask: "Merge it?", why: "merged" } }, + mind.deps, + NOW, + ), + /no ask of todo\/fix-the-bar\.md begins with "Merge it\?"\. It asks: "Xero's plan, or our own adapter\?", "Jonas: turn on/, + ); + const two = fakeMind({ + files: { + "todo/fix-the-bar.md": CARD.replace( + "owner: misha@nustom.com\n", + "owner: misha@nustom.com\nhuman-ask:\n - Jonas, the first?\n - Jonas, the second?\n", + ), + }, + }); + await assert.rejects( + taskUpdate( + two.itx, + { file: "todo/fix-the-bar.md", reword: { ask: "Jonas, the", to: "One?" } }, + two.deps, + NOW, + ), + /2 asks of todo\/fix-the-bar\.md begin with "Jonas, the"/, + ); + await assert.rejects( + taskUpdate( + two.itx, + { file: "todo/fix-the-bar.md", withdraw: { ask: "Jonas, the first?" } }, + two.deps, + NOW, + ), + /withdraw is \{ ask, why \}/, + ); + await assert.rejects( + taskUpdate( + two.itx, + { file: "todo/fix-the-bar.md", reword: ["Jonas, the first?"] }, + two.deps, + NOW, + ), + /reword is \{ ask, to \}/, + ); + assert.deepEqual([mind.commits.length, two.commits.length], [1, 0]); +}); + +test("an update of nothing is refused, in words; a commit that another one overtook is made again", async () => { + const mind = fakeMind(); + await assert.rejects( + taskUpdate(mind.itx, { file: "todo/fix-the-bar.md" }, mind.deps, NOW), + /name what changes: status, title, owner/, + ); + await assert.rejects( + taskUpdate(mind.itx, { file: "worker.ts", status: "done" }, mind.deps, NOW), + /file is a task's path/, + ); + await assert.rejects( + taskUpdate(mind.itx, { file: "todo/none.md", status: "done" }, mind.deps, NOW), + /\/repos\/task-board has no todo\/none\.md/, + ); + await assert.rejects( + taskUpdate(mind.itx, { file: "todo/fix-the-bar.md", status: " " }, mind.deps, NOW), + /status is a word/, + ); + await assert.rejects( + taskUpdate(mind.itx, ["todo/fix-the-bar.md"], mind.deps, NOW), + /taskUpdate takes \{ file, status\?/, + ); + assert.equal(mind.commits.length, 0); + const { get } = mind.itx.repos; + let stale = true; + mind.itx.repos.get = (path) => ({ + ...get(path), + tip: async () => (stale ? ((stale = false), "t0") : get(path).tip()), + }); + const done = await taskUpdate( + mind.itx, + { file: "todo/fix-the-bar.md", status: "done" }, + mind.deps, + NOW, + ); + assert.deepEqual([done.commitOid, done.card.status, mind.commits.length], ["t1+", "done", 1]); +}); + +test("a card given to an agent that runs: the card names it, and it gets the brief once", async () => { + const mind = fakeMind({ caller: EM }); + const owner = "/agents/claude/owner-1"; + const given = await taskAssign( + mind.itx, + { file: "todo/fix-the-bar.md", agent: owner, message: " Misha waits\n in the room. " }, + mind.deps, + NOW, + ); + assert.deepEqual( + [given.agent, given.starting, given.model, given.running, given.card.status, given.card.agent], + [owner, false, null, null, "in-progress", owner], + ); + assert.equal( + mind.file("todo/fix-the-bar.md"), + `---\nstatus: in-progress\nowner: misha@nustom.com\nagent: "${owner}"\n---\n\n# Fix the bar\n\nIn Misha's words: the bar overlaps.\n\n## Log\n\n- 2026-11-20 16:05 UTC, ${EM}: Given to ${owner}.\n`, + ); + assert.deepEqual( + mind.messages.map((message) => message.to), + [owner], + ); + const [{ text }] = mind.messages; + assert.match( + text, + /^You have a task from \/agents\/engineering-manager\. The card is your brief: todo\/fix-the-bar\.md in the repo \/repos\/task-board of this mind\.\n\n1\. Read it/, + ); + assert.match( + text, + /itx\.config\.followTasks\(\{ file: "todo\/fix-the-bar\.md", agent: "\/agents\/claude\/owner-1", repo: "task-board" \}\)/, + ); + assert.match( + text, + /itx\.config\.taskUpdate\(\{ file: "todo\/fix-the-bar\.md", by: "\/agents\/claude\/owner-1", note: "…", repo: "task-board" \}\)/, + ); + assert.match( + text, + /\n4\. Send no status messages: whoever needs your state reads the card or follows it\.\n5\. Close out your own card: [^\n]*gets a card of its own \(taskOpen\) BEFORE you close, and your last note names it\.\n\nIn the words/, + ); + assert.match( + text, + /\n\nIn the words of the agent that gives you the card: Misha waits in the room\.$/, + ); + assert.equal(mind.appended.length, 0); + // a card that is in review or done keeps its status + const late = fakeMind({ + files: { "todo/fix-the-bar.md": CARD.replace("status: todo", "status: in-review") }, + }); + assert.equal( + ( + await taskAssign( + late.itx, + { file: "todo/fix-the-bar.md", agent: owner, by: EM }, + late.deps, + NOW, + ) + ).card.status, + "in-review", + ); +}); + +test("a mind's own start of a new agent: the card names what it started, and the brief ends with the mind's own rules", async () => { + const file = "todo/fix-the-bar.md"; + const worker = "/agents/claude/fix-bar-abc123"; + const asked = []; + const own = { + startWorker: async (_itx, input) => { + asked.push(input); + return { agent: worker, model: "a-model", effort: "medium", running: 2 }; + }, + briefRules: async ({ worker: isNew }) => [ + "6. Merge your own pull request.", + ...(isNew ? ["7. One heavy check at a time."] : []), + ], + }; + const mind = fakeMind({ caller: EM, own }); + const given = await taskAssign( + mind.itx, + { file, worker: { name: "fix-bar", repo: "config" } }, + mind.deps, + NOW, + ); + assert.deepEqual(asked, [ + { worker: { name: "fix-bar", repo: "config" }, by: EM, file, repo: "/repos/task-board" }, + ]); + assert.deepEqual( + [given.agent, given.starting, given.model, given.effort, given.running], + [worker, true, "a-model", "medium", 2], + ); + assert.deepEqual( + [given.card.agent, given.card.model, given.card.effort, given.card.status], + [worker, "a-model", "medium", "in-progress"], + ); + assert.match( + mind.file(file), + /\nagent: "\/agents\/claude\/fix-bar-abc123"\nmodel: a-model\neffort: medium\n---\n/, + ); + // the card says what is true at this moment: the worker was asked for + assert.match( + mind.file(file), + /A new worker was asked for: \/agents\/claude\/fix-bar-abc123 \(a-model, medium\)\.\n$/, + ); + assert.deepEqual( + mind.messages.map((message) => message.to), + [worker], + ); + assert.match( + mind.messages[0].text, + /\n5\. Close out your own card: [^\n]*\n6\. Merge your own pull request\.\n7\. One heavy check at a time\.$/, + ); + // an agent that runs gets the mind's rules too, without those of a new one + const old = fakeMind({ caller: EM, own }); + await taskAssign(old.itx, { file, agent: "/agents/claude/owner-1" }, old.deps, NOW); + assert.match(old.messages[0].text, /\n6\. Merge your own pull request\.$/); + // a start that names no model: the card names the agent alone + const bare = fakeMind({ caller: EM, own: { startWorker: async () => ({ agent: worker }) } }); + const plain = await taskAssign(bare.itx, { file, worker: {} }, bare.deps, NOW); + assert.deepEqual( + [plain.model, plain.effort, plain.running, plain.card.model], + [null, null, null, ""], + ); + assert.match( + bare.file(file), + /A new worker was asked for: \/agents\/claude\/fix-bar-abc123\.\n$/, + ); + // the start's own refusal is the call's: nothing was written + const refused = fakeMind({ + caller: EM, + own: { + startWorker: async () => { + throw new Error("this computer is short of memory"); + }, + }, + }); + await assert.rejects( + taskAssign(refused.itx, { file, worker: { name: "a" } }, refused.deps, NOW), + /this computer is short of memory/, + ); + assert.deepEqual([refused.commits.length, refused.messages.length], [0, 0]); + // a mind that starts no agent says so, and writes nothing + const none = fakeMind({ caller: EM }); + await assert.rejects( + taskAssign(none.itx, { file, worker: { name: "a" } }, none.deps, NOW), + /this mind starts no new agent for a card\. Give the card to an agent that runs: \{ file, agent \}\./, + ); + assert.deepEqual([none.commits.length, none.messages.length], [0, 0]); +}); + +test("an agent that provably does not run takes no card; one that cannot be proven gone takes it", async () => { + const file = "todo/fix-the-bar.md"; + // as the mind's catalog has them: a closed window sends no end, so its row stays idle + const closed = "/agents/claude/first-deploy-fix-mwo8bsev-4c0268"; + // NOW is 20 Nov 16:05 UTC: a turn of 14:05 was 2 hours ago, one of the day before 24 hours ago + const lately = "2026-11-20T14:05:00.000Z"; + const yesterday = "2026-11-19T16:05:00.000Z"; + const rows = { + [closed]: { kind: "claude", status: "idle", lastActivityAt: lately }, + "/agents/claude/owner-1": { kind: "claude", status: "idle", lastActivityAt: yesterday }, + "/agents/claude/failed-start-abc123": { kind: "claude", status: "ended" }, + "/agents/claude/on-a-mac-abc123": { kind: "claude", status: "idle", lastActivityAt: lately }, + "/agents/claude/on-a-mac-def456": { + kind: "claude", + status: "working", + lastActivityAt: yesterday, + }, + "/agents/codex/long-idle": { kind: "codex", status: "idle", lastActivityAt: yesterday }, + "/agents/herdr/a-pane": { kind: "herdr", status: "idle" }, + [EM]: { kind: "iterate", status: "idle", lastActivityAt: yesterday }, + }; + // what this mind can prove of a session: it lists the ones that run on its own computer + const seen = []; + const own = { + sessionState: async (_itx, agent, row) => { + seen.push([agent, row.kind]); + if (agent === "/agents/claude/owner-1") return "runs"; + if (agent === closed) return "is a session that does not run now"; + return undefined; + }, + }; + const mind = fakeMind({ caller: EM, rows, own }); + await assert.rejects( + taskAssign(mind.itx, { file, agent: closed }, mind.deps, NOW), + /first-deploy-fix-mwo8bsev-4c0268 is a session that does not run now\. Nobody would read the card\. Give it to an agent that runs; name \/agents\/claude\/first-deploy-fix-mwo8bsev-4c0268 in the card's text/, + ); + await assert.rejects( + taskAssign(mind.itx, { file, agent: "/agents/claude/failed-start-abc123" }, mind.deps, NOW), + /failed-start-abc123 has ended\. Nobody would read the card/, + ); + // nothing was written and nobody was told; a row that ended is not asked about + assert.deepEqual([mind.commits.length, mind.messages.length], [0, 0]); + assert.deepEqual(seen, [[closed, "claude"]]); + // the mind proves that it runs, however long ago its last turn was + assert.equal( + (await taskAssign(mind.itx, { file, agent: "/agents/claude/owner-1" }, mind.deps, NOW)).agent, + "/agents/claude/owner-1", + ); + // WHAT THE MIND CANNOT PROVE goes by the agent's last turn. Given: a session with a turn 2 hours + // ago; a row with no time; and an iterate agent, which is the mind's own loop, however long it + // was idle. With no `sessionState` at all, the last turn decides for every session + for (const agent of ["/agents/claude/on-a-mac-abc123", "/agents/herdr/a-pane", EM]) { + const each = fakeMind({ caller: SYSADMIN, rows, own }); + assert.equal( + (await taskAssign(each.itx, { file, agent }, each.deps, NOW)).card.agent, + agent, + agent, + ); + } + const plain = fakeMind({ caller: EM, rows }); + assert.equal( + (await taskAssign(plain.itx, { file, agent: closed }, plain.deps, NOW)).agent, + closed, + ); + // refused: no turn for a day, whatever the row says the agent does + for (const agent of ["/agents/claude/on-a-mac-def456", "/agents/codex/long-idle"]) { + const each = fakeMind({ caller: SYSADMIN, rows, own }); + await assert.rejects( + taskAssign(each.itx, { file, agent }, each.deps, NOW), + /has had no turn since 2026-11-19 16:05 UTC \(more than 12 hours\), and the mind cannot tell whether it still runs\. Nobody would read the card\. Give it to an agent that runs/, + agent, + ); + assert.deepEqual([each.commits.length, each.messages.length], [0, 0]); + } +}); + +test("what goes wrong when a card is given is said in words, with what to do", async () => { + const mind = fakeMind({ caller: EM }); + const file = "todo/fix-the-bar.md"; + await assert.rejects( + taskAssign(mind.itx, { file }, mind.deps, NOW), + /taskAssign takes \{ file, agent \} for an agent that runs, or \{ file, worker/, + ); + await assert.rejects( + taskAssign( + mind.itx, + { file, agent: "/agents/a", worker: { name: "a", repo: "private" } }, + mind.deps, + NOW, + ), + /taskAssign takes/, + ); + await assert.rejects( + taskAssign(mind.itx, { file, agent: "/agents/typo" }, mind.deps, NOW), + /\/agents\/typo is no agent/, + ); + await assert.rejects( + taskAssign(mind.itx, { file, worker: "fix-bar" }, mind.deps, NOW), + /worker is what this mind's start of a new agent takes, as an object/, + ); + await assert.rejects( + taskAssign(mind.itx, { file: "todo/none.md", agent: EM }, mind.deps, NOW), + /\/repos\/task-board has no todo\/none\.md\. Open the card first \(taskOpen\)\./, + ); + assert.deepEqual([mind.commits.length, mind.messages.length], [0, 0]); + // the card was written and the agent did not take the message: the call says how to send it again + const deaf = fakeMind({ caller: EM, machine: { deaf: "/agents/claude/owner-1" } }); + await assert.rejects( + taskAssign(deaf.itx, { file, agent: "/agents/claude/owner-1" }, deaf.deps, NOW), + /the card names \/agents\/claude\/owner-1, and the message to it failed \(no such agent\): call taskAssign again with \{ file: "todo\/fix-the-bar\.md", agent: "\/agents\/claude\/owner-1" \}/, + ); + assert.equal(parseTask(file, deaf.file(file)).agent, "/agents/claude/owner-1"); +}); + +test("the brief names the repo when it is not the tasks repo, and its sender when there is one", () => { + const far = briefOf({ + repo: "/repos/other", + file: "todo/a.md", + agent: "/agents/w", + by: null, + words: "", + }); + assert.match( + far, + /^You have a task\. The card is your brief: todo\/a\.md in the repo \/repos\/other of this mind\./, + ); + assert.match( + far, + /followTasks\(\{ file: "todo\/a\.md", agent: "\/agents\/w", repo: "other" \}\)/, + ); + assert.match( + far, + /taskUpdate\(\{ file: "todo\/a\.md", by: "\/agents\/w", note: "…", repo: "other" \}\)/, + ); + assert.doesNotMatch(far, /In the words of/); +}); + +test("a mind's own way with a note: the card keeps what it answers, and a mind with none keeps the note", async () => { + const file = "todo/fix-the-bar.md"; + const mind = fakeMind({ + caller: EM, + own: { + linkNote: async (_itx, note) => + note.replace("9217f14", "[9217f14](https://example.com/c/9217f14)"), + }, + }); + await taskUpdate( + mind.itx, + { file, status: "done", note: "Live: config commit 9217f14." }, + mind.deps, + NOW, + ); + assert.match( + mind.file(file), + /: Live: config commit \[9217f14\]\(https:\/\/example\.com\/c\/9217f14\)\.\n$/, + ); + const plain = fakeMind({ caller: EM }); + await taskUpdate(plain.itx, { file, note: "Live: config commit 9217f14." }, plain.deps, NOW); + assert.match(plain.file(file), /: Live: config commit 9217f14\.\n$/); +}); + +test("an ask that is a choice brings its options and a recommendation, or says why it is no choice", async () => { + const decision = { + options: [ + { name: "Friday", tradeoff: "Live two days sooner; nobody watches it over the weekend." }, + { name: "Monday", tradeoff: "Two days later; the team is there when it lands." }, + ], + recommend: "Monday", + why: "The change touches sign-in.", + }; + const mind = fakeMind(); + const done = await taskUpdate( + mind.itx, + { + file: "todo/fix-the-bar.md", + by: "/agents/worker", + ask: "Jonas: ship on Friday or on Monday?", + decision, + }, + mind.deps, + NOW, + ); + assert.deepEqual(done.card.humanAsk, ["Jonas: ship on Friday or on Monday?"]); + assert.equal( + mind.file("todo/fix-the-bar.md"), + "---\nstatus: todo\nowner: misha@nustom.com\nhuman-ask:\n - Jonas: ship on Friday or on Monday?\n---\n\n# Fix the bar\n\nIn Misha's words: the bar overlaps.\n\n## Decisions\n\n- **Jonas: ship on Friday or on Monday?**\n - Option: Friday: Live two days sooner; nobody watches it over the weekend.\n - Option: Monday: Two days later; the team is there when it lands.\n - Recommended: Monday: The change touches sign-in.\n", + ); + assert.equal(mind.commits.length, 1); + assert.equal(done.warning, undefined); + // an ask with neither is taken, and the call's answer warns ("Only warn": Jonas, 25 Nov 2026) + const bare = fakeMind(); + const warned = await taskUpdate( + bare.itx, + { file: "todo/fix-the-bar.md", ask: "Ship it?" }, + bare.deps, + NOW, + ); + assert.deepEqual(warned.card.humanAsk, ["Ship it?"]); + assert.match( + warned.warning, + /^This ask has no options\. An ask that is a choice names them: add decision: .* add noChoice: "<why>" instead/, + ); + assert.match( + (await taskOpen(bare.itx, { title: "A card", ask: "Ship it?" }, bare.deps)).warning, + /^This ask has no options/, + ); + // no warning for an ask that says why it is no choice, and none for a call that adds no ask + assert.equal( + ( + await taskUpdate( + bare.itx, + { + file: "todo/fix-the-bar.md", + ask: "Open the link?", + noChoice: "Only a person sees the page.", + }, + bare.deps, + NOW, + ) + ).warning, + undefined, + ); + assert.equal( + (await taskUpdate(bare.itx, { file: "todo/fix-the-bar.md", note: "x" }, bare.deps, NOW)) + .warning, + undefined, + ); + const refused = fakeMind(); + // a decision that is not whole + const bad = (change, words) => + assert.rejects( + taskUpdate( + refused.itx, + { file: "todo/fix-the-bar.md", ask: "Ship it?", decision: { ...decision, ...change } }, + refused.deps, + NOW, + ), + words, + ); + await bad({ options: [decision.options[0]] }, /at least two options/); + await bad( + { options: [{ name: "Friday" }, decision.options[1]] }, + /each of decision\.options is \{ name, tradeoff \}/, + ); + await bad( + { recommend: "Tuesday" }, + /decision\.recommend is the name of one option: "Friday", "Monday"/, + ); + await bad({ why: " " }, /decision\.why says why/); + await assert.rejects( + taskUpdate( + refused.itx, + { file: "todo/fix-the-bar.md", ask: ["One?", "Two?"], decision }, + refused.deps, + NOW, + ), + /a decision is of ONE ask/, + ); + await assert.rejects( + taskUpdate( + refused.itx, + { file: "todo/fix-the-bar.md", note: "x", decision }, + refused.deps, + NOW, + ), + /go with an ask/, + ); + assert.equal(refused.commits.length, 0); + // a new card with a decision ask + const opened = await taskOpen( + refused.itx, + { title: "Ship day", ask: "Jonas: ship on Friday or on Monday?", decision }, + refused.deps, + ); + assert.match( + refused.file(opened.file), + /## Decisions\n\n- \*\*Jonas: ship on Friday or on Monday\?\*\*\n {2}- Option: Friday: /, + ); + // the first message to a card's agent says the rule + assert.match( + briefOf({ repo: "/repos/task-board", file: "todo/a.md", agent: "/agents/a", by: EM }), + /An ask that is a choice goes with decision: \{ options: \[\{ name, tradeoff \}, …\], recommend, why \}.* its answer then holds a warning/, + ); +}); + +test("an ask whose answer another agent acts on names that agent, and the words that the asker waits for", async () => { + const mind = fakeMind({ caller: EM }); + const file = "todo/fix-the-bar.md"; + const told = await taskUpdate( + mind.itx, + { + file, + ask: "Jonas: release the move of Jeeves.", + tell: { agent: " /agents/sysadmin ", words: "Move Jeeves after the local test." }, + }, + mind.deps, + NOW, + ); + // it is no choice: no warning, and the card keeps where the answer goes + assert.equal(told.warning, undefined); + assert.deepEqual(told.card.humanAsk, ["Jonas: release the move of Jeeves."]); + assert.match( + mind.file(file), + /\n## Decisions\n\n- \*\*Jonas: release the move of Jeeves\.\*\*\n {2}- Tell: \/agents\/sysadmin: Move Jeeves after the local test\.\n/, + ); + assert.match( + mind.commits[0].message, + /"Jonas: release the move of Jeeves\." is answered by a message to \/agents\/sysadmin/, + ); + // what is refused, in words, and writes nothing + const before = mind.commits.length; + await assert.rejects( + taskUpdate( + mind.itx, + { file, ask: "A?", tell: { agent: "sysadmin", words: "x" } }, + mind.deps, + NOW, + ), + /tell\.agent is the path of the agent/, + ); + await assert.rejects( + taskUpdate( + mind.itx, + { file, ask: ["A?", "B?"], tell: { agent: "/agents/a", words: "x" } }, + mind.deps, + NOW, + ), + /a tell is of ONE ask/, + ); + await assert.rejects( + taskUpdate(mind.itx, { file, tell: { agent: "/agents/a", words: "x" } }, mind.deps, NOW), + /go with an ask, and this call adds none/, + ); + await assert.rejects( + taskUpdate( + mind.itx, + { + file, + ask: "A?", + tell: { agent: "/agents/a", words: "x" }, + decision: { + options: [ + { name: "a", tradeoff: "x" }, + { name: "b", tradeoff: "y" }, + ], + recommend: "a", + why: "z", + }, + }, + mind.deps, + NOW, + ), + /a decision or a tell, not both/, + ); + assert.equal(mind.commits.length, before); + // a new card takes one too + const opened = await taskOpen( + mind.itx, + { title: "Release", ask: "Jonas: say go.", tell: { agent: "/agents/sysadmin", words: "Go." } }, + mind.deps, + ); + assert.match(mind.file(opened.file), / {2}- Tell: \/agents\/sysadmin: Go\.\n/); +});
A tests/feed.test.mjs
@@ -0,0 +1,661 @@ +// feed.test.mjs — the task change feed (feed.js): what an update of the tasks repo's main turns +// into, and how an agent follows. Run it with `node --test apps/tasks/`. +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { + boardPathOf, + FEED_TRUNCATED, + followRowOf, + followTasks, + isTaskFile, + lineDiff, + MAX_DIFF_BYTES, + MAX_FILE_BYTES, + MAX_FILES, + MOVES, + TASK_CHANGED, + TASK_FEED, + taskChangeOf, + taskChangesEvent, + taskFollowers, + unfollowTasks, +} from "../feed.js"; + +const REPO = "/repos/task-board"; +const BOARD = "/task-files/task-board"; +const OTHER = "/repos/other"; +const OTHER_BOARD = "/task-files/other"; +const card = (status, extra = "") => + `---\nstatus: ${status}\ntags: [a, b]\n${extra}---\n\n# Ship it\n\nBody.\n`; +const fact = { + commitOid: "c2", + beforeOid: "c1", + commitOffset: 7, + committedAt: "2026-11-20T14:00:00.000Z", + message: "tasks: move", + by: "a@x", +}; + +test("a task file is Markdown under the folder; a feed with no folder takes the whole repo", () => { + assert.equal(boardPathOf(TASK_FEED), BOARD); + assert.deepEqual( + ["todo/a.md", "todo/a/b.markdown", "tasksx/c.md", "todo/img.png", "worker.ts"].map((path) => + isTaskFile(TASK_FEED, path), + ), + [true, true, false, false, false], + ); + assert.equal(isTaskFile({ ...TASK_FEED, dir: "" }, "a.md"), true); +}); + +test("modified: the card before and after, one line that says what moved, and a small diff", () => { + const change = taskChangeOf({ + feed: TASK_FEED, + fact, + file: "todo/x.md", + before: card("todo"), + after: card( + "in-progress", + "blocked-on: PR #12\nhuman-ask:\n - Sign the grant?\n - Merge #12, or wait?\n", + ), + }); + assert.equal(change.change, "modified"); + assert.deepEqual( + [ + change.repo, + change.file, + change.commitOid, + change.beforeOid, + change.commitOffset, + change.message, + change.by, + ], + [REPO, "todo/x.md", "c2", "c1", 7, "tasks: move", "a@x"], + ); + assert.deepEqual(change.before, { + title: "Ship it", + status: "todo", + tags: ["a", "b"], + owner: "", + agent: "", + blockedOn: null, + humanAsk: null, + }); + assert.equal(change.after.blockedOn, "PR #12"); + assert.deepEqual(change.after.humanAsk, ["Sign the grant?", "Merge #12, or wait?"]); + assert.equal( + change.summary, + "todo/x.md changed by a@x: status todo → in-progress; blocked-on none → PR #12; human-ask +2 -0 (now 2)", + ); + assert.deepEqual(change.moved, ["status", "blocked-on", "human-ask"]); + const given = taskChangeOf({ + feed: TASK_FEED, + fact, + file: "todo/x.md", + before: card("todo"), + after: card("todo", "owner: jonas\nagent: /agents/w\n") + .replace("# Ship it", "# Ship it now") + .replace("[a, b]", "[a]"), + }); + assert.deepEqual(given.moved, ["title", "owner", "agent", "tags"]); + assert.ok([...change.moved, ...given.moved].every((move) => MOVES.includes(move))); + assert.equal( + change.diff, + "@@ -1,5 +1,9 @@\n ---\n-status: todo\n+status: in-progress\n tags: [a, b]\n+blocked-on: PR #12\n+human-ask:\n+ - Sign the grant?\n+ - Merge #12, or wait?\n ---\n ", + ); + assert.equal(change.diffOmitted, undefined); +}); + +test("added and deleted; a change of the text alone says so", () => { + const added = taskChangeOf({ + feed: TASK_FEED, + fact, + file: "todo/x.md", + before: null, + after: "# New\n", + }); + assert.deepEqual([added.change, added.before, added.after.title], ["added", null, "New"]); + assert.equal(added.summary, 'todo/x.md added by a@x: "New", status none'); + assert.equal(added.diff, "@@ -0,0 +1,1 @@\n+# New"); + const deleted = taskChangeOf({ + feed: TASK_FEED, + fact: { ...fact, by: null }, + file: "todo/x.md", + before: "# Old\n", + after: null, + }); + assert.deepEqual( + [deleted.change, deleted.after, deleted.summary], + ["deleted", null, 'todo/x.md deleted: "Old"'], + ); + assert.equal(deleted.diff, "@@ -1,1 +0,0 @@\n-# Old"); + const body = taskChangeOf({ + feed: TASK_FEED, + fact, + file: "todo/x.md", + before: card("todo"), + after: card("todo").replace("Body.", "Body, and more."), + }); + assert.equal(body.summary, "todo/x.md changed by a@x: its text"); + // what moved, by name: a file that came or went, and "text" for a change that moved no field + assert.deepEqual([added.moved, deleted.moved, body.moved], [["added"], ["deleted"], ["text"]]); +}); + +test("an ask that left with an answer is told with its answer; one that only left is counted", () => { + const asks = card( + "todo", + "human-ask:\n - Merge #12 now, or wait?\n - Sign the grant?\n - A third one?\n", + ); + // the first is answered by the committer, the second by another person (an agent wrote it down), the third is withdrawn + const after = `${card("todo")}\n## Answers\n\n- **Merge #12 now, or wait?** Wait for the deploy. (a@x, 2026-11-20 14:50 UTC)\n- **Sign the grant?** Signed. (misha@nustom.com, 2026-11-20 14:51 UTC)\n`; + const told = taskChangeOf({ feed: TASK_FEED, fact, file: "todo/x.md", before: asks, after }); + assert.equal( + told.summary, + 'todo/x.md changed by a@x: answered "Merge #12 now, or wait?": Wait for the deploy.; answered "Sign the grant?": Signed. (misha@nustom.com); human-ask +0 -1 (now 0)', + ); + // an answer moves the asks: a follower of asks alone hears of it + assert.deepEqual(told.moved, ["human-ask"]); + // a long ask and a long answer are cut, and the whole line stays under its bound + const long = taskChangeOf({ + feed: TASK_FEED, + fact, + file: "todo/x.md", + before: card("todo", `human-ask:\n - ${"q".repeat(200)}?\n`), + after: `${card("todo")}\n## Answers\n\n- **${"q".repeat(200)}?** ${"y".repeat(900)} (a@x, 2026-11-20 14:50 UTC)\n`, + }); + assert.equal( + long.summary, + `todo/x.md changed by a@x: answered "${"q".repeat(69)}…": ${"y".repeat(159)}…`, + ); +}); + +test("a diff keeps the lines between two changes out, and shows a missing line end", () => { + const lines = Array.from({ length: 12 }, (_, at) => `line ${at + 1}`); + const after = lines.map((line, at) => (at === 1 ? "LINE 2" : at === 10 ? "LINE 11" : line)); + assert.equal( + lineDiff(`${lines.join("\n")}\n`, `${after.join("\n")}\n`), + "@@ -1,4 +1,4 @@\n line 1\n-line 2\n+LINE 2\n line 3\n line 4\n@@ -9,4 +9,4 @@\n line 9\n line 10\n-line 11\n+LINE 11\n line 12", + ); + assert.equal(lineDiff("same", "same"), ""); + assert.equal(lineDiff("a\n", "a"), "@@ -1,2 +1,1 @@\n a\n-"); + // two changes that touch are one stretch + assert.equal(lineDiff("a\nb\nc\nd\n", "A\nb\nc\nD\n"), "@@ -1,4 +1,4 @@\n-a\n+A\n b\n c\n-d\n+D"); +}); + +test("a big diff and a big file are left out with a flag; the card is still told", () => { + const big = taskChangeOf({ + feed: TASK_FEED, + fact, + file: "todo/x.md", + before: "a\n", + after: `${"y".repeat(MAX_DIFF_BYTES)}\n`, + }); + assert.deepEqual([big.diff, big.diffOmitted], [null, "diff-too-large"]); + const huge = taskChangeOf({ + feed: TASK_FEED, + fact, + file: "todo/x.md", + before: card("todo"), + after: card("done") + "z".repeat(MAX_FILE_BYTES), + }); + assert.deepEqual( + [huge.diff, huge.diffOmitted, huge.after.status], + [null, "file-too-large", "done"], + ); +}); + +// A fake mind: the repo's own log of facts, a commit's files, logs that refuse a second key with +// other content, and rows as the platform lists them. +function fakeMind({ facts, files, agents = [], otherFacts = [] }) { + const logs = new Map([ + [REPO, facts], + [OTHER, otherFacts], + ]); + const keys = new Map(); + const reads = []; + const eventsOf = (path) => logs.get(path) ?? logs.set(path, []).get(path); + const itx = { + repos: { + list: async () => [{ path: REPO }, { path: OTHER }], + get: () => ({ + modules: async ({ commitOid, dir }) => { + reads.push(commitOid); + if (!files[commitOid]) throw new Error(`no commit ${commitOid}`); + return Object.fromEntries( + Object.entries(files[commitOid]) + .filter(([path]) => path.startsWith(`${dir}/`)) + .map(([path, text]) => [path.slice(dir.length + 1), text]), + ); + }, + readFile: async (path) => Object.values(files).at(-1)[path] ?? null, + }), + }, + cd: (path) => ({ + readEvents: async (after, limit) => { + const events = eventsOf(path) + .filter((event) => event.offset > after) + .slice(0, limit); + return { + events, + scannedThroughOffset: events.at(-1)?.offset ?? eventsOf(path).at(-1)?.offset ?? 0, + }; + }, + append: async (event) => { + const seen = keys.get(`${path} ${event.idempotencyKey}`); + if (event.idempotencyKey && seen) { + if (JSON.stringify(seen) === JSON.stringify(event.payload)) return; + throw Object.assign(new Error("IDEMPOTENCY_CONFLICT"), { code: "IDEMPOTENCY_CONFLICT" }); + } + if (event.idempotencyKey) keys.set(`${path} ${event.idempotencyKey}`, event.payload); + eventsOf(path).push({ ...event, path, offset: (eventsOf(path).at(-1)?.offset ?? 0) + 1 }); + }, + subscriptions: { + // the rows as the platform folds them: the last event of a name, none after `target: null` + list: async () => { + const rows = new Map(); + for (const event of eventsOf(path).filter((each) => + each.type.endsWith("/itx/subscription-configured"), + )) { + if (event.payload.target === null) rows.delete(event.payload.name); + else + rows.set(event.payload.name, { + name: event.payload.name, + filter: event.payload.filter, + copy: event.payload.target, + }); + } + return [...rows.values()]; + }, + }, + }), + }; + const deps = { callerPath: () => "/", isAgent: async (path) => agents.includes(path) }; + return { + itx, + deps, + reads, + told: (log = BOARD) => eventsOf(log).filter((event) => !event.type.includes("/itx/")), + rows: (log = BOARD) => itx.cd(log).subscriptions.list(), + }; +} +const commitFact = (offset, commitOid, changedPaths, repo = REPO) => ({ + type: "events.iterate.com/repo/commit-completed", + path: repo, + offset, + createdAt: `2026-11-20T14:00:0${offset}.000Z`, + source: { onBehalfOf: { principal: { actor: "user_1", email: "a@x" } } }, + payload: { path: repo, commitOid, message: `${commitOid}\n\nmore`, changedPaths }, +}); +/** Three updates of main, with other events of the repo's log between them. */ +function history() { + const facts = [ + commitFact(2, "c1", ["todo/a.md"]), + { type: "events.iterate.com/repo/pushed", path: REPO, offset: 3, payload: {} }, + commitFact(5, "c2", ["todo/a.md", "worker.ts"]), + { type: "events.iterate.com/itx/woken", path: REPO, offset: 6, payload: {} }, + commitFact(9, "c3", ["todo/b.md"]), + ]; + const files = { + c1: { "todo/a.md": "a1\n", "worker.ts": "w1" }, + c2: { "todo/a.md": "a2\n", "worker.ts": "w2" }, + c3: { "todo/a.md": "a2\n", "todo/b.md": "# B\n", "worker.ts": "w2" }, + }; + return { facts, files }; +} + +test("before is the commit of the fact before on the repo's log, whatever order the facts arrive in", async () => { + const { facts, files } = history(); + const mind = fakeMind({ facts, files }); + // the newest first, then the one before it, as an unordered delivery may hand them over + await taskChangesEvent(mind.itx, facts[4]); + await taskChangesEvent(mind.itx, facts[2]); + const [b, a] = mind.told(); + assert.deepEqual( + [ + b.type, + b.payload.file, + b.payload.change, + b.payload.beforeOid, + b.payload.commitOid, + b.payload.commitOffset, + ], + [TASK_CHANGED, "todo/b.md", "added", "c2", "c3", 9], + ); + assert.deepEqual( + [ + a.payload.file, + a.payload.change, + a.payload.beforeOid, + a.payload.commitOid, + a.payload.commitOffset, + ], + ["todo/a.md", "modified", "c1", "c2", 5], + ); + assert.equal(a.payload.diff, "@@ -1,1 +1,1 @@\n-a1\n+a2"); + assert.deepEqual( + [a.payload.by, a.payload.message, a.payload.committedAt], + ["a@x", "c2", "2026-11-20T14:00:05.000Z"], + ); + assert.equal(a.idempotencyKey, "todo/task-changed:/repos/task-board@5:todo/a.md"); + // the repo's first fact has no commit before it: its files are added. A commit that no person + // asked for is by the context whose event caused it + await taskChangesEvent(mind.itx, { + ...facts[0], + source: { origin: REPO, cause: { parent: "/agents/meet/a-call@2161" } }, + }); + const first = mind.told()[2].payload; + assert.deepEqual( + [first.change, first.beforeOid, first.by, first.via], + ["added", null, "/agents/meet/a-call", null], + ); + assert.equal(first.summary, 'todo/a.md added by /agents/meet/a-call: "A", status none'); +}); + +test("a commit that an agent's session made through a person's sign-in says so: its Via line", async () => { + const { facts, files } = history(); + const mind = fakeMind({ facts, files }); + // the platform stamps the person; the commit's message names the session + const message = + "tasks: a moves\n\nWhy it moved.\n\nVia: Claude Code (tasks pilot, session b7fb218f on beelink)\nIterate-Run: /@187197"; + await taskChangesEvent(mind.itx, { ...facts[2], payload: { ...facts[2].payload, message } }); + const [told] = mind.told(); + assert.deepEqual( + [told.payload.by, told.payload.via, told.payload.message], + ["a@x", "Claude Code (tasks pilot, session b7fb218f on beelink)", "tasks: a moves"], + ); + assert.equal( + told.payload.summary, + "todo/a.md changed by a@x via Claude Code (tasks pilot, session b7fb218f on beelink): its text", + ); + // a script through a person's sign-in has no page; the person's own act on the board has one + assert.equal(told.payload.page, null); + const onBoard = { + onBehalfOf: { + principal: { actor: "user_1", email: "a@x" }, + via: { appPage: "tasks.iterate.com" }, + call: "/repos/task-board#repo.commitFiles", + }, + }; + await taskChangesEvent(mind.itx, { ...facts[4], source: onBoard }); + const own = mind.told()[1].payload; + assert.deepEqual([own.by, own.page, own.via], ["a@x", "tasks.iterate.com", null]); + assert.equal(own.summary, 'todo/b.md added by a@x on tasks.iterate.com: "B", status none'); +}); + +test("a fact that is delivered twice adds nothing, and the root's copy is not this feed's", async () => { + const { facts, files } = history(); + const mind = fakeMind({ facts, files }); + await taskChangesEvent(mind.itx, facts[2]); + await taskChangesEvent(mind.itx, facts[2]); + await taskChangesEvent(mind.itx, { ...facts[2], path: "/" }); + await taskChangesEvent(mind.itx, { ...facts[2], payload: { ...facts[2].payload, path: OTHER } }); + await taskChangesEvent(mind.itx, { ...facts[2], path: "/repos/a/nested" }); + assert.equal(mind.told().length, 1); +}); + +test("every repo of the mind has a feed: a commit to another repo is told on that repo's log", async () => { + const { facts, files } = history(); + const otherFacts = [ + commitFact(3, "o1", ["README.md"], OTHER), + commitFact(4, "o2", ["todo/z.md"], OTHER), + ]; + const mind = fakeMind({ + facts, + files: { + ...files, + o1: { "README.md": "# Other\n" }, + o2: { "README.md": "# Other\n", "todo/z.md": "# Z\n" }, + }, + otherFacts, + }); + await taskChangesEvent(mind.itx, otherFacts[0]); + await taskChangesEvent(mind.itx, otherFacts[1]); + assert.equal(mind.told().length, 0); + const [z] = mind.told("/task-files/other"); + assert.deepEqual( + [z.payload.repo, z.payload.file, z.payload.change, z.payload.beforeOid], + [OTHER, "todo/z.md", "added", "o1"], + ); + assert.equal(z.idempotencyKey, "todo/task-changed:/repos/other@4:todo/z.md"); +}); + +test("a commit that names no task file reads nothing; one that names no file at all is compared", async () => { + const { facts, files } = history(); + const mind = fakeMind({ facts, files }); + await taskChangesEvent(mind.itx, commitFact(5, "c2", ["worker.ts"])); + assert.deepEqual([mind.reads.length, mind.told().length], [0, 0]); + // a `git push` to the repo: the fact names no file, and the folders say what changed + await taskChangesEvent(mind.itx, commitFact(9, "c3", [])); + assert.deepEqual( + mind.told().map((event) => event.payload.file), + ["todo/b.md"], + ); + // the same tip announced again changes nothing, and so does a commit that left the folder as it was + const again = fakeMind({ facts: [...facts, commitFact(12, "c3", [])], files }); + await taskChangesEvent(again.itx, commitFact(12, "c3", [])); + assert.deepEqual([again.reads.length, again.told().length], [0, 0]); +}); + +test("past the cap, one summary names the rest", async () => { + const many = Array.from( + { length: MAX_FILES + 2 }, + (_, at) => `todo/t${String(at).padStart(2, "0")}.md`, + ); + const facts = [commitFact(2, "c1", ["x"]), commitFact(4, "c2", many)]; + const mind = fakeMind({ + facts, + files: { c1: {}, c2: Object.fromEntries(many.map((path) => [path, "# T\n"])) }, + }); + await taskChangesEvent(mind.itx, facts[1]); + const told = mind.told(); + assert.deepEqual( + told.filter((event) => event.type === TASK_CHANGED).map((event) => event.payload.file), + many.slice(0, MAX_FILES), + ); + const [summary] = told.filter((event) => event.type === FEED_TRUNCATED); + assert.deepEqual( + [summary.payload.total, summary.payload.sent, summary.payload.skipped], + [MAX_FILES + 2, MAX_FILES, many.slice(MAX_FILES)], + ); + assert.equal(told.at(-1), summary); +}); + +test("a read that fails once is tried again; one that keeps failing is thrown, and tells nothing twice", async () => { + const { facts, files } = history(); + const mind = fakeMind({ facts, files }); + const { get } = mind.itx.repos; + let failures = 1; + mind.itx.repos.get = () => ({ + ...get(), + modules: async (options) => + failures-- > 0 ? Promise.reject(new Error("overloaded")) : get().modules(options), + }); + await taskChangesEvent(mind.itx, facts[2]); + assert.equal(mind.told().length, 1); + failures = 9; + await assert.rejects(taskChangesEvent(mind.itx, facts[4]), /overloaded/); + assert.equal(mind.told().length, 1); +}); + +test("a follower is one row on the log: a filter for one file, and a message to the agent", async () => { + const { facts, files } = history(); + const mind = fakeMind({ facts, files, agents: ["/agents/em", "/agents/worker"] }); + const one = await followTasks( + mind.itx, + { agent: "/agents/worker", file: "todo/a.md" }, + mind.deps, + ); + assert.deepEqual([one.agent, one.follows, one.log], ["/agents/worker", "todo/a.md", BOARD]); + // an agent's own script names nobody: the platform says where the call came from + const all = await followTasks(mind.itx, undefined, { + ...mind.deps, + callerPath: () => "/agents/em", + }); + assert.deepEqual([all.agent, all.follows], ["/agents/em", "every task"]); + const [worker, em] = await mind.rows(); + // the row takes the file's changes, but not a commit that the follower made itself: one that + // its own turn caused (`by`), or one whose message names it (`via`) + assert.deepEqual( + [worker.name, worker.filter, worker.copy.path, worker.copy.type], + [ + one.row, + 'payload.file = "todo/a.md" and payload.by != "/agents/worker" and payload.via != "/agents/worker"', + "/agents/worker", + "events.iterate.com/agent/message-received", + ], + ); + assert.equal( + worker.copy.payload, + '{ "message": "A task changed: " & payload.summary & (payload.diff ? "\\n\\n" & payload.diff : " (no diff here: " & payload.diffOmitted & "; read the file)")' + + ' & "\\n\\nYou follow todo/a.md of /repos/task-board. To stop: await itx.config.unfollowTasks({\\"agent\\":\\"/agents/worker\\",\\"file\\":\\"todo/a.md\\",\\"repo\\":\\"task-board\\"})" }', + ); + assert.equal(em.filter, 'payload.by != "/agents/em" and payload.via != "/agents/em"'); + // a row that an earlier version wrote, with the file alone in its filter, is read as well + await mind.itx.cd(OTHER_BOARD).append({ + type: "events.iterate.com/itx/subscription-configured", + payload: { + name: "task-follow-old", + filter: 'payload.file = "todo/od\\"d.md"', + target: { path: "/agents/old" }, + }, + }); + assert.deepEqual(await taskFollowers(mind.itx, { repo: "other" }), [ + { + agent: "/agents/old", + follows: 'todo/od"d.md', + only: null, + repo: OTHER, + row: "task-follow-old", + }, + ]); + await mind.itx.cd(OTHER_BOARD).append({ + type: "events.iterate.com/itx/subscription-configured", + payload: { name: "task-follow-old", target: null }, + }); + assert.deepEqual(await taskFollowers(mind.itx), [ + { agent: "/agents/worker", follows: "todo/a.md", only: null, repo: REPO, row: one.row }, + { agent: "/agents/em", follows: "every task", only: null, repo: REPO, row: all.row }, + ]); + // some changes and no other: the same row, with the moves in its filter, and the words say so + const some = await followTasks( + mind.itx, + { agent: "/agents/em", only: ["status", "blocked-on", "human-ask", "status"] }, + mind.deps, + ); + assert.deepEqual([some.row, some.only], [all.row, ["status", "blocked-on", "human-ask"]]); + const [, narrowed] = await mind.rows(); + assert.equal( + narrowed.filter, + 'payload.by != "/agents/em" and payload.via != "/agents/em" and ("status" in payload.moved or "blocked-on" in payload.moved or "human-ask" in payload.moved)', + ); + assert.match( + narrowed.copy.payload, + /You follow every task \(only a change of: status, blocked-on, human-ask\) of \/repos\/task-board\./, + ); + assert.deepEqual((await taskFollowers(mind.itx))[1], { + agent: "/agents/em", + follows: "every task", + only: ["status", "blocked-on", "human-ask"], + repo: REPO, + row: all.row, + }); + // and following with no `only` is every change again + await followTasks(mind.itx, { agent: "/agents/em" }, mind.deps); + assert.equal((await taskFollowers(mind.itx))[1].only, null); + // a task of another repo: its row is on that repo's log, and the call that ends it names the repo + const far = await followTasks( + mind.itx, + { agent: "/agents/em", file: "todo/a.md", repo: "other" }, + mind.deps, + ); + assert.deepEqual([far.repo, far.log], [OTHER, "/task-files/other"]); + const [there] = await mind.rows("/task-files/other"); + assert.match( + there.copy.payload, + /You follow todo\/a\.md of \/repos\/other\. To stop: await itx\.config\.unfollowTasks\(\{\\"agent\\":\\"\/agents\/em\\",\\"file\\":\\"todo\/a\.md\\",\\"repo\\":\\"other\\"\}\)/, + ); + assert.deepEqual(await taskFollowers(mind.itx, { repo: OTHER }), [ + { agent: "/agents/em", follows: "todo/a.md", only: null, repo: OTHER, row: far.row }, + ]); + assert.equal( + ( + await unfollowTasks( + mind.itx, + { agent: "/agents/em", file: "todo/a.md", repo: "other" }, + mind.deps, + ) + ).ended, + true, + ); + assert.equal((await mind.rows()).length, 2); + // following again is the same row; unfollowing ends it, once + assert.equal( + (await followTasks(mind.itx, { agent: "/agents/worker", file: "todo/a.md" }, mind.deps)).row, + one.row, + ); + assert.equal((await mind.rows()).length, 2); + assert.equal( + (await unfollowTasks(mind.itx, { agent: "/agents/worker", file: "todo/a.md" }, mind.deps)) + .ended, + true, + ); + assert.equal( + (await unfollowTasks(mind.itx, { agent: "/agents/worker", file: "todo/a.md" }, mind.deps)) + .ended, + false, + ); + assert.deepEqual( + (await taskFollowers(mind.itx)).map((row) => row.agent), + ["/agents/em"], + ); + assert.match( + followRowOf(TASK_FEED, { agent: "/agents/em", wake: false }).target.payload, + /, "trigger": false \}$/, + ); +}); + +test("a follow that would reach nothing is refused, in words", async () => { + const { facts, files } = history(); + const long = `/agents/${"x".repeat(900)}`; + const mind = fakeMind({ facts, files, agents: ["/agents/em", long] }); + await assert.rejects( + followTasks(mind.itx, { file: "todo/a.md" }, mind.deps), + /came from no agent's context: name the agent/, + ); + await assert.rejects( + followTasks(mind.itx, { agent: "/agents/typo", file: "todo/a.md" }, mind.deps), + /\/agents\/typo is no agent/, + ); + await assert.rejects( + followTasks(mind.itx, { agent: "/agents/em", file: "worker.ts" }, mind.deps), + /file is a task's path in \/repos\/task-board, like "todo\/a-task\.md"/, + ); + await assert.rejects( + followTasks(mind.itx, { agent: "/agents/em", file: "todo/none.md" }, mind.deps), + /\/repos\/task-board has no todo\/none\.md/, + ); + await assert.rejects( + followTasks(mind.itx, { agent: long, file: "todo/a.md" }, mind.deps), + /too long together/, + ); + await assert.rejects( + followTasks(mind.itx, "todo/a.md", mind.deps), + /takes \{ file\?, agent\?, repo\? \}/, + ); + await assert.rejects( + followTasks(mind.itx, { agent: "/agents/em", repo: "none" }, mind.deps), + /the mind has no repo \/repos\/none/, + ); + await assert.rejects( + followTasks(mind.itx, { agent: "/agents/em", repo: "/agents/em" }, mind.deps), + /repo is a repo's name or its path/, + ); + await assert.rejects( + followTasks(mind.itx, { agent: "/agents/em", only: ["status", "mood"] }, mind.deps), + /only is a list of what a change moved, from: added, deleted, status/, + ); + await assert.rejects( + followTasks(mind.itx, { agent: "/agents/em", only: [] }, mind.deps), + /only is a list of what a change moved/, + ); + assert.equal((await mind.rows()).length, 0); +});
M tests/tasks-model.test.mjs
Not shown: the change is larger than this page shows. A clone has it.