@workover/cli 0.1.0 → 0.3.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/README.md CHANGED
@@ -11,14 +11,86 @@ npm i -g @workover/cli
11
11
  ## Usage
12
12
 
13
13
  ```sh
14
- workover login # sign in (opens your browser to approve)
15
- workover whoami # show the current sign-in
16
- workover logout # sign out and revoke this device's token
14
+ workover login # sign in (opens your browser to approve)
15
+ workover login --publish # ...and also request permission to publish to WordPress
16
+ workover login --draft # ...and also request permission to write drafts with AI
17
+ workover login --write # ...and also allow direct edits, with no suggestions to review
18
+ workover projects # the projects you can reach, with their ids
19
+ workover doc list --project 11
20
+ workover doc read 1234
21
+ workover draft --org 3 --project 11 "Document the billing flow"
22
+ workover whoami # show the current sign-in
23
+ workover logout # sign out and revoke this device's token
17
24
  ```
18
25
 
19
26
  `workover login` uses the browser device-authorization flow: it prints a short code, opens your browser, and you approve the connection while signed in to Workover. The token is stored at `~/.workover/config.json` (owner-only) and can be revoked anytime in **Workover → Settings → Developer**.
20
27
 
21
- A connected tool can read your documents and propose changes as suggestions you review. It **cannot** publish to WordPress or change your account security.
28
+ A connected tool can read your documents, create new ones, and propose changes as suggestions you review. By default it **cannot** publish to WordPress, and it **cannot** edit an existing document without leaving you something to accept.
29
+
30
+ Pass `--publish` if you want the tool to be able to publish to your connected WordPress sites — useful for an agent building out a documentation set rather than editing one. The browser shows exactly what is being granted before you approve, and even a publishing token **cannot** override a "WordPress is newer" conflict: forcing past someone else's edit needs a person who can go and look.
31
+
32
+ Pass `--write` if you want the tool to edit documents directly rather than suggesting changes — see
33
+ [Editing directly](#editing-directly) below for when that is the right call.
34
+
35
+ Whatever you grant, a token can never change your account security, your billing, or your other tokens.
36
+
37
+ ## Working on documents
38
+
39
+ `workover doc` is the whole document surface, so signing in and then doing something with a document
40
+ are the same tool. Bodies come from `--file`, or from stdin:
41
+
42
+ ```sh
43
+ workover projects # find the project id
44
+ workover doc list --project 11 # documents in it, with their ids
45
+ workover doc read 1234 # the current text
46
+ workover doc read 1234 --json # ...for a script
47
+
48
+ workover doc create --project 11 --title "Billing" --file billing.md
49
+ cat billing.md | workover doc propose 1234 --note "tightened the intro"
50
+ ```
51
+
52
+ `doc create` writes the content **into** the new document. There is nothing to accept: a document
53
+ that did not exist a moment ago has no earlier version for anybody to review the new text against,
54
+ and asking would leave you accepting your own content against a blank page.
55
+
56
+ `doc propose` is the default for a document that already exists. It leaves tracked-change
57
+ suggestions for a person to accept or reject, which is what you want when the agent is working
58
+ unattended on somebody else's writing.
59
+
60
+ ### Editing directly
61
+
62
+ Sometimes review is the wrong answer: you are working alongside the agent on a document you have
63
+ open, you say "make that change", and fifty tracked suggestions to click through is not a safeguard,
64
+ it is the thing that teaches people to press *Accept all* without reading.
65
+
66
+ ```sh
67
+ workover login --write # once, and the browser says what it grants
68
+ workover doc write 1234 --file rewritten.md --note "as discussed"
69
+ ```
70
+
71
+ `doc write` **replaces the whole body**, so pass the complete document — anything you leave out is
72
+ deleted. Read it first with `workover doc read`. It needs a token from `workover login --write`;
73
+ without that scope it is refused and `doc propose` is the way through. Every direct edit is recorded
74
+ in the workspace's audit log, since unlike a proposal it leaves no review trail of its own.
75
+
76
+ ## Queueing a draft
77
+
78
+ `workover draft` asks Workover to write something; it does not write it itself. Workover reads the
79
+ project's linked GitHub repo for grounding, writes the draft, and captures any screenshots it needs
80
+ by signing in to the app you connected in **Settings → Integrations** — all server-side. The command
81
+ just queues the job and reports progress:
82
+
83
+ ```sh
84
+ workover draft --org 3 --project 11 "Write a guide to inviting teammates" --ground yes
85
+ ```
86
+
87
+ That division is the point. The tool at your terminal never handles your app's password: it stays
88
+ encrypted in Workover and is decrypted only where the screenshots are taken. Queueing a draft this
89
+ way is the same operation as typing the brief into the prompt box, so an agent can set the work up
90
+ and then review what came back.
91
+
92
+ `--draft` is not granted by default, because a draft spends AI credits and signs in to your
93
+ connected app. The browser says so before you approve.
22
94
 
23
95
  ## Coworking with Claude Code
24
96
 
@@ -30,6 +102,11 @@ claude mcp add workover -- npx -y @workover/mcp
30
102
 
31
103
  Then ask Claude Code to read or revise a document — its edits appear in Workover as tracked-change suggestions you accept or reject.
32
104
 
105
+ The MCP server and `workover doc` do the same things on purpose. A newly-registered MCP server is
106
+ not available in the session that registered it, so an agent that discovers mid-task that it needs
107
+ Workover has no route in until it restarts; a CLI subcommand works the moment the CLI is installed.
108
+ Either surface, same operations, same permissions.
109
+
33
110
  ## Configuration
34
111
 
35
112
  - `WORKOVER_API` — point the CLI at a different Workover API (defaults to `https://api.workover.dev`).
package/bin/workover.mjs CHANGED
@@ -12,9 +12,20 @@ import {
12
12
  import { homedir } from 'os';
13
13
  import { join } from 'path';
14
14
  import { spawn } from 'child_process';
15
+ import {
16
+ normalizeApi,
17
+ browserCommand,
18
+ pollDecision,
19
+ summariseEvaluations,
20
+ parseArgs,
21
+ rowId,
22
+ stripHtml,
23
+ documentText,
24
+ contentCommitted,
25
+ } from '../lib.mjs';
15
26
 
16
27
  // Point at a different API with WORKOVER_API (e.g. https://api.workover.test for local dev).
17
- const API = (process.env.WORKOVER_API || 'https://api.workover.dev').replace(/\/+$/, '');
28
+ const API = normalizeApi(process.env.WORKOVER_API || 'https://api.workover.dev');
18
29
  const CONFIG_DIR = join(homedir(), '.workover');
19
30
  const CONFIG_FILE = join(CONFIG_DIR, 'config.json');
20
31
 
@@ -32,9 +43,7 @@ const loadConfig = () => {
32
43
  };
33
44
 
34
45
  const openBrowser = (url) => {
35
- const cmd =
36
- process.platform === 'darwin' ? 'open' : process.platform === 'win32' ? 'cmd' : 'xdg-open';
37
- const args = process.platform === 'win32' ? ['/c', 'start', '', url] : [url];
46
+ const { cmd, args } = browserCommand(process.platform, url);
38
47
  try {
39
48
  spawn(cmd, args, { stdio: 'ignore', detached: true }).unref();
40
49
  } catch {
@@ -51,10 +60,64 @@ const post = async (path, body) => {
51
60
  return res.json().catch(() => ({}));
52
61
  };
53
62
 
63
+ /** An authenticated call against the signed-in API. GET unless a body is given. */
64
+ const authedCall = async (cfg, path, body) => {
65
+ const res = await fetch(`${cfg.api}${path}`, {
66
+ method: body ? 'POST' : 'GET',
67
+ headers: {
68
+ authorization: `Bearer ${cfg.token}`,
69
+ ...(body ? { 'content-type': 'application/json' } : {}),
70
+ },
71
+ ...(body ? { body: JSON.stringify(body) } : {}),
72
+ });
73
+ const text = await res.text();
74
+ if (!res.ok) {
75
+ // The API's own sentence when it sent one. Nest puts it in `message`, and the scope refusals
76
+ // in particular are written to tell you what to run next — which the raw JSON buries behind
77
+ // punctuation at exactly the moment somebody is trying to read it.
78
+ let detail = text.slice(0, 300);
79
+ try {
80
+ const parsed = JSON.parse(text);
81
+ const message = Array.isArray(parsed?.message)
82
+ ? parsed.message.join('; ')
83
+ : parsed?.message;
84
+ if (typeof message === 'string' && message) detail = message;
85
+ } catch {
86
+ /* not JSON — the raw prefix above is still better than nothing */
87
+ }
88
+ console.error(`\n ✗ ${res.status} ${detail}\n`);
89
+ process.exit(1);
90
+ }
91
+ return text ? JSON.parse(text) : null;
92
+ };
93
+
94
+ const flagValue = (name) => {
95
+ const i = process.argv.indexOf(`--${name}`);
96
+ return i === -1 ? undefined : process.argv[i + 1];
97
+ };
98
+
99
+ const requireSignIn = (hint) => {
100
+ const cfg = loadConfig();
101
+ if (!cfg?.token) {
102
+ console.log(` Not signed in. Run \`${`workover login ${hint || ''}`.trim()}\`.`);
103
+ process.exit(1);
104
+ }
105
+ return cfg;
106
+ };
107
+
108
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
109
+
54
110
  async function login() {
111
+ // `--publish` and `--draft` ask for scopes beyond the default. Off unless asked: a login that
112
+ // silently granted them would defeat the point of asking.
113
+ const scopes = ['read', 'propose'];
114
+ if (process.argv.includes('--publish')) scopes.push('publish');
115
+ if (process.argv.includes('--draft')) scopes.push('draft');
116
+ if (process.argv.includes('--write')) scopes.push('write');
117
+
55
118
  let start;
56
119
  try {
57
- start = await post('/cli-auth/device/code');
120
+ start = await post('/cli-auth/device/code', { scopes });
58
121
  } catch {
59
122
  console.error(`\n ✗ Couldn't reach Workover at ${API}\n`);
60
123
  process.exit(1);
@@ -64,6 +127,19 @@ async function login() {
64
127
  process.exit(1);
65
128
  }
66
129
 
130
+ if (scopes.includes('publish')) {
131
+ console.log('\n Requesting permission to PUBLISH to your connected WordPress sites.');
132
+ }
133
+ if (scopes.includes('draft')) {
134
+ console.log('\n Requesting permission to WRITE DRAFTS with AI. This spends AI credits, and a');
135
+ console.log(' repo-grounded draft also captures screenshots by signing in to your connected');
136
+ console.log(' app with the credential you stored in Workover.');
137
+ }
138
+ if (scopes.includes('write')) {
139
+ console.log('\n Requesting permission to EDIT DOCUMENTS DIRECTLY — `workover doc write`');
140
+ console.log(' replaces a document’s body with no suggestions to accept. Without it every');
141
+ console.log(' change is a proposal you review, which is the default and stays available.');
142
+ }
67
143
  console.log(`\n Your login code: \x1b[1m${start.user_code}\x1b[0m`);
68
144
  console.log(` Approve it here: ${start.verification_uri_complete}\n`);
69
145
  console.log(' Opening your browser…');
@@ -77,16 +153,17 @@ async function login() {
77
153
  await new Promise((r) => setTimeout(r, interval));
78
154
  process.stdout.write('.');
79
155
  const res = await post('/cli-auth/device/token', { device_code: start.device_code });
80
- if (res.status === 'complete') {
156
+ const decision = pollDecision(res);
157
+ if (decision === 'complete') {
81
158
  saveConfig({ api: API, token: res.access_token });
82
159
  console.log('\n\n \x1b[32m✓\x1b[0m Signed in to Workover.\n');
83
160
  return;
84
161
  }
85
- if (res.status === 'denied') {
162
+ if (decision === 'denied') {
86
163
  console.log('\n\n ✗ Approval was denied.\n');
87
164
  process.exit(1);
88
165
  }
89
- if (res.status === 'expired') {
166
+ if (decision === 'expired') {
90
167
  console.log('\n\n ✗ The code expired. Run `workover login` again.\n');
91
168
  process.exit(1);
92
169
  }
@@ -115,14 +192,618 @@ function whoami() {
115
192
  console.log(` Token: ${cfg.token.slice(0, 12)}… (manage in Workover → Settings → Developer)`);
116
193
  }
117
194
 
195
+ /**
196
+ * Queue a draft and watch it.
197
+ *
198
+ * The CLI only ASKS. Workover does the work: reading the linked repo for grounding, writing, and
199
+ * capturing screenshots by signing in to the connected app with the credential in its vault. That
200
+ * split is deliberate — whatever queues the job never sees the app credential, so this is the same
201
+ * operation as typing the brief into the prompt box, just initiated from a terminal.
202
+ */
203
+ async function draft() {
204
+ const cfg = loadConfig();
205
+ if (!cfg?.token) {
206
+ console.log(' Not signed in. Run `workover login --draft`.');
207
+ process.exit(1);
208
+ }
209
+
210
+ const flag = (name) => {
211
+ const i = process.argv.indexOf(`--${name}`);
212
+ return i === -1 ? undefined : process.argv[i + 1];
213
+ };
214
+ const projectId = Number(flag('project'));
215
+ const organizationId = Number(flag('org'));
216
+ // Everything that is not a flag or a flag's value is the brief.
217
+ const prompt = flag('prompt') ?? process.argv.slice(3).filter((a, i, all) => {
218
+ if (a.startsWith('--')) return false;
219
+ return !all[i - 1]?.startsWith('--');
220
+ }).join(' ');
221
+
222
+ const DOC_TYPES = ['tutorial', 'how-to', 'reference', 'explanation'];
223
+ const docType = flag('type');
224
+ if (docType && !DOC_TYPES.includes(docType)) {
225
+ console.log(`\n ✗ --type must be one of: ${DOC_TYPES.join(', ')}\n`);
226
+ process.exit(1);
227
+ }
228
+
229
+ if (!projectId || !organizationId || !prompt) {
230
+ console.log('\n Usage: workover draft --org <id> --project <id> "<brief>"');
231
+ console.log(' [--ground yes|no|auto] read the linked GitHub repo (default: auto)');
232
+ console.log(' [--type <kind>] tutorial | how-to | reference | explanation');
233
+ console.log(' one Divio type, held throughout the article\n');
234
+ process.exit(1);
235
+ }
236
+
237
+ const authed = async (path, init = {}) => {
238
+ const res = await fetch(`${cfg.api}${path}`, {
239
+ ...init,
240
+ headers: {
241
+ authorization: `Bearer ${cfg.token}`,
242
+ ...(init.body ? { 'content-type': 'application/json' } : {}),
243
+ },
244
+ });
245
+ const text = await res.text();
246
+ if (res.status === 403 && text.includes('scope')) {
247
+ console.error('\n ✗ This token cannot draft. Run `workover login --draft`.\n');
248
+ process.exit(1);
249
+ }
250
+ if (!res.ok) {
251
+ console.error(`\n ✗ ${res.status} ${text.slice(0, 300)}\n`);
252
+ process.exit(1);
253
+ }
254
+ return text ? JSON.parse(text) : null;
255
+ };
256
+
257
+ const job = await authed('/ai/draft', {
258
+ method: 'POST',
259
+ body: JSON.stringify({
260
+ organizationId,
261
+ projectId,
262
+ prompt,
263
+ ground: flag('ground') || 'auto',
264
+ ...(docType ? { docType } : {}),
265
+ }),
266
+ });
267
+
268
+ console.log(
269
+ `\n Queued draft #${job.jobId}${job.useRepo ? ' (reading the linked repo)' : ''}.`,
270
+ );
271
+
272
+ // A repo-grounded draft reads many files and may capture screenshots, so minutes is normal.
273
+ const deadline = Date.now() + 20 * 60_000;
274
+ let lastStep = '';
275
+ while (Date.now() < deadline) {
276
+ await new Promise((r) => setTimeout(r, 5_000));
277
+ const state = await authed(
278
+ `/ai/draft/job/${job.jobId}?organizationId=${organizationId}`,
279
+ );
280
+
281
+ // Echo Workover's own progress rather than a spinner: when a draft is slow you want to know
282
+ // whether it is reading the repo or driving a browser, not that it is still alive.
283
+ const step = state.progress?.[state.progress.length - 1];
284
+ if (step && step !== lastStep) {
285
+ console.log(` ${step}`);
286
+ lastStep = step;
287
+ }
288
+
289
+ if (state.status === 'ready') {
290
+ console.log('\n \x1b[32m✓\x1b[0m Draft ready.');
291
+ if (state.grounding?.repo)
292
+ console.log(` Grounded in: ${state.grounding.repo} (${state.grounding.status})`);
293
+ // The number worth checking: whether Workover captured its own screenshots, or only
294
+ // suggested that some would help.
295
+ if (state.screenshots)
296
+ console.log(
297
+ ` Screenshots: ${state.screenshots.added} captured${
298
+ state.screenshots.suggested ? ', more suggested' : ''
299
+ }`,
300
+ );
301
+ if (state.documentId) console.log(` Document: ${state.documentId}`);
302
+ return;
303
+ }
304
+ if (state.status === 'failed') {
305
+ console.log(`\n ✗ Draft failed: ${state.error || 'unknown error'}\n`);
306
+ process.exit(1);
307
+ }
308
+ }
309
+ console.log('\n ✗ Still running after 20 minutes. Check Workover for the job.\n');
310
+ process.exit(1);
311
+ }
312
+
313
+ /**
314
+ * Plan a whole documentation set for a feature, then draft each article.
315
+ *
316
+ * Two steps on purpose. The plan is one cheap call and is printed before anything is drafted, so a
317
+ * wrong plan — the wrong types, articles we already publish — costs seconds instead of a dozen
318
+ * grounded drafts. `--dry-run` stops after printing it.
319
+ */
320
+ async function draftSet() {
321
+ const cfg = loadConfig();
322
+ if (!cfg?.token) {
323
+ console.log(' Not signed in. Run `workover login --draft`.');
324
+ process.exit(1);
325
+ }
326
+ const flag = (name) => {
327
+ const i = process.argv.indexOf(`--${name}`);
328
+ return i === -1 ? undefined : process.argv[i + 1];
329
+ };
330
+ const organizationId = Number(flag('org'));
331
+ const projectId = Number(flag('project'));
332
+ const feature = flag('feature');
333
+ if (!organizationId || !projectId || !feature) {
334
+ console.log('\n Usage: workover draft-set --org <id> --project <id> --feature "<name>"');
335
+ console.log(' [--kind documentation|content] default: documentation');
336
+ console.log(' [--dry-run] print the plan and stop');
337
+ console.log(' [--yes] skip the confirmation (for scripts)\n');
338
+ process.exit(1);
339
+ }
340
+
341
+ const call = async (path, body) => {
342
+ const res = await fetch(`${cfg.api}${path}`, {
343
+ method: body ? 'POST' : 'GET',
344
+ headers: {
345
+ authorization: `Bearer ${cfg.token}`,
346
+ ...(body ? { 'content-type': 'application/json' } : {}),
347
+ },
348
+ ...(body ? { body: JSON.stringify(body) } : {}),
349
+ });
350
+ const text = await res.text();
351
+ if (!res.ok) {
352
+ console.error(`\n ✗ ${res.status} ${text.slice(0, 300)}\n`);
353
+ process.exit(1);
354
+ }
355
+ return text ? JSON.parse(text) : null;
356
+ };
357
+
358
+ const kind = flag('kind') || 'documentation';
359
+ const plan = await call('/ai/doc-set/plan', {
360
+ organizationId,
361
+ projectId,
362
+ feature,
363
+ kind,
364
+ });
365
+
366
+ console.log(`\n ${plan.count} pieces planned for "${plan.feature}" (${plan.kind}):\n`);
367
+ plan.articles.forEach((a, i) => {
368
+ console.log(` ${String(i + 1).padStart(2)}. [${a.docType.padEnd(11)}] ${a.title}`);
369
+ if (a.brief) console.log(` ${a.brief}`);
370
+ });
371
+ // Named, not silently filled: a small feature may genuinely not warrant all four types, and
372
+ // inventing an article to satisfy a checklist is padding.
373
+ if (plan.gaps?.length) console.log(`\n Not covered: ${plan.gaps.join(', ')}`);
374
+
375
+ if (process.argv.includes('--dry-run')) {
376
+ console.log('\n Dry run — nothing drafted.\n');
377
+ return;
378
+ }
379
+
380
+ // Nothing has been drafted yet, and nothing will be until this is answered. A plan is cheap; the
381
+ // drafts are minutes of work and real AI spend each, so the size of the commitment is stated and
382
+ // the default is no.
383
+ if (!process.argv.includes('--yes')) {
384
+ const { createInterface } = await import('node:readline/promises');
385
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
386
+ console.log(
387
+ `\n This will draft ${plan.count} article${plan.count === 1 ? '' : 's'}, each reading the ` +
388
+ `linked repo. That takes a few minutes each and spends AI credits.`,
389
+ );
390
+ console.log(' Drop any you do not want by number, e.g. "1,4" — or press enter to draft all.');
391
+ const answer = (await rl.question(' Draft them? [y/N/numbers to skip] ')).trim();
392
+ rl.close();
393
+
394
+ const skip = new Set(
395
+ answer
396
+ .split(/[\s,]+/)
397
+ .map((s) => Number(s))
398
+ .filter((n) => Number.isInteger(n) && n > 0),
399
+ );
400
+ if (!skip.size && !/^y(es)?$/i.test(answer)) {
401
+ console.log('\n Nothing drafted.\n');
402
+ return;
403
+ }
404
+ if (skip.size) {
405
+ plan.articles = plan.articles.filter((_, i) => !skip.has(i + 1));
406
+ console.log(`\n Skipping ${skip.size}; drafting ${plan.articles.length}.`);
407
+ }
408
+ }
409
+
410
+ if (!plan.articles.length) {
411
+ console.log('\n Nothing left to draft.\n');
412
+ return;
413
+ }
414
+
415
+ // Send back the list as approved — the server drafts exactly this, not the plan it produced.
416
+ const { jobs } = await call('/ai/doc-set/draft', {
417
+ organizationId,
418
+ projectId,
419
+ articles: plan.articles.map((a) => ({
420
+ title: a.title,
421
+ docType: a.docType,
422
+ brief: a.brief,
423
+ })),
424
+ });
425
+ console.log('');
426
+ for (const j of jobs) console.log(` queued #${j.jobId} [${j.docType}] ${j.title}`);
427
+ console.log(`\n ${jobs.length} drafts queued. Watch them in Workover.\n`);
428
+ }
429
+
430
+ /**
431
+ * Score a project's published documentation against the editorial rubric.
432
+ *
433
+ * The point is the LIST, not the number. Every quality judgement on these docs so far has been made
434
+ * by eye, and by eye a permission-denied screenshot passed, a loading spinner got published, and a
435
+ * reference article citing a service class read fine. A fixed rubric that has to quote the article
436
+ * back at you is the cheapest correction available.
437
+ *
438
+ * The number exists only to answer one question between passes: is the list getting shorter?
439
+ */
440
+ async function evaluateDocs() {
441
+ const cfg = requireSignIn('--draft');
442
+ const organizationId = Number(flagValue('org'));
443
+ const projectId = Number(flagValue('project'));
444
+ if (!organizationId || !projectId) {
445
+ console.log('\n Usage: workover eval --org <id> --project <id>');
446
+ console.log(' [--limit N] score only the first N documents');
447
+ console.log(' [--json] machine-readable, for diffing between passes\n');
448
+ process.exit(1);
449
+ }
450
+
451
+ const limit = Number(flagValue('limit')) || 0;
452
+ const asJson = process.argv.includes('--json');
453
+
454
+ const docs = (await authedCall(cfg, `/project/${projectId}/documents`)) || [];
455
+ const targets = (limit ? docs.slice(0, limit) : docs).filter((d) => !d.deletedAt);
456
+ if (!targets.length) {
457
+ console.log('\n No documents to score in that project.\n');
458
+ return;
459
+ }
460
+
461
+ if (!asJson) {
462
+ console.log(`\n Scoring ${targets.length} document(s) — one model call each.\n`);
463
+ }
464
+
465
+ const results = [];
466
+ for (const [i, doc] of targets.entries()) {
467
+ // Paced deliberately. The AI endpoints allow 20 calls a minute per user, and a project of any
468
+ // size would trip that in the first ten seconds and fail the rest of the run.
469
+ if (i > 0) await sleep(3200);
470
+ try {
471
+ const r = await authedCall(cfg, '/ai/evaluate', {
472
+ organizationId,
473
+ documentId: doc.id,
474
+ });
475
+ results.push(r);
476
+ if (!asJson) {
477
+ const weak = (r.weakest || []).map((w) => `${w.criterion} ${w.score}`).join(', ');
478
+ console.log(` ${String(r.overall).padStart(4)} ${r.title || `#${doc.id}`}`);
479
+ if (weak) console.log(` ${weak}`);
480
+ if (r.topFix) console.log(` → ${r.topFix}`);
481
+ }
482
+ } catch {
483
+ // One unscoreable document must not cost the whole sweep — an empty doc, or a model reply
484
+ // that came back unusable. Reported in the count below rather than swallowed.
485
+ if (!asJson) console.log(` — ${doc.title || `#${doc.id}`} (could not score)`);
486
+ }
487
+ }
488
+
489
+ if (asJson) {
490
+ console.log(JSON.stringify(results, null, 2));
491
+ return;
492
+ }
493
+
494
+ const summary = summariseEvaluations(results);
495
+ if (!summary.count) {
496
+ console.log('\n Nothing could be scored.\n');
497
+ return;
498
+ }
499
+
500
+ console.log(`\n ${summary.count} scored · overall ${summary.overall.toFixed(2)}/5\n`);
501
+ for (const { criterion, mean } of summary.criteria) {
502
+ console.log(` ${criterion.padEnd(20)} ${mean.toFixed(2)} ${'█'.repeat(Math.round(mean * 4))}`);
503
+ }
504
+ console.log(
505
+ `\n ${summary.needingWork} of ${summary.count} would still be changed by a human editor.\n`,
506
+ );
507
+ }
508
+
509
+ // ── Documents ────────────────────────────────────────────────────────────────
510
+ //
511
+ // Why these exist. `login` proved the CLI could reach Workover and then stopped: its verbs were
512
+ // login / logout / whoami / draft / draft-set / eval, so "connect to Workover and write this to a
513
+ // doc" was an instruction the CLI could do the first half of and had no word for the second. Doing
514
+ // it anyway meant reading apps/mcp/lib.mjs for the endpoints, digging the bearer token out of
515
+ // ~/.workover/config.json and hand-rolling curl — which an agent without a checkout of this repo
516
+ // cannot do at all.
517
+ //
518
+ // "Use the MCP server instead" is not an answer to that. A newly-registered MCP server is not
519
+ // available in the session that registered it, so an agent that discovers mid-task that it needs
520
+ // Workover has no route in until it is restarted — and it is mid-task, which is exactly when
521
+ // restarting costs the most. A subcommand works the moment the CLI is installed.
522
+ //
523
+ // So these mirror the MCP tools one for one, deliberately: list, read, create, propose, search. The
524
+ // two surfaces should never be able to do different things, because whichever one an agent reaches
525
+ // for is an accident of how it was set up.
526
+
527
+ /** The markdown body for a write: `--file <path>`, `--file -`, or piped stdin. */
528
+ const readBody = async (flags) => {
529
+ const file = flags.file;
530
+ if (typeof file === 'string' && file !== '-') {
531
+ try {
532
+ return readFileSync(file, 'utf8');
533
+ } catch {
534
+ console.error(`\n ✗ Couldn't read ${file}\n`);
535
+ process.exit(1);
536
+ }
537
+ }
538
+ // Piped input is the natural shape for an agent (a heredoc), so it is accepted without asking.
539
+ // Only when stdin is a terminal is there nothing to read — reading it then would hang forever,
540
+ // looking like a command that had silently stopped.
541
+ if (file === '-' || !process.stdin.isTTY) {
542
+ let body = '';
543
+ for await (const chunk of process.stdin) body += chunk;
544
+ return body;
545
+ }
546
+ return '';
547
+ };
548
+
549
+ /** A document id from the first positional argument, or a usage error naming what to pass. */
550
+ const docIdArg = (positionals, usage) => {
551
+ const id = rowId(positionals[0]);
552
+ if (id === null) {
553
+ console.log(`\n Usage: ${usage}`);
554
+ console.log(' The numeric document id — `workover doc list` prints it as "#123".\n');
555
+ process.exit(1);
556
+ }
557
+ return id;
558
+ };
559
+
560
+ const DOC_USAGE = [
561
+ '',
562
+ ' Usage: workover doc <command>',
563
+ '',
564
+ ' list --project <id> [--json] documents in a project',
565
+ ' read <docId> [--json] [--html] a document’s current text',
566
+ ' create --project <id> --title "<t>" a new document, content written in',
567
+ ' [--file <path> | piped stdin] [--json]',
568
+ ' propose <docId> [--note "<why>"] suggest a rewrite for review',
569
+ ' [--file <path> | piped stdin] [--json]',
570
+ ' write <docId> [--note "<why>"] REPLACE the body, no review step',
571
+ ' [--file <path> | piped stdin] [--json]',
572
+ ' needs `workover login --write`; use it only when asked to',
573
+ ' search "<query>" [--limit N] [--json] find documents by title/content',
574
+ '',
575
+ ' `workover projects` lists the project ids.',
576
+ '',
577
+ ' propose vs write: propose leaves tracked-change suggestions for a person to',
578
+ ' accept, and is the right default when nobody asked for anything else. write',
579
+ ' edits the document then and there — for when the person you are working with',
580
+ ' said to make the change.',
581
+ '',
582
+ ].join('\n');
583
+
584
+ async function docCommand() {
585
+ const sub = process.argv[3];
586
+ // Usage before sign-in: someone who typed the command wrong is asking what the commands are, and
587
+ // answering "not signed in" sends them to fix the wrong thing.
588
+ if (!['list', 'read', 'create', 'propose', 'write', 'search'].includes(sub)) {
589
+ console.log(DOC_USAGE);
590
+ process.exit(sub ? 1 : 0);
591
+ }
592
+ const { flags, positionals } = parseArgs(process.argv.slice(4), {
593
+ booleans: ['json', 'html'],
594
+ });
595
+ const cfg = requireSignIn();
596
+ const asJson = flags.json === true;
597
+
598
+ const projectIdFlag = (usage) => {
599
+ const id = rowId(flags.project);
600
+ if (id === null) {
601
+ console.log(`\n Usage: ${usage}`);
602
+ console.log(' Find the project id with `workover projects`.\n');
603
+ process.exit(1);
604
+ }
605
+ return id;
606
+ };
607
+
608
+ if (sub === 'list') {
609
+ const projectId = projectIdFlag('workover doc list --project <id>');
610
+ const all = (await authedCall(cfg, `/project/${projectId}/documents`)) || [];
611
+ const docs = all.filter((d) => !d.deletedAt);
612
+ if (asJson) return console.log(JSON.stringify(docs, null, 2));
613
+ if (!docs.length) return console.log('\n No documents in that project.\n');
614
+ console.log('');
615
+ for (const d of docs) {
616
+ console.log(
617
+ ` #${String(d.id).padEnd(6)} ${String(d.status || '').padEnd(18)} ${d.title || 'Untitled'}`,
618
+ );
619
+ }
620
+ console.log(`\n ${docs.length} document${docs.length === 1 ? '' : 's'}.\n`);
621
+ return;
622
+ }
623
+
624
+ if (sub === 'read') {
625
+ const docId = docIdArg(positionals, 'workover doc read <docId>');
626
+ const doc = await authedCall(cfg, `/project/doc/${docId}`);
627
+ if (!doc?.id) {
628
+ console.error(`\n ✗ Document ${docId} not found (or no access).\n`);
629
+ process.exit(1);
630
+ }
631
+ if (asJson) return console.log(JSON.stringify(doc, null, 2));
632
+ if (flags.html === true) return console.log(doc.content || '');
633
+ console.log(`\n# ${doc.title || 'Untitled'} (id ${doc.id})\n`);
634
+ console.log(documentText(doc) || '(empty document)');
635
+ console.log('');
636
+ return;
637
+ }
638
+
639
+ if (sub === 'create') {
640
+ const usage = 'workover doc create --project <id> --title "<title>" --file <path>';
641
+ const projectId = projectIdFlag(usage);
642
+ const title = typeof flags.title === 'string' ? flags.title.trim() : '';
643
+ if (!title) {
644
+ console.log(`\n Usage: ${usage}\n`);
645
+ process.exit(1);
646
+ }
647
+ const markdown = (await readBody(flags)).trim();
648
+ if (!markdown) {
649
+ console.log(`\n Usage: ${usage}`);
650
+ console.log(' The body comes from --file, or from stdin:');
651
+ console.log(` echo "# Hello" | ${usage.replace(' --file <path>', '')}\n`);
652
+ process.exit(1);
653
+ }
654
+
655
+ const doc = await authedCall(cfg, `/project/${projectId}/documents`, {
656
+ title,
657
+ markdown,
658
+ });
659
+ if (!doc?.id) {
660
+ console.error('\n ✗ Could not create the document.\n');
661
+ process.exit(1);
662
+ }
663
+
664
+ // The content went WITH the create, so on a current Workover it is simply in the document:
665
+ // there is no earlier version of a document this old for anyone to review it against.
666
+ if (contentCommitted(doc)) {
667
+ if (asJson) return console.log(JSON.stringify(doc, null, 2));
668
+ console.log(`\n \x1b[32m✓\x1b[0m Created "${title}" as document #${doc.id}.`);
669
+ console.log(' The content is in the document — nothing to accept.');
670
+ if (doc.documentUrl) console.log(` ${doc.documentUrl}`);
671
+ console.log('\n Changes to it from here go through `workover doc propose`.\n');
672
+ return;
673
+ }
674
+
675
+ // An older Workover validates the body against a whitelist and drops the field it does not
676
+ // know, which creates an EMPTY document and returns success. Proposing the content is the
677
+ // recovery; saying so is the point — a create that quietly lost the body would look identical.
678
+ const proposal = await authedCall(cfg, `/project/doc/${doc.id}/propose`, {
679
+ markdown,
680
+ source: 'Workover CLI',
681
+ });
682
+ if (asJson) {
683
+ return console.log(JSON.stringify({ ...doc, committed: false, proposal }, null, 2));
684
+ }
685
+ console.log(`\n Created "${title}" as document #${doc.id}, but it is EMPTY.`);
686
+ console.log(" This Workover can't write a new document's content directly, so the body");
687
+ console.log(' is waiting as suggestions. Open it and accept them:');
688
+ if (proposal?.documentUrl) console.log(` ${proposal.documentUrl}`);
689
+ console.log('');
690
+ return;
691
+ }
692
+
693
+ if (sub === 'propose') {
694
+ const usage = 'workover doc propose <docId> --file <path> [--note "<why>"]';
695
+ const docId = docIdArg(positionals, usage);
696
+ const markdown = (await readBody(flags)).trim();
697
+ if (!markdown) {
698
+ console.log(`\n Usage: ${usage}`);
699
+ console.log(' Pass the COMPLETE revised document, not just the changed part —');
700
+ console.log(' Workover diffs it against the current text to build the suggestions.');
701
+ console.log(' The body comes from --file, or from stdin.\n');
702
+ process.exit(1);
703
+ }
704
+ const res = await authedCall(cfg, `/project/doc/${docId}/propose`, {
705
+ markdown,
706
+ note: typeof flags.note === 'string' ? flags.note : undefined,
707
+ source: 'Workover CLI',
708
+ });
709
+ if (asJson) return console.log(JSON.stringify(res, null, 2));
710
+ console.log(`\n \x1b[32m✓\x1b[0m Proposed changes to document #${docId}.`);
711
+ console.log(' They appear as tracked-change suggestions for a person to accept or reject.');
712
+ if (res?.documentUrl) console.log(` ${res.documentUrl}`);
713
+ console.log('');
714
+ return;
715
+ }
716
+
717
+ if (sub === 'write') {
718
+ const usage = 'workover doc write <docId> --file <path> [--note "<why>"]';
719
+ const docId = docIdArg(positionals, usage);
720
+ const markdown = (await readBody(flags)).trim();
721
+ if (!markdown) {
722
+ console.log(`\n Usage: ${usage}`);
723
+ console.log(' Pass the COMPLETE document — this REPLACES the body, so anything');
724
+ console.log(' you leave out is deleted. Read it first with `workover doc read`.');
725
+ console.log(' Needs a token from `workover login --write`.\n');
726
+ process.exit(1);
727
+ }
728
+ const res = await authedCall(cfg, `/project/doc/${docId}/content`, {
729
+ markdown,
730
+ note: typeof flags.note === 'string' ? flags.note : undefined,
731
+ source: 'Workover CLI',
732
+ });
733
+ if (asJson) return console.log(JSON.stringify(res, null, 2));
734
+ console.log(`\n \x1b[32m✓\x1b[0m Wrote document #${docId} directly — nothing to review.`);
735
+ if (res?.replacedCharacters) {
736
+ console.log(` Replaced ${res.replacedCharacters} characters of existing text.`);
737
+ }
738
+ if (res?.documentUrl) console.log(` ${res.documentUrl}`);
739
+ console.log('');
740
+ return;
741
+ }
742
+
743
+ if (sub === 'search') {
744
+ const query = positionals.join(' ').trim();
745
+ if (!query) {
746
+ console.log('\n Usage: workover doc search "<query>" [--limit N]\n');
747
+ process.exit(1);
748
+ }
749
+ const limit = rowId(flags.limit) ?? 10;
750
+ const { results = [] } = await authedCall(
751
+ cfg,
752
+ `/search/documents?q=${encodeURIComponent(query)}&limit=${limit}`,
753
+ );
754
+ if (asJson) return console.log(JSON.stringify(results, null, 2));
755
+ if (!results.length) return console.log('\n No matching documents.\n');
756
+ console.log('');
757
+ for (const r of results) {
758
+ console.log(` #${String(r.id).padEnd(6)} ${r.title || 'Untitled'}`);
759
+ if (r.snippet) console.log(` ${stripHtml(r.snippet).slice(0, 160)}`);
760
+ }
761
+ console.log('');
762
+ return;
763
+ }
764
+
765
+ }
766
+
767
+ /** The project ids every `doc` command asks for. */
768
+ async function projects() {
769
+ const cfg = requireSignIn();
770
+ const { flags } = parseArgs(process.argv.slice(3), { booleans: ['json'] });
771
+ const res = await authedCall(cfg, '/project');
772
+ const list = Array.isArray(res) ? res : res?.projects || [];
773
+ if (flags.json === true) return console.log(JSON.stringify(list, null, 2));
774
+ if (!list.length) return console.log('\n No projects.\n');
775
+ console.log('');
776
+ for (const p of list) {
777
+ console.log(` #${String(p.id).padEnd(6)} ${p.name || p.title || 'Project'}`);
778
+ }
779
+ console.log('');
780
+ }
781
+
118
782
  const cmd = process.argv[2];
119
783
  if (cmd === 'login') await login();
120
784
  else if (cmd === 'logout') await logout();
121
785
  else if (cmd === 'whoami') whoami();
786
+ else if (cmd === 'draft') await draft();
787
+ else if (cmd === 'draft-set') await draftSet();
788
+ else if (cmd === 'eval') await evaluateDocs();
789
+ else if (cmd === 'doc') await docCommand();
790
+ else if (cmd === 'projects') await projects();
122
791
  else {
123
792
  console.log('\n Workover CLI\n');
124
793
  console.log(' Usage: workover <command>\n');
125
794
  console.log(' login Sign in to Workover (opens your browser to approve)');
795
+ console.log(' --publish also request permission to publish to WordPress');
796
+ console.log(' --draft also request permission to write drafts with AI');
797
+ console.log(' --write also allow direct edits (no suggestions to review)');
798
+ console.log(' doc Work on documents: list, read, create, propose, write, search');
799
+ console.log(' workover doc create --project 11 --title "Billing" --file b.md');
800
+ console.log(' workover doc read 123 · workover doc propose 123 --file new.md');
801
+ console.log(' projects List the projects you can reach, with their ids');
802
+ console.log(' draft Queue a draft in Workover and wait for it');
803
+ console.log(' --type tutorial|how-to|reference|explanation');
804
+ console.log(' draft-set Plan a feature’s whole documentation set, then draft each article');
805
+ console.log(' eval Score a project’s documentation against the editorial rubric');
806
+ console.log(' --org <id> --project <id> [--limit N] [--json]');
126
807
  console.log(' logout Sign out and revoke this device’s token');
127
808
  console.log(' whoami Show the current sign-in\n');
128
809
  }
package/lib.mjs ADDED
@@ -0,0 +1,161 @@
1
+ // Pure helpers for the Workover CLI, split out so they can be unit-tested without importing
2
+ // bin/workover.mjs (which runs a command + calls process.exit on load).
3
+
4
+ /** Strip trailing slashes from the API base URL (so `${API}${path}` never doubles up). */
5
+ export const normalizeApi = (raw) => (raw || '').replace(/\/+$/, '');
6
+
7
+ /** Map a platform + URL to the browser-open command used to approve the device login. */
8
+ export const browserCommand = (platform, url) => {
9
+ if (platform === 'darwin') return { cmd: 'open', args: [url] };
10
+ if (platform === 'win32') return { cmd: 'cmd', args: ['/c', 'start', '', url] };
11
+ return { cmd: 'xdg-open', args: [url] };
12
+ };
13
+
14
+ /**
15
+ * RFC 8628 device-token poll: reduce a token-endpoint response to a decision. Anything that isn't a
16
+ * terminal state (complete/denied/expired) is 'pending' → keep polling.
17
+ */
18
+ export const pollDecision = (res) => {
19
+ const s = res?.status;
20
+ if (s === 'complete') return 'complete';
21
+ if (s === 'denied') return 'denied';
22
+ if (s === 'expired') return 'expired';
23
+ return 'pending';
24
+ };
25
+
26
+ /**
27
+ * Split `argv` into flags and positionals.
28
+ *
29
+ * Replaces the per-command `indexOf('--x') + 1` scan, which could not tell a flag's VALUE from a
30
+ * positional argument — so `workover doc read 12 --json` and `workover doc propose 12 --note fixed`
31
+ * needed different hand-written rules to find the same document id.
32
+ *
33
+ * `--flag value`, `--flag=value` and bare `--flag` all work. A flag named in `booleans`, or one
34
+ * followed by another flag or nothing, is `true`. Everything after a lone `--` is positional, so a
35
+ * body that starts with a dash can still be passed.
36
+ */
37
+ export const parseArgs = (argv, { booleans = [] } = {}) => {
38
+ const flags = {};
39
+ const positionals = [];
40
+ for (let i = 0; i < argv.length; i++) {
41
+ const arg = argv[i];
42
+ if (arg === '--') {
43
+ positionals.push(...argv.slice(i + 1));
44
+ break;
45
+ }
46
+ if (!arg.startsWith('--')) {
47
+ positionals.push(arg);
48
+ continue;
49
+ }
50
+ const rest = arg.slice(2);
51
+ const eq = rest.indexOf('=');
52
+ if (eq !== -1) {
53
+ flags[rest.slice(0, eq)] = rest.slice(eq + 1);
54
+ continue;
55
+ }
56
+ const next = argv[i + 1];
57
+ if (booleans.includes(rest) || next === undefined || next.startsWith('--')) {
58
+ flags[rest] = true;
59
+ continue;
60
+ }
61
+ flags[rest] = next;
62
+ i++;
63
+ }
64
+ return { flags, positionals };
65
+ };
66
+
67
+ /**
68
+ * Coerce a user-supplied row id, or null if it isn't one.
69
+ *
70
+ * People and agents pass what is in front of them: the `#12345` these commands print, or the handle
71
+ * out of a document URL. `Number('#12345')` is `NaN`, which we would then send as a literal
72
+ * `/project/doc/NaN` — the API answers 500 and pages on-call. The MCP server learned this in
73
+ * production; the CLI is the same shape of client and gets the same guard rather than the same
74
+ * incident.
75
+ */
76
+ export const rowId = (value) => {
77
+ const s = String(value ?? '')
78
+ .trim()
79
+ .replace(/^#/, '');
80
+ return /^\d+$/.test(s) ? Number(s) : null;
81
+ };
82
+
83
+ /** Flatten HTML to readable plain text: drop tags + named entities, collapse whitespace. */
84
+ export const stripHtml = (html) =>
85
+ (html || '')
86
+ .replace(/<(script|style)\b[^>]*>[\s\S]*?<\/\1\b[^>]*>/gi, ' ')
87
+ .replace(/<[^>]+>/g, ' ')
88
+ .replace(/&nbsp;/gi, ' ')
89
+ .replace(/&lt;/gi, '<')
90
+ .replace(/&gt;/gi, '>')
91
+ .replace(/&quot;/gi, '"')
92
+ .replace(/&#39;/g, "'")
93
+ // &amp; last: decoding it first turns the escaped text "&amp;lt;" into a "<" the source
94
+ // never contained.
95
+ .replace(/&amp;/gi, '&')
96
+ .replace(/\s+/g, ' ')
97
+ .trim();
98
+
99
+ /**
100
+ * A document's body as readable text.
101
+ *
102
+ * `bodyText` first: the collab server derives it from the live Yjs state on every save, so it is
103
+ * what the document currently SAYS. `content` is only refreshed on import and on creation, so
104
+ * reading it first would hand back the version a document had when it arrived, months of editing
105
+ * ago, with nothing to indicate the difference.
106
+ */
107
+ export const documentText = (doc) =>
108
+ (doc?.bodyText || '').trim() || stripHtml(doc?.content) || '';
109
+
110
+ /**
111
+ * Whether a just-created document came back with its body already in it.
112
+ *
113
+ * `doc create` sends the markdown WITH the create, and a Workover that understands it writes the
114
+ * content straight in — a document one call old has no prior text for anybody to review the first
115
+ * body against. An older API validates the request against a whitelist, silently drops the unknown
116
+ * field, and returns a perfectly successful empty document. That is the case worth catching: the
117
+ * content would be gone and the command would look like it worked. So it is read off the response
118
+ * rather than assumed, and the caller falls back to proposing the body instead of losing it.
119
+ */
120
+ export const contentCommitted = (doc) =>
121
+ typeof doc?.content === 'string' && doc.content.trim().length > 0;
122
+
123
+ /**
124
+ * Reduce a run of per-document evaluations to the shape a reader can act on.
125
+ *
126
+ * The per-CRITERION mean is the number that matters, and it is deliberately reported before the
127
+ * per-document one. Which article scored worst tells you to go and edit that article; which
128
+ * criterion scored worst tells you what is wrong with how they are all being written — a prompt
129
+ * change moves a column, editing one article moves a row.
130
+ *
131
+ * Averaged over the documents that actually scored each criterion, not over every document. A judge
132
+ * that skipped a criterion has said nothing about it, and counting that as a zero would make the
133
+ * rubric look like it found a problem it never looked for.
134
+ */
135
+ export const summariseEvaluations = (results) => {
136
+ const scored = (results || []).filter((r) => r && Number.isFinite(r.overall));
137
+ if (!scored.length) {
138
+ return { count: 0, overall: 0, criteria: [], needingWork: 0 };
139
+ }
140
+
141
+ const byCriterion = new Map();
142
+ for (const r of scored) {
143
+ for (const [criterion, v] of Object.entries(r.scores || {})) {
144
+ if (!Number.isFinite(v?.score)) continue;
145
+ if (!byCriterion.has(criterion)) byCriterion.set(criterion, []);
146
+ byCriterion.get(criterion).push(v.score);
147
+ }
148
+ }
149
+
150
+ const mean = (xs) => xs.reduce((a, b) => a + b, 0) / xs.length;
151
+
152
+ return {
153
+ count: scored.length,
154
+ overall: mean(scored.map((r) => r.overall)),
155
+ // Worst first: the top line is what to fix next.
156
+ criteria: [...byCriterion.entries()]
157
+ .map(([criterion, xs]) => ({ criterion, mean: mean(xs), scored: xs.length }))
158
+ .sort((a, b) => a.mean - b.mean || a.criterion.localeCompare(b.criterion)),
159
+ needingWork: scored.filter((r) => (r.weakest || []).length > 0).length,
160
+ };
161
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@workover/cli",
3
- "version": "0.1.0",
3
+ "version": "0.3.0",
4
4
  "description": "Workover command line — sign in and cowork on your documents from the terminal.",
5
5
  "license": "UNLICENSED",
6
6
  "author": "ScaleMath",
@@ -21,6 +21,7 @@
21
21
  },
22
22
  "files": [
23
23
  "bin/",
24
+ "lib.mjs",
24
25
  "README.md"
25
26
  ],
26
27
  "engines": {
@@ -30,6 +31,7 @@
30
31
  "access": "public"
31
32
  },
32
33
  "scripts": {
33
- "workover": "node bin/workover.mjs"
34
+ "workover": "node bin/workover.mjs",
35
+ "test": "node --test"
34
36
  }
35
37
  }