@bigmistqke/workpad 0.19.0 → 0.20.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (89) hide show
  1. package/README.md +29 -16
  2. package/bin/workpad.ts +193 -37
  3. package/dist/bin/workpad.js +161 -32
  4. package/dist/client/runtime.js +141 -18
  5. package/dist/plugins/chat/README.md +7 -3
  6. package/dist/plugins/chat/index.js +1 -0
  7. package/dist/plugins/chat/public/client.js +2 -2
  8. package/dist/plugins/chat/public/style.css +10 -0
  9. package/dist/plugins/claude/channel.js +22 -4
  10. package/dist/plugins/claude/doctor.js +15 -5
  11. package/dist/plugins/comments/README.md +2 -1
  12. package/dist/plugins/comments/index.js +2 -0
  13. package/dist/plugins/comments/public/client.js +6 -5
  14. package/dist/plugins/comments/public/style.css +9 -0
  15. package/dist/plugins/form/README.md +1 -1
  16. package/dist/plugins/index.js +3 -1
  17. package/dist/plugins/opencode/channel.js +1 -0
  18. package/dist/plugins/progress/README.md +41 -0
  19. package/dist/plugins/progress/index.js +117 -0
  20. package/dist/plugins/progress/public/client.js +1 -0
  21. package/dist/plugins/progress/public/style.css +85 -0
  22. package/dist/plugins/progress/state.js +210 -0
  23. package/dist/solid/index.js +3 -1
  24. package/dist/src/agents.js +7 -3
  25. package/dist/src/anchors.js +25 -1
  26. package/dist/src/build.js +1 -1
  27. package/dist/src/client/page/base.css +48 -2
  28. package/dist/src/client/page/main.js +58 -30
  29. package/dist/src/document.js +6 -4
  30. package/dist/src/entries.js +6 -2
  31. package/dist/src/events.js +19 -9
  32. package/dist/src/files.js +26 -3
  33. package/dist/src/help.js +43 -8
  34. package/dist/src/hub.js +20 -4
  35. package/dist/src/loader.js +11 -6
  36. package/dist/src/migrate.js +1 -1
  37. package/dist/src/pages/board.js +1 -1
  38. package/dist/src/pages/markdown.js +3 -3
  39. package/dist/src/pages/render.js +16 -0
  40. package/dist/src/server.js +70 -32
  41. package/dist/src/set.js +99 -0
  42. package/dist/src/status.js +47 -8
  43. package/package.json +6 -1
  44. package/plugins/README.md +3 -1
  45. package/plugins/chat/README.md +7 -3
  46. package/plugins/chat/client.tsx +20 -3
  47. package/plugins/chat/index.ts +1 -0
  48. package/plugins/chat/public/style.css +10 -0
  49. package/plugins/claude/channel.ts +19 -5
  50. package/plugins/claude/doctor.ts +11 -3
  51. package/plugins/comments/README.md +2 -1
  52. package/plugins/comments/client.ts +19 -0
  53. package/plugins/comments/index.ts +7 -1
  54. package/plugins/comments/public/style.css +9 -0
  55. package/plugins/form/README.md +1 -1
  56. package/plugins/index.ts +2 -0
  57. package/plugins/opencode/channel.ts +2 -1
  58. package/plugins/progress/README.md +41 -0
  59. package/plugins/progress/client.ts +172 -0
  60. package/plugins/progress/index.ts +166 -0
  61. package/plugins/progress/public/style.css +85 -0
  62. package/plugins/progress/state.ts +278 -0
  63. package/skills/workpad/SKILL.md +126 -15
  64. package/solid/index.tsx +6 -2
  65. package/src/agents.ts +17 -2
  66. package/src/anchors.ts +32 -0
  67. package/src/build.ts +1 -1
  68. package/src/client/delivery.ts +49 -0
  69. package/src/client/forms.ts +18 -11
  70. package/src/client/page/base.css +48 -2
  71. package/src/client/page/waiting.ts +45 -25
  72. package/src/client/read.ts +9 -5
  73. package/src/client/runtime.ts +7 -3
  74. package/src/client/toast.ts +27 -3
  75. package/src/define.ts +92 -8
  76. package/src/document.ts +19 -5
  77. package/src/entries.ts +18 -7
  78. package/src/events.ts +26 -6
  79. package/src/files.ts +28 -2
  80. package/src/help.ts +42 -7
  81. package/src/hub.ts +25 -8
  82. package/src/loader.ts +20 -10
  83. package/src/migrate.ts +1 -1
  84. package/src/pages/board.ts +3 -1
  85. package/src/pages/markdown.ts +4 -4
  86. package/src/pages/render.ts +19 -1
  87. package/src/server.ts +114 -42
  88. package/src/set.ts +118 -0
  89. package/src/status.ts +100 -13
