// The page's pure logic: what the person answered, and what they asked for, in // the words those things have to reach the agent as. // // Everything here is a pure function of an item and a value. That is the point // of the file: app.js cannot be loaded outside a browser (it touches `document` // at module scope and starts a session on import), so any logic that stays in // it is logic no test can reach. Three defects in this exact code got as far as // the screen before anyone noticed. It lives here so `node --test` can see it. // // No DOM, no `local`, no fetch. If a function in here needs any of those, it // belongs in app.js instead. import { NOT_CONNECTED } from "./labels.js"; import { FIXED_REASON, FLOW_SKILLS, SKILLS, labelFor, skillByName, skillFor } from "./skills.js"; import { SPEC_STATES, stateFor } from "./spec-states.js"; /* ----------------------------------------------------- the sent answer */ /** * The value an in-flight send carries, or null if it carries no answer. * * A send can be a note on its own: someone asks a question about the question * before answering it. That still goes in `local.sent`, because the note really * is on its way, but it must NOT make the page treat the question as answered * and lock the form. They have not answered it yet, and locking them out is how * an open question becomes unanswerable. */ export function sentAnswer(sent) { return sent && sent.value ? sent.value : null; } /** * What the person settled on, for a question that is no longer open. * * `answer` is what the agent recorded when it settled the question. `submitted` * is what the server wrote down the moment Send was pressed. The second exists * because the first depends on the agent remembering to do it, and a card that * says "Settled" above an empty form is the worst thing this page can show. */ export function recordedAnswer(item) { const a = item && item.answer && typeof item.answer === "object" ? item.answer : null; const s = item && item.submitted && typeof item.submitted === "object" ? item.submitted : null; if (!a && !s) return null; return { ...(s || {}), ...(a || {}) }; } /** * True when the agent wrote in the item's thread after the person's last send * and has not settled it: the question is being asked again, so what they sent * belongs back on the form rather than gone. */ export function agentRepliedAfterSend(item) { const s = item && item.submitted; if (!s || typeof s !== "object" || (item.answer && typeof item.answer === "object")) return false; const thread = Array.isArray(item.thread) ? item.thread : []; return thread.some((m) => m && threadWho(m) === "agent" && (!s.at || !m.at || m.at >= s.at)); } /** * A send the person made that the agent never settled, still sitting on an * OPEN question. * * `local.sent` covers this while the same tab is alive; `submitted` is the * server's own record of the send and survives a reload, a resume onto a new * port, and a second tab. An open item that carries one, and has had no agent * reply since, is "sent, waiting on Plan2Code" — not a question still * waiting for them, which is what it reads as when an agent takes the answer * and moves on without marking the item settled. * * Two ways out, both meaning the question is theirs again: * * - an agent message in the item's thread AFTER the send means the question * is being asked again — the person gets a live form back, not a locked * record of what they already said; * - a recorded `answer` means the agent did settle it at some point (the * status is just stale or the question was re-asked), so the leftover * `submitted` is the old send, not one in flight. */ export function submittedAwaiting(item) { const s = item && item.submitted; if (!s || typeof s !== "object") return null; if (item.answer && typeof item.answer === "object") return null; const thread = Array.isArray(item.thread) ? item.thread : []; const replied = thread.some((m) => m && threadWho(m) === "agent" && (!s.at || !m.at || m.at >= s.at)); return replied ? null : s; } /** * The note (and its attachments) the person last sent on an item, while the * agent has yet to say anything after it. The server records it as `sentNote` * on every send, so the page can show it in the Notes pane and in the Sent * box instead of letting it vanish into a send that shows no sign of arriving. * Any agent message from the send onwards, or one with no clock to compare, * means it has been picked up. The person's own entries never count: the * server writes their note into the thread as it arrives. */ export function noteAwaiting(item) { const n = item && item.sentNote; if (!n || typeof n !== "object") return null; const thread = Array.isArray(item.thread) ? item.thread : []; const picked = thread.some((m) => m && threadWho(m) === "agent" && (!n.at || !m.at || m.at >= n.at)); return picked ? null : n; } /** * Who said a thread entry and what they said. The contract is `{ who, text }` * and the server lifts anything else into it, but sessions written before that * hold `{ from, md }` replies, which would otherwise draw as empty bubbles. */ export function threadWho(m) { return m && (m.who || m.from || m.role) === "user" ? "user" : "agent"; } export function threadText(m) { if (!m) return ""; for (const k of ["text", "md", "body", "content"]) if (typeof m[k] === "string" && m[k].trim()) return m[k]; return ""; } /* -------------------------------------------------------------- labels */ // A key worth showing: one or two letters or digits (A, 2) a person can say // back in the terminal. A word key (commit-first, yes) is an id for the agent, // and as a chip beside its own label it is noise. export function showKey(k, text) { if (k == null) return false; const key = String(k); return /^[A-Za-z0-9]{1,2}$/.test(key) && key.toLowerCase() !== String(text || "").trim().toLowerCase(); } export function optionLabel(item, k) { const o = ((item && item.options) || []).find((x) => x.k === k); if (!o) return String(k); return showKey(o.k, o.text) ? `${o.k} · ${o.text}` : o.text; } export function verdictLabel(item, id) { const list = (item && item.verdicts) || [ { id: "approve", label: "Looks good, go ahead" }, { id: "changes", label: "I want changes" }, ]; const v = list.find((x) => x.id === id); return v ? verdictText(v) : String(id); } // A verdict's button text. `label` is the contract; `text` is what menu // options use, and an agent that borrows it must not get blank buttons. export function verdictText(v) { return v.label || v.text || v.id; } export const CHECK_STATE_LABEL = { done: "All done", blocked: "I am stuck", help: "I need help", defer: "Later", }; /** * The answer as lines to show back, in the page's words rather than the * agent's shorthand: "A · Run the setup first", not "a". */ export function answerLines(item, v) { const out = []; if (!v) return out; if (v.skipped) out.push("Skipped"); if (v.k) out.push(optionLabel(item, v.k)); if (Array.isArray(v.ks)) for (const k of v.ks) out.push(optionLabel(item, k)); // A card that opened ticked can be sent with nothing ticked: say so, so the // settled card is not blank. Other multis keep their record as it was. if (item && Array.isArray(v.ks) && v.ks.length === 0 && !v.skipped && startsTicked(item)) { out.push("None ticked"); } if (typeof v.yes === "boolean") out.push(v.yes ? item.yesLabel || "Yes" : item.noLabel || "No"); if (typeof v.ok === "boolean") { out.push(v.ok ? item.yesLabel || "Yes, that is right" : item.noLabel || "Not quite"); } if (v.verdict) out.push(verdictLabel(item, v.verdict)); if (v.state) out.push(CHECK_STATE_LABEL[v.state] || String(v.state)); if (Array.isArray(v.done) && v.done.length) { out.push(`Steps done: ${v.done.map((n) => n + 1).join(", ")}`); } if (Array.isArray(v.rows) && v.rows.length) { out.push(`${v.rows.length} steps, in the order you set`); } if (item && item.kind === "lessons") out.push(...lessonLines(item, v)); return out; } /* ------------------------------------------------------ the lessons card */ // The choice that keeps a row as it stands, per row type (FR-15). A refused // row cannot take it until it is reworded. export const LESSON_KEEP_WORD = { lesson: "Keep", doubt: "Keep", gone: "Keep", "agents-fix": "Apply", tidy: "Apply", "log-line": "Move", area: "Create" }; // The choices that open the row for editing. export const LESSON_EDIT_WORDS = new Set(["Reword", "Reword and move", "Rename"]); // The edit word per row type: what a refused row's keep word goes back to. export const LESSON_EDIT_WORD = { lesson: "Reword", doubt: "Reword", gone: "Reword", "agents-fix": "Reword", tidy: "Reword", "log-line": "Reword and move", area: "Rename" }; // The first ask's answers, as the agent reads them. export const FIRST_ASK_WORDS = { yes: "Switch Learning on", no: "Not for this project" }; /** The field a row's edit must fill, and the label that names it. */ export function lessonEditField(row) { if (row && row.type === "agents-fix") return { key: "after", label: "The new wording" }; if (row && row.type === "area") return { key: "name", label: "The area's name" }; if (row && row.type === "log-line") return { key: "lessons", label: "The lesson" }; return { key: "text", label: "The lesson" }; } // The lessons a failure log line would become, or the line itself when the // list gave none (a refused line comes masked and with none). const logLessons = (row) => (Array.isArray(row.lessons) && row.lessons.length ? row.lessons.map(String) : [row.text || ""]); /** * The edit fields' first values: the row as it stands, or its text replaced by * `prefill` (a suggested wording) when one is given. */ export function lessonEditStart(row, prefill) { const given = typeof prefill === "string" && prefill.trim() ? prefill : null; if (row.type === "agents-fix") return { after: given ?? lessonOriginal(row) }; if (row.type === "area") return { name: given ?? lessonOriginal(row), paths: [...(row.paths || [])] }; if (row.type === "log-line") return { lessons: given ? [given] : logLessons(row), why: row.why || "", area: row.area || "" }; if (row.type === "tidy") return { text: given ?? lessonOriginal(row), why: row.wordingWhy || "", area: row.area || "" }; return { text: given ?? lessonOriginal(row), why: row.why || "", area: row.area || "" }; } /** * The row's own words, the ones its edit starts from and is compared with to * tell whether it was reworded. A log line's lessons are joined by newlines. */ export function lessonOriginal(row) { if (row.type === "agents-fix") return row.after || row.text || ""; if (row.type === "area") return row.name || row.text || ""; if (row.type === "log-line") return logLessons(row).join("\n"); // A tidy row's words are the new wording, not the sentence describing the change. if (row.type === "tidy") return row.wording || ""; return row.text || ""; } /** * The agent's suggestion for a row (Ask for suggestions): `{ choice, text, why }` * from either form `suggested` takes, a bare choice word or an object. The * words are kept only for a choice that opens an edit; null without one. */ export function lessonSuggestion(item, row) { const all = item && item.suggested && typeof item.suggested === "object" ? item.suggested : null; const given = all && row ? all[row.id] : null; if (typeof given === "string") return { choice: given, text: "", why: "" }; if (!given || typeof given !== "object" || typeof given.choice !== "string") return null; const edit = LESSON_EDIT_WORDS.has(given.choice); const words = (v) => (edit && typeof v === "string" && v.trim() ? v.trim() : ""); return { choice: given.choice, text: words(given.text), why: words(given.why) }; } /** The edit's words in the same form as lessonOriginal, or the original when untouched. */ function lessonTyped(row, edit) { const field = lessonEditField(row).key; if (field === "lessons") return Array.isArray(edit.lessons) ? edit.lessons.map((t) => String(t).trim()).join("\n") : lessonOriginal(row); return typeof edit[field] === "string" ? edit[field].trim() : lessonOriginal(row); } /** Whether a row's edit changed its words. */ export function lessonReworded(row, edit = {}) { return lessonTyped(row, edit) !== lessonOriginal(row); } /** * One decision as lessons.mjs decide takes it: `{ id, choice }` plus what the * choice needs from the row's edits (`edit`, the person's typed values). A * refused row kept after a reword goes as a Reword, since its words changed. * Only values that differ from the row are sent for an area's paths or a * lesson's area; `why` goes whenever it is not empty or was emptied. A log * line's "Reword and move" goes as `lessons: [{ text, why?, area? }]`; the * agent adds each `about` (End step 6). */ export function lessonDecision(row, choice, edit = {}) { const typed = lessonTyped(row, edit); const keepWord = LESSON_KEEP_WORD[row.type]; let pick = choice; if (row.refused && choice === keepWord && typed !== lessonOriginal(row)) pick = LESSON_EDIT_WORD[row.type]; const d = { id: row.id, choice: pick }; if (!LESSON_EDIT_WORDS.has(pick)) return d; if (row.type === "agents-fix") return { ...d, after: typed }; if (row.type === "area") { const out = { ...d, name: typed }; if (Array.isArray(edit.paths)) { const paths = edit.paths.map((p) => String(p).trim()).filter(Boolean); if (paths.join(",") !== (row.paths || []).join(",")) out.paths = paths; } return out; } const baseWhy = row.type === "tidy" ? row.wordingWhy || "" : row.why || ""; const why = typeof edit.why === "string" ? edit.why.trim() : baseWhy; const area = typeof edit.area === "string" && edit.area && edit.area !== (row.area || "") ? edit.area : ""; if (row.type === "log-line") { const texts = typed.split("\n"); return { ...d, lessons: texts.map((text) => ({ text, ...(why ? { why } : {}), ...(area ? { area } : {}) })) }; } const out = { ...d, text: typed }; // An emptied Why is sent as "", so decide does not keep the old one. if (why || (typeof edit.why === "string" && baseWhy)) out.why = why; if (area) out.area = area; return out; } /** What is still missing before a row's decision can go, or "" when nothing is. */ export function lessonMissing(row, decision) { if (!decision || !LESSON_EDIT_WORDS.has(decision.choice)) return ""; const { key, label } = lessonEditField(row); if (key === "lessons") { const list = Array.isArray(decision.lessons) ? decision.lessons : []; return list.length && list.every((l) => String((l && l.text) || "").trim()) ? "" : label; } return String(decision[key] || "").trim() ? "" : label; } /** The words one decision reads as: "Keep: ", "Reword: ", "Apply: ". */ export function lessonDecisionLine(row, d) { const shown = d.choice === "Apply" && !(row && row.type === "tidy") ? (row && row.file) || "AGENTS.md" : Array.isArray(d.lessons) ? d.lessons.map((l) => (l && l.text) || "").join(" / ") : d.after || d.name || d.text || (row ? (row.type === "area" ? row.name || row.text : row.text) : "") || d.id; return `${d.choice}: ${shown}`; } /** * The lessons card's answer as lines: one per decision, then how many were * left waiting; or the first ask's answer. */ export function lessonLines(item, v) { if (!v) return []; if (v.firstAsk === "yes" || v.firstAsk === "no") return [FIRST_ASK_WORDS[v.firstAsk]]; if (!Array.isArray(v.decisions)) return []; const rows = Array.isArray(item && item.rows) ? item.rows : []; const byRow = new Map(rows.map((r) => [r.id, r])); const out = v.decisions.map((d) => lessonDecisionLine(byRow.get(d.id), d)); const left = rows.filter((r) => !v.decisions.some((d) => d.id === r.id)).length; if (left) out.push(`${left} left waiting`); else if (!out.length) out.push("Nothing chosen"); return out; } /** * What the agent reads for the lessons card: the lines above, and the * decisions exactly as lessons.mjs decide takes them, on one `Decisions:` * line, so the console and the terminal write the same decisions file. */ export function lessonsReply(item, v) { if (!v) return ""; if (!Array.isArray(v.decisions)) return [...lessonLines(item, v), ...(v.text ? [v.text] : [])].join("\n"); const rows = Array.isArray(item && item.rows) ? item.rows : []; const byRow = new Map(rows.map((r) => [r.id, r])); const left = rows.filter((r) => !v.decisions.some((d) => d.id === r.id)).length; // The count leads, so each decision starts a line of its own under the card's title. const lines = [`${v.decisions.length} decided${left ? `, ${left} left waiting` : ""}`]; for (const d of v.decisions) lines.push(lessonDecisionLine(byRow.get(d.id), d)); lines.push(`Decisions: ${JSON.stringify(v.decisions)}`); if (v.text) lines.push(v.text); return lines.join("\n"); } /** * A single-choice answer, which is one thing or the other and never both. * * Picking an option and then writing "none of these, because…" used to send * both, joined, with the pick first: an answer that argued with itself. The * rule lives here rather than in the two click handlers that apply it, so it * is one statement that a test can hold to. * * Returns null when there is nothing to stage, which is what "they have not * answered yet" looks like everywhere else in the page. */ export function choiceAnswer({ k, text } = {}) { if (k) return { type: "answer", kind: "choice", k }; const said = String(text || "").trim(); return said ? { type: "answer", kind: "choice", text: said } : null; } /* -------------------------------------------------------- the brief ask */ /** * The words a brief request reaches the agent as. * * This is not an answer, but it is the same kind of thing and it belongs to the * same rule: a string the agent parses, so it has to be exactly right, so it * has to be somewhere a test can see it. `range` is the Pathfinder brief * playbook's own grammar -- `today`, `this week`, `since `, `full`. */ export function briefPhrase(range) { const r = String(range || "today").trim(); if (r === "full") return "Write a full brief."; if (r.startsWith("since ")) return `Write a brief covering everything ${r}.`; return `Write a brief for ${r}.`; } /* ---------------------------------------------------- the autofill text */ // A placeholder is a suggestion nobody can edit, and it vanishes the moment you // type. On a question whose example is most of a good answer, retyping it is // busywork, so offer it as a value instead. The lead-in ("For example:") is the // agent talking about the example, not part of it, so it is stripped. // // Two rules keep the stripping from mangling a real answer: // // The lead-in must be FOLLOWED by a separator. Without that, "Egypt office" // loses its "Eg" and "Exampled output" loses its "Example". // // A bare hyphen only separates when it has space around it. "For example - a" // is a lead-in; the hyphen in "example-name-here" is part of the name, and a // kebab-case suggestion must survive intact for a field with a `pattern`. // // "Say" is deliberately not in the list: "Say when you need it by" is a // question far more often than it is a preamble. const EXAMPLE_LEAD = /^\s*(?:for\s+(?:example|instance)|examples?|such\s+as|e\.?\s?g\.?|i\.?\s?e\.?)(?:\s+-\s+|\s*[:,.]\s*|\s+)/i; /** * The placeholder, as a value someone could accept as their own answer. * Empty string when there is nothing worth offering. */ export function suggestionFrom(item) { const raw = String((item && item.placeholder) || "").trim(); if (!raw) return ""; const stripped = raw.replace(EXAMPLE_LEAD, "").trim(); if (!stripped) return ""; // Recapitalize only when a lead-in was actually removed, and never on a // field with a shape to match: "audit-export" must not become "Audit-export". if (stripped !== raw && !item.pattern && /^[a-z]/.test(stripped)) { return stripped[0].toUpperCase() + stripped.slice(1); } return stripped; } /* ------------------------------------------------------ the hand-off */ // The badge each workflow wears. Shared with the server, which writes it into // the page it serves so the first paint already names the session instead of // flashing a placeholder until the script arrives. Derived from skills.js. export const WORKFLOW_LABEL = Object.fromEntries(FLOW_SKILLS.map((s) => [s.workflow, s.label])); export function workflowLabel(workflow) { return labelFor(workflow) || workflow || "Session"; } // The workflows that ship the console (install.js bundles it into every // skill as `additionalReferences`). Any other next step has no browser page // to open, and asking for one would send the next session looking for // something that is not there. Derived from skills.js: every entry is one. export const CONSOLE_WORKFLOWS = FLOW_SKILLS.map((s) => s.command).filter(Boolean); // Rides on the end of the command as part of the skill's argument. Every // console skill takes it as the answer to "web console or terminal?" instead // of asking again. It must stay clear of "brief", "recap" and "minutes": // pathfinder reads any of those in its argument as a request for a brief. export const CONTINUE_IN_CONSOLE = "--web"; // The long form the skills still accept. A command that carries it is copied // with the flag instead, which is shorter and reads as the parameter it is. const CONSOLE_SENTENCE = /\s*Use the web console for this session\.?/gi; /** * What the Copy button on the finished screen puts on the clipboard. * * Someone who worked the whole session in the browser should land back in the * browser, not be asked the interface question as though they were new. The * `--web` flag goes on the same line as the command, because what follows a * slash command is its argument, and a pasted second line is not reliably that. * A command written with the long sentence is copied with the flag instead. * * `fin.console` overrides the inference either way; otherwise it follows from * whether the next step is a workflow that has a console at all. */ export function handoffText(fin) { const raw = String((fin && fin.command) || "").trim(); if (!raw) return ""; const cmd = raw.replace(CONSOLE_SENTENCE, "").trim(); const capable = typeof fin.console === "boolean" ? fin.console : cmd !== raw || CONSOLE_WORKFLOWS.some((w) => cmd === w || cmd.startsWith(w + " ")); // An agent that already wrote the flag should not get it twice. if (!capable || /(^|\s)--web\b/.test(cmd)) return cmd; return `${cmd} ${CONTINUE_IN_CONSOLE}`; } /** * A finish is a pause when its headline says so. There is no flag to read: * the stop playbook asks the agent to write "a headline that says it is * paused rather than done", so the page reads the same words the person * does. A session that ends on its own says nothing of the sort. */ export function finishPaused(fin) { return /^\s*paused\b/i.test(String((fin && fin.headline) || "")); } // The line a finished session shows when it has nothing left to run. Split so // the page can render the backticked command as code; joined with a space they // read as one sentence. export const ALL_DONE_LEAD = "All done, nothing left to run."; export const ALL_DONE_REST = "To start something else, run `/plan2code` in a new conversation to open the dashboard."; // The same line for the desktop app: there is no separate "new conversation" // to paste this into, only the one terminal panel the agent already runs in. export const ALL_DONE_REST_IN_APP = "To start something else, paste `/plan2code` into the terminal panel below to open the dashboard."; export const DASHBOARD_COMMAND = "/plan2code"; /** * Which hand-off a finish gets: a pause always offers its resume command, a * finish with a command offers it as the next step, and one without has * nothing left to run. */ export function handoffShape(fin) { if (finishPaused(fin)) return "paused"; return String((fin && fin.command) || "").trim() ? "next" : "all-done"; } /* ------------------------------------------------------------ stopping */ // What a stop request reads as, the way a typed message would. It goes to the // agent as part of `reply`, so the same caution applies as to the hand-off // sentence: nothing Pathfinder would read as asking for a brief. export const STOP_REPLY = "Stop here and save my place, so I can pick this up later."; // The same request, with a handoff note written first. Same plain voice: the // reply is read by the agent, and a word like "brief" would send Pathfinder // off to write one. export const STOP_HANDOFF_REPLY = "Stop here, save my place and write a handoff, so the dashboard can pick this up later."; /** The `__stop` action; `handoff: true` only when the handoff choice was pressed. */ export function stopAction({ handoff } = {}) { return handoff ? { i: "__stop", type: "stop", handoff: true } : { i: "__stop", type: "stop" }; } /** * Why a session-level button (Stop session, Back to the dashboard) cannot be * pressed right now, or null when it can. Both wait for the person's turn: * while Plan2Code has the ball it may be halfway through writing their last * answers into the files, and a request landing then is how a question ends up * half recorded. `waiting` is the caller's "the agent is working or a reply is * owed, and it has not gone adrift" -- an agent that has stopped checking in * never replies, and a button grayed out forever would lock the person in. An * uncollected send still blocks even then, because the server takes one at a * time. */ export function turnGate({ gone = false, pendingResult = false, waiting = false } = {}) { if (gone) return "gone"; if (pendingResult) return "pending"; if (waiting) return "waiting"; return null; } // What the top bar's Back to the dashboard button reads as to the agent. It // goes in `reply` like the stop, so the same caution applies: nothing // Pathfinder would read as asking for a brief. export const HOME_REPLY = "Save my place and take me back to the dashboard, right here in this session."; const HOME_TITLES = { gone: NOT_CONNECTED, pending: "Your last answers are still being picked up. You can leave once they have been.", waiting: "Plan2Code is working on your answers. You can leave once it replies.", }; /** * The top bar's Back to the dashboard button. Hidden on the dashboard itself, * on a finished screen (which carries its own way back) and while a stop is * under way; otherwise pressable on the person's turn, like Stop session. * Once pressed it waits for the page to turn, unless the agent has gone * adrift: then it comes back, and a second press is safe because the server * refuses a duplicate while the first is uncollected. */ export function homeButtonState({ workflow, finished = false, stopping = false, homeward = false, adrift = false, warned = false, ...turn } = {}) { if (!workflow || workflow === "dashboard" || finished || stopping) return { hidden: true, disabled: true, title: "" }; if (homeward && !adrift) return { hidden: false, disabled: true, title: "Opening the dashboard…" }; const gate = turnGate(turn); return { hidden: false, disabled: Boolean(gate), // With a stop warning up, the work since the last save is what leaving // loses: the tooltip says so rather than promising a saved place. title: gate ? HOME_TITLES[gate] : warned ? "Back to the dashboard. Work since the last save is not kept." : "Back to the dashboard. Your place is saved first.", }; } /** * The resume command the PAGE can offer when the agent cannot: it stopped * listening, or went away without posting a finish. Built only from what the * session state says, never guessed. * * Pathfinder resumes from its folder, so it needs `specDir` (`specs/`), * which the workflow posts once the folder exists. Without one the bare * command still works: Pathfinder asks which idea. Planning finds its own * draft and takes no path. The implementation steps, Revision and * Finalization take the spec's overview.md, and without it they ask which * spec (or find the only one). A quick task keeps nothing on disk to resume * from, so its command starts it again. */ export function resumeCommand({ workflow, specDir } = {}) { const raw = String(specDir || "").trim().replace(/\\/g, "/").replace(/\/+$/, ""); // Only a real relative specs/ path. Anything else would be run verbatim by // someone with no way to tell it was wrong. const dir = /^specs\/[a-z0-9][a-z0-9._-]*$/i.test(raw) ? raw : ""; // What follows the command is the entry's `resume` (skills.js). A workflow // the console does not know (an old session's, or an agent-less one like // setup, which has no command) resumes as Pathfinder. let entry = skillFor(workflow); if (!entry || !entry.command) entry = skillFor("pathfinder"); if (dir && entry.resume === "overview") return `${entry.command} ${dir}/overview.md`; if (dir && entry.resume === "folder") return `${entry.command} ${dir}/pathfinder`; return entry.command; } /* ------------------------------------------------ after a build is done */ // What the two buttons on a finished build's hand-off reach the agent as. They // go in `reply` like any typed message, so the same caution applies as to the // other session phrases: plain words, nothing Pathfinder would read as a brief. export const REVIEW_REPLY = "Review what was just built before I go: run the focused code review on this session's changes, here on the page."; export const DONE_REPLY = "No review, thanks. I am done: close the session."; export const DASHBOARD_REPLY = "Take me back to the dashboard, right here in this session."; export const COMMIT_REPLY = "Commit what was just built: open Git's commit flow, right here in this session."; export const CHANGELOG_REPLY = "Update the CHANGELOG before I commit: open Changelog, right here in this session."; // Shown under the Back to the dashboard button: the press picks up in the same // conversation, which carries a long skill's context into the next one. export const DASHBOARD_NOTE = "This picks up in the same conversation. That's fine after a quick or small skill; after a long one, type `/clear` in your terminal and run `/plan2code` for a clean start."; // Under the app, a clean start is New Session, not typing `/clear` by hand: // it also leaves the dashboard a handoff brief of where this step left off. export const DASHBOARD_NOTE_IN_APP = "This picks up in the same conversation. That's fine after a quick or small skill; after a long one, press New Session at the top of the window for a clean start instead."; /** * Whether a finish offers the way back to the dashboard. The agent opts in * with `finish.dashboard: true`, so a skill that predates the button never * shows one nobody answers; a pause never offers it. */ export function dashboardOffer(fin) { return Boolean(fin && fin.dashboard === true && !finishPaused(fin)); } /** * Whether a finish offers to commit what was just built from this page. The * agent opts in with `finish.commit: true` on a build that ended with a git * command; the press starts Git's commit flow in the same session, as the dashboard's * card does. A pause never offers it. */ export function commitOffer(fin) { return Boolean(fin && fin.commit === true && !finishPaused(fin)); } /** * Whether a finish offers to update the CHANGELOG before the commit. The agent * opts in with `finish.changelog: true` on a finished quick task or finalize; * the press opens Changelog in the same session, whose "Commit this now?" yes * carries on to Git. A pause never offers it. */ export function changelogOffer(fin) { return Boolean(fin && fin.changelog === true && !finishPaused(fin)); } /** * The skill a finish's next step names, when it is one the page can start in * this session: `{ skill, workflow, spec }`, or null. The agent writes nothing * new for it. The command's leading `/plan2code-...` is looked up in skills.js * (a trailing `--web` and any other argument are ignored), and `spec` is the * `specs/` folder the command mentions, when it does. A pause, the * dashboard's own `/plan2code` and any command that is not a skill (a git * commit) offer nothing. */ export function continueOffer(fin) { if (!fin || finishPaused(fin)) return null; const first = String(fin.command || "").trim().split(/\s+/)[0]; if (!first.startsWith("/")) return null; const entry = skillByName(first.slice(1)); if (!entry || entry.workflow === "dashboard") return null; const match = /(?:^|[\s"'])(specs\/[A-Za-z0-9][A-Za-z0-9._-]*)(?=[/\s"']|$)/.exec(String(fin.command)); return { skill: entry.skill, workflow: entry.workflow, spec: match ? match[1] : undefined }; } /** What Continue here reaches the agent as: a launch's sentence, naming the skill. */ export function continueReply(offer) { const entry = SKILLS.find((s) => s.skill === offer.skill); const card = entry && entry.card ? entry.card.title : entry ? entry.name : offer.skill; return launchReply({ title: card, command: entry ? entry.command : `/${offer.skill}` }, offer.spec ? { dir: offer.spec } : null); } /** * Whether a finish carries the offer to review what was just built. The agent * posts `finish.review` as `true` or as `{ "label": "..." }` on a finished * quick task (an implementation phase offers the review earlier, as a verdict * on its sign-off card). */ export function reviewOffer(fin) { const r = fin && fin.review; if (!r) return null; const label = typeof r === "object" && typeof r.label === "string" ? r.label.trim() : ""; return { label: label || "Review what was just built" }; } /** * One offer button on a finish (review, done, commit, changelog, dashboard, launch). A press of * any of them is the session's one answer, so it locks every button until the * finish goes away, not just until the agent collects the send: `asked` is * the pressed one, which keeps its "requested…" label. */ export function afterFinishButton(afterBuild, kind, pendingResult) { return { asked: afterBuild === kind, disabled: Boolean(afterBuild) || Boolean(pendingResult) }; } /* ------------------------------------------------------- the dashboard */ // The skills the dashboard offers, in the order it offers them. The page owns // this list rather than the session state: the catalog is product UI, fixed // for everyone, and the alternative — the agent posting it — would put a dozen // cards of boilerplate through the patch channel every time the menu opened. // `menu` in the state can still say what the agent knows: a `recommend` skill // to highlight and a `details` line per card ("Phase 2 of 4 is next"). // // `workflow` is the name the skill resumes the session under: the dashboard // hands its session over, and this is what turns the page into that skill's // console. A test holds this list against the skills install.js builds, so a // new skill cannot ship without a card here. export const CATALOG_GROUPS = [ { id: "setup", title: "First, the project" }, { id: "pipeline", title: "The steps, in order" }, { id: "extra", title: "Useful any time" }, ]; // `spec: true` marks the cards that take a spec folder as their target: when // the picker has a spec selected, its `dir` rides along in the `__launch` // action so the launched skill knows which spec it was picked for. Derived from // skills.js: the entries with a card, in their order, each card's fields // beside the skill's name, command and workflow. export const SKILL_CATALOG = FLOW_SKILLS.filter((s) => s.card).map((s) => ({ skill: s.skill, command: s.command, workflow: s.workflow, ...(s.review ? { review: s.review } : {}), ...s.card, })); // The desktop app's Implementation Loop card: not a skill, so not in // SKILL_CATALOG. The dashboard draws it after its group's other cards, and its // click opens the setup screen instead of launching anything. const LOOP_SKILL = SKILLS.find((s) => s.appOnly && s.card); export const LOOP_ENTRY = LOOP_SKILL ? { skill: LOOP_SKILL.skill, command: "Desktop app only", workflow: null, appOnly: true, ...LOOP_SKILL.card } : null; // The Review Loop's card, the second app-only entry: same shape, own setup screen. const REVIEW_LOOP_SKILL = SKILLS.find((s) => s.appOnly && s.card && s !== LOOP_SKILL); export const REVIEW_LOOP_ENTRY = REVIEW_LOOP_SKILL ? { skill: REVIEW_LOOP_SKILL.skill, command: "Desktop app only", workflow: null, appOnly: true, ...REVIEW_LOOP_SKILL.card } : null; // Every app-only card, in the order the dashboard draws them. export const APP_ONLY_ENTRIES = Object.freeze([LOOP_ENTRY, REVIEW_LOOP_ENTRY].filter(Boolean)); export const OUTSIDE_APP_LINE = "Runs only in the Plan2Code desktop app."; // A workflow by the name its dashboard card gives it ("Implement"), for the // screens that speak of it as a thing being started rather than as a badge. export function workflowTitle(workflow) { const entry = SKILL_CATALOG.find((e) => e.workflow === workflow); return entry ? entry.title : workflowLabel(workflow); } // Every skill gets its own Planny on the starting and waiting screens, drawn // as a