dsh-work-fish 0.1.0 → 0.1.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.
package/README.md CHANGED
@@ -24,15 +24,9 @@ No install script ships with the package on purpose: the agent on that machine r
24
24
 
25
25
  After install the workbench is created at `%USERPROFILE%\.dsh\work-fish` and holds the task board, memory and rules. To keep it elsewhere, point the `WF_HOME` environment variable at the target directory.
26
26
 
27
- ## The task panel and the desktop pet
27
+ ## The task panel
28
28
 
29
- Work Fish draws no character of its own: the desktop pet belongs to `dsh-pet`, which owns the sprite, the physics, the right-click menu and its settings page. Work Fish adds the ledger side.
30
-
31
- - **Task panel** — a floating card with four tabs (进行中 / 待办 / 等待 / 今日), a button per row (开始 / 推进 / 完成 / 暂停 / 催一下 / 继续) and an inline composer. Open it from the 「🐋 任务」 button in the conversation header, or from the 「大肥鱼」 group in the desktop pet's right-click menu.
32
- - **Pet menu** — 「打开任务板」「开始下一件」「完成进行中」 are registered on the pet at start-up; a click writes through the same `wf-task` CLI the assistant uses.
33
- - **Work status** — the top in-progress row is pushed to the pet as its task line, and a newly overdue row earns one short bubble.
34
-
35
- `dsh-pet` is optional: without it the panel still works from the header button, and `/wf/info` reports the pet as disconnected.
29
+ A floating card with four tabs (进行中 / 待办 / 等待 / 今日), a button per row (开始 / 推进 / 完成 / 暂停 / 催一下 / 继续) and an inline composer. Open it from the 「🐋 任务」 button in the conversation header.
36
30
 
37
31
  ## Usage
38
32
 
@@ -52,10 +52,8 @@ port; the change list is history, not a summary.
52
52
 
53
53
  | Component | Licence | Where |
54
54
  |---|---|---|
55
- | `dsh-pet` desktop pet (optional) | Code MIT; character artwork may not be used commercially, derivative works must credit | `github.com/PC2005-cloud/dsh-pet` |
56
55
  | ComfyUI (optional, H3 video) | GPL-3.0 | `github.com/comfyanonymous/ComfyUI` |
57
56
  | MiniMax H3 weights (downloaded by the user) | See upstream | `comfy.org/minimax/license` |
58
57
 
59
- None of these ship inside this package. `core/pet-bridge.mjs` calls `dsh-pet`'s own HTTP routes and
60
- contains none of its code or artwork; the `comfyui-h3` skill installs ComfyUI on the user's machine
61
- rather than bundling it.
58
+ None of these ship inside this package: the `comfyui-h3` skill installs ComfyUI on the user's
59
+ machine, and the model weights are downloaded there rather than bundled.
package/board/client.js CHANGED
@@ -1,10 +1,8 @@
1
1
  /**
2
2
  * Browser half of Work Fish (`dsh-work-fish` client entry).
3
3
  *
4
- * One surface: the task panel. The character that used to stand next to it now
5
- * belongs to `dsh-pet` — that plugin owns the sprite, the physics, the
6
- * right-click menu and the settings page — so this module draws no pet at all.
7
- * What is left is the thing only Work Fish can show: the ledger.
4
+ * One surface: the task panel. It draws no character of its own; what it shows
5
+ * is the thing only Work Fish can show: the ledger.
8
6
  *
9
7
  * Three mounts:
10
8
  *
@@ -15,9 +13,8 @@
15
13
  * by its own header;
16
14
  * - `settings.section` — the persona editor and read-only host facts.
17
15
  *
18
- * The panel is opened from either place: the header button, or the 「大肥鱼」
19
- * group in the desktop pet's right-click menu, which reaches this half through
20
- * the host's `GET /wf/events` long poll.
16
+ * The panel opens from the header button. `GET /wf/events` is the long poll that
17
+ * tells it to refresh after a write elsewhere moved the ledger.
21
18
  *
22
19
  * @module dsh-work-fish/client
23
20
  */
@@ -606,11 +603,11 @@ window.__ModuleLoader__.load({
606
603
  }, [open, load])
607
604
 
608
605
  /**
609
- * Host events: the pet's menu asks for the panel, or a write elsewhere moved
610
- * the ledger. The first poll subscribes from "now", so remounting the panel
611
- * cannot replay a click that happened before it existed; after that the
612
- * cursor follows the host's sequence — zero included, because a restarted
613
- * host starts its sequence over.
606
+ * Host events: a write elsewhere moved the ledger. The first poll
607
+ * subscribes from "now", so remounting the panel cannot replay an event
608
+ * that happened before it existed; after that the cursor follows the
609
+ * host's sequence — zero included, because a restarted host starts its
610
+ * sequence over.
614
611
  */
