@dinoxx/dinox-cli 2.18.5 → 2.19.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (33) hide show
  1. package/dist/commands/notes/contentEngine.js +8 -4
  2. package/dist/commands/schema/renderSkills.js +3 -1
  3. package/dist/commands/todo/contentModel.d.ts +5 -3
  4. package/dist/commands/todo/contentModel.js +7 -5
  5. package/dist/commands/todo/dryRun.d.ts +9 -7
  6. package/dist/commands/todo/dryRun.js +99 -86
  7. package/dist/commands/todo/index.js +279 -93
  8. package/dist/commands/todo/repo.d.ts +128 -7
  9. package/dist/commands/todo/repo.js +474 -130
  10. package/dist/commands/todo/taskModel.d.ts +20 -1
  11. package/dist/commands/todo/taskModel.js +153 -20
  12. package/dist/commands/todo/taskPatch.d.ts +119 -0
  13. package/dist/commands/todo/taskPatch.js +502 -0
  14. package/dist/commands/todo/taskText.d.ts +26 -0
  15. package/dist/commands/todo/taskText.js +221 -0
  16. package/dist/dsh-plugin/lib/client.js +713 -289
  17. package/dist/dsh-plugin/lib/index.js +7 -2
  18. package/dist/dsh-plugin/package.json +1 -1
  19. package/dist/dsh-plugin/runtime.json +1 -1
  20. package/dist/editor/compat.d.ts +6 -0
  21. package/dist/editor/compat.js +18 -0
  22. package/dist/editor/daemon.js +27 -0
  23. package/dist/editor/mcp.js +99 -2
  24. package/dist/editor/service.d.ts +57 -1
  25. package/dist/editor/service.js +174 -7
  26. package/dist/editor/todos.d.ts +67 -0
  27. package/dist/editor/todos.js +293 -0
  28. package/dist/editor-ui/mcp-app.html +262 -253
  29. package/dist/integrations/dsh/host.js +10 -2
  30. package/dist/utils/tiptapMarkdown.js +15 -1
  31. package/dist/vendor/electron/shared/task-priority.d.ts +42 -0
  32. package/dist/vendor/electron/shared/task-priority.js +186 -0
  33. package/package.json +1 -1
@@ -1,36 +1,78 @@
1
1
  import { createNote } from '../notes/repo.js';
2
+ import { projectNoteContent, serializeNoteContentMarkdown } from '../notes/contentEngine.js';
2
3
  import { DinoxError } from '../../utils/errors.js';
3
4
  import { generateId } from '../../utils/id.js';
4
5
  import { nowIsoUtc } from '../../utils/time.js';
5
- import { applyTaskCheckedStatus, appendTasksToDoc, buildAppendMarkdown, buildContentTextPreview, buildCreateMarkdown, buildSummaryTitle, createTodoDocFromTasks, deriveImageDetailFromContentJson, normalizeTaskTexts, patchTaskMarkdownByOrder, parseTiptapDocFromDb, } from './contentModel.js';
6
+ import { buildContentTextPreview, buildSummaryTitle, deriveImageDetailFromContentJson, normalizeTaskTexts, patchTaskMarkdownByOrder, parseTiptapDocFromDb, } from './contentModel.js';
7
+ import { appendSubtaskBlock, applyTaskPatches, buildTaskListBlock, countDrafts, findTaskItemById, formatLocalDateKey, normalizeTodoDrafts, parseLocalDateKey, patchLegacyHtmlChecked, resolveTodoDuePoint, } from './taskPatch.js';
6
8
  import { buildTaskKey, extractFlattenedTasks, filterTasksForTodoList, } from './taskModel.js';
7
9
  import { isLegacyTaskId } from './taskIdentity.js';
8
10
  export { normalizeTaskTexts } from './contentModel.js';
9
11
  const TODO_TASK_CANDIDATE_SCAN_LIMIT = 500;
12
+ const TODO_WRITE_ATTEMPTS = 3;
13
+ const CONTENT_TEXT_PREVIEW_LIMIT = 300;
14
+ const DAILY_TODO_TITLE_SUFFIX = '待办';
10
15
  export function validateTodoAppendTarget(target) {
11
16
  if (typeof target.is_del === 'number' && target.is_del !== 0) {
12
- throw new DinoxError(`Note has been deleted: ${target.id}`);
17
+ throw new DinoxError(`Note has been deleted: ${target.id}`, { code: 'NOTE_NOT_FOUND' });
13
18
  }
14
19
  const noteId = target.id?.trim() ?? '';
15
20
  if (!noteId) {
16
21
  throw new DinoxError('Note id is required');
17
22
  }
18
23
  const currentDoc = parseTiptapDocFromDb(target.content_json);
19
- const hasMarkdownSnapshot = Boolean(target.content_md?.trim());
20
- const hasDocContent = Array.isArray(currentDoc.content) && currentDoc.content.length > 0;
21
- if (!hasMarkdownSnapshot && hasDocContent) {
22
- throw new DinoxError('Cannot append todo: current note has non-empty content_json but empty content_md. Please repair note markdown before append.');
23
- }
24
24
  return { currentDoc, noteId, expectedVersion: normalizeVersion(target.version) };
25
25
  }
