advisers 0.4.1 → 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/README-zh.md CHANGED
@@ -5,12 +5,12 @@
5
5
  ## 安装
6
6
 
7
7
  ```sh
8
- # 0.4.1 已于 2026-11-21 发布;npm @latest 现为 0.4.1(稳定渠道 = 默认 `latest`):
8
+ # 0.4.2 已于 2026-11-22 发布;npm @latest 现为 0.4.2(稳定渠道 = 默认 `latest`):
9
9
  # npm i -g --registry=https://registry.npmjs.org advisers@latest advisers-office@latest
10
10
  # 从 checkout 运行:
11
11
  # corepack pnpm install && corepack pnpm -r build
12
12
  # ADVISERS_OFFICE_LOCAL=1 node packages/advisers/bin/advisers.js status
13
- # `next` 渠道也指向 0.4.1:
13
+ # `next` 渠道也指向 0.4.2:
14
14
  # npm i -g --registry=https://registry.npmjs.org advisers@next advisers-office@next
15
15
  advisers soul init
16
16
  advisers brief "做一份 Q4 预算 Excel,周五前给老板"
@@ -36,7 +36,7 @@ CLI 是**本地秘书运行时**:一个 REPL、用户账/承诺账/流程账
36
36
 
37
37
  ## 状态
38
38
 
39
- `0.4.1` 已于 2026-11-21 发布(npm `latest` = `0.4.1`;`next` 也为 `0.4.1`)。0.4.1 是 0.4.0 功能发布之上的当日补丁:接线 KB/邮件审查链接(`kb link/unlink`、`mail link/dismiss`),为 `remind --deliver --notify` 增加运行时安静时段 + 按本地日去重 + `--force-notify`,新增 `kb`/`mail`/`policy` 三组确定性评测(30 cases / 277 checks)与 38 个 documented-additive CLI 命令。0.4.0 的功能面不变:本地知识库(schema v22)、TLS-only IMAP 邮件入口、交互式壳、可解释的主动式晨报、Policy/Evidence 2.0 子集、回款/对账与客户状态包 v2、MCP modern dual-era、Windows CI 与便携 ZIP,以及 v2026.11.4 法务修订。所有新命令都不需要模型调用,也没有后台常驻进程,`mail sync` 是唯一新增的显式网络路径(TLS-only、只读、用户主动触发)。**schema v22 是单向迁移**:升级前 CLI 会写 `state.db.before-migrate-v*` 备份,0.3.2 打开 v22 数据库会报 `E_SCHEMA_NEWER`,降级需要恢复该备份。`0.4.0`/`0.3.2`/`0.3.1`/`0.3.0` 仍可按版本号安装但已被取代。运行时基线仍是「可信交付」feature line:所有出网面逐 item secrecy clearance、本地审计尾锚、备份轮换/可验证恢复与 `doctor --repair`、200k 读路径、MCP 输出上限 + legacy 协议协商、DSH 只读账本门面、机器可读契约、无 key 的确定性评测套件与 SBOM 门禁。`0.4.1` tarball 由 GitHub Actions OIDC/Trusted Publishing 发布,带 SLSA provenance;可用 `scripts/verify-release.mjs --version 0.4.1 --tag latest --sbom artifacts/sbom.cdx.json --require-sbom` 校验(SBOM 由 `pnpm run sbom` 生成)。Release notes:<https://github.com/PerryLink/advisers/releases/tag/v0.4.1>。模型化 `kb compile`/`kb ask`、embedding、完整 PolicyGrant/exit 4–6 与 DSH 写账本仍属后续版本;未交付清单见仓库 CHANGELOG。
39
+ `0.4.2` 已于 2026-11-22 发布(npm `latest` = `0.4.2`;`next` 也为 `0.4.2`)。0.4.2 是 0.4.1 之上的补丁:新增手工事实录入(`fact add`,`--quote` 必填、重复幂等,事实 + supersede 链 + KB 链接 + 一条 `fact.add` 审计同事务提交)、只读 IMAP 探测(`mail account test`)、显式前台 `mail sync --watch`、`sync pull --dry-run` 预览、`doctor --check-db` 的备份年龄提示、子命令 `--help` 一致性(TOS 接受前即可用),以及零模型/零网络的 `pnpm eval:mail-local` 质量门(30 个合成 fixture,已接入 Linux CI),并按审计结论纠偏文档。0.4.0 的功能面不变:本地知识库(schema v22)、TLS-only IMAP 邮件入口、交互式壳、可解释的主动式晨报、Policy/Evidence 2.0 子集、回款/对账与客户状态包 v2、MCP modern dual-era、Windows CI 与便携 ZIP,以及 v2026.11.4 法务修订。所有新命令都不需要模型调用,也没有后台常驻进程,`mail sync` 是唯一新增的显式网络路径(TLS-only、只读、用户主动触发)。**schema v22 是单向迁移**:升级前 CLI 会写 `state.db.before-migrate-v*` 备份,0.3.2 打开 v22 数据库会报 `E_SCHEMA_NEWER`,降级需要恢复该备份。`0.4.1`/`0.4.0`/`0.3.2`/`0.3.1`/`0.3.0` 仍可按版本号安装但已被取代。运行时基线仍是「可信交付」feature line:所有出网面逐 item secrecy clearance、本地审计尾锚、备份轮换/可验证恢复与 `doctor --repair`、200k 读路径、MCP 输出上限 + legacy 协议协商、DSH 只读账本门面、机器可读契约、无 key 的确定性评测套件与 SBOM 门禁。`0.4.2` tarball 由 GitHub Actions OIDC/Trusted Publishing 发布,带 SLSA provenance;可用 `scripts/verify-release.mjs --version 0.4.2 --tag latest --sbom artifacts/sbom.cdx.json --require-sbom` 校验(SBOM 由 `pnpm run sbom` 生成)。Release notes:<https://github.com/PerryLink/advisers/releases/tag/v0.4.2>。模型化 `kb compile`/`kb ask`、embedding、完整 PolicyGrant/exit 4–6 与 DSH 写账本仍属后续版本;未交付清单见仓库 CHANGELOG。
40
40
 
41
41
  - SQLite 账本 `~/.advisers/state.db`(JSON fallback;schema v22 —— 0.4.0 一次迁移加入 KB/邮件/回款对象、无锁只读快照、增量写);
42
42
  - soul 位于 `~/.advisers/soul.md`,人类独占;
package/README.md CHANGED
@@ -7,12 +7,12 @@ routines.
7
7
  ## Install
8
8
 
9
9
  ```sh
