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.
Files changed (44) hide show
  1. package/README-zh.md +13 -14
  2. package/README.md +37 -23
  3. package/THIRD-PARTY-NOTICES.md +1 -1
  4. package/bin/advisers.js +2302 -95
  5. package/index.js +1 -1
  6. package/lib/brief-archive.js +267 -0
  7. package/lib/client-pack.js +1016 -0
  8. package/lib/consent.js +390 -0
  9. package/lib/credentials.js +195 -0
  10. package/lib/error-codes.js +516 -7
  11. package/lib/evidence.js +697 -113
  12. package/lib/kb-extract.js +626 -0
  13. package/lib/kb-facts.js +429 -0
  14. package/lib/kb-pages.js +1084 -0
  15. package/lib/kb.js +1036 -0
  16. package/lib/mail-errors.js +46 -0
  17. package/lib/mail-extract.js +351 -0
  18. package/lib/mail-imap.js +446 -0
  19. package/lib/mail-import.js +176 -0
  20. package/lib/mail-parse.js +223 -0
  21. package/lib/mail-store.js +731 -0
  22. package/lib/mail.js +506 -0
  23. package/lib/mcp-server.js +196 -10
  24. package/lib/notify.js +265 -7
  25. package/lib/policy/decision.js +315 -0
  26. package/lib/policy/egress.js +268 -0
  27. package/lib/policy/errors.js +71 -0
  28. package/lib/policy/index.js +99 -0
  29. package/lib/policy/rules.js +468 -0
  30. package/lib/policy/surfaces.js +141 -0
  31. package/lib/receipt-verify.js +199 -19
  32. package/lib/receivables.js +1653 -0
  33. package/lib/scheduler.js +453 -9
  34. package/lib/shell.js +1406 -0
  35. package/lib/source.js +98 -3
  36. package/lib/sqlite.js +366 -49
  37. package/lib/tos/index.js +2 -2
  38. package/lib/tos/manifest.json +6 -6
  39. package/lib/tos/privacy.zh-CN.md +33 -20
  40. package/lib/tos/safety.zh-CN.md +7 -6
  41. package/lib/tos/summary.zh-CN.md +3 -2
  42. package/lib/tos/terms.zh-CN.md +31 -16
  43. package/lib/urgency.js +467 -0
  44. package/package.json +4 -4
package/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  export * from 'advisers-core'
2
2
 
3
- export const version = '0.3.2'
3
+ export const version = '0.4.1'
4
4
  export const distribution = 'cordis'
5
5
  export const status = 'bootstrapping'