package/README.md CHANGED
@@ -159,10 +159,11 @@ gets `-2`. The server looks for projects again every few seconds, so a new
159
159
  worktree with a `.workpad/` shows up, and a removed one goes, without a
160
160
  restart.
161
161
 
162
- An entry's `"files": false` makes each of its projects serve none of its own
163
- files and watch only its `.workpad/`, as `files: false` in a project's
164
- config does, for projects with a config and without; a project's config that
165
- sets `files` still has its way. Left out, a project serves its files, as
162
+ An entry's `files` is the default `files` of each of its projects, with a
163
+ config and without: `"files": false` serves none of their own files and
164
+ watches only their `.workpad/`, and `"files": { "include": [...], "exclude":
165
+ [...] }` says which, as in a project's config (below). A project's config
166
+ that sets `files` still has its way. Left out, a project serves its files, as
166
167
  without the machine config.
167
168
 
168
169
  - **`/` is the overview of every project,** as a project's own overview is of
@@ -227,7 +228,8 @@ without the machine config.
227
228
  `url --full`). `$WORKPAD_URL` does the same for a project's own server
228
229
  started with it. By default `http://localhost:<port>`.
229
230
  - `"files": false` on an entry (see above) keeps its projects from
230
- watching more than their `.workpad/`. A page's own folder is watched
231
+ watching more than their `.workpad/`; `"files": { "exclude": ["**/dist"]
232
+ }` leaves out what nothing needs to show. A page's own folder is watched
231
233
  besides, once it is opened, so a page in a folder made and written into
