oneie 4.0.3 → 4.2.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.
package/dist/src/skill.js CHANGED
@@ -1,8 +1,9 @@
1
1
  import { Command } from 'commander';
2
+ import { KEY_FILE } from './lib/paths.js';
2
3
  import { readFileSync, writeFileSync, existsSync, mkdirSync, statSync, readdirSync } from 'node:fs';
3
4
  import { resolve, basename, join } from 'node:path';
4
- import { homedir } from 'node:os';
5
5
  import { parse as parseSkill } from './skill-parser.js';
6
+ import { askPath } from './lib/api-path.js';
6
7
  export function skillCmd() {
7
8
  const cmd = new Command('skill').description('Skill management');
8
9
  cmd.command('new <name>')
@@ -77,7 +78,7 @@ export function skillCmd() {
77
78
  .option('--name <name>', 'Override skill name')
78
79
  .option('--yes', 'Skip approval prompt (CI-friendly)')
79
80
  .action(async (ref, opts) => {
80
- const keyFile = resolve(homedir(), '.config', 'oneie', 'key');
81
+ const keyFile = KEY_FILE;
81
82
  const token = process.env.ONEIE_API_KEY ?? (existsSync(keyFile) ? readFileSync(keyFile, 'utf8').trim() : '');
82
83
  if (!token) {
83
84
  out(cmd, { ok: false, error: 'not authenticated — run `oneie auth login`' });
@@ -112,18 +113,91 @@ export function skillCmd() {
112
113
  out(cmd, { ok: false, error: err.message, hint: 'try `oneie skill validate <path>` for offline validation' });
113
114
  }
114
115
  });
116
+ // `skill:save` is the ONLY writer of the store `skill:run` / `skills:list`
117
+ // actually read (`{slug}/skills/{name}/SKILL.md` in R2). It had no CLI verb:
118
+ // `skill publish` writes the agentskills.io directory format to the LOCAL disk
119
+ // and `skill import` pulls someone else's in, so the one thing an author could
120
+ // not do from the CLI was push their own skill to their own workspace. `one push`
121
+ // reaches it, but only by compiling a whole `ai/` tree — there was no way to
122
+ // send a single file.
123
+ cmd.command('push <path>')
124
+ .description("Upload a SKILL.md into a workspace's R2 catalog — the store skill:run and skills:list read")
125
+ .requiredOption('--slug <slug>', 'Workspace slug')
126
+ .option('--api <url>', 'API base URL', 'https://one.ie')
127
+ .option('--name <name>', 'Override skill name (defaults to frontmatter name:)')
128
+ .action(async (path, opts) => {
129
+ if (!existsSync(path)) {
130
+ out(cmd, { ok: false, error: `not found: ${path}` });
131
+ return;
132
+ }
133
+ const content = readFileSync(path, 'utf8');
134
+ // THE NAME IS NEVER GUESSED FROM THE PATH. An earlier draft fell back to the
135
+ // parent directory name, and `skill push /etc/hosts --slug one` therefore
136
+ // published a skill called "etc" containing the host file — accepted, live,
137
+ // and resolvable by `skill:run`. R2 has no skill-delete receiver, so that had
138
+ // to be cleaned up with a direct `wrangler r2 object delete`. A path is not
139
+ // an identity: the frontmatter declares the name, or the caller does.
140
+ if (!/^---\s*$/m.test(content.split('\n')[0] ?? '')) {
141
+ out(cmd, { ok: false, error: `not a skill: ${path} has no YAML frontmatter (a SKILL.md opens with ---)` });
142
+ return;
143
+ }
144
+ const fmName = /^name:\s*(\S+)\s*$/m.exec(content.split(/^---\s*$/m)[1] ?? '')?.[1];
145
+ const name = opts.name ?? fmName;
146
+ if (!name) {
147
+ out(cmd, { ok: false, error: 'no skill name — add `name:` to the frontmatter, or pass --name <name>' });
148
+ return;
149
+ }
150
+ if (!/^[a-z0-9][a-z0-9-]*$/.test(name)) {
151
+ out(cmd, { ok: false, error: `invalid skill name "${name}" — lowercase alphanumeric and hyphens only` });
152
+ return;
153
+ }
154
+ const keyFile = KEY_FILE;
155
+ const key = process.env.ONE_API_KEY ?? process.env.ONEIE_API_KEY
156
+ ?? (existsSync(keyFile) ? readFileSync(keyFile, 'utf8').trim() : '');
157
+ if (!key) {
158
+ out(cmd, { ok: false, error: 'no API key — run `oneie auth login` or set ONE_API_KEY' });
159
+ return;
160
+ }
161
+ try {
162
+ const res = await fetch(askPath(opts.api.replace(/\/$/, ''), 'skill:save'), {
163
+ method: 'POST',
164
+ headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${key}` },
165
+ body: JSON.stringify({ data: { slug: opts.slug, name, content } }),
166
+ });
167
+ const text = await res.text();
168
+ const envelope = (text ? JSON.parse(text) : {});
169
+ const result = envelope.result ?? {};
170
+ // THE ASK ENVELOPE ANSWERS HTTP 200 ON A REFUSAL — `outcome: "failure"`
171
+ // carries the receiver's error under a 200, so `res.ok` alone would report
172
+ // a refused push as a success.
173
+ if (!res.ok || envelope.outcome === 'failure' || result.ok === false) {
174
+ const base = result.error ?? text ?? 'push failed';
175
+ const hint = result.callerRole === 'anonymous'
176
+ ? 'the key was not recognised — run `oneie auth login`, or set ONE_API_KEY to a world key (it starts `one-` or `osk_`)'
177
+ : result.error === 'forbidden'
178
+ ? `the key is valid but does not control workspace "${opts.slug}"`
179
+ : undefined;
180
+ out(cmd, { ok: false, status: res.status, error: hint ? `${base} — ${hint}` : base });
181
+ return;
182
+ }
183
+ out(cmd, { ok: true, name: result.name ?? name, slug: opts.slug, bytes: result.bytes ?? content.length });
184
+ }
185
+ catch (err) {
186
+ out(cmd, { ok: false, error: err.message });
187
+ }
188
+ });
115
189
  cmd.command('fork <name>')
116
190
  .description('Copy an open skill into a workspace (refuses sealed — invoke-only)')
117
191
  .requiredOption('--slug <slug>', 'Workspace slug')
118
192
  .option('--api <url>', 'API base URL', 'https://one.ie')
119
193
  .action(async (name, opts) => {
120
- const keyFile = resolve(homedir(), '.config', 'oneie', 'key');
194
+ const keyFile = KEY_FILE;
121
195
  const key = process.env.ONEIE_API_KEY ?? (existsSync(keyFile) ? readFileSync(keyFile, 'utf8').trim() : '');
122
196
  if (!key) {
123
197
  out(cmd, { ok: false, error: 'no API key — run `oneie auth login`' });
124
198
  return;
125
199
  }
126
- const token = `${opts.slug}:${key}`;
200
+ const token = key; // PLAIN key: requireAuth resolves a world key by `one-`/`osk_` PREFIX; a `slug:` prefix breaks it
127
201
  try {
128
202
  const res = await fetch(`${opts.api.replace(/\/$/, '')}/api/skills/workspace?slug=${encodeURIComponent(opts.slug)}`, {
129
203
  headers: { Authorization: `Bearer ${token}` },
@@ -153,13 +227,13 @@ export function skillCmd() {
153
227
  .requiredOption('--slug <slug>', 'Workspace slug')
154
228
  .option('--api <url>', 'API base URL', 'https://one.ie')
155
229
  .action(async (opts) => {
156
- const keyFile = resolve(homedir(), '.config', 'oneie', 'key');
230
+ const keyFile = KEY_FILE;
157
231
  const key = process.env.ONEIE_API_KEY ?? (existsSync(keyFile) ? readFileSync(keyFile, 'utf8').trim() : '');
158
232
  if (!key) {
159
233
  out(cmd, { ok: false, error: 'no API key — run `oneie auth login`' });
160
234
  return;
161
235
  }
162
- const token = `${opts.slug}:${key}`;
236
+ const token = key; // PLAIN key: requireAuth resolves a world key by `one-`/`osk_` PREFIX; a `slug:` prefix breaks it
163
237
  try {
164
238
  const res = await fetch(`${opts.api.replace(/\/$/, '')}/api/skills/workspace?slug=${encodeURIComponent(opts.slug)}`, {
165
239
  headers: { Authorization: `Bearer ${token}` },
@@ -180,13 +254,13 @@ export function skillCmd() {
180
254
  .requiredOption('--slug <slug>', 'Workspace slug')
181
255
  .option('--api <url>', 'API base URL', 'https://one.ie')
182
256
  .action(async (name, opts) => {
183
- const keyFile = resolve(homedir(), '.config', 'oneie', 'key');
257
+ const keyFile = KEY_FILE;
184
258
  const key = process.env.ONEIE_API_KEY ?? (existsSync(keyFile) ? readFileSync(keyFile, 'utf8').trim() : '');
185
259
  if (!key) {
186
260
  out(cmd, { ok: false, error: 'no API key — run `oneie auth login`' });
187
261
  return;
188
262
  }
189
- const token = `${opts.slug}:${key}`;
263
+ const token = key; // PLAIN key: requireAuth resolves a world key by `one-`/`osk_` PREFIX; a `slug:` prefix breaks it
190
264
  try {
191
265
  const res = await fetch(`${opts.api.replace(/\/$/, '')}/api/skill/${encodeURIComponent(name)}?slug=${encodeURIComponent(opts.slug)}`, {
192
266
  method: 'DELETE',
@@ -267,7 +341,7 @@ export function skillCmd() {
267
341
  out(cmd, { ok: false, error: `not found: ${path}` });
268
342
  return;
269
343
  }
270
- const keyFile = resolve(homedir(), '.config', 'oneie', 'key');
344
+ const keyFile = KEY_FILE;
271
345
  const token = process.env.ONEIE_API_KEY ?? (existsSync(keyFile) ? readFileSync(keyFile, 'utf8').trim() : '');
272
346
  if (!token) {
273
347
  out(cmd, { ok: false, error: 'not authenticated — run `oneie auth login`' });
@@ -276,15 +350,17 @@ export function skillCmd() {
276
350
  const content = readFileSync(path, 'utf8');
277
351
  const parsed = parseSkill(content, { pathStem: basename(path, '.md') });
278
352
  const skillName = typeof parsed.meta.name === 'string' ? parsed.meta.name : basename(path, '.md');
279
- const evals = extractEvals(content);
353
+ // Frontmatter is canonical when present; otherwise fall back to the bank.
354
+ const frontmatterEvals = extractEvals(content);
355
+ const evals = frontmatterEvals.length ? frontmatterEvals : readSidecarEvals(path);
280
356
  if (!evals.length) {
281
- out(cmd, { ok: false, error: 'no evals found in frontmatter — add an evals: block (see `oneie skill new`)' });
357
+ out(cmd, { ok: false, error: `no evals for ${skillName} — add an evals: block to the frontmatter, or an evals/evals.json bank beside it (see \`oneie skill new\`)` });
282
358
  return;
283
359
  }
284
360
  try {
285
361
  const res = await fetch(`${opts.api.replace(/\/$/, '')}/api/eval`, {
286
362
  method: 'POST',
287
- headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${opts.slug}:${token}` },
363
+ headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` },
288
364
  body: JSON.stringify({ slug: opts.slug, skillPath: skillName, iteration: Number(opts.iteration), draftContent: content, draftEvals: evals }),
289
365
  });
290
366
  const data = await res.json().catch(() => ({}));
@@ -310,6 +386,46 @@ export function skillCmd() {
310
386
  });
311
387
  return cmd;
312
388
  }
389
+ /**
390
+ * Evals live in two places and only one of them was ever read here:
391
+ * 1. an `evals:` block in SKILL.md frontmatter
392
+ * 2. a sibling `evals/evals.json` bank
393
+ * Every shipped skill uses (2) — measured 51 sidecar banks and 0 frontmatter
394
+ * blocks under one.ie/ai/skills — so `skill eval` refused every real skill with
395
+ * "no evals found in frontmatter". The server already reads both
396
+ * (pages/api/eval.ts), so this only brings the CLI's local read in line.
397
+ *
398
+ * The bank is either a bare array or `{ skill_name, evals: [...] }`, and its
399
+ * cases say `expected_output` where TestCase says `expected`. Normalise both.
400
+ */
401
+ function readSidecarEvals(skillPath) {
402
+ const dir = skillPath.endsWith('.md') ? resolve(skillPath, '..') : skillPath;
403
+ const bank = join(dir, 'evals', 'evals.json');
404
+ if (!existsSync(bank))
405
+ return [];
406
+ try {
407
+ const raw = JSON.parse(readFileSync(bank, 'utf8'));
408
+ const list = Array.isArray(raw)
409
+ ? raw
410
+ : Array.isArray(raw.evals)
411
+ ? raw.evals
412
+ : [];
413
+ return list
414
+ .map((c, i) => {
415
+ const o = c;
416
+ return {
417
+ id: o.id === undefined ? `case-${i + 1}` : String(o.id),
418
+ prompt: typeof o.prompt === 'string' ? o.prompt : '',
419
+ expected: String(o.expected ?? o.expected_output ?? ''),
420
+ assertions: Array.isArray(o.assertions) ? o.assertions.map(String) : [],
421
+ };
422
+ })
423
+ .filter(c => c.prompt && c.assertions.length > 0);
424
+ }
425
+ catch {
426
+ return [];
427
+ }
428
+ }
313
429
  // Mirrors one.ie/web/src/lib/eval/evals-source.ts and packages/mcp/src/tools/lifecycle.ts
314
430
  function extractEvals(content) {
315
431
  const fm = content.match(/^---\n([\s\S]*?)\n---/)?.[1];
@@ -0,0 +1,2 @@
1
+ import { Command } from 'commander';
2
+ export declare function tasksCmd(): Command;
@@ -0,0 +1,424 @@
1
+ import { Command } from 'commander';
2
+ import { readFileSync, writeFileSync } from 'node:fs';
3
+ import { boardAllWith, bulkAllWith, unwrapAsk, } from '@oneie/sdk/tasks-bulk';
4
+ import { authHeaders, jsonMode, resolveBase } from './lib/client.js';
5
+ import { askPath } from './lib/api-path.js';
6
+ import { digest, filterKind, kindOf, renderDigest } from './lib/tasks-digest.js';
7
+ import { planWaves, renderPlan, sequenceEdits, subtree, toDispatch } from './lib/tasks-graph.js';
8
+ // `one tasks` — the whole board and the whole edit in one command. Both ride
9
+ // existing receivers (tasks:board, tasks:bulk) through the ask door; the page walk
10
+ // and the 25-row chunking live in @oneie/sdk/tasks-bulk so the SDK and the CLI
11
+ // run the same loop over their own transports.
12
+ const DEFAULT_API = 'https://api.one.ie';
13
+ 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
+ };
35
+ }
36
+ const collect = (v, prev = []) => [...prev, v];
37
+ function fail(msg) {
38
+ process.stderr.write(`error ${msg}\n`);
39
+ process.exitCode = 1;
40
+ }
41
+ function top(rec, n) {
42
+ if (!rec)
43
+ return '-';
44
+ const rows = Object.entries(rec).sort((a, b) => b[1] - a[1]).slice(0, n);
45
+ return rows.length ? rows.map(([k, v]) => `${k === '' ? '(unassigned)' : k}=${v}`).join(' ') : '-';
46
+ }
47
+ function renderBoard(res) {
48
+ const tasks = res.tasks ?? [];
49
+ const w = process.stdout;
50
+ w.write(`${tasks.length} of ${res.total ?? '?'} (asOf ${res.asOf ?? '?'})${res.pages ? ` pages=${res.pages}` : ''}\n`);
51
+ if (res.truncated) {
52
+ const t = res.truncated;
53
+ const parts = [
54
+ t.rows !== undefined ? `rows=${t.rows} (total is a floor or rows are missing)` : '',
55
+ t.edges ? 'edges capped (blocked/orphan counts may be wrong)' : '',
56
+ t.tags !== undefined ? `tags missing on ${t.tags} rows` : '',
57
+ ].filter(Boolean);
58
+ w.write(`TRUNCATED: ${parts.join('; ') || JSON.stringify(t)}\n`);
59
+ }
60
+ if (res.nextCursor)
61
+ w.write(`MORE: nextCursor=${res.nextCursor} — rerun with --all to walk every page\n`);
62
+ const s = res.summary;
63
+ if (s) {
64
+ w.write('\nsummary\n');
65
+ w.write(` status ${top(s.byStatus, 20)}\n`);
66
+ w.write(` tags ${top(s.byTag, 15)}\n`);
67
+ w.write(` assignee ${top(s.byAssignee, 20)}\n`);
68
+ if (Object.keys(s.byWorkspace ?? {}).length > 1)
69
+ w.write(` workspace ${top(s.byWorkspace, 20)}\n`);
70
+ w.write(` ready=${s.ready} blocked=${s.blocked} overdue=${s.overdue} unassigned=${s.unassigned} orphans=${s.orphans} noNotes=${s.noNotes}\n`);
71
+ }
72
+ if (tasks.length)
73
+ w.write('\n');
74
+ for (const t of tasks) {
75
+ const tags = t.tags.length ? ` [${t.tags.join(',')}]` : '';
76
+ w.write(`${t.tid} ${t.status} p${t.priority} @${t.assignee || '-'} ${t.name}${tags}\n`);
77
+ }
78
+ }
79
+ function renderBulk(res, preview) {
80
+ const w = process.stdout;
81
+ if (preview && res.ok === false) {
82
+ // A preview that never reached the server has no match count to report — don't print "matched 0".
83
+ }
84
+ else if (preview) {
85
+ w.write(`DRY RUN — nothing moved. matched ${res.matched ?? res.matchedIds?.length ?? 0}\n`);
86
+ for (const id of res.matchedIds ?? [])
87
+ w.write(` ${id}\n`);
88
+ if (res.nextCursor)
89
+ w.write(` … more matches beyond this page (applies continue across pages with --apply)\n`);
90
+ w.write('rerun with --apply to apply\n');
91
+ }
92
+ else {
93
+ w.write(`total=${res.total ?? 0} attempted=${res.attempted ?? 0} applied=${res.applied ?? 0} failed=${res.failed ?? 0} notAttempted=${res.notAttempted ?? 0}` +
94
+ (res.matched !== undefined ? ` matched=${res.matched}` : '') +
95
+ '\n');
96
+ for (const [ref, tid] of Object.entries(res.created ?? {}))
97
+ w.write(` created ${ref} → ${tid}\n`);
98
+ if (res.nextCursor)
99
+ w.write(`STOPPED EARLY: nextCursor=${res.nextCursor} — rows remain unapplied\n`);
100
+ }
101
+ for (const r of res.results ?? []) {
102
+ if (r.ok)
103
+ continue;
104
+ const fields = (r.fields ?? []).filter((f) => !f.ok).map((f) => `${f.field}:${f.reason ?? 'failed'}`);
105
+ process.stderr.write(`FAILED ${r.tid || '-'}${r.ref ? ` (ref ${r.ref})` : ''} ${r.reason ?? ''}${fields.length ? ` ${fields.join(' ')}` : ''}${r.retryable ? ' retryable' : ''}\n`);
106
+ }
107
+ if (res.ok === false)
108
+ process.stderr.write(`error ${res.error ?? 'tasks:bulk failed'}${res.detail ? ` — ${res.detail}` : ''}\n`);
109
+ }
110
+ // ── planning helpers (brief · plan · sequence · depend) ────────────────────
111
+ // Reads walk every page of tasks:board (2000 rows a page) — never one request per
112
+ // row. The digest and the waves are computed HERE from the rows, so approvals can
113
+ // be left out of the counts without a receiver change (text/tasks-cli.md § the cheap cut).
114
+ const KINDS = ['work', 'approval', 'all'];
115
+ function parseKind(v) {
116
+ const k = (v ?? 'work');
117
+ return KINDS.includes(k) ? k : undefined;
118
+ }
119
+ async function readAll(api, req) {
120
+ return boardAllWith(asker(api), { limit: 2000, ...req });
121
+ }
122
+ function writeOut(file, data) {
123
+ if (!file)
124
+ return;
125
+ writeFileSync(file, JSON.stringify(data, null, 2) + '\n');
126
+ process.stderr.write(`wrote ${file}\n`);
127
+ }
128
+ function boardMeta(res) {
129
+ return {
130
+ ...(res.total !== undefined ? { total: res.total } : {}),
131
+ ...(res.asOf ? { asOf: res.asOf } : {}),
132
+ ...(res.pages !== undefined ? { pages: res.pages } : {}),
133
+ ...(res.truncated ? { truncated: res.truncated } : {}),
134
+ ...(res.nextCursor ? { nextCursor: res.nextCursor } : {}),
135
+ };
136
+ }
137
+ async function runEdits(sub, api, workspace, edits) {
138
+ await runBulk(sub, api, { ...(workspace ? { workspace } : {}), edits }, false);
139
+ if (!process.exitCode && !jsonMode(sub)) {
140
+ process.stdout.write('waves change on the next board snapshot (≤60s memo) — then: one tasks plan <goal>\n');
141
+ }
142
+ }
143
+ async function runBulk(cmd, api, req, apply) {
144
+ const hasWhere = !!req.where;
145
+ if (hasWhere)
146
+ req = { ...req, dryRun: !apply };
147
+ const res = await bulkAllWith(asker(api), req);
148
+ if (jsonMode(cmd))
149
+ process.stdout.write(JSON.stringify(res, null, 2) + '\n');
150
+ else
151
+ renderBulk(res, hasWhere && !apply && !(req.creates?.length || req.edits?.length));
152
+ const unapplied = hasWhere && !apply ? 0 : (res.notAttempted ?? 0);
153
+ if (res.ok === false || (res.failed ?? 0) > 0 || unapplied > 0 || (!!res.nextCursor && apply))
154
+ process.exitCode = 1;
155
+ }
156
+ export function tasksCmd() {
157
+ const cmd = new Command('tasks').description('The whole task board in one read, and many task edits in one write');
158
+ cmd
159
+ .command('board')
160
+ .description('Read the task board (tasks:board) — total, summary over all matched rows, and the rows')
161
+ .option('--workspace <slug>', 'Group slug (default: your own)')
162
+ .option('--tree', 'This group and every descendant group')
163
+ .option('--status <s>', "open|blocked|picked|done|verified|failed|dissolved, 'active' (default) or 'all'; comma for many")
164
+ .option('--tag <t>', 'Row must carry this tag (repeatable, AND)', collect)
165
+ .option('--any-tag <t>', 'Row must carry at least one of these (repeatable, OR)', collect)
166
+ .option('--assignee <a>', "Actor slug; '' = unassigned")
167
+ .option('--search <q>', 'Substring on the task name')
168
+ .option('--ready', 'Only rows claimable now')
169
+ .option('--include <list>', 'Comma list: notes,graph,dates,thread')
170
+ .option('--summary', 'Counts and sets only, no rows')
171
+ .option('--all', 'Follow nextCursor until every page is read (ceiling 20 pages)')
172
+ .option('--limit <n>', 'Rows per page (max 2000)')
173
+ .option('--fresh', 'Rebuild the snapshot instead of reading the memo')
174
+ .option('--kind <k>', "work (default) | approval | all — approvals are parked workflow runs; filtered from ROWS here, the server summary still counts them", 'work')
175
+ .option('--api <url>', 'API base URL', DEFAULT_API)
176
+ .option('--json', 'Print the raw response')
177
+ .action(async (opts, sub) => {
178
+ const kind = parseKind(opts.kind);
179
+ if (!kind)
180
+ return fail('--kind must be work, approval or all');
181
+ const status = opts.status?.includes(',') ? opts.status.split(',').map((s) => s.trim()).filter(Boolean) : opts.status;
182
+ const req = {
183
+ ...(opts.workspace ? { workspace: opts.workspace } : {}),
184
+ ...(opts.tree ? { scope: 'tree' } : {}),
185
+ ...(status ? { status } : {}),
186
+ ...(opts.tag?.length ? { tags: opts.tag } : {}),
187
+ ...(opts.anyTag?.length ? { anyTags: opts.anyTag } : {}),
188
+ ...(opts.assignee !== undefined ? { assignee: opts.assignee } : {}),
189
+ ...(opts.search ? { search: opts.search } : {}),
190
+ ...(opts.ready ? { ready: true } : {}),
191
+ ...(opts.include ? { include: opts.include.split(',').map((s) => s.trim()).filter(Boolean) } : {}),
192
+ ...(opts.summary ? { view: 'summary' } : {}),
193
+ ...(opts.limit ? { limit: Number(opts.limit) } : {}),
194
+ ...(opts.fresh ? { fresh: true } : {}),
195
+ };
196
+ const ask = asker(opts.api);
197
+ let res;
198
+ try {
199
+ res = opts.all ? await boardAllWith(ask, req) : (await ask('tasks:board', req));
200
+ }
201
+ catch (e) {
202
+ return fail(e instanceof Error ? e.message : String(e));
203
+ }
204
+ let excluded = 0;
205
+ if (res.tasks && kind !== 'all') {
206
+ const f = filterKind(res.tasks, kind);
207
+ excluded = kind === 'work' ? f.excluded.approval : f.excluded.work;
208
+ res = { ...res, tasks: f.rows, kindExcluded: excluded };
209
+ }
210
+ if (jsonMode(sub))
211
+ process.stdout.write(JSON.stringify(res, null, 2) + '\n');
212
+ else if (res.ok !== false) {
213
+ renderBoard(res);
214
+ if (excluded) {
215
+ process.stdout.write(`\n--kind ${kind}: ${excluded} ${kind === 'work' ? 'approval' : 'work'} rows left out of the rows above (the summary is server-side and still counts them). --kind all to include.\n`);
216
+ }
217
+ }
218
+ if (res.ok === false)
219
+ fail(res.error ?? 'tasks:board failed');
220
+ });
221
+ cmd
222
+ .command('bulk')
223
+ .description('Apply a tasks:bulk request from a file — creates/edits chunked at 25, where+set previewed unless --apply')
224
+ .requiredOption('--file <path>', 'JSON file holding a tasks:bulk request')
225
+ .option('--apply', 'For where+set: apply (dryRun:false). Without it, preview the matches only')
226
+ .option('--api <url>', 'API base URL', DEFAULT_API)
227
+ .option('--json', 'Print the merged receipt as JSON')
228
+ .action(async (opts, sub) => {
229
+ let req;
230
+ try {
231
+ req = JSON.parse(readFileSync(opts.file, 'utf8'));
232
+ }
233
+ catch (e) {
234
+ return fail(`--file: ${e instanceof Error ? e.message : String(e)}`);
235
+ }
236
+ if (!req || typeof req !== 'object')
237
+ return fail('--file must hold a JSON object');
238
+ if (!req.creates?.length && !req.edits?.length && !(req.where && req.set))
239
+ return fail('send edits, creates, or where+set');
240
+ if (!req.where !== !req.set)
241
+ return fail('where and set go together');
242
+ await runBulk(sub, opts.api, req, !!opts.apply);
243
+ });
244
+ cmd
245
+ .command('set')
246
+ .description('One edit to every task a filter matches (tasks:bulk where+set). Preview unless --apply')
247
+ .option('--workspace <slug>', 'Group slug (default: your own)')
248
+ .option('--where-status <s>', 'Match status (comma for many)')
249
+ .option('--where-tag <t>', 'Match rows carrying this tag (repeatable, AND)', collect)
250
+ .option('--where-any-tag <t>', 'Match rows carrying any of these (repeatable, OR)', collect)
251
+ .option('--where-assignee <a>', "Match assignee; '' = unassigned")
252
+ .option('--set-assignee <a>', "New assignee; '' unassigns")
253
+ .option('--set-status <s>', 'New status')
254
+ .option('--set-priority <n>', 'New priority (1-100)')
255
+ .option('--set-add-tag <t>', 'Add a tag (repeatable)', collect)
256
+ .option('--set-remove-tag <t>', 'Remove a tag (repeatable)', collect)
257
+ .option('--comment <text>', "Post to each task's thread — say why")
258
+ .option('--apply', 'Apply (dryRun:false). Without it, preview the matches only')
259
+ .option('--kind <k>', "all = allow the edit to touch approval rows (refused by default on --apply)")
260
+ .option('--api <url>', 'API base URL', DEFAULT_API)
261
+ .option('--json', 'Print the merged receipt as JSON')
262
+ .action(async (opts, sub) => {
263
+ const status = opts.whereStatus?.includes(',') ? opts.whereStatus.split(',').map((s) => s.trim()).filter(Boolean) : opts.whereStatus;
264
+ const where = {
265
+ ...(status ? { status } : {}),
266
+ ...(opts.whereTag?.length ? { tags: opts.whereTag } : {}),
267
+ ...(opts.whereAnyTag?.length ? { anyTags: opts.whereAnyTag } : {}),
268
+ ...(opts.whereAssignee !== undefined ? { assignee: opts.whereAssignee } : {}),
269
+ };
270
+ const set = {
271
+ ...(opts.setAssignee !== undefined ? { assignee: opts.setAssignee } : {}),
272
+ ...(opts.setStatus ? { status: opts.setStatus } : {}),
273
+ ...(opts.setPriority ? { priority: Number(opts.setPriority) } : {}),
274
+ ...(opts.setAddTag?.length ? { addTags: opts.setAddTag } : {}),
275
+ ...(opts.setRemoveTag?.length ? { removeTags: opts.setRemoveTag } : {}),
276
+ ...(opts.comment ? { comment: opts.comment } : {}),
277
+ };
278
+ if (!Object.keys(where).length)
279
+ return fail('name at least one --where-* filter (an empty filter would match the whole board)');
280
+ if (!Object.keys(set).length)
281
+ return fail('name at least one --set-* field or --comment');
282
+ if (set.priority !== undefined && !Number.isFinite(set.priority))
283
+ return fail('--set-priority must be a number');
284
+ // An approval row is a parked workflow run: a status edit strands it. Before an
285
+ // apply, read what the filter matches and refuse if any approval is in it.
286
+ if (opts.apply && opts.kind !== 'all') {
287
+ const seen = await readAll(opts.api, { ...(opts.workspace ? { workspace: opts.workspace } : {}), ...(where.status ? { status: where.status } : {}), ...(where.tags ? { tags: where.tags } : {}), ...(where.anyTags ? { anyTags: where.anyTags } : {}), ...(where.assignee !== undefined ? { assignee: where.assignee } : {}) });
288
+ if (seen.ok === false)
289
+ return fail(`approval guard could not read the board: ${seen.error ?? 'tasks:board failed'} — nothing applied`);
290
+ const approvals = (seen.tasks ?? []).filter((t) => kindOf(t) === 'approval').length;
291
+ if (approvals)
292
+ return fail(`${approvals} matched row(s) are approvals (parked workflow runs) — resolve them with tasks_approve / workflow:stop, narrow the filter, or pass --kind all. Nothing applied`);
293
+ if (seen.nextCursor || seen.truncated?.rows !== undefined)
294
+ process.stderr.write('warning approval guard read a partial board — at least the rows it saw hold no approvals\n');
295
+ }
296
+ await runBulk(sub, opts.api, { ...(opts.workspace ? { workspace: opts.workspace } : {}), where, set }, !!opts.apply);
297
+ });
298
+ cmd
299
+ .command('brief')
300
+ .description('One screen: counts, ready, blocked (by which open row), overdue, unowned, orphans, stale DONE, next five moves')
301
+ .option('--workspace <slug>', 'Group slug (default: your own)')
302
+ .option('--group <slug>', 'Alias of --workspace')
303
+ .option('--tree', 'This group and every descendant group')
304
+ .option('--kind <k>', 'work (default) | approval | all', 'work')
305
+ .option('--as <lens>', "ceo | director:<assignee> — director narrows to one assignee's rows")
306
+ .option('--top <n>', 'Rows per section (default 5)')
307
+ .option('--fresh', 'Rebuild the snapshot instead of reading the memo')
308
+ .option('--out <file>', 'Also write the full digest as JSON to this file')
309
+ .option('--api <url>', 'API base URL', DEFAULT_API)
310
+ .option('--json', 'Print the digest as JSON')
311
+ .action(async (opts, sub) => {
312
+ const kind = parseKind(opts.kind);
313
+ if (!kind)
314
+ return fail('--kind must be work, approval or all');
315
+ const group = opts.group ?? opts.workspace;
316
+ 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>");
319
+ const res = await readAll(opts.api, {
320
+ ...(group ? { workspace: group } : {}),
321
+ ...(opts.tree ? { scope: 'tree' } : {}),
322
+ ...(director ? { assignee: director } : {}),
323
+ include: ['notes'],
324
+ ...(opts.fresh ? { fresh: true } : {}),
325
+ });
326
+ if (res.ok === false)
327
+ 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 });
331
+ if (jsonMode(sub))
332
+ process.stdout.write(JSON.stringify({ meta, digest: d }, null, 2) + '\n');
333
+ else
334
+ process.stdout.write(renderDigest(d, meta, { top: opts.top ? Number(opts.top) : 5 }) + '\n');
335
+ });
336
+ cmd
337
+ .command('plan <goal>')
338
+ .description('Order the rows under a goal task (or carrying a tag) into waves, with the critical path in hops')
339
+ .option('--workspace <slug>', 'Group slug (default: your own)')
340
+ .option('--group <slug>', 'Alias of --workspace')
341
+ .option('--tree', 'This group and every descendant group')
342
+ .option('--kind <k>', 'work (default) | approval | all', 'work')
343
+ .option('--emit <what>', "dispatch = write the hand-off JSON (waves of tid/assignee/model/effort/touches/accept)")
344
+ .option('--out <file>', 'Write the JSON (plan, or dispatch with --emit) to this file')
345
+ .option('--api <url>', 'API base URL', DEFAULT_API)
346
+ .option('--json', 'Print the plan as JSON')
347
+ .action(async (goal, opts, sub) => {
348
+ const kind = parseKind(opts.kind);
349
+ if (!kind)
350
+ return fail('--kind must be work, approval or all');
351
+ if (opts.emit && opts.emit !== 'dispatch')
352
+ return fail('--emit takes: dispatch');
353
+ const group = opts.group ?? opts.workspace;
354
+ const res = await readAll(opts.api, {
355
+ ...(group ? { workspace: group } : {}),
356
+ ...(opts.tree ? { scope: 'tree' } : {}),
357
+ include: ['notes'],
358
+ });
359
+ if (res.ok === false)
360
+ return fail(res.error ?? 'tasks:board failed');
361
+ const all = (res.tasks ?? []);
362
+ const byGoal = all.some((r) => r.tid === goal);
363
+ const picked = byGoal ? subtree(all, goal) : all.filter((r) => r.tags.includes(goal));
364
+ const rows = filterKind(picked, kind).rows;
365
+ if (!rows.length)
366
+ return fail(`no active rows under '${goal}' — not a task id in this group, and no row carries it as a tag`);
367
+ if (!byGoal && res.truncated?.tags !== undefined) {
368
+ process.stderr.write(`warning planning from tag '${goal}' while ${res.truncated.tags} rows may be missing tags — this plan may miss rows\n`);
369
+ }
370
+ if (res.nextCursor || res.truncated?.rows !== undefined)
371
+ process.stderr.write('warning the board read was partial — at least these rows; the plan may be missing some\n');
372
+ const plan = planWaves(rows);
373
+ const meta = { goal, ...(res.asOf ? { asOf: res.asOf } : {}), ...(res.truncated ? { truncated: res.truncated } : {}) };
374
+ const payload = opts.emit === 'dispatch' ? toDispatch(plan, rows, meta) : { ...meta, ...plan };
375
+ writeOut(opts.out, payload);
376
+ if (jsonMode(sub))
377
+ process.stdout.write(JSON.stringify(payload, null, 2) + '\n');
378
+ else
379
+ process.stdout.write(renderPlan(plan, rows, { goal }) + '\n');
380
+ });
381
+ cmd
382
+ .command('sequence <tids...>')
383
+ .description('Chain tasks in order — each waits for the one before it (one tasks:bulk call). Preview unless --apply')
384
+ .option('--workspace <slug>', 'Group slug (default: your own)')
385
+ .option('--apply', 'Write the edges. Without it, print them')
386
+ .option('--api <url>', 'API base URL', DEFAULT_API)
387
+ .option('--json', 'Print the receipt as JSON')
388
+ .action(async (tids, opts, sub) => {
389
+ const seq = sequenceEdits(tids);
390
+ if (!seq.ok)
391
+ return fail(seq.error);
392
+ if (!opts.apply) {
393
+ process.stdout.write('PREVIEW — nothing written\n');
394
+ for (const e of seq.edits)
395
+ process.stdout.write(` ${e.tid} waits for ${e.addBlockedBy?.join(',')}\n`);
396
+ process.stdout.write('rerun with --apply to write\n');
397
+ return;
398
+ }
399
+ await runEdits(sub, opts.api, opts.workspace, seq.edits);
400
+ });
401
+ cmd
402
+ .command('depend <tid> <blockedBy>')
403
+ .description('Record that <tid> waits for <blockedBy> (the server refuses reverse edges)')
404
+ .option('--workspace <slug>', 'Group slug (default: your own)')
405
+ .option('--api <url>', 'API base URL', DEFAULT_API)
406
+ .option('--json', 'Print the receipt as JSON')
407
+ .action(async (tid, blockedBy, opts, sub) => {
408
+ if (tid === blockedBy)
409
+ return fail('a task cannot wait for itself');
410
+ await runEdits(sub, opts.api, opts.workspace, [{ tid, addBlockedBy: [blockedBy] }]);
411
+ });
412
+ cmd
413
+ .command('undepend <tid> <blockedBy>')
414
+ .description('Remove the edge: <tid> no longer waits for <blockedBy>')
415
+ .option('--workspace <slug>', 'Group slug (default: your own)')
416
+ .option('--api <url>', 'API base URL', DEFAULT_API)
417
+ .option('--json', 'Print the receipt as JSON')
418
+ .action(async (tid, blockedBy, opts, sub) => {
419
+ if (tid === blockedBy)
420
+ return fail('a task cannot wait for itself');
421
+ await runEdits(sub, opts.api, opts.workspace, [{ tid, removeBlockedBy: [blockedBy] }]);
422
+ });
423
+ return cmd;
424
+ }