fwdloop 0.23.0 → 0.25.0

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.
Files changed (71) hide show
  1. package/bin/fwdloop +62 -32
  2. package/package.json +1 -1
  3. package/src/ask.js +15 -1
  4. package/src/attemptdiff.js +118 -0
  5. package/src/audit-fold.js +2 -0
  6. package/src/authoring.js +32 -2
  7. package/src/cited-record.js +3 -22
  8. package/src/cited-source.js +5 -6
  9. package/src/citedwords.js +36 -2
  10. package/src/config.js +5 -1
  11. package/src/diary.js +21 -17
  12. package/src/drafter.js +6 -2
  13. package/src/flowmodel.js +52 -28
  14. package/src/keysfile.js +1 -1
  15. package/src/launcher.js +552 -0
  16. package/src/learn.js +952 -0
  17. package/src/learnstore.js +348 -0
  18. package/src/line-checks.js +55 -0
  19. package/src/model-step.js +2 -0
  20. package/src/opener.js +33 -0
  21. package/src/pagedry.js +3 -4
  22. package/src/pagefetch.js +9 -2
  23. package/src/pagerules.js +28 -5
  24. package/src/panel/author.js +2 -0
  25. package/src/panel/authorflows.js +9 -9
  26. package/src/panel/authorresume.js +4 -3
  27. package/src/panel/data.js +63 -14
  28. package/src/panel/index.html +162 -16
  29. package/src/panel/result.js +7 -12
  30. package/src/panel/server.js +53 -5
  31. package/src/panel/settings.js +4 -18
  32. package/src/panel/spawn.js +0 -9
  33. package/src/prompts.js +33 -0
  34. package/src/redact.js +6 -6
  35. package/src/runfile.js +60 -0
  36. package/src/runner.js +144 -33
  37. package/src/sheet-record.js +15 -35
  38. package/src/sheetblock.js +3 -3
  39. package/src/sheetrun.js +6 -6
  40. package/src/summary-words.js +13 -5
  41. package/src/thinking.js +11 -0
  42. package/src/tty-colour.js +29 -0
  43. package/types/ask.d.ts +7 -2
  44. package/types/attemptdiff.d.ts +38 -0
  45. package/types/cited-record.d.ts +0 -2
  46. package/types/citedwords.d.ts +14 -0
  47. package/types/diary.d.ts +2 -5
  48. package/types/drafter.d.ts +6 -1
  49. package/types/flowmodel.d.ts +37 -20
  50. package/types/keysfile.d.ts +7 -0
  51. package/types/launcher.d.ts +307 -0
  52. package/types/learn.d.ts +576 -0
  53. package/types/learnstore.d.ts +168 -0
  54. package/types/line-checks.d.ts +26 -0
  55. package/types/opener.d.ts +12 -0
  56. package/types/pagerules.d.ts +7 -0
  57. package/types/panel/author.d.ts +2 -0
  58. package/types/panel/data.d.ts +2 -1
  59. package/types/panel/result.d.ts +2 -4
  60. package/types/panel/server.d.ts +24 -3
  61. package/types/panel/settings.d.ts +2 -2
  62. package/types/panel/spawn.d.ts +0 -6
  63. package/types/prompts.d.ts +14 -0
  64. package/types/runfile.d.ts +48 -0
  65. package/types/runner.d.ts +14 -5
  66. package/types/sheet-record.d.ts +0 -2
  67. package/types/sheetblock.d.ts +2 -2
  68. package/types/sheetrun.d.ts +1 -1
  69. package/types/summary-words.d.ts +2 -1
  70. package/types/thinking.d.ts +11 -0
  71. package/types/tty-colour.d.ts +33 -0