10
- # 0.4.1 was published on 2026-11-21; npm @latest is now 0.4.1:
10
+ # 0.4.2 was published on 2026-11-22; npm @latest is now 0.4.2:
11
11
  # npm i -g --registry=https://registry.npmjs.org advisers@latest advisers-office@latest
12
12
  # From checkout:
13
13
  # corepack pnpm install && corepack pnpm -r build
14
14
  # ADVISERS_OFFICE_LOCAL=1 node packages/advisers/bin/advisers.js status
15
- # The `next` channel also points at 0.4.1:
15
+ # The `next` channel also points at 0.4.2:
16
16
  # npm i -g --registry=https://registry.npmjs.org advisers@next advisers-office@next
17
17
  advisers soul init
18
18
  advisers brief "做一份 Q4 预算 Excel,周五前给老板"
@@ -43,12 +43,14 @@ turn natural language into commitments or artifacts.
43
43
 
44
44
  ## Status
45
45
 
46
- `0.4.1` was published on 2026-11-21 (npm `latest` = `0.4.1`; `next` is also `0.4.1`). It
47
- is a same-day follow-up patch on the 0.4.0 feature release: it wires the KB/mail review
48
- links (`kb link/unlink`, `mail link/dismiss`), enforces runtime quiet hours + per-local-day
49
- dedupe + `--force-notify` for `remind --deliver --notify`, and adds the
50
- `kb`/`mail`/`policy` deterministic eval groups (30 cases / 277 checks) plus 38
51
- documented-additive CLI commands. The 0.4.0 feature surface is unchanged: the local
46
+ `0.4.2` was published on 2026-11-22 (npm `latest` = `0.4.2`; `next` is also `0.4.2`). It
47
+ is a patch on the 0.4.1 same-day follow-up: it adds manual fact entry (`fact add`, with a
48
+ required evidence quote and one-transaction supersede/KB-link/audit), the read-only IMAP
49
+ probe (`mail account test`), the explicit foreground `mail sync --watch`, the `sync pull
50
+ --dry-run` preview, the backup-age hint in `doctor --check-db`, a subcommand `--help`
51
+ consistency pass (usable before TOS acceptance) and the zero-model/zero-network
52
+ `pnpm eval:mail-local` quality gate (30 synthetic fixtures, wired into Linux CI), plus the
53
+ audit-driven documentation corrections. The 0.4.0 feature surface is unchanged: the local
52
54
  knowledge base (schema v22), TLS-only IMAP mail entry, the interactive shell, proactive
