advisers 0.4.0 → 0.4.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/bin/advisers.js CHANGED
@@ -130,6 +130,9 @@ const loadKb = lazyModule(() => import('../lib/kb.js'))
130
130
  const loadKbPages = lazyModule(() => import('../lib/kb-pages.js'))
131
131
  const loadKbFacts = lazyModule(() => import('../lib/kb-facts.js'))
132
132
  const loadMail = lazyModule(() => import('../lib/mail.js'))
133
+ const loadMailProbe = lazyModule(() => import('../lib/mail-probe.js'))
134
+ const loadFactEntry = lazyModule(() => import('../lib/fact-entry.js'))
135
+ const loadMailWatch = lazyModule(() => import('../lib/mail-watch.js'))
133
136
  const loadCredentials = lazyModule(() => import('../lib/credentials.js'))
134
137
  const loadConsent = lazyModule(() => import('../lib/consent.js'))
135
138
  const loadPolicy = lazyModule(() => import('../lib/policy/index.js'))
@@ -1230,7 +1233,7 @@ Usage:
1230
1233
  advisers compact ls|rollback summary versions
1231
1234
  advisers today [--calendar] [--sources] [--json [--limit n]]
1232
1235
  one-screen today/week/waiting view (+ local events)
1233
- advisers remind [--json] [--ics [path]] [--deliver [--notify]] due reminders + ICS/VALARM export
1236
+ advisers remind [--json] [--ics [path]] [--deliver [--notify]] [--quiet-hours HH:MM-HH:MM] [--force-notify] due reminders + ICS/VALARM export
1234
1237
  advisers remind install|uninstall|status [--apply] [--schedule "0 9 * * *"]
1235
1238
  scheduler scripts + OS plan (dry-run by default; --apply executes)
1236
1239
  --morning adds the second morning block (--morning-time 08:30, --morning-days 1-5)
