@oneie/cli 5.2.0 → 5.2.2

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/src/tasks.js CHANGED
@@ -1,42 +1,40 @@
1
1
  import { Command } from 'commander';
2
- import { readFileSync, writeFileSync } from 'node:fs';
3
- import { boardAllWith, bulkAllWith, unwrapAsk, } from '@oneie/sdk/tasks-bulk';
2
+ import { existsSync, readFileSync, writeFileSync } from 'node:fs';
3
+ import { boardAllWith, bulkAllWith, } from '@oneie/sdk/tasks-bulk';
4
4
  import { authHeaders, jsonMode, resolveBase } from './lib/client.js';
5
- import { askPath } from './lib/api-path.js';
5
+ import { exitCodeFor, failureFor, makeAsker, RETRYABLE_EXIT } from './lib/asker.js';
6
6
  import { digest, filterKind, kindOf, renderDigest } from './lib/tasks-digest.js';
7
7
  import { planWaves, renderPlan, sequenceEdits, subtree, toDispatch } from './lib/tasks-graph.js';
8
+ import { drawPlan, planHeader, toLazydraw } from './lib/plan-draw.js';
9
+ import { runLivePlan } from './lib/plan-live.js';
10
+ import { runFlow, FLOWS as FLOW_IDS } from './lib/flow-tag.js';
11
+ import { buildLens, lensRows } from './lib/tasks-lens.js';
12
+ import { loadRoster } from './lib/roster.js';
13
+ import { proposeOwners, routeEdits } from './lib/tasks-route.js';
14
+ import { claimNext, nextCandidates } from './lib/tasks-next.js';
15
+ import { resolveBulkWorkspaces, spreadWarning, workspaceSpread } from './lib/tasks-workspace.js';
16
+ import { renderScore, scoreboard } from './lib/tasks-score.js';
17
+ import { CONFIG_DIR } from './lib/paths.js';
18
+ import { homedir } from 'node:os';
19
+ import { dirname, join } from 'node:path';
20
+ import { mkdirSync } from 'node:fs';
8
21
  // `one tasks` — the whole board and the whole edit in one command. Both ride
9
22
  // existing receivers (tasks:board, tasks:bulk) through the ask door; the page walk
10
23
  // and the 25-row chunking live in @oneie/sdk/tasks-bulk so the SDK and the CLI
11
24
  // run the same loop over their own transports.
12
25
  const DEFAULT_API = 'https://api.one.ie';
26
+ // The last transport failure any asker saw. The SDK's page walk and chunker catch a
27
+ // throw and keep only its message, so the retryable verdict is carried here and read
28
+ // back by fail() — the exit code is how a script tells "retry" from "fix the call".
29
+ let lastAskFailure;
13
30
  function asker(api) {
14
- const base = resolveBase({ api }, DEFAULT_API);
15
- return async (receiver, data) => {
16
- const res = await fetch(askPath(base, receiver), {
17
- method: 'POST',
18
- headers: authHeaders(),
19
- body: JSON.stringify({ data }),
20
- });
21
- const text = await res.text();
22
- let body;
23
- try {
24
- body = text ? JSON.parse(text) : undefined;
25
- }
26
- catch {
27
- throw new Error(`${receiver} → ${res.status} ${text.slice(0, 200)}`);
28
- }
29
- // A refusal still carries an envelope ({ outcome:'failure', result:{ error } }) — keep its reason.
30
- if (!res.ok && !(body && typeof body === 'object' && 'outcome' in body)) {
31
- throw new Error(`${receiver} → ${res.status} ${text.slice(0, 200)}`);
32
- }
33
- return unwrapAsk(receiver, body);
34
- };
31
+ return makeAsker(resolveBase({ api }, DEFAULT_API), { headers: authHeaders(), onFailure: (f) => { lastAskFailure = f; } });
35
32
  }
36
33
  const collect = (v, prev = []) => [...prev, v];
37
34
  function fail(msg) {
38
- process.stderr.write(`error ${msg}\n`);
39
- process.exitCode = 1;
35
+ const f = failureFor(msg, lastAskFailure);
36
+ process.stderr.write(`error ${msg}${f ? ` (${f.retryable ? 'retryable' : 'not retryable'}, httpStatus ${f.httpStatus}${f.retryable ? `, exit ${RETRYABLE_EXIT}` : ''})` : ''}\n`);
37
+ process.exitCode = exitCodeFor(f);
40
38
  }