53
55
  urgent-first briefs, the policy/evidence 2.0 subset, receivables/payments with client
54
56
  pack v2, MCP modern dual-era, Windows CI plus a portable ZIP, and the v2026.11.4 legal
@@ -56,16 +58,17 @@ revision. No new command requires a model call,
56
58
  there is no background daemon, and `mail sync` is the one new explicit network path
57
59
  (TLS-only, read-only, user-invoked). **Schema v22 is a one-way migration**: the CLI writes
58
60
  `state.db.before-migrate-v*` before upgrading, a 0.3.2 binary opening a v22 database fails
59
- with `E_SCHEMA_NEWER`, and downgrading means restoring that backup. `0.4.0`/`0.3.2`/`0.3.1`/`0.3.0`
60
- remain installable by pinning but are superseded. The runtime baseline remains the
61
+ with `E_SCHEMA_NEWER`, and downgrading means restoring that backup.
62
+ `0.4.1`/`0.4.0`/`0.3.2`/`0.3.1`/`0.3.0` remain installable by pinning but are superseded.
63
+ The runtime baseline remains the
61
64
  "trustworthy delivery" line: per-item secrecy clearance on every egress surface, a local
62
65
  audit tail anchor, backup rotation/verified restore and `doctor --repair`, 200k-row read
63
66
  paths, MCP output caps plus legacy protocol negotiation, a read-only ledger facade, machine
64
- readable contracts, a deterministic no-key eval suite and an SBOM gate. The `0.4.1` tarballs
67
+ readable contracts, a deterministic no-key eval suite and an SBOM gate. The `0.4.2` tarballs
65
68
  are published from GitHub Actions OIDC/Trusted Publishing with SLSA provenance; verify with
