advisers 0.2.0-preview.71 → 0.2.0
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 +32 -6
- package/README.md +36 -7
- package/THIRD-PARTY-NOTICES.md +277 -0
- package/bin/advisers.js +1634 -290
- package/index.js +1 -1
- package/lib/attachments.js +153 -27
- 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 +129 -3
- package/lib/pdf.js +44 -6
- package/lib/pet-brief.js +78 -15
- package/lib/receipt-verify.js +624 -0
- package/lib/remind.js +261 -11
- package/lib/research.js +142 -18
- package/lib/safety/classifier.js +392 -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 +361 -37
- package/lib/sync.js +58 -13
- 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 +7 -6
package/bin/advisers.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
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
6
|
import { basename, dirname, extname, join } from 'node:path'
|
|
@@ -15,7 +16,6 @@ try {
|
|
|
15
16
|
}
|
|
16
17
|
import { runAgent } from '../lib/agent.js'
|
|
17
18
|
import { chatCompletion } from '../lib/model.js'
|
|
18
|
-
import { extractAttachment, ofdText } from '../lib/attachments.js'
|
|
19
19
|
import { applyPreferenceDecay, buildRoutineCandidate, correctionStatement } from '../lib/learning.js'
|
|
20
20
|
import { checkRoutine } from '../lib/routine.js'
|
|
21
21
|
import { backupBeforeWrite, diffLatest, listBackups, undoLatest } from '../lib/undo.js'
|
|
@@ -27,18 +27,52 @@ import { egressDeniedReason } from '../lib/egress.js'
|
|
|
27
27
|
import { research as runResearch } from '../lib/research.js'
|
|
28
28
|
import { reviewDocument } from '../lib/doc-review.js'
|
|
29
29
|
import { buildHistory, buildOpening, buildPins, continuityProbes, ensurePins, fitHistory, shouldSummarize, summarizeTurns } from '../lib/context-window.js'
|
|
30
|
-
import {
|
|
31
|
-
|
|
32
|
-
|
|
30
|
+
import {
|
|
31
|
+
PET_BRIEF_DEFAULT_DISPLAY_POLICY,
|
|
32
|
+
PET_BRIEF_DISPLAY_POLICIES,
|
|
33
|
+
PET_BRIEF_MAX_ITEMS,
|
|
34
|
+
PET_BRIEF_MAX_LINE_LENGTH,
|
|
35
|
+
PET_BRIEF_MAX_SUGGESTED_LINES,
|
|
36
|
+
PET_BRIEF_MOODS,
|
|
37
|
+
PET_BRIEF_SCHEMA_VERSION,
|
|
38
|
+
PET_BRIEF_SOURCE,
|
|
39
|
+
buildPetBrief,
|
|
40
|
+
validatePetBrief,
|
|
41
|
+
writePetBriefAtomic,
|
|
42
|
+
} from '../lib/pet-brief.js'
|
|
33
43
|
import { fetchImapMessages } from '../lib/imap.js'
|
|
34
|
-
import { buildEvidencePack, evidenceForCommitment, evidenceForFact, evidenceForPreference, sha256Hex, toDocxRows, verifyPack } from '../lib/evidence.js'
|
|
35
44
|
import { createReadOnlyServer } from '../lib/ui.js'
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
import
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* P1-1: lazy-load the heavy / rarely used libraries.
|
|
48
|
+
*
|
|
49
|
+
* Before this, every invocation (including `advisers --version`) paid for the
|
|
50
|
+
* whole static import graph: pdf-lib + fontkit was ~106ms / +34MB RSS and
|
|
51
|
+
* jszip (via attachments) ~22ms / +10MB, plus importers/evidence/sync/vault/
|
|
52
|
+
* ocr/timestamp/notify/remind which only a subset of commands needs. Each
|
|
53
|
+
* loader memoizes its module promise, so a command that needs a library pays
|
|
54
|
+
* for it at most once, and it fails on first use instead of at startup.
|
|
55
|
+
*/
|
|
56
|
+
const lazyModule = (loader) => {
|
|
57
|
+
let promise
|
|
58
|
+
return () => (promise ??= loader())
|
|
59
|
+
}
|
|
60
|
+
const loadAttachments = lazyModule(() => import('../lib/attachments.js'))
|
|
61
|
+
const loadEvidence = lazyModule(() => import('../lib/evidence.js'))
|
|
62
|
+
const loadIcal = lazyModule(() => import('../lib/ical.js'))
|
|
63
|
+
const loadImporters = lazyModule(() => import('../lib/importers.js'))
|
|
64
|
+
const loadNotify = lazyModule(() => import('../lib/notify.js'))
|
|
65
|
+
const loadReceiptVerify = lazyModule(() => import('../lib/receipt-verify.js'))
|
|
66
|
+
const loadScheduler = lazyModule(() => import('../lib/scheduler.js'))
|
|
67
|
+
const loadSource = lazyModule(() => import('../lib/source.js'))
|
|
68
|
+
const loadOcr = lazyModule(() => import('../lib/ocr.js'))
|
|
69
|
+
const loadPdf = lazyModule(() => import('../lib/pdf.js'))
|
|
70
|
+
const loadRemind = lazyModule(() => import('../lib/remind.js'))
|
|
71
|
+
const loadSync = lazyModule(() => import('../lib/sync.js'))
|
|
72
|
+
const loadTimestamp = lazyModule(() => import('../lib/timestamp.js'))
|
|
73
|
+
const loadVault = lazyModule(() => import('../lib/vault.js'))
|
|
74
|
+
const loadTos = lazyModule(() => import('../lib/tos/index.js'))
|
|
75
|
+
const loadMcpServer = lazyModule(() => import('../lib/mcp-server.js'))
|
|
42
76
|
|
|
43
77
|
let core
|
|
44
78
|
if (process.env.ADVISERS_CORE_LOCAL === '1') {
|
|
@@ -64,18 +98,53 @@ const DB = join(HOME, 'state.db')
|
|
|
64
98
|
let mode = process.env.ADVISERS_STORE === 'json' ? 'json' : 'sqlite'
|
|
65
99
|
let activeStore
|
|
66
100
|
|
|
101
|
+
/**
|
|
102
|
+
* P0-1: one shared ICU formatter instead of `new Intl.DateTimeFormat` per
|
|
103
|
+
* commitment. The old today()/tick() code built a fresh formatter for every
|
|
104
|
+
* date comparison (~4 per commitment), so 25k open commitments instantiated
|
|
105
|
+
* ~100k ICU objects: 3.5s and 1.6GB RSS. Intl.DateTimeFormat instances cost
|
|
106
|
+
* ~49µs/~17KB and are not tracked in the V8 heap.
|
|
107
|
+
*/
|
|
108
|
+
const DAY_FORMAT = new Intl.DateTimeFormat('en-CA', { timeZone: 'Asia/Shanghai' })
|
|
109
|
+
/** Asia/Shanghai calendar day (YYYY-MM-DD) for a Date, timestamp or ISO string. */
|
|
110
|
+
const localDayOf = (value) => DAY_FORMAT.format(new Date(value))
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* P1-6: default upper bound for `advisers deliver` (open commitments).
|
|
114
|
+
* --all lifts it; the command always reports the untruncated total.
|
|
115
|
+
*/
|
|
116
|
+
const DELIVER_DEFAULT_LIMIT = 500
|
|
117
|
+
|
|
67
118
|
const AUDIT_KEY_FILE = join(HOME, 'audit.key')
|
|
119
|
+
function readAuditKey() {
|
|
120
|
+
const key = readFileSync(AUDIT_KEY_FILE, 'utf8').trim()
|
|
121
|
+
if (key.length < 16) throw new Error(`audit key file is too short (${key.length} chars, expected >= 16): ${AUDIT_KEY_FILE}`)
|
|
122
|
+
return key
|
|
123
|
+
}
|
|
68
124
|
function ensureAuditKey() {
|
|
69
125
|
if (process.env.ADVISERS_AUDIT_KEY) return
|
|
70
126
|
try {
|
|
71
127
|
if (existsSync(AUDIT_KEY_FILE)) {
|
|
72
|
-
|
|
73
|
-
|
|
128
|
+
process.env.ADVISERS_AUDIT_KEY = readAuditKey()
|
|
129
|
+
return
|
|
74
130
|
}
|
|
75
131
|
const key = randomBytes(32).toString('hex')
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
132
|
+
try {
|
|
133
|
+
// P0-4: O_EXCL so two first-run processes agree on exactly one key. The
|
|
134
|
+
// loser must read the winner's key, not overwrite it (that would leave
|
|
135
|
+
// rows signed with a key that no longer exists on disk).
|
|
136
|
+
writeFileSync(AUDIT_KEY_FILE, key, { mode: 0o600, flag: 'wx' })
|
|
137
|
+
process.env.ADVISERS_AUDIT_KEY = key
|
|
138
|
+
} catch (error) {
|
|
139
|
+
if (error?.code !== 'EEXIST') throw error
|
|
140
|
+
process.env.ADVISERS_AUDIT_KEY = readAuditKey()
|
|
141
|
+
}
|
|
142
|
+
} catch (error) {
|
|
143
|
+
console.error(`advisers: audit key unavailable (${error.message})`)
|
|
144
|
+
console.error(` expected a readable ${AUDIT_KEY_FILE} with at least 16 characters.`)
|
|
145
|
+
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).')
|
|
146
|
+
process.exit(1)
|
|
147
|
+
}
|
|
79
148
|
}
|
|
80
149
|
function ensureHome() {
|
|
81
150
|
mkdirSync(HOME, { recursive: true, mode: 0o700 })
|
|
@@ -83,9 +152,22 @@ function ensureHome() {
|
|
|
83
152
|
ensureAuditKey()
|
|
84
153
|
}
|
|
85
154
|
|
|
155
|
+
/**
|
|
156
|
+
* P1-1: core ids are `${prefix}_${Date.now().toString(36)}_${seq}` with a
|
|
157
|
+
* per-process counter, so two CLIs started in the same millisecond can mint the
|
|
158
|
+
* same commitment id and one row would overwrite the other on save. Add a
|
|
159
|
+
* process-unique segment so ids from concurrent commands never collide.
|
|
160
|
+
*/
|
|
161
|
+
const PROCESS_ID = process.pid.toString(36) + randomBytes(2).toString('hex')
|
|
162
|
+
let localIdSeq = 0
|
|
163
|
+
const LOCAL_PORTS = {
|
|
164
|
+
clock: { now: () => new Date().toISOString() },
|
|
165
|
+
ids: { next: (prefix) => `${prefix}_${Date.now().toString(36)}_${PROCESS_ID}_${++localIdSeq}` },
|
|
166
|
+
}
|
|
167
|
+
|
|
86
168
|
function loadJson() {
|
|
87
|
-
if (!existsSync(STATE)) return new Ledger()
|
|
88
|
-
return Ledger.fromJSON(JSON.parse(readFileSync(STATE, 'utf8')))
|
|
169
|
+
if (!existsSync(STATE)) return new Ledger(LOCAL_PORTS)
|
|
170
|
+
return Ledger.fromJSON(JSON.parse(readFileSync(STATE, 'utf8')), LOCAL_PORTS)
|
|
89
171
|
}
|
|
90
172
|
|
|
91
173
|
function saveJson(ledger) {
|
|
@@ -93,10 +175,13 @@ function saveJson(ledger) {
|
|
|
93
175
|
writeFileSync(STATE, JSON.stringify(ledger.toJSON(), null, 2) + '\n')
|
|
94
176
|
}
|
|
95
177
|
|
|
96
|
-
function openStore() {
|
|
178
|
+
function openStore({ checkIntegrity = false } = {}) {
|
|
97
179
|
if (!activeStore) {
|
|
98
|
-
|
|
180
|
+
ensureHome()
|
|
181
|
+
activeStore = new SqliteStore(DB, { checkIntegrity })
|
|
99
182
|
try { chmodSync(DB, 0o600) } catch {}
|
|
183
|
+
} else if (checkIntegrity) {
|
|
184
|
+
activeStore.assertIntegrity()
|
|
100
185
|
}
|
|
101
186
|
return activeStore
|
|
102
187
|
}
|
|
@@ -110,7 +195,7 @@ function loadLedger() {
|
|
|
110
195
|
openStore().save(ledger.toJSON())
|
|
111
196
|
return ledger
|
|
112
197
|
}
|
|
113
|
-
return Ledger.fromJSON(openStore().load())
|
|
198
|
+
return Ledger.fromJSON(openStore().load(), LOCAL_PORTS)
|
|
114
199
|
} catch (error) {
|
|
115
200
|
console.error(`sqlite unavailable: ${error.message}`)
|
|
116
201
|
console.error('Run `advisers doctor`; refusing to silently switch to JSON (would split the ledger).')
|
|
@@ -118,18 +203,65 @@ function loadLedger() {
|
|
|
118
203
|
}
|
|
119
204
|
}
|
|
120
205
|
|
|
206
|
+
function exitStoreWriteFailure(error) {
|
|
207
|
+
// P0-2: never fall back to state.json. The SQLite database is the only ledger
|
|
208
|
+
// once it exists, so a JSON fallback would silently split the book (and the
|
|
209
|
+
// command would still exit 0). Fail loudly instead.
|
|
210
|
+
console.error(`advisers: could not write the ledger to ${DB}: ${error.message}`)
|
|
211
|
+
console.error('Nothing was written to state.json; the SQLite database is the only ledger, so this command did not apply.')
|
|
212
|
+
console.error('Retry the command; if it keeps failing run `advisers doctor` (or `advisers audit --check-db`).')
|
|
213
|
+
process.exit(1)
|
|
214
|
+
}
|
|
215
|
+
|
|
121
216
|
function saveLedger(ledger) {
|
|
122
217
|
ensureHome()
|
|
123
218
|
if (mode === 'json') return saveJson(ledger)
|
|
124
219
|
try {
|
|
125
|
-
openStore().save(ledger.toJSON())
|
|
220
|
+
return openStore().save(ledger.toJSON())
|
|
126
221
|
} catch (error) {
|
|
127
|
-
|
|
128
|
-
mode = 'json'
|
|
129
|
-
saveJson(ledger)
|
|
222
|
+
exitStoreWriteFailure(error)
|
|
130
223
|
}
|
|
131
224
|
}
|
|
132
225
|
|
|
226
|
+
function saveLedgerWithAudit(ledger, audit, inside) {
|
|
227
|
+
ensureHome()
|
|
228
|
+
if (mode === 'json') return saveJson(ledger)
|
|
229
|
+
try {
|
|
230
|
+
return openStore().saveWithAudit(ledger.toJSON(), audit, inside)
|
|
231
|
+
} catch (error) {
|
|
232
|
+
exitStoreWriteFailure(error)
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
function updateStoreWithAudit(fn, audit) {
|
|
237
|
+
ensureHome()
|
|
238
|
+
const store = dbStore()
|
|
239
|
+
if (!store) return
|
|
240
|
+
try {
|
|
241
|
+
return store.transaction(() => {
|
|
242
|
+
fn(store)
|
|
243
|
+
return store.appendAudit(audit)
|
|
244
|
+
})
|
|
245
|
+
} catch (error) {
|
|
246
|
+
exitStoreWriteFailure(error)
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
function recordDeliveryWithAudit({ files, tool, title, validation, audit }) {
|
|
251
|
+
const store = dbStore()
|
|
252
|
+
if (!store) return
|
|
253
|
+
let matterId = 'matter'
|
|
254
|
+
try { matterId = activeMatterId(loadLedger()) } catch {}
|
|
255
|
+
updateStoreWithAudit((s) => s.addDelivery({
|
|
256
|
+
matterId,
|
|
257
|
+
conversationId: latestConversationId(),
|
|
258
|
+
files,
|
|
259
|
+
tool,
|
|
260
|
+
title,
|
|
261
|
+
validation: typeof validation === 'string' ? validation : JSON.stringify(validation),
|
|
262
|
+
}), audit)
|
|
263
|
+
}
|
|
264
|
+
|
|
133
265
|
function loadSoul() {
|
|
134
266
|
if (!existsSync(SOUL)) return undefined
|
|
135
267
|
const meta = existsSync(SOUL_META) ? JSON.parse(readFileSync(SOUL_META, 'utf8')) : {}
|
|
@@ -149,11 +281,47 @@ function saveSoul(doc) {
|
|
|
149
281
|
writeFileSync(SOUL_META, JSON.stringify({ version: doc.version, updatedAt: doc.updatedAt }, null, 2) + '\n', { mode: 0o600 })
|
|
150
282
|
}
|
|
151
283
|
|
|
284
|
+
/** Write bytes to an already-created same-directory temp file and fsync it. */
|
|
285
|
+
function writeDurableTemp(target, bytes, { mode = 0o600 } = {}) {
|
|
286
|
+
const fd = openSync(target, 'wx', mode)
|
|
287
|
+
try {
|
|
288
|
+
writeSync(fd, bytes)
|
|
289
|
+
fsyncSync(fd)
|
|
290
|
+
} finally {
|
|
291
|
+
closeSync(fd)
|
|
292
|
+
}
|
|
293
|
+
return target
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
/** fsync a directory entry so a rename survives a crash. */
|
|
297
|
+
function fsyncDir(path) {
|
|
298
|
+
try {
|
|
299
|
+
const fd = openSync(path, 'r')
|
|
300
|
+
try { fsyncSync(fd) } finally { closeSync(fd) }
|
|
301
|
+
} catch {}
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
/** Atomic write: same-directory temp + fsync + rename + directory fsync. */
|
|
305
|
+
function atomicWriteFileSync(path, bytes, { mode = 0o600 } = {}) {
|
|
306
|
+
mkdirSync(dirname(path), { recursive: true })
|
|
307
|
+
const tmp = join(dirname(path), `.${basename(path)}.tmp-${process.pid}-${randomBytes(4).toString('hex')}`)
|
|
308
|
+
try {
|
|
309
|
+
writeDurableTemp(tmp, bytes, { mode })
|
|
310
|
+
renameSync(tmp, path)
|
|
311
|
+
} catch (error) {
|
|
312
|
+
try { if (existsSync(tmp)) rmSync(tmp) } catch {}
|
|
313
|
+
throw error
|
|
314
|
+
}
|
|
315
|
+
try { chmodSync(path, mode) } catch {}
|
|
316
|
+
fsyncDir(dirname(path))
|
|
317
|
+
return path
|
|
318
|
+
}
|
|
319
|
+
|
|
152
320
|
const soulStore = { load: loadSoul, save: saveSoul }
|
|
153
321
|
|
|
154
322
|
function runtimeFor(ledger) {
|
|
155
323
|
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' }) } })
|
|
324
|
+
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
325
|
}
|
|
158
326
|
|
|
159
327
|
async function backupCliFile(path) {
|
|
@@ -270,7 +438,19 @@ function friendlyError(error) {
|
|
|
270
438
|
}
|
|
271
439
|
process.on('uncaughtException', (error) => { console.error(`advisers: ${friendlyError(error)}`); process.exit(1) })
|
|
272
440
|
process.on('unhandledRejection', (error) => { console.error(`advisers: ${friendlyError(error)}`); process.exit(1) })
|
|
273
|
-
|
|
441
|
+
/**
|
|
442
|
+
* TOS gate: `--accept-tos[=<version>]` is a global pre-dispatch flag, so it is
|
|
443
|
+
* stripped from argv before the command is parsed (it may appear before or after
|
|
444
|
+
* the command name). The value is resolved by lib/tos when the gate runs.
|
|
445
|
+
*/
|
|
446
|
+
const rawArgv = process.argv.slice(2)
|
|
447
|
+
let acceptTosFlag
|
|
448
|
+
for (let index = rawArgv.length - 1; index >= 0; index--) {
|
|
449
|
+
const value = rawArgv[index]
|
|
450
|
+
if (value === '--accept-tos') { acceptTosFlag = true; rawArgv.splice(index, 1) }
|
|
451
|
+
else if (value.startsWith('--accept-tos=')) { acceptTosFlag = value.slice('--accept-tos='.length); rawArgv.splice(index, 1) }
|
|
452
|
+
}
|
|
453
|
+
const [command, ...args] = rawArgv
|
|
274
454
|
|
|
275
455
|
function help() {
|
|
276
456
|
console.log(`advisers — a staff of AI advisers
|
|
@@ -285,12 +465,16 @@ Usage:
|
|
|
285
465
|
advisers history recent conversations
|
|
286
466
|
advisers search <text> full-text search old turns
|
|
287
467
|
advisers compact ls|rollback summary versions
|
|
288
|
-
advisers today [--calendar]
|
|
289
|
-
|
|
290
|
-
advisers remind
|
|
468
|
+
advisers today [--calendar] [--sources] [--json]
|
|
469
|
+
one-screen today/week/waiting view (+ local events)
|
|
470
|
+
advisers remind [--json] [--ics [path]] [--deliver [--notify]] due reminders + ICS/VALARM export
|
|
471
|
+
advisers remind install|uninstall|status [--apply] [--schedule "0 9 * * *"]
|
|
472
|
+
scheduler scripts + OS plan (dry-run by default; --apply executes)
|
|
473
|
+
status also shows the last recorded run (scheduler/status.json)
|
|
291
474
|
advisers calendar import --ics <file> local .ics read-only import
|
|
292
475
|
advisers risks up to 3 deterministic obligation risks
|
|
293
|
-
advisers pet-brief [--json] [--out [path]] [--check]
|
|
476
|
+
advisers pet-brief [--json] [--out [path]] [--check [--strict]] [--display-policy public|private|none]
|
|
477
|
+
read-only redacted Pet Brief (contract v0.2); --print-schema prints the JSON Schema
|
|
294
478
|
advisers tick due commitments in the next 7 days
|
|
295
479
|
advisers week last 7 days
|
|
296
480
|
advisers digest day|week short digest
|
|
@@ -300,14 +484,17 @@ Usage:
|
|
|
300
484
|
advisers learn review <id> LLM routine review (needs API key)
|
|
301
485
|
advisers memory what I remember
|
|
302
486
|
advisers memory search <q> search facts/preferences
|
|
303
|
-
advisers memory candidates pending memory candidates
|
|
487
|
+
advisers memory candidates [--json] [--all] pending memory candidates
|
|
304
488
|
advisers memory accept|reject <id>
|
|
305
489
|
advisers prefs [--all] | correct <text>
|
|
306
490
|
advisers nudge list|done|ignore <id> nudge outcomes
|
|
307
491
|
advisers decay apply 30-day preference decay
|
|
308
492
|
advisers audit verify the local audit hash chain
|
|
309
493
|
advisers purge <matter> [--yes] privacy delete a matter
|
|
310
|
-
advisers commit add|ls|done|snooze commitments
|
|
494
|
+
advisers commit add|edit|ls|done|snooze commitments
|
|
495
|
+
advisers commit add "..." --quote "..." [--remind-offsets "-1d,-2h"]
|
|
496
|
+
advisers commit edit <id> [--remind-offsets "<list>" | --no-remind]
|
|
497
|
+
per-commitment reminder offsets (Asia/Shanghai wall clock)
|
|
311
498
|
advisers deliveries recent generated files
|
|
312
499
|
advisers receipt one-screen delivery receipt
|
|
313
500
|
advisers ls list matters
|
|
@@ -325,23 +512,26 @@ Usage:
|
|
|
325
512
|
advisers review <file> --request "..." model content review (no edits)
|
|
326
513
|
advisers research --web|--url <url> [--deep] <query>
|
|
327
514
|
server-side web search/read URL with citations (explicit egress)
|
|
328
|
-
advisers capture [--file f] [--source s] [--date ISO] [--matter id] <text>
|
|
515
|
+
advisers capture [--file f] [--source s] [--date ISO] [--matter id] [--json] <text>
|
|
329
516
|
从中文工作内容抽取候选承诺(不自动入账)
|
|
330
517
|
advisers capture --from-mail <file|dir> [--limit n] .eml/.mbox 只读导入→候选
|
|
331
518
|
advisers capture --from-transcript <file> 转写稿导入→候选(不录音/不入会)
|
|
332
519
|
advisers capture --from-imap 只读 IMAP 导入(EXAMINE/FETCH;env 凭据)
|
|
333
520
|
advisers ui [--port n] 本地只读视图(127.0.0.1,GET only)
|
|
334
|
-
advisers mcp --stdio
|
|
521
|
+
advisers mcp --stdio MCP server(7 工具 + 4 resources;写入口仅 pending 候选/回执校验)
|
|
335
522
|
advisers evidence show <id> [--json] 承诺/事实/偏好→原文来源
|
|
336
523
|
advisers deliver [--commit id] [--type confirmation|weekly|statement|ledger] [--format docx|xlsx|pdf] [--out f] 交付物
|
|
337
524
|
advisers deliveries --pack [--out dir] 证据包(manifest/README/SHA256SUMS + DOCX 回执)
|
|
525
|
+
advisers deliveries --receipt [--out dir] [--ids ...] [--all] [--recipient "Name <mail>"]
|
|
526
|
+
交付回执包 v1.1(交付文件副本 + 全文件 SHA-256 + 证据;默认上限 2000)
|
|
527
|
+
advisers evidence verify <dir> 离线校验回执包(JSON,exit 0/1;不读账本、不联网)
|
|
338
528
|
advisers policy check <text> policy/crisis check
|
|
339
529
|
advisers office-read <file> read DOCX/XLSX/PPTX/OFD text
|
|
340
530
|
advisers ocr <image> [--out text] local OCR adapter (ADVISERS_OCR_CMD; no cloud)
|
|
341
531
|
advisers timestamp <file> [--out proof] local timestamp/signing adapter
|
|
342
532
|
advisers tui [--once] read-only terminal dashboard
|
|
343
533
|
advisers office-edit <file> <ops.json> [out] surgical Office edit
|
|
344
|
-
advisers verify <file> [--content] structural + deterministic content checks
|
|
534
|
+
advisers verify <file> [--json] [--content] structural + deterministic content checks
|
|
345
535
|
advisers office <kind> <spec.json> <out>
|
|
346
536
|
build docx/xlsx/pptx/xmind/mermaid/drawio
|
|
347
537
|
advisers routine ls list routines
|
|
@@ -376,6 +566,7 @@ Usage:
|
|
|
376
566
|
advisers soul show print soul.md
|
|
377
567
|
advisers soul set <file> set soul.md from a file (human action)
|
|
378
568
|
advisers soul init write a minimal starter soul.md
|
|
569
|
+
advisers tos show|status [--json]|accept|revoke 使用条款:全文/状态/接受/撤回
|
|
379
570
|
advisers help
|
|
380
571
|
|
|
381
572
|
Environment:
|
|
@@ -386,6 +577,15 @@ Environment:
|
|
|
386
577
|
ADVISERS_YES=1 skip the plan confirmation
|
|
387
578
|
ADVISERS_FORCE=1 overwrite existing files without asking
|
|
388
579
|
ADVISERS_PROGRESS=0 hide [tool] progress lines
|
|
580
|
+
ADVISERS_ACCEPT_TOS=1 record TOS consent without a TTY (same as --accept-tos)
|
|
581
|
+
ADVISERS_NOTIFY_WEBHOOK optional outbound webhook for remind --deliver --notify
|
|
582
|
+
|
|
583
|
+
Exit codes:
|
|
584
|
+
0 success
|
|
585
|
+
1 user/config/runtime error (bad args, missing key, unknown id, failed verification)
|
|
586
|
+
3 TOS consent required: non-interactive command blocked by the consent gate.
|
|
587
|
+
Run \`advisers tos accept\` in a TTY, or pass --accept-tos / ADVISERS_ACCEPT_TOS=1.
|
|
588
|
+
\`advisers evidence verify <dir>\` is offline/read-only and exempt from the gate.
|
|
389
589
|
`)
|
|
390
590
|
}
|
|
391
591
|
|
|
@@ -433,15 +633,14 @@ function purgeMatter(id, confirmed) {
|
|
|
433
633
|
}
|
|
434
634
|
const counts = ledger.purgeMatter(id)
|
|
435
635
|
const sqlite = dbStore()?.purgeMatterData(id)
|
|
436
|
-
|
|
437
|
-
saveLedger(ledger)
|
|
636
|
+
saveLedgerWithAudit(ledger, { actor: 'local', action: 'matter.purge', allowed: true, reason: `${id} ${JSON.stringify(counts)}` })
|
|
438
637
|
console.log(`purged: ${JSON.stringify(counts)} sqlite=${JSON.stringify(sqlite ?? {})}`)
|
|
439
638
|
}
|
|
440
639
|
|
|
441
640
|
function parseFlags(args) {
|
|
442
641
|
const flags = {}
|
|
443
642
|
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'])
|
|
643
|
+
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
644
|
for (let i = 0; i < args.length; i++) {
|
|
446
645
|
if (args[i].startsWith('--')) {
|
|
447
646
|
const key = args[i].slice(2)
|
|
@@ -452,6 +651,20 @@ function parseFlags(args) {
|
|
|
452
651
|
return { flags, positional }
|
|
453
652
|
}
|
|
454
653
|
|
|
654
|
+
/**
|
|
655
|
+
* Read --remind / --remind-offsets from parsed flags and strictly normalise.
|
|
656
|
+
* `--remind -1d` is a one-offset alias of `--remind-offsets "-1d,-2h"`.
|
|
657
|
+
* Returns undefined when neither flag was given; invalid input throws.
|
|
658
|
+
*/
|
|
659
|
+
async function parseReminderOffsetsFlag(flags) {
|
|
660
|
+
const raw = flags['remind-offsets'] !== undefined ? flags['remind-offsets'] : flags.remind
|
|
661
|
+
if (raw === undefined) return undefined
|
|
662
|
+
if (raw === true) throw new Error('--remind-offsets requires a value, e.g. --remind-offsets "-1d,-2h" or --remind -1d')
|
|
663
|
+
const list = String(raw).split(',').map((item) => item.trim()).filter(Boolean)
|
|
664
|
+
const { normalizeReminderOffsets } = await loadRemind()
|
|
665
|
+
return normalizeReminderOffsets(list)
|
|
666
|
+
}
|
|
667
|
+
|
|
455
668
|
function recordManualDelivery(files, tool, title, validation) {
|
|
456
669
|
try {
|
|
457
670
|
const store = dbStore()
|
|
@@ -534,83 +747,182 @@ function risks(ledger) {
|
|
|
534
747
|
for (const line of out.slice(0, 3)) console.log(`- ${line}`)
|
|
535
748
|
}
|
|
536
749
|
|
|
537
|
-
|
|
538
|
-
|
|
750
|
+
/**
|
|
751
|
+
* Read-side provenance compatibility (source v2): stored v1 source rows are
|
|
752
|
+
* normalised before display so mail/transcript/IMAP provenance renders the same
|
|
753
|
+
* way regardless of when the row was written. Read-only: normalizeSource() is
|
|
754
|
+
* pure and never touches the database.
|
|
755
|
+
*/
|
|
756
|
+
async function collectSourceRows(ledger) {
|
|
757
|
+
const { normalizeSource } = await loadSource()
|
|
539
758
|
const rows = []
|
|
540
|
-
for (const c of
|
|
759
|
+
for (const c of ledger.listCommitments()) {
|
|
541
760
|
for (const e of c.evidence ?? []) {
|
|
542
|
-
const
|
|
543
|
-
|
|
761
|
+
const source = normalizeSource(e.source)
|
|
762
|
+
const type = source?.type ?? 'conversation'
|
|
763
|
+
rows.push({
|
|
764
|
+
commitmentId: c.id,
|
|
765
|
+
action: c.action,
|
|
766
|
+
type,
|
|
767
|
+
ref: source?.ref ?? (e.sessionId ? `${e.sessionId}#${e.turnId}` : (e.turnId ?? null)),
|
|
768
|
+
label: `${type}${source?.subject ? `:${source.subject}` : source?.messageId ? `:${source.messageId}` : source?.file ? `:${source.file}` : ''}`,
|
|
769
|
+
quote: e.quote ?? '',
|
|
770
|
+
source: source ?? null,
|
|
771
|
+
})
|
|
544
772
|
}
|
|
545
773
|
}
|
|
774
|
+
return rows
|
|
775
|
+
}
|
|
776
|
+
|
|
777
|
+
async function printSources(ledger) {
|
|
778
|
+
const rows = await collectSourceRows(ledger)
|
|
546
779
|
if (!rows.length) { console.log('来源:还没有可回溯的承诺来源;先 capture/导入并 accept。'); return }
|
|
547
780
|
console.log('来源(承诺 → 本地入口):')
|
|
548
|
-
for (const r of rows.slice(0, 20)) console.log(` ${r.
|
|
781
|
+
for (const r of rows.slice(0, 20)) console.log(` ${r.commitmentId} ${r.action} ← ${r.label} (${r.ref ?? '-'}) 「${r.quote.slice(0, 80)}」`)
|
|
549
782
|
}
|
|
550
783
|
|
|
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
|
|
784
|
+
async function today(ledger, { calendar = false, sources = false, json = false } = {}) {
|
|
785
|
+
const nowMs = Date.now()
|
|
786
|
+
const localDay = localDayOf(nowMs)
|
|
787
|
+
const weekAhead = nowMs + 7 * 86400_000
|
|
788
|
+
// P0-1: classify in one pass, formatting each due date at most once (the old
|
|
789
|
+
// four filters called day() up to four times per commitment).
|
|
790
|
+
const overdue = []
|
|
791
|
+
const todayDue = []
|
|
792
|
+
const week = []
|
|
793
|
+
const waiting = []
|
|
794
|
+
const noDue = []
|
|
795
|
+
for (const c of ledger.openCommitments()) {
|
|
796
|
+
if (c.debtor === 'third' || c.debtor.startsWith('third:')) waiting.push(c)
|
|
797
|
+
if (!c.dueAt) { noDue.push(c); continue }
|
|
798
|
+
const due = Date.parse(c.dueAt)
|
|
799
|
+
if (due < nowMs) {
|
|
800
|
+
if (localDayOf(c.dueAt) !== localDay) overdue.push(c)
|
|
801
|
+
else todayDue.push(c)
|
|
802
|
+
} else if (localDayOf(c.dueAt) === localDay) {
|
|
803
|
+
todayDue.push(c)
|
|
804
|
+
} else if (due <= weekAhead) {
|
|
805
|
+
week.push(c)
|
|
806
|
+
}
|
|
807
|
+
}
|
|
808
|
+
const next = [...overdue, ...todayDue, ...week].sort((a, b) => Date.parse(a.dueAt) - Date.parse(b.dueAt))[0]
|
|
809
|
+
if (json) {
|
|
810
|
+
// JSON contract v1 (docs/CLI-JSON.md): same classification as the human view.
|
|
811
|
+
const payload = {
|
|
812
|
+
now: new Date(nowMs).toISOString(),
|
|
813
|
+
localDay,
|
|
814
|
+
counts: { today: todayDue.length, overdue: overdue.length, week: week.length, waiting: waiting.length, noDue: noDue.length },
|
|
815
|
+
overdue,
|
|
816
|
+
today: todayDue,
|
|
817
|
+
week,
|
|
818
|
+
waiting,
|
|
819
|
+
noDue,
|
|
820
|
+
next: next ? { id: next.id, action: next.action, dueAt: next.dueAt } : null,
|
|
821
|
+
}
|
|
822
|
+
if (calendar) payload.calendar = (await calendarOccurrencesToday()).occurrences
|
|
823
|
+
if (sources) {
|
|
824
|
+
payload.sources = (await collectSourceRows(ledger)).map(({ commitmentId, action, type, ref, quote }) => ({ commitmentId, action, type, ref, quote }))
|
|
825
|
+
}
|
|
826
|
+
console.log(JSON.stringify(payload, null, 2))
|
|
827
|
+
return
|
|
828
|
+
}
|
|
561
829
|
console.log(`今天:${todayDue.length} · 逾期:${overdue.length} · 未来 7 天:${week.length} · 等别人:${waiting.length} · 无截止:${noDue.length}`)
|
|
562
830
|
for (const [label, list] of [['逾期', overdue], ['今天', todayDue], ['未来 7 天', week], ['等别人', waiting]]) {
|
|
563
831
|
if (!list.length) continue
|
|
564
832
|
console.log(`${label}:`)
|
|
565
833
|
for (const c of list.slice(0, 5)) console.log(` ${c.id} ${c.creditor} · ${c.action}${c.dueAt ? ` · ${c.dueAt.slice(0, 10)}` : ''}`)
|
|
566
834
|
}
|
|
567
|
-
console.log('下一件:' + (
|
|
568
|
-
if (calendar) printCalendarToday()
|
|
569
|
-
if (sources) printSources(ledger)
|
|
835
|
+
console.log('下一件:' + (next?.action ?? '先定一个承诺或交付。'))
|
|
836
|
+
if (calendar) await printCalendarToday()
|
|
837
|
+
if (sources) await printSources(ledger)
|
|
570
838
|
}
|
|
571
839
|
|
|
572
840
|
function tick(ledger, asJson = false) {
|
|
573
841
|
const now = Date.now()
|
|
574
842
|
const store = dbStore()
|
|
575
|
-
const localDay =
|
|
843
|
+
const localDay = localDayOf(now)
|
|
844
|
+
const weekAhead = now + 7 * 86400_000
|
|
576
845
|
const due = []
|
|
846
|
+
const candidates = []
|
|
847
|
+
const snoozeKeys = []
|
|
848
|
+
let statusChanged = false
|
|
849
|
+
// P0-2: one meta query for every snooze deadline instead of getMeta() per
|
|
850
|
+
// snoozed commitment.
|
|
851
|
+
const snoozeUntil = store ? store.listMetaByPrefix('snooze:') : new Map()
|
|
577
852
|
for (const c of ledger.listCommitments()) {
|
|
578
853
|
if (c.status === 'done' || c.status === 'dropped') continue
|
|
579
854
|
if (c.status === 'snoozed') {
|
|
580
|
-
const until =
|
|
855
|
+
const until = snoozeUntil.get(`snooze:${c.id}`)
|
|
581
856
|
if (until && Date.parse(until) > now) continue
|
|
582
857
|
c.status = 'open'
|
|
583
|
-
|
|
858
|
+
statusChanged = true
|
|
859
|
+
snoozeKeys.push(`snooze:${c.id}`)
|
|
584
860
|
}
|
|
585
|
-
if (!c.dueAt || Date.parse(c.dueAt) >
|
|
586
|
-
|
|
861
|
+
if (!c.dueAt || Date.parse(c.dueAt) > weekAhead) continue
|
|
862
|
+
candidates.push(c)
|
|
863
|
+
}
|
|
864
|
+
// P0-2: replace the per-commitment N+1 queries (listCommitmentNudges +
|
|
865
|
+
// countNudges) with three batch reads: recent outcomes per commitment,
|
|
866
|
+
// today's level counts and today's existing (commitment, level) keys.
|
|
867
|
+
const recentByCommitment = store && candidates.length ? store.recentNudgeOutcomes(3) : new Map()
|
|
868
|
+
const levelCounts = store && candidates.length ? store.countNudgesByDay(localDay) : new Map()
|
|
869
|
+
const existingKeys = store && candidates.length ? store.listNudgeLevelKeysByDay(localDay) : new Set()
|
|
870
|
+
const pendingKeys = new Set()
|
|
871
|
+
let l3Today = levelCounts.get('L3') ?? 0
|
|
872
|
+
let l2Today = levelCounts.get('L2') ?? 0
|
|
873
|
+
const nudgeRows = []
|
|
874
|
+
for (const c of candidates) {
|
|
875
|
+
const dueDay = localDayOf(c.dueAt)
|
|
587
876
|
const msLeft = Date.parse(c.dueAt) - now
|
|
588
877
|
let level = (msLeft < 0 || dueDay === localDay) ? 'L2' : 'L1'
|
|
589
878
|
if (level === 'L2' && Date.parse(c.dueAt) < now - 86400_000 && process.env.ADVISERS_ALLOW_L3 === '1') level = 'L3'
|
|
590
|
-
const recent =
|
|
591
|
-
if (recent.length === 3 && recent.every((
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
879
|
+
const recent = recentByCommitment.get(c.id) ?? []
|
|
880
|
+
if (recent.length === 3 && recent.every((outcome) => outcome === 'ignored') && level !== 'L1') level = level === 'L3' ? 'L2' : 'L1'
|
|
881
|
+
// Budgets keep the historical in-run semantics: a nudge already written by
|
|
882
|
+
// this tick counts toward the caps of the commitments that follow it, but a
|
|
883
|
+
// deduped (already present) key does not.
|
|
884
|
+
if (level === 'L3' && l3Today >= 1) level = 'L2'
|
|
885
|
+
if (level === 'L2' && l2Today >= 3) level = 'L1'
|
|
886
|
+
const key = `${c.id}\u0000${level}`
|
|
887
|
+
if (!existingKeys.has(key) && !pendingKeys.has(key)) {
|
|
888
|
+
if (level === 'L3') l3Today++
|
|
889
|
+
else if (level === 'L2') l2Today++
|
|
890
|
+
pendingKeys.add(key)
|
|
891
|
+
}
|
|
892
|
+
nudgeRows.push({ localDay, level, commitmentId: c.id, body: c.action })
|
|
595
893
|
due.push({ ...c, level })
|
|
596
894
|
}
|
|
597
|
-
|
|
895
|
+
// P0-2: one transaction for all nudge inserts and one for snooze cleanup;
|
|
896
|
+
// the ledger snapshot is only rewritten when a snooze actually woke up.
|
|
897
|
+
if (store && nudgeRows.length) store.addNudges(nudgeRows)
|
|
898
|
+
if (store && snoozeKeys.length) store.deleteMetaKeys(snoozeKeys)
|
|
899
|
+
if (statusChanged) saveLedger(ledger)
|
|
598
900
|
if (asJson) {
|
|
599
901
|
console.log(JSON.stringify({ now: new Date(now).toISOString(), localDay, due }, null, 2))
|
|
600
902
|
return
|
|
601
903
|
}
|
|
602
904
|
if (!due.length) { console.log('未来 7 天无到期。'); return }
|
|
603
905
|
for (const c of due) {
|
|
604
|
-
const dueDay =
|
|
906
|
+
const dueDay = localDayOf(c.dueAt)
|
|
605
907
|
const label = Date.parse(c.dueAt) < now ? '逾期' : dueDay === localDay ? '今天到期' : '即将到期'
|
|
606
908
|
console.log(`[${c.level}] ${label}:${c.action}(${c.dueAt})`)
|
|
607
909
|
}
|
|
608
910
|
}
|
|
609
911
|
|
|
610
|
-
function printAudit() {
|
|
912
|
+
function printAudit(args = []) {
|
|
611
913
|
ensureHome()
|
|
612
914
|
const store = dbStore()
|
|
613
915
|
if (!store) { console.log('audit requires SQLite store'); return }
|
|
916
|
+
if (args.includes('--check-db')) {
|
|
917
|
+
try {
|
|
918
|
+
store.assertIntegrity()
|
|
919
|
+
console.log('integrity: ok')
|
|
920
|
+
} catch (error) {
|
|
921
|
+
console.error(`integrity: FAIL (${error.message})`)
|
|
922
|
+
process.exitCode = 1
|
|
923
|
+
return
|
|
924
|
+
}
|
|
925
|
+
}
|
|
614
926
|
const verify = store.verifyAudit()
|
|
615
927
|
console.log(`audit: ${verify.ok ? 'verified' : `BROKEN at seq ${verify.seq}`} (${verify.count ?? 0} entries)`)
|
|
616
928
|
if (!verify.ok) process.exitCode = 1
|
|
@@ -656,9 +968,9 @@ function printPrivacy(args = []) {
|
|
|
656
968
|
['home exists', existsSync(HOME)],
|
|
657
969
|
['database exists', existsSync(DB)],
|
|
658
970
|
['audit verified', Boolean(audit?.ok)],
|
|
659
|
-
['telemetry disabled',
|
|
660
|
-
['network
|
|
661
|
-
['secret matter fail-closed',
|
|
971
|
+
['telemetry disabled', facts.telemetry === 'none'],
|
|
972
|
+
['no default network egress', facts.default_egress === 'none'],
|
|
973
|
+
['secret matter fail-closed', (() => { try { return Boolean(egressDeniedReason({ secrecy: 1 }, 'prove')) && !egressDeniedReason({ secrecy: 0 }, 'prove') } catch { return false } })()],
|
|
662
974
|
]
|
|
663
975
|
let failed = 0
|
|
664
976
|
for (const [name, ok] of checks) { if (!ok) failed++; console.log(`[${ok ? 'PASS' : 'FAIL'}] ${name}`) }
|
|
@@ -677,29 +989,143 @@ function printLinks() {
|
|
|
677
989
|
}
|
|
678
990
|
|
|
679
991
|
/**
|
|
680
|
-
*
|
|
992
|
+
* JSON Schema (draft 2020-12) for the Pet Brief contract v0.2, generated from
|
|
993
|
+
* the exported lib constants so `--print-schema` also works from the published
|
|
994
|
+
* package (docs/pet-brief/schema-v0.2.json is not in the npm `files`
|
|
995
|
+
* allowlist). The test suite asserts the generated document is deep-equal to
|
|
996
|
+
* the canonical snapshot in docs/pet-brief/schema-v0.2.json.
|
|
997
|
+
*/
|
|
998
|
+
function petBriefJsonSchema() {
|
|
999
|
+
const maxItems = PET_BRIEF_MAX_ITEMS
|
|
1000
|
+
const id = { type: 'string', minLength: 1, maxLength: 64 }
|
|
1001
|
+
const confidence = { type: 'number', minimum: 0, maximum: 1 }
|
|
1002
|
+
const arrayOf = (required, properties) => ({
|
|
1003
|
+
type: 'array',
|
|
1004
|
+
maxItems,
|
|
1005
|
+
items: { type: 'object', additionalProperties: false, required, properties },
|
|
1006
|
+
})
|
|
1007
|
+
return {
|
|
1008
|
+
$schema: 'https://json-schema.org/draft/2020-12/schema',
|
|
1009
|
+
$id: 'https://github.com/PerryLink/advisers/docs/pet-brief/schema-v0.2.json',
|
|
1010
|
+
title: 'Advisers Pet Brief (contract v0.2)',
|
|
1011
|
+
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.',
|
|
1012
|
+
type: 'object',
|
|
1013
|
+
additionalProperties: false,
|
|
1014
|
+
required: ['schemaVersion', 'generatedAt', 'expiresAt', 'source', 'displayPolicy', 'counts', 'today', 'commitments', 'risks', 'facts', 'mood', 'suggestedLines', 'redactions'],
|
|
1015
|
+
properties: {
|
|
1016
|
+
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.' },
|
|
1017
|
+
generatedAt: { type: 'string', format: 'date-time' },
|
|
1018
|
+
expiresAt: { type: 'string', format: 'date-time', description: 'generatedAt + 5 min by default; consumers discard the brief when now >= expiresAt.' },
|
|
1019
|
+
source: { type: 'string', const: PET_BRIEF_SOURCE },
|
|
1020
|
+
displayPolicy: {
|
|
1021
|
+
type: 'string',
|
|
1022
|
+
enum: [...PET_BRIEF_DISPLAY_POLICIES],
|
|
1023
|
+
default: PET_BRIEF_DEFAULT_DISPLAY_POLICY,
|
|
1024
|
+
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.',
|
|
1025
|
+
},
|
|
1026
|
+
counts: {
|
|
1027
|
+
type: 'object',
|
|
1028
|
+
additionalProperties: false,
|
|
1029
|
+
required: ['today', 'commitments', 'risks', 'facts'],
|
|
1030
|
+
properties: {
|
|
1031
|
+
today: { type: 'integer', minimum: 0, maximum: maxItems },
|
|
1032
|
+
commitments: { type: 'integer', minimum: 0, maximum: maxItems },
|
|
1033
|
+
risks: { type: 'integer', minimum: 0, maximum: maxItems },
|
|
1034
|
+
facts: { type: 'integer', minimum: 0, maximum: maxItems },
|
|
1035
|
+
},
|
|
1036
|
+
},
|
|
1037
|
+
today: arrayOf(['id', 'title', 'status'], {
|
|
1038
|
+
id,
|
|
1039
|
+
title: { type: 'string', minLength: 1, maxLength: 80 },
|
|
1040
|
+
status: { type: 'string', enum: ['open', 'doing', 'done'] },
|
|
1041
|
+
}),
|
|
1042
|
+
commitments: arrayOf(['id', 'matter', 'who', 'what', 'due', 'risk', 'confidence'], {
|
|
1043
|
+
id,
|
|
1044
|
+
matter: { type: 'string', minLength: 1, maxLength: 64 },
|
|
1045
|
+
who: { type: 'string', minLength: 1, maxLength: 40 },
|
|
1046
|
+
what: { type: 'string', minLength: 1, maxLength: 80 },
|
|
1047
|
+
due: { type: 'string', minLength: 1, maxLength: 32 },
|
|
1048
|
+
risk: { type: 'string', enum: ['low', 'medium', 'high'] },
|
|
1049
|
+
confidence,
|
|
1050
|
+
}),
|
|
1051
|
+
risks: arrayOf(['id', 'level', 'summary', 'evidence', 'confidence'], {
|
|
1052
|
+
id,
|
|
1053
|
+
level: { type: 'string', enum: ['low', 'medium', 'high'] },
|
|
1054
|
+
summary: { type: 'string', minLength: 1, maxLength: 80 },
|
|
1055
|
+
evidence: { type: 'string', minLength: 1, maxLength: 64 },
|
|
1056
|
+
confidence,
|
|
1057
|
+
}),
|
|
1058
|
+
facts: arrayOf(['id', 'subject', 'predicate', 'value', 'confidence'], {
|
|
1059
|
+
id,
|
|
1060
|
+
subject: { type: 'string', minLength: 1, maxLength: 40 },
|
|
1061
|
+
predicate: { type: 'string', minLength: 1, maxLength: 40 },
|
|
1062
|
+
value: { type: 'string', minLength: 1, maxLength: 80 },
|
|
1063
|
+
confidence,
|
|
1064
|
+
}),
|
|
1065
|
+
mood: { type: 'string', enum: [...PET_BRIEF_MOODS], description: 'Workload-only rendering hint, never an emotional state about the user.' },
|
|
1066
|
+
suggestedLines: {
|
|
1067
|
+
type: 'array',
|
|
1068
|
+
maxItems: PET_BRIEF_MAX_SUGGESTED_LINES,
|
|
1069
|
+
items: { type: 'string', minLength: 1, maxLength: PET_BRIEF_MAX_LINE_LENGTH },
|
|
1070
|
+
},
|
|
1071
|
+
redactions: {
|
|
1072
|
+
type: 'array',
|
|
1073
|
+
maxItems,
|
|
1074
|
+
items: { type: 'string', minLength: 1, maxLength: 80 },
|
|
1075
|
+
},
|
|
1076
|
+
},
|
|
1077
|
+
}
|
|
1078
|
+
}
|
|
1079
|
+
|
|
1080
|
+
/**
|
|
1081
|
+
* `advisers pet-brief` — read-only projection for the pet (contract v0.2).
|
|
681
1082
|
* Never opens the store read-write, never calls a model, never writes the
|
|
682
1083
|
* ledger. The only write is the optional `--out` file (0600, atomic rename).
|
|
1084
|
+
*
|
|
1085
|
+
* CLI surface: `--json`, `--out [path]`, `--check [--strict] [--in file]`,
|
|
1086
|
+
* `--display-policy public|private|none` and `--print-schema`. Warnings from
|
|
1087
|
+
* the validator are reported but never change the exit code (strict mode turns
|
|
1088
|
+
* legacy/missing-displayPolicy into errors instead).
|
|
683
1089
|
*/
|
|
684
1090
|
async function petBrief(args) {
|
|
685
1091
|
const { flags } = parseFlags(args)
|
|
686
1092
|
const asJson = args.includes('--json')
|
|
687
1093
|
const check = args.includes('--check')
|
|
1094
|
+
const strict = args.includes('--strict')
|
|
1095
|
+
const printSchema = args.includes('--print-schema')
|
|
688
1096
|
const inFile = flags.in
|
|
689
1097
|
const outFlag = flags.out
|
|
1098
|
+
const displayPolicyFlag = flags['display-policy']
|
|
690
1099
|
const fail = (code, message) => {
|
|
691
1100
|
console.error(JSON.stringify({ error: { code, message } }))
|
|
692
1101
|
process.exitCode = 1
|
|
693
1102
|
}
|
|
1103
|
+
if (printSchema) {
|
|
1104
|
+
if (inFile !== undefined || outFlag !== undefined || displayPolicyFlag !== undefined || asJson || check) {
|
|
1105
|
+
return fail('E_USAGE', '--print-schema cannot be combined with other pet-brief options')
|
|
1106
|
+
}
|
|
1107
|
+
console.log(JSON.stringify(petBriefJsonSchema(), null, 2))
|
|
1108
|
+
return
|
|
1109
|
+
}
|
|
694
1110
|
if (inFile !== undefined && !check) return fail('E_USAGE', '--in can only be used with --check')
|
|
695
1111
|
if (inFile !== undefined && typeof inFile !== 'string') return fail('E_USAGE', '--in needs a file path')
|
|
696
1112
|
if (outFlag !== undefined && typeof outFlag !== 'string' && outFlag !== true) return fail('E_USAGE', '--out takes an optional file path')
|
|
1113
|
+
if (strict && !check) return fail('E_USAGE', '--strict can only be used with --check')
|
|
1114
|
+
let displayPolicy
|
|
1115
|
+
if (displayPolicyFlag !== undefined) {
|
|
1116
|
+
if (typeof displayPolicyFlag !== 'string' || !PET_BRIEF_DISPLAY_POLICIES.includes(displayPolicyFlag)) {
|
|
1117
|
+
return fail('E_USAGE', `--display-policy must be one of ${PET_BRIEF_DISPLAY_POLICIES.join('|')}`)
|
|
1118
|
+
}
|
|
1119
|
+
if (inFile !== undefined) return fail('E_USAGE', '--display-policy can only be used when generating a brief')
|
|
1120
|
+
displayPolicy = displayPolicyFlag
|
|
1121
|
+
}
|
|
1122
|
+
const validateOptions = strict ? { now: Date.now(), acceptLegacy: false, requireDisplayPolicy: true } : { now: Date.now() }
|
|
697
1123
|
try {
|
|
698
1124
|
if (inFile) {
|
|
699
1125
|
let text
|
|
700
1126
|
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))
|
|
1127
|
+
const result = validatePetBrief(text, validateOptions)
|
|
1128
|
+
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
1129
|
if (!result.ok) process.exitCode = 1
|
|
704
1130
|
return
|
|
705
1131
|
}
|
|
@@ -711,10 +1137,10 @@ async function petBrief(args) {
|
|
|
711
1137
|
return fail(error?.code ?? 'E_STORE', error?.message ?? String(error))
|
|
712
1138
|
}
|
|
713
1139
|
const ledger = Ledger.fromJSON(snapshot)
|
|
714
|
-
const brief = buildPetBrief(ledger, { now: Date.now() })
|
|
1140
|
+
const brief = buildPetBrief(ledger, displayPolicy ? { now: Date.now(), displayPolicy } : { now: Date.now() })
|
|
715
1141
|
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))
|
|
1142
|
+
const result = validatePetBrief(brief, validateOptions)
|
|
1143
|
+
console.log(JSON.stringify({ ok: result.ok, checked: 'generated', expiresAt: brief.expiresAt, counts: brief.counts, errors: result.errors, warnings: result.warnings }, null, 2))
|
|
718
1144
|
if (!result.ok) process.exitCode = 1
|
|
719
1145
|
return
|
|
720
1146
|
}
|
|
@@ -724,7 +1150,7 @@ async function petBrief(args) {
|
|
|
724
1150
|
}
|
|
725
1151
|
if (asJson) { console.log(JSON.stringify(brief, null, 2)); return }
|
|
726
1152
|
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}`)
|
|
1153
|
+
console.log(`mood ${brief.mood} · expires ${brief.expiresAt} · displayPolicy ${brief.displayPolicy}`)
|
|
728
1154
|
if (outPath) console.log(`wrote ${outPath} (mode 600, atomic)`)
|
|
729
1155
|
} catch (error) {
|
|
730
1156
|
fail(error?.code ?? 'E_BRIEF', error?.message ?? String(error))
|
|
@@ -759,7 +1185,7 @@ async function doctor() {
|
|
|
759
1185
|
try { ensureHome(); check('home', existsSync(HOME), HOME) } catch (error) { check('home', false, error.message) }
|
|
760
1186
|
try {
|
|
761
1187
|
const store = openStore()
|
|
762
|
-
const integrity = store.
|
|
1188
|
+
const integrity = store.assertIntegrity()
|
|
763
1189
|
check('sqlite', integrity === 'ok', `${DB} (${integrity})`)
|
|
764
1190
|
const audit = store.verifyAudit()
|
|
765
1191
|
check('audit', audit.ok, audit.ok ? `${audit.count} entries` : `BROKEN at seq ${audit.seq}`)
|
|
@@ -939,9 +1365,10 @@ async function runTurn({ runtime, ledger, text, conversationId, debug = false, c
|
|
|
939
1365
|
const intent = context.intent
|
|
940
1366
|
let agentText = text
|
|
941
1367
|
const extracted = []
|
|
1368
|
+
const attachmentLib = attachments.length ? await loadAttachments() : null
|
|
942
1369
|
for (const file of attachments) {
|
|
943
1370
|
try {
|
|
944
|
-
const attachment = await extractAttachment(file, { cwd: process.cwd() })
|
|
1371
|
+
const attachment = await attachmentLib.extractAttachment(file, { cwd: process.cwd() })
|
|
945
1372
|
extracted.push(attachment)
|
|
946
1373
|
console.log(`[attach] ${attachment.name} (${attachment.text.length} chars${attachment.truncated ? ', truncated' : ''})`)
|
|
947
1374
|
} catch (error) {
|
|
@@ -1339,8 +1766,7 @@ async function repl() {
|
|
|
1339
1766
|
const feedback = correctionStatement(text)
|
|
1340
1767
|
if (feedback) {
|
|
1341
1768
|
const result = learnPreference(ledger, feedback, text, { explicit: /^(以后|记住|每次)/.test(text) })
|
|
1342
|
-
|
|
1343
|
-
saveLedger(ledger)
|
|
1769
|
+
saveLedgerWithAudit(ledger, { actor: 'local', action: 'correct', allowed: true, reason: result.preference.id })
|
|
1344
1770
|
printLearnReceipt(result)
|
|
1345
1771
|
continue
|
|
1346
1772
|
}
|
|
@@ -1402,7 +1828,7 @@ function forget(id) {
|
|
|
1402
1828
|
if (!ok) process.exitCode = 1
|
|
1403
1829
|
}
|
|
1404
1830
|
|
|
1405
|
-
function exportLedger(all = false, options = {}) {
|
|
1831
|
+
async function exportLedger(all = false, options = {}) {
|
|
1406
1832
|
const ledger = loadLedger().toJSON()
|
|
1407
1833
|
const payload = all ? (() => {
|
|
1408
1834
|
const store = dbStore()
|
|
@@ -1415,6 +1841,7 @@ function exportLedger(all = false, options = {}) {
|
|
|
1415
1841
|
if (options.encrypted) {
|
|
1416
1842
|
const passphrase = process.env.ADVISERS_EXPORT_PASSPHRASE
|
|
1417
1843
|
if (!passphrase) { console.error('export --encrypted requires ADVISERS_EXPORT_PASSPHRASE (min 8 chars)'); process.exitCode = 1; return }
|
|
1844
|
+
const { encryptJson } = await loadVault()
|
|
1418
1845
|
text = JSON.stringify(encryptJson(payload, passphrase), null, 2)
|
|
1419
1846
|
}
|
|
1420
1847
|
if (options.out) {
|
|
@@ -1425,11 +1852,12 @@ function exportLedger(all = false, options = {}) {
|
|
|
1425
1852
|
} else console.log(text)
|
|
1426
1853
|
}
|
|
1427
1854
|
|
|
1428
|
-
function importLedger(file, { replace = false } = {}) {
|
|
1855
|
+
async function importLedger(file, { replace = false } = {}) {
|
|
1429
1856
|
if (!file) { console.error('usage: advisers import <file> [--replace]'); process.exitCode = 1; return }
|
|
1430
1857
|
if (!replace) { console.error('import replaces the local ledger; pass --replace to confirm'); process.exitCode = 1; return }
|
|
1431
1858
|
let payload
|
|
1432
1859
|
try {
|
|
1860
|
+
const { isVaultEnvelope, decryptJson } = await loadVault()
|
|
1433
1861
|
const raw = JSON.parse(readFileSync(file, 'utf8'))
|
|
1434
1862
|
if (isVaultEnvelope(raw)) {
|
|
1435
1863
|
const passphrase = process.env.ADVISERS_EXPORT_PASSPHRASE
|
|
@@ -1439,15 +1867,15 @@ function importLedger(file, { replace = false } = {}) {
|
|
|
1439
1867
|
} catch (error) { console.error(`import failed: ${error.message}`); process.exitCode = 1; return }
|
|
1440
1868
|
const data = payload?.ledger ?? payload
|
|
1441
1869
|
if (!data || !Array.isArray(data.matters)) { console.error('import file does not contain an Advisers ledger'); process.exitCode = 1; return }
|
|
1870
|
+
await requireTosReaccept({ scope: 'import', subject: basename(file), action: 'import --replace' })
|
|
1442
1871
|
ensureHome()
|
|
1443
1872
|
try {
|
|
1444
1873
|
const store = dbStore()
|
|
1445
1874
|
if (store) copyFileSync(DB, join(HOME, `import-backup-${Date.now()}.db`))
|
|
1446
1875
|
} catch {}
|
|
1447
1876
|
try {
|
|
1448
|
-
const ledger = Ledger.fromJSON(data)
|
|
1449
|
-
|
|
1450
|
-
dbStore()?.appendAudit({ actor: 'local', action: 'import.ledger', allowed: true, reason: basename(file) })
|
|
1877
|
+
const ledger = Ledger.fromJSON(data, LOCAL_PORTS)
|
|
1878
|
+
saveLedgerWithAudit(ledger, { actor: 'local', action: 'import.ledger', allowed: true, reason: basename(file) })
|
|
1451
1879
|
console.log(`imported ${data.matters.length} matters, ${data.commitments?.length ?? 0} commitments`)
|
|
1452
1880
|
if (payload?.data) console.error('note: SQLite-only tables in the import were not merged; ledger was replaced.')
|
|
1453
1881
|
} catch (error) { console.error(`import failed: ${error.message}`); process.exitCode = 1 }
|
|
@@ -1456,7 +1884,8 @@ function importLedger(file, { replace = false } = {}) {
|
|
|
1456
1884
|
function backup(file) {
|
|
1457
1885
|
if (!file) { console.error('usage: advisers backup <path.db>'); process.exitCode = 1; return }
|
|
1458
1886
|
const store = openStore()
|
|
1459
|
-
store.
|
|
1887
|
+
const checkpoint = store.checkpoint()
|
|
1888
|
+
if (checkpoint.busy) { console.error('backup failed: database is busy (another advisers process is writing); close it and retry'); process.exitCode = 1; return }
|
|
1460
1889
|
mkdirSync(dirname(file), { recursive: true })
|
|
1461
1890
|
copyFileSync(DB, file)
|
|
1462
1891
|
chmodSync(file, 0o600)
|
|
@@ -1474,6 +1903,9 @@ async function brief(text, deep = false) {
|
|
|
1474
1903
|
console.log(core.renderIntentBrief(brief))
|
|
1475
1904
|
console.log('\n' + core.renderReadback(brief))
|
|
1476
1905
|
if (deep && process.env.ADVISERS_API_KEY) {
|
|
1906
|
+
const briefLedger = loadLedger()
|
|
1907
|
+
const briefDenied = egressDeniedReason(briefLedger.getMatter(activeMatterId(briefLedger)), 'brief --deep')
|
|
1908
|
+
if (briefDenied) { console.error(briefDenied); process.exitCode = 1; return }
|
|
1477
1909
|
try {
|
|
1478
1910
|
const response = await chatCompletion({
|
|
1479
1911
|
apiKey: process.env.ADVISERS_API_KEY,
|
|
@@ -1492,7 +1924,7 @@ async function brief(text, deep = false) {
|
|
|
1492
1924
|
}
|
|
1493
1925
|
}
|
|
1494
1926
|
|
|
1495
|
-
function routine(sub, arg, arg2) {
|
|
1927
|
+
async function routine(sub, arg, arg2) {
|
|
1496
1928
|
const ledger = loadLedger()
|
|
1497
1929
|
if (typeof ledger.addRoutine !== 'function') {
|
|
1498
1930
|
console.error('routine requires advisers-core@0.1.0-preview.3 or newer')
|
|
@@ -1514,6 +1946,7 @@ function routine(sub, arg, arg2) {
|
|
|
1514
1946
|
process.exitCode = 1
|
|
1515
1947
|
return
|
|
1516
1948
|
}
|
|
1949
|
+
await requireTosReaccept({ scope: 'routine', subject: 'routine:add', action: 'routine add' })
|
|
1517
1950
|
const spec = JSON.parse(readFileSync(arg, 'utf8'))
|
|
1518
1951
|
const routine = ledger.addRoutine({
|
|
1519
1952
|
name: spec.name,
|
|
@@ -1545,6 +1978,7 @@ function routine(sub, arg, arg2) {
|
|
|
1545
1978
|
process.exitCode = 1
|
|
1546
1979
|
return
|
|
1547
1980
|
}
|
|
1981
|
+
await requireTosReaccept({ scope: 'routine', subject: `routine:${arg}`, action: 'routine patch' })
|
|
1548
1982
|
const changes = JSON.parse(readFileSync(arg2, 'utf8'))
|
|
1549
1983
|
const patch = ledger.proposeRoutinePatch(arg, changes)
|
|
1550
1984
|
saveLedger(ledger)
|
|
@@ -1574,6 +2008,7 @@ function routine(sub, arg, arg2) {
|
|
|
1574
2008
|
}
|
|
1575
2009
|
if (sub === 'curate') {
|
|
1576
2010
|
const apply = arg === '--apply'
|
|
2011
|
+
if (apply) await requireTosReaccept({ scope: 'routine', subject: 'routine:curate', action: 'routine curate --apply' })
|
|
1577
2012
|
const now = Date.now()
|
|
1578
2013
|
let changed = 0
|
|
1579
2014
|
for (const r of ledger.listRoutines().filter((x) => x.status === 'active')) {
|
|
@@ -1592,6 +2027,7 @@ function routine(sub, arg, arg2) {
|
|
|
1592
2027
|
}
|
|
1593
2028
|
if (sub === 'restore') {
|
|
1594
2029
|
if (!arg) { console.error('usage: advisers routine restore <id>'); process.exitCode = 1; return }
|
|
2030
|
+
await requireTosReaccept({ scope: 'routine', subject: `routine:${arg}`, action: 'routine restore' })
|
|
1595
2031
|
const r = ledger.restoreRoutine(arg)
|
|
1596
2032
|
saveLedger(ledger)
|
|
1597
2033
|
console.log(`restored to draft: ${r.id}`)
|
|
@@ -1599,6 +2035,7 @@ function routine(sub, arg, arg2) {
|
|
|
1599
2035
|
}
|
|
1600
2036
|
if (sub === 'revert') {
|
|
1601
2037
|
if (!arg) { console.error('usage: advisers routine revert <patch-id>'); process.exitCode = 1; return }
|
|
2038
|
+
await requireTosReaccept({ scope: 'routine', subject: `routine:${arg}`, action: 'routine revert' })
|
|
1602
2039
|
const patch = ledger.revertRoutinePatch(arg)
|
|
1603
2040
|
saveLedger(ledger)
|
|
1604
2041
|
console.log(`rolled_back: ${patch.id}`)
|
|
@@ -1611,6 +2048,7 @@ function routine(sub, arg, arg2) {
|
|
|
1611
2048
|
return
|
|
1612
2049
|
}
|
|
1613
2050
|
if (sub === 'apply') {
|
|
2051
|
+
await requireTosReaccept({ scope: 'routine', subject: `routine:${arg}`, action: 'routine apply' })
|
|
1614
2052
|
const pending = ledger.listRoutinePatches('pending').find((p) => p.id === arg)
|
|
1615
2053
|
if (!pending) { console.error(`unknown or closed routine patch: ${arg}`); process.exitCode = 1; return }
|
|
1616
2054
|
const routine = ledger.listRoutines().find((r) => r.id === pending.routineId)
|
|
@@ -1635,6 +2073,7 @@ function routine(sub, arg, arg2) {
|
|
|
1635
2073
|
process.exitCode = 1
|
|
1636
2074
|
return
|
|
1637
2075
|
}
|
|
2076
|
+
await requireTosReaccept({ scope: 'routine', subject: `routine:${arg}`, action: `routine ${sub}` })
|
|
1638
2077
|
const routine = sub === 'approve' ? ledger.approveRoutine(arg) : ledger.archiveRoutine(arg)
|
|
1639
2078
|
saveLedger(ledger)
|
|
1640
2079
|
console.log(`${routine.status}: ${routine.id}`)
|
|
@@ -1706,6 +2145,9 @@ async function documentReview(args) {
|
|
|
1706
2145
|
if (!file) { console.error('usage: advisers review <file> --request "..."'); process.exitCode = 1; return }
|
|
1707
2146
|
const apiKey = process.env.ADVISERS_API_KEY
|
|
1708
2147
|
if (!apiKey) { console.error('document review requires ADVISERS_API_KEY'); process.exitCode = 1; return }
|
|
2148
|
+
const reviewLedger = loadLedger()
|
|
2149
|
+
const reviewDenied = egressDeniedReason(reviewLedger.getMatter(activeMatterId(reviewLedger)), 'review')
|
|
2150
|
+
if (reviewDenied) { console.error(reviewDenied); process.exitCode = 1; return }
|
|
1709
2151
|
let mod
|
|
1710
2152
|
if (process.env.ADVISERS_OFFICE_LOCAL === '1') mod = await import('../../office/dist/index.js')
|
|
1711
2153
|
else { try { mod = await import('advisers-office') } catch { mod = await import('../../office/dist/index.js') } }
|
|
@@ -1742,21 +2184,50 @@ async function research(args) {
|
|
|
1742
2184
|
}
|
|
1743
2185
|
}
|
|
1744
2186
|
|
|
1745
|
-
|
|
2187
|
+
/**
|
|
2188
|
+
* Source v2 write path (docs/SOURCE-SCHEMA.md).
|
|
2189
|
+
*
|
|
2190
|
+
* normalizeSource() maps v1/ad-hoc provenance (email -> mail, sessionId/turnId ->
|
|
2191
|
+
* ref, speakers -> speaker, file path -> basename) and preserves unknown fields
|
|
2192
|
+
* as extensions; validateSource() rejects a source with no real pointer and no
|
|
2193
|
+
* quote, so an invented provenance row is never written. A plain capture without
|
|
2194
|
+
* import metadata uses type "conversation" plus the local turn reference.
|
|
2195
|
+
*/
|
|
2196
|
+
async function buildCaptureSource({ meta, quote, ref, capturedAt }) {
|
|
2197
|
+
const { normalizeSource, validateSource } = await loadSource()
|
|
2198
|
+
const raw = { ...(meta && typeof meta === 'object' ? meta : {}) }
|
|
2199
|
+
raw.type = raw.type ?? 'conversation'
|
|
2200
|
+
if (quote) raw.quote = quote
|
|
2201
|
+
if (ref) raw.ref = ref
|
|
2202
|
+
if (!raw.capturedAt) raw.capturedAt = capturedAt
|
|
2203
|
+
const checked = validateSource(raw)
|
|
2204
|
+
if (!checked.ok) throw new Error(`invalid source: ${checked.errors.join('; ')}`)
|
|
2205
|
+
return normalizeSource(raw)
|
|
2206
|
+
}
|
|
2207
|
+
|
|
2208
|
+
/**
|
|
2209
|
+
* Run the capture model and persist pending candidates (never auto-accept).
|
|
2210
|
+
* @returns {Promise<{count: number, candidates: object[]}>}
|
|
2211
|
+
*/
|
|
2212
|
+
async function proposeCaptureText({ text, source = 'wechat', date, matterId, meta = {}, store, json = false }) {
|
|
1746
2213
|
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
|
|
2214
|
+
if (!result.candidates.length) return { count: 0, candidates: [] }
|
|
1748
2215
|
const conversationId = latestConversationId()
|
|
1749
2216
|
const turn = store.addTurn({ conversationId, role: 'user', content: text })
|
|
2217
|
+
const capturedAt = new Date().toISOString()
|
|
2218
|
+
const created = []
|
|
1750
2219
|
for (const c of result.candidates) {
|
|
2220
|
+
const evidenceSource = await buildCaptureSource({ meta, quote: c.quote, ref: `${conversationId}#${turn.id}`, capturedAt })
|
|
1751
2221
|
const candidate = store.proposeCandidate({
|
|
1752
2222
|
kind: 'commitment',
|
|
1753
2223
|
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:
|
|
2224
|
+
evidence: [{ quote: c.quote, turnId: turn.id, sessionId: conversationId, source: evidenceSource }],
|
|
1755
2225
|
})
|
|
1756
|
-
|
|
2226
|
+
created.push(candidate)
|
|
2227
|
+
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
2228
|
}
|
|
1758
|
-
store.appendAudit({ actor: 'local', action: 'capture.propose', allowed: true, reason: `${
|
|
1759
|
-
return
|
|
2229
|
+
store.appendAudit({ actor: 'local', action: 'capture.propose', allowed: true, reason: `${created.length} candidates` })
|
|
2230
|
+
return { count: created.length, candidates: created }
|
|
1760
2231
|
}
|
|
1761
2232
|
|
|
1762
2233
|
async function capture(args) {
|
|
@@ -1767,6 +2238,7 @@ async function capture(args) {
|
|
|
1767
2238
|
let text = positional.join(' ').trim()
|
|
1768
2239
|
if (flags.file) {
|
|
1769
2240
|
try {
|
|
2241
|
+
const { extractAttachment } = await loadAttachments()
|
|
1770
2242
|
const extracted = await extractAttachment(flags.file, { cwd: process.cwd() })
|
|
1771
2243
|
if (!extracted.text) throw new Error('no extractable text')
|
|
1772
2244
|
text = extracted.text
|
|
@@ -1783,8 +2255,12 @@ async function capture(args) {
|
|
|
1783
2255
|
const denied = egressDeniedReason(ledger.getMatter(matterId), 'capture')
|
|
1784
2256
|
if (denied) { console.error(denied); process.exitCode = 1; return }
|
|
1785
2257
|
saveLedger(ledger)
|
|
1786
|
-
const
|
|
1787
|
-
if (
|
|
2258
|
+
const result = await proposeCaptureText({ text, source: flags.source, date: flags.date, matterId, store, json: flags.json === true })
|
|
2259
|
+
if (flags.json) {
|
|
2260
|
+
console.log(JSON.stringify({ ok: true, command: 'capture', source: typeof flags.source === 'string' ? flags.source : 'wechat', count: result.count, candidates: result.candidates }, null, 2))
|
|
2261
|
+
return
|
|
2262
|
+
}
|
|
2263
|
+
if (!result.count) console.log('没有找到可确认的承诺候选。')
|
|
1788
2264
|
else console.log('确认:advisers memory accept <id>;拒绝:advisers memory reject <id>')
|
|
1789
2265
|
}
|
|
1790
2266
|
|
|
@@ -1806,13 +2282,15 @@ async function captureFromMail(flags) {
|
|
|
1806
2282
|
const denied = egressDeniedReason(ledger.getMatter(matterId), 'mail')
|
|
1807
2283
|
if (denied) { console.error(denied); process.exitCode = 1; return }
|
|
1808
2284
|
saveLedger(ledger)
|
|
2285
|
+
const { parseMbox, parseEml, dedupeKey, toCaptureInput } = await loadImporters()
|
|
1809
2286
|
let files = []
|
|
1810
2287
|
try {
|
|
1811
2288
|
const info = statSync(target)
|
|
1812
2289
|
files = info.isDirectory() ? readdirSync(target).filter((f) => /\.(eml|mbox)$/i.test(f)).map((f) => join(target, f)) : [target]
|
|
1813
2290
|
} catch (error) { console.error(`cannot read mail path: ${error.message}`); process.exitCode = 1; return }
|
|
1814
2291
|
const limit = Math.max(1, Math.min(200, Number(flags.limit) || 20))
|
|
1815
|
-
let seen = 0, skipped = 0, failed = 0
|
|
2292
|
+
let seen = 0, skipped = 0, failed = 0
|
|
2293
|
+
const created = []
|
|
1816
2294
|
for (const file of files.slice(0, limit)) {
|
|
1817
2295
|
let messages = []
|
|
1818
2296
|
try {
|
|
@@ -1826,17 +2304,21 @@ async function captureFromMail(flags) {
|
|
|
1826
2304
|
const input = toCaptureInput(msg, { source: 'email' })
|
|
1827
2305
|
if (!input.text.trim()) { skipped++; continue }
|
|
1828
2306
|
try {
|
|
1829
|
-
const
|
|
1830
|
-
text: input.text, source: 'email', date: parseEmailDate(msg.date), matterId, store,
|
|
2307
|
+
const result = await proposeCaptureText({
|
|
2308
|
+
text: input.text, source: 'email', date: parseEmailDate(msg.date), matterId, store, json: flags.json === true,
|
|
1831
2309
|
meta: { type: 'mail', messageId: msg.messageId, subject: msg.subject, from: msg.from },
|
|
1832
2310
|
})
|
|
1833
|
-
candidates
|
|
2311
|
+
created.push(...result.candidates)
|
|
1834
2312
|
store.markSeen('import', 'mail', key)
|
|
1835
2313
|
} catch (error) { failed++; console.error(`${msg.messageId || file}: ${error.message}`) }
|
|
1836
2314
|
}
|
|
1837
2315
|
}
|
|
1838
|
-
store.appendAudit({ actor: 'local', action: 'import.mail', allowed: true, reason: `${seen} seen, ${
|
|
1839
|
-
|
|
2316
|
+
store.appendAudit({ actor: 'local', action: 'import.mail', allowed: true, reason: `${seen} seen, ${created.length} candidates, ${failed} failed` })
|
|
2317
|
+
if (flags.json) {
|
|
2318
|
+
console.log(JSON.stringify({ ok: true, command: 'capture --from-mail', seen, skipped, failed, count: created.length, candidates: created }, null, 2))
|
|
2319
|
+
return
|
|
2320
|
+
}
|
|
2321
|
+
console.log(`mail import: ${seen} messages, ${created.length} candidates, ${skipped} skipped, ${failed} failed`)
|
|
1840
2322
|
}
|
|
1841
2323
|
|
|
1842
2324
|
async function captureFromTranscript(flags) {
|
|
@@ -1851,19 +2333,28 @@ async function captureFromTranscript(flags) {
|
|
|
1851
2333
|
const denied = egressDeniedReason(ledger.getMatter(matterId), 'transcript')
|
|
1852
2334
|
if (denied) { console.error(denied); process.exitCode = 1; return }
|
|
1853
2335
|
saveLedger(ledger)
|
|
2336
|
+
const { parseTranscript, dedupeKey, toCaptureInput } = await loadImporters()
|
|
1854
2337
|
let parsed
|
|
1855
2338
|
try { parsed = parseTranscript(readFileSync(file, 'utf8')) } catch (error) { console.error(`cannot parse transcript: ${error.message}`); process.exitCode = 1; return }
|
|
1856
2339
|
const key = dedupeKey('transcript', parsed)
|
|
1857
|
-
if (store.hasSeen('import', 'transcript', key, 30)) {
|
|
2340
|
+
if (store.hasSeen('import', 'transcript', key, 30)) {
|
|
2341
|
+
if (flags.json) { console.log(JSON.stringify({ ok: true, command: 'capture --from-transcript', alreadyImported: true, count: 0, candidates: [] }, null, 2)); return }
|
|
2342
|
+
console.log('transcript already imported')
|
|
2343
|
+
return
|
|
2344
|
+
}
|
|
1858
2345
|
const input = toCaptureInput(parsed, { source: 'meeting' })
|
|
1859
2346
|
if (!input.text.trim()) { console.error('transcript has no text'); process.exitCode = 1; return }
|
|
1860
|
-
const
|
|
1861
|
-
text: input.text, source: 'meeting', matterId, store,
|
|
2347
|
+
const result = await proposeCaptureText({
|
|
2348
|
+
text: input.text, source: 'meeting', matterId, store, json: flags.json === true,
|
|
1862
2349
|
meta: { type: 'transcript', file: basename(file), speakers: input.meta?.speakers ?? [] },
|
|
1863
2350
|
})
|
|
1864
2351
|
store.markSeen('import', 'transcript', key)
|
|
1865
|
-
store.appendAudit({ actor: 'local', action: 'import.transcript', allowed: true, reason: `${
|
|
1866
|
-
|
|
2352
|
+
store.appendAudit({ actor: 'local', action: 'import.transcript', allowed: true, reason: `${result.count} candidates` })
|
|
2353
|
+
if (flags.json) {
|
|
2354
|
+
console.log(JSON.stringify({ ok: true, command: 'capture --from-transcript', count: result.count, candidates: result.candidates }, null, 2))
|
|
2355
|
+
return
|
|
2356
|
+
}
|
|
2357
|
+
console.log(`transcript import: ${result.count} candidates`)
|
|
1867
2358
|
}
|
|
1868
2359
|
|
|
1869
2360
|
async function captureFromImap(flags) {
|
|
@@ -1879,6 +2370,7 @@ async function captureFromImap(flags) {
|
|
|
1879
2370
|
const denied = egressDeniedReason(ledger.getMatter(matterId), 'imap')
|
|
1880
2371
|
if (denied) { console.error(denied); process.exitCode = 1; return }
|
|
1881
2372
|
saveLedger(ledger)
|
|
2373
|
+
const { parseEml, dedupeKey, toCaptureInput } = await loadImporters()
|
|
1882
2374
|
let messages
|
|
1883
2375
|
try {
|
|
1884
2376
|
messages = await fetchImapMessages({
|
|
@@ -1891,7 +2383,8 @@ async function captureFromImap(flags) {
|
|
|
1891
2383
|
limit: Math.max(1, Math.min(100, Number(flags.limit) || 20)),
|
|
1892
2384
|
})
|
|
1893
2385
|
} catch (error) { console.error(`imap failed: ${error.message}`); process.exitCode = 1; return }
|
|
1894
|
-
let seen = 0, skipped = 0, failed = 0
|
|
2386
|
+
let seen = 0, skipped = 0, failed = 0
|
|
2387
|
+
const created = []
|
|
1895
2388
|
for (const msg of messages) {
|
|
1896
2389
|
seen++
|
|
1897
2390
|
let parsed
|
|
@@ -1901,16 +2394,20 @@ async function captureFromImap(flags) {
|
|
|
1901
2394
|
const input = toCaptureInput(parsed, { source: 'email' })
|
|
1902
2395
|
if (!input.text.trim()) { skipped++; continue }
|
|
1903
2396
|
try {
|
|
1904
|
-
const
|
|
1905
|
-
candidates
|
|
2397
|
+
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 } })
|
|
2398
|
+
created.push(...result.candidates)
|
|
1906
2399
|
store.markSeen('import', 'imap', key)
|
|
1907
2400
|
} catch (error) { failed++; console.error(`imap message ${msg.uid}: ${error.message}`) }
|
|
1908
2401
|
}
|
|
1909
|
-
store.appendAudit({ actor: 'local', action: 'import.imap', allowed: true, reason: `${seen} seen, ${
|
|
1910
|
-
|
|
2402
|
+
store.appendAudit({ actor: 'local', action: 'import.imap', allowed: true, reason: `${seen} seen, ${created.length} candidates, ${failed} failed` })
|
|
2403
|
+
if (flags.json) {
|
|
2404
|
+
console.log(JSON.stringify({ ok: true, command: 'capture --from-imap', seen, skipped, failed, count: created.length, candidates: created }, null, 2))
|
|
2405
|
+
return
|
|
2406
|
+
}
|
|
2407
|
+
console.log(`imap import: ${seen} messages, ${created.length} candidates, ${skipped} skipped, ${failed} failed (EXAMINE/read-only)`)
|
|
1911
2408
|
}
|
|
1912
2409
|
|
|
1913
|
-
function calendarImport(args) {
|
|
2410
|
+
async function calendarImport(args) {
|
|
1914
2411
|
const { flags, positional } = parseFlags(args)
|
|
1915
2412
|
const file = typeof flags.ics === 'string' ? flags.ics : positional[0]
|
|
1916
2413
|
if (!file) { console.error('usage: advisers calendar import --ics <file>'); process.exitCode = 1; return }
|
|
@@ -1921,7 +2418,10 @@ function calendarImport(args) {
|
|
|
1921
2418
|
const denied = egressDeniedReason(ledger.getMatter(matterId), 'calendar')
|
|
1922
2419
|
if (denied) { console.error(denied); process.exitCode = 1; return }
|
|
1923
2420
|
let events
|
|
1924
|
-
try {
|
|
2421
|
+
try {
|
|
2422
|
+
const { parseIcs } = await loadImporters()
|
|
2423
|
+
events = parseIcs(readFileSync(file, 'utf8'))
|
|
2424
|
+
} catch (error) { console.error(`cannot parse ics: ${error.message}`); process.exitCode = 1; return }
|
|
1925
2425
|
let imported = 0
|
|
1926
2426
|
for (const e of events) {
|
|
1927
2427
|
if (!e.uid) continue
|
|
@@ -1932,14 +2432,46 @@ function calendarImport(args) {
|
|
|
1932
2432
|
console.log(`calendar import: ${imported} events (read-only)`)
|
|
1933
2433
|
}
|
|
1934
2434
|
|
|
1935
|
-
|
|
2435
|
+
/**
|
|
2436
|
+
* Read-only expansion of the stored calendar rows into the occurrences that
|
|
2437
|
+
* start today (Asia/Shanghai). expandRrule() is pure and bounded; an
|
|
2438
|
+
* unsupported/malformed RRULE falls back to the stored DTSTART occurrence, so a
|
|
2439
|
+
* bad rule never hides a real meeting.
|
|
2440
|
+
*/
|
|
2441
|
+
async function calendarOccurrencesToday() {
|
|
1936
2442
|
const store = dbStore()
|
|
1937
|
-
|
|
1938
|
-
|
|
1939
|
-
const
|
|
1940
|
-
|
|
2443
|
+
const localDay = localDayOf(Date.now())
|
|
2444
|
+
if (!store) return { localDay, occurrences: [] }
|
|
2445
|
+
const { expandRrule } = await loadIcal()
|
|
2446
|
+
const occurrences = []
|
|
2447
|
+
for (const row of store.listCalendarEvents()) {
|
|
2448
|
+
let instances
|
|
2449
|
+
try { instances = expandRrule(row, { from: localDay, to: localDay }) } catch { instances = [] }
|
|
2450
|
+
for (const instance of instances) {
|
|
2451
|
+
occurrences.push({
|
|
2452
|
+
uid: instance.uid,
|
|
2453
|
+
summary: instance.summary ?? '',
|
|
2454
|
+
startsAt: instance.startsAt,
|
|
2455
|
+
endsAt: instance.endsAt ?? null,
|
|
2456
|
+
allDay: Boolean(instance.allDay),
|
|
2457
|
+
recurring: Boolean(instance.recurring),
|
|
2458
|
+
location: instance.location ?? null,
|
|
2459
|
+
rrule: instance.rrule ?? null,
|
|
2460
|
+
})
|
|
2461
|
+
}
|
|
2462
|
+
}
|
|
2463
|
+
occurrences.sort((a, b) => (a.startsAt < b.startsAt ? -1 : a.startsAt > b.startsAt ? 1 : String(a.summary).localeCompare(String(b.summary))))
|
|
2464
|
+
return { localDay, occurrences }
|
|
2465
|
+
}
|
|
2466
|
+
|
|
2467
|
+
async function printCalendarToday() {
|
|
2468
|
+
const { localDay, occurrences } = await calendarOccurrencesToday()
|
|
2469
|
+
if (!occurrences.length) { console.log('日历:今天没有本地导入的会议。'); return }
|
|
1941
2470
|
console.log(`日历(本地只读,${localDay}):`)
|
|
1942
|
-
for (const e of
|
|
2471
|
+
for (const e of occurrences) {
|
|
2472
|
+
const time = e.allDay ? '全天' : e.startsAt.slice(11, 16)
|
|
2473
|
+
console.log(` ${time} ${e.summary}${e.recurring ? '(循环)' : ''}${e.location ? ` · ${e.location}` : ''}`)
|
|
2474
|
+
}
|
|
1943
2475
|
}
|
|
1944
2476
|
|
|
1945
2477
|
async function ui(args) {
|
|
@@ -1947,6 +2479,7 @@ async function ui(args) {
|
|
|
1947
2479
|
const port = Number(flags.port) || 17860
|
|
1948
2480
|
const ledger = loadLedger()
|
|
1949
2481
|
const store = dbStore()
|
|
2482
|
+
const { buildReminders } = await loadRemind()
|
|
1950
2483
|
const snapshot = {
|
|
1951
2484
|
today: () => {
|
|
1952
2485
|
const open = ledger.openCommitments()
|
|
@@ -1969,22 +2502,48 @@ async function remind(args) {
|
|
|
1969
2502
|
ensureHome()
|
|
1970
2503
|
const store = dbStore()
|
|
1971
2504
|
const ledger = loadLedger()
|
|
2505
|
+
const scheduler = await loadScheduler()
|
|
1972
2506
|
const sub = positional[0]
|
|
2507
|
+
const apply = flags.apply === true
|
|
1973
2508
|
if (sub === 'install' || flags.install) {
|
|
1974
2509
|
const dir = join(HOME, 'scheduler')
|
|
1975
2510
|
mkdirSync(dir, { recursive: true, mode: 0o700 })
|
|
1976
2511
|
const nodeBin = process.execPath
|
|
1977
2512
|
const cli = process.argv[1]
|
|
1978
|
-
writeFileSync(join(dir, 'remind.sh'),
|
|
1979
|
-
writeFileSync(join(dir, 'remind.ps1'),
|
|
2513
|
+
writeFileSync(join(dir, 'remind.sh'), '#!/bin/sh\n"' + nodeBin + '" "' + cli + '" remind --deliver --notify >> "' + join(HOME, 'reminders.log') + '" 2>&1\n', { mode: 0o700 })
|
|
2514
|
+
writeFileSync(join(dir, 'remind.ps1'), '& "' + nodeBin + '" "' + cli + '" remind --deliver --notify *>> "' + join(HOME, 'reminders.log') + '"\n', { mode: 0o700 })
|
|
1980
2515
|
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
2516
|
store?.appendAudit({ actor: 'local', action: 'notify.install', allowed: true, reason: dir })
|
|
1982
|
-
console.log(
|
|
2517
|
+
console.log('scheduler scripts written: ' + dir)
|
|
1983
2518
|
console.log('opt-in: import ~/.advisers/reminders.ics, or register remind.sh/.ps1 with your OS scheduler.')
|
|
2519
|
+
const command = scheduler.buildCronCommand({ nodeBin, cliPath: cli })
|
|
2520
|
+
const schedule = typeof flags.schedule === 'string' ? flags.schedule : scheduler.DEFAULT_CRON_SCHEDULE
|
|
2521
|
+
const time = typeof flags.time === 'string' ? flags.time : scheduler.DEFAULT_TASK_TIME
|
|
2522
|
+
const existing = apply ? await readCrontabText() : { ok: false }
|
|
2523
|
+
const plan = scheduler.planScheduler({
|
|
2524
|
+
platform: process.platform,
|
|
2525
|
+
action: 'install',
|
|
2526
|
+
dryRun: !apply,
|
|
2527
|
+
command,
|
|
2528
|
+
schedule,
|
|
2529
|
+
time,
|
|
2530
|
+
...(existing.ok ? { existingText: existing.text } : {}),
|
|
2531
|
+
})
|
|
2532
|
+
console.log('schedule: ' + (plan.platform === 'win32' ? plan.taskName + ' daily ' + plan.time : plan.schedule))
|
|
2533
|
+
console.log('command: ' + command)
|
|
2534
|
+
await applySchedulerPlan(plan, { apply })
|
|
1984
2535
|
return
|
|
1985
2536
|
}
|
|
1986
2537
|
if (sub === 'uninstall' || flags.uninstall) {
|
|
1987
2538
|
const dir = join(HOME, 'scheduler')
|
|
2539
|
+
const existing = await readCrontabText()
|
|
2540
|
+
const plan = scheduler.planScheduler({
|
|
2541
|
+
platform: process.platform,
|
|
2542
|
+
action: 'uninstall',
|
|
2543
|
+
dryRun: !apply,
|
|
2544
|
+
...(existing.ok ? { existingText: existing.text } : {}),
|
|
2545
|
+
})
|
|
2546
|
+
await applySchedulerPlan(plan, { apply })
|
|
1988
2547
|
if (existsSync(dir)) rmSync(dir, { recursive: true, force: true })
|
|
1989
2548
|
store?.appendAudit({ actor: 'local', action: 'notify.uninstall', allowed: true, reason: dir })
|
|
1990
2549
|
console.log('scheduler scripts removed (calendar events remain in your calendar app).')
|
|
@@ -1992,13 +2551,31 @@ async function remind(args) {
|
|
|
1992
2551
|
}
|
|
1993
2552
|
if (sub === 'status' || flags.status) {
|
|
1994
2553
|
const dir = join(HOME, 'scheduler')
|
|
1995
|
-
console.log(
|
|
1996
|
-
console.log(
|
|
2554
|
+
console.log('scheduler scripts: ' + (existsSync(dir) ? dir : 'not installed (optional)'))
|
|
2555
|
+
console.log('reminder log: ' + join(HOME, 'reminders.log'))
|
|
2556
|
+
const status = scheduler.readSchedulerStatus({ homeDir: HOME })
|
|
2557
|
+
if (!status.lastRun) console.log('last run: none recorded' + (status.corrupt ? ' (status.json corrupt)' : ''))
|
|
2558
|
+
else console.log('last run: ' + status.lastRun + ' · result=' + (status.lastResult ?? '-') + ' · count=' + (status.lastCount ?? '-') + ' · channel=' + (status.lastChannel ?? '-'))
|
|
2559
|
+
if (process.platform === 'win32') {
|
|
2560
|
+
const plan = scheduler.planWindowsStatus({})
|
|
2561
|
+
console.log('os plan: ' + plan.commands.map((entry) => entry.command + ' ' + entry.args.join(' ')).join('; ') + '(运行该命令;exit 0 表示已注册)')
|
|
2562
|
+
} else if (scheduler.CRON_PLATFORMS.includes(process.platform)) {
|
|
2563
|
+
const existing = await readCrontabText()
|
|
2564
|
+
if (existing.ok) {
|
|
2565
|
+
const plan = scheduler.planCronStatus({ existingText: existing.text })
|
|
2566
|
+
console.log(plan.installed ? 'os plan: installed (' + plan.schedule + ')' : 'os plan: not installed')
|
|
2567
|
+
} else {
|
|
2568
|
+
console.log('os plan: unknown (' + (existing.error ?? 'crontab unavailable') + ')')
|
|
2569
|
+
}
|
|
2570
|
+
} else {
|
|
2571
|
+
console.log('os plan: unsupported platform ' + process.platform)
|
|
2572
|
+
}
|
|
1997
2573
|
return
|
|
1998
2574
|
}
|
|
2575
|
+
const { buildReminders, toIcs } = await loadRemind()
|
|
1999
2576
|
const snoozed = {}
|
|
2000
2577
|
for (const c of ledger.listCommitments()) {
|
|
2001
|
-
const until = store?.getMeta(
|
|
2578
|
+
const until = store?.getMeta('snooze:' + c.id)
|
|
2002
2579
|
if (until) snoozed[c.id] = until
|
|
2003
2580
|
}
|
|
2004
2581
|
const reminders = buildReminders(ledger, { now: new Date(), snoozedUntil: snoozed })
|
|
@@ -2006,23 +2583,102 @@ async function remind(args) {
|
|
|
2006
2583
|
const path = typeof flags.ics === 'string' ? flags.ics : (positional[0] || join(HOME, 'reminders.ics'))
|
|
2007
2584
|
writeFileSync(path, toIcs(reminders, { now: new Date() }), { mode: 0o600 })
|
|
2008
2585
|
store?.appendAudit({ actor: 'local', action: 'notify.ics', allowed: true, reason: basename(path) })
|
|
2009
|
-
console.log(
|
|
2586
|
+
console.log('ics written: ' + path + ' (' + reminders.length + ' events)')
|
|
2010
2587
|
return
|
|
2011
2588
|
}
|
|
2012
2589
|
if (flags.json) { console.log(JSON.stringify({ now: new Date().toISOString(), reminders }, null, 2)); return }
|
|
2013
|
-
if (!reminders.length) {
|
|
2014
|
-
|
|
2590
|
+
if (!reminders.length) {
|
|
2591
|
+
console.log('现在没有到期的提醒。')
|
|
2592
|
+
if (flags.deliver) recordReminderRun(scheduler, { count: 0, channel: 'log' })
|
|
2593
|
+
return
|
|
2594
|
+
}
|
|
2595
|
+
for (const r of reminders) console.log('[' + r.level + '/' + r.bucket + '] ' + r.action + (r.dueAt ? ' · ' + r.dueAt.slice(0, 16) : ''))
|
|
2015
2596
|
if (flags.deliver) {
|
|
2016
|
-
const line =
|
|
2597
|
+
const line = new Date().toISOString() + '\t' + reminders.length + '\t' + reminders.map((r) => r.action).join(';') + '\n'
|
|
2017
2598
|
writeFileSync(join(HOME, 'reminders.log'), line, { flag: 'a', mode: 0o600 })
|
|
2018
2599
|
let channel = 'log'
|
|
2019
2600
|
if (flags.notify) {
|
|
2020
|
-
const
|
|
2021
|
-
|
|
2601
|
+
const notify = await loadNotify()
|
|
2602
|
+
const local = await notify.sendNotification({ title: 'Advisers · 到期提醒', body: reminders.length + ' 条承诺到期或即将到期' })
|
|
2603
|
+
channel = local.sent ? local.channel : 'log-only'
|
|
2604
|
+
const webhook = await notify.sendWebhookNotification(reminders)
|
|
2605
|
+
if (webhook.sent) channel = channel === 'log-only' ? 'webhook' : channel + '+webhook'
|
|
2606
|
+
else if (webhook.configured) console.error('webhook 未发送:' + (webhook.error ?? 'unknown') + (webhook.detail ? '(' + webhook.detail + ')' : ''))
|
|
2607
|
+
}
|
|
2608
|
+
store?.appendAudit({ actor: 'local', action: 'notify.delivered', allowed: true, reason: reminders.length + ' reminders channel=' + channel })
|
|
2609
|
+
recordReminderRun(scheduler, { count: reminders.length, channel })
|
|
2610
|
+
if (flags.notify) console.log('通知通道:' + channel)
|
|
2611
|
+
}
|
|
2612
|
+
return
|
|
2613
|
+
}
|
|
2614
|
+
|
|
2615
|
+
/** Execute one system scheduler command; missing binaries become structured failures. */
|
|
2616
|
+
function runSchedulerCommand(commandPlan, { timeout = 20000 } = {}) {
|
|
2617
|
+
if (!commandPlan || typeof commandPlan.command !== 'string') return { ok: false, error: 'no-command' }
|
|
2618
|
+
const result = spawnSync(commandPlan.command, commandPlan.args ?? [], { input: commandPlan.stdin, encoding: 'utf8', timeout, windowsHide: true })
|
|
2619
|
+
return {
|
|
2620
|
+
ok: !result.error && result.status === 0,
|
|
2621
|
+
status: result.status,
|
|
2622
|
+
stdout: result.stdout ?? '',
|
|
2623
|
+
stderr: result.stderr ?? '',
|
|
2624
|
+
error: result.error ? (result.error.code ?? result.error.message) : undefined,
|
|
2625
|
+
}
|
|
2626
|
+
}
|
|
2627
|
+
|
|
2628
|
+
/** Read the current crontab text; read-only and best-effort (never fails a command). */
|
|
2629
|
+
async function readCrontabText() {
|
|
2630
|
+
const scheduler = await loadScheduler()
|
|
2631
|
+
if (!scheduler.CRON_PLATFORMS.includes(process.platform)) return { ok: false, unsupported: true }
|
|
2632
|
+
const result = runSchedulerCommand(scheduler.crontabReadCommand())
|
|
2633
|
+
if (result.error) return { ok: false, error: result.error }
|
|
2634
|
+
return { ok: true, text: result.ok ? result.stdout : '' }
|
|
2635
|
+
}
|
|
2636
|
+
|
|
2637
|
+
/** Record a successful delivery run in ~/.advisers/scheduler/status.json. */
|
|
2638
|
+
function recordReminderRun(scheduler, { count, channel }) {
|
|
2639
|
+
try {
|
|
2640
|
+
scheduler.recordSchedulerRun({ homeDir: HOME, at: new Date(), result: 'ok', count, channel, dryRun: false })
|
|
2641
|
+
} catch (error) {
|
|
2642
|
+
console.error('scheduler status not recorded: ' + error.message)
|
|
2643
|
+
}
|
|
2644
|
+
}
|
|
2645
|
+
|
|
2646
|
+
/**
|
|
2647
|
+
* Apply (or print) a scheduler plan. The library never runs a system command, so
|
|
2648
|
+
* the CLI is the only place that can: dry-run prints the exact argv/stdin and
|
|
2649
|
+
* only `--apply` executes it.
|
|
2650
|
+
*/
|
|
2651
|
+
async function applySchedulerPlan(plan, { apply = false } = {}) {
|
|
2652
|
+
const commands = Array.isArray(plan.commands) ? plan.commands : []
|
|
2653
|
+
if (!commands.length) {
|
|
2654
|
+
console.log(plan.action === 'uninstall' ? '未发现需要移除的系统调度项。' : '系统调度未变更。')
|
|
2655
|
+
return { applied: false, results: [] }
|
|
2656
|
+
}
|
|
2657
|
+
if (!apply) {
|
|
2658
|
+
console.log('dry-run(默认不执行;加 --apply 才注册/移除系统任务):')
|
|
2659
|
+
for (const command of commands) {
|
|
2660
|
+
if (command.stdin !== undefined) {
|
|
2661
|
+
console.log(' ' + command.command + ' ' + command.args.join(' ') + ' <<EOF')
|
|
2662
|
+
for (const line of String(command.stdin).split('\n')) console.log(' ' + line)
|
|
2663
|
+
console.log(' EOF')
|
|
2664
|
+
} else {
|
|
2665
|
+
console.log(' ' + command.command + ' ' + command.args.join(' '))
|
|
2666
|
+
}
|
|
2022
2667
|
}
|
|
2023
|
-
|
|
2024
|
-
if (flags.notify) console.log(`通知通道:${channel}`)
|
|
2668
|
+
return { applied: false, results: [] }
|
|
2025
2669
|
}
|
|
2670
|
+
const results = []
|
|
2671
|
+
for (const command of commands) {
|
|
2672
|
+
const result = runSchedulerCommand(command)
|
|
2673
|
+
results.push({ command: command.command, args: command.args, ...result })
|
|
2674
|
+
if (!result.ok) {
|
|
2675
|
+
console.error('系统调度命令失败:' + command.command + ' ' + command.args.join(' ') + (result.stderr ? '\n' + result.stderr.trim() : '') + (result.error ? ' (' + result.error + ')' : ''))
|
|
2676
|
+
process.exitCode = 1
|
|
2677
|
+
return { applied: false, results }
|
|
2678
|
+
}
|
|
2679
|
+
}
|
|
2680
|
+
console.log('已执行 ' + commands.length + ' 个系统调度命令。')
|
|
2681
|
+
return { applied: true, results }
|
|
2026
2682
|
}
|
|
2027
2683
|
|
|
2028
2684
|
async function deliver(args) {
|
|
@@ -2042,8 +2698,20 @@ async function deliver(args) {
|
|
|
2042
2698
|
commitments = [c]
|
|
2043
2699
|
} else commitments = ledger.openCommitments()
|
|
2044
2700
|
if (!commitments.length) { console.error('no commitments to deliver'); process.exitCode = 1; return }
|
|
2701
|
+
// P1-6: a confirmation should not dump an unbounded list of open commitments
|
|
2702
|
+
// into one file (5000 open commitments used to make a 7.8s / 1.57GB PDF).
|
|
2703
|
+
// The default covers the latest/default view; --all is the explicit opt-in
|
|
2704
|
+
// for a full export, and the total is always printed so nothing disappears
|
|
2705
|
+
// silently.
|
|
2706
|
+
const totalOpen = commitments.length
|
|
2707
|
+
const truncated = totalOpen > DELIVER_DEFAULT_LIMIT && flags.all !== true && !flags.commit
|
|
2708
|
+
if (truncated) commitments = commitments.slice(0, DELIVER_DEFAULT_LIMIT)
|
|
2709
|
+
const { sha256Hex } = await loadEvidence()
|
|
2045
2710
|
const label = type === 'weekly' ? '周报' : type === 'statement' ? '对账单' : '确认单'
|
|
2046
|
-
const
|
|
2711
|
+
const scopeLine = truncated
|
|
2712
|
+
? `承诺数:${totalOpen}(本文件只列前 ${commitments.length} 条;用 --all 生成全部)`
|
|
2713
|
+
: `承诺数:${commitments.length}`
|
|
2714
|
+
const sections = [{ heading: label, paragraphs: [`生成时间:${new Date().toISOString()}`, scopeLine] }]
|
|
2047
2715
|
for (const c of commitments) {
|
|
2048
2716
|
sections.push({ heading: c.action, paragraphs: [`对象:${c.creditor}`, `截止:${c.dueAt ?? '未定'}`, `状态:${c.status}`, `证据:${(c.evidence ?? []).length} 条`] })
|
|
2049
2717
|
}
|
|
@@ -2052,12 +2720,12 @@ async function deliver(args) {
|
|
|
2052
2720
|
const mod = process.env.ADVISERS_OFFICE_LOCAL === '1' ? await import('../../office/dist/index.js') : await import('advisers-office')
|
|
2053
2721
|
let buffer
|
|
2054
2722
|
if (format === 'pdf') {
|
|
2723
|
+
const { buildSimplePdf } = await loadPdf()
|
|
2055
2724
|
const lines = commitments.map((c) => `${c.id} ${c.creditor} · ${c.action}${c.dueAt ? ` · 截止 ${c.dueAt}` : ''} · ${c.status}`)
|
|
2056
2725
|
buffer = await buildSimplePdf({ title: `${label} · Advisers`, paragraphs: [`承诺数:${commitments.length}`, ...lines, 'SHA256SUMS/回执说明:本 PDF 为本地账本生成,不是第三方存证。'] })
|
|
2057
2726
|
if (!buffer.subarray(0, 5).equals(Buffer.from('%PDF-'))) throw new Error('pdf builder returned a non-PDF buffer')
|
|
2058
2727
|
await backupCliFile(out)
|
|
2059
2728
|
writeFileSync(out, buffer)
|
|
2060
|
-
recordManualDelivery([out], `deliver:${type}`, label, 'pdf')
|
|
2061
2729
|
} else if (format === 'xlsx') {
|
|
2062
2730
|
const rows = commitments.map((c) => ({
|
|
2063
2731
|
id: c.id, creditor: c.creditor, action: c.action, due: c.dueAt ?? '',
|
|
@@ -2073,86 +2741,57 @@ async function deliver(args) {
|
|
|
2073
2741
|
await mod.validateOffice(buffer, 'xlsx')
|
|
2074
2742
|
await backupCliFile(out)
|
|
2075
2743
|
writeFileSync(out, buffer)
|
|
2076
|
-
recordManualDelivery([out], `deliver:${type}`, label, 'xlsx')
|
|
2077
2744
|
} else {
|
|
2078
2745
|
buffer = await mod.buildDocx({ title: `${label} · Advisers`, sections })
|
|
2079
2746
|
await mod.validateOffice(buffer, 'docx')
|
|
2080
2747
|
await backupCliFile(out)
|
|
2081
2748
|
writeFileSync(out, buffer)
|
|
2082
|
-
recordManualDelivery([out], `deliver:${type}`, label, 'docx')
|
|
2083
2749
|
}
|
|
2084
|
-
|
|
2085
|
-
|
|
2086
|
-
|
|
2750
|
+
// Delivery row + audit row commit together (robustness audit P0-3).
|
|
2751
|
+
recordDeliveryWithAudit({
|
|
2752
|
+
files: [out],
|
|
2753
|
+
tool: `deliver:${type}`,
|
|
2754
|
+
title: label,
|
|
2755
|
+
validation: format,
|
|
2756
|
+
audit: { actor: 'local', action: 'deliver', allowed: true, reason: `${label} ${commitments.length}` },
|
|
2757
|
+
})
|
|
2758
|
+
if (flags.json) console.log(JSON.stringify({ ok: true, out, type, format, commitments: commitments.length, total: totalOpen, truncated }, null, 2))
|
|
2759
|
+
else {
|
|
2760
|
+
console.log(`wrote ${out}`)
|
|
2761
|
+
if (truncated) console.log(`提示:共 ${totalOpen} 条未完成承诺,本文件只生成前 ${commitments.length} 条;用 --all 生成全部。`)
|
|
2762
|
+
}
|
|
2087
2763
|
} catch (error) { console.error(`deliver failed: ${error.message}`); process.exitCode = 1 }
|
|
2088
2764
|
}
|
|
2089
2765
|
|
|
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
|
-
|
|
2766
|
+
/**
|
|
2767
|
+
* `advisers mcp --stdio`: the shipped stdio entry for the MCP server.
|
|
2768
|
+
*
|
|
2769
|
+
* The protocol surface lives in lib/mcp-server.js (7 tools incl. the pending-only
|
|
2770
|
+
* candidate write + read-only pack verification, 4 read-only resources, 1 MiB
|
|
2771
|
+
* line cap, -32601/-32602/-32002/-32700). This wiring only supplies process
|
|
2772
|
+
* state: the home, the store/ledger, the version and the audit sink. Every
|
|
2773
|
+
* tools/call is audited through store.appendAudit; a write whose audit row
|
|
2774
|
+
* cannot be appended fails closed (a created candidate is rolled back).
|
|
2775
|
+
*/
|
|
2107
2776
|
async function mcpServer() {
|
|
2108
2777
|
ensureHome()
|
|
2109
2778
|
const store = dbStore()
|
|
2110
2779
|
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
|
-
}
|
|
2780
|
+
const { createMcpServer } = await loadMcpServer()
|
|
2781
|
+
const server = createMcpServer({
|
|
2782
|
+
store,
|
|
2783
|
+
ledger,
|
|
2784
|
+
version: VERSION,
|
|
2785
|
+
audit: (entry) => store?.appendAudit(entry),
|
|
2148
2786
|
})
|
|
2149
|
-
await
|
|
2787
|
+
await server.serve(process.stdin, process.stdout)
|
|
2150
2788
|
}
|
|
2151
2789
|
|
|
2152
2790
|
async function ocrCommand(args) {
|
|
2153
2791
|
const file = args.find((a) => !a.startsWith('--'))
|
|
2154
2792
|
if (!file) { console.error('usage: advisers ocr <image> [--out text]'); process.exitCode = 1; return }
|
|
2155
2793
|
try {
|
|
2794
|
+
const { runLocalOcr } = await loadOcr()
|
|
2156
2795
|
const text = await runLocalOcr(file)
|
|
2157
2796
|
const outIdx = args.indexOf('--out')
|
|
2158
2797
|
if (outIdx >= 0 && args[outIdx + 1]) {
|
|
@@ -2172,48 +2811,97 @@ function vaultPass() {
|
|
|
2172
2811
|
return pass
|
|
2173
2812
|
}
|
|
2174
2813
|
|
|
2175
|
-
function vaultSeal(args) {
|
|
2814
|
+
async function vaultSeal(args) {
|
|
2176
2815
|
const { flags } = parseFlags(args)
|
|
2177
2816
|
ensureHome()
|
|
2178
2817
|
if (!existsSync(DB)) { console.error(`no database at ${DB}`); process.exitCode = 1; return }
|
|
2179
2818
|
const pass = vaultPass(); if (!pass) return
|
|
2819
|
+
const { encryptJson, decryptJson } = await loadVault()
|
|
2820
|
+
const removePlaintext = Boolean(flags.remove) || args.includes('--remove')
|
|
2180
2821
|
try {
|
|
2181
2822
|
const store = new SqliteStore(DB)
|
|
2182
|
-
|
|
2183
|
-
|
|
2184
|
-
|
|
2823
|
+
try {
|
|
2824
|
+
// The copied bytes must contain every committed write, so fold the WAL
|
|
2825
|
+
// first and never ignore a busy checkpoint.
|
|
2826
|
+
const before = store.checkpoint()
|
|
2827
|
+
if (before.busy) throw new Error('database is busy (another advisers process is writing); close it and retry vault seal')
|
|
2828
|
+
store.appendAudit({ actor: 'local', action: 'vault.seal', allowed: true, reason: 'database encrypted at rest' })
|
|
2829
|
+
const after = store.checkpoint()
|
|
2830
|
+
if (after.busy) throw new Error('database is busy (another advisers process is writing); close it and retry vault seal')
|
|
2831
|
+
} finally {
|
|
2832
|
+
try { store.close() } catch {}
|
|
2833
|
+
}
|
|
2185
2834
|
} catch (error) { console.error(`vault seal failed: ${error.message}`); process.exitCode = 1; return }
|
|
2186
2835
|
try {
|
|
2187
2836
|
const bytes = readFileSync(DB)
|
|
2188
2837
|
const sha = createHash('sha256').update(bytes).digest('hex')
|
|
2189
2838
|
const envelope = encryptJson({ kind: 'advisers-db', version: VERSION, sha256: sha, db: bytes.toString('base64') }, pass)
|
|
2190
2839
|
const out = typeof flags.out === 'string' ? flags.out : `${DB}.vault`
|
|
2191
|
-
|
|
2840
|
+
atomicWriteFileSync(out, JSON.stringify(envelope) + '\n', { mode: 0o600 })
|
|
2192
2841
|
const check = decryptJson(JSON.parse(readFileSync(out, 'utf8')), pass)
|
|
2193
2842
|
if (check.sha256 !== sha) throw new Error('sealed file verification failed')
|
|
2194
|
-
if (
|
|
2843
|
+
if (removePlaintext) {
|
|
2195
2844
|
for (const f of [DB, `${DB}-wal`, `${DB}-shm`]) { try { if (existsSync(f)) rmSync(f) } catch {} }
|
|
2845
|
+
fsyncDir(HOME)
|
|
2196
2846
|
}
|
|
2197
|
-
console.log(`sealed ${DB} -> ${out}${
|
|
2847
|
+
console.log(`sealed ${DB} -> ${out}${removePlaintext ? ' (plaintext removed)' : ' (plaintext kept; pass --remove)'}`)
|
|
2198
2848
|
} catch (error) { console.error(`vault seal failed: ${error.message}`); process.exitCode = 1 }
|
|
2199
2849
|
}
|
|
2200
2850
|
|
|
2201
|
-
function vaultUnseal(args) {
|
|
2851
|
+
async function vaultUnseal(args) {
|
|
2202
2852
|
const file = args.find((a) => !a.startsWith('--')) || `${DB}.vault`
|
|
2203
2853
|
if (!existsSync(file)) { console.error(`no sealed database at ${file}`); process.exitCode = 1; return }
|
|
2204
2854
|
const pass = vaultPass(); if (!pass) return
|
|
2855
|
+
let bytes
|
|
2205
2856
|
try {
|
|
2857
|
+
const { decryptJson } = await loadVault()
|
|
2206
2858
|
const payload = decryptJson(JSON.parse(readFileSync(file, 'utf8')), pass)
|
|
2207
2859
|
if (payload.kind !== 'advisers-db' || typeof payload.db !== 'string') throw new Error('not an Advisers database vault')
|
|
2208
|
-
|
|
2860
|
+
bytes = Buffer.from(payload.db, 'base64')
|
|
2209
2861
|
const sha = createHash('sha256').update(bytes).digest('hex')
|
|
2210
2862
|
if (sha !== payload.sha256) throw new Error('vault checksum mismatch')
|
|
2211
|
-
|
|
2212
|
-
|
|
2213
|
-
|
|
2863
|
+
} catch (error) {
|
|
2864
|
+
console.error(`vault unseal failed: ${error.message}`)
|
|
2865
|
+
console.error(`The sealed file ${file} was not touched; retry with the correct passphrase.`)
|
|
2866
|
+
process.exitCode = 1
|
|
2867
|
+
return
|
|
2868
|
+
}
|
|
2869
|
+
ensureHome()
|
|
2870
|
+
// P1-3: never write the payload straight over the live database. Write a
|
|
2871
|
+
// same-directory temp file, fsync it, verify the SQLite image, keep the old
|
|
2872
|
+
// database (and its WAL) as a backup, then rename atomically.
|
|
2873
|
+
const tmp = join(HOME, `.state.db.unseal-${process.pid}-${randomBytes(4).toString('hex')}`)
|
|
2874
|
+
try {
|
|
2875
|
+
writeDurableTemp(tmp, bytes)
|
|
2876
|
+
let check
|
|
2877
|
+
try {
|
|
2878
|
+
check = new SqliteStore(tmp, { readOnly: true, checkIntegrity: true })
|
|
2879
|
+
} catch (error) {
|
|
2880
|
+
throw new Error(`the unsealed database failed its integrity check (${error.message})`)
|
|
2881
|
+
} finally {
|
|
2882
|
+
try { check?.close() } catch {}
|
|
2883
|
+
}
|
|
2884
|
+
let backup
|
|
2885
|
+
if (existsSync(DB)) {
|
|
2886
|
+
backup = `${DB}.before-unseal-${Date.now()}`
|
|
2887
|
+
copyFileSync(DB, backup)
|
|
2888
|
+
for (const suffix of ['-wal', '-shm']) {
|
|
2889
|
+
try { if (existsSync(DB + suffix)) copyFileSync(DB + suffix, backup + suffix) } catch {}
|
|
2890
|
+
}
|
|
2891
|
+
}
|
|
2892
|
+
// A WAL from the old database must never be replayed onto the new file.
|
|
2893
|
+
for (const suffix of ['-wal', '-shm']) { try { if (existsSync(DB + suffix)) rmSync(DB + suffix) } catch {} }
|
|
2894
|
+
renameSync(tmp, DB)
|
|
2214
2895
|
try { chmodSync(DB, 0o600) } catch {}
|
|
2215
|
-
|
|
2216
|
-
|
|
2896
|
+
fsyncDir(HOME)
|
|
2897
|
+
console.log(`unsealed ${file} -> ${DB} (${bytes.length} bytes, integrity ok${backup ? `; previous database kept at ${backup}` : ''})`)
|
|
2898
|
+
} catch (error) {
|
|
2899
|
+
try { if (existsSync(tmp)) rmSync(tmp) } catch {}
|
|
2900
|
+
console.error(`vault unseal failed: ${error.message}`)
|
|
2901
|
+
console.error(`The sealed file ${file} is intact (${bytes.length} bytes of plaintext); the existing database was not replaced.`)
|
|
2902
|
+
console.error('Fix the disk/permissions problem and retry `advisers vault unseal`.')
|
|
2903
|
+
process.exitCode = 1
|
|
2904
|
+
}
|
|
2217
2905
|
}
|
|
2218
2906
|
|
|
2219
2907
|
function vaultStatus() {
|
|
@@ -2228,6 +2916,7 @@ async function timestampCommand(args) {
|
|
|
2228
2916
|
const file = args.find((a) => !a.startsWith('--'))
|
|
2229
2917
|
if (!file) { console.error('usage: advisers timestamp <file> [--out proof]'); process.exitCode = 1; return }
|
|
2230
2918
|
try {
|
|
2919
|
+
const { runLocalTimestamp } = await loadTimestamp()
|
|
2231
2920
|
const proof = await runLocalTimestamp(file)
|
|
2232
2921
|
const outIdx = args.indexOf('--out')
|
|
2233
2922
|
if (outIdx >= 0 && args[outIdx + 1]) {
|
|
@@ -2240,11 +2929,12 @@ async function timestampCommand(args) {
|
|
|
2240
2929
|
|
|
2241
2930
|
async function tui(args) {
|
|
2242
2931
|
const once = args.includes('--once')
|
|
2932
|
+
const { buildReminders } = await loadRemind()
|
|
2243
2933
|
const render = () => {
|
|
2244
2934
|
const ledger = loadLedger()
|
|
2245
2935
|
const store = dbStore()
|
|
2246
2936
|
const open = ledger.openCommitments()
|
|
2247
|
-
const localDay =
|
|
2937
|
+
const localDay = localDayOf(Date.now())
|
|
2248
2938
|
const due = open.filter((c) => c.dueAt && c.dueAt.slice(0, 10) <= localDay)
|
|
2249
2939
|
const reminders = buildReminders(ledger, { now: new Date() })
|
|
2250
2940
|
const deliveries = store?.listDeliveries(3) ?? []
|
|
@@ -2284,12 +2974,56 @@ function syncPass() {
|
|
|
2284
2974
|
return pass
|
|
2285
2975
|
}
|
|
2286
2976
|
|
|
2287
|
-
function
|
|
2977
|
+
async function readSyncDevice() {
|
|
2978
|
+
try {
|
|
2979
|
+
const { sanitizeDevice } = await loadSync()
|
|
2980
|
+
const device = readFileSync(join(HOME, 'sync.device'), 'utf8').trim()
|
|
2981
|
+
return device ? sanitizeDevice(device) : undefined
|
|
2982
|
+
} catch {
|
|
2983
|
+
return undefined
|
|
2984
|
+
}
|
|
2985
|
+
}
|
|
2986
|
+
|
|
2987
|
+
async function rememberSyncDevice(device) {
|
|
2988
|
+
try {
|
|
2989
|
+
const { sanitizeDevice } = await loadSync()
|
|
2990
|
+
writeFileSync(join(HOME, 'sync.device'), sanitizeDevice(device) + '\n', { mode: 0o600 })
|
|
2991
|
+
} catch {}
|
|
2992
|
+
}
|
|
2993
|
+
|
|
2994
|
+
/** Latest mtime of the database + its WAL (captured before any checkpoint). */
|
|
2995
|
+
function latestLocalDbMtime() {
|
|
2996
|
+
let latest = 0
|
|
2997
|
+
for (const file of [DB, `${DB}-wal`]) {
|
|
2998
|
+
try { latest = Math.max(latest, statSync(file).mtimeMs) } catch {}
|
|
2999
|
+
}
|
|
3000
|
+
return latest
|
|
3001
|
+
}
|
|
3002
|
+
|
|
3003
|
+
/** Fold the WAL into the main file before a copy/replace; never ignore busy. */
|
|
3004
|
+
function checkpointLocalDatabase() {
|
|
3005
|
+
if (!existsSync(DB)) return { ok: true, skipped: true }
|
|
3006
|
+
let store
|
|
3007
|
+
try {
|
|
3008
|
+
store = new SqliteStore(DB)
|
|
3009
|
+
const result = store.checkpoint()
|
|
3010
|
+
return { ok: !result.busy, ...result }
|
|
3011
|
+
} catch (error) {
|
|
3012
|
+
// A locked database can make even the open/migrate fail; treat that as
|
|
3013
|
+
// busy so pull refuses instead of replacing a live database (see below).
|
|
3014
|
+
return { ok: false, busy: /SQLITE_BUSY|SQLITE_LOCKED|database is locked/i.test(String(error?.message ?? error)), error }
|
|
3015
|
+
} finally {
|
|
3016
|
+
try { store?.close() } catch {}
|
|
3017
|
+
}
|
|
3018
|
+
}
|
|
3019
|
+
|
|
3020
|
+
async function syncCommand(args) {
|
|
2288
3021
|
const { flags, positional } = parseFlags(args)
|
|
2289
3022
|
const sub = positional[0]
|
|
2290
3023
|
const dir = typeof flags.dir === 'string' ? flags.dir : undefined
|
|
2291
3024
|
if (!dir) { console.error('usage: advisers sync push|pull|status --dir <sync-dir>'); process.exitCode = 1; return }
|
|
2292
3025
|
if (sub === 'status') {
|
|
3026
|
+
const { listSnapshots } = await loadSync()
|
|
2293
3027
|
const snaps = listSnapshots(dir)
|
|
2294
3028
|
if (flags.json) { console.log(JSON.stringify(snaps, null, 2)); return }
|
|
2295
3029
|
console.log(`sync dir: ${dir}`)
|
|
@@ -2301,27 +3035,79 @@ function syncCommand(args) {
|
|
|
2301
3035
|
ensureHome()
|
|
2302
3036
|
if (sub === 'push') {
|
|
2303
3037
|
if (!existsSync(DB)) { console.error(`no database at ${DB}`); process.exitCode = 1; return }
|
|
3038
|
+
const device = typeof flags.device === 'string' ? flags.device : hostname()
|
|
2304
3039
|
try {
|
|
2305
3040
|
const store = new SqliteStore(DB)
|
|
2306
|
-
|
|
2307
|
-
|
|
2308
|
-
|
|
2309
|
-
|
|
3041
|
+
try {
|
|
3042
|
+
const checkpoint = store.checkpoint()
|
|
3043
|
+
if (checkpoint.busy) throw new Error('database is busy (another advisers process is writing); close it and retry sync push')
|
|
3044
|
+
store.appendAudit({ actor: 'local', action: 'sync.push', allowed: true, reason: basename(dir) })
|
|
3045
|
+
const afterAudit = store.checkpoint()
|
|
3046
|
+
if (afterAudit.busy) throw new Error('database is busy (another advisers process is writing); close it and retry sync push')
|
|
3047
|
+
} finally {
|
|
3048
|
+
try { store.close() } catch {}
|
|
3049
|
+
}
|
|
3050
|
+
const { pushSnapshot } = await loadSync()
|
|
3051
|
+
const result = pushSnapshot({ dir, dbPath: DB, passphrase: pass, device })
|
|
3052
|
+
await rememberSyncDevice(device)
|
|
2310
3053
|
console.log(`pushed ${result.file}`)
|
|
2311
3054
|
console.log(`sha256 ${result.sha256}`)
|
|
2312
3055
|
} catch (error) { console.error(`sync push failed: ${error.message}`); process.exitCode = 1 }
|
|
2313
3056
|
} else if (sub === 'pull') {
|
|
3057
|
+
const force = Boolean(flags.force)
|
|
2314
3058
|
try {
|
|
2315
|
-
|
|
3059
|
+
// Capture the local write time before checkpointing (checkpoint touches mtime).
|
|
3060
|
+
const localMtimeMs = latestLocalDbMtime()
|
|
3061
|
+
if (existsSync(DB)) {
|
|
3062
|
+
const checkpoint = checkpointLocalDatabase()
|
|
3063
|
+
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)')
|
|
3064
|
+
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.`)
|
|
3065
|
+
}
|
|
3066
|
+
const { pullSnapshot } = await loadSync()
|
|
3067
|
+
const result = pullSnapshot({
|
|
3068
|
+
dir,
|
|
3069
|
+
dbPath: DB,
|
|
3070
|
+
passphrase: pass,
|
|
3071
|
+
file: typeof flags.file === 'string' ? flags.file : undefined,
|
|
3072
|
+
force,
|
|
3073
|
+
localMtimeMs,
|
|
3074
|
+
localDevice: await readSyncDevice(),
|
|
3075
|
+
})
|
|
2316
3076
|
if (!result.changed) console.log('local database already matches the latest snapshot')
|
|
2317
3077
|
else console.log(`pulled ${result.file} (${result.sha256})${result.backup ? `; backup ${result.backup}` : ''}`)
|
|
2318
|
-
if (result.changed) {
|
|
3078
|
+
if (result.changed) {
|
|
3079
|
+
try { dbStore()?.appendAudit({ actor: 'local', action: 'sync.pull', allowed: true, reason: result.file }) }
|
|
3080
|
+
catch (error) { console.error(`warning: database replaced but the sync.pull audit row failed: ${error.message}`); process.exitCode = 1 }
|
|
3081
|
+
}
|
|
2319
3082
|
} catch (error) { console.error(`sync pull failed: ${error.message}`); process.exitCode = 1 }
|
|
2320
3083
|
} else { console.error('usage: advisers sync push|pull|status --dir <sync-dir>'); process.exitCode = 1 }
|
|
2321
3084
|
}
|
|
2322
3085
|
|
|
2323
|
-
|
|
3086
|
+
/** Read-side source v2 compatibility for the JSON evidence view. */
|
|
3087
|
+
async function normalizeEvidenceSources(result) {
|
|
3088
|
+
const { normalizeSource } = await loadSource()
|
|
3089
|
+
const record = result?.commitment ?? result?.fact ?? result?.preference
|
|
3090
|
+
if (!record || typeof record !== 'object') return result
|
|
3091
|
+
if (Array.isArray(record.evidence)) {
|
|
3092
|
+
record.evidence = record.evidence.map((item) => (item && typeof item === 'object' && item.source ? { ...item, source: normalizeSource(item.source) ?? item.source } : item))
|
|
3093
|
+
}
|
|
3094
|
+
if (record.source && typeof record.source === 'object') record.source = normalizeSource(record.source) ?? record.source
|
|
3095
|
+
return result
|
|
3096
|
+
}
|
|
3097
|
+
|
|
3098
|
+
async function printEvidence(args) {
|
|
2324
3099
|
const { flags, positional } = parseFlags(args)
|
|
3100
|
+
// Offline receipt-pack verification: reads only the given directory. It runs
|
|
3101
|
+
// before ensureHome() so a clean machine needs no ~/.advisers state.
|
|
3102
|
+
if (positional[0] === 'verify') {
|
|
3103
|
+
const dir = positional[1] ?? (typeof flags.dir === 'string' ? flags.dir : undefined)
|
|
3104
|
+
if (!dir) { console.error('usage: advisers evidence verify <dir>'); process.exitCode = 1; return }
|
|
3105
|
+
const { verifyReceiptPackDir } = await loadReceiptVerify()
|
|
3106
|
+
const result = verifyReceiptPackDir(dir)
|
|
3107
|
+
console.log(JSON.stringify(result, null, 2))
|
|
3108
|
+
process.exitCode = result.ok ? 0 : 1
|
|
3109
|
+
return
|
|
3110
|
+
}
|
|
2325
3111
|
ensureHome()
|
|
2326
3112
|
const store = dbStore()
|
|
2327
3113
|
const ledger = loadLedger()
|
|
@@ -2329,12 +3115,14 @@ function printEvidence(args) {
|
|
|
2329
3115
|
if (!id) { console.error('usage: advisers evidence show <id> [--json]'); process.exitCode = 1; return }
|
|
2330
3116
|
let result
|
|
2331
3117
|
try {
|
|
3118
|
+
const { evidenceForCommitment, evidenceForFact, evidenceForPreference } = await loadEvidence()
|
|
2332
3119
|
if (id.startsWith('cm_')) result = evidenceForCommitment(store, ledger, id)
|
|
2333
3120
|
else if (id.startsWith('fact_')) result = evidenceForFact(store, ledger, id)
|
|
2334
3121
|
else if (id.startsWith('pref_')) result = evidenceForPreference(store, ledger, id)
|
|
2335
3122
|
else { console.error('unknown evidence id prefix (want cm_/fact_/pref_)'); process.exitCode = 1; return }
|
|
2336
3123
|
} catch (error) { console.error(error.message); process.exitCode = 1; return }
|
|
2337
3124
|
if (!result || (!result.commitment && !result.fact && !result.preference)) { console.error(`not found: ${id}`); process.exitCode = 1; return }
|
|
3125
|
+
await normalizeEvidenceSources(result)
|
|
2338
3126
|
if (flags.json) { console.log(JSON.stringify(result, null, 2)); return }
|
|
2339
3127
|
const label = result.commitment ? `${result.commitment.action}` : result.fact ? `${result.fact.subject} ${result.fact.predicate}` : result.preference?.statement
|
|
2340
3128
|
console.log(`${id} ${label ?? ''}`)
|
|
@@ -2357,6 +3145,7 @@ async function evidencePack(args) {
|
|
|
2357
3145
|
facts: ledger.listFacts().map((f) => f.id),
|
|
2358
3146
|
preferences: ledger.listPreferences({ includeCandidates: false }).map((p) => p.id),
|
|
2359
3147
|
}
|
|
3148
|
+
const { buildEvidencePack, toDocxRows, verifyPack } = await loadEvidence()
|
|
2360
3149
|
const pack = buildEvidencePack({ store, ledger, ids: targetIds })
|
|
2361
3150
|
const out = flags.out ? String(flags.out) : join(HOME, 'evidence', `evidence-${new Date().toISOString().replace(/[:.]/g, '-')}`)
|
|
2362
3151
|
mkdirSync(out, { recursive: true, mode: 0o700 })
|
|
@@ -2371,12 +3160,226 @@ async function evidencePack(args) {
|
|
|
2371
3160
|
receipt = join(out, 'receipt.docx')
|
|
2372
3161
|
} catch (error) { console.error(`docx receipt skipped: ${error.message}`) }
|
|
2373
3162
|
const verification = verifyPack(pack.files)
|
|
2374
|
-
|
|
2375
|
-
|
|
3163
|
+
// Delivery row + audit row commit together (robustness audit P0-3).
|
|
3164
|
+
recordDeliveryWithAudit({
|
|
3165
|
+
files: [join(out, 'manifest.json'), join(out, 'README.txt'), join(out, 'SHA256SUMS'), ...(receipt ? [receipt] : [])],
|
|
3166
|
+
tool: 'evidence-pack',
|
|
3167
|
+
title: 'evidence pack',
|
|
3168
|
+
validation: verification,
|
|
3169
|
+
audit: { actor: 'local', action: 'evidence.pack', allowed: true, reason: `${pack.summary?.entryCount ?? 0} entries` },
|
|
3170
|
+
})
|
|
2376
3171
|
console.log(JSON.stringify({ out, files: Object.keys(pack.files), receipt, verification }, null, 2))
|
|
2377
3172
|
if (!verification.ok) process.exitCode = 1
|
|
2378
3173
|
}
|
|
2379
3174
|
|
|
3175
|
+
/** "Name <mail>" / "mail" / "Name" -> buildReceiptPack recipient input. */
|
|
3176
|
+
function parseReceiptRecipient(value) {
|
|
3177
|
+
if (value === undefined || value === null || value === true) return undefined
|
|
3178
|
+
const text = String(value).trim()
|
|
3179
|
+
if (!text) return undefined
|
|
3180
|
+
const bracketed = /^(.*?)\s*<([^<>\s]+@[^<>\s]+)>\s*$/.exec(text)
|
|
3181
|
+
if (bracketed) return { name: bracketed[1].trim() || null, email: bracketed[2] }
|
|
3182
|
+
if (/^[^@\s]+@[^@\s]+$/.test(text)) return { email: text }
|
|
3183
|
+
return { name: text }
|
|
3184
|
+
}
|
|
3185
|
+
|
|
3186
|
+
/**
|
|
3187
|
+
* Resolve ONE dist submodule of the optional advisers-office peer without
|
|
3188
|
+
* importing its barrel file. Importing the barrel pulls exceljs/pptxgenjs and
|
|
3189
|
+
* cost ~17s on the test host; verify.js/docx.js only need jszip/docx (~100ms).
|
|
3190
|
+
* Tries the workspace build first (repo/dev/tests), then the installed peer via
|
|
3191
|
+
* its resolved entry URL, then the bare package (portable fallback).
|
|
3192
|
+
*/
|
|
3193
|
+
async function importOfficeSubmodule(name) {
|
|
3194
|
+
try { return await import('../../office/dist/' + name + '.js') } catch {}
|
|
3195
|
+
try {
|
|
3196
|
+
const entry = import.meta.resolve('advisers-office')
|
|
3197
|
+
if (entry.startsWith('file:')) return await import(new URL('./' + name + '.js', entry).href)
|
|
3198
|
+
} catch {}
|
|
3199
|
+
return null
|
|
3200
|
+
}
|
|
3201
|
+
|
|
3202
|
+
/** Load one operation from a specific office submodule, falling back to the barrel. */
|
|
3203
|
+
async function loadOfficeOperation(moduleName, exportName) {
|
|
3204
|
+
const submodule = await importOfficeSubmodule(moduleName)
|
|
3205
|
+
if (typeof submodule?.[exportName] === 'function') return submodule[exportName]
|
|
3206
|
+
const mod = await import('advisers-office')
|
|
3207
|
+
return mod[exportName]
|
|
3208
|
+
}
|
|
3209
|
+
|
|
3210
|
+
/**
|
|
3211
|
+
* Best-effort structural verification of delivered Office artifacts for the
|
|
3212
|
+
* receipt manifest. The optional advisers-office peer may be absent (portable
|
|
3213
|
+
* install): an empty result means "not recorded", which the pack discloses.
|
|
3214
|
+
*/
|
|
3215
|
+
async function verifyDeliveryArtifacts(files) {
|
|
3216
|
+
const supported = []
|
|
3217
|
+
for (const file of files) {
|
|
3218
|
+
const ext = extname(file).slice(1).toLowerCase()
|
|
3219
|
+
if (ext === 'docx' || ext === 'xlsx' || ext === 'pptx') supported.push({ file, ext })
|
|
3220
|
+
}
|
|
3221
|
+
if (!supported.length) return []
|
|
3222
|
+
const verifyModule = await importOfficeSubmodule('verify')
|
|
3223
|
+
const verifyOffice = verifyModule?.verifyOffice
|
|
3224
|
+
if (typeof verifyOffice !== 'function') return []
|
|
3225
|
+
const results = []
|
|
3226
|
+
for (const { file, ext } of supported) {
|
|
3227
|
+
const source = 'advisers verify ' + basename(file)
|
|
3228
|
+
try {
|
|
3229
|
+
const result = await verifyOffice(readFileSync(file), ext)
|
|
3230
|
+
results.push({ source, ...result })
|
|
3231
|
+
} catch (error) {
|
|
3232
|
+
results.push({ source, ok: false, errors: [String(error?.message ?? error)] })
|
|
3233
|
+
}
|
|
3234
|
+
}
|
|
3235
|
+
return results
|
|
3236
|
+
}
|
|
3237
|
+
|
|
3238
|
+
/**
|
|
3239
|
+
* `advisers deliveries --receipt`: build a v1.1 delivery receipt pack.
|
|
3240
|
+
*
|
|
3241
|
+
* The pack copies the delivered artifacts, records their SHA-256 plus the
|
|
3242
|
+
* generator environment / verify results / recipient, and includes the
|
|
3243
|
+
* evidence-pack entries (capped at DEFAULT_MAX_EVIDENCE_ENTRIES unless --all or
|
|
3244
|
+
* --ids narrows/extends it). The old evidence-only path stays on
|
|
3245
|
+
* `deliveries --pack`.
|
|
3246
|
+
*/
|
|
3247
|
+
async function receiptPack(args) {
|
|
3248
|
+
const { flags } = parseFlags(args)
|
|
3249
|
+
ensureHome()
|
|
3250
|
+
const store = dbStore()
|
|
3251
|
+
if (!store) { console.error('deliveries --receipt requires SQLite store'); process.exitCode = 1; return }
|
|
3252
|
+
const ledger = loadLedger()
|
|
3253
|
+
const denied = egressDeniedReason(ledger.getMatter(activeMatterId(ledger)), 'evidence')
|
|
3254
|
+
if (denied) { console.error(denied); process.exitCode = 1; return }
|
|
3255
|
+
const ids = typeof flags.ids === 'string' ? flags.ids.split(',').map((item) => item.trim()).filter(Boolean) : undefined
|
|
3256
|
+
if (ids && !ids.length) { console.error('--ids is empty'); process.exitCode = 1; return }
|
|
3257
|
+
const deliveryLimit = Math.max(1, Math.min(2000, Number(flags.limit) || 100))
|
|
3258
|
+
// A receipt pack records itself as a delivery for discoverability, but a new
|
|
3259
|
+
// receipt must not recursively copy older receipt packs (unbounded growth).
|
|
3260
|
+
const rows = store.listDeliveries(deliveryLimit).filter((row) => row.tool !== 'receipt-pack')
|
|
3261
|
+
if (!rows.length) {
|
|
3262
|
+
console.error('没有交付记录可生成回执包;先运行 `advisers deliver` / `advisers office` / `advisers template`。')
|
|
3263
|
+
process.exitCode = 1
|
|
3264
|
+
return
|
|
3265
|
+
}
|
|
3266
|
+
const skippedFiles = []
|
|
3267
|
+
const deliveries = []
|
|
3268
|
+
for (const row of rows) {
|
|
3269
|
+
const files = []
|
|
3270
|
+
for (const file of Array.isArray(row.files) ? row.files : []) {
|
|
3271
|
+
try {
|
|
3272
|
+
if (typeof file === 'string' && existsSync(file) && statSync(file).isFile()) files.push(file)
|
|
3273
|
+
else skippedFiles.push(row.id + ': ' + String(file))
|
|
3274
|
+
} catch { skippedFiles.push(row.id + ': ' + String(file)) }
|
|
3275
|
+
}
|
|
3276
|
+
if (!files.length) continue
|
|
3277
|
+
deliveries.push({
|
|
3278
|
+
id: row.id,
|
|
3279
|
+
title: row.title ?? null,
|
|
3280
|
+
tool: row.tool ?? null,
|
|
3281
|
+
createdAt: row.createdAt ?? null,
|
|
3282
|
+
validation: row.validation ?? null,
|
|
3283
|
+
files,
|
|
3284
|
+
})
|
|
3285
|
+
}
|
|
3286
|
+
if (!deliveries.length) {
|
|
3287
|
+
console.error('没有仍存在的交付文件,无法生成回执包(文件可能已被移动或删除)。')
|
|
3288
|
+
if (skippedFiles.length) console.error('缺失:' + skippedFiles.slice(0, 5).join('; '))
|
|
3289
|
+
process.exitCode = 1
|
|
3290
|
+
return
|
|
3291
|
+
}
|
|
3292
|
+
if (skippedFiles.length) console.error('注意:' + skippedFiles.length + ' 个交付文件缺失,已跳过(回执只覆盖仍存在的文件)。')
|
|
3293
|
+
|
|
3294
|
+
const verifyResults = await verifyDeliveryArtifacts(deliveries.flatMap((delivery) => delivery.files))
|
|
3295
|
+
const { buildEvidencePack, buildReceiptPack, EvidencePackLimitError } = await loadEvidence()
|
|
3296
|
+
let evidence
|
|
3297
|
+
try {
|
|
3298
|
+
const targetIds = ids ?? {
|
|
3299
|
+
commitments: ledger.listCommitments().map((row) => row.id),
|
|
3300
|
+
facts: ledger.listFacts().map((row) => row.id),
|
|
3301
|
+
preferences: ledger.listPreferences({ includeCandidates: false }).map((row) => row.id),
|
|
3302
|
+
}
|
|
3303
|
+
evidence = buildEvidencePack({ store, ledger, ids: targetIds, all: flags.all === true })
|
|
3304
|
+
} catch (error) {
|
|
3305
|
+
if (error instanceof EvidencePackLimitError || error?.code === 'EVIDENCE_PACK_TOO_LARGE') {
|
|
3306
|
+
console.error('error: ' + error.message)
|
|
3307
|
+
if (error.hint) console.error('hint: ' + error.hint)
|
|
3308
|
+
process.exitCode = 1
|
|
3309
|
+
return
|
|
3310
|
+
}
|
|
3311
|
+
throw error
|
|
3312
|
+
}
|
|
3313
|
+
const out = typeof flags.out === 'string'
|
|
3314
|
+
? flags.out
|
|
3315
|
+
: join(HOME, 'receipts', 'receipt-' + new Date().toISOString().replace(/[:.]/g, '-'))
|
|
3316
|
+
// Generate receipt.docx with the office DOCX submodule when available (fast,
|
|
3317
|
+
// nicer table) or the built-in deterministic writer otherwise.
|
|
3318
|
+
const docxModule = await importOfficeSubmodule('docx')
|
|
3319
|
+
const docxBuilder = typeof docxModule?.buildDocx === 'function'
|
|
3320
|
+
? async (spec) => docxModule.buildDocx(spec)
|
|
3321
|
+
: false
|
|
3322
|
+
let pack
|
|
3323
|
+
try {
|
|
3324
|
+
pack = await buildReceiptPack({
|
|
3325
|
+
deliveries,
|
|
3326
|
+
evidence,
|
|
3327
|
+
verifyResults,
|
|
3328
|
+
docxBuilder,
|
|
3329
|
+
env: {
|
|
3330
|
+
advisersVersion: VERSION,
|
|
3331
|
+
nodeVersion: process.version,
|
|
3332
|
+
platform: process.platform,
|
|
3333
|
+
command: 'advisers deliveries --receipt',
|
|
3334
|
+
},
|
|
3335
|
+
recipient: parseReceiptRecipient(flags.recipient),
|
|
3336
|
+
anchors: [],
|
|
3337
|
+
outDir: out,
|
|
3338
|
+
overwrite: flags.force === true,
|
|
3339
|
+
})
|
|
3340
|
+
} catch (error) {
|
|
3341
|
+
console.error('receipt pack failed: ' + String(error?.message ?? error))
|
|
3342
|
+
process.exitCode = 1
|
|
3343
|
+
return
|
|
3344
|
+
}
|
|
3345
|
+
const summary = pack.summary
|
|
3346
|
+
try {
|
|
3347
|
+
recordDeliveryWithAudit({
|
|
3348
|
+
files: [join(summary.outDir, 'manifest.json'), join(summary.outDir, 'README.txt'), join(summary.outDir, 'SHA256SUMS'), join(summary.outDir, 'receipt.docx')],
|
|
3349
|
+
tool: 'receipt-pack',
|
|
3350
|
+
title: 'delivery receipt pack',
|
|
3351
|
+
validation: 'receipt-pack-v1.1: ' + summary.verifyStatus,
|
|
3352
|
+
audit: { actor: 'local', action: 'receipt.pack', allowed: true, reason: deliveries.length + ' deliveries/' + summary.fileCount + ' files' },
|
|
3353
|
+
})
|
|
3354
|
+
} catch {}
|
|
3355
|
+
const { verifyReceiptPackDir } = await loadReceiptVerify()
|
|
3356
|
+
const verification = verifyReceiptPackDir(summary.outDir)
|
|
3357
|
+
console.log(JSON.stringify({
|
|
3358
|
+
ok: verification.ok,
|
|
3359
|
+
format: summary.format,
|
|
3360
|
+
version: summary.version,
|
|
3361
|
+
out: summary.outDir,
|
|
3362
|
+
replaced: summary.replaced ?? null,
|
|
3363
|
+
deliveryCount: summary.deliveryCount,
|
|
3364
|
+
fileCount: summary.fileCount,
|
|
3365
|
+
verifyStatus: summary.verifyStatus,
|
|
3366
|
+
anchored: summary.anchored,
|
|
3367
|
+
recipient: summary.recipient,
|
|
3368
|
+
manifestDigest: summary.manifestDigest,
|
|
3369
|
+
receiptSha256: summary.receiptSha256,
|
|
3370
|
+
evidence: summary.evidence,
|
|
3371
|
+
files: summary.files,
|
|
3372
|
+
skippedFiles,
|
|
3373
|
+
verification: {
|
|
3374
|
+
ok: verification.ok,
|
|
3375
|
+
errors: verification.errors,
|
|
3376
|
+
warnings: verification.warnings,
|
|
3377
|
+
checksumCount: verification.checksumCount,
|
|
3378
|
+
},
|
|
3379
|
+
}, null, 2))
|
|
3380
|
+
if (!verification.ok) process.exitCode = 1
|
|
3381
|
+
}
|
|
3382
|
+
|
|
2380
3383
|
function link(sub, from, to, type) {
|
|
2381
3384
|
const ledger = loadLedger()
|
|
2382
3385
|
if (sub === 'ls' || !sub) {
|
|
@@ -2476,8 +3479,7 @@ function link(sub, from, to, type) {
|
|
|
2476
3479
|
const factId = proposal.rollback.slice(5)
|
|
2477
3480
|
const ok = ledger.forget('fact', factId)
|
|
2478
3481
|
proposal.rollback = `rolledback:${factId}`
|
|
2479
|
-
|
|
2480
|
-
saveLedger(ledger)
|
|
3482
|
+
saveLedgerWithAudit(ledger, { actor: 'local', action: 'link.rollback', allowed: true, reason: factId })
|
|
2481
3483
|
console.log(ok ? `rolled back: ${factId}` : `fact not found: ${factId}`)
|
|
2482
3484
|
if (!ok) process.exitCode = 1
|
|
2483
3485
|
return
|
|
@@ -2528,8 +3530,7 @@ function link(sub, from, to, type) {
|
|
|
2528
3530
|
}
|
|
2529
3531
|
if (sub === 'reject') {
|
|
2530
3532
|
ledger.resolveUpdate(from, 'rejected')
|
|
2531
|
-
|
|
2532
|
-
saveLedger(ledger)
|
|
3533
|
+
saveLedgerWithAudit(ledger, { actor: 'local', action: 'link.reject', allowed: true, reason: from })
|
|
2533
3534
|
console.log(`rejected: ${from}`)
|
|
2534
3535
|
return
|
|
2535
3536
|
}
|
|
@@ -2542,8 +3543,7 @@ function link(sub, from, to, type) {
|
|
|
2542
3543
|
source: { type: 'import', ref: proposal.id },
|
|
2543
3544
|
})
|
|
2544
3545
|
ledger.resolveUpdate(from, 'applied', `fact:${fact.id}`)
|
|
2545
|
-
|
|
2546
|
-
saveLedger(ledger)
|
|
3546
|
+
saveLedgerWithAudit(ledger, { actor: 'local', action: 'link.apply', allowed: true, reason: `${from} -> ${fact.id}` })
|
|
2547
3547
|
console.log(`applied: ${from} -> target fact ${fact.id}`)
|
|
2548
3548
|
return
|
|
2549
3549
|
}
|
|
@@ -2695,7 +3695,7 @@ async function office(kind, specFile, outFile) {
|
|
|
2695
3695
|
if (!result.ok) process.exitCode = 1
|
|
2696
3696
|
}
|
|
2697
3697
|
|
|
2698
|
-
function soul(sub, file) {
|
|
3698
|
+
async function soul(sub, file) {
|
|
2699
3699
|
if (sub === 'show') {
|
|
2700
3700
|
const doc = loadSoul()
|
|
2701
3701
|
if (!doc) {
|
|
@@ -2717,6 +3717,7 @@ function soul(sub, file) {
|
|
|
2717
3717
|
process.exitCode = 1
|
|
2718
3718
|
return
|
|
2719
3719
|
}
|
|
3720
|
+
await requireTosReaccept({ scope: 'config', subject: 'soul', action: 'soul set' })
|
|
2720
3721
|
const previous = loadSoul()
|
|
2721
3722
|
const content = readFileSync(file, 'utf8')
|
|
2722
3723
|
const doc = {
|
|
@@ -2735,6 +3736,7 @@ function soul(sub, file) {
|
|
|
2735
3736
|
console.log('soul.md already exists; use `advisers soul set <file>` to replace it')
|
|
2736
3737
|
return
|
|
2737
3738
|
}
|
|
3739
|
+
await requireTosReaccept({ scope: 'config', subject: 'soul', action: 'soul init' })
|
|
2738
3740
|
const doc = {
|
|
2739
3741
|
id: 'soul',
|
|
2740
3742
|
version: 1,
|
|
@@ -2753,6 +3755,299 @@ function soul(sub, file) {
|
|
|
2753
3755
|
process.exitCode = 1
|
|
2754
3756
|
}
|
|
2755
3757
|
|
|
3758
|
+
// ---------------------------------------------------------------------------
|
|
3759
|
+
// TOS consent gate (docs/TOS.md §2)
|
|
3760
|
+
//
|
|
3761
|
+
// L1: every non-exempt command requires an accepted TOS for the CURRENT version
|
|
3762
|
+
// + text hash. Missing acceptance: TTY shows a 12-line summary and requires
|
|
3763
|
+
// typing 同意; non-TTY exits 3 with a single E_TOS_REQUIRED stderr line
|
|
3764
|
+
// (`--accept-tos` / `ADVISERS_ACCEPT_TOS=1` records channel=flag|env and
|
|
3765
|
+
// nonInteractive=1, then continues). A version/text change re-requires.
|
|
3766
|
+
// L2: modification surfaces (soul set/init, routine writes, import --replace)
|
|
3767
|
+
// each need a fresh confirmation and write audit action=tos.reaccept.
|
|
3768
|
+
//
|
|
3769
|
+
// The acceptance record is ~/.advisers/tos.json (0600, atomic); the audit chain
|
|
3770
|
+
// gets action=tos.accept|tos.block|tos.reaccept|tos.revoke with a reason that
|
|
3771
|
+
// names version/sha256/channel and NEVER the terms text.
|
|
3772
|
+
// ---------------------------------------------------------------------------
|
|
3773
|
+
|
|
3774
|
+
/** Commands usable without accepting the TOS (TOS §2.1: local functions stay usable). */
|
|
3775
|
+
const TOS_EXEMPT_COMMANDS = new Set(['help', '--help', 'version', '--version', '-v', 'status', 'doctor', 'init', 'tos'])
|
|
3776
|
+
/** Known commands. Unknown commands keep the plain "unknown command" error, not the gate. */
|
|
3777
|
+
const KNOWN_COMMANDS = new Set([
|
|
3778
|
+
'version', '--version', '-v', 'help', '--help', 'chat', 'status', 'doctor', 'init', 'history', 'mcp',
|
|
3779
|
+
'deliver', 'timestamp', 'tui', 'ocr', 'evidence', 'receipt', 'deliveries', 'learn', 'commit', 'diff',
|
|
3780
|
+
'undo', 'compact', 'search', 'nudge', 'risks', 'pet-brief', 'today', 'tick', 'ui', 'remind', 'calendar',
|
|
3781
|
+
'who', 'memory', 'digest', 'week', 'prefs', 'privacy', 'audit', 'purge', 'decay', 'correct', 'ls', 'why',
|
|
3782
|
+
'forget', 'sync', 'vault', 'export', 'import', 'backup', 'brief', 'review', 'research', 'capture', 'policy',
|
|
3783
|
+
'office-edit', 'office-read', 'verify', 'office', 'routine', 'template', 'link', 'bridge', 'soul', 'tos',
|
|
3784
|
+
])
|
|
3785
|
+
|
|
3786
|
+
/** Append a TOS audit row; audit is best-effort (JSON store has no audit chain). */
|
|
3787
|
+
function tosAudit(action, allowed, reason) {
|
|
3788
|
+
try {
|
|
3789
|
+
ensureHome()
|
|
3790
|
+
dbStore()?.appendAudit({ actor: 'local', action, allowed, reason })
|
|
3791
|
+
} catch {}
|
|
3792
|
+
}
|
|
3793
|
+
|
|
3794
|
+
/** Audit reason material: names version/sha256/channel, never the terms text. */
|
|
3795
|
+
function tosAuditReason({ version, sha256, channel, nonInteractive, extra = '' }) {
|
|
3796
|
+
return `version=${version};sha256=${sha256};channel=${channel};nonInteractive=${nonInteractive ? 1 : 0}${extra}`
|
|
3797
|
+
}
|
|
3798
|
+
|
|
3799
|
+
async function recordTosAcceptance(tos, info, { channel, nonInteractive }) {
|
|
3800
|
+
const record = tos.writeAcceptance(HOME, {
|
|
3801
|
+
version: info.version,
|
|
3802
|
+
sha256: info.sha256,
|
|
3803
|
+
acceptedAt: new Date().toISOString(),
|
|
3804
|
+
channel,
|
|
3805
|
+
nonInteractive,
|
|
3806
|
+
})
|
|
3807
|
+
tosAudit('tos.accept', true, tosAuditReason({ version: info.version, sha256: info.sha256, channel, nonInteractive, extra: ';scope=app' }))
|
|
3808
|
+
return record
|
|
3809
|
+
}
|
|
3810
|
+
|
|
3811
|
+
function tosRequiredLine(version) {
|
|
3812
|
+
return `advisers: 需要先同意使用条款 ${version}(E_TOS_REQUIRED)。运行 advisers tos show 查看全文;非交互环境加 --accept-tos 或 ADVISERS_ACCEPT_TOS=1。`
|
|
3813
|
+
}
|
|
3814
|
+
|
|
3815
|
+
function tosReacceptRequiredLine(version) {
|
|
3816
|
+
return `advisers: 此修改需要再次确认使用条款 ${version}(E_TOS_REQUIRED)。--yes 不能代替 TOS 确认;非交互环境加 --accept-tos 或 ADVISERS_ACCEPT_TOS=1(运行 advisers tos show 查看全文)。`
|
|
3817
|
+
}
|
|
3818
|
+
|
|
3819
|
+
/** TOS §2.3 "源码修改版" notice: TTY-only, non-blocking, once per fingerprint change. */
|
|
3820
|
+
async function maybeSourceModifiedNotice(tos) {
|
|
3821
|
+
try {
|
|
3822
|
+
if (!process.stdin.isTTY) return
|
|
3823
|
+
const fingerprint = tos.sourceCheckoutFingerprint()
|
|
3824
|
+
if (!fingerprint || !tos.shouldNoticeSourceModified({ home: HOME, fingerprint })) return
|
|
3825
|
+
for (const line of tos.sourceModifiedNotice({ fingerprint })) console.error(line)
|
|
3826
|
+
tos.writeSourceFingerprint(HOME, fingerprint)
|
|
3827
|
+
} catch {}
|
|
3828
|
+
}
|
|
3829
|
+
|
|
3830
|
+
/** L1 gate: run before dispatch; exits the process on block/reject (exit 3 / exit 1). */
|
|
3831
|
+
async function tosGate() {
|
|
3832
|
+
const isTTY = Boolean(process.stdin.isTTY)
|
|
3833
|
+
if (!command) { if (!isTTY) return }
|
|
3834
|
+
// Offline receipt verification must work on a clean machine without a
|
|
3835
|
+
// ~/.advisers consent record (docs/DELIVERY-RECEIPT.md); it reads only <dir>.
|
|
3836
|
+
else if (command === 'evidence' && args[0] === 'verify') return
|
|
3837
|
+
else if (TOS_EXEMPT_COMMANDS.has(command) || !KNOWN_COMMANDS.has(command)) return
|
|
3838
|
+
const tos = await loadTos()
|
|
3839
|
+
const info = tos.currentTos()
|
|
3840
|
+
const status = tos.acceptanceStatus({ home: HOME, version: info.version, sha256: info.sha256 })
|
|
3841
|
+
if (status.accepted) { await maybeSourceModifiedNotice(tos); return }
|
|
3842
|
+
const explicit = tos.resolveConsent({ flag: acceptTosFlag, env: process.env.ADVISERS_ACCEPT_TOS, version: info.version, isTTY })
|
|
3843
|
+
if (explicit?.error) { console.error(`advisers: ${explicit.error}`); process.exit(1) }
|
|
3844
|
+
if (explicit?.ok) {
|
|
3845
|
+
await recordTosAcceptance(tos, info, { channel: explicit.channel, nonInteractive: true })
|
|
3846
|
+
await maybeSourceModifiedNotice(tos)
|
|
3847
|
+
return
|
|
3848
|
+
}
|
|
3849
|
+
if (!isTTY) {
|
|
3850
|
+
tosAudit('tos.block', false, tosAuditReason({ version: info.version, sha256: info.sha256, channel: 'none', nonInteractive: true, extra: `;scope=app;reason=${status.reason}` }))
|
|
3851
|
+
console.error(tosRequiredLine(info.version))
|
|
3852
|
+
process.exit(3)
|
|
3853
|
+
}
|
|
3854
|
+
const answer = await tos.promptForConsent({ version: info.version, url: info.url })
|
|
3855
|
+
if (answer.accepted) {
|
|
3856
|
+
await recordTosAcceptance(tos, info, { channel: 'interactive', nonInteractive: false })
|
|
3857
|
+
console.log(`已接受使用条款 v${info.version}(channel=interactive);撤回:advisers tos revoke。`)
|
|
3858
|
+
await maybeSourceModifiedNotice(tos)
|
|
3859
|
+
return
|
|
3860
|
+
}
|
|
3861
|
+
tosAudit('tos.block', false, tosAuditReason({ version: info.version, sha256: info.sha256, channel: 'interactive', nonInteractive: false, extra: `;scope=app;reason=${answer.reason}` }))
|
|
3862
|
+
console.error(`未接受使用条款 v${info.version};受门控的命令已停止(运行 advisers tos show 查看全文)。`)
|
|
3863
|
+
process.exit(1)
|
|
3864
|
+
}
|
|
3865
|
+
|
|
3866
|
+
/** L2 gate: per-modification re-confirmation (TOS §2.3). Returns true when allowed. */
|
|
3867
|
+
async function requireTosReaccept({ scope, subject = '', action }) {
|
|
3868
|
+
const tos = await loadTos()
|
|
3869
|
+
const info = tos.currentTos()
|
|
3870
|
+
const isTTY = Boolean(process.stdin.isTTY)
|
|
3871
|
+
const extra = `;scope=${scope}${subject ? `;subject=${subject}` : ''};action=${action ?? '-'}`
|
|
3872
|
+
const explicit = tos.resolveConsent({ flag: acceptTosFlag, env: process.env.ADVISERS_ACCEPT_TOS, version: info.version, isTTY })
|
|
3873
|
+
if (explicit?.error) { console.error(`advisers: ${explicit.error}`); process.exit(1) }
|
|
3874
|
+
if (explicit?.ok) {
|
|
3875
|
+
tosAudit('tos.reaccept', true, tosAuditReason({ version: info.version, sha256: info.sha256, channel: explicit.channel, nonInteractive: true, extra }))
|
|
3876
|
+
return true
|
|
3877
|
+
}
|
|
3878
|
+
if (!isTTY) {
|
|
3879
|
+
tosAudit('tos.block', false, tosAuditReason({ version: info.version, sha256: info.sha256, channel: 'none', nonInteractive: true, extra: `;reason=reaccept-required${extra}` }))
|
|
3880
|
+
console.error(tosReacceptRequiredLine(info.version))
|
|
3881
|
+
process.exit(3)
|
|
3882
|
+
}
|
|
3883
|
+
const answer = await tos.promptForConsent({
|
|
3884
|
+
version: info.version,
|
|
3885
|
+
lines: tos.modificationNotice({ scope, action }),
|
|
3886
|
+
question: '继续?输入“同意”或 y 确认(n 或直接 Enter 取消):',
|
|
3887
|
+
})
|
|
3888
|
+
if (answer.accepted) {
|
|
3889
|
+
tosAudit('tos.reaccept', true, tosAuditReason({ version: info.version, sha256: info.sha256, channel: 'interactive', nonInteractive: false, extra }))
|
|
3890
|
+
console.log(`已再次确认使用条款(scope=${scope});本次确认已写入本地审计链。`)
|
|
3891
|
+
return true
|
|
3892
|
+
}
|
|
3893
|
+
tosAudit('tos.block', false, tosAuditReason({ version: info.version, sha256: info.sha256, channel: 'interactive', nonInteractive: false, extra: `;reason=rejected${extra}` }))
|
|
3894
|
+
console.error(`未确认修改(scope=${scope});操作已取消。`)
|
|
3895
|
+
process.exit(1)
|
|
3896
|
+
}
|
|
3897
|
+
|
|
3898
|
+
function tosAuditState() {
|
|
3899
|
+
if (mode !== 'sqlite') return { available: false, note: 'unavailable (json store)' }
|
|
3900
|
+
if (!existsSync(DB)) return { available: false, note: 'no audit chain yet' }
|
|
3901
|
+
try {
|
|
3902
|
+
const store = openStore()
|
|
3903
|
+
const verify = store.verifyAudit()
|
|
3904
|
+
const counts = { accept: 0, block: 0, reaccept: 0, revoke: 0 }
|
|
3905
|
+
for (const row of store.listAudit(10000)) {
|
|
3906
|
+
if (row.action === 'tos.accept') counts.accept++
|
|
3907
|
+
else if (row.action === 'tos.block') counts.block++
|
|
3908
|
+
else if (row.action === 'tos.reaccept') counts.reaccept++
|
|
3909
|
+
else if (row.action === 'tos.revoke') counts.revoke++
|
|
3910
|
+
}
|
|
3911
|
+
return { available: true, verified: verify.ok, brokenAt: verify.ok ? null : verify.seq, count: verify.count ?? 0, counts }
|
|
3912
|
+
} catch (error) {
|
|
3913
|
+
return { available: false, note: `unavailable (${error.message})` }
|
|
3914
|
+
}
|
|
3915
|
+
}
|
|
3916
|
+
|
|
3917
|
+
function tosStatusFacts(tos, info, status) {
|
|
3918
|
+
const record = status.record
|
|
3919
|
+
return {
|
|
3920
|
+
version: info.version,
|
|
3921
|
+
manifestVersion: info.manifestVersion,
|
|
3922
|
+
effectiveFrom: info.effectiveFrom,
|
|
3923
|
+
textSha256: info.sha256,
|
|
3924
|
+
canonical: info.canonical,
|
|
3925
|
+
termsPath: info.termsPath,
|
|
3926
|
+
url: info.url,
|
|
3927
|
+
accepted: status.accepted,
|
|
3928
|
+
reason: status.reason,
|
|
3929
|
+
acceptance: record ? {
|
|
3930
|
+
version: record.version,
|
|
3931
|
+
sha256: record.sha256,
|
|
3932
|
+
acceptedAt: record.acceptedAt,
|
|
3933
|
+
channel: record.channel,
|
|
3934
|
+
nonInteractive: record.nonInteractive,
|
|
3935
|
+
...(record.revokedAt ? { revokedAt: record.revokedAt } : {}),
|
|
3936
|
+
} : null,
|
|
3937
|
+
store: { type: mode, path: mode === 'sqlite' ? DB : STATE },
|
|
3938
|
+
audit: tosAuditState(),
|
|
3939
|
+
futureSeparateConsent: ['content packs / DLC (not shipped in 0.2.0)', 'text-to-speech / TTS (not shipped in 0.2.0)'],
|
|
3940
|
+
}
|
|
3941
|
+
}
|
|
3942
|
+
|
|
3943
|
+
function printTosStatus(tos, info, status, asJson) {
|
|
3944
|
+
const facts = tosStatusFacts(tos, info, status)
|
|
3945
|
+
if (asJson) { console.log(JSON.stringify(facts, null, 2)); return }
|
|
3946
|
+
const record = facts.acceptance
|
|
3947
|
+
console.log(`version ${facts.version}(生效 ${facts.effectiveFrom};manifest ${facts.manifestVersion})`)
|
|
3948
|
+
console.log(`sha256 ${facts.textSha256}`)
|
|
3949
|
+
if (facts.accepted) {
|
|
3950
|
+
console.log(`accepted yes · channel=${record.channel} · nonInteractive=${record.nonInteractive ? 1 : 0} · ${record.acceptedAt}`)
|
|
3951
|
+
} else {
|
|
3952
|
+
console.log(`accepted no · reason=${facts.reason}${record ? ` · last channel=${record.channel} · ${record.acceptedAt}` : ''}${record?.revokedAt ? ` · revokedAt=${record.revokedAt}` : ''}`)
|
|
3953
|
+
console.log('next advisers tos accept(交互输入“同意”)或非交互加 --accept-tos / ADVISERS_ACCEPT_TOS=1')
|
|
3954
|
+
}
|
|
3955
|
+
console.log(`terms ${facts.termsPath}`)
|
|
3956
|
+
console.log(`url ${facts.url}`)
|
|
3957
|
+
console.log(`store ${facts.store.type}${facts.store.path ? ` (${facts.store.path})` : ''}`)
|
|
3958
|
+
if (facts.audit.available) {
|
|
3959
|
+
const c = facts.audit.counts
|
|
3960
|
+
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}`)
|
|
3961
|
+
} else {
|
|
3962
|
+
console.log(`audit ${facts.audit.note}`)
|
|
3963
|
+
}
|
|
3964
|
+
console.log('future DLC / TTS are not available in 0.2.0; if they ship they will require a separate, explicit consent')
|
|
3965
|
+
}
|
|
3966
|
+
|
|
3967
|
+
function tosUsage(version = '') {
|
|
3968
|
+
console.log(`usage: advisers tos <show|status|accept|revoke>${version ? ` (当前版本 v${version})` : ''}
|
|
3969
|
+
advisers tos show 打印完整使用条款
|
|
3970
|
+
advisers tos status [--json] 版本、接受记录、审计状态(含 DLC/TTS 未来单独同意说明)
|
|
3971
|
+
advisers tos accept 接受当前使用条款(非交互需 --accept-tos 或 ADVISERS_ACCEPT_TOS=1)
|
|
3972
|
+
advisers tos revoke [--yes] 撤回同意(受门控命令随后会重新要求确认)`)
|
|
3973
|
+
}
|
|
3974
|
+
|
|
3975
|
+
async function tosCommand(argv) {
|
|
3976
|
+
const tos = await loadTos()
|
|
3977
|
+
const sub = argv[0]
|
|
3978
|
+
const info = tos.currentTos()
|
|
3979
|
+
if (!sub || sub === 'help' || sub === '--help') { tosUsage(info.version); return }
|
|
3980
|
+
const status = tos.acceptanceStatus({ home: HOME, version: info.version, sha256: info.sha256 })
|
|
3981
|
+
if (sub === 'show') {
|
|
3982
|
+
console.log(`Advisers 使用条款 v${info.version}(生效 ${info.effectiveFrom})`)
|
|
3983
|
+
console.log(`文本 SHA-256:${info.sha256}`)
|
|
3984
|
+
console.log(`规范文本:${info.canonical};随包副本:${info.termsPath};在线:${info.url}`)
|
|
3985
|
+
console.log('---')
|
|
3986
|
+
process.stdout.write(readFileSync(info.termsPath, 'utf8'))
|
|
3987
|
+
return
|
|
3988
|
+
}
|
|
3989
|
+
if (sub === 'status') { printTosStatus(tos, info, status, argv.includes('--json')); return }
|
|
3990
|
+
if (sub === 'accept') {
|
|
3991
|
+
if (status.accepted) {
|
|
3992
|
+
console.log(`已接受使用条款 v${info.version}(channel=${status.record.channel},${status.record.acceptedAt});撤回:advisers tos revoke。`)
|
|
3993
|
+
return
|
|
3994
|
+
}
|
|
3995
|
+
const isTTY = Boolean(process.stdin.isTTY)
|
|
3996
|
+
const explicit = tos.resolveConsent({ flag: acceptTosFlag, env: process.env.ADVISERS_ACCEPT_TOS, version: info.version, isTTY })
|
|
3997
|
+
if (explicit?.error) { console.error(`advisers: ${explicit.error}`); process.exitCode = 1; return }
|
|
3998
|
+
if (explicit?.ok) {
|
|
3999
|
+
await recordTosAcceptance(tos, info, { channel: explicit.channel, nonInteractive: true })
|
|
4000
|
+
console.log(`已接受使用条款 v${info.version}(channel=${explicit.channel},nonInteractive=1);已写入本地审计链。`)
|
|
4001
|
+
return
|
|
4002
|
+
}
|
|
4003
|
+
if (!isTTY) {
|
|
4004
|
+
tosAudit('tos.block', false, tosAuditReason({ version: info.version, sha256: info.sha256, channel: 'none', nonInteractive: true, extra: ';scope=app;reason=command-accept-requires-flag' }))
|
|
4005
|
+
console.error(tosRequiredLine(info.version))
|
|
4006
|
+
process.exitCode = 3
|
|
4007
|
+
return
|
|
4008
|
+
}
|
|
4009
|
+
const answer = await tos.promptForConsent({ version: info.version, url: info.url })
|
|
4010
|
+
if (answer.accepted) {
|
|
4011
|
+
await recordTosAcceptance(tos, info, { channel: 'interactive', nonInteractive: false })
|
|
4012
|
+
console.log(`已接受使用条款 v${info.version}(channel=interactive);已写入本地审计链。撤回:advisers tos revoke。`)
|
|
4013
|
+
return
|
|
4014
|
+
}
|
|
4015
|
+
tosAudit('tos.block', false, tosAuditReason({ version: info.version, sha256: info.sha256, channel: 'interactive', nonInteractive: false, extra: ';scope=app;reason=rejected' }))
|
|
4016
|
+
console.error(`未接受使用条款 v${info.version}。`)
|
|
4017
|
+
process.exitCode = 1
|
|
4018
|
+
return
|
|
4019
|
+
}
|
|
4020
|
+
if (sub === 'revoke') {
|
|
4021
|
+
const record = tos.readAcceptance(HOME)
|
|
4022
|
+
if (!record || record.revokedAt) { console.log('当前没有有效的同意记录(无需撤回)。'); return }
|
|
4023
|
+
const isTTY = Boolean(process.stdin.isTTY)
|
|
4024
|
+
const confirmedByFlag = argv.includes('--yes')
|
|
4025
|
+
if (!isTTY && !confirmedByFlag) {
|
|
4026
|
+
console.error('advisers: 撤回同意会停止受门控命令;非交互环境请加 --yes 确认(advisers tos revoke --yes)。')
|
|
4027
|
+
process.exitCode = 1
|
|
4028
|
+
return
|
|
4029
|
+
}
|
|
4030
|
+
if (isTTY && !confirmedByFlag) {
|
|
4031
|
+
const answer = await tos.promptForConsent({
|
|
4032
|
+
version: info.version,
|
|
4033
|
+
lines: ['撤回同意 · ' + `v${info.version}`, '撤回后受门控的命令会停止(help/status/doctor/tos 等本地功能仍可用)。', '撤回不影响撤回前已发生行为的效力,也不影响仓库许可证已授予的权利。'],
|
|
4034
|
+
question: '确认撤回?输入“同意”或 y 确认(n 或直接 Enter 取消):',
|
|
4035
|
+
})
|
|
4036
|
+
if (!answer.accepted) { console.log('已取消撤回。'); return }
|
|
4037
|
+
}
|
|
4038
|
+
const revoked = tos.revokeAcceptance(HOME, { revokedAt: new Date().toISOString() })
|
|
4039
|
+
if (!revoked) { console.log('当前没有有效的同意记录(无需撤回)。'); return }
|
|
4040
|
+
tosAudit('tos.revoke', true, tosAuditReason({ version: revoked.version, sha256: revoked.sha256, channel: isTTY ? 'interactive' : 'command', nonInteractive: isTTY ? false : true, extra: ';scope=app' }))
|
|
4041
|
+
console.log(`已撤回使用条款 v${info.version} 的同意;受门控的命令将重新要求确认(advisers tos accept 可重新接受)。`)
|
|
4042
|
+
return
|
|
4043
|
+
}
|
|
4044
|
+
tosUsage(info.version)
|
|
4045
|
+
process.exitCode = 1
|
|
4046
|
+
}
|
|
4047
|
+
|
|
4048
|
+
// L1 consent gate: runs once before dispatch (exempt commands return immediately).
|
|
4049
|
+
await tosGate()
|
|
4050
|
+
|
|
2756
4051
|
if (!command) {
|
|
2757
4052
|
if (process.stdin.isTTY) await repl()
|
|
2758
4053
|
else help()
|
|
@@ -2782,17 +4077,24 @@ if (!command) {
|
|
|
2782
4077
|
} else if (command === 'ocr') {
|
|
2783
4078
|
await ocrCommand(args)
|
|
2784
4079
|
} else if (command === 'evidence') {
|
|
2785
|
-
printEvidence(args)
|
|
4080
|
+
await printEvidence(args)
|
|
2786
4081
|
} else if (command === 'receipt') {
|
|
2787
4082
|
printReceipt()
|
|
2788
4083
|
} else if (command === 'deliveries') {
|
|
2789
|
-
if (args.includes('--
|
|
4084
|
+
if (args.includes('--receipt')) await receiptPack(args)
|
|
4085
|
+
else if (args.includes('--pack')) await evidencePack(args)
|
|
2790
4086
|
else if (args.includes('--json')) console.log(JSON.stringify(dbStore()?.listDeliveries(100) ?? [], null, 2))
|
|
2791
4087
|
else printDeliveries()
|
|
2792
4088
|
} else if (command === 'learn') {
|
|
2793
4089
|
const sub = args[0]
|
|
2794
4090
|
const store = dbStore()
|
|
2795
|
-
|
|
4091
|
+
let learnDenied = null
|
|
4092
|
+
if (sub === 'review') {
|
|
4093
|
+
const learnLedger = loadLedger()
|
|
4094
|
+
learnDenied = egressDeniedReason(learnLedger.getMatter(activeMatterId(learnLedger)), 'learn review')
|
|
4095
|
+
}
|
|
4096
|
+
if (sub === 'review' && learnDenied) { console.error(learnDenied); process.exitCode = 1 }
|
|
4097
|
+
else if (sub === 'ls') {
|
|
2796
4098
|
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
4099
|
} else if (sub === 'review') {
|
|
2798
4100
|
const run = store?.listTaskRuns(100).find((r) => r.id === args[1])
|
|
@@ -2816,21 +4118,58 @@ if (!command) {
|
|
|
2816
4118
|
const { flags, positional } = parseFlags(args.slice(1))
|
|
2817
4119
|
if (sub === 'add') {
|
|
2818
4120
|
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 }
|
|
4121
|
+
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
4122
|
else {
|
|
2821
|
-
|
|
2822
|
-
|
|
2823
|
-
|
|
2824
|
-
|
|
2825
|
-
|
|
2826
|
-
|
|
2827
|
-
|
|
2828
|
-
|
|
2829
|
-
|
|
2830
|
-
|
|
2831
|
-
|
|
2832
|
-
|
|
2833
|
-
|
|
4123
|
+
let reminderOffsets
|
|
4124
|
+
let offsetsError
|
|
4125
|
+
try { reminderOffsets = await parseReminderOffsetsFlag(flags) } catch (error) { offsetsError = error }
|
|
4126
|
+
if (offsetsError) { console.error(offsetsError.message); process.exitCode = 1 }
|
|
4127
|
+
else {
|
|
4128
|
+
const c = ledger.addCommitment({
|
|
4129
|
+
matterId: activeMatterId(ledger, flags.matter),
|
|
4130
|
+
debtor: flags.debtor ?? 'user',
|
|
4131
|
+
creditor: flags.creditor ?? /(?:发给|给|向|对)([\u4e00-\u9fa5A-Za-z0-9_]{1,12})/.exec(action)?.[1] ?? 'someone',
|
|
4132
|
+
action,
|
|
4133
|
+
dueAt: flags.due,
|
|
4134
|
+
timezone: flags.tz ?? 'Asia/Shanghai',
|
|
4135
|
+
capability: flags.capability ?? 'todo',
|
|
4136
|
+
evidence: [{ sessionId: latestConversationId(), turnId: 'cli', quote: String(flags.quote) }],
|
|
4137
|
+
...(reminderOffsets !== undefined ? { reminderOffsets } : {}),
|
|
4138
|
+
})
|
|
4139
|
+
saveLedgerWithAudit(ledger, { actor: 'local', action: 'commit.add', allowed: true, reason: c.id })
|
|
4140
|
+
console.log(`${c.id} open ${c.action}${c.dueAt ? ` due ${c.dueAt}` : ''}`)
|
|
4141
|
+
if (reminderOffsets !== undefined) console.log('reminder-offsets: ' + JSON.stringify(reminderOffsets))
|
|
4142
|
+
}
|
|
4143
|
+
}
|
|
4144
|
+
} else if (sub === 'edit' || sub === 'update') {
|
|
4145
|
+
const id = positional[0]
|
|
4146
|
+
const usage = 'usage: advisers commit edit <id> [--action text] [--due ISO] [--remind-offsets "<list>" | --no-remind]'
|
|
4147
|
+
if (!id) { console.error(usage); process.exitCode = 1 }
|
|
4148
|
+
else {
|
|
4149
|
+
const patch = {}
|
|
4150
|
+
if (typeof flags.action === 'string') patch.action = flags.action
|
|
4151
|
+
if (typeof flags.due === 'string') patch.dueAt = flags.due
|
|
4152
|
+
if (typeof flags.tz === 'string') patch.timezone = flags.tz
|
|
4153
|
+
if (typeof flags.capability === 'string') patch.capability = flags.capability
|
|
4154
|
+
let offsetsError
|
|
4155
|
+
try {
|
|
4156
|
+
if (flags['no-remind'] === true) patch.reminderOffsets = null
|
|
4157
|
+
else {
|
|
4158
|
+
const offsets = await parseReminderOffsetsFlag(flags)
|
|
4159
|
+
if (offsets !== undefined) patch.reminderOffsets = offsets
|
|
4160
|
+
}
|
|
4161
|
+
} catch (error) { offsetsError = error }
|
|
4162
|
+
if (offsetsError) { console.error(offsetsError.message); process.exitCode = 1 }
|
|
4163
|
+
else if (!Object.keys(patch).length) { console.error(usage); process.exitCode = 1 }
|
|
4164
|
+
else {
|
|
4165
|
+
try {
|
|
4166
|
+
const c = ledger.updateCommitment(id, patch)
|
|
4167
|
+
saveLedgerWithAudit(ledger, { actor: 'local', action: 'commit.update', allowed: true, reason: id })
|
|
4168
|
+
console.log(`updated: ${c.id}`)
|
|
4169
|
+
if ('reminderOffsets' in patch) console.log('reminder-offsets: ' + JSON.stringify(c.reminderOffsets ?? []))
|
|
4170
|
+
if (patch.dueAt !== undefined) console.log('due: ' + (c.dueAt ?? '未定'))
|
|
4171
|
+
} catch (error) { console.error(error.message); process.exitCode = 1 }
|
|
4172
|
+
}
|
|
2834
4173
|
}
|
|
2835
4174
|
} else if (sub === 'ls') printCommitments(ledger, flags.json)
|
|
2836
4175
|
else if (sub === 'snooze') {
|
|
@@ -2840,9 +4179,7 @@ if (!command) {
|
|
|
2840
4179
|
if (!c || !Number.isFinite(hours) || hours <= 0) { console.error('usage: advisers commit snooze <id> <hours>'); process.exitCode = 1 }
|
|
2841
4180
|
else {
|
|
2842
4181
|
c.status = 'snoozed'
|
|
2843
|
-
|
|
2844
|
-
saveLedger(ledger)
|
|
2845
|
-
dbStore()?.appendAudit({ actor: 'local', action: 'commit.snooze', allowed: true, reason: id })
|
|
4182
|
+
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
4183
|
console.log(`snoozed: ${id} for ${hours}h`)
|
|
2847
4184
|
}
|
|
2848
4185
|
}
|
|
@@ -2855,12 +4192,11 @@ if (!command) {
|
|
|
2855
4192
|
console.error(`evidence file not found: ${String(evidence).slice(5)}`); process.exitCode = 1
|
|
2856
4193
|
} else {
|
|
2857
4194
|
ledger.completeCommitment(id, [{ sessionId: latestConversationId(), turnId: 'cli', quote: String(evidence) }])
|
|
2858
|
-
|
|
2859
|
-
dbStore()?.appendAudit({ actor: 'local', action: 'commit.done', allowed: true, reason: id })
|
|
4195
|
+
saveLedgerWithAudit(ledger, { actor: 'local', action: 'commit.done', allowed: true, reason: id })
|
|
2860
4196
|
console.log(`done: ${id}`)
|
|
2861
4197
|
}
|
|
2862
4198
|
}
|
|
2863
|
-
} else { console.error('usage: advisers commit add|ls|done'); process.exitCode = 1 }
|
|
4199
|
+
} else { console.error('usage: advisers commit add|edit|ls|done|snooze'); process.exitCode = 1 }
|
|
2864
4200
|
} else if (command === 'diff') {
|
|
2865
4201
|
const result = await diffLatest({ cwd: process.cwd(), backupDir: join(HOME, 'undo') })
|
|
2866
4202
|
console.log(result.ok ? result.diff : `diff failed: ${result.error}`)
|
|
@@ -2907,7 +4243,7 @@ if (!command) {
|
|
|
2907
4243
|
} else if (command === 'pet-brief') {
|
|
2908
4244
|
await petBrief(args)
|
|
2909
4245
|
} else if (command === 'today') {
|
|
2910
|
-
today(loadLedger(), { calendar: args.includes('--calendar'), sources: args.includes('--sources') })
|
|
4246
|
+
await today(loadLedger(), { calendar: args.includes('--calendar'), sources: args.includes('--sources'), json: args.includes('--json') })
|
|
2911
4247
|
} else if (command === 'tick') {
|
|
2912
4248
|
tick(loadLedger(), args.includes('--json'))
|
|
2913
4249
|
} else if (command === 'ui') {
|
|
@@ -2915,7 +4251,7 @@ if (!command) {
|
|
|
2915
4251
|
} else if (command === 'remind') {
|
|
2916
4252
|
await remind(args)
|
|
2917
4253
|
} else if (command === 'calendar') {
|
|
2918
|
-
calendarImport(args.slice(1))
|
|
4254
|
+
await calendarImport(args.slice(1))
|
|
2919
4255
|
} else if (command === 'who') {
|
|
2920
4256
|
const open = loadLedger().openCommitments()
|
|
2921
4257
|
const mine = open.filter((c) => c.debtor === 'user' || c.debtor === 'agent')
|
|
@@ -2930,9 +4266,12 @@ if (!command) {
|
|
|
2930
4266
|
} else if (command === 'memory') {
|
|
2931
4267
|
const ledger = loadLedger()
|
|
2932
4268
|
if (args[0] === 'candidates') {
|
|
2933
|
-
const rows = dbStore()?.listCandidates(args
|
|
2934
|
-
if (
|
|
2935
|
-
|
|
4269
|
+
const rows = dbStore()?.listCandidates(args.includes('--all') ? 'all' : 'pending') ?? []
|
|
4270
|
+
if (args.includes('--json')) console.log(JSON.stringify(rows, null, 2))
|
|
4271
|
+
else {
|
|
4272
|
+
if (!rows.length) console.log('(没有待确认记忆)')
|
|
4273
|
+
for (const c of rows) console.log(`${c.id}\t${c.kind}\t${JSON.stringify(c.payload)}\t${c.status}`)
|
|
4274
|
+
}
|
|
2936
4275
|
} else if (args[0] === 'accept') {
|
|
2937
4276
|
const store = dbStore()
|
|
2938
4277
|
const candidate = store?.getCandidate(args[1])
|
|
@@ -2949,9 +4288,7 @@ if (!command) {
|
|
|
2949
4288
|
if (candidate.kind === 'fact') ledger.remember({ ...candidate.payload, authority: 'user', evidence: candidate.evidence.map(sourceRef) })
|
|
2950
4289
|
else if (candidate.kind === 'preference') ledger.addPreference({ ...candidate.payload, evidence: candidate.evidence.map(sourceRef) })
|
|
2951
4290
|
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 })
|
|
4291
|
+
saveLedgerWithAudit(ledger, { actor: 'local', action: 'memory.accept', allowed: true, reason: candidate.id }, (s) => s.reviewCandidate(candidate.id, 'accepted'))
|
|
2955
4292
|
console.log(`accepted ${candidate.id}`)
|
|
2956
4293
|
} catch (error) { console.error(error.message); process.exitCode = 1 }
|
|
2957
4294
|
}
|
|
@@ -2960,8 +4297,7 @@ if (!command) {
|
|
|
2960
4297
|
const candidate = store?.getCandidate(args[1])
|
|
2961
4298
|
if (!candidate) { console.error('candidate not found'); process.exitCode = 1 }
|
|
2962
4299
|
else {
|
|
2963
|
-
|
|
2964
|
-
store.appendAudit({ actor: 'local', action: 'memory.reject', allowed: true, reason: candidate.id })
|
|
4300
|
+
updateStoreWithAudit((s) => s.reviewCandidate(candidate.id, 'rejected', args.slice(2).join(' ') || undefined), { actor: 'local', action: 'memory.reject', allowed: true, reason: candidate.id })
|
|
2965
4301
|
console.log(`rejected ${candidate.id}`)
|
|
2966
4302
|
}
|
|
2967
4303
|
} else if (args[0] === 'search') {
|
|
@@ -2992,7 +4328,7 @@ if (!command) {
|
|
|
2992
4328
|
} else if (command === 'privacy') {
|
|
2993
4329
|
printPrivacy(args)
|
|
2994
4330
|
} else if (command === 'audit') {
|
|
2995
|
-
printAudit()
|
|
4331
|
+
printAudit(args)
|
|
2996
4332
|
} else if (command === 'purge') {
|
|
2997
4333
|
purgeMatter(args[0], args.includes('--yes'))
|
|
2998
4334
|
} else if (command === 'decay') {
|
|
@@ -3006,8 +4342,7 @@ if (!command) {
|
|
|
3006
4342
|
else {
|
|
3007
4343
|
const ledger = loadLedger()
|
|
3008
4344
|
const result = learnPreference(ledger, statement, statement, { explicit: true })
|
|
3009
|
-
|
|
3010
|
-
saveLedger(ledger)
|
|
4345
|
+
saveLedgerWithAudit(ledger, { actor: 'local', action: 'correct', allowed: true, reason: result.preference.id })
|
|
3011
4346
|
printLearnReceipt(result)
|
|
3012
4347
|
}
|
|
3013
4348
|
} else if (command === 'ls') {
|
|
@@ -3017,18 +4352,18 @@ if (!command) {
|
|
|
3017
4352
|
} else if (command === 'forget') {
|
|
3018
4353
|
forget(args[0])
|
|
3019
4354
|
} else if (command === 'sync') {
|
|
3020
|
-
syncCommand(args)
|
|
4355
|
+
await syncCommand(args)
|
|
3021
4356
|
} else if (command === 'vault') {
|
|
3022
4357
|
const sub = args[0]
|
|
3023
|
-
if (sub === 'seal') vaultSeal(args.slice(1))
|
|
3024
|
-
else if (sub === 'unseal') vaultUnseal(args.slice(1))
|
|
4358
|
+
if (sub === 'seal') await vaultSeal(args.slice(1))
|
|
4359
|
+
else if (sub === 'unseal') await vaultUnseal(args.slice(1))
|
|
3025
4360
|
else if (sub === 'status' || !sub) vaultStatus()
|
|
3026
4361
|
else { console.error('usage: advisers vault seal [--out file] [--remove] | unseal [file] | status'); process.exitCode = 1 }
|
|
3027
4362
|
} else if (command === 'export') {
|
|
3028
4363
|
const { flags } = parseFlags(args)
|
|
3029
|
-
exportLedger(flags.all === true || args.includes('--all'), { encrypted: args.includes('--encrypted'), out: typeof flags.out === 'string' ? flags.out : undefined })
|
|
4364
|
+
await exportLedger(flags.all === true || args.includes('--all'), { encrypted: args.includes('--encrypted'), out: typeof flags.out === 'string' ? flags.out : undefined })
|
|
3030
4365
|
} else if (command === 'import') {
|
|
3031
|
-
importLedger(args.find((a) => !a.startsWith('--')), { replace: args.includes('--replace') })
|
|
4366
|
+
await importLedger(args.find((a) => !a.startsWith('--')), { replace: args.includes('--replace') })
|
|
3032
4367
|
} else if (command === 'backup') {
|
|
3033
4368
|
backup(args[0])
|
|
3034
4369
|
} else if (command === 'brief') {
|
|
@@ -3070,7 +4405,10 @@ if (!command) {
|
|
|
3070
4405
|
if (!file) { console.error('usage: advisers office-read <file>'); process.exitCode = 1 }
|
|
3071
4406
|
else {
|
|
3072
4407
|
if (file.toLowerCase().endsWith('.ofd')) {
|
|
3073
|
-
try {
|
|
4408
|
+
try {
|
|
4409
|
+
const { ofdText } = await loadAttachments()
|
|
4410
|
+
console.log(await ofdText(readFileSync(file)))
|
|
4411
|
+
} catch (error) { console.error(`ofd read failed: ${error.message}`); process.exitCode = 1 }
|
|
3074
4412
|
} else {
|
|
3075
4413
|
let mod
|
|
3076
4414
|
if (process.env.ADVISERS_OFFICE_LOCAL === '1') mod = await import('../../office/dist/index.js')
|
|
@@ -3080,30 +4418,34 @@ if (!command) {
|
|
|
3080
4418
|
}
|
|
3081
4419
|
}
|
|
3082
4420
|
} else if (command === 'verify') {
|
|
3083
|
-
const
|
|
3084
|
-
|
|
4421
|
+
const { flags, positional } = parseFlags(args)
|
|
4422
|
+
const file = positional[0]
|
|
4423
|
+
if (!file) { console.error('usage: advisers verify <file> [--json] [--content]'); process.exitCode = 1 }
|
|
3085
4424
|
else {
|
|
3086
4425
|
const ext = file.split('.').pop()?.toLowerCase()
|
|
3087
4426
|
if (!['docx', 'xlsx', 'pptx'].includes(ext)) { console.error('verify supports docx/xlsx/pptx'); process.exitCode = 1 }
|
|
3088
4427
|
else {
|
|
3089
|
-
|
|
3090
|
-
|
|
3091
|
-
|
|
3092
|
-
|
|
3093
|
-
|
|
3094
|
-
|
|
3095
|
-
|
|
3096
|
-
|
|
3097
|
-
|
|
3098
|
-
|
|
3099
|
-
|
|
4428
|
+
try {
|
|
4429
|
+
const verifyOffice = await loadOfficeOperation('verify', 'verifyOffice')
|
|
4430
|
+
const result = await verifyOffice(readFileSync(file), ext)
|
|
4431
|
+
if (flags.content === true) {
|
|
4432
|
+
const checkOffice = await loadOfficeOperation('check', 'checkOffice')
|
|
4433
|
+
const content = await checkOffice(readFileSync(file), ext)
|
|
4434
|
+
console.log(JSON.stringify({ structure: result, content }, null, 2))
|
|
4435
|
+
if (!content.ok) process.exitCode = 1
|
|
4436
|
+
} else console.log(JSON.stringify(result, null, 2))
|
|
4437
|
+
if (!result.ok) process.exitCode = 1
|
|
4438
|
+
} catch (error) {
|
|
4439
|
+
console.error(`verify failed: ${error.message}`)
|
|
4440
|
+
process.exitCode = 1
|
|
4441
|
+
}
|
|
3100
4442
|
}
|
|
3101
4443
|
}
|
|
3102
4444
|
} else if (command === 'office') {
|
|
3103
4445
|
await office(args[0], args[1], args[2])
|
|
3104
4446
|
process.exit(process.exitCode || 0)
|
|
3105
4447
|
} else if (command === 'routine') {
|
|
3106
|
-
routine(args[0], args[1], args[2])
|
|
4448
|
+
await routine(args[0], args[1], args[2])
|
|
3107
4449
|
} else if (command === 'template') {
|
|
3108
4450
|
await template(args[0], args[1], args[2])
|
|
3109
4451
|
process.exit(process.exitCode || 0)
|
|
@@ -3112,7 +4454,9 @@ if (!command) {
|
|
|
3112
4454
|
} else if (command === 'bridge') {
|
|
3113
4455
|
await bridge(args)
|
|
3114
4456
|
} else if (command === 'soul') {
|
|
3115
|
-
soul(args[0], args[1])
|
|
4457
|
+
await soul(args[0], args[1])
|
|
4458
|
+
} else if (command === 'tos') {
|
|
4459
|
+
await tosCommand(args)
|
|
3116
4460
|
} else {
|
|
3117
4461
|
console.error(`unknown command: ${command}`)
|
|
3118
4462
|
help()
|