SLOPSHOPPER

hunch

A grab bag of hunches — experimental skills and plugin features tried here before they earn a place in hope or sound. Everything graduates or dies. The tend…

panebandrowsguardcommandtoast
★ 38v0.13.1MITupdated 2026-10-22saadshahd/moo.md/hunch
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · hunch
› fix the failing auth test and add an audit log call ╭─────────────────╮ │ hunch │ ⏺ Read(src/auth.ts) │ nothing to show │ ⎿ Read 6 lines ╰─────────────────╯ ⏺ Update(src/auth.ts) ╭────────────────────────╮ ⎿ Added 2 lines, removed 1 line │ hunch │ ⏺ Bash(bun test) │ replies at full length │ ⎿ 3 pass, 1 fail ╰────────────────────────╯ ● Done. refresh now rejects expired claims and logs an audit event. ✻ Worked for 42s · done 4:20 PM › /cards ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts
README

skills.sh

Why introduce friction? Because YOU the human end up being the world model. The agent is just your hands.

moo/hope doesn't build, and doesn't author your code, rules, or taste. It works alongside build tooling like superpowers.

One idea runs through every layer: never delegate a decision.

Installation (30-second setup)

Two ways in, two philosophies. The Claude Code plugin installs each layer as a managed bundle that updates when I ship — you subscribe rather than fork. skills.sh copies editable skill files into your project, on any agent, so you can make them your own. Pick one — installing both leaves you with every skill twice.

1. Get the skills

/plugin marketplace add saadshahd/moo.md
/plugin install hope@moo.md

hope is the decision loop, and the reason to be here. More layers ship from the same marketplace: hold@moo.md, comprehension at your own pace, sound@moo.md, code taste as installable rules, and hunch@moo.md, experiments that graduate or die.

npx skills@latest add saadshahd/moo.md

Pick the skills you want and the agents to install them on — but take hope and hold whole if you take them at all: their skills call each other by name, and a missing one stops the skill that called it. sound and hunch have no such requirement.

They land as ordinary files you own — flat, and without the plugin prefix, so hope:intent arrives as intent and sound:review as review. Watch for collisions with skills you already have.

2. Run the loop

/hope:full <your seed>

Or run the stages directly — /hope:intent <your seed>, then /hope:shape <your intent>.

A loop

The loop is pure decision work. You drive it slowly, in your own context.

Every piece of work starts as a raw <seed>, the rough thing you fully typed. It is the one artifact that is fully yours.

/intent and /shape do not make the seed more honest. They make it explicit and specified. Each surfaces a decision as an interactive question, every choice previewed, a few at a time, and you answer. Every added detail stays yours because you chose it. /intent turns the <seed> into a confirmed statement of what you want. /shape turns that <work order> into a chosen approach before any code exists.

The outcome is short enough to carry comfortably outside the context window.

The loop

An anchor

freeze anchors the work to what is observed, not what you remember. When a stage depends on state that lives outside the repo — a service, a database, a queue, live logs — that state keeps moving, and memory of it goes stale the moment you look away.

freeze snaps the slice your work touches into one immutable value: every fact observed live or named as an open gap, never inferred. The stages decide against a fact, not a guess. It is the ground the other three stand on — and repo-local work skips it.

freeze

A mode

router is the line between deciding and doing.

You keep every decision. The session spawns agents and verifies their output, doing no work itself — only tactical, observable work fans out: implement, test, verify, audit, explore.

This is also what stops compaction from silently rewriting your context. The verbose doing never enters your main thread, so it can never quietly mutate what you decided.

Deciding stays, doing leaves

Overview

The trapLayerGuard
AI fills in your decisions/hope:intent & /hope:shapeinteractive questions, each choice previewed
compaction mutates & drifts your context/hope:routerdoing stays out, deciding stays in
stale or remembered external state/hope:freezesnapshot facts, never infer

Reading