66
- `scripts/verify-release.mjs --version 0.4.1 --tag latest --sbom artifacts/sbom.cdx.json
69
+ `scripts/verify-release.mjs --version 0.4.2 --tag latest --sbom artifacts/sbom.cdx.json
67
70
  --require-sbom` (the SBOM is generated by `pnpm run sbom`).
68
- Release notes: <https://github.com/PerryLink/advisers/releases/tag/v0.4.1>. Model-backed KB
71
+ Release notes: <https://github.com/PerryLink/advisers/releases/tag/v0.4.2>. Model-backed KB
69
72
  compile/ask, embeddings, the full PolicyGrant/exit 4–6 and DSH writes remain future work;
70
73
  see the repository CHANGELOG for the full not-delivered list.
71
74
 
@@ -11,7 +11,7 @@ dependency closure of the published packages ("pnpm list --prod --depth 100";
11
11
  devDependencies and workspace packages excluded). Do not edit by hand; CI runs
12
12
  "node scripts/check-licenses.mjs".
13
13
 
14
- This file is shipped with the advisers@0.4.1 npm package and covers the third-party production dependencies of that package only. Each dependency keeps its own license.
14
+ This file is shipped with the advisers@0.4.2 npm package and covers the third-party production dependencies of that package only. Each dependency keeps its own license.
15
15
 
16
16
  Optional platform-specific binaries (for example the @napi-rs/canvas builds for
17
17
  other operating systems and CPU architectures) are installed only on a matching
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'))
@@ -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
@@ -7047,7 +7071,9 @@ async function kbLinkCommand(rawArgs, unlink = false) {
7047
7071
  }
7048
7072
 
7049
7073
  const FACT_USAGE = [
7050
- '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]',
7051
7077
  ' advisers fact history <id> [--json]',
7052
7078
  ' advisers fact as-of <YYYY-MM-DD|ISO> [--matter id] [--client id] [--subject s] [--predicate s] [--limit n] [--include-deleted] [--json]',
7053
7079
  ].join('\n')
@@ -7060,10 +7086,37 @@ async function factCommand(rawArgs) {
7060
7086
  const sub = rawArgs[0]
7061
7087
  try {
7062
7088
  if (!sub || sub === 'help' || sub === '--help') { console.log(FACT_USAGE); return }
7063
- 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)
7064
7090
  if (!parsed) return
7065
7091
  const flags = parsed.flags
7066
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
+ }
7067
7120
  if (sub === 'show') {
7068
7121
  const id = parsed.positional[0]
7069
7122
  if (!id) { usageFail('missing fact id', FACT_USAGE); return }
@@ -7230,6 +7283,7 @@ const MAIL_USAGE = [
7230
7283
  'usage: advisers mail account add --name n --host h [--port 993] [--tls tls|starttls] --user u [--pass-stdin]',
7231
7284
  ' [--mailbox INBOX] [--retention-days 30] [--client id] [--matter id] [--json]',
7232
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)',
7233
7287
  ' advisers mail sync [<account>] [--full] [--dry-run] [--since-days 30] [--limit 50] [--mailbox INBOX] [--json]',
7234
7288
  ' advisers mail ls [--account a] [--client id] [--status s] [--since 30d] [--limit n] [--json]',
7235
7289
  ' advisers mail show <id> [--body] [--json]',
@@ -7249,7 +7303,7 @@ function mailHumanRow(message) {
7249
7303
  async function mailAccountCommand(args) {
7250
7304
  const sub = args[0]
7251
7305
  const rest = args.slice(1)
7252
- const usage = 'usage: advisers mail account add|ls|show|rm ...'
7306
+ const usage = 'usage: advisers mail account add|ls|show|test|rm ...'
7253
7307
  if (!sub || sub === 'help' || sub === '--help') { console.log(MAIL_USAGE); return }
7254
7308
  const mail = await loadMail()
7255
7309
  if (sub === 'add') {
@@ -7304,6 +7358,19 @@ async function mailAccountCommand(args) {
7304
7358
  console.log('mailbox=' + account.mailbox + ' retentionDays=' + account.retentionDays + ' credential=' + (account.hasCredential ? 'stored' : 'missing') + (account.lastSyncAt ? ' lastSyncAt=' + account.lastSyncAt : ''))
7305
7359
  return
7306
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
+ }
7307
7374
  if (sub === 'rm' || sub === 'remove') {
7308
7375
  const parsed = familyFlags(rest, { booleans: ['json', 'purge-messages'], values: [] }, usage)
7309
7376
  if (!parsed) return
@@ -7317,34 +7384,108 @@ async function mailAccountCommand(args) {
7317
7384
  usageFail('unknown mail account subcommand: ' + sub, MAIL_USAGE)
7318
7385
  }
7319
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
+
7320
7399
  async function mailSyncCommand(args) {
7321
- const usage = 'usage: advisers mail sync [<account>] [--full] [--dry-run] [--since-days n] [--limit n] [--mailbox INBOX] [--json]'
7322
- 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)
7323
7402
  if (!parsed) return
7324
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 }
7325
7408
  const mail = await loadMail()
7326
- const store = familyStore({ write: true })
7327
7409
  const requested = parsed.positional[0] ?? flags.account
7328
- let accounts
7329
- if (requested) accounts = [String(requested)]
7330
- else {
7331
- const listed = mail.mailAccountList(store, { home: HOME })
7332
- accounts = listed.accounts.filter((account) => account.status === 'active' && (account.tls === 'tls' || account.tls === 'starttls')).map((account) => account.id)
7333
- 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
+ }
7334
7441
  }
7335
- const results = []
7336
- for (const account of accounts) {
7337
- results.push(await mail.mailSync(store, account, {
7338
- full: flags.full === true,
7339
- dryRun: flags['dry-run'] === true,
7340
- sinceDays: flags['since-days'] === undefined ? undefined : familyInteger(flags['since-days'], '--since-days', 1, 3650),
7341
- limit: flags.limit === undefined ? undefined : familyInteger(flags.limit, '--limit', 1, 200),
7342
- mailbox: flags.mailbox,
7343
- home: HOME,
7344
- }))
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
7345
7484
  }
7346
- const payload = requested ? results[0] : { ok: true, command: 'mail sync', results }
7485
+
7486
+ const payload = await round()
7347
7487
  if (flags.json) { console.log(JSON.stringify(payload, null, 2)); return }
7488
+ const results = Array.isArray(payload.results) ? payload.results : [payload]
7348
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)' : ''))
7349
7490
  }
7350
7491
 
@@ -10805,7 +10946,14 @@ function checkBackupReadable(check) {
10805
10946
  let store = null
10806
10947
  try {
10807
10948
  store = new SqliteStore(backup, { readOnly: true, checkIntegrity: true })
10808
- 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}`)
10809
10957
  } catch (error) {
10810
10958
  check('db-backup', false, `${basename(backup)}: ${String(error?.message ?? error).slice(0, 200)}`)
10811
10959
  } finally {
@@ -11238,10 +11386,11 @@ function reportSyncPullResult(result) {
11238
11386
  }
11239
11387
 
11240
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 }
11241
11390
  const { flags, positional } = parseFlags(args)