26
26
  function normalizeVersion(value) {
27
27
  const parsed = Number(value ?? 0);
28
28
  return Number.isSafeInteger(parsed) && parsed >= 0 ? parsed : 0;
29
29
  }
30
- function assertSingleUpdatedRow(result, message) {
31
- if (result.rows?.length !== 1) {
32
- throw new DinoxError(message);
30
+ function concurrentChangeError(noteId, command) {
31
+ return new DinoxError(`Note changed concurrently: ${noteId}. Re-run the todo ${command} command.`);
32
+ }
33
+ /** Plain-text preview from the document itself, so `[time …]` shortcodes never leak into it. */
34
+ function buildContentText(doc, contentMd) {
35
+ let text;
36
+ try {
37
+ text = projectNoteContent(doc).contentText;
38
+ }
39
+ catch {
40
+ return buildContentTextPreview(contentMd);
33
41
  }
42
+ const chars = Array.from(text);
43
+ return chars.length <= CONTENT_TEXT_PREVIEW_LIMIT ? text : chars.slice(0, CONTENT_TEXT_PREVIEW_LIMIT).join('');
44
+ }
45
+ /**
46
+ * Version-checked write of a note's task content. content_json is the source of truth;
47
+ * image_detail, content_md and content_text are derived from it here.
48
+ */
49
+ async function writeTodoNote(db, noteId, expectedVersion, write) {
50
+ const imageDetail = deriveImageDetailFromContentJson(write.doc, noteId);
51
+ const hasContent = write.content !== undefined;
52
+ const result = await db.execute(`
53
+ UPDATE c_note
54
+ SET
55
+ content_json = ?,
56
+ image_detail = ?,
57
+ content_md = ?,
58
+ content_text = ?,${hasContent ? '\n content = ?,' : ''}
59
+ updated_at = ?,
60
+ version = COALESCE(version, 0) + 1
61
+ WHERE id = ?
62
+ AND (is_del IS NULL OR is_del = 0)
63
+ AND COALESCE(version, 0) = ?
64
+ RETURNING id
65
+ `, [
66
+ JSON.stringify(write.doc),
67
+ JSON.stringify(imageDetail),
68
+ write.contentMd,
69
+ buildContentText(write.doc, write.contentMd),
70
+ ...(hasContent ? [write.content ?? null] : []),
71
+ nowIsoUtc(),
72
+ noteId,
73
+ expectedVersion,
74
+ ]);
75
+ return result.rows?.length === 1;
34
76
  }
35
77
  /** Serialize parsed todo-search options into a JSON-safe wire payload. */
36
78
  export function toTodoSearchWire(query, options) {
@@ -39,6 +81,7 @@ export function toTodoSearchWire(query, options) {
39
81
  includeDeleted: options.includeDeleted,
40
82
  taskStatus: options.taskStatus,
41
83
  taskTagFilter: options.taskTagFilter,
84
+ ...(options.taskPriorityFilter?.length ? { taskPriorityFilter: options.taskPriorityFilter } : {}),
42
85
  limit: options.limit,
43
86
  ...(options.offset ? { offset: options.offset } : {}),
44
87
  scanLimit: options.scanLimit,
@@ -61,10 +104,12 @@ export async function executeTodoSearch(db, wire) {
61
104
  includeDeleted: wire.includeDeleted,
62
105
  taskStatus: wire.taskStatus,
63
106
  taskTagFilter: wire.taskTagFilter,
107
+ taskPriorityFilter: wire.taskPriorityFilter ?? [],
64
108
  taskDateRange,
65
109
  limit: wire.limit,
66
110
  offset: wire.offset,
67
111
  scanLimit: wire.scanLimit,
112
+ ...(wire.includeEditText ? { includeEditText: true } : {}),
68
113
  });
69
114
  }
70
115
  export async function searchTodoTasks(db, query, options) {
@@ -72,7 +117,8 @@ export async function searchTodoTasks(db, query, options) {
72
117
  const scanTruncated = scannedRows.length > options.scanLimit;
73
118
  const noteRows = scannedRows.slice(0, options.scanLimit);
74
119
  const allTasks = extractFlattenedTasks(noteRows);
75
- const filteredTasks = filterTasksForTodoList(allTasks, query, options.taskStatus, options.taskTagFilter, options.taskDateRange);
120
+ const taskPriorityFilter = options.taskPriorityFilter ?? [];
121
+ const filteredTasks = filterTasksForTodoList(allTasks, query, options.taskStatus, options.taskTagFilter, options.taskDateRange, taskPriorityFilter);
76
122
  const offset = options.offset ?? 0;
77
123
  const visibleTasks = filteredTasks.slice(offset, offset + options.limit);
78
124
  const tasks = visibleTasks.map((task) => ({
@@ -81,14 +127,17 @@ export async function searchTodoTasks(db, query, options) {
81
127
  note_title: task.noteTitle,
82
128
  task_id: task.taskId,
83
129
  text: task.text,
130
+ ...(options.includeEditText ? { edit_text: task.editText } : {}),
84
131
  checked: task.checked,
85
132
  status: task.checked ? 'completed' : 'uncompleted',
133
+ priority: task.priority,
86
134
  created_at: task.createdAtRaw,
87
135
  depth: task.depth,
88
136
  has_children: task.hasChildren,
89
137
  parent_id: task.parentId,
90
138
  tags: task.tags ?? [],
91
139
  note_tags: task.noteTags ?? [],
140
+ note_box_ids: task.noteBoxIds ?? [],
92
141
  start_time: task.startTime,
93
142
  due_time: task.dueTime,
94
143
  }));
@@ -109,6 +158,7 @@ export async function searchTodoTasks(db, query, options) {
109
158
  applied_filters: {
110
159
  status: options.taskStatus,
111
160
  tags: [...options.taskTagFilter],
161
+ priority: [...taskPriorityFilter],
112
162
  include_deleted: options.includeDeleted,
113
163
  date_range: serializeTaskDateRange(options.taskDateRange),
114
164
  },
@@ -116,101 +166,295 @@ export async function searchTodoTasks(db, query, options) {
116
166
  tasks,
117
167
  };
118
168
  }
119
- export async function appendTodoTasks(db, options) {
120
- const taskTexts = normalizeTaskTexts(options.taskTexts);
121
- const explicitNoteId = typeof options.noteId === 'string' ? options.noteId.trim() : '';
122
- const source = explicitNoteId ? 'explicit' : 'latest_non_empty_image_detail';
169
+ // ---- append ----------------------------------------------------------------------------
170
+ function draftsFromInput(input) {
171
+ const drafts = [...(input.items ?? [])];
172
+ if (input.taskTexts?.length) {
173
+ drafts.push(...normalizeTaskTexts(input.taskTexts).map((text) => ({ text })));
174
+ }
175
+ return normalizeTodoDrafts(drafts);
176
+ }
177
+ function dailyTodoTitle(dayKey) {
178
+ return `${dayKey} ${DAILY_TODO_TITLE_SUFFIX}`;
179
+ }
180
+ export function resolveDailyDayKey(date, now = new Date()) {
181
+ const raw = date?.trim();
182
+ if (!raw)
183
+ return formatLocalDateKey(now);
184
+ const parsed = parseLocalDateKey(raw);
185
+ if (!parsed) {
186
+ throw new DinoxError(`Invalid --date: ${date}. Use a real YYYY-MM-DD date.`, { code: 'INVALID_ARGUMENT' });
187
+ }
188
+ return formatLocalDateKey(parsed);
189
+ }
190
+ /** Resolve the append target and build the new task block without writing anything. */
191
+ export async function planTodoAppend(db, options) {
192
+ const drafts = draftsFromInput(options);
193
+ const explicitNoteId = options.noteId?.trim() ?? '';
194
+ if (options.noteId !== undefined && !explicitNoteId) {
195
+ throw new DinoxError('--note-id cannot be empty', { code: 'INVALID_ARGUMENT' });
196
+ }
197
+ const parentTaskId = options.parentTaskId?.trim() ?? '';
198
+ if (options.parentTaskId !== undefined && !parentTaskId) {
199
+ throw new DinoxError('--parent cannot be empty', { code: 'INVALID_ARGUMENT' });
200
+ }
201
+ if (options.date !== undefined && (explicitNoteId || parentTaskId)) {
202
+ throw new DinoxError('--date only applies to the daily todo note; drop --note-id/--parent', { code: 'INVALID_ARGUMENT' });
203
+ }
204
+ const tasks = [];
205
+ if (parentTaskId) {
206
+ const match = await resolveTaskNote(db, parentTaskId, explicitNoteId || undefined);
207
+ const block = buildTaskListBlock(drafts, { parentTaskId, created: tasks });
208
+ return {
209
+ kind: 'append',
210
+ source: 'task',
211
+ target: match,
212
+ dayKey: null,
213
+ parentTaskId,
214
+ tasks,
215
+ build: (row) => {
216
+ const { currentDoc, noteId, expectedVersion } = validateTodoAppendTarget(row);
217
+ const doc = JSON.parse(JSON.stringify(currentDoc));
218
+ const parent = findTaskItemById(doc, noteId, parentTaskId);
219
+ if (!parent) {
220
+ throw new DinoxError(`Task not found: ${parentTaskId}`, { code: 'TODO_TASK_NOT_FOUND' });
221
+ }
222
+ appendSubtaskBlock(parent, JSON.parse(JSON.stringify(block)));
223
+ // Nesting changes the list structure, so content_md is regenerated from content_json.
224
+ return { noteId, expectedVersion, doc, contentMd: serializeNoteContentMarkdown(doc) };
225
+ },
226
+ };
227
+ }
228
+ const dayKey = explicitNoteId ? null : resolveDailyDayKey(options.date, options.now);
229
+ // A future daily note is still created today; pin its tasks to the requested day.
230
+ const defaultSchedule = !explicitNoteId && options.date ? { date: dayKey } : undefined;
231
+ const block = buildTaskListBlock(drafts, { parentTaskId: null, created: tasks, defaultSchedule });
123
232
  const target = explicitNoteId
124
233
  ? await getTodoAppendTargetById(db, explicitNoteId)
125
- : await getLatestTodoAppendTarget(db);
234
+ : await getDailyTodoTarget(db, dayKey);
126
235
  if (!target) {
127
236
  if (explicitNoteId) {
128
- throw new DinoxError(`Note not found: ${explicitNoteId}`);
237
+ throw new DinoxError(`Note not found: ${explicitNoteId}`, { code: 'NOTE_NOT_FOUND' });
129
238
  }
130
- throw new DinoxError('No eligible note found for append. Try `dino todo create ...` first.');
131
- }
132
- const { currentDoc, noteId, expectedVersion } = validateTodoAppendTarget(target);
133
- const nextDoc = appendTasksToDoc(currentDoc, taskTexts);
134
- const imageDetail = deriveImageDetailFromContentJson(nextDoc, noteId);
135
- const contentMd = buildAppendMarkdown(target.content_md, taskTexts);
136
- const contentText = buildContentTextPreview(contentMd);
137
- const now = nowIsoUtc();
138
- const updateResult = await db.execute(`
139
- UPDATE c_note
140
- SET
141
- content_json = ?,
142
- image_detail = ?,
143
- content_md = ?,
144
- content_text = ?,
145
- updated_at = ?,
146
- version = COALESCE(version, 0) + 1
147
- WHERE id = ?
148
- AND (is_del IS NULL OR is_del = 0)
149
- AND COALESCE(version, 0) = ?
150
- RETURNING id
151
- `, [
152
- JSON.stringify(nextDoc),
153
- JSON.stringify(imageDetail),
154
- contentMd,
155
- contentText,
156
- now,
157
- noteId,
158
- expectedVersion,
159
- ]);
160
- assertSingleUpdatedRow(updateResult, `Note changed concurrently: ${noteId}. Re-run the todo append command.`);
239
+ return {
240
+ kind: 'create_daily',
241
+ source: 'daily',
242
+ dayKey: dayKey,
243
+ title: dailyTodoTitle(dayKey),
244
+ doc: { type: 'doc', content: [block] },
245
+ tasks,
246
+ };
247
+ }
161
248
  return {
162
- note_id: noteId,
163
- title: (target.title ?? '').trim(),
164
- appended_count: taskTexts.length,
165
- source,
249
+ kind: 'append',
250
+ source: explicitNoteId ? 'explicit' : 'daily',
251
+ target,
252
+ dayKey,
253
+ parentTaskId: null,
254
+ tasks,
255
+ build: (row) => {
256
+ const { currentDoc, noteId, expectedVersion } = validateTodoAppendTarget(row);
257
+ const doc = JSON.parse(JSON.stringify(currentDoc));
258
+ const content = doc.content;
259
+ const last = content[content.length - 1];
260
+ const newItems = JSON.parse(JSON.stringify(block.content ?? []));
261
+ if (last && last.type === 'taskList') {
262
+ last.content = [...(Array.isArray(last.content) ? last.content : []), ...newItems];
263
+ }
264
+ else {
265
+ content.push({ ...block, content: newItems });
266
+ }
267
+ // Existing Markdown is kept verbatim; only the new block is rendered from its JSON.
268
+ const blockMd = serializeNoteContentMarkdown({ type: 'doc', content: [{ ...block, content: newItems }] });
269
+ const existingMd = (row.content_md ?? '').replace(/(?:\r\n|\n|\r)+$/, '');
270
+ const contentMd = existingMd.trim()
271
+ ? `${existingMd}\n\n${blockMd}`
272
+ : serializeNoteContentMarkdown(doc);
273
+ return { noteId, expectedVersion, doc, contentMd };
274
+ },
166
275
  };
167
276
  }
277
+ export async function appendTodoTasks(db, options) {
278
+ const plan = await planTodoAppend(db, options);
279
+ if (plan.kind === 'create_daily') {
280
+ if (!options.userId) {
281
+ throw new DinoxError('Cannot create the daily todo note without a user id');
282
+ }
283
+ const noteId = generateId();
284
+ const contentMd = serializeNoteContentMarkdown(plan.doc);
285
+ const created = await createNote(db, {
286
+ id: noteId,
287
+ title: plan.title,
288
+ noteType: 'note',
289
+ contentMd,
290
+ contentJson: plan.doc,
291
+ contentText: buildContentText(plan.doc, contentMd),
292
+ tags: [],
293
+ zettelBoxIds: [],
294
+ userId: options.userId,
295
+ imageDetail: deriveImageDetailFromContentJson(plan.doc, noteId),
296
+ });
297
+ return {
298
+ note_id: created.id,
299
+ title: plan.title,
300
+ appended_count: plan.tasks.length,
301
+ source: 'daily',
302
+ created: true,
303
+ day_key: plan.dayKey,
304
+ parent_task_id: null,
305
+ tasks: plan.tasks,
306
+ };
307
+ }
308
+ let row = plan.target;
309
+ let noteId = (row.id ?? '').trim();
310
+ for (let attempt = 0; attempt < TODO_WRITE_ATTEMPTS; attempt += 1) {
311
+ if (!row)
312
+ throw new DinoxError(`Note not found: ${noteId}`, { code: 'NOTE_NOT_FOUND' });
313
+ const next = plan.build(row);
314
+ noteId = next.noteId;
315
+ if (await writeTodoNote(db, next.noteId, next.expectedVersion, next)) {
316
+ return {
317
+ note_id: next.noteId,
318
+ title: (row.title ?? '').trim(),
319
+ appended_count: plan.tasks.length,
320
+ source: plan.source,
321
+ created: false,
322
+ day_key: plan.dayKey,
323
+ parent_task_id: plan.parentTaskId,
324
+ tasks: plan.tasks,
325
+ };
326
+ }
327
+ // Lost the version race (e.g. a sync landed in between): re-read and rebuild on fresh content.
328
+ row = await getTodoAppendTargetById(db, next.noteId);
329
+ }
330
+ throw concurrentChangeError(noteId, 'append');
331
+ }
168
332
  export async function createTodoNote(db, options) {
169
- const taskTexts = normalizeTaskTexts(options.taskTexts);
170
- const title = options.title?.trim() || buildSummaryTitle(taskTexts);
333
+ const drafts = draftsFromInput(options);
334
+ const title = options.title?.trim() || buildSummaryTitle(drafts.map((draft) => draft.text));
171
335
  const noteId = generateId();
172
- const contentJson = createTodoDocFromTasks(taskTexts);
173
- const imageDetail = deriveImageDetailFromContentJson(contentJson, noteId);
174
- const contentMd = buildCreateMarkdown(taskTexts);
175
- const contentText = buildContentTextPreview(contentMd);
336
+ const tasks = [];
337
+ const contentJson = { type: 'doc', content: [buildTaskListBlock(drafts, { parentTaskId: null, created: tasks })] };
338
+ const contentMd = serializeNoteContentMarkdown(contentJson);
176
339
  const created = await createNote(db, {
177
340
  id: noteId,
178
341
  title,
179
342
  noteType: 'note',
180
343
  contentMd,
181
344
  contentJson,
182
- contentText,
345
+ contentText: buildContentText(contentJson, contentMd),
183
346
  tags: [],
184
347
  zettelBoxIds: [],
185
348
  userId: options.userId,
186
- imageDetail,
349
+ imageDetail: deriveImageDetailFromContentJson(contentJson, noteId),
187
350
  });
188
351
  return {
189
352
  note_id: created.id,
190
353
  title,
191
- created_count: taskTexts.length,
354
+ created_count: countDrafts(drafts),
355
+ tasks,
192
356
  };
193
357
  }
194
- export async function updateTodoTaskStatus(db, options) {
195
- const taskId = options.taskId.trim();
196
- if (!taskId) {
197
- throw new DinoxError('taskId is required');
358
+ export function previewCreateTodoNote(options) {
359
+ const drafts = draftsFromInput(options);
360
+ const tasks = [];
361
+ buildTaskListBlock(drafts, { parentTaskId: null, created: tasks });
362
+ return {
363
+ title: options.title?.trim() || buildSummaryTitle(drafts.map((draft) => draft.text)),
364
+ created_count: countDrafts(drafts),
365
+ tasks,
366
+ };
367
+ }
368
+ function toTaskPatch(update) {
369
+ const patch = { taskId: update.taskId.trim() };
370
+ if (typeof update.checked === 'boolean')
371
+ patch.checked = update.checked;
372
+ if (update.priority !== undefined)
373
+ patch.priority = update.priority;
374
+ if (update.schedule !== undefined) {
375
+ patch.dueAt = update.schedule === null ? null : resolveTodoDuePoint(update.schedule);
376
+ }
377
+ if (update.text !== undefined) {
378
+ const text = update.text.replace(/\s+/g, ' ').trim();
379
+ if (!text)
380
+ throw new DinoxError('Task text cannot be empty', { code: 'INVALID_ARGUMENT' });
381
+ patch.text = text;
382
+ }
383
+ return patch;
384
+ }
385
+ function hasMutation(patch) {
386
+ return patch.checked !== undefined || patch.priority !== undefined || patch.dueAt !== undefined || Boolean(patch.remove)
387
+ || patch.text !== undefined || patch.paragraph !== undefined;
388
+ }
389
+ /**
390
+ * content_md follows content_json. A checked-only change patches the checkbox characters in
391
+ * place so the rest of the Markdown stays byte-identical; anything else (or a checklist that
392
+ * no longer lines up with the JSON) regenerates content_md from the document.
393
+ */
394
+ function nextContentMarkdown(row, patches, outcome) {
395
+ const onlyChecked = patches.every((patch) => patch.priority === undefined && patch.dueAt === undefined && !patch.remove
396
+ && patch.text === undefined && patch.paragraph === undefined);
397
+ const current = row.content_md ?? '';
398
+ if (onlyChecked && current.trim()) {
399
+ try {
400
+ let markdown = current;
401
+ for (const value of [true, false]) {
402
+ const indices = outcome.taskOrder.flatMap((taskId, index) => outcome.checkedChanges.get(taskId) === value ? [index] : []);
403
+ markdown = patchTaskMarkdownByOrder(markdown, outcome.taskOrder, indices, value);
404
+ }
405
+ return markdown;
406
+ }
407
+ catch {
408
+ // Fall through to regeneration.
409
+ }
198
410
  }
199
- const candidates = await loadTodoTaskCandidatesByTaskId(db, taskId, { noteId: options.noteId });
411
+ return serializeNoteContentMarkdown(outcome.doc);
412
+ }
413
+ function planNoteUpdate(row, patches) {
414
+ const noteId = (row.id ?? '').trim();
415
+ if (!noteId)
416
+ throw new DinoxError('Note id is required');
417
+ const doc = parseTiptapDocFromDb(row.content_json);
418
+ const outcome = applyTaskPatches(doc, noteId, patches);
419
+ if (outcome.missingTaskIds.length > 0) {
420
+ throw new DinoxError(`Task not found: ${outcome.missingTaskIds.join(', ')}`, {
421
+ code: 'TODO_TASK_NOT_FOUND',
422
+ details: { noteId, missingTaskIds: outcome.missingTaskIds },
423
+ });
424
+ }
425
+ if (!outcome.changed) {
426
+ // Never write when only legacy ids would be materialized.
427
+ return { noteId, row, patches, outcome, write: null };
428
+ }
429
+ const contentMd = nextContentMarkdown(row, patches, outcome);
430
+ const legacyHtml = patchLegacyHtmlChecked(row.content, outcome.checkedChanges);
431
+ return {
432
+ noteId,
433
+ row,
434
+ patches,
435
+ outcome,
436
+ write: {
437
+ doc: outcome.doc,
438
+ contentMd,
439
+ ...(legacyHtml !== (row.content ?? null) ? { content: legacyHtml } : {}),
440
+ },
441
+ };
442
+ }
443
+ /** Find the single note holding a task (explicit or legacy id), with the existing safety errors. */
444
+ async function resolveTaskNote(db, taskId, noteId) {
445
+ const candidates = await loadTodoTaskCandidatesByTaskId(db, taskId, { noteId });
200
446
  const matches = [];
201
447
  const skippedCandidates = [];
202
448
  for (const candidate of candidates) {
203
449
  try {
204
- const noteId = (candidate.id ?? '').trim();
205
- if (!noteId) {
450
+ const candidateNoteId = (candidate.id ?? '').trim();
451
+ if (!candidateNoteId) {
206
452
  throw new DinoxError('Note id is required');
207
453
  }
208
454
  const doc = parseTiptapDocFromDb(candidate.content_json);
209
- const applied = applyTaskCheckedStatus(doc, noteId, taskId, options.checked);
210
- if (applied.matchedIndices.length === 0) {
211
- continue;
455
+ if (findTaskItemById(JSON.parse(JSON.stringify(doc)), candidateNoteId, taskId)) {
456
+ matches.push(candidate);
212
457
  }
213
- matches.push({ candidate, applied });
214
458
  }
215
459
  catch (error) {
216
460
  skippedCandidates.push({
@@ -243,77 +487,174 @@ export async function updateTodoTaskStatus(db, options) {
243
487
  recoverable: true,
244
488
  });
245
489
  }
246
- throw new DinoxError(`Task not found: ${taskId}`);
490
+ throw new DinoxError(`Task not found: ${taskId}`, { code: 'TODO_TASK_NOT_FOUND' });
247
491
  }
248
492
  if (matches.length > 1) {
249
493
  const noteIds = matches
250
- .map((entry) => entry.candidate.id?.trim())
494
+ .map((entry) => entry.id?.trim())
251
495
  .filter((value) => Boolean(value));
252
496
  throw new DinoxError(`Task id is not unique; found in multiple notes: ${noteIds.join(', ')}`);
253
497
  }
254
- const match = matches[0];
255
- const noteId = (match.candidate.id ?? '').trim();
256
- if (!noteId) {
257
- throw new DinoxError('Note id is required');
498
+ return matches[0];
499
+ }
500
+ /** Normalize updates: drop no-op entries, merge repeats of one task (later fields win). */
501
+ function normalizeTaskUpdates(updates) {
502
+ const merged = new Map();
503
+ for (const update of updates) {
504
+ const taskId = typeof update?.taskId === 'string' ? update.taskId.trim() : '';
505
+ if (!taskId) {
506
+ throw new DinoxError('Each task update needs a taskId', { code: 'INVALID_ARGUMENT' });
507
+ }
508
+ const noteId = update.noteId?.trim() || undefined;
509
+ if (update.noteId !== undefined && !noteId) {
510
+ throw new DinoxError('--note-id cannot be empty', { code: 'INVALID_ARGUMENT' });
511
+ }
512
+ const key = `${noteId ?? ''}\0${taskId}`;
513
+ const previous = merged.get(key);
514
+ const next = { ...(previous ?? {}), taskId, ...(noteId ? { noteId } : {}) };
515
+ if (typeof update.checked === 'boolean')
516
+ next.checked = update.checked;
517
+ if (update.priority !== undefined)
518
+ next.priority = update.priority;
519
+ if (update.schedule !== undefined)
520
+ next.schedule = update.schedule;
521
+ if (update.text !== undefined)
522
+ next.text = update.text;
523
+ merged.set(key, next);
258
524
  }
259
- const nextContentMd = patchTaskMarkdownByOrder(match.candidate.content_md, match.applied.taskOrder, match.applied.matchedIndices, options.checked);
260
- const nextContentText = buildContentTextPreview(nextContentMd);
261
- const nextImageDetail = deriveImageDetailFromContentJson(match.applied.nextDoc, noteId);
262
- const hasMarkdownChanged = nextContentMd !== (match.candidate.content_md ?? '');
263
- const hasStatusChanged = match.applied.statusChangedCount > 0;
264
- if (!hasStatusChanged && !hasMarkdownChanged) {
265
- return {
266
- note_id: noteId,
267
- task_id: taskId,
268
- checked: options.checked,
269
- updated: false,
270
- title: (match.candidate.title ?? '').trim(),
271
- };
525
+ const normalized = [...merged.values()].filter((update) => hasMutation(toTaskPatch(update)));
526
+ if (normalized.length === 0) {
527
+ throw new DinoxError('Nothing to update: pass --status, --priority, --due or --clear-due', { code: 'INVALID_ARGUMENT' });
528
+ }
529
+ return normalized;
530
+ }
531
+ /** Group updates per note (one write per note) and compute each note's patched content. */
532
+ export async function planTodoUpdates(db, updates) {
533
+ const normalized = normalizeTaskUpdates(updates);
534
+ const grouped = new Map();
535
+ for (const update of normalized) {
536
+ const patch = toTaskPatch(update);
537
+ const row = await resolveTaskNote(db, patch.taskId, update.noteId);
538
+ const noteId = (row.id ?? '').trim();
539
+ const group = grouped.get(noteId);
540
+ if (group)
541
+ group.patches.push(patch);
542
+ else
543
+ grouped.set(noteId, { row, patches: [patch] });
544
+ }
545
+ return [...grouped.values()].map(({ row, patches }) => planNoteUpdate(row, patches));
546
+ }
547
+ async function rereadNote(db, noteId, taskId) {
548
+ const rows = await loadTodoTaskCandidatesByTaskId(db, taskId, { noteId });
549
+ const row = rows[0];
550
+ if (!row)
551
+ throw new DinoxError(`Note not found: ${noteId}`, { code: 'NOTE_NOT_FOUND' });
552
+ return row;
553
+ }
554
+ function summarizePlan(plan, written) {
555
+ return plan.outcome.results.map((result) => ({
556
+ ...result,
557
+ note_id: plan.noteId,
558
+ note_title: (plan.row.title ?? '').trim(),
559
+ updated: written && (result.checked_from !== result.checked_to
560
+ || result.priority_from !== result.priority_to
561
+ || JSON.stringify(result.due_from) !== JSON.stringify(result.due_to)
562
+ || result.cascaded_task_ids.length > 0
563
+ || Boolean(result.removed)
564
+ || result.text_from !== undefined),
565
+ }));
566
+ }
567
+ /** Batch task update (checked / priority / due), one version-checked write per note. */
568
+ export async function updateTodoTasks(db, updates) {
569
+ return writeUpdatePlans(db, await planTodoUpdates(db, updates));
570
+ }
571
+ export async function restoreTodoTasks(db, entries) {
572
+ const grouped = new Map();
573
+ for (const entry of entries) {
574
+ const patch = { taskId: entry.taskId.trim(), cascade: false };
575
+ if (entry.checked !== undefined)
576
+ patch.checked = entry.checked;
577
+ if (entry.priority !== undefined)
578
+ patch.priority = entry.priority;
579
+ if (entry.dueAt !== undefined)
580
+ patch.dueAt = entry.dueAt;
581
+ if (entry.remove)
582
+ patch.remove = true;
583
+ if (entry.paragraph !== undefined)
584
+ patch.paragraph = entry.paragraph;
585
+ const group = grouped.get(entry.noteId);
586
+ if (group) {
587
+ group.patches.push(patch);
588
+ continue;
589
+ }
590
+ grouped.set(entry.noteId, { row: await resolveTaskNote(db, patch.taskId, entry.noteId), patches: [patch] });
591
+ }
592
+ return writeUpdatePlans(db, [...grouped.values()].map(({ row, patches }) => planNoteUpdate(row, patches)));
593
+ }
594
+ async function writeUpdatePlans(db, plans) {
595
+ const tasks = [];
596
+ for (let plan of plans) {
597
+ let written = false;
598
+ for (let attempt = 0; plan.write && attempt < TODO_WRITE_ATTEMPTS; attempt += 1) {
599
+ if (await writeTodoNote(db, plan.noteId, normalizeVersion(plan.row.version), plan.write)) {
600
+ written = true;
601
+ break;
602
+ }
603
+ plan = planNoteUpdate(await rereadNote(db, plan.noteId, plan.patches[0].taskId), plan.patches);
604
+ }
605
+ if (plan.write && !written)
606
+ throw concurrentChangeError(plan.noteId, 'update');
607
+ tasks.push(...summarizePlan(plan, written));
272
608
  }
273
- const updateResult = await db.execute(`
274
- UPDATE c_note
275
- SET
276
- content_json = ?,
277
- image_detail = ?,
278
- content_md = ?,
279
- content_text = ?,
280
- updated_at = ?,
281
- version = COALESCE(version, 0) + 1
282
- WHERE id = ?
283
- AND (is_del IS NULL OR is_del = 0)
284
- AND COALESCE(version, 0) = ?
285
- RETURNING id
286
- `, [
287
- JSON.stringify(match.applied.nextDoc),
288
- JSON.stringify(nextImageDetail),
289
- nextContentMd,
290
- nextContentText,
291
- nowIsoUtc(),
292
- noteId,
293
- normalizeVersion(match.candidate.version),
294
- ]);
295
- assertSingleUpdatedRow(updateResult, `Note changed concurrently: ${noteId}. Re-run the todo update command.`);
296
609
  return {
297
- note_id: noteId,
298
- task_id: taskId,
299
- checked: options.checked,
300
- updated: true,
301
- title: (match.candidate.title ?? '').trim(),
610
+ updated_count: tasks.filter((task) => task.updated).length,
611
+ note_ids: plans.map((plan) => plan.noteId),
612
+ tasks,
302
613
  };
303
614
  }
615
+ export async function updateTodoTaskStatus(db, options) {
616
+ const taskId = options.taskId.trim();
617
+ if (!taskId) {
618
+ throw new DinoxError('taskId is required', { code: 'INVALID_ARGUMENT' });
619
+ }
620
+ const result = await updateTodoTasks(db, [{
621
+ taskId,
622
+ ...(options.noteId !== undefined ? { noteId: options.noteId } : {}),
623
+ ...(options.checked !== undefined ? { checked: options.checked } : {}),
624
+ ...(options.priority !== undefined ? { priority: options.priority } : {}),
625
+ ...(options.schedule !== undefined ? { schedule: options.schedule } : {}),
626
+ }]);
627
+ const task = result.tasks[0];
628
+ return {
629
+ note_id: task.note_id,
630
+ task_id: task.task_id,
631
+ checked: task.checked_to,
632
+ priority: task.priority_to,
633
+ due_time: task.due_to,
634
+ updated: task.updated,
635
+ cascaded_task_ids: task.cascaded_task_ids,
636
+ title: task.note_title,
637
+ };
638
+ }
639
+ // ---- reads -----------------------------------------------------------------------------
304
640
  async function loadTodoNoteRows(db, includeDeleted, scanLimit) {
641
+ // content_json is the source of truth (the app derives its task index from it);
642
+ // image_detail is kept as a fallback for notes whose content_json is unreadable.
305
643
  const whereClauses = [
306
644
  includeDeleted ? '1 = 1' : '(n.is_del IS NULL OR n.is_del = 0)',
307
- 'n.image_detail IS NOT NULL',
308
- "LENGTH(TRIM(n.image_detail)) > 0",
309
- "TRIM(n.image_detail) <> '[]'",
645
+ `(
646
+ n.content_json LIKE '%"taskItem"%'
647
+ OR (n.image_detail IS NOT NULL AND LENGTH(TRIM(n.image_detail)) > 0 AND TRIM(n.image_detail) <> '[]')
648
+ )`,
310
649
  ];
311
650
  return db.getAll(`
312
651
  SELECT
313
652
  n.id,
314
653
  n.title,
654
+ n.content_json,
315
655
  n.image_detail,
316
656
  n.tags,
657
+ n.zettel_boxes,
317
658
  n.created_at,
318
659
  n.updated_at
319
660
  FROM c_note n
@@ -335,7 +676,8 @@ export async function getTodoAppendTargetById(db, noteId) {
335
676
  WHERE n.id = ?
336
677
  `, [noteId]);
337
678
  }
338
- export async function getLatestTodoAppendTarget(db) {
679
+ /** The latest live note created on `dayKey` (local time) that already holds tasks. */
680
+ export async function getDailyTodoTarget(db, dayKey) {
339
681
  return db.getOptional(`
340
682
  SELECT
341
683
  n.id,
@@ -346,25 +688,25 @@ export async function getLatestTodoAppendTarget(db) {
346
688
  n.version
347
689
  FROM c_note n
348
690
  WHERE (n.is_del IS NULL OR n.is_del = 0)
349
- AND n.image_detail IS NOT NULL
350
- AND LENGTH(TRIM(n.image_detail)) > 0
351
- AND TRIM(n.image_detail) <> '[]'
352
- ORDER BY n.created_at DESC
691
+ AND DATE(n.created_at, 'localtime') = DATE(?)
692
+ AND n.content_json LIKE '%"taskItem"%'
693
+ ORDER BY n.created_at DESC, n.id DESC
353
694
  LIMIT 1
354
- `, []);
695
+ `, [dayKey]);
355
696
  }
356
697
  export async function loadTodoTaskCandidatesByTaskId(db, taskId, options = {}) {
357
698
  const exactNoteId = options.noteId?.trim();
358
699
  if (options.noteId !== undefined && !exactNoteId) {
359
- throw new DinoxError('--note-id cannot be empty');
700
+ throw new DinoxError('--note-id cannot be empty', { code: 'INVALID_ARGUMENT' });
360
701
  }
361
702
  if (exactNoteId) {
362
- return db.getAll(`
703
+ const rows = await db.getAll(`
363
704
  SELECT
364
705
  n.id,
365
706
  n.title,
366
707
  n.content_json,
367
708
  n.content_md,
709
+ n.content,
368
710
  n.is_del,
369
711
  n.created_at,
370
712
  n.version
@@ -375,6 +717,7 @@ export async function loadTodoTaskCandidatesByTaskId(db, taskId, options = {}) {
375
717
  AND LENGTH(TRIM(n.content_json)) > 0
376
718
  LIMIT 1
377
719
  `, [exactNoteId]);
720
+ return rows;
378
721
  }
379
722
  const pattern = isLegacyTaskId(taskId)
380
723
  ? '%taskItem%'
@@ -386,6 +729,7 @@ export async function loadTodoTaskCandidatesByTaskId(db, taskId, options = {}) {
386
729
  n.title,
387
730
  n.content_json,
388
731
  n.content_md,
732
+ n.content,
389
733
  n.is_del,
390
734
  n.created_at,
391
735
  n.version