@@ -1600,7 +1603,7 @@ function purgeMatter(id, confirmed) {
1600
1603
  function parseFlags(args) {
1601
1604
  const flags = {}
1602
1605
  const positional = []
1603
- const booleanFlags = new Set(['web', 'deep', 'all', 'yes', 'json', 'list', 'force', 'apply', 'quiet', 'help', 'content', 'ics', 'deliver', 'install', 'uninstall', 'status', 'calendar', 'sources', 'pack', 'receipt', 'from-imap', 'remove', 'force', 'notify', 'no-remind', 'dry-run', 'unclassified', 'no-calendar', 'include-done', 'record-delivery', 'include-global', 'archive', 'morning', 'include-deleted', 'all-new', 'local', 'model', 'full', 'pass-stdin'])
1606
+ const booleanFlags = new Set(['web', 'deep', 'all', 'yes', 'json', 'list', 'force', 'apply', 'quiet', 'help', 'content', 'ics', 'deliver', 'install', 'uninstall', 'status', 'calendar', 'sources', 'pack', 'receipt', 'from-imap', 'remove', 'force', 'notify', 'no-remind', 'dry-run', 'unclassified', 'no-calendar', 'include-done', 'record-delivery', 'include-global', 'archive', 'morning', 'include-deleted', 'all-new', 'local', 'model', 'full', 'pass-stdin', 'force-notify'])
1604
1607
  for (let i = 0; i < args.length; i++) {
1605
1608
  if (args[i].startsWith('--')) {
1606
1609
  const key = args[i].slice(2)
@@ -3358,6 +3361,12 @@ async function clientCommand(rawArgs) {
3358
3361
  const sub = rawArgs[0]
3359
3362
  const rest = rawArgs.slice(1)
3360
3363
  if (!sub || sub === 'help' || sub === '--help') { clientUsage(); return }
3364
+ if (rest.includes('--help') || rest.includes('-h')) {
3365
+ const usage = CUSTOMER_USAGE[sub]
3366
+ if (usage) console.log(usage)
3367
+ else clientUsage()
3368
+ return
3369
+ }
3361
3370
  if (sub === 'add') return clientAdd(rest)
3362
3371
  if (sub === 'list' || sub === 'ls') return clientList(rest)
3363
3372
  if (sub === 'show') return clientShow(rest)
@@ -3533,6 +3542,12 @@ function projectCommand(rawArgs) {
3533
3542
  const sub = rawArgs[0]
3534
3543
  const rest = rawArgs.slice(1)
3535
3544
  if (!sub || sub === 'help' || sub === '--help') { projectUsage(); return }
3545
+ if (rest.includes('--help') || rest.includes('-h')) {
3546
+ const usage = CUSTOMER_USAGE['project' + sub.charAt(0).toUpperCase() + sub.slice(1)]
3547
+ if (usage) console.log(usage)
3548
+ else projectUsage()
3549
+ return
3550
+ }
3536
3551
  if (sub === 'add') return projectAdd(rest)
3537
3552
  if (sub === 'list' || sub === 'ls') return projectList(rest)
3538
3553
  if (sub === 'show') return projectShow(rest)
@@ -5053,6 +5068,7 @@ function printPreferences() {
5053
5068
  * and unknown flags fail closed with E_USAGE instead of being ignored.
5054
5069
  */
5055
5070
  async function doctor(args = []) {
5071
+ if (args.includes('--help') || args.includes('-h')) { console.log(DOCTOR_USAGE); return }
5056
5072
  const parsed = parseStrictFlags(args, {
5057
5073
  booleans: ['check-db', 'json', 'repair', 'dry-run', 'yes'],
5058
5074
  values: ['only'],
@@ -6776,6 +6792,14 @@ function familyStore({ write = false } = {}) {
6776
6792
 
6777
6793
  /** Shared strict flag parse that reports E_USAGE for the family commands. */
6778
6794
  function familyFlags(args, spec, usage) {
6795
+ // Subcommand --help is a help request, not an unknown option. Before 0.4.2
6796
+ // `kb add --help`/`mail account add --help` failed with E_USAGE because the
6797
+ // strict flag parser only knew the documented values. Print the command's own
6798
+ // usage block (no store/TOS/key needed) and let the caller return.
6799
+ if (Array.isArray(args) && (args.includes('--help') || args.includes('-h'))) {
6800
+ console.log(usage)
6801
+ return null
6802
+ }
6779
6803
  const parsed = parseStrictFlags(args, spec)
6780
6804
  if (!parsed.ok) { usageFail(parsed.error, usage); return null }
6781
6805
  return parsed
@@ -6799,6 +6823,8 @@ const KB_USAGE = [
6799
6823
  ' advisers kb reindex [--rebuild] [--json]',
6800
6824
  ' advisers kb search <query> [--scope kb|pages|all] [--limit n] [--clearance 0-3] [--json]',
6801
6825
  ' advisers kb page ls|show|rebuild|diff ... [--json]',
6826
+ ' advisers kb link <doc-id> --fact <fact-id> [--relation source|mentions] [--chunk id] [--json]',
6827
+ ' advisers kb unlink <doc-id> --fact <fact-id> [--relation source|mentions] [--json]',
6802
6828
  ].join('\n')
6803
6829
 
6804
6830
  function kbDocRowText(doc) {
@@ -7017,12 +7043,37 @@ async function kbCommand(rawArgs) {
7017
7043
  if (sub === 'reindex') return await kbReindexCommand(rawArgs.slice(1))
7018
7044
  if (sub === 'page') return await kbPageCommand(rawArgs.slice(1))
7019
7045
  if (sub === 'search') return await kbSearchCommand(rawArgs.slice(1))
7046
+ if (sub === 'link') return await kbLinkCommand(rawArgs.slice(1), false)
7047
+ if (sub === 'unlink') return await kbLinkCommand(rawArgs.slice(1), true)
7020
7048
  usageFail('unknown kb subcommand: ' + sub, KB_USAGE)
7021
7049
  } catch (error) { reportFamilyFailure(error) }
7022
7050
  }
7023
7051
 
7052
+ /** kb link/unlink: explicit fact <-> document provenance (0.4.x follow-up). */
7053
+ async function kbLinkCommand(rawArgs, unlink = false) {
7054
+ const usage = unlink
7055
+ ? 'usage: advisers kb unlink <doc-id> --fact <fact-id> [--relation source|mentions] [--json]'
7056
+ : 'usage: advisers kb link <doc-id> --fact <fact-id> [--relation source|mentions] [--chunk id] [--json]'
7057
+ const parsed = familyFlags(rawArgs, { booleans: ['json'], values: ['fact', 'relation', 'chunk'] }, usage)
7058
+ if (!parsed) return
7059
+ const docId = parsed.positional[0]
7060
+ const factId = parsed.flags.fact
7061
+ if (!docId) { usageFail('missing document id', usage); return }
7062
+ if (!factId) { usageFail('--fact is required', usage); return }
7063
+ const kb = await loadKb()
7064
+ const store = familyStore({ write: true })
7065
+ const result = unlink
7066
+ ? kb.kbUnlink(store, { docId, factId, relation: parsed.flags.relation })
7067
+ : kb.kbLink(store, { docId, factId, relation: parsed.flags.relation, chunkId: parsed.flags.chunk })
7068
+ if (parsed.flags.json) { console.log(JSON.stringify(result, null, 2)); return }
7069
+ if (unlink) console.log('unlinked ' + result.removed + ' link(s): ' + docId + ' x ' + factId)
7070
+ else console.log('linked ' + docId + ' -> ' + factId + ' (' + result.link.relation + ')')
7071
+ }
7072
+
7024
7073
  const FACT_USAGE = [
7025
- 'usage: advisers fact show <id> [--include-deleted] [--json]',
7074
+ 'usage: advisers fact add <subject> <predicate> <object> --quote "evidence" [--matter id] [--valid-from ISO] [--source ref]',
7075
+ ' [--doc <kb-doc-id>] [--relation source|mentions] [--supersedes <fact-id>] [--json]',
7076
+ ' advisers fact show <id> [--include-deleted] [--json]',
7026
7077
  ' advisers fact history <id> [--json]',
7027
7078
  ' advisers fact as-of <YYYY-MM-DD|ISO> [--matter id] [--client id] [--subject s] [--predicate s] [--limit n] [--include-deleted] [--json]',
7028
7079
  ].join('\n')
@@ -7035,10 +7086,37 @@ async function factCommand(rawArgs) {
7035
7086
  const sub = rawArgs[0]
7036
7087
  try {
7037
7088
  if (!sub || sub === 'help' || sub === '--help') { console.log(FACT_USAGE); return }
7038
- const parsed = familyFlags(rawArgs.slice(1), { booleans: ['json', 'include-deleted'], values: ['matter', 'client', 'subject', 'predicate', 'limit', 'at'] }, FACT_USAGE)
7089
+ const parsed = familyFlags(rawArgs.slice(1), { booleans: ['json', 'include-deleted'], values: ['matter', 'client', 'subject', 'predicate', 'limit', 'at', 'quote', 'valid-from', 'source', 'doc', 'relation', 'supersedes'] }, FACT_USAGE)
7039
7090
  if (!parsed) return
7040
7091
  const flags = parsed.flags
7041
7092
  const facts = await loadKbFacts()
7093
+ if (sub === 'add') {
7094
+ const usage = FACT_USAGE
7095
+ const parsedAdd = familyFlags(rawArgs.slice(1), { booleans: ['json'], values: ['quote', 'matter', 'valid-from', 'source', 'doc', 'relation', 'supersedes'] }, usage)
7096
+ if (!parsedAdd) return
7097
+ const [subject, predicate, object] = parsedAdd.positional
7098
+ if (!subject || !predicate || !object) { usageFail('fact add needs <subject> <predicate> <object>', usage); return }
7099
+ if (typeof parsedAdd.flags.quote !== 'string' || !parsedAdd.flags.quote.trim()) { usageFail('--quote is required (the evidence for a manually entered fact)', usage); return }
7100
+ if (parsedAdd.flags.doc !== undefined && parsedAdd.flags.relation === undefined) parsedAdd.flags.relation = 'source'
7101
+ if (parsedAdd.flags.relation !== undefined && parsedAdd.flags.doc === undefined) { usageFail('--relation requires --doc', usage); return }
7102
+ if (parsedAdd.flags.relation !== undefined && !['source', 'mentions'].includes(parsedAdd.flags.relation)) { usageFail('--relation must be source or mentions', usage); return }
7103
+ const entry = await loadFactEntry()
7104
+ const result = entry.factAdd(familyStore({ write: true }), {
7105
+ subject,
7106
+ predicate,
7107
+ object,
7108
+ quote: parsedAdd.flags.quote,
7109
+ matterId: parsedAdd.flags.matter,
7110
+ validFrom: parsedAdd.flags['valid-from'],
7111
+ source: parsedAdd.flags.source,
7112
+ docId: parsedAdd.flags.doc,
7113
+ relation: parsedAdd.flags.relation,
7114
+ supersedes: parsedAdd.flags.supersedes,
7115
+ })
7116
+ if (parsedAdd.flags.json) { console.log(JSON.stringify(result, null, 2)); return }
7117
+ console.log((result.deduped ? 'existing ' : 'added ') + factLine(result.fact))
7118
+ return
7119
+ }
7042
7120
  if (sub === 'show') {
7043
7121
  const id = parsed.positional[0]
7044
7122
  if (!id) { usageFail('missing fact id', FACT_USAGE); return }
@@ -7205,12 +7283,15 @@ const MAIL_USAGE = [
7205
7283
  'usage: advisers mail account add --name n --host h [--port 993] [--tls tls|starttls] --user u [--pass-stdin]',
7206
7284
  ' [--mailbox INBOX] [--retention-days 30] [--client id] [--matter id] [--json]',
7207
7285
  ' advisers mail account ls|show <account>|rm <account> [--json]',
7286
+ ' advisers mail account test <account> [--mailbox INBOX] [--timeout 1..120] [--json] (read-only IMAP probe)',
7208
7287
  ' advisers mail sync [<account>] [--full] [--dry-run] [--since-days 30] [--limit 50] [--mailbox INBOX] [--json]',
7209
7288
  ' advisers mail ls [--account a] [--client id] [--status s] [--since 30d] [--limit n] [--json]',
7210
7289
  ' advisers mail show <id> [--body] [--json]',
7211
7290
  ' advisers mail extract [<id>...] [--all-new] [--local|--model] [--yes] [--matter id] [--limit n] [--dry-run] [--json]',
7212
7291
  ' advisers mail import <file|dir> [--limit n] [--dry-run] [--client id] [--project id] [--json]',
7213
7292
  ' advisers mail purge [--older-than 30d] [--dry-run|--yes] [--account a] [--json]',
7293
+ ' advisers mail link <message> [--client id] [--project id] [--json]',
7294
+ ' advisers mail dismiss <message> [--json]',
7214
7295
  ].join('\n')
7215
7296
 
7216
7297
  function mailHumanRow(message) {
@@ -7222,7 +7303,7 @@ function mailHumanRow(message) {
7222
7303
  async function mailAccountCommand(args) {
7223
7304
  const sub = args[0]
7224
7305
  const rest = args.slice(1)
7225
- const usage = 'usage: advisers mail account add|ls|show|rm ...'
7306
+ const usage = 'usage: advisers mail account add|ls|show|test|rm ...'
7226
7307
  if (!sub || sub === 'help' || sub === '--help') { console.log(MAIL_USAGE); return }
7227
7308
  const mail = await loadMail()
7228
7309
  if (sub === 'add') {
@@ -7277,6 +7358,19 @@ async function mailAccountCommand(args) {
7277
7358
  console.log('mailbox=' + account.mailbox + ' retentionDays=' + account.retentionDays + ' credential=' + (account.hasCredential ? 'stored' : 'missing') + (account.lastSyncAt ? ' lastSyncAt=' + account.lastSyncAt : ''))
7278
7359
  return
7279
7360
  }
7361
+ if (sub === 'test') {
7362
+ const parsed = familyFlags(rest, { booleans: ['json'], values: ['mailbox', 'timeout'] }, usage)
7363
+ if (!parsed) return
7364
+ const ref = parsed.positional[0]
7365
+ if (!ref) { usageFail('missing account id or name', usage); return }
7366
+ const timeoutMs = parsed.flags.timeout === undefined ? undefined : familyInteger(parsed.flags.timeout, '--timeout', 1, 120) * 1000
7367
+ const probe = await loadMailProbe()
7368
+ const result = await probe.mailAccountTest(familyStore(), ref, { home: HOME, mailbox: parsed.flags.mailbox, timeoutMs })
7369
+ if (parsed.flags.json) { console.log(JSON.stringify(result, null, 2)); return }
7370
+ console.log('IMAP ok ' + result.accountId + ' ' + result.host + ':' + result.port + ' (' + result.tls + ') mailbox=' + result.mailbox + ' latency=' + result.latencyMs + 'ms')
7371
+ console.log('uidValidity=' + String(result.uidValidity ?? '-') + ' messages=' + String(result.messages ?? '-') + ' capabilities=' + result.capabilities.count + (result.capabilities.flags.idle ? ' idle' : '') + (result.capabilities.flags.starttls ? ' starttls' : ''))
7372
+ return
7373
+ }
7280
7374
  if (sub === 'rm' || sub === 'remove') {
7281
7375
  const parsed = familyFlags(rest, { booleans: ['json', 'purge-messages'], values: [] }, usage)
7282
7376
  if (!parsed) return
@@ -7290,34 +7384,108 @@ async function mailAccountCommand(args) {
7290
7384
  usageFail('unknown mail account subcommand: ' + sub, MAIL_USAGE)
7291
7385
  }
7292
7386
 
7387
+ function mailWatchInterval(value) {
7388
+ if (value === undefined) return undefined
7389
+ const text = String(value).trim().toLowerCase()
7390
+ const match = /^(\d+)(ms|s|m|h)?$/.exec(text)
7391
+ if (!match) return null
7392
+ const amount = Number(match[1])
7393
+ const unit = match[2] ?? 's'
7394
+ const ms = unit === 'ms' ? amount : unit === 's' ? amount * 1000 : unit === 'm' ? amount * 60_000 : amount * 3_600_000
7395
+ if (ms < 1000 || ms > 24 * 3_600_000) return null
7396
+ return ms
7397
+ }
7398
+
7293
7399
  async function mailSyncCommand(args) {
7294
- const usage = 'usage: advisers mail sync [<account>] [--full] [--dry-run] [--since-days n] [--limit n] [--mailbox INBOX] [--json]'
7295
- const parsed = familyFlags(args, { booleans: ['json', 'full', 'dry-run'], values: ['account', 'since-days', 'limit', 'mailbox'] }, usage)
7400
+ const usage = 'usage: advisers mail sync [<account>] [--full] [--dry-run] [--since-days n] [--limit n] [--mailbox INBOX] [--json] [--watch [--interval 300s] [--max-runs n]]'
7401
+ const parsed = familyFlags(args, { booleans: ['json', 'full', 'dry-run', 'watch'], values: ['account', 'since-days', 'limit', 'mailbox', 'interval', 'max-runs'] }, usage)
7296
7402
  if (!parsed) return
7297
7403
  const flags = parsed.flags
7404
+ const intervalMs = mailWatchInterval(flags.interval)
7405
+ if (flags.interval !== undefined && intervalMs === null) { usageFail('--interval must be 1s..24h (for example 300s or 5m)', usage); return }
7406
+ const maxRuns = flags['max-runs'] === undefined ? Infinity : familyInteger(flags['max-runs'], '--max-runs', 1, 100000)
7407
+ if (flags.watch !== true && (flags.interval !== undefined || flags['max-runs'] !== undefined)) { usageFail('--interval/--max-runs are only valid with --watch', usage); return }
7298
7408
  const mail = await loadMail()
7299
- const store = familyStore({ write: true })
7300
7409
  const requested = parsed.positional[0] ?? flags.account
7301
- let accounts
7302
- if (requested) accounts = [String(requested)]
7303
- else {
7304
- const listed = mail.mailAccountList(store, { home: HOME })
7305
- accounts = listed.accounts.filter((account) => account.status === 'active' && (account.tls === 'tls' || account.tls === 'starttls')).map((account) => account.id)
7306
- if (!accounts.length) throw familyError('E_MAIL_CONFIG', 'no IMAP account is configured', 'add one with advisers mail account add')
7410
+ const sinceDays = flags['since-days'] === undefined ? undefined : familyInteger(flags['since-days'], '--since-days', 1, 3650)
7411
+ const limit = flags.limit === undefined ? undefined : familyInteger(flags.limit, '--limit', 1, 200)
7412
+
7413
+ // One round opens the ledger, syncs every selected account and (in watch mode)
7414
+ // closes it again before sleeping: a foreground watch must not hold the writer
7415
+ // lock for hours while the operator works in another terminal.
7416
+ const round = async ({ closeStore = false } = {}) => {
7417
+ const store = familyStore({ write: true })
7418
+ try {
7419
+ let accounts
7420
+ if (requested) accounts = [String(requested)]
7421
+ else {
7422
+ const listed = mail.mailAccountList(store, { home: HOME })
7423
+ accounts = listed.accounts.filter((account) => account.status === 'active' && (account.tls === 'tls' || account.tls === 'starttls')).map((account) => account.id)
7424
+ if (!accounts.length) throw familyError('E_MAIL_CONFIG', 'no IMAP account is configured', 'add one with advisers mail account add')
7425
+ }
7426
+ const results = []
7427
+ for (const account of accounts) {
7428
+ results.push(await mail.mailSync(store, account, {
7429
+ full: flags.full === true,
7430
+ dryRun: flags['dry-run'] === true,
7431
+ sinceDays,
7432
+ limit,
7433
+ mailbox: flags.mailbox,
7434
+ home: HOME,
7435
+ }))
7436
+ }
7437
+ return requested ? results[0] : { ok: true, command: 'mail sync', results }
7438
+ } finally {
7439
+ if (closeStore) { try { store.close?.() } catch {} }
7440
+ }
7307
7441
  }
7308
- const results = []
7309
- for (const account of accounts) {
7310
- results.push(await mail.mailSync(store, account, {
7311
- full: flags.full === true,
7312
- dryRun: flags['dry-run'] === true,
7313
- sinceDays: flags['since-days'] === undefined ? undefined : familyInteger(flags['since-days'], '--since-days', 1, 3650),
7314
- limit: flags.limit === undefined ? undefined : familyInteger(flags.limit, '--limit', 1, 200),
7315
- mailbox: flags.mailbox,
7316
- home: HOME,
7317
- }))
7442
+
7443
+ if (flags.watch === true) {
7444
+ const { runMailWatch } = await loadMailWatch()
7445
+ const controller = new AbortController()
7446
+ let interrupted = false
7447
+ const onSignal = () => {
7448
+ if (controller.signal.aborted) process.exit(130)
7449
+ interrupted = true
7450
+ controller.abort()
7451
+ }
7452
+ process.on('SIGINT', onSignal)
7453
+ process.on('SIGTERM', onSignal)
7454
+ try {
7455
+ const summary = await runMailWatch({
7456
+ syncOnce: () => round({ closeStore: true }),
7457
+ intervalMs,
7458
+ maxRuns,
7459
+ signal: controller.signal,
7460
+ onResult: (record) => {
7461
+ if (record.ok) {
7462
+ const payload = record.result
7463
+ const results = Array.isArray(payload?.results) ? payload.results : (payload ? [payload] : [])
7464
+ const totals = results.reduce((acc, result) => ({
7465
+ fetched: acc.fetched + Number(result.fetched ?? 0),
7466
+ inserted: acc.inserted + Number(result.inserted ?? 0),
7467
+ skipped: acc.skipped + Number(result.skipped ?? 0),
7468
+ failed: acc.failed + Number(result.failed ?? 0),
7469
+ }), { fetched: 0, inserted: 0, skipped: 0, failed: 0 })
7470
+ console.log('watch round ' + record.run + ': fetched=' + totals.fetched + ' inserted=' + totals.inserted + ' skipped=' + totals.skipped + ' failed=' + totals.failed + ' next=' + Math.round(record.nextDelayMs / 1000) + 's')
7471
+ } else {
7472
+ console.error('watch round ' + record.run + ' failed: ' + (record.error?.message ?? 'unknown') + '; next=' + Math.round(record.nextDelayMs / 1000) + 's')
7473
+ }
7474
+ },
7475
+ })
7476
+ if (flags.json) { console.log(JSON.stringify(summary, null, 2)); return }
7477
+ console.log('mail watch stopped: ' + summary.stopped + ' runs=' + summary.runs + ' success=' + summary.success + ' errors=' + summary.errors)
7478
+ if (summary.stopped === 'aborted' && interrupted) process.exitCode = 130
7479
+ } finally {
7480
+ process.removeListener('SIGINT', onSignal)
7481
+ process.removeListener('SIGTERM', onSignal)
7482
+ }
7483
+ return
7318
7484
  }
7319
- const payload = requested ? results[0] : { ok: true, command: 'mail sync', results }
7485
+
7486
+ const payload = await round()
7320
7487
  if (flags.json) { console.log(JSON.stringify(payload, null, 2)); return }
7488
+ const results = Array.isArray(payload.results) ? payload.results : [payload]
7321
7489
  for (const result of results) console.log('sync ' + result.accountId + ' ' + result.mailbox + ': fetched=' + result.fetched + ' inserted=' + result.inserted + ' skipped=' + result.skipped + ' failed=' + result.failed + ' duplicates=' + result.duplicates + (result.dryRun ? ' (dry-run)' : '') + (result.needsResync ? ' NEEDS-RESYNC(--full)' : ''))
7322
7490
  }
7323
7491
 
@@ -7541,10 +7709,32 @@ async function mailCommand(rawArgs) {
7541
7709
  if (sub === 'extract') return await mailExtractCommand(rawArgs.slice(1))
7542
7710
  if (sub === 'import') return await mailImportCommand(rawArgs.slice(1))
7543
7711
  if (sub === 'purge') return await mailPurgeCommand(rawArgs.slice(1))
7712
+ if (sub === 'link') return await mailLinkCommand(rawArgs.slice(1), false)
7713
+ if (sub === 'dismiss') return await mailLinkCommand(rawArgs.slice(1), true)
7544
7714
  usageFail('unknown mail subcommand: ' + sub, MAIL_USAGE)
7545
7715
  } catch (error) { reportFamilyFailure(error) }
7546
7716
  }
7547
7717
 
7718
+ /** mail link/dismiss: explicit review decisions on one imported message (0.4.x follow-up). */
7719
+ async function mailLinkCommand(rawArgs, dismiss = false) {
7720
+ const usage = dismiss
7721
+ ? 'usage: advisers mail dismiss <message> [--json]'
7722
+ : 'usage: advisers mail link <message> [--client id] [--project id] [--json]'
7723
+ const parsed = familyFlags(rawArgs, { booleans: ['json'], values: ['client', 'project'] }, usage)
7724
+ if (!parsed) return
7725
+ const ref = parsed.positional[0]
7726
+ if (!ref) { usageFail('missing message id', usage); return }
7727
+ const mail = await loadMail()
7728
+ const store = familyStore({ write: true })
7729
+ const result = dismiss
7730
+ ? mail.mailDismiss(store, ref, {})
7731
+ : mail.mailLink(store, ref, { clientId: parsed.flags.client, projectId: parsed.flags.project })
7732
+ if (parsed.flags.json) { console.log(JSON.stringify(result, null, 2)); return }
7733
+ const message = result.message
7734
+ console.log((dismiss ? 'dismissed ' : 'linked ') + message.id + ' [' + message.status + ']' + (message.clientId ? ' client=' + message.clientId : '') + (message.projectId ? ' project=' + message.projectId : ''))
7735
+ }
7736
+
7737
+ /* ------------------------- receivable / payment ------------------------- */
7548
7738
  /* ------------------------- receivable / payment ------------------------- */
7549
7739
 
7550
7740
  const RECEIVABLE_USAGE = [
@@ -10118,6 +10308,46 @@ function parseQuietHours(value) {
10118
10308
  return { value: value }
10119
10309
  }
10120
10310
 
10311
+ const QUIET_HOURS_PARTS_RE = /^([01]\d|2[0-3]):([0-5]\d)-([01]\d|2[0-3]):([0-5]\d)$/
10312
+
10313
+ /** Local minute-of-day in the agenda timezone (deterministic for --now tests). */
10314
+ function localMinuteOfDay(date) {
10315
+ const parts = new Intl.DateTimeFormat('en-GB', { timeZone: AGENDA_TIMEZONE, hour: '2-digit', minute: '2-digit', hour12: false }).formatToParts(date)
10316
+ const hour = Number(parts.find((part) => part.type === 'hour')?.value ?? 0) % 24
10317
+ const minute = Number(parts.find((part) => part.type === 'minute')?.value ?? 0)
10318
+ return hour * 60 + minute
10319
+ }
10320
+
10321
+ /** True when `date` falls inside a validated HH:MM-HH:MM quiet window (cross-midnight supported). */
10322
+ function isInsideQuietHours(spec, date) {
10323
+ const match = QUIET_HOURS_PARTS_RE.exec(String(spec ?? ''))
10324
+ if (!match) return false
10325
+ const start = Number(match[1]) * 60 + Number(match[2])
10326
+ const end = Number(match[3]) * 60 + Number(match[4])
10327
+ if (start === end) return false
10328
+ const minute = localMinuteOfDay(date)
10329
+ return start < end ? minute >= start && minute < end : minute >= start || minute < end
10330
+ }
10331
+
10332
+ /** Dedupe key for one reminder notification scoped to a local day. */
10333
+ function reminderNotifyDedupeKey(reminder, localDay) {
10334
+ return 'notify:dedupe:' + [reminder.commitmentId, reminder.bucket, reminder.ruleId, localDay].join('|')
10335
+ }
10336
+
10337
+ function localDayOfInstant(date) {
10338
+ return new Intl.DateTimeFormat('en-CA', { timeZone: AGENDA_TIMEZONE }).format(date)
10339
+ }
10340
+
10341
+ /** Drop dedupe keys older than 30 local days (bounded metadata growth). */
10342
+ function pruneNotifyDedupe(store, nowDate) {
10343
+ if (!store || typeof store.listMetaByPrefix !== 'function' || typeof store.deleteMeta !== 'function') return
10344
+ const cutoff = nowDate.getTime() - 30 * 86400_000
10345
+ for (const [key, value] of store.listMetaByPrefix('notify:dedupe:')) {
10346
+ const at = Date.parse(String(value ?? ''))
10347
+ if (Number.isFinite(at) && at < cutoff) store.deleteMeta(key)
10348
+ }
10349
+ }
10350
+
10121
10351
  const HHMM_RE = /^([01]\d|2[0-3]):([0-5]\d)$/
10122
10352
  function parseHhmm(value, flag) {
10123
10353
  if (typeof value !== 'string' || !HHMM_RE.test(value)) return { error: flag + ' must be HH:MM' }
@@ -10314,7 +10544,11 @@ async function remind(args) {
10314
10544
  // 0.4.0: --now pins planning and the echoed instant, so a fixed run is
10315
10545
  // byte-reproducible (the same value is used by reminders/ICS/JSON/webhook).
10316
10546
  const nowInfo = parseRemindNow(flags)
10317
- if (nowInfo.error) { usageFail(nowInfo.error, 'usage: advisers remind [--json] [--now ISO] [--ics [path]] [--deliver [--notify]]'); return }
10547
+ if (nowInfo.error) { usageFail(nowInfo.error, 'usage: advisers remind [--json] [--now ISO] [--ics [path]] [--deliver [--notify]] [--quiet-hours HH:MM-HH:MM] [--force-notify]'); return }
10548
+ if (flags['quiet-hours'] !== undefined) {
10549
+ const quiet = parseQuietHours(flags['quiet-hours'])
10550
+ if (quiet.error) { usageFail(quiet.error, 'usage: advisers remind [--json] [--now ISO] [--ics [path]] [--deliver [--notify]] [--quiet-hours HH:MM-HH:MM] [--force-notify]'); return }
10551
+ }
10318
10552
  const nowDate = nowInfo.date
10319
10553
  // One prefix query instead of getMeta() per commitment (read-only store safe).
10320
10554
  const snoozed = {}
@@ -10355,20 +10589,46 @@ async function remind(args) {
10355
10589
  let channel = 'log'
10356
10590
  if (flags.notify) {
10357
10591
  const notify = await loadNotify()
10358
- const local = await notify.sendNotification({ title: 'Advisers · 到期提醒', body: reminders.length + ' 条承诺到期或即将到期' })
10359
- channel = local.sent ? local.channel : 'log-only'
10360
- const webhook = await notify.sendWebhookNotification(reminders, { now: nowDate })
10361
- if (webhook.sent) {
10362
- channel = channel === 'log-only' ? 'webhook' : channel + '+webhook'
10363
- // 0.4.0: remember whether the delivery was signed, without changing the
10364
- // payload bytes. A configured webhook with no secret still sends but says
10365
- // so exactly once per process (sanitised, no secret material).
10366
- if (typeof webhook.signing === 'string' && webhook.signing !== '') channel += '+signing:' + webhook.signing
10367
- if (webhook.warning === 'missing-secret' && !webhookSecretWarned) {
10368
- webhookSecretWarned = true
10369
- console.error(sanitizeConsoleText('webhook 已配置但未设置 ADVISERS_NOTIFY_WEBHOOK_SECRET:本次按未签名发送(signing=none);建议设置 secret,否则接收端无法验证请求来源。', { max: 2000 }))
10592
+ const forceNotify = flags['force-notify'] === true
10593
+ const quietSpec = typeof flags['quiet-hours'] === 'string' ? flags['quiet-hours'] : (typeof process.env.ADVISERS_QUIET_HOURS === 'string' ? process.env.ADVISERS_QUIET_HOURS : null)
10594
+ if (!forceNotify && quietSpec && isInsideQuietHours(quietSpec, nowDate)) {
10595
+ // Quiet hours are a delivery policy, not an error: the log line above is
10596
+ // still written, the channel is recorded as suppressed and the audit row
10597
+ // records why. --force-notify bypasses (for an explicit one-off).
10598
+ channel = 'quiet-suppressed'
10599
+ console.log('通知已静默:当前处于安静时段 ' + quietSpec + '(本地日志已记录;--force-notify 可强制发送)')
10600
+ } else {
10601
+ const localDay = localDayOfInstant(nowDate)
10602
+ let notifyList = reminders
10603
+ if (!forceNotify && store && typeof store.listMetaByPrefix === 'function') {
10604
+ const seen = new Set(store.listMetaByPrefix('notify:dedupe:').keys())
10605
+ notifyList = reminders.filter((reminder) => !seen.has(reminderNotifyDedupeKey(reminder, localDay)))
10606
+ if (!notifyList.length) {
10607
+ channel = 'deduped'
10608
+ console.log('通知已去重:本批提醒今天已经通知过(本地日志仍记录;--force-notify 可重发)')
10609
+ }
10370
10610
  }
10371
- } else if (webhook.configured) { console.error(sanitizeConsoleText('webhook 未发送:' + (webhook.error ?? 'unknown') + (webhook.detail ? '(' + webhook.detail + ')' : ''), { max: 2000 })) }
10611
+ if (channel !== 'deduped') {
10612
+ const local = await notify.sendNotification({ title: 'Advisers · 到期提醒', body: notifyList.length + ' 条承诺到期或即将到期' })
10613
+ channel = local.sent ? local.channel : 'log-only'
10614
+ const webhook = await notify.sendWebhookNotification(notifyList, { now: nowDate })
10615
+ if (webhook.sent) {
10616
+ channel = channel === 'log-only' ? 'webhook' : channel + '+webhook'
10617
+ // 0.4.0: remember whether the delivery was signed, without changing the
10618
+ // payload bytes. A configured webhook with no secret still sends but says
10619
+ // so exactly once per process (sanitised, no secret material).
10620
+ if (typeof webhook.signing === 'string' && webhook.signing !== '') channel += '+signing:' + webhook.signing
10621
+ if (webhook.warning === 'missing-secret' && !webhookSecretWarned) {
10622
+ webhookSecretWarned = true
10623
+ console.error(sanitizeConsoleText('webhook 已配置但未设置 ADVISERS_NOTIFY_WEBHOOK_SECRET:本次按未签名发送(signing=none);建议设置 secret,否则接收端无法验证请求来源。', { max: 2000 }))
10624
+ }
10625
+ } else if (webhook.configured) { console.error(sanitizeConsoleText('webhook 未发送:' + (webhook.error ?? 'unknown') + (webhook.detail ? '(' + webhook.detail + ')' : ''), { max: 2000 })) }
10626
+ if (store && typeof store.setMeta === 'function') {
10627
+ for (const reminder of notifyList) store.setMeta(reminderNotifyDedupeKey(reminder, localDay), nowDate.toISOString())
10628
+ pruneNotifyDedupe(store, nowDate)
10629
+ }
10630
+ }
10631
+ }
10372
10632
  }
10373
10633
  store?.appendAudit({ actor: 'local', action: 'notify.delivered', allowed: true, reason: reminders.length + ' reminders channel=' + channel })
10374
10634
  recordReminderRun(scheduler, { count: reminders.length, channel })
@@ -10686,7 +10946,14 @@ function checkBackupReadable(check) {
10686
10946
  let store = null
10687
10947
  try {
10688
10948
  store = new SqliteStore(backup, { readOnly: true, checkIntegrity: true })
10689
- check('db-backup', true, `${basename(backup)} (readable, quick_check ok)`)
10949
+ // Age is informational: a readable old backup is still a PASS, but the
10950
+ // operator should know that the newest managed copy is stale.
10951
+ let age = ''
10952
+ try {
10953
+ const days = (Date.now() - statSync(backup).mtimeMs) / 86_400_000
10954
+ age = `; age ${days.toFixed(1)}d${days > 7 ? ' (older than 7 days; run `advisers backup`)' : ''}`
10955
+ } catch {}
10956
+ check('db-backup', true, `${basename(backup)} (readable, quick_check ok)${age}`)
10690
10957
  } catch (error) {
10691
10958
  check('db-backup', false, `${basename(backup)}: ${String(error?.message ?? error).slice(0, 200)}`)
10692
10959
  } finally {
@@ -11119,10 +11386,11 @@ function reportSyncPullResult(result) {
11119
11386
  }
11120
11387
 
11121
11388
  async function syncCommand(args) {
11389
+ if (args.includes('--help') || args.includes('-h')) { console.log('usage: advisers sync push|pull|status --dir <sync-dir> [--force] [--file name] [--device name] [--dry-run] [--json]'); return }
11122
11390
  const { flags, positional } = parseFlags(args)
11123
11391
  const sub = positional[0]
11124
11392
  const dir = typeof flags.dir === 'string' ? flags.dir : undefined
11125
- if (!dir) { console.error('usage: advisers sync push|pull|status --dir <sync-dir>'); process.exitCode = 1; return }
11393
+ if (!dir) { console.error('usage: advisers sync push|pull|status --dir <sync-dir> [--dry-run]'); process.exitCode = 1; return }
11126
11394
  if (sub === 'status') {
11127
11395
  const { listSnapshots } = await loadSync()
11128
11396
  const snaps = listSnapshots(dir)
@@ -11160,6 +11428,7 @@ async function syncCommand(args) {
11160
11428
  } catch (error) { console.error(`sync push failed: ${error.message}`); process.exitCode = 1 }
11161
11429
  } else if (sub === 'pull') {
11162
11430
  const force = Boolean(flags.force)
11431
+ const dryRun = flags['dry-run'] === true
11163
11432
  const { pullSnapshot, cleanupStalePullTemps } = await loadSync()
11164
11433
  try {
11165
11434
  // Capture the local write time before checkpointing (checkpoint touches mtime).
@@ -11177,7 +11446,16 @@ async function syncCommand(args) {
11177
11446
  force,
11178
11447
  localMtimeMs,
11179
11448
  localDevice: await readSyncDevice(),
11449
+ dryRun,
11180
11450
  })
11451
+ if (dryRun) {
11452
+ if (flags.json) { console.log(JSON.stringify(result, null, 2)); return }
11453
+ const snapshotLabel = `${result.file} (${result.device ?? 'unknown device'}, ${result.createdAt ?? 'unknown time'})`
11454
+ for (const warning of result.warnings ?? []) console.error('warning: ' + warning)
11455
+ if (!result.wouldChange) console.log(`dry-run: no change; the local database already matches ${snapshotLabel}`)
11456
+ else console.log(`dry-run: would ${result.wouldStatus === 'bootstrapped' ? 'bootstrap from' : result.wouldStatus === 'forced' ? 'force-replace with' : 'pull'} ${snapshotLabel}${result.wouldBackup ? '; a backup of the current database would be written first' : ''}; local database unchanged`)
11457
+ return
11458
+ }
11181
11459
  // 0.2.3 Wave 1: distinguish bootstrapped / forced / plain pull / unchanged.
11182
11460
  reportSyncPullResult(result)
11183
11461
  if (result.changed) {
@@ -12576,6 +12854,9 @@ async function tosGate() {
12576
12854
  // Offline receipt verification must work on a clean machine without a
12577
12855
  // ~/.advisers consent record (docs/DELIVERY-RECEIPT.md); it reads only <dir>.
12578
12856
  else if (command === 'evidence' && args[0] === 'verify') return
12857
+ // `--help`/`-h` anywhere is a pure help request: it must work before TOS
12858
+ // acceptance (and before HOME/database setup), like the top-level help.
12859
+ else if (args.includes('--help') || args.includes('-h')) return
12579
12860
  else if (TOS_EXEMPT_COMMANDS.has(command) || !KNOWN_COMMANDS.has(command)) return
12580
12861
  const tos = await loadTos()
12581
12862
  const { info } = resolveTosFacts(tos)
package/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  export * from 'advisers-core'
2
2
 
3
- export const version = '0.4.0'
3
+ export const version = '0.4.2'
4
4
  export const distribution = 'cordis'
5
5
  export const status = 'bootstrapping'