dsh-todo-time-log 0.5.0 → 0.5.2

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/lib/index.js CHANGED
@@ -32,6 +32,195 @@ import { formatLocalDateTime, TIME_FORMAT, EMPTY_TIME } from './time.js';
32
32
  import { parseQuickAdd, parseQuickAddLine, hasQuickAddMarkers } from './parse.js';
33
33
  import { createFileIndex } from './files.js';
34
34
 
35
+ /**
36
+ * A todo record exactly as `store.js` persists it (see the data-model comment
37
+ * at the top of that module). `project` is `''` for 未分类, `priority`/`type`
38
+ * are `''` when unset, and `completedAt` is non-null exactly while completed.
39
+ *
40
+ * @typedef {object} Todo
41
+ * @property {string} id
42
+ * @property {string} title
43
+ * @property {string} project
44
+ * @property {string[]} files
45
+ * @property {'pending' | 'completed'} status
46
+ * @property {string} priority
47
+ * @property {string} type
48
+ * @property {string} createdAt
49
+ * @property {string | null} completedAt
50
+ * @property {string} updatedAt
51
+ */
52
+
53
+ /**
54
+ * Display-only fields `decorateTodo()` adds on top of a stored todo.
55
+ *
56
+ * @typedef {object} DecoratedFields
57
+ * @property {string} projectLabel
58
+ * @property {string} priorityLabel
59
+ * @property {string} typeLabel
60
+ * @property {number} fileCount
61
+ * @property {string[]} fileNames
62
+ * @property {string} createdAtLocal
63
+ * @property {string} completedAtLocal
64
+ * @property {string} updatedAtLocal
65
+ * @property {string} statusLabel
66
+ */
67
+
68
+ /** @typedef {Todo & DecoratedFields} DecoratedTodo */
69
+
70
+ /**
71
+ * One row of the per-category summary (`store.computeProjects()`).
72
+ *
73
+ * @typedef {object} ProjectGroup
74
+ * @property {string} name
75
+ * @property {number} count
76
+ * @property {number} pending
77
+ * @property {number} completed
78
+ */
79
+
80
+ /**
81
+ * List statistics (`store.computeStats()`).
82
+ *
83
+ * @typedef {object} TodoStats
84
+ * @property {number} total
85
+ * @property {number} pending
86
+ * @property {number} completed
87
+ */
88
+
89
+ /**
90
+ * A quick-add line that produced no title and was therefore not created.
91
+ *
92
+ * @typedef {object} SkippedLine
93
+ * @property {string} line
94
+ * @property {string} reason
95
+ */
96
+
97
+ /**
98
+ * One quick-add line that the store rejected.
99
+ *
100
+ * @typedef {object} QuickAddError
101
+ * @property {string} title
102
+ * @property {string} [code]
103
+ * @property {string} [message]
104
+ */
105
+
106
+ /**
107
+ * The union of every field `executeTodoAction()` understands. Every action reads
108
+ * only the fields it documents; all are optional because both the HTTP body and
109
+ * the tool arguments are untrusted JSON (a missing field must fall back to the
110
+ * store default rather than throw).
111
+ *
112
+ * @typedef {object} TodoActionPayload
113
+ * @property {string} [action] tool: list / get / create / …
114
+ * @property {string} [id]
115
+ * @property {string} [title]
116
+ * @property {string | null} [project] '' = 未分类; null = not supplied
117
+ * @property {string[] | null} [files]
118
+ * @property {string | null} [priority]
119
+ * @property {string | null} [type]
120
+ * @property {string} [text] quick_add: raw natural language
121
+ * @property {string} [filter] list: all / pending / completed
122
+ * @property {string} [sortBy] list: createdAt / completedAt / …
123
+ * @property {string} [direction] list: asc / desc
124
+ * @property {string | number} [at] complete: explicit completion time
125
+ * @property {string} [workspace] /files, /projects, /quick-add root
126
+ */
127
+
128
+ /**
129
+ * Result envelope of `executeTodoAction()`. Success and failure share one shape
130
+ * because both the HTTP route and the tool render either branch; every payload
131
+ * field is optional and present only for the action that produced it.
132
+ *
133
+ * @typedef {object} TodoResult
134
+ * @property {boolean} ok
135
+ * @property {string} [code]
136
+ * @property {string} [message]
137
+ * @property {string[]} [notices]
138
+ * @property {Todo[]} [todos]
139
+ * @property {TodoStats} [stats]
140
+ * @property {ProjectGroup[]} [projects]
141
+ * @property {string} [filter]
142
+ * @property {string} [sortBy]
143
+ * @property {string} [direction]
144
+ * @property {string | null} [project]
145
+ * @property {string} [timeFormat]
146
+ * @property {Todo} [todo]
147
+ * @property {string} [deleted]
148
+ * @property {Todo[]} [created]
149
+ * @property {SkippedLine[]} [skipped]
150
+ * @property {QuickAddError[]} [errors]
151
+ * @property {number} [parsed]
152
+ * @property {number} [count]
153
+ * @property {string} [dataFile]
154
+ * @property {boolean} [persisted]
155
+ * @property {{ code?: string, message?: string }} [error]
156
+ */
157
+
158
+ /**
159
+ * Result of `runQuickAdd()`: a result envelope whose payload is the quick-add
160
+ * outcome instead of a single todo.
161
+ *
162
+ * @typedef {object} QuickAddResult
163
+ * @property {boolean} ok
164
+ * @property {string} [code]
165
+ * @property {string} [message]
166
+ * @property {Todo[]} [created]
167
+ * @property {SkippedLine[]} [skipped]
168
+ * @property {QuickAddError[]} [errors]
169
+ * @property {number} [parsed]
170
+ * @property {string | null} [workspaceRoot]
171
+ */
172
+
173
+ /**
174
+ * The cached workspace file index returned by `createFileIndex()`.
175
+ *
176
+ * @typedef {object} FileIndex
177
+ * @property {(request?: { root?: string, query?: string, limit?: number }) => Promise<{ root: string, files: string[], total: number, truncated: boolean }>} list
178
+ * @property {(request?: { root?: string, limit?: number }) => Promise<string[]>} listDirectories
179
+ * @property {(explicitRoot?: string) => Promise<Set<string>>} knownFileSet
180
+ * @property {() => void} invalidate
181
+ */
182
+
183
+ /**
184
+ * Row config accepted by `apply()` (see `cordis.patch.yml`).
185
+ *
186
+ * @typedef {object} PluginConfig
187
+ * @property {string} [dataFile]
188
+ * @property {string} [workspaceRoot]
189
+ */
190
+
191
+ /**
192
+ * The subset of the Cordis plugin context this module touches. Every member is
193
+ * optional so the plugin still loads on a build that lacks one of the services.
194
+ *
195
+ * @typedef {object} PluginContext
196
+ * @property {(name: string) => any} [get]
197
+ * @property {(callback: Function) => any} [effect]
198
+ * @property {(names: string[], callback: Function) => void} [inject]
199
+ * @property {(name: string) => any} [logger]
200
+ * @property {{ register: Function }} [webServer]
201
+ * @property {{ register: Function }} [tools]
202
+ * @property {{ register: Function }} [commands]
203
+ */
204
+
205
+ /**
206
+ * A slash-command invocation as passed by the Harness.
207
+ *
208
+ * @typedef {object} CommandInvocation
209
+ * @property {string} [rawInput]
210
+ * @property {Array<{ type?: string, attachment?: { name?: string } }>} [attachments]
211
+ */
212
+
213
+ /**
214
+ * Options of `createHttpHandler()`: every collaborator is injectable so the
215
+ * route can be tested without a live profile.
216
+ *
217
+ * @typedef {object} HttpHandlerOptions
218
+ * @property {FileIndex | null} [fileIndex]
219
+ * @property {() => string} [getWorkspaceRoot]
220
+ * @property {string} [workspaceRoot]
221
+ * @property {() => Array<{ path: string, title: string, source: string }>} [listWorkspaces]
222
+ */
223
+
35
224
  export const name = 'dsh-todo-time-log';