@@ -0,0 +1,267 @@
1
+ /**
2
+ * Proactive 0.4 — morning brief archive.
3
+ *
4
+ * `advisers morning --archive` (CLI wiring is a separate integration task) stores
5
+ * the deterministic markdown under `<ADVISERS_HOME>/briefs/`:
6
+ *
7
+ * briefs/2026-11-21.md write-once-per-day file, atomically overwritten on re-run
8
+ * briefs/latest.md byte copy of the most recent archive
9
+ *
10
+ * Privacy/retention rules baked into this module:
11
+ * - the directory is 0700 and every file 0600 (owner-only);
12
+ * - only files matching `YYYY-MM-DD.md` are ever deleted, never recursively,
13
+ * so unrelated files in `briefs/` are preserved;
14
+ * - the default retention is 14 local days (1..365 configurable) and only the
15
+ * archived day files are pruned;
16
+ * - the audit row suggestion never contains the brief body.
17
+ *
18
+ * Pure-library style: no console output, JSON-ready return values, caller owns
19
+ * the audit write and the writer lock.
20
+ */
21
+ import { chmodSync, existsSync, mkdirSync, readdirSync, readFileSync, statSync, unlinkSync } from 'node:fs'
22
+ import { homedir } from 'node:os'
23
+ import { join, resolve } from 'node:path'
24
+ import { atomicWriteFileSync } from './fs-safe.js'
25
+
26
+ export const BRIEFS_DIR = 'briefs'
27
+ export const BRIEF_LATEST_FILE = 'latest.md'
28
+ /** Default number of daily briefs kept by `--archive`. */
29
+ export const BRIEF_RETENTION_DAYS = 14
30
+ export const BRIEF_MIN_KEEP = 1
31
+ export const BRIEF_MAX_KEEP = 365
32
+ /** Audit action written by the CLI after a successful archive. */
33
+ export const BRIEF_AUDIT_ACTION = 'brief.archive'
34
+
35
+ const DATE_ONLY_RE = /^(\d{4})-(\d{2})-(\d{2})$/
36
+ const DAY_FILE_RE = /^(\d{4})-(\d{2})-(\d{2})\.md$/
37
+
38
+ /** Local usage error carrying the registered CLI code (never throws an E_* literal). */
39
+ function usageError(message) {
40
+ const error = new RangeError(message)
41
+ error.code = 'E_USAGE'
42
+ return error
43
+ }
44
+
45
+ function validCalendarDay(year, month, day) {
46
+ if (!Number.isInteger(year) || !Number.isInteger(month) || !Number.isInteger(day)) return false
47
+ if (year < 1000 || year > 9999 || month < 1 || month > 12 || day < 1 || day > 31) return false
48
+ const probe = new Date(Date.UTC(year, month - 1, day))
49
+ return probe.getUTCFullYear() === year && probe.getUTCMonth() === month - 1 && probe.getUTCDate() === day
50
+ }
51
+
52
+ /**
53
+ * Validate an archive day. Accepts only real `YYYY-MM-DD` calendar days so the
54
+ * filename, the retention key and the audit reason can never disagree.
55
+ * @param {string} localDay
56
+ * @returns {string} the trimmed canonical day
57
+ */
58
+ export function validateBriefDay(localDay) {
59
+ if (typeof localDay !== 'string') throw usageError('brief localDay must be a YYYY-MM-DD string')
60
+ const text = localDay.trim()
61
+ const match = DATE_ONLY_RE.exec(text)
62
+ if (!match) throw usageError('brief localDay must be YYYY-MM-DD')
63
+ if (!validCalendarDay(Number(match[1]), Number(match[2]), Number(match[3]))) {
64
+ throw usageError('brief localDay is not a real calendar day: ' + text)
65
+ }
66
+ return text
67
+ }
68
+
69
+ /** Resolve the Advisers home without assuming a real HOME when one is passed. */
70
+ export function briefHome({ home, env = process.env } = {}) {
71
+ if (home !== undefined && home !== null && String(home).trim() !== '') return resolve(String(home))
72
+ const fromEnv = env?.ADVISERS_HOME
73
+ if (fromEnv !== undefined && fromEnv !== null && String(fromEnv).trim() !== '') return resolve(String(fromEnv))
74
+ return resolve(join(homedir(), '.advisers'))
75
+ }
76
+
77
+ /**
78
+ * Paths of the managed archive directory. `home` wins over `env.ADVISERS_HOME`;
79
+ * tests always pass an explicit `home` (temporary directory).
80
+ * @returns {{home: string, dir: string, latestFile: string}}
81
+ */
82
+ export function briefPaths({ home, env } = {}) {
83
+ const root = briefHome({ home, env })
84
+ const dir = join(root, BRIEFS_DIR)
85
+ return { home: root, dir, latestFile: join(dir, BRIEF_LATEST_FILE) }
86
+ }
87
+
88
+ /** Absolute path of one archived day file (validates the day). */
89
+ export function briefFilePath({ home, env, localDay } = {}) {
90
+ const day = validateBriefDay(localDay)
91
+ return join(briefPaths({ home, env }).dir, day + '.md')
92
+ }
93
+
94
+ function normalizeKeep(keep) {
95
+ if (keep === undefined || keep === null) return BRIEF_RETENTION_DAYS
96
+ if (!Number.isInteger(keep) || keep < BRIEF_MIN_KEEP || keep > BRIEF_MAX_KEEP) {
97
+ throw usageError('brief keep must be an integer ' + BRIEF_MIN_KEEP + '..' + BRIEF_MAX_KEEP)
98
+ }
99
+ return keep
100
+ }
101
+
102
+ /**
103
+ * List archived day files, newest first. Non-matching entries (including
104
+ * `latest.md`, unrelated files and symlinks) are never considered: retention and
105
+ * deletion only ever touch `YYYY-MM-DD.md` regular files.
106
+ */
107
+ function listDayFiles(dir) {
108
+ let entries
109
+ try {
110
+ entries = readdirSync(dir, { withFileTypes: true })
111
+ } catch (error) {
112
+ if (error?.code === 'ENOENT') return []
113
+ throw error
114
+ }
115
+ const files = []
116
+ for (const entry of entries) {
117
+ if (!entry.isFile()) continue
118
+ const match = DAY_FILE_RE.exec(entry.name)
119
+ if (!match) continue
120
+ if (!validCalendarDay(Number(match[1]), Number(match[2]), Number(match[3]))) continue
121
+ const path = join(dir, entry.name)
122
+ let info
123
+ try {
124
+ info = statSync(path)
125
+ } catch {
126
+ continue
127
+ }
128
+ files.push({
129
+ localDay: match[1] + '-' + match[2] + '-' + match[3],
130
+ path,
131
+ bytes: info.size,
132
+ modifiedAt: info.mtime.toISOString(),
133
+ })
134
+ }
135
+ files.sort((left, right) => (left.localDay < right.localDay ? 1 : left.localDay > right.localDay ? -1 : 0))
136
+ return files
137
+ }
138
+
139
+ /**
140
+ * Audit-row suggestion for a successful archive. Contains the local day only —
141
+ * never the brief body — and is returned rather than written so the CLI keeps
142
+ * ownership of the writer lock (`store.appendAudit`).
143
+ *
144
+ * @param {{localDay: string}} options
145
+ * @returns {{actor: 'local', action: string, allowed: true, reason: string}}
146
+ */
147
+ export function briefAuditRow({ localDay } = {}) {
148
+ const day = validateBriefDay(localDay)
149
+ return { actor: 'local', action: BRIEF_AUDIT_ACTION, allowed: true, reason: day }
150
+ }
151
+
152
+ function latestInfo(latestFile) {
153
+ try {
154
+ const info = statSync(latestFile)
155
+ return { exists: true, path: latestFile, bytes: info.size, modifiedAt: info.mtime.toISOString() }
156
+ } catch (error) {
157
+ if (error?.code === 'ENOENT') return { exists: false, path: latestFile, bytes: 0, modifiedAt: null }
158
+ throw error
159
+ }
160
+ }
161
+
162
+ /**
163
+ * Atomically write one archived brief (plus `latest.md`) and prune older day
164
+ * files down to `keep`. Returns the plan as data: the caller prints the removed
165
+ * absolute paths, takes the writer lock and writes `audit` (see
166
+ * {@link briefAuditRow}).
167
+ *
168
+ * `dryRun` computes the same result without touching the filesystem.
169
+ *
170
+ * @param {{home?: string, env?: object, localDay: string, markdown: string,
171
+ * keep?: number, dryRun?: boolean}} options
172
+ * @returns {{ok: true, dryRun: boolean, written: boolean, localDay: string,
173
+ * path: string, latestPath: string, keep: number, bytes: number,
174
+ * retained: string[], removed: string[], failed: Array<{path: string, code: string}>,
175
+ * audit: object}}
176
+ */
177
+ export function archiveBrief({ home, env, localDay, markdown, keep, dryRun = false } = {}) {
178
+ const day = validateBriefDay(localDay)
179
+ if (typeof markdown !== 'string') throw new TypeError('brief markdown must be a string')
180
+ const retention = normalizeKeep(keep)
181
+ const paths = briefPaths({ home, env })
182
+ const target = join(paths.dir, day + '.md')
183
+ const existing = listDayFiles(paths.dir).filter((file) => file.localDay !== day)
184
+ const all = [{ localDay: day, path: target }, ...existing]
185
+ .sort((left, right) => (left.localDay < right.localDay ? 1 : left.localDay > right.localDay ? -1 : 0))
186
+ const retained = all.slice(0, retention).map((file) => file.localDay)
187
+ const pruned = all.slice(retention).filter((file) => file.localDay !== day)
188
+ const bytes = Buffer.byteLength(markdown, 'utf8')
189
+ const audit = briefAuditRow({ localDay: day })
190
+ if (dryRun === true) {
191
+ return {
192
+ ok: true, dryRun: true, written: false, localDay: day, path: target,
193
+ latestPath: paths.latestFile, keep: retention, bytes, retained,
194
+ removed: pruned.map((file) => file.path), failed: [], audit,
195
+ }
196
+ }
197
+ mkdirSync(paths.dir, { recursive: true, mode: 0o700 })
198
+ try { chmodSync(paths.dir, 0o700) } catch {}
199
+ // Atomic overwrite: re-running the same day replaces the file, and latest.md
200
+ // always ends up byte-identical to the newest archive.
201
+ atomicWriteFileSync(target, markdown, { mode: 0o600 })
202
+ atomicWriteFileSync(paths.latestFile, markdown, { mode: 0o600 })
203
+ const failed = []
204
+ const removed = []
205
+ for (const file of pruned) {
206
+ try {
207
+ unlinkSync(file.path)
208
+ removed.push(file.path)
209
+ } catch (error) {
210
+ failed.push({ path: file.path, code: typeof error?.code === 'string' ? error.code : 'E_UNKNOWN' })
211
+ }
212
+ }
213
+ return {
214
+ ok: true, dryRun: false, written: true, localDay: day, path: target,
215
+ latestPath: paths.latestFile, keep: retention, bytes, retained,
216
+ removed, failed, audit,
217
+ }
218
+ }
219
+
220
+ /**
221
+ * Read one archived brief. A missing day is `{found: false}` rather than an
222
+ * error (an archive is optional); other filesystem errors are rethrown.
223
+ *
224
+ * @param {{home?: string, env?: object, localDay: string}} options
225
+ * @returns {{ok: true, found: boolean, localDay: string, path: string,
226
+ * markdown: string|null, bytes: number}}
227
+ */
228
+ export function readBrief({ home, env, localDay } = {}) {
229
+ const day = validateBriefDay(localDay)
230
+ const path = join(briefPaths({ home, env }).dir, day + '.md')
231
+ try {
232
+ const markdown = readFileSync(path, 'utf8')
233
+ return { ok: true, found: true, localDay: day, path, markdown, bytes: Buffer.byteLength(markdown, 'utf8') }
234
+ } catch (error) {
235
+ if (error?.code === 'ENOENT') return { ok: true, found: false, localDay: day, path, markdown: null, bytes: 0 }
236
+ throw error
237
+ }
238
+ }
239
+
240
+ /**
241
+ * List the archive without reading any brief body: day metadata newest first,
242
+ * plus the `latest.md` copy's metadata. `exists: false` means no archive has
243
+ * ever been written.
244
+ *
245
+ * @param {{home?: string, env?: object, limit?: number}} options
246
+ * @returns {{ok: true, dir: string, exists: boolean, count: number,
247
+ * briefs: Array<{localDay: string, path: string, bytes: number, modifiedAt: string}>,
248
+ * latest: {exists: boolean, path: string, bytes: number, modifiedAt: string|null}}}
249
+ */
250
+ export function listBriefs({ home, env, limit } = {}) {
251
+ const paths = briefPaths({ home, env })
252
+ const exists = existsSync(paths.dir)
253
+ const all = listDayFiles(paths.dir)
254
+ let briefs = all
255
+ if (limit !== undefined && limit !== null) {
256
+ if (!Number.isInteger(limit) || limit < 1) throw usageError('brief limit must be a positive integer')
257
+ briefs = all.slice(0, limit)
258
+ }
259
+ return {
260
+ ok: true,
261
+ dir: paths.dir,
262
+ exists,
263
+ count: all.length,
264
+ briefs: briefs.map((file) => ({ localDay: file.localDay, path: file.path, bytes: file.bytes, modifiedAt: file.modifiedAt })),
265
+ latest: latestInfo(paths.latestFile),
266
+ }
267
+ }