11242
11391
  const sub = positional[0]
11243
11392
  const dir = typeof flags.dir === 'string' ? flags.dir : undefined
11244
- 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 }
11245
11394
  if (sub === 'status') {
11246
11395
  const { listSnapshots } = await loadSync()
11247
11396
  const snaps = listSnapshots(dir)
@@ -11279,6 +11428,7 @@ async function syncCommand(args) {
11279
11428
  } catch (error) { console.error(`sync push failed: ${error.message}`); process.exitCode = 1 }
11280
11429
  } else if (sub === 'pull') {
11281
11430
  const force = Boolean(flags.force)
11431
+ const dryRun = flags['dry-run'] === true
11282
11432
  const { pullSnapshot, cleanupStalePullTemps } = await loadSync()
11283
11433
  try {
11284
11434
  // Capture the local write time before checkpointing (checkpoint touches mtime).
@@ -11296,7 +11446,16 @@ async function syncCommand(args) {
11296
11446
  force,
11297
11447
  localMtimeMs,
11298
11448
  localDevice: await readSyncDevice(),
11449
+ dryRun,
11299
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
+ }
11300
11459
  // 0.2.3 Wave 1: distinguish bootstrapped / forced / plain pull / unchanged.
11301
11460
  reportSyncPullResult(result)
11302
11461
  if (result.changed) {
@@ -12695,6 +12854,9 @@ async function tosGate() {
12695
12854
  // Offline receipt verification must work on a clean machine without a
12696
12855
  // ~/.advisers consent record (docs/DELIVERY-RECEIPT.md); it reads only <dir>.
12697
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
12698
12860
  else if (TOS_EXEMPT_COMMANDS.has(command) || !KNOWN_COMMANDS.has(command)) return
12699
12861
  const tos = await loadTos()
12700
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.1'
3
+ export const version = '0.4.2'
4
4
  export const distribution = 'cordis'
5
5
  export const status = 'bootstrapping'