41
39
  function top(rec, n) {
42
40
  if (!rec)
@@ -116,8 +114,28 @@ function parseKind(v) {
116
114
  const k = (v ?? 'work');
117
115
  return KINDS.includes(k) ? k : undefined;
118
116
  }
117
+ // Said once per process, on the first read that spans several groups.
118
+ let spreadWarned = false;
119
+ function warnSpread(rows) {
120
+ if (spreadWarned || !rows?.length)
121
+ return;
122
+ const w = spreadWarning(workspaceSpread(rows));
123
+ if (!w)
124
+ return;
125
+ spreadWarned = true;
126
+ process.stderr.write(w + '\n');
127
+ }
119
128
  async function readAll(api, req) {
120
- return boardAllWith(asker(api), { limit: 2000, ...req });
129
+ const res = await boardAllWith(asker(api), { limit: 2000, ...req });
130
+ warnSpread(res.tasks);
131
+ return res;
132
+ }
133
+ function saveDrawing(name, lines) {
134
+ const dir = join(process.env.XDG_DATA_HOME || join(homedir(), '.local', 'share'), 'lazydraw', 'drawings');
135
+ mkdirSync(dir, { recursive: true });
136
+ const file = join(dir, `${name.replace(/[^a-z0-9-]+/gi, '-').toLowerCase()}.ld.json`);
137
+ writeFileSync(file, toLazydraw(lines, name));
138
+ process.stderr.write(`saved — open it with: one draw ${name}\n`);
121
139
  }
122
140
  function writeOut(file, data) {
123
141
  if (!file)
@@ -151,7 +169,83 @@ async function runBulk(cmd, api, req, apply) {
151
169
  renderBulk(res, hasWhere && !apply && !(req.creates?.length || req.edits?.length));
152
170
  const unapplied = hasWhere && !apply ? 0 : (res.notAttempted ?? 0);
153
171
  if (res.ok === false || (res.failed ?? 0) > 0 || unapplied > 0 || (!!res.nextCursor && apply))
154
- process.exitCode = 1;
172
+ process.exitCode = res.ok === false ? exitCodeFor(failureFor(res.error ?? '', lastAskFailure)) : 1;
173
+ }
174
+ // `one tasks flow` — the human report (flow-tag.ts holds the plan and the apply guards).
175
+ function renderFlowPlan(r, scope, classifiedFrom) {
176
+ const firstLine = r.dryRun ? 'DRY RUN — nothing written' : 'APPLIED';
177
+ console.log(firstLine);
178
+ if (r.plan === undefined) {
179
+ return;
180
+ }
181
+ console.log(`board total=${r.total} rows read (status ${scope}) asOf=${r.asOf}`);
182
+ if (r.truncated !== undefined && typeof r.truncated === 'object') {
183
+ console.log('TRUNCATED: ' + JSON.stringify(r.truncated) + ' — tag signals are unknown on rows whose tags were cut');
184
+ }
185
+ console.log('signals from: ' + classifiedFrom);
186
+ for (const flow of FLOW_IDS) {
187
+ const count = r.plan.counts[flow];
188
+ console.log(` ${flow.padEnd(8)} ${count}`);
189
+ }
190
+ console.log(`placed=${r.plan.placed} unplaced=${r.plan.unplaced.length} (left for a person) alreadyTagged=${r.plan.alreadyTagged.length} mismatches=${r.plan.mismatches.length} edits=${r.plan.edits.length}`);
191
+ console.log(`by source notes=${r.plan.bySource.notes} tags=${r.plan.bySource.tags} classified=${r.plan.bySource.classified}`);
192
+ for (const m of r.plan.mismatches) {
193
+ console.log(` MISMATCH ${m.tid} computed=${m.computed} file=${m.file} — the rule wins (flow-route.test.ts)`);
194
+ }
195
+ if (r.dryRun && r.plan.edits.length > 0) {
196
+ console.log(`rerun with --apply to write ${r.plan.edits.length} rows (needs a live read fresher than --max-age)`);
197
+ }
198
+ }
199
+ // A seat's lens — its staked tags + itself and every seat that reports up to it.
200
+ // `--tags` builds one without the roster (the documented escape when no key can read it).
201
+ async function resolveLens(api, workspace, seat, opts) {
202
+ if (opts.tags) {
203
+ const tags = [...new Set(opts.tags.split(',').map((t) => t.trim()).filter(Boolean))].sort();
204
+ if (!tags.length)
205
+ return { ok: false, error: '--tags is empty' };
206
+ return { ok: true, lens: { seat, tags, seats: [seat], all: false }, source: '--tags (roster not read: reports are not in this lens)' };
207
+ }
208
+ const r = await loadRoster({ base: resolveBase({ api }, DEFAULT_API), workspace, file: opts.roster, headers: authHeaders() });
209
+ if (!r.ok)
210
+ return r;
211
+ const l = buildLens(r.seats, seat);
212
+ return l.ok ? { ok: true, lens: l.lens, source: r.source } : l;
213
+ }
214
+ function lensLine(lens, source, kept, of) {
215
+ const seats = lens.seats.filter((s) => s !== lens.seat);
216
+ const shown = seats.slice(0, 8).join(',') + (seats.length > 8 ? `,+${seats.length - 8}` : '');
217
+ return `lens ${lens.seat}: ${lens.all ? 'every row (staked *)' : `tags [${lens.tags.join(',')}]`} · reports ${seats.length}${seats.length ? ` (${shown})` : ''} · roster ${source} — ${kept} of ${of} rows`;
218
+ }
219
+ // The CEO scoreboard remembers the last brief so the next one prints deltas. Closed
220
+ // rows are read only when there is a last brief to compare with (status:'all' costs a
221
+ // second walk), and a PARTIAL read is never saved — it would fake a drop next time.
222
+ async function ceoScore(api, group, tree, active, res, file) {
223
+ const path = file ?? join(CONFIG_DIR, 'briefs', `${(group ?? 'own').replace(/[^a-z0-9-]+/gi, '-')}${tree ? '-tree' : ''}.json`);
224
+ let prev;
225
+ if (existsSync(path)) {
226
+ try {
227
+ prev = JSON.parse(readFileSync(path, 'utf8'));
228
+ }
229
+ catch {
230
+ process.stderr.write(`warning ${path} is not a scoreboard — starting over\n`);
231
+ }
232
+ }
233
+ let rows = active;
234
+ if (prev) {
235
+ const closed = await readAll(api, { ...(group ? { workspace: group } : {}), ...(tree ? { scope: 'tree' } : {}), status: ['done', 'verified', 'dissolved', 'failed'] });
236
+ if (closed.ok === false)
237
+ process.stderr.write(`warning closed rows unread (${closed.error ?? 'tasks:board failed'}) — closed-per-seat reads 0\n`);
238
+ else
239
+ rows = [...active, ...(closed.tasks ?? [])];
240
+ }
241
+ const score = scoreboard(rows, prev, { ...(res.asOf ? { asOf: res.asOf } : {}) });
242
+ if (res.nextCursor || res.truncated?.rows !== undefined) {
243
+ process.stderr.write('warning partial board read — scoreboard shown, NOT saved\n');
244
+ return score;
245
+ }
246
+ mkdirSync(dirname(path), { recursive: true });
247
+ writeFileSync(path, JSON.stringify(score.snap) + '\n');
248
+ return score;
155
249
  }
156
250
  export function tasksCmd() {
157
251
  const cmd = new Command('tasks').description('The whole task board in one read, and many task edits in one write');
@@ -201,6 +295,7 @@ export function tasksCmd() {
201
295
  catch (e) {
202
296
  return fail(e instanceof Error ? e.message : String(e));
203
297
  }
298
+ warnSpread(res.tasks);
204
299
  let excluded = 0;
205
300
  if (res.tasks && kind !== 'all') {
206
301
  const f = filterKind(res.tasks, kind);
@@ -239,7 +334,19 @@ export function tasksCmd() {
239
334
  return fail('send edits, creates, or where+set');
240
335
  if (!req.where !== !req.set)
241
336
  return fail('where and set go together');
242
- await runBulk(sub, opts.api, req, !!opts.apply);
337
+ // A tid carries no workspace: an edit without one is resolved from its board row,
338
+ // so a file mixing groups does not answer not_found for every row outside --workspace.
339
+ const r = await resolveBulkWorkspaces(asker(opts.api), req);
340
+ // An unreadable board is not a reason to refuse a write that worked before this
341
+ // existed: say so, and send with the file's workspace as it always was.
342
+ if (!r.ok)
343
+ process.stderr.write(`warning ${r.error.replace(' — nothing sent', '')} — sending with the file's workspace\n`);
344
+ const resolved = r.ok ? r : { req, filled: 0, unknown: [] };
345
+ if (resolved.filled)
346
+ process.stderr.write(`resolved the workspace of ${resolved.filled} edit(s) from their board rows\n`);
347
+ if (resolved.unknown.length)
348
+ process.stderr.write(`warning ${resolved.unknown.length} edit(s) not on the board read (${resolved.unknown.slice(0, 5).join(', ')}${resolved.unknown.length > 5 ? ', …' : ''}) — sent with the file's workspace\n`);
349
+ await runBulk(sub, opts.api, resolved.req, !!opts.apply);
243
350
  });
244
351
  cmd
245
352
  .command('set')
@@ -302,7 +409,10 @@ export function tasksCmd() {
302
409
  .option('--group <slug>', 'Alias of --workspace')
303
410
  .option('--tree', 'This group and every descendant group')
304
411
  .option('--kind <k>', 'work (default) | approval | all', 'work')
305
- .option('--as <lens>', "ceo | director:<assignee> — director narrows to one assignee's rows")
412
+ .option('--as <seat>', "ceo (whole board) | <seat> (its staked tags + rows held by it or anyone reporting to it) | director:<assignee> (that one assignee's rows only)")
413
+ .option('--tags <list>', 'With --as <seat>: use these comma tags as the lens instead of reading the roster')
414
+ .option('--roster <file>', 'With --as <seat>: read seats from a saved /api/agents/roster response')
415
+ .option('--score-file <path>', 'With --as ceo: where the scoreboard remembers the last brief (default ~/.config/one/briefs/<group>.json)')
306
416
  .option('--top <n>', 'Rows per section (default 5)')
307
417
  .option('--fresh', 'Rebuild the snapshot instead of reading the memo')
308
418
  .option('--out <file>', 'Also write the full digest as JSON to this file')
@@ -314,8 +424,13 @@ export function tasksCmd() {
314
424
  return fail('--kind must be work, approval or all');
315
425
  const group = opts.group ?? opts.workspace;
316
426
  const director = opts.as?.startsWith('director:') ? opts.as.slice('director:'.length) : undefined;
317
- if (opts.as && opts.as !== 'ceo' && !director)
318
- return fail("--as must be ceo or director:<assignee>");
427
+ let lens;
428
+ if (opts.as && opts.as !== 'ceo' && !director) {
429
+ const r = await resolveLens(opts.api, group, opts.as, opts);
430
+ if (!r.ok)
431
+ return fail(r.error);
432
+ lens = r;
433
+ }
319
434
  const res = await readAll(opts.api, {
320
435
  ...(group ? { workspace: group } : {}),
321
436
  ...(opts.tree ? { scope: 'tree' } : {}),
@@ -325,13 +440,111 @@ export function tasksCmd() {
325
440
  });
326
441
  if (res.ok === false)
327
442
  return fail(res.error ?? 'tasks:board failed');
328
- const d = digest((res.tasks ?? []), { kind });
329
- const meta = boardMeta(res);
330
- writeOut(opts.out, { meta, digest: d });
443
+ const all = (res.tasks ?? []);
444
+ const rows = lens ? lensRows(all, lens.lens) : all;
445
+ const d = digest(rows, { kind });
446
+ const meta = { ...boardMeta(res), ...(lens ? { lens: { ...lens.lens, source: lens.source, rows: rows.length, of: all.length } } : {}) };
447
+ const score = opts.as === 'ceo' ? await ceoScore(opts.api, group, opts.tree, all, res, opts.scoreFile) : undefined;
448
+ writeOut(opts.out, { meta, digest: d, ...(score ? { score } : {}) });
331
449
  if (jsonMode(sub))
332
- process.stdout.write(JSON.stringify({ meta, digest: d }, null, 2) + '\n');
333
- else
450
+ process.stdout.write(JSON.stringify({ meta, digest: d, ...(score ? { score } : {}) }, null, 2) + '\n');
451
+ else {
452
+ if (lens)
453
+ process.stdout.write(lensLine(lens.lens, lens.source, rows.length, all.length) + '\n');
334
454
  process.stdout.write(renderDigest(d, meta, { top: opts.top ? Number(opts.top) : 5 }) + '\n');
455
+ if (score)
456
+ process.stdout.write(renderScore(score, { color: !!process.stdout.isTTY }) + '\n');
457
+ }
458
+ });
459
+ cmd
460
+ .command('route')
461
+ .description("Propose an owner for every unassigned row from the seats' staked tags (dry run unless --apply). Zero overlap stays unassigned and is listed by tag")
462
+ .option('--workspace <slug>', 'Group slug (default: your own) — also whose roster is read')
463
+ .option('--group <slug>', 'Alias of --workspace')
464
+ .option('--tree', 'This group and every descendant group (each edit carries its own row\'s workspace)')
465
+ .option('--roster <file>', 'Read seats from a saved /api/agents/roster response instead of the live route')
466
+ .option('--apply', 'Send the edits (tasks:bulk, 25 a call), each with a comment naming the matched tags')
467
+ .option('--out <file>', 'Write the edits as a tasks:bulk request file (review it, then: one tasks bulk --file <it>)')
468
+ .option('--top <n>', 'Rows per list (default 10)')
469
+ .option('--api <url>', 'API base URL', DEFAULT_API)
470
+ .option('--json', 'Print the plan as JSON')
471
+ .action(async (opts, sub) => {
472
+ const group = opts.group ?? opts.workspace;
473
+ const roster = await loadRoster({ base: resolveBase({ api: opts.api }, DEFAULT_API), workspace: group, file: opts.roster, headers: authHeaders() });
474
+ if (!roster.ok)
475
+ return fail(roster.error);
476
+ const res = await readAll(opts.api, { ...(group ? { workspace: group } : {}), ...(opts.tree ? { scope: 'tree' } : {}) });
477
+ if (res.ok === false)
478
+ return fail(res.error ?? 'tasks:board failed');
479
+ const plan = proposeOwners((res.tasks ?? []), roster.seats);
480
+ const edits = routeEdits(plan);
481
+ const partial = !!res.nextCursor || res.truncated?.rows !== undefined;
482
+ writeOut(opts.out, { ...(group ? { workspace: group } : {}), edits });
483
+ if (jsonMode(sub)) {
484
+ process.stdout.write(JSON.stringify({ meta: { ...boardMeta(res), roster: roster.source }, ...plan, edits }, null, 2) + '\n');
485
+ }
486
+ else {
487
+ const topN = opts.top ? Number(opts.top) : 10;
488
+ const ties = plan.unrouted.filter((u) => u.reason === 'tie');
489
+ const w = process.stdout;
490
+ w.write(`route: ${plan.unassigned} unassigned · proposed ${plan.proposals.length} · unrouted ${plan.unrouted.length} (no-stake ${plan.unrouted.length - ties.length} · tie ${ties.length}) · ${plan.proposals.length} + ${plan.unrouted.length} = ${plan.proposals.length + plan.unrouted.length}\n`);
491
+ w.write(`roster ${roster.source} · board asOf ${res.asOf ?? '?'}\n`);
492
+ if (partial)
493
+ w.write('PARTIAL: the board read was short (nextCursor/truncated) — these counts cover the rows read, not the group\n');
494
+ const bySeat = {};
495
+ for (const p of plan.proposals)
496
+ bySeat[p.assignee] = (bySeat[p.assignee] ?? 0) + 1;
497
+ w.write(` by seat ${top(bySeat, 20)}\n`);
498
+ w.write(` unrouted tags ${top(plan.unroutedByTag, 25)} (no seat stakes these — rows stay unassigned)\n`);
499
+ for (const u of ties.slice(0, topN))
500
+ w.write(` tie ${u.tid} [${u.tags.join(',')}] → ${u.candidates?.join(' | ')}\n`);
501
+ for (const p of plan.proposals.slice(0, topN))
502
+ w.write(` ${p.tid} → @${p.assignee} [${p.matched.join(',')}] ${p.why}\n`);
503
+ if (!opts.apply)
504
+ w.write(`DRY RUN — nothing moved. --apply sends ${edits.length} edits; --out <file> writes them for review\n`);
505
+ }
506
+ if (opts.apply && edits.length)
507
+ await runBulk(sub, opts.api, { ...(group ? { workspace: group } : {}), edits }, true);
508
+ });
509
+ cmd
510
+ .command('next')
511
+ .description("Take the highest-priority READY row in a seat's lens and claim it — one call instead of board → filter → pick → claim. --peek claims nothing")
512
+ .requiredOption('--as <seat>', 'The seat whose lens to read (its staked tags + rows held by it or its reports)')
513
+ .option('--peek', 'Show the row that would be claimed; claim nothing')
514
+ .option('--workspace <slug>', 'Group slug (default: your own) — also whose roster is read')
515
+ .option('--group <slug>', 'Alias of --workspace')
516
+ .option('--tree', 'This group and every descendant group')
517
+ .option('--tags <list>', 'Use these comma tags as the lens instead of reading the roster')
518
+ .option('--roster <file>', 'Read seats from a saved /api/agents/roster response')
519
+ .option('--tries <n>', 'Claim at most this many candidates before giving up (default 5)')
520
+ .option('--api <url>', 'API base URL', DEFAULT_API)
521
+ .option('--json', 'Print the result as JSON')
522
+ .action(async (opts, sub) => {
523
+ const group = opts.group ?? opts.workspace;
524
+ const l = await resolveLens(opts.api, group, opts.as, opts);
525
+ if (!l.ok)
526
+ return fail(l.error);
527
+ const res = await readAll(opts.api, { ...(group ? { workspace: group } : {}), ...(opts.tree ? { scope: 'tree' } : {}), include: ['notes'] });
528
+ if (res.ok === false)
529
+ return fail(res.error ?? 'tasks:board failed');
530
+ const { candidates, refusal } = nextCandidates((res.tasks ?? []), l.lens);
531
+ if (!candidates.length)
532
+ return fail(refusal ?? `nothing ready in ${opts.as}'s lens`);
533
+ const r = await claimNext(asker(opts.api), candidates, opts.as, { peek: !!opts.peek, ...(opts.tries ? { tries: Number(opts.tries) } : {}) });
534
+ if (!r.ok)
535
+ return fail(r.error);
536
+ const row = r.row;
537
+ if (jsonMode(sub)) {
538
+ process.stdout.write(JSON.stringify({ ok: true, claimed: r.claimed, claimant: r.claimant, reassigned: r.reassigned, row, candidates: candidates.length, lens: { ...l.lens, source: l.source }, asOf: res.asOf }, null, 2) + '\n');
539
+ return;
540
+ }
541
+ const w = process.stdout;
542
+ w.write(`${r.claimed ? 'claimed' : 'PEEK — nothing claimed'} ${row.tid} p${row.priority} ${row.workspace} ${row.name}\n`);
543
+ if (r.reassigned)
544
+ w.write(` claim landed as @${r.claimant} (shared key) — handed to @${opts.as} with tasks:reassign\n`);
545
+ w.write(` ${candidates.length} ready in ${opts.as}'s lens · tags [${row.tags.join(',')}] · roster ${l.source}\n`);
546
+ w.write(` notes from the board snapshot asOf ${res.asOf ?? '?'} (no live tasks:get exists yet — task:01a0b93c761aa8a4e257f65e)\n\n`);
547
+ w.write((row.notes ?? '(no notes)') + '\n');
335
548
  });
336
549
  cmd
337
550
  .command('plan <goal>')
@@ -342,6 +555,9 @@ export function tasksCmd() {
342
555
  .option('--kind <k>', 'work (default) | approval | all', 'work')
343
556
  .option('--emit <what>', "dispatch = write the hand-off JSON (waves of tid/assignee/model/effort/touches/accept)")
344
557
  .option('--out <file>', 'Write the JSON (plan, or dispatch with --emit) to this file')
558
+ .option('--draw', 'Draw the plan: waves as columns, the critical path as arrows. In a terminal it is LIVE — select a row, act on it (claim · done · reopen · comment), and see what became ready')
559
+ .option('--print', 'With --draw: print the drawing once, never interactive (the default with no TTY, e.g. an agent or a pipe)')
560
+ .option('--save <name>', 'With --draw: also save the drawing for `one draw <name>`')
345
561
  .option('--api <url>', 'API base URL', DEFAULT_API)
346
562
  .option('--json', 'Print the plan as JSON')
347
563
  .action(async (goal, opts, sub) => {
@@ -369,6 +585,43 @@ export function tasksCmd() {
369
585
  }
370
586
  if (res.nextCursor || res.truncated?.rows !== undefined)
371
587
  process.stderr.write('warning the board read was partial — at least these rows; the plan may be missing some\n');
588
+ if (opts.draw) {
589
+ const world = new Map(all.map((r) => [r.tid, r]));
590
+ const title = byGoal ? (all.find((r) => r.tid === goal)?.name ?? goal) : `tag: ${goal}`;
591
+ const live = !opts.print && !jsonMode(sub) && process.stdin.isTTY && process.stdout.isTTY;
592
+ if (!live) {
593
+ const d = drawPlan(rows, { world });
594
+ const text = [...planHeader(rows, d.plan, { title, asOf: res.asOf, world }), '', ...d.lines].join('\n');
595
+ if (opts.save)
596
+ saveDrawing(opts.save, d.lines);
597
+ process.stdout.write(text + '\n');
598
+ return;
599
+ }
600
+ const ask = asker(opts.api);
601
+ let first = true;
602
+ const load = async () => {
603
+ if (first) {
604
+ first = false;
605
+ return { rows, world, asOf: res.asOf };
606
+ }
607
+ const r2 = await readAll(opts.api, { ...(group ? { workspace: group } : {}), ...(opts.tree ? { scope: 'tree' } : {}), include: ['notes'] });
608
+ if (r2.ok === false)
609
+ throw new Error(r2.error ?? 'tasks:board failed');
610
+ const all2 = (r2.tasks ?? []);
611
+ const picked2 = byGoal ? subtree(all2, goal) : all2.filter((r) => r.tags.includes(goal));
612
+ return { rows: filterKind(picked2, kind).rows, world: new Map(all2.map((r) => [r.tid, r])), asOf: r2.asOf };
613
+ };
614
+ await runLivePlan({
615
+ title,
616
+ workspace: group,
617
+ load,
618
+ act: async (receiver, data) => {
619
+ const out = (await ask(receiver, data));
620
+ return { ok: out?.ok !== false && !out?.error, error: out?.error, detail: out?.detail };
621
+ },
622
+ });
623
+ return;
624
+ }
372
625
  const plan = planWaves(rows);
373
626
  const meta = { goal, ...(res.asOf ? { asOf: res.asOf } : {}), ...(res.truncated ? { truncated: res.truncated } : {}) };
374
627
  const payload = opts.emit === 'dispatch' ? toDispatch(plan, rows, meta) : { ...meta, ...plan };
@@ -420,5 +673,67 @@ export function tasksCmd() {
420
673
  return fail('a task cannot wait for itself');
421
674
  await runEdits(sub, opts.api, opts.workspace, [{ tid, removeBlockedBy: [blockedBy] }]);
422
675
  });
676
+ cmd.command('flow')
677
+ .description('Name each row\'s flow: plan a `Flow: <flow>` notes line + `flow-<flow>` tag for every row that has none (dry run unless --apply)')
678
+ .option('--workspace <slug>', 'Group slug (default: your own)')
679
+ .option('--tree', 'This group and every descendant group')
680
+ .option('--status <s>', "Board status filter ('active', 'all', or a list)", 'active')
681
+ .option('--classified <path>', 'classified rows JSON ({rows:[{tid,role,family,rung,flow}]}); default .claude/bake/top100-classified.json when present')
682
+ .option('--board <file>', 'plan from a saved tasks board --json file instead of a live read; never applies')
683
+ .option('--apply', 'write the edits via tasks:bulk')
684
+ .option('--max-age <sec>', 'Refuse --apply when the board snapshot is older than this', '120')
685
+ .option('--fresh', 'Rebuild the board snapshot before planning (honoured at most once per memo window)')
686
+ .option('--out <file>', 'Write the whole result (plan + edits) as JSON')
687
+ .option('--api <url>', 'API base URL', DEFAULT_API)
688
+ .option('--json', 'Print the result as JSON')
689
+ .action((opts, sub) => {
690
+ let classifiedPath = opts.classified;
691
+ if (!classifiedPath) {
692
+ if (existsSync('.claude/bake/top100-classified.json')) {
693
+ classifiedPath = '.claude/bake/top100-classified.json';
694
+ }
695
+ }
696
+ let rows = [];
697
+ if (classifiedPath) {
698
+ try {
699
+ const content = readFileSync(classifiedPath, 'utf8');
700
+ const j = JSON.parse(content);
701
+ rows = Array.isArray(j) ? j : (j.rows ?? []);
702
+ }
703
+ catch (e) {
704
+ return fail('--classified: ' + e.message);
705
+ }
706
+ }
707
+ let board = undefined;
708
+ if (opts.board) {
709
+ try {
710
+ board = JSON.parse(readFileSync(opts.board, 'utf8'));
711
+ }
712
+ catch (e) {
713
+ return fail('--board: ' + e.message);
714
+ }
715
+ }
716
+ runFlow(asker(opts.api), rows, {
717
+ workspace: opts.workspace,
718
+ tree: !!opts.tree,
719
+ status: opts.status ?? 'active',
720
+ apply: !!opts.apply,
721
+ maxAgeSec: Number(opts.maxAge ?? '120'),
722
+ fresh: !!opts.fresh,
723
+ board,
724
+ }).then(r => {
725
+ writeOut(opts.out, r);
726
+ if (jsonMode(sub)) {
727
+ console.log(JSON.stringify(r, null, 2));
728
+ }
729
+ else {
730
+ const sourceDesc = classifiedPath ? `notes + tags + ${classifiedPath}` : 'notes + tags only (no --classified file)';
731
+ renderFlowPlan(r, opts.status ?? 'active', sourceDesc);
732
+ }
733
+ if (!r.ok) {
734
+ fail(r.error ?? 'tasks flow failed');
735
+ }
736
+ }).catch((e) => fail(e.message));
737
+ });
423
738
  return cmd;
424
739
  }
@@ -16,3 +16,5 @@ export declare function walletCmd(): Command;
16
16
  */
17
17
  export declare function addressesOnly(source: unknown): Record<string, string>;
18
18
  export declare function writeKeysFile(filePath: string, contents: string, accepted: boolean): void;
19
+ /** Read a secret from the TTY with echo off. Never argv (world-readable in ps), never env. */
20
+ export declare function promptSecret(prompt: string): Promise<string>;
@@ -416,7 +416,7 @@ function out(cmd, data) {
416
416
  }
417
417
  }
418
418
  /** Read a secret from the TTY with echo off. Never argv (world-readable in ps), never env. */
419
- async function promptSecret(prompt) {
419
+ export async function promptSecret(prompt) {
420
420
  if (!process.stdin.isTTY)
421
421
  throw new Error('a passphrase must be typed at a terminal — refusing to read one from a pipe');
422
422
  const rl = createInterface({ input: process.stdin, output: process.stdout, terminal: true });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@oneie/cli",
3
- "version": "5.2.0",
3
+ "version": "5.2.2",
4
4
  "description": "ONE agent CLI",
5
5
  "type": "module",
6
6
  "bin": {
@@ -20,7 +20,7 @@
20
20
  },
21
21
  "dependencies": {
22
22
  "commander": "^12.0.0",
23
- "@oneie/sdk": "^0.16.0"
23
+ "@oneie/sdk": "^0.16.3"
24
24
  },
25
25
  "devDependencies": {
26
26
  "@oneie/evals": "^0.2.0",