advisers 0.2.0-preview.71 → 0.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +130 -201
- package/NOTICE +29 -4
- package/README-zh.md +35 -8
- package/README.md +37 -8
- package/THIRD-PARTY-NOTICES.md +277 -0
- package/bin/advisers.js +2264 -350
- package/index.js +1 -1
- package/lib/attachments.js +158 -29
- package/lib/capture.js +82 -2
- package/lib/evidence.js +1180 -26
- package/lib/ical.js +542 -0
- package/lib/imap.js +82 -24
- package/lib/mcp-server.js +869 -0
- package/lib/model.js +151 -2
- package/lib/notify.js +156 -4
- package/lib/ocr.js +26 -1
- package/lib/pdf.js +52 -6
- package/lib/pet-brief.js +78 -15
- package/lib/receipt-verify.js +644 -0
- package/lib/remind.js +261 -11
- package/lib/research.js +148 -18
- package/lib/safety/classifier.js +444 -0
- package/lib/safety/explain.js +157 -0
- package/lib/safety/index.js +333 -0
- package/lib/safety/redact.js +212 -0
- package/lib/safety/rules.js +824 -0
- package/lib/scheduler.js +399 -0
- package/lib/source.js +294 -0
- package/lib/sqlite.js +702 -42
- package/lib/sync.js +141 -20
- package/lib/timestamp.js +26 -1
- package/lib/tos/index.js +332 -0
- package/lib/tos/manifest.json +32 -0
- package/lib/tos/privacy.zh-CN.md +136 -0
- package/lib/tos/safety.zh-CN.md +101 -0
- package/lib/tos/summary.zh-CN.md +12 -0
- package/lib/tos/terms.zh-CN.md +439 -0
- package/package.json +10 -8
package/bin/advisers.js
CHANGED
|
@@ -1,44 +1,73 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import {
|
|
2
|
+
import { spawnSync } from 'node:child_process'
|
|
3
|
+
import { chmodSync, closeSync, copyFileSync, existsSync, fsyncSync, mkdirSync, openSync, readdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync, writeSync } from 'node:fs'
|
|
3
4
|
import { homedir, hostname } from 'node:os'
|
|
4
5
|
import { createHash, randomBytes, randomUUID } from 'node:crypto'
|
|
5
|
-
import { basename, dirname, extname, join } from 'node:path'
|
|
6
|
+
import { basename, dirname, extname, isAbsolute, join } from 'node:path'
|
|
6
7
|
let SqliteStore
|
|
8
|
+
let acquireInstanceLock
|
|
9
|
+
let instanceLockPath
|
|
7
10
|
try {
|
|
8
|
-
({ SqliteStore } = await import('../lib/sqlite.js'))
|
|
11
|
+
({ SqliteStore, acquireInstanceLock, instanceLockPath } = await import('../lib/sqlite.js'))
|
|
9
12
|
} catch (error) {
|
|
10
13
|
if (String(error?.message || error).includes('node:sqlite')) {
|
|
11
|
-
console.error(`Advisers needs Node >= 22.
|
|
14
|
+
console.error(`Advisers needs Node >= 22.16 (node:sqlite). You have ${process.version}. Install Node 24 or use nvm-windows.`)
|
|
12
15
|
process.exit(1)
|
|
13
16
|
}
|
|
14
17
|
throw error
|
|
15
18
|
}
|
|
16
|
-
import { runAgent } from '../lib/agent.js'
|
|
17
|
-
import { chatCompletion } from '../lib/model.js'
|
|
18
|
-
import { extractAttachment, ofdText } from '../lib/attachments.js'
|
|
19
|
-
import { applyPreferenceDecay, buildRoutineCandidate, correctionStatement } from '../lib/learning.js'
|
|
20
|
-
import { checkRoutine } from '../lib/routine.js'
|
|
21
|
-
import { backupBeforeWrite, diffLatest, listBackups, undoLatest } from '../lib/undo.js'
|
|
22
|
-
import { lintReview, materializeReview, reviewRun } from '../lib/review.js'
|
|
23
|
-
import { classifyNudgeOutcome } from '../lib/nudge.js'
|
|
24
|
-
import { buildDigest } from '../lib/digest.js'
|
|
25
|
-
import { captureCandidates } from '../lib/capture.js'
|
|
26
19
|
import { egressDeniedReason } from '../lib/egress.js'
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
import
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* P1-1: lazy-load the heavy / rarely used libraries.
|
|
23
|
+
*
|
|
24
|
+
* Before this, every invocation (including `advisers --version`) paid for the
|
|
25
|
+
* whole static import graph: pdf-lib + fontkit was ~106ms / +34MB RSS and
|
|
26
|
+
* jszip (via attachments) ~22ms / +10MB, plus importers/evidence/sync/vault/
|
|
27
|
+
* ocr/timestamp/notify/remind which only a subset of commands needs. Each
|
|
28
|
+
* loader memoizes its module promise, so a command that needs a library pays
|
|
29
|
+
* for it at most once, and it fails on first use instead of at startup.
|
|
30
|
+
*/
|
|
31
|
+
const lazyModule = (loader) => {
|
|
32
|
+
let promise
|
|
33
|
+
return () => (promise ??= loader())
|
|
34
|
+
}
|
|
35
|
+
const loadAttachments = lazyModule(() => import('../lib/attachments.js'))
|
|
36
|
+
const loadEvidence = lazyModule(() => import('../lib/evidence.js'))
|
|
37
|
+
const loadIcal = lazyModule(() => import('../lib/ical.js'))
|
|
38
|
+
const loadImporters = lazyModule(() => import('../lib/importers.js'))
|
|
39
|
+
const loadNotify = lazyModule(() => import('../lib/notify.js'))
|
|
40
|
+
const loadReceiptVerify = lazyModule(() => import('../lib/receipt-verify.js'))
|
|
41
|
+
const loadScheduler = lazyModule(() => import('../lib/scheduler.js'))
|
|
42
|
+
const loadSource = lazyModule(() => import('../lib/source.js'))
|
|
43
|
+
const loadOcr = lazyModule(() => import('../lib/ocr.js'))
|
|
44
|
+
const loadPdf = lazyModule(() => import('../lib/pdf.js'))
|
|
45
|
+
const loadRemind = lazyModule(() => import('../lib/remind.js'))
|
|
46
|
+
const loadSync = lazyModule(() => import('../lib/sync.js'))
|
|
47
|
+
const loadTimestamp = lazyModule(() => import('../lib/timestamp.js'))
|
|
48
|
+
const loadVault = lazyModule(() => import('../lib/vault.js'))
|
|
49
|
+
const loadTos = lazyModule(() => import('../lib/tos/index.js'))
|
|
50
|
+
const loadMcpServer = lazyModule(() => import('../lib/mcp-server.js'))
|
|
51
|
+
const loadSafety = lazyModule(() => import('../lib/safety/index.js'))
|
|
52
|
+
// P2-4 (0.2.1): every command used to pay for the full static import graph,
|
|
53
|
+
// including the model/agent stack, safety classifier, Pet Brief, UI server,
|
|
54
|
+
// IMAP client and review helpers (~63-75ms of compiled JS). They are only
|
|
55
|
+
// needed by a subset of commands, so each one is a memoized dynamic import.
|
|
56
|
+
const loadAgent = lazyModule(() => import('../lib/agent.js'))
|
|
57
|
+
const loadModel = lazyModule(() => import('../lib/model.js'))
|
|
58
|
+
const loadLearning = lazyModule(() => import('../lib/learning.js'))
|
|
59
|
+
const loadRoutine = lazyModule(() => import('../lib/routine.js'))
|
|
60
|
+
const loadUndo = lazyModule(() => import('../lib/undo.js'))
|
|
61
|
+
const loadReview = lazyModule(() => import('../lib/review.js'))
|
|
62
|
+
const loadNudge = lazyModule(() => import('../lib/nudge.js'))
|
|
63
|
+
const loadDigest = lazyModule(() => import('../lib/digest.js'))
|
|
64
|
+
const loadCapture = lazyModule(() => import('../lib/capture.js'))
|
|
65
|
+
const loadResearch = lazyModule(() => import('../lib/research.js'))
|
|
66
|
+
const loadDocReview = lazyModule(() => import('../lib/doc-review.js'))
|
|
67
|
+
const loadContextWindow = lazyModule(() => import('../lib/context-window.js'))
|
|
68
|
+
const loadPetBrief = lazyModule(() => import('../lib/pet-brief.js'))
|
|
69
|
+
const loadImap = lazyModule(() => import('../lib/imap.js'))
|
|
70
|
+
const loadUi = lazyModule(() => import('../lib/ui.js'))
|
|
42
71
|
|
|
43
72
|
let core
|
|
44
73
|
if (process.env.ADVISERS_CORE_LOCAL === '1') {
|
|
@@ -64,18 +93,120 @@ const DB = join(HOME, 'state.db')
|
|
|
64
93
|
let mode = process.env.ADVISERS_STORE === 'json' ? 'json' : 'sqlite'
|
|
65
94
|
let activeStore
|
|
66
95
|
|
|
96
|
+
/**
|
|
97
|
+
* 0.2.1 robustness audit P0-1: one SQLite writer per HOME.
|
|
98
|
+
*
|
|
99
|
+
* Every process that opens state.db first takes ~/.advisers/instance.lock
|
|
100
|
+
* (O_EXCL create). A second ordinary command waits (ADVISERS_LOCK_TIMEOUT_MS,
|
|
101
|
+
* default 10s) and then exits E_DB_LOCKED instead of saving from a stale
|
|
102
|
+
* snapshot; long-lived holders (ui/mcp/bridge) keep the lock while they run.
|
|
103
|
+
* The lock is released on exit and on SIGINT/SIGTERM. Read-only commands never
|
|
104
|
+
* open the store, so --version/help create no home and no lock.
|
|
105
|
+
*/
|
|
106
|
+
let instanceLock = null
|
|
107
|
+
let storeExitHooksInstalled = false
|
|
108
|
+
const LOCK_PATH = instanceLockPath(HOME)
|
|
109
|
+
|
|
110
|
+
function lockCommandLabel() {
|
|
111
|
+
return process.argv
|
|
112
|
+
.slice(2)
|
|
113
|
+
.filter((value) => !/^--accept-tos(?:=|$)/.test(value))
|
|
114
|
+
.join(' ')
|
|
115
|
+
.slice(0, 160)
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
function releaseInstanceLock() {
|
|
119
|
+
const lock = instanceLock
|
|
120
|
+
instanceLock = null
|
|
121
|
+
try { lock?.release() } catch {}
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
function installStoreExitHooks() {
|
|
125
|
+
if (storeExitHooksInstalled) return
|
|
126
|
+
storeExitHooksInstalled = true
|
|
127
|
+
process.on('exit', releaseInstanceLock)
|
|
128
|
+
for (const signal of ['SIGINT', 'SIGTERM']) {
|
|
129
|
+
process.on(signal, () => {
|
|
130
|
+
releaseInstanceLock()
|
|
131
|
+
// With no other listener the signal should still terminate the process,
|
|
132
|
+
// with the conventional exit code; otherwise the command's own handler
|
|
133
|
+
// (ui/bridge) finishes its cleanup and exits normally.
|
|
134
|
+
if (process.listenerCount(signal) <= 1) process.exit(signal === 'SIGINT' ? 130 : 143)
|
|
135
|
+
})
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/** Take the HOME instance lock once per process (SQLite store mode only). */
|
|
140
|
+
function ensureInstanceLock() {
|
|
141
|
+
if (mode !== 'sqlite') return null
|
|
142
|
+
if (instanceLock?.held) return instanceLock
|
|
143
|
+
installStoreExitHooks()
|
|
144
|
+
instanceLock = acquireInstanceLock({ home: HOME, command: lockCommandLabel() })
|
|
145
|
+
return instanceLock
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/** Human-readable hint for E_DB_LOCKED/E_DB_CORRUPT; null for other errors. */
|
|
149
|
+
function storeFailureHint(error) {
|
|
150
|
+
if (error?.code === 'E_DB_LOCKED') {
|
|
151
|
+
return `advisers: ${error.message}\n` +
|
|
152
|
+
'No changes were made and the JSON store was not used as a fallback. ' +
|
|
153
|
+
'Wait for the other process or stop the long-running server, then retry.'
|
|
154
|
+
}
|
|
155
|
+
if (error?.code === 'E_DB_CORRUPT') {
|
|
156
|
+
return `advisers: ${error.message}\n` +
|
|
157
|
+
`Back up ${DB} before touching it (do not delete it), then run \`advisers doctor\`; ` +
|
|
158
|
+
'the database was not rebuilt and no fallback store was created.'
|
|
159
|
+
}
|
|
160
|
+
return null
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/**
|
|
164
|
+
* P0-1: one shared ICU formatter instead of `new Intl.DateTimeFormat` per
|
|
165
|
+
* commitment. The old today()/tick() code built a fresh formatter for every
|
|
166
|
+
* date comparison (~4 per commitment), so 25k open commitments instantiated
|
|
167
|
+
* ~100k ICU objects: 3.5s and 1.6GB RSS. Intl.DateTimeFormat instances cost
|
|
168
|
+
* ~49µs/~17KB and are not tracked in the V8 heap.
|
|
169
|
+
*/
|
|
170
|
+
const DAY_FORMAT = new Intl.DateTimeFormat('en-CA', { timeZone: 'Asia/Shanghai' })
|
|
171
|
+
/** Asia/Shanghai calendar day (YYYY-MM-DD) for a Date, timestamp or ISO string. */
|
|
172
|
+
const localDayOf = (value) => DAY_FORMAT.format(new Date(value))
|
|
173
|
+
|
|
174
|
+
/**
|
|
175
|
+
* P1-6: default upper bound for `advisers deliver` (open commitments).
|
|
176
|
+
* --all lifts it; the command always reports the untruncated total.
|
|
177
|
+
*/
|
|
178
|
+
const DELIVER_DEFAULT_LIMIT = 500
|
|
179
|
+
|
|
67
180
|
const AUDIT_KEY_FILE = join(HOME, 'audit.key')
|
|
181
|
+
function readAuditKey() {
|
|
182
|
+
const key = readFileSync(AUDIT_KEY_FILE, 'utf8').trim()
|
|
183
|
+
if (key.length < 16) throw new Error(`audit key file is too short (${key.length} chars, expected >= 16): ${AUDIT_KEY_FILE}`)
|
|
184
|
+
return key
|
|
185
|
+
}
|
|
68
186
|
function ensureAuditKey() {
|
|
69
187
|
if (process.env.ADVISERS_AUDIT_KEY) return
|
|
70
188
|
try {
|
|
71
189
|
if (existsSync(AUDIT_KEY_FILE)) {
|
|
72
|
-
|
|
73
|
-
|
|
190
|
+
process.env.ADVISERS_AUDIT_KEY = readAuditKey()
|
|
191
|
+
return
|
|
74
192
|
}
|
|
75
193
|
const key = randomBytes(32).toString('hex')
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
194
|
+
try {
|
|
195
|
+
// P0-4: O_EXCL so two first-run processes agree on exactly one key. The
|
|
196
|
+
// loser must read the winner's key, not overwrite it (that would leave
|
|
197
|
+
// rows signed with a key that no longer exists on disk).
|
|
198
|
+
writeFileSync(AUDIT_KEY_FILE, key, { mode: 0o600, flag: 'wx' })
|
|
199
|
+
process.env.ADVISERS_AUDIT_KEY = key
|
|
200
|
+
} catch (error) {
|
|
201
|
+
if (error?.code !== 'EEXIST') throw error
|
|
202
|
+
process.env.ADVISERS_AUDIT_KEY = readAuditKey()
|
|
203
|
+
}
|
|
204
|
+
} catch (error) {
|
|
205
|
+
console.error(`advisers: audit key unavailable (${error.message})`)
|
|
206
|
+
console.error(` expected a readable ${AUDIT_KEY_FILE} with at least 16 characters.`)
|
|
207
|
+
console.error(' refusing to write an unkeyed audit chain. Restore the key file; if it is lost, move it aside and rerun (the existing chain will then verify as BROKEN).')
|
|
208
|
+
process.exit(1)
|
|
209
|
+
}
|
|
79
210
|
}
|
|
80
211
|
function ensureHome() {
|
|
81
212
|
mkdirSync(HOME, { recursive: true, mode: 0o700 })
|
|
@@ -83,9 +214,22 @@ function ensureHome() {
|
|
|
83
214
|
ensureAuditKey()
|
|
84
215
|
}
|
|
85
216
|
|
|
217
|
+
/**
|
|
218
|
+
* P1-1: core ids are `${prefix}_${Date.now().toString(36)}_${seq}` with a
|
|
219
|
+
* per-process counter, so two CLIs started in the same millisecond can mint the
|
|
220
|
+
* same commitment id and one row would overwrite the other on save. Add a
|
|
221
|
+
* process-unique segment so ids from concurrent commands never collide.
|
|
222
|
+
*/
|
|
223
|
+
const PROCESS_ID = process.pid.toString(36) + randomBytes(2).toString('hex')
|
|
224
|
+
let localIdSeq = 0
|
|
225
|
+
const LOCAL_PORTS = {
|
|
226
|
+
clock: { now: () => new Date().toISOString() },
|
|
227
|
+
ids: { next: (prefix) => `${prefix}_${Date.now().toString(36)}_${PROCESS_ID}_${++localIdSeq}` },
|
|
228
|
+
}
|
|
229
|
+
|
|
86
230
|
function loadJson() {
|
|
87
|
-
if (!existsSync(STATE)) return new Ledger()
|
|
88
|
-
return Ledger.fromJSON(JSON.parse(readFileSync(STATE, 'utf8')))
|
|
231
|
+
if (!existsSync(STATE)) return new Ledger(LOCAL_PORTS)
|
|
232
|
+
return Ledger.fromJSON(JSON.parse(readFileSync(STATE, 'utf8')), LOCAL_PORTS)
|
|
89
233
|
}
|
|
90
234
|
|
|
91
235
|
function saveJson(ledger) {
|
|
@@ -93,10 +237,48 @@ function saveJson(ledger) {
|
|
|
93
237
|
writeFileSync(STATE, JSON.stringify(ledger.toJSON(), null, 2) + '\n')
|
|
94
238
|
}
|
|
95
239
|
|
|
96
|
-
|
|
240
|
+
/** Sealed vault detection: vault bytes exist but the plaintext database does not. */
|
|
241
|
+
function vaultSealedPath() {
|
|
242
|
+
if (mode !== 'sqlite') return null
|
|
243
|
+
const sealed = `${DB}.vault`
|
|
244
|
+
return !existsSync(DB) && existsSync(sealed) ? sealed : null
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
/**
|
|
248
|
+
* Robustness audit P1-1: after `vault seal --remove` every ordinary command used
|
|
249
|
+
* to create a brand-new empty state.db (and doctor/backup reported on the empty
|
|
250
|
+
* database). Fail fast with a stable code instead; the vault commands and
|
|
251
|
+
* `evidence verify` never reach this path.
|
|
252
|
+
*/
|
|
253
|
+
function vaultSealedError(sealed) {
|
|
254
|
+
const error = new Error(
|
|
255
|
+
`E_VAULT_SEALED: the database is sealed at ${sealed}; no plaintext database exists. ` +
|
|
256
|
+
'Run `ADVISERS_VAULT_PASSPHRASE=... advisers vault unseal` (or `advisers vault status`); no empty database was created.',
|
|
257
|
+
)
|
|
258
|
+
error.code = 'E_VAULT_SEALED'
|
|
259
|
+
return error
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
/** Robustness audit P2-1: SQLite creates -wal/-shm with the process umask (often 0644). */
|
|
263
|
+
function secureDbSidecars() {
|
|
264
|
+
for (const file of [DB, `${DB}-wal`, `${DB}-shm`]) {
|
|
265
|
+
try { if (existsSync(file)) chmodSync(file, 0o600) } catch {}
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
function openStore({ checkIntegrity = false } = {}) {
|
|
97
270
|
if (!activeStore) {
|
|
98
|
-
|
|
99
|
-
|
|
271
|
+
const sealed = vaultSealedPath()
|
|
272
|
+
if (sealed) throw vaultSealedError(sealed)
|
|
273
|
+
ensureHome()
|
|
274
|
+
// P0-1: take the single-writer lock before SQLite sees state.db. The sealed
|
|
275
|
+
// check above runs first so a sealed HOME creates neither a database nor a
|
|
276
|
+
// lock file. E_DB_LOCKED / E_DB_CORRUPT propagate to the caller.
|
|
277
|
+
ensureInstanceLock()
|
|
278
|
+
activeStore = new SqliteStore(DB, { checkIntegrity })
|
|
279
|
+
secureDbSidecars()
|
|
280
|
+
} else if (checkIntegrity) {
|
|
281
|
+
activeStore.assertIntegrity()
|
|
100
282
|
}
|
|
101
283
|
return activeStore
|
|
102
284
|
}
|
|
@@ -104,32 +286,91 @@ function openStore() {
|
|
|
104
286
|
function loadLedger() {
|
|
105
287
|
ensureHome()
|
|
106
288
|
if (mode === 'json') return loadJson()
|
|
289
|
+
const sealed = vaultSealedPath()
|
|
290
|
+
if (sealed) throw vaultSealedError(sealed)
|
|
107
291
|
try {
|
|
108
292
|
if (!existsSync(DB) && existsSync(STATE)) {
|
|
109
293
|
const ledger = loadJson()
|
|
110
294
|
openStore().save(ledger.toJSON())
|
|
111
295
|
return ledger
|
|
112
296
|
}
|
|
113
|
-
return Ledger.fromJSON(openStore().load())
|
|
297
|
+
return Ledger.fromJSON(openStore().load(), LOCAL_PORTS)
|
|
114
298
|
} catch (error) {
|
|
299
|
+
const hint = storeFailureHint(error)
|
|
300
|
+
if (hint) {
|
|
301
|
+
console.error(hint)
|
|
302
|
+
process.exit(1)
|
|
303
|
+
}
|
|
115
304
|
console.error(`sqlite unavailable: ${error.message}`)
|
|
116
305
|
console.error('Run `advisers doctor`; refusing to silently switch to JSON (would split the ledger).')
|
|
117
306
|
process.exit(1)
|
|
118
307
|
}
|
|
119
308
|
}
|
|
120
309
|
|
|
310
|
+
function exitStoreWriteFailure(error) {
|
|
311
|
+
// P0-2: never fall back to state.json. The SQLite database is the only ledger
|
|
312
|
+
// once it exists, so a JSON fallback would silently split the book (and the
|
|
313
|
+
// command would still exit 0). Fail loudly instead.
|
|
314
|
+
const hint = storeFailureHint(error)
|
|
315
|
+
if (hint) {
|
|
316
|
+
console.error(hint)
|
|
317
|
+
process.exit(1)
|
|
318
|
+
}
|
|
319
|
+
console.error(`advisers: could not write the ledger to ${DB}: ${error.message}`)
|
|
320
|
+
console.error('Nothing was written to state.json; the SQLite database is the only ledger, so this command did not apply.')
|
|
321
|
+
console.error('Retry the command; if it keeps failing run `advisers doctor` (or `advisers audit --check-db`).')
|
|
322
|
+
process.exit(1)
|
|
323
|
+
}
|
|
324
|
+
|
|
121
325
|
function saveLedger(ledger) {
|
|
122
326
|
ensureHome()
|
|
123
327
|
if (mode === 'json') return saveJson(ledger)
|
|
124
328
|
try {
|
|
125
|
-
openStore().save(ledger.toJSON())
|
|
329
|
+
return openStore().save(ledger.toJSON())
|
|
330
|
+
} catch (error) {
|
|
331
|
+
exitStoreWriteFailure(error)
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
function saveLedgerWithAudit(ledger, audit, inside) {
|
|
336
|
+
ensureHome()
|
|
337
|
+
if (mode === 'json') return saveJson(ledger)
|
|
338
|
+
try {
|
|
339
|
+
return openStore().saveWithAudit(ledger.toJSON(), audit, inside)
|
|
126
340
|
} catch (error) {
|
|
127
|
-
|
|
128
|
-
mode = 'json'
|
|
129
|
-
saveJson(ledger)
|
|
341
|
+
exitStoreWriteFailure(error)
|
|
130
342
|
}
|
|
131
343
|
}
|
|
132
344
|
|
|
345
|
+
function updateStoreWithAudit(fn, audit) {
|
|
346
|
+
ensureHome()
|
|
347
|
+
const store = dbStore()
|
|
348
|
+
if (!store) return
|
|
349
|
+
try {
|
|
350
|
+
return store.transaction(() => {
|
|
351
|
+
fn(store)
|
|
352
|
+
return store.appendAudit(audit)
|
|
353
|
+
})
|
|
354
|
+
} catch (error) {
|
|
355
|
+
exitStoreWriteFailure(error)
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
function recordDeliveryWithAudit({ files, tool, title, validation, audit }) {
|
|
360
|
+
const store = dbStore()
|
|
361
|
+
if (!store) return
|
|
362
|
+
let matterId = 'matter'
|
|
363
|
+
try { matterId = activeMatterId(loadLedger()) } catch {}
|
|
364
|
+
updateStoreWithAudit((s) => s.addDelivery({
|
|
365
|
+
matterId,
|
|
366
|
+
conversationId: latestConversationId(),
|
|
367
|
+
files,
|
|
368
|
+
tool,
|
|
369
|
+
title,
|
|
370
|
+
validation: typeof validation === 'string' ? validation : JSON.stringify(validation),
|
|
371
|
+
}), audit)
|
|
372
|
+
}
|
|
373
|
+
|
|
133
374
|
function loadSoul() {
|
|
134
375
|
if (!existsSync(SOUL)) return undefined
|
|
135
376
|
const meta = existsSync(SOUL_META) ? JSON.parse(readFileSync(SOUL_META, 'utf8')) : {}
|
|
@@ -149,15 +390,51 @@ function saveSoul(doc) {
|
|
|
149
390
|
writeFileSync(SOUL_META, JSON.stringify({ version: doc.version, updatedAt: doc.updatedAt }, null, 2) + '\n', { mode: 0o600 })
|
|
150
391
|
}
|
|
151
392
|
|
|
393
|
+
/** Write bytes to an already-created same-directory temp file and fsync it. */
|
|
394
|
+
function writeDurableTemp(target, bytes, { mode = 0o600 } = {}) {
|
|
395
|
+
const fd = openSync(target, 'wx', mode)
|
|
396
|
+
try {
|
|
397
|
+
writeSync(fd, bytes)
|
|
398
|
+
fsyncSync(fd)
|
|
399
|
+
} finally {
|
|
400
|
+
closeSync(fd)
|
|
401
|
+
}
|
|
402
|
+
return target
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
/** fsync a directory entry so a rename survives a crash. */
|
|
406
|
+
function fsyncDir(path) {
|
|
407
|
+
try {
|
|
408
|
+
const fd = openSync(path, 'r')
|
|
409
|
+
try { fsyncSync(fd) } finally { closeSync(fd) }
|
|
410
|
+
} catch {}
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
/** Atomic write: same-directory temp + fsync + rename + directory fsync. */
|
|
414
|
+
function atomicWriteFileSync(path, bytes, { mode = 0o600 } = {}) {
|
|
415
|
+
mkdirSync(dirname(path), { recursive: true })
|
|
416
|
+
const tmp = join(dirname(path), `.${basename(path)}.tmp-${process.pid}-${randomBytes(4).toString('hex')}`)
|
|
417
|
+
try {
|
|
418
|
+
writeDurableTemp(tmp, bytes, { mode })
|
|
419
|
+
renameSync(tmp, path)
|
|
420
|
+
} catch (error) {
|
|
421
|
+
try { if (existsSync(tmp)) rmSync(tmp) } catch {}
|
|
422
|
+
throw error
|
|
423
|
+
}
|
|
424
|
+
try { chmodSync(path, mode) } catch {}
|
|
425
|
+
fsyncDir(dirname(path))
|
|
426
|
+
return path
|
|
427
|
+
}
|
|
428
|
+
|
|
152
429
|
const soulStore = { load: loadSoul, save: saveSoul }
|
|
153
430
|
|
|
154
431
|
function runtimeFor(ledger) {
|
|
155
432
|
const ports = { ...systemPorts(), soul: soulStore }
|
|
156
|
-
return createAdvisers({ ledger, ports, seen: mode === 'sqlite' ? openStore().seenStore() : undefined, ownerIds: process.env.ADVISERS_OWNER?.split(',').map((x) => x.trim()).filter(Boolean), defaultMatterId: activeMatterId(ledger), policyResolver: StrictPolicyPack ? new StrictPolicyPack() : { resolve: () => ({ allowed: false, action: 'deny', code: 'FAIL_CLOSED', reason: 'policy pack missing' }) } })
|
|
433
|
+
return createAdvisers({ ledger, ports: { ...ports, clock: LOCAL_PORTS.clock, ids: LOCAL_PORTS.ids }, seen: mode === 'sqlite' ? openStore().seenStore() : undefined, ownerIds: process.env.ADVISERS_OWNER?.split(',').map((x) => x.trim()).filter(Boolean), defaultMatterId: activeMatterId(ledger), policyResolver: StrictPolicyPack ? new StrictPolicyPack() : { resolve: () => ({ allowed: false, action: 'deny', code: 'FAIL_CLOSED', reason: 'policy pack missing' }) } })
|
|
157
434
|
}
|
|
158
435
|
|
|
159
436
|
async function backupCliFile(path) {
|
|
160
|
-
try { await backupBeforeWrite(path, { cwd: process.cwd(), backupDir: join(HOME, 'undo') }) } catch {}
|
|
437
|
+
try { const { backupBeforeWrite } = await loadUndo(); await backupBeforeWrite(path, { cwd: process.cwd(), backupDir: join(HOME, 'undo') }) } catch {}
|
|
161
438
|
}
|
|
162
439
|
|
|
163
440
|
function now() {
|
|
@@ -268,9 +545,28 @@ function friendlyError(error) {
|
|
|
268
545
|
if (/database is locked/.test(message)) return 'database is busy; close other advisers processes and retry'
|
|
269
546
|
return message
|
|
270
547
|
}
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
548
|
+
function reportFatalError(error) {
|
|
549
|
+
// E_DB_LOCKED / E_DB_CORRUPT get backup/doctor/concurrency guidance instead of
|
|
550
|
+
// the generic one-line message (commands that touch the store without going
|
|
551
|
+
// through loadLedger() end up here).
|
|
552
|
+
console.error(storeFailureHint(error) ?? `advisers: ${friendlyError(error)}`)
|
|
553
|
+
process.exit(1)
|
|
554
|
+
}
|
|
555
|
+
process.on('uncaughtException', reportFatalError)
|
|
556
|
+
process.on('unhandledRejection', reportFatalError)
|
|
557
|
+
/**
|
|
558
|
+
* TOS gate: `--accept-tos[=<version>]` is a global pre-dispatch flag, so it is
|
|
559
|
+
* stripped from argv before the command is parsed (it may appear before or after
|
|
560
|
+
* the command name). The value is resolved by lib/tos when the gate runs.
|
|
561
|
+
*/
|
|
562
|
+
const rawArgv = process.argv.slice(2)
|
|
563
|
+
let acceptTosFlag
|
|
564
|
+
for (let index = rawArgv.length - 1; index >= 0; index--) {
|
|
565
|
+
const value = rawArgv[index]
|
|
566
|
+
if (value === '--accept-tos') { acceptTosFlag = true; rawArgv.splice(index, 1) }
|
|
567
|
+
else if (value.startsWith('--accept-tos=')) { acceptTosFlag = value.slice('--accept-tos='.length); rawArgv.splice(index, 1) }
|
|
568
|
+
}
|
|
569
|
+
const [command, ...args] = rawArgv
|
|
274
570
|
|
|
275
571
|
function help() {
|
|
276
572
|
console.log(`advisers — a staff of AI advisers
|
|
@@ -285,12 +581,16 @@ Usage:
|
|
|
285
581
|
advisers history recent conversations
|
|
286
582
|
advisers search <text> full-text search old turns
|
|
287
583
|
advisers compact ls|rollback summary versions
|
|
288
|
-
advisers today [--calendar]
|
|
289
|
-
|
|
290
|
-
advisers remind
|
|
584
|
+
advisers today [--calendar] [--sources] [--json]
|
|
585
|
+
one-screen today/week/waiting view (+ local events)
|
|
586
|
+
advisers remind [--json] [--ics [path]] [--deliver [--notify]] due reminders + ICS/VALARM export
|
|
587
|
+
advisers remind install|uninstall|status [--apply] [--schedule "0 9 * * *"]
|
|
588
|
+
scheduler scripts + OS plan (dry-run by default; --apply executes)
|
|
589
|
+
status also shows the last recorded run (scheduler/status.json)
|
|
291
590
|
advisers calendar import --ics <file> local .ics read-only import
|
|
292
591
|
advisers risks up to 3 deterministic obligation risks
|
|
293
|
-
advisers pet-brief [--json] [--out [path]] [--check]
|
|
592
|
+
advisers pet-brief [--json] [--out [path]] [--check [--strict]] [--display-policy public|private|none]
|
|
593
|
+
read-only redacted Pet Brief (contract v0.2); --print-schema prints the JSON Schema
|
|
294
594
|
advisers tick due commitments in the next 7 days
|
|
295
595
|
advisers week last 7 days
|
|
296
596
|
advisers digest day|week short digest
|
|
@@ -300,14 +600,17 @@ Usage:
|
|
|
300
600
|
advisers learn review <id> LLM routine review (needs API key)
|
|
301
601
|
advisers memory what I remember
|
|
302
602
|
advisers memory search <q> search facts/preferences
|
|
303
|
-
advisers memory candidates pending memory candidates
|
|
603
|
+
advisers memory candidates [--json] [--all] pending memory candidates
|
|
304
604
|
advisers memory accept|reject <id>
|
|
305
605
|
advisers prefs [--all] | correct <text>
|
|
306
606
|
advisers nudge list|done|ignore <id> nudge outcomes
|
|
307
607
|
advisers decay apply 30-day preference decay
|
|
308
608
|
advisers audit verify the local audit hash chain
|
|
309
609
|
advisers purge <matter> [--yes] privacy delete a matter
|
|
310
|
-
advisers commit add|ls|done|snooze commitments
|
|
610
|
+
advisers commit add|edit|ls|done|snooze commitments
|
|
611
|
+
advisers commit add "..." --quote "..." [--remind-offsets "-1d,-2h"]
|
|
612
|
+
advisers commit edit <id> [--remind-offsets "<list>" | --no-remind]
|
|
613
|
+
per-commitment reminder offsets (Asia/Shanghai wall clock)
|
|
311
614
|
advisers deliveries recent generated files
|
|
312
615
|
advisers receipt one-screen delivery receipt
|
|
313
616
|
advisers ls list matters
|
|
@@ -325,23 +628,26 @@ Usage:
|
|
|
325
628
|
advisers review <file> --request "..." model content review (no edits)
|
|
326
629
|
advisers research --web|--url <url> [--deep] <query>
|
|
327
630
|
server-side web search/read URL with citations (explicit egress)
|
|
328
|
-
advisers capture [--file f] [--source s] [--date ISO] [--matter id] <text>
|
|
631
|
+
advisers capture [--file f] [--source s] [--date ISO] [--matter id] [--json] <text>
|
|
329
632
|
从中文工作内容抽取候选承诺(不自动入账)
|
|
330
633
|
advisers capture --from-mail <file|dir> [--limit n] .eml/.mbox 只读导入→候选
|
|
331
634
|
advisers capture --from-transcript <file> 转写稿导入→候选(不录音/不入会)
|
|
332
635
|
advisers capture --from-imap 只读 IMAP 导入(EXAMINE/FETCH;env 凭据)
|
|
333
636
|
advisers ui [--port n] 本地只读视图(127.0.0.1,GET only)
|
|
334
|
-
advisers mcp --stdio
|
|
637
|
+
advisers mcp --stdio MCP server(7 工具 + 4 resources;写入口仅 pending 候选/回执校验)
|
|
335
638
|
advisers evidence show <id> [--json] 承诺/事实/偏好→原文来源
|
|
336
639
|
advisers deliver [--commit id] [--type confirmation|weekly|statement|ledger] [--format docx|xlsx|pdf] [--out f] 交付物
|
|
337
|
-
advisers deliveries --pack [--out dir]
|
|
640
|
+
advisers deliveries --pack [--out dir] [--ids ...] [--all] 证据包(manifest/README/SHA256SUMS + DOCX 回执;默认上限 2000)
|
|
641
|
+
advisers deliveries --receipt [--out dir] [--ids ...] [--all] [--recipient "Name <mail>"]
|
|
642
|
+
交付回执包 v1.1(交付文件副本 + 全文件 SHA-256 + 证据;默认上限 2000)
|
|
643
|
+
advisers evidence verify <dir> 离线校验回执包(JSON,exit 0/1;不读账本、不联网)
|
|
338
644
|
advisers policy check <text> policy/crisis check
|
|
339
645
|
advisers office-read <file> read DOCX/XLSX/PPTX/OFD text
|
|
340
646
|
advisers ocr <image> [--out text] local OCR adapter (ADVISERS_OCR_CMD; no cloud)
|
|
341
647
|
advisers timestamp <file> [--out proof] local timestamp/signing adapter
|
|
342
648
|
advisers tui [--once] read-only terminal dashboard
|
|
343
649
|
advisers office-edit <file> <ops.json> [out] surgical Office edit
|
|
344
|
-
advisers verify <file> [--content] structural + deterministic content checks
|
|
650
|
+
advisers verify <file> [--json] [--content] structural + deterministic content checks
|
|
345
651
|
advisers office <kind> <spec.json> <out>
|
|
346
652
|
build docx/xlsx/pptx/xmind/mermaid/drawio
|
|
347
653
|
advisers routine ls list routines
|
|
@@ -376,6 +682,7 @@ Usage:
|
|
|
376
682
|
advisers soul show print soul.md
|
|
377
683
|
advisers soul set <file> set soul.md from a file (human action)
|
|
378
684
|
advisers soul init write a minimal starter soul.md
|
|
685
|
+
advisers tos show|status [--json]|accept|revoke 使用条款:全文/状态/接受/撤回
|
|
379
686
|
advisers help
|
|
380
687
|
|
|
381
688
|
Environment:
|
|
@@ -386,6 +693,34 @@ Environment:
|
|
|
386
693
|
ADVISERS_YES=1 skip the plan confirmation
|
|
387
694
|
ADVISERS_FORCE=1 overwrite existing files without asking
|
|
388
695
|
ADVISERS_PROGRESS=0 hide [tool] progress lines
|
|
696
|
+
ADVISERS_ACCEPT_TOS=1 record TOS consent without a TTY (same as --accept-tos)
|
|
697
|
+
ADVISERS_NOTIFY_WEBHOOK optional outbound webhook for remind --deliver --notify
|
|
698
|
+
ADVISERS_LOCK_TIMEOUT_MS wait for another advisers process to release the
|
|
699
|
+
instance lock (milliseconds; default 10000, 0 = fail immediately)
|
|
700
|
+
|
|
701
|
+
Concurrency:
|
|
702
|
+
One advisers process per ADVISERS_HOME uses the SQLite ledger at a time. The
|
|
703
|
+
CLI takes ~/.advisers/instance.lock before opening state.db; a second process
|
|
704
|
+
waits up to ADVISERS_LOCK_TIMEOUT_MS and then exits with E_DB_LOCKED instead
|
|
705
|
+
of writing from a stale ledger snapshot. ui / mcp / bridge keep the lock while
|
|
706
|
+
they run, so stop them before running other commands (or raise the timeout).
|
|
707
|
+
A stale lock (dead pid, or not refreshed for 1h) is reclaimed; SIGINT/SIGTERM
|
|
708
|
+
and normal exit release the lock. Concurrent commands therefore either run one
|
|
709
|
+
after another or fail explicitly — they never silently overwrite each other.
|
|
710
|
+
|
|
711
|
+
Exit codes:
|
|
712
|
+
0 success
|
|
713
|
+
1 user/config/runtime error (bad args, missing key, unknown id, failed
|
|
714
|
+
verification, E_DB_LOCKED when another process holds the instance lock,
|
|
715
|
+
E_DB_CORRUPT when state.db is 0 bytes/corrupt: back it up and run
|
|
716
|
+
\`advisers doctor\`; damaged databases are never silently rebuilt)
|
|
717
|
+
3 TOS consent required: non-interactive command blocked by the consent gate.
|
|
718
|
+
Run \`advisers tos accept\` in a TTY, or pass --accept-tos / ADVISERS_ACCEPT_TOS=1.
|
|
719
|
+
\`advisers evidence verify <dir>\` is offline/read-only and exempt from the gate.
|
|
720
|
+
Data-rights commands (audit/export/privacy/purge) and \`tos\` are exempt too.
|
|
721
|
+
|
|
722
|
+
Requirements:
|
|
723
|
+
Node >= 22.16 (node:sqlite). Node 22 prints an ExperimentalWarning for SQLite; Node 24 does not.
|
|
389
724
|
`)
|
|
390
725
|
}
|
|
391
726
|
|
|
@@ -433,15 +768,14 @@ function purgeMatter(id, confirmed) {
|
|
|
433
768
|
}
|
|
434
769
|
const counts = ledger.purgeMatter(id)
|
|
435
770
|
const sqlite = dbStore()?.purgeMatterData(id)
|
|
436
|
-
|
|
437
|
-
saveLedger(ledger)
|
|
771
|
+
saveLedgerWithAudit(ledger, { actor: 'local', action: 'matter.purge', allowed: true, reason: `${id} ${JSON.stringify(counts)}` })
|
|
438
772
|
console.log(`purged: ${JSON.stringify(counts)} sqlite=${JSON.stringify(sqlite ?? {})}`)
|
|
439
773
|
}
|
|
440
774
|
|
|
441
775
|
function parseFlags(args) {
|
|
442
776
|
const flags = {}
|
|
443
777
|
const positional = []
|
|
444
|
-
const booleanFlags = new Set(['web', 'deep', 'all', 'yes', 'json', 'list', 'force', 'apply', 'quiet', 'help', 'content', 'ics', 'deliver', 'install', 'uninstall', 'status', 'calendar', 'pack', 'from-imap', 'remove', 'force', 'notify'])
|
|
778
|
+
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'])
|
|
445
779
|
for (let i = 0; i < args.length; i++) {
|
|
446
780
|
if (args[i].startsWith('--')) {
|
|
447
781
|
const key = args[i].slice(2)
|
|
@@ -452,6 +786,20 @@ function parseFlags(args) {
|
|
|
452
786
|
return { flags, positional }
|
|
453
787
|
}
|
|
454
788
|
|
|
789
|
+
/**
|
|
790
|
+
* Read --remind / --remind-offsets from parsed flags and strictly normalise.
|
|
791
|
+
* `--remind -1d` is a one-offset alias of `--remind-offsets "-1d,-2h"`.
|
|
792
|
+
* Returns undefined when neither flag was given; invalid input throws.
|
|
793
|
+
*/
|
|
794
|
+
async function parseReminderOffsetsFlag(flags) {
|
|
795
|
+
const raw = flags['remind-offsets'] !== undefined ? flags['remind-offsets'] : flags.remind
|
|
796
|
+
if (raw === undefined) return undefined
|
|
797
|
+
if (raw === true) throw new Error('--remind-offsets requires a value, e.g. --remind-offsets "-1d,-2h" or --remind -1d')
|
|
798
|
+
const list = String(raw).split(',').map((item) => item.trim()).filter(Boolean)
|
|
799
|
+
const { normalizeReminderOffsets } = await loadRemind()
|
|
800
|
+
return normalizeReminderOffsets(list)
|
|
801
|
+
}
|
|
802
|
+
|
|
455
803
|
function recordManualDelivery(files, tool, title, validation) {
|
|
456
804
|
try {
|
|
457
805
|
const store = dbStore()
|
|
@@ -534,83 +882,193 @@ function risks(ledger) {
|
|
|
534
882
|
for (const line of out.slice(0, 3)) console.log(`- ${line}`)
|
|
535
883
|
}
|
|
536
884
|
|
|
537
|
-
|
|
538
|
-
|
|
885
|
+
/**
|
|
886
|
+
* Read-side provenance compatibility (source v2): stored v1 source rows are
|
|
887
|
+
* normalised before display so mail/transcript/IMAP provenance renders the same
|
|
888
|
+
* way regardless of when the row was written. Read-only: normalizeSource() is
|
|
889
|
+
* pure and never touches the database.
|
|
890
|
+
*/
|
|
891
|
+
async function collectSourceRows(ledger) {
|
|
892
|
+
const { normalizeSource } = await loadSource()
|
|
539
893
|
const rows = []
|
|
540
|
-
for (const c of
|
|
894
|
+
for (const c of ledger.listCommitments()) {
|
|
541
895
|
for (const e of c.evidence ?? []) {
|
|
542
|
-
const
|
|
543
|
-
|
|
896
|
+
const source = normalizeSource(e.source)
|
|
897
|
+
const type = source?.type ?? 'conversation'
|
|
898
|
+
rows.push({
|
|
899
|
+
commitmentId: c.id,
|
|
900
|
+
action: c.action,
|
|
901
|
+
type,
|
|
902
|
+
ref: source?.ref ?? (e.sessionId ? `${e.sessionId}#${e.turnId}` : (e.turnId ?? null)),
|
|
903
|
+
label: `${type}${source?.subject ? `:${source.subject}` : source?.messageId ? `:${source.messageId}` : source?.file ? `:${source.file}` : ''}`,
|
|
904
|
+
quote: e.quote ?? '',
|
|
905
|
+
source: source ?? null,
|
|
906
|
+
})
|
|
544
907
|
}
|
|
545
908
|
}
|
|
909
|
+
return rows
|
|
910
|
+
}
|
|
911
|
+
|
|
912
|
+
async function printSources(ledger) {
|
|
913
|
+
const rows = await collectSourceRows(ledger)
|
|
546
914
|
if (!rows.length) { console.log('来源:还没有可回溯的承诺来源;先 capture/导入并 accept。'); return }
|
|
547
915
|
console.log('来源(承诺 → 本地入口):')
|
|
548
|
-
for (const r of rows.slice(0, 20)) console.log(` ${r.
|
|
916
|
+
for (const r of rows.slice(0, 20)) console.log(` ${r.commitmentId} ${r.action} ← ${r.label} (${r.ref ?? '-'}) 「${r.quote.slice(0, 80)}」`)
|
|
549
917
|
}
|
|
550
918
|
|
|
551
|
-
function today(ledger, { calendar = false, sources = false, json = false } = {}) {
|
|
552
|
-
const
|
|
553
|
-
const localDay =
|
|
554
|
-
const
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
const
|
|
558
|
-
const
|
|
559
|
-
const
|
|
560
|
-
const
|
|
919
|
+
async function today(ledger, { calendar = false, sources = false, json = false } = {}) {
|
|
920
|
+
const nowMs = Date.now()
|
|
921
|
+
const localDay = localDayOf(nowMs)
|
|
922
|
+
const weekAhead = nowMs + 7 * 86400_000
|
|
923
|
+
// P0-1: classify in one pass, formatting each due date at most once (the old
|
|
924
|
+
// four filters called day() up to four times per commitment).
|
|
925
|
+
const overdue = []
|
|
926
|
+
const todayDue = []
|
|
927
|
+
const week = []
|
|
928
|
+
const waiting = []
|
|
929
|
+
const noDue = []
|
|
930
|
+
for (const c of ledger.openCommitments()) {
|
|
931
|
+
if (c.debtor === 'third' || c.debtor.startsWith('third:')) waiting.push(c)
|
|
932
|
+
if (!c.dueAt) { noDue.push(c); continue }
|
|
933
|
+
const due = Date.parse(c.dueAt)
|
|
934
|
+
if (due < nowMs) {
|
|
935
|
+
if (localDayOf(c.dueAt) !== localDay) overdue.push(c)
|
|
936
|
+
else todayDue.push(c)
|
|
937
|
+
} else if (localDayOf(c.dueAt) === localDay) {
|
|
938
|
+
todayDue.push(c)
|
|
939
|
+
} else if (due <= weekAhead) {
|
|
940
|
+
week.push(c)
|
|
941
|
+
}
|
|
942
|
+
}
|
|
943
|
+
const next = [...overdue, ...todayDue, ...week].sort((a, b) => Date.parse(a.dueAt) - Date.parse(b.dueAt))[0]
|
|
944
|
+
if (json) {
|
|
945
|
+
// JSON contract v1 (docs/CLI-JSON.md): same classification as the human view.
|
|
946
|
+
const payload = {
|
|
947
|
+
now: new Date(nowMs).toISOString(),
|
|
948
|
+
localDay,
|
|
949
|
+
counts: { today: todayDue.length, overdue: overdue.length, week: week.length, waiting: waiting.length, noDue: noDue.length },
|
|
950
|
+
overdue,
|
|
951
|
+
today: todayDue,
|
|
952
|
+
week,
|
|
953
|
+
waiting,
|
|
954
|
+
noDue,
|
|
955
|
+
next: next ? { id: next.id, action: next.action, dueAt: next.dueAt } : null,
|
|
956
|
+
}
|
|
957
|
+
if (calendar) payload.calendar = (await calendarOccurrencesToday()).occurrences
|
|
958
|
+
if (sources) {
|
|
959
|
+
payload.sources = (await collectSourceRows(ledger)).map(({ commitmentId, action, type, ref, quote }) => ({ commitmentId, action, type, ref, quote }))
|
|
960
|
+
}
|
|
961
|
+
console.log(JSON.stringify(payload, null, 2))
|
|
962
|
+
return
|
|
963
|
+
}
|
|
561
964
|
console.log(`今天:${todayDue.length} · 逾期:${overdue.length} · 未来 7 天:${week.length} · 等别人:${waiting.length} · 无截止:${noDue.length}`)
|
|
562
965
|
for (const [label, list] of [['逾期', overdue], ['今天', todayDue], ['未来 7 天', week], ['等别人', waiting]]) {
|
|
563
966
|
if (!list.length) continue
|
|
564
967
|
console.log(`${label}:`)
|
|
565
968
|
for (const c of list.slice(0, 5)) console.log(` ${c.id} ${c.creditor} · ${c.action}${c.dueAt ? ` · ${c.dueAt.slice(0, 10)}` : ''}`)
|
|
566
969
|
}
|
|
567
|
-
console.log('下一件:' + (
|
|
568
|
-
if (calendar) printCalendarToday()
|
|
569
|
-
if (sources) printSources(ledger)
|
|
970
|
+
console.log('下一件:' + (next?.action ?? '先定一个承诺或交付。'))
|
|
971
|
+
if (calendar) await printCalendarToday()
|
|
972
|
+
if (sources) await printSources(ledger)
|
|
570
973
|
}
|
|
571
974
|
|
|
572
975
|
function tick(ledger, asJson = false) {
|
|
573
976
|
const now = Date.now()
|
|
574
977
|
const store = dbStore()
|
|
575
|
-
const localDay =
|
|
978
|
+
const localDay = localDayOf(now)
|
|
979
|
+
const weekAhead = now + 7 * 86400_000
|
|
576
980
|
const due = []
|
|
981
|
+
const candidates = []
|
|
982
|
+
const snoozeKeys = []
|
|
983
|
+
let statusChanged = false
|
|
984
|
+
// P0-2: one meta query for every snooze deadline instead of getMeta() per
|
|
985
|
+
// snoozed commitment.
|
|
986
|
+
const snoozeUntil = store ? store.listMetaByPrefix('snooze:') : new Map()
|
|
577
987
|
for (const c of ledger.listCommitments()) {
|
|
578
988
|
if (c.status === 'done' || c.status === 'dropped') continue
|
|
579
989
|
if (c.status === 'snoozed') {
|
|
580
|
-
const until =
|
|
990
|
+
const until = snoozeUntil.get(`snooze:${c.id}`)
|
|
581
991
|
if (until && Date.parse(until) > now) continue
|
|
582
992
|
c.status = 'open'
|
|
583
|
-
|
|
993
|
+
statusChanged = true
|
|
994
|
+
snoozeKeys.push(`snooze:${c.id}`)
|
|
584
995
|
}
|
|
585
|
-
if (!c.dueAt || Date.parse(c.dueAt) >
|
|
586
|
-
|
|
996
|
+
if (!c.dueAt || Date.parse(c.dueAt) > weekAhead) continue
|
|
997
|
+
candidates.push(c)
|
|
998
|
+
}
|
|
999
|
+
// P2-2 (0.2.1): the recent-outcome read is bounded by the candidate set.
|
|
1000
|
+
// Only candidates whose pre-outcome level is L2/L3 can be downgraded by an
|
|
1001
|
+
// ignored run (the `level !== 'L1'` guard below), so those are the only ids
|
|
1002
|
+
// the query needs; the history table is never scanned as a whole.
|
|
1003
|
+
const baseLevelById = new Map()
|
|
1004
|
+
const outcomeIds = []
|
|
1005
|
+
for (const c of candidates) {
|
|
1006
|
+
const dueDay = localDayOf(c.dueAt)
|
|
587
1007
|
const msLeft = Date.parse(c.dueAt) - now
|
|
588
|
-
let
|
|
589
|
-
if (
|
|
590
|
-
|
|
591
|
-
if (
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
1008
|
+
let baseLevel = (msLeft < 0 || dueDay === localDay) ? 'L2' : 'L1'
|
|
1009
|
+
if (baseLevel === 'L2' && Date.parse(c.dueAt) < now - 86400_000 && process.env.ADVISERS_ALLOW_L3 === '1') baseLevel = 'L3'
|
|
1010
|
+
baseLevelById.set(c.id, baseLevel)
|
|
1011
|
+
if (baseLevel !== 'L1') outcomeIds.push(c.id)
|
|
1012
|
+
}
|
|
1013
|
+
// P0-2: replace the per-commitment N+1 queries (listCommitmentNudges +
|
|
1014
|
+
// countNudges) with three batch reads: recent outcomes per commitment,
|
|
1015
|
+
// today's level counts and today's existing (commitment, level) keys.
|
|
1016
|
+
const recentByCommitment = store && outcomeIds.length ? store.recentNudgeOutcomes(3, outcomeIds) : new Map()
|
|
1017
|
+
const levelCounts = store && candidates.length ? store.countNudgesByDay(localDay) : new Map()
|
|
1018
|
+
const existingKeys = store && candidates.length ? store.listNudgeLevelKeysByDay(localDay) : new Set()
|
|
1019
|
+
const pendingKeys = new Set()
|
|
1020
|
+
let l3Today = levelCounts.get('L3') ?? 0
|
|
1021
|
+
let l2Today = levelCounts.get('L2') ?? 0
|
|
1022
|
+
const nudgeRows = []
|
|
1023
|
+
for (const c of candidates) {
|
|
1024
|
+
let level = baseLevelById.get(c.id)
|
|
1025
|
+
const recent = recentByCommitment.get(c.id) ?? []
|
|
1026
|
+
if (recent.length === 3 && recent.every((outcome) => outcome === 'ignored') && level !== 'L1') level = level === 'L3' ? 'L2' : 'L1'
|
|
1027
|
+
// Budgets keep the historical in-run semantics: a nudge already written by
|
|
1028
|
+
// this tick counts toward the caps of the commitments that follow it, but a
|
|
1029
|
+
// deduped (already present) key does not.
|
|
1030
|
+
if (level === 'L3' && l3Today >= 1) level = 'L2'
|
|
1031
|
+
if (level === 'L2' && l2Today >= 3) level = 'L1'
|
|
1032
|
+
const key = `${c.id}\u0000${level}`
|
|
1033
|
+
if (!existingKeys.has(key) && !pendingKeys.has(key)) {
|
|
1034
|
+
if (level === 'L3') l3Today++
|
|
1035
|
+
else if (level === 'L2') l2Today++
|
|
1036
|
+
pendingKeys.add(key)
|
|
1037
|
+
}
|
|
1038
|
+
nudgeRows.push({ localDay, level, commitmentId: c.id, body: c.action })
|
|
595
1039
|
due.push({ ...c, level })
|
|
596
1040
|
}
|
|
597
|
-
|
|
1041
|
+
// P0-2: one transaction for all nudge inserts and one for snooze cleanup;
|
|
1042
|
+
// the ledger snapshot is only rewritten when a snooze actually woke up.
|
|
1043
|
+
if (store && nudgeRows.length) store.addNudges(nudgeRows)
|
|
1044
|
+
if (store && snoozeKeys.length) store.deleteMetaKeys(snoozeKeys)
|
|
1045
|
+
if (statusChanged) saveLedger(ledger)
|
|
598
1046
|
if (asJson) {
|
|
599
1047
|
console.log(JSON.stringify({ now: new Date(now).toISOString(), localDay, due }, null, 2))
|
|
600
1048
|
return
|
|
601
1049
|
}
|
|
602
1050
|
if (!due.length) { console.log('未来 7 天无到期。'); return }
|
|
603
1051
|
for (const c of due) {
|
|
604
|
-
const dueDay =
|
|
1052
|
+
const dueDay = localDayOf(c.dueAt)
|
|
605
1053
|
const label = Date.parse(c.dueAt) < now ? '逾期' : dueDay === localDay ? '今天到期' : '即将到期'
|
|
606
1054
|
console.log(`[${c.level}] ${label}:${c.action}(${c.dueAt})`)
|
|
607
1055
|
}
|
|
608
1056
|
}
|
|
609
1057
|
|
|
610
|
-
function printAudit() {
|
|
1058
|
+
function printAudit(args = []) {
|
|
611
1059
|
ensureHome()
|
|
612
1060
|
const store = dbStore()
|
|
613
1061
|
if (!store) { console.log('audit requires SQLite store'); return }
|
|
1062
|
+
if (args.includes('--check-db')) {
|
|
1063
|
+
try {
|
|
1064
|
+
store.assertIntegrity()
|
|
1065
|
+
console.log('integrity: ok')
|
|
1066
|
+
} catch (error) {
|
|
1067
|
+
console.error(`integrity: FAIL (${error.message})`)
|
|
1068
|
+
process.exitCode = 1
|
|
1069
|
+
return
|
|
1070
|
+
}
|
|
1071
|
+
}
|
|
614
1072
|
const verify = store.verifyAudit()
|
|
615
1073
|
console.log(`audit: ${verify.ok ? 'verified' : `BROKEN at seq ${verify.seq}`} (${verify.count ?? 0} entries)`)
|
|
616
1074
|
if (!verify.ok) process.exitCode = 1
|
|
@@ -626,25 +1084,39 @@ function printPrivacy(args = []) {
|
|
|
626
1084
|
const store = dbStore()
|
|
627
1085
|
let audit = null
|
|
628
1086
|
try { const v = store?.verifyAudit(); if (v) audit = { ok: v.ok, count: v.count ?? 0 } } catch {}
|
|
1087
|
+
// Privacy audit P2-2: list every actual egress surface from the code base
|
|
1088
|
+
// instead of two hardcoded names, and never expose internal numbering.
|
|
1089
|
+
const egressSurfaces = [
|
|
1090
|
+
'model provider — chat / brief --deep / review / learn review (only when ADVISERS_API_KEY is set; ADVISERS_BASE_URL)',
|
|
1091
|
+
'research --web|--url — provider web search/read tool (explicit opt-in; no silent research egress)',
|
|
1092
|
+
'capture --from-imap — read-only IMAP fetch from the server you configure (TLS by default)',
|
|
1093
|
+
'remind --deliver --notify — optional outbound webhook or local notifier you configure',
|
|
1094
|
+
'sync push|pull — the directory you provide; snapshots are AES-256-GCM encrypted before writing',
|
|
1095
|
+
'bridge — Hermes file gateway: inbox/outbox JSON files are handed to the Hermes process',
|
|
1096
|
+
'MCP --stdio / DSH host tools / pet-brief — local consumers; the host or reader may forward the data',
|
|
1097
|
+
'ocr / timestamp — local adapter subprocess you configure (this CLI does not call a cloud OCR/TSA)',
|
|
1098
|
+
]
|
|
629
1099
|
const facts = {
|
|
630
1100
|
home: HOME,
|
|
631
1101
|
database: DB,
|
|
632
1102
|
telemetry: 'none',
|
|
633
1103
|
default_egress: 'none',
|
|
634
|
-
explicit_egress:
|
|
635
|
-
provider: { baseUrl: process.env.ADVISERS_BASE_URL ?? 'https://api.deepseek.com', model: process.env.ADVISERS_MODEL ?? 'deepseek-
|
|
636
|
-
secret_matter: 'egress fail-closed
|
|
637
|
-
at_rest_encryption: '
|
|
1104
|
+
explicit_egress: egressSurfaces,
|
|
1105
|
+
provider: { baseUrl: process.env.ADVISERS_BASE_URL ?? 'https://api.deepseek.com', model: process.env.ADVISERS_MODEL ?? 'deepseek-flash' },
|
|
1106
|
+
secret_matter: 'egress fail-closed for secrecy > 0 on the wired model paths (local rule layer)',
|
|
1107
|
+
at_rest_encryption: 'opt-in database vault (advisers vault seal); general data is not encrypted at rest',
|
|
638
1108
|
audit,
|
|
639
1109
|
export: 'advisers export --all',
|
|
640
1110
|
delete: 'advisers purge <matter> --yes',
|
|
641
1111
|
}
|
|
642
1112
|
if (asJson) { console.log(JSON.stringify(facts, null, 2)); return }
|
|
643
1113
|
console.log('privacy · local data facts')
|
|
1114
|
+
console.log('self-attestation(本地自检口径:只读本机文件/环境与纯函数,不是第三方审计;本命令不联网)')
|
|
644
1115
|
console.log(`home: ${facts.home}`)
|
|
645
1116
|
console.log(`database: ${facts.database}`)
|
|
646
|
-
console.log(`telemetry: ${facts.telemetry}`)
|
|
647
|
-
console.log(`egress: ${facts.default_egress} by default
|
|
1117
|
+
console.log(`telemetry: ${facts.telemetry} (build-time statement; this package contains no telemetry code)`)
|
|
1118
|
+
console.log(`egress: ${facts.default_egress} by default — nothing leaves the machine until you configure/opt in to:`)
|
|
1119
|
+
for (const surface of egressSurfaces) console.log(` - ${surface}`)
|
|
648
1120
|
console.log(`provider: ${facts.provider.model} @ ${facts.provider.baseUrl}`)
|
|
649
1121
|
console.log(`secret: ${facts.secret_matter}`)
|
|
650
1122
|
console.log(`encryption: ${facts.at_rest_encryption}`)
|
|
@@ -653,15 +1125,18 @@ function printPrivacy(args = []) {
|
|
|
653
1125
|
console.log(`delete: ${facts.delete}`)
|
|
654
1126
|
if (prove) {
|
|
655
1127
|
const checks = [
|
|
656
|
-
['home exists', existsSync(HOME)],
|
|
657
|
-
['database exists', existsSync(DB)],
|
|
658
|
-
['audit verified', Boolean(audit?.ok)],
|
|
659
|
-
['telemetry disabled',
|
|
660
|
-
['network
|
|
661
|
-
['secret matter fail-closed',
|
|
1128
|
+
['home exists', existsSync(HOME), 'local self-check'],
|
|
1129
|
+
['database exists', existsSync(DB), 'local self-check'],
|
|
1130
|
+
['audit verified', Boolean(audit?.ok), 'local self-check: keyed hash chain'],
|
|
1131
|
+
['telemetry disabled', facts.telemetry === 'none', 'local self-check: build-time statement, not network-verified'],
|
|
1132
|
+
['no default network egress', facts.default_egress === 'none', 'local self-check: build-time statement, not network-verified'],
|
|
1133
|
+
['secret matter fail-closed', (() => { try { return Boolean(egressDeniedReason({ secrecy: 1 }, 'prove')) && !egressDeniedReason({ secrecy: 0 }, 'prove') } catch { return false } })(), 'local self-check: egress-gate function; per-path wiring is covered by tests'],
|
|
662
1134
|
]
|
|
1135
|
+
console.log('')
|
|
1136
|
+
console.log('self-checks(本地自检:结果只说明本机文件/配置与纯函数检查;不是第三方审计,也不证明运行时无出网)')
|
|
663
1137
|
let failed = 0
|
|
664
|
-
for (const [name, ok] of checks) { if (!ok) failed++; console.log(`[${ok ? 'PASS' : 'FAIL'}] ${name}`) }
|
|
1138
|
+
for (const [name, ok, detail] of checks) { if (!ok) failed++; console.log(`[${ok ? 'PASS' : 'FAIL'}] ${name} (${detail})`) }
|
|
1139
|
+
console.log('egress gate coverage: chat/model, review, research, brief --deep, learn review, bridge and capture are wired to the local secrecy gate; the other surfaces listed above are self-attested.')
|
|
665
1140
|
if (failed) process.exitCode = 1
|
|
666
1141
|
}
|
|
667
1142
|
}
|
|
@@ -677,32 +1152,165 @@ function printLinks() {
|
|
|
677
1152
|
}
|
|
678
1153
|
|
|
679
1154
|
/**
|
|
680
|
-
*
|
|
1155
|
+
* JSON Schema (draft 2020-12) for the Pet Brief contract v0.2, generated from
|
|
1156
|
+
* the exported lib constants so `--print-schema` also works from the published
|
|
1157
|
+
* package (docs/pet-brief/schema-v0.2.json is not in the npm `files`
|
|
1158
|
+
* allowlist). The test suite asserts the generated document is deep-equal to
|
|
1159
|
+
* the canonical snapshot in docs/pet-brief/schema-v0.2.json.
|
|
1160
|
+
*/
|
|
1161
|
+
async function petBriefJsonSchema() {
|
|
1162
|
+
const {
|
|
1163
|
+
PET_BRIEF_DEFAULT_DISPLAY_POLICY, PET_BRIEF_DISPLAY_POLICIES, PET_BRIEF_MAX_ITEMS,
|
|
1164
|
+
PET_BRIEF_MAX_LINE_LENGTH, PET_BRIEF_MAX_SUGGESTED_LINES, PET_BRIEF_MOODS,
|
|
1165
|
+
PET_BRIEF_SCHEMA_VERSION, PET_BRIEF_SOURCE,
|
|
1166
|
+
} = await loadPetBrief()
|
|
1167
|
+
const maxItems = PET_BRIEF_MAX_ITEMS
|
|
1168
|
+
const id = { type: 'string', minLength: 1, maxLength: 64 }
|
|
1169
|
+
const confidence = { type: 'number', minimum: 0, maximum: 1 }
|
|
1170
|
+
const arrayOf = (required, properties) => ({
|
|
1171
|
+
type: 'array',
|
|
1172
|
+
maxItems,
|
|
1173
|
+
items: { type: 'object', additionalProperties: false, required, properties },
|
|
1174
|
+
})
|
|
1175
|
+
return {
|
|
1176
|
+
$schema: 'https://json-schema.org/draft/2020-12/schema',
|
|
1177
|
+
$id: 'https://github.com/PerryLink/advisers/docs/pet-brief/schema-v0.2.json',
|
|
1178
|
+
title: 'Advisers Pet Brief (contract v0.2)',
|
|
1179
|
+
description: 'Read-only, redacted, expiring projection from Advisers to a desktop-pet consumer. No reasoning, secrets, documents, or emotional fields. v0.2 adds displayPolicy (public|private|none); v0.1 briefs had schemaVersion 1 and no displayPolicy.',
|
|
1180
|
+
type: 'object',
|
|
1181
|
+
additionalProperties: false,
|
|
1182
|
+
required: ['schemaVersion', 'generatedAt', 'expiresAt', 'source', 'displayPolicy', 'counts', 'today', 'commitments', 'risks', 'facts', 'mood', 'suggestedLines', 'redactions'],
|
|
1183
|
+
properties: {
|
|
1184
|
+
schemaVersion: { type: 'integer', const: PET_BRIEF_SCHEMA_VERSION, description: 'Contract v0.2. v0.1 = 1 is accepted by the producer validator as legacy with warnings; consumers are not required to accept it.' },
|
|
1185
|
+
generatedAt: { type: 'string', format: 'date-time' },
|
|
1186
|
+
expiresAt: { type: 'string', format: 'date-time', description: 'generatedAt + 5 min by default; consumers discard the brief when now >= expiresAt.' },
|
|
1187
|
+
source: { type: 'string', const: PET_BRIEF_SOURCE },
|
|
1188
|
+
displayPolicy: {
|
|
1189
|
+
type: 'string',
|
|
1190
|
+
enum: [...PET_BRIEF_DISPLAY_POLICIES],
|
|
1191
|
+
default: PET_BRIEF_DEFAULT_DISPLAY_POLICY,
|
|
1192
|
+
description: 'Who may see brief-derived content. public: may be shown whenever the pet is visible (still redacted). private (default): only in a personal/no-bystander context; the consumer must auto-collapse, one-click hide and hide during screen sharing/recording. none: consumer must not render or retain any brief-derived content (treat as disabled). Missing (legacy v0.1) means private.',
|
|
1193
|
+
},
|
|
1194
|
+
counts: {
|
|
1195
|
+
type: 'object',
|
|
1196
|
+
additionalProperties: false,
|
|
1197
|
+
required: ['today', 'commitments', 'risks', 'facts'],
|
|
1198
|
+
properties: {
|
|
1199
|
+
today: { type: 'integer', minimum: 0, maximum: maxItems },
|
|
1200
|
+
commitments: { type: 'integer', minimum: 0, maximum: maxItems },
|
|
1201
|
+
risks: { type: 'integer', minimum: 0, maximum: maxItems },
|
|
1202
|
+
facts: { type: 'integer', minimum: 0, maximum: maxItems },
|
|
1203
|
+
},
|
|
1204
|
+
},
|
|
1205
|
+
today: arrayOf(['id', 'title', 'status'], {
|
|
1206
|
+
id,
|
|
1207
|
+
title: { type: 'string', minLength: 1, maxLength: 80 },
|
|
1208
|
+
status: { type: 'string', enum: ['open', 'doing', 'done'] },
|
|
1209
|
+
}),
|
|
1210
|
+
commitments: arrayOf(['id', 'matter', 'who', 'what', 'due', 'risk', 'confidence'], {
|
|
1211
|
+
id,
|
|
1212
|
+
matter: { type: 'string', minLength: 1, maxLength: 64 },
|
|
1213
|
+
who: { type: 'string', minLength: 1, maxLength: 40 },
|
|
1214
|
+
what: { type: 'string', minLength: 1, maxLength: 80 },
|
|
1215
|
+
due: { type: 'string', minLength: 1, maxLength: 32 },
|
|
1216
|
+
risk: { type: 'string', enum: ['low', 'medium', 'high'] },
|
|
1217
|
+
confidence,
|
|
1218
|
+
}),
|
|
1219
|
+
risks: arrayOf(['id', 'level', 'summary', 'evidence', 'confidence'], {
|
|
1220
|
+
id,
|
|
1221
|
+
level: { type: 'string', enum: ['low', 'medium', 'high'] },
|
|
1222
|
+
summary: { type: 'string', minLength: 1, maxLength: 80 },
|
|
1223
|
+
evidence: { type: 'string', minLength: 1, maxLength: 64 },
|
|
1224
|
+
confidence,
|
|
1225
|
+
}),
|
|
1226
|
+
facts: arrayOf(['id', 'subject', 'predicate', 'value', 'confidence'], {
|
|
1227
|
+
id,
|
|
1228
|
+
subject: { type: 'string', minLength: 1, maxLength: 40 },
|
|
1229
|
+
predicate: { type: 'string', minLength: 1, maxLength: 40 },
|
|
1230
|
+
value: { type: 'string', minLength: 1, maxLength: 80 },
|
|
1231
|
+
confidence,
|
|
1232
|
+
}),
|
|
1233
|
+
mood: { type: 'string', enum: [...PET_BRIEF_MOODS], description: 'Workload-only rendering hint, never an emotional state about the user.' },
|
|
1234
|
+
suggestedLines: {
|
|
1235
|
+
type: 'array',
|
|
1236
|
+
maxItems: PET_BRIEF_MAX_SUGGESTED_LINES,
|
|
1237
|
+
items: { type: 'string', minLength: 1, maxLength: PET_BRIEF_MAX_LINE_LENGTH },
|
|
1238
|
+
},
|
|
1239
|
+
redactions: {
|
|
1240
|
+
type: 'array',
|
|
1241
|
+
maxItems,
|
|
1242
|
+
items: { type: 'string', minLength: 1, maxLength: 80 },
|
|
1243
|
+
},
|
|
1244
|
+
},
|
|
1245
|
+
}
|
|
1246
|
+
}
|
|
1247
|
+
|
|
1248
|
+
/**
|
|
1249
|
+
* `advisers pet-brief` — read-only projection for the pet (contract v0.2).
|
|
681
1250
|
* Never opens the store read-write, never calls a model, never writes the
|
|
682
1251
|
* ledger. The only write is the optional `--out` file (0600, atomic rename).
|
|
1252
|
+
*
|
|
1253
|
+
* CLI surface: `--json`, `--out [path]`, `--check [--strict] [--in file]`,
|
|
1254
|
+
* `--display-policy public|private|none` and `--print-schema`. Warnings from
|
|
1255
|
+
* the validator are reported but never change the exit code (strict mode turns
|
|
1256
|
+
* legacy/missing-displayPolicy into errors instead).
|
|
683
1257
|
*/
|
|
684
1258
|
async function petBrief(args) {
|
|
1259
|
+
const {
|
|
1260
|
+
PET_BRIEF_DEFAULT_DISPLAY_POLICY, PET_BRIEF_DISPLAY_POLICIES, PET_BRIEF_MAX_ITEMS,
|
|
1261
|
+
PET_BRIEF_MAX_LINE_LENGTH, PET_BRIEF_MAX_SUGGESTED_LINES, PET_BRIEF_MOODS,
|
|
1262
|
+
PET_BRIEF_SCHEMA_VERSION, PET_BRIEF_SOURCE, buildPetBrief, validatePetBrief, writePetBriefAtomic,
|
|
1263
|
+
} = await loadPetBrief()
|
|
685
1264
|
const { flags } = parseFlags(args)
|
|
686
1265
|
const asJson = args.includes('--json')
|
|
687
1266
|
const check = args.includes('--check')
|
|
1267
|
+
const strict = args.includes('--strict')
|
|
1268
|
+
const printSchema = args.includes('--print-schema')
|
|
688
1269
|
const inFile = flags.in
|
|
689
1270
|
const outFlag = flags.out
|
|
1271
|
+
const displayPolicyFlag = flags['display-policy']
|
|
690
1272
|
const fail = (code, message) => {
|
|
691
1273
|
console.error(JSON.stringify({ error: { code, message } }))
|
|
692
1274
|
process.exitCode = 1
|
|
693
1275
|
}
|
|
1276
|
+
if (printSchema) {
|
|
1277
|
+
if (inFile !== undefined || outFlag !== undefined || displayPolicyFlag !== undefined || asJson || check) {
|
|
1278
|
+
return fail('E_USAGE', '--print-schema cannot be combined with other pet-brief options')
|
|
1279
|
+
}
|
|
1280
|
+
console.log(JSON.stringify(await petBriefJsonSchema(), null, 2))
|
|
1281
|
+
return
|
|
1282
|
+
}
|
|
694
1283
|
if (inFile !== undefined && !check) return fail('E_USAGE', '--in can only be used with --check')
|
|
695
1284
|
if (inFile !== undefined && typeof inFile !== 'string') return fail('E_USAGE', '--in needs a file path')
|
|
696
1285
|
if (outFlag !== undefined && typeof outFlag !== 'string' && outFlag !== true) return fail('E_USAGE', '--out takes an optional file path')
|
|
1286
|
+
if (strict && !check) return fail('E_USAGE', '--strict can only be used with --check')
|
|
1287
|
+
let displayPolicy
|
|
1288
|
+
if (displayPolicyFlag !== undefined) {
|
|
1289
|
+
if (typeof displayPolicyFlag !== 'string' || !PET_BRIEF_DISPLAY_POLICIES.includes(displayPolicyFlag)) {
|
|
1290
|
+
return fail('E_USAGE', `--display-policy must be one of ${PET_BRIEF_DISPLAY_POLICIES.join('|')}`)
|
|
1291
|
+
}
|
|
1292
|
+
if (inFile !== undefined) return fail('E_USAGE', '--display-policy can only be used when generating a brief')
|
|
1293
|
+
displayPolicy = displayPolicyFlag
|
|
1294
|
+
}
|
|
1295
|
+
const validateOptions = strict ? { now: Date.now(), acceptLegacy: false, requireDisplayPolicy: true } : { now: Date.now() }
|
|
697
1296
|
try {
|
|
698
1297
|
if (inFile) {
|
|
699
1298
|
let text
|
|
700
1299
|
try { text = readFileSync(inFile, 'utf8') } catch (error) { return fail('E_READ', `cannot read ${inFile}: ${error.message}`) }
|
|
701
|
-
const result = validatePetBrief(text,
|
|
702
|
-
console.log(JSON.stringify({ ok: result.ok, checked: inFile, expiresAt: result.brief?.expiresAt ?? null, counts: result.brief?.counts ?? null, errors: result.errors }, null, 2))
|
|
1300
|
+
const result = validatePetBrief(text, validateOptions)
|
|
1301
|
+
console.log(JSON.stringify({ ok: result.ok, checked: inFile, expiresAt: result.brief?.expiresAt ?? null, counts: result.brief?.counts ?? null, errors: result.errors, warnings: result.warnings }, null, 2))
|
|
703
1302
|
if (!result.ok) process.exitCode = 1
|
|
704
1303
|
return
|
|
705
1304
|
}
|
|
1305
|
+
// P1-1/P0-1: pet-brief reads state.db read-only, but it still shares the
|
|
1306
|
+
// single-writer HOME. Report a sealed vault with the stable code instead of
|
|
1307
|
+
// "store not found", and take the instance lock so the read cannot race a
|
|
1308
|
+
// seal/unseal/sync-pull replacing the database.
|
|
1309
|
+
if (mode === 'sqlite') {
|
|
1310
|
+
const sealed = vaultSealedPath()
|
|
1311
|
+
if (sealed) return fail('E_VAULT_SEALED', 'the database is sealed at ' + sealed + '; run "ADVISERS_VAULT_PASSPHRASE=... advisers vault unseal" first (no empty database was created)')
|
|
1312
|
+
ensureInstanceLock()
|
|
1313
|
+
}
|
|
706
1314
|
const { readLedgerSnapshotReadOnly } = await import('../lib/pet-brief-store.js')
|
|
707
1315
|
let snapshot
|
|
708
1316
|
try {
|
|
@@ -711,10 +1319,10 @@ async function petBrief(args) {
|
|
|
711
1319
|
return fail(error?.code ?? 'E_STORE', error?.message ?? String(error))
|
|
712
1320
|
}
|
|
713
1321
|
const ledger = Ledger.fromJSON(snapshot)
|
|
714
|
-
const brief = buildPetBrief(ledger, { now: Date.now() })
|
|
1322
|
+
const brief = buildPetBrief(ledger, displayPolicy ? { now: Date.now(), displayPolicy } : { now: Date.now() })
|
|
715
1323
|
if (check) {
|
|
716
|
-
const result = validatePetBrief(brief,
|
|
717
|
-
console.log(JSON.stringify({ ok: result.ok, checked: 'generated', expiresAt: brief.expiresAt, counts: brief.counts, errors: result.errors }, null, 2))
|
|
1324
|
+
const result = validatePetBrief(brief, validateOptions)
|
|
1325
|
+
console.log(JSON.stringify({ ok: result.ok, checked: 'generated', expiresAt: brief.expiresAt, counts: brief.counts, errors: result.errors, warnings: result.warnings }, null, 2))
|
|
718
1326
|
if (!result.ok) process.exitCode = 1
|
|
719
1327
|
return
|
|
720
1328
|
}
|
|
@@ -724,7 +1332,7 @@ async function petBrief(args) {
|
|
|
724
1332
|
}
|
|
725
1333
|
if (asJson) { console.log(JSON.stringify(brief, null, 2)); return }
|
|
726
1334
|
console.log(`pet-brief · ${brief.counts.today} today · ${brief.counts.commitments} commitments · ${brief.counts.risks} risks · ${brief.counts.facts} facts`)
|
|
727
|
-
console.log(`mood ${brief.mood} · expires ${brief.expiresAt}`)
|
|
1335
|
+
console.log(`mood ${brief.mood} · expires ${brief.expiresAt} · displayPolicy ${brief.displayPolicy}`)
|
|
728
1336
|
if (outPath) console.log(`wrote ${outPath} (mode 600, atomic)`)
|
|
729
1337
|
} catch (error) {
|
|
730
1338
|
fail(error?.code ?? 'E_BRIEF', error?.message ?? String(error))
|
|
@@ -755,18 +1363,56 @@ function printPreferences() {
|
|
|
755
1363
|
async function doctor() {
|
|
756
1364
|
const rows = []
|
|
757
1365
|
const check = (name, ok, detail = '') => rows.push({ name, ok, detail })
|
|
758
|
-
|
|
1366
|
+
const [nodeMajor, nodeMinor] = process.versions.node.split('.').map(Number)
|
|
1367
|
+
check('node', nodeMajor > 22 || (nodeMajor === 22 && nodeMinor >= 16), process.version)
|
|
759
1368
|
try { ensureHome(); check('home', existsSync(HOME), HOME) } catch (error) { check('home', false, error.message) }
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
check('
|
|
766
|
-
check('
|
|
767
|
-
|
|
1369
|
+
// Sealed vault (robustness audit P1-1): report the real state instead of
|
|
1370
|
+
// silently creating an empty database and printing all-PASS diagnostics.
|
|
1371
|
+
const sealed = vaultSealedPath()
|
|
1372
|
+
if (sealed) {
|
|
1373
|
+
check('vault', true, `sealed (${sealed}); run ` + '`advisers vault unseal`')
|
|
1374
|
+
check('lock', true, 'not taken (vault sealed)')
|
|
1375
|
+
check('database', true, 'skipped (vault sealed)')
|
|
1376
|
+
check('sqlite', true, 'skipped (vault sealed)')
|
|
1377
|
+
check('audit', true, 'skipped (vault sealed)')
|
|
1378
|
+
check('schema', true, 'skipped (vault sealed)')
|
|
1379
|
+
} else {
|
|
1380
|
+
try {
|
|
1381
|
+
const store = openStore()
|
|
1382
|
+
// P0-1: doctor holds the instance lock while it inspects the store; the
|
|
1383
|
+
// row also exposes the lock path so a stuck holder can be diagnosed.
|
|
1384
|
+
check('lock', true, `${instanceLock?.path ?? LOCK_PATH} (held by pid ${process.pid})`)
|
|
1385
|
+
let dbBytes = 0
|
|
1386
|
+
try { dbBytes = statSync(DB).size } catch {}
|
|
1387
|
+
check('database', dbBytes > 0, dbBytes > 0 ? `${DB} (${dbBytes} bytes)` : `E_DB_CORRUPT: ${DB} is 0 bytes; back it up and restore`)
|
|
1388
|
+
const integrity = store.assertIntegrity()
|
|
1389
|
+
check('sqlite', integrity === 'ok', `${DB} (${integrity})`)
|
|
1390
|
+
const audit = store.verifyAudit()
|
|
1391
|
+
check('audit', audit.ok, audit.ok ? `${audit.count} entries` : `BROKEN at seq ${audit.seq}`)
|
|
1392
|
+
check('schema', true, String(store.db.prepare("SELECT value FROM meta WHERE key='schema_version'").get()?.value ?? '?'))
|
|
1393
|
+
} catch (error) {
|
|
1394
|
+
if (error?.code === 'E_DB_LOCKED') {
|
|
1395
|
+
// Another live process holds the store; this is a real FAIL, not a
|
|
1396
|
+
// reason to silently inspect a stale snapshot.
|
|
1397
|
+
check('lock', false, error.message)
|
|
1398
|
+
check('sqlite', false, 'skipped (another instance holds the instance lock)')
|
|
1399
|
+
} else if (error?.code === 'E_DB_CORRUPT') {
|
|
1400
|
+
check('lock', true, `${instanceLock?.path ?? LOCK_PATH} (held by pid ${process.pid})`)
|
|
1401
|
+
check('database', false, error.message)
|
|
1402
|
+
check('sqlite', false, 'refusing to open a 0-byte/corrupt database (no silent rebuild)')
|
|
1403
|
+
check('audit', false, 'skipped (database damaged)')
|
|
1404
|
+
check('schema', false, 'skipped (database damaged)')
|
|
1405
|
+
} else {
|
|
1406
|
+
check('lock', Boolean(instanceLock?.held), instanceLock?.held ? `${LOCK_PATH} (held by pid ${process.pid})` : 'not taken')
|
|
1407
|
+
check('sqlite', false, error.message)
|
|
1408
|
+
}
|
|
1409
|
+
}
|
|
1410
|
+
}
|
|
1411
|
+
// P2-3 (0.2.1): probe resolvability instead of importing the office barrel
|
|
1412
|
+
// (222-573ms, and only needed to answer "is the peer installed?").
|
|
768
1413
|
let officeOk = false
|
|
769
|
-
try {
|
|
1414
|
+
try { officeOk = Boolean(import.meta.resolve('advisers-office')) } catch {}
|
|
1415
|
+
if (!officeOk) officeOk = existsSync(new URL('../../office/dist/index.js', import.meta.url))
|
|
770
1416
|
check('office', officeOk, officeOk ? 'advisers-office resolvable' : 'npm i -g advisers-office@next, or ADVISERS_OFFICE_LOCAL=1 in checkout')
|
|
771
1417
|
check('policy', Boolean(StrictPolicyPack), StrictPolicyPack ? 'strict pack loaded' : 'policy pack missing')
|
|
772
1418
|
check('model', true, process.env.ADVISERS_API_KEY ? 'API key present (not tested)' : 'optional; ADVISERS_API_KEY not set')
|
|
@@ -826,10 +1472,11 @@ function printStatus(asJson = false) {
|
|
|
826
1472
|
console.log(`soul ${data.soul}`)
|
|
827
1473
|
}
|
|
828
1474
|
|
|
829
|
-
function loadHistory(conversationId) {
|
|
1475
|
+
async function loadHistory(conversationId) {
|
|
830
1476
|
try {
|
|
831
1477
|
const store = dbStore()
|
|
832
1478
|
if (!store) return { turns: [], summary: '' }
|
|
1479
|
+
const { buildHistory } = await loadContextWindow()
|
|
833
1480
|
const turns = store.listTurns(conversationId, 100)
|
|
834
1481
|
const summary = store.getSessionSummary(conversationId)
|
|
835
1482
|
return buildHistory({ turns, summary: summary?.summary, throughSeq: summary?.throughSeq ?? 0 })
|
|
@@ -847,6 +1494,7 @@ async function maybeSummarize(conversationId, { apiKey, baseUrl, model, ledger }
|
|
|
847
1494
|
try {
|
|
848
1495
|
const store = dbStore()
|
|
849
1496
|
if (!store) return
|
|
1497
|
+
const { shouldSummarize, buildPins, summarizeTurns, ensurePins, continuityProbes } = await loadContextWindow()
|
|
850
1498
|
const turns = store.listTurns(conversationId, 500)
|
|
851
1499
|
const old = store.getSessionSummary(conversationId)
|
|
852
1500
|
if (!shouldSummarize(turns, old?.throughSeq ?? 0, 10, 20)) return
|
|
@@ -859,6 +1507,7 @@ async function maybeSummarize(conversationId, { apiKey, baseUrl, model, ledger }
|
|
|
859
1507
|
if (apiKey && process.env.ADVISERS_LLM_SUMMARY !== '0') {
|
|
860
1508
|
try {
|
|
861
1509
|
const transcript = fresh.map((t) => `${t.role === 'user' ? '用户' : '助手'}:${t.content}`).join('\n')
|
|
1510
|
+
const { chatCompletion } = await loadModel()
|
|
862
1511
|
const response = await chatCompletion({
|
|
863
1512
|
apiKey,
|
|
864
1513
|
baseUrl: baseUrl || 'https://api.deepseek.com',
|
|
@@ -879,10 +1528,11 @@ async function maybeSummarize(conversationId, { apiKey, baseUrl, model, ledger }
|
|
|
879
1528
|
} catch {}
|
|
880
1529
|
}
|
|
881
1530
|
|
|
882
|
-
function printOpening(conversationId) {
|
|
1531
|
+
async function printOpening(conversationId) {
|
|
883
1532
|
try {
|
|
884
1533
|
const store = dbStore()
|
|
885
1534
|
if (!store) return
|
|
1535
|
+
const { buildOpening } = await loadContextWindow()
|
|
886
1536
|
const turns = store.listTurns(conversationId, 20)
|
|
887
1537
|
const summary = store.getSessionSummary(conversationId)
|
|
888
1538
|
const commitments = loadLedger().openCommitments()
|
|
@@ -890,7 +1540,8 @@ function printOpening(conversationId) {
|
|
|
890
1540
|
} catch {}
|
|
891
1541
|
}
|
|
892
1542
|
|
|
893
|
-
function applyNudgeFeedback(text) {
|
|
1543
|
+
async function applyNudgeFeedback(text) {
|
|
1544
|
+
const { classifyNudgeOutcome } = await loadNudge()
|
|
894
1545
|
const outcome = classifyNudgeOutcome(text)
|
|
895
1546
|
if (!outcome) return
|
|
896
1547
|
try {
|
|
@@ -902,7 +1553,75 @@ function applyNudgeFeedback(text) {
|
|
|
902
1553
|
} catch {}
|
|
903
1554
|
}
|
|
904
1555
|
|
|
905
|
-
|
|
1556
|
+
let safetyModule
|
|
1557
|
+
let lastTurnSafetyBlock = null
|
|
1558
|
+
|
|
1559
|
+
/** Build the structured audit reason for a safety decision (never the original text). */
|
|
1560
|
+
function safetyReasonFor(result, fallbackSurface = 'model.output') {
|
|
1561
|
+
try {
|
|
1562
|
+
return safetyModule.buildAuditReason({
|
|
1563
|
+
rulesetVersion: result?.rulesetVersion,
|
|
1564
|
+
surface: result?.surface ?? fallbackSurface,
|
|
1565
|
+
action: result?.action ?? 'block',
|
|
1566
|
+
code: result?.code ?? 'CONTENT_SAFETY_BLOCKED',
|
|
1567
|
+
ruleIds: result?.ruleIds,
|
|
1568
|
+
evidenceHash: result?.evidenceHash,
|
|
1569
|
+
})
|
|
1570
|
+
} catch {
|
|
1571
|
+
return `code=${result?.code ?? 'CONTENT_SAFETY_BLOCKED'}`
|
|
1572
|
+
}
|
|
1573
|
+
}
|
|
1574
|
+
|
|
1575
|
+
/**
|
|
1576
|
+
* Report a local content-safety block without echoing or persisting the original
|
|
1577
|
+
* text (privacy audit P2 / security audit SEC2-04): user-facing rejection plus a
|
|
1578
|
+
* keyed `actor: 'safety'` audit row so the block is explainable later.
|
|
1579
|
+
*/
|
|
1580
|
+
function recordSafetyBlock(result, { action = 'safety.chat', surface = 'model.output' } = {}) {
|
|
1581
|
+
const code = result?.code || 'CONTENT_SAFETY_BLOCKED'
|
|
1582
|
+
const ruleIds = Array.isArray(result?.ruleIds) ? result.ruleIds : []
|
|
1583
|
+
console.error('advisers: 内容安全审核未通过(CONTENT_SAFETY_BLOCKED)')
|
|
1584
|
+
console.error('本次输入未发送到模型,也未写入账本或会话;被拒内容不会保存为标题或会话。')
|
|
1585
|
+
console.error(`本地自检(${surface}):code=${code} rules=${ruleIds.join(',') || '-'};这是本地规则层判定,不是人工审核。`)
|
|
1586
|
+
if (result?.crisis) console.error('如果你或他人正处于危险中,请立即联系当地紧急服务或可信任的人。')
|
|
1587
|
+
try {
|
|
1588
|
+
ensureHome()
|
|
1589
|
+
dbStore()?.appendAudit({ actor: 'safety', action, allowed: false, reason: safetyReasonFor(result, surface) })
|
|
1590
|
+
} catch {}
|
|
1591
|
+
}
|
|
1592
|
+
|
|
1593
|
+
/**
|
|
1594
|
+
* Wrapper around runTurnInner: local content-safety pre-flight BEFORE
|
|
1595
|
+
* runtime.ingest()/upsertSession() (SEC2-04). A blocked input must not create a
|
|
1596
|
+
* matter, a session title or a ledger fact, and must not purge the active matter
|
|
1597
|
+
* pointer later (the old order persisted the raw text as sessions.title).
|
|
1598
|
+
*/
|
|
1599
|
+
async function runTurn(options) {
|
|
1600
|
+
lastTurnSafetyBlock = null
|
|
1601
|
+
ensureHome()
|
|
1602
|
+
safetyModule ??= await loadSafety()
|
|
1603
|
+
const text = String(options?.text ?? '')
|
|
1604
|
+
const decision = safetyModule.classify(text, { surface: 'model.output', hmacKey: process.env.ADVISERS_AUDIT_KEY })
|
|
1605
|
+
if (decision.action === 'block') {
|
|
1606
|
+
lastTurnSafetyBlock = decision
|
|
1607
|
+
recordSafetyBlock(decision, { surface: 'chat.input' })
|
|
1608
|
+
return undefined
|
|
1609
|
+
}
|
|
1610
|
+
try {
|
|
1611
|
+
return await runTurnInner(options)
|
|
1612
|
+
} catch (error) {
|
|
1613
|
+
// Context/history/attachments can still trip the model choke point; audit
|
|
1614
|
+
// it as safety rather than letting it look like an unexplained crash.
|
|
1615
|
+
if (error?.name === 'ContentSafetyError') {
|
|
1616
|
+
lastTurnSafetyBlock = error
|
|
1617
|
+
recordSafetyBlock(error, { surface: error.surface || 'model.output' })
|
|
1618
|
+
return undefined
|
|
1619
|
+
}
|
|
1620
|
+
throw error
|
|
1621
|
+
}
|
|
1622
|
+
}
|
|
1623
|
+
|
|
1624
|
+
async function runTurnInner({ runtime, ledger, text, conversationId, debug = false, confirm, attachments = [] }) {
|
|
906
1625
|
const result = await runtime.ingest({
|
|
907
1626
|
linkId: 'cli',
|
|
908
1627
|
accountId: 'local',
|
|
@@ -917,7 +1636,7 @@ async function runTurn({ runtime, ledger, text, conversationId, debug = false, c
|
|
|
917
1636
|
console.log(`[ignored: ${result.reason}]`)
|
|
918
1637
|
return
|
|
919
1638
|
}
|
|
920
|
-
applyNudgeFeedback(text)
|
|
1639
|
+
await applyNudgeFeedback(text)
|
|
921
1640
|
const context = runtime.lastContext
|
|
922
1641
|
if (!context) throw new Error('runtime did not produce a context')
|
|
923
1642
|
const egressDenied = egressDeniedReason(context.matter, 'chat')
|
|
@@ -939,9 +1658,10 @@ async function runTurn({ runtime, ledger, text, conversationId, debug = false, c
|
|
|
939
1658
|
const intent = context.intent
|
|
940
1659
|
let agentText = text
|
|
941
1660
|
const extracted = []
|
|
1661
|
+
const attachmentLib = attachments.length ? await loadAttachments() : null
|
|
942
1662
|
for (const file of attachments) {
|
|
943
1663
|
try {
|
|
944
|
-
const attachment = await extractAttachment(file, { cwd: process.cwd() })
|
|
1664
|
+
const attachment = await attachmentLib.extractAttachment(file, { cwd: process.cwd() })
|
|
945
1665
|
extracted.push(attachment)
|
|
946
1666
|
console.log(`[attach] ${attachment.name} (${attachment.text.length} chars${attachment.truncated ? ', truncated' : ''})`)
|
|
947
1667
|
} catch (error) {
|
|
@@ -974,7 +1694,8 @@ async function runTurn({ runtime, ledger, text, conversationId, debug = false, c
|
|
|
974
1694
|
if (!intent?.questions?.length) console.log('[local] 未配置模型;已记录到当前会话,但没有创建承诺或文件。设置 ADVISERS_API_KEY 后可用自然语言执行;也可用 `advisers office` / `advisers template` 直接生成文件。')
|
|
975
1695
|
return intent?.questions?.[0]
|
|
976
1696
|
}
|
|
977
|
-
const
|
|
1697
|
+
const { buildPins, fitHistory } = await loadContextWindow()
|
|
1698
|
+
const history = await loadHistory(conversationId)
|
|
978
1699
|
const pins = buildPins({
|
|
979
1700
|
preferences: ledger.listPreferences({ matterId: context.matter.id }),
|
|
980
1701
|
commitments: ledger.openCommitments(context.matter.id),
|
|
@@ -982,6 +1703,7 @@ async function runTurn({ runtime, ledger, text, conversationId, debug = false, c
|
|
|
982
1703
|
const prompt = pins ? `${context.prompt}\n<session-pins>\n${pins}\n</session-pins>` : context.prompt
|
|
983
1704
|
const fitted = fitHistory({ system: prompt, summary: history.summary, history: history.turns, current: agentText, maxTokens: Number(process.env.ADVISERS_CONTEXT_TOKENS || 12000) })
|
|
984
1705
|
if (fitted.trimmed) console.log(`[compact] 裁剪 ${fitted.trimmed} 轮旧历史`)
|
|
1706
|
+
const { runAgent } = await loadAgent()
|
|
985
1707
|
const { reply, artifacts, toolLog } = await runAgent({
|
|
986
1708
|
runtime,
|
|
987
1709
|
text: agentText,
|
|
@@ -1048,6 +1770,7 @@ async function runTurn({ runtime, ledger, text, conversationId, debug = false, c
|
|
|
1048
1770
|
if (runId && process.env.ADVISERS_LEARNING === 'auto' && apiKey) {
|
|
1049
1771
|
try {
|
|
1050
1772
|
const run = dbStore()?.listTaskRuns(50).find((r) => r.id === runId)
|
|
1773
|
+
const { reviewRun, lintReview, materializeReview } = await loadReview()
|
|
1051
1774
|
const review = await reviewRun({ run, routines: ledger.listRoutines(), apiKey, baseUrl: process.env.ADVISERS_BASE_URL, model: process.env.ADVISERS_MODEL })
|
|
1052
1775
|
const checked = lintReview(review, { run, routines: ledger.listRoutines() })
|
|
1053
1776
|
if (checked.ok && checked.review.verdict !== 'NONE') {
|
|
@@ -1057,6 +1780,7 @@ async function runTurn({ runtime, ledger, text, conversationId, debug = false, c
|
|
|
1057
1780
|
}
|
|
1058
1781
|
} catch {}
|
|
1059
1782
|
}
|
|
1783
|
+
const { buildRoutineCandidate } = await loadLearning()
|
|
1060
1784
|
const candidate = buildRoutineCandidate({ text, toolLog, artifacts })
|
|
1061
1785
|
if (candidate && !ledger.listRoutines().some((r) => r.name === candidate.name)) {
|
|
1062
1786
|
try {
|
|
@@ -1094,6 +1818,7 @@ async function chat(args) {
|
|
|
1094
1818
|
const ledger = loadLedger()
|
|
1095
1819
|
const runtime = runtimeFor(ledger)
|
|
1096
1820
|
await runTurn({ runtime, ledger, text, conversationId: latestConversationId(), attachments: files })
|
|
1821
|
+
if (lastTurnSafetyBlock) process.exitCode = 1
|
|
1097
1822
|
saveLedger(ledger)
|
|
1098
1823
|
}
|
|
1099
1824
|
|
|
@@ -1113,7 +1838,7 @@ async function repl() {
|
|
|
1113
1838
|
}
|
|
1114
1839
|
try {
|
|
1115
1840
|
const latest = dbStore()?.listSessions(1)[0]
|
|
1116
|
-
printOpening(latest?.conversationId ?? conversationId)
|
|
1841
|
+
await printOpening(latest?.conversationId ?? conversationId)
|
|
1117
1842
|
} catch {}
|
|
1118
1843
|
console.log('/help for commands, /quit to leave')
|
|
1119
1844
|
|
|
@@ -1218,6 +1943,7 @@ async function repl() {
|
|
|
1218
1943
|
continue
|
|
1219
1944
|
}
|
|
1220
1945
|
if (text === '/decay') {
|
|
1946
|
+
const { applyPreferenceDecay } = await loadLearning()
|
|
1221
1947
|
const changed = applyPreferenceDecay(ledger.listPreferences({ includeCandidates: true }))
|
|
1222
1948
|
saveLedger(ledger)
|
|
1223
1949
|
console.log(`[decay] ${changed.length} preference(s) updated`)
|
|
@@ -1237,6 +1963,7 @@ async function repl() {
|
|
|
1237
1963
|
if (text === '/week') { printWeek(ledger); continue }
|
|
1238
1964
|
if (text === '/digest' || text === '/digest day' || text === '/digest week') {
|
|
1239
1965
|
const store = dbStore()
|
|
1966
|
+
const { buildDigest } = await loadDigest()
|
|
1240
1967
|
console.log(buildDigest({
|
|
1241
1968
|
period: text.endsWith('week') ? 'week' : 'day',
|
|
1242
1969
|
turns: store?.listTurns(conversationId, 200) ?? [],
|
|
@@ -1246,11 +1973,13 @@ async function repl() {
|
|
|
1246
1973
|
continue
|
|
1247
1974
|
}
|
|
1248
1975
|
if (text === '/diff') {
|
|
1976
|
+
const { diffLatest } = await loadUndo()
|
|
1249
1977
|
const result = await diffLatest({ cwd: process.cwd(), backupDir: join(HOME, 'undo') })
|
|
1250
1978
|
console.log(result.ok ? result.diff : `diff failed: ${result.error}`)
|
|
1251
1979
|
continue
|
|
1252
1980
|
}
|
|
1253
1981
|
if (text === '/undo') {
|
|
1982
|
+
const { undoLatest } = await loadUndo()
|
|
1254
1983
|
const result = await undoLatest({ cwd: process.cwd(), backupDir: join(HOME, 'undo'), force: args.includes('--force') })
|
|
1255
1984
|
console.log(result.ok ? `已回滚:${result.path}` : `撤销失败:${result.error}`)
|
|
1256
1985
|
continue
|
|
@@ -1326,7 +2055,7 @@ async function repl() {
|
|
|
1326
2055
|
pendingFiles = []
|
|
1327
2056
|
console.log(`resumed: ${pick.title} [${pick.conversationId}]`)
|
|
1328
2057
|
} catch { console.log('history is not available') }
|
|
1329
|
-
printOpening(conversationId)
|
|
2058
|
+
await printOpening(conversationId)
|
|
1330
2059
|
continue
|
|
1331
2060
|
}
|
|
1332
2061
|
if (text.startsWith('/brief ')) {
|
|
@@ -1336,11 +2065,11 @@ async function repl() {
|
|
|
1336
2065
|
continue
|
|
1337
2066
|
}
|
|
1338
2067
|
if (text.startsWith('/')) { console.log(`unknown command: ${text}; /help`); continue }
|
|
2068
|
+
const { correctionStatement } = await loadLearning()
|
|
1339
2069
|
const feedback = correctionStatement(text)
|
|
1340
2070
|
if (feedback) {
|
|
1341
2071
|
const result = learnPreference(ledger, feedback, text, { explicit: /^(以后|记住|每次)/.test(text) })
|
|
1342
|
-
|
|
1343
|
-
saveLedger(ledger)
|
|
2072
|
+
saveLedgerWithAudit(ledger, { actor: 'local', action: 'correct', allowed: true, reason: result.preference.id })
|
|
1344
2073
|
printLearnReceipt(result)
|
|
1345
2074
|
continue
|
|
1346
2075
|
}
|
|
@@ -1402,7 +2131,7 @@ function forget(id) {
|
|
|
1402
2131
|
if (!ok) process.exitCode = 1
|
|
1403
2132
|
}
|
|
1404
2133
|
|
|
1405
|
-
function exportLedger(all = false, options = {}) {
|
|
2134
|
+
async function exportLedger(all = false, options = {}) {
|
|
1406
2135
|
const ledger = loadLedger().toJSON()
|
|
1407
2136
|
const payload = all ? (() => {
|
|
1408
2137
|
const store = dbStore()
|
|
@@ -1415,6 +2144,7 @@ function exportLedger(all = false, options = {}) {
|
|
|
1415
2144
|
if (options.encrypted) {
|
|
1416
2145
|
const passphrase = process.env.ADVISERS_EXPORT_PASSPHRASE
|
|
1417
2146
|
if (!passphrase) { console.error('export --encrypted requires ADVISERS_EXPORT_PASSPHRASE (min 8 chars)'); process.exitCode = 1; return }
|
|
2147
|
+
const { encryptJson } = await loadVault()
|
|
1418
2148
|
text = JSON.stringify(encryptJson(payload, passphrase), null, 2)
|
|
1419
2149
|
}
|
|
1420
2150
|
if (options.out) {
|
|
@@ -1425,11 +2155,12 @@ function exportLedger(all = false, options = {}) {
|
|
|
1425
2155
|
} else console.log(text)
|
|
1426
2156
|
}
|
|
1427
2157
|
|
|
1428
|
-
function importLedger(file, { replace = false } = {}) {
|
|
2158
|
+
async function importLedger(file, { replace = false } = {}) {
|
|
1429
2159
|
if (!file) { console.error('usage: advisers import <file> [--replace]'); process.exitCode = 1; return }
|
|
1430
2160
|
if (!replace) { console.error('import replaces the local ledger; pass --replace to confirm'); process.exitCode = 1; return }
|
|
1431
2161
|
let payload
|
|
1432
2162
|
try {
|
|
2163
|
+
const { isVaultEnvelope, decryptJson } = await loadVault()
|
|
1433
2164
|
const raw = JSON.parse(readFileSync(file, 'utf8'))
|
|
1434
2165
|
if (isVaultEnvelope(raw)) {
|
|
1435
2166
|
const passphrase = process.env.ADVISERS_EXPORT_PASSPHRASE
|
|
@@ -1439,15 +2170,18 @@ function importLedger(file, { replace = false } = {}) {
|
|
|
1439
2170
|
} catch (error) { console.error(`import failed: ${error.message}`); process.exitCode = 1; return }
|
|
1440
2171
|
const data = payload?.ledger ?? payload
|
|
1441
2172
|
if (!data || !Array.isArray(data.matters)) { console.error('import file does not contain an Advisers ledger'); process.exitCode = 1; return }
|
|
2173
|
+
await requireTosReaccept({ scope: 'import', subject: basename(file), action: 'import --replace' })
|
|
1442
2174
|
ensureHome()
|
|
2175
|
+
// import replaces the ledger wholesale; serialize it with every other store
|
|
2176
|
+
// user (P0-1) before copying the pre-import backup and writing.
|
|
2177
|
+
ensureInstanceLock()
|
|
1443
2178
|
try {
|
|
1444
2179
|
const store = dbStore()
|
|
1445
2180
|
if (store) copyFileSync(DB, join(HOME, `import-backup-${Date.now()}.db`))
|
|
1446
2181
|
} catch {}
|
|
1447
2182
|
try {
|
|
1448
|
-
const ledger = Ledger.fromJSON(data)
|
|
1449
|
-
|
|
1450
|
-
dbStore()?.appendAudit({ actor: 'local', action: 'import.ledger', allowed: true, reason: basename(file) })
|
|
2183
|
+
const ledger = Ledger.fromJSON(data, LOCAL_PORTS)
|
|
2184
|
+
saveLedgerWithAudit(ledger, { actor: 'local', action: 'import.ledger', allowed: true, reason: basename(file) })
|
|
1451
2185
|
console.log(`imported ${data.matters.length} matters, ${data.commitments?.length ?? 0} commitments`)
|
|
1452
2186
|
if (payload?.data) console.error('note: SQLite-only tables in the import were not merged; ledger was replaced.')
|
|
1453
2187
|
} catch (error) { console.error(`import failed: ${error.message}`); process.exitCode = 1 }
|
|
@@ -1455,8 +2189,16 @@ function importLedger(file, { replace = false } = {}) {
|
|
|
1455
2189
|
|
|
1456
2190
|
function backup(file) {
|
|
1457
2191
|
if (!file) { console.error('usage: advisers backup <path.db>'); process.exitCode = 1; return }
|
|
2192
|
+
const sealed = vaultSealedPath()
|
|
2193
|
+
if (sealed) {
|
|
2194
|
+
console.error(`advisers: E_VAULT_SEALED — cannot back up a sealed database (${sealed}).`)
|
|
2195
|
+
console.error('Run `advisers vault unseal` first; the sealed file itself is already an encrypted backup.')
|
|
2196
|
+
process.exitCode = 1
|
|
2197
|
+
return
|
|
2198
|
+
}
|
|
1458
2199
|
const store = openStore()
|
|
1459
|
-
store.
|
|
2200
|
+
const checkpoint = store.checkpoint()
|
|
2201
|
+
if (checkpoint.busy) { console.error('backup failed: database is busy (another advisers process is writing); close it and retry'); process.exitCode = 1; return }
|
|
1460
2202
|
mkdirSync(dirname(file), { recursive: true })
|
|
1461
2203
|
copyFileSync(DB, file)
|
|
1462
2204
|
chmodSync(file, 0o600)
|
|
@@ -1474,7 +2216,11 @@ async function brief(text, deep = false) {
|
|
|
1474
2216
|
console.log(core.renderIntentBrief(brief))
|
|
1475
2217
|
console.log('\n' + core.renderReadback(brief))
|
|
1476
2218
|
if (deep && process.env.ADVISERS_API_KEY) {
|
|
2219
|
+
const briefLedger = loadLedger()
|
|
2220
|
+
const briefDenied = egressDeniedReason(briefLedger.getMatter(activeMatterId(briefLedger)), 'brief --deep')
|
|
2221
|
+
if (briefDenied) { console.error(briefDenied); process.exitCode = 1; return }
|
|
1477
2222
|
try {
|
|
2223
|
+
const { chatCompletion } = await loadModel()
|
|
1478
2224
|
const response = await chatCompletion({
|
|
1479
2225
|
apiKey: process.env.ADVISERS_API_KEY,
|
|
1480
2226
|
baseUrl: process.env.ADVISERS_BASE_URL,
|
|
@@ -1492,7 +2238,7 @@ async function brief(text, deep = false) {
|
|
|
1492
2238
|
}
|
|
1493
2239
|
}
|
|
1494
2240
|
|
|
1495
|
-
function routine(sub, arg, arg2) {
|
|
2241
|
+
async function routine(sub, arg, arg2) {
|
|
1496
2242
|
const ledger = loadLedger()
|
|
1497
2243
|
if (typeof ledger.addRoutine !== 'function') {
|
|
1498
2244
|
console.error('routine requires advisers-core@0.1.0-preview.3 or newer')
|
|
@@ -1514,6 +2260,7 @@ function routine(sub, arg, arg2) {
|
|
|
1514
2260
|
process.exitCode = 1
|
|
1515
2261
|
return
|
|
1516
2262
|
}
|
|
2263
|
+
await requireTosReaccept({ scope: 'routine', subject: 'routine:add', action: 'routine add' })
|
|
1517
2264
|
const spec = JSON.parse(readFileSync(arg, 'utf8'))
|
|
1518
2265
|
const routine = ledger.addRoutine({
|
|
1519
2266
|
name: spec.name,
|
|
@@ -1545,6 +2292,7 @@ function routine(sub, arg, arg2) {
|
|
|
1545
2292
|
process.exitCode = 1
|
|
1546
2293
|
return
|
|
1547
2294
|
}
|
|
2295
|
+
await requireTosReaccept({ scope: 'routine', subject: `routine:${arg}`, action: 'routine patch' })
|
|
1548
2296
|
const changes = JSON.parse(readFileSync(arg2, 'utf8'))
|
|
1549
2297
|
const patch = ledger.proposeRoutinePatch(arg, changes)
|
|
1550
2298
|
saveLedger(ledger)
|
|
@@ -1556,6 +2304,7 @@ function routine(sub, arg, arg2) {
|
|
|
1556
2304
|
if (!arg) { console.error('usage: advisers routine check <id>'); process.exitCode = 1; return }
|
|
1557
2305
|
const routine = ledger.listRoutines().find((r) => r.id === arg)
|
|
1558
2306
|
if (!routine) { console.error(`unknown routine: ${arg}`); process.exitCode = 1; return }
|
|
2307
|
+
const { checkRoutine } = await loadRoutine()
|
|
1559
2308
|
const result = checkRoutine(routine)
|
|
1560
2309
|
for (const item of result.results) console.log(`${item.ok ? 'ok' : 'FAIL'}\t${item.kind}\t${item.entry}`)
|
|
1561
2310
|
if (!result.ok) process.exitCode = 1
|
|
@@ -1574,6 +2323,7 @@ function routine(sub, arg, arg2) {
|
|
|
1574
2323
|
}
|
|
1575
2324
|
if (sub === 'curate') {
|
|
1576
2325
|
const apply = arg === '--apply'
|
|
2326
|
+
if (apply) await requireTosReaccept({ scope: 'routine', subject: 'routine:curate', action: 'routine curate --apply' })
|
|
1577
2327
|
const now = Date.now()
|
|
1578
2328
|
let changed = 0
|
|
1579
2329
|
for (const r of ledger.listRoutines().filter((x) => x.status === 'active')) {
|
|
@@ -1592,6 +2342,7 @@ function routine(sub, arg, arg2) {
|
|
|
1592
2342
|
}
|
|
1593
2343
|
if (sub === 'restore') {
|
|
1594
2344
|
if (!arg) { console.error('usage: advisers routine restore <id>'); process.exitCode = 1; return }
|
|
2345
|
+
await requireTosReaccept({ scope: 'routine', subject: `routine:${arg}`, action: 'routine restore' })
|
|
1595
2346
|
const r = ledger.restoreRoutine(arg)
|
|
1596
2347
|
saveLedger(ledger)
|
|
1597
2348
|
console.log(`restored to draft: ${r.id}`)
|
|
@@ -1599,6 +2350,7 @@ function routine(sub, arg, arg2) {
|
|
|
1599
2350
|
}
|
|
1600
2351
|
if (sub === 'revert') {
|
|
1601
2352
|
if (!arg) { console.error('usage: advisers routine revert <patch-id>'); process.exitCode = 1; return }
|
|
2353
|
+
await requireTosReaccept({ scope: 'routine', subject: `routine:${arg}`, action: 'routine revert' })
|
|
1602
2354
|
const patch = ledger.revertRoutinePatch(arg)
|
|
1603
2355
|
saveLedger(ledger)
|
|
1604
2356
|
console.log(`rolled_back: ${patch.id}`)
|
|
@@ -1611,11 +2363,13 @@ function routine(sub, arg, arg2) {
|
|
|
1611
2363
|
return
|
|
1612
2364
|
}
|
|
1613
2365
|
if (sub === 'apply') {
|
|
2366
|
+
await requireTosReaccept({ scope: 'routine', subject: `routine:${arg}`, action: 'routine apply' })
|
|
1614
2367
|
const pending = ledger.listRoutinePatches('pending').find((p) => p.id === arg)
|
|
1615
2368
|
if (!pending) { console.error(`unknown or closed routine patch: ${arg}`); process.exitCode = 1; return }
|
|
1616
2369
|
const routine = ledger.listRoutines().find((r) => r.id === pending.routineId)
|
|
1617
2370
|
if (!routine) { console.error(`unknown routine: ${pending.routineId}`); process.exitCode = 1; return }
|
|
1618
2371
|
const candidate = { ...routine, ...pending.changes }
|
|
2372
|
+
const { checkRoutine } = await loadRoutine()
|
|
1619
2373
|
const check = checkRoutine(candidate)
|
|
1620
2374
|
if (!check.ok) {
|
|
1621
2375
|
console.error('routine checks failed; patch not applied')
|
|
@@ -1635,6 +2389,7 @@ function routine(sub, arg, arg2) {
|
|
|
1635
2389
|
process.exitCode = 1
|
|
1636
2390
|
return
|
|
1637
2391
|
}
|
|
2392
|
+
await requireTosReaccept({ scope: 'routine', subject: `routine:${arg}`, action: `routine ${sub}` })
|
|
1638
2393
|
const routine = sub === 'approve' ? ledger.approveRoutine(arg) : ledger.archiveRoutine(arg)
|
|
1639
2394
|
saveLedger(ledger)
|
|
1640
2395
|
console.log(`${routine.status}: ${routine.id}`)
|
|
@@ -1706,10 +2461,14 @@ async function documentReview(args) {
|
|
|
1706
2461
|
if (!file) { console.error('usage: advisers review <file> --request "..."'); process.exitCode = 1; return }
|
|
1707
2462
|
const apiKey = process.env.ADVISERS_API_KEY
|
|
1708
2463
|
if (!apiKey) { console.error('document review requires ADVISERS_API_KEY'); process.exitCode = 1; return }
|
|
2464
|
+
const reviewLedger = loadLedger()
|
|
2465
|
+
const reviewDenied = egressDeniedReason(reviewLedger.getMatter(activeMatterId(reviewLedger)), 'review')
|
|
2466
|
+
if (reviewDenied) { console.error(reviewDenied); process.exitCode = 1; return }
|
|
1709
2467
|
let mod
|
|
1710
2468
|
if (process.env.ADVISERS_OFFICE_LOCAL === '1') mod = await import('../../office/dist/index.js')
|
|
1711
2469
|
else { try { mod = await import('advisers-office') } catch { mod = await import('../../office/dist/index.js') } }
|
|
1712
2470
|
const doc = await mod.readOffice(readFileSync(file))
|
|
2471
|
+
const { reviewDocument } = await loadDocReview()
|
|
1713
2472
|
const result = await reviewDocument({ text: mod.officeToText(doc, 20_000), request: flags.request, apiKey, baseUrl: process.env.ADVISERS_BASE_URL, model: process.env.ADVISERS_MODEL })
|
|
1714
2473
|
dbStore()?.appendAudit({ actor: 'local', action: 'doc.review', allowed: !result.findings.some((f) => f.severity === 'blocker'), reason: file })
|
|
1715
2474
|
console.log(result.summary || '(no summary)')
|
|
@@ -1730,7 +2489,20 @@ async function research(args) {
|
|
|
1730
2489
|
const matterId = activeMatterId(ledger)
|
|
1731
2490
|
const denied = egressDeniedReason(ledger.getMatter(matterId), 'research')
|
|
1732
2491
|
if (denied) { console.error(denied); process.exitCode = 1; return }
|
|
1733
|
-
|
|
2492
|
+
// Privacy audit P1-2: the library already redacts upstream bodies, but the CLI
|
|
2493
|
+
// must not print stacks/upstream text either. Print only stable status + code.
|
|
2494
|
+
let result
|
|
2495
|
+
try {
|
|
2496
|
+
const { research: runResearch } = await loadResearch()
|
|
2497
|
+
result = await runResearch({ query, urls, apiKey, baseUrl: process.env.ADVISERS_BASE_URL, deep: Boolean(flags.deep) })
|
|
2498
|
+
} catch (error) {
|
|
2499
|
+
const status = Number.isFinite(Number(error?.status)) ? `HTTP ${Number(error.status)} ` : ''
|
|
2500
|
+
const rawCode = String(error?.code ?? error?.name ?? 'RESEARCH_FAILED').toUpperCase().replace(/[^A-Z0-9_-]/g, '').slice(0, 40)
|
|
2501
|
+
console.error(`research failed: ${status}(${rawCode || 'RESEARCH_FAILED'})`)
|
|
2502
|
+
console.error('Upstream response bodies and stack traces are not printed. Check ADVISERS_API_KEY, ADVISERS_BASE_URL and the network, then run `advisers doctor`.')
|
|
2503
|
+
process.exitCode = 1
|
|
2504
|
+
return
|
|
2505
|
+
}
|
|
1734
2506
|
const store = dbStore()
|
|
1735
2507
|
store?.addResearchRun({ matterId, query: query || urls[0], answer: result.answer, sources: result.sources, usage: result.usage, stopReason: result.stopReason })
|
|
1736
2508
|
store?.appendAudit({ actor: 'local', action: 'egress.research', allowed: true, reason: `${urls.length ? 'url' : 'search'}:${result.sources.length}` })
|
|
@@ -1742,21 +2514,51 @@ async function research(args) {
|
|
|
1742
2514
|
}
|
|
1743
2515
|
}
|
|
1744
2516
|
|
|
1745
|
-
|
|
2517
|
+
/**
|
|
2518
|
+
* Source v2 write path (docs/SOURCE-SCHEMA.md).
|
|
2519
|
+
*
|
|
2520
|
+
* normalizeSource() maps v1/ad-hoc provenance (email -> mail, sessionId/turnId ->
|
|
2521
|
+
* ref, speakers -> speaker, file path -> basename) and preserves unknown fields
|
|
2522
|
+
* as extensions; validateSource() rejects a source with no real pointer and no
|
|
2523
|
+
* quote, so an invented provenance row is never written. A plain capture without
|
|
2524
|
+
* import metadata uses type "conversation" plus the local turn reference.
|
|
2525
|
+
*/
|
|
2526
|
+
async function buildCaptureSource({ meta, quote, ref, capturedAt }) {
|
|
2527
|
+
const { normalizeSource, validateSource } = await loadSource()
|
|
2528
|
+
const raw = { ...(meta && typeof meta === 'object' ? meta : {}) }
|
|
2529
|
+
raw.type = raw.type ?? 'conversation'
|
|
2530
|
+
if (quote) raw.quote = quote
|
|
2531
|
+
if (ref) raw.ref = ref
|
|
2532
|
+
if (!raw.capturedAt) raw.capturedAt = capturedAt
|
|
2533
|
+
const checked = validateSource(raw)
|
|
2534
|
+
if (!checked.ok) throw new Error(`invalid source: ${checked.errors.join('; ')}`)
|
|
2535
|
+
return normalizeSource(raw)
|
|
2536
|
+
}
|
|
2537
|
+
|
|
2538
|
+
/**
|
|
2539
|
+
* Run the capture model and persist pending candidates (never auto-accept).
|
|
2540
|
+
* @returns {Promise<{count: number, candidates: object[]}>}
|
|
2541
|
+
*/
|
|
2542
|
+
async function proposeCaptureText({ text, source = 'wechat', date, matterId, meta = {}, store, json = false }) {
|
|
2543
|
+
const { captureCandidates } = await loadCapture()
|
|
1746
2544
|
const result = await captureCandidates({ text, apiKey: process.env.ADVISERS_API_KEY, baseUrl: process.env.ADVISERS_BASE_URL, model: process.env.ADVISERS_MODEL, date, source })
|
|
1747
|
-
if (!result.candidates.length) return 0
|
|
2545
|
+
if (!result.candidates.length) return { count: 0, candidates: [] }
|
|
1748
2546
|
const conversationId = latestConversationId()
|
|
1749
2547
|
const turn = store.addTurn({ conversationId, role: 'user', content: text })
|
|
2548
|
+
const capturedAt = new Date().toISOString()
|
|
2549
|
+
const created = []
|
|
1750
2550
|
for (const c of result.candidates) {
|
|
2551
|
+
const evidenceSource = await buildCaptureSource({ meta, quote: c.quote, ref: `${conversationId}#${turn.id}`, capturedAt })
|
|
1751
2552
|
const candidate = store.proposeCandidate({
|
|
1752
2553
|
kind: 'commitment',
|
|
1753
2554
|
payload: { matterId, debtor: c.debtor === 'third' ? 'third' : 'user', creditor: c.creditor || 'someone', action: c.action, dueAt: c.dueAt, capability: 'none' },
|
|
1754
|
-
evidence: [{ quote: c.quote, turnId: turn.id, sessionId: conversationId, source:
|
|
2555
|
+
evidence: [{ quote: c.quote, turnId: turn.id, sessionId: conversationId, source: evidenceSource }],
|
|
1755
2556
|
})
|
|
1756
|
-
|
|
2557
|
+
created.push(candidate)
|
|
2558
|
+
if (!json) console.log(`${candidate.id}\t${c.modal}\t${c.action}${c.dueAt ? ` · ${c.dueAt.slice(0, 10)}` : ''}\t「${c.quote.slice(0, 60)}」`)
|
|
1757
2559
|
}
|
|
1758
|
-
store.appendAudit({ actor: 'local', action: 'capture.propose', allowed: true, reason: `${
|
|
1759
|
-
return
|
|
2560
|
+
store.appendAudit({ actor: 'local', action: 'capture.propose', allowed: true, reason: `${created.length} candidates` })
|
|
2561
|
+
return { count: created.length, candidates: created }
|
|
1760
2562
|
}
|
|
1761
2563
|
|
|
1762
2564
|
async function capture(args) {
|
|
@@ -1767,6 +2569,7 @@ async function capture(args) {
|
|
|
1767
2569
|
let text = positional.join(' ').trim()
|
|
1768
2570
|
if (flags.file) {
|
|
1769
2571
|
try {
|
|
2572
|
+
const { extractAttachment } = await loadAttachments()
|
|
1770
2573
|
const extracted = await extractAttachment(flags.file, { cwd: process.cwd() })
|
|
1771
2574
|
if (!extracted.text) throw new Error('no extractable text')
|
|
1772
2575
|
text = extracted.text
|
|
@@ -1783,8 +2586,12 @@ async function capture(args) {
|
|
|
1783
2586
|
const denied = egressDeniedReason(ledger.getMatter(matterId), 'capture')
|
|
1784
2587
|
if (denied) { console.error(denied); process.exitCode = 1; return }
|
|
1785
2588
|
saveLedger(ledger)
|
|
1786
|
-
const
|
|
1787
|
-
if (
|
|
2589
|
+
const result = await proposeCaptureText({ text, source: flags.source, date: flags.date, matterId, store, json: flags.json === true })
|
|
2590
|
+
if (flags.json) {
|
|
2591
|
+
console.log(JSON.stringify({ ok: true, command: 'capture', source: typeof flags.source === 'string' ? flags.source : 'wechat', count: result.count, candidates: result.candidates }, null, 2))
|
|
2592
|
+
return
|
|
2593
|
+
}
|
|
2594
|
+
if (!result.count) console.log('没有找到可确认的承诺候选。')
|
|
1788
2595
|
else console.log('确认:advisers memory accept <id>;拒绝:advisers memory reject <id>')
|
|
1789
2596
|
}
|
|
1790
2597
|
|
|
@@ -1806,13 +2613,15 @@ async function captureFromMail(flags) {
|
|
|
1806
2613
|
const denied = egressDeniedReason(ledger.getMatter(matterId), 'mail')
|
|
1807
2614
|
if (denied) { console.error(denied); process.exitCode = 1; return }
|
|
1808
2615
|
saveLedger(ledger)
|
|
2616
|
+
const { parseMbox, parseEml, dedupeKey, toCaptureInput } = await loadImporters()
|
|
1809
2617
|
let files = []
|
|
1810
2618
|
try {
|
|
1811
2619
|
const info = statSync(target)
|
|
1812
2620
|
files = info.isDirectory() ? readdirSync(target).filter((f) => /\.(eml|mbox)$/i.test(f)).map((f) => join(target, f)) : [target]
|
|
1813
2621
|
} catch (error) { console.error(`cannot read mail path: ${error.message}`); process.exitCode = 1; return }
|
|
1814
2622
|
const limit = Math.max(1, Math.min(200, Number(flags.limit) || 20))
|
|
1815
|
-
let seen = 0, skipped = 0, failed = 0
|
|
2623
|
+
let seen = 0, skipped = 0, failed = 0
|
|
2624
|
+
const created = []
|
|
1816
2625
|
for (const file of files.slice(0, limit)) {
|
|
1817
2626
|
let messages = []
|
|
1818
2627
|
try {
|
|
@@ -1826,17 +2635,21 @@ async function captureFromMail(flags) {
|
|
|
1826
2635
|
const input = toCaptureInput(msg, { source: 'email' })
|
|
1827
2636
|
if (!input.text.trim()) { skipped++; continue }
|
|
1828
2637
|
try {
|
|
1829
|
-
const
|
|
1830
|
-
text: input.text, source: 'email', date: parseEmailDate(msg.date), matterId, store,
|
|
2638
|
+
const result = await proposeCaptureText({
|
|
2639
|
+
text: input.text, source: 'email', date: parseEmailDate(msg.date), matterId, store, json: flags.json === true,
|
|
1831
2640
|
meta: { type: 'mail', messageId: msg.messageId, subject: msg.subject, from: msg.from },
|
|
1832
2641
|
})
|
|
1833
|
-
candidates
|
|
2642
|
+
created.push(...result.candidates)
|
|
1834
2643
|
store.markSeen('import', 'mail', key)
|
|
1835
2644
|
} catch (error) { failed++; console.error(`${msg.messageId || file}: ${error.message}`) }
|
|
1836
2645
|
}
|
|
1837
2646
|
}
|
|
1838
|
-
store.appendAudit({ actor: 'local', action: 'import.mail', allowed: true, reason: `${seen} seen, ${
|
|
1839
|
-
|
|
2647
|
+
store.appendAudit({ actor: 'local', action: 'import.mail', allowed: true, reason: `${seen} seen, ${created.length} candidates, ${failed} failed` })
|
|
2648
|
+
if (flags.json) {
|
|
2649
|
+
console.log(JSON.stringify({ ok: true, command: 'capture --from-mail', seen, skipped, failed, count: created.length, candidates: created }, null, 2))
|
|
2650
|
+
return
|
|
2651
|
+
}
|
|
2652
|
+
console.log(`mail import: ${seen} messages, ${created.length} candidates, ${skipped} skipped, ${failed} failed`)
|
|
1840
2653
|
}
|
|
1841
2654
|
|
|
1842
2655
|
async function captureFromTranscript(flags) {
|
|
@@ -1851,19 +2664,28 @@ async function captureFromTranscript(flags) {
|
|
|
1851
2664
|
const denied = egressDeniedReason(ledger.getMatter(matterId), 'transcript')
|
|
1852
2665
|
if (denied) { console.error(denied); process.exitCode = 1; return }
|
|
1853
2666
|
saveLedger(ledger)
|
|
2667
|
+
const { parseTranscript, dedupeKey, toCaptureInput } = await loadImporters()
|
|
1854
2668
|
let parsed
|
|
1855
2669
|
try { parsed = parseTranscript(readFileSync(file, 'utf8')) } catch (error) { console.error(`cannot parse transcript: ${error.message}`); process.exitCode = 1; return }
|
|
1856
2670
|
const key = dedupeKey('transcript', parsed)
|
|
1857
|
-
if (store.hasSeen('import', 'transcript', key, 30)) {
|
|
2671
|
+
if (store.hasSeen('import', 'transcript', key, 30)) {
|
|
2672
|
+
if (flags.json) { console.log(JSON.stringify({ ok: true, command: 'capture --from-transcript', alreadyImported: true, count: 0, candidates: [] }, null, 2)); return }
|
|
2673
|
+
console.log('transcript already imported')
|
|
2674
|
+
return
|
|
2675
|
+
}
|
|
1858
2676
|
const input = toCaptureInput(parsed, { source: 'meeting' })
|
|
1859
2677
|
if (!input.text.trim()) { console.error('transcript has no text'); process.exitCode = 1; return }
|
|
1860
|
-
const
|
|
1861
|
-
text: input.text, source: 'meeting', matterId, store,
|
|
2678
|
+
const result = await proposeCaptureText({
|
|
2679
|
+
text: input.text, source: 'meeting', matterId, store, json: flags.json === true,
|
|
1862
2680
|
meta: { type: 'transcript', file: basename(file), speakers: input.meta?.speakers ?? [] },
|
|
1863
2681
|
})
|
|
1864
2682
|
store.markSeen('import', 'transcript', key)
|
|
1865
|
-
store.appendAudit({ actor: 'local', action: 'import.transcript', allowed: true, reason: `${
|
|
1866
|
-
|
|
2683
|
+
store.appendAudit({ actor: 'local', action: 'import.transcript', allowed: true, reason: `${result.count} candidates` })
|
|
2684
|
+
if (flags.json) {
|
|
2685
|
+
console.log(JSON.stringify({ ok: true, command: 'capture --from-transcript', count: result.count, candidates: result.candidates }, null, 2))
|
|
2686
|
+
return
|
|
2687
|
+
}
|
|
2688
|
+
console.log(`transcript import: ${result.count} candidates`)
|
|
1867
2689
|
}
|
|
1868
2690
|
|
|
1869
2691
|
async function captureFromImap(flags) {
|
|
@@ -1879,8 +2701,10 @@ async function captureFromImap(flags) {
|
|
|
1879
2701
|
const denied = egressDeniedReason(ledger.getMatter(matterId), 'imap')
|
|
1880
2702
|
if (denied) { console.error(denied); process.exitCode = 1; return }
|
|
1881
2703
|
saveLedger(ledger)
|
|
2704
|
+
const { parseEml, dedupeKey, toCaptureInput } = await loadImporters()
|
|
1882
2705
|
let messages
|
|
1883
2706
|
try {
|
|
2707
|
+
const { fetchImapMessages } = await loadImap()
|
|
1884
2708
|
messages = await fetchImapMessages({
|
|
1885
2709
|
host,
|
|
1886
2710
|
port: Number(process.env.ADVISERS_IMAP_PORT) || (String(process.env.ADVISERS_IMAP_SECURE) === '0' ? 143 : 993),
|
|
@@ -1891,7 +2715,8 @@ async function captureFromImap(flags) {
|
|
|
1891
2715
|
limit: Math.max(1, Math.min(100, Number(flags.limit) || 20)),
|
|
1892
2716
|
})
|
|
1893
2717
|
} catch (error) { console.error(`imap failed: ${error.message}`); process.exitCode = 1; return }
|
|
1894
|
-
let seen = 0, skipped = 0, failed = 0
|
|
2718
|
+
let seen = 0, skipped = 0, failed = 0
|
|
2719
|
+
const created = []
|
|
1895
2720
|
for (const msg of messages) {
|
|
1896
2721
|
seen++
|
|
1897
2722
|
let parsed
|
|
@@ -1901,16 +2726,20 @@ async function captureFromImap(flags) {
|
|
|
1901
2726
|
const input = toCaptureInput(parsed, { source: 'email' })
|
|
1902
2727
|
if (!input.text.trim()) { skipped++; continue }
|
|
1903
2728
|
try {
|
|
1904
|
-
const
|
|
1905
|
-
candidates
|
|
2729
|
+
const result = await proposeCaptureText({ text: input.text, source: 'email', date: parseEmailDate(parsed.date), matterId, store, json: flags.json === true, meta: { type: 'mail', channel: 'imap', uid: msg.uid, messageId: parsed.messageId, subject: parsed.subject, from: parsed.from } })
|
|
2730
|
+
created.push(...result.candidates)
|
|
1906
2731
|
store.markSeen('import', 'imap', key)
|
|
1907
2732
|
} catch (error) { failed++; console.error(`imap message ${msg.uid}: ${error.message}`) }
|
|
1908
2733
|
}
|
|
1909
|
-
store.appendAudit({ actor: 'local', action: 'import.imap', allowed: true, reason: `${seen} seen, ${
|
|
1910
|
-
|
|
2734
|
+
store.appendAudit({ actor: 'local', action: 'import.imap', allowed: true, reason: `${seen} seen, ${created.length} candidates, ${failed} failed` })
|
|
2735
|
+
if (flags.json) {
|
|
2736
|
+
console.log(JSON.stringify({ ok: true, command: 'capture --from-imap', seen, skipped, failed, count: created.length, candidates: created }, null, 2))
|
|
2737
|
+
return
|
|
2738
|
+
}
|
|
2739
|
+
console.log(`imap import: ${seen} messages, ${created.length} candidates, ${skipped} skipped, ${failed} failed (EXAMINE/read-only)`)
|
|
1911
2740
|
}
|
|
1912
2741
|
|
|
1913
|
-
function calendarImport(args) {
|
|
2742
|
+
async function calendarImport(args) {
|
|
1914
2743
|
const { flags, positional } = parseFlags(args)
|
|
1915
2744
|
const file = typeof flags.ics === 'string' ? flags.ics : positional[0]
|
|
1916
2745
|
if (!file) { console.error('usage: advisers calendar import --ics <file>'); process.exitCode = 1; return }
|
|
@@ -1921,7 +2750,10 @@ function calendarImport(args) {
|
|
|
1921
2750
|
const denied = egressDeniedReason(ledger.getMatter(matterId), 'calendar')
|
|
1922
2751
|
if (denied) { console.error(denied); process.exitCode = 1; return }
|
|
1923
2752
|
let events
|
|
1924
|
-
try {
|
|
2753
|
+
try {
|
|
2754
|
+
const { parseIcs } = await loadImporters()
|
|
2755
|
+
events = parseIcs(readFileSync(file, 'utf8'))
|
|
2756
|
+
} catch (error) { console.error(`cannot parse ics: ${error.message}`); process.exitCode = 1; return }
|
|
1925
2757
|
let imported = 0
|
|
1926
2758
|
for (const e of events) {
|
|
1927
2759
|
if (!e.uid) continue
|
|
@@ -1932,21 +2764,65 @@ function calendarImport(args) {
|
|
|
1932
2764
|
console.log(`calendar import: ${imported} events (read-only)`)
|
|
1933
2765
|
}
|
|
1934
2766
|
|
|
1935
|
-
|
|
2767
|
+
/**
|
|
2768
|
+
* Read-only expansion of the stored calendar rows into the occurrences that
|
|
2769
|
+
* start today (Asia/Shanghai). expandRrule() is pure and bounded; an
|
|
2770
|
+
* unsupported/malformed RRULE falls back to the stored DTSTART occurrence, so a
|
|
2771
|
+
* bad rule never hides a real meeting.
|
|
2772
|
+
*/
|
|
2773
|
+
async function calendarOccurrencesToday() {
|
|
1936
2774
|
const store = dbStore()
|
|
1937
|
-
|
|
1938
|
-
|
|
1939
|
-
const
|
|
1940
|
-
|
|
2775
|
+
const localDay = localDayOf(Date.now())
|
|
2776
|
+
if (!store) return { localDay, occurrences: [] }
|
|
2777
|
+
const { expandRrule } = await loadIcal()
|
|
2778
|
+
const occurrences = []
|
|
2779
|
+
for (const row of store.listCalendarEvents()) {
|
|
2780
|
+
let instances
|
|
2781
|
+
try { instances = expandRrule(row, { from: localDay, to: localDay }) } catch { instances = [] }
|
|
2782
|
+
for (const instance of instances) {
|
|
2783
|
+
occurrences.push({
|
|
2784
|
+
uid: instance.uid,
|
|
2785
|
+
summary: instance.summary ?? '',
|
|
2786
|
+
startsAt: instance.startsAt,
|
|
2787
|
+
endsAt: instance.endsAt ?? null,
|
|
2788
|
+
allDay: Boolean(instance.allDay),
|
|
2789
|
+
recurring: Boolean(instance.recurring),
|
|
2790
|
+
location: instance.location ?? null,
|
|
2791
|
+
rrule: instance.rrule ?? null,
|
|
2792
|
+
})
|
|
2793
|
+
}
|
|
2794
|
+
}
|
|
2795
|
+
occurrences.sort((a, b) => (a.startsAt < b.startsAt ? -1 : a.startsAt > b.startsAt ? 1 : String(a.summary).localeCompare(String(b.summary))))
|
|
2796
|
+
return { localDay, occurrences }
|
|
2797
|
+
}
|
|
2798
|
+
|
|
2799
|
+
async function printCalendarToday() {
|
|
2800
|
+
const { localDay, occurrences } = await calendarOccurrencesToday()
|
|
2801
|
+
if (!occurrences.length) { console.log('日历:今天没有本地导入的会议。'); return }
|
|
1941
2802
|
console.log(`日历(本地只读,${localDay}):`)
|
|
1942
|
-
for (const e of
|
|
2803
|
+
for (const e of occurrences) {
|
|
2804
|
+
const time = e.allDay ? '全天' : e.startsAt.slice(11, 16)
|
|
2805
|
+
console.log(` ${time} ${e.summary}${e.recurring ? '(循环)' : ''}${e.location ? ` · ${e.location}` : ''}`)
|
|
2806
|
+
}
|
|
2807
|
+
}
|
|
2808
|
+
|
|
2809
|
+
/** Host header allowlist for the local read-only UI (DNS-rebinding hardening, SEC2-07). */
|
|
2810
|
+
function isLoopbackHostHeader(host) {
|
|
2811
|
+
if (!host) return false
|
|
2812
|
+
const value = String(host).trim().toLowerCase()
|
|
2813
|
+
const bare = value.startsWith('[')
|
|
2814
|
+
? value.replace(/^\[([^\]]+)\](?::\d+)?$/, '$1')
|
|
2815
|
+
: value.replace(/:\d+$/, '')
|
|
2816
|
+
return bare === '127.0.0.1' || bare === 'localhost' || bare === '::1'
|
|
1943
2817
|
}
|
|
1944
2818
|
|
|
1945
2819
|
async function ui(args) {
|
|
1946
2820
|
const flags = parseFlags(args).flags
|
|
1947
|
-
|
|
2821
|
+
// --port 0 requests an ephemeral port (used by tests and scripts).
|
|
2822
|
+
const port = typeof flags.port === 'string' && flags.port.trim() !== '' ? Number(flags.port) : 17860
|
|
1948
2823
|
const ledger = loadLedger()
|
|
1949
2824
|
const store = dbStore()
|
|
2825
|
+
const { buildReminders } = await loadRemind()
|
|
1950
2826
|
const snapshot = {
|
|
1951
2827
|
today: () => {
|
|
1952
2828
|
const open = ledger.openCommitments()
|
|
@@ -1956,7 +2832,20 @@ async function ui(args) {
|
|
|
1956
2832
|
who: () => ({ mine: ledger.openCommitments().filter((c) => c.debtor === 'user' || c.debtor === 'agent'), waiting: ledger.openCommitments().filter((c) => c.debtor === 'third' || c.debtor.startsWith('third:')) }),
|
|
1957
2833
|
reminders: () => buildReminders(ledger, { now: new Date() }),
|
|
1958
2834
|
}
|
|
2835
|
+
const { createReadOnlyServer } = await loadUi()
|
|
1959
2836
|
const app = createReadOnlyServer({ snapshot, port })
|
|
2837
|
+
// SEC2-07: DNS rebinding can point an attacker origin at 127.0.0.1; the
|
|
2838
|
+
// library only checks method=GET, so validate Host before its handler runs.
|
|
2839
|
+
const handlers = app.server.listeners('request').slice()
|
|
2840
|
+
app.server.removeAllListeners('request')
|
|
2841
|
+
app.server.on('request', (req, res) => {
|
|
2842
|
+
if (!isLoopbackHostHeader(req.headers.host)) {
|
|
2843
|
+
res.writeHead(403, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store', 'x-content-type-options': 'nosniff' })
|
|
2844
|
+
res.end(JSON.stringify({ error: 'forbidden host header' }))
|
|
2845
|
+
return
|
|
2846
|
+
}
|
|
2847
|
+
for (const handler of handlers) handler.call(app.server, req, res)
|
|
2848
|
+
})
|
|
1960
2849
|
const url = await app.listen()
|
|
1961
2850
|
console.log(`advisers ui (read-only): ${url}`)
|
|
1962
2851
|
console.log('Ctrl-C to stop; no writes, no telemetry, 127.0.0.1 only.')
|
|
@@ -1969,22 +2858,48 @@ async function remind(args) {
|
|
|
1969
2858
|
ensureHome()
|
|
1970
2859
|
const store = dbStore()
|
|
1971
2860
|
const ledger = loadLedger()
|
|
2861
|
+
const scheduler = await loadScheduler()
|
|
1972
2862
|
const sub = positional[0]
|
|
2863
|
+
const apply = flags.apply === true
|
|
1973
2864
|
if (sub === 'install' || flags.install) {
|
|
1974
2865
|
const dir = join(HOME, 'scheduler')
|
|
1975
2866
|
mkdirSync(dir, { recursive: true, mode: 0o700 })
|
|
1976
2867
|
const nodeBin = process.execPath
|
|
1977
2868
|
const cli = process.argv[1]
|
|
1978
|
-
writeFileSync(join(dir, 'remind.sh'),
|
|
1979
|
-
writeFileSync(join(dir, 'remind.ps1'),
|
|
2869
|
+
writeFileSync(join(dir, 'remind.sh'), '#!/bin/sh\n"' + nodeBin + '" "' + cli + '" remind --deliver --notify >> "' + join(HOME, 'reminders.log') + '" 2>&1\n', { mode: 0o700 })
|
|
2870
|
+
writeFileSync(join(dir, 'remind.ps1'), '& "' + nodeBin + '" "' + cli + '" remind --deliver --notify *>> "' + join(HOME, 'reminders.log') + '"\n', { mode: 0o700 })
|
|
1980
2871
|
writeFileSync(join(dir, 'README.txt'), 'Install one of these user-level schedules (opt-in):\nLinux: systemd --user timer or cron: 0 9 * * * sh ' + join(dir, 'remind.sh') + '\nWindows: Task Scheduler -> run remind.ps1 daily\nOr import ~/.advisers/reminders.ics into your calendar.\n')
|
|
1981
2872
|
store?.appendAudit({ actor: 'local', action: 'notify.install', allowed: true, reason: dir })
|
|
1982
|
-
console.log(
|
|
2873
|
+
console.log('scheduler scripts written: ' + dir)
|
|
1983
2874
|
console.log('opt-in: import ~/.advisers/reminders.ics, or register remind.sh/.ps1 with your OS scheduler.')
|
|
2875
|
+
const command = scheduler.buildCronCommand({ nodeBin, cliPath: cli })
|
|
2876
|
+
const schedule = typeof flags.schedule === 'string' ? flags.schedule : scheduler.DEFAULT_CRON_SCHEDULE
|
|
2877
|
+
const time = typeof flags.time === 'string' ? flags.time : scheduler.DEFAULT_TASK_TIME
|
|
2878
|
+
const existing = apply ? await readCrontabText() : { ok: false }
|
|
2879
|
+
const plan = scheduler.planScheduler({
|
|
2880
|
+
platform: process.platform,
|
|
2881
|
+
action: 'install',
|
|
2882
|
+
dryRun: !apply,
|
|
2883
|
+
command,
|
|
2884
|
+
schedule,
|
|
2885
|
+
time,
|
|
2886
|
+
...(existing.ok ? { existingText: existing.text } : {}),
|
|
2887
|
+
})
|
|
2888
|
+
console.log('schedule: ' + (plan.platform === 'win32' ? plan.taskName + ' daily ' + plan.time : plan.schedule))
|
|
2889
|
+
console.log('command: ' + command)
|
|
2890
|
+
await applySchedulerPlan(plan, { apply })
|
|
1984
2891
|
return
|
|
1985
2892
|
}
|
|
1986
2893
|
if (sub === 'uninstall' || flags.uninstall) {
|
|
1987
2894
|
const dir = join(HOME, 'scheduler')
|
|
2895
|
+
const existing = await readCrontabText()
|
|
2896
|
+
const plan = scheduler.planScheduler({
|
|
2897
|
+
platform: process.platform,
|
|
2898
|
+
action: 'uninstall',
|
|
2899
|
+
dryRun: !apply,
|
|
2900
|
+
...(existing.ok ? { existingText: existing.text } : {}),
|
|
2901
|
+
})
|
|
2902
|
+
await applySchedulerPlan(plan, { apply })
|
|
1988
2903
|
if (existsSync(dir)) rmSync(dir, { recursive: true, force: true })
|
|
1989
2904
|
store?.appendAudit({ actor: 'local', action: 'notify.uninstall', allowed: true, reason: dir })
|
|
1990
2905
|
console.log('scheduler scripts removed (calendar events remain in your calendar app).')
|
|
@@ -1992,13 +2907,31 @@ async function remind(args) {
|
|
|
1992
2907
|
}
|
|
1993
2908
|
if (sub === 'status' || flags.status) {
|
|
1994
2909
|
const dir = join(HOME, 'scheduler')
|
|
1995
|
-
console.log(
|
|
1996
|
-
console.log(
|
|
2910
|
+
console.log('scheduler scripts: ' + (existsSync(dir) ? dir : 'not installed (optional)'))
|
|
2911
|
+
console.log('reminder log: ' + join(HOME, 'reminders.log'))
|
|
2912
|
+
const status = scheduler.readSchedulerStatus({ homeDir: HOME })
|
|
2913
|
+
if (!status.lastRun) console.log('last run: none recorded' + (status.corrupt ? ' (status.json corrupt)' : ''))
|
|
2914
|
+
else console.log('last run: ' + status.lastRun + ' · result=' + (status.lastResult ?? '-') + ' · count=' + (status.lastCount ?? '-') + ' · channel=' + (status.lastChannel ?? '-'))
|
|
2915
|
+
if (process.platform === 'win32') {
|
|
2916
|
+
const plan = scheduler.planWindowsStatus({})
|
|
2917
|
+
console.log('os plan: ' + plan.commands.map((entry) => entry.command + ' ' + entry.args.join(' ')).join('; ') + '(运行该命令;exit 0 表示已注册)')
|
|
2918
|
+
} else if (scheduler.CRON_PLATFORMS.includes(process.platform)) {
|
|
2919
|
+
const existing = await readCrontabText()
|
|
2920
|
+
if (existing.ok) {
|
|
2921
|
+
const plan = scheduler.planCronStatus({ existingText: existing.text })
|
|
2922
|
+
console.log(plan.installed ? 'os plan: installed (' + plan.schedule + ')' : 'os plan: not installed')
|
|
2923
|
+
} else {
|
|
2924
|
+
console.log('os plan: unknown (' + (existing.error ?? 'crontab unavailable') + ')')
|
|
2925
|
+
}
|
|
2926
|
+
} else {
|
|
2927
|
+
console.log('os plan: unsupported platform ' + process.platform)
|
|
2928
|
+
}
|
|
1997
2929
|
return
|
|
1998
2930
|
}
|
|
2931
|
+
const { buildReminders, toIcs } = await loadRemind()
|
|
1999
2932
|
const snoozed = {}
|
|
2000
2933
|
for (const c of ledger.listCommitments()) {
|
|
2001
|
-
const until = store?.getMeta(
|
|
2934
|
+
const until = store?.getMeta('snooze:' + c.id)
|
|
2002
2935
|
if (until) snoozed[c.id] = until
|
|
2003
2936
|
}
|
|
2004
2937
|
const reminders = buildReminders(ledger, { now: new Date(), snoozedUntil: snoozed })
|
|
@@ -2006,23 +2939,102 @@ async function remind(args) {
|
|
|
2006
2939
|
const path = typeof flags.ics === 'string' ? flags.ics : (positional[0] || join(HOME, 'reminders.ics'))
|
|
2007
2940
|
writeFileSync(path, toIcs(reminders, { now: new Date() }), { mode: 0o600 })
|
|
2008
2941
|
store?.appendAudit({ actor: 'local', action: 'notify.ics', allowed: true, reason: basename(path) })
|
|
2009
|
-
console.log(
|
|
2942
|
+
console.log('ics written: ' + path + ' (' + reminders.length + ' events)')
|
|
2010
2943
|
return
|
|
2011
2944
|
}
|
|
2012
2945
|
if (flags.json) { console.log(JSON.stringify({ now: new Date().toISOString(), reminders }, null, 2)); return }
|
|
2013
|
-
if (!reminders.length) {
|
|
2014
|
-
|
|
2946
|
+
if (!reminders.length) {
|
|
2947
|
+
console.log('现在没有到期的提醒。')
|
|
2948
|
+
if (flags.deliver) recordReminderRun(scheduler, { count: 0, channel: 'log' })
|
|
2949
|
+
return
|
|
2950
|
+
}
|
|
2951
|
+
for (const r of reminders) console.log('[' + r.level + '/' + r.bucket + '] ' + r.action + (r.dueAt ? ' · ' + r.dueAt.slice(0, 16) : ''))
|
|
2015
2952
|
if (flags.deliver) {
|
|
2016
|
-
const line =
|
|
2953
|
+
const line = new Date().toISOString() + '\t' + reminders.length + '\t' + reminders.map((r) => r.action).join(';') + '\n'
|
|
2017
2954
|
writeFileSync(join(HOME, 'reminders.log'), line, { flag: 'a', mode: 0o600 })
|
|
2018
2955
|
let channel = 'log'
|
|
2019
2956
|
if (flags.notify) {
|
|
2020
|
-
const
|
|
2021
|
-
|
|
2957
|
+
const notify = await loadNotify()
|
|
2958
|
+
const local = await notify.sendNotification({ title: 'Advisers · 到期提醒', body: reminders.length + ' 条承诺到期或即将到期' })
|
|
2959
|
+
channel = local.sent ? local.channel : 'log-only'
|
|
2960
|
+
const webhook = await notify.sendWebhookNotification(reminders)
|
|
2961
|
+
if (webhook.sent) channel = channel === 'log-only' ? 'webhook' : channel + '+webhook'
|
|
2962
|
+
else if (webhook.configured) console.error('webhook 未发送:' + (webhook.error ?? 'unknown') + (webhook.detail ? '(' + webhook.detail + ')' : ''))
|
|
2963
|
+
}
|
|
2964
|
+
store?.appendAudit({ actor: 'local', action: 'notify.delivered', allowed: true, reason: reminders.length + ' reminders channel=' + channel })
|
|
2965
|
+
recordReminderRun(scheduler, { count: reminders.length, channel })
|
|
2966
|
+
if (flags.notify) console.log('通知通道:' + channel)
|
|
2967
|
+
}
|
|
2968
|
+
return
|
|
2969
|
+
}
|
|
2970
|
+
|
|
2971
|
+
/** Execute one system scheduler command; missing binaries become structured failures. */
|
|
2972
|
+
function runSchedulerCommand(commandPlan, { timeout = 20000 } = {}) {
|
|
2973
|
+
if (!commandPlan || typeof commandPlan.command !== 'string') return { ok: false, error: 'no-command' }
|
|
2974
|
+
const result = spawnSync(commandPlan.command, commandPlan.args ?? [], { input: commandPlan.stdin, encoding: 'utf8', timeout, windowsHide: true })
|
|
2975
|
+
return {
|
|
2976
|
+
ok: !result.error && result.status === 0,
|
|
2977
|
+
status: result.status,
|
|
2978
|
+
stdout: result.stdout ?? '',
|
|
2979
|
+
stderr: result.stderr ?? '',
|
|
2980
|
+
error: result.error ? (result.error.code ?? result.error.message) : undefined,
|
|
2981
|
+
}
|
|
2982
|
+
}
|
|
2983
|
+
|
|
2984
|
+
/** Read the current crontab text; read-only and best-effort (never fails a command). */
|
|
2985
|
+
async function readCrontabText() {
|
|
2986
|
+
const scheduler = await loadScheduler()
|
|
2987
|
+
if (!scheduler.CRON_PLATFORMS.includes(process.platform)) return { ok: false, unsupported: true }
|
|
2988
|
+
const result = runSchedulerCommand(scheduler.crontabReadCommand())
|
|
2989
|
+
if (result.error) return { ok: false, error: result.error }
|
|
2990
|
+
return { ok: true, text: result.ok ? result.stdout : '' }
|
|
2991
|
+
}
|
|
2992
|
+
|
|
2993
|
+
/** Record a successful delivery run in ~/.advisers/scheduler/status.json. */
|
|
2994
|
+
function recordReminderRun(scheduler, { count, channel }) {
|
|
2995
|
+
try {
|
|
2996
|
+
scheduler.recordSchedulerRun({ homeDir: HOME, at: new Date(), result: 'ok', count, channel, dryRun: false })
|
|
2997
|
+
} catch (error) {
|
|
2998
|
+
console.error('scheduler status not recorded: ' + error.message)
|
|
2999
|
+
}
|
|
3000
|
+
}
|
|
3001
|
+
|
|
3002
|
+
/**
|
|
3003
|
+
* Apply (or print) a scheduler plan. The library never runs a system command, so
|
|
3004
|
+
* the CLI is the only place that can: dry-run prints the exact argv/stdin and
|
|
3005
|
+
* only `--apply` executes it.
|
|
3006
|
+
*/
|
|
3007
|
+
async function applySchedulerPlan(plan, { apply = false } = {}) {
|
|
3008
|
+
const commands = Array.isArray(plan.commands) ? plan.commands : []
|
|
3009
|
+
if (!commands.length) {
|
|
3010
|
+
console.log(plan.action === 'uninstall' ? '未发现需要移除的系统调度项。' : '系统调度未变更。')
|
|
3011
|
+
return { applied: false, results: [] }
|
|
3012
|
+
}
|
|
3013
|
+
if (!apply) {
|
|
3014
|
+
console.log('dry-run(默认不执行;加 --apply 才注册/移除系统任务):')
|
|
3015
|
+
for (const command of commands) {
|
|
3016
|
+
if (command.stdin !== undefined) {
|
|
3017
|
+
console.log(' ' + command.command + ' ' + command.args.join(' ') + ' <<EOF')
|
|
3018
|
+
for (const line of String(command.stdin).split('\n')) console.log(' ' + line)
|
|
3019
|
+
console.log(' EOF')
|
|
3020
|
+
} else {
|
|
3021
|
+
console.log(' ' + command.command + ' ' + command.args.join(' '))
|
|
3022
|
+
}
|
|
3023
|
+
}
|
|
3024
|
+
return { applied: false, results: [] }
|
|
3025
|
+
}
|
|
3026
|
+
const results = []
|
|
3027
|
+
for (const command of commands) {
|
|
3028
|
+
const result = runSchedulerCommand(command)
|
|
3029
|
+
results.push({ command: command.command, args: command.args, ...result })
|
|
3030
|
+
if (!result.ok) {
|
|
3031
|
+
console.error('系统调度命令失败:' + command.command + ' ' + command.args.join(' ') + (result.stderr ? '\n' + result.stderr.trim() : '') + (result.error ? ' (' + result.error + ')' : ''))
|
|
3032
|
+
process.exitCode = 1
|
|
3033
|
+
return { applied: false, results }
|
|
2022
3034
|
}
|
|
2023
|
-
store?.appendAudit({ actor: 'local', action: 'notify.delivered', allowed: true, reason: `${reminders.length} reminders channel=${channel}` })
|
|
2024
|
-
if (flags.notify) console.log(`通知通道:${channel}`)
|
|
2025
3035
|
}
|
|
3036
|
+
console.log('已执行 ' + commands.length + ' 个系统调度命令。')
|
|
3037
|
+
return { applied: true, results }
|
|
2026
3038
|
}
|
|
2027
3039
|
|
|
2028
3040
|
async function deliver(args) {
|
|
@@ -2042,23 +3054,37 @@ async function deliver(args) {
|
|
|
2042
3054
|
commitments = [c]
|
|
2043
3055
|
} else commitments = ledger.openCommitments()
|
|
2044
3056
|
if (!commitments.length) { console.error('no commitments to deliver'); process.exitCode = 1; return }
|
|
3057
|
+
// P1-6: a confirmation should not dump an unbounded list of open commitments
|
|
3058
|
+
// into one file (5000 open commitments used to make a 7.8s / 1.57GB PDF).
|
|
3059
|
+
// The default covers the latest/default view; --all is the explicit opt-in
|
|
3060
|
+
// for a full export, and the total is always printed so nothing disappears
|
|
3061
|
+
// silently.
|
|
3062
|
+
const totalOpen = commitments.length
|
|
3063
|
+
const truncated = totalOpen > DELIVER_DEFAULT_LIMIT && flags.all !== true && !flags.commit
|
|
3064
|
+
if (truncated) commitments = commitments.slice(0, DELIVER_DEFAULT_LIMIT)
|
|
3065
|
+
const { sha256Hex } = await loadEvidence()
|
|
2045
3066
|
const label = type === 'weekly' ? '周报' : type === 'statement' ? '对账单' : '确认单'
|
|
2046
|
-
const
|
|
3067
|
+
const scopeLine = truncated
|
|
3068
|
+
? `承诺数:${totalOpen}(本文件只列前 ${commitments.length} 条;用 --all 生成全部)`
|
|
3069
|
+
: `承诺数:${commitments.length}`
|
|
3070
|
+
const sections = [{ heading: label, paragraphs: [`生成时间:${new Date().toISOString()}`, scopeLine] }]
|
|
2047
3071
|
for (const c of commitments) {
|
|
2048
3072
|
sections.push({ heading: c.action, paragraphs: [`对象:${c.creditor}`, `截止:${c.dueAt ?? '未定'}`, `状态:${c.status}`, `证据:${(c.evidence ?? []).length} 条`] })
|
|
2049
3073
|
}
|
|
2050
3074
|
sections.push({ heading: '校验', paragraphs: [`内容哈希:${sha256Hex(JSON.stringify(commitments.map((c) => ({ id: c.id, action: c.action, dueAt: c.dueAt, evidence: c.evidence }))))}`, '本文件由本地账本生成;哈希用于事后比对,不是第三方存证。'] })
|
|
2051
3075
|
try {
|
|
2052
|
-
const mod = process.env.ADVISERS_OFFICE_LOCAL === '1' ? await import('../../office/dist/index.js') : await import('advisers-office')
|
|
2053
3076
|
let buffer
|
|
2054
3077
|
if (format === 'pdf') {
|
|
3078
|
+
const { buildSimplePdf } = await loadPdf()
|
|
2055
3079
|
const lines = commitments.map((c) => `${c.id} ${c.creditor} · ${c.action}${c.dueAt ? ` · 截止 ${c.dueAt}` : ''} · ${c.status}`)
|
|
2056
3080
|
buffer = await buildSimplePdf({ title: `${label} · Advisers`, paragraphs: [`承诺数:${commitments.length}`, ...lines, 'SHA256SUMS/回执说明:本 PDF 为本地账本生成,不是第三方存证。'] })
|
|
2057
3081
|
if (!buffer.subarray(0, 5).equals(Buffer.from('%PDF-'))) throw new Error('pdf builder returned a non-PDF buffer')
|
|
2058
3082
|
await backupCliFile(out)
|
|
2059
3083
|
writeFileSync(out, buffer)
|
|
2060
|
-
recordManualDelivery([out], `deliver:${type}`, label, 'pdf')
|
|
2061
3084
|
} else if (format === 'xlsx') {
|
|
3085
|
+
// P2-3: the office barrel (exceljs + pptxgenjs + read/check) is only paid
|
|
3086
|
+
// on the formats that actually need it; PDF used to import it too.
|
|
3087
|
+
const mod = process.env.ADVISERS_OFFICE_LOCAL === '1' ? await import('../../office/dist/index.js') : await import('advisers-office')
|
|
2062
3088
|
const rows = commitments.map((c) => ({
|
|
2063
3089
|
id: c.id, creditor: c.creditor, action: c.action, due: c.dueAt ?? '',
|
|
2064
3090
|
status: c.status, evidence: (c.evidence ?? []).length,
|
|
@@ -2073,86 +3099,74 @@ async function deliver(args) {
|
|
|
2073
3099
|
await mod.validateOffice(buffer, 'xlsx')
|
|
2074
3100
|
await backupCliFile(out)
|
|
2075
3101
|
writeFileSync(out, buffer)
|
|
2076
|
-
recordManualDelivery([out], `deliver:${type}`, label, 'xlsx')
|
|
2077
3102
|
} else {
|
|
3103
|
+
const mod = process.env.ADVISERS_OFFICE_LOCAL === '1' ? await import('../../office/dist/index.js') : await import('advisers-office')
|
|
2078
3104
|
buffer = await mod.buildDocx({ title: `${label} · Advisers`, sections })
|
|
2079
3105
|
await mod.validateOffice(buffer, 'docx')
|
|
2080
3106
|
await backupCliFile(out)
|
|
2081
3107
|
writeFileSync(out, buffer)
|
|
2082
|
-
recordManualDelivery([out], `deliver:${type}`, label, 'docx')
|
|
2083
3108
|
}
|
|
2084
|
-
|
|
2085
|
-
|
|
2086
|
-
|
|
3109
|
+
// Delivery row + audit row commit together (robustness audit P0-3).
|
|
3110
|
+
recordDeliveryWithAudit({
|
|
3111
|
+
files: [out],
|
|
3112
|
+
tool: `deliver:${type}`,
|
|
3113
|
+
title: label,
|
|
3114
|
+
validation: format,
|
|
3115
|
+
audit: { actor: 'local', action: 'deliver', allowed: true, reason: `${label} ${commitments.length}` },
|
|
3116
|
+
})
|
|
3117
|
+
if (flags.json) console.log(JSON.stringify({ ok: true, out, type, format, commitments: commitments.length, total: totalOpen, truncated }, null, 2))
|
|
3118
|
+
else {
|
|
3119
|
+
console.log(`wrote ${out}`)
|
|
3120
|
+
if (truncated) console.log(`提示:共 ${totalOpen} 条未完成承诺,本文件只生成前 ${commitments.length} 条;用 --all 生成全部。`)
|
|
3121
|
+
}
|
|
2087
3122
|
} catch (error) { console.error(`deliver failed: ${error.message}`); process.exitCode = 1 }
|
|
2088
3123
|
}
|
|
2089
3124
|
|
|
2090
|
-
|
|
2091
|
-
|
|
2092
|
-
|
|
2093
|
-
|
|
2094
|
-
|
|
2095
|
-
|
|
2096
|
-
|
|
2097
|
-
|
|
2098
|
-
|
|
2099
|
-
|
|
2100
|
-
{ name: 'advisers_commit_ls', description: 'List commitments (open by default).', inputSchema: { type: 'object', properties: { all: { type: 'boolean' } } } },
|
|
2101
|
-
{ name: 'advisers_who', description: 'Who owes whom.', inputSchema: { type: 'object', properties: {} } },
|
|
2102
|
-
{ name: 'advisers_evidence', description: 'Read the source turns for a commitment/fact/preference id.', inputSchema: { type: 'object', properties: { id: { type: 'string' } }, required: ['id'] } },
|
|
2103
|
-
{ name: 'advisers_remind', description: 'Read due reminders (no delivery).', inputSchema: { type: 'object', properties: {} } },
|
|
2104
|
-
]
|
|
2105
|
-
}
|
|
2106
|
-
|
|
3125
|
+
/**
|
|
3126
|
+
* `advisers mcp --stdio`: the shipped stdio entry for the MCP server.
|
|
3127
|
+
*
|
|
3128
|
+
* The protocol surface lives in lib/mcp-server.js (7 tools incl. the pending-only
|
|
3129
|
+
* candidate write + read-only pack verification, 4 read-only resources, 1 MiB
|
|
3130
|
+
* line cap, -32601/-32602/-32002/-32700). This wiring only supplies process
|
|
3131
|
+
* state: the home, the store/ledger, the version and the audit sink. Every
|
|
3132
|
+
* tools/call is audited through store.appendAudit; a write whose audit row
|
|
3133
|
+
* cannot be appended fails closed (a created candidate is rolled back).
|
|
3134
|
+
*/
|
|
2107
3135
|
async function mcpServer() {
|
|
2108
3136
|
ensureHome()
|
|
2109
3137
|
const store = dbStore()
|
|
2110
3138
|
const ledger = loadLedger()
|
|
2111
|
-
const
|
|
2112
|
-
|
|
2113
|
-
|
|
2114
|
-
|
|
2115
|
-
|
|
2116
|
-
|
|
2117
|
-
if (method !== 'tools/call') return mcpError(id, -32601, `unknown method: ${method}`)
|
|
2118
|
-
const name = params?.name
|
|
2119
|
-
const args = params?.arguments ?? {}
|
|
2120
|
-
try {
|
|
2121
|
-
let data
|
|
2122
|
-
if (name === 'advisers_today') {
|
|
2123
|
-
const open = ledger.openCommitments()
|
|
2124
|
-
data = { open: open.length, commitments: open.map((c) => ({ id: c.id, debtor: c.debtor, creditor: c.creditor, action: c.action, dueAt: c.dueAt })) }
|
|
2125
|
-
} else if (name === 'advisers_commit_ls') data = ledger.listCommitments().filter((c) => args.all || c.status === 'open').map((c) => ({ id: c.id, status: c.status, action: c.action, dueAt: c.dueAt, creditor: c.creditor }))
|
|
2126
|
-
else if (name === 'advisers_who') data = { mine: ledger.openCommitments().filter((c) => c.debtor === 'user' || c.debtor === 'agent'), waiting: ledger.openCommitments().filter((c) => c.debtor === 'third' || c.debtor.startsWith('third:')) }
|
|
2127
|
-
else if (name === 'advisers_evidence') {
|
|
2128
|
-
if (!args.id) throw new Error('id is required')
|
|
2129
|
-
const r = args.id.startsWith('cm_') ? evidenceForCommitment(store, ledger, args.id) : args.id.startsWith('fact_') ? evidenceForFact(store, ledger, args.id) : args.id.startsWith('pref_') ? evidenceForPreference(store, ledger, args.id) : null
|
|
2130
|
-
if (!r) throw new Error('unknown evidence id prefix')
|
|
2131
|
-
data = r
|
|
2132
|
-
} else if (name === 'advisers_remind') data = buildReminders(ledger, { now: new Date() })
|
|
2133
|
-
else return mcpError(id, -32602, `unknown tool: ${name}`)
|
|
2134
|
-
process.stdout.write(JSON.stringify({ jsonrpc: '2.0', id, result: { content: [{ type: 'text', text: JSON.stringify(data, null, 2) }], isError: false } }) + '\n')
|
|
2135
|
-
store?.appendAudit({ actor: 'mcp', action: 'mcp.call', allowed: true, reason: name })
|
|
2136
|
-
} catch (error) { mcpReply(id, { content: [{ type: 'text', text: error.message }], isError: true }) }
|
|
2137
|
-
}
|
|
2138
|
-
let buf = ''
|
|
2139
|
-
process.stdin.setEncoding('utf8')
|
|
2140
|
-
process.stdin.on('data', (chunk) => {
|
|
2141
|
-
buf += chunk
|
|
2142
|
-
let i
|
|
2143
|
-
while ((i = buf.indexOf('\n')) >= 0) {
|
|
2144
|
-
const line = buf.slice(0, i).trim(); buf = buf.slice(i + 1)
|
|
2145
|
-
if (!line) continue
|
|
2146
|
-
try { const msg = JSON.parse(line); void handle(msg) } catch { mcpError(null, -32700, 'parse error') }
|
|
2147
|
-
}
|
|
3139
|
+
const { createMcpServer } = await loadMcpServer()
|
|
3140
|
+
const server = createMcpServer({
|
|
3141
|
+
store,
|
|
3142
|
+
ledger,
|
|
3143
|
+
version: VERSION,
|
|
3144
|
+
audit: (entry) => store?.appendAudit(entry),
|
|
2148
3145
|
})
|
|
2149
|
-
|
|
3146
|
+
// Robustness audit P2-3: a closed client stdout surfaces as an asynchronous
|
|
3147
|
+
// 'error' event (EPIPE) and used to reach the global uncaughtException handler
|
|
3148
|
+
// as "write EPIPE"/exit 1. The MCP host went away, so exit cleanly (0).
|
|
3149
|
+
const onStdoutError = (error) => {
|
|
3150
|
+
if (error?.code === 'EPIPE') {
|
|
3151
|
+
try { process.stdin.pause() } catch {}
|
|
3152
|
+
process.exit(0)
|
|
3153
|
+
}
|
|
3154
|
+
console.error(`advisers: ${friendlyError(error)}`)
|
|
3155
|
+
process.exit(1)
|
|
3156
|
+
}
|
|
3157
|
+
process.stdout.on('error', onStdoutError)
|
|
3158
|
+
try {
|
|
3159
|
+
await server.serve(process.stdin, process.stdout)
|
|
3160
|
+
} finally {
|
|
3161
|
+
process.stdout.removeListener('error', onStdoutError)
|
|
3162
|
+
}
|
|
2150
3163
|
}
|
|
2151
3164
|
|
|
2152
3165
|
async function ocrCommand(args) {
|
|
2153
3166
|
const file = args.find((a) => !a.startsWith('--'))
|
|
2154
3167
|
if (!file) { console.error('usage: advisers ocr <image> [--out text]'); process.exitCode = 1; return }
|
|
2155
3168
|
try {
|
|
3169
|
+
const { runLocalOcr } = await loadOcr()
|
|
2156
3170
|
const text = await runLocalOcr(file)
|
|
2157
3171
|
const outIdx = args.indexOf('--out')
|
|
2158
3172
|
if (outIdx >= 0 && args[outIdx + 1]) {
|
|
@@ -2172,48 +3186,161 @@ function vaultPass() {
|
|
|
2172
3186
|
return pass
|
|
2173
3187
|
}
|
|
2174
3188
|
|
|
2175
|
-
|
|
3189
|
+
/**
|
|
3190
|
+
* Plaintext database copies left behind by unseal/migrate/import/sync and by an
|
|
3191
|
+
* interrupted unseal (robustness audit P1-2). `vault seal --remove` must delete
|
|
3192
|
+
* these too, otherwise the CLI says "plaintext removed" while a readable SQLite
|
|
3193
|
+
* copy (including the before-unseal backup) is still in HOME.
|
|
3194
|
+
*/
|
|
3195
|
+
const PLAINTEXT_DB_COPY_RE = /^(?:state\.db\.before-(?:unseal|migrate|sync)-|\.state\.db\.unseal-|import-backup-)/
|
|
3196
|
+
function plaintextDbCopies() {
|
|
3197
|
+
try {
|
|
3198
|
+
return readdirSync(HOME).filter((name) => PLAINTEXT_DB_COPY_RE.test(name)).map((name) => join(HOME, name))
|
|
3199
|
+
} catch {
|
|
3200
|
+
return []
|
|
3201
|
+
}
|
|
3202
|
+
}
|
|
3203
|
+
|
|
3204
|
+
/**
|
|
3205
|
+
* Remove the live plaintext database and every plaintext copy. Failures are
|
|
3206
|
+
* collected (never swallowed) so the caller can report them and exit non-zero.
|
|
3207
|
+
*/
|
|
3208
|
+
function removePlaintextDatabase() {
|
|
3209
|
+
const removed = []
|
|
3210
|
+
const failures = []
|
|
3211
|
+
for (const file of [DB, `${DB}-wal`, `${DB}-shm`, ...plaintextDbCopies()]) {
|
|
3212
|
+
try {
|
|
3213
|
+
if (!existsSync(file)) continue
|
|
3214
|
+
rmSync(file)
|
|
3215
|
+
removed.push(file)
|
|
3216
|
+
} catch (error) {
|
|
3217
|
+
failures.push(`${file}: ${error.message}`)
|
|
3218
|
+
}
|
|
3219
|
+
}
|
|
3220
|
+
fsyncDir(HOME)
|
|
3221
|
+
return { removed, failures }
|
|
3222
|
+
}
|
|
3223
|
+
|
|
3224
|
+
/** Print the result of a --remove cleanup; returns true only when nothing failed. */
|
|
3225
|
+
function reportPlaintextCleanup(cleanup, out) {
|
|
3226
|
+
if (cleanup.failures.length) {
|
|
3227
|
+
console.error(`vault seal failed: the sealed file ${out} is in place, but ${cleanup.failures.length} plaintext file(s) could not be removed:`)
|
|
3228
|
+
for (const failure of cleanup.failures) console.error(` ${failure}`)
|
|
3229
|
+
console.error('Close other advisers processes / check file permissions, then rerun `advisers vault seal --remove`.')
|
|
3230
|
+
process.exitCode = 1
|
|
3231
|
+
return false
|
|
3232
|
+
}
|
|
3233
|
+
console.log(`sealed ${DB} -> ${out} (plaintext removed: ${cleanup.removed.length} file(s))`)
|
|
3234
|
+
return true
|
|
3235
|
+
}
|
|
3236
|
+
|
|
3237
|
+
async function vaultSeal(args) {
|
|
2176
3238
|
const { flags } = parseFlags(args)
|
|
2177
3239
|
ensureHome()
|
|
2178
|
-
|
|
3240
|
+
// P1-3: seal mutates/removes state.db, so it takes the same single-writer lock
|
|
3241
|
+
// as ordinary commands; a ui/mcp/bridge server holding the store now makes seal
|
|
3242
|
+
// fail with E_DB_LOCKED instead of silently discarding that process's writes.
|
|
3243
|
+
ensureInstanceLock()
|
|
3244
|
+
const removePlaintext = Boolean(flags.remove) || args.includes('--remove')
|
|
3245
|
+
if (!existsSync(DB)) {
|
|
3246
|
+
const sealed = vaultSealedPath()
|
|
3247
|
+
// Already sealed: --remove still means "purge the leftover plaintext copies".
|
|
3248
|
+
if (sealed && removePlaintext) return reportPlaintextCleanup(removePlaintextDatabase(), sealed)
|
|
3249
|
+
console.error(sealed
|
|
3250
|
+
? `advisers: E_VAULT_SEALED — no plaintext database at ${DB}; the sealed file ${sealed} is intact.`
|
|
3251
|
+
: `no database at ${DB}`)
|
|
3252
|
+
process.exitCode = 1
|
|
3253
|
+
return
|
|
3254
|
+
}
|
|
2179
3255
|
const pass = vaultPass(); if (!pass) return
|
|
3256
|
+
const { encryptJson, decryptJson } = await loadVault()
|
|
2180
3257
|
try {
|
|
2181
3258
|
const store = new SqliteStore(DB)
|
|
2182
|
-
|
|
2183
|
-
|
|
2184
|
-
|
|
3259
|
+
try {
|
|
3260
|
+
// The copied bytes must contain every committed write, so fold the WAL
|
|
3261
|
+
// first and never ignore a busy checkpoint.
|
|
3262
|
+
const before = store.checkpoint()
|
|
3263
|
+
if (before.busy) throw new Error('database is busy (another advisers process is writing); close it and retry vault seal')
|
|
3264
|
+
store.appendAudit({ actor: 'local', action: 'vault.seal', allowed: true, reason: 'database encrypted at rest' })
|
|
3265
|
+
const after = store.checkpoint()
|
|
3266
|
+
if (after.busy) throw new Error('database is busy (another advisers process is writing); close it and retry vault seal')
|
|
3267
|
+
} finally {
|
|
3268
|
+
try { store.close() } catch {}
|
|
3269
|
+
}
|
|
2185
3270
|
} catch (error) { console.error(`vault seal failed: ${error.message}`); process.exitCode = 1; return }
|
|
2186
3271
|
try {
|
|
2187
3272
|
const bytes = readFileSync(DB)
|
|
2188
3273
|
const sha = createHash('sha256').update(bytes).digest('hex')
|
|
2189
3274
|
const envelope = encryptJson({ kind: 'advisers-db', version: VERSION, sha256: sha, db: bytes.toString('base64') }, pass)
|
|
2190
3275
|
const out = typeof flags.out === 'string' ? flags.out : `${DB}.vault`
|
|
2191
|
-
|
|
3276
|
+
atomicWriteFileSync(out, JSON.stringify(envelope) + '\n', { mode: 0o600 })
|
|
2192
3277
|
const check = decryptJson(JSON.parse(readFileSync(out, 'utf8')), pass)
|
|
2193
3278
|
if (check.sha256 !== sha) throw new Error('sealed file verification failed')
|
|
2194
|
-
if (
|
|
2195
|
-
|
|
3279
|
+
if (removePlaintext) {
|
|
3280
|
+
if (!reportPlaintextCleanup(removePlaintextDatabase(), out)) return
|
|
3281
|
+
return
|
|
2196
3282
|
}
|
|
2197
|
-
console.log(`sealed ${DB} -> ${out}
|
|
3283
|
+
console.log(`sealed ${DB} -> ${out} (plaintext kept; pass --remove)`)
|
|
2198
3284
|
} catch (error) { console.error(`vault seal failed: ${error.message}`); process.exitCode = 1 }
|
|
2199
3285
|
}
|
|
2200
3286
|
|
|
2201
|
-
function vaultUnseal(args) {
|
|
3287
|
+
async function vaultUnseal(args) {
|
|
2202
3288
|
const file = args.find((a) => !a.startsWith('--')) || `${DB}.vault`
|
|
2203
3289
|
if (!existsSync(file)) { console.error(`no sealed database at ${file}`); process.exitCode = 1; return }
|
|
2204
3290
|
const pass = vaultPass(); if (!pass) return
|
|
3291
|
+
let bytes
|
|
2205
3292
|
try {
|
|
3293
|
+
const { decryptJson } = await loadVault()
|
|
2206
3294
|
const payload = decryptJson(JSON.parse(readFileSync(file, 'utf8')), pass)
|
|
2207
3295
|
if (payload.kind !== 'advisers-db' || typeof payload.db !== 'string') throw new Error('not an Advisers database vault')
|
|
2208
|
-
|
|
3296
|
+
bytes = Buffer.from(payload.db, 'base64')
|
|
2209
3297
|
const sha = createHash('sha256').update(bytes).digest('hex')
|
|
2210
3298
|
if (sha !== payload.sha256) throw new Error('vault checksum mismatch')
|
|
2211
|
-
|
|
2212
|
-
|
|
2213
|
-
|
|
3299
|
+
} catch (error) {
|
|
3300
|
+
console.error(`vault unseal failed: ${error.message}`)
|
|
3301
|
+
console.error(`The sealed file ${file} was not touched; retry with the correct passphrase.`)
|
|
3302
|
+
process.exitCode = 1
|
|
3303
|
+
return
|
|
3304
|
+
}
|
|
3305
|
+
ensureHome()
|
|
3306
|
+
// P1-3: unseal replaces state.db; hold the single-writer lock for the whole
|
|
3307
|
+
// verify + backup + rename sequence (E_DB_LOCKED while another process runs).
|
|
3308
|
+
ensureInstanceLock()
|
|
3309
|
+
// P1-3: never write the payload straight over the live database. Write a
|
|
3310
|
+
// same-directory temp file, fsync it, verify the SQLite image, keep the old
|
|
3311
|
+
// database (and its WAL) as a backup, then rename atomically.
|
|
3312
|
+
const tmp = join(HOME, `.state.db.unseal-${process.pid}-${randomBytes(4).toString('hex')}`)
|
|
3313
|
+
try {
|
|
3314
|
+
writeDurableTemp(tmp, bytes)
|
|
3315
|
+
let check
|
|
3316
|
+
try {
|
|
3317
|
+
check = new SqliteStore(tmp, { readOnly: true, checkIntegrity: true })
|
|
3318
|
+
} catch (error) {
|
|
3319
|
+
throw new Error(`the unsealed database failed its integrity check (${error.message})`)
|
|
3320
|
+
} finally {
|
|
3321
|
+
try { check?.close() } catch {}
|
|
3322
|
+
}
|
|
3323
|
+
let backup
|
|
3324
|
+
if (existsSync(DB)) {
|
|
3325
|
+
backup = `${DB}.before-unseal-${Date.now()}`
|
|
3326
|
+
copyFileSync(DB, backup)
|
|
3327
|
+
for (const suffix of ['-wal', '-shm']) {
|
|
3328
|
+
try { if (existsSync(DB + suffix)) copyFileSync(DB + suffix, backup + suffix) } catch {}
|
|
3329
|
+
}
|
|
3330
|
+
}
|
|
3331
|
+
// A WAL from the old database must never be replayed onto the new file.
|
|
3332
|
+
for (const suffix of ['-wal', '-shm']) { try { if (existsSync(DB + suffix)) rmSync(DB + suffix) } catch {} }
|
|
3333
|
+
renameSync(tmp, DB)
|
|
2214
3334
|
try { chmodSync(DB, 0o600) } catch {}
|
|
2215
|
-
|
|
2216
|
-
|
|
3335
|
+
fsyncDir(HOME)
|
|
3336
|
+
console.log(`unsealed ${file} -> ${DB} (${bytes.length} bytes, integrity ok${backup ? `; previous database kept at ${backup}` : ''})`)
|
|
3337
|
+
} catch (error) {
|
|
3338
|
+
try { if (existsSync(tmp)) rmSync(tmp) } catch {}
|
|
3339
|
+
console.error(`vault unseal failed: ${error.message}`)
|
|
3340
|
+
console.error(`The sealed file ${file} is intact (${bytes.length} bytes of plaintext); the existing database was not replaced.`)
|
|
3341
|
+
console.error('Fix the disk/permissions problem and retry `advisers vault unseal`.')
|
|
3342
|
+
process.exitCode = 1
|
|
3343
|
+
}
|
|
2217
3344
|
}
|
|
2218
3345
|
|
|
2219
3346
|
function vaultStatus() {
|
|
@@ -2222,12 +3349,15 @@ function vaultStatus() {
|
|
|
2222
3349
|
console.log(`database: ${existsSync(DB) ? DB : 'absent'}`)
|
|
2223
3350
|
console.log(`sealed: ${existsSync(sealed) ? sealed : 'none'}`)
|
|
2224
3351
|
console.log(`state: ${existsSync(DB) ? 'plaintext at rest' : existsSync(sealed) ? 'encrypted at rest (run vault unseal)' : 'empty'}`)
|
|
3352
|
+
const copies = plaintextDbCopies()
|
|
3353
|
+
if (copies.length) console.log(`plaintext copies: ${copies.length} (run \`advisers vault seal --remove\` to purge them)`)
|
|
2225
3354
|
}
|
|
2226
3355
|
|
|
2227
3356
|
async function timestampCommand(args) {
|
|
2228
3357
|
const file = args.find((a) => !a.startsWith('--'))
|
|
2229
3358
|
if (!file) { console.error('usage: advisers timestamp <file> [--out proof]'); process.exitCode = 1; return }
|
|
2230
3359
|
try {
|
|
3360
|
+
const { runLocalTimestamp } = await loadTimestamp()
|
|
2231
3361
|
const proof = await runLocalTimestamp(file)
|
|
2232
3362
|
const outIdx = args.indexOf('--out')
|
|
2233
3363
|
if (outIdx >= 0 && args[outIdx + 1]) {
|
|
@@ -2240,11 +3370,12 @@ async function timestampCommand(args) {
|
|
|
2240
3370
|
|
|
2241
3371
|
async function tui(args) {
|
|
2242
3372
|
const once = args.includes('--once')
|
|
3373
|
+
const { buildReminders } = await loadRemind()
|
|
2243
3374
|
const render = () => {
|
|
2244
3375
|
const ledger = loadLedger()
|
|
2245
3376
|
const store = dbStore()
|
|
2246
3377
|
const open = ledger.openCommitments()
|
|
2247
|
-
const localDay =
|
|
3378
|
+
const localDay = localDayOf(Date.now())
|
|
2248
3379
|
const due = open.filter((c) => c.dueAt && c.dueAt.slice(0, 10) <= localDay)
|
|
2249
3380
|
const reminders = buildReminders(ledger, { now: new Date() })
|
|
2250
3381
|
const deliveries = store?.listDeliveries(3) ?? []
|
|
@@ -2284,12 +3415,56 @@ function syncPass() {
|
|
|
2284
3415
|
return pass
|
|
2285
3416
|
}
|
|
2286
3417
|
|
|
2287
|
-
function
|
|
3418
|
+
async function readSyncDevice() {
|
|
3419
|
+
try {
|
|
3420
|
+
const { sanitizeDevice } = await loadSync()
|
|
3421
|
+
const device = readFileSync(join(HOME, 'sync.device'), 'utf8').trim()
|
|
3422
|
+
return device ? sanitizeDevice(device) : undefined
|
|
3423
|
+
} catch {
|
|
3424
|
+
return undefined
|
|
3425
|
+
}
|
|
3426
|
+
}
|
|
3427
|
+
|
|
3428
|
+
async function rememberSyncDevice(device) {
|
|
3429
|
+
try {
|
|
3430
|
+
const { sanitizeDevice } = await loadSync()
|
|
3431
|
+
writeFileSync(join(HOME, 'sync.device'), sanitizeDevice(device) + '\n', { mode: 0o600 })
|
|
3432
|
+
} catch {}
|
|
3433
|
+
}
|
|
3434
|
+
|
|
3435
|
+
/** Latest mtime of the database + its WAL (captured before any checkpoint). */
|
|
3436
|
+
function latestLocalDbMtime() {
|
|
3437
|
+
let latest = 0
|
|
3438
|
+
for (const file of [DB, `${DB}-wal`]) {
|
|
3439
|
+
try { latest = Math.max(latest, statSync(file).mtimeMs) } catch {}
|
|
3440
|
+
}
|
|
3441
|
+
return latest
|
|
3442
|
+
}
|
|
3443
|
+
|
|
3444
|
+
/** Fold the WAL into the main file before a copy/replace; never ignore busy. */
|
|
3445
|
+
function checkpointLocalDatabase() {
|
|
3446
|
+
if (!existsSync(DB)) return { ok: true, skipped: true }
|
|
3447
|
+
let store
|
|
3448
|
+
try {
|
|
3449
|
+
store = new SqliteStore(DB)
|
|
3450
|
+
const result = store.checkpoint()
|
|
3451
|
+
return { ok: !result.busy, ...result }
|
|
3452
|
+
} catch (error) {
|
|
3453
|
+
// A locked database can make even the open/migrate fail; treat that as
|
|
3454
|
+
// busy so pull refuses instead of replacing a live database (see below).
|
|
3455
|
+
return { ok: false, busy: /SQLITE_BUSY|SQLITE_LOCKED|database is locked/i.test(String(error?.message ?? error)), error }
|
|
3456
|
+
} finally {
|
|
3457
|
+
try { store?.close() } catch {}
|
|
3458
|
+
}
|
|
3459
|
+
}
|
|
3460
|
+
|
|
3461
|
+
async function syncCommand(args) {
|
|
2288
3462
|
const { flags, positional } = parseFlags(args)
|
|
2289
3463
|
const sub = positional[0]
|
|
2290
3464
|
const dir = typeof flags.dir === 'string' ? flags.dir : undefined
|
|
2291
3465
|
if (!dir) { console.error('usage: advisers sync push|pull|status --dir <sync-dir>'); process.exitCode = 1; return }
|
|
2292
3466
|
if (sub === 'status') {
|
|
3467
|
+
const { listSnapshots } = await loadSync()
|
|
2293
3468
|
const snaps = listSnapshots(dir)
|
|
2294
3469
|
if (flags.json) { console.log(JSON.stringify(snaps, null, 2)); return }
|
|
2295
3470
|
console.log(`sync dir: ${dir}`)
|
|
@@ -2299,29 +3474,85 @@ function syncCommand(args) {
|
|
|
2299
3474
|
}
|
|
2300
3475
|
const pass = syncPass(); if (!pass) return
|
|
2301
3476
|
ensureHome()
|
|
3477
|
+
// P1-3: push checkpoints/copies the live database and pull replaces it, so both
|
|
3478
|
+
// must not run while another process holds the store (or be run by two sync
|
|
3479
|
+
// commands at once). The lock is held for the whole operation.
|
|
3480
|
+
if (sub === 'push' || sub === 'pull') ensureInstanceLock()
|
|
2302
3481
|
if (sub === 'push') {
|
|
2303
3482
|
if (!existsSync(DB)) { console.error(`no database at ${DB}`); process.exitCode = 1; return }
|
|
3483
|
+
const device = typeof flags.device === 'string' ? flags.device : hostname()
|
|
2304
3484
|
try {
|
|
2305
3485
|
const store = new SqliteStore(DB)
|
|
2306
|
-
|
|
2307
|
-
|
|
2308
|
-
|
|
2309
|
-
|
|
3486
|
+
try {
|
|
3487
|
+
const checkpoint = store.checkpoint()
|
|
3488
|
+
if (checkpoint.busy) throw new Error('database is busy (another advisers process is writing); close it and retry sync push')
|
|
3489
|
+
store.appendAudit({ actor: 'local', action: 'sync.push', allowed: true, reason: basename(dir) })
|
|
3490
|
+
const afterAudit = store.checkpoint()
|
|
3491
|
+
if (afterAudit.busy) throw new Error('database is busy (another advisers process is writing); close it and retry sync push')
|
|
3492
|
+
} finally {
|
|
3493
|
+
try { store.close() } catch {}
|
|
3494
|
+
}
|
|
3495
|
+
const { pushSnapshot } = await loadSync()
|
|
3496
|
+
const result = pushSnapshot({ dir, dbPath: DB, passphrase: pass, device })
|
|
3497
|
+
await rememberSyncDevice(device)
|
|
2310
3498
|
console.log(`pushed ${result.file}`)
|
|
2311
3499
|
console.log(`sha256 ${result.sha256}`)
|
|
2312
3500
|
} catch (error) { console.error(`sync push failed: ${error.message}`); process.exitCode = 1 }
|
|
2313
3501
|
} else if (sub === 'pull') {
|
|
3502
|
+
const force = Boolean(flags.force)
|
|
2314
3503
|
try {
|
|
2315
|
-
|
|
3504
|
+
// Capture the local write time before checkpointing (checkpoint touches mtime).
|
|
3505
|
+
const localMtimeMs = latestLocalDbMtime()
|
|
3506
|
+
if (existsSync(DB)) {
|
|
3507
|
+
const checkpoint = checkpointLocalDatabase()
|
|
3508
|
+
if (checkpoint.busy && !force) throw new Error('local database is busy (another advisers process is writing); close it and retry sync pull, or re-run with --force (a backup is kept)')
|
|
3509
|
+
if (!checkpoint.busy && checkpoint.error) console.error(`note: local database could not be checkpointed (${checkpoint.error.message}); the snapshot replaces it and a backup is kept.`)
|
|
3510
|
+
}
|
|
3511
|
+
const { pullSnapshot } = await loadSync()
|
|
3512
|
+
const result = pullSnapshot({
|
|
3513
|
+
dir,
|
|
3514
|
+
dbPath: DB,
|
|
3515
|
+
passphrase: pass,
|
|
3516
|
+
file: typeof flags.file === 'string' ? flags.file : undefined,
|
|
3517
|
+
force,
|
|
3518
|
+
localMtimeMs,
|
|
3519
|
+
localDevice: await readSyncDevice(),
|
|
3520
|
+
})
|
|
2316
3521
|
if (!result.changed) console.log('local database already matches the latest snapshot')
|
|
2317
3522
|
else console.log(`pulled ${result.file} (${result.sha256})${result.backup ? `; backup ${result.backup}` : ''}`)
|
|
2318
|
-
if (result.changed) {
|
|
3523
|
+
if (result.changed) {
|
|
3524
|
+
try { dbStore()?.appendAudit({ actor: 'local', action: 'sync.pull', allowed: true, reason: result.file }) }
|
|
3525
|
+
catch (error) { console.error(`warning: database replaced but the sync.pull audit row failed: ${error.message}`); process.exitCode = 1 }
|
|
3526
|
+
}
|
|
2319
3527
|
} catch (error) { console.error(`sync pull failed: ${error.message}`); process.exitCode = 1 }
|
|
2320
3528
|
} else { console.error('usage: advisers sync push|pull|status --dir <sync-dir>'); process.exitCode = 1 }
|
|
2321
3529
|
}
|
|
2322
3530
|
|
|
2323
|
-
|
|
3531
|
+
/** Read-side source v2 compatibility for the JSON evidence view. */
|
|
3532
|
+
async function normalizeEvidenceSources(result) {
|
|
3533
|
+
const { normalizeSource } = await loadSource()
|
|
3534
|
+
const record = result?.commitment ?? result?.fact ?? result?.preference
|
|
3535
|
+
if (!record || typeof record !== 'object') return result
|
|
3536
|
+
if (Array.isArray(record.evidence)) {
|
|
3537
|
+
record.evidence = record.evidence.map((item) => (item && typeof item === 'object' && item.source ? { ...item, source: normalizeSource(item.source) ?? item.source } : item))
|
|
3538
|
+
}
|
|
3539
|
+
if (record.source && typeof record.source === 'object') record.source = normalizeSource(record.source) ?? record.source
|
|
3540
|
+
return result
|
|
3541
|
+
}
|
|
3542
|
+
|
|
3543
|
+
async function printEvidence(args) {
|
|
2324
3544
|
const { flags, positional } = parseFlags(args)
|
|
3545
|
+
// Offline receipt-pack verification: reads only the given directory. It runs
|
|
3546
|
+
// before ensureHome() so a clean machine needs no ~/.advisers state.
|
|
3547
|
+
if (positional[0] === 'verify') {
|
|
3548
|
+
const dir = positional[1] ?? (typeof flags.dir === 'string' ? flags.dir : undefined)
|
|
3549
|
+
if (!dir) { console.error('usage: advisers evidence verify <dir>'); process.exitCode = 1; return }
|
|
3550
|
+
const { verifyReceiptPackDir } = await loadReceiptVerify()
|
|
3551
|
+
const result = verifyReceiptPackDir(dir)
|
|
3552
|
+
console.log(JSON.stringify(result, null, 2))
|
|
3553
|
+
process.exitCode = result.ok ? 0 : 1
|
|
3554
|
+
return
|
|
3555
|
+
}
|
|
2325
3556
|
ensureHome()
|
|
2326
3557
|
const store = dbStore()
|
|
2327
3558
|
const ledger = loadLedger()
|
|
@@ -2329,12 +3560,14 @@ function printEvidence(args) {
|
|
|
2329
3560
|
if (!id) { console.error('usage: advisers evidence show <id> [--json]'); process.exitCode = 1; return }
|
|
2330
3561
|
let result
|
|
2331
3562
|
try {
|
|
3563
|
+
const { evidenceForCommitment, evidenceForFact, evidenceForPreference } = await loadEvidence()
|
|
2332
3564
|
if (id.startsWith('cm_')) result = evidenceForCommitment(store, ledger, id)
|
|
2333
3565
|
else if (id.startsWith('fact_')) result = evidenceForFact(store, ledger, id)
|
|
2334
3566
|
else if (id.startsWith('pref_')) result = evidenceForPreference(store, ledger, id)
|
|
2335
3567
|
else { console.error('unknown evidence id prefix (want cm_/fact_/pref_)'); process.exitCode = 1; return }
|
|
2336
3568
|
} catch (error) { console.error(error.message); process.exitCode = 1; return }
|
|
2337
3569
|
if (!result || (!result.commitment && !result.fact && !result.preference)) { console.error(`not found: ${id}`); process.exitCode = 1; return }
|
|
3570
|
+
await normalizeEvidenceSources(result)
|
|
2338
3571
|
if (flags.json) { console.log(JSON.stringify(result, null, 2)); return }
|
|
2339
3572
|
const label = result.commitment ? `${result.commitment.action}` : result.fact ? `${result.fact.subject} ${result.fact.predicate}` : result.preference?.statement
|
|
2340
3573
|
console.log(`${id} ${label ?? ''}`)
|
|
@@ -2357,26 +3590,257 @@ async function evidencePack(args) {
|
|
|
2357
3590
|
facts: ledger.listFacts().map((f) => f.id),
|
|
2358
3591
|
preferences: ledger.listPreferences({ includeCandidates: false }).map((p) => p.id),
|
|
2359
3592
|
}
|
|
2360
|
-
const
|
|
3593
|
+
const { buildEvidencePack, toDocxRows, verifyPack, EvidencePackLimitError } = await loadEvidence()
|
|
3594
|
+
let pack
|
|
3595
|
+
try {
|
|
3596
|
+
// Performance audit P1-1: --all was parsed but never forwarded, so the
|
|
3597
|
+
// documented escape hatch was a no-op and large ledgers always failed.
|
|
3598
|
+
pack = buildEvidencePack({ store, ledger, ids: targetIds, all: flags.all === true })
|
|
3599
|
+
} catch (error) {
|
|
3600
|
+
if (error instanceof EvidencePackLimitError || error?.code === 'EVIDENCE_PACK_TOO_LARGE') {
|
|
3601
|
+
console.error('error: ' + error.message)
|
|
3602
|
+
if (error.hint) console.error('hint: ' + error.hint)
|
|
3603
|
+
process.exitCode = 1
|
|
3604
|
+
return
|
|
3605
|
+
}
|
|
3606
|
+
throw error
|
|
3607
|
+
}
|
|
2361
3608
|
const out = flags.out ? String(flags.out) : join(HOME, 'evidence', `evidence-${new Date().toISOString().replace(/[:.]/g, '-')}`)
|
|
2362
3609
|
mkdirSync(out, { recursive: true, mode: 0o700 })
|
|
2363
3610
|
for (const [name, content] of Object.entries(pack.files)) writeFileSync(join(out, name), content, { mode: 0o600 })
|
|
2364
3611
|
let receipt
|
|
2365
3612
|
try {
|
|
2366
|
-
|
|
3613
|
+
// P2-3: import the docx/validate submodules, not the office barrel.
|
|
3614
|
+
const docxModule = await importOfficeSubmodule('docx')
|
|
3615
|
+
if (typeof docxModule?.buildDocx !== 'function') throw new Error('advisers-office docx builder is not available')
|
|
3616
|
+
const validateOffice = await loadOfficeOperation('validate', 'validateOffice')
|
|
2367
3617
|
const rows = toDocxRows(pack, { maxRows: 80 })
|
|
2368
|
-
const buffer = await
|
|
2369
|
-
await
|
|
3618
|
+
const buffer = await docxModule.buildDocx({ title: '证据包回执', sections: [{ heading: '证据清单', paragraphs: rows.length ? rows : ['(没有可导出条目)'] }, { heading: '校验', paragraphs: [`manifest.json / README.txt 的 SHA256 见 SHA256SUMS`, `生成时间:${new Date().toISOString()}`, 'SHA256SUMS 只证明包生成后未被修改;不是签名或第三方存证。'] }] })
|
|
3619
|
+
await validateOffice(buffer, 'docx')
|
|
2370
3620
|
writeFileSync(join(out, 'receipt.docx'), buffer)
|
|
2371
3621
|
receipt = join(out, 'receipt.docx')
|
|
2372
3622
|
} catch (error) { console.error(`docx receipt skipped: ${error.message}`) }
|
|
2373
3623
|
const verification = verifyPack(pack.files)
|
|
2374
|
-
|
|
2375
|
-
|
|
3624
|
+
// Delivery row + audit row commit together (robustness audit P0-3).
|
|
3625
|
+
recordDeliveryWithAudit({
|
|
3626
|
+
files: [join(out, 'manifest.json'), join(out, 'README.txt'), join(out, 'SHA256SUMS'), ...(receipt ? [receipt] : [])],
|
|
3627
|
+
tool: 'evidence-pack',
|
|
3628
|
+
title: 'evidence pack',
|
|
3629
|
+
validation: verification,
|
|
3630
|
+
audit: { actor: 'local', action: 'evidence.pack', allowed: true, reason: `${pack.summary?.entryCount ?? 0} entries` },
|
|
3631
|
+
})
|
|
2376
3632
|
console.log(JSON.stringify({ out, files: Object.keys(pack.files), receipt, verification }, null, 2))
|
|
2377
3633
|
if (!verification.ok) process.exitCode = 1
|
|
2378
3634
|
}
|
|
2379
3635
|
|
|
3636
|
+
/** "Name <mail>" / "mail" / "Name" -> buildReceiptPack recipient input. */
|
|
3637
|
+
function parseReceiptRecipient(value) {
|
|
3638
|
+
if (value === undefined || value === null || value === true) return undefined
|
|
3639
|
+
const text = String(value).trim()
|
|
3640
|
+
if (!text) return undefined
|
|
3641
|
+
const bracketed = /^(.*?)\s*<([^<>\s]+@[^<>\s]+)>\s*$/.exec(text)
|
|
3642
|
+
if (bracketed) return { name: bracketed[1].trim() || null, email: bracketed[2] }
|
|
3643
|
+
if (/^[^@\s]+@[^@\s]+$/.test(text)) return { email: text }
|
|
3644
|
+
return { name: text }
|
|
3645
|
+
}
|
|
3646
|
+
|
|
3647
|
+
/**
|
|
3648
|
+
* Resolve ONE dist submodule of the optional advisers-office peer without
|
|
3649
|
+
* importing its barrel file. Importing the barrel pulls exceljs/pptxgenjs and
|
|
3650
|
+
* cost ~17s on the test host; verify.js/docx.js only need jszip/docx (~100ms).
|
|
3651
|
+
* Tries the workspace build first (repo/dev/tests), then the installed peer via
|
|
3652
|
+
* its resolved entry URL, then the bare package (portable fallback).
|
|
3653
|
+
*/
|
|
3654
|
+
async function importOfficeSubmodule(name) {
|
|
3655
|
+
try { return await import('../../office/dist/' + name + '.js') } catch {}
|
|
3656
|
+
try {
|
|
3657
|
+
const entry = import.meta.resolve('advisers-office')
|
|
3658
|
+
if (entry.startsWith('file:')) return await import(new URL('./' + name + '.js', entry).href)
|
|
3659
|
+
} catch {}
|
|
3660
|
+
return null
|
|
3661
|
+
}
|
|
3662
|
+
|
|
3663
|
+
/** Load one operation from a specific office submodule, falling back to the barrel. */
|
|
3664
|
+
async function loadOfficeOperation(moduleName, exportName) {
|
|
3665
|
+
const submodule = await importOfficeSubmodule(moduleName)
|
|
3666
|
+
if (typeof submodule?.[exportName] === 'function') return submodule[exportName]
|
|
3667
|
+
const mod = await import('advisers-office')
|
|
3668
|
+
return mod[exportName]
|
|
3669
|
+
}
|
|
3670
|
+
|
|
3671
|
+
/**
|
|
3672
|
+
* Best-effort structural verification of delivered Office artifacts for the
|
|
3673
|
+
* receipt manifest. The optional advisers-office peer may be absent (portable
|
|
3674
|
+
* install): an empty result means "not recorded", which the pack discloses.
|
|
3675
|
+
*/
|
|
3676
|
+
async function verifyDeliveryArtifacts(files) {
|
|
3677
|
+
const supported = []
|
|
3678
|
+
for (const file of files) {
|
|
3679
|
+
const ext = extname(file).slice(1).toLowerCase()
|
|
3680
|
+
if (ext === 'docx' || ext === 'xlsx' || ext === 'pptx') supported.push({ file, ext })
|
|
3681
|
+
}
|
|
3682
|
+
if (!supported.length) return []
|
|
3683
|
+
const verifyModule = await importOfficeSubmodule('verify')
|
|
3684
|
+
const verifyOffice = verifyModule?.verifyOffice
|
|
3685
|
+
if (typeof verifyOffice !== 'function') return []
|
|
3686
|
+
const results = []
|
|
3687
|
+
for (const { file, ext } of supported) {
|
|
3688
|
+
const source = 'advisers verify ' + basename(file)
|
|
3689
|
+
try {
|
|
3690
|
+
const result = await verifyOffice(readFileSync(file), ext)
|
|
3691
|
+
results.push({ source, ...result })
|
|
3692
|
+
} catch (error) {
|
|
3693
|
+
results.push({ source, ok: false, errors: [String(error?.message ?? error)] })
|
|
3694
|
+
}
|
|
3695
|
+
}
|
|
3696
|
+
return results
|
|
3697
|
+
}
|
|
3698
|
+
|
|
3699
|
+
/**
|
|
3700
|
+
* `advisers deliveries --receipt`: build a v1.1 delivery receipt pack.
|
|
3701
|
+
*
|
|
3702
|
+
* The pack copies the delivered artifacts, records their SHA-256 plus the
|
|
3703
|
+
* generator environment / verify results / recipient, and includes the
|
|
3704
|
+
* evidence-pack entries (capped at DEFAULT_MAX_EVIDENCE_ENTRIES unless --all or
|
|
3705
|
+
* --ids narrows/extends it). The old evidence-only path stays on
|
|
3706
|
+
* `deliveries --pack`.
|
|
3707
|
+
*/
|
|
3708
|
+
async function receiptPack(args) {
|
|
3709
|
+
const { flags } = parseFlags(args)
|
|
3710
|
+
ensureHome()
|
|
3711
|
+
const store = dbStore()
|
|
3712
|
+
if (!store) { console.error('deliveries --receipt requires SQLite store'); process.exitCode = 1; return }
|
|
3713
|
+
const ledger = loadLedger()
|
|
3714
|
+
const denied = egressDeniedReason(ledger.getMatter(activeMatterId(ledger)), 'evidence')
|
|
3715
|
+
if (denied) { console.error(denied); process.exitCode = 1; return }
|
|
3716
|
+
const ids = typeof flags.ids === 'string' ? flags.ids.split(',').map((item) => item.trim()).filter(Boolean) : undefined
|
|
3717
|
+
if (ids && !ids.length) { console.error('--ids is empty'); process.exitCode = 1; return }
|
|
3718
|
+
const deliveryLimit = Math.max(1, Math.min(2000, Number(flags.limit) || 100))
|
|
3719
|
+
// A receipt pack records itself as a delivery for discoverability, but a new
|
|
3720
|
+
// receipt must not recursively copy older receipt packs (unbounded growth).
|
|
3721
|
+
const rows = store.listDeliveries(deliveryLimit).filter((row) => row.tool !== 'receipt-pack')
|
|
3722
|
+
if (!rows.length) {
|
|
3723
|
+
console.error('没有交付记录可生成回执包;先运行 `advisers deliver` / `advisers office` / `advisers template`。')
|
|
3724
|
+
process.exitCode = 1
|
|
3725
|
+
return
|
|
3726
|
+
}
|
|
3727
|
+
const skippedFiles = []
|
|
3728
|
+
const deliveries = []
|
|
3729
|
+
for (const row of rows) {
|
|
3730
|
+
const files = []
|
|
3731
|
+
for (const file of Array.isArray(row.files) ? row.files : []) {
|
|
3732
|
+
try {
|
|
3733
|
+
if (typeof file === 'string' && existsSync(file) && statSync(file).isFile()) files.push(file)
|
|
3734
|
+
else skippedFiles.push(row.id + ': ' + String(file))
|
|
3735
|
+
} catch { skippedFiles.push(row.id + ': ' + String(file)) }
|
|
3736
|
+
}
|
|
3737
|
+
if (!files.length) continue
|
|
3738
|
+
deliveries.push({
|
|
3739
|
+
id: row.id,
|
|
3740
|
+
title: row.title ?? null,
|
|
3741
|
+
tool: row.tool ?? null,
|
|
3742
|
+
createdAt: row.createdAt ?? null,
|
|
3743
|
+
validation: row.validation ?? null,
|
|
3744
|
+
files,
|
|
3745
|
+
})
|
|
3746
|
+
}
|
|
3747
|
+
if (!deliveries.length) {
|
|
3748
|
+
console.error('没有仍存在的交付文件,无法生成回执包(文件可能已被移动或删除)。')
|
|
3749
|
+
if (skippedFiles.length) console.error('缺失:' + skippedFiles.slice(0, 5).join('; '))
|
|
3750
|
+
process.exitCode = 1
|
|
3751
|
+
return
|
|
3752
|
+
}
|
|
3753
|
+
if (skippedFiles.length) console.error('注意:' + skippedFiles.length + ' 个交付文件缺失,已跳过(回执只覆盖仍存在的文件)。')
|
|
3754
|
+
|
|
3755
|
+
const verifyResults = await verifyDeliveryArtifacts(deliveries.flatMap((delivery) => delivery.files))
|
|
3756
|
+
const { buildEvidencePack, buildReceiptPack, EvidencePackLimitError } = await loadEvidence()
|
|
3757
|
+
let evidence
|
|
3758
|
+
try {
|
|
3759
|
+
const targetIds = ids ?? {
|
|
3760
|
+
commitments: ledger.listCommitments().map((row) => row.id),
|
|
3761
|
+
facts: ledger.listFacts().map((row) => row.id),
|
|
3762
|
+
preferences: ledger.listPreferences({ includeCandidates: false }).map((row) => row.id),
|
|
3763
|
+
}
|
|
3764
|
+
evidence = buildEvidencePack({ store, ledger, ids: targetIds, all: flags.all === true })
|
|
3765
|
+
} catch (error) {
|
|
3766
|
+
if (error instanceof EvidencePackLimitError || error?.code === 'EVIDENCE_PACK_TOO_LARGE') {
|
|
3767
|
+
console.error('error: ' + error.message)
|
|
3768
|
+
if (error.hint) console.error('hint: ' + error.hint)
|
|
3769
|
+
process.exitCode = 1
|
|
3770
|
+
return
|
|
3771
|
+
}
|
|
3772
|
+
throw error
|
|
3773
|
+
}
|
|
3774
|
+
const out = typeof flags.out === 'string'
|
|
3775
|
+
? flags.out
|
|
3776
|
+
: join(HOME, 'receipts', 'receipt-' + new Date().toISOString().replace(/[:.]/g, '-'))
|
|
3777
|
+
// Generate receipt.docx with the office DOCX submodule when available (fast,
|
|
3778
|
+
// nicer table) or the built-in deterministic writer otherwise.
|
|
3779
|
+
const docxModule = await importOfficeSubmodule('docx')
|
|
3780
|
+
const docxBuilder = typeof docxModule?.buildDocx === 'function'
|
|
3781
|
+
? async (spec) => docxModule.buildDocx(spec)
|
|
3782
|
+
: false
|
|
3783
|
+
let pack
|
|
3784
|
+
try {
|
|
3785
|
+
pack = await buildReceiptPack({
|
|
3786
|
+
deliveries,
|
|
3787
|
+
evidence,
|
|
3788
|
+
verifyResults,
|
|
3789
|
+
docxBuilder,
|
|
3790
|
+
env: {
|
|
3791
|
+
advisersVersion: VERSION,
|
|
3792
|
+
nodeVersion: process.version,
|
|
3793
|
+
platform: process.platform,
|
|
3794
|
+
command: 'advisers deliveries --receipt',
|
|
3795
|
+
},
|
|
3796
|
+
recipient: parseReceiptRecipient(flags.recipient),
|
|
3797
|
+
anchors: [],
|
|
3798
|
+
outDir: out,
|
|
3799
|
+
overwrite: flags.force === true,
|
|
3800
|
+
})
|
|
3801
|
+
} catch (error) {
|
|
3802
|
+
console.error('receipt pack failed: ' + String(error?.message ?? error))
|
|
3803
|
+
process.exitCode = 1
|
|
3804
|
+
return
|
|
3805
|
+
}
|
|
3806
|
+
const summary = pack.summary
|
|
3807
|
+
try {
|
|
3808
|
+
recordDeliveryWithAudit({
|
|
3809
|
+
files: [join(summary.outDir, 'manifest.json'), join(summary.outDir, 'README.txt'), join(summary.outDir, 'SHA256SUMS'), join(summary.outDir, 'receipt.docx')],
|
|
3810
|
+
tool: 'receipt-pack',
|
|
3811
|
+
title: 'delivery receipt pack',
|
|
3812
|
+
validation: 'receipt-pack-v1.1: ' + summary.verifyStatus,
|
|
3813
|
+
audit: { actor: 'local', action: 'receipt.pack', allowed: true, reason: deliveries.length + ' deliveries/' + summary.fileCount + ' files' },
|
|
3814
|
+
})
|
|
3815
|
+
} catch {}
|
|
3816
|
+
const { verifyReceiptPackDir } = await loadReceiptVerify()
|
|
3817
|
+
const verification = verifyReceiptPackDir(summary.outDir)
|
|
3818
|
+
console.log(JSON.stringify({
|
|
3819
|
+
ok: verification.ok,
|
|
3820
|
+
format: summary.format,
|
|
3821
|
+
version: summary.version,
|
|
3822
|
+
out: summary.outDir,
|
|
3823
|
+
replaced: summary.replaced ?? null,
|
|
3824
|
+
deliveryCount: summary.deliveryCount,
|
|
3825
|
+
fileCount: summary.fileCount,
|
|
3826
|
+
verifyStatus: summary.verifyStatus,
|
|
3827
|
+
anchored: summary.anchored,
|
|
3828
|
+
recipient: summary.recipient,
|
|
3829
|
+
manifestDigest: summary.manifestDigest,
|
|
3830
|
+
receiptSha256: summary.receiptSha256,
|
|
3831
|
+
evidence: summary.evidence,
|
|
3832
|
+
files: summary.files,
|
|
3833
|
+
skippedFiles,
|
|
3834
|
+
verification: {
|
|
3835
|
+
ok: verification.ok,
|
|
3836
|
+
errors: verification.errors,
|
|
3837
|
+
warnings: verification.warnings,
|
|
3838
|
+
checksumCount: verification.checksumCount,
|
|
3839
|
+
},
|
|
3840
|
+
}, null, 2))
|
|
3841
|
+
if (!verification.ok) process.exitCode = 1
|
|
3842
|
+
}
|
|
3843
|
+
|
|
2380
3844
|
function link(sub, from, to, type) {
|
|
2381
3845
|
const ledger = loadLedger()
|
|
2382
3846
|
if (sub === 'ls' || !sub) {
|
|
@@ -2476,8 +3940,7 @@ function link(sub, from, to, type) {
|
|
|
2476
3940
|
const factId = proposal.rollback.slice(5)
|
|
2477
3941
|
const ok = ledger.forget('fact', factId)
|
|
2478
3942
|
proposal.rollback = `rolledback:${factId}`
|
|
2479
|
-
|
|
2480
|
-
saveLedger(ledger)
|
|
3943
|
+
saveLedgerWithAudit(ledger, { actor: 'local', action: 'link.rollback', allowed: true, reason: factId })
|
|
2481
3944
|
console.log(ok ? `rolled back: ${factId}` : `fact not found: ${factId}`)
|
|
2482
3945
|
if (!ok) process.exitCode = 1
|
|
2483
3946
|
return
|
|
@@ -2528,8 +3991,7 @@ function link(sub, from, to, type) {
|
|
|
2528
3991
|
}
|
|
2529
3992
|
if (sub === 'reject') {
|
|
2530
3993
|
ledger.resolveUpdate(from, 'rejected')
|
|
2531
|
-
|
|
2532
|
-
saveLedger(ledger)
|
|
3994
|
+
saveLedgerWithAudit(ledger, { actor: 'local', action: 'link.reject', allowed: true, reason: from })
|
|
2533
3995
|
console.log(`rejected: ${from}`)
|
|
2534
3996
|
return
|
|
2535
3997
|
}
|
|
@@ -2542,8 +4004,7 @@ function link(sub, from, to, type) {
|
|
|
2542
4004
|
source: { type: 'import', ref: proposal.id },
|
|
2543
4005
|
})
|
|
2544
4006
|
ledger.resolveUpdate(from, 'applied', `fact:${fact.id}`)
|
|
2545
|
-
|
|
2546
|
-
saveLedger(ledger)
|
|
4007
|
+
saveLedgerWithAudit(ledger, { actor: 'local', action: 'link.apply', allowed: true, reason: `${from} -> ${fact.id}` })
|
|
2547
4008
|
console.log(`applied: ${from} -> target fact ${fact.id}`)
|
|
2548
4009
|
return
|
|
2549
4010
|
}
|
|
@@ -2551,6 +4012,76 @@ function link(sub, from, to, type) {
|
|
|
2551
4012
|
process.exitCode = 1
|
|
2552
4013
|
}
|
|
2553
4014
|
|
|
4015
|
+
/**
|
|
4016
|
+
* Bridge (Hermes file gateway) hardening — security audit P1-1 / SEC2-09.
|
|
4017
|
+
*
|
|
4018
|
+
* The bridge library owns the wire format; the CLI tightens what it can before
|
|
4019
|
+
* the library sees it: 0700 directories / 0600 files (the library used mkdir and
|
|
4020
|
+
* writeFile defaults), a 1 MiB inbox cap enforced before its unbounded readFile,
|
|
4021
|
+
* and no absolute local attachment paths in the outbox JSON. The library polls
|
|
4022
|
+
* through the instance method, so wrapping pollOnce() covers both the immediate
|
|
4023
|
+
* poll in start() and the interval.
|
|
4024
|
+
*/
|
|
4025
|
+
const BRIDGE_INBOX_MAX_BYTES = 1024 * 1024
|
|
4026
|
+
|
|
4027
|
+
function bridgeDirs(bridgeDir, name) {
|
|
4028
|
+
return {
|
|
4029
|
+
inbox: join(bridgeDir, 'inbox', name),
|
|
4030
|
+
outbox: join(bridgeDir, 'outbox', name),
|
|
4031
|
+
status: join(bridgeDir, 'status', name),
|
|
4032
|
+
registry: join(bridgeDir, 'registry'),
|
|
4033
|
+
quarantine: join(bridgeDir, 'quarantine', name),
|
|
4034
|
+
}
|
|
4035
|
+
}
|
|
4036
|
+
|
|
4037
|
+
function secureBridgeTree(bridgeDir, name) {
|
|
4038
|
+
const dirs = bridgeDirs(bridgeDir, name)
|
|
4039
|
+
for (const dir of Object.values(dirs)) {
|
|
4040
|
+
try { mkdirSync(dir, { recursive: true, mode: 0o700 }); chmodSync(dir, 0o700) } catch {}
|
|
4041
|
+
}
|
|
4042
|
+
for (const dir of [dirs.outbox, dirs.registry, dirs.inbox]) {
|
|
4043
|
+
let files
|
|
4044
|
+
try { files = readdirSync(dir) } catch { continue }
|
|
4045
|
+
for (const file of files) {
|
|
4046
|
+
try { chmodSync(join(dir, file), 0o600) } catch {}
|
|
4047
|
+
}
|
|
4048
|
+
}
|
|
4049
|
+
}
|
|
4050
|
+
|
|
4051
|
+
/** Move oversized inbox files out of the library's readFile path (DoS guard). */
|
|
4052
|
+
function guardBridgeInbox(bridgeDir, name) {
|
|
4053
|
+
const dirs = bridgeDirs(bridgeDir, name)
|
|
4054
|
+
let files
|
|
4055
|
+
try { files = readdirSync(dirs.inbox) } catch { return }
|
|
4056
|
+
for (const file of files) {
|
|
4057
|
+
if (!file.endsWith('.json')) continue
|
|
4058
|
+
const source = join(dirs.inbox, file)
|
|
4059
|
+
let size
|
|
4060
|
+
try { size = statSync(source).size } catch { continue }
|
|
4061
|
+
try { chmodSync(source, 0o600) } catch {}
|
|
4062
|
+
if (size <= BRIDGE_INBOX_MAX_BYTES) continue
|
|
4063
|
+
try {
|
|
4064
|
+
mkdirSync(dirs.quarantine, { recursive: true, mode: 0o700 })
|
|
4065
|
+
chmodSync(dirs.quarantine, 0o700)
|
|
4066
|
+
renameSync(source, join(dirs.quarantine, file))
|
|
4067
|
+
dbStore()?.appendAudit({ actor: 'bridge', action: 'bridge.inbox_quarantine', allowed: false, reason: `${size} bytes > ${BRIDGE_INBOX_MAX_BYTES}` })
|
|
4068
|
+
console.log(`[bridge] quarantined oversized inbox file ${file} (${size} bytes)`)
|
|
4069
|
+
} catch {}
|
|
4070
|
+
}
|
|
4071
|
+
}
|
|
4072
|
+
|
|
4073
|
+
/** Never hand an absolute local attachment path to the third-party Hermes side. */
|
|
4074
|
+
function sanitizeBridgeOutbound(message) {
|
|
4075
|
+
if (!message || !Array.isArray(message.attachments) || !message.attachments.length) return message
|
|
4076
|
+
const attachments = message.attachments.map((attachment) => {
|
|
4077
|
+
const next = { ...(attachment ?? {}) }
|
|
4078
|
+
delete next.localPath
|
|
4079
|
+
if (typeof next.url === 'string' && isAbsolute(next.url)) delete next.url
|
|
4080
|
+
return next
|
|
4081
|
+
})
|
|
4082
|
+
return { ...message, attachments }
|
|
4083
|
+
}
|
|
4084
|
+
|
|
2554
4085
|
async function bridge(args) {
|
|
2555
4086
|
let dir
|
|
2556
4087
|
let name = 'advisers'
|
|
@@ -2564,6 +4095,9 @@ async function bridge(args) {
|
|
|
2564
4095
|
process.exitCode = 1
|
|
2565
4096
|
return
|
|
2566
4097
|
}
|
|
4098
|
+
// Files/directories below are private conversation data; tighten the umask for
|
|
4099
|
+
// every file this process creates in the bridge tree (SEC2-09: outbox 0644).
|
|
4100
|
+
process.umask(0o077)
|
|
2567
4101
|
let mod
|
|
2568
4102
|
if (process.env.ADVISERS_BRIDGE_LOCAL === '1') {
|
|
2569
4103
|
mod = await import('../../bridge-hermes/dist/index.js')
|
|
@@ -2579,6 +4113,20 @@ async function bridge(args) {
|
|
|
2579
4113
|
const ledger = loadLedger()
|
|
2580
4114
|
const runtime = runtimeFor(ledger)
|
|
2581
4115
|
const link = new mod.HermesBridgeLink({ bridgeDir: dir, name })
|
|
4116
|
+
const libraryPollOnce = link.pollOnce.bind(link)
|
|
4117
|
+
link.pollOnce = async () => {
|
|
4118
|
+
guardBridgeInbox(dir, name)
|
|
4119
|
+
const polled = await libraryPollOnce()
|
|
4120
|
+
secureBridgeTree(dir, name)
|
|
4121
|
+
return polled
|
|
4122
|
+
}
|
|
4123
|
+
const librarySend = link.send.bind(link)
|
|
4124
|
+
link.send = async (message) => {
|
|
4125
|
+
const sent = await librarySend(sanitizeBridgeOutbound(message))
|
|
4126
|
+
secureBridgeTree(dir, name)
|
|
4127
|
+
return sent
|
|
4128
|
+
}
|
|
4129
|
+
secureBridgeTree(dir, name)
|
|
2582
4130
|
const permitSecret = process.env.ADVISERS_PERMIT_SECRET || randomUUID()
|
|
2583
4131
|
const permitGate = new core.PermitGate(permitSecret, { replay: dbStore()?.permitReplayStore() })
|
|
2584
4132
|
const host = {
|
|
@@ -2594,6 +4142,14 @@ async function bridge(args) {
|
|
|
2594
4142
|
dbStore()?.appendAudit({ actor: 'bridge', action: 'policy.deny', allowed: false, reason: context.policy.code ?? 'DENY' })
|
|
2595
4143
|
reply = context.policy.reason
|
|
2596
4144
|
}
|
|
4145
|
+
// Security audit P1-1: bridge is a model egress path; apply the same
|
|
4146
|
+
// matter-secrecy gate as chat/review/research BEFORE any network call.
|
|
4147
|
+
const bridgeEgressDenied = reply ? null : egressDeniedReason(context.matter, 'bridge')
|
|
4148
|
+
if (bridgeEgressDenied) {
|
|
4149
|
+
dbStore()?.appendAudit({ actor: 'bridge', action: 'policy.egress_deny', allowed: false, reason: 'bridge' })
|
|
4150
|
+
console.log(`[bridge] blocked: ${bridgeEgressDenied}`)
|
|
4151
|
+
reply = '[advisers] received (protected matter: model call denied)'
|
|
4152
|
+
}
|
|
2597
4153
|
const key = process.env.ADVISERS_API_KEY
|
|
2598
4154
|
if (!reply && key && process.env.ADVISERS_NO_MODEL !== '1') {
|
|
2599
4155
|
try {
|
|
@@ -2695,7 +4251,7 @@ async function office(kind, specFile, outFile) {
|
|
|
2695
4251
|
if (!result.ok) process.exitCode = 1
|
|
2696
4252
|
}
|
|
2697
4253
|
|
|
2698
|
-
function soul(sub, file) {
|
|
4254
|
+
async function soul(sub, file) {
|
|
2699
4255
|
if (sub === 'show') {
|
|
2700
4256
|
const doc = loadSoul()
|
|
2701
4257
|
if (!doc) {
|
|
@@ -2717,6 +4273,7 @@ function soul(sub, file) {
|
|
|
2717
4273
|
process.exitCode = 1
|
|
2718
4274
|
return
|
|
2719
4275
|
}
|
|
4276
|
+
await requireTosReaccept({ scope: 'config', subject: 'soul', action: 'soul set' })
|
|
2720
4277
|
const previous = loadSoul()
|
|
2721
4278
|
const content = readFileSync(file, 'utf8')
|
|
2722
4279
|
const doc = {
|
|
@@ -2735,6 +4292,7 @@ function soul(sub, file) {
|
|
|
2735
4292
|
console.log('soul.md already exists; use `advisers soul set <file>` to replace it')
|
|
2736
4293
|
return
|
|
2737
4294
|
}
|
|
4295
|
+
await requireTosReaccept({ scope: 'config', subject: 'soul', action: 'soul init' })
|
|
2738
4296
|
const doc = {
|
|
2739
4297
|
id: 'soul',
|
|
2740
4298
|
version: 1,
|
|
@@ -2753,6 +4311,308 @@ function soul(sub, file) {
|
|
|
2753
4311
|
process.exitCode = 1
|
|
2754
4312
|
}
|
|
2755
4313
|
|
|
4314
|
+
// ---------------------------------------------------------------------------
|
|
4315
|
+
// TOS consent gate (docs/TOS.md §2)
|
|
4316
|
+
//
|
|
4317
|
+
// L1: every non-exempt command requires an accepted TOS for the CURRENT version
|
|
4318
|
+
// + text hash. Missing acceptance: TTY shows a 12-line summary and requires
|
|
4319
|
+
// typing 同意; non-TTY exits 3 with a single E_TOS_REQUIRED stderr line
|
|
4320
|
+
// (`--accept-tos` / `ADVISERS_ACCEPT_TOS=1` records channel=flag|env and
|
|
4321
|
+
// nonInteractive=1, then continues). A version/text change re-requires.
|
|
4322
|
+
// L2: modification surfaces (soul set/init, routine writes, import --replace)
|
|
4323
|
+
// each need a fresh confirmation and write audit action=tos.reaccept.
|
|
4324
|
+
//
|
|
4325
|
+
// The acceptance record is ~/.advisers/tos.json (0600, atomic); the audit chain
|
|
4326
|
+
// gets action=tos.accept|tos.block|tos.reaccept|tos.revoke with a reason that
|
|
4327
|
+
// names version/sha256/channel and NEVER the terms text.
|
|
4328
|
+
// ---------------------------------------------------------------------------
|
|
4329
|
+
|
|
4330
|
+
/**
|
|
4331
|
+
* Commands usable without accepting the TOS (TOS §2.1: local functions stay usable).
|
|
4332
|
+
* TOS §2.1 / §9.8: reviewing, exporting and deleting your own local data is not
|
|
4333
|
+
* a gated feature. After a revoke the data-rights commands (privacy/export/
|
|
4334
|
+
* audit/purge), tos itself, and the other local-only commands below must stay
|
|
4335
|
+
* usable, otherwise the user must re-consent before exporting or deleting data.
|
|
4336
|
+
*/
|
|
4337
|
+
const TOS_EXEMPT_COMMANDS = new Set([
|
|
4338
|
+
'help', '--help', '-h', 'version', '--version', '-v', 'status', 'doctor', 'init', 'tos',
|
|
4339
|
+
'privacy', 'export', 'audit', 'purge',
|
|
4340
|
+
])
|
|
4341
|
+
/** Known commands. Unknown commands keep the plain "unknown command" error, not the gate. */
|
|
4342
|
+
const KNOWN_COMMANDS = new Set([
|
|
4343
|
+
'version', '--version', '-v', 'help', '--help', 'chat', 'status', 'doctor', 'init', 'history', 'mcp',
|
|
4344
|
+
'deliver', 'timestamp', 'tui', 'ocr', 'evidence', 'receipt', 'deliveries', 'learn', 'commit', 'diff',
|
|
4345
|
+
'undo', 'compact', 'search', 'nudge', 'risks', 'pet-brief', 'today', 'tick', 'ui', 'remind', 'calendar',
|
|
4346
|
+
'who', 'memory', 'digest', 'week', 'prefs', 'privacy', 'audit', 'purge', 'decay', 'correct', 'ls', 'why',
|
|
4347
|
+
'forget', 'sync', 'vault', 'export', 'import', 'backup', 'brief', 'review', 'research', 'capture', 'policy',
|
|
4348
|
+
'office-edit', 'office-read', 'verify', 'office', 'routine', 'template', 'link', 'bridge', 'soul', 'tos',
|
|
4349
|
+
])
|
|
4350
|
+
|
|
4351
|
+
/** Append a TOS audit row; audit is best-effort (JSON store has no audit chain). */
|
|
4352
|
+
function tosAudit(action, allowed, reason) {
|
|
4353
|
+
try {
|
|
4354
|
+
ensureHome()
|
|
4355
|
+
dbStore()?.appendAudit({ actor: 'local', action, allowed, reason })
|
|
4356
|
+
} catch {}
|
|
4357
|
+
}
|
|
4358
|
+
|
|
4359
|
+
/** Audit reason material: names version/sha256/channel, never the terms text. */
|
|
4360
|
+
function tosAuditReason({ version, sha256, channel, nonInteractive, extra = '' }) {
|
|
4361
|
+
return `version=${version};sha256=${sha256};channel=${channel};nonInteractive=${nonInteractive ? 1 : 0}${extra}`
|
|
4362
|
+
}
|
|
4363
|
+
|
|
4364
|
+
async function recordTosAcceptance(tos, info, { channel, nonInteractive }) {
|
|
4365
|
+
const record = tos.writeAcceptance(HOME, {
|
|
4366
|
+
version: info.version,
|
|
4367
|
+
sha256: info.sha256,
|
|
4368
|
+
acceptedAt: new Date().toISOString(),
|
|
4369
|
+
channel,
|
|
4370
|
+
nonInteractive,
|
|
4371
|
+
})
|
|
4372
|
+
tosAudit('tos.accept', true, tosAuditReason({ version: info.version, sha256: info.sha256, channel, nonInteractive, extra: ';scope=app' }))
|
|
4373
|
+
return record
|
|
4374
|
+
}
|
|
4375
|
+
|
|
4376
|
+
function tosRequiredLine(version) {
|
|
4377
|
+
return `advisers: 需要先同意使用条款 ${version}(E_TOS_REQUIRED)。运行 advisers tos show 查看全文;非交互环境加 --accept-tos 或 ADVISERS_ACCEPT_TOS=1。`
|
|
4378
|
+
}
|
|
4379
|
+
|
|
4380
|
+
function tosReacceptRequiredLine(version) {
|
|
4381
|
+
return `advisers: 此修改需要再次确认使用条款 ${version}(E_TOS_REQUIRED)。--yes 不能代替 TOS 确认;非交互环境加 --accept-tos 或 ADVISERS_ACCEPT_TOS=1(运行 advisers tos show 查看全文)。`
|
|
4382
|
+
}
|
|
4383
|
+
|
|
4384
|
+
/** TOS §2.3 "源码修改版" notice: TTY-only, non-blocking, once per fingerprint change. */
|
|
4385
|
+
async function maybeSourceModifiedNotice(tos) {
|
|
4386
|
+
try {
|
|
4387
|
+
if (!process.stdin.isTTY) return
|
|
4388
|
+
const fingerprint = tos.sourceCheckoutFingerprint()
|
|
4389
|
+
if (!fingerprint || !tos.shouldNoticeSourceModified({ home: HOME, fingerprint })) return
|
|
4390
|
+
for (const line of tos.sourceModifiedNotice({ fingerprint })) console.error(line)
|
|
4391
|
+
tos.writeSourceFingerprint(HOME, fingerprint)
|
|
4392
|
+
} catch {}
|
|
4393
|
+
}
|
|
4394
|
+
|
|
4395
|
+
/** L1 gate: run before dispatch; exits the process on block/reject (exit 3 / exit 1). */
|
|
4396
|
+
async function tosGate() {
|
|
4397
|
+
const isTTY = Boolean(process.stdin.isTTY)
|
|
4398
|
+
if (!command) { if (!isTTY) return }
|
|
4399
|
+
// Offline receipt verification must work on a clean machine without a
|
|
4400
|
+
// ~/.advisers consent record (docs/DELIVERY-RECEIPT.md); it reads only <dir>.
|
|
4401
|
+
else if (command === 'evidence' && args[0] === 'verify') return
|
|
4402
|
+
else if (TOS_EXEMPT_COMMANDS.has(command) || !KNOWN_COMMANDS.has(command)) return
|
|
4403
|
+
const tos = await loadTos()
|
|
4404
|
+
const info = tos.currentTos()
|
|
4405
|
+
const status = tos.acceptanceStatus({ home: HOME, version: info.version, sha256: info.sha256 })
|
|
4406
|
+
if (status.accepted) { await maybeSourceModifiedNotice(tos); return }
|
|
4407
|
+
const explicit = tos.resolveConsent({ flag: acceptTosFlag, env: process.env.ADVISERS_ACCEPT_TOS, version: info.version, isTTY })
|
|
4408
|
+
if (explicit?.error) { console.error(`advisers: ${explicit.error}`); process.exit(1) }
|
|
4409
|
+
if (explicit?.ok) {
|
|
4410
|
+
await recordTosAcceptance(tos, info, { channel: explicit.channel, nonInteractive: true })
|
|
4411
|
+
await maybeSourceModifiedNotice(tos)
|
|
4412
|
+
return
|
|
4413
|
+
}
|
|
4414
|
+
if (!isTTY) {
|
|
4415
|
+
tosAudit('tos.block', false, tosAuditReason({ version: info.version, sha256: info.sha256, channel: 'none', nonInteractive: true, extra: `;scope=app;reason=${status.reason}` }))
|
|
4416
|
+
console.error(tosRequiredLine(info.version))
|
|
4417
|
+
process.exit(3)
|
|
4418
|
+
}
|
|
4419
|
+
const answer = await tos.promptForConsent({ version: info.version, url: info.url })
|
|
4420
|
+
if (answer.accepted) {
|
|
4421
|
+
await recordTosAcceptance(tos, info, { channel: 'interactive', nonInteractive: false })
|
|
4422
|
+
console.log(`已接受使用条款 v${info.version}(channel=interactive);撤回:advisers tos revoke。`)
|
|
4423
|
+
await maybeSourceModifiedNotice(tos)
|
|
4424
|
+
return
|
|
4425
|
+
}
|
|
4426
|
+
tosAudit('tos.block', false, tosAuditReason({ version: info.version, sha256: info.sha256, channel: 'interactive', nonInteractive: false, extra: `;scope=app;reason=${answer.reason}` }))
|
|
4427
|
+
console.error(`未接受使用条款 v${info.version};受门控的命令已停止(运行 advisers tos show 查看全文)。`)
|
|
4428
|
+
process.exit(1)
|
|
4429
|
+
}
|
|
4430
|
+
|
|
4431
|
+
/** L2 gate: per-modification re-confirmation (TOS §2.3). Returns true when allowed. */
|
|
4432
|
+
async function requireTosReaccept({ scope, subject = '', action }) {
|
|
4433
|
+
const tos = await loadTos()
|
|
4434
|
+
const info = tos.currentTos()
|
|
4435
|
+
const isTTY = Boolean(process.stdin.isTTY)
|
|
4436
|
+
const extra = `;scope=${scope}${subject ? `;subject=${subject}` : ''};action=${action ?? '-'}`
|
|
4437
|
+
const explicit = tos.resolveConsent({ flag: acceptTosFlag, env: process.env.ADVISERS_ACCEPT_TOS, version: info.version, isTTY })
|
|
4438
|
+
if (explicit?.error) { console.error(`advisers: ${explicit.error}`); process.exit(1) }
|
|
4439
|
+
if (explicit?.ok) {
|
|
4440
|
+
tosAudit('tos.reaccept', true, tosAuditReason({ version: info.version, sha256: info.sha256, channel: explicit.channel, nonInteractive: true, extra }))
|
|
4441
|
+
return true
|
|
4442
|
+
}
|
|
4443
|
+
if (!isTTY) {
|
|
4444
|
+
tosAudit('tos.block', false, tosAuditReason({ version: info.version, sha256: info.sha256, channel: 'none', nonInteractive: true, extra: `;reason=reaccept-required${extra}` }))
|
|
4445
|
+
console.error(tosReacceptRequiredLine(info.version))
|
|
4446
|
+
process.exit(3)
|
|
4447
|
+
}
|
|
4448
|
+
const answer = await tos.promptForConsent({
|
|
4449
|
+
version: info.version,
|
|
4450
|
+
lines: tos.modificationNotice({ scope, action }),
|
|
4451
|
+
question: '继续?输入“同意”或 y 确认(n 或直接 Enter 取消):',
|
|
4452
|
+
})
|
|
4453
|
+
if (answer.accepted) {
|
|
4454
|
+
tosAudit('tos.reaccept', true, tosAuditReason({ version: info.version, sha256: info.sha256, channel: 'interactive', nonInteractive: false, extra }))
|
|
4455
|
+
console.log(`已再次确认使用条款(scope=${scope});本次确认已写入本地审计链。`)
|
|
4456
|
+
return true
|
|
4457
|
+
}
|
|
4458
|
+
tosAudit('tos.block', false, tosAuditReason({ version: info.version, sha256: info.sha256, channel: 'interactive', nonInteractive: false, extra: `;reason=rejected${extra}` }))
|
|
4459
|
+
console.error(`未确认修改(scope=${scope});操作已取消。`)
|
|
4460
|
+
process.exit(1)
|
|
4461
|
+
}
|
|
4462
|
+
|
|
4463
|
+
function tosAuditState() {
|
|
4464
|
+
if (mode !== 'sqlite') return { available: false, note: 'unavailable (json store)' }
|
|
4465
|
+
if (!existsSync(DB)) return { available: false, note: 'no audit chain yet' }
|
|
4466
|
+
try {
|
|
4467
|
+
const store = openStore()
|
|
4468
|
+
const verify = store.verifyAudit()
|
|
4469
|
+
const counts = { accept: 0, block: 0, reaccept: 0, revoke: 0 }
|
|
4470
|
+
for (const row of store.listAudit(10000)) {
|
|
4471
|
+
if (row.action === 'tos.accept') counts.accept++
|
|
4472
|
+
else if (row.action === 'tos.block') counts.block++
|
|
4473
|
+
else if (row.action === 'tos.reaccept') counts.reaccept++
|
|
4474
|
+
else if (row.action === 'tos.revoke') counts.revoke++
|
|
4475
|
+
}
|
|
4476
|
+
return { available: true, verified: verify.ok, brokenAt: verify.ok ? null : verify.seq, count: verify.count ?? 0, counts }
|
|
4477
|
+
} catch (error) {
|
|
4478
|
+
return { available: false, note: `unavailable (${error.message})` }
|
|
4479
|
+
}
|
|
4480
|
+
}
|
|
4481
|
+
|
|
4482
|
+
function tosStatusFacts(tos, info, status) {
|
|
4483
|
+
const record = status.record
|
|
4484
|
+
return {
|
|
4485
|
+
version: info.version,
|
|
4486
|
+
manifestVersion: info.manifestVersion,
|
|
4487
|
+
effectiveFrom: info.effectiveFrom,
|
|
4488
|
+
textSha256: info.sha256,
|
|
4489
|
+
canonical: info.canonical,
|
|
4490
|
+
termsPath: info.termsPath,
|
|
4491
|
+
url: info.url,
|
|
4492
|
+
accepted: status.accepted,
|
|
4493
|
+
reason: status.reason,
|
|
4494
|
+
acceptance: record ? {
|
|
4495
|
+
version: record.version,
|
|
4496
|
+
sha256: record.sha256,
|
|
4497
|
+
acceptedAt: record.acceptedAt,
|
|
4498
|
+
channel: record.channel,
|
|
4499
|
+
nonInteractive: record.nonInteractive,
|
|
4500
|
+
...(record.revokedAt ? { revokedAt: record.revokedAt } : {}),
|
|
4501
|
+
} : null,
|
|
4502
|
+
store: { type: mode, path: mode === 'sqlite' ? DB : STATE },
|
|
4503
|
+
audit: tosAuditState(),
|
|
4504
|
+
futureSeparateConsent: ['content packs / DLC (not shipped in 0.2.0)', 'text-to-speech / TTS (not shipped in 0.2.0)'],
|
|
4505
|
+
}
|
|
4506
|
+
}
|
|
4507
|
+
|
|
4508
|
+
function printTosStatus(tos, info, status, asJson) {
|
|
4509
|
+
const facts = tosStatusFacts(tos, info, status)
|
|
4510
|
+
if (asJson) { console.log(JSON.stringify(facts, null, 2)); return }
|
|
4511
|
+
const record = facts.acceptance
|
|
4512
|
+
console.log(`version ${facts.version}(生效 ${facts.effectiveFrom};manifest ${facts.manifestVersion})`)
|
|
4513
|
+
console.log(`sha256 ${facts.textSha256}`)
|
|
4514
|
+
if (facts.accepted) {
|
|
4515
|
+
console.log(`accepted yes · channel=${record.channel} · nonInteractive=${record.nonInteractive ? 1 : 0} · ${record.acceptedAt}`)
|
|
4516
|
+
} else {
|
|
4517
|
+
console.log(`accepted no · reason=${facts.reason}${record ? ` · last channel=${record.channel} · ${record.acceptedAt}` : ''}${record?.revokedAt ? ` · revokedAt=${record.revokedAt}` : ''}`)
|
|
4518
|
+
console.log('next advisers tos accept(交互输入“同意”)或非交互加 --accept-tos / ADVISERS_ACCEPT_TOS=1')
|
|
4519
|
+
}
|
|
4520
|
+
console.log(`terms ${facts.termsPath}`)
|
|
4521
|
+
console.log(`url ${facts.url}`)
|
|
4522
|
+
console.log(`store ${facts.store.type}${facts.store.path ? ` (${facts.store.path})` : ''}`)
|
|
4523
|
+
if (facts.audit.available) {
|
|
4524
|
+
const c = facts.audit.counts
|
|
4525
|
+
console.log(`audit ${facts.audit.verified ? 'verified' : `BROKEN at seq ${facts.audit.brokenAt}`} · ${facts.audit.count} entries · tos.accept=${c.accept} tos.block=${c.block} tos.reaccept=${c.reaccept} tos.revoke=${c.revoke}`)
|
|
4526
|
+
} else {
|
|
4527
|
+
console.log(`audit ${facts.audit.note}`)
|
|
4528
|
+
}
|
|
4529
|
+
console.log('future DLC / TTS are not available in 0.2.0; if they ship they will require a separate, explicit consent')
|
|
4530
|
+
}
|
|
4531
|
+
|
|
4532
|
+
function tosUsage(version = '') {
|
|
4533
|
+
console.log(`usage: advisers tos <show|status|accept|revoke>${version ? ` (当前版本 v${version})` : ''}
|
|
4534
|
+
advisers tos show 打印完整使用条款
|
|
4535
|
+
advisers tos status [--json] 版本、接受记录、审计状态(含 DLC/TTS 未来单独同意说明)
|
|
4536
|
+
advisers tos accept 接受当前使用条款(非交互需 --accept-tos 或 ADVISERS_ACCEPT_TOS=1)
|
|
4537
|
+
advisers tos revoke [--yes] 撤回同意(受门控命令随后会重新要求确认)`)
|
|
4538
|
+
}
|
|
4539
|
+
|
|
4540
|
+
async function tosCommand(argv) {
|
|
4541
|
+
const tos = await loadTos()
|
|
4542
|
+
const sub = argv[0]
|
|
4543
|
+
const info = tos.currentTos()
|
|
4544
|
+
if (!sub || sub === 'help' || sub === '--help') { tosUsage(info.version); return }
|
|
4545
|
+
const status = tos.acceptanceStatus({ home: HOME, version: info.version, sha256: info.sha256 })
|
|
4546
|
+
if (sub === 'show') {
|
|
4547
|
+
console.log(`Advisers 使用条款 v${info.version}(生效 ${info.effectiveFrom})`)
|
|
4548
|
+
console.log(`文本 SHA-256:${info.sha256}`)
|
|
4549
|
+
console.log(`规范文本:${info.canonical};随包副本:${info.termsPath};在线:${info.url}`)
|
|
4550
|
+
console.log('---')
|
|
4551
|
+
process.stdout.write(readFileSync(info.termsPath, 'utf8'))
|
|
4552
|
+
return
|
|
4553
|
+
}
|
|
4554
|
+
if (sub === 'status') { printTosStatus(tos, info, status, argv.includes('--json')); return }
|
|
4555
|
+
if (sub === 'accept') {
|
|
4556
|
+
if (status.accepted) {
|
|
4557
|
+
console.log(`已接受使用条款 v${info.version}(channel=${status.record.channel},${status.record.acceptedAt});撤回:advisers tos revoke。`)
|
|
4558
|
+
return
|
|
4559
|
+
}
|
|
4560
|
+
const isTTY = Boolean(process.stdin.isTTY)
|
|
4561
|
+
const explicit = tos.resolveConsent({ flag: acceptTosFlag, env: process.env.ADVISERS_ACCEPT_TOS, version: info.version, isTTY })
|
|
4562
|
+
if (explicit?.error) { console.error(`advisers: ${explicit.error}`); process.exitCode = 1; return }
|
|
4563
|
+
if (explicit?.ok) {
|
|
4564
|
+
await recordTosAcceptance(tos, info, { channel: explicit.channel, nonInteractive: true })
|
|
4565
|
+
console.log(`已接受使用条款 v${info.version}(channel=${explicit.channel},nonInteractive=1);已写入本地审计链。`)
|
|
4566
|
+
return
|
|
4567
|
+
}
|
|
4568
|
+
if (!isTTY) {
|
|
4569
|
+
tosAudit('tos.block', false, tosAuditReason({ version: info.version, sha256: info.sha256, channel: 'none', nonInteractive: true, extra: ';scope=app;reason=command-accept-requires-flag' }))
|
|
4570
|
+
console.error(tosRequiredLine(info.version))
|
|
4571
|
+
process.exitCode = 3
|
|
4572
|
+
return
|
|
4573
|
+
}
|
|
4574
|
+
const answer = await tos.promptForConsent({ version: info.version, url: info.url })
|
|
4575
|
+
if (answer.accepted) {
|
|
4576
|
+
await recordTosAcceptance(tos, info, { channel: 'interactive', nonInteractive: false })
|
|
4577
|
+
console.log(`已接受使用条款 v${info.version}(channel=interactive);已写入本地审计链。撤回:advisers tos revoke。`)
|
|
4578
|
+
return
|
|
4579
|
+
}
|
|
4580
|
+
tosAudit('tos.block', false, tosAuditReason({ version: info.version, sha256: info.sha256, channel: 'interactive', nonInteractive: false, extra: ';scope=app;reason=rejected' }))
|
|
4581
|
+
console.error(`未接受使用条款 v${info.version}。`)
|
|
4582
|
+
process.exitCode = 1
|
|
4583
|
+
return
|
|
4584
|
+
}
|
|
4585
|
+
if (sub === 'revoke') {
|
|
4586
|
+
const record = tos.readAcceptance(HOME)
|
|
4587
|
+
if (!record || record.revokedAt) { console.log('当前没有有效的同意记录(无需撤回)。'); return }
|
|
4588
|
+
const isTTY = Boolean(process.stdin.isTTY)
|
|
4589
|
+
const confirmedByFlag = argv.includes('--yes')
|
|
4590
|
+
if (!isTTY && !confirmedByFlag) {
|
|
4591
|
+
console.error('advisers: 撤回同意会停止受门控命令;非交互环境请加 --yes 确认(advisers tos revoke --yes)。')
|
|
4592
|
+
process.exitCode = 1
|
|
4593
|
+
return
|
|
4594
|
+
}
|
|
4595
|
+
if (isTTY && !confirmedByFlag) {
|
|
4596
|
+
const answer = await tos.promptForConsent({
|
|
4597
|
+
version: info.version,
|
|
4598
|
+
lines: ['撤回同意 · ' + `v${info.version}`, '撤回后受门控的命令会停止(help/status/doctor/tos 等本地功能仍可用)。', '撤回不影响撤回前已发生行为的效力,也不影响仓库许可证已授予的权利。'],
|
|
4599
|
+
question: '确认撤回?输入“同意”或 y 确认(n 或直接 Enter 取消):',
|
|
4600
|
+
})
|
|
4601
|
+
if (!answer.accepted) { console.log('已取消撤回。'); return }
|
|
4602
|
+
}
|
|
4603
|
+
const revoked = tos.revokeAcceptance(HOME, { revokedAt: new Date().toISOString() })
|
|
4604
|
+
if (!revoked) { console.log('当前没有有效的同意记录(无需撤回)。'); return }
|
|
4605
|
+
tosAudit('tos.revoke', true, tosAuditReason({ version: revoked.version, sha256: revoked.sha256, channel: isTTY ? 'interactive' : 'command', nonInteractive: isTTY ? false : true, extra: ';scope=app' }))
|
|
4606
|
+
console.log(`已撤回使用条款 v${info.version} 的同意;受门控的命令将重新要求确认(advisers tos accept 可重新接受)。`)
|
|
4607
|
+
return
|
|
4608
|
+
}
|
|
4609
|
+
tosUsage(info.version)
|
|
4610
|
+
process.exitCode = 1
|
|
4611
|
+
}
|
|
4612
|
+
|
|
4613
|
+
// L1 consent gate: runs once before dispatch (exempt commands return immediately).
|
|
4614
|
+
await tosGate()
|
|
4615
|
+
|
|
2756
4616
|
if (!command) {
|
|
2757
4617
|
if (process.stdin.isTTY) await repl()
|
|
2758
4618
|
else help()
|
|
@@ -2782,17 +4642,24 @@ if (!command) {
|
|
|
2782
4642
|
} else if (command === 'ocr') {
|
|
2783
4643
|
await ocrCommand(args)
|
|
2784
4644
|
} else if (command === 'evidence') {
|
|
2785
|
-
printEvidence(args)
|
|
4645
|
+
await printEvidence(args)
|
|
2786
4646
|
} else if (command === 'receipt') {
|
|
2787
4647
|
printReceipt()
|
|
2788
4648
|
} else if (command === 'deliveries') {
|
|
2789
|
-
if (args.includes('--
|
|
4649
|
+
if (args.includes('--receipt')) await receiptPack(args)
|
|
4650
|
+
else if (args.includes('--pack')) await evidencePack(args)
|
|
2790
4651
|
else if (args.includes('--json')) console.log(JSON.stringify(dbStore()?.listDeliveries(100) ?? [], null, 2))
|
|
2791
4652
|
else printDeliveries()
|
|
2792
4653
|
} else if (command === 'learn') {
|
|
2793
4654
|
const sub = args[0]
|
|
2794
4655
|
const store = dbStore()
|
|
2795
|
-
|
|
4656
|
+
let learnDenied = null
|
|
4657
|
+
if (sub === 'review') {
|
|
4658
|
+
const learnLedger = loadLedger()
|
|
4659
|
+
learnDenied = egressDeniedReason(learnLedger.getMatter(activeMatterId(learnLedger)), 'learn review')
|
|
4660
|
+
}
|
|
4661
|
+
if (sub === 'review' && learnDenied) { console.error(learnDenied); process.exitCode = 1 }
|
|
4662
|
+
else if (sub === 'ls') {
|
|
2796
4663
|
for (const r of store?.listTaskRuns(20) ?? []) console.log(`${r.id}\t${r.outcome}\t${r.tools.map((t) => t.name).join(',')}\t${r.task.slice(0, 60)}`)
|
|
2797
4664
|
} else if (sub === 'review') {
|
|
2798
4665
|
const run = store?.listTaskRuns(100).find((r) => r.id === args[1])
|
|
@@ -2800,6 +4667,7 @@ if (!command) {
|
|
|
2800
4667
|
if (!run || !apiKey) { console.error('usage: ADVISERS_API_KEY=... advisers learn review <run-id>'); process.exitCode = 1 }
|
|
2801
4668
|
else {
|
|
2802
4669
|
const ledger = loadLedger()
|
|
4670
|
+
const { reviewRun, lintReview, materializeReview } = await loadReview()
|
|
2803
4671
|
const review = await reviewRun({ run, routines: ledger.listRoutines(), apiKey, baseUrl: process.env.ADVISERS_BASE_URL, model: process.env.ADVISERS_MODEL })
|
|
2804
4672
|
const checked = lintReview(review, { run, routines: ledger.listRoutines() })
|
|
2805
4673
|
if (!checked.ok) { console.error(`review rejected: ${checked.error}`); process.exitCode = 1 }
|
|
@@ -2816,21 +4684,58 @@ if (!command) {
|
|
|
2816
4684
|
const { flags, positional } = parseFlags(args.slice(1))
|
|
2817
4685
|
if (sub === 'add') {
|
|
2818
4686
|
const action = positional.join(' ').trim()
|
|
2819
|
-
if (!action || !flags.quote) { console.error('usage: advisers commit add "<action>" --quote "<原话>" [--due ISO] [--debtor user|agent] [--creditor name] [--matter id]'); process.exitCode = 1 }
|
|
4687
|
+
if (!action || !flags.quote) { console.error('usage: advisers commit add "<action>" --quote "<原话>" [--due ISO] [--debtor user|agent] [--creditor name] [--matter id] [--remind-offsets "-1d,-2h"]'); process.exitCode = 1 }
|
|
2820
4688
|
else {
|
|
2821
|
-
|
|
2822
|
-
|
|
2823
|
-
|
|
2824
|
-
|
|
2825
|
-
|
|
2826
|
-
|
|
2827
|
-
|
|
2828
|
-
|
|
2829
|
-
|
|
2830
|
-
|
|
2831
|
-
|
|
2832
|
-
|
|
2833
|
-
|
|
4689
|
+
let reminderOffsets
|
|
4690
|
+
let offsetsError
|
|
4691
|
+
try { reminderOffsets = await parseReminderOffsetsFlag(flags) } catch (error) { offsetsError = error }
|
|
4692
|
+
if (offsetsError) { console.error(offsetsError.message); process.exitCode = 1 }
|
|
4693
|
+
else {
|
|
4694
|
+
const c = ledger.addCommitment({
|
|
4695
|
+
matterId: activeMatterId(ledger, flags.matter),
|
|
4696
|
+
debtor: flags.debtor ?? 'user',
|
|
4697
|
+
creditor: flags.creditor ?? /(?:发给|给|向|对)([\u4e00-\u9fa5A-Za-z0-9_]{1,12})/.exec(action)?.[1] ?? 'someone',
|
|
4698
|
+
action,
|
|
4699
|
+
dueAt: flags.due,
|
|
4700
|
+
timezone: flags.tz ?? 'Asia/Shanghai',
|
|
4701
|
+
capability: flags.capability ?? 'todo',
|
|
4702
|
+
evidence: [{ sessionId: latestConversationId(), turnId: 'cli', quote: String(flags.quote) }],
|
|
4703
|
+
...(reminderOffsets !== undefined ? { reminderOffsets } : {}),
|
|
4704
|
+
})
|
|
4705
|
+
saveLedgerWithAudit(ledger, { actor: 'local', action: 'commit.add', allowed: true, reason: c.id })
|
|
4706
|
+
console.log(`${c.id} open ${c.action}${c.dueAt ? ` due ${c.dueAt}` : ''}`)
|
|
4707
|
+
if (reminderOffsets !== undefined) console.log('reminder-offsets: ' + JSON.stringify(reminderOffsets))
|
|
4708
|
+
}
|
|
4709
|
+
}
|
|
4710
|
+
} else if (sub === 'edit' || sub === 'update') {
|
|
4711
|
+
const id = positional[0]
|
|
4712
|
+
const usage = 'usage: advisers commit edit <id> [--action text] [--due ISO] [--remind-offsets "<list>" | --no-remind]'
|
|
4713
|
+
if (!id) { console.error(usage); process.exitCode = 1 }
|
|
4714
|
+
else {
|
|
4715
|
+
const patch = {}
|
|
4716
|
+
if (typeof flags.action === 'string') patch.action = flags.action
|
|
4717
|
+
if (typeof flags.due === 'string') patch.dueAt = flags.due
|
|
4718
|
+
if (typeof flags.tz === 'string') patch.timezone = flags.tz
|
|
4719
|
+
if (typeof flags.capability === 'string') patch.capability = flags.capability
|
|
4720
|
+
let offsetsError
|
|
4721
|
+
try {
|
|
4722
|
+
if (flags['no-remind'] === true) patch.reminderOffsets = null
|
|
4723
|
+
else {
|
|
4724
|
+
const offsets = await parseReminderOffsetsFlag(flags)
|
|
4725
|
+
if (offsets !== undefined) patch.reminderOffsets = offsets
|
|
4726
|
+
}
|
|
4727
|
+
} catch (error) { offsetsError = error }
|
|
4728
|
+
if (offsetsError) { console.error(offsetsError.message); process.exitCode = 1 }
|
|
4729
|
+
else if (!Object.keys(patch).length) { console.error(usage); process.exitCode = 1 }
|
|
4730
|
+
else {
|
|
4731
|
+
try {
|
|
4732
|
+
const c = ledger.updateCommitment(id, patch)
|
|
4733
|
+
saveLedgerWithAudit(ledger, { actor: 'local', action: 'commit.update', allowed: true, reason: id })
|
|
4734
|
+
console.log(`updated: ${c.id}`)
|
|
4735
|
+
if ('reminderOffsets' in patch) console.log('reminder-offsets: ' + JSON.stringify(c.reminderOffsets ?? []))
|
|
4736
|
+
if (patch.dueAt !== undefined) console.log('due: ' + (c.dueAt ?? '未定'))
|
|
4737
|
+
} catch (error) { console.error(error.message); process.exitCode = 1 }
|
|
4738
|
+
}
|
|
2834
4739
|
}
|
|
2835
4740
|
} else if (sub === 'ls') printCommitments(ledger, flags.json)
|
|
2836
4741
|
else if (sub === 'snooze') {
|
|
@@ -2840,9 +4745,7 @@ if (!command) {
|
|
|
2840
4745
|
if (!c || !Number.isFinite(hours) || hours <= 0) { console.error('usage: advisers commit snooze <id> <hours>'); process.exitCode = 1 }
|
|
2841
4746
|
else {
|
|
2842
4747
|
c.status = 'snoozed'
|
|
2843
|
-
|
|
2844
|
-
saveLedger(ledger)
|
|
2845
|
-
dbStore()?.appendAudit({ actor: 'local', action: 'commit.snooze', allowed: true, reason: id })
|
|
4748
|
+
saveLedgerWithAudit(ledger, { actor: 'local', action: 'commit.snooze', allowed: true, reason: id }, (store) => store.setMeta(`snooze:${id}`, new Date(Date.now() + hours * 3600_000).toISOString()))
|
|
2846
4749
|
console.log(`snoozed: ${id} for ${hours}h`)
|
|
2847
4750
|
}
|
|
2848
4751
|
}
|
|
@@ -2855,17 +4758,18 @@ if (!command) {
|
|
|
2855
4758
|
console.error(`evidence file not found: ${String(evidence).slice(5)}`); process.exitCode = 1
|
|
2856
4759
|
} else {
|
|
2857
4760
|
ledger.completeCommitment(id, [{ sessionId: latestConversationId(), turnId: 'cli', quote: String(evidence) }])
|
|
2858
|
-
|
|
2859
|
-
dbStore()?.appendAudit({ actor: 'local', action: 'commit.done', allowed: true, reason: id })
|
|
4761
|
+
saveLedgerWithAudit(ledger, { actor: 'local', action: 'commit.done', allowed: true, reason: id })
|
|
2860
4762
|
console.log(`done: ${id}`)
|
|
2861
4763
|
}
|
|
2862
4764
|
}
|
|
2863
|
-
} else { console.error('usage: advisers commit add|ls|done'); process.exitCode = 1 }
|
|
4765
|
+
} else { console.error('usage: advisers commit add|edit|ls|done|snooze'); process.exitCode = 1 }
|
|
2864
4766
|
} else if (command === 'diff') {
|
|
4767
|
+
const { diffLatest } = await loadUndo()
|
|
2865
4768
|
const result = await diffLatest({ cwd: process.cwd(), backupDir: join(HOME, 'undo') })
|
|
2866
4769
|
console.log(result.ok ? result.diff : `diff failed: ${result.error}`)
|
|
2867
4770
|
if (!result.ok) process.exitCode = 1
|
|
2868
4771
|
} else if (command === 'undo') {
|
|
4772
|
+
const { listBackups, undoLatest } = await loadUndo()
|
|
2869
4773
|
if (args.includes('--list')) {
|
|
2870
4774
|
for (const row of await listBackups(join(HOME, 'undo'), { workspace: process.cwd() })) console.log(`${row.id}\t${row.path}\t${row.existed ? 'overwrite' : 'create'}`)
|
|
2871
4775
|
} else {
|
|
@@ -2907,7 +4811,7 @@ if (!command) {
|
|
|
2907
4811
|
} else if (command === 'pet-brief') {
|
|
2908
4812
|
await petBrief(args)
|
|
2909
4813
|
} else if (command === 'today') {
|
|
2910
|
-
today(loadLedger(), { calendar: args.includes('--calendar'), sources: args.includes('--sources') })
|
|
4814
|
+
await today(loadLedger(), { calendar: args.includes('--calendar'), sources: args.includes('--sources'), json: args.includes('--json') })
|
|
2911
4815
|
} else if (command === 'tick') {
|
|
2912
4816
|
tick(loadLedger(), args.includes('--json'))
|
|
2913
4817
|
} else if (command === 'ui') {
|
|
@@ -2915,7 +4819,7 @@ if (!command) {
|
|
|
2915
4819
|
} else if (command === 'remind') {
|
|
2916
4820
|
await remind(args)
|
|
2917
4821
|
} else if (command === 'calendar') {
|
|
2918
|
-
calendarImport(args.slice(1))
|
|
4822
|
+
await calendarImport(args.slice(1))
|
|
2919
4823
|
} else if (command === 'who') {
|
|
2920
4824
|
const open = loadLedger().openCommitments()
|
|
2921
4825
|
const mine = open.filter((c) => c.debtor === 'user' || c.debtor === 'agent')
|
|
@@ -2930,9 +4834,12 @@ if (!command) {
|
|
|
2930
4834
|
} else if (command === 'memory') {
|
|
2931
4835
|
const ledger = loadLedger()
|
|
2932
4836
|
if (args[0] === 'candidates') {
|
|
2933
|
-
const rows = dbStore()?.listCandidates(args
|
|
2934
|
-
if (
|
|
2935
|
-
|
|
4837
|
+
const rows = dbStore()?.listCandidates(args.includes('--all') ? 'all' : 'pending') ?? []
|
|
4838
|
+
if (args.includes('--json')) console.log(JSON.stringify(rows, null, 2))
|
|
4839
|
+
else {
|
|
4840
|
+
if (!rows.length) console.log('(没有待确认记忆)')
|
|
4841
|
+
for (const c of rows) console.log(`${c.id}\t${c.kind}\t${JSON.stringify(c.payload)}\t${c.status}`)
|
|
4842
|
+
}
|
|
2936
4843
|
} else if (args[0] === 'accept') {
|
|
2937
4844
|
const store = dbStore()
|
|
2938
4845
|
const candidate = store?.getCandidate(args[1])
|
|
@@ -2949,9 +4856,7 @@ if (!command) {
|
|
|
2949
4856
|
if (candidate.kind === 'fact') ledger.remember({ ...candidate.payload, authority: 'user', evidence: candidate.evidence.map(sourceRef) })
|
|
2950
4857
|
else if (candidate.kind === 'preference') ledger.addPreference({ ...candidate.payload, evidence: candidate.evidence.map(sourceRef) })
|
|
2951
4858
|
else if (candidate.kind === 'commitment') ledger.addCommitment({ ...candidate.payload, matterId: candidate.payload.matterId ?? ledger.listMatters()[0]?.id, evidence: candidate.evidence.map(commitmentEvidence) })
|
|
2952
|
-
|
|
2953
|
-
saveLedger(ledger)
|
|
2954
|
-
store.appendAudit({ actor: 'local', action: 'memory.accept', allowed: true, reason: candidate.id })
|
|
4859
|
+
saveLedgerWithAudit(ledger, { actor: 'local', action: 'memory.accept', allowed: true, reason: candidate.id }, (s) => s.reviewCandidate(candidate.id, 'accepted'))
|
|
2955
4860
|
console.log(`accepted ${candidate.id}`)
|
|
2956
4861
|
} catch (error) { console.error(error.message); process.exitCode = 1 }
|
|
2957
4862
|
}
|
|
@@ -2960,8 +4865,7 @@ if (!command) {
|
|
|
2960
4865
|
const candidate = store?.getCandidate(args[1])
|
|
2961
4866
|
if (!candidate) { console.error('candidate not found'); process.exitCode = 1 }
|
|
2962
4867
|
else {
|
|
2963
|
-
|
|
2964
|
-
store.appendAudit({ actor: 'local', action: 'memory.reject', allowed: true, reason: candidate.id })
|
|
4868
|
+
updateStoreWithAudit((s) => s.reviewCandidate(candidate.id, 'rejected', args.slice(2).join(' ') || undefined), { actor: 'local', action: 'memory.reject', allowed: true, reason: candidate.id })
|
|
2965
4869
|
console.log(`rejected ${candidate.id}`)
|
|
2966
4870
|
}
|
|
2967
4871
|
} else if (args[0] === 'search') {
|
|
@@ -2979,6 +4883,7 @@ if (!command) {
|
|
|
2979
4883
|
} else if (command === 'digest') {
|
|
2980
4884
|
const period = args[0] === 'week' ? 'week' : 'day'
|
|
2981
4885
|
const store = dbStore()
|
|
4886
|
+
const { buildDigest } = await loadDigest()
|
|
2982
4887
|
console.log(buildDigest({
|
|
2983
4888
|
period,
|
|
2984
4889
|
turns: store?.listTurns(latestConversationId(), 200) ?? [],
|
|
@@ -2992,11 +4897,12 @@ if (!command) {
|
|
|
2992
4897
|
} else if (command === 'privacy') {
|
|
2993
4898
|
printPrivacy(args)
|
|
2994
4899
|
} else if (command === 'audit') {
|
|
2995
|
-
printAudit()
|
|
4900
|
+
printAudit(args)
|
|
2996
4901
|
} else if (command === 'purge') {
|
|
2997
4902
|
purgeMatter(args[0], args.includes('--yes'))
|
|
2998
4903
|
} else if (command === 'decay') {
|
|
2999
4904
|
const ledger = loadLedger()
|
|
4905
|
+
const { applyPreferenceDecay } = await loadLearning()
|
|
3000
4906
|
const changed = applyPreferenceDecay(ledger.listPreferences({ includeCandidates: true }))
|
|
3001
4907
|
saveLedger(ledger)
|
|
3002
4908
|
console.log(`[decay] ${changed.length} preference(s) updated`)
|
|
@@ -3006,8 +4912,7 @@ if (!command) {
|
|
|
3006
4912
|
else {
|
|
3007
4913
|
const ledger = loadLedger()
|
|
3008
4914
|
const result = learnPreference(ledger, statement, statement, { explicit: true })
|
|
3009
|
-
|
|
3010
|
-
saveLedger(ledger)
|
|
4915
|
+
saveLedgerWithAudit(ledger, { actor: 'local', action: 'correct', allowed: true, reason: result.preference.id })
|
|
3011
4916
|
printLearnReceipt(result)
|
|
3012
4917
|
}
|
|
3013
4918
|
} else if (command === 'ls') {
|
|
@@ -3017,18 +4922,18 @@ if (!command) {
|
|
|
3017
4922
|
} else if (command === 'forget') {
|
|
3018
4923
|
forget(args[0])
|
|
3019
4924
|
} else if (command === 'sync') {
|
|
3020
|
-
syncCommand(args)
|
|
4925
|
+
await syncCommand(args)
|
|
3021
4926
|
} else if (command === 'vault') {
|
|
3022
4927
|
const sub = args[0]
|
|
3023
|
-
if (sub === 'seal') vaultSeal(args.slice(1))
|
|
3024
|
-
else if (sub === 'unseal') vaultUnseal(args.slice(1))
|
|
4928
|
+
if (sub === 'seal') await vaultSeal(args.slice(1))
|
|
4929
|
+
else if (sub === 'unseal') await vaultUnseal(args.slice(1))
|
|
3025
4930
|
else if (sub === 'status' || !sub) vaultStatus()
|
|
3026
4931
|
else { console.error('usage: advisers vault seal [--out file] [--remove] | unseal [file] | status'); process.exitCode = 1 }
|
|
3027
4932
|
} else if (command === 'export') {
|
|
3028
4933
|
const { flags } = parseFlags(args)
|
|
3029
|
-
exportLedger(flags.all === true || args.includes('--all'), { encrypted: args.includes('--encrypted'), out: typeof flags.out === 'string' ? flags.out : undefined })
|
|
4934
|
+
await exportLedger(flags.all === true || args.includes('--all'), { encrypted: args.includes('--encrypted'), out: typeof flags.out === 'string' ? flags.out : undefined })
|
|
3030
4935
|
} else if (command === 'import') {
|
|
3031
|
-
importLedger(args.find((a) => !a.startsWith('--')), { replace: args.includes('--replace') })
|
|
4936
|
+
await importLedger(args.find((a) => !a.startsWith('--')), { replace: args.includes('--replace') })
|
|
3032
4937
|
} else if (command === 'backup') {
|
|
3033
4938
|
backup(args[0])
|
|
3034
4939
|
} else if (command === 'brief') {
|
|
@@ -3070,7 +4975,10 @@ if (!command) {
|
|
|
3070
4975
|
if (!file) { console.error('usage: advisers office-read <file>'); process.exitCode = 1 }
|
|
3071
4976
|
else {
|
|
3072
4977
|
if (file.toLowerCase().endsWith('.ofd')) {
|
|
3073
|
-
try {
|
|
4978
|
+
try {
|
|
4979
|
+
const { ofdText } = await loadAttachments()
|
|
4980
|
+
console.log(await ofdText(readFileSync(file)))
|
|
4981
|
+
} catch (error) { console.error(`ofd read failed: ${error.message}`); process.exitCode = 1 }
|
|
3074
4982
|
} else {
|
|
3075
4983
|
let mod
|
|
3076
4984
|
if (process.env.ADVISERS_OFFICE_LOCAL === '1') mod = await import('../../office/dist/index.js')
|
|
@@ -3080,30 +4988,34 @@ if (!command) {
|
|
|
3080
4988
|
}
|
|
3081
4989
|
}
|
|
3082
4990
|
} else if (command === 'verify') {
|
|
3083
|
-
const
|
|
3084
|
-
|
|
4991
|
+
const { flags, positional } = parseFlags(args)
|
|
4992
|
+
const file = positional[0]
|
|
4993
|
+
if (!file) { console.error('usage: advisers verify <file> [--json] [--content]'); process.exitCode = 1 }
|
|
3085
4994
|
else {
|
|
3086
4995
|
const ext = file.split('.').pop()?.toLowerCase()
|
|
3087
4996
|
if (!['docx', 'xlsx', 'pptx'].includes(ext)) { console.error('verify supports docx/xlsx/pptx'); process.exitCode = 1 }
|
|
3088
4997
|
else {
|
|
3089
|
-
|
|
3090
|
-
|
|
3091
|
-
|
|
3092
|
-
|
|
3093
|
-
|
|
3094
|
-
|
|
3095
|
-
|
|
3096
|
-
|
|
3097
|
-
|
|
3098
|
-
|
|
3099
|
-
|
|
4998
|
+
try {
|
|
4999
|
+
const verifyOffice = await loadOfficeOperation('verify', 'verifyOffice')
|
|
5000
|
+
const result = await verifyOffice(readFileSync(file), ext)
|
|
5001
|
+
if (flags.content === true) {
|
|
5002
|
+
const checkOffice = await loadOfficeOperation('check', 'checkOffice')
|
|
5003
|
+
const content = await checkOffice(readFileSync(file), ext)
|
|
5004
|
+
console.log(JSON.stringify({ structure: result, content }, null, 2))
|
|
5005
|
+
if (!content.ok) process.exitCode = 1
|
|
5006
|
+
} else console.log(JSON.stringify(result, null, 2))
|
|
5007
|
+
if (!result.ok) process.exitCode = 1
|
|
5008
|
+
} catch (error) {
|
|
5009
|
+
console.error(`verify failed: ${error.message}`)
|
|
5010
|
+
process.exitCode = 1
|
|
5011
|
+
}
|
|
3100
5012
|
}
|
|
3101
5013
|
}
|
|
3102
5014
|
} else if (command === 'office') {
|
|
3103
5015
|
await office(args[0], args[1], args[2])
|
|
3104
5016
|
process.exit(process.exitCode || 0)
|
|
3105
5017
|
} else if (command === 'routine') {
|
|
3106
|
-
routine(args[0], args[1], args[2])
|
|
5018
|
+
await routine(args[0], args[1], args[2])
|
|
3107
5019
|
} else if (command === 'template') {
|
|
3108
5020
|
await template(args[0], args[1], args[2])
|
|
3109
5021
|
process.exit(process.exitCode || 0)
|
|
@@ -3112,7 +5024,9 @@ if (!command) {
|
|
|
3112
5024
|
} else if (command === 'bridge') {
|
|
3113
5025
|
await bridge(args)
|
|
3114
5026
|
} else if (command === 'soul') {
|
|
3115
|
-
soul(args[0], args[1])
|
|
5027
|
+
await soul(args[0], args[1])
|
|
5028
|
+
} else if (command === 'tos') {
|
|
5029
|
+
await tosCommand(args)
|
|
3116
5030
|
} else {
|
|
3117
5031
|
console.error(`unknown command: ${command}`)
|
|
3118
5032
|
help()
|