dsh-project-recall 0.2.0 → 0.3.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/CHANGELOG.md CHANGED
@@ -1,5 +1,26 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.3.1 — 2026-11-22
4
+
5
+ 把 Codex 版 / 飞牛上的待办对齐进续忆。
6
+
7
+ - 新增 `scripts/import-from-nas.mjs`(`npm run import:nas`):从 Codex 版 project-memory 的 HTTP 接口拉计划,按「项目名 + 标题」去重后合并进续忆,默认 dry-run,`--apply` 才写;`--all` 连已结束的一起搬,`--token` 支持同步令牌。
8
+ - 两边的差异有了正式说法:续忆不读 Codex 版 SQLite,两个面板条数不同是设计如此;对齐走这个脚本,只增不改。
9
+ - README 补「与 Codex 版 / 飞牛对齐」一节。
10
+
11
+ ## 0.3.0 — 2026-11-22
12
+
13
+ 在续忆里点一下「去做」,DSH 直接开一个会话来动手。
14
+
15
+ - 新动作「去做」:焦点卡、每一行、详情弹窗都有;点了就用计划本身渲染成一段指令,交给一个新会话,然后自动跳到那个会话。
16
+ - 交接指令带全上下文:这件事是什么、当时为什么先没做、等着的条件、项目目录、优先级与工作量、当时的原话、计划 id,并要求收尾时用 `project_memory_update_plan` 把计划结掉。
17
+ - 落在正确的目录:计划的真实项目路径能对上 Workspace 就进那个 Workspace,对不上就直接在项目目录里开会话,目录没了则退回默认目录,不会卡住。
18
+ - 派过的会话会记住(`dispatch_session_id`):同一件计划再点一次「去做」,默认接着上次那个会话继续说,不铺一堆碎会话。
19
+ - 派出去过的计划会留下痕迹:`dispatch_count` / `dispatched_at`,详情页显示「交出去做过 N 次」;还只是想法的计划会被提到「排上了」,正在等条件的保持原状。
20
+ - 新 HTTP 接口 `POST /project-memory/api/plans/:id/dispatch`,body 可带 `mode`(`auto` / `new` / `continue`);已结束的计划 409,运行时没有会话服务 503。
21
+ - 新 Agent 工具 `project_memory_dispatch_plan`:Agent 也能把一件计划派给一个会真正动手的会话。
22
+ - 测试:新增 `test/dispatch.test.js`,HTTP 侧补 dispatch 路由用例,共 28 个用例全绿。
23
+
3
24
  ## 0.2.0 — 2026-11-15
4
25
 
5
26
  面板重做成更直观的待办界面。
package/README.md CHANGED
@@ -13,8 +13,9 @@
13
13
  ## 功能
14
14
 
15
15
  - **侧栏入口**:点击侧栏书签图标打开「续忆」面板。
16
+ - **点一下就去做**:焦点卡、每一行、详情里都有「去做」,点了 DSH 会开一个会话,把这件事的完整上下文交给它动手,并跳到那个会话。
16
17
  - **按「现在能不能处理」分组**:轮到你 / 在等条件 / 找时间做 / 已结束,不再用 7 个状态名让人猜。
17
- - **焦点卡**:一次只面对最该处理的一件,直接「做好了 / 再等一周 / 这件事不做了 / 改一改」。
18
+ - **焦点卡**:一次只面对最该处理的一件,直接「去做 / 做好了 / 再等一周 / 这件事不做了 / 改一改」。
18
19
  - **一键完成 + 撤销**:每行左侧的圆圈点一下就算做完,顶部提示 7 秒内可撤销。
19
20
  - **人话状态**:拖了 N 天 / 放了 N 天 / 在等条件 / 排到 11/18 / 先记着 / 做完了 / 不做了。
20
21
  - **完整上下文**:为什么现在不做、什么条件下回来、下一步从哪继续,都记在详情里。
@@ -26,7 +27,7 @@
26
27
  ## 要求
27
28
 
28
29
  - DSH `>= 0.2.1-rc.3`
29
- - 当前版本:`0.2.0`(待办面板版)
30
+ - 当前版本:`0.3.0`(一键派活版)
30
31
 
31
32
  ## 安装
32
33
 
@@ -49,11 +50,30 @@ GitHub:https://github.com/hhse/dsh-project-recall
49
50
 
50
51
  1. 点侧栏的「续忆」图标。
51
52
  2. 点「记一件」,只写标题也可以;有明确的回来条件就填条件,有大致时间就点「今天 / 三天后 / 一周后」。
52
- 3. 之后打开面板,先看顶部的焦点卡:做好、再等一周,或者干脆不做,都只需要一下。
53
+ 3. 之后打开面板,先看顶部的焦点卡:想现在就做就点「去做」,DSH 会开一个会话来动手;也可以「再等一周」或者干脆不做,都只需要一下。
53
54
  4. 手滑点错了也没关系,提示里 7 秒内可以撤销。
54
55
 
55
56
  也可以在对话里直接说「这个先记一下,等 v0.2 发布后再做」,模型会调用原生工具记录。
56
57
 
58
+ ## 去做(派活)
59
+
60
+ 点「去做」之后发生的事:
61
+
62
+ 1. 把计划渲染成一段指令:这件事是什么、当时为什么先没做、等着的条件、项目目录、优先级和大概工作量、当时的原话、计划 id,并要求收尾时用 `project_memory_update_plan` 把计划结掉(做完 done / 还得等 blocked / 不该做 dropped)。
63
+ 2. 找一个落脚点:计划的真实项目路径能对上已有的 Workspace 就进那个 Workspace;对不上就直接在该项目目录里开会话;目录已经不在了就退回默认目录,不会卡住。
64
+ 3. 把指令投进那个会话,然后把界面切过去,你看着它动手。
65
+ 4. 记住这个会话:同一件计划再点一次「去做」,默认接着上次那个会话说,不铺一堆碎会话;`dispatch_count` / `dispatched_at` 会留在计划上,详情里显示「交出去做过 N 次」。
66
+
67
+ 还只是想法的计划会被顺手提到「排上了」;正在等条件的保持原状。已结束的计划要先「捡回来」才能派。
68
+
69
+ HTTP 接口:`POST /project-memory/api/plans/:id/dispatch`,body 可带 `mode`:
70
+
71
+ - `auto`(默认):有上次的会话就继续,没有就新开。
72
+ - `new`:总是新开一个会话。
73
+ - `continue`:只往上次那个会话里说,没有就新开。
74
+
75
+ 返回 `{ plan, session_id, continued }`;计划不存在 404,已结束 409,运行时没有会话服务 503。
76
+
57
77
  ## Agent 工具
58
78
 
59
79
  | 工具 | 用途 |
@@ -65,6 +85,7 @@ GitHub:https://github.com/hhse/dsh-project-recall
65
85
  | `project_memory_review_queue` | 取回到期/陈旧的计划 |