@@ -0,0 +1,552 @@
1
+ // borrowed-from: bareloop src/launcher.js@v0.47.1 (704d598)
2
+ // Adaptations: fwdloop name, app and ports (4800..4809, not 4700); config home ~/.config/fwdloop (src/config.js) and the node >= 22 check; the run counts read fwdloop's
3
+ // `listRuns` rows (`live`, `needs`: the two reads the panel page makes) through `runsListForCount`, no schedules-gave-up part (fwdloop has none); the header version is
4
+ // `readOwnVersion`; `start` spawns through src/panel/spawn.js `spawnDetached` (detached = its own session, log opened 0600 and appended) with `--root <flows folder>`;
5
+ // install creates the keys file with `createKeysFile`; the silent-port words are M4b am5 item 3's (bareloop 6d10023, unreleased); `launcherMain` is the entry bin/fwdloop calls
6
+ // (bareloop's runLauncher in cli.js). M4b am4 + am5.
7
+ //
8
+ // M4b am4/am5 (bareloop PANEL-BUILD.md addendum 2026-10-24, L) - the `fwdloop` launcher: the bare-`fwdloop` menu and `fwdloop start | stop | restart | status | install`.
9
+ //
10
+ // No pid file: the panel is FOUND by asking the panel ports 4800..4809 for `GET /api/whoami` (src/panel/server.js), several at once, 2000 ms
11
+ // each; a reply with `app === "fwdloop"` is a panel. Every call prints the same two header lines first, from {@link buildHeader}.
12
+ // The run counts are the panel's own (`runsListForCount`: the `listRuns` rows' `live` and `needs`, the two reads the page makes for Running now and Needs you) — never a second spelling of "running" or "needs you".
13
+ // This file owns no arbiter state: it starts/stops the panel process and reads the run list at $0. Every OS touch (spawn, kill, open,
14
+ // port bind, clock, stdin) comes through `deps` so tests inject all of them and never see a real panel.
15
+
16
+ import {
17
+ existsSync, statSync, mkdirSync, chmodSync,
18
+ } from 'node:fs';
19
+ import { createServer } from 'node:net';
20
+ import { openAsker } from './prompts.js';
21
+ import { dirname, join } from 'node:path';
22
+ import { fileURLToPath } from 'node:url';
23
+ import { readConfig, updateConfig, configPath, ConfigError } from './config.js';
24
+ import { keysHome, keysFilePath, createKeysFile } from './keysfile.js';
25
+ import { openInOs } from './opener.js';
26
+ import { PLAIN, makePaint } from './tty-colour.js';
27
+ import { readOwnVersion } from './version.js';
28
+ import { spawnDetached } from './panel/spawn.js';
29
+ import { runsListForCount, panelUrl } from './panel/server.js';
30
+
31
+ const HERE = dirname(fileURLToPath(import.meta.url));
32
+ /** the first port tried, and how many in a row (4800..4809) */
33
+ export const PORT_START = 4800;
34
+ export const PORT_COUNT = 10;
35
+ const PROBE_TIMEOUT_MS = 2000;
36
+ const WAIT_DEADLINE_MS = 10_000;
37
+ /** how long `start` keeps asking a TAKEN port that stays silent before it refuses to open another panel next to it */
38
+ const SILENT_PORT_WAIT_MS = 10_000;
39
+ const POLL_MS = 100;
40
+ const MIN_NODE_MAJOR = 22;
41
+ const RULE_WIDTH = 56;
42
+
43
+ /**
44
+ * @typedef {object} Panel one answered probe
45
+ * @property {number} port @property {number} pid @property {string} version @property {number} drafts @property {number} schedules @property {string} [startedAt] ISO, absent on an older panel
46
+ * @property {string} url
47
+ */
48
+
49
+ /**
50
+ * @typedef {object} LauncherDeps every OS touch, injectable (a test passes all of them)
51
+ * @property {string} [home] the fwdloop config home (`~/.config/fwdloop`, src/config.js `configHome`); undefined = the real one
52
+ * @property {string} [root] the flows folder the runs line reads and `start` hands the panel (`--root`); default '.' like `fwdloop panel`
53
+ * @property {number} [portStart] @property {number} [portCount]
54
+ * @property {number[]} [ports] an explicit port list (tests); wins over portStart/portCount
55
+ * @property {number} [timeoutMs] probe timeout per port
56
+ * @property {number} [deadlineMs] start/stop wait deadline
57
+ * @property {number} [silentWaitMs] how long start keeps asking a taken, silent port (default 10 s)
58
+ * @property {string} [nodeVersion] default process.versions.node
59
+ * @property {typeof fetch} [fetchImpl]
60
+ * @property {(a: {bin: string, argv: string[], env: Record<string, string|undefined>, logPath: string}) => any} [spawnFn] default src/panel/spawn.js `spawnDetached`
61
+ * @property {(pid: number, sig: string|number) => void} [kill] default process.kill
62
+ * @property {((target: string) => Promise<boolean>)} [open] default the shared OS opener
63
+ * @property {(port: number) => Promise<boolean>} [portFree] default: try to bind 127.0.0.1:port
64
+ * @property {(ms: number) => Promise<void>} [sleep]
65
+ * @property {(question: string) => Promise<string>} [ask] the y/N and menu reader
66
+ * @property {string} [fwdloopBin] default bin/fwdloop of this package
67
+ * @property {import('./tty-colour.js').Paint} [paint] colour for stdout lines (default none); {@link makePaint} decides TTY / NO_COLOR / TERM
68
+ * @property {import('./tty-colour.js').Paint} [paintErr] colour for stderr lines (default: `paint`)
69
+ * @property {number} [now] ms clock for the run list's 7-day rule (default: real time); tests pass their own
70
+ * @property {Record<string, string|undefined>} [env] raw env handed to the panel child (default process.env)
71
+ */
72
+
73
+ /**
74
+ * The run counts, from the panel's own `listRuns` rows - the SAME two reads the page makes (src/panel/index.html: Running now = `live === true`,
75
+ * Needs you = a non-empty `needs`, the tag `needsYouOf` decides, M11 included). A flow with no runs yet (`runId` null) is not a run. A part that is 0 still shows.
76
+ * @param {any[]} rows
77
+ * @returns {{running: number, needYou: number, total: number}}
78
+ */
79
+ export function countRuns(rows) {
80
+ let running = 0;
81
+ let needYou = 0;
82
+ let total = 0;
83
+ for (const r of rows) {
84
+ if (!r || r.runId === null || r.runId === undefined) continue;
85
+ total += 1;
86
+ if (r.live === true) running += 1;
87
+ if (typeof r.needs === 'string' && r.needs !== '') needYou += 1;
88
+ }
89
+ return { running, needYou, total };
90
+ }
91
+
92
+ /**
93
+ * "installed ✓" = the folder exists, config.json is there and reads with no problem, `.env` exists with mode 600, node >= 22.
94
+ * Otherwise the FIRST missing thing in plain words.
95
+ * @param {{home?: string, nodeVersion?: string}} o
96
+ * @returns {{ok: boolean, problem: string|null}}
97
+ */
98
+ export function installState(o) {
99
+ const dir = keysHome(o.home);
100
+ if (!existsSync(dir)) return { ok: false, problem: 'no fwdloop folder yet' };
101
+ if (!existsSync(configPath(o.home))) return { ok: false, problem: 'no settings file yet' };
102
+ try { readConfig({ home: o.home }); } catch { return { ok: false, problem: 'config.json cannot be read' }; }
103
+ const env = keysFilePath(o.home);
104
+ if (!existsSync(env)) return { ok: false, problem: 'no keys file yet' };
105
+ try {
106
+ if ((statSync(env).mode & 0o077) !== 0) return { ok: false, problem: 'the keys file is readable by other users' };
107
+ } catch { return { ok: false, problem: 'the keys file cannot be read' }; }
108
+ const major = Number((o.nodeVersion ?? process.versions.node).split('.')[0]);
109
+ if (!(major >= MIN_NODE_MAJOR)) return { ok: false, problem: `node ${MIN_NODE_MAJOR} or newer is needed` };
110
+ return { ok: true, problem: null };
111
+ }
112
+
113
+ /**
114
+ * Ask one port for `/api/whoami`. Never throws. `silent` = no reply inside the timeout (a loaded or stuck process may still be a
115
+ * panel); `other` = something replied (or refused) and it is not a fwdloop whoami.
116
+ * @param {{port: number, timeoutMs?: number, fetchImpl?: typeof fetch}} o
117
+ * @returns {Promise<{state: 'panel', panel: Panel}|{state: 'other'}|{state: 'silent'}>}
118
+ */
119
+ export async function probePort(o) {
120
+ const f = o.fetchImpl ?? fetch;
121
+ const ms = o.timeoutMs ?? PROBE_TIMEOUT_MS;
122
+ const port = o.port;
123
+ try {
124
+ const res = await f(`${panelUrl(port)}/api/whoami`, { signal: AbortSignal.timeout(ms) });
125
+ if (!res.ok) return { state: 'other' };
126
+ const j = /** @type {any} */ (await res.json());
127
+ if (!j || j.app !== 'fwdloop') return { state: 'other' };
128
+ return {
129
+ state: 'panel',
130
+ panel: {
131
+ port,
132
+ pid: Number(j.pid),
133
+ version: String(j.version ?? ''),
134
+ drafts: Number(j.drafts) || 0,
135
+ schedules: Number(j.schedules) || 0,
136
+ ...(typeof j.startedAt === 'string' && j.startedAt !== '' ? { startedAt: j.startedAt } : {}),
137
+ url: panelUrl(port),
138
+ },
139
+ };
140
+ } catch (e) {
141
+ const name = /** @type {any} */ (e)?.name;
142
+ return name === 'TimeoutError' || name === 'AbortError' ? { state: 'silent' } : { state: 'other' };
143
+ }
144
+ }
145
+
146
+ /**
147
+ * Ask 127.0.0.1 across the ports in parallel; a reply with `app === "fwdloop"` is a panel. Never throws.
148
+ * @param {{ports: number[], timeoutMs?: number, fetchImpl?: typeof fetch}} o
149
+ * @returns {Promise<Panel[]>} in port order
150
+ */
151
+ export async function probePanels(o) {
152
+ const answers = await Promise.all(o.ports.map((port) => probePort({ port, timeoutMs: o.timeoutMs, fetchImpl: o.fetchImpl })));
153
+ return /** @type {Panel[]} */ (answers.flatMap((a) => (a.state === 'panel' ? [a.panel] : [])));
154
+ }
155
+
156
+ /**
157
+ * The panel's own date style (src/panel/index.html rlShortDate): local `MM/DD HH:MM`; an unparseable stamp is shown raw, never blank.
158
+ * @param {string} iso
159
+ */
160
+ export function shortDate(iso) {
161
+ const d = new Date(iso);
162
+ if (Number.isNaN(d.getTime())) return String(iso);
163
+ const t = (/** @type {number} */ n) => String(n).padStart(2, '0');
164
+ return `${t(d.getMonth() + 1)}/${t(d.getDate())} ${t(d.getHours())}:${t(d.getMinutes())}`;
165
+ }
166
+
167
+ /** @param {LauncherDeps} d @returns {number[]} */
168
+ function portsOf(d) {
169
+ if (d.ports) return d.ports;
170
+ const start = d.portStart ?? PORT_START;
171
+ return Array.from({ length: d.portCount ?? PORT_COUNT }, (_, i) => start + i);
172
+ }
173
+
174
+ /** @param {LauncherDeps} d @returns {Promise<Panel[]>} */
175
+ function probeAll(d) {
176
+ return probePanels({ ports: portsOf(d), timeoutMs: d.timeoutMs, fetchImpl: d.fetchImpl });
177
+ }
178
+
179
+ /**
180
+ * The header, ONCE per call: the two lines every `fwdloop` command prints first, plus the panels the probe found (the commands
181
+ * reuse them, so nothing is probed twice).
182
+ * @param {LauncherDeps & {version?: string}} d
183
+ * @returns {Promise<{lines: string[], panels: Panel[]}>}
184
+ */
185
+ export async function buildHeader(d) {
186
+ const version = d.version ?? readOwnVersion() ?? 'unknown';
187
+ const panels = await probeAll(d);
188
+ const inst = installState({ home: d.home, nodeVersion: d.nodeVersion });
189
+ const P = d.paint ?? PLAIN;
190
+ const sep = P.grey(' · ');
191
+ const where = panels.length === 0
192
+ ? `panel ${P.grey('not running')}`
193
+ : `panel${panels.length > 1 ? 's' : ''} ${P.green('running')} at ${panels.map((p) => P.cyan(p.url) + (p.startedAt ? P.grey(` · started ${shortDate(p.startedAt)}`) : '') + (p.version !== version ? P.yellow(` (version ${p.version} — stop and start to use ${version})`) : '')).join(', ')}`;
194
+ const state = inst.ok ? P.green('installed ✓') : `${P.red('not installed')} — ${inst.problem}, pick ${P.boldCyan('5')} install`;
195
+ const first = `${P.boldCyan('fwdloop')} ${P.grey(version)}${sep}${state}${sep}${where}`;
196
+ let second;
197
+ try {
198
+ const c = countRuns(runsListForCount({ root: d.root ?? '.', ...(typeof d.now === 'number' ? { now: () => /** @type {number} */ (d.now) } : {}) }));
199
+ second = `${P.grey('runs:')} ${c.running > 0 ? P.green(`${c.running} running`) : P.grey(`${c.running} running`)}${sep}`
200
+ + `${c.needYou > 0 ? P.yellow(`${c.needYou} need you`) : P.grey(`${c.needYou} need you`)}${sep}${c.total} in all`;
201
+ } catch {
202
+ second = `${P.grey('runs:')} the run list could not be read`;
203
+ }
204
+ // the thin rule frames the header only on a colour terminal (plain output keeps exactly the two lines)
205
+ const rule = P.on ? [P.grey('─'.repeat(RULE_WIDTH))] : [];
206
+ return { lines: [...rule, first, second, ...rule], panels };
207
+ }
208
+
209
+ /**
210
+ * @param {LauncherDeps & {version?: string}} d
211
+ * @returns {Promise<string[]>} the two header lines
212
+ */
213
+ export async function headerLines(d) {
214
+ return (await buildHeader(d)).lines;
215
+ }
216
+
217
+ /**
218
+ * Print the header unless the caller (the menu) already did; hand back the panels either way.
219
+ * @param {{out: (s: string) => void}} io @param {LauncherDeps & {version?: string}} d @param {{lines: string[], panels: Panel[]}} [shown]
220
+ */
221
+ async function headerOnce(io, d, shown) {
222
+ if (shown) return shown;
223
+ const h = await buildHeader(d);
224
+ for (const l of h.lines) io.out(l);
225
+ return h;
226
+ }
227
+
228
+ /** stderr line, red on a colour terminal @param {{err: (s: string) => void}} io @param {LauncherDeps} d @param {string} text */
229
+ const fail = (io, d, text) => io.err((d.paintErr ?? d.paint ?? PLAIN).red(text));
230
+
231
+ /** @param {number} n @param {string} one @param {string} many */
232
+ const plural = (n, one, many) => `${n} ${n === 1 ? one : many}`;
233
+
234
+ /** @param {LauncherDeps} d */
235
+ const sleepOf = (d) => d.sleep ?? ((/** @type {number} */ ms) => new Promise((r) => { setTimeout(r, ms); }));
236
+
237
+ /** @param {number} port @returns {Promise<boolean>} true when nothing holds 127.0.0.1:port */
238
+ function bindFree(port) {
239
+ return new Promise((resolve) => {
240
+ const s = createServer();
241
+ s.once('error', () => resolve(false));
242
+ s.listen(port, '127.0.0.1', () => { s.close(() => resolve(true)); });
243
+ });
244
+ }
245
+
246
+ /**
247
+ * `fwdloop install` — creates only what is missing, never reads a key value.
248
+ * @param {{out: (s: string) => void, err: (s: string) => void}} io @param {LauncherDeps & {version?: string}} d @param {{lines: string[], panels: Panel[]}} [shown]
249
+ * @returns {Promise<number>}
250
+ */
251
+ export async function installCmd(io, d, shown) {
252
+ await headerOnce(io, d, shown);
253
+ const major = Number((d.nodeVersion ?? process.versions.node).split('.')[0]);
254
+ if (!(major >= MIN_NODE_MAJOR)) {
255
+ fail(io, d, `fwdloop needs node ${MIN_NODE_MAJOR} or newer; this is node ${d.nodeVersion ?? process.versions.node}. Nothing was changed.`);
256
+ return 1;
257
+ }
258
+ const dir = keysHome(d.home);
259
+ /** @type {string[]} */
260
+ const made = [];
261
+ if (!existsSync(dir)) { mkdirSync(dir, { recursive: true, mode: 0o700 }); made.push(`${dir} (only you can open it)`); }
262
+ const envFile = keysFilePath(d.home);
263
+ if (createKeysFile(d.home)) made.push(`${envFile} (the keys file, only you can read it)`);
264
+ else {
265
+ try {
266
+ if ((statSync(envFile).mode & 0o077) !== 0) { chmodSync(envFile, 0o600); made.push(`${envFile} set so only you can read it`); }
267
+ } catch { /* unreadable: the header says so */ }
268
+ }
269
+ if (!existsSync(configPath(d.home))) {
270
+ try { updateConfig({}, { home: d.home }); made.push(`${configPath(d.home)} (your settings)`); } catch (e) {
271
+ if (!(e instanceof ConfigError)) throw e;
272
+ fail(io, d, `${e.message}. Install did not touch it.`);
273
+ return 1;
274
+ }
275
+ } else {
276
+ try { readConfig({ home: d.home }); } catch (e) {
277
+ if (!(e instanceof ConfigError)) throw e;
278
+ fail(io, d, `${e.message}. Install did not touch it.`);
279
+ return 1;
280
+ }
281
+ }
282
+ if (made.length === 0) { io.out('Already installed, nothing to do.'); return 0; }
283
+ io.out('Installed. Created:');
284
+ for (const m of made) io.out(` ${m}`);
285
+ return 0;
286
+ }
287
+
288
+ /**
289
+ * `fwdloop status` — the header, then one line per panel (or `Panel not running.`). Exit 0 running, 3 not running; 0 when the menu ran it.
290
+ * @param {{out: (s: string) => void}} io @param {LauncherDeps & {version?: string}} d @param {{lines: string[], panels: Panel[]}} [shown] header the menu already printed
291
+ * @returns {Promise<number>}
292
+ */
293
+ export async function statusCmd(io, d, shown) {
294
+ const h = await headerOnce(io, d, shown);
295
+ if (h.panels.length === 0) {
296
+ io.out('Panel not running.');
297
+ // the sub-command's exit says "not running" (3); from the menu the menu itself worked (0)
298
+ return shown ? 0 : 3;
299
+ }
300
+ for (const p of h.panels) {
301
+ const body = `pid ${p.pid} · version ${p.version} · ${plural(p.drafts, 'draft', 'drafts')} open · ${plural(p.schedules, 'schedule', 'schedules')} on${p.startedAt ? ` · started ${shortDate(p.startedAt)}` : ''}`;
302
+ io.out(h.panels.length > 1 ? `${p.url} · ${body}` : body);
303
+ }
304
+ return 0;
305
+ }
306
+
307
+ /**
308
+ * Wait until `port` stops (gone=true) or starts (gone=false) answering whoami as fwdloop.
309
+ * @param {LauncherDeps} d @param {number} port @param {boolean} gone
310
+ * @returns {Promise<boolean>} false when the deadline passed first
311
+ */
312
+ async function waitFor(d, port, gone) {
313
+ const sleep = sleepOf(d);
314
+ const deadline = d.deadlineMs ?? WAIT_DEADLINE_MS;
315
+ // real clock time (CLOCK_MONOTONIC): a probe can take up to its whole timeout, so counting POLL_MS a turn would overshoot the deadline many times over
316
+ const t0 = performance.now();
317
+ while (performance.now() - t0 <= deadline) {
318
+ const found = await probePanels({ ports: [port], timeoutMs: d.timeoutMs, fetchImpl: d.fetchImpl });
319
+ if (gone ? found.length === 0 : found.length > 0) return true;
320
+ await sleep(POLL_MS);
321
+ }
322
+ return false;
323
+ }
324
+
325
+ /**
326
+ * A taken port that no probe recognised: ask it again until it answers or ~10 s of real time pass. A fwdloop whoami = a panel;
327
+ * any other reply = not ours (move on); still silent at the end = `silent`.
328
+ * @param {LauncherDeps} d @param {number} port
329
+ * @returns {Promise<{state: 'panel', panel: Panel}|{state: 'other'}|{state: 'silent'}>}
330
+ */
331
+ async function askTakenPort(d, port) {
332
+ const sleep = sleepOf(d);
333
+ const limit = d.silentWaitMs ?? SILENT_PORT_WAIT_MS;
334
+ const t0 = performance.now();
335
+ for (;;) {
336
+ const r = await probePort({ port, timeoutMs: d.timeoutMs, fetchImpl: d.fetchImpl });
337
+ if (r.state !== 'silent') return r;
338
+ if (performance.now() - t0 >= limit) return r;
339
+ await sleep(POLL_MS);
340
+ }
341
+ }
342
+
343
+ /**
344
+ * `fwdloop start` — find a running panel first; else start one detached on the first free port 4800..4809, wait until it answers,
345
+ * open the page.
346
+ * @param {{out: (s: string) => void, err: (s: string) => void}} io @param {LauncherDeps & {version?: string}} d @param {{lines: string[], panels: Panel[]}} [shown]
347
+ * @returns {Promise<number>}
348
+ */
349
+ export async function startCmd(io, d, shown) {
350
+ const h = await headerOnce(io, d, shown);
351
+ const P = d.paint ?? PLAIN;
352
+ const open = d.open ?? ((/** @type {string} */ t) => openInOs(t));
353
+ /** @param {string} url @param {string} said */
354
+ const finish = async (url, said) => {
355
+ const opened = await open(url);
356
+ io.out(opened ? `${said} — opening the page.` : `${said} — open it in your browser.`);
357
+ return 0;
358
+ };
359
+ /** @param {Panel} found */
360
+ const alreadyRunning = async (found) => {
361
+ const rc = await finish(found.url, `Panel already running at ${P.cyan(found.url)}`);
362
+ const mine = d.version ?? readOwnVersion() ?? 'unknown';
363
+ if (found.version !== mine) io.out(P.yellow(`It is version ${found.version}; this fwdloop is ${mine}. Run fwdloop stop, then fwdloop start, to use ${mine}.`));
364
+ return rc;
365
+ };
366
+ if (h.panels.length > 0) return alreadyRunning(h.panels[0]);
367
+ const free = d.portFree ?? bindFree;
368
+ const ports = portsOf(d);
369
+ /** @type {number|null} */
370
+ let chosen = null;
371
+ for (const p of ports) {
372
+ if (await free(p)) { chosen = p; break; }
373
+ // taken: if it is a loaded panel that missed the probe, a second panel next to it would double every scheduled run
374
+ const verdict = await askTakenPort(d, p);
375
+ if (verdict.state === 'panel') return alreadyRunning(verdict.panel);
376
+ if (verdict.state === 'silent') {
377
+ fail(io, d, `Port ${p} is taken and not answering. To see what holds it: lsof -i :${p}. If it is a stuck fwdloop, end it: kill <pid>`);
378
+ return 1;
379
+ }
380
+ }
381
+ if (chosen === null) {
382
+ fail(io, d, `Every port from ${ports[0]} to ${ports[ports.length - 1]} is taken by something else, so the panel was not started.`);
383
+ return 1;
384
+ }
385
+ if (chosen !== ports[0]) io.out(`${ports[0]} is taken, using ${chosen}.`);
386
+ const dir = keysHome(d.home);
387
+ try { mkdirSync(dir, { recursive: true, mode: 0o700 }); } catch { /* the log open below reports it */ }
388
+ const logFile = join(dir, 'panel.log');
389
+ const bin = d.fwdloopBin ?? join(HERE, '..', 'bin', 'fwdloop');
390
+ const argv = ['panel', '--port', String(chosen), '--root', d.root ?? '.'];
391
+ const spawnFn = d.spawnFn ?? spawnDetached;
392
+ try {
393
+ const child = spawnFn({ bin, argv, env: d.env ?? process.env, logPath: logFile });
394
+ if (child && typeof child.once === 'function') child.once('error', () => { /* seen as "never answered" below */ });
395
+ if (child && typeof child.unref === 'function') child.unref();
396
+ } catch (e) {
397
+ fail(io, d, `Could not start the panel: ${/** @type {Error} */ (e).message}`);
398
+ return 1;
399
+ }
400
+ if (!(await waitFor(d, chosen, false))) {
401
+ fail(io, d, `The panel did not answer within ${(d.deadlineMs ?? WAIT_DEADLINE_MS) / 1000} seconds. See ${logFile}.`);
402
+ return 1;
403
+ }
404
+ return finish(panelUrl(chosen), `${P.green('Panel started')} at ${P.cyan(panelUrl(chosen))}`);
405
+ }
406
+
407
+ /**
408
+ * `fwdloop stop [--yes]` — SIGTERM the pid of EVERY panel the probe finds (one panel at a time is the rule; no "which one"), wait until each
409
+ * port stops answering. Drafts are in memory: warn (summed over all found panels) and ask y/N unless `--yes`.
410
+ * @param {string[]} args
411
+ * @param {{out: (s: string) => void, err: (s: string) => void}} io @param {LauncherDeps & {version?: string}} d @param {{lines: string[], panels: Panel[]}} [shown]
412
+ * @returns {Promise<number>}
413
+ */
414
+ export async function stopCmd(args, io, d, shown) {
415
+ return (await stopPanels('stop', args, io, d, shown)).rc;
416
+ }
417
+
418
+ /**
419
+ * The one stop: `stopCmd` and `restartCmd` both run it. `stopped` is true only when panels were signalled and are gone (declined, not-running and failed are all
420
+ * false), so `restart` can tell "Not stopped." (exit 0) from a stop that happened.
421
+ * @param {string} verb the word the unknown-option line names (stop | restart)
422
+ * @param {string[]} args @param {{out: (s: string) => void, err: (s: string) => void}} io @param {LauncherDeps & {version?: string}} d @param {{lines: string[], panels: Panel[]}} [shown]
423
+ * @returns {Promise<{rc: number, stopped: boolean, panels: Panel[], shown: {lines: string[], panels: Panel[]}}>}
424
+ */
425
+ async function stopPanels(verb, args, io, d, shown) {
426
+ /** @param {number} rc */
427
+ const done = (rc, stopped = false, panels = /** @type {Panel[]} */ ([]), h = shown ?? { lines: [], panels: [] }) => ({ rc, stopped, panels, shown: h });
428
+ const bad = args.find((a) => a !== '--yes');
429
+ if (bad !== undefined) {
430
+ fail(io, d, `Unknown option ${JSON.stringify(bad)} — fwdloop ${verb} takes only --yes. It stops every panel it finds.`);
431
+ return done(1);
432
+ }
433
+ const h = await headerOnce(io, d, shown);
434
+ const yes = args.includes('--yes');
435
+ const panels = h.panels;
436
+ if (panels.length === 0) { io.out('Panel not running.'); return done(0, false, [], h); }
437
+ const ask = d.ask;
438
+ const drafts = panels.reduce((n, p) => n + p.drafts, 0);
439
+ if (drafts > 0 && !yes) {
440
+ io.out(`${drafts === 1 ? '1 draft is' : `${drafts} drafts are`} open in the panel and will be lost.`);
441
+ io.out('Runs keep going. Scheduled runs wait until the panel is started again.');
442
+ const a = ask ? (await ask('Stop the panel? [y/N] ')).trim().toLowerCase() : '';
443
+ if (a !== 'y' && a !== 'yes') { io.out('Not stopped.'); return done(0, false, [], h); }
444
+ }
445
+ const kill = d.kill ?? ((/** @type {number} */ pid, /** @type {string} */ sig) => process.kill(pid, /** @type {NodeJS.Signals} */ (sig)));
446
+ for (const p of panels) {
447
+ if (!Number.isInteger(p.pid) || p.pid <= 1) { fail(io, d, `The panel at ${p.url} reported no usable pid, so it was not stopped.`); return done(1, false, [], h); }
448
+ try { kill(p.pid, 'SIGTERM'); } catch (e) {
449
+ fail(io, d, `Could not stop the panel at ${p.url} (pid ${p.pid}): ${/** @type {Error} */ (e).message}`);
450
+ return done(1, false, [], h);
451
+ }
452
+ }
453
+ // the pid being gone is the truth (signal 0: ESRCH = gone, EPERM = alive); the port going quiet is checked after, for those that went
454
+ const t0 = performance.now();
455
+ const limit = d.deadlineMs ?? WAIT_DEADLINE_MS;
456
+ const sleep = sleepOf(d);
457
+ let pending = panels.slice();
458
+ while (pending.length > 0) {
459
+ pending = pending.filter((p) => {
460
+ try { kill(p.pid, 0); return true; } catch (e) { return /** @type {any} */ (e)?.code !== 'ESRCH'; }
461
+ });
462
+ if (pending.length === 0 || performance.now() - t0 > limit) break;
463
+ await sleep(POLL_MS);
464
+ }
465
+ if (pending.length > 0) {
466
+ for (const p of panels) {
467
+ if (!pending.includes(p)) io.out(`The panel at ${p.url} (pid ${p.pid}) stopped.`);
468
+ }
469
+ for (const p of pending) fail(io, d, `The panel at ${p.url} (pid ${p.pid}) did not stop.`);
470
+ return done(1, false, [], h);
471
+ }
472
+ for (const p of panels) {
473
+ if (!(await waitFor(d, p.port, true))) {
474
+ fail(io, d, `The panel at ${p.url} still answers after ${(d.deadlineMs ?? WAIT_DEADLINE_MS) / 1000} seconds (pid ${p.pid}).`);
475
+ return done(1, false, [], h);
476
+ }
477
+ }
478
+ io.out((d.paint ?? PLAIN).green(panels.length > 1 ? `${panels.length} panels stopped.` : 'Panel stopped.'));
479
+ return done(0, true, panels, h);
480
+ }
481
+
482
+ /**
483
+ * `fwdloop restart [--yes]` (M4b am6 item 2) — the existing stop (same open-drafts warning and question; `--yes` skips it), then the existing start, on the port
484
+ * the panel had when it is free. No panel running: it just starts. A declined or failed stop starts nothing.
485
+ * @param {string[]} args
486
+ * @param {{out: (s: string) => void, err: (s: string) => void}} io @param {LauncherDeps & {version?: string}} d @param {{lines: string[], panels: Panel[]}} [shown]
487
+ * @returns {Promise<number>}
488
+ */
489
+ export async function restartCmd(args, io, d, shown) {
490
+ const r = await stopPanels('restart', args, io, d, shown);
491
+ if (r.rc !== 0) return r.rc;
492
+ // the header is already on screen and nothing is running now: start must not see the old panels
493
+ const afterStop = { lines: r.shown.lines, panels: /** @type {Panel[]} */ ([]) };
494
+ if (!r.stopped) return r.shown.panels.length > 0 ? 0 : startCmd(io, d, afterStop); // panels found but not stopped = declined ("Not stopped.")
495
+ const same = r.panels[0].port;
496
+ return startCmd(io, { ...d, ports: [same, ...portsOf(d).filter((p) => p !== same)] }, afterStop);
497
+ }
498
+
499
+ /**
500
+ * The bare `fwdloop` menu: header, the five choices, one question. Runs the chosen command and returns its exit code.
501
+ * @param {{out: (s: string) => void, err: (s: string) => void}} io @param {LauncherDeps & {version?: string}} d
502
+ * @returns {Promise<number>}
503
+ */
504
+ export async function menuCmd(io, d) {
505
+ const ask = d.ask;
506
+ const h = await buildHeader(d);
507
+ for (const l of h.lines) io.out(l);
508
+ const P = d.paint ?? PLAIN;
509
+ if (!P.on) io.out('');
510
+ const n = (/** @type {string} */ k) => P.boldCyan(k);
511
+ const items = `${n('1')} start ${n('2')} stop ${n('3')} restart ${n('4')} status ${n('5')} install ${n('q')} quit`;
512
+ io.out(P.on ? ` ${items}` : items);
513
+ const choice = ask ? (await ask(`${P.cyan('>')} `)).trim().toLowerCase() : 'q';
514
+ // the header is already on screen: the chosen command reuses it instead of printing it a second time
515
+ if (choice === '1' || choice === 'start') return startCmd(io, d, h);
516
+ if (choice === '2' || choice === 'stop') return stopCmd([], io, d, h);
517
+ if (choice === '3' || choice === 'restart') return restartCmd([], io, d, h);
518
+ if (choice === '4' || choice === 'status') return statusCmd(io, d, h);
519
+ if (choice === '5' || choice === 'install') return installCmd(io, d, h);
520
+ if (choice === '' || choice === 'q' || choice === 'quit') return 0;
521
+ fail(io, d, `unknown choice ${JSON.stringify(choice)} — one of: 1, 2, 3, 4, 5, q`);
522
+ return 1;
523
+ }
524
+
525
+ /**
526
+ * The launcher doors: the bare `fwdloop` menu and `start | stop | restart | status | install` (bin/fwdloop calls this; bareloop's runLauncher in src/cli.js). All logic is above;
527
+ * this only supplies the line reader and the colour. `deps.launcher` is the test seam for every OS touch (ports, spawn, kill, opener, clock).
528
+ * @param {'menu'|'start'|'stop'|'restart'|'status'|'install'} cmd @param {string[]} rest
529
+ * @param {{ stdin?: any, stdout?: any, stderr?: any, home?: string, root?: string, processEnv?: Record<string, string|undefined>, launcher?: LauncherDeps & {version?: string} }} deps
530
+ * @returns {Promise<number>}
531
+ */
532
+ export async function launcherMain(cmd, rest, deps) {
533
+ const stdout = deps.stdout ?? process.stdout;
534
+ const stderr = deps.stderr ?? process.stderr;
535
+ const io = { out: (/** @type {string} */ s) => stdout.write(`${s}\n`), err: (/** @type {string} */ s) => stderr.write(`${s}\n`) };
536
+ // borrowed-from: bareloop src/prompts.js@1bad2c8 — a line queue, so input that ends during the header's port probe is not dropped
537
+ const { ask, close } = openAsker({ stdin: deps.stdin, stdout });
538
+ const rawEnv = deps.processEnv ?? process.env;
539
+ const d = {
540
+ home: deps.home, root: deps.root, ask, paint: makePaint(stdout, rawEnv), paintErr: makePaint(stderr, rawEnv), ...(deps.launcher ?? {}),
541
+ };
542
+ try {
543
+ if (cmd === 'start') return await startCmd(io, d);
544
+ if (cmd === 'stop') return await stopCmd(rest, io, d);
545
+ if (cmd === 'restart') return await restartCmd(rest, io, d);
546
+ if (cmd === 'status') return await statusCmd(io, d);
547
+ if (cmd === 'install') return await installCmd(io, d);
548
+ return await menuCmd(io, d);
549
+ } finally {
550
+ close();
551
+ }
552
+ }