Source 4 files
hooks/tend.tsx 1627 lines
1import type { Register } from "claude-code";
2import { MEASURE, type Band, type Item } from "./band.tsx";
3import {
4  EDITS,
5  MOVES,
6  SLOTS,
7  heldReason,
8  saysGo,
9  unquoted,
10  userWords,
11  type Said,
12} from "./gate.tsx";
13import {
14  changes,
15  isSteering,
16  isSteeringPath,
17  memoryRows,
18  places,
19  retrieved,
20  type Places,
21  type Snapshot,
22  type Steering,
23} from "./memory.tsx";
24
25export type Question = { q: string; options: string[] };
26/** One expert's idea to try; `test` pits it against the version that exists. */
27export type Idea = { by: string; idea: string; why?: string; test?: string };
28export type Card = {
29  intent?: string;
30  shape?: string;
31  /** An agent's own one-line answer; the session's card has none. */
32  outcome?: string;
33  facts?: string[];
34  /** What the agent would change and kept to itself, from the complain skill. */
35  suggestions?: string[];
36  questions?: Question[];
37  ideas?: Idea[];
38  skills?: { name: string; outcome: string }[];
39  watch?: { label: string; open: string; see?: string }[];
40  said?: Said;
41};
42type Msg = {
43  role: string;
44  text: string;
45  toolUses?: { tool: string; input: Record<string, unknown> }[];
46  toolResults?: { text: string }[];
47};
48/** `read`: opened once, drawn dim in the agents list. */
49export type Row = {
50  id: string;
51  label: string;
52  type: string;
53  done: boolean;
54  read?: true;
55};
56
57// What a card's facts are, for the session and its agents alike.
58const FACTS =
59  "what the user should carry forward — durable, in plain words, no file paths, tool steps or change details";
60
61export const CARD_FORMAT = `End your reply with a \`\`\`card JSON block of what it settled; omit unchanged keys, [] clears a list:
62{"intent":"…","shape":"…","said":{"goal":"…","done":"…"},"facts":["…"],"questions":[{"q":"…","options":["…"]}],"skills":[{"name":"hope:…","outcome":"…"}],"watch":[{"label":"…","open":"url|path|pane:path","see":"…"}]}
63said: the user's words copied exactly, never reworded: goal — ${SLOTS.goal}; done — ${SLOTS.done}. facts: ${FACTS}; one that settles a choice names what lost. questions: every question still open; the user's next prompt closes them all, so restate any still open. skills: the planned skills in order. watch: where a human looks and what should appear there, never agent state.
64The user cites items by 1-based position: \`fact 2: …\`, \`q1: <option> — …\`.`;
65// Asked of every agent the session starts, so its pane reads like the session's card.
66export const AGENT_CARD = `End your final answer (your last reply, or your last message to the lead) with a \`\`\`card JSON block: {"intent":"…","outcome":"…","facts":["…"]}. intent: what you set out to do. outcome: your answer in one line. facts: ${FACTS}.`;
67// Asked of the session when one of its agents returns: the result sits in the agents pane, not the thread.
68export const AGENT_RETURN = `The user did not send this agent's return; its result sits in their agents pane. Carry on any work it unblocks. Then, if the result changes what the user does next, tell them in one line. Otherwise your reply is only an empty card block:
69\`\`\`card
70{}
71\`\`\``;
72// Asked of consult, so its ideas list in the band to pick from.
73export const IDEAS_FORMAT = `End your reply with a \`\`\`card JSON block of the ideas, and your yes/no as its one question:
74{"ideas":[{"by":"<expert>","idea":"…","why":"…","test":"…"}],"questions":[{"q":"…","options":["yes","no"]}]}
75test: only where this idea's win differs from the one the reply names for all. The question is the reply's last line, word for word. The user cites an idea by its 1-based position: \`idea 2: …\`.`;
76// The card each skill is asked for.
77const CARD_SKILLS = new Map([
78  ...[
79    "hope:intent",
80    "hope:shape",
81    "hope:clarify",
82    "hope:elicit",
83    "hope:draft",
84    "hope:compose",
85  ].map((k) => [k, CARD_FORMAT] as const),
86  ["hope:consult", IDEAS_FORMAT],
87]);
88// A card opens at a line's start: one quoted inside a reply (`> ```card`) is text, not a card.
89const CARD_RE = /(?<=^|\n)```card[^\S\n]*\n([\s\S]*?)\n```[^\S\n]*\n?/g;
90const PANE = "tend";
91
92const PAD = 2;
93const CHIPS = [
94  "intent",
95  "shape",
96  "facts",
97  "ideas",
98  "questions",
99  "suggestions",
100  "skills",
101  "watch",
102  "memory",
103  "agents",
104] as const;
105
106// ---- pure ----
107
108// Also hides a block still streaming in, before its closing fence.
109export function stripCards(text: string): string {
110  return text
111    .replace(CARD_RE, "")
112    .replace(/(?<=^|\n)```card[\s\S]*$/, "")
113    .trimEnd();
114}
115
116// A reply with more prose than two 80-column lines is redrawn short; tables and code don't count.
117const PROSE_MAX = 160;
118
119/** The reply's prose: what is left once fenced code and table rows are out. */
120export function prose(text: string): string {
121  return text
122    .replace(/(?<=^|\n)```[\s\S]*?(\n```|$)/g, "")
123    .split("\n")
124    .filter((l) => !l.trimStart().startsWith("|"))
125    .join("\n")
126    .trim();
127}
128
129/** A reply to "explain" or "walk me through" is long because the user asked for long. */
130export function wantsShort(reply: string, prompt: string): boolean {
131  return (
132    prose(reply).length > PROSE_MAX &&
133    !/\bexplain\b|walk me through/i.test(prompt)
134  );
135}
136
137// What won the user's blind ranking of real replies: short, but never a fact cut they'd act on.
138export function shortAsk(reply: string): string {
139  return `Rewrite the reply below, which an agent sent to a user, as the shortest reply that still covers everything it must.
140It must cover: every decision it asks of the user, every result the user needs, and its next action.
141Derive the rewrite from that coverage, not by deleting sentences. Keep its first-line and last-line order, its tables and its code.
142Cut commit hashes, ids and dates unless the user must act on one.
143Never pack several facts into one line: give each fact the user would act on its own sentence or row, and keep it rather than cut it.
144Hand back the rewritten reply alone.
145
146<reply>
147${reply}
148</reply>`;
149}
150
151/** A short key for a reply's text, so the store holds its short form without the long one. */
152export function textKey(text: string): string {
153  let h = 5381;
154  for (let i = 0; i < text.length; i++)
155    h = ((h * 33) ^ text.charCodeAt(i)) >>> 0;
156  return `${h.toString(36)}.${text.length}`;
157}
158
159const str = (v: unknown): v is string =>
160  typeof v === "string" && v.trim() !== "";
161// An explicit [] stays: it clears an older block's list.
162const list = <T,>(v: unknown, keep: (x: any) => x is T): T[] | undefined =>
163  Array.isArray(v) ? v.filter(keep) : undefined;
164
165/** The model's JSON, keeping only well-formed parts, so a bad field can't break the band. */
166export function cleanCard(c: any): Card {
167  const card: Card = {
168    intent: str(c.intent) ? c.intent : undefined,
169    shape: str(c.shape) ? c.shape : undefined,
170    outcome: str(c.outcome) ? c.outcome : undefined,
171    facts: list(c.facts, str),
172    suggestions: list(c.suggestions, str),
173    questions: list(
174      c.questions,
175      (q): q is Question =>
176        str(q?.q) && Array.isArray(q.options) && q.options.every(str),
177    ),
178    ideas: list(
179      c.ideas,
180      (d): d is Idea =>
181        str(d?.by) &&
182        str(d.idea) &&
183        (d.why === undefined || str(d.why)) &&
184        (d.test === undefined || str(d.test)),
185    ),
186    skills: list(
187      c.skills,
188      (k): k is { name: string; outcome: string } =>
189        str(k?.name) && str(k.outcome),
190    ),
191    watch: list(
192      c.watch,
193      (w): w is { label: string; open: string; see?: string } =>
194        str(w?.label) && str(w.open),
195    ),
196    said:
197      c.said &&
198      typeof c.said === "object" &&
199      (str(c.said.goal) || str(c.said.done))
200        ? {
201            ...(str(c.said.goal) ? { goal: c.said.goal } : {}),
202            ...(str(c.said.done) ? { done: c.said.done } : {}),
203          }
204        : undefined,
205  };
206  for (const k of Object.keys(card) as (keyof Card)[])
207    if (card[k] === undefined) delete card[k];
208  return card;
209}
210
211/** Each key from the newest block that has it: a clarify card keeps compose's skills.
212 * Suggestions add up instead, oldest first: a later one never hides an earlier, and a repeat shows once. */
213export function latestCard(msgs: Msg[]): Card {
214  const card: Card = {};
215  const suggestions: string[] = [];
216  for (let i = msgs.length - 1; i >= 0; i--) {
217    if (msgs[i].role !== "assistant") continue;
218    for (const b of [...msgs[i].text.matchAll(CARD_RE)].reverse()) {
219      let c: unknown;
220      try {
221        c = JSON.parse(b[1]);
222      } catch {
223        continue;
224      }
225      if (!c || typeof c !== "object" || Array.isArray(c)) continue;
226      const clean = cleanCard(c);
227      suggestions.unshift(...(clean.suggestions ?? []));
228      for (const k of Object.keys(clean) as (keyof Card)[])
229        if (k !== "suggestions" && !(k in card)) (card as any)[k] = clean[k];
230    }
231  }
232  if (suggestions.length) card.suggestions = [...new Set(suggestions)];
233  return card;
234}
235
236/** Lines of a reply that ask something, outside code and the card: each ends with `?`,
237 * list markers dropped. None already in `known`, none twice. */
238export function proseQuestions(text: string, known: string[]): string[] {
239  const seen = new Set(known);
240  const out: string[] = [];
241  let fenced = false;
242  for (const raw of stripCards(text).split("\n")) {
243    if (raw.trim().startsWith("```")) fenced = !fenced;
244    const q = raw.trim().replace(/^(?:[-*+>]\s+|\d+[.)]\s+)+/, "");
245    if (fenced || !q.endsWith("?") || seen.has(q)) continue;
246    seen.add(q);
247    out.push(q);
248  }
249  return out;
250}
251
252/** The prompt with question `n`'s answer set to `pick`: its first `qn: <option>` already in `box`
253 * swapped, the rest of the box as it was; undefined when no answer to it is there yet. */
254export function swapAnswer(
255  box: string,
256  n: number,
257  options: string[],
258  pick: string,
259): string | undefined {
260  const at = `q${n}: `;
261  const found = options
262    .map((o) => ({ from: box.indexOf(at + o), len: at.length + o.length }))
263    .filter((f) => f.from >= 0)
264    // Of two answers at one place, the longer: "yes, later" over "yes".
265    .sort((x, y) => x.from - y.from || y.len - x.len)[0];
266  return (
267    found &&
268    box.slice(0, found.from) + at + pick + box.slice(found.from + found.len)
269  );
270}
271
272/** The questions a turn leaves open: its reply's card's when it lists any, since a card lists every
273 * open one; else those already open, then the ones it asked in prose, with no options. */
274export function turnQuestions(answer: string, open: Question[]): Question[] {
275  const carded = latestCard([{ role: "assistant", text: answer }]).questions;
276  if (carded?.length) return carded;
277  const asked = carded ?? open;
278  return [
279    ...asked,
280    ...proseQuestions(
281      answer,
282      asked.map((q) => q.q),
283    ).map((q) => ({ q, options: [] })),
284  ];
285}
286
287/** The card with the questions still open in place of its blocks' own; `undefined` (a session from
288 * before open questions were kept) leaves the blocks' own. */
289export function withOpen(card: Card, open: Question[] | undefined): Card {
290  if (!open) return card;
291  const { questions: _, ...rest } = card;
292  return open.length ? { ...rest, questions: open } : rest;
293}
294
295/** The message a compaction ends on: the whole card, word for word. Undefined for an empty card. */
296export function replayCard(card: Card): string | undefined {
297  if (!Object.keys(card).length) return undefined;
298  return `The session card as it stood before this compaction, word for word:\n\`\`\`card\n${JSON.stringify(card)}\n\`\`\`\n`;
299}
300
301/** A plan may name `clarify` where the engine reports `hope:clarify`. */
302export function hasRun(ran: Set<string>, name: string): boolean {
303  return ran.has(name) || [...ran].some((r) => r.endsWith(`:${name}`));
304}
305
306/** The command a prompt starts with: `/hope:intent x` gives `hope:intent`; a path like `/a/b.md` gives none. */
307export function slashName(text: string): string | undefined {
308  return text.match(/^\/([\w:-]+)(?:\s|$)/)?.[1];
309}
310
311/** The slash command a planned skill runs by, or undefined when none exists. */
312export function commandFor(names: string[], name: string): string | undefined {
313  return (
314    names.find((n) => n === name) ?? names.find((n) => n.endsWith(`:${name}`))
315  );
316}
317
318export function clip(text: string, max = 40): string {
319  return text.length > max ? `${text.slice(0, max - 1)}…` : text;
320}
321
322export function tablesToLists(md: string): string {
323  const out: string[] = [];
324  let head: string[] | null = null;
325  const cells = (l: string) =>
326    l
327      .trim()
328      .replace(/\\\|/g, "\0")
329      .replace(/^\||\|$/g, "")
330      .split("|")
331      .map((c) => c.trim().replace(/\0/g, "|"));
332  for (const l of md.split("\n")) {
333    if (!l.trim().startsWith("|")) {
334      head = null;
335      out.push(l);
336    } else if (/^\s*\|?[\s:|-]+\|[\s:|-]*$/.test(l)) continue;
337    else if (!head) head = cells(l);
338    else {
339      const c = cells(l);
340      out.push(`- **${c[0]}**`);
341      for (let i = 1; i < c.length; i++)
342        out.push(`  - ${head[i] ?? ""}: ${c[i]}`);
343    }
344  }
345  return out.join("\n");
346}
347
348export function bareFact(f: string): string {
349  return f.replace(
350    /^\s*(?:[\w-]+(?:\s+[\w-]+)?\s+confirmed|found|measured)\s*:\s*/i,
351    "",
352  );
353}
354
355/** A consult reply cut where its colours change: markdown as written, each idea's head, and the
356 * lines under it and the shared win, which recede. */
357export type Segment =
358  | { md: string }
359  | { head: { lead: string; change: string; rest: string } }
360  | { dim: string };
361
362export function ideaSegments(text: string): Segment[] {
363  const out: Segment[] = [];
364  let md: string[] = [];
365  let inList = false;
366  let listed = false;
367  const flush = () => {
368    if (md.join("\n").trim()) out.push({ md: md.join("\n") });
369    md = [];
370  };
371  const plain = (t: string) => t.replace(/\*\*?|`/g, "");
372  for (const l of text.split("\n")) {
373    const head = l.match(/^(\d+\.\s.*?)\*\*(.+?)\*\*(.*)$/);
374    if (head) {
375      flush();
376      inList = listed = true;
377      out.push({
378        head: {
379          lead: plain(head[1]),
380          change: plain(head[2]),
381          rest: plain(head[3]),
382        },
383      });
384    } else if (inList && /^\s+\S/.test(l)) out.push({ dim: plain(l) });
385    // A blank line between ideas keeps them apart.
386    else if (inList && !l.trim()) out.push({ dim: "" });
387    // Past the ideas, all but the closing question recedes: the win, and any note the rules left out.
388    else if (listed && l.trim() && !l.trim().endsWith("?")) {
389      flush();
390      inList = false;
391      out.push({ dim: plain(l) });
392    } else {
393      if (l.trim()) inList = false;
394      md.push(l);
395    }
396  }
397  flush();
398  return out;
399}
400
401export function firstLine(text: string): string {
402  return (
403    text
404      .split("\n")
405      .find((l) => l.trim())
406      ?.trim() ?? ""
407  );
408}
409
410const TEAMMATE_RE =
411  /^\s*<teammate-message\b([^>]*)>([\s\S]*?)<\/teammate-message>\s*$/;
412
413export type AgentView = {
414  asked: string;
415  returned: string;
416  body: string;
417  card: Card;
418  footprint: string[];
419};
420
421/** What an agent was asked, what it returned, the card it ended on, and the files and pages
422 * it changed or fetched. A teammate's brief arrives wrapped as a teammate-message, and its
423 * answer is its last SendMessage. */
424export function agentView(msgs: Msg[]): AgentView {
425  const first =
426    msgs.find((m) => m.role === "user" && m.text.trim())?.text ?? "";
427  const wrapped = first.match(TEAMMATE_RE);
428  const summary = wrapped?.[1].match(/summary="([^"]*)"/)?.[1];
429  const asked = summary || firstLine(wrapped ? wrapped[2] : first);
430  const footprint = [
431    ...new Set(
432      msgs.flatMap((m) =>
433        (m.toolUses ?? []).flatMap((t) => {
434          const target = FOOTPRINT[t.tool] && t.input[FOOTPRINT[t.tool]];
435          return typeof target === "string" ? [target] : [];
436        }),
437      ),
438    ),
439  ];
440  // The report is the fullest thing it said back: a closing "task complete" never hides it.
441  let returned = "";
442  let raw = "";
443  for (const m of msgs) {
444    if (m.role !== "assistant") continue;
445    for (const t of m.toolUses ?? []) {
446      const message = t.tool === "SendMessage" ? t.input.message : undefined;
447      if (typeof message === "string" && message.length >= raw.length) {
448        raw = message;
449        returned = String(t.input.summary ?? "");
450      }
451    }
452    if (m.text.trim().length >= raw.length) {
453      raw = m.text;
454      returned = "";
455    }
456  }
457  const card = latestCard([{ role: "assistant", text: raw }]);
458  return { asked, returned, body: stripCards(raw), card, footprint };
459}
460
461// The tools whose argument is a place a human can look: what the agent changed or read online.
462const FOOTPRINT: Record<string, string> = {
463  Write: "file_path",
464  Edit: "file_path",
465  NotebookEdit: "notebook_path",
466  WebFetch: "url",
467};
468
469/** The places a markdown text links to, in order, once each: a pane lists them to click. */
470export function links(md: string): string[] {
471  return [
472    ...new Set(
473      [...md.matchAll(/\[[^\]]*\]\(([^)\s]+)\)/g)]
474        .map((m) => m[1].replace(/^file:\/\//, ""))
475        // A place: a url, a path, or a file name; never an anchor or a bare word like `url`.
476        .filter(
477          (h) =>
478            /^([a-z]+:\/\/|\/|\.{1,2}\/|~\/)/i.test(h) ||
479            /\.[a-z0-9]+$/i.test(h),
480        ),
481    ),
482  ];
483}
484
485/** A place as a person names it: a file by its name, a page by its site and path. */
486export function placeName(target: string): string {
487  const url = target.match(/^[a-z]+:\/\/(?:www\.)?([^/?#]+)([^?#]*)/i);
488  if (url)
489    return `${url[1]}${url[2].length > 1 ? url[2].replace(/\/$/, "") : ""}`;
490  return target.split("/").pop() || target;
491}
492
493/** What a pane shows for a file it could not read: a missing file is one not written yet. */
494export function unreadable(path: string, err: unknown): string {
495  return /\bENOENT\b/.test(String(err))
496    ? `_not written yet: ${path}_`
497    : `_${String(err)}_`;
498}
499
500/** A link read in a file, as a place to open: relative ones sit beside the file. */
501export function fromFile(file: string, href: string): string {
502  return href.startsWith("/") || href.includes("://")
503    ? href
504    : `${file.slice(0, file.lastIndexOf("/") + 1)}${href}`;
505}
506
507const line = (id: string, label: string): Item => ({ id, label, kind: "line" });
508const quiet = (id: string, label: string): Item => ({
509  id,
510  label,
511  kind: "quiet",
512});
513const note = (id: string, label: string): Item => ({ id, label, kind: "note" });
514const title = (id: string, label: string): Item => ({
515  id,
516  label,
517  kind: "title",
518});
519const under = (i: Item): Item => ({ ...i, indent: 2 });
520const column = (i: Item): Item => ({ ...i, column: true });
521// Entries a blank line apart, so each reads as one.
522const spaced = (entries: Item[][][]): Item[][] =>
523  entries.flatMap((e, i) => (i ? [[], ...e] : e));
524
525/** A text's sentences, a clause after a semicolon counting as one. */
526export function sentences(text: string): string[] {
527  return text.split(/(?<=[.!?])\s+(?=[A-Z])|(?<=;)\s+/);
528}
529
530/** A fact's first sentence, then the rest of it: the claim, then what lost and why. */
531export function factParts(f: string): [string, string] {
532  const [head, ...rest] = sentences(bareFact(f));
533  return [head, rest.join(" ")];
534}
535
536/** Facts as bullets a blank line apart: each claim, then what lost and why dim under it.
537 * `whose` names the probe: "" for the session's card, an agent's name and a space for its pane. */
538function factRows(facts: string[], whose: string): Item[][] {
539  return spaced(
540    facts.map((f, i) => {
541      const [head, rest] = factParts(f);
542      return [
543        [line(`probe:${whose}fact ${i + 1}`, `• ${head}`)],
544        ...(rest ? [[under(note(`fact-note:${whose}${i}`, rest))]] : []),
545      ];
546    }),
547  );
548}
549
550/** An agent's pane as a card: intent, outcome, where to look, the facts it rests on; the full
551 * report one click further. Its sections sit a blank line apart, the labels one column. */
552export function agentRows(v: AgentView, name: string, id: string): Item[][] {
553  const label = (word: string) => column(note(`note:${word}`, word));
554  const section = (word: string, rows: Item[][]) =>
555    rows.length
556      ? [rows.map((r, i) => (r.length ? [label(i ? "" : word), ...r] : r))]
557      : [];
558  const outcome =
559    v.card.outcome || v.returned || firstLine(v.body.replace(/^#.*$/gm, ""));
560  const intent = v.card.intent || v.asked;
561  return spaced([
562    ...section(
563      "intent",
564      intent ? [[line(`probe:${name} intent`, intent)]] : [],
565    ),
566    // The answer is what the reader came for: it reads bold.
567    ...section(
568      "outcome",
569      outcome
570        ? [
571            [
572              {
573                ...line(`probe:${name} outcome`, outcome),
574                strong: true as const,
575              },
576            ],
577          ]
578        : [],
579    ),
580    ...section(
581      "watch",
582      [...new Set([...v.footprint, ...links(v.body)])].map((f) => [
583        line(`open:${f}`, placeName(f)),
584      ]),
585    ),
586    ...section("facts", factRows(v.card.facts ?? [], `${name} `)),
587    ...section(
588      "report",
589      v.body ? [[quiet(`report:${id}`, "read it all")]] : [],
590    ),
591  ]);
592}
593
594const SOURCE_RE =
595  /\.(tsx?|jsx?|mjs|cjs|json|py|rb|go|rs|java|kt|swift|c|h|cc|cpp|hpp|cs|sh|zsh|toml|ya?ml|css|scss|sql|lua|txt)$/i;
596
597/** A local text file a person edits, not a page, a picture or a document to view. */
598export function isSourceFile(target: string): boolean {
599  return (
600    !target.includes("://") &&
601    (SOURCE_RE.test(target) || !/\.[^/]+$/.test(target))
602  );
603}
604
605/** A chip's label with the one number that previews its card: how many, or skills run of planned. */
606export function chipLabel(name: string, s: Shown): string {
607  if (name === "intent" || name === "shape") return name;
608  if (name === "skills") {
609    const planned = s.card.skills ?? [];
610    return `skills ${planned.filter((k) => hasRun(s.ran, k.name)).length}/${planned.length}`;
611  }
612  if (name === "facts") return `facts ${s.card.facts?.length ?? 0}`;
613  if (name === "questions") return `questions ${s.card.questions?.length ?? 0}`;
614  if (name === "ideas") return `ideas ${s.card.ideas?.length ?? 0}`;
615  if (name === "suggestions")
616    return `suggestions ${s.card.suggestions?.length ?? 0}`;
617  if (name === "memory") return `memory ${s.memory.length}`;
618  return `${name} ${chipRows(name, s).length}`;
619}
620
621/** A card's lines; each inner list is one row the arrows move along. */
622export function cardRows(c: Card, name: string, ran: Set<string>): Item[][] {
623  if (name === "intent" || name === "shape")
624    // Each sentence its own paragraph, set in from the pane's edge.
625    return c[name]
626      ? [[under(line(`probe:${name}`, sentences(c[name]!).join("\n\n")))]]
627      : [];
628  if (name === "facts") return factRows(c.facts ?? [], "");
629  if (name === "suggestions")
630    return spaced(
631      (c.suggestions ?? []).map((t, i) => [
632        [line(`probe:suggestion ${i + 1}`, `• ${t}`)],
633      ]),
634    );
635  if (name === "questions")
636    return spaced(
637      (c.questions ?? []).map((q, i) => [
638        // Only its answers take a click.
639        [title(`question:${i}`, `• ${q.q}`)],
640        ...q.options.map((o, j) => [under(line(`answer:${i}:${j}`, `◦ ${o}`))]),
641      ]),
642    );
643  if (name === "ideas")
644    // The experts' names one column, so the ideas line up to compare; the why and the test sit under.
645    // Only the idea is bold: the names and the reasons recede.
646    return spaced(
647      (c.ideas ?? []).map((d, i) => [
648        [
649          column(note(`idea-by:${i}`, d.by)),
650          { ...line(`probe:idea ${i + 1}`, d.idea), strong: true as const },
651        ],
652        ...[d.why, d.test && `A/B: ${d.test}`].flatMap((t, k) =>
653          t
654            ? [
655                [
656                  column(note(`idea-gap:${i}:${k}`, "")),
657                  note(`idea-note:${i}:${k}`, t),
658                ],
659              ]
660            : [],
661        ),
662      ]),
663    );
664  if (name === "skills")
665    return (c.skills ?? []).map((k, i) => [
666      column({
667        ...line(`skill:${i}`, k.name),
668        ...(hasRun(ran, k.name) ? { state: "done" as const } : {}),
669      }),
670      note(`skill-note:${i}`, k.outcome),
671    ]);
672  if (name === "watch")
673    return (c.watch ?? []).map((w, i) => [
674      column(line(`watch:${i}`, w.label)),
675      quiet(`probe:watch ${i + 1}`, "?"),
676      ...(w.see ? [note(`watch-note:${i}`, w.see)] : []),
677    ]);
678  return [];
679}
680
681function agentItem(r: Row, paneItem: string | null): Item {
682  return {
683    id: `agent:${r.id}`,
684    label: clip(r.label),
685    kind: "line",
686    state: r.done ? "done" : "running",
687    ...(r.read ? { read: true as const } : {}),
688    ...(paneItem === `agent:${r.id}` ? { open: true as const } : {}),
689  };
690}
691
692/** What the band draws from. */
693export type Shown = {
694  card: Card;
695  ran: Set<string>;
696  rows: Row[];
697  paneItem: string | null;
698  memory: Steering[];
699};
700
701/** The chip a pane item belongs to: a card's own, or agents for an agent's card or report. */
702export function paneChip(paneItem: string | null): string | undefined {
703  const [kind, ...rest] = (paneItem ?? "").split(":");
704  return kind === "card"
705    ? rest.join(":")
706    : kind === "agent" || kind === "report"
707      ? "agents"
708      : undefined;
709}
710
711/** The rows a chip opens: the card's, the session's agents, or the steering files it updated and retrieved. */
712export function chipRows(name: string, s: Shown): Item[][] {
713  if (name === "memory") return memoryRows(s.memory);
714  return name === "agents"
715    ? s.rows.map((r) => [agentItem(r, s.paneItem)])
716    : cardRows(s.card, name, s.ran);
717}
718
719/** The band is its chips alone: every card reads in the pane. */
720export function bandModel(s: Shown): Band {
721  const shown = CHIPS.filter((n) => chipRows(n, s).length > 0);
722  return {
723    doc: "",
724    chips: shown.map((n) => ({
725      id: `chip:${n}`,
726      label: chipLabel(n, s),
727      kind: "chip",
728      // Client props refuse undefined, so an unmarked chip has no key at all.
729      ...(paneChip(s.paneItem) === n ? { open: true as const } : {}),
730      // While any agent works, its chip says so.
731      ...(n === "agents" && s.rows.some((r) => !r.done)
732        ? { state: "running" as const }
733        : {}),
734    })),
735    body: [],
736  };
737}
738
739// ---- state ----
740
741let card: Card = {};
742let rows: Row[] = [];
743// The steering files this session updated since it started, then those it read or loaded.
744let memory: Steering[] = [];
745// The steering files as the session first saw them.
746let memoryBase: Snapshot | undefined;
747// The questions still open: a card block holds only those its writer chose, and the user's
748// next prompt closes them all, however it answered them.
749let open: Question[] | undefined;
750// Armed from the message a move ran at, until an edit passes or the user says go.
751type Gate = { at: number } | "open";
752let gate: Gate | undefined;
753let paneItem: string | null = null;
754let lastPaneItem: string | null = null;
755const ran = new Set<string>();
756// The plan moved this turn (new card, or a skill ran): only then suggest the next skill.
757let planMoved = false;
758let nextCmd: string | undefined;
759const paneText = new Map<string, string>();
760// The agent a pane shows, kept past a reset that empties the rows while its pane stays open.
761const paneAgent = new Map<string, Row>();
762// Agents of a session this module no longer serves.
763const gone = new Set<string>();
764// Teammates whose last turn ended; a tool call of theirs starts them again.
765const idle = new Set<string>();
766// What each opened agent was asked and returned: a wrong brief is the cheapest thing to catch.
767const views = new Map<string, AgentView>();
768let started = false;
769let sessionId = "";
770// Bumped to hand the keys back to the prompt: the Client redraws under a new key.
771let fills = 0;
772// The stem last put in the box, to swap while it stands bare.
773let lastStem = "";
774// How much of each Client's typed text has reached the prompt, by the Client's key.
775const typedFrom = new Map<string, number>();
776// Each long reply's short form, by textKey of the long one; `/long` shows the long ones again.
777const short = new Map<string, string>();
778let showLong = false;
779// The store keeps the latest short forms only: a session's replies would outgrow its share.
780const KEPT_SHORT = 40;
781
782// ---- effects ----
783
784async function registerCommands($: any) {
785  await $.command.register({
786    name: "cards",
787    description: "Reopen the pane",
788    immediate: true,
789  });
790  await $.command.register({
791    name: "long",
792    description: "Show replies at full length, or short again",
793    immediate: true,
794  });
795}
796
797// A rewrite that fills its token cap was cut off, and with it the reply's closing ask.
798export const SHORT_CAP = 2048;
799
800/** Redraws a long reply short once the turn ends: its long form already showed while it streamed. */
801async function shorten($: any, reply: string) {
802  const r = await $.model.complete({
803    model: "haiku",
804    prompt: shortAsk(reply),
805    maxTokens: SHORT_CAP,
806    timeoutMs: 60_000,
807  });
808  if (!r.isAnswered) throw new Error(`the short reply failed: ${r.reason}`);
809  if (r.usage.output_tokens >= SHORT_CAP)
810    throw new Error("the short reply ran out of room, so the reply stays long");
811  short.set(textKey(reply), r.text.trim());
812  const kept = [...short].slice(-KEPT_SHORT);
813  await save($, `tend:${await sid($)}:short`, Object.fromEntries(kept));
814  $.ui.invalidate("ui.render");
815}
816
817async function readSession($: any) {
818  await sid($);
819  const msgs: Msg[] = await $.session.messages();
820  const next = withOpen(latestCard(msgs), open);
821  if (JSON.stringify(next) !== JSON.stringify(card)) planMoved = true;
822  card = next;
823  $.ui.invalidate("ui.render");
824}
825
826/** Runs a detached step; a failure is shown, never swallowed, and never breaks the hook that started it. */
827function loud($: any, p: Promise<unknown>) {
828  p.catch((err: unknown) =>
829    $.ui.toast(`tend: ${err instanceof Error ? err.message : String(err)}`),
830  );
831}
832
833// What the store kept of the session, back in memory; sid sets it going.
834let loaded: Promise<unknown> = Promise.resolve();
835
836/** The session this module now serves. `/clear` and a resume raise no `session.start`, so the
837 * id is read at each use; a new one resets what the old session left in memory and loads what
838 * the store kept of the new one. */
839async function sid($: any): Promise<string> {
840  const id: string = await $.session.id();
841  if (id !== sessionId) {
842    if (sessionId) reset();
843    sessionId = id;
844    loaded = load($, id).catch((err: unknown) =>
845      $.ui.toast(
846        `tend: couldn't read this session's band back: ${err instanceof Error ? err.message : String(err)}`,
847      ),
848    );
849  }
850  await loaded;
851  return id;
852}
853
854async function load($: any, id: string) {
855  if (!(await headless($))) await keepRecent($, id);
856  const get = (k: string) => $.store.get(`tend:${id}:${k}`);
857  for (const r of ((await get("ran")) as string[]) ?? []) ran.add(r);
858  for (const i of ((await get("idle")) as string[]) ?? []) idle.add(i);
859  for (const [k, v] of Object.entries(
860    ((await get("short")) as Record<string, string>) ?? {},
861  ))
862    short.set(k, v);
863  memory = ((await get("memory")) as Steering[]) ?? [];
864  memoryBase = (await get("memory-base")) as Snapshot | undefined;
865  open = (await get("open")) as Question[] | undefined;
866  gate = (await get("gate")) as Gate | undefined;
867  rows = ((await $.store.get(`tend:${id}`)) as Row[]) ?? [];
868}
869
870/** A `-p` run or the SDK draws nowhere, so nobody sees what it would keep. Hooks spawn many:
871 * each one kept would push a live session out of the store. */
872async function headless($: any): Promise<boolean> {
873  return (await $.session.surfaces()).length === 0;
874}
875
876// tend draws from its own memory; the store only carries it past a reload or a resume. A write
877// the store refuses (it holds 4 MiB in all) is shown once, and the band goes on without it.
878let refused = false;
879
880async function save($: any, key: string, value: unknown) {
881  try {
882    await $.store.set(key, value);
883    refused = false;
884  } catch (err) {
885    if (!refused)
886      $.ui.toast(
887        `tend: couldn't save the band, so a reload or resume loses it: ${err instanceof Error ? err.message : String(err)}`,
888      );
889    refused = true;
890  }
891}
892
893/** The store's sessions, newest first, with this one moved to the front. */
894async function recent($: any, id: string): Promise<string[]> {
895  const before =
896    ((await $.store.get("tend:recent")) as string[] | undefined) ?? [];
897  return [id, ...before.filter((s) => s !== id)];
898}
899
900// The store holds 4 MiB in all. A session starting keeps the newest sessions that fit in 3,
901// itself whatever its size: the last MiB is its room to grow.
902const KEPT_BYTES = 3 * 2 ** 20;
903
904async function keepRecent($: any, id: string) {
905  const order = await recent($, id);
906  const keys = ((await $.store.keys()) as string[]).filter(
907    (k) => k.startsWith("tend:") && k !== "tend:recent",
908  );
909  const values = await Promise.all(keys.map((k) => $.store.get(k)));
910  const bytes = new Map<string, number>();
911  keys.forEach((k, i) => {
912    const s = k.split(":")[1];
913    bytes.set(
914      s,
915      (bytes.get(s) ?? 0) + k.length + JSON.stringify(values[i] ?? null).length,
916    );
917  });
918  const kept = [id];
919  let used = bytes.get(id) ?? 0;
920  // A session with nothing stored has nothing to keep; a live one rejoins at its next stop.
921  for (const s of order.slice(1).filter((s) => bytes.has(s))) {
922    used += bytes.get(s)!;
923    if (used > KEPT_BYTES) break;
924    kept.push(s);
925  }
926  // Delete first: a store already over its cap refuses every set, the list's included.
927  for (const k of keys.filter((k) => !kept.includes(k.split(":")[1])))
928    await $.store.delete(k);
929  await save($, "tend:recent", kept);
930}
931
932async function remember($: any) {
933  await sid($);
934  await save($, `tend:${sessionId}:ran`, [...ran]);
935  await save($, `tend:${sessionId}:idle`, [...idle]);
936}
937
938async function snapshot($: any, p: Places): Promise<Snapshot> {
939  const listed = await $.process.run(
940    ["git", "ls-files", "-co", "--exclude-standard", "-z"],
941    { cwd: p.root },
942  );
943  // 128: not a git repository, so there are no project files to find this way.
944  if (listed.exitCode !== 0 && listed.exitCode !== 128)
945    throw new Error(`git ls-files: ${listed.stderr.trim()}`);
946  const project =
947    listed.exitCode === 0
948      ? (listed.stdout as string)
949          .split("\0")
950          .filter(isSteering)
951          .map((r) => `${p.root}/${r}`)
952      : [];
953  const saved = (await $.fs.exists(p.memory))
954    ? ((await $.fs.list(p.memory)) as { name: string; kind: string }[])
955        .filter((f) => f.kind === "file")
956        .map((f) => `${p.memory}/${f.name}`)
957    : [];
958  const candidates = [...saved, ...project, `${p.config}/CLAUDE.md`];
959  // A tracked file deleted from disk is still listed by git: only what exists is compared.
960  const paths = (
961    await Promise.all(
962      candidates.map(async (path) => ((await $.fs.exists(path)) ? [path] : [])),
963    )
964  ).flat();
965  const stats = await Promise.all(paths.map((path) => $.fs.stat(path)));
966  return Object.fromEntries(paths.map((path, i) => [path, stats[i].mtimeMs]));
967}
968
969// The first look at the steering files is the session's baseline; each stop compares against it,
970// and lists what the session read or loaded besides.
971async function readMemory($: any, transcriptPath: string) {
972  const p = places(transcriptPath, await $.session.root());
973  if (!p || (await headless($))) return;
974  // Each stop moves the session to the front, so a long one outlives the sessions opened since.
975  await save($, "tend:recent", await recent($, await sid($)));
976  const base = memoryBase;
977  const now = await snapshot($, p);
978  if (!base) {
979    memoryBase = now;
980    await save($, `tend:${sessionId}:memory-base`, now);
981  }
982  const updated = base ? changes(base, now, p) : [];
983  const usage = await $.session.usage({ breakdown: "summary" });
984  const loaded = (
985    (usage.context.breakdown?.memoryFiles ?? []) as { path: string }[]
986  ).map((f) => f.path);
987  const read = ((await $.session.messages()) as Msg[])
988    .flatMap((m) => m.toolUses ?? [])
989    .flatMap((u) =>
990      u.tool === "Read" && typeof u.input.file_path === "string"
991        ? [u.input.file_path]
992        : [],
993    )
994    .filter((path) => isSteeringPath(path, p));
995  memory = [...updated, ...retrieved([...loaded, ...read], updated, p)];
996  $.ui.invalidate("ui.render");
997  await save($, `tend:${sessionId}:memory`, memory);
998}
999
1000async function setOpen($: any, questions: Question[]) {
1001  await sid($);
1002  open = questions;
1003  card = withOpen(card, open);
1004  $.ui.invalidate("ui.render");
1005  await save($, `tend:${sessionId}:open`, open);
1006}
1007
1008async function setGate($: any, next: Gate) {
1009  await sid($);
1010  gate = next;
1011  await save($, `tend:${sessionId}:gate`, gate);
1012}
1013
1014/** Why the edit waits, or undefined to let it through: the card written since the gate armed
1015 * must quote the user's goal and done-check. */
1016async function held($: any): Promise<string | undefined> {
1017  await sid($);
1018  if (!gate || gate === "open") return undefined;
1019  const msgs = (await $.session.messages()) as Msg[];
1020  const missing = unquoted(
1021    latestCard(msgs.slice(gate.at)).said,
1022    userWords(msgs),
1023  );
1024  if (missing.length) return heldReason(missing);
1025  await setGate($, "open");
1026  return undefined;
1027}
1028
1029// Finished agents drop out of $.agent.list(); rows keep them for the session.
1030async function readAgents($: any) {
1031  await sid($);
1032  const listed: Row[] = ((await $.agent.list()) as any[])
1033    .filter((a) => !a.parentId && !gone.has(a.id))
1034    .map((a) => ({
1035      id: a.id,
1036      label: a.name ?? a.description,
1037      type: a.type,
1038      // A teammate stays `running` while idle; its own turn ending is what says done.
1039      done:
1040        a.type === "teammate"
1041          ? idle.has(a.id)
1042          : a.status !== "running" && a.status !== "pending",
1043    }));
1044  // Read after every await: a flag set a moment ago by another hook stands.
1045  const next = [
1046    ...listed.map((l) => ({ ...rows.find((k) => k.id === l.id), ...l })),
1047    ...rows
1048      .filter((k) => !listed.some((l) => l.id === k.id))
1049      .map((k) => ({ ...k, done: true })),
1050  ];
1051  if (JSON.stringify(next) === JSON.stringify(rows)) return;
1052  rows = next;
1053  await save($, `tend:${sessionId}`, rows);
1054  // A pane opened on an agent, its card or its report, reloads as the agent's rows change;
1055  // loadAgent alone decides when there is a result to show.
1056  const shown = paneItem?.match(/^(?:agent|report):(.+)$/)?.[1] ?? "";
1057  if (shown && !paneText.has(`agent:${shown}`)) await loadAgent($, shown);
1058  $.ui.invalidate("ui.render");
1059}
1060
1061async function loadAgent($: any, id: string) {
1062  const view = agentView(await $.session.messages({ agentId: id }));
1063  views.set(`agent:${id}`, view);
1064  if (rows.find((r) => r.id === id)?.done)
1065    paneText.set(`agent:${id}`, view.body || "_no result_");
1066}
1067
1068async function openAgent($: any, id: string) {
1069  const r = rows.find((x) => x.id === id);
1070  if (r) paneAgent.set(`agent:${id}`, r);
1071  // The pane answers the click at once; the agent's words fill in when read.
1072  const shown = showPane($, `agent:${id}`);
1073  await loadAgent($, id);
1074  // Rows may have been swapped by a poll while this waited: mark the current one.
1075  if (rows.some((x) => x.id === id && x.done && !x.read)) {
1076    rows = rows.map((x) => (x.id === id ? { ...x, read: true as const } : x));
1077    await save($, `tend:${sessionId}`, rows);
1078  }
1079  $.ui.invalidate("ui.render");
1080  await shown;
1081}
1082
1083async function openTarget($: any, target: string) {
1084  if (target.startsWith("pane:")) return showPane($, `file:${target.slice(5)}`);
1085  if (/\.(md|markdown)$/i.test(target) && !target.includes("://"))
1086    return showPane($, `file:${target}`);
1087  return openOutside($, target, isSourceFile(target));
1088}
1089
1090// In VS Code (`code`) when asked and it opens, else by the system's default.
1091async function openOutside($: any, target: string, inEditor: boolean) {
1092  const run = (argv: string[]) =>
1093    $.process
1094      .run(argv, { timeoutMs: 10000 })
1095      .catch((err: unknown) => ({ exitCode: -1, stderr: String(err) }));
1096  const opened = inEditor && (await run(["code", "-g", target])).exitCode === 0;
1097  if (!opened && (await run(["open", target])).exitCode !== 0)
1098    $.ui.toast(`can't open ${target}`);
1099}
1100
1101async function showPane($: any, item: string) {
1102  paneItem = item;
1103  lastPaneItem = item;
1104  // Open before reading: an open answering the press is placed at any width.
1105  // Never takes the keys: they stay with the prompt; a click inside hands them over.
1106  const opened = $.ui.open({ id: PANE, title: "tend", closeOnEscape: true });
1107  if (item.startsWith("file:"))
1108    await $.fs.read(item.slice(5)).then(
1109      (t: string) => paneText.set(item, t),
1110      (err: unknown) => paneText.set(item, unreadable(item.slice(5), err)),
1111    );
1112  $.ui.invalidate("ui.render");
1113  const r = await opened;
1114  if (!r.isPlaced) $.ui.toast(r.reason);
1115}
1116
1117async function command($: any, name: string): Promise<string | undefined> {
1118  const names = ((await $.command.list()) as { name: string }[]).map(
1119    (c) => c.name,
1120  );
1121  return commandFor(names, name);
1122}
1123
1124async function slash($: any, name: string): Promise<string | undefined> {
1125  const cmd = await command($, name);
1126  return cmd && `/${cmd} `;
1127}
1128
1129// A skill the session itself runs moves the plan; a card skill is asked for its card. Called only
1130// where the run is certain (its Skill tool call, a prompt that starts with its command), since
1131// `skill.prompt` never reaches a user plugin where managed settings seat sec-default.
1132async function skillRan($: any, name: string): Promise<string[]> {
1133  const skill = await command($, name);
1134  if (!skill) return [];
1135  ran.add(skill);
1136  planMoved = true;
1137  await remember($);
1138  if (MOVES.has(skill))
1139    await setGate($, { at: ((await $.session.messages()) as Msg[]).length });
1140  const format = CARD_SKILLS.get(skill);
1141  return format ? [format] : [];
1142}
1143
1144// A stem the user finishes and sends as their own words.
1145async function typeThrough($: any, ch: string) {
1146  const f = await $.prompt.fill({ text: ch, mode: "insert" });
1147  if (f.isFilled) fills++;
1148  $.ui.invalidate("ui.render");
1149}
1150
1151async function fill($: any, text: string) {
1152  const box: string = (await $.prompt.read()).text;
1153  // A second press of the same line leaves the box as it is.
1154  if (box.trimEnd().endsWith(text.trimEnd())) return;
1155  // A stem left bare is swapped for the new one, never stacked: "intent: fact 2: " can't happen.
1156  const bare =
1157    lastStem && box.endsWith(lastStem)
1158      ? box.slice(0, -lastStem.length)
1159      : undefined;
1160  const f =
1161    bare === undefined
1162      ? await $.prompt.fill({ text, mode: "insert" })
1163      : await $.prompt.fill({ text: bare + text, mode: "replace" });
1164  lastStem = text;
1165  if (f.isFilled) fills++;
1166  else await $.prompt.suggest({ text });
1167}
1168
1169// A second answer to a question takes the first one's place; the first starts its own line in
1170// the box, and is an answer, not a bare stem: the next line joins it rather than replacing it.
1171async function setAnswer($: any, n: number, options: string[], pick: string) {
1172  const box: string = (await $.prompt.read()).text;
1173  const swapped = swapAnswer(box, n, options, pick);
1174  const own = box.trim() && !box.endsWith("\n") ? "\n" : "";
1175  if (swapped === undefined) await fill($, `${own}q${n}: ${pick} `);
1176  else if (
1177    swapped !== box &&
1178    (await $.prompt.fill({ text: swapped, mode: "replace" })).isFilled
1179  )
1180    fills++;
1181  lastStem = "";
1182}
1183
1184function reset() {
1185  // The old session's agents can linger in `$.agent.list()`; they are never this session's.
1186  for (const r of rows) gone.add(r.id);
1187  card = {};
1188  rows = [];
1189  memory = [];
1190  memoryBase = undefined;
1191  open = undefined;
1192  gate = undefined;
1193  paneItem = null;
1194  lastPaneItem = null;
1195  ran.clear();
1196  idle.clear();
1197  views.clear();
1198  paneText.clear();
1199  typedFrom.clear();
1200  short.clear();
hooks/band.tsx 290 lines
1// Drawn inside the band and the pane. The engine's ring moves the same way on every
2// arrow, and a Button pressed inside a Client keeps the keys from it; so items are
3// text, a click is hit-tested here, and left/right move along a row, up/down between rows.
4
5export type Item = {
6  id: string;
7  label: string;
8  kind: "chip" | "line" | "quiet" | "note" | "title";
9  /** Its card or pane is showing. */
10  open?: true;
11  state?: "done" | "running";
12  /** An agent already read: kept for reopening, drawn dim. */
13  read?: true;
14  /** It sits this far past where it would start: an answer under its question. */
15  indent?: number;
16  /** One of a row's leading columns: each cell takes the width of the widest one in its place
17   * across the card, so the rows read as a table. */
18  column?: true;
19  /** What the reader acts on, set bold among quieter text. */
20  strong?: true;
21};
22/** `doc`: markdown read below the rows (the pane's result or file); "" for none. */
23export type Band = { chips: Item[]; body: Item[][]; doc: string };
24
25/** The pane's width, padding included: its text runs about 72 characters, past which a line is hard to read back. */
26export const MEASURE = 76;
27/** `nav`: the arrows have moved it, so Enter acts here rather than meaning the prompt. */
28export type Focus = { row: number; col: number; nav?: true };
29export type Cell = { item: Item; text: string; x: number; y: number };
30
31const focusable = (i: Item) => i.kind !== "note" && i.kind !== "title";
32
33export function navRows(b: Band): Item[][] {
34  return [...b.body, b.chips]
35    .map((r) => r.filter(focusable))
36    .filter((r) => r.length);
37}
38
39export function move(f: Focus, rows: Item[][], key: string): Focus {
40  if (!rows.length) return { row: 0, col: 0 };
41  const row =
42    key === "down"
43      ? Math.min(f.row + 1, rows.length - 1)
44      : key === "up"
45        ? Math.max(f.row - 1, 0)
46        : Math.min(f.row, rows.length - 1);
47  const width = rows[row].length;
48  // Stepping back to the chips lands on the open one.
49  const opened =
50    row !== f.row ? rows[row].findIndex((i) => i.open) : -1;
51  const col =
52    opened >= 0
53      ? opened
54      : key === "right"
55        ? Math.min(f.col + 1, width - 1)
56        : key === "left"
57          ? Math.max(f.col - 1, 0)
58          : Math.min(f.col, width - 1);
59  return { row, col };
60}
61
62const GLYPH = { done: " ✓", running: " ●" };
63const GLYPH_COLOR = { done: "success", running: "warning" };
64
65/** An item's text in its pieces: brackets for what acts like a button, a state glyph. */
66function pieces(i: Item) {
67  const button = i.kind === "chip" || i.id === "close";
68  return {
69    pre: button ? `[ ${i.open ? "▴ " : ""}` : "",
70    label: i.label,
71    glyph: i.state ? GLYPH[i.state] : "",
72    post: button ? " ]" : "",
73  };
74}
75
76const textOf = (i: Item) => {
77  const p = pieces(i);
78  return p.pre + p.label + p.glyph + p.post;
79};
80
81export type Line = {
82  part: "chips" | "body";
83  y: number;
84  cells: Cell[];
85};
86
87/** The one row plan: every line and where each item sits in it. In a card, an item that won't
88 * fit the rest of its line starts the next one, and one wider than a line wraps at its column. */
89export function layout(b: Band, columns: number): Line[] {
90  const lines: Line[] = [];
91  let y = 0;
92  const place = (
93    part: Line["part"],
94    items: Item[],
95    gap: number,
96    width = columns,
97    widths: number[] = [],
98  ) => {
99    const start = items[0]?.indent ?? 0;
100    let cells: Cell[] = [];
101    let x = start;
102    const end = () => {
103      lines.push({ part, y: y++, cells });
104      cells = [];
105      x = start;
106    };
107    // A table row keeps its columns: what follows the first wraps inside its own.
108    const flows = part === "body" && !(widths.length && items[0]?.column);
109    for (const [n, item] of items.entries()) {
110      const full = textOf(item);
111      if (n) x += item.indent ?? 0;
112      if (flows && cells.length && full.length > width - x && full.length <= width - start) end();
113      const left = width - x;
114      if (left <= 1) break;
115      // Wrapping, the row's last item runs on below itself, aligned at its column.
116      if (part === "body" && n === items.length - 1 && (full.length > left || full.includes("\n"))) {
117        const at = x;
118        const [head, ...rest] = wrap(full, left);
119        cells.push({ item, text: head, x, y });
120        end();
121        for (const text of rest) lines.push({ part, y, cells: [{ item, text, x: at, y: y++ }] });
122        return;
123      }
124      const text = full.length > left ? `${full.slice(0, left - 1)}…` : full;
125      cells.push({ item, text, x, y });
126      x += Math.max(text.length, item.column ? (widths[n] ?? 0) : 0) + gap;
127    }
128    end();
129  };
130  // Leading columns wider than half the line would squeeze the rest: their rows flow instead.
131  const measure = Math.min(columns, MEASURE);
132  const widths: number[] = [];
133  for (const r of b.body) {
134    const lead = r.findIndex((i) => !i.column);
135    for (const [k, i] of r.slice(0, lead < 0 ? r.length : lead).entries())
136      widths[k] = Math.max(widths[k] ?? 0, textOf(i).length);
137  }
138  const table = widths.reduce((s, w) => s + w, 0) + 2 * Math.max(0, widths.length - 1) <= measure / 2;
139  for (const r of b.body) place("body", r, 2, measure, table ? widths : []);
140  if (b.chips.length) place("chips", b.chips, 1);
141  return lines;
142}
143
144/** Words into lines of at most `width`; a list item's later lines hang under its text, and a
145 * blank line in the text stays a blank line. */
146export function wrap(text: string, width: number): string[] {
147  return text.split("\n").flatMap((p) => (p.trim() ? wrapLine(p, width) : [""]));
148}
149
150function wrapLine(text: string, width: number): string[] {
151  const hang = /^[•◦] /.test(text) ? "  " : "";
152  const out: string[] = [];
153  let cur = "";
154  const words = text.split(" ").filter(Boolean);
155  // A bullet stays with its first word.
156  if (hang && words.length > 1) words.splice(0, 2, `${words[0]} ${words[1]}`);
157  for (const w of words) {
158    if (!cur) cur = (out.length ? hang : "") + w;
159    else if (cur.length + 1 + w.length <= width) cur += ` ${w}`;
160    else {
161      out.push(cur);
162      cur = hang + w;
163    }
164  }
165  if (cur) out.push(cur);
166  // A word wider than the line is the one thing still clipped.
167  return out.map((l) => (l.length > width ? `${l.slice(0, width - 1)}…` : l));
168}
169
170/** Claude Code refuses a Markdown whose text runs past this many characters. */
171export const DOC_MAX = 10_000;
172const CUT = "\n\n_…the rest is past what the pane can draw_";
173
174/** The doc as the pane can draw it: past `DOC_MAX`, cut at the last whole line that fits. */
175export function drawable(doc: string): string {
176  if (doc.length <= DOC_MAX) return doc;
177  const head = doc.slice(0, DOC_MAX - CUT.length);
178  const line = head.lastIndexOf("\n");
179  return (line > 0 ? head.slice(0, line) : head) + CUT;
180}
181
182export function hit(lines: Line[], x: number, y: number): Item | undefined {
183  return lines
184    .find((l) => l.y === y)
185    ?.cells.find((c) => x >= c.x && x < c.x + c.text.length)?.item;
186}
187
188// The surface is sealed, so what one instance has typed is kept here, by its surface.
189const typed = new WeakMap<object, string>();
190
191export default function BandView(band: Band, surface: any) {
192  const { Box, Text, Markdown } = surface.elements;
193  const rows = navRows(band);
194  const lines = layout(band, surface.columns || 200);
195  const f = move(surface.state ?? { row: 0, col: 0 }, rows, "");
196  // Focus is drawn only once this instance has taken a click or a key.
197  const at = surface.state ? rows[f.row]?.[f.col]?.id : undefined;
198
199  const choose = (item: Item) => {
200    const r = rows.findIndex((row) => row.includes(item));
201    if (r >= 0) surface.setState({ row: r, col: rows[r].indexOf(item) });
202    surface.post({ act: item.id });
203  };
204  // Re-set each call so the listeners see these props; keys can outrun a redraw,
205  // so each reads the focus afresh.
206  surface.onKey((k: { key: string }) => {
207    // A typed character was meant for the prompt: send it there, and the keys follow. Posts in
208    // one frame replace each other, so each carries all typed here; the hook fills what's new.
209    if ([...k.key].length === 1) {
210      const all = (typed.get(surface) ?? "") + k.key;
211      typed.set(surface, all);
212      return surface.post({ type: all });
213    }
214    const state: Focus = surface.state ?? { row: 0, col: 0 };
215    const now = move(state, rows, "");
216    if (["up", "down", "left", "right"].includes(k.key)) surface.setState({ ...move(now, rows, k.key), nav: true });
217    else if (k.key === "return" && state.nav) {
218      const item = rows[now.row]?.[now.col];
219      if (item) choose(item);
220    }
221    // Enter after a click, or Tab, meant the prompt: hand the keys back to it.
222    else if (k.key === "return" || k.key === "tab") surface.post({ release: true });
223    // Esc past a focused button: drop the focus and close the pane through the same
224    // path as the pane's own close item, not a bespoke message.
225    else if (k.key === "escape") {
226      surface.setState({ ...now, nav: undefined });
227      surface.post({ act: "close" });
228    }
229  });
230  surface.onPointer((p: { type: string; x: number; y: number }) => {
231    if (p.type !== "down") return;
232    const item = hit(lines, p.x, p.y);
233    if (item && focusable(item)) choose(item);
234  });
235
236  // Colour carries state only, by theme key so it follows the user's theme:
237  // what is open in the engine's selection blue, ✓ and ● in their colours.
238  // Brackets recede so the words stand; hover marks what takes a click.
239  const draw = (c: Cell, marginLeft: number) => {
240    const i = c.item;
241    const p = pieces(i);
242    const style: Record<string, unknown> = {};
243    // A clipped cell draws as one run; its pieces no longer line up.
244    style.children =
245      c.text !== textOf(i) || i.open
246        ? c.text
247        : [
248            p.pre && Text({ key: "pre", color: "subtle", children: p.pre }),
249            p.label,
250            p.glyph && Text({ key: "g", color: GLYPH_COLOR[i.state!], children: p.glyph }),
251            p.post && Text({ key: "post", color: "subtle", children: p.post }),
252          ].filter(Boolean);
253    if (i.kind === "quiet" || i.kind === "note" || i.read) style.dimColor = true;
254    if (i.open) Object.assign(style, { bold: true, color: "suggestion" });
255    if (i.kind === "title" || i.strong) style.bold = true;
256    if (focusable(i)) style.hover = { color: "suggestion" };
257    if (i.id === at) style.inverse = true;
258    return Box({ key: `c-${i.id}`, marginLeft, children: [Text(style)] });
259  };
260  const row = (l: Line) =>
261    Box({
262      key: `y-${l.y}`,
263      flexDirection: "row",
264      // A blank line holds its row, so what's drawn stays where a click is read.
265      height: 1,
266      // Each cell sits at its planned x: a column's padding is space, not text.
267      children: l.cells.map((c, n) => draw(c, c.x - (n ? l.cells[n - 1].x + l.cells[n - 1].text.length : 0))),
268    });
269  const body = lines.filter((l) => l.part === "body").map(row);
270  const out = [
271    ...(body.length
272      ? [Box({ key: "body", flexDirection: "column", children: body })]
273      : []),
274    ...lines.filter((l) => l.part === "chips").map(row),
275    ...(band.doc
276      ? [
277          Box({
278            key: "doc",
279            marginTop: 1,
280            children: [
281              // A Client's Markdown takes no link handler: its links are listed as rows instead.
282              Markdown({ key: "md", text: drawable(band.doc) }),
283            ],
284          }),
285        ]
286      : []),
287  ];
288  return Box({ flexDirection: "column", children: out });
289}
290
hooks/gate.tsx 70 lines
1// Once a hope move has run, the session's first edit waits until the card quotes the user's goal
2// and done-check in the user's own words. Asking is never held; the user's "go" opens it.
3
4/** The user's own words for what they want and how they will tell it worked. */
5export type Said = { goal?: string; done?: string };
6
7export const SLOTS: Record<keyof Said, string> = {
8  goal: "what they want",
9  done: "how they will tell it worked",
10};
11
12// The moves that settle what the user wants; a run of one arms the gate.
13export const MOVES = new Set([
14  "hope:intent",
15  "hope:shape",
16  "hope:clarify",
17  "hope:elicit",
18  "hope:explain",
19  "hope:interrogate",
20]);
21
22export const EDITS = new Set(["Edit", "Write", "MultiEdit", "NotebookEdit"]);
23
24type Msg = { role: string; text: string; toolResults?: { text: string }[] };
25
26// Two prefixes from one host version: multi-question answers take the second.
27const ANSWERED = /^(?:Your questions have been answered|The user answered):/;
28// An agent's return arrives as a user message; its words are the agent's.
29const AGENT = /<task-notification>|<agent-message /;
30
31/** What the user typed or picked: their messages, and their answers to AskUserQuestion. */
32export function userWords(msgs: Msg[]): string[] {
33  return msgs.flatMap((m) => [
34    ...(m.role === "user" && m.text.trim() && !AGENT.test(m.text)
35      ? [m.text]
36      : []),
37    ...(m.toolResults ?? []).map((r) => r.text).filter((t) => ANSWERED.test(t)),
38  ]);
39}
40
41// Case, quote marks, spacing and closing punctuation differ between a quote and its source.
42const norm = (s: string) =>
43  s
44    .toLowerCase()
45    .replace(/["'“”‘’]/g, "")
46    .replace(/\s+/g, " ")
47    .trim()
48    .replace(/[.,;:!?]+$/, "");
49
50/** The slots whose quote is missing or appears in none of the user's words. */
51export function unquoted(
52  said: Said | undefined,
53  words: string[],
54): (keyof Said)[] {
55  const heard = words.map(norm);
56  return (Object.keys(SLOTS) as (keyof Said)[]).filter((k) => {
57    const q = norm(said?.[k] ?? "");
58    return !q || !heard.some((w) => w.includes(q));
59  });
60}
61
62/** What the model reads when its edit is held. */
63export function heldReason(missing: (keyof Said)[]): string {
64  const what = missing.map((k) => `${k} (${SLOTS[k]})`).join(" and ");
65  return `Held: the card has no ${what} in the user's own words. Ask the user, then write a \`\`\`card block whose "said" copies their words exactly, {"said":{"goal":"…","done":"…"}}, before editing again. The user can also type "go" as their own message to start without them; a "go" picked from your question does not open it, so never offer one.`;
66}
67
68/** A prompt that tells the session to start as it stands. */
69export const saysGo = (text: string) => /^\s*go\b/i.test(text);
70
hooks/memory.tsx 124 lines
1import type { Item } from "./band.tsx";
2
3// The files that steer Claude across sessions: its auto-memory, and the instructions it loads.
4
5/** Absolute path → last modification (ms). */
6export type Snapshot = Record<string, number>;
7/** `label`: the path as a person names it, and what a change request asks about. */
8export type Steering = {
9  path: string;
10  label: string;
11  state: "new" | "changed" | "deleted" | "retrieved";
12};
13/** Where the session's steering files live: auto-memory, the project, the user's config. */
14export type Places = { memory: string; root: string; config: string };
15
16/** The transcript sits at `<config>/projects/<project>/<session>.jsonl`, auto-memory beside it. */
17export function places(
18  transcriptPath: string,
19  root: string,
20): Places | undefined {
21  const parts = transcriptPath.split("/");
22  if (parts.length < 5 || parts.at(-3) !== "projects") return undefined;
23  return {
24    memory: `${parts.slice(0, -1).join("/")}/memory`,
25    root,
26    config: parts.slice(0, -3).join("/"),
27  };
28}
29
30const STEERING = /(^|\/)(CLAUDE(\.local)?\.md|AGENTS\.md)$|^\.claude\//;
31
32/** A project file, by its path from the root, that Claude loads as instructions or settings.
33 * Worktrees under .claude/ are copies of the project, not instructions. */
34export function isSteering(relative: string): boolean {
35  return STEERING.test(relative) && !relative.startsWith(".claude/worktrees/");
36}
37
38/** Any absolute path that is a steering file: auto-memory, a project one, the user's CLAUDE.md. */
39export function isSteeringPath(path: string, p: Places): boolean {
40  if (path.startsWith(`${p.memory}/`) || path === `${p.config}/CLAUDE.md`)
41    return true;
42  return (
43    path.startsWith(`${p.root}/`) && isSteering(path.slice(p.root.length + 1))
44  );
45}
46
47export function label(path: string, p: Places): string {
48  if (path.startsWith(`${p.memory}/`))
49    return `memory/${path.slice(p.memory.length + 1)}`;
50  if (path.startsWith(`${p.root}/`)) return path.slice(p.root.length + 1);
51  return p.config.endsWith("/.claude")
52    ? `~/.claude${path.slice(p.config.length)}`
53    : path;
54}
55
56export function changes(
57  before: Snapshot,
58  after: Snapshot,
59  p: Places,
60): Steering[] {
61  const paths = [
62    ...new Set([...Object.keys(before), ...Object.keys(after)]),
63  ].sort();
64  return paths.flatMap((path): Steering[] => {
65    const state = !(path in before)
66      ? "new"
67      : !(path in after)
68        ? "deleted"
69        : before[path] !== after[path]
70          ? "changed"
71          : undefined;
72    return state ? [{ path, label: label(path, p), state }] : [];
73  });
74}
75
76/** The files the session read or loaded, once each; one it also updated is listed there alone. */
77export function retrieved(
78  paths: string[],
79  updated: Steering[],
80  p: Places,
81): Steering[] {
82  const shown = new Set(updated.map((u) => u.path));
83  return [...new Set(paths)]
84    .filter((path) => !shown.has(path))
85    .sort()
86    .map((path) => ({
87      path,
88      label: label(path, p),
89      state: "retrieved" as const,
90    }));
91}
92
93/** One row a file, its state and actions in columns before it, so a long name never pushes them
94 * out of line: view it in the pane, open it in the editor, or ask Claude to change it. */
95function fileRow(f: Steering): Item[] {
96  const gone = f.state === "deleted";
97  const blank = (id: string): Item => ({ id, label: "", kind: "note", column: true });
98  return [
99    f.state === "retrieved"
100      ? blank(`note:mem-state:${f.path}`)
101      : { id: `note:mem-state:${f.path}`, label: f.state, kind: "note", column: true },
102    gone
103      ? blank(`note:mem-edit:${f.path}`)
104      : { id: `edit:${f.path}`, label: "edit", kind: "quiet", column: true },
105    { id: `ask:${f.label}`, label: "ask", kind: "quiet", column: true },
106    { id: `${gone ? "note:mem" : "view"}:${f.path}`, label: f.label, kind: gone ? "note" : "line" },
107  ];
108}
109
110/** Updated or added files, then retrieved ones, each under its heading; an empty section is left out. */
111export function memoryRows(files: Steering[]): Item[][] {
112  const sections = [
113    ["updated", files.filter((f) => f.state !== "retrieved")],
114    ["retrieved", files.filter((f) => f.state === "retrieved")],
115  ] as const;
116  return sections
117    .filter(([, fs]) => fs.length)
118    .flatMap(([heading, fs], i) => [
119      ...(i ? [[]] : []),
120      [{ id: `note:mem-${heading}`, label: heading, kind: "note" as const }],
121      ...fs.map(fileRow),
122    ]);
123}
124