615
612
  React.useEffect(() => {
616
613
  let alive = true
@@ -629,7 +626,6 @@ window.__ModuleLoader__.load({
629
626
  if (body?.ok !== true) throw new Error(body?.message ?? 'events')
630
627
  if (typeof body.since === 'number') since = body.since
631
628
  for (const event of Array.isArray(body.events) ? body.events : []) {
632
- if (event?.type === 'open') setBoardOpen(true)
633
629
  if (event?.type === 'changed') void load()
634
630
  }
635
631
  } catch {
@@ -833,10 +829,8 @@ window.__ModuleLoader__.load({
833
829
  }
834
830
 
835
831
  /**
836
- * Settings → 大肥鱼: the persona editor plus read-only host facts.
837
- *
838
- * The pet's own preferences (size, physics, notifications) live in
839
- * `dsh-pet`'s settings page now; this section only owns what Work Fish owns.
832
+ * Settings → 大肥鱼: the persona editor plus read-only host facts — only
833
+ * what Work Fish itself owns.
840
834
  */
841
835
  function WorkFishSettings() {
842
836
  const [info, setInfo] = React.useState(null)
@@ -950,10 +944,9 @@ window.__ModuleLoader__.load({
950
944
  const factsCard = h(
951
945
  'section',
952
946
  { className: 'jps-card' },
953
- h('h3', { className: 'jps-title' }, '台账与桌宠'),
947
+ h('h3', { className: 'jps-title' }, '台账'),
954
948
  infoRow('台账', info?.ledger?.path ?? '—', '唯一事实来源,面板与 CLI 读写同一份'),
955
- infoRow('桌宠', info?.pet?.connected === true ? `已连上 ${info.pet.petId}` : info?.pet?.reason || '未连上', '形象与菜单由 dsh-pet 提供'),
956
- infoRow('写入', info?.allowWrites === true ? '允许' : '已关闭', '关掉后桌宠菜单与面板都只能读'),
949
+ infoRow('写入', info?.allowWrites === true ? '允许' : '已关闭', '关掉后面板只能读'),
957
950
  )
958
951
 
959
952
  const personaCard = h(
package/cordis.patch.yml CHANGED
@@ -1,13 +1,12 @@
1
- # Work Fish bundle: one preset plus the ledger host that feeds the dsh-pet pet.
1
+ # Work Fish bundle: one preset plus the ledger host behind the task panel.
2
2
  #
3
3
  # Three rows are inserted:
4
4
  # 1. `preset-work-fish` — @deepseek-ai/dsh-agent-preset declaration; mounts the
5
5
  # persona / tools / skills only in sessions that select this preset;
6
6
  # 2. `work-fish-host` — the ledger host (`core/index.mjs`), a global row:
7
- # installing this bundle seeds the workbench, serves `/wf/*` and pushes the
8
- # current task to the desktop pet regardless of the selected preset. The
9
- # browser half (task panel) is served from the same package through
10
- # `package.json` → `dsh.client`. The character itself belongs to `dsh-pet`.
7
+ # installing this bundle seeds the workbench and serves `/wf/*` regardless of
8
+ # the selected preset. The browser half (task panel) is served from the same
9
+ # package through `package.json` → `dsh.client`.
11
10
  # 3. `work-fish-approve` — answers escalation approvals on the user's behalf. Three
12
11
  # kinds of root are trusted: this bundle's own package directory (plus, in a dev
13
12
  # checkout, the checkout that holds `out/`), the workbench directory itself
@@ -11,9 +11,8 @@
11
11
  * Skills are not copied either — `core/skills.mjs` registers them from the
12
12
  * package at activation.
13
13
  *
14
- * Seeding used to ride along with the desktop pet; since the pet moved to
15
- * `dsh-pet`, the host entry (`core/index.mjs`) calls this directly, so a fresh
16
- * install still gets a workbench without any character being drawn.
14
+ * The host entry (`core/index.mjs`) calls this once per start, so a fresh install
15
+ * gets a workbench with no extra step.
17
16
  *
18
17
  * @module dsh-work-fish/core/bootstrap
19
18
  */
package/core/events.mjs CHANGED
@@ -1,9 +1,9 @@
1
1
  /**
2
- * Panel event bus: the bridge pushes, `GET /wf/events` drains.
2
+ * Panel event bus: the host pushes, `GET /wf/events` drains.
3
3
  *
4
4
  * The task panel lives in the browser while the events that should move it are
5
- * detected by the host (a right-click menu item on the `dsh-pet` character, or
6
- * a ledger write performed on its behalf). Polling `/wf/tasks` every second
5
+ * detected by the host (a ledger write from the panel or from `wf-task` on the
6
+ * CLI). Polling `/wf/tasks` every second
7
7
  * would answer "did anything change" by re-reading the ledger each time, so the
8
8
  * host keeps a tiny in-memory sequence instead and the client long-polls it.
9
9
  *
@@ -28,7 +28,7 @@ const waiters = new Set()
28
28
 
29
29
  /**
30
30
  * Record one event and wake every pending poll.
31
- * @param {'open' | 'changed'} type what the panel should do.
31
+ * @param {'changed'} type what the panel should do.
32
32
  * @returns {number} the sequence number assigned.
33
33
  */
34
34
  export function pushEvent(type) {
@@ -43,7 +43,7 @@ export function pushEvent(type) {
43
43
  * Read every event newer than a cursor, optionally waiting for one.
44
44
  *
45
45
  * `since === null` means "subscribe from now": a freshly mounted panel must not
46
- * see the `open` of a click that happened before it existed. A cursor from a
46
+ * see a change that happened before it existed. A cursor from a
47
47
  * previous process (larger than the current sequence) is reported as `reset`
48
48
  * and also starts from now, so a restarted host cannot silently swallow the
49
49
  * next real event.
package/core/index.mjs CHANGED
@@ -1,19 +1,15 @@
1
1
  /**
2
2
  * Host half of the Work Fish bundle (`dsh-work-fish` root entry).
3
3
  *
4
- * Work Fish no longer draws a character of its own: the desktop pet belongs to
5
- * `dsh-pet`, which owns the sprite, the physics and the right-click menu. This
6
- * half keeps what is Work Fish's own — the task ledger — and offers it to three
7
- * consumers under one prefix:
4
+ * This half keeps what is Work Fish's own — the task ledger — and offers it to
5
+ * two consumers under one prefix:
8
6
  *
9
7
  * 1. the task panel's payload (`GET /wf/tasks`), read from `tasks/index.md`
10
8
  * on every request — never cached, so the panel can never disagree with
11
9
  * the file;
12
10
  * 2. the workbench itself: first-run seeding, the persona store, diagnostics
13
- * (`/wf/info`, `/wf/client-report`);
14
- * 3. `./pet-bridge.mjs`, which feeds the current task to `dsh-pet` and turns
15
- * the pet's menu items into ledger writes, plus `GET /wf/events`, the
16
- * long-poll that tells the panel when to open or refresh.
11
+ * (`/wf/info`, `/wf/client-report`), plus `GET /wf/events`, the long-poll
12
+ * that tells the panel when to open or refresh.
17
13
  *
18
14
  * Writes are CAS-guarded by `expectRev` and go through `tools/wf-task.mjs`, the
19
15
  * same CLI path the assistant uses; there is no second ledger implementation.
@@ -29,8 +25,7 @@ import { execFile } from 'node:child_process'
29
25
 
30
26
  import { buildReport } from './report.mjs'
31
27
  import { bootstrap } from './bootstrap.mjs'
32
- import { waitEvents } from './events.mjs'
33
- import { startPetBridge } from './pet-bridge.mjs'
28
+ import { pushEvent, waitEvents } from './events.mjs'
34
29
 
35
30
  /** Plugin name used by the loader / Cordis row. */
36
31
  export const name = 'work-fish'
@@ -285,17 +280,29 @@ export function apply(ctx, config) {
285
280
  }
286
281
  }
287
282
 
288
- // The character belongs to `dsh-pet`; this is the one place that talks to it.
289
- const bridge = startPetBridge({
290
- options,
291
- logger: ctx.logger,
292
- getOrigin: serverOrigin,
293
- runCli,
294
- buildReport,
295
- })
296
- // The bridge runs its own timers and long poll: hand its shutdown to the
297
- // row's lifetime, or a reloaded row leaves a second poller behind.
298
- web.effect(() => () => bridge.stop(), 'wf: pet bridge')
283
+ /** The ledger this host serves. */
284
+ const ledgerPath = `${options.homeDir}/tasks/index.md`
285
+
286
+ /**
287
+ * Watch the ledger's modification time: a write from `wf-task` on the CLI
288
+ * happens outside this process, so the file is the only way an open panel
289
+ * hears about it before its own slow poll comes round.
290
+ */
291
+ let ledgerStamp = ''
292
+ const watchLedger = setInterval(() => {
293
+ let stamp
294
+ try {
295
+ stamp = String(fs.statSync(ledgerPath).mtimeMs)
296
+ } catch {
297
+ return
298
+ }
299
+ if (ledgerStamp !== '' && stamp !== ledgerStamp) pushEvent('changed')
300
+ ledgerStamp = stamp
301
+ }, 4000)
302
+ // Never hold the process open on this timer's account; the effect below is
303
+ // what actually stops it when the row unloads.
304
+ watchLedger.unref?.()
305
+ web.effect(() => () => clearInterval(watchLedger), 'wf: ledger watch')
299
306
 
300
307
  /**
301
308
  * Register one exact route, containing its failure to that route.
@@ -335,7 +342,6 @@ export function apply(ctx, config) {
335
342
  `${ROUTE_PREFIX}/info`,
336
343
  'GET',
337
344
  async (_request, response) => {
338
- const ledgerPath = `${options.homeDir}/tasks/index.md`
339
345
  let ledgerReadable = false
340
346
  try {
341
347
  ledgerReadable = fs.statSync(ledgerPath).isFile()
@@ -352,7 +358,6 @@ export function apply(ctx, config) {
352
358
  timeZone: options.timeZone,
353
359
  allowWrites: options.allowWrites,
354
360
  ledger: { path: ledgerPath, readable: ledgerReadable },
355
- pet: bridge.status(),
356
361
  client: { reports: clientReports.slice(-10) },
357
362
  })
358
363
  },
@@ -381,7 +386,7 @@ export function apply(ctx, config) {
381
386
  'POST',
382
387
  async (request, response) => {
383
388
  if (!options.allowWrites) {
384
- writeJson(response, 403, { ok: false, code: 'writes-disabled', message: '桌宠写台账已在配置里关闭' })
389
+ writeJson(response, 403, { ok: false, code: 'writes-disabled', message: '写台账已在配置里关闭' })
385
390
  return
386
391
  }
387
392
  if (!admitted(request, serverOrigin())) {
@@ -413,6 +418,9 @@ export function apply(ctx, config) {
413
418
  : result?.verdict === 'MISSING'
414
419
  ? 404
415
420
  : 400
421
+ // Broadcast at once: the file watcher would find the same change
422
+ // within its interval, but the panel that made it is already open.
423
+ if (result?.ok === true) pushEvent('changed')
416
424
  writeJson(response, status, result ?? { ok: false, code: 'empty', message: '写入没有返回结果' })
417
425
  } catch (error) {
418
426
  const code = /** @type {{code?: string}} */ (error)?.code
@@ -428,13 +436,12 @@ export function apply(ctx, config) {
428
436
  )
429
437
  }
430
438
 
431
- /** Every write goes through `wf-task`, tagged so the event log shows 桌宠. */
439
+ /** Every write goes through `wf-task`, so the ledger and its event log agree. */
432
440
  const cli = (command, body, extra = []) => runCli([
433
441
  command,
434
442
  '--task', body.task,
435
443
  '--expect-rev', String(body.expectRev),
436
444
  ...extra,
437
- '--source', '桌宠',
438
445
  ])
439
446
  const move = (body, to, extra = []) => cli('move', body, ['--to', to, ...extra])
440
447
  const passed = (value, flag) => (value === undefined || value === null || value === '' ? [] : [flag, String(value)])
package/locale/en.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "meta": {
3
- "title": "Work Fish",
3
+ "title": "dsh-work-fish",
4
4
  "description": "Standing work assistant: turns a request into an acceptance-checkable task card, tracks it on a task board with deadlines and next steps, and files deliverables under the workbench's out/ directory. Unofficial plugin, not affiliated with DeepSeek.",
5
5
  "detail": "docs/DETAIL.md"
6
6
  }
package/locale/zh.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "meta": {
3
- "title": "大肥鱼",
3
+ "title": "dsh-work-fish",
4
4
  "description": "常驻的工作助手:先把需求写成可验收的任务卡,在任务板上跟踪截止与下一步,交付物落到工作台的 out/ 目录。非官方插件,与 DeepSeek 官方无关。",
5
5
  "detail": "docs/DETAIL.zh.md"
6
6
  }
package/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "dsh-work-fish",
3
- "version": "0.1.0",
3
+ "version": "0.1.1",
4
4
  "license": "MIT",
5
- "description": "Unofficial Work Fish plugin for DeepSeek Harness: task setup, task board tracking and delivery, with a task panel fed to the dsh-pet desktop pet. Not affiliated with DeepSeek.",
5
+ "description": "Unofficial Work Fish plugin for DeepSeek Harness: task setup, task board tracking and delivery, with a floating task panel. Not affiliated with DeepSeek.",
6
6
  "type": "module",
7
7
  "main": "./core/index.mjs",
8
8
  "exports": {
@@ -34,7 +34,7 @@ A candidate is an unproven hypothesis; a rule is a proven conclusion. **No evide
34
34
 
35
35
  - Sample 5 U rules a month (plugin G rules are read-only; sample them only for the weekly report): "any applicable case in the last 30 days?" Two consecutive "no" → dormancy candidate.
36
36
  - Citation counts are hints only, never a criterion.
37
- - After user sign-off, move it into the dormant section of `memory/user-rules.md` — text kept, ID never reused.
37
+ - After user sign-off, move it into the dormant section of `rules/user-rules.md` — text kept, ID never reused.
38
38
  - Three consecutive months with net growth > 2 rules/month → run dormancy before adding more.
39
39
 
40
40
  ## 5. Five elements of a promoted rule (none optional)
@@ -56,4 +56,4 @@ Self-check: an assistant that never did the original work can follow the rule as
56
56
 
57
57
  ## Pool
58
58
 
59
- The live queue is the **workbench's** `rules/experience-pool.md` (seeded from `template/memory/pool/experience.md`): this file is read-only and carries the rules only. Read the queue there and add rows there, never here.
59
+ The live queue is the **workbench's** `memory/pool/experience.md` (seeded from `template/memory/pool/experience.md`): this file is read-only and carries the rules only. Read the queue there and add rows there, never here.
@@ -46,7 +46,7 @@ Inside the package (read-only for the user): `board/` (browser half, the task pa
46
46
  |---|---|---|---|
47
47
  | `AGENTS.md` | Start-up and close-out procedure, coordination protocol, task-board conventions | Maintainer | Every session (auto-loaded) |
48
48
  | `rules/INDEX.md` | Generated pointer to the plugin rule files below | Bootstrap | Every session |
49
- | `rules/experience-pool.md` | Your undecided experience, queue only | Assistant | Close-out, weekly review |
49
+ | `memory/pool/experience.md` | Your undecided experience, queue only | Assistant | Close-out, weekly review |
50
50
  | plugin `file-rules.md` | This file | Maintainer (release) | Placing files |
51
51
  | plugin `task-rules.md` | Task board: admission, row shape, ceilings, retention, commit discipline | Maintainer (release) | Before any board write |
52
52
  | plugin `memory-rules.md` | Memory layers, writing and cleaning | Maintainer (release) | Maintaining memory |
@@ -54,7 +54,7 @@ Inside the package (read-only for the user): `board/` (browser half, the task pa
54
54
  | `tasks/index.md` | Single source of truth for tasks | Assistant via `<tools>/wf-task.mjs` | Every session starts here |
55
55
  | `memory/user-profile.md` | Who the user is, role, stakeholders, goals | Assistant, incrementally | When the task needs context |
56
56
  | `memory/preferences.md` | Output preferences, tone, taboos | Assistant, incrementally | Before producing a deliverable |
57
- | `memory/user-rules.md` | Your own promoted rules (U numbers); wins over the plugin baseline | Assistant, incrementally | When a rule conflicts with the plugin baseline |
57
+ | `rules/user-rules.md` | Your own promoted rules (U numbers); wins over the plugin baseline | Assistant, incrementally | When a rule conflicts with the plugin baseline |
58
58
  | `memory/projects/README.md` | One line per project | Assistant | Every session (index) |
59
59
  | `memory/projects/<code>/profile.md` | Project facts, rules, pitfalls (stable layer) | Assistant | When the task concerns that project |
60
60
  | `memory/projects/<code>/state.md` | Branch, uncommitted, current mainline (volatile layer) | Assistant, overwritten at close-out | Same |
@@ -7,7 +7,7 @@
7
7
 
8
8
  - **The workbench is the only write point**: `<workbench>/memory/`. Project directories keep no personal memory.
9
9
  - `AGENTS.md`, `docs/` and `openspec/` inside a project are **team assets**: never migrate or rewrite them. Team assets describe how the project is built; personal memory describes how I work on it.
10
- - Layers: `code-rules.md` (plugin engineering baseline, read-only), `memory/user-rules.md` (your own promoted rules, U numbers), this file (how memory is written and cleaned), `memory/preferences.md` (output and reporting taste), `memory/projects/<code>/` (project-specific facts).
10
+ - Layers: `code-rules.md` (plugin engineering baseline, read-only), `rules/user-rules.md` (your own promoted rules, U numbers), this file (how memory is written and cleaned), `memory/preferences.md` (output and reporting taste), `memory/projects/<code>/` (project-specific facts).
11
11
 
12
12
  ## 2. Three layers (knowing all projects without hoarding raw text)
13
13
 
@@ -44,7 +44,7 @@ Context budget: index plus one project's profile and state ≤ 20 KB; even a mul
44
44
 
45
45
  ## 4. Promotion
46
46
 
47
- - A rule used by ≥2 projects, or unrelated to any project (comment style, Git operations, line endings, verification), is **promoted** out of a project profile: engineering rules go to `memory/user-rules.md` (U numbers; the plugin's `code-rules.md` only changes with a release), output taste to `memory/preferences.md`, memory upkeep here. Leave the old number **empty and unused** in the profile, with a one-line pointer.
47
+ - A rule used by ≥2 projects, or unrelated to any project (comment style, Git operations, line endings, verification), is **promoted** out of a project profile: engineering rules go to `rules/user-rules.md` (U numbers; the plugin's `code-rules.md` only changes with a release), output taste to `memory/preferences.md`, memory upkeep here. Leave the old number **empty and unused** in the profile, with a one-line pointer.
48
48
  - Distilling rules from task experience (candidate → pool → promotion → dormancy) is described in [experience-pool.md](experience-pool.md); this section only answers where a distilled rule lands.
49
49
  - A project profile keeps only what is specific to that project (entry points, layout, pipelines, commands, pitfalls). General rules are not repeated per project.
50
50
  - Contracts or acceptance criteria a team must keep belong in the project's `openspec/specs/`, not in personal memory.
@@ -397,7 +397,7 @@ function decideTaskUnlogged(doc, options = {}) {
397
397
  }
398
398
 
399
399
  export function newTask(file, options = {}) {
400
- const { title, accept, relation, section = '待办', priority = '中', deadline = '未定', next = '确认验收后开工', note = '依据:用户交办', mode = null, eventsFile, source } = options
400
+ const { title, accept, relation, section = '待办', priority = '中', deadline = '未定', next = '确认验收后开工', note = '依据:用户交办', mode = null, eventsFile } = options
401
401
  if (!title) return { ok: false, code: 4, verdict: 'ERROR', message: 'new 需要 task 标题' }
402
402
  if (!accept) return { ok: false, code: 4, verdict: 'ERROR', message: 'new 需要 accept 验收' }
403
403
  const normalized = normalizeRelation(relation)
@@ -420,7 +420,7 @@ export function newTask(file, options = {}) {
420
420
  : [id, title, accept, priority, deadline, next, token]
421
421
  appendRow(doc, section, cells)
422
422
  saveLedger(file, renderLedger(doc))
423
- if (eventsFile) appendEvent(eventsFile, { action: 'new', task: id, rev: 1, relation: normalized, section, title, ...(source === undefined ? {} : { source }) })
423
+ if (eventsFile) appendEvent(eventsFile, { action: 'new', task: id, rev: 1, relation: normalized, section, title })
424
424
  return { ok: true, verdict: 'ACC', task: id, rev: 1, relation: normalized, section, mode }
425
425
  })
426
426
  }
@@ -471,7 +471,7 @@ export function bumpTask(file, options = {}) {
471
471
  cells[noteIndex] = withToken(rest, found.note.rev + 1, relationToUse)
472
472
  section.rows[found.index] = cells
473
473
  saveLedger(file, renderLedger(doc))
474
- if (eventsFile) appendEvent(eventsFile, { action: 'bump', task, fromRev: found.note.rev, toRev: found.note.rev + 1, ...(options.source === undefined ? {} : { source: options.source }) })
474
+ if (eventsFile) appendEvent(eventsFile, { action: 'bump', task, fromRev: found.note.rev, toRev: found.note.rev + 1 })
475
475
  return { ok: true, verdict: 'ACC', task, rev: found.note.rev + 1, relation: relationToUse }
476
476
  })
477
477
  }
@@ -479,7 +479,7 @@ export function bumpTask(file, options = {}) {
479
479
  /**
480
480
  * Move one active row to another section of the ledger.
481
481
  *
482
- * Used by the Work Fish pet's task bubble (start / pause / finish / wait) and by
482
+ * Used by the task panel's per-row buttons (start / pause / finish / wait) and by
483
483
  * the CLI's `move` command. The move is a CAS write: the caller passes the
484
484
  * revision it read, and a mismatch returns STALE without touching the file.
485
485
  *
@@ -499,12 +499,11 @@ export function bumpTask(file, options = {}) {
499
499
  * @param {string} [options.chase] when to chase (等待他人).
500
500
  * @param {string} [options.note] extra text appended to the note.
501
501
  * @param {string} [options.marker] action label appended to the note.
502
- * @param {string} [options.source] writer label, default 桌宠.
503
502
  * @param {string} [options.eventsFile] event log path.
504
503
  * @returns {object} ACC / STALE / MISSING / COMPLETED / ERROR.
505
504
  */
506
505
  export function moveTask(file, options = {}) {
507
- const { task, expectRev, to, relation, priority, deadline, next, result, deliverable, who, what, chase, note, marker, source = '桌宠', eventsFile } = options
506
+ const { task, expectRev, to, relation, priority, deadline, next, result, deliverable, who, what, chase, note, marker, eventsFile } = options
508
507
  if (!task) return { ok: false, code: 4, verdict: 'ERROR', message: 'move 需要 task' }
509
508
  if (!Number.isInteger(expectRev)) return { ok: false, code: 4, verdict: 'ERROR', message: 'move 需要 expectRev' }
510
509
  const targets = ['进行中', '待办', '等待他人', '已完成']
@@ -540,7 +539,7 @@ export function moveTask(file, options = {}) {
540
539
  const sourceNext = from === '待办' || from === '进行中' ? cells[5] : ''
541
540
  const rest = found.note.rest
542
541
  const labels = { 进行中: '开始', 待办: '暂停', 等待他人: '等待', 已完成: '完成' }
543
- const stamp = `${source} ${localDate()} ${localTime()} ${marker || labels[to]}`
542
+ const stamp = `${localDate()} ${localTime()} ${marker || labels[to]}`
544
543
  const newRest = `${rest ? `${rest} · ` : ''}${stamp}${note ? ` ${note}` : ''}`
545
544
  const nextRev = found.note.rev + 1
546
545
  let targetCells
@@ -582,7 +581,6 @@ export function moveTask(file, options = {}) {
582
581
  to,
583
582
  fromRev: found.note.rev,
584
583
  toRev: to === '已完成' ? 0 : nextRev,
585
- source,
586
584
  })
587
585
  }
588
586
  return { ok: true, verdict: 'ACC', task, from, to, rev: to === '已完成' ? 0 : nextRev, relation: relationToUse ?? null }
@@ -600,12 +598,11 @@ export function moveTask(file, options = {}) {
600
598
  * @param {string} options.task task id.
601
599
  * @param {number} options.expectRev revision the caller read.
602
600
  * @param {string} options.reason why the row leaves the board.
603
- * @param {string} [options.source] writer label, default 桌宠.
604
601
  * @param {string} [options.eventsFile] event log path.
605
602
  * @returns {object} ACC / STALE / MISSING / ERROR.
606
603
  */
607
604
  export function dropTask(file, options = {}) {
608
- const { task, expectRev, reason, source = '桌宠', eventsFile } = options
605
+ const { task, expectRev, reason, eventsFile } = options
609
606
  if (!task) return { ok: false, code: 4, verdict: 'ERROR', message: 'drop 需要 task' }
610
607
  if (!Number.isInteger(expectRev)) return { ok: false, code: 4, verdict: 'ERROR', message: 'drop 需要 expectRev' }
611
608
  const why = String(reason ?? '').trim()
@@ -643,7 +640,7 @@ export function dropTask(file, options = {}) {
643
640
  )
644
641
  }
645
642
  fs.appendFileSync(archiveFile, `${joinRow([task, cells[1] ?? '', sectionName, why, stamp, cells.slice(2).join(' / ')])}\n`, 'utf8')
646
- if (eventsFile) appendEvent(eventsFile, { action: 'drop', task, from: sectionName, reason: why, source })
643
+ if (eventsFile) appendEvent(eventsFile, { action: 'drop', task, from: sectionName, reason: why })
647
644
  return { ok: true, verdict: 'ACC', task, from: sectionName, archive: archiveFile }
648
645
  })
649
646
  }
@@ -651,8 +648,8 @@ export function dropTask(file, options = {}) {
651
648
  /**
652
649
  * Append one progress line to an active row and bump its revision.
653
650
  *
654
- * The note keeps its `[rN][relation]` token; the new text is appended with a
655
- * timestamped writer label, so the ledger records who advanced the task.
651
+ * The note keeps its `[rN][relation]` token; the new text is appended after a
652
+ * timestamp, so every progress line is dated in the ledger.
656
653
  *
657
654
  * @param {string} file ledger path.
658
655
  * @param {object} options progress options.
@@ -660,12 +657,11 @@ export function dropTask(file, options = {}) {
660
657
  * @param {number} options.expectRev revision the caller read.
661
658
  * @param {string} options.text progress sentence.
662
659
  * @param {string} [options.next] replacement next step.
663
- * @param {string} [options.source] writer label, default 桌宠.
664
660
  * @param {string} [options.eventsFile] event log path.
665
661
  * @returns {object} ACC / STALE / MISSING / COMPLETED / ERROR.
666
662
  */
667
663
  export function progressTask(file, options = {}) {
668
- const { task, expectRev, text, next, source = '桌宠', eventsFile } = options
664
+ const { task, expectRev, text, next, eventsFile } = options
669
665
  if (!task) return { ok: false, code: 4, verdict: 'ERROR', message: 'progress 需要 task' }
670
666
  if (!Number.isInteger(expectRev)) return { ok: false, code: 4, verdict: 'ERROR', message: 'progress 需要 expectRev' }
671
667
  const addition = String(text ?? '').trim()
@@ -691,7 +687,7 @@ export function progressTask(file, options = {}) {
691
687
  const section = found.section
692
688
  const noteIndex = section.header.length - 1
693
689
  const rest = found.note.rest
694
- const stamp = `${source} ${localDate()} ${localTime()}`
690
+ const stamp = `${localDate()} ${localTime()}`
695
691
  const newRest = `${rest ? `${rest} · ` : ''}${stamp} ${addition}`
696
692
  const cells = found.cells.slice()
697
693
  cells[noteIndex] = withToken(newRest, found.note.rev + 1, relation)
@@ -705,7 +701,6 @@ export function progressTask(file, options = {}) {
705
701
  fromRev: found.note.rev,
706
702
  toRev: found.note.rev + 1,
707
703
  text: addition,
708
- source,
709
704
  })
710
705
  }
711
706
  return { ok: true, verdict: 'ACC', task, rev: found.note.rev + 1, text: addition }
@@ -20,7 +20,7 @@ import { join, sep } from 'node:path'
20
20
  import { loadLedger } from './lib/taskboard.mjs'
21
21
  import { resolveWorkHome } from './lib/paths.mjs'
22
22
 
23
- const POOL_PATH = 'rules/experience-pool.md'
23
+ const POOL_PATH = 'memory/pool/experience.md'
24
24
  const RULES_PATH = 'rules/code-rules.md'
25
25
  const LEDGER_PATH = 'tasks/index.md'
26
26
  const EVENTS_PATH = '.tmp/ledger-events.jsonl'
@@ -30,7 +30,7 @@ const CLOSED_STATUS = ['已提升', '未成规则']
30
30
  // 这几份文档里出现的是设计目标名或在举反例,不是条款引用;计入会误算成「在用」(该提示已停用:条款去编号)
31
31
  const CITATION_SKIP_FILES = new Set([
32
32
  RULES_PATH,
33
- 'rules/experience-pool.md',
33
+ 'memory/pool/experience.md',
34
34
  '设计方案.md',
35
35
  '记账监督机制设计方案.md',
36
36
  '经验提炼与量化设计方案.md',
@@ -61,13 +61,11 @@ function alert(scene) {
61
61
  function sections(scene) {
62
62
  const over = scene === 'warn'
63
63
 
64
- // 桌面偏好(尺寸、物理、通知)已归 dsh-pet 的设置页,这里只剩大肥鱼自己的事实。
65
64
  const facts = card(
66
- '台账与桌宠',
65
+ '台账',
67
66
  [
68
67
  row({ label: '台账', hint: '唯一事实来源,面板与 CLI 读写同一份', value: '%USERPROFILE%\\.dsh\\work-fish\\tasks\\index.md' }),
69
- row({ label: '桌宠', hint: '形象与菜单由 dsh-pet 提供', value: '已连上 main' }),
70
- row({ label: '写入', hint: '关掉后桌宠菜单与面板都只能读', value: '允许' }),
68
+ row({ label: '写入', hint: '关掉后面板只能读', value: '允许' }),
71
69
  ].join(''),
72
70
  )
73
71
 
package/tools/wf-task.mjs CHANGED
@@ -97,7 +97,6 @@ function cmdNew(opts) {
97
97
  next: opts.next,
98
98
  note: opts.note,
99
99
  mode: opts.mode,
100
- source: opts.source,
101
100
  eventsFile: eventsOf(opts),
102
101
  })
103
102
  print(result)
@@ -117,7 +116,6 @@ function cmdBump(opts) {
117
116
  who: opts.who,
118
117
  what: opts.what,
119
118
  chase: opts.chase,
120
- source: opts.source,
121
119
  eventsFile: eventsOf(opts),
122
120
  })
123
121
  print(result)
@@ -140,7 +138,6 @@ function cmdMove(opts) {
140
138
  chase: opts.chase,
141
139
  note: opts.note,
142
140
  marker: opts.marker,
143
- source: opts.source,
144
141
  eventsFile: eventsOf(opts),
145
142
  })
146
143
  print(result)
@@ -153,7 +150,6 @@ function cmdProgress(opts) {
153
150
  expectRev: Number.isInteger(expect) ? expect : undefined,
154
151
  text: opts.text,
155
152
  next: opts.next,
156
- source: opts.source,
157
153
  eventsFile: eventsOf(opts),
158
154
  })
159
155
  print(result)
@@ -165,7 +161,6 @@ function cmdDrop(opts) {
165
161
  task: opts.task,
166
162
  expectRev: Number.isInteger(expect) ? expect : undefined,
167
163
  reason: opts.reason,
168
- source: opts.source,
169
164
  eventsFile: eventsOf(opts),
170
165
  })
171
166
  print(result)
@@ -228,9 +223,9 @@ function selfTest() {
228
223
  const created = newTask(file, { title: '新事项', accept: '可检查', relation: '协作', section: '待办', eventsFile: events })
229
224
  ok('new 成功', created.ok && /^T-\d{8}-01$/.test(created.task))
230
225
  ok('事件日志有记录', fs.existsSync(events) && fs.readFileSync(events, 'utf8').trim().split('\n').length >= 2)
231
- newTask(file, { title: '带来源', accept: 'x', relation: '协作', source: '桌宠', eventsFile: events })
226
+ newTask(file, { title: '不带来源', accept: 'x', relation: '协作', eventsFile: events })
232
227
  const lastEvent = JSON.parse(fs.readFileSync(events, 'utf8').trim().split('\n').pop())
233
- ok('事件记录带上写入来源', lastEvent.source === '桌宠', JSON.stringify(lastEvent))
228
+ ok('事件不再记录写入来源', lastEvent.source === undefined, JSON.stringify(lastEvent))
234
229
  const moved = moveTask(file, { task: 'T-20261106-02', expectRev: 1, to: '进行中', eventsFile: events })
235
230
  ok('move 待办→进行中', moved.ok && moved.from === '待办' && moved.to === '进行中', moved.message)
236
231
  const movedRow = findTask(loadLedger(file), 'T-20261106-02')
@@ -1,439 +0,0 @@
1
- /**
2
- * The bridge between the Work Fish ledger and the `dsh-pet` character.
3
- *
4
- * Work Fish used to draw its own pet. Since the character belongs to `dsh-pet`,
5
- * this module is the whole of the relationship: a few HTTP calls over the Web
6
- * server's own origin, never an import, so either plugin can be upgraded or
7
- * removed without the other one failing to load.
8
- *
9
- * Three things travel over it:
10
- *
11
- * 1. **Menu items** — the pet's right-click menu gets a 「大肥鱼」 group
12
- * (`/menu/item`). A click comes back through `/menu/events`, which this
13
- * module long-polls; that is how the task panel is opened from the
14
- * character and how 「开始下一件」「完成进行中」become ledger writes.
15
- * 2. **Work status** — the top in-progress row is pushed as the pet's task
16
- * line (`/work-status`), so the character says what is being worked on.
17
- * 3. **Reminders** — a new overdue row earns one short bubble (`/broadcast`).
18
- *
19
- * Every call is best-effort: `dsh-pet` may be disabled, missing, asleep or
20
- * holding its lock, and none of that is an error worth surfacing to the user.
21
- * The bridge therefore never throws, never retries in a tight loop, and reports
22
- * its own state through `status()` so `/wf/info` can show it.
23
- *
24
- * @module dsh-work-fish/core/pet-bridge
25
- */
26
-
27
- import fs from 'node:fs'
28
- import { pushEvent } from './events.mjs'
29
-
30
- /** Registry key for our menu group; also the group label the pet shows. */
31
- const OWNER = '大肥鱼'
32
-
33
- /** The three menu items, in menu order. Labels double as click identifiers. */
34
- const LABELS = {
35
- board: '打开任务板',
36
- start: '开始下一件',
37
- finish: '完成进行中',
38
- }
39
-
40
- /** Wait ceiling for the menu long-poll, matching `dsh-pet`'s own limit. */
41
- const POLL_WAIT_MS = 10_000
42
-
43
- /** Backoff after a failed call: long enough that a missing pet costs nothing. */
44
- const RETRY_MS = 15_000
45
-
46
- /**
47
- * Sleep without holding anything.
48
- * @param {number} ms milliseconds.
49
- * @returns {Promise<void>} resolves after `ms`.
50
- */
51
- const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms))
52
-
53
- /**
54
- * Cut a string to `max` code points so a proxy pair never splits.
55
- * @param {string} text source text.
56
- * @param {number} max code points allowed.
57
- * @returns {string} the (possibly shortened) text.
58
- */
59
- function clip(text, max) {
60
- const points = Array.from(String(text ?? ''))
61
- return points.length > max ? `${points.slice(0, max - 1).join('')}…` : points.join('')
62
- }
63
-
64
- /**
65
- * Start the bridge. Safe to call once per mount; every failure stays inside.
66
- *
67
- * @param {object} deps dependencies, all supplied by the host entry.
68
- * @param {{homeDir: string, timeZone: string, allowWrites: boolean}} deps.options resolved row options.
69
- * @param {{info?: Function, warn?: Function, error?: Function}} [deps.logger] Cordis logger.
70
- * @param {() => string} deps.getOrigin returns the Web server origin, or `''`.
71
- * @param {(args: string[]) => Promise<object>} deps.runCli runs `wf-task` and returns its JSON.
72
- * @param {(options: object) => Promise<object>} deps.buildReport reads the ledger into the panel payload.
73
- * @returns {{status: () => object}} liveness facts for `/wf/info`.
74
- */
75
- export function startPetBridge({ options, logger, getOrigin, runCli, buildReport }) {
76
- /** @type {{connected: boolean, petId: string, display: string, reason: string, lastFeedAt: number, lastAction: string}} */
77
- const state = { connected: false, petId: '', display: '', reason: 'starting', lastFeedAt: 0, lastAction: '' }
78
-
79
- /** Set once `dsh-pet` accepted our menu registration; cleared on any failure. */
80
- let registered = false
81
-
82
- /** Overdue count last announced, so a reminder is news rather than a loop. */
83
- let announcedOverdue = -1
84
-
85
- /** Last time a reminder was shown, in ms; reminders are rate-limited. */
86
- let remindedAt = 0
87
-
88
- /** Set by `stop()`; every loop checks it before continuing. */
89
- let stopped = false
90
-
91
- /** Handle of the feed interval, cleared by `stop()`. */
92
- let feedTimer = undefined
93
-
94
- /** Ledger mtime last seen, used to nudge open panels. */
95
- let ledgerStamp = ''
96
-
97
- /**
98
- * `dsh-pet` mounts every route under one constant segment; this is the only
99
- * place that spells it, and the probe in `/wf/info` shows when it stops matching.
100
- * @returns {string} `origin + segment`, or `''` before the server knows its origin.
101
- */
102
- const base = () => {
103
- const origin = String(getOrigin() ?? '')
104
- return origin === '' ? '' : `${origin.replace(/\/+$/u, '')}/dsh-pet-7340`
105
- }
106
-
107
- /**
108
- * One JSON call against `dsh-pet`.
109
- *
110
- * `signal` bounds the long poll: without it a half-open socket would keep the
111
- * loop from ever retrying. Every non-2xx answer is a rejection here so the
112
- * caller has one branch, not two.
113
- *
114
- * @param {string} url absolute URL.
115
- * @param {{method?: string, body?: object, timeoutMs?: number}} [init] request shape.
116
- * @returns {Promise<object>} the parsed body, or `{ ok: false }` on any failure.
117
- */
118
- async function call(url, init = {}) {
119
- const controller = new AbortController()
120
- const timer = setTimeout(() => controller.abort(), init.timeoutMs ?? 5_000)
121
- try {
122
- const response = await fetch(url, {
123
- method: init.method ?? 'GET',
124
- headers: init.body === undefined ? { accept: 'application/json' } : { accept: 'application/json', 'content-type': 'application/json' },
125
- body: init.body === undefined ? undefined : JSON.stringify(init.body),
126
- signal: controller.signal,
127
- cache: 'no-store',
128
- })
129
- const text = await response.text()
130
- let body = {}
131
- try {
132
- body = text === '' ? {} : JSON.parse(text)
133
- } catch {
134
- body = { ok: false, code: 'bad-json', message: `HTTP ${response.status}` }
135
- }
136
- if (!response.ok) return { ...body, ok: false, code: body?.code ?? `http-${response.status}` }
137
- return body
138
- } catch (error) {
139
- return { ok: false, code: 'unreachable', message: error instanceof Error ? error.message : String(error) }
140
- } finally {
141
- clearTimeout(timer)
142
- }
143
- }
144
-
145
- /**
146
- * Learn which character to address.
147
- *
148
- * `dsh-pet` requires an explicit `?pet=` on every feed call and refuses to
149
- * guess, so the id is read from its merged config instead of being assumed.
150
- * That config is keyed by pet id (`{ main: {...} }`), one entry per layer —
151
- * it is not the same shape as the `pets[]` array in the on-disk file.
152
- *
153
- * The merged config is keyed by animation-entry name and each entry carries
154
- * the `pets[]` array; the first pet's id is what `?pet=` wants, and its
155
- * `display` decides which `surface` a bubble is allowed to target (`dsh-pet`
156
- * refuses a bubble for a surface the pet is not shown on).
157
- *
158
- * @param {string} root `origin + segment`.
159
- * @returns {Promise<{id: string, display: string}>} the first pet, or blanks.
160
- */
161
- async function discoverPet(root) {
162
- const config = await call(`${root}/config`)
163
- if (config === null || typeof config !== 'object') return { id: '', display: '' }
164
- for (const key of Object.keys(config)) {
165
- const layer = config[key]
166
- const pets = Array.isArray(layer?.pets) ? layer.pets : []
167
- const pet = pets.find((candidate) => typeof candidate?.id === 'string' && candidate.id.trim() !== '')
168
- if (pet !== undefined) {
169
- return { id: pet.id.trim(), display: typeof pet.display === 'string' ? pet.display : '' }
170
- }
171
- }
172
- return { id: '', display: '' }
173
- }
174
-
175
- /**
176
- * (Re)register the 「大肥鱼」 menu group.
177
- *
178
- * Registration replaces the whole owner, so this is idempotent; it is repeated
179
- * whenever a poll reports the owner is gone, which is what a `dsh-pet` restart
180
- * looks like from here.
181
- *
182
- * @param {string} root `origin + segment`.
183
- * @returns {Promise<boolean>} whether the group is in place.
184
- */
185
- async function registerMenu(root) {
186
- const result = await call(`${root}/menu/item`, {
187
- method: 'POST',
188
- body: { owner: OWNER, labels: Object.values(LABELS), target: 'both' },
189
- })
190
- if (result?.ok === true) return true
191
- logger?.warn?.(`wf: 桌宠菜单注册失败(${result?.reason ?? result?.code ?? 'unknown'})`)
192
- return false
193
- }
194
-
195
- /**
196
- * Forget the pet address so the next poll discovers it again.
197
- *
198
- * `dsh-pet` answers `unknown-pet` after the character is renamed or removed;
199
- * without this the bridge would keep feeding an id nobody owns while still
200
- * reporting itself as connected.
201
- */
202
- function forgetPet() {
203
- state.petId = ''
204
- state.display = ''
205
- state.connected = false
206
- state.reason = 'pet id no longer exists, rediscovering'
207
- registered = false
208
- }
209
-
210
- /**
211
- * Show one short line on the character.
212
- *
213
- * The `surface` must match where the character is actually shown, so it is
214
- * read from its own config rather than assumed; `both` is the tolerant default.
215
- *
216
- * @param {string} text what to say; `dsh-pet` cuts a long line itself.
217
- * @returns {Promise<boolean>} whether the character accepted the line.
218
- */
219
- async function say(text) {
220
- const root = base()
221
- if (root === '' || state.petId === '') return false
222
- const surface = state.display === 'desktop' || state.display === 'web' ? state.display : 'both'
223
- const result = await call(`${root}/broadcast?pet=${encodeURIComponent(state.petId)}&surface=${surface}`, {
224
- method: 'POST',
225
- body: { text: clip(text, 120), duration: 8_000, anim: false },
226
- })
227
- if (result?.ok === true) return true
228
- if (result?.reason === 'unknown-pet' || result?.reason === 'pet-required') forgetPet()
229
- return false
230
- }
231
-
232
- /**
233
- * Push (or clear) the pet's task line from the top in-progress row.
234
- * @returns {Promise<void>} resolves when the call is done or has failed.
235
- */
236
- async function feed() {
237
- const root = base()
238
- if (root === '' || state.petId === '') return
239
- const query = `?pet=${encodeURIComponent(state.petId)}`
240
- let report
241
- try {
242
- report = await buildReport(options)
243
- } catch (error) {
244
- logger?.warn?.(`wf: 台账读取失败(${error instanceof Error ? error.message : String(error)})`)
245
- return
246
- }
247
- const current = Array.isArray(report?.inProgress) ? report.inProgress[0] : undefined
248
- /** Nothing in progress hands the slot back rather than leaving a stale line. */
249
- const status =
250
- current === undefined
251
- ? await call(`${root}/work-status${query}`, { method: 'DELETE' })
252
- : await call(`${root}/work-status${query}`, {
253
- method: 'POST',
254
- body: { state: 'working', task: clip(`${current.id} ${current.title ?? ''}`.trim(), 40) },
255
- })
256
- if (status?.reason === 'unknown-pet' || status?.reason === 'pet-required') {
257
- forgetPet()
258
- return
259
- }
260
- state.lastFeedAt = Date.now()
261
-
262
- const overdue = Number(report?.counts?.overdue ?? 0)
263
- if (overdue > 0 && overdue !== announcedOverdue && Date.now() - remindedAt > 30 * 60_000) {
264
- const late = [...(report?.inProgress ?? []), ...(report?.todo ?? [])].find((row) => Number(row?.overdueDays) > 0)
265
- const spoken = await say(late === undefined ? `今天逾期 ${overdue} 件` : `逾期 ${overdue} 件,先看 ${late.id}`)
266
- // Only a delivered line counts as told: a mute pet must not swallow the reminder.
267
- if (spoken) remindedAt = Date.now()
268
- else return
269
- }
270
- announcedOverdue = overdue
271
- }
272
-
273
- /**
274
- * Move one ledger row through the shared CLI.
275
- * @param {object} row panel row (`id`, `rev`).
276
- * @param {string} to target section name.
277
- * @param {string[]} [extra] additional CLI flags.
278
- * @returns {Promise<object>} the CLI verdict.
279
- */
280
- async function move(row, to, extra = []) {
281
- const result = await runCli([
282
- 'move',
283
- '--task', String(row.id),
284
- '--expect-rev', String(row.rev),
285
- '--to', to,
286
- ...extra,
287
- '--source', '桌宠',
288
- ])
289
- state.lastAction = `${to} ${row.id}`
290
- pushEvent('changed')
291
- if (result?.ok === true) return result
292
- if (result?.verdict === 'STALE') await say('台账刚被改过,已刷新')
293
- else await say(`没写成:${clip(result?.message ?? '未知原因', 40)}`)
294
- return result
295
- }
296
-
297
- /**
298
- * React to one click on a menu item, in order of what the user asked for.
299
- * @param {string} label the clicked label.
300
- * @returns {Promise<void>} resolves when the action is done.
301
- */
302
- async function onMenuClick(label) {
303
- if (label === LABELS.board) {
304
- pushEvent('open')
305
- return
306
- }
307
- if (options.allowWrites !== true) {
308
- await say('台账写入已关闭')
309
- return
310
- }
311
- let report
312
- try {
313
- report = await buildReport(options)
314
- } catch {
315
- await say('台账读不到')
316
- return
317
- }
318
- if (label === LABELS.start) {
319
- const next = Array.isArray(report?.todo) ? report.todo[0] : undefined
320
- if (next === undefined) {
321
- await say('待办里没有可开的任务')
322
- return
323
- }
324
- const result = await move(next, '进行中')
325
- if (result?.ok === true) await say(`开始 ${next.id}`)
326
- return
327
- }
328
- if (label === LABELS.finish) {
329
- const current = Array.isArray(report?.inProgress) ? report.inProgress[0] : undefined
330
- if (current === undefined) {
331
- await say('没有进行中的任务')
332
- return
333
- }
334
- const result = await move(current, '已完成', ['--result', '已完成'])
335
- if (result?.ok === true) await say(`完成 ${current.id}`)
336
- }
337
- }
338
-
339
- /** One poll round: discover, register, then drain clicks until aborted. */
340
- async function pollLoop() {
341
- while (!stopped) {
342
- const root = base()
343
- if (root === '') {
344
- state.reason = 'web server origin unknown'
345
- await sleep(RETRY_MS)
346
- continue
347
- }
348
- if (state.petId === '') {
349
- const found = await discoverPet(root)
350
- state.petId = found.id
351
- state.display = found.display
352
- if (state.petId === '') {
353
- state.connected = false
354
- state.reason = 'dsh-pet 未安装或未启用'
355
- await sleep(RETRY_MS)
356
- continue
357
- }
358
- }
359
- if (!registered) {
360
- registered = await registerMenu(root)
361
- if (!registered) {
362
- state.connected = false
363
- state.reason = 'menu registration refused'
364
- await sleep(RETRY_MS)
365
- continue
366
- }
367
- state.connected = true
368
- state.reason = ''
369
- }
370
- const batch = await call(
371
- `${root}/menu/events?owner=${encodeURIComponent(OWNER)}&wait=${POLL_WAIT_MS}`,
372
- { timeoutMs: POLL_WAIT_MS + 5_000 },
373
- )
374
- if (batch?.ok !== true) {
375
- // A leftover long poll and a `dsh-pet` restart look the same here: drop
376
- // the registration and let the next round re-establish both.
377
- registered = false
378
- state.connected = false
379
- state.reason = 'pet unreachable'
380
- await sleep(RETRY_MS)
381
- continue
382
- }
383
- // `dsh-pet` answers `{ ok, events: { label: petId | null } }`: a null slot
384
- // means "registered but not clicked", which is the common case.
385
- const clicks = batch?.events !== null && typeof batch?.events === 'object' ? batch.events : {}
386
- for (const [label, pet] of Object.entries(clicks)) {
387
- if (typeof pet !== 'string' || pet === '') continue // unused click slot
388
- try {
389
- await onMenuClick(label)
390
- } catch (error) {
391
- logger?.warn?.(`wf: 菜单动作失败(${error instanceof Error ? error.message : String(error)})`)
392
- }
393
- }
394
- }
395
- }
396
-
397
- /** Refresh the feed and nudge open panels when the ledger file moved. */
398
- function watchLoop() {
399
- feedTimer = setInterval(() => {
400
- if (stopped) return
401
- try {
402
- const stamp = String(fs.statSync(`${options.homeDir}/tasks/index.md`).mtimeMs)
403
- if (ledgerStamp !== '' && stamp !== ledgerStamp) pushEvent('changed')
404
- ledgerStamp = stamp
405
- } catch {
406
- // An unreadable ledger is the panel's problem to show, not the loop's.
407
- }
408
- void feed()
409
- }, 30_000)
410
- feedTimer.unref?.()
411
- }
412
-
413
- void pollLoop()
414
- watchLoop()
415
-
416
- return {
417
- /** Liveness facts for `/wf/info` and the settings page. */
418
- status() {
419
- return {
420
- connected: state.connected,
421
- owner: OWNER,
422
- petId: state.petId,
423
- display: state.display,
424
- labels: Object.values(LABELS),
425
- reason: state.reason,
426
- lastFeedAt: state.lastFeedAt,
427
- lastAction: state.lastAction,
428
- }
429
- },
430
- /** Stop polling; used when the row is disposed. */
431
- stop() {
432
- stopped = true
433
- if (feedTimer !== undefined) {
434
- clearInterval(feedTimer)
435
- feedTimer = undefined
436
- }
437
- },
438
- }
439
- }