36
225
 
37
226
  /**
@@ -114,7 +303,12 @@ function defaultBaseDir() {
114
303
  return path.join(os.homedir(), '.dsh');
115
304
  }
116
305
 
117
- /** Resolve the data file: row config > env override > profile-scoped default. */
306
+ /**
307
+ * Resolve the data file: row config > env override > profile-scoped default.
308
+ *
309
+ * @param {PluginConfig} [config]
310
+ * @returns {string}
311
+ */
118
312
  export function resolveDataFile(config = {}) {
119
313
  const configured = typeof config?.dataFile === 'string' ? config.dataFile.trim() : '';
120
314
  if (configured !== '') {
@@ -137,6 +331,10 @@ export function resolveDataFile(config = {}) {
137
331
  * The panel is not Session-bound, so this list is also what `/workspaces`
138
332
  * exposes and what `/files` accepts an explicit `workspace` from: a client can
139
333
  * only ask for a root that is already a known workspace.
334
+ *
335
+ * @param {PluginContext} ctx
336
+ * @param {PluginConfig} [config]
337
+ * @returns {Array<{ path: string, title: string, source: string }>}
140
338
  */
141
339
  export function listWorkspaceCandidates(ctx, config = {}) {
142
340
  const seen = new Map();
@@ -217,12 +415,22 @@ export function listWorkspaceCandidates(ctx, config = {}) {
217
415
  return [...seen.values()];
218
416
  }
219
417
 
220
- /** The active workspace root: the first candidate. */
418
+ /**
419
+ * The active workspace root: the first candidate.
420
+ *
421
+ * @param {PluginContext} ctx
422
+ * @param {PluginConfig} [config]
423
+ * @returns {string}
424
+ */
221
425
  export function resolveWorkspaceRoot(ctx, config = {}) {
222
426
  const candidates = listWorkspaceCandidates(ctx, config);
223
427
  return candidates[0]?.path ?? process.cwd();
224
428
  }
225
429
 
430
+ /**
431
+ * @param {PluginContext} ctx
432
+ * @returns {{ debug: Function, info: Function, warn: Function, error: Function }}
433
+ */
226
434
  function createLogger(ctx) {
227
435
  const prefix = '[dsh-todo-time-log]';
228
436
  let sink = null;
@@ -239,6 +447,13 @@ function createLogger(ctx) {
239
447
  return { debug: emit('debug'), info: emit('info'), warn: emit('warn'), error: emit('error') };
240
448
  }
241
449
 
450
+ /**
451
+ * The failure half of the result envelope.
452
+ *
453
+ * @param {string} code
454
+ * @param {string} message
455
+ * @returns {{ ok: false, code: string, message: string }}
456
+ */
242
457
  function failure(code, message) {
243
458
  return { ok: false, code, message };
244
459
  }
@@ -246,8 +461,14 @@ function failure(code, message) {
246
461
  /**
247
462
  * The single implementation of every operation. Both the HTTP route and the
248
463
  * agent tool call this; it never throws for expected user errors.
464
+ *
465
+ * @param {TodoStore} store
466
+ * @param {string} action
467
+ * @param {TodoActionPayload} [payload]
468
+ * @returns {Promise<TodoResult>}
249
469
  */
250
470
  export async function executeTodoAction(store, action, payload = {}) {
471
+ /** @type {TodoActionPayload} */
251
472
  const body = payload && typeof payload === 'object' ? payload : {};
252
473
  switch (action) {
253
474
  case 'list': {
@@ -322,7 +543,12 @@ export async function executeTodoAction(store, action, payload = {}) {
322
543
  }
323
544
  }
324
545
 
325
- /** Add the display-formatted local times a model-facing result needs. */
546
+ /**
547
+ * Add the display-formatted local times a model-facing result needs.
548
+ *
549
+ * @param {Todo} todo
550
+ * @returns {DecoratedTodo}
551
+ */
326
552
  export function decorateTodo(todo) {
327
553
  const files = Array.isArray(todo.files) ? todo.files : [];
328
554
  const priority = todo.priority ?? '';
@@ -345,16 +571,33 @@ export function decorateTodo(todo) {
345
571
  };
346
572
  }
347
573
 
348
- /** `【高】` / `【中】` / `【低】`; '' when no priority is set. */
574
+ /**
575
+ * `【高】` / `【中】` / `【低】`; '' when no priority is set.
576
+ *
577
+ * @param {Todo} todo
578
+ * @returns {string}
579
+ */
349
580
  function priorityTag(todo) {
350
581
  const label = PRIORITY_LABELS[todo?.priority] ?? '';
351
582
  return label === '' ? '' : `【${label}】`;
352
583
  }
353
584
 
585
+ /**
586
+ * `[分类] `; '' when the todo is uncategorized.
587
+ *
588
+ * @param {Todo} todo
589
+ * @returns {string}
590
+ */
354
591
  function projectTag(todo) {
355
592
  return todo.project ? `[${todo.project}] ` : '';
356
593
  }
357
594
 
595
+ /**
596
+ * `|文件 a、b`; '' when the todo references no file.
597
+ *
598
+ * @param {Todo} todo
599
+ * @returns {string}
600
+ */
358
601
  function fileSuffix(todo) {
359
602
  const files = Array.isArray(todo.files) ? todo.files : [];
360
603
  if (files.length === 0) return '';
@@ -371,6 +614,14 @@ function fileSuffix(todo) {
371
614
  *
372
615
  * Names are de-duplicated case-insensitively and must fit the stored project
373
616
  * limit, so a suggestion is always immediately acceptable as a category.
617
+ *
618
+ * @param {{
619
+ * used?: Array<{ name: string, count?: number }>,
620
+ * workspaces?: Array<{ title?: string }>,
621
+ * folders?: string[],
622
+ * limit?: number,
623
+ * }} [options]
624
+ * @returns {Array<{ name: string, source: string, count: number }>}
374
625
  */
375
626
  export function buildProjectSuggestions(options = {}) {
376
627
  const { used = [], workspaces = [], folders = [], limit = 80 } = options;
@@ -406,6 +657,15 @@ export function buildProjectSuggestions(options = {}) {
406
657
  * `extraPriority` is the form-picker value: a `!high`-style marker in a line
407
658
  * always wins, otherwise the picker value applies to every created todo.
408
659
  * `extraType` follows the same fallback rule for `^bug`-style type markers.
660
+ *
661
+ * @param {TodoStore} store
662
+ * @param {FileIndex | null} fileIndex
663
+ * @param {string} text
664
+ * @param {string} [workspaceRoot]
665
+ * @param {string[]} [extraFiles]
666
+ * @param {string} [extraPriority]
667
+ * @param {string} [extraType]
668
+ * @returns {Promise<QuickAddResult>}
409
669
  */
410
670
  export async function runQuickAdd(store, fileIndex, text, workspaceRoot = '', extraFiles = [], extraPriority = '', extraType = '') {
411
671
  const raw = typeof text === 'string' ? text : '';
@@ -428,10 +688,13 @@ export async function runQuickAdd(store, fileIndex, text, workspaceRoot = '', ex
428
688
  const inherited = Array.isArray(extraFiles)
429
689
  ? extraFiles.map((file) => normalizeFilePath(file)).filter((file) => file !== '')
430
690
  : [];
691
+ /** @type {Todo[]} */
431
692
  const created = [];
693
+ /** @type {QuickAddError[]} */
432
694
  const errors = [];
433
695
  for (const item of items) {
434
696
  const mergedFiles = [...new Set([...(item.files ?? []), ...inherited])].slice(0, MAX_FILES);
697
+ /** @type {TodoResult} */
435
698
  const result = await store.create({
436
699
  title: item.title,
437
700
  project: item.project === '' ? undefined : item.project,
@@ -457,6 +720,11 @@ export async function runQuickAdd(store, fileIndex, text, workspaceRoot = '', ex
457
720
  * `/todo 写周报` with a file attached (or `@`-mentioned through the composer)
458
721
  * records a usable reference. A name that is already a relative path wins;
459
722
  * otherwise the first indexed file with the same basename is used.
723
+ *
724
+ * @param {CommandInvocation} invocation
725
+ * @param {FileIndex | null} fileIndex
726
+ * @param {string} workspaceRoot
727
+ * @returns {Promise<string[]>}
460
728
  */
461
729
  export async function resolveCommandAttachmentFiles(invocation, fileIndex, workspaceRoot) {
462
730
  const blocks = Array.isArray(invocation?.attachments) ? invocation.attachments : [];
@@ -486,6 +754,13 @@ export async function resolveCommandAttachmentFiles(invocation, fileIndex, works
486
754
 
487
755
  const STATUS_LABEL = { pending: '未完成', completed: '已完成' };
488
756
 
757
+ /**
758
+ * Render one result envelope as the model-facing text.
759
+ *
760
+ * @param {string} action
761
+ * @param {TodoResult} value
762
+ * @returns {string}
763
+ */
489
764
  export function renderTodoResult(action, value) {
490
765
  if (!value || value.ok !== true) {
491
766
  const code = value?.code ?? value?.error?.code ?? 'INTERNAL';
@@ -566,7 +841,14 @@ export function renderTodoResult(action, value) {
566
841
  return JSON.stringify(value) + notices;
567
842
  }
568
843
 
569
- /** Build the single agent tool definition shared by every action. */
844
+ /**
845
+ * Build the single agent tool definition shared by every action.
846
+ *
847
+ * @param {TodoStore} store
848
+ * @param {FileIndex | null} [fileIndex]
849
+ * @param {() => string} [getWorkspaceRoot]
850
+ * @returns {object}
851
+ */
570
852
  export function createTodoTool(store, fileIndex = null, getWorkspaceRoot = () => '') {
571
853
  return {
572
854
  name: TOOL_NAME,
@@ -681,7 +963,12 @@ export function createTodoTool(store, fileIndex = null, getWorkspaceRoot = () =>
681
963
  return [{ type: 'text', text: renderTodoResult(action, value) }];
682
964
  },
683
965
  },
966
+ /**
967
+ * @param {TodoActionPayload} [rawArgs]
968
+ * @returns {Promise<TodoResult & { action: string }>}
969
+ */
684
970
  async execute(rawArgs) {
971
+ /** @type {TodoActionPayload} */
685
972
  const args = rawArgs && typeof rawArgs === 'object' ? rawArgs : {};
686
973
  const action = typeof args.action === 'string' ? args.action : '';
687
974
  try {
@@ -719,6 +1006,12 @@ export function createTodoTool(store, fileIndex = null, getWorkspaceRoot = () =>
719
1006
  };
720
1007
  }
721
1008
 
1009
+ /**
1010
+ * Map a result code onto the HTTP status the panel expects.
1011
+ *
1012
+ * @param {string} [code]
1013
+ * @returns {number}
1014
+ */
722
1015
  function httpStatusForCode(code) {
723
1016
  switch (code) {
724
1017
  case 'BAD_REQUEST':
@@ -744,6 +1037,14 @@ function httpStatusForCode(code) {
744
1037
  }
745
1038
  }
746
1039
 
1040
+ /**
1041
+ * Send one JSON envelope and end the response.
1042
+ *
1043
+ * @param {import('node:http').ServerResponse} res
1044
+ * @param {number} status
1045
+ * @param {any} payload a JSON-serialisable response envelope
1046
+ * @returns {void}
1047
+ */
747
1048
  function sendJson(res, status, payload) {
748
1049
  const body = JSON.stringify(payload);
749
1050
  res.statusCode = status;
@@ -752,6 +1053,12 @@ function sendJson(res, status, payload) {
752
1053
  res.end(body);
753
1054
  }
754
1055
 
1056
+ /**
1057
+ * Read and parse a JSON request body (an empty body means `{}`).
1058
+ *
1059
+ * @param {import('node:http').IncomingMessage} req
1060
+ * @returns {Promise<Record<string, any>>}
1061
+ */
755
1062
  function readJsonBody(req) {
756
1063
  return new Promise((resolve, reject) => {
757
1064
  const chunks = [];
@@ -793,6 +1100,10 @@ function readJsonBody(req) {
793
1100
  /**
794
1101
  * HTTP front door for the Web UI. Mounted as a `prefix` route, so every request
795
1102
  * whose path starts with ROUTE_PREFIX lands here; the suffix selects the action.
1103
+ *
1104
+ * @param {TodoStore} store
1105
+ * @param {HttpHandlerOptions} [options]
1106
+ * @returns {(req: import('node:http').IncomingMessage, res: import('node:http').ServerResponse) => Promise<void>}
796
1107
  */
797
1108
  export function createHttpHandler(store, options = {}) {
798
1109
  const fileIndex = options.fileIndex ?? null;
@@ -1007,6 +1318,10 @@ export function createHttpHandler(store, options = {}) {
1007
1318
  * observe an optional service (and its later removal). The direct fallback keeps
1008
1319
  * the plugin working on a Cordis build without it, at the cost of not observing
1009
1320
  * a service mounted after activation.
1321
+ *
1322
+ * @param {PluginContext} ctx
1323
+ * @param {string[]} dependencies
1324
+ * @param {(scope: PluginContext) => void} setup
1010
1325
  */
1011
1326
  function mountOn(ctx, dependencies, setup) {
1012
1327
  if (typeof ctx.inject === 'function') {
@@ -1020,6 +1335,12 @@ function mountOn(ctx, dependencies, setup) {
1020
1335
  }
1021
1336
  }
1022
1337
 
1338
+ /**
1339
+ * Mount the plugin against the given services.
1340
+ *
1341
+ * @param {PluginContext} ctx
1342
+ * @param {PluginConfig} [config]
1343
+ */
1023
1344
  export function apply(ctx, config = {}) {
1024
1345
  const logger = createLogger(ctx);
1025
1346
  const dataFile = resolveDataFile(config);
package/lib/parse.js CHANGED
@@ -148,7 +148,7 @@ export function hasQuickAddMarkers(text) {
148
148
  if (typeof text !== 'string' || text === '') return false;
149
149
  if (hasPriorityMarker(text)) return true;
150
150
  if (hasTypeMarker(text)) return true;
151
- return /(^|\s)[#@]|\[[^\[\]]*\]|(?:项目|分类)\s*[::]|[\r\n]|;|;/.test(text);
151
+ return /(^|\s)[#@]|\[[^[\]]*\]|(?:项目|分类)\s*[::]|[\r\n]|;|;/.test(text);
152
152
  }
153
153
 
154
154
  /** True when an `@token` should be read as a workspace file instead of a category. */
@@ -229,7 +229,7 @@ function collectProject(line) {
229
229
  const candidates = [];
230
230
  const patterns = [
231
231
  { pattern: /(?:项目|分类)\s*[::]\s*([^\s,,;;]+)/g, valueIndex: 1 },
232
- { pattern: /\[([^\[\]]*)\]/g, valueIndex: 1 },
232
+ { pattern: /\[([^[\]]*)\]/g, valueIndex: 1 },
233
233
  { pattern: /#([^\s#,,;;]+)/g, valueIndex: 1 },
234
234
  { pattern: /(^|\s)@([^\s@]+)/g, valueIndex: 2 },
235
235
  ];