232
234
  at once (which a container's mount may say nothing of) still goes live.
233
235
  - **A project per checkout.** A folder is a project once it has a
@@ -283,8 +285,9 @@ time it is read. A listen prints everything on its page not handled yet,
283
285
  including what came before it started and what it was handed before (marked
284
286
  `"again": true`), so an answer an agent saw and forgot comes back. So an
285
287
  agent can ask, do other work, and listen later. Any number listen on a
286
- page, and each hears everything there but its own events; the page's green
287
- dot lists who listens.
288
+ page, and each hears everything there but its own events (written under its
289
+ id, or in its session when `WORKPAD_AGENT` names it); another agent's message
290
+ comes to it once, not again; the page's green dot lists who listens.
288
291
 
289
292
  `listen` is built from smaller pieces that are commands too, for a script that
290
293
  wants to use the log its own way:
@@ -434,22 +437,23 @@ commands answer it too.
434
437
  | `workpad new <name>` | create a page under a name no other page has (`name`, else `name-2`, …), print its path |
435
438
  | `workpad show <page\|file> [<anchor>]` | start the project's server if needed (never the shared one), print the page's URL; with an anchor, one that opens the page there |
436
439
  | `workpad url <page\|file> [<anchor>] [--full]` | a link to a page or a place on it, from the server's root (`/rg/jobs/x/decisions#form:logger`), so it works however the board is opened; `--full` for the whole URL; checks the anchor |
437
- | `workpad settle <page\|file> <form>… \| --all` | settle questions answered elsewhere (a chat, the design moving on): no longer unanswered; an answer opens one again |
440
+ | `workpad settle <page\|file> <form>… \| --all` | settle questions answered elsewhere (a chat, the design moving on): no longer unanswered; an answer opens one again. With one form and `--replace-with <file\|->`, the form on the page is replaced with that markdown (what was decided) in the same step |
438
441
  | `workpad hold <page\|file> <form>… "<reason>"` | hold questions that wait on something else ("waits for !2145"): shown held with the reason, not waiting for the reader, not settled; an answer ends the hold |
439
442
  | `workpad release <page\|file> <form>…` | release held questions: they wait for the reader again |
440
- | `workpad check [<page\|file>…]` | what is wrong on pages as they render, a line each; exits 1 when there is any |
443
+ | `workpad check [<page\|file>…]` | what is wrong on pages as they render, a line each, links to an anchor that isn't there included (on the page, or on another page of the project, with the nearest it has); exits 1 when there is any |
441
444
  | `workpad migrate [<folder\|file>…] [--write]` | after updating workpad, pages written in an older syntax in the current one (0.15: items as `:::item`, `steps` → `tabs`, callouts → alerts, `:check` → `:checkbox`, an ansi fence's title window); code is left alone, a second run changes nothing. Before that, a project or machine still under the old name, whiteboard, moves to the new one (see above). A dry run lists each page and what would change, exiting 1 when any would; `--write` rewrites them. Default: `.workpad/pages` |
442
445
  | `workpad anchors <page\|file>` | what a page can be linked to: `#open-questions` (a heading), `#form:logger`, `#chat:notes`, `#tab:intro`, `#details:why` |
446
+ | `workpad set <page\|file> <anchor\|form> --file <file\|->` | replace one block of a page, found by parsing it: a form (`form:logger`), a heading's section (`open-questions`, up to the next heading of its level), a named block (`chat:notes`), with markdown from a file or standard input; the rest of the page stays byte for byte; a name the page lacks exits 1, listing what it has |
443
447
  | `workpad archive <page>` | a page that did its job: it leaves the pages and its events the log, kept in `.workpad/archive/` as markdown with what was answered on it |
444
448
  | `workpad destroy <page>` | a throwaway page: remove its file, and all its events from the log |
445
449
  | `workpad prune <page> [--type <t>] [--id <id>]` | remove a page's events from the log (all, one type, or one), keep the page |
446
- | `workpad edit <event id> --data <json>` | change an agent's own event in place: merged into its data, its id kept |
450
+ | `workpad edit <event id> --data <json> \| --file <file\|-> \| --text-file <file\|->` | change an agent's own event in place: merged into its data, its id kept |
447
451
  | `workpad thread <event id>` | an answer or chat message with its question: the form as written (chosen options marked), its answers and its chat, in order |
448
452
  | `workpad scroll <page\|file> <where>` | scroll the tabs that have the page open to a heading's text, a form's name or any text on it; exits 1 when nothing matches or no tab has it open |
449
453
  | `workpad docs [<block\|plugin> \| --all]` | print how to write pages in this project: a line per block, grouped by what it is for (ask, show, arrange, mark); with a block's or plugin's name, that plugin's docs; with `--all`, every plugin's |
450
454
  | `workpad events [filters] [--follow]` | print recorded events; with `--follow`, then each new one as it comes, marking nothing |
451
455
  | `workpad listen [filters] [--wait \| --channel] [--agent <who>]` | print everything matching you haven't handled (the reader's answers, other agents' messages; one handed out before with `"again": true`), then each as it comes, never exiting; with `--wait`, exit once it printed what there is, or with nothing there the next; with `--channel`, make the pages yours and exit, your session's confirmed channel bringing their answers (without `--page`, every page, also later ones); any number listen on a page; with `--page`, subscribes you to it; without, every page (in a project of the machine config's entries, every page of the entry, each event with its `project` and `url`) |
452
- | `workpad append --page <p> --type <t> [--data <json>]` | add an event to a page's log, such as a reply to a comment |
456
+ | `workpad append --page <p> --type <t> [--data <json> \| --file <file\|->] [--text-file <file\|->]` | add an event to a page's log, such as a reply to a comment: its data as JSON on the command line, or from a file or standard input (`--file`), with markdown from a file or standard input as its `text` (`--text-file`) |
453
457
  | `workpad handled <event id…>` | you handled these answers (a reply in their chat does it too): no listen hands them out again |
454
458
  | `workpad agent [name <n> \| name --clear \| list \| unsubscribe <agent> [--page <p>…] \| ping [<code>]]` | who you are (your id, `--agent`): alone, your id and name; `name` names you (one per agent, shown in the list of who listens and in `status`); `list` everyone on the board, saying who is subscribed and not listening; `unsubscribe` takes an agent (id or name) off the pages named, else off all; `ping` checks that an agent plugin's channel reaches you (it pushes a pong with a code; with the code, confirms it, and the channel then brings the answers on your pages, as received) |
455
459
  | `workpad status [--page <p>]` | per page: who is subscribed, questions without an answer, answers nobody received, answers received and not handled, chats waiting for a reply, who is listening |
@@ -570,8 +574,10 @@ export default defineConfig({
570
574
  ```
571
575
 
572
576
  Without `include`, all files are shown but what `exclude` names.
573
- `node_modules` and `.git` are always left out, at any depth, and never
574
- watched.
577
+ `node_modules` and `.git` are always left out, at any depth (in folders
578
+ whose name starts with a dot too), and never watched. On Linux each folder
579
+ that can hold something shown is watched on its own, so what is left out
580
+ costs no watches; `WORKPAD_WATCH=folders` does the same elsewhere.
575
581
 
576
582
  ## Building a site
577
583
 
@@ -677,13 +683,20 @@ Not started.
677
683
  recorded in the log, so it holds in every browser. An answered form waits
678
684
  for an agent to receive it; once one has it, the form folds into a card:
679
685
  what you chose (several answers each on a line, under the button you
680
- pressed), what you wrote, and "received · change" while the agent is on
686
+ pressed), what you wrote, and "received by <agent> · change" while the agent is on
681
687
  it, "decided · change" once it handled it; a click opens it again. Its chat folds into "💬 n messages", and opens when the agent
682
688
  writes there, or stays open while you are writing in it. The corner's
683
689
  toasts go to the next question ("→ unanswered (n)") and the next
684
690
  unread message ("→ unread (n)", whose ✕ puts it away until another
685
- comes), and the tab title gets a `(!n)` prefix. An answer sent while nobody
686
- listens says so in a toast; it stays in the log for whoever listens next.
691
+ comes), and the tab title gets a `(!n)` prefix.
692
+ - **Where what you sent went.** Beside an answer, a chat message or a
693
+ comment, in a small line: "no one follows this page — it waits until an
694
+ agent listens" (it stays in the log for whoever listens next), "waiting
695
+ for an agent to receive it", "received by <agent>", "handled". One no
696
+ agent received after 10 minutes says "not received after 10 min" in the
697
+ warning colour, and the corner counts them ("→ not received (n)"). A send
698
+ the server doesn't answer is tried again a few times (never appended
699
+ twice); one that never gets through says so, with a button to try again.
687
700
  - **Who listens.** The dot at the end of the header is green while the page
688
701
  is live and someone listens for its answers, grey when nobody does
689
702
  (answers wait in the log), and a ring while the page reconnects. A click
package/bin/workpad.ts CHANGED
@@ -38,7 +38,8 @@ import { archived, archiveFile } from '../src/archive.ts'
38
38
  import { thread } from '../src/thread.ts'
39
39
  import { markdownFiles, migrate } from '../src/migrate.ts'
40
40
  import { OLD, machineSteps, oldProjectDir, projectSteps } from '../src/rename.ts'
41
- import { anchorsOf, hashOf, type Anchor } from '../src/anchors.ts'
41
+ import { anchorsOf, hashOf, nearest, type Anchor } from '../src/anchors.ts'
42
+ import { findBlock, setBlock } from '../src/set.ts'
42
43
  import { projectToken } from '../src/auth.ts'
43
44
  import { PACKAGE_DIR, packagePath } from '../src/package.ts'
44
45
  import {
@@ -60,11 +61,12 @@ import {
60
61
  stateDir,
61
62
  } from '../src/entries.ts'
62
63
  import { compareVersions, VERSION } from '../src/package.ts'
63
- import { statusLines, whose } from '../src/status.ts'
64
+ import { refusal, statusLines, whose } from '../src/status.ts'
64
65
  import { holdForms, releaseForms, settleForms } from '../src/formstate.ts'
65
66
  import { client, probe } from '../src/api.ts'
66
67
  import { everyPage, everyProject, holdChannel, listen } from '../src/listen.ts'
67
68
  import { lastTurnEnd } from '../src/turns.ts'
69
+ import { line as progressLine, running as runningProgress } from '../plugins/progress/state.ts'
68
70
  import type { Listener, PageStatus, WpEvent } from '../src/define.ts'
69
71
 
70
72
  // a failing command prints its message, not a stack trace
@@ -131,6 +133,9 @@ const { values: opts, positionals } =
131
133
  channel: { type: 'boolean' },
132
134
  unfollowed: { type: 'boolean' },
133
135
  all: { type: 'boolean' },
136
+ file: { type: 'string' },
137
+ 'text-file': { type: 'string' },
138
+ 'replace-with': { type: 'string' },
134
139
  },
135
140
  })
136
141
 
@@ -190,6 +195,12 @@ async function ensureServer(): Promise<string> {
190
195
  )
191
196
  return base
192
197
  }
198
+ // the first ask timed out and this one was answered: the server is slow (busy), not missing the project
199
+ const mine = server?.projects.find(p => p.dir === proj.dir)
200
+ if (server && mine) {
201
+ console.error(`workpad: the shared server at ${server.origin} was slow to answer; it serves this project`)
202
+ return `${server.origin}${mine.base}`
203
+ }
193
204
  const at = recordedOrigin(machineServerFile())
194
205
  if (!server && at && (await stuckAt(at))) throw new Error(stuck(at, 'its login service log'))
195
206
  throw new Error(
@@ -296,6 +307,46 @@ function pageIn(target: string): { proj: Project; id: string } {
296
307
  return { proj, id: pageId(proj, target) }
297
308
  }
298
309
 
310
+ /** The file a page or repository file of the project is: `README.md`, `plan`, `.workpad/pages/plan.md`. */
311
+ function fileOf(proj: Project, target: string): string {
312
+ const id = pageId(proj, target)
313
+ if (!id) throw new Error(`no page ${target}`)
314
+ return id === '-' || id.startsWith('-/') ? path.join(proj.dir, id.slice(2)) : path.join(proj.pagesDir, `${id}.md`)
315
+ }
316
+
317
+ /**
318
+ * What a file holds, or with `-` what comes on standard input: for markdown and JSON an agent writes,
319
+ * which never passes through the shell's quoting that way (a heredoc with a quoted delimiter, or a file).
320
+ */
321
+ function readInput(from: string, option: string): string {
322
+ if (from === '-') return fs.readFileSync(0, 'utf8')
323
+ if (!fs.existsSync(from)) throw new Error(`${option} ${from}: no such file`)
324
+ return fs.readFileSync(from, 'utf8')
325
+ }
326
+
327
+ /**
328
+ * An event's data as the command line gives it: JSON from --data or --file (a file, or - for standard
329
+ * input), with --text-file's contents (a file, or -) as its `text`. Nothing given: undefined.
330
+ */
331
+ function eventData(): unknown {
332
+ if (opts.data !== undefined && opts.file !== undefined) throw new Error('give the data with --data or --file, not both')
333
+ const json = opts.file !== undefined ? readInput(opts.file, '--file') : opts.data
334
+ let data: unknown
335
+ if (json !== undefined) {
336
+ try {
337
+ data = JSON.parse(json)
338
+ } catch {
339
+ throw new Error(
340
+ `${opts.file !== undefined ? `--file ${opts.file}` : '--data'} must be JSON, e.g. {"text":"…"}; for markdown, --text-file <file|->`,
341
+ )
342
+ }
343
+ }
344
+ if (opts['text-file'] === undefined) return data
345
+ if (data !== undefined && (!data || typeof data !== 'object' || Array.isArray(data)))
346
+ throw new Error('with --text-file, the data must be a JSON object: the text goes in as its "text"')
347
+ return { ...(data as object | undefined), text: readInput(opts['text-file'], '--text-file').replace(/\s+$/, '') }
348
+ }
349
+
299
350
  /** Where a project is served: its running server, or an error saying how to start one. */
300
351
  async function serverOf(proj: Project): Promise<string> {
301
352
  if (proj.dir === project?.dir) return needServer()
@@ -517,6 +568,18 @@ async function whoAmI(proj: Project): Promise<string | null> {
517
568
  return (opts.agent as string | undefined) || process.env.WORKPAD_AGENT || (await currentSession(proj))
518
569
  }
519
570
 
571
+ /**
572
+ * Who runs this command, and the other id it goes by: the agent session a plugin names, when
573
+ * `--agent` or `WORKPAD_AGENT` named it otherwise. What it writes records both (appendEvent), and a
574
+ * listen leaves out what either wrote: a channel that knows the agent by its session, and the
575
+ * agent's commands that name it, are the same agent.
576
+ */
577
+ async function whoAmIWithSession(proj: Project): Promise<{ me: string | null; session: string | null }> {
578
+ const session = await currentSession(proj)
579
+ const me = (opts.agent as string | undefined) || process.env.WORKPAD_AGENT || session
580
+ return { me, session: session !== me ? session : null }
581
+ }
582
+
520
583
  /**
521
584
  * The agent session this command runs in, as the project's plugins know it (Claude Code's
522
585
  * plugin reads it from the environment): the first one that names one. Null without any.
@@ -547,16 +610,24 @@ async function status() {
547
610
  api(`/api/status${pageOpt ? `?page=${encodeURIComponent(pageId(proj, pageOpt))}` : ''}`),
548
611
  whoAmI(proj),
549
612
  ])
550
- const names = namesOf(readEvents(proj.eventsFile))
613
+ const events = readEvents(proj.eventsFile)
614
+ const names = namesOf(events)
551
615
  const busy = pages.filter(p => p.unreceived.length || p.open.length)
552
- if (!busy.length) {
553
- console.log('nothing open: every question is answered, and every answer received')
554
- return
555
- }
616
+ // the progress running on the pages asked about (plugins/progress), the latest moved first
617
+ const now = Date.now()
618
+ const runs = runningProgress(events).filter(r => pages.some(p => p.page === r.page))
619
+ if (!busy.length) console.log('nothing open: every question is answered, and every answer received')
556
620
  for (const p of busy) {
557
621
  console.log(`${p.page} (${whose(p, me, names)})`)
558
622
  for (const l of statusLines(p, relFile(p.file))) console.log(` ${l}`)
559
623
  }
624
+ if (runs.length) {
625
+ console.log('running:')
626
+ for (const r of runs)
627
+ console.log(
628
+ ` ${r.page}: ${progressLine(r, now)}${r.by ? ` (${r.by === me ? 'you' : (names.get(r.by) ?? r.by)})` : ''}`,
629
+ )
630
+ }
560
631
  }
561
632
 
562
633
  switch (cmd) {
@@ -866,6 +937,58 @@ switch (cmd) {
866
937
  .replace(/&#39;/g, "'")
867
938
  .replace(/&amp;/g, '&')
868
939
  .trim()
940
+ // the anchors of each page a link goes to, rendered once (null: there is no such page)
941
+ const anchorsOfPage = new Map<string, Promise<string[] | null>>()
942
+ const anchorsFor = (page: string) => {
943
+ if (!anchorsOfPage.has(page))
944
+ anchorsOfPage.set(
945
+ page,
946
+ anchorsAt(base, page).then(
947
+ as => as.map(a => a.id),
948
+ () => null,
949
+ ),
950
+ )
951
+ return anchorsOfPage.get(page)!
952
+ }
953
+ const served = new URL(base)
954
+ const root = served.pathname.replace(/\/$/, '')
955
+ /**
956
+ * The links of a rendered page to a place on another page of this project (`decisions.md#form:x`,
957
+ * or its own page by its file) whose anchor that page doesn't have. A link to `#…` alone is the
958
+ * render's own notice; one to another project, server or site isn't checked.
959
+ */
960
+ const brokenLinks = async (id: string, body: string): Promise<string[]> => {
961
+ const out: string[] = []
962
+ for (const m of body.matchAll(/<a\b[^>]*?\shref="([^"]*)"/g)) {
963
+ const href = text(m[1])
964
+ if (!href || href.startsWith('#')) continue
965
+ let url: URL
966
+ try {
967
+ url = new URL(href, `${base}/${id.split('/').map(encodeURIComponent).join('/')}`)
968
+ } catch {
969
+ continue
970
+ }
971
+ if (url.origin !== served.origin || !url.pathname.startsWith(`${root}/`) || url.hash.length < 2) continue
972
+ let page: string
973
+ let anchor: string
974
+ try {
975
+ page = decodeURIComponent(url.pathname.slice(root.length + 1)).replace(/\/$/, '')
976
+ anchor = decodeURIComponent(url.hash.slice(1))
977
+ } catch {
978
+ continue
979
+ }
980
+ // a chat message is drawn later, and a file of the repository other than markdown has none
981
+ if (anchor.startsWith('message:')) continue
982
+ const repo = page === '-' || page.startsWith('-/')
983
+ if (repo ? !/\.(md|markdown)$/i.test(page) : path.extname(page) && !/\.md$/i.test(page)) continue
984
+ if (!repo) page = page.replace(/\.md$/i, '')
985
+ const has = await anchorsFor(page)
986
+ if (!has) out.push(`a link to \`${page}${hashOf(anchor)}\`: there is no page ${page}`)
987
+ else if (!has.includes(anchor))
988
+ out.push(`a link to \`${page}${hashOf(anchor)}\`, which ${page} doesn't have${nearest(anchor, has)}`)
989
+ }
990
+ return out
991
+ }
869
992
  let found = 0
870
993
  const config = new Set<string>()
871
994
  for (const id of ids) {
@@ -876,10 +999,13 @@ switch (cmd) {
876
999
  continue
877
1000
  }
878
1001
  const { html: body = '', notices = [] } = (await res.json()) as { html?: string; notices?: string[] }
1002
+ anchorsOfPage.set(id, Promise.resolve(anchorsOf(body).map(a => a.id)))
879
1003
  const errors = [...body.matchAll(/<(\w+) class="wp-error"[^>]*>([\s\S]*?)<\/\1>/g)].map(m => text(m[2]))
880
1004
  // the config's errors are every page's: said once, at the end
881
1005
  for (const n of notices) if (n.startsWith('config: ')) config.add(n)
882
- const problems = [...new Set([...notices.filter(n => !n.startsWith('config: ')), ...errors])]
1006
+ const problems = [
1007
+ ...new Set([...notices.filter(n => !n.startsWith('config: ')), ...errors, ...(await brokenLinks(id, body))]),
1008
+ ]
883
1009
  if (!problems.length) continue
884
1010
  found += problems.length
885
1011
  console.log(`${id}\n${problems.map(p => ` ${p.replace(/\n/g, '\n ')}`).join('\n')}`)
@@ -943,6 +1069,21 @@ switch (cmd) {
943
1069
  console.log(`${hashOf(a.id)} ${a.kind}${a.label !== a.id.slice(a.kind.length + 1) ? ` ${a.label}` : ''}`)
944
1070
  break
945
1071
  }
1072
+ case 'set': {
1073
+ // a block of a page replaced by name (a form, a heading's section, a named block), with markdown
1074
+ // from a file or standard input: found by parsing the page, never by matching its text
1075
+ const [target, name] = positionals
1076
+ if (!target || !name || opts.file === undefined)
1077
+ throw new Error('usage: workpad set <page|file> <anchor|form> --file <file|->')
1078
+ const proj = needProject()
1079
+ const file = fileOf(proj, target)
1080
+ if (!fs.existsSync(file)) throw new Error(`no page ${target} (${relFile(file)})`)
1081
+ const source = fs.readFileSync(file, 'utf8')
1082
+ const block = findBlock(source, name)
1083
+ fs.writeFileSync(file, setBlock(source, name, readInput(opts.file, '--file')))
1084
+ console.log(`replaced ${hashOf(block.id)} (${block.kind === 'heading' ? 'its section' : block.kind}) in ${relFile(file)}`)
1085
+ break
1086
+ }
946
1087
  case 'archive':
947
1088
  case 'destroy': {
948
1089
  // a page that has done its job: its file leaves the pages, and its events leave the log (answers,
@@ -1016,17 +1157,14 @@ switch (cmd) {
1016
1157
  case 'edit': {
1017
1158
  // an agent's own event, changed in place: --data is merged into its data
1018
1159
  const eventId = positionals[0]
1019
- if (!eventId || !opts.data)
1020
- throw new Error("usage: workpad edit <event id> --data <json> (merged into the event's data)")
1160
+ const data = eventData()
1161
+ if (!eventId || data === undefined)
1162
+ throw new Error(
1163
+ "usage: workpad edit <event id> --data <json> | --file <file|-> | --text-file <file|-> (merged into the event's data)",
1164
+ )
1021
1165
  const proj = needProject()
1022
- let data: Record<string, unknown>
1023
- try {
1024
- data = JSON.parse(opts.data)
1025
- } catch {
1026
- throw new Error('--data must be a JSON object')
1027
- }
1028
- if (!data || typeof data !== 'object' || Array.isArray(data)) throw new Error('--data must be a JSON object')
1029
- console.log(JSON.stringify(editEvent(proj.eventsFile, eventId, data)))
1166
+ if (!data || typeof data !== 'object' || Array.isArray(data)) throw new Error('the data must be a JSON object')
1167
+ console.log(JSON.stringify(editEvent(proj.eventsFile, eventId, data as Record<string, unknown>)))
1030
1168
  break
1031
1169
  }
1032
1170
  case 'scroll': {
@@ -1184,9 +1322,21 @@ switch (cmd) {
1184
1322
  throw new Error(
1185
1323
  `name the forms to settle, or --all for every open one: open on ${p.page} ${p.open.length ? `are ${p.open.join(', ')}` : 'is none'}`,
1186
1324
  )
1325
+ // --replace-with: the form on the page becomes what was decided, in the same step. Made first,
1326
+ // so a form the page doesn't have settles nothing
1327
+ let replaced: string | null = null
1328
+ if (opts['replace-with'] !== undefined) {
1329
+ if (opts.all || named.length !== 1) throw new Error('--replace-with replaces one form: name it, without --all')
1330
+ const source = fs.readFileSync(p.file, 'utf8')
1331
+ replaced = setBlock(source, `form:${named[0]}`, readInput(opts['replace-with'], '--replace-with'))
1332
+ }
1187
1333
  const { forms, skipped } = settleForms(proj.eventsFile, p, opts.all ? 'all' : named, await whoAmI(proj))
1188
1334
  for (const { name, state } of skipped) console.error(`workpad: ${name} isn't open (${state}): left as it is`)
1189
1335
  console.log(forms.length ? `settled on ${p.page}: ${forms.join(', ')}` : `nothing to settle on ${p.page}`)
1336
+ if (replaced !== null) {
1337
+ fs.writeFileSync(p.file, replaced)
1338
+ console.log(`replaced the form ${named[0]} on ${p.page}`)
1339
+ }
1190
1340
  break
1191
1341
  }
1192
1342
  case 'hold': {
@@ -1241,7 +1391,9 @@ switch (cmd) {
1241
1391
  // coordinator (holdUnfollowed).
1242
1392
  const proj = needProject()
1243
1393
  const f = filter()
1244
- const agent = await whoAmI(proj)
1394
+ const { me: agent, session } = await whoAmIWithSession(proj)
1395
+ // what it wrote in its session, when WORKPAD_AGENT or --agent names it, is its own too
1396
+ const aliases = new Set(session ? [session] : [])
1245
1397
  if (opts.follow) throw new Error('listen runs on by itself: --wait stops at the first answer, --channel hands over to the channel')
1246
1398
  if (opts.wait && opts.channel) throw new Error('listen takes --wait or --channel, not both')
1247
1399
  if (opts.timeout && !opts.wait) throw new Error('--timeout goes with --wait')
@@ -1257,7 +1409,7 @@ switch (cmd) {
1257
1409
  }
1258
1410
  const entry = !f.page && isShared(proj) ? matchesEntries(readMachineConfig()!, proj.dir) : null
1259
1411
  if (entry) {
1260
- await entryListen(entry, f, agent)
1412
+ await entryListen(entry, f, agent, aliases)
1261
1413
  break
1262
1414
  }
1263
1415
  const isForAgent = await liveForAgent(proj)
@@ -1273,7 +1425,7 @@ switch (cmd) {
1273
1425
  // one line each; one handed out before and still not handled says so
1274
1426
  const print = (e: WpEvent, again: boolean) => console.log(JSON.stringify(again ? { ...e, again: true } : e))
1275
1427
  const at = () => needServer().catch(() => null)
1276
- const options = { batch: !!opts.wait, forAgent: isForAgent, agent }
1428
+ const options = { batch: !!opts.wait, forAgent: isForAgent, agent, aliases }
1277
1429
  if (opts.timeout && opts.wait)
1278
1430
  setTimeout(
1279
1431
  () => {
@@ -1325,19 +1477,20 @@ switch (cmd) {
1325
1477
  // comment. Waits skip what is appended here, so an agent does not hear its own events.
1326
1478
  const proj = needProject()
1327
1479
  if (!pageOpt || !opts.type)
1328
- throw new Error("usage: workpad append --page <page|file> --type <type> [--data '<json>']")
1329
- let data = {}
1330
- if (opts.data) {
1331
- try {
1332
- data = JSON.parse(opts.data)
1333
- } catch {
1334
- throw new Error('--data must be JSON, e.g. \'{"text":"…"}\'')
1335
- }
1336
- }
1480
+ throw new Error(
1481
+ "usage: workpad append --page <page|file> --type <type> [--data '<json>' | --file <file|->] [--text-file <file|->]",
1482
+ )
1483
+ const data = (eventData() ?? {}) as Record<string, unknown>
1484
+ // an event without the data its type requires shows nowhere (a chat message with no text):
1485
+ // most often its JSON was lost to the shell's quoting
1486
+ const refused = refusal(opts.type, data as Record<string, unknown>, (await projectConfig(proj)).requires)
1487
+ if (refused)
1488
+ throw new Error(
1489
+ `${refused}\nNothing was appended. Pass it so the shell's quoting can't lose it: the JSON in a file with --file message.json, or the text on standard input with --text-file -`,
1490
+ )
1491
+ const { me, session } = await whoAmIWithSession(proj)
1337
1492
  console.log(
1338
- JSON.stringify(
1339
- appendEvent(proj.eventsFile, { page: pageId(proj, pageOpt), type: opts.type, data }, 'cli', await whoAmI(proj)),
1340
- ),
1493
+ JSON.stringify(appendEvent(proj.eventsFile, { page: pageId(proj, pageOpt), type: opts.type, data }, 'cli', me, session)),
1341
1494
  )
1342
1495
  break
1343
1496
  }
@@ -1444,6 +1597,7 @@ switch (cmd) {
1444
1597
  return { base, version: String(health?.version ?? 'unknown') }
1445
1598
  },
1446
1599
  version: VERSION,
1600
+ agent: me,
1447
1601
  // the API, at the project's server, started at its first call
1448
1602
  wp: client(async () => probe(await ensureServer()), { token: projectToken(project.wp), agent: me }),
1449
1603
  page: page => pageId(project, page),
@@ -1454,10 +1608,11 @@ switch (cmd) {
1454
1608
  ...options,
1455
1609
  forAgent: await liveForAgent(project, options?.signal),
1456
1610
  }),
1457
- listen: (page, { agent = null } = {}) =>
1611
+ listen: (page, { agent = null, signal } = {}) =>
1458
1612
  listen({
1459
1613
  at: () => ensureServer().catch(() => null),
1460
1614
  query: { page: pageId(project, page), ...(agent ? { agent } : {}) },
1615
+ signal,
1461
1616
  }),
1462
1617
  unfollowed: (onEvent, { agent = null, mark, signal } = {}) =>
1463
1618
  holdUnfollowed(project, { at: () => ensureServer().catch(() => null), agent, mark, signal, onEvent }),
@@ -1504,7 +1659,8 @@ async function channelListen(proj: Project, who: string | null) {
1504
1659
  const handled = handledIds(events)
1505
1660
  const received = receivedIds(events)
1506
1661
  const skipped = events.filter(e => {
1507
- if (fromReader(e) || !e.by || e.by === agent || !isForAgent(e.type) || handled.has(e.id)) return false
1662
+ if (fromReader(e) || !e.by || e.by === agent || e.session === agent || !isForAgent(e.type) || handled.has(e.id))
1663
+ return false
1508
1664
  if (!received.has(e.id)) return false
1509
1665
  const since = channelSince(events, agent, e.page)
1510
1666
  if (!since) return false
@@ -1674,7 +1830,7 @@ async function channelUnfollowed(proj: Project, agent: string | null) {
1674
1830
  * Without a shared server running it waits for one, as any listen does. Projects that appear
1675
1831
  * meanwhile are followed too.
1676
1832
  */
1677
- async function entryListen(entry: string, f: EventFilter, agent: string | null) {
1833
+ async function entryListen(entry: string, f: EventFilter, agent: string | null, aliases: ReadonlySet<string>) {
1678
1834
  const file = machineServerFile()
1679
1835
  // across projects as they come: with --wait it stops at the first
1680
1836
  const count = opts.wait ? 1 : Infinity
@@ -1705,7 +1861,7 @@ async function entryListen(entry: string, f: EventFilter, agent: string | null)
1705
1861
  console.log(JSON.stringify({ ...e, project: p.dir, url: `${origin}${p.base}/${page(e.page)}` }))
1706
1862
  if (++total >= count) done.abort()
1707
1863
  },
1708
- { forAgent: forAgent(handedOut), agent, signal: AbortSignal.any([signal, done.signal]) },
1864
+ { forAgent: forAgent(handedOut), agent, aliases, signal: AbortSignal.any([signal, done.signal]) },
1709
1865
  ),
1710
1866
  )
1711
1867
  })