66
86
  | `project_memory_get_plan` | 读取单条计划的完整上下文 |
67
87
  | `project_memory_update_plan` | 修改状态、复盘时间、内容 |
88
+ | `project_memory_dispatch_plan` | 把一件计划交给一个会真正动手的会话执行 |
68
89
 
69
90
  模型会被提示:只记录**明确推迟的具体工作**,模糊想法和普通待办不记;调用时尽量传入当前工作目录的绝对路径。
70
91
 
@@ -80,6 +101,23 @@ GitHub:https://github.com/hhse/dsh-project-recall
80
101
 
81
102
  建议在覆盖导入或清空前先导出一份 JSON。
82
103
 
104
+ ## 与 Codex 版 / 飞牛对齐
105
+
106
+ 续忆用的是 DSH 独立数据域,**不读** Codex 版(本机 SQLite + 飞牛 4318 服务)那份库,两边各记各的——所以同一个项目的待办会在两个面板里看到不同的条数,这是设计如此,不是丢数据。
107
+
108
+ 要把 Codex 版里还没结束的计划并进来,仓库带了一个一次性对齐脚本:
109
+
110
+ ```bash
111
+ node scripts/import-from-nas.mjs # dry-run,只打印会新增哪些
112
+ node scripts/import-from-nas.mjs --apply # 真正写进续忆
113
+ node scripts/import-from-nas.mjs --all # 连 done / dropped 一起
114
+ ```
115
+
116
+ - 源默认 `http://192.168.5.8:4318`(飞牛),目标默认 `http://127.0.0.1:52497`(本机 DSH),可用 `--source` / `--target` 或环境变量 `PROJECT_MEMORY_NAS_URL`、`DSH_URL` 覆盖。
117
+ - 默认只搬未结束(`candidate` / `idea` / `someday` / `planned` / `blocked`)的计划,按「项目名 + 标题」去重,已经存在的跳过;缺的项目会一起补上。
118
+ - 源需要 `x-sync-token` 时加 `--token`(或 `PROJECT_MEMORY_SYNC_TOKEN`)。
119
+ - 只会新增,不会改动或删除续忆里已有的计划。
120
+
83
121
  ## 数据
84
122
 
85
123
  - 使用 DSH `storageDomain` 的独立域 `project_memory`。
@@ -108,7 +146,7 @@ npm run check
108
146
  npm test
