@oneie/cli 5.1.0 → 5.2.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.
@@ -0,0 +1,270 @@
1
+ /**
2
+ * key.ts — `one key new | recover | public | verify`, the text/key.md door on a terminal.
3
+ *
4
+ * A VERB OVER WALLET KEYGEN, NOT A SECOND DERIVATION. Every address comes from
5
+ * `@oneie/sdk/wallet` — the same core `one wallet keygen`, packages/recover and
6
+ * the browser (by parity test) derive with. The public identity is the SDK's
7
+ * `@oneie/sdk/key-identity`, byte-identical to one.ie/web's `deriveUserIdPub`.
8
+ *
9
+ * THE KEY NEVER LEAVES THIS MACHINE.
10
+ * • new · recover · public make no network call at all.
11
+ * • verify makes one kind of call — `fetchReferences(base, apiKey)` — and it is
12
+ * structurally unable to send the key: its only inputs are a URL and the API
13
+ * key. It reads the public identities the server holds and the comparison
14
+ * happens HERE, so not even the public identity is transmitted.
15
+ * • The words never come from argv (shell history, `ps`): env or stdin, or a
16
+ * hidden prompt on a terminal. An argv token is never echoed — it may BE the
17
+ * phrase.
18
+ * • Under --json the words never reach stdout (an agent's stdout is a model
19
+ * context and a session log). They reach disk only behind keygen's own
20
+ * --yes-i-accept-plaintext-file, at 0600.
21
+ */
22
+ import { Command } from 'commander';
23
+ import { existsSync, readFileSync } from 'node:fs';
24
+ import { generateWallet, recoverWallet } from '@oneie/sdk/wallet';
25
+ import { userIdPubFromPhrase } from '@oneie/sdk/key-identity';
26
+ import { jsonMode, resolveBase, resolveKey } from './lib/client.js';
27
+ import { promptSecret, writeKeysFile } from './wallet.js';
28
+ const REFUSE_ARGV_SECRET = 'A secret on the command line is refused on purpose: it is written to your shell history and is ' +
29
+ 'visible in `ps` to every user on this machine. Set ONE_WALLET_MNEMONIC or pipe the words on stdin.';
30
+ const REFUSE_ARGV = 'Unrecognised argument. It is not repeated here on purpose — it may BE your recovery phrase. ' +
31
+ 'Words go on stdin or in ONE_WALLET_MNEMONIC, never on the command line. Run --help.';
32
+ const INVALID_PHRASE = 'That is not a valid 24-word BIP-39 recovery phrase. Nothing was derived.';
33
+ // text/key.md, verbatim in substance: the difference is silent and it costs money.
34
+ const NOT_SUI = 'These 24 words are not a Sui wallet mnemonic under v1: ONE derives every chain by HKDF from their ' +
35
+ '32 bytes of entropy, while a standard wallet derives by BIP-44/SLIP-0010 from the same phrase. ' +
36
+ 'Both succeed; the standard one shows different, empty addresses. Recover them here, at /key, or with @oneie/recover.';
37
+ const PAPER = 'Write these on paper. The paper is the only backup — ONE never holds this key and cannot recover it.';
38
+ function labelFor(d) {
39
+ return d === 'v2'
40
+ ? 'v2 — standard paths (BIP-44 / SLIP-0010). Any BIP-39 wallet recovers these.'
41
+ : 'v1 — original ONE derivation (HKDF labels). Only one.ie and @oneie/recover derive these.';
42
+ }
43
+ /** Field by field from the four chains — a private key has no route into the value. */
44
+ function addressesOf(w) {
45
+ const pick = (c) => w.keys.find((k) => k.chain === c)?.address ?? '';
46
+ return { sui: pick('sui'), evm: pick('evm'), sol: pick('sol'), btc: pick('btc') };
47
+ }
48
+ function fail(cmd, error) {
49
+ if (jsonMode(cmd))
50
+ process.stdout.write(JSON.stringify({ ok: false, error }) + '\n');
51
+ else
52
+ process.stderr.write(`error ${error}\n`);
53
+ process.exitCode = 1;
54
+ }
55
+ function done(cmd, data) {
56
+ if (jsonMode(cmd)) {
57
+ process.stdout.write(JSON.stringify(data) + '\n');
58
+ return;
59
+ }
60
+ const lines = Object.entries(data)
61
+ .filter(([k]) => k !== 'ok')
62
+ .map(([k, v]) => ` ${k}: ${typeof v === 'string' ? v : JSON.stringify(v)}`);
63
+ process.stdout.write(`ok\n${lines.join('\n')}\n`);
64
+ }
65
+ function readDerivationOpt(v) {
66
+ if (v === undefined || v === 'v1')
67
+ return 'v1';
68
+ if (v === 'v2')
69
+ return 'v2';
70
+ return null;
71
+ }
72
+ /** Refuse a secret-bearing flag or any stray argv token, never echoing it. */
73
+ function refuseArgv(cmd, opts, rest) {
74
+ if (opts.phrase !== undefined || opts.mnemonic !== undefined) {
75
+ fail(cmd, REFUSE_ARGV_SECRET);
76
+ return true;
77
+ }
78
+ if (rest.length > 0) {
79
+ fail(cmd, REFUSE_ARGV);
80
+ return true;
81
+ }
82
+ return false;
83
+ }
84
+ /** The words: ONE_WALLET_MNEMONIC, else stdin when piped, else a hidden prompt. '' = none given. */
85
+ async function readWords() {
86
+ const fromEnv = process.env.ONE_WALLET_MNEMONIC?.trim();
87
+ if (fromEnv)
88
+ return fromEnv;
89
+ if (!process.stdin.isTTY) {
90
+ try {
91
+ return readFileSync(0, 'utf8').trim();
92
+ }
93
+ catch {
94
+ return '';
95
+ }
96
+ }
97
+ return (await promptSecret('Your 24 words (hidden): ')).trim();
98
+ }
99
+ /** Adds the two refused secret flags and the argv catch-all every word-reading verb shares. */
100
+ function wordsCommand(name, description) {
101
+ return new Command(name)
102
+ .description(description)
103
+ .argument('[refused...]')
104
+ .allowUnknownOption()
105
+ .option('--phrase [words]', 'REFUSED — never put the words on the command line')
106
+ .option('--mnemonic [words]', 'REFUSED — never put the words on the command line');
107
+ }
108
+ /**
109
+ * The public identities the server holds for the caller: `vault_blob.user_id_pub`
110
+ * and every `vault_passkey_hints.user_id_pub` (the same two sources /keys reads).
111
+ * Its only inputs are a URL and the API key — nothing derived from the key can
112
+ * reach the request, by signature.
113
+ */
114
+ async function fetchReferences(base, apiKey) {
115
+ const out = [];
116
+ for (const path of ['/api/vault/sync', '/api/vault/devices']) {
117
+ try {
118
+ const res = await fetch(base + path, { headers: { Authorization: `Bearer ${apiKey}` } });
119
+ if (path === '/api/vault/sync' && res.status === 404) {
120
+ out.push({ answered: true, ids: [] });
121
+ continue;
122
+ }
123
+ if (!res.ok) {
124
+ out.push({ answered: false, ids: [] });
125
+ continue;
126
+ }
127
+ const body = (await res.json());
128
+ const raw = path === '/api/vault/sync' ? [body.userIdPub] : (body.devices ?? []).map((d) => d?.userIdPub);
129
+ out.push({ answered: true, ids: raw.filter((r) => typeof r === 'string' && r.length > 0) });
130
+ }
131
+ catch {
132
+ out.push({ answered: false, ids: [] });
133
+ }
134
+ }
135
+ return out;
136
+ }
137
+ function verdictOf(local, refs) {
138
+ if (!local)
139
+ return 'locked';
140
+ if (refs.length === 0)
141
+ return 'unregistered';
142
+ return refs.includes(local) ? 'verified' : 'mismatch';
143
+ }
144
+ // ── the command ──────────────────────────────────────────────────────────────
145
+ export function keyCmd() {
146
+ const cmd = new Command('key').description('One key — new · recover · public · verify. Offline except verify, which sends only your API key');
147
+ cmd.command('new')
148
+ .description('Mint a key on this machine: 24 words, printed ONCE, for paper. No network')
149
+ .option('--derivation <v>', 'v1 (default — what one.ie mints) or v2 (standard BIP-44 paths)', 'v1')
150
+ .option('--out <file>', 'Write the words + keys to a file at mode 0600 instead of printing them')
151
+ .option('--yes-i-accept-plaintext-file', 'Required with --out — acknowledge that unencrypted key material will be written to disk')
152
+ .action(async (opts, sub) => {
153
+ const derivation = readDerivationOpt(opts.derivation);
154
+ if (!derivation)
155
+ return fail(sub, '--derivation must be v1 or v2');
156
+ // Refuse BEFORE minting: words that exist only in a process about to exit are lost money.
157
+ if (opts.out && !opts.yesIAcceptPlaintextFile) {
158
+ return fail(sub, 'refusing to write plaintext key material to disk — pass --yes-i-accept-plaintext-file to override');
159
+ }
160
+ if (opts.out && existsSync(opts.out))
161
+ return fail(sub, 'that file already exists — move it aside first; a key file is never overwritten');
162
+ if (!opts.out && jsonMode(sub)) {
163
+ return fail(sub, 'refusing to print the words under --json — stdout may be a log or a model context. Use --out <file> --yes-i-accept-plaintext-file');
164
+ }
165
+ const wallet = await generateWallet(derivation);
166
+ const addresses = addressesOf(wallet);
167
+ const userIdPub = await userIdPubFromPhrase(wallet.mnemonic);
168
+ if (opts.out) {
169
+ const contents = JSON.stringify({ mnemonic: wallet.mnemonic, derivation, userIdPub, addresses, keys: wallet.keys }, null, 2) + '\n';
170
+ writeKeysFile(opts.out, contents, true);
171
+ return done(sub, { ok: true, out: opts.out, derivation, label: labelFor(derivation), addresses, userIdPub });
172
+ }
173
+ // Straight to stdout, never through a JSON receipt (refused above).
174
+ const words = wallet.mnemonic.split(' ');
175
+ const sheet = words.map((w, i) => `${String(i + 1).padStart(4)}. ${w}`).join('\n');
176
+ process.stdout.write(`\n${PAPER}\n\n${sheet}\n\n${NOT_SUI}\n\n` +
177
+ `derivation ${labelFor(derivation)}\n` +
178
+ Object.entries(addresses).map(([c, a]) => `${c.padEnd(11)} ${a}`).join('\n') +
179
+ `\nidentity ${userIdPub}\n\nThis is the only time the words are shown. Close the terminal when they are on paper.\n`);
180
+ });
181
+ cmd.addCommand(wordsCommand('recover', 'Rebuild a key from its 24 words (stdin or ONE_WALLET_MNEMONIC) — both address sets, no network')
182
+ .option('--derivation <v>', 'which set --out writes: v1 (default) or v2', 'v1')
183
+ .option('--out <file>', 'Write the words + keys to a file at mode 0600')
184
+ .option('--yes-i-accept-plaintext-file', 'Required with --out')
185
+ .action(async (rest, opts, sub) => {
186
+ if (refuseArgv(sub, opts, rest))
187
+ return;
188
+ const derivation = readDerivationOpt(opts.derivation);
189
+ if (!derivation)
190
+ return fail(sub, '--derivation must be v1 or v2');
191
+ if (opts.out && !opts.yesIAcceptPlaintextFile) {
192
+ return fail(sub, 'refusing to write plaintext key material to disk — pass --yes-i-accept-plaintext-file to override');
193
+ }
194
+ const words = await readWords();
195
+ let v1, v2, userIdPub;
196
+ try {
197
+ v1 = await recoverWallet(words, 'v1');
198
+ v2 = await recoverWallet(words, 'v2');
199
+ userIdPub = await userIdPubFromPhrase(words);
200
+ }
201
+ catch {
202
+ return fail(sub, INVALID_PHRASE);
203
+ }
204
+ if (opts.out) {
205
+ if (existsSync(opts.out))
206
+ return fail(sub, 'that file already exists — move it aside first; a key file is never overwritten');
207
+ const w = derivation === 'v2' ? v2 : v1;
208
+ writeKeysFile(opts.out, JSON.stringify({ mnemonic: w.mnemonic, derivation, userIdPub, addresses: addressesOf(w), keys: w.keys }, null, 2) + '\n', true);
209
+ }
210
+ done(sub, {
211
+ ok: true,
212
+ userIdPub,
213
+ v1: { label: labelFor('v1'), addresses: addressesOf(v1) },
214
+ v2: { label: labelFor('v2'), addresses: addressesOf(v2) },
215
+ ...(opts.out ? { out: opts.out, wrote: derivation } : {}),
216
+ });
217
+ }));
218
+ cmd.addCommand(wordsCommand('public', 'The public identity + the four chain addresses for your words — nothing secret, no network')
219
+ .option('--derivation <v>', 'v1 (default) or v2', 'v1')
220
+ .action(async (rest, opts, sub) => {
221
+ if (refuseArgv(sub, opts, rest))
222
+ return;
223
+ const derivation = readDerivationOpt(opts.derivation);
224
+ if (!derivation)
225
+ return fail(sub, '--derivation must be v1 or v2');
226
+ const words = await readWords();
227
+ let wallet, userIdPub;
228
+ try {
229
+ wallet = await recoverWallet(words, derivation);
230
+ userIdPub = await userIdPubFromPhrase(words);
231
+ }
232
+ catch {
233
+ return fail(sub, INVALID_PHRASE);
234
+ }
235
+ done(sub, { ok: true, derivation, label: labelFor(derivation), addresses: addressesOf(wallet), userIdPub });
236
+ }));
237
+ cmd.addCommand(wordsCommand('verify', "Compare this key's public identity with what the server holds — locked | verified | mismatch | unregistered")
238
+ .option('--api <url>', 'API base URL (default https://one.ie)')
239
+ .action(async (rest, opts, sub) => {
240
+ if (refuseArgv(sub, opts, rest))
241
+ return;
242
+ const words = await readWords();
243
+ if (!words) {
244
+ done(sub, { ok: true, verdict: 'locked', note: 'no words given — nothing to compare, and no request was made' });
245
+ process.exitCode = 1;
246
+ return;
247
+ }
248
+ let local;
249
+ try {
250
+ local = await userIdPubFromPhrase(words);
251
+ }
252
+ catch {
253
+ return fail(sub, INVALID_PHRASE);
254
+ }
255
+ const apiKey = resolveKey();
256
+ if (!apiKey)
257
+ return fail(sub, 'no API key — set ONE_API_KEY or run: one login');
258
+ const refs = await fetchReferences(resolveBase({ api: opts.api }, 'https://one.ie'), apiKey);
259
+ const verdict = verdictOf(local, refs.flatMap((r) => r.ids));
260
+ // `unregistered` is a claim about ABSENCE: believable only when every source
261
+ // answered. A refused or failed probe is inconclusive, never "not registered".
262
+ if (verdict === 'unregistered' && refs.some((r) => !r.answered)) {
263
+ return fail(sub, 'inconclusive — the server did not answer (auth refused or unreachable), so absence cannot be claimed. A key that is not a person\'s own login also reads as nothing here');
264
+ }
265
+ done(sub, { ok: true, verdict, userIdPub: local });
266
+ if (verdict === 'mismatch')
267
+ process.exitCode = 1;
268
+ }));
269
+ return cmd;
270
+ }
@@ -0,0 +1,56 @@
1
+ import { type PlanResult, type Row } from './tasks-graph.js';
2
+ export declare const BOX_W = 26;
3
+ export type Style = 'selected' | 'critical' | 'ready' | 'changed' | 'dim';
4
+ export interface Drawn {
5
+ lines: string[];
6
+ /** style per cell, keyed "x,y" — only for cells that carry one */
7
+ styles: Map<string, Style>;
8
+ boxes: Map<string, {
9
+ x: number;
10
+ y: number;
11
+ col: number;
12
+ idx: number;
13
+ }>;
14
+ /** columns[c] = tids in draw order, for arrow-key navigation */
15
+ columns: string[][];
16
+ }
17
+ /** Status after local receipts: a write we just made is the truth about that
18
+ * row, even while the board snapshot (a ≤60s memo) still shows the old state. */
19
+ export declare function withOverrides(rows: Row[], overrides: ReadonlyMap<string, string>): Row[];
20
+ /** Open blockers of a row.
21
+ * - in view: by name, from its CURRENT status (a local receipt counts);
22
+ * - outside the view but in `world` (the board read, as the snapshot saw it): by status;
23
+ * - not returned by the read at all (the read carries ACTIVE rows, so a DONE
24
+ * blocker is simply absent): the snapshot's own `openBlockers` count decides —
25
+ * whatever it counted open beyond the blockers we can see is still open. */
26
+ export declare function openBlockers(r: Row, byTid: ReadonlyMap<string, Row>, world?: ReadonlyMap<string, Row>): {
27
+ names: string[];
28
+ outside: number;
29
+ };
30
+ export declare function isReady(r: Row, byTid: ReadonlyMap<string, Row>, world?: ReadonlyMap<string, Row>): boolean;
31
+ /** A short handle: a `cli-*`-style slug tag when the row carries one, else its name. */
32
+ export declare function shortName(r: Row): string;
33
+ export interface DrawOpts {
34
+ title?: string;
35
+ selected?: string;
36
+ changed?: ReadonlySet<string>;
37
+ /** every row the board read returned — resolves blockers outside the view */
38
+ world?: ReadonlyMap<string, Row>;
39
+ }
40
+ export declare function drawPlan(rows: Row[], opts?: DrawOpts): Drawn & {
41
+ plan: PlanResult;
42
+ };
43
+ /** The one-paragraph header both the print and the live view carry. */
44
+ export declare function planHeader(rows: Row[], plan: PlanResult, opts: {
45
+ title?: string;
46
+ asOf?: string;
47
+ world?: ReadonlyMap<string, Row>;
48
+ }): string[];
49
+ /** What changed between two views of the same plan — the answer to "what happened?" */
50
+ export declare function planDelta(before: Row[], after: Row[], world?: ReadonlyMap<string, Row>): {
51
+ nowReady: string[];
52
+ critBefore: string[];
53
+ critAfter: string[];
54
+ };
55
+ /** lazydraw's file shape, so `one draw <name>` can open and edit the picture. */
56
+ export declare function toLazydraw(lines: string[], name: string): string;
@@ -0,0 +1,219 @@
1
+ import { CLOSED, planWaves } from './tasks-graph.js';
2
+ // A plan, drawn. Pure — rows in, lines out — so the live view, `--draw` for a
3
+ // pipe or an agent, and the tests all render the same picture.
4
+ //
5
+ // The shape was chosen by looking, not by theory (2026-09-25): drawing every
6
+ // dependency as a routed arrow turned 25 edges into a wiring loom nobody could
7
+ // read. So only the CRITICAL PATH is drawn as arrows, on one row across the top,
8
+ // and every other dependency is written as words inside the box ("waits: view").
9
+ // The critical path is the one chain that decides when the plan can finish.
10
+ export const BOX_W = 26;
11
+ const BOX_H = 5;
12
+ const GAP = 6;
13
+ const TOP = 0;
14
+ /** Status after local receipts: a write we just made is the truth about that
15
+ * row, even while the board snapshot (a ≤60s memo) still shows the old state. */
16
+ export function withOverrides(rows, overrides) {
17
+ if (!overrides.size)
18
+ return rows;
19
+ return rows.map((r) => (overrides.has(r.tid) ? { ...r, status: overrides.get(r.tid) } : r));
20
+ }
21
+ /** Open blockers of a row.
22
+ * - in view: by name, from its CURRENT status (a local receipt counts);
23
+ * - outside the view but in `world` (the board read, as the snapshot saw it): by status;
24
+ * - not returned by the read at all (the read carries ACTIVE rows, so a DONE
25
+ * blocker is simply absent): the snapshot's own `openBlockers` count decides —
26
+ * whatever it counted open beyond the blockers we can see is still open. */
27
+ export function openBlockers(r, byTid, world) {
28
+ const ids = r.blockedBy ?? [];
29
+ const names = [];
30
+ let outside = 0;
31
+ let openAtSnapshotSeen = 0;
32
+ for (const b of ids) {
33
+ const snap = world?.get(b);
34
+ if (snap && !CLOSED.has(snap.status))
35
+ openAtSnapshotSeen++;
36
+ const inView = byTid.get(b);
37
+ if (inView) {
38
+ if (!CLOSED.has(inView.status))
39
+ names.push(shortName(inView));
40
+ }
41
+ else if (snap) {
42
+ if (!CLOSED.has(snap.status))
43
+ outside++;
44
+ }
45
+ }
46
+ const snapshotOpen = r.openBlockers ?? 0;
47
+ outside += Math.max(0, snapshotOpen - openAtSnapshotSeen);
48
+ return { names, outside };
49
+ }
50
+ export function isReady(r, byTid, world) {
51
+ if (r.status !== 'open')
52
+ return false;
53
+ const ob = openBlockers(r, byTid, world);
54
+ return ob.names.length === 0 && ob.outside === 0;
55
+ }
56
+ /** A short handle: a `cli-*`-style slug tag when the row carries one, else its name. */
57
+ export function shortName(r) {
58
+ const slug = (r.tags ?? []).find((t) => /^[a-z]+-[a-z][a-z0-9-]*$/.test(t) && !/-\d+$/.test(t));
59
+ const base = slug && r.name.length > BOX_W - 4 ? slug : r.name;
60
+ return base.replace(/\s+—.*$/, '').trim();
61
+ }
62
+ function wrap(s, w, lines) {
63
+ const words = s.split(/\s+/);
64
+ const out = [];
65
+ let cur = '';
66
+ for (const word of words) {
67
+ if ((cur + ' ' + word).trim().length > w) {
68
+ out.push(cur.trim());
69
+ cur = word;
70
+ if (out.length === lines)
71
+ break;
72
+ }
73
+ else
74
+ cur += ' ' + word;
75
+ }
76
+ if (out.length < lines && cur.trim())
77
+ out.push(cur.trim());
78
+ if (out.length === lines && words.join(' ').length > out.join(' ').length) {
79
+ out[lines - 1] = out[lines - 1].slice(0, w - 1) + '…';
80
+ }
81
+ return out.map((l) => l.slice(0, w));
82
+ }
83
+ export function drawPlan(rows, opts = {}) {
84
+ const byTid = new Map(rows.map((r) => [r.tid, r]));
85
+ const plan = planWaves(rows);
86
+ const crit = plan.criticalPath.tids;
87
+ const critSet = new Set(crit);
88
+ const G = new Map();
89
+ const styles = new Map();
90
+ const put = (x, y, s, style) => {
91
+ ;
92
+ [...s].forEach((c, i) => {
93
+ G.set(`${x + i},${y}`, c);
94
+ if (style)
95
+ styles.set(`${x + i},${y}`, style);
96
+ });
97
+ };
98
+ // Strip a prefix most rows share ("cli-") — it carries no information in a
99
+ // box 22 characters wide, and it is what cut every "waits …" line short.
100
+ const names = rows.map((r) => shortName(r));
101
+ const pre = (names.find((n) => /^[a-z]+-/.test(n)) ?? '').replace(/^([a-z]+-).*$/, '$1');
102
+ const strip = pre !== '' && names.filter((n) => n.startsWith(pre)).length >= names.length * 0.6;
103
+ const label = (r) => { const n = shortName(r); return strip && n.startsWith(pre) ? n.slice(pre.length) : n; };
104
+ // A row with open subtasks cannot be claimed (tasks:claim's containment gate),
105
+ // so it is never "ready", whatever its own blockers say.
106
+ const openKids = new Map();
107
+ for (const r of rows)
108
+ if (r.parent && !CLOSED.has(r.status))
109
+ openKids.set(r.parent, (openKids.get(r.parent) ?? 0) + 1);
110
+ const boxes = new Map();
111
+ const columns = [];
112
+ plan.waves.forEach((wave, col) => {
113
+ const critHere = wave.tids.find((t) => critSet.has(t));
114
+ const rest = wave.tids
115
+ .filter((t) => t !== critHere)
116
+ .sort((a, b) => {
117
+ const ra = byTid.get(a), rb = byTid.get(b);
118
+ return Number(isReady(rb, byTid, opts.world)) - Number(isReady(ra, byTid, opts.world)) || (rb.priority ?? 0) - (ra.priority ?? 0);
119
+ });
120
+ // Slot 0 of every column is the critical path's lane — empty when this wave
121
+ // has no critical row, so the arrow can pass straight through.
122
+ const order = [critHere ?? null, ...rest];
123
+ columns[col] = order.filter((t) => t !== null);
124
+ order.forEach((tid, idx) => {
125
+ const x = col * (BOX_W + GAP);
126
+ const y = TOP + idx * (BOX_H + 1);
127
+ if (!tid)
128
+ return;
129
+ const r = byTid.get(tid);
130
+ boxes.set(tid, { x, y, col, idx: columns[col].indexOf(tid) });
131
+ const kids = openKids.get(tid) ?? 0;
132
+ const ready = kids === 0 && isReady(r, byTid, opts.world);
133
+ const style = opts.selected === tid ? 'selected'
134
+ : opts.changed?.has(tid) ? 'changed'
135
+ : critSet.has(tid) ? 'critical'
136
+ : ready ? 'ready'
137
+ : 'dim';
138
+ const edge = critSet.has(tid) ? '=' : '-';
139
+ put(x, y, '+' + edge.repeat(BOX_W - 2) + '+', style);
140
+ put(x, y + BOX_H - 1, '+' + edge.repeat(BOX_W - 2) + '+', style);
141
+ for (let k = 1; k < BOX_H - 1; k++) {
142
+ put(x, y + k, '|', style);
143
+ put(x + BOX_W - 1, y + k, '|', style);
144
+ }
145
+ const [l1 = '', l2 = ''] = wrap(label(r), BOX_W - 4, 2);
146
+ put(x + 2, y + 1, l1, style);
147
+ put(x + 2, y + 2, l2, style);
148
+ const ob = openBlockers(r, byTid, opts.world);
149
+ const who = r.assignee ? ` @${r.assignee}` : '';
150
+ const status = r.status === 'picked' ? `picked${who}`
151
+ : ready ? '> ready to start'
152
+ : kids ? `waits ${kids} subtasks`
153
+ : r.status === 'open' ? `waits ${[...ob.names.map((n) => (strip && n.startsWith(pre) ? n.slice(pre.length) : n)), ...(ob.outside ? [`+${ob.outside} outside`] : [])].join(', ')}`
154
+ : r.status;
155
+ put(x + 2, y + 3, status.slice(0, BOX_W - 4), style);
156
+ });
157
+ });
158
+ // The critical path, drawn along lane 0 between consecutive critical boxes.
159
+ for (let i = 1; i < crit.length; i++) {
160
+ const a = boxes.get(crit[i - 1]), b = boxes.get(crit[i]);
161
+ if (!a || !b)
162
+ continue;
163
+ for (let x = a.x + BOX_W; x < b.x - 1; x++) {
164
+ if (!G.has(`${x},2`))
165
+ put(x, 2, '=', 'critical');
166
+ }
167
+ put(b.x - 1, 2, '>', 'critical');
168
+ }
169
+ let maxX = 0, maxY = 0;
170
+ for (const k of G.keys()) {
171
+ const [x, y] = k.split(',').map(Number);
172
+ if (x > maxX)
173
+ maxX = x;
174
+ if (y > maxY)
175
+ maxY = y;
176
+ }
177
+ const lines = [];
178
+ for (let y = 0; y <= maxY; y++) {
179
+ let line = '';
180
+ for (let x = 0; x <= maxX; x++)
181
+ line += G.get(`${x},${y}`) ?? ' ';
182
+ lines.push(line.replace(/\s+$/, ''));
183
+ }
184
+ return { lines, styles, boxes, columns, plan };
185
+ }
186
+ /** The one-paragraph header both the print and the live view carry. */
187
+ export function planHeader(rows, plan, opts) {
188
+ const byTid = new Map(rows.map((r) => [r.tid, r]));
189
+ const open = rows.filter((r) => !CLOSED.has(r.status));
190
+ const parents = new Set(open.map((r) => r.parent).filter(Boolean));
191
+ const ready = open.filter((r) => !parents.has(r.tid) && isReady(r, byTid, opts.world)).length;
192
+ const cp = plan.criticalPath.tids.map((t) => shortName(byTid.get(t)));
193
+ return [
194
+ `${opts.title ?? 'plan'} — ${open.length} open · ${ready} ready to start · ${plan.waves.length} waves${opts.asOf ? ` · board read ${opts.asOf.slice(0, 16)}Z` : ''}`,
195
+ `critical path (${cp.length} steps decide the finish): ${cp.join(' → ') || '(none)'}`,
196
+ ];
197
+ }
198
+ /** What changed between two views of the same plan — the answer to "what happened?" */
199
+ export function planDelta(before, after, world) {
200
+ const bBy = new Map(before.map((r) => [r.tid, r]));
201
+ const aBy = new Map(after.map((r) => [r.tid, r]));
202
+ const nowReady = after
203
+ .filter((r) => isReady(r, aBy, world) && !(bBy.has(r.tid) && isReady(bBy.get(r.tid), bBy, world)))
204
+ .map((r) => r.tid);
205
+ const name = (by) => (t) => shortName(by.get(t));
206
+ return {
207
+ nowReady,
208
+ critBefore: planWaves(before).criticalPath.tids.map(name(bBy)),
209
+ critAfter: planWaves(after).criticalPath.tids.map(name(aBy)),
210
+ };
211
+ }
212
+ /** lazydraw's file shape, so `one draw <name>` can open and edit the picture. */
213
+ export function toLazydraw(lines, name) {
214
+ const cells = [];
215
+ lines.forEach((l, y) => [...l].forEach((c, x) => { if (c !== ' ')
216
+ cells.push([x, y, c]); }));
217
+ const now = new Date().toISOString();
218
+ return JSON.stringify({ version: 1, name, createdAt: now, updatedAt: now, cells }, null, 2) + '\n';
219
+ }
@@ -0,0 +1,20 @@
1
+ import type { Row } from './tasks-graph.js';
2
+ export interface LiveData {
3
+ rows: Row[];
4
+ world: Map<string, Row>;
5
+ asOf?: string;
6
+ }
7
+ export type Act = (receiver: string, data: Record<string, unknown>) => Promise<{
8
+ ok: boolean;
9
+ error?: string;
10
+ detail?: string;
11
+ }>;
12
+ export interface LiveOpts {
13
+ title: string;
14
+ load: () => Promise<LiveData>;
15
+ act: Act;
16
+ workspace?: string;
17
+ input?: NodeJS.ReadStream;
18
+ output?: NodeJS.WriteStream;
19
+ }
20
+ export declare function runLivePlan(o: LiveOpts): Promise<void>;