advisers 0.3.2 → 0.4.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README-zh.md +13 -14
- package/README.md +37 -23
- package/THIRD-PARTY-NOTICES.md +1 -1
- package/bin/advisers.js +2302 -95
- package/index.js +1 -1
- package/lib/brief-archive.js +267 -0
- package/lib/client-pack.js +1016 -0
- package/lib/consent.js +390 -0
- package/lib/credentials.js +195 -0
- package/lib/error-codes.js +516 -7
- package/lib/evidence.js +697 -113
- package/lib/kb-extract.js +626 -0
- package/lib/kb-facts.js +429 -0
- package/lib/kb-pages.js +1084 -0
- package/lib/kb.js +1036 -0
- package/lib/mail-errors.js +46 -0
- package/lib/mail-extract.js +351 -0
- package/lib/mail-imap.js +446 -0
- package/lib/mail-import.js +176 -0
- package/lib/mail-parse.js +223 -0
- package/lib/mail-store.js +731 -0
- package/lib/mail.js +506 -0
- package/lib/mcp-server.js +196 -10
- package/lib/notify.js +265 -7
- package/lib/policy/decision.js +315 -0
- package/lib/policy/egress.js +268 -0
- package/lib/policy/errors.js +71 -0
- package/lib/policy/index.js +99 -0
- package/lib/policy/rules.js +468 -0
- package/lib/policy/surfaces.js +141 -0
- package/lib/receipt-verify.js +199 -19
- package/lib/receivables.js +1653 -0
- package/lib/scheduler.js +453 -9
- package/lib/shell.js +1406 -0
- package/lib/source.js +98 -3
- package/lib/sqlite.js +366 -49
- package/lib/tos/index.js +2 -2
- package/lib/tos/manifest.json +6 -6
- package/lib/tos/privacy.zh-CN.md +33 -20
- package/lib/tos/safety.zh-CN.md +7 -6
- package/lib/tos/summary.zh-CN.md +3 -2
- package/lib/tos/terms.zh-CN.md +31 -16
- package/lib/urgency.js +467 -0
- package/package.json +4 -4
package/lib/scheduler.js
CHANGED
|
@@ -23,12 +23,26 @@ export const DEFAULT_CRON_SCHEDULE = '0 9 * * *'
|
|
|
23
23
|
export const DEFAULT_TASK_NAME = 'Advisers Remind'
|
|
24
24
|
export const DEFAULT_TASK_TIME = '09:00'
|
|
25
25
|
export const DEFAULT_REMIND_ARGS = Object.freeze(['remind', '--deliver', '--notify'])
|
|
26
|
+
|
|
27
|
+
/** Proactive 0.4: second managed crontab block for the archived morning brief. */
|
|
28
|
+
export const MORNING_CRON_MARKER = 'advisers-morning'
|
|
29
|
+
export const DEFAULT_MORNING_CRON_SCHEDULE = '30 8 * * 1-5'
|
|
30
|
+
export const DEFAULT_MORNING_TASK_NAME = 'Advisers Morning'
|
|
31
|
+
export const DEFAULT_MORNING_TASK_TIME = '08:30'
|
|
32
|
+
/** Windows weekly day abbreviations accepted by `schtasks /D`. */
|
|
33
|
+
export const DEFAULT_MORNING_WEEKDAYS = Object.freeze(['MON', 'TUE', 'WED', 'THU', 'FRI'])
|
|
34
|
+
export const DEFAULT_MORNING_ARGS = Object.freeze(['morning', '--archive'])
|
|
35
|
+
|
|
36
|
+
/** Version 2 scheduler status: per-section lastRun for remind + morning. */
|
|
37
|
+
export const SCHEDULER_STATUS_VERSION_V2 = 2
|
|
38
|
+
export const SCHEDULER_SECTIONS = Object.freeze(['remind', 'morning'])
|
|
26
39
|
/** Platforms where `crontab(1)` is the user-level scheduler. */
|
|
27
40
|
export const CRON_PLATFORMS = Object.freeze(['linux', 'darwin', 'freebsd', 'openbsd', 'sunos'])
|
|
28
41
|
|
|
29
42
|
const MARKER_PATTERN = /^[A-Za-z0-9._-]{1,64}$/
|
|
30
43
|
const CRON_FIELD = /^[0-9A-Za-z*,/-]+$/
|
|
31
44
|
const TASK_TIME = /^([01][0-9]|2[0-3]):[0-5][0-9]$/
|
|
45
|
+
const TASK_DAY = /^(MON|TUE|WED|THU|FRI|SAT|SUN)$/
|
|
32
46
|
|
|
33
47
|
/** Quote one argv element for a POSIX shell (cron runs commands via /bin/sh). */
|
|
34
48
|
export function quoteShellArgument(value) {
|
|
@@ -170,6 +184,93 @@ export function removeCronEntry(text, { marker = CRON_MARKER } = {}) {
|
|
|
170
184
|
return { text: remaining, changed: true, removed: true }
|
|
171
185
|
}
|
|
172
186
|
|
|
187
|
+
|
|
188
|
+
function normalizeMarkers(markers) {
|
|
189
|
+
if (!Array.isArray(markers) || !markers.length) throw new TypeError('markers must be a non-empty array')
|
|
190
|
+
const seen = new Set()
|
|
191
|
+
const list = []
|
|
192
|
+
for (const marker of markers) {
|
|
193
|
+
const safe = validateMarker(marker)
|
|
194
|
+
if (seen.has(safe)) throw new TypeError(`duplicate scheduler marker: ${safe}`)
|
|
195
|
+
seen.add(safe)
|
|
196
|
+
list.push(safe)
|
|
197
|
+
}
|
|
198
|
+
return list
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
function normalizeCronBlocks(blocks) {
|
|
202
|
+
if (!Array.isArray(blocks) || !blocks.length) throw new TypeError('blocks must be a non-empty array')
|
|
203
|
+
const seen = new Set()
|
|
204
|
+
return blocks.map((block) => {
|
|
205
|
+
if (!block || typeof block !== 'object') throw new TypeError('each scheduler block must be an object')
|
|
206
|
+
const marker = validateMarker(block.marker)
|
|
207
|
+
if (seen.has(marker)) throw new TypeError(`duplicate scheduler marker: ${marker}`)
|
|
208
|
+
seen.add(marker)
|
|
209
|
+
return {
|
|
210
|
+
marker,
|
|
211
|
+
schedule: validateCronSchedule(block.schedule ?? DEFAULT_CRON_SCHEDULE),
|
|
212
|
+
command: validateCronCommand(block.command),
|
|
213
|
+
}
|
|
214
|
+
})
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
/**
|
|
218
|
+
* Read several managed blocks in the caller-supplied `markers` order.
|
|
219
|
+
* Unmanaged crontab lines are never inspected or modified.
|
|
220
|
+
*
|
|
221
|
+
* @returns {Array<{marker: string, installed: boolean, schedule: string|null,
|
|
222
|
+
* command: string|null, malformed: boolean}>}
|
|
223
|
+
*/
|
|
224
|
+
export function getCronEntries(text, { markers = [CRON_MARKER] } = {}) {
|
|
225
|
+
const list = normalizeMarkers(markers)
|
|
226
|
+
return list.map((marker) => ({ marker, ...getCronEntry(text, { marker }) }))
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
/**
|
|
230
|
+
* Append or replace several managed blocks in one pass. Blocks are applied in
|
|
231
|
+
* order to the evolving text; every other crontab line is preserved verbatim.
|
|
232
|
+
*
|
|
233
|
+
* @returns {{text: string, changed: boolean, blocks: Array<{marker: string,
|
|
234
|
+
* changed: boolean, added: boolean, alreadyInstalled: boolean, updated: boolean}>}}
|
|
235
|
+
*/
|
|
236
|
+
export function addCronBlocks(text, { blocks } = {}) {
|
|
237
|
+
const list = normalizeCronBlocks(blocks)
|
|
238
|
+
let current = String(text ?? '')
|
|
239
|
+
let changed = false
|
|
240
|
+
const results = []
|
|
241
|
+
for (const block of list) {
|
|
242
|
+
const change = addCronEntry(current, block)
|
|
243
|
+
current = change.text
|
|
244
|
+
changed = changed || change.changed
|
|
245
|
+
results.push({
|
|
246
|
+
marker: block.marker,
|
|
247
|
+
changed: change.changed,
|
|
248
|
+
added: change.added,
|
|
249
|
+
alreadyInstalled: change.alreadyInstalled,
|
|
250
|
+
updated: change.updated,
|
|
251
|
+
})
|
|
252
|
+
}
|
|
253
|
+
return { text: current, changed, blocks: results }
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
/**
|
|
257
|
+
* Remove several managed blocks by marker, leaving every unmanaged line as-is.
|
|
258
|
+
* A marker that is not installed is reported (not an error), so uninstall is
|
|
259
|
+
* idempotent for both blocks.
|
|
260
|
+
*
|
|
261
|
+
* @returns {{text: string, changed: boolean, removedMarkers: string[]}}
|
|
262
|
+
*/
|
|
263
|
+
export function removeCronBlocks(text, { markers } = {}) {
|
|
264
|
+
const list = normalizeMarkers(markers)
|
|
265
|
+
let current = String(text ?? '')
|
|
266
|
+
const removedMarkers = []
|
|
267
|
+
for (const marker of list) {
|
|
268
|
+
const change = removeCronEntry(current, { marker })
|
|
269
|
+
current = change.text
|
|
270
|
+
if (change.removed) removedMarkers.push(marker)
|
|
271
|
+
}
|
|
272
|
+
return { text: current, changed: removedMarkers.length > 0, removedMarkers }
|
|
273
|
+
}
|
|
173
274
|
export function crontabReadCommand() {
|
|
174
275
|
return { command: 'crontab', args: ['-l'] }
|
|
175
276
|
}
|
|
@@ -194,17 +295,51 @@ export function validateTaskTime(time) {
|
|
|
194
295
|
return text
|
|
195
296
|
}
|
|
196
297
|
|
|
298
|
+
/**
|
|
299
|
+
* Validate a Windows weekly day list (`MON`..`SUN`), as an array or a
|
|
300
|
+
* comma-separated string. Duplicates collapse and the input order is preserved.
|
|
301
|
+
*
|
|
302
|
+
* @param {string[]|string} days
|
|
303
|
+
* @returns {string[]}
|
|
304
|
+
*/
|
|
305
|
+
export function validateTaskDays(days) {
|
|
306
|
+
const items = Array.isArray(days) ? days : typeof days === 'string' ? days.split(',') : null
|
|
307
|
+
if (!items) throw new TypeError('task days must be an array or a comma-separated string')
|
|
308
|
+
const seen = new Set()
|
|
309
|
+
const normalized = []
|
|
310
|
+
for (const item of items) {
|
|
311
|
+
const text = String(item ?? '').trim().toUpperCase()
|
|
312
|
+
if (!TASK_DAY.test(text)) throw new TypeError(`invalid task day: ${String(item)} (expected MON..SUN)`)
|
|
313
|
+
if (seen.has(text)) continue
|
|
314
|
+
seen.add(text)
|
|
315
|
+
normalized.push(text)
|
|
316
|
+
}
|
|
317
|
+
if (!normalized.length) throw new TypeError('task days must not be empty')
|
|
318
|
+
return normalized
|
|
319
|
+
}
|
|
320
|
+
|
|
197
321
|
/**
|
|
198
322
|
* Generate the schtasks argv for create/delete/query. Nothing is executed.
|
|
199
323
|
*
|
|
324
|
+
* Proactive 0.4 adds an additive `schedule: 'daily'|'weekly'` (+ `days` for
|
|
325
|
+
* weekly); the default daily argv is byte-identical to 0.3.2.
|
|
326
|
+
*
|
|
200
327
|
* @returns {{ command: 'schtasks', args: string[] }}
|
|
201
328
|
*/
|
|
202
|
-
export function buildSchtasksCommand({ action = 'create', taskName = DEFAULT_TASK_NAME, command, time = DEFAULT_TASK_TIME } = {}) {
|
|
329
|
+
export function buildSchtasksCommand({ action = 'create', taskName = DEFAULT_TASK_NAME, command, time = DEFAULT_TASK_TIME, schedule = 'daily', days } = {}) {
|
|
203
330
|
const safeTask = validateTaskName(taskName)
|
|
204
331
|
if (action === 'create') {
|
|
205
332
|
const safeCommand = validateCronCommand(command)
|
|
206
333
|
const safeTime = validateTaskTime(time)
|
|
207
|
-
|
|
334
|
+
if (schedule === 'daily') {
|
|
335
|
+
if (days !== undefined && days !== null) throw new TypeError('a daily schtasks schedule does not take days')
|
|
336
|
+
return { command: 'schtasks', args: ['/Create', '/TN', safeTask, '/TR', safeCommand, '/SC', 'DAILY', '/ST', safeTime, '/F'] }
|
|
337
|
+
}
|
|
338
|
+
if (schedule === 'weekly') {
|
|
339
|
+
const safeDays = validateTaskDays(days ?? DEFAULT_MORNING_WEEKDAYS)
|
|
340
|
+
return { command: 'schtasks', args: ['/Create', '/TN', safeTask, '/TR', safeCommand, '/SC', 'WEEKLY', '/D', safeDays.join(','), '/ST', safeTime, '/F'] }
|
|
341
|
+
}
|
|
342
|
+
throw new TypeError(`unknown schtasks schedule: ${String(schedule)}`)
|
|
208
343
|
}
|
|
209
344
|
if (action === 'delete') return { command: 'schtasks', args: ['/Delete', '/TN', safeTask, '/F'] }
|
|
210
345
|
if (action === 'query') return { command: 'schtasks', args: ['/Query', '/TN', safeTask] }
|
|
@@ -255,9 +390,59 @@ export function planCronStatus({ existingText = '', marker = CRON_MARKER } = {})
|
|
|
255
390
|
}
|
|
256
391
|
}
|
|
257
392
|
|
|
258
|
-
|
|
259
|
-
|
|
393
|
+
|
|
394
|
+
/**
|
|
395
|
+
* Dry-run plan for installing several cron blocks at once (one `crontab -`
|
|
396
|
+
* write for all changes, matching 0.3.2's single-block contract).
|
|
397
|
+
*/
|
|
398
|
+
export function planCronInstallBlocks({ existingText = '', blocks, dryRun = true } = {}) {
|
|
399
|
+
const list = normalizeCronBlocks(blocks)
|
|
400
|
+
const change = addCronBlocks(existingText, { blocks: list })
|
|
401
|
+
return {
|
|
402
|
+
platform: 'cron',
|
|
403
|
+
action: 'install',
|
|
404
|
+
dryRun: dryRun !== false,
|
|
405
|
+
changed: change.changed,
|
|
406
|
+
installed: true,
|
|
407
|
+
markers: list.map((block) => block.marker),
|
|
408
|
+
blocks: change.blocks,
|
|
409
|
+
text: change.text,
|
|
410
|
+
commands: change.changed ? [crontabWriteCommand(change.text)] : [],
|
|
411
|
+
}
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
/** Dry-run plan for removing several cron blocks at once. */
|
|
415
|
+
export function planCronUninstallBlocks({ existingText = '', markers, dryRun = true } = {}) {
|
|
416
|
+
const list = normalizeMarkers(markers)
|
|
417
|
+
const change = removeCronBlocks(existingText, { markers: list })
|
|
418
|
+
return {
|
|
419
|
+
platform: 'cron',
|
|
420
|
+
action: 'uninstall',
|
|
421
|
+
dryRun: dryRun !== false,
|
|
422
|
+
changed: change.changed,
|
|
423
|
+
installed: false,
|
|
424
|
+
markers: list,
|
|
425
|
+
removedMarkers: change.removedMarkers,
|
|
426
|
+
text: change.text,
|
|
427
|
+
commands: change.changed ? [crontabWriteCommand(change.text)] : [],
|
|
428
|
+
}
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
/** Read-only status for several cron blocks (the CLI executes the read command). */
|
|
432
|
+
export function planCronStatusBlocks({ existingText = '', markers = [CRON_MARKER, MORNING_CRON_MARKER] } = {}) {
|
|
433
|
+
const list = normalizeMarkers(markers)
|
|
260
434
|
return {
|
|
435
|
+
platform: 'cron',
|
|
436
|
+
action: 'status',
|
|
437
|
+
dryRun: true,
|
|
438
|
+
entries: list.map((marker) => getCronEntry(existingText, { marker })),
|
|
439
|
+
commands: [crontabReadCommand()],
|
|
440
|
+
}
|
|
441
|
+
}
|
|
442
|
+
/** Dry-run plan for a Windows Task Scheduler install (argv only, not executed). */
|
|
443
|
+
export function planWindowsInstall({ command, taskName = DEFAULT_TASK_NAME, time = DEFAULT_TASK_TIME, schedule = 'daily', days, dryRun = true } = {}) {
|
|
444
|
+
if (schedule !== 'daily' && schedule !== 'weekly') throw new TypeError(`unknown schtasks schedule: ${String(schedule)}`)
|
|
445
|
+
const plan = {
|
|
261
446
|
platform: 'win32',
|
|
262
447
|
action: 'install',
|
|
263
448
|
dryRun: dryRun !== false,
|
|
@@ -265,8 +450,11 @@ export function planWindowsInstall({ command, taskName = DEFAULT_TASK_NAME, time
|
|
|
265
450
|
installed: null,
|
|
266
451
|
taskName: validateTaskName(taskName),
|
|
267
452
|
time: validateTaskTime(time),
|
|
268
|
-
|
|
453
|
+
schedule,
|
|
454
|
+
commands: [buildSchtasksCommand({ action: 'create', taskName, command, time, schedule, ...(days === undefined ? {} : { days }) })],
|
|
269
455
|
}
|
|
456
|
+
if (schedule === 'weekly') plan.days = validateTaskDays(days ?? DEFAULT_MORNING_WEEKDAYS)
|
|
457
|
+
return plan
|
|
270
458
|
}
|
|
271
459
|
|
|
272
460
|
export function planWindowsUninstall({ taskName = DEFAULT_TASK_NAME, dryRun = true } = {}) {
|
|
@@ -294,6 +482,94 @@ export function planWindowsStatus({ taskName = DEFAULT_TASK_NAME } = {}) {
|
|
|
294
482
|
}
|
|
295
483
|
}
|
|
296
484
|
|
|
485
|
+
function normalizeWindowsInstallBlock(block) {
|
|
486
|
+
if (!block || typeof block !== 'object') throw new TypeError('each scheduler block must be an object')
|
|
487
|
+
const schedule = block.schedule === undefined ? (block.days === undefined ? 'daily' : 'weekly') : block.schedule
|
|
488
|
+
if (schedule !== 'daily' && schedule !== 'weekly') throw new TypeError(`unknown schtasks schedule: ${String(schedule)}`)
|
|
489
|
+
const taskName = validateTaskName(block.taskName ?? (schedule === 'weekly' ? DEFAULT_MORNING_TASK_NAME : DEFAULT_TASK_NAME))
|
|
490
|
+
const time = validateTaskTime(block.time ?? (schedule === 'weekly' ? DEFAULT_MORNING_TASK_TIME : DEFAULT_TASK_TIME))
|
|
491
|
+
const days = schedule === 'weekly' ? validateTaskDays(block.days ?? DEFAULT_MORNING_WEEKDAYS) : undefined
|
|
492
|
+
return {
|
|
493
|
+
marker: block.marker === undefined || block.marker === null ? null : validateMarker(block.marker),
|
|
494
|
+
taskName,
|
|
495
|
+
command: validateCronCommand(block.command),
|
|
496
|
+
time,
|
|
497
|
+
schedule,
|
|
498
|
+
days,
|
|
499
|
+
}
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
function normalizeWindowsTaskList(blocks) {
|
|
503
|
+
if (!Array.isArray(blocks) || !blocks.length) throw new TypeError('blocks must be a non-empty array')
|
|
504
|
+
return blocks.map((block) => {
|
|
505
|
+
if (typeof block === 'string') return { taskName: validateTaskName(block) }
|
|
506
|
+
if (!block || typeof block !== 'object') throw new TypeError('each scheduler block must be an object or a task name')
|
|
507
|
+
if (block.taskName === undefined || block.taskName === null) throw new TypeError('windows scheduler blocks require taskName')
|
|
508
|
+
return { taskName: validateTaskName(block.taskName) }
|
|
509
|
+
})
|
|
510
|
+
}
|
|
511
|
+
|
|
512
|
+
/**
|
|
513
|
+
* Dry-run plan for installing several Windows scheduled tasks (argv only).
|
|
514
|
+
* Each block carries its own taskName/time/schedule/days; the daily argv is
|
|
515
|
+
* byte-identical to the 0.3.2 single-task plan.
|
|
516
|
+
*/
|
|
517
|
+
export function planWindowsInstallBlocks({ blocks, dryRun = true } = {}) {
|
|
518
|
+
if (!Array.isArray(blocks) || !blocks.length) throw new TypeError('blocks must be a non-empty array')
|
|
519
|
+
const list = blocks.map(normalizeWindowsInstallBlock)
|
|
520
|
+
return {
|
|
521
|
+
platform: 'win32',
|
|
522
|
+
action: 'install',
|
|
523
|
+
dryRun: dryRun !== false,
|
|
524
|
+
changed: true,
|
|
525
|
+
installed: null,
|
|
526
|
+
blocks: list.map((block) => ({
|
|
527
|
+
marker: block.marker,
|
|
528
|
+
taskName: block.taskName,
|
|
529
|
+
time: block.time,
|
|
530
|
+
schedule: block.schedule,
|
|
531
|
+
...(block.days ? { days: block.days } : {}),
|
|
532
|
+
})),
|
|
533
|
+
commands: list.map((block) => buildSchtasksCommand({
|
|
534
|
+
action: 'create',
|
|
535
|
+
taskName: block.taskName,
|
|
536
|
+
command: block.command,
|
|
537
|
+
time: block.time,
|
|
538
|
+
schedule: block.schedule,
|
|
539
|
+
...(block.days ? { days: block.days } : {}),
|
|
540
|
+
})),
|
|
541
|
+
}
|
|
542
|
+
}
|
|
543
|
+
|
|
544
|
+
/** Dry-run plan for removing several Windows scheduled tasks (argv only). */
|
|
545
|
+
export function planWindowsUninstallBlocks({ blocks, dryRun = true } = {}) {
|
|
546
|
+
const list = normalizeWindowsTaskList(blocks)
|
|
547
|
+
return {
|
|
548
|
+
platform: 'win32',
|
|
549
|
+
action: 'uninstall',
|
|
550
|
+
dryRun: dryRun !== false,
|
|
551
|
+
changed: true,
|
|
552
|
+
installed: false,
|
|
553
|
+
blocks: list.map((block) => ({ taskName: block.taskName })),
|
|
554
|
+
commands: list.map((block) => buildSchtasksCommand({ action: 'delete', taskName: block.taskName })),
|
|
555
|
+
}
|
|
556
|
+
}
|
|
557
|
+
|
|
558
|
+
/** Read-only plan for several Windows scheduled tasks (the CLI runs the query). */
|
|
559
|
+
export function planWindowsStatusBlocks({ blocks } = {}) {
|
|
560
|
+
const list = normalizeWindowsTaskList(blocks)
|
|
561
|
+
return {
|
|
562
|
+
platform: 'win32',
|
|
563
|
+
action: 'status',
|
|
564
|
+
dryRun: true,
|
|
565
|
+
installed: null,
|
|
566
|
+
entries: list.map((block) => ({
|
|
567
|
+
taskName: block.taskName,
|
|
568
|
+
installed: null,
|
|
569
|
+
commands: [buildSchtasksCommand({ action: 'query', taskName: block.taskName })],
|
|
570
|
+
})),
|
|
571
|
+
}
|
|
572
|
+
}
|
|
297
573
|
/** Platform dispatcher used by the CLI: returns a plan, never executes it. */
|
|
298
574
|
export function planScheduler(options = {}) {
|
|
299
575
|
const opts = options ?? {}
|
|
@@ -311,6 +587,27 @@ export function planScheduler(options = {}) {
|
|
|
311
587
|
throw new TypeError(`unsupported scheduler platform/action: ${String(platform)}/${String(action)}`)
|
|
312
588
|
}
|
|
313
589
|
|
|
590
|
+
|
|
591
|
+
/**
|
|
592
|
+
* Platform dispatcher for the multi-block install/uninstall/status plans.
|
|
593
|
+
* Accepts `{ blocks }` for install, `{ markers }`/`{ blocks }` for uninstall and
|
|
594
|
+
* the same options for status; never executes a system command.
|
|
595
|
+
*/
|
|
596
|
+
export function planSchedulerBlocks(options = {}) {
|
|
597
|
+
const opts = options ?? {}
|
|
598
|
+
const platform = opts.platform ?? process.platform
|
|
599
|
+
const action = opts.action ?? 'install'
|
|
600
|
+
if (platform === 'win32') {
|
|
601
|
+
if (action === 'install') return planWindowsInstallBlocks(opts)
|
|
602
|
+
if (action === 'uninstall') return planWindowsUninstallBlocks(opts)
|
|
603
|
+
if (action === 'status') return planWindowsStatusBlocks(opts)
|
|
604
|
+
} else if (CRON_PLATFORMS.includes(platform)) {
|
|
605
|
+
if (action === 'install') return planCronInstallBlocks(opts)
|
|
606
|
+
if (action === 'uninstall') return planCronUninstallBlocks(opts)
|
|
607
|
+
if (action === 'status') return planCronStatusBlocks(opts)
|
|
608
|
+
}
|
|
609
|
+
throw new TypeError(`unsupported scheduler platform/action: ${String(platform)}/${String(action)}`)
|
|
610
|
+
}
|
|
314
611
|
/** Resolve `~/.advisers/scheduler/` without assuming a real HOME. */
|
|
315
612
|
export function schedulerPaths({ homeDir } = {}) {
|
|
316
613
|
const home = String(homeDir ?? process.env.ADVISERS_HOME ?? join(homedir(), '.advisers'))
|
|
@@ -354,11 +651,16 @@ export function readSchedulerStatus(options = {}) {
|
|
|
354
651
|
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
|
|
355
652
|
return { ...defaultSchedulerStatus(), exists: true, corrupt: true }
|
|
356
653
|
}
|
|
654
|
+
// Cross-version read: a v2 document maps its `remind` section back to the flat
|
|
655
|
+
// v1 fields, so a 0.3.2 reader never loses lastRun after a v2 writer ran.
|
|
656
|
+
const source = parsed.version === SCHEDULER_STATUS_VERSION_V2 && parsed.remind && typeof parsed.remind === 'object'
|
|
657
|
+
? parsed.remind
|
|
658
|
+
: parsed
|
|
357
659
|
const status = defaultSchedulerStatus()
|
|
358
|
-
if (typeof
|
|
359
|
-
if (typeof
|
|
360
|
-
if (Number.isFinite(
|
|
361
|
-
if (typeof
|
|
660
|
+
if (typeof source.lastRun === 'string' && !Number.isNaN(Date.parse(source.lastRun))) status.lastRun = new Date(source.lastRun).toISOString()
|
|
661
|
+
if (typeof source.lastResult === 'string' && source.lastResult) status.lastResult = source.lastResult
|
|
662
|
+
if (Number.isFinite(source.lastCount)) status.lastCount = Number(source.lastCount)
|
|
663
|
+
if (typeof source.lastChannel === 'string' && source.lastChannel) status.lastChannel = source.lastChannel
|
|
362
664
|
if (typeof parsed.updatedAt === 'string' && !Number.isNaN(Date.parse(parsed.updatedAt))) status.updatedAt = new Date(parsed.updatedAt).toISOString()
|
|
363
665
|
return { ...status, exists: true, corrupt: false }
|
|
364
666
|
}
|
|
@@ -397,3 +699,145 @@ export function recordSchedulerRun({ homeDir, at = new Date(), result = 'ok', co
|
|
|
397
699
|
}
|
|
398
700
|
return { status, path: paths.statusFile, written: true }
|
|
399
701
|
}
|
|
702
|
+
|
|
703
|
+
/* ------------------------------------------------------------------ */
|
|
704
|
+
/* Status v2: per-section lastRun for remind + morning (additive to v1) */
|
|
705
|
+
/* ------------------------------------------------------------------ */
|
|
706
|
+
|
|
707
|
+
/** `remind` section of the version-2 status document. */
|
|
708
|
+
export function defaultSchedulerRemindStatus() {
|
|
709
|
+
return { lastRun: null, lastResult: null, lastCount: null, lastChannel: null }
|
|
710
|
+
}
|
|
711
|
+
|
|
712
|
+
/** `morning` section of the version-2 status document. */
|
|
713
|
+
export function defaultSchedulerMorningStatus() {
|
|
714
|
+
return { lastRun: null, lastResult: null, lastCount: null, lastPath: null }
|
|
715
|
+
}
|
|
716
|
+
|
|
717
|
+
export function defaultSchedulerStatusV2() {
|
|
718
|
+
return {
|
|
719
|
+
version: SCHEDULER_STATUS_VERSION_V2,
|
|
720
|
+
remind: defaultSchedulerRemindStatus(),
|
|
721
|
+
morning: defaultSchedulerMorningStatus(),
|
|
722
|
+
updatedAt: null,
|
|
723
|
+
}
|
|
724
|
+
}
|
|
725
|
+
|
|
726
|
+
function readStatusDocument(options = {}) {
|
|
727
|
+
const { statusFile } = schedulerPaths(options ?? {})
|
|
728
|
+
let raw
|
|
729
|
+
try {
|
|
730
|
+
raw = readFileSync(statusFile, 'utf8')
|
|
731
|
+
} catch (error) {
|
|
732
|
+
return { statusFile, doc: null, exists: false, corrupt: false, error: error?.code === 'ENOENT' ? null : 'read-error' }
|
|
733
|
+
}
|
|
734
|
+
let parsed
|
|
735
|
+
try {
|
|
736
|
+
parsed = JSON.parse(raw)
|
|
737
|
+
} catch {
|
|
738
|
+
return { statusFile, doc: null, exists: true, corrupt: true, error: null }
|
|
739
|
+
}
|
|
740
|
+
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
|
|
741
|
+
return { statusFile, doc: null, exists: true, corrupt: true, error: null }
|
|
742
|
+
}
|
|
743
|
+
return { statusFile, doc: parsed, exists: true, corrupt: false, error: null }
|
|
744
|
+
}
|
|
745
|
+
|
|
746
|
+
function sanitizeStatusTime(value) {
|
|
747
|
+
if (typeof value !== 'string' || !value) return null
|
|
748
|
+
const ms = Date.parse(value)
|
|
749
|
+
return Number.isNaN(ms) ? null : new Date(ms).toISOString()
|
|
750
|
+
}
|
|
751
|
+
|
|
752
|
+
function readRemindStatusSection(source) {
|
|
753
|
+
const section = defaultSchedulerRemindStatus()
|
|
754
|
+
if (!source || typeof source !== 'object' || Array.isArray(source)) return section
|
|
755
|
+
section.lastRun = sanitizeStatusTime(source.lastRun)
|
|
756
|
+
if (typeof source.lastResult === 'string' && source.lastResult) section.lastResult = source.lastResult
|
|
757
|
+
if (Number.isFinite(source.lastCount)) section.lastCount = Number(source.lastCount)
|
|
758
|
+
if (typeof source.lastChannel === 'string' && source.lastChannel) section.lastChannel = source.lastChannel
|
|
759
|
+
return section
|
|
760
|
+
}
|
|
761
|
+
|
|
762
|
+
function readMorningStatusSection(source) {
|
|
763
|
+
const section = defaultSchedulerMorningStatus()
|
|
764
|
+
if (!source || typeof source !== 'object' || Array.isArray(source)) return section
|
|
765
|
+
section.lastRun = sanitizeStatusTime(source.lastRun)
|
|
766
|
+
if (typeof source.lastResult === 'string' && source.lastResult) section.lastResult = source.lastResult
|
|
767
|
+
if (Number.isFinite(source.lastCount)) section.lastCount = Number(source.lastCount)
|
|
768
|
+
if (typeof source.lastPath === 'string' && source.lastPath) section.lastPath = source.lastPath
|
|
769
|
+
return section
|
|
770
|
+
}
|
|
771
|
+
|
|
772
|
+
/**
|
|
773
|
+
* Read the version-2 scheduler status. A v1 (flat) file is mapped into the
|
|
774
|
+
* `remind` section instead of failing — upgrading never loses lastRun — and a
|
|
775
|
+
* corrupt file degrades to defaults. `legacy: true` means the file on disk is
|
|
776
|
+
* still the v1 layout (the next record writes v2).
|
|
777
|
+
*
|
|
778
|
+
* @returns {{version: 2, remind: object, morning: object, updatedAt: string|null,
|
|
779
|
+
* exists: boolean, corrupt: boolean, legacy: boolean, error: string|null, path: string}}
|
|
780
|
+
*/
|
|
781
|
+
export function readSchedulerStatusV2(options = {}) {
|
|
782
|
+
const read = readStatusDocument(options)
|
|
783
|
+
const base = defaultSchedulerStatusV2()
|
|
784
|
+
if (!read.exists) return { ...base, exists: false, corrupt: false, legacy: false, error: read.error, path: read.statusFile }
|
|
785
|
+
if (read.corrupt) return { ...base, exists: true, corrupt: true, legacy: false, error: null, path: read.statusFile }
|
|
786
|
+
const doc = read.doc
|
|
787
|
+
const legacy = doc.version !== SCHEDULER_STATUS_VERSION_V2
|
|
788
|
+
return {
|
|
789
|
+
version: SCHEDULER_STATUS_VERSION_V2,
|
|
790
|
+
remind: readRemindStatusSection(legacy ? doc : doc.remind),
|
|
791
|
+
morning: readMorningStatusSection(legacy ? null : doc.morning),
|
|
792
|
+
updatedAt: sanitizeStatusTime(doc.updatedAt),
|
|
793
|
+
exists: true,
|
|
794
|
+
corrupt: false,
|
|
795
|
+
legacy,
|
|
796
|
+
error: null,
|
|
797
|
+
path: read.statusFile,
|
|
798
|
+
}
|
|
799
|
+
}
|
|
800
|
+
|
|
801
|
+
/**
|
|
802
|
+
* Record one run in a section of the version-2 status file. Reads the current
|
|
803
|
+
* document first (mapping v1 or recovering from a corrupt file), updates only
|
|
804
|
+
* the named section and writes atomically. Defaults to dry-run; pass
|
|
805
|
+
* `dryRun: false` (the CLI does this after a real run) to write the file.
|
|
806
|
+
*
|
|
807
|
+
* @returns {{status: object, path: string, written: boolean}}
|
|
808
|
+
*/
|
|
809
|
+
export function recordSchedulerRunV2({ homeDir, at = new Date(), section = 'remind', result = 'ok', count = null, channel = null, path = null, dryRun = true } = {}) {
|
|
810
|
+
if (!SCHEDULER_SECTIONS.includes(section)) throw new TypeError(`unknown scheduler status section: ${String(section)}`)
|
|
811
|
+
const when = at instanceof Date ? at : new Date(at)
|
|
812
|
+
if (Number.isNaN(when.getTime())) throw new RangeError('invalid scheduler run time')
|
|
813
|
+
const paths = schedulerPaths({ homeDir })
|
|
814
|
+
const current = readSchedulerStatusV2({ homeDir })
|
|
815
|
+
const stamp = when.toISOString()
|
|
816
|
+
const next = {
|
|
817
|
+
version: SCHEDULER_STATUS_VERSION_V2,
|
|
818
|
+
remind: { ...current.remind },
|
|
819
|
+
morning: { ...current.morning },
|
|
820
|
+
updatedAt: stamp,
|
|
821
|
+
}
|
|
822
|
+
const target = section === 'remind' ? next.remind : next.morning
|
|
823
|
+
target.lastRun = stamp
|
|
824
|
+
target.lastResult = typeof result === 'string' && result ? result : 'ok'
|
|
825
|
+
target.lastCount = Number.isFinite(count) ? Number(count) : null
|
|
826
|
+
if (section === 'remind') target.lastChannel = typeof channel === 'string' && channel ? channel : null
|
|
827
|
+
else target.lastPath = typeof path === 'string' && path ? path : null
|
|
828
|
+
if (dryRun !== false) return { status: next, path: paths.statusFile, written: false }
|
|
829
|
+
mkdirSync(paths.dir, { recursive: true, mode: 0o700 })
|
|
830
|
+
const temp = `${paths.statusFile}.${process.pid}.tmp`
|
|
831
|
+
try {
|
|
832
|
+
writeFileSync(temp, JSON.stringify(next, null, 2) + '\n', { mode: 0o600 })
|
|
833
|
+
renameSync(temp, paths.statusFile)
|
|
834
|
+
} catch (error) {
|
|
835
|
+
try {
|
|
836
|
+
if (existsSync(temp)) unlinkSync(temp)
|
|
837
|
+
} catch {
|
|
838
|
+
// Best-effort cleanup only; the original error is the one that matters.
|
|
839
|
+
}
|
|
840
|
+
throw error
|
|
841
|
+
}
|
|
842
|
+
return { status: next, path: paths.statusFile, written: true }
|
|
843
|
+
}
|