109
147
  ```
110
148
 
111
- 测试覆盖计划捕获、去重、复盘队列、搜索、完整备份、合并/覆盖导入、清空数据和 HTTP 接口。HTTP 接口只监听本机 DSH Web,并校验同源写入。
149
+ 测试覆盖计划捕获、去重、复盘队列、搜索、完整备份、合并/覆盖导入、清空数据、派活(`test/dispatch.test.js`)和 HTTP 接口。HTTP 接口只监听本机 DSH Web,并校验同源写入。
112
150
 
113
151
  ## 隐私
114
152
 
package/client.js CHANGED
@@ -207,6 +207,10 @@ window.__ModuleLoader__.load({
207
207
  return h(IconBase, { size }, h('circle', { cx: 32, cy: 32, r: 22 }), h('path', { d: 'M32 19v14l9 5' }));
208
208
  }
209
209
 
210
+ function ArrowRightIcon({ size = 14 }) {
211
+ return h(IconBase, { size }, h('path', { d: 'M14 32h30M32 20l12 12-12 12' }));
212
+ }
213
+
210
214
  function Toast({ toast, onDismiss }) {
211
215
  if (!toast) return null;
212
216
  const { message, action } = toast;
@@ -344,7 +348,8 @@ window.__ModuleLoader__.load({
344
348
  );
345
349
  }
346
350
 
347
- function FocusCard({ plan, total, onOpen, onAct }) {
351
+ function FocusCard({ plan, total, onOpen, onAct, onDispatch, dispatching }) {
352
+ const busy = dispatching === plan.id;
348
353
  const conditions = plan.reactivation_conditions || [];
349
354
  return h(
350
355
  'section',
@@ -376,10 +381,21 @@ window.__ModuleLoader__.load({
376
381
  ),
377
382
  )
378
383
  : null,
379
- h('p', { className: 'pm-focus-ask' }, '花两分钟定一下,然后就可以去忙别的了。'),
384
+ h('p', { className: 'pm-focus-ask' }, '花两分钟定一下,或者直接交给我去做。'),
380
385
  h(
381
386
  'div',
382
387
  { className: 'pm-focus-actions' },
388
+ h(
389
+ 'button',
390
+ {
391
+ className: 'pm-btn pm-btn-go',
392
+ onClick: () => onDispatch(plan),
393
+ disabled: busy,
394
+ title: '开一个会话,把这件事交给它真正去做',
395
+ },
396
+ h(ArrowRightIcon, { size: 14 }),
397
+ busy ? '正在开会话…' : '去做',
398
+ ),
383
399
  h('button', { className: 'pm-btn pm-btn-done', onClick: () => onAct(plan, 'done') }, h(CheckIcon, { size: 14 }), '做好了'),
384
400
  h('button', { className: 'pm-btn pm-btn-ghost', onClick: () => onAct(plan, 'snooze') }, h(ClockIcon, { size: 14 }), '再等一周'),
385
401
  h('button', { className: 'pm-btn pm-btn-quiet', onClick: () => onAct(plan, 'drop') }, '这件事不做了'),
@@ -388,8 +404,9 @@ window.__ModuleLoader__.load({
388
404
  );
389
405
  }
390
406
 
391
- function PlanRow({ plan, group, onOpen, onAct }) {
407
+ function PlanRow({ plan, group, onOpen, onAct, onDispatch, dispatching }) {
392
408
  const closed = group === 'done' || group === 'dropped';
409
+ const busy = dispatching === plan.id;
393
410
  const chip = statusChip(plan, group);
394
411
  const conditions = plan.reactivation_conditions || [];
395
412
  const description = plan.details || plan.reason_deferred || '';
@@ -397,21 +414,25 @@ window.__ModuleLoader__.load({
397
414
  ? [{ label: '捡回来', action: 'restore' }]
398
415
  : group === 'now'
399
416
  ? [
417
+ { label: '去做', action: 'dispatch', go: true },
400
418
  { label: '再等一周', action: 'snooze' },
401
419
  { label: '不做了', action: 'drop', danger: true },
402
420
  ]
403
421
  : group === 'waiting'
404
422
  ? [
405
423
  { label: '条件到了', action: 'advance' },
424
+ { label: '去做', action: 'dispatch', go: true },
406
425
  { label: '再等一周', action: 'snooze' },
407
426
  ]
408
427
  : plan.status === 'planned'
409
428
  ? [
429
+ { label: '去做', action: 'dispatch', go: true },
410
430
  { label: '今天做', action: 'advance' },
411
431
  { label: '不做了', action: 'drop', danger: true },
412
432
  ]
413
433
  : [
414
434
  { label: '排进这周', action: 'thisweek' },
435
+ { label: '去做', action: 'dispatch', go: true },
415
436
  { label: '不做了', action: 'drop', danger: true },
416
437
  ];
417
438
 
@@ -488,13 +509,18 @@ window.__ModuleLoader__.load({
488
509
  {
489
510
  key: action.action,
490
511
  type: 'button',
491
- className: `pm-text-btn${action.danger ? ' pm-text-btn-danger' : ''}`,
512
+ className: `pm-text-btn${action.danger ? ' pm-text-btn-danger' : ''}${action.go ? ' pm-text-btn-go' : ''}`,
513
+ disabled: action.action === 'dispatch' && busy,
492
514
  onClick: (event) => {
493
515
  event.stopPropagation();
516
+ if (action.action === 'dispatch') {
517
+ onDispatch(plan);
518
+ return;
519
+ }
494
520
  onAct(plan, action.action);
495
521
  },
496
522
  },
497
- action.label,
523
+ action.action === 'dispatch' && busy ? '正在开…' : action.label,
498
524
  ),
499
525
  ),
500
526
  ),
@@ -503,7 +529,7 @@ window.__ModuleLoader__.load({
503
529
  );
504
530
  }
505
531
 
506
- function DetailModal({ plan, onClose, onSaved, onAct, notify }) {
532
+ function DetailModal({ plan, onClose, onSaved, onAct, onDispatch, dispatching, notify }) {
507
533
  const [draft, setDraft] = useState(() => toDraft(plan));
508
534
  const [statusTouched, setStatusTouched] = useState(false);
509
535
  const [saving, setSaving] = useState(false);
@@ -562,7 +588,9 @@ window.__ModuleLoader__.load({
562
588
  footer: h(
563
589
  React.Fragment,
564
590
  null,
565
- h('span', { className: 'pm-modal-note' }, `更新于 ${fmtDate(plan.updated_at, true)}`),
591
+ h('span', { className: 'pm-modal-note' }, plan.dispatch_count
592
+ ? `更新于 ${fmtDate(plan.updated_at, true)} · 交出去做过 ${plan.dispatch_count} 次`
593
+ : `更新于 ${fmtDate(plan.updated_at, true)}`),
566
594
  h(
567
595
  'div',
568
596
  { className: 'pm-modal-actions' },
@@ -577,7 +605,7 @@ window.__ModuleLoader__.load({
577
605
  h(
578
606
  'div',
579
607
  { className: 'pm-decision' },
580
- h('span', { className: 'pm-decision-label' }, closed ? '结束了,也可以捡回来' : '直接处理'),
608
+ h('span', { className: 'pm-decision-label' }, closed ? '结束了,也可以捡回来' : '直接处理,或者交给我去做'),
581
609
  closed
582
610
  ? h(
583
611
  'button',
@@ -593,6 +621,16 @@ window.__ModuleLoader__.load({
593
621
  : h(
594
622
  React.Fragment,
595
623
  null,
624
+ h(
625
+ 'button',
626
+ {
627
+ className: 'pm-btn pm-btn-go pm-btn-sm',
628
+ disabled: dispatching === plan.id,
629
+ onClick: () => onDispatch(plan),
630
+ },
631
+ h(ArrowRightIcon, { size: 13 }),
632
+ dispatching === plan.id ? '正在开…' : '去做',
633
+ ),
596
634
  h(
597
635
  'button',
598
636
  {
@@ -931,7 +969,7 @@ window.__ModuleLoader__.load({
931
969
  };
932
970
  }
933
971
 
934
- function App() {
972
+ function App({ onOpenSession }) {
935
973
  const [summary, setSummary] = useState(null);
936
974
  const [openPlans, setOpenPlans] = useState([]);
937
975
  const [closedPlans, setClosedPlans] = useState([]);
@@ -944,6 +982,7 @@ window.__ModuleLoader__.load({
944
982
  const [selected, setSelected] = useState(null);
945
983
  const [creating, setCreating] = useState(false);
946
984
  const [picked, setPicked] = useState(false);
985
+ const [dispatching, setDispatching] = useState('');
947
986
  const toastTimer = useRef(null);
948
987
 
949
988
  const notify = useCallback((message, action = null) => {
@@ -1089,6 +1128,55 @@ window.__ModuleLoader__.load({
1089
1128
  [load, notify],
1090
1129
  );
1091
1130
 
1131
+ const openSession = useCallback(
1132
+ (sessionId) => {
1133
+ if (!sessionId || typeof onOpenSession !== 'function') return false;
1134
+ try {
1135
+ onOpenSession(sessionId);
1136
+ return true;
1137
+ } catch {
1138
+ return false;
1139
+ }
1140
+ },
1141
+ [onOpenSession],
1142
+ );
1143
+
1144
+ const dispatch = useCallback(
1145
+ async (plan) => {
1146
+ if (dispatching) return;
1147
+ setDispatching(plan.id);
1148
+ try {
1149
+ const result = await api(`/plans/${encodeURIComponent(plan.id)}/dispatch`, {
1150
+ method: 'POST',
1151
+ body: JSON.stringify({ mode: 'auto' }),
1152
+ });
1153
+ setSelected(null);
1154
+ await load();
1155
+ const opened = openSession(result.session_id);
1156
+ notify(
1157
+ opened
1158
+ ? result.continued
1159
+ ? '接着上次那个会话继续做'
1160
+ : '开了一个新会话,交给我来做'
1161
+ : `已经派出去了,会话 ${result.session_id}`,
1162
+ opened
1163
+ ? null
1164
+ : {
1165
+ label: '再试一次',
1166
+ run: () => {
1167
+ openSession(result.session_id);
1168
+ },
1169
+ },
1170
+ );
1171
+ } catch (dispatchError) {
1172
+ notify(dispatchError.message);
1173
+ } finally {
1174
+ setDispatching('');
1175
+ }
1176
+ },
1177
+ [dispatching, load, notify, openSession],
1178
+ );
1179
+
1092
1180
  const projects = summary?.projects || [];
1093
1181
  const searching = query.trim().length > 0;
1094
1182
  const current = view === 'closed' ? [...groups.done, ...groups.dropped] : groups[view] || [];
@@ -1096,7 +1184,15 @@ window.__ModuleLoader__.load({
1096
1184
 
1097
1185
  function rows(list) {
1098
1186
  return list.map((plan) =>
1099
- h(PlanRow, { key: plan.id, plan, group: groupOf(plan), onOpen: setSelected, onAct: act }),
1187
+ h(PlanRow, {
1188
+ key: plan.id,
1189
+ plan,
1190
+ group: groupOf(plan),
1191
+ onOpen: setSelected,
1192
+ onAct: act,
1193
+ onDispatch: dispatch,
1194
+ dispatching,
1195
+ }),
1100
1196
  );
1101
1197
  }
1102
1198
 
@@ -1172,7 +1268,14 @@ window.__ModuleLoader__.load({
1172
1268
  h('h2', null, '轮到你', h('span', { className: 'pm-section-count' }, current.length)),
1173
1269
  h('p', { className: 'pm-section-hint' }, VIEWS[0].hint),
1174
1270
  ),
1175
- h(FocusCard, { plan: hero, total: current.length, onOpen: setSelected, onAct: act }),
1271
+ h(FocusCard, {
1272
+ plan: hero,
1273
+ total: current.length,
1274
+ onOpen: setSelected,
1275
+ onAct: act,
1276
+ onDispatch: dispatch,
1277
+ dispatching,
1278
+ }),
1176
1279
  rest.length
1177
1280
  ? h(
1178
1281
  'div',
@@ -1333,6 +1436,8 @@ window.__ModuleLoader__.load({
1333
1436
  plan: selected,
1334
1437
  onClose: () => setSelected(null),
1335
1438
  onAct: act,
1439
+ onDispatch: dispatch,
1440
+ dispatching,
1336
1441
  notify,
1337
1442
  onSaved: async () => {
1338
1443
  setSelected(null);
@@ -1611,6 +1716,9 @@ window.__ModuleLoader__.load({
1611
1716
  .pm-btn-ghost:hover { border-color: var(--dsw-alias-border-l2); background: var(--dsw-alias-bg-layer-2); }
1612
1717
  .pm-btn-quiet { color: var(--pm-muted); }
1613
1718
  .pm-btn-quiet:hover { color: var(--dsw-alias-label-primary); }
1719
+ .pm-btn-go { background: color-mix(in srgb, var(--dsw-alias-state-business-primary) 15%, var(--dsw-alias-bg-layer-1)); border-color: color-mix(in srgb, var(--dsw-alias-state-business-primary) 36%, var(--dsw-alias-border-l1)); color: var(--dsw-alias-state-business-primary); }
1720
+ .pm-btn-go:hover { background: color-mix(in srgb, var(--dsw-alias-state-business-primary) 24%, var(--dsw-alias-bg-layer-1)); }
1721
+ .pm-btn-go:disabled { opacity: .6; cursor: default; }
1614
1722
  .pm-btn-done { background: var(--pm-ok-tint); border-color: color-mix(in srgb, var(--dsw-alias-state-success-primary) 30%, var(--dsw-alias-border-l1)); color: var(--pm-ok); }
1615
1723
  .pm-btn-done:hover { background: color-mix(in srgb, var(--dsw-alias-state-success-primary) 17%, var(--dsw-alias-bg-layer-1)); }
1616
1724
  .pm-btn-danger { color: var(--dsw-alias-state-error-primary); border-color: color-mix(in srgb, var(--dsw-alias-state-error-primary) 26%, var(--dsw-alias-border-l1)); background: color-mix(in srgb, var(--dsw-alias-state-error-primary) 7%, var(--dsw-alias-bg-layer-1)); }
@@ -1700,6 +1808,9 @@ window.__ModuleLoader__.load({
1700
1808
  .pm-text-btn:hover { background: var(--dsw-alias-bg-layer-1); color: var(--dsw-alias-label-primary); }
1701
1809
  .pm-item:hover .pm-text-btn:hover { background: var(--dsw-alias-bg-layer-2); }
1702
1810
  .pm-text-btn-danger:hover { color: var(--dsw-alias-state-error-primary); background: color-mix(in srgb, var(--dsw-alias-state-error-primary) 8%, transparent); }
1811
+ .pm-text-btn-go { color: var(--dsw-alias-state-business-primary); }
1812
+ .pm-text-btn-go:hover { color: var(--dsw-alias-state-business-primary); background: color-mix(in srgb, var(--dsw-alias-state-business-primary) 10%, transparent); }
1813
+ .pm-text-btn:disabled { opacity: .55; cursor: default; }
1703
1814
  .pm-subgroup + .pm-subgroup { margin-top: 14px; }
1704
1815
  .pm-subgroup-head { display: flex; align-items: center; gap: 6px; margin: 0 2px 7px; font-size: 11px; font-weight: 650; color: var(--pm-faint); }
1705
1816
  .pm-subgroup-count { font-size: 10px; font-weight: 650; background: var(--dsw-alias-bg-layer-2); border-radius: 99px; padding: 0 5px; }
@@ -1799,7 +1910,21 @@ window.__ModuleLoader__.load({
1799
1910
  ),
1800
1911
  );
1801
1912
  ctx.slots.inject('main', () =>
1802
- ctx.slots.register({ name: 'main', key: 'project-memory' }, App),
1913
+ ctx.slots.register(
1914
+ {
1915
+ name: 'main',
1916
+ key: 'project-memory',
1917
+ inject: () => ({
1918
+ onOpenSession: (sessionId) => {
1919
+ const workspace = ctx.get('uiWorkspace');
1920
+ if (workspace === undefined || sessionId === undefined) return false;
1921
+ workspace.openSession(sessionId);
1922
+ return true;
1923
+ },
1924
+ }),
1925
+ },
1926
+ App,
1927
+ ),
1803
1928
  );
1804
1929
  ctx.slots.inject('settings.section', () =>
1805
1930
  ctx.slots.register(
package/index.js CHANGED
@@ -2,6 +2,7 @@ import { ProjectMemoryStore } from './lib/store.js';
2
2
  import { domainSpec } from './lib/model.js';
3
3
  import { registerTools } from './lib/tools.js';
4
4
  import { API_PREFIX, createApi } from './lib/http.js';
5
+ import { dispatchPlan } from './lib/dispatch.js';
5
6
 
6
7
  export const name = 'project-memory';
7
8
  export const inject = ['storageDomain', 'tools', 'systemPrompt'];
@@ -14,6 +15,7 @@ const STORE_METHODS = [
14
15
  'projectView',
15
16
  'capturePlan',
16
17
  'updatePlan',
18
+ 'markDispatched',
17
19
  'reviewPlan',
18
20
  'decorate',
19
21
  'listPlans',
@@ -28,7 +30,7 @@ const STORE_METHODS = [
28
30
  'resetAll',
29
31
  ];
30
32
 
31
- const INSTRUCTIONS = `「续忆」保存跨会话的延后计划。只有在用户明确把一件具体工作推迟到以后、下一版、或某个条件满足之后,才调用 project_memory_propose_plan;模糊想法、普通待办、闲聊不要记录。调用时尽量传 project_path(当前会话工作目录的绝对路径),并先 search_plans 检查是否已经记过。用户问“接下来做什么 / 有什么在等 / 复盘一下”时调用 project_memory_review_queue;问“之前记过什么”时用 list_plans 或 search_plans。用户确认完成后用 update_plan 把 status 改为 done。`;
33
+ const INSTRUCTIONS = `「续忆」保存跨会话的延后计划。只有在用户明确把一件具体工作推迟到以后、下一版、或某个条件满足之后,才调用 project_memory_propose_plan;模糊想法、普通待办、闲聊不要记录。调用时尽量传 project_path(当前会话工作目录的绝对路径),并先 search_plans 检查是否已经记过。用户问“接下来做什么 / 有什么在等 / 复盘一下”时调用 project_memory_review_queue;问“之前记过什么”时用 list_plans 或 search_plans。用户说「去做 / 直接开始这件 / 派出去」时,用 project_memory_dispatch_plan 把它交给一个会真正动手的会话执行。用户确认完成后用 update_plan 把 status 改为 done。`;
32
34
 
33
35
  export function apply(ctx, config = {}) {
34
36
  const staleDays = Number.isInteger(config.staleDays) ? config.staleDays : 30;
@@ -48,7 +50,7 @@ export function apply(ctx, config = {}) {
48
50
  lazyStore[method] = (...args) => storePromise.then((store) => store[method](...args));
49
51
  }
50
52
 
51
- registerTools(ctx, lazyStore);
53
+ registerTools(ctx, lazyStore, { dispatch: (plan, options) => dispatchPlan(ctx, plan, options) });
52
54
 
53
55
  ctx.effect(
54
56
  () =>
@@ -66,7 +68,9 @@ export function apply(ctx, config = {}) {
66
68
  hostCtx.webServer.register({
67
69
  kind: 'prefix',
68
70
  path: API_PREFIX,
69
- handler: createApi(storePromise),
71
+ handler: createApi(storePromise, {
72
+ dispatch: (plan, options) => dispatchPlan(hostCtx, plan, options),
73
+ }),
70
74
  }),
71
75
  'project-memory api',
72
76
  );
@@ -0,0 +1,149 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { EFFORT_LABELS, PRIORITY_LABELS } from './model.js';
3
+
4
+ function localTimeZone() {
5
+ try {
6
+ return Intl.DateTimeFormat().resolvedOptions().timeZone || undefined;
7
+ } catch {
8
+ return undefined;
9
+ }
10
+ }
11
+
12
+ function statusError(status, message) {
13
+ const error = new Error(message);
14
+ error.status = status;
15
+ return error;
16
+ }
17
+
18
+ /** The real project directory behind a plan; the inbox has none. */
19
+ export function planProjectPath(plan) {
20
+ const root = plan && plan.project ? plan.project.root_path : '';
21
+ return typeof root === 'string' && root && root !== 'inbox' ? root : '';
22
+ }
23
+
24
+ /**
25
+ * Render one plan as the instruction a working Session receives.
26
+ * The prompt closes the loop: whatever happens, the plan itself gets updated.
27
+ */
28
+ export function buildPlanPrompt(plan) {
29
+ const rootPath = planProjectPath(plan);
30
+ const projectName = plan.project && plan.project.name ? plan.project.name : '';
31
+ const conditions = Array.isArray(plan.reactivation_conditions) ? plan.reactivation_conditions : [];
32
+ const tags = Array.isArray(plan.tags) ? plan.tags : [];
33
+ const lines = [
34
+ '【续忆 · 现在去做】',
35
+ '',
36
+ `我把之前记下的一件事派给你了,现在开始做:**${plan.title}**`,
37
+ ];
38
+ if (plan.details) lines.push('', '## 这件事是什么', plan.details);
39
+ if (plan.reason_deferred) lines.push('', '## 当时为什么先没做', plan.reason_deferred);
40
+ if (conditions.length) lines.push('', '## 等着的条件(现在到了)', ...conditions.map((condition) => `- ${condition}`));
41
+
42
+ const facts = [];
43
+ if (projectName) facts.push(`项目:${projectName}${rootPath ? `(${rootPath})` : ''}`);
44
+ facts.push(
45
+ `优先级:${PRIORITY_LABELS[plan.priority] || plan.priority};大概要花:${EFFORT_LABELS[plan.effort] || plan.effort}`,
46
+ );
47
+ if (tags.length) facts.push(`标签:${tags.join('、')}`);
48
+ if (plan.source_excerpt) facts.push(`当时的原话:「${plan.source_excerpt}」`);
49
+ if (plan.created_at) facts.push(`记于 ${plan.created_at}`);
50
+ facts.push(`计划 id:${plan.id}`);
51
+ lines.push('', '## 记录', ...facts.map((fact) => `- ${fact}`));
52
+
53
+ lines.push(
54
+ '',
55
+ '## 要求',
56
+ '1. 先看当前工作目录的真实状态(代码、文档、git 状态),再决定从哪下手,不要凭记忆假设。',
57
+ '2. 直接做完能做的部分。需要我拍板的地方按最合理的做法往前推,最后一次性告诉我。',
58
+ `3. 收尾时用 project_memory_update_plan 把这件计划结掉:做完就把 id 为 ${plan.id} 的计划 status 改成 done;还得等条件就改成 blocked 并写清 reason_deferred;判断不该做就改成 dropped 并说明原因。`,
59
+ );
60
+ return lines.join('\n');
61
+ }
62
+
63
+ /** Match the plan's project directory to an existing Workspace so the Session lands in the right place. */
64
+ function workspaceForPath(ctx, rootPath) {
65
+ if (!rootPath) return undefined;
66
+ const registry = ctx.get('workspaceRegistry');
67
+ if (registry === undefined || typeof registry.list !== 'function') return undefined;
68
+ try {
69
+ return registry.list().find((workspace) => workspace.path === rootPath);
70
+ } catch {
71
+ return undefined;
72
+ }
73
+ }
74
+
75
+ async function promptInto(ctx, controller, sessionId, text, signal) {
76
+ const timeZone = localTimeZone();
77
+ // The Session API takes its own cancellation signal and builds the durable
78
+ // user message source from requestId, so only the content travels here.
79
+ await controller.prompt(
80
+ {
81
+ requestId: `pm-dispatch-${randomUUID()}`,
82
+ sessionId,
83
+ mode: 'queue',
84
+ content: [{ type: 'text', text }],
85
+ ...(timeZone === undefined ? {} : { clientTimeZone: timeZone }),
86
+ },
87
+ signal,
88
+ );
89
+ // Best effort: persist the handed-over message now so a restart cannot lose it.
90
+ const sessions = ctx.get('sessions');
91
+ if (sessions === undefined || typeof sessions.flush !== 'function') return;
92
+ const agent = await controller.resolveAgent(sessionId).catch(() => undefined);
93
+ if (agent !== undefined && agent.session !== undefined) await sessions.flush(agent.session).catch(() => {});
94
+ }
95
+
96
+ function admissionSignal() {
97
+ try {
98
+ return AbortSignal.timeout(30_000);
99
+ } catch {
100
+ return new AbortController().signal;
101
+ }
102
+ }
103
+
104
+ async function createSession(ctx, controller, rootPath) {
105
+ const workspace = workspaceForPath(ctx, rootPath);
106
+ if (workspace !== undefined) return (await controller.create({ workspaceId: workspace.id })).sessionId;
107
+ if (rootPath) return (await controller.create({ cwd: rootPath })).sessionId;
108
+ return (await controller.create({})).sessionId;
109
+ }
110
+
111
+ /**
112
+ * Hand one plan to a working Session: continue the Session it was dispatched
113
+ * into last time when asked to, otherwise open a fresh one and prompt it.
114
+ * @param ctx - Host context carrying sessionController.
115
+ * @param plan - decorated plan record.
116
+ * @param options - `mode`: auto (default) | new | continue.
117
+ * @returns the Session identity and whether an earlier Session was reused.
118
+ */
119
+ export async function dispatchPlan(ctx, plan, options = {}) {
120
+ const controller = ctx.get('sessionController');
121
+ if (controller === undefined || typeof controller.create !== 'function') {
122
+ throw statusError(503, '这个 DSH 运行时没有提供会话服务,没法在这里直接开会话');
123
+ }
124
+ const text = buildPlanPrompt(plan);
125
+ const signal = admissionSignal();
126
+ const previous = typeof plan.dispatch_session_id === 'string' ? plan.dispatch_session_id : '';
127
+ const mode = options.mode === 'new' || options.mode === 'continue' ? options.mode : 'auto';
128
+
129
+ if (mode !== 'new' && previous) {
130
+ try {
131
+ await promptInto(ctx, controller, previous, text, signal);
132
+ return { sessionId: previous, continued: true };
133
+ } catch (error) {
134
+ ctx.logger?.warn?.(`[project-memory] 继续上次会话失败,改为新开一个:${String(error)}`);
135
+ }
136
+ }
137
+
138
+ const rootPath = planProjectPath(plan);
139
+ let sessionId;
140
+ try {
141
+ sessionId = await createSession(ctx, controller, rootPath);
142
+ } catch (error) {
143
+ // A moved or deleted project directory must not block the hand-over.
144
+ if (!rootPath) throw error;
145
+ sessionId = (await controller.create({})).sessionId;
146
+ }
147
+ await promptInto(ctx, controller, sessionId, text, signal);
148
+ return { sessionId, continued: false };
149
+ }
package/lib/http.js CHANGED
@@ -1,5 +1,6 @@
1
- const API_PREFIX = '/project-memory/api';
2
- const MAX_BODY = 64 * 1024;
1
+ import { isOpen } from './model.js';
2
+
3
+ const API_PREFIX = '/project-memory/api';const MAX_BODY = 64 * 1024;
3
4
  const MAX_IMPORT_BODY = 5 * 1024 * 1024;
4
5
 
5
6
  class HttpError extends Error {
@@ -59,7 +60,7 @@ function planPayload(plan) {
59
60
  return plan;
60
61
  }
61
62
 
62
- export function createApi(storeSource) {
63
+ export function createApi(storeSource, options = {}) {
63
64
  const storePromise = Promise.resolve(storeSource);
64
65
  async function route(req, res) {
65
66
  const store = await storePromise;
@@ -184,6 +185,26 @@ export function createApi(storeSource) {
184
185
  return;
185
186
  }
186
187
 
188
+ const dispatchMatch = sub.match(/^\/plans\/([^/]+)\/dispatch$/);
189
+ if (dispatchMatch && method === 'POST') {
190
+ const id = decodeURIComponent(dispatchMatch[1]);
191
+ const plan = store.getPlan(id);
192
+ if (!plan) throw new HttpError(404, 'Plan not found');
193
+ if (!isOpen(plan.status)) throw new HttpError(409, '这件计划已经结束了,先捡回来再派出去');
194
+ if (typeof options.dispatch !== 'function') {
195
+ throw new HttpError(503, '这个 DSH 运行时没有提供会话服务,没法在这里直接开会话');
196
+ }
197
+ const body = await readJsonBody(req);
198
+ const result = await options.dispatch(plan, { mode: body.mode });
199
+ const updated = await store.markDispatched(id, { sessionId: result.sessionId });
200
+ sendJson(res, 200, {
201
+ plan: planPayload(updated),
202
+ session_id: result.sessionId,
203
+ continued: result.continued === true,
204
+ });
205
+ return;
206
+ }
207
+
187
208
  sendJson(res, 404, { error: 'Not found' });
188
209
  }
189
210
 
@@ -191,7 +212,9 @@ export function createApi(storeSource) {
191
212
  try {
192
213
  await route(req, res);
193
214
  } catch (error) {
194
- const status = error instanceof HttpError ? error.status : 500;
215
+ const status = error instanceof HttpError
216
+ ? error.status
217
+ : Number.isInteger(error?.status) ? error.status : 500;
195
218
  if (status >= 500) {
196
219
  console.error('[project-memory] API error:', error);
197
220
  }
package/lib/model.js CHANGED
@@ -63,6 +63,9 @@ export const planSchema = z
63
63
  created_at: z.string().min(1),
64
64
  updated_at: z.string().min(1),
65
65
  completed_at: z.string().nullable().default(null),
66
+ dispatch_session_id: z.string().nullable().default(null),
67
+ dispatched_at: z.string().nullable().default(null),
68
+ dispatch_count: z.number().int().min(0).default(0),
66
69
  })
67
70
  .passthrough();
68
71
 
package/lib/store.js CHANGED
@@ -24,6 +24,9 @@ const ALLOWED_UPDATE_FIELDS = new Set([
24
24
  'last_reviewed_at',
25
25
  ]);
26
26
 
27
+ /** Statuses a plan leaves behind once it is handed to a working Session. */
28
+ const DISPATCH_PROMOTED_FROM = new Set(['candidate', 'idea', 'someday']);
29
+
27
30
  function nowIso() {
28
31
  return new Date().toISOString();
29
32
  }
@@ -201,6 +204,9 @@ export class ProjectMemoryStore {
201
204
  created_at: timestamp,
202
205
  updated_at: timestamp,
203
206
  completed_at: null,
207
+ dispatch_session_id: null,
208
+ dispatched_at: null,
209
+ dispatch_count: 0,
204
210
  };
205
211
  await this.plans.put(id, plan);
206
212
  await this.projects.put(project.id, { ...project, updated_at: timestamp });
@@ -248,6 +254,28 @@ export class ProjectMemoryStore {
248
254
  return this.decorate(next);
249
255
  }
250
256
 
257
+ /**
258
+ * Record that this plan was handed to a working Session.
259
+ * A plan that was only being kept for later becomes planned at the same time.
260
+ */
261
+ async markDispatched(id, { sessionId = null } = {}) {
262
+ const current = this.plans.get(id);
263
+ if (!current) throw new Error(`Plan not found: ${id}`);
264
+ const timestamp = nowIso();
265
+ const next = {
266
+ ...current,
267
+ dispatch_session_id: sessionId,
268
+ dispatched_at: timestamp,
269
+ dispatch_count: (Number(current.dispatch_count) || 0) + 1,
270
+ updated_at: timestamp,
271
+ };
272
+ if (DISPATCH_PROMOTED_FROM.has(current.status)) next.status = 'planned';
273
+ await this.plans.put(id, next);
274
+ const project = this.projects.get(next.project_id);
275
+ if (project) await this.projects.put(project.id, { ...project, updated_at: timestamp });
276
+ return this.decorate(next);
277
+ }
278
+
251
279
  async reviewPlan(id, action = 'done', options = {}) {
252
280
  if (action === 'done') return this.updatePlan(id, { status: 'done' });
253
281
  if (action === 'drop') return this.updatePlan(id, { status: 'dropped' });
package/lib/tools.js CHANGED
@@ -1,4 +1,4 @@
1
- import { EFFORTS, PRIORITIES, STATUSES } from './model.js';
1
+ import { EFFORTS, PRIORITIES, STATUSES, isOpen } from './model.js';
2
2
 
3
3
  const projectPathSchema = {
4
4
  type: 'string',
@@ -23,6 +23,9 @@ const planSummary = (plan) => ({
23
23
  review_at: plan.review_at,
24
24
  is_due: plan.is_due,
25
25
  is_stale: plan.is_stale,
26
+ dispatch_session_id: plan.dispatch_session_id ?? null,
27
+ dispatch_count: plan.dispatch_count ?? 0,
28
+ dispatched_at: plan.dispatched_at ?? null,
26
29
  updated_at: plan.updated_at,
27
30
  });
28
31
 
@@ -81,7 +84,7 @@ const captureProperties = {
81
84
  },
82
85
  };
83
86
 
84
- export function registerTools(ctx, store) {
87
+ export function registerTools(ctx, store, options = {}) {
85
88
  const definitions = [
86
89
  defineTool(
87
90
  'project_memory_propose_plan',
@@ -228,6 +231,39 @@ export function registerTools(ctx, store) {
228
231
  },
229
232
  ),
230
233
 
234
+ defineTool(
235
+ 'project_memory_dispatch_plan',
236
+ 'Hand one saved plan to a Session that actually does the work now: a new Session opens in the plan\'s project with the plan rendered as its instruction, and the plan records which Session got it. Use when the user says 去做 / 直接开始这件 / 派出去 / dispatch this plan.',
237
+ {
238
+ type: 'object',
239
+ properties: {
240
+ id: { type: 'string', description: 'Plan id.' },
241
+ mode: {
242
+ type: 'string',
243
+ enum: ['auto', 'new', 'continue'],
244
+ description: 'auto continues the Session this plan was last dispatched into; new always opens a fresh Session.',
245
+ },
246
+ },
247
+ required: ['id'],
248
+ additionalProperties: false,
249
+ },
250
+ async (args) => {
251
+ if (typeof options.dispatch !== 'function') {
252
+ throw new Error('这个 DSH 运行时没有提供会话服务,没法派出去');
253
+ }
254
+ const plan = await store.getPlan(args.id);
255
+ if (!plan) throw new Error(`Plan not found: ${args.id}`);
256
+ if (!isOpen(plan.status)) throw new Error(`Plan already ${plan.status}: ${args.id}`);
257
+ const result = await options.dispatch(plan, { mode: args.mode });
258
+ const updated = await store.markDispatched(args.id, { sessionId: result.sessionId });
259
+ return {
260
+ session_id: result.sessionId,
261
+ continued: result.continued === true,
262
+ plan: planSummary(updated),
263
+ };
264
+ },
265
+ ),
266
+
231
267
  defineTool(
232
268
  'project_memory_update_plan',
233
269
  'Update a saved plan. Use for status changes, rescheduling review, editing title/details, or marking done/dropped after the user confirms.',
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-project-recall",
3
- "version": "0.2.0",
3
+ "version": "0.3.1",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "description": "续忆 — 为 DeepSeek Harness 保存跨会话的延后计划,并在合适的时候提醒你回来继续。",
@@ -24,6 +24,7 @@
24
24
  "index.js",
25
25
  "client.js",
26
26
  "lib/*.js",
27
+ "scripts/import-from-nas.mjs",
27
28
  "cordis.patch.yml",
28
29
  "locale/*.json",
29
30
  "icon.svg",
@@ -49,7 +50,8 @@
49
50
  },
50
51
  "scripts": {
51
52
  "test": "node --test",
52
- "check": "node --check index.js && node --check client.js && node --check lib/model.js && node --check lib/store.js && node --check lib/http.js && node --check lib/tools.js"
53
+ "check": "node --check index.js && node --check client.js && node --check lib/model.js && node --check lib/store.js && node --check lib/http.js && node --check lib/tools.js && node --check lib/dispatch.js",
54
+ "import:nas": "node scripts/import-from-nas.mjs"
53
55
  },
54
56
  "repository": {
55
57
  "type": "git",
@@ -0,0 +1,170 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * 把 Codex 版 project-memory(本机 SQLite / 飞牛上的 4318 服务)里还没结束的计划
4
+ * 合并进 DSH 续忆(dsh-project-recall)的 project_memory 存储域。
5
+ *
6
+ * 默认只做 dry-run,打印「会新增哪些」,加 --apply 才真的写。
7
+ *
8
+ * node scripts/import-from-nas.mjs # 看差异
9
+ * node scripts/import-from-nas.mjs --apply # 真导入
10
+ * node scripts/import-from-nas.mjs --all # 连 done/dropped 一起
11
+ * node scripts/import-from-nas.mjs --source http://127.0.0.1:4318 --target http://127.0.0.1:52497
12
+ */
13
+
14
+ const OPEN_STATUSES = new Set(['candidate', 'idea', 'someday', 'planned', 'blocked']);
15
+
16
+ function parseArgs(argv) {
17
+ const options = {
18
+ source: process.env.PROJECT_MEMORY_NAS_URL || 'http://192.168.5.8:4318',
19
+ target: process.env.DSH_URL || 'http://127.0.0.1:52497',
20
+ token: process.env.PROJECT_MEMORY_SYNC_TOKEN || '',
21
+ apply: false,
22
+ all: false,
23
+ };
24
+ for (let index = 0; index < argv.length; index += 1) {
25
+ const arg = argv[index];
26
+ if (arg === '--apply') options.apply = true;
27
+ else if (arg === '--all') options.all = true;
28
+ else if (arg === '--source') options.source = argv[++index];
29
+ else if (arg === '--target') options.target = argv[++index];
30
+ else if (arg === '--token') options.token = argv[++index];
31
+ else if (arg === '--help' || arg === '-h') {
32
+ console.log('用法: node scripts/import-from-nas.mjs [--apply] [--all] [--source URL] [--target URL] [--token TOKEN]');
33
+ process.exit(0);
34
+ } else {
35
+ console.error(`未知参数: ${arg}`);
36
+ process.exit(2);
37
+ }
38
+ }
39
+ options.source = String(options.source || '').replace(/\/+$/, '');
40
+ options.target = String(options.target || '').replace(/\/+$/, '');
41
+ return options;
42
+ }
43
+
44
+ function trim(value) {
45
+ return String(value ?? '').trim();
46
+ }
47
+
48
+ function key(projectName, title) {
49
+ return `${trim(projectName).toLowerCase()}::${trim(title).replace(/\s+/g, ' ').toLowerCase()}`;
50
+ }
51
+
52
+ async function getJson(url, headers = {}) {
53
+ const response = await fetch(url, { headers });
54
+ if (!response.ok) {
55
+ throw new Error(`${url} → HTTP ${response.status}`);
56
+ }
57
+ return response.json();
58
+ }
59
+
60
+ async function main() {
61
+ const options = parseArgs(process.argv.slice(2));
62
+ const headers = options.token ? { 'x-sync-token': options.token } : {};
63
+
64
+ console.log(`源(Codex 版): ${options.source}`);
65
+ console.log(`目标(DSH 续忆): ${options.target}`);
66
+
67
+ const [remoteProjects, remotePlans, exported] = await Promise.all([
68
+ getJson(`${options.source}/api/projects`, headers),
69
+ getJson(`${options.source}/api/plans`, headers),
70
+ // /plans 只返回未结束的计划,去重要用 /export 的全量(含 done/dropped)
71
+ getJson(`${options.target}/project-memory/api/export`, { origin: options.target }),
72
+ ]);
73
+
74
+ const projects = Array.isArray(remoteProjects) ? remoteProjects : remoteProjects.projects ?? [];
75
+ const plans = Array.isArray(remotePlans) ? remotePlans : remotePlans.plans ?? [];
76
+ const existing = Array.isArray(exported) ? exported : exported.plans ?? [];
77
+ const projectName = new Map(projects.map((project) => [project.id, project.name]));
78
+ const targetProjects = Array.isArray(exported) ? [] : exported.projects ?? [];
79
+ const targetProjectName = new Map(targetProjects.map((project) => [project.id, project.name]));
80
+
81
+ const seen = new Set(
82
+ existing.map((plan) => key(plan.project?.name ?? targetProjectName.get(plan.project_id) ?? '', plan.title)),
83
+ );
84
+ const knownProjectIds = new Set(existing.map((plan) => plan.project_id));
85
+
86
+ const wanted = plans.filter((plan) => options.all || OPEN_STATUSES.has(plan.status));
87
+ const fresh = [];
88
+ for (const plan of wanted) {
89
+ const name = projectName.get(plan.project_id) ?? '未归档';
90
+ const planKey = key(name, plan.title);
91
+ if (seen.has(planKey)) continue;
92
+ seen.add(planKey);
93
+ fresh.push({ plan, name });
94
+ }
95
+
96
+ const wantedProjects = new Map();
97
+ for (const { plan, name } of fresh) {
98
+ const project = projects.find((item) => item.id === plan.project_id);
99
+ const id = project?.id ?? 'inbox';
100
+ if (knownProjectIds.has(id)) continue;
101
+ wantedProjects.set(id, {
102
+ id,
103
+ name: name || '未归档',
104
+ root_path: project?.root_path ?? 'inbox',
105
+ created_at: project?.created_at ?? plan.created_at,
106
+ updated_at: project?.updated_at ?? plan.updated_at,
107
+ });
108
+ }
109
+
110
+ console.log(`源里 ${plans.length} 条(${options.all ? '全部状态' : '仅未结束'} ${wanted.length} 条),DSH 侧现有 ${existing.length} 条。`);
111
+ if (fresh.length === 0) {
112
+ console.log('没有需要新增的计划,两边已经对齐。');
113
+ return;
114
+ }
115
+
116
+ console.log(`\n会新增 ${fresh.length} 条:`);
117
+ for (const { plan, name } of fresh) {
118
+ console.log(` • [${plan.status}] ${trim(plan.title).slice(0, 70)} (${name})`);
119
+ }
120
+ if (wantedProjects.size > 0) {
121
+ console.log(`\n会补 ${wantedProjects.size} 个项目:${[...wantedProjects.values()].map((project) => project.name).join('、')}`);
122
+ }
123
+
124
+ if (!options.apply) {
125
+ console.log('\n这是 dry-run。确认无误后加 --apply 真正写进 DSH 续忆。');
126
+ return;
127
+ }
128
+
129
+ const payload = {
130
+ format: 'dsh-project-recall',
131
+ version: 1,
132
+ projects: [...wantedProjects.values()],
133
+ plans: fresh.map(({ plan }) => ({
134
+ id: plan.id,
135
+ project_id: plan.project_id,
136
+ title: plan.title,
137
+ details: plan.details ?? '',
138
+ status: plan.status,
139
+ reason_deferred: plan.reason_deferred ?? '',
140
+ reactivation_conditions: Array.isArray(plan.reactivation_conditions) ? plan.reactivation_conditions : [],
141
+ tags: Array.isArray(plan.tags) ? plan.tags : [],
142
+ priority: plan.priority ?? 'medium',
143
+ effort: plan.effort ?? 'unknown',
144
+ source_type: plan.source_type ?? 'conversation',
145
+ source_ref: plan.source_ref ?? '',
146
+ source_excerpt: plan.source_excerpt ?? '',
147
+ review_at: plan.review_at ?? null,
148
+ last_reviewed_at: plan.last_reviewed_at ?? null,
149
+ completed_at: plan.completed_at ?? null,
150
+ created_at: plan.created_at,
151
+ updated_at: plan.updated_at,
152
+ })),
153
+ };
154
+
155
+ const response = await fetch(`${options.target}/project-memory/api/import`, {
156
+ method: 'POST',
157
+ headers: { 'content-type': 'application/json', origin: options.target },
158
+ body: JSON.stringify({ ...payload, mode: 'merge' }),
159
+ });
160
+ const text = await response.text();
161
+ if (!response.ok) {
162
+ throw new Error(`导入失败 HTTP ${response.status}: ${text.slice(0, 300)}`);
163
+ }
164
+ console.log(`\n导入完成: ${text}`);
165
+ }
166
+
167
+ main().catch((error) => {
168
+ console.error(`失败: ${error.message}`);
169
+ process.exit(1);
170
+ });