@join-pantheon/cli 0.35.2-rc.2 → 0.35.3-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -28,7 +28,7 @@ import { AGENT_SURFACES, applyProfileInit, cleanList, dropCatchAllClaims, isAgen
28
28
  import { runGuide, terminalIO, questionOrNull, parseSetupFlags, questionnaire, optOutsFrom, decisionAreasProblem, ALERT_WORDS, AUTOPILOT_WAKE_OFF } from "./setup-guide.js";
29
29
  import { APPROVED_ENV, unsandboxedRisk, beginApproval, changeLabel, composeSetupAlert, dropPending, findPending, gateChanges, lastChangeLine, loadPending, logChanges, machineSetUp, markFirstSetup, askedByLabel, pendingSaid, whoIsAsking } from "./setup-changes.js";
30
30
  import { selectActs, formatAct, resolveRef } from "./history-view.js";
31
- import { doctor, render, shareBlock } from "./doctor.js";
31
+ import { doctor, ownProcesses, render, shareBlock } from "./doctor.js";
32
32
  import { FEEDBACK_ADDRESS } from "./feedback.js";
33
33
  import { menubarProc, notifierProc, relayProc, runBy, workerProc, workerFlagRunMinutes, wiring, logFileFor, dataSummary, stopProc, statFile, elapsed, windowsProcessInfo } from "./machine.js";
34
34
  import { assess } from "./untrusted.js";
@@ -50,7 +50,7 @@ import { loadPolicy, requestReadinessRecheck, unsandboxedAllowed, savePolicy, MO
50
50
  import { alreadyMemberLine, askedLine, configureLines, fetchSeats, inUseLine, offerSeats, seatsForTeam, seatsToMove, startGate, RECOVER_WAITING_EXIT } from "./recover-offer.js";
51
51
  import { hyphenateSpaces, shellArg, teamNameProblem } from "./team-name.js";
52
52
  import { folderRefusalHere, isTemporaryRefusal, projectFolderAnswer } from "./folder-guard.js";
53
- import { installService, serviceInstalled, serviceLogFile, uninstallService } from "./service.js";
53
+ import { borrowedHome, installService, serviceInstalled, serviceLogFile, serviceState, servicesUnavailable, uninstallService } from "./service.js";
54
54
  import { LEGACY_TASK_NAME, hostAlive, hostFiles, readHostState, recordedTaskName } from "./win-host.js";
55
55
  import { ACTS, LIMITS } from "./protocol.js";
56
56
  import { loadPersonas, personaByName, describePersona, initPersona, personaDir, olderTeammatesNote } from "./persona.js";
@@ -400,9 +400,12 @@ async function findAndBindRepos(all, m, teamRepos, opts = {}) {
400
400
  console.error(D(` ${name(fp)}: you unbound it on this machine — left so (pantheon use ${m.name} --here inside it to bind it again)`));
401
401
  const todo = want.filter((fp) => !already.has(fp) && !unbound.has(fp));
402
402
  if (!todo.length) {
403
- console.error(`${C("✓")} every repo "${m.name}" works from is bound on this machine: ${want.map(name).join(", ")}`);
403
+ if (!opts.quiet)
404
+ console.error(`${C("✓")} every repo "${m.name}" works from is bound on this machine: ${want.map(name).join(", ")}`);
404
405
  return;
405
406
  }
407
+ if (opts.quiet)
408
+ console.error("");
406
409
  let recents = opts.recents;
407
410
  const tty = !!process.stdin.isTTY && !!process.stderr.isTTY;
408
411
  if (recents === undefined && tty) {
@@ -415,7 +418,7 @@ async function findAndBindRepos(all, m, teamRepos, opts = {}) {
415
418
  console.error(D(` looking for ${todo.map(name).join(", ")} on this machine…`));
416
419
  let found = findTeamClones(todo, { recents: !!recents, ...(opts.extra ? { extra: opts.extra } : {}) });
417
420
  let missing = todo.filter((fp) => !found.some((f) => f.repo.fingerprint === fp));
418
- if (missing.length && tty) {
421
+ if (missing.length && tty && opts.askFolder !== false) {
419
422
  const rl = createInterface({ input: process.stdin, output: process.stderr });
420
423
  const a = ((await questionOrNull(rl, ` Not found: ${missing.map(name).join(", ")}. The folder your repos live in (Enter to skip): `)) ?? "").trim();
421
424
  rl.close();
@@ -547,7 +550,12 @@ async function workerAfterBinding(how) {
547
550
  try {
548
551
  const { commandsChosen } = await import("./profile.js");
549
552
  const commandsOn = ws.some((w) => w.kind === "repo") && commandsChosen() !== false;
550
- installService("worker", ws[0].path, commandsOn ? ["--allow-bash"] : []);
553
+ const { notLoadedWhy } = await import("./setup-guide.js");
554
+ const why = notLoadedWhy(installService("worker", ws[0].path, commandsOn ? ["--allow-bash"] : []));
555
+ if (why) {
556
+ console.error(`\x1b[33m ! the worker is installed but not running (${why}) — teammates' requests wait for you until it runs: pantheon service restart worker\x1b[0m`);
557
+ return;
558
+ }
551
559
  console.error(` ${C("✓")} worker on — serves ${ws.map((w) => w.name).join(", ")} while you are away${wakeMode(loadProfile(j)) === "approved" ? "; you are asked the first time each teammate needs it" : ""}${commandsOn ? "; a run may run tests, commit and push to its own branch (edits only: pantheon setup --commands no)" : ""}`);
552
560
  }
553
561
  catch (e) {
@@ -1123,6 +1131,12 @@ const SET_UP = (() => { try {
1123
1131
  catch {
1124
1132
  return false;
1125
1133
  } })();
1134
+ const WORKER_BEFORE = (() => { try {
1135
+ return serviceInstalled("worker");
1136
+ }
1137
+ catch {
1138
+ return false;
1139
+ } })();
1126
1140
  function personName() {
1127
1141
  try {
1128
1142
  const c = load();
@@ -1396,16 +1410,26 @@ async function rejectPendingChange(id, by) {
1396
1410
  logChanges(entry.changes.map((c) => ({ at: Date.now(), setting: c.setting, from: c.from, to: c.to, ...(c.about ? { about: c.about } : {}), asked_by: entry.asked_by, outcome: "kept", approved_by: by, id })));
1397
1411
  return { ok: true, said: `kept as it is — ${entry.changes.map((c) => changeLabel(c)).join("; ")} was not made` };
1398
1412
  }
1413
+ function guideAsks(preset) {
1414
+ return !!process.stdin.isTTY && !!process.stderr.isTTY && !argv.includes("--yes") && !argv.includes("--no-guide") && !Object.keys(preset).length;
1415
+ }
1399
1416
  async function guidedSetup(cfg, project, opts = {}) {
1400
- if (argv.includes("--no-guide"))
1401
- return;
1402
1417
  const preset = opts.preset ?? {};
1403
- const interactive = !!process.stdin.isTTY && !argv.includes("--yes") && !Object.keys(preset).length;
1418
+ if (argv.includes("--no-guide") && !Object.keys(preset).length) {
1419
+ if (opts.command === "setup")
1420
+ console.log("Nothing changed: --no-guide asks no questions, and no answers were passed. Pass the ones to change (pantheon setup --questions lists them), or run pantheon setup without --no-guide.");
1421
+ return { cancelled: false };
1422
+ }
1423
+ const interactive = guideAsks(preset);
1404
1424
  if (!interactive && !opts.force)
1405
- return;
1425
+ return { cancelled: false };
1406
1426
  const rl = interactive ? createInterface({ input: process.stdin, output: process.stderr }) : null;
1407
1427
  const io = rl ? terminalIO(rl, (l) => console.error(l)) : null;
1408
- console.error(`\n${B("A few choices, then you're done.")}${io ? "" : Object.keys(preset).length ? D(" (applying the answers you passed)") : D(" (no terminal — taking the defaults)")}`);
1428
+ const summary = !!io && !!opts.summary && !opts.founder;
1429
+ if (!summary)
1430
+ console.error(`\n${B("A few choices, then you're done.")}${io ? "" : Object.keys(preset).length ? D(" (applying the answers you passed)") : D(" (no terminal — taking the defaults)")}`);
1431
+ else
1432
+ console.error("");
1409
1433
  try {
1410
1434
  let serves = null;
1411
1435
  if (!project && cfg.spaceId) {
@@ -1433,7 +1457,7 @@ async function guidedSetup(cfg, project, opts = {}) {
1433
1457
  }
1434
1458
  }
1435
1459
  }
1436
- const r = await runGuide(io, { cfg, project, optOut: optOutsFrom(argv), serves, setUp: SET_UP, ...(base !== undefined ? { base } : {}), ...(opts.founder !== undefined ? { founder: opts.founder } : {}) }, {
1460
+ const r = await runGuide(io, { cfg, project, optOut: optOutsFrom(argv), serves, setUp: SET_UP, ...(base !== undefined ? { base } : {}), ...(opts.founder !== undefined ? { founder: opts.founder } : {}), ...(summary ? { summary: true } : {}) }, {
1437
1461
  gate: (changes, a) => protectSetup(changes, { replay: setupReplay(a, changes, preset), io }),
1438
1462
  unsandboxedAgents: () => { try {
1439
1463
  return agentsNeedingUnsandboxed();
@@ -1441,7 +1465,7 @@ async function guidedSetup(cfg, project, opts = {}) {
1441
1465
  catch {
1442
1466
  return [];
1443
1467
  } },
1444
- readiness: () => agentReadiness(cfg),
1468
+ ...(opts.finish ? {} : { readiness: () => agentReadiness(cfg) }),
1445
1469
  publish: async (p, keep) => {
1446
1470
  const c = new PantheonClient(cfg, undefined, { role: "cli" });
1447
1471
  try {
@@ -1474,8 +1498,14 @@ async function guidedSetup(cfg, project, opts = {}) {
1474
1498
  },
1475
1499
  } : {}),
1476
1500
  }, preset);
1477
- if (r.held)
1478
- return;
1501
+ if (r.held) {
1502
+ if (r.cancelled) {
1503
+ console.error("");
1504
+ for (const l of await cancelledLines(cfg, opts.command === "setup"))
1505
+ console.error(` ${l}`);
1506
+ }
1507
+ return { cancelled: !!r.cancelled };
1508
+ }
1479
1509
  if (!SET_UP) {
1480
1510
  try {
1481
1511
  markFirstSetup(askedByLabel(whoIsAsking()));
@@ -1501,6 +1531,28 @@ async function guidedSetup(cfg, project, opts = {}) {
1501
1531
  finally {
1502
1532
  rl?.close();
1503
1533
  }
1534
+ return { cancelled: false };
1535
+ }
1536
+ const STOPPED_ITEM = { says: "Your settings weren't chosen: you stopped at the settings screen (what was already set up is said above).", fix: "pantheon setup" };
1537
+ async function cancelledLines(cfg, rerun) {
1538
+ const { stoppedLines } = await import("./finish-line.js");
1539
+ let wake = "anyone", installed = false, running = false;
1540
+ let commands = "off";
1541
+ try {
1542
+ wake = wakeMode(loadProfile(cfg));
1543
+ }
1544
+ catch { }
1545
+ try {
1546
+ installed = serviceInstalled("worker");
1547
+ running = installed && (borrowedHome() ? ownProcesses().worker : serviceState("worker").running);
1548
+ }
1549
+ catch { }
1550
+ try {
1551
+ commands = commandState({ project: process.cwd() }).level;
1552
+ }
1553
+ catch { }
1554
+ return stoppedLines({ rerun, installed, installedBefore: WORKER_BEFORE, running, wake, commands })
1555
+ .map((l) => l.replace(/pantheon setup --wake no$/, C("pantheon setup --wake no")).replace(/^To change any of it: pantheon setup /, `To change any of it: ${C("pantheon setup")} `));
1504
1556
  }
1505
1557
  function setupStatusLines() {
1506
1558
  try {
@@ -1723,6 +1775,105 @@ function printReady(tools) {
1723
1775
  console.error(D(` ${l}`));
1724
1776
  }
1725
1777
  }
1778
+ async function workerHeld() {
1779
+ try {
1780
+ if (servicesUnavailable(process.platform))
1781
+ return null;
1782
+ const { workerRunning } = await import("./finish-line.js");
1783
+ return await workerRunning({
1784
+ installed: () => serviceInstalled("worker"),
1785
+ running: () => borrowedHome() ? ownProcesses().worker : serviceState("worker").running,
1786
+ });
1787
+ }
1788
+ catch {
1789
+ return null;
1790
+ }
1791
+ }
1792
+ async function finishLine(tools, o) {
1793
+ const { finishItems, finishLines, finishMarker, SIGN_IN_RUN } = await import("./finish-line.js");
1794
+ const { teamWorkspaces } = await import("./worker-fleet.js");
1795
+ const cfg = load();
1796
+ const windows = (() => { try {
1797
+ return borrowedHome() ? null : mcpWindows.unwiredAgentWindows();
1798
+ }
1799
+ catch {
1800
+ return null;
1801
+ } })();
1802
+ const gather = async () => {
1803
+ let wakeOn = false, ready = null, served = null, pending = 0;
1804
+ try {
1805
+ if (cfg && !inWokenRun()) {
1806
+ wakeOn = wakeMode(loadProfile(cfg)) !== "no";
1807
+ if (wakeOn) {
1808
+ requestReadinessRecheck();
1809
+ ready = agentReadiness(cfg);
1810
+ }
1811
+ }
1812
+ }
1813
+ catch { }
1814
+ try {
1815
+ if (cfg?.spaceId)
1816
+ served = teamWorkspaces(loadAll(), cfg.spaceId).length;
1817
+ }
1818
+ catch {
1819
+ served = null;
1820
+ }
1821
+ try {
1822
+ pending = loadPending().length;
1823
+ }
1824
+ catch {
1825
+ pending = 0;
1826
+ }
1827
+ const workerWanted = wakeOn && !argv.includes("--no-worker");
1828
+ return [...(o.extra ?? []), ...finishItems({ tools, readiness: ready, team: cfg?.space ?? "<team>", workerWanted, served, windows, pending, worker: workerWanted && (served ?? 0) > 0 ? await workerHeld() : null })];
1829
+ };
1830
+ let items = await gather();
1831
+ if (guideAsks(o.preset)) {
1832
+ for (const it of items.filter((x) => x.signIn)) {
1833
+ const { agentById, resolveBinary } = await import("./agents.js");
1834
+ const b = agentById(it.signIn);
1835
+ const bin = b ? resolveBinary(b) : null;
1836
+ if (!b || !bin)
1837
+ continue;
1838
+ const how = SIGN_IN_RUN[b.id];
1839
+ console.error(`\n${it.says}`);
1840
+ const a = ((await askOnce(` Sign in to ${b.label} now?${how.inside ? ` It opens ${b.label} here: ${how.inside}.` : ""} [Y/n] `)) ?? "n").trim().toLowerCase();
1841
+ if (!(a === "" || a === "y" || a === "yes"))
1842
+ continue;
1843
+ const { spawn } = await import("node:child_process");
1844
+ const win = process.platform === "win32";
1845
+ const ignore = () => { };
1846
+ process.on("SIGINT", ignore);
1847
+ try {
1848
+ await new Promise((res) => {
1849
+ const p = spawn(win ? `"${bin}"` : bin, how.args, { stdio: "inherit", ...(win ? { shell: true } : {}) });
1850
+ p.on("exit", () => res());
1851
+ p.on("error", (e) => { console.error(D(` could not start ${b.label}: ${e.message} — ${it.fix}`)); res(); });
1852
+ });
1853
+ }
1854
+ finally {
1855
+ process.off("SIGINT", ignore);
1856
+ }
1857
+ }
1858
+ if (items.some((x) => x.signIn))
1859
+ items = await gather();
1860
+ }
1861
+ const lines = finishLines(items, { founder: o.founder, windowsUnknown: windows === null });
1862
+ console.error("");
1863
+ console.error(items.length ? `\x1b[33m${B(lines[0])}\x1b[0m` : `${C("✓")} ${B(lines[0].replace(/^✓ /, ""))}`);
1864
+ for (const l of lines.slice(1))
1865
+ console.error(l);
1866
+ const rd = readiness(tools);
1867
+ if (rd.attempted && !rd.wired)
1868
+ process.exitCode = 1;
1869
+ const marker = process.env["PANTHEON_FINISH_FILE"];
1870
+ if (marker) {
1871
+ try {
1872
+ writeFileSync(marker, finishMarker(items));
1873
+ }
1874
+ catch { }
1875
+ }
1876
+ }
1726
1877
  const PLAIN = !!process.env["NO_COLOR"];
1727
1878
  if (PLAIN) {
1728
1879
  const SGR = /\x1b\[[0-9;]*m/g;
@@ -1918,7 +2069,7 @@ const COMMAND_FLAGS = {
1918
2069
  trust: "[<member>] --yes --space <team>",
1919
2070
  recover: "[<team>] | withdraw <team> | confirm <member> | cancel <member> [--yes] --space <team> --no-worker --no-hook --no-notifications --no-menubar\n exits 3 when the move was asked for and waits for a teammate (or a day); 0 when it moved",
1920
2071
  say: "<ACT> <text> --to <member>[,<member>] --goal <id> --ref <id | seq | last> --summary '<one line>' --question (an ASK with no goal: a simple question, one answer and done) --domains <a,b> --branch --commit --remote (DELIVERED) --space <team>",
1921
- goal: "list | open \"<title>\" --with <member>[,…] [--acceptance \"…\"] [--deadline <ISO time>] [--list] | close <id> \"<summary>\"",
2072
+ goal: "list | open \"<title>\" --with <member>[,…] [--acceptance \"…\"] [--deadline <ISO time>] [--list] | close <id> \"<summary>\" | close <id> --settled",
1922
2073
  history: "--goal <id> --from <member> --last <n> --since <seq> --short --presence --json",
1923
2074
  usage: "--space <team> --days <n> --json",
1924
2075
  network: "--proxy <url> [--no-proxy <hosts>] | --direct | --clear",
@@ -2241,11 +2392,11 @@ async function main() {
2241
2392
  await workerAfterBinding(wp.how);
2242
2393
  windowsOverridesForBoundRepos();
2243
2394
  }
2244
- printReady(r.tools);
2245
- if (r.claimed)
2246
- await guidedSetup(load() ?? r.cfg, repoInfo(process.cwd())?.root ?? null, { preset: setupFlags.preset, force: Object.keys(setupFlags.preset).length > 0 || argv.includes("--yes"), founder: true });
2247
- if (r.claimed)
2248
- sayAgentReadiness(load() ?? r.cfg);
2395
+ const guided = r.claimed ? await guidedSetup(load() ?? r.cfg, repoInfo(process.cwd())?.root ?? null, { preset: setupFlags.preset, force: Object.keys(setupFlags.preset).length > 0 || argv.includes("--yes"), founder: true, finish: true }) : { cancelled: false };
2396
+ await finishLine(r.tools, { founder: true, preset: setupFlags.preset, extra: [
2397
+ ...(guided.cancelled ? [STOPPED_ITEM] : []),
2398
+ ...(!r.reach.shareable && r.reach.hint ? [{ says: "Your team's relay address only works on this machine, so the invite above can't be used from your teammate's yet.", fix: r.reach.hint.replace(/^A teammate cannot reach it\.\s*/, "") }] : []),
2399
+ ] });
2249
2400
  if (r.relay) {
2250
2401
  console.error(D(`\nKeeping the relay running here. Ctrl-C stops it (your teammate goes offline too).`));
2251
2402
  await new Promise(() => { });
@@ -2506,8 +2657,7 @@ async function main() {
2506
2657
  printGranted(r.granted);
2507
2658
  printRelayNote(r.cfg?.relay ?? parsed.relay);
2508
2659
  rememberWorkingProxy();
2509
- printReady(r.tools);
2510
- {
2660
+ if (!guideAsks(setupFlags.preset)) {
2511
2661
  const jc = load();
2512
2662
  const mode = jc ? wakeMode(loadProfile(jc)) : "anyone";
2513
2663
  console.error(D(mode === "anyone"
@@ -2539,20 +2689,18 @@ async function main() {
2539
2689
  if (!teamRepos.length && m?.repos?.length)
2540
2690
  teamRepos = m.repos.map((r) => ({ fingerprint: r.fp, origin: r.name }));
2541
2691
  if (all && m && teamRepos.length) {
2542
- console.error("");
2543
- await findAndBindRepos(all, m, teamRepos, { auto: !process.stdin.isTTY }).catch(() => { });
2692
+ const inRepo = !!repoInfo(process.cwd());
2693
+ if (!inRepo)
2694
+ console.error("");
2695
+ await findAndBindRepos(all, m, teamRepos, { auto: !process.stdin.isTTY, recents: false, ...(inRepo ? { askFolder: false, quiet: true } : {}) }).catch(() => { });
2544
2696
  }
2545
2697
  }
2546
2698
  await bindProjectFromScratch();
2547
2699
  await workerAfterBinding(wp.how);
2548
2700
  windowsOverridesForBoundRepos();
2549
- {
2550
- const joined = load();
2551
- if (joined)
2552
- await guidedSetup(joined, repoInfo(process.cwd())?.root ?? null, { preset: setupFlags.preset, force: Object.keys(setupFlags.preset).length > 0 || argv.includes("--yes") });
2553
- sayAgentReadiness(joined);
2554
- }
2555
- console.error(`\n${D('Then ask your agent: "check pantheon_status and say hello to the team".')}`);
2701
+ const joined = load();
2702
+ const guided = joined ? await guidedSetup(joined, repoInfo(process.cwd())?.root ?? null, { preset: setupFlags.preset, force: Object.keys(setupFlags.preset).length > 0 || argv.includes("--yes"), summary: true, finish: true }) : { cancelled: false };
2703
+ await finishLine(r.tools, { founder: false, preset: setupFlags.preset, ...(guided.cancelled ? { extra: [STOPPED_ITEM] } : {}) });
2556
2704
  return;
2557
2705
  }
2558
2706
  case "install": {
@@ -2751,7 +2899,7 @@ async function main() {
2751
2899
  if (errors.length)
2752
2900
  die(errors.join("\n") + "\n pantheon setup --questions lists every answer");
2753
2901
  const cfg = need();
2754
- await guidedSetup(cfg, repoInfo(process.cwd())?.root ?? null, { force: true, preset });
2902
+ await guidedSetup(cfg, repoInfo(process.cwd())?.root ?? null, { force: true, preset, command: "setup" });
2755
2903
  sayAgentReadiness(load() ?? cfg);
2756
2904
  return;
2757
2905
  }
@@ -2813,12 +2961,22 @@ async function main() {
2813
2961
  }
2814
2962
  }
2815
2963
  const goals = [...client.goals.values()];
2964
+ const { isSettled, SETTLED_HEADING } = await import("./settled.js");
2965
+ const settledNow = goals.filter((g) => isSettled(g, client.obligations, client.relayNow(), (id) => client.seenAct(id)?.goal));
2816
2966
  console.log(`\n${B("goals")}`);
2817
2967
  if (!goals.length)
2818
2968
  console.log(` ${D("(none)")}`);
2819
2969
  for (const g of goals) {
2970
+ if (settledNow.includes(g))
2971
+ continue;
2820
2972
  console.log(` ${goalStateWord(g.state).padEnd(10)} ${g.title}${g.kind === "worklist" ? D(" [your list]") : ""} ${D(`${g.acts} of ${g.budget} messages · ${g.id}`)}`);
2821
2973
  }
2974
+ if (settledNow.length) {
2975
+ console.log(D(` ${SETTLED_HEADING} (${settledNow.length}) — nothing owed, quiet three days: ${settledNow.slice(0, 3).map((g) => `"${clipWords(termSafe(g.title), 40)}"`).join(", ")}${settledNow.length > 3 ? `, +${settledNow.length - 3} more` : ""}`));
2976
+ const mineS = settledNow.filter((g) => g.opened_by === cfg.member);
2977
+ if (mineS.length)
2978
+ console.log(D(` yours to close: ${mineS.slice(0, 3).map((g) => `pantheon goal close ${g.id} --settled`).join(" · ")}${mineS.length > 3 ? " · pantheon goal list shows the rest" : ""}`));
2979
+ }
2822
2980
  const owed = client.obligations;
2823
2981
  const ageOf = (t) => {
2824
2982
  const m = Math.round((Date.now() - t) / 60000);
@@ -3062,10 +3220,18 @@ async function main() {
3062
3220
  try {
3063
3221
  if (sub === "list") {
3064
3222
  const open = [...client.goals.values()].filter((g) => g.state !== "CLOSED");
3223
+ const { isSettled, SETTLED_HEADING } = await import("./settled.js");
3224
+ const settledNow = open.filter((g) => isSettled(g, client.obligations, client.relayNow(), (id) => client.seenAct(id)?.goal));
3065
3225
  if (!open.length)
3066
3226
  console.log(D("no open goals — pantheon goal open \"<what it is about>\" --with <member>"));
3067
3227
  for (const g of open)
3068
- console.log(` ${g.id} ${g.state.padEnd(8)} ${g.title} ${D(`with ${g.members.join(", ")} · ${g.acts}/${g.budget} acts`)}`);
3228
+ if (!settledNow.includes(g))
3229
+ console.log(` ${g.id} ${g.state.padEnd(8)} ${g.title} ${D(`with ${g.members.join(", ")} · ${g.acts}/${g.budget} acts`)}`);
3230
+ if (settledNow.length) {
3231
+ console.log(D(`\n ${SETTLED_HEADING} — nothing owed, quiet three days after their last answer or delivery:`));
3232
+ for (const g of settledNow)
3233
+ console.log(D(` ${g.id} ${g.title}${g.opened_by === cfg.member ? ` · pantheon goal close ${g.id} --settled` : ` · ${g.opened_by} opened it`}`));
3234
+ }
3069
3235
  return;
3070
3236
  }
3071
3237
  if (sub === "open") {
@@ -3091,6 +3257,28 @@ async function main() {
3091
3257
  console.error(D(` now: pantheon say ASK "…" --to <member> --goal ${g.id}`));
3092
3258
  return;
3093
3259
  }
3260
+ if (sub === "close" && argv.includes("--settled")) {
3261
+ const { settledCloseBody } = await import("./settled.js");
3262
+ const id = argv[2] && !argv[2].startsWith("--") ? argv[2] : die("usage: pantheon goal close <goal id> --settled");
3263
+ const notSent = (why) => { client.close(); console.log(`not sent: ${why}`); process.exit(1); };
3264
+ const g = client.goals.get(id) ?? notSent("that goal is not in this team");
3265
+ if (g.state === "CLOSED") {
3266
+ console.log(`already closed: ${id}`);
3267
+ return;
3268
+ }
3269
+ if (g.opened_by !== cfg.member)
3270
+ notSent(`${g.opened_by} opened it, so they close it`);
3271
+ const read = await signedRead(cfg, "/obligations", {}, { timeoutMs: 5000 })
3272
+ .then(async (res) => (res.ok ? (await res.json()) : undefined), () => undefined);
3273
+ const listed = read?.settled_goals;
3274
+ if (!Array.isArray(listed) || typeof read?.seq !== "number")
3275
+ notSent("the relay could not say whether it is still settled — nothing was closed; try again in a moment");
3276
+ if (!listed.some((x) => x && x.id === id))
3277
+ notSent("it is not settled any more — something happened in it or something is owed there, so it stays open");
3278
+ const r = await client.send({ act: "CLOSE", body: settledCloseBody(cfg.member), goal: id, after_seq: read.seq }).catch((e) => notSent(plainError(e.message)));
3279
+ console.log(`closed ${id} (act ${r.id})`);
3280
+ return;
3281
+ }
3094
3282
  if (sub === "close") {
3095
3283
  const id = argv[2] ?? die('usage: pantheon goal close <goal id> "<what was done>"');
3096
3284
  const summary = argv.slice(3).filter((a) => !a.startsWith("--")).join(" ").trim() || die("say what was done: it is the goal's record");
@@ -5656,7 +5844,7 @@ async function main() {
5656
5844
  return need();
5657
5845
  const f = loadAll();
5658
5846
  const first = Object.values(f?.spaces ?? {})[0];
5659
- if (f && first && (!hud || ["details", "open", "fix", "done", "wake"].includes(hud.action)))
5847
+ if (f && first && (!hud || ["details", "open", "fix", "done", "moot", "wake"].includes(hud.action)))
5660
5848
  return configFor(f, first, null);
5661
5849
  if (hud && (hud.action === "reply" || hud.action === "retract")) {
5662
5850
  console.log(`not sent: which team it belongs to was not recorded — answer it from the board`);
@@ -6028,7 +6216,7 @@ async function main() {
6028
6216
  console.log(line);
6029
6217
  return;
6030
6218
  }
6031
- if (hud?.action === "done") {
6219
+ if (hud?.action === "done" || hud?.action === "moot") {
6032
6220
  const deadline = queuedDeadline();
6033
6221
  const tries = hud.space ? [cfg] : (() => { const f = loadAll(); const all = f ? Object.values(f.spaces ?? {}).map((m) => configFor(f, m, null)) : []; return all.length ? all : [cfg]; })();
6034
6222
  let c2 = null;
@@ -6060,9 +6248,32 @@ async function main() {
6060
6248
  return;
6061
6249
  }
6062
6250
  const open = o.goal && c2.goals.get(o.goal)?.state !== "CLOSED" ? o.goal : null;
6063
- const doneBody = `${doneCfg.member} marked this handled — dealt with outside Pantheon.`;
6251
+ const moot = hud.action === "moot";
6252
+ if (moot && /^"[\s\S]*" spent its act budget without closing$/.test(o.body)) {
6253
+ c2.close();
6254
+ console.log("not sent: this one asks whether its goal goes on — answer it, or close the goal");
6255
+ process.exit(1);
6256
+ }
6257
+ const ownEscalation = o.body.startsWith(`${doneCfg.member} escalated:`);
6258
+ let doneBody = `${doneCfg.member}: no longer needed — set aside.`;
6259
+ if (!moot) {
6260
+ const { cleanOutcome, doneAnswerBody } = await import("./done-outcome.js");
6261
+ const outcome = cleanOutcome(hud.body);
6262
+ if (outcome) {
6263
+ const { refuseOutbound } = await import("./outbound-guard.js");
6264
+ const leak = refuseOutbound(doneCfg, { body: outcome });
6265
+ if (leak) {
6266
+ c2.close();
6267
+ console.log(`not sent: ${panelLine(leak.replace(/^pantheon: (not sent — )?/, ""))}`);
6268
+ process.exit(1);
6269
+ }
6270
+ }
6271
+ doneBody = doneAnswerBody(doneCfg.member, outcome);
6272
+ }
6064
6273
  deadline.sending();
6065
- await c2.sendSettled({ act: "ANSWER", ref: o.ref, goal: open, after_seq: c2.readSeq, body: doneBody }).catch(async (e) => {
6274
+ await c2.sendSettled(moot && ownEscalation
6275
+ ? { act: "RETRACT", ref: o.ref, goal: null, to: null, after_seq: c2.readSeq, body: `${doneCfg.member} set this question aside: no longer needed.`, meta: { surface: "menubar" } }
6276
+ : { act: "ANSWER", ref: o.ref, goal: open, after_seq: c2.readSeq, body: doneBody }).catch(async (e) => {
6066
6277
  const { certainlyNotStored } = await import("./client.js");
6067
6278
  c2.close();
6068
6279
  console.log(certainlyNotStored(e)
@@ -6072,7 +6283,7 @@ async function main() {
6072
6283
  });
6073
6284
  deadline.done();
6074
6285
  c2.close();
6075
- console.error(D(`done — that decision is no longer waiting on you`));
6286
+ console.error(D(moot ? `set aside — that question is no longer on your board` : `done — that decision is no longer waiting on you`));
6076
6287
  return;
6077
6288
  }
6078
6289
  if (hud?.action === "details") {
package/dist/client.js CHANGED
@@ -11,6 +11,7 @@ import { expectsSigs, joinedSigning, loadPins, markMemberSigns, markSigs, member
11
11
  export { joinedSigning } from "./pins.js";
12
12
  import { trusted, verifyAct, verifyGoal, vouchedMove } from "./verify-act.js";
13
13
  import { newId, UPKEEP_AGENT } from "./protocol.js";
14
+ import { applyLast, lastOfView, noteLast } from "./settled.js";
14
15
  import { VERSION } from "./version.js";
15
16
  import { describeNetError, explainNetError, noteRelayAnswered, settleSystemFallback, systemFallbackPending, trySystemFallback, wsOptions } from "./network.js";
16
17
  const REFUSED_BEFORE_STORING = new Set([
@@ -436,6 +437,12 @@ export class PantheonClient {
436
437
  }
437
438
  if (this.seen.size > 500)
438
439
  this.seen.delete(this.seen.keys().next().value);
440
+ if (msg.act.goal) {
441
+ const g = this.goals.get(msg.act.goal);
442
+ const prev = g ? lastOfView(g) : undefined;
443
+ if (g && prev)
444
+ this.goals.set(g.id, applyLast(g, noteLast(prev, msg.act, msg.act.act === "ACCEPT" && msg.act.ref ? this.seen.get(msg.act.ref)?.act ?? null : null)));
445
+ }
439
446
  if (msg.act.from !== this.cfg.member && msg.act.act !== "JOIN" && msg.act.act !== "LEAVE") {
440
447
  this.push(msg.act);
441
448
  }
@@ -448,9 +455,13 @@ export class PantheonClient {
448
455
  this.obligations = msg.list;
449
456
  this.changed();
450
457
  break;
451
- case "goal":
452
- this.goals.set(msg.goal.id, msg.goal);
458
+ case "goal": {
459
+ const had = this.goals.get(msg.goal.id);
460
+ const kept = had ? lastOfView(had) : undefined;
461
+ this.goals.set(msg.goal.id, kept && msg.goal.last_at === undefined
462
+ ? { ...applyLast(msg.goal, kept), ...(had?.held ? { held: true } : {}) } : msg.goal);
453
463
  break;
464
+ }
454
465
  case "ack": {
455
466
  const fn = msg.cid ? this.acks.get(msg.cid) : undefined;
456
467
  if (fn && msg.cid) {
@@ -1321,6 +1332,9 @@ export class PantheonClient {
1321
1332
  .filter((r) => r.from === this.cfg.member && r.ts >= ts && r.act !== "JOIN" && r.act !== "LEAVE" && (goal == null || r.goal === goal))
1322
1333
  .sort((a, b) => a.seq - b.seq);
1323
1334
  }
1335
+ seenSince(ts) {
1336
+ return [...this.seen.values()].filter((r) => r.ts >= ts && r.act !== "JOIN" && r.act !== "LEAVE").sort((a, b) => a.seq - b.seq);
1337
+ }
1324
1338
  takenBySibling() {
1325
1339
  return this.myObligations().filter((o) => o.claimed_by && o.claimed_by.session !== this.session);
1326
1340
  }
@@ -1,5 +1,7 @@
1
1
  import { clipWords } from "./plain.js";
2
2
  const oneLine = (value) => value.replace(/\s+/g, " ").trim();
3
+ export const STALE_DECISION_MS = 5 * 24 * 3600_000;
4
+ export const BOARD_CARDS = 5;
3
5
  export function namedMarker(from, meta, passed) {
4
6
  if (meta?.authority !== "named")
5
7
  return null;
@@ -61,6 +63,61 @@ export function decisionTitle(body, max = 96) {
61
63
  text = text[0].toUpperCase() + text.slice(1);
62
64
  return clipWords(text, max);
63
65
  }
66
+ export function clipClause(text, max) {
67
+ const t = oneLine(text);
68
+ if (t.length <= max)
69
+ return t;
70
+ let cut = null;
71
+ for (const m of t.slice(0, max + 1).matchAll(/[.!?](?=\s)|[,;:](?=\s)|\s[—–-]\s|\s\(/g)) {
72
+ const whole = /^[.!?]$/.test(m[0]);
73
+ const at = whole ? m.index + 1 : m.index;
74
+ const head = t.slice(0, at);
75
+ if ((head.match(/\(/g)?.length ?? 0) > (head.match(/\)/g)?.length ?? 0))
76
+ continue;
77
+ if (at >= max * 0.4 && at <= max - 1)
78
+ cut = { at, whole };
79
+ }
80
+ if (!cut) {
81
+ const w = clipWords(t, max);
82
+ const open = w.lastIndexOf("(");
83
+ return open >= 20 && open > w.lastIndexOf(")") ? `${t.slice(0, open).replace(/[\s,;:—–-]+$/, "")}…` : w;
84
+ }
85
+ const head = t.slice(0, cut.at).replace(/[\s,;:—–-]+$/, "");
86
+ return cut.whole ? head.replace(/\.$/, "") : `${head}…`;
87
+ }
88
+ export const DECISION_ASKS = ["decide", "approve", "answer", "schedule"];
89
+ export function decisionDue(v) {
90
+ if (typeof v !== "string" || v.length > 40)
91
+ return undefined;
92
+ const dateOnly = /^\d{4}-\d{2}-\d{2}$/.test(v);
93
+ const t = Date.parse(dateOnly ? `${v}T23:59:59Z` : v);
94
+ return Number.isFinite(t) && t > Date.UTC(2020, 0, 1) && t < Date.UTC(2100, 0, 1) ? t : undefined;
95
+ }
96
+ export const ANSWER_OPTIONS_SCAN = 4096;
97
+ export function decisionQuestion(body, o = {}) {
98
+ const clean = (s) => {
99
+ let t = tidyIds(stripCeremony(s).text).replace(/^\(?(?:\d|[a-h])[).]\s+/i, "").trim();
100
+ for (const n of o.names ?? [])
101
+ t = tidyLead(t, n);
102
+ return t.replace(/^./, (c) => c.toUpperCase());
103
+ };
104
+ const summary = clean(o.summary ?? "");
105
+ if (summary)
106
+ return summary;
107
+ const text = clean(body.slice(0, 2000));
108
+ const sentences = text.split(/(?<=[.!?])\s+(?=[("“'A-Z0-9])/).map((s) => clean(s)).filter(Boolean);
109
+ const asks = sentences.find((s) => /\?$/.test(s) && s.length >= 12);
110
+ if (asks)
111
+ return asks;
112
+ const first = sentences[0] ?? "";
113
+ const whole = /[.!]$/.test(first) || (sentences.length === 1 && !/(?:…|\.\.\.)$/.test(first));
114
+ if (first && whole && first.length <= 400)
115
+ return first.replace(/\.$/, "");
116
+ const goal = clean(o.goalTitle ?? "");
117
+ if (goal)
118
+ return goal;
119
+ return first || text;
120
+ }
64
121
  export function decisionPrompt(id, title) {
65
122
  const head = title?.trim() ? `Pantheon decision: ${title.trim()}
66
123
 
@@ -122,15 +179,16 @@ export function runBrief(r) {
122
179
  ];
123
180
  return lines.join("\n");
124
181
  }
125
- export function answerOptions(body) {
126
- const at = body.search(/\boptions?\b\s*[:—-]/i);
182
+ export function answerOptions(body0, scan) {
183
+ const body = (scan !== undefined && body0.length > scan ? body0.slice(0, scan) : body0).replace(/\r\n?/g, "\n");
184
+ const at = body.search(/\boptions?\b[ \t]*[:—-]/i);
127
185
  if (at < 0)
128
186
  return [];
129
187
  const tail = body.slice(at).replace(/^[^:—-]*[:—-]/, " ");
130
- const ends = [tail.search(/\n\s*\n(?!\s*(?:\(?[a-d1-4][).]))/i), tail.search(/(?:[.!?]\s+|\n\s*)(?:I(?:'d| would)? recommend|Recommend(?:ation|ed)?\b|Why\b)/i)].filter((n) => n > 0);
188
+ const ends = [tail.search(/\n[ \t]*\n(?=[ \t]*\S)(?![ \t]*\(?[a-d1-4][).])/i), tail.search(/(?:[.!?][ \t]+|\n[ \t]*)(?:I(?:'d| would)? recommend|Recommend(?:ation|ed)?\b|Why\b)/i)].filter((n) => n > 0);
131
189
  const span = ends.length ? tail.slice(0, Math.min(...ends) + 1) : tail;
132
190
  const inline = !span.trim().includes("\n");
133
- const parts = span.split(/(?:^|\s|\n)\(?([a-d]|[1-4])[).]\s+/i).slice(1);
191
+ const parts = span.split(/(?:^|\s)\(?([a-d]|[1-4])[).][ \t\n]+/i).slice(1);
134
192
  const out = [];
135
193
  for (let i = 0; i + 1 < parts.length; i += 2) {
136
194
  const key = parts[i].toLowerCase();
@@ -0,0 +1,14 @@
1
+ export const OUTCOME_MAX = 300;
2
+ export function cleanOutcome(v) {
3
+ if (typeof v !== "string")
4
+ return null;
5
+ const t = v.replace(/[\u0000-\u001f\u007f-\u009f\u2028\u2029]+/g, " ").replace(/\s+/g, " ").trim();
6
+ if (!t)
7
+ return null;
8
+ return t.length > OUTCOME_MAX ? `${t.slice(0, OUTCOME_MAX - 1)}…` : t;
9
+ }
10
+ export function doneAnswerBody(member, outcome) {
11
+ const base = `${member} marked this handled — dealt with outside Pantheon.`;
12
+ return outcome ? `${base} What happened: ${outcome}` : base;
13
+ }
14
+ //# sourceMappingURL=done-outcome.js.map