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.
@@ -0,0 +1,287 @@
1
+ /**
2
+ * 0.4.x: `mail sync --watch` — interruptible polling loop (library layer).
3
+ *
4
+ * `advisers mail sync --watch` is a foreground, Ctrl+C-interruptible poller:
5
+ * run one sync pass, record the outcome, wait, repeat until the operator stops
6
+ * it. The CLI wiring (arg parsing, SIGINT, human/JSON lines, lock handling) is
7
+ * a separate integration task; this module owns only the loop so it can be
8
+ * tested with a fake clock, no network and no console.
9
+ *
10
+ * Contract:
11
+ * - `syncOnce()` is called with no arguments once per round; the caller closes
12
+ * over the account list, the store and the credentials. A thrown error or a
13
+ * rejected promise is recorded and the loop continues: one failing mailbox
14
+ * must never stop the watch;
15
+ * - `signal` (AbortSignal) stops the loop promptly. The default wait resolves
16
+ * on abort, and an in-flight round is allowed to finish before the summary is
17
+ * returned;
18
+ * - `onResult(record, counts)` is a pure observer called after every round. If
19
+ * it throws, the watch keeps going and counts `callbackErrors`;
20
+ * - `stopped` is `'aborted'` after an abort and `'max-runs'` once `maxRuns`
21
+ * rounds have been attempted; with the default `Infinity` only an abort
22
+ * stops the loop;
23
+ * - failures back off exponentially (5s, 10s, 20s ... capped at 5 min) and a
24
+ * successful round resets the streak; the normal wait is `intervalMs`
25
+ * (default 5 min);
26
+ * - no I/O: this module never reads credentials, never opens the ledger and
27
+ * never prints. Callers own stdout/stderr, the summary rendering and the
28
+ * operator-facing lines.
29
+ *
30
+ * The returned summary is JSON-ready: error text is collapsed to one printable
31
+ * line (no ANSI/control characters) and `maxRuns` is `null` when unlimited, so
32
+ * a `--json` caller can serialise it as-is.
33
+ */
34
+ import { sanitizeConsoleText } from './text-safe.js'
35
+
36
+ /** Default poll interval: 5 minutes. */
37
+ export const MAIL_WATCH_DEFAULT_INTERVAL_MS = 300_000
38
+ /** Smallest accepted poll interval: 1 second (protects servers from busy loops). */
39
+ export const MAIL_WATCH_MIN_INTERVAL_MS = 1_000
40
+ /** Largest accepted poll interval: 24 hours. */
41
+ export const MAIL_WATCH_MAX_INTERVAL_MS = 24 * 60 * 60 * 1000
42
+ /** First retry delay after a failed round; doubles per consecutive failure. */
43
+ export const MAIL_WATCH_RETRY_BASE_MS = 5_000
44
+ /** Cap for the exponential retry backoff. */
45
+ export const MAIL_WATCH_RETRY_MAX_MS = 5 * 60 * 1000
46
+ /** Attempt records kept in `history`; older ones are counted, not stored. */
47
+ export const MAIL_WATCH_HISTORY_LIMIT = 20
48
+ /** Maximum characters of an error message kept in the summary. */
49
+ export const MAIL_WATCH_ERROR_MAX = 500
50
+ /** Why the loop stopped (`summary.stopped`). */
51
+ export const MAIL_WATCH_STOPPED = Object.freeze({ ABORTED: 'aborted', MAX_RUNS: 'max-runs' })
52
+
53
+ /** Usage error carrying the registered CLI code; never a bare E_* literal. */
54
+ function usageError(message) {
55
+ const error = new RangeError('mail watch: ' + message)
56
+ error.code = 'E_USAGE'
57
+ return error
58
+ }
59
+
60
+ function typeError(message) {
61
+ return new TypeError('mail watch: ' + message)
62
+ }
63
+
64
+ function normalizeInterval(value) {
65
+ if (value === undefined) return MAIL_WATCH_DEFAULT_INTERVAL_MS
66
+ if (typeof value !== 'number' || !Number.isInteger(value)) {
67
+ throw usageError('intervalMs must be an integer number of milliseconds')
68
+ }
69
+ if (value < MAIL_WATCH_MIN_INTERVAL_MS || value > MAIL_WATCH_MAX_INTERVAL_MS) {
70
+ throw usageError('intervalMs must be within ' + MAIL_WATCH_MIN_INTERVAL_MS + '..' + MAIL_WATCH_MAX_INTERVAL_MS + ' ms (1s..24h)')
71
+ }
72
+ return value
73
+ }
74
+
75
+ function normalizeMaxRuns(value) {
76
+ if (value === undefined) return Infinity
77
+ if (value === Infinity) return Infinity
78
+ if (typeof value !== 'number' || Number.isNaN(value) || !Number.isInteger(value)) {
79
+ throw usageError('maxRuns must be Infinity or a positive integer')
80
+ }
81
+ if (value < 1) throw usageError('maxRuns must be at least 1')
82
+ return value
83
+ }
84
+
85
+ function normalizeSignal(value) {
86
+ if (value === undefined || value === null) return null
87
+ if (
88
+ typeof value !== 'object' ||
89
+ typeof value.aborted !== 'boolean' ||
90
+ typeof value.addEventListener !== 'function' ||
91
+ typeof value.removeEventListener !== 'function'
92
+ ) {
93
+ throw typeError('signal must be an AbortSignal')
94
+ }
95
+ return value
96
+ }
97
+
98
+ function normalizeOptionalFunction(value, name, fallback) {
99
+ if (value === undefined || value === null) return fallback
100
+ if (typeof value !== 'function') throw typeError(name + ' must be a function')
101
+ return value
102
+ }
103
+
104
+ function normalizeClock(value) {
105
+ if (value === undefined || value === null) return Date.now
106
+ if (typeof value !== 'function') throw typeError('now must be a function returning epoch milliseconds')
107
+ return function readNow() {
108
+ const ms = value()
109
+ if (typeof ms !== 'number' || !Number.isFinite(ms)) throw typeError('now() must return finite epoch milliseconds')
110
+ return ms
111
+ }
112
+ }
113
+
114
+ /**
115
+ * Abort-aware wait used by the loop. The timer is deliberately ref'd: a
116
+ * foreground `--watch` must keep the process alive while it sleeps. The abort
117
+ * listener is removed on both the timer and the abort path so a long watch
118
+ * cannot accumulate listeners on the signal.
119
+ */
120
+ function defaultSleep(ms, signal) {
121
+ if (signal?.aborted) return Promise.resolve()
122
+ return new Promise((resolve) => {
123
+ let timer = null
124
+ function finish() {
125
+ if (timer !== null) { clearTimeout(timer); timer = null }
126
+ signal?.removeEventListener('abort', finish)
127
+ resolve()
128
+ }
129
+ timer = setTimeout(finish, ms)
130
+ if (signal) signal.addEventListener('abort', finish, { once: true })
131
+ })
132
+ }
133
+
134
+ /** Exponential retry delay for `consecutiveErrors` consecutive failures. */
135
+ function retryDelay(consecutiveErrors) {
136
+ if (consecutiveErrors <= 0) return 0
137
+ const exponent = Math.min(consecutiveErrors - 1, 30)
138
+ return Math.min(MAIL_WATCH_RETRY_MAX_MS, MAIL_WATCH_RETRY_BASE_MS * 2 ** exponent)
139
+ }
140
+
141
+ /**
142
+ * One printable, JSON-safe description of a failed round. The message is
143
+ * sanitised because a sync implementation may surface remote IMAP/server text;
144
+ * no stdout/stderr write happens here, this is only what the summary carries.
145
+ */
146
+ function summarizeError(error) {
147
+ const value = error === null || error === undefined ? new Error('syncOnce failed without an error value') : error
148
+ const isObject = typeof value === 'object'
149
+ const rawMessage = isObject ? value.message : String(value)
150
+ const summary = {
151
+ name: isObject && typeof value.name === 'string' && value.name ? value.name : 'Error',
152
+ message: sanitizeConsoleText(rawMessage === undefined || rawMessage === null ? String(value) : rawMessage, { max: MAIL_WATCH_ERROR_MAX }),
153
+ }
154
+ if (isObject && typeof value.code === 'string' && value.code) summary.code = value.code
155
+ return summary
156
+ }
157
+
158
+ function pushHistory(state, record) {
159
+ state.history.push(record)
160
+ while (state.history.length > MAIL_WATCH_HISTORY_LIMIT) {
161
+ state.history.shift()
162
+ state.historyDropped += 1
163
+ }
164
+ }
165
+
166
+ function buildSummary(state, stopped, finishedAtMs) {
167
+ return {
168
+ runs: state.runs,
169
+ success: state.success,
170
+ errors: state.errors,
171
+ consecutiveErrors: state.consecutiveErrors,
172
+ stopped,
173
+ last: state.last,
174
+ history: state.history.slice(),
175
+ historyDropped: state.historyDropped,
176
+ callbackErrors: state.callbackErrors,
177
+ intervalMs: state.intervalMs,
178
+ maxRuns: Number.isFinite(state.maxRuns) ? state.maxRuns : null,
179
+ nextDelayMs: state.nextDelayMs,
180
+ backoffMs: state.backoffMs,
181
+ startedAt: new Date(state.startedAtMs).toISOString(),
182
+ finishedAt: new Date(finishedAtMs).toISOString(),
183
+ durationMs: Math.max(0, finishedAtMs - state.startedAtMs),
184
+ }
185
+ }
186
+
187
+ /**
188
+ * Run the interruptible mail-watch loop until it is aborted or reaches
189
+ * `maxRuns`. See the module header for the full contract.
190
+ *
191
+ * @param {object} options
192
+ * @param {() => Promise<unknown>} options.syncOnce called with no arguments once
193
+ * per round; the caller closes over accounts/store/credentials.
194
+ * @param {number} [options.intervalMs=300000] wait between successful rounds (1s..24h).
195
+ * @param {number|Infinity} [options.maxRuns=Infinity] attempt cap (tests / one-shot).
196
+ * @param {AbortSignal|null} [options.signal] stops the loop promptly on abort.
197
+ * @param {(record: object, counts: object) => (void|Promise<void>)} [options.onResult]
198
+ * per-round observer; a throw is counted in `callbackErrors` and does not stop the loop.
199
+ * @param {(ms: number, signal: AbortSignal|null) => Promise<void>} [options.sleep]
200
+ * test/embedding hook; defaults to an abort-aware setTimeout.
201
+ * @param {() => number} [options.now] test/embedding clock (epoch milliseconds).
202
+ * @returns {Promise<object>} JSON-ready summary: `runs`, `success`, `errors`,
203
+ * `consecutiveErrors`, `stopped` ('aborted'|'max-runs'), `last`, `history`,
204
+ * `historyDropped`, `callbackErrors`, `intervalMs`, `maxRuns`, `nextDelayMs`,
205
+ * `backoffMs`, `startedAt`, `finishedAt`, `durationMs`.
206
+ */
207
+ export async function runMailWatch(options = {}) {
208
+ if (options === null || typeof options !== 'object') throw typeError('options must be an object')
209
+ const syncOnce = options.syncOnce
210
+ if (typeof syncOnce !== 'function') throw typeError('syncOnce must be a function returning a promise')
211
+ const intervalMs = normalizeInterval(options.intervalMs)
212
+ const maxRuns = normalizeMaxRuns(options.maxRuns)
213
+ const signal = normalizeSignal(options.signal)
214
+ const onResult = normalizeOptionalFunction(options.onResult, 'onResult', null)
215
+ const sleep = normalizeOptionalFunction(options.sleep, 'sleep', defaultSleep)
216
+ const now = normalizeClock(options.now)
217
+ const state = {
218
+ runs: 0,
219
+ success: 0,
220
+ errors: 0,
221
+ consecutiveErrors: 0,
222
+ callbackErrors: 0,
223
+ last: null,
224
+ history: [],
225
+ historyDropped: 0,
226
+ intervalMs,
227
+ maxRuns,
228
+ nextDelayMs: null,
229
+ backoffMs: 0,
230
+ startedAtMs: now(),
231
+ }
232
+ let stopped = null
233
+ while (stopped === null) {
234
+ if (signal?.aborted) { stopped = MAIL_WATCH_STOPPED.ABORTED; break }
235
+ if (state.runs >= maxRuns) { stopped = MAIL_WATCH_STOPPED.MAX_RUNS; break }
236
+ const startedAtMs = now()
237
+ let result
238
+ let error = null
239
+ try {
240
+ result = await syncOnce()
241
+ } catch (caught) {
242
+ error = caught
243
+ }
244
+ const durationMs = Math.max(0, now() - startedAtMs)
245
+ const ok = error === null
246
+ state.runs += 1
247
+ if (ok) {
248
+ state.success += 1
249
+ state.consecutiveErrors = 0
250
+ state.backoffMs = 0
251
+ } else {
252
+ state.errors += 1
253
+ state.consecutiveErrors += 1
254
+ state.backoffMs = retryDelay(state.consecutiveErrors)
255
+ }
256
+ state.nextDelayMs = ok ? intervalMs : state.backoffMs
257
+ const record = {
258
+ run: state.runs,
259
+ ok,
260
+ startedAt: new Date(startedAtMs).toISOString(),
261
+ durationMs,
262
+ nextDelayMs: state.nextDelayMs,
263
+ backoffMs: state.backoffMs,
264
+ }
265
+ if (ok) record.result = result
266
+ else record.error = summarizeError(error)
267
+ state.last = record
268
+ pushHistory(state, record)
269
+ if (onResult) {
270
+ const counts = {
271
+ runs: state.runs,
272
+ success: state.success,
273
+ errors: state.errors,
274
+ consecutiveErrors: state.consecutiveErrors,
275
+ }
276
+ try {
277
+ await onResult(record, counts)
278
+ } catch {
279
+ state.callbackErrors += 1
280
+ }
281
+ }
282
+ if (signal?.aborted) { stopped = MAIL_WATCH_STOPPED.ABORTED; break }
283
+ if (state.runs >= maxRuns) { stopped = MAIL_WATCH_STOPPED.MAX_RUNS; break }
284
+ await sleep(state.nextDelayMs, signal)
285
+ }
286
+ return buildSummary(state, stopped, now())
287
+ }
package/lib/mail.js CHANGED
@@ -321,8 +321,8 @@ export function mailLink(store, ref, options = {}) {
321
321
  mailDb.assertMailTables(store)
322
322
  const now = asDate(options.now)
323
323
  const message = mailDb.getMailMessage(store, ref)
324
- const clientId = options.clientId == null ? message.clientId : String(options.clientId)
325
- const projectId = options.projectId == null ? message.projectId : String(options.projectId)
324
+ const clientId = options.clientId == null ? (message.clientId ?? null) : String(options.clientId)
325
+ const projectId = options.projectId == null ? (message.projectId ?? null) : String(options.projectId)
326
326
  const audit = { actor: options.actor ?? 'local', action: 'mail.link', allowed: true, reason: message.id }
327
327
  const updated = store.mutate(() => mailDb.updateMailMessage(store, message.id, { clientId, projectId, status: 'linked' }, { now }), audit).result
328
328
  return { ok: true, command: 'mail link', message: updated }
package/lib/sync.js CHANGED
@@ -28,6 +28,14 @@
28
28
  * loop, fsync, rename retry) and the staging file plus its -wal/-shm siblings
29
29
  * are always removed; `cleanupStalePullTemps()` (bin/doctor hook) sweeps
30
30
  * leftovers from a crashed pull.
31
+ * - `pullSnapshot({ dryRun: true })` makes the same decision — snapshot
32
+ * selection, decryption + SHA-256, the local-empty/older/same-device checks —
33
+ * and predicts whether a real pull would replace the database, but writes
34
+ * nothing: no database replace, no backup, no staging temp, no stale-temp
35
+ * sweep and no audit row. It returns `status: 'dry-run'` (or `'unchanged'`
36
+ * when the local bytes already match and `force` is not set) plus
37
+ * `wouldChange` / `wouldStatus` / `wouldBackup`; warnings are returned for
38
+ * the caller to print, because a dry run never prints or writes.
31
39
  */
32
40
  import { chmodSync, existsSync, mkdirSync, readFileSync, readdirSync, statSync } from 'node:fs'
33
41
  import { createHash } from 'node:crypto'
@@ -433,8 +441,21 @@ function emitWarnings(warnings) {
433
441
  * - --force never changes WHICH snapshot is selected (selection is always the
434
442
  * newest readable one unless --file names one), and replacing the local
435
443
  * ledger with an older snapshot is warned about loudly.
444
+ * - dryRun:true stops after the read-only decision phase. It reports the same
445
+ * file/sha256/device/createdAt/localEmpty/snapshotOlder/sameDevice/warnings a
446
+ * real pull would report, plus `wouldChange`, `wouldStatus` (the status a
447
+ * real pull would return: pulled | bootstrapped | forced | unchanged) and
448
+ * `wouldBackup`, while `changed` stays false and `backup` stays null. A
449
+ * caller can therefore explain what WOULD happen, and bin/ keeps its
450
+ * sync.pull audit off because it only audits `changed` pulls. The snapshot's
451
+ * PRAGMA quick_check is intentionally NOT run: it needs the decrypted bytes
452
+ * staged next to the database, which a dry run must not do, so a snapshot
453
+ * whose SHA-256 is self-consistent but whose bytes are not a SQLite database
454
+ * is predicted as a change and then refused by the real pull (the live
455
+ * database stays intact; see test/sync-pull-integrity.test.js).
436
456
  */
437
- export function pullSnapshot({ dir, dbPath, passphrase, file, force = false, localMtimeMs, localDevice, now = Date.now() }) {
457
+ export function pullSnapshot({ dir, dbPath, passphrase, file, force = false, dryRun = false, localMtimeMs, localDevice, now = Date.now() }) {
458
+ const isDryRun = Boolean(dryRun)
438
459
  const { chosen, warnings: selectionWarnings } = selectSnapshot({ dir, passphrase, file, now })
439
460
  const envelope = JSON.parse(readFileSync(chosen.file, 'utf8'))
440
461
  if (!isVaultEnvelope(envelope)) throw new Error('snapshot is not an Advisers encrypted envelope')
@@ -460,7 +481,10 @@ export function pullSnapshot({ dir, dbPath, passphrase, file, force = false, loc
460
481
  let localBytes = null
461
482
  try { localBytes = readFileSync(dbPath) } catch {}
462
483
  if (localBytes && localBytes.equals(bytes)) {
463
- return { ...base, changed: false, status: 'unchanged' }
484
+ const unchanged = { ...base, changed: false, status: 'unchanged' }
485
+ // A dry run reports the same no-op verdict without touching anything.
486
+ if (!isDryRun) return unchanged
487
+ return { ...unchanged, dryRun: true, wouldChange: false, wouldStatus: 'unchanged', wouldBackup: false }
464
488
  }
465
489
  }
466
490
 
@@ -476,6 +500,17 @@ export function pullSnapshot({ dir, dbPath, passphrase, file, force = false, loc
476
500
  const reason = force ? '--force was given' : 'the snapshot was pushed from this device'
477
501
  warnings.push(`replacing a newer local database (${new Date(localAt).toISOString()}) with older snapshot ${chosen.name} (${new Date(snapshotAt).toISOString()}) because ${reason}; a backup is kept`)
478
502
  }
503
+
504
+ // Dry run: everything above (selection, decryption, SHA-256, refusal rules,
505
+ // local state) is the same decision a real pull makes; everything below
506
+ // (temp staging, backup, rename, stale-temp sweep) is a write. Stop here and
507
+ // predict instead. `changed` stays false so a caller cannot mistake this for
508
+ // an applied pull (bin/ only audits changed pulls and keeps its backup note
509
+ // from `backup`, which stays null). Warnings are returned, not printed.
510
+ if (isDryRun) {
511
+ return { ...base, changed: false, status: 'dry-run', dryRun: true, wouldChange: true, wouldStatus: status, wouldBackup: local.exists }
512
+ }
513
+
479
514
  emitWarnings(warnings)
480
515
 
481
516
  const parent = dirname(dbPath)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "advisers",
3
- "version": "0.4.0",
3
+ "version": "0.4.2",
4
4
  "description": "A staff of AI advisers: a cordis-native personal secretary runtime with scoped memory, commitments, and reviewable routines.",
5
5
  "keywords": [
6
6
  "cordis",
@@ -36,8 +36,8 @@
36
36
  ],
37
37
  "dependencies": {
38
38
  "@pdf-lib/fontkit": "^1.1.1",
39
- "advisers-core": "0.4.0",
40
- "advisers-policy-strict": "0.4.0",
39
+ "advisers-core": "0.4.2",
40
+ "advisers-policy-strict": "0.4.2",
41
41
  "jszip": "^3.10.2",
42
42
  "pdf-lib": "^1.17.1",
43
43
  "pdfjs-dist": "^6.5.438"
@@ -61,7 +61,7 @@
61
61
  "test": "node --experimental-strip-types --test test/*.test.js"
62
62
  },
63
63
  "peerDependencies": {
64
- "advisers-office": "0.4.0"
64
+ "advisers-office": "0.4.2"
65
65
  },
66
66
  "peerDependenciesMeta": {
67
67
  "advisers-office": {