/** * #1065 T2: the guided prompt of `ahub init` for a person in a terminal on a new project. * * It asks one question per setting of the spec's table, in the table's order, one line each: the label, the choices and the default in brackets. Enter keeps the default and leaves * that setting out of the request; any other answer is an explicit choice, exactly as the equivalent flag is (so typing the default is `--coordination advisory`, which writes the * key). Unknown input asks again and never guesses. When every question is answered it shows the plan, in the words `--dry-run` prints, and asks y/N. N, an empty answer, end of * input and Ctrl-C write nothing. What it returns are the values the flags would have set, so the files it leads to are the files the equivalent flags write (AC4); nothing here * writes or reads a file. * * Who is offered it is decided by `promptGate`: a person at a terminal, on a new project, with no setting flag and no `--yes`. A delegated peer, a live test and any run without a * terminal never reach `runInitPrompt` and get defaults plus their flags (AC5). */ import { INIT_SETTINGS, TRACK_CONFIG, SDLC_MODES, SPEC_REVIEW_MODES, COORDINATION_MODES, AUTONOMY_CHOICES, type InitSettingRow, type InitSettingsRequest } from "./init-settings.ts"; import { readFileSync } from "node:fs"; import { join } from "node:path"; import { PROFILE_NAMES } from "../hub/profiles.ts"; import { DEFAULT_CONFIG } from "../hub/daemon.ts"; import { DEFAULT_SPECS_CONFIG } from "../hub/specs-config.ts"; import { START_AGENTS_ALLOWED, START_AGENTS_DEFAULT } from "../hub/start-agents.ts"; import { NO_CONDUCTOR, PERSON_REVIEWS, ROLE_FLAGS, eligiblePeers, parseRoleFlag, roleKeyOf, type RoleFlag } from "./init-roles.ts"; /** What a prompt needs from its surroundings. `ask` resolves to `null` at the end of input and after Ctrl-C (the caller turns both into `null`); it never throws for either. */ export interface InitPromptPorts { ask(question: string): Promise; print(line: string): void; } /** Everything the questions set: the settings request the flags build, plus the three choices that are not settings rows. */ export interface InitAnswers { request: InitSettingsRequest; profile?: string; shadow: boolean; releaseGuard: boolean } /** `declined`: the person answered no. `interrupted`: end of input or Ctrl-C. `refused`: a question got no valid answer in three tries. Nothing is written in any of the three. */ export type InitPromptResult = { ok: true; answers: InitAnswers } | { ok: false; reason: "declined" | "interrupted" | "refused"; message: string }; /** The four questions that are choices of `ahub init` but not rows of the settings table. */ const NOT_ROWS: ReadonlySet = new Set(["profile", TRACK_CONFIG, "autonomy", "release-guard", "shadow", ...Object.values(ROLE_FLAGS).map(roleKeyOf)]); const MAX_TRIES = 3; const NOTHING = "nothing was written"; const yes = (text: string) => /^(y|yes)$/i.test(text.trim()); const word = (text: string) => text.trim().toLowerCase(); export interface InitQuestion { /** The `INIT_SETTINGS` id, or `profile`, `autonomy`, `release-guard`, `shadow` for the four choices that are not rows. */ id: string; label: string; choices: string; /** The default in brackets: what an empty answer keeps. */ shown: string; /** Reads an answer into the value to put in the answers, or throws a reason that names the allowed values. */ read(text: string): unknown; } /** * The defaults the brackets show, read from where the writer gets them so a change there cannot leave the prompt showing a wrong one while Enter writes the real one: the shipped * `templates/config.json` for the keys it carries (memory, snapshots, each adapter switch, specs), the loader's own `DEFAULT_CONFIG` for coordination, and the specs config defaults. A key neither * source has throws, naming the key, so a new row without a known default is a loud failure in `test/init-prompt.test.ts` and not a guess. */ const TEMPLATE = JSON.parse(readFileSync(join(import.meta.dir, "..", "..", "templates", "config.json"), "utf8")) as Record; const at = (doc: unknown, path: readonly string[]): unknown => path.reduce((node, key) => node && typeof node === "object" ? (node as Record)[key] : undefined, doc); export function shownDefault(id: string): string { const row = INIT_SETTINGS.find(entry => entry.id === id); if (!row) throw new Error(`no init setting ${id}`); const path = row.path as readonly string[]; const fromTemplate = row.file === "config.json" ? at(TEMPLATE, path) : undefined; const value = fromTemplate !== undefined ? fromTemplate : id === "coordination" ? DEFAULT_CONFIG.coordination : id === "specs.enabled" ? DEFAULT_SPECS_CONFIG.enabled : id === "specs.review" ? DEFAULT_SPECS_CONFIG.review : id === "sdlc.required_checks" ? "none" : id === "sdlc.mode" ? "off" // no file is written for it: the loader's own default (src/hub/sdlc.ts) : row.id.endsWith(".enabled") ? false // a legacy `.enabled` switch that the template does not carry reads as off : undefined; if (typeof value === "boolean") return value ? "on" : "off"; if (typeof value === "string") return value; throw new Error(`the shown default of ${id} is unknown: add it to templates/config.json or to shownDefault`); } const onOff = (id: string, label: string, shown: "on" | "off"): InitQuestion => ({ id, label, choices: "on|off", shown, read: text => { const w = word(text); if (["on", "y", "yes", "true"].includes(w)) return true; if (["off", "n", "no", "false"].includes(w)) return false; throw new Error("answer on or off"); }, }); const oneOf = (id: string, label: string, values: readonly string[], shown: string): InitQuestion => ({ id, label, choices: values.join("|"), shown, read: text => { const w = word(text); if (values.includes(w)) return w; throw new Error(`answer one of ${values.join(", ")}`); }, }); export interface InitQuestionContext { /** The agent set `ahub setup` chose on this machine (the default shown for the agents question), or `undefined` for the shipped default. */ machineAgents?: readonly string[]; /** Effective research default for this new project, read from the trusted setup choice (else off). */ machineResearch?: boolean; /** Project packs a profile answer may name besides the shipped profiles. */ packs?: readonly string[]; discoverChecks?: () => Promise; /** Shadow history is offered only for a folder with no Git work tree. */ shadowAvailable?: boolean; /** The peers whose agent CLI is on this machine, offered first in the role questions (#1408). */ installedPeers?: readonly string[]; } /** * The questions, in the order of the spec's table: profile, agents, specs, spec review, SDLC, coordination, memory, snapshots, each adapter's enable switch, machine autonomy, release * guard and shadow history. A settings row is asked only while `INIT_SETTINGS` has it, and a row the table gains is caught by the test that compares the two. */ export function initQuestions(context: InitQuestionContext = {}): InitQuestion[] { const ids = new Set(INIT_SETTINGS.map(row => row.id)); const packs = context.packs ?? []; const profile: InitQuestion = { id: "profile", label: "Profile", choices: [...PROFILE_NAMES, ...packs].join("|"), shown: "dev", read: text => { const w = text.trim(); if ((PROFILE_NAMES as readonly string[]).includes(w) || packs.includes(w)) return w; throw new Error(`answer one of ${[...PROFILE_NAMES, ...packs].join(", ")}`); }, }; const agents: InitQuestion = { id: "start.agents", label: "Agents ahub up starts", choices: `${START_AGENTS_ALLOWED.join(",")} as a comma list, or none`, shown: (context.machineAgents ?? START_AGENTS_DEFAULT).join(", ") || "none", read: text => INIT_SETTINGS.find(row => row.id === "start.agents")!.parse(text.trim().toLowerCase()), }; // #1408 T2: one question per role, with only the peers that can hold it (a new project has no start modes yet, so each kind is judged in its own default form). Installed agents come first. const roleQuestion = (flag: RoleFlag): InitQuestion => { const role = ROLE_FLAGS[flag], peers = eligiblePeers(role, () => undefined, context.installedPeers ?? []); const shown = shippedHolders(role); return { id: roleKeyOf(role), label: role === "conductor" ? "Conductor (reports to you, asks for your decisions; needs an interactive peer)" : role === "planner" ? "Planner" : "Reviewer", choices: role === "conductor" ? [...peers, NO_CONDUCTOR].join("|") : role === "reviewer" ? `${peers.join(",")} as a comma list, or ${PERSON_REVIEWS}` : `${peers.join(",")} as a comma list`, shown, read: text => { const choice = parseRoleFlag(flag, text.trim().toLowerCase()); const named = choice === NO_CONDUCTOR || choice === PERSON_REVIEWS ? [] : Array.isArray(choice) ? choice : [choice]; const refused = named.find(peer => !peers.includes(peer)); if (refused !== undefined) throw new Error(`${refused} cannot be ${role} here; answer ${role === "conductor" ? [...peers, NO_CONDUCTOR].join(", ") : peers.join(", ")}`); return choice; }, }; }; const switches = INIT_SETTINGS.filter(row => row.id.endsWith(".enabled") && !["specs.enabled", "memory.enabled", "research.enabled", "snapshots.enabled"].includes(row.id)); const all: InitQuestion[] = [ profile, agents, roleQuestion("--conductor"), roleQuestion("--planner"), roleQuestion("--reviewer"), // #1411: Enter leaves the choice out, so .gitignore stays as git has it today and the block follows that. { ...onOff(TRACK_CONFIG, "Commit the shared hub config (config.json, routing.toml, sdlc.toml) to git", "off"), shown: "as .gitignore has it" }, onOff("specs.enabled", "Design specs and their freshness checks", shownDefault("specs.enabled") as "on" | "off"), oneOf("specs.review", "Spec review mode", SPEC_REVIEW_MODES, shownDefault("specs.review")), oneOf("sdlc.mode", "SDLC mode", SDLC_MODES, shownDefault("sdlc.mode")), { id: "sdlc.required_checks", label: "Required CI checks", choices: "comma-separated names", shown: "none", read: text => INIT_SETTINGS.find(row => row.id === "sdlc.required_checks")!.parse(text) }, oneOf("coordination", "Coordination", COORDINATION_MODES, shownDefault("coordination")), onOff("memory.enabled", "Shared memory", shownDefault("memory.enabled") as "on" | "off"), onOff("research.enabled", "Research records", context.machineResearch === true ? "on" : "off"), onOff("snapshots.enabled", "Per-turn snapshots", shownDefault("snapshots.enabled") as "on" | "off"), ...switches.map(row => onOff(row.id, row.describe.charAt(0).toUpperCase() + row.describe.slice(1), shownDefault(row.id) as "on" | "off")), oneOf("autonomy", "Machine autonomy preset", AUTONOMY_CHOICES, "inherit"), onOff("release-guard", "Release guard (AGENTS.md block and pre-push hook)", "off"), ...(context.shadowAvailable ? [onOff("shadow", "Shadow history (a folder with no Git work tree)", "off")] : []), ]; return all.filter(question => NOT_ROWS.has(question.id) || ids.has(question.id)); } /** Who holds `role` in the shipped `templates/config.json` (what Enter keeps), or `none` when nobody does: read from the template so the bracket cannot drift from what is written. */ function shippedHolders(role: "conductor" | "planner" | "reviewer"): string { const roles = at(TEMPLATE, ["roles"]); const holders = roles && typeof roles === "object" ? Object.entries(roles as Record).filter(([, list]) => Array.isArray(list) && list.includes(role)).map(([peer]) => peer) : []; return holders.join(", ") || (role === "reviewer" ? PERSON_REVIEWS : "none"); } /** The question line: `label (a|b|c) [default]: `. */ export const questionLine = (question: InitQuestion): string => `${question.label} (${question.choices}) [${question.shown}]: `; /** * Asks every question, then the confirmation. `preview` turns the answers into the lines of the plan; the caller runs the same planner `--dry-run` runs, so what is shown is what is * written, and a throw from it (a custom hooks path under the release guard, a config the loader refuses) ends the prompt with its message and no write. */ export async function runInitPrompt(ports: InitPromptPorts, context: InitQuestionContext, preview: (answers: InitAnswers) => string[]): Promise { const answers: InitAnswers = { request: { values: {} }, shadow: false, releaseGuard: false }; ports.print("ahub init: press Enter to keep the default in brackets. N at the end, Ctrl-C or Ctrl-D writes nothing."); for (const original of initQuestions(context)) { let question = original; if (question.id === "sdlc.required_checks") { if (!["advise", "enforce"].includes(String(answers.request.values["sdlc.mode"]))) continue; const names = await context.discoverChecks?.() ?? []; answers.request.values["sdlc.required_checks"] = [...names]; question = { ...question, shown: names.join(", ") || "none; supply check names" }; } let settled = false; for (let attempt = 0; attempt < MAX_TRIES && !settled; attempt++) { const answer = await ports.ask(questionLine(question)); if (answer === null) return { ok: false, reason: "interrupted", message: NOTHING }; if (!answer.trim()) { settled = true; break; } // Enter: the default, and nothing is set for this question try { const value = question.read(answer); if (question.id === "profile") answers.profile = value as string; else if (question.id === "autonomy") answers.request.autonomy = value as typeof AUTONOMY_CHOICES[number]; else if (question.id === "release-guard") answers.releaseGuard = value as boolean; else if (question.id === "shadow") answers.shadow = value as boolean; else answers.request.values[question.id] = value; settled = true; } catch (error) { ports.print(` ${(error as Error).message}; asking again`); } } if (!settled) return { ok: false, reason: "refused", message: `no valid answer for "${question.label}" after ${MAX_TRIES} tries, so ${NOTHING}; run ahub init again, or pass the setting as a flag` }; } let lines: string[]; try { lines = preview(answers); } catch (error) { return { ok: false, reason: "refused", message: `${(error as Error).message}` }; } ports.print(lines.length ? `This will be written:\n${lines.join("\n")}` : "Nothing differs from the defaults; the project gets the shipped configuration."); const confirm = await ports.ask("Write this? [y/N]: "); if (confirm === null) return { ok: false, reason: "interrupted", message: NOTHING }; if (!yes(confirm)) return { ok: false, reason: "declined", message: NOTHING }; return { ok: true, answers }; } /** * Whether the shadow-history question is asked: shadow history exists for a folder with no Git work tree, so an absent repository is eligible (that is the case it is for), a shadow repository that is * already there is eligible too (`--shadow` accepts it), and a real Git work tree is not (`ahub init --shadow` refuses it). */ export const shadowOffered = (repo: { shadow?: boolean } | undefined): boolean => repo === undefined || repo.shadow === true; /** The rows of the plan in the words `ahub init --dry-run` prints, so the prompt and the preview cannot disagree. */ export const settingLines = (rows: readonly InitSettingRow[]): string[] => rows.map(row => ` ${row.key}: ${row.from === undefined ? "(not set)" : JSON.stringify(row.from)} -> ${JSON.stringify(row.to)} (${row.file})`); /** * Whether a run is offered the prompt: a person (the console role, not a delegated peer or a live test) at a terminal (stdin and stdout), on a new project, with no flag of any kind * that sets something and no `--yes`. Every other run gets defaults plus its flags and is never asked anything. */ export function promptGate(input: { newProject: boolean; flagGiven: boolean; yes: boolean; dryRun: boolean; stdinIsTTY: boolean; stdoutIsTTY: boolean; role: string; delegated: boolean; liveTest: boolean }): boolean { return input.newProject && !input.flagGiven && !input.yes && !input.dryRun && input.stdinIsTTY && input.stdoutIsTTY && input.role === "console" && !input.delegated && !input.liveTest; }