advisers 0.1.0-preview.4 → 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 +131 -21
- package/NOTICE +34 -0
- package/README-zh.md +40 -9
- package/README.md +53 -10
- package/THIRD-PARTY-NOTICES.md +277 -0
- package/bin/advisers.js +4230 -122
- package/index.js +1 -1
- package/lib/agent.js +414 -0
- package/lib/attachments.js +283 -0
- package/lib/capture.js +168 -0
- package/lib/context-window.js +123 -0
- package/lib/digest.js +27 -0
- package/lib/doc-review.js +30 -0
- package/lib/egress.js +27 -0
- package/lib/evidence.js +1995 -0
- package/lib/ical.js +542 -0
- package/lib/imap.js +181 -0
- package/lib/importers.js +1001 -0
- package/lib/learning.js +46 -0
- package/lib/mcp-server.js +869 -0
- package/lib/model.js +307 -0
- package/lib/notify.js +189 -0
- package/lib/nudge.js +10 -0
- package/lib/ocr.js +47 -0
- package/lib/pdf.js +105 -0
- package/lib/pet-brief-store.js +51 -0
- package/lib/pet-brief.js +644 -0
- package/lib/receipt-verify.js +624 -0
- package/lib/relative-date.js +393 -0
- package/lib/remind.js +690 -0
- package/lib/research.js +193 -0
- package/lib/review.js +88 -0
- package/lib/routine.js +22 -0
- 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 +1022 -0
- package/lib/sync.js +129 -0
- package/lib/timestamp.js +45 -0
- 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/lib/ui.js +49 -0
- package/lib/undo.js +83 -0
- package/lib/vault.js +51 -0
- package/package.json +26 -4
package/bin/advisers.js
CHANGED
|
@@ -1,7 +1,78 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
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'
|
|
4
|
+
import { homedir, hostname } from 'node:os'
|
|
5
|
+
import { createHash, randomBytes, randomUUID } from 'node:crypto'
|
|
6
|
+
import { basename, dirname, extname, join } from 'node:path'
|
|
7
|
+
let SqliteStore
|
|
8
|
+
try {
|
|
9
|
+
({ SqliteStore } = await import('../lib/sqlite.js'))
|
|
10
|
+
} catch (error) {
|
|
11
|
+
if (String(error?.message || error).includes('node:sqlite')) {
|
|
12
|
+
console.error(`Advisers needs Node >= 22.13 (node:sqlite). You have ${process.version}. Install Node 24 or use nvm-windows.`)
|
|
13
|
+
process.exit(1)
|
|
14
|
+
}
|
|
15
|
+
throw error
|
|
16
|
+
}
|
|
17
|
+
import { runAgent } from '../lib/agent.js'
|
|
18
|
+
import { chatCompletion } from '../lib/model.js'
|
|
19
|
+
import { applyPreferenceDecay, buildRoutineCandidate, correctionStatement } from '../lib/learning.js'
|
|
20
|
+
import { checkRoutine } from '../lib/routine.js'
|
|
21
|
+
import { backupBeforeWrite, diffLatest, listBackups, undoLatest } from '../lib/undo.js'
|
|
22
|
+
import { lintReview, materializeReview, reviewRun } from '../lib/review.js'
|
|
23
|
+
import { classifyNudgeOutcome } from '../lib/nudge.js'
|
|
24
|
+
import { buildDigest } from '../lib/digest.js'
|
|
25
|
+
import { captureCandidates } from '../lib/capture.js'
|
|
26
|
+
import { egressDeniedReason } from '../lib/egress.js'
|
|
27
|
+
import { research as runResearch } from '../lib/research.js'
|
|
28
|
+
import { reviewDocument } from '../lib/doc-review.js'
|
|
29
|
+
import { buildHistory, buildOpening, buildPins, continuityProbes, ensurePins, fitHistory, shouldSummarize, summarizeTurns } from '../lib/context-window.js'
|
|
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'
|
|
43
|
+
import { fetchImapMessages } from '../lib/imap.js'
|
|
44
|
+
import { createReadOnlyServer } from '../lib/ui.js'
|
|
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'))
|
|
5
76
|
|
|
6
77
|
let core
|
|
7
78
|
if (process.env.ADVISERS_CORE_LOCAL === '1') {
|
|
@@ -15,24 +86,180 @@ if (process.env.ADVISERS_CORE_LOCAL === '1') {
|
|
|
15
86
|
}
|
|
16
87
|
}
|
|
17
88
|
const { createAdvisers, Ledger, systemPorts } = core
|
|
89
|
+
let StrictPolicyPack
|
|
90
|
+
let policyImportError
|
|
91
|
+
try { ({ StrictPolicyPack } = await import('advisers-policy-strict')) } catch { try { ({ StrictPolicyPack } = await import('../../policy-strict/dist/index.js')) } catch (error) { policyImportError = error } }
|
|
18
92
|
|
|
19
93
|
const HOME = process.env.ADVISERS_HOME || join(homedir(), '.advisers')
|
|
20
94
|
const STATE = join(HOME, 'state.json')
|
|
21
95
|
const SOUL = join(HOME, 'soul.md')
|
|
22
96
|
const SOUL_META = join(HOME, 'soul.meta.json')
|
|
97
|
+
const DB = join(HOME, 'state.db')
|
|
98
|
+
let mode = process.env.ADVISERS_STORE === 'json' ? 'json' : 'sqlite'
|
|
99
|
+
let activeStore
|
|
23
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
|
+
|
|
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
|
+
}
|
|
124
|
+
function ensureAuditKey() {
|
|
125
|
+
if (process.env.ADVISERS_AUDIT_KEY) return
|
|
126
|
+
try {
|
|
127
|
+
if (existsSync(AUDIT_KEY_FILE)) {
|
|
128
|
+
process.env.ADVISERS_AUDIT_KEY = readAuditKey()
|
|
129
|
+
return
|
|
130
|
+
}
|
|
131
|
+
const key = randomBytes(32).toString('hex')
|
|
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
|
+
}
|
|
148
|
+
}
|
|
24
149
|
function ensureHome() {
|
|
25
|
-
mkdirSync(HOME, { recursive: true })
|
|
150
|
+
mkdirSync(HOME, { recursive: true, mode: 0o700 })
|
|
151
|
+
try { chmodSync(HOME, 0o700) } catch {}
|
|
152
|
+
ensureAuditKey()
|
|
153
|
+
}
|
|
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
|
+
|
|
168
|
+
function loadJson() {
|
|
169
|
+
if (!existsSync(STATE)) return new Ledger(LOCAL_PORTS)
|
|
170
|
+
return Ledger.fromJSON(JSON.parse(readFileSync(STATE, 'utf8')), LOCAL_PORTS)
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
function saveJson(ledger) {
|
|
174
|
+
ensureHome()
|
|
175
|
+
writeFileSync(STATE, JSON.stringify(ledger.toJSON(), null, 2) + '\n')
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
function openStore({ checkIntegrity = false } = {}) {
|
|
179
|
+
if (!activeStore) {
|
|
180
|
+
ensureHome()
|
|
181
|
+
activeStore = new SqliteStore(DB, { checkIntegrity })
|
|
182
|
+
try { chmodSync(DB, 0o600) } catch {}
|
|
183
|
+
} else if (checkIntegrity) {
|
|
184
|
+
activeStore.assertIntegrity()
|
|
185
|
+
}
|
|
186
|
+
return activeStore
|
|
26
187
|
}
|
|
27
188
|
|
|
28
189
|
function loadLedger() {
|
|
29
|
-
|
|
30
|
-
|
|
190
|
+
ensureHome()
|
|
191
|
+
if (mode === 'json') return loadJson()
|
|
192
|
+
try {
|
|
193
|
+
if (!existsSync(DB) && existsSync(STATE)) {
|
|
194
|
+
const ledger = loadJson()
|
|
195
|
+
openStore().save(ledger.toJSON())
|
|
196
|
+
return ledger
|
|
197
|
+
}
|
|
198
|
+
return Ledger.fromJSON(openStore().load(), LOCAL_PORTS)
|
|
199
|
+
} catch (error) {
|
|
200
|
+
console.error(`sqlite unavailable: ${error.message}`)
|
|
201
|
+
console.error('Run `advisers doctor`; refusing to silently switch to JSON (would split the ledger).')
|
|
202
|
+
process.exit(1)
|
|
203
|
+
}
|
|
204
|
+
}
|
|
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)
|
|
31
214
|
}
|
|
32
215
|
|
|
33
216
|
function saveLedger(ledger) {
|
|
34
217
|
ensureHome()
|
|
35
|
-
|
|
218
|
+
if (mode === 'json') return saveJson(ledger)
|
|
219
|
+
try {
|
|
220
|
+
return openStore().save(ledger.toJSON())
|
|
221
|
+
} catch (error) {
|
|
222
|
+
exitStoreWriteFailure(error)
|
|
223
|
+
}
|
|
224
|
+
}
|
|
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)
|
|
36
263
|
}
|
|
37
264
|
|
|
38
265
|
function loadSoul() {
|
|
@@ -50,33 +277,261 @@ function loadSoul() {
|
|
|
50
277
|
|
|
51
278
|
function saveSoul(doc) {
|
|
52
279
|
ensureHome()
|
|
53
|
-
writeFileSync(SOUL, doc.content)
|
|
54
|
-
writeFileSync(SOUL_META, JSON.stringify({ version: doc.version, updatedAt: doc.updatedAt }, null, 2) + '\n')
|
|
280
|
+
writeFileSync(SOUL, doc.content, { mode: 0o600 })
|
|
281
|
+
writeFileSync(SOUL_META, JSON.stringify({ version: doc.version, updatedAt: doc.updatedAt }, null, 2) + '\n', { mode: 0o600 })
|
|
282
|
+
}
|
|
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
|
|
55
318
|
}
|
|
56
319
|
|
|
57
320
|
const soulStore = { load: loadSoul, save: saveSoul }
|
|
58
321
|
|
|
59
322
|
function runtimeFor(ledger) {
|
|
60
323
|
const ports = { ...systemPorts(), soul: soulStore }
|
|
61
|
-
return createAdvisers({ ledger, ports })
|
|
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' }) } })
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
async function backupCliFile(path) {
|
|
328
|
+
try { await backupBeforeWrite(path, { cwd: process.cwd(), backupDir: join(HOME, 'undo') }) } catch {}
|
|
62
329
|
}
|
|
63
330
|
|
|
64
331
|
function now() {
|
|
65
332
|
return new Date().toISOString()
|
|
66
333
|
}
|
|
67
334
|
|
|
68
|
-
|
|
335
|
+
function dbStore() {
|
|
336
|
+
return mode === 'sqlite' ? openStore() : undefined
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
function latestConversationId() {
|
|
340
|
+
try {
|
|
341
|
+
const store = dbStore()
|
|
342
|
+
return store?.listSessions(1)[0]?.conversationId ?? 'local'
|
|
343
|
+
} catch {
|
|
344
|
+
return 'local'
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
function printHistory() {
|
|
349
|
+
const store = dbStore()
|
|
350
|
+
const rows = store?.listSessions(12) ?? []
|
|
351
|
+
if (!rows.length) {
|
|
352
|
+
console.log('no saved sessions yet')
|
|
353
|
+
return
|
|
354
|
+
}
|
|
355
|
+
rows.forEach((row, index) => {
|
|
356
|
+
console.log(`${index + 1}. ${row.title} [${row.conversationId}] ${row.updatedAt}`)
|
|
357
|
+
})
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
function printReceipt() {
|
|
361
|
+
const store = dbStore()
|
|
362
|
+
if (!store) { console.log('receipt requires SQLite store'); return }
|
|
363
|
+
const delivery = store.listDeliveries(1)[0]
|
|
364
|
+
if (!delivery) { console.log('还没有交付记录;先运行 `advisers office` / `advisers template`。'); return }
|
|
365
|
+
const ledger = loadLedger()
|
|
366
|
+
const open = ledger.openCommitments(delivery.matterId)
|
|
367
|
+
console.log(`回执 ${delivery.id}`)
|
|
368
|
+
console.log(`时间:${delivery.createdAt}`)
|
|
369
|
+
console.log(`事项:${delivery.title || '(untitled)'}`)
|
|
370
|
+
console.log(`产物:${delivery.files.join(', ')}`)
|
|
371
|
+
console.log(`工具:${delivery.tool || '-'}`)
|
|
372
|
+
console.log(`校验:${delivery.validation || '未记录'}`)
|
|
373
|
+
console.log(`未完成承诺:${open.length}`)
|
|
374
|
+
for (const c of open.slice(0, 3)) console.log(` ${c.id} ${c.action}${c.dueAt ? ` · ${c.dueAt.slice(0, 10)}` : ''}`)
|
|
375
|
+
const usage = store.sumModelUsage()
|
|
376
|
+
if (usage.calls) console.log(`模型:${usage.calls} calls · ${usage.total_tokens} tokens`)
|
|
377
|
+
const research = store.listResearch?.(1)?.[0]
|
|
378
|
+
if (research) {
|
|
379
|
+
console.log(`研究:${research.query}`)
|
|
380
|
+
for (const source of research.sources.slice(0, 3)) console.log(` web: ${source.title || '(untitled)'} ${source.url}`)
|
|
381
|
+
}
|
|
382
|
+
console.log('提示:结构校验通过不等于内容正确;对外发送仍需 permit。')
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
function printDeliveries() {
|
|
386
|
+
const store = dbStore()
|
|
387
|
+
const rows = store?.listDeliveries(12) ?? []
|
|
388
|
+
if (!rows.length) {
|
|
389
|
+
console.log('no deliveries yet')
|
|
390
|
+
return
|
|
391
|
+
}
|
|
392
|
+
let matters = []
|
|
393
|
+
try { matters = loadLedger().listMatters() } catch {}
|
|
394
|
+
const title = new Map(matters.map((m) => [m.id, m.title]))
|
|
395
|
+
for (const row of rows) {
|
|
396
|
+
console.log(`${row.createdAt.slice(0, 19)} ${row.title ?? title.get(row.matterId) ?? row.matterId} [${row.tool ?? 'tool'}] ${row.validation ?? ''}`)
|
|
397
|
+
for (const file of row.files) {
|
|
398
|
+
let size = 0
|
|
399
|
+
try { size = statSync(file).size } catch {}
|
|
400
|
+
console.log(` ${file} ${size} B`)
|
|
401
|
+
}
|
|
402
|
+
}
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
|
|
406
|
+
function shouldPlan(text, brief) {
|
|
407
|
+
if (process.env.ADVISERS_YES === '1') return false
|
|
408
|
+
if (brief.action === 'ask') return false
|
|
409
|
+
return text.length > 80 || /(先|然后|接着|最后|同时|并且)/.test(text)
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
function planLines(brief) {
|
|
413
|
+
return [
|
|
414
|
+
`1. 确认交付:${brief.goal}`,
|
|
415
|
+
`2. 生成 ${brief.deliverable},保存到工作区(默认 out/)`,
|
|
416
|
+
'3. 校验产物,回执文件路径',
|
|
417
|
+
]
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
async function askYesNo(rl, prompt, defaultYes = true) {
|
|
421
|
+
try {
|
|
422
|
+
const answer = (await rl.question(prompt)).trim()
|
|
423
|
+
if (!answer) return defaultYes
|
|
424
|
+
return /^y(es)?$/i.test(answer)
|
|
425
|
+
} catch {
|
|
426
|
+
return false
|
|
427
|
+
}
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
const VERSION = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version
|
|
431
|
+
function friendlyError(error) {
|
|
432
|
+
const message = error instanceof Error ? error.message : String(error)
|
|
433
|
+
if (/ENOENT/.test(message)) return 'file not found; check the path and run `advisers doctor`'
|
|
434
|
+
if (/Unexpected token|JSON/.test(message)) return 'invalid JSON; use UTF-8 without BOM and see examples/'
|
|
435
|
+
if (/model (HTTP|timeout)|fetch failed|ECONN/.test(message)) return 'model request failed; check ADVISERS_API_KEY / network and run `advisers doctor`'
|
|
436
|
+
if (/database is locked/.test(message)) return 'database is busy; close other advisers processes and retry'
|
|
437
|
+
return message
|
|
438
|
+
}
|
|
439
|
+
process.on('uncaughtException', (error) => { console.error(`advisers: ${friendlyError(error)}`); process.exit(1) })
|
|
440
|
+
process.on('unhandledRejection', (error) => { console.error(`advisers: ${friendlyError(error)}`); process.exit(1) })
|
|
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
|
|
69
454
|
|
|
70
455
|
function help() {
|
|
71
456
|
console.log(`advisers — a staff of AI advisers
|
|
72
457
|
|
|
73
458
|
Usage:
|
|
74
|
-
advisers
|
|
459
|
+
advisers start the local conversation (TTY)
|
|
460
|
+
advisers chat [--file <path>] [text]
|
|
461
|
+
one-shot task, or start the local conversation
|
|
462
|
+
advisers init initialize home + soul
|
|
463
|
+
advisers doctor check Node/SQLite/Office/policy/model
|
|
464
|
+
advisers status home/store/model/counts
|
|
465
|
+
advisers history recent conversations
|
|
466
|
+
advisers search <text> full-text search old turns
|
|
467
|
+
advisers compact ls|rollback summary versions
|
|
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)
|
|
474
|
+
advisers calendar import --ics <file> local .ics read-only import
|
|
475
|
+
advisers risks up to 3 deterministic obligation risks
|
|
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
|
|
478
|
+
advisers tick due commitments in the next 7 days
|
|
479
|
+
advisers week last 7 days
|
|
480
|
+
advisers digest day|week short digest
|
|
481
|
+
advisers diff show the last changed file
|
|
482
|
+
advisers undo [--list] restore the last file write
|
|
483
|
+
advisers learn ls recent task trajectories
|
|
484
|
+
advisers learn review <id> LLM routine review (needs API key)
|
|
485
|
+
advisers memory what I remember
|
|
486
|
+
advisers memory search <q> search facts/preferences
|
|
487
|
+
advisers memory candidates [--json] [--all] pending memory candidates
|
|
488
|
+
advisers memory accept|reject <id>
|
|
489
|
+
advisers prefs [--all] | correct <text>
|
|
490
|
+
advisers nudge list|done|ignore <id> nudge outcomes
|
|
491
|
+
advisers decay apply 30-day preference decay
|
|
492
|
+
advisers audit verify the local audit hash chain
|
|
493
|
+
advisers purge <matter> [--yes] privacy delete a matter
|
|
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)
|
|
498
|
+
advisers deliveries recent generated files
|
|
499
|
+
advisers receipt one-screen delivery receipt
|
|
75
500
|
advisers ls list matters
|
|
501
|
+
advisers privacy [--json] [--prove] show/verify local data & egress facts
|
|
76
502
|
advisers why <pref-id> explain a preference
|
|
77
503
|
advisers forget <pref-id> forget a preference (tombstone)
|
|
78
|
-
advisers export
|
|
79
|
-
advisers
|
|
504
|
+
advisers export [--all] [--encrypted] [--out file] export ledger (AES-256-GCM with passphrase)
|
|
505
|
+
advisers import <file> [--replace] import an export (encrypted or plain)
|
|
506
|
+
advisers vault seal [--out f] [--remove] | unseal [f] | status AES-256-GCM database vault
|
|
507
|
+
advisers sync push|pull|status --dir <dir> file-based E2EE snapshot sync (user-provided dir)
|
|
508
|
+
advisers backup <path.db> checkpoint and copy the SQLite database
|
|
509
|
+
advisers brief [--deep] <text> print the IntentBrief; --deep adds model refinement
|
|
510
|
+
advisers --version print the CLI version
|
|
511
|
+
advisers who who I owe / who owes me
|
|
512
|
+
advisers review <file> --request "..." model content review (no edits)
|
|
513
|
+
advisers research --web|--url <url> [--deep] <query>
|
|
514
|
+
server-side web search/read URL with citations (explicit egress)
|
|
515
|
+
advisers capture [--file f] [--source s] [--date ISO] [--matter id] [--json] <text>
|
|
516
|
+
从中文工作内容抽取候选承诺(不自动入账)
|
|
517
|
+
advisers capture --from-mail <file|dir> [--limit n] .eml/.mbox 只读导入→候选
|
|
518
|
+
advisers capture --from-transcript <file> 转写稿导入→候选(不录音/不入会)
|
|
519
|
+
advisers capture --from-imap 只读 IMAP 导入(EXAMINE/FETCH;env 凭据)
|
|
520
|
+
advisers ui [--port n] 本地只读视图(127.0.0.1,GET only)
|
|
521
|
+
advisers mcp --stdio MCP server(7 工具 + 4 resources;写入口仅 pending 候选/回执校验)
|
|
522
|
+
advisers evidence show <id> [--json] 承诺/事实/偏好→原文来源
|
|
523
|
+
advisers deliver [--commit id] [--type confirmation|weekly|statement|ledger] [--format docx|xlsx|pdf] [--out f] 交付物
|
|
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;不读账本、不联网)
|
|
528
|
+
advisers policy check <text> policy/crisis check
|
|
529
|
+
advisers office-read <file> read DOCX/XLSX/PPTX/OFD text
|
|
530
|
+
advisers ocr <image> [--out text] local OCR adapter (ADVISERS_OCR_CMD; no cloud)
|
|
531
|
+
advisers timestamp <file> [--out proof] local timestamp/signing adapter
|
|
532
|
+
advisers tui [--once] read-only terminal dashboard
|
|
533
|
+
advisers office-edit <file> <ops.json> [out] surgical Office edit
|
|
534
|
+
advisers verify <file> [--json] [--content] structural + deterministic content checks
|
|
80
535
|
advisers office <kind> <spec.json> <out>
|
|
81
536
|
build docx/xlsx/pptx/xmind/mermaid/drawio
|
|
82
537
|
advisers routine ls list routines
|
|
@@ -85,153 +540,3114 @@ Usage:
|
|
|
85
540
|
advisers routine approve <id>
|
|
86
541
|
activate a routine (human action)
|
|
87
542
|
advisers routine archive <id>
|
|
543
|
+
advisers routine patches list routine patches
|
|
544
|
+
advisers routine patch <id> <changes.json>
|
|
545
|
+
advisers routine diff <patch-id>
|
|
546
|
+
advisers routine apply <patch-id>
|
|
547
|
+
advisers routine reject <patch-id>
|
|
548
|
+
advisers routine revert <patch-id> restore the pre-apply values
|
|
549
|
+
advisers routine check <id> run file/manual verification
|
|
550
|
+
advisers routine curate [--apply] mark stale/deprecated routines
|
|
551
|
+
advisers routine restore <id> restore an archived routine to draft
|
|
552
|
+
advisers template <weekly|budget|presentation|flow|mindmap|minutes|notice> <data.json> <out>
|
|
553
|
+
build a template into docx/xlsx/pptx/mmd/drawio/xmind
|
|
554
|
+
advisers link ls list matter links
|
|
555
|
+
advisers link add <from> <to> <type>
|
|
556
|
+
advisers link confirm <id>
|
|
557
|
+
advisers link suggest <id> suggest similar matters
|
|
558
|
+
advisers link updates list cross-matter proposals
|
|
559
|
+
advisers link propose-update <source> <target> <change>
|
|
560
|
+
advisers link apply <id> write to target only, then mark applied
|
|
561
|
+
advisers link diff <id> show the pending/applied change
|
|
562
|
+
advisers link reject <id>
|
|
563
|
+
advisers link rollback <id> delete the fact written by an applied update
|
|
564
|
+
advisers bridge --dir <path> [--name advisers]
|
|
565
|
+
expose Advisers to the Hermes messaging gateway
|
|
88
566
|
advisers soul show print soul.md
|
|
89
567
|
advisers soul set <file> set soul.md from a file (human action)
|
|
90
568
|
advisers soul init write a minimal starter soul.md
|
|
569
|
+
advisers tos show|status [--json]|accept|revoke 使用条款:全文/状态/接受/撤回
|
|
91
570
|
advisers help
|
|
92
571
|
|
|
93
|
-
Environment:
|
|
94
|
-
ADVISERS_HOME
|
|
95
|
-
|
|
572
|
+
Environment:
|
|
573
|
+
ADVISERS_HOME default ~/.advisers
|
|
574
|
+
ADVISERS_STORE sqlite (default) or json
|
|
575
|
+
ADVISERS_API_KEY / ADVISERS_BASE_URL / ADVISERS_MODEL
|
|
576
|
+
enable the model call in chat
|
|
577
|
+
ADVISERS_YES=1 skip the plan confirmation
|
|
578
|
+
ADVISERS_FORCE=1 overwrite existing files without asking
|
|
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.
|
|
589
|
+
`)
|
|
590
|
+
}
|
|
591
|
+
|
|
592
|
+
let cliSeq = 0
|
|
593
|
+
let lastRun
|
|
594
|
+
|
|
595
|
+
function modelLabel() {
|
|
596
|
+
if (!process.env.ADVISERS_API_KEY) return 'not configured (local mode)'
|
|
597
|
+
if (process.env.ADVISERS_NO_MODEL === '1') return 'disabled (ADVISERS_NO_MODEL=1)'
|
|
598
|
+
return `${process.env.ADVISERS_MODEL || 'deepseek-flash'} @ ${process.env.ADVISERS_BASE_URL || 'https://api.deepseek.com'}`
|
|
599
|
+
}
|
|
600
|
+
|
|
601
|
+
function learnPreference(ledger, statement, quote, { explicit = false } = {}) {
|
|
602
|
+
const existing = ledger.listPreferences({ includeCandidates: true }).find((p) => p.statement === statement)
|
|
603
|
+
if (existing) {
|
|
604
|
+
existing.confidence = Math.min(1, existing.confidence + 0.2)
|
|
605
|
+
existing.lastConfirmed = now()
|
|
606
|
+
if (existing.confidence >= 0.7) existing.status = 'confirmed'
|
|
607
|
+
return { preference: existing, promoted: existing.status === 'confirmed' }
|
|
608
|
+
}
|
|
609
|
+
const pref = ledger.addPreference({
|
|
610
|
+
kind: 'preference',
|
|
611
|
+
statement,
|
|
612
|
+
source: { type: explicit ? 'user_explicit' : 'inferred', quote },
|
|
613
|
+
confidence: explicit ? 0.8 : 0.5,
|
|
614
|
+
status: explicit ? 'confirmed' : 'candidate',
|
|
615
|
+
})
|
|
616
|
+
return { preference: pref, promoted: false }
|
|
617
|
+
}
|
|
618
|
+
|
|
619
|
+
function purgeMatter(id, confirmed) {
|
|
620
|
+
if (!id) { console.error('usage: advisers purge <matter-id> [--yes]'); process.exitCode = 1; return }
|
|
621
|
+
const ledger = loadLedger()
|
|
622
|
+
const matter = ledger.getMatter(id)
|
|
623
|
+
if (!matter) { console.error(`unknown matter: ${id}`); process.exitCode = 1; return }
|
|
624
|
+
const facts = ledger.listFacts(id).length
|
|
625
|
+
const links = ledger.listLinks(id).length
|
|
626
|
+
const updates = ledger.listUpdates().filter((u) => u.sourceMatter === id || u.targetMatter === id).length
|
|
627
|
+
const commitments = ledger.openCommitments(id).length
|
|
628
|
+
console.log(`matter ${id}: ${matter.title}`)
|
|
629
|
+
console.log(`facts=${facts} links=${links} updates=${updates} open_commitments=${commitments}`)
|
|
630
|
+
if (!confirmed) {
|
|
631
|
+
console.log('dry-run only; re-run with --yes to purge')
|
|
632
|
+
return
|
|
633
|
+
}
|
|
634
|
+
const counts = ledger.purgeMatter(id)
|
|
635
|
+
const sqlite = dbStore()?.purgeMatterData(id)
|
|
636
|
+
saveLedgerWithAudit(ledger, { actor: 'local', action: 'matter.purge', allowed: true, reason: `${id} ${JSON.stringify(counts)}` })
|
|
637
|
+
console.log(`purged: ${JSON.stringify(counts)} sqlite=${JSON.stringify(sqlite ?? {})}`)
|
|
638
|
+
}
|
|
639
|
+
|
|
640
|
+
function parseFlags(args) {
|
|
641
|
+
const flags = {}
|
|
642
|
+
const positional = []
|
|
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'])
|
|
644
|
+
for (let i = 0; i < args.length; i++) {
|
|
645
|
+
if (args[i].startsWith('--')) {
|
|
646
|
+
const key = args[i].slice(2)
|
|
647
|
+
if (booleanFlags.has(key)) flags[key] = true
|
|
648
|
+
else flags[key] = args[i + 1] && !args[i + 1].startsWith('--') ? args[++i] : true
|
|
649
|
+
} else positional.push(args[i])
|
|
650
|
+
}
|
|
651
|
+
return { flags, positional }
|
|
652
|
+
}
|
|
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
|
+
|
|
668
|
+
function recordManualDelivery(files, tool, title, validation) {
|
|
669
|
+
try {
|
|
670
|
+
const store = dbStore()
|
|
671
|
+
if (!store) return
|
|
672
|
+
const ledger = loadLedger()
|
|
673
|
+
store.addDelivery({
|
|
674
|
+
matterId: activeMatterId(ledger),
|
|
675
|
+
conversationId: latestConversationId(),
|
|
676
|
+
files,
|
|
677
|
+
tool,
|
|
678
|
+
title,
|
|
679
|
+
validation: typeof validation === 'string' ? validation : JSON.stringify(validation),
|
|
680
|
+
})
|
|
681
|
+
} catch {}
|
|
682
|
+
}
|
|
683
|
+
|
|
684
|
+
function activeMatterId(ledger, explicit) {
|
|
685
|
+
if (explicit) return explicit
|
|
686
|
+
try {
|
|
687
|
+
const latest = dbStore()?.listSessions(1)[0]
|
|
688
|
+
if (latest) return latest.matterId
|
|
689
|
+
} catch {}
|
|
690
|
+
return ledger.listMatters()[0]?.id ?? ledger.addMatter({ title: '默认事项' }).id
|
|
691
|
+
}
|
|
692
|
+
|
|
693
|
+
function printCommitments(ledger, asJson = false) {
|
|
694
|
+
const rows = ledger.listCommitments()
|
|
695
|
+
if (asJson) { console.log(JSON.stringify(rows, null, 2)); return }
|
|
696
|
+
if (!rows.length) { console.log('没有承诺'); return }
|
|
697
|
+
for (const c of rows) console.log(`${c.id}\t${c.status}\t${c.dueAt ?? '无截止'}\t${c.action}`)
|
|
698
|
+
}
|
|
699
|
+
|
|
700
|
+
function printMemory(ledger) {
|
|
701
|
+
const prefs = ledger.listPreferences({ includeCandidates: true })
|
|
702
|
+
const commitments = ledger.listCommitments()
|
|
703
|
+
const routines = ledger.listRoutines()
|
|
704
|
+
console.log('记忆 · 我这边存了什么')
|
|
705
|
+
console.log(`关于你(${prefs.length})`)
|
|
706
|
+
for (const p of prefs.slice(0, 6)) console.log(` ${p.id} ${p.statement} [${p.status}/${p.priority}]`)
|
|
707
|
+
console.log(`承诺(${commitments.filter((c) => c.status === 'open').length} 未完成 / ${commitments.length} 总数)`)
|
|
708
|
+
for (const c of commitments.slice(0, 6)) console.log(` ${c.id} ${c.status} ${c.action}${c.dueAt ? ` ${c.dueAt}` : ''}`)
|
|
709
|
+
console.log(`流程(${routines.filter((r) => r.status === 'active').length} 生效 / ${routines.length} 总数)`)
|
|
710
|
+
for (const r of routines.slice(0, 6)) console.log(` ${r.id} ${r.status} ${r.name}`)
|
|
711
|
+
console.log('输入 /why <pref-id> 看依据;/forget <pref-id> 删除;/audit 看审计。')
|
|
712
|
+
}
|
|
713
|
+
|
|
714
|
+
function printWeek(ledger) {
|
|
715
|
+
const now = Date.now()
|
|
716
|
+
const weekAgo = now - 7 * 86400_000
|
|
717
|
+
const commitments = ledger.listCommitments()
|
|
718
|
+
const due = commitments.filter((c) => c.dueAt && (Date.parse(c.dueAt) >= weekAgo || Date.parse(c.dueAt) < now))
|
|
719
|
+
const done = due.filter((c) => c.status === 'done')
|
|
720
|
+
const open = commitments.filter((c) => c.status === 'open')
|
|
721
|
+
const overdue = open.filter((c) => c.dueAt && Date.parse(c.dueAt) < now)
|
|
722
|
+
let deliveries = []
|
|
723
|
+
try { deliveries = dbStore()?.listDeliveries(100) ?? [] } catch {}
|
|
724
|
+
const weekDeliveries = deliveries.filter((d) => Date.parse(d.createdAt) >= weekAgo)
|
|
725
|
+
console.log(`本周(${new Date(weekAgo).toISOString().slice(0, 10)} – ${new Date(now).toISOString().slice(0, 10)})`)
|
|
726
|
+
console.log(`承诺:到期 ${due.length} 件,完成 ${done.length} 件,未完成 ${open.length} 件,逾期 ${overdue.length} 件。`)
|
|
727
|
+
for (const c of due.slice(0, 5)) console.log(` ${c.status === 'done' ? '✓' : '○'} ${c.action}${c.dueAt ? `(${c.dueAt.slice(0, 10)})` : ''}`)
|
|
728
|
+
console.log(`交付:${weekDeliveries.length} 个文件。`)
|
|
729
|
+
const next = [...open].filter((c) => c.dueAt).sort((a, b) => Date.parse(a.dueAt) - Date.parse(b.dueAt))[0]
|
|
730
|
+
console.log('下周一件:' + (next?.action ?? open[0]?.action ?? '先定一个承诺或交付。'))
|
|
731
|
+
}
|
|
732
|
+
|
|
733
|
+
function risks(ledger) {
|
|
734
|
+
const open = ledger.openCommitments()
|
|
735
|
+
const out = []
|
|
736
|
+
const byDay = new Map()
|
|
737
|
+
for (const c of open) {
|
|
738
|
+
if (!c.dueAt) continue
|
|
739
|
+
const day = c.dueAt.slice(0, 10)
|
|
740
|
+
byDay.set(day, [...(byDay.get(day) ?? []), c])
|
|
741
|
+
}
|
|
742
|
+
for (const [day, list] of byDay) if (list.length >= 2) out.push(`${day} 有 ${list.length} 个截止:${list.map((c) => c.action).join('、')}`)
|
|
743
|
+
for (const c of open.filter((c) => !c.dueAt)) out.push(`${c.action} 没有截止时间(${c.creditor})`)
|
|
744
|
+
for (const c of open.filter((c) => c.creditor === 'someone' || !c.creditor)) out.push(`${c.action} 没有明确对象`)
|
|
745
|
+
for (const c of open.filter((c) => c.debtor === 'third' || c.debtor.startsWith('third:'))) out.push(`等 ${c.debtor} 回复:${c.action}`)
|
|
746
|
+
if (!out.length) { console.log('目前没有明显的义务风险。'); return }
|
|
747
|
+
for (const line of out.slice(0, 3)) console.log(`- ${line}`)
|
|
748
|
+
}
|
|
749
|
+
|
|
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()
|
|
758
|
+
const rows = []
|
|
759
|
+
for (const c of ledger.listCommitments()) {
|
|
760
|
+
for (const e of c.evidence ?? []) {
|
|
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
|
+
})
|
|
772
|
+
}
|
|
773
|
+
}
|
|
774
|
+
return rows
|
|
775
|
+
}
|
|
776
|
+
|
|
777
|
+
async function printSources(ledger) {
|
|
778
|
+
const rows = await collectSourceRows(ledger)
|
|
779
|
+
if (!rows.length) { console.log('来源:还没有可回溯的承诺来源;先 capture/导入并 accept。'); return }
|
|
780
|
+
console.log('来源(承诺 → 本地入口):')
|
|
781
|
+
for (const r of rows.slice(0, 20)) console.log(` ${r.commitmentId} ${r.action} ← ${r.label} (${r.ref ?? '-'}) 「${r.quote.slice(0, 80)}」`)
|
|
782
|
+
}
|
|
783
|
+
|
|
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
|
+
}
|
|
829
|
+
console.log(`今天:${todayDue.length} · 逾期:${overdue.length} · 未来 7 天:${week.length} · 等别人:${waiting.length} · 无截止:${noDue.length}`)
|
|
830
|
+
for (const [label, list] of [['逾期', overdue], ['今天', todayDue], ['未来 7 天', week], ['等别人', waiting]]) {
|
|
831
|
+
if (!list.length) continue
|
|
832
|
+
console.log(`${label}:`)
|
|
833
|
+
for (const c of list.slice(0, 5)) console.log(` ${c.id} ${c.creditor} · ${c.action}${c.dueAt ? ` · ${c.dueAt.slice(0, 10)}` : ''}`)
|
|
834
|
+
}
|
|
835
|
+
console.log('下一件:' + (next?.action ?? '先定一个承诺或交付。'))
|
|
836
|
+
if (calendar) await printCalendarToday()
|
|
837
|
+
if (sources) await printSources(ledger)
|
|
838
|
+
}
|
|
839
|
+
|
|
840
|
+
function tick(ledger, asJson = false) {
|
|
841
|
+
const now = Date.now()
|
|
842
|
+
const store = dbStore()
|
|
843
|
+
const localDay = localDayOf(now)
|
|
844
|
+
const weekAhead = now + 7 * 86400_000
|
|
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()
|
|
852
|
+
for (const c of ledger.listCommitments()) {
|
|
853
|
+
if (c.status === 'done' || c.status === 'dropped') continue
|
|
854
|
+
if (c.status === 'snoozed') {
|
|
855
|
+
const until = snoozeUntil.get(`snooze:${c.id}`)
|
|
856
|
+
if (until && Date.parse(until) > now) continue
|
|
857
|
+
c.status = 'open'
|
|
858
|
+
statusChanged = true
|
|
859
|
+
snoozeKeys.push(`snooze:${c.id}`)
|
|
860
|
+
}
|
|
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)
|
|
876
|
+
const msLeft = Date.parse(c.dueAt) - now
|
|
877
|
+
let level = (msLeft < 0 || dueDay === localDay) ? 'L2' : 'L1'
|
|
878
|
+
if (level === 'L2' && Date.parse(c.dueAt) < now - 86400_000 && process.env.ADVISERS_ALLOW_L3 === '1') level = 'L3'
|
|
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 })
|
|
893
|
+
due.push({ ...c, level })
|
|
894
|
+
}
|
|
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)
|
|
900
|
+
if (asJson) {
|
|
901
|
+
console.log(JSON.stringify({ now: new Date(now).toISOString(), localDay, due }, null, 2))
|
|
902
|
+
return
|
|
903
|
+
}
|
|
904
|
+
if (!due.length) { console.log('未来 7 天无到期。'); return }
|
|
905
|
+
for (const c of due) {
|
|
906
|
+
const dueDay = localDayOf(c.dueAt)
|
|
907
|
+
const label = Date.parse(c.dueAt) < now ? '逾期' : dueDay === localDay ? '今天到期' : '即将到期'
|
|
908
|
+
console.log(`[${c.level}] ${label}:${c.action}(${c.dueAt})`)
|
|
909
|
+
}
|
|
910
|
+
}
|
|
911
|
+
|
|
912
|
+
function printAudit(args = []) {
|
|
913
|
+
ensureHome()
|
|
914
|
+
const store = dbStore()
|
|
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
|
+
}
|
|
926
|
+
const verify = store.verifyAudit()
|
|
927
|
+
console.log(`audit: ${verify.ok ? 'verified' : `BROKEN at seq ${verify.seq}`} (${verify.count ?? 0} entries)`)
|
|
928
|
+
if (!verify.ok) process.exitCode = 1
|
|
929
|
+
for (const row of store.listAudit(20)) {
|
|
930
|
+
console.log(`${row.seq}\t${row.at.slice(0, 19)}\t${row.action}\t${row.allowed ? 'allow' : 'deny'}\t${row.reason ?? ''}`)
|
|
931
|
+
}
|
|
932
|
+
}
|
|
933
|
+
|
|
934
|
+
function printPrivacy(args = []) {
|
|
935
|
+
ensureHome()
|
|
936
|
+
const asJson = args.includes('--json')
|
|
937
|
+
const prove = args.includes('--prove')
|
|
938
|
+
const store = dbStore()
|
|
939
|
+
let audit = null
|
|
940
|
+
try { const v = store?.verifyAudit(); if (v) audit = { ok: v.ok, count: v.count ?? 0 } } catch {}
|
|
941
|
+
const facts = {
|
|
942
|
+
home: HOME,
|
|
943
|
+
database: DB,
|
|
944
|
+
telemetry: 'none',
|
|
945
|
+
default_egress: 'none',
|
|
946
|
+
explicit_egress: ['research --web|--url', 'model calls (chat/capture/review/brief --deep)'],
|
|
947
|
+
provider: { baseUrl: process.env.ADVISERS_BASE_URL ?? 'https://api.deepseek.com', model: process.env.ADVISERS_MODEL ?? 'deepseek-chat' },
|
|
948
|
+
secret_matter: 'egress fail-closed (secrecy > 0)',
|
|
949
|
+
at_rest_encryption: 'not implemented for general data; secret-matter encryption is E9-T3',
|
|
950
|
+
audit,
|
|
951
|
+
export: 'advisers export --all',
|
|
952
|
+
delete: 'advisers purge <matter> --yes',
|
|
953
|
+
}
|
|
954
|
+
if (asJson) { console.log(JSON.stringify(facts, null, 2)); return }
|
|
955
|
+
console.log('privacy · local data facts')
|
|
956
|
+
console.log(`home: ${facts.home}`)
|
|
957
|
+
console.log(`database: ${facts.database}`)
|
|
958
|
+
console.log(`telemetry: ${facts.telemetry}`)
|
|
959
|
+
console.log(`egress: ${facts.default_egress} by default; explicit: ${facts.explicit_egress.join(', ')}`)
|
|
960
|
+
console.log(`provider: ${facts.provider.model} @ ${facts.provider.baseUrl}`)
|
|
961
|
+
console.log(`secret: ${facts.secret_matter}`)
|
|
962
|
+
console.log(`encryption: ${facts.at_rest_encryption}`)
|
|
963
|
+
console.log(`audit: ${audit ? (audit.ok ? `verified (${audit.count} entries)` : 'BROKEN') : 'unavailable'}`)
|
|
964
|
+
console.log(`export: ${facts.export}`)
|
|
965
|
+
console.log(`delete: ${facts.delete}`)
|
|
966
|
+
if (prove) {
|
|
967
|
+
const checks = [
|
|
968
|
+
['home exists', existsSync(HOME)],
|
|
969
|
+
['database exists', existsSync(DB)],
|
|
970
|
+
['audit verified', Boolean(audit?.ok)],
|
|
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 } })()],
|
|
974
|
+
]
|
|
975
|
+
let failed = 0
|
|
976
|
+
for (const [name, ok] of checks) { if (!ok) failed++; console.log(`[${ok ? 'PASS' : 'FAIL'}] ${name}`) }
|
|
977
|
+
if (failed) process.exitCode = 1
|
|
978
|
+
}
|
|
979
|
+
}
|
|
980
|
+
|
|
981
|
+
function printLinks() {
|
|
982
|
+
const ledger = loadLedger()
|
|
983
|
+
const rows = ledger.listLinks()
|
|
984
|
+
if (!rows.length) { console.log('no links yet'); return }
|
|
985
|
+
const title = new Map(ledger.listMatters().map((m) => [m.id, m.title]))
|
|
986
|
+
for (const l of rows) {
|
|
987
|
+
console.log(`${l.id}\t${l.status}\t${l.type}\t${title.get(l.fromMatter) ?? l.fromMatter} -> ${title.get(l.toMatter) ?? l.toMatter}\tconf=${l.confidence}`)
|
|
988
|
+
}
|
|
989
|
+
}
|
|
990
|
+
|
|
991
|
+
/**
|
|
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).
|
|
1082
|
+
* Never opens the store read-write, never calls a model, never writes the
|
|
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).
|
|
1089
|
+
*/
|
|
1090
|
+
async function petBrief(args) {
|
|
1091
|
+
const { flags } = parseFlags(args)
|
|
1092
|
+
const asJson = args.includes('--json')
|
|
1093
|
+
const check = args.includes('--check')
|
|
1094
|
+
const strict = args.includes('--strict')
|
|
1095
|
+
const printSchema = args.includes('--print-schema')
|
|
1096
|
+
const inFile = flags.in
|
|
1097
|
+
const outFlag = flags.out
|
|
1098
|
+
const displayPolicyFlag = flags['display-policy']
|
|
1099
|
+
const fail = (code, message) => {
|
|
1100
|
+
console.error(JSON.stringify({ error: { code, message } }))
|
|
1101
|
+
process.exitCode = 1
|
|
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
|
+
}
|
|
1110
|
+
if (inFile !== undefined && !check) return fail('E_USAGE', '--in can only be used with --check')
|
|
1111
|
+
if (inFile !== undefined && typeof inFile !== 'string') return fail('E_USAGE', '--in needs a file path')
|
|
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() }
|
|
1123
|
+
try {
|
|
1124
|
+
if (inFile) {
|
|
1125
|
+
let text
|
|
1126
|
+
try { text = readFileSync(inFile, 'utf8') } catch (error) { return fail('E_READ', `cannot read ${inFile}: ${error.message}`) }
|
|
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))
|
|
1129
|
+
if (!result.ok) process.exitCode = 1
|
|
1130
|
+
return
|
|
1131
|
+
}
|
|
1132
|
+
const { readLedgerSnapshotReadOnly } = await import('../lib/pet-brief-store.js')
|
|
1133
|
+
let snapshot
|
|
1134
|
+
try {
|
|
1135
|
+
snapshot = readLedgerSnapshotReadOnly({ store: mode, dbPath: DB, statePath: STATE })
|
|
1136
|
+
} catch (error) {
|
|
1137
|
+
return fail(error?.code ?? 'E_STORE', error?.message ?? String(error))
|
|
1138
|
+
}
|
|
1139
|
+
const ledger = Ledger.fromJSON(snapshot)
|
|
1140
|
+
const brief = buildPetBrief(ledger, displayPolicy ? { now: Date.now(), displayPolicy } : { now: Date.now() })
|
|
1141
|
+
if (check) {
|
|
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))
|
|
1144
|
+
if (!result.ok) process.exitCode = 1
|
|
1145
|
+
return
|
|
1146
|
+
}
|
|
1147
|
+
const outPath = outFlag === true ? join(HOME, 'pet-brief.json') : outFlag
|
|
1148
|
+
if (outPath) {
|
|
1149
|
+
try { writePetBriefAtomic(outPath, brief) } catch (error) { return fail('E_WRITE', `cannot write ${outPath}: ${error.message}`) }
|
|
1150
|
+
}
|
|
1151
|
+
if (asJson) { console.log(JSON.stringify(brief, null, 2)); return }
|
|
1152
|
+
console.log(`pet-brief · ${brief.counts.today} today · ${brief.counts.commitments} commitments · ${brief.counts.risks} risks · ${brief.counts.facts} facts`)
|
|
1153
|
+
console.log(`mood ${brief.mood} · expires ${brief.expiresAt} · displayPolicy ${brief.displayPolicy}`)
|
|
1154
|
+
if (outPath) console.log(`wrote ${outPath} (mode 600, atomic)`)
|
|
1155
|
+
} catch (error) {
|
|
1156
|
+
fail(error?.code ?? 'E_BRIEF', error?.message ?? String(error))
|
|
1157
|
+
}
|
|
1158
|
+
}
|
|
1159
|
+
|
|
1160
|
+
function tokenize(text) {
|
|
1161
|
+
return new Set((String(text).toLowerCase().match(/[a-z0-9]{2,}|[\u4e00-\u9fa5]{2}/g) ?? []))
|
|
1162
|
+
}
|
|
1163
|
+
|
|
1164
|
+
function printLearnReceipt(result) {
|
|
1165
|
+
const p = result.preference
|
|
1166
|
+
console.log(`记下了:${p.statement}`)
|
|
1167
|
+
console.log(`范围:全局(默认);要限定说「只对…」`)
|
|
1168
|
+
console.log(`有效期:30 天后复核${result.promoted ? ';已确认' : ';先按候选,重复一次才确认'}`)
|
|
1169
|
+
console.log(`下次:同类任务按这条执行;撤销用 /forget ${p.id}`)
|
|
1170
|
+
}
|
|
1171
|
+
|
|
1172
|
+
function printPreferences() {
|
|
1173
|
+
const ledger = loadLedger()
|
|
1174
|
+
const rows = ledger.listPreferences({ includeCandidates: true })
|
|
1175
|
+
if (!rows.length) { console.log('no preferences yet'); return }
|
|
1176
|
+
for (const p of rows) {
|
|
1177
|
+
console.log(`${p.id}\t${p.status}\tconf=${p.confidence.toFixed(2)}\t${p.statement}`)
|
|
1178
|
+
}
|
|
1179
|
+
}
|
|
1180
|
+
|
|
1181
|
+
async function doctor() {
|
|
1182
|
+
const rows = []
|
|
1183
|
+
const check = (name, ok, detail = '') => rows.push({ name, ok, detail })
|
|
1184
|
+
check('node', Number(process.versions.node.split('.')[0]) > 22 || (Number(process.versions.node.split('.')[0]) === 22 && Number(process.versions.node.split('.')[1]) >= 13), process.version)
|
|
1185
|
+
try { ensureHome(); check('home', existsSync(HOME), HOME) } catch (error) { check('home', false, error.message) }
|
|
1186
|
+
try {
|
|
1187
|
+
const store = openStore()
|
|
1188
|
+
const integrity = store.assertIntegrity()
|
|
1189
|
+
check('sqlite', integrity === 'ok', `${DB} (${integrity})`)
|
|
1190
|
+
const audit = store.verifyAudit()
|
|
1191
|
+
check('audit', audit.ok, audit.ok ? `${audit.count} entries` : `BROKEN at seq ${audit.seq}`)
|
|
1192
|
+
check('schema', true, String(store.db.prepare("SELECT value FROM meta WHERE key='schema_version'").get()?.value ?? '?'))
|
|
1193
|
+
} catch (error) { check('sqlite', false, error.message) }
|
|
1194
|
+
let officeOk = false
|
|
1195
|
+
try { await import('advisers-office'); officeOk = true } catch { try { await import('../../office/dist/index.js'); officeOk = true } catch {} }
|
|
1196
|
+
check('office', officeOk, officeOk ? 'advisers-office resolvable' : 'npm i -g advisers-office@next, or ADVISERS_OFFICE_LOCAL=1 in checkout')
|
|
1197
|
+
check('policy', Boolean(StrictPolicyPack), StrictPolicyPack ? 'strict pack loaded' : 'policy pack missing')
|
|
1198
|
+
check('model', true, process.env.ADVISERS_API_KEY ? 'API key present (not tested)' : 'optional; ADVISERS_API_KEY not set')
|
|
1199
|
+
for (const row of rows) console.log(`${row.ok ? 'PASS' : 'FAIL'} ${row.name} ${row.detail}`)
|
|
1200
|
+
if (rows.some((r) => !r.ok)) process.exitCode = 1
|
|
1201
|
+
}
|
|
1202
|
+
|
|
1203
|
+
function init() {
|
|
1204
|
+
ensureHome()
|
|
1205
|
+
if (!existsSync(SOUL)) {
|
|
1206
|
+
const doc = { id: 'soul', version: 1, content: '你是我的幕僚:直接、简洁、有用。\n你是我生活里的客人:私事保持私密。\n如果你要改这个文件,先告诉我。\n', updatedAt: now(), updatedBy: 'human' }
|
|
1207
|
+
saveSoul(doc)
|
|
1208
|
+
}
|
|
1209
|
+
console.log(`home ${HOME}`)
|
|
1210
|
+
console.log(`soul ${existsSync(SOUL) ? SOUL : 'failed'}`)
|
|
1211
|
+
console.log('next advisers doctor')
|
|
1212
|
+
console.log(' advisers template weekly examples/templates/weekly.json out/weekly.docx')
|
|
1213
|
+
console.log(' advisers commit add "周五前发报价给王工" --quote "周五前发报价给王工" --due <ISO>')
|
|
1214
|
+
}
|
|
1215
|
+
|
|
1216
|
+
function printStatus(asJson = false) {
|
|
1217
|
+
const ledger = loadLedger()
|
|
1218
|
+
const data = {
|
|
1219
|
+
version: VERSION,
|
|
1220
|
+
node: process.version,
|
|
1221
|
+
office: process.env.ADVISERS_OFFICE_LOCAL === '1' || existsSync(new URL('../../office/dist/index.js', import.meta.url)) ? 'local build linked' : 'external package',
|
|
1222
|
+
home: HOME,
|
|
1223
|
+
store: mode === 'sqlite' ? { type: 'sqlite', path: DB } : { type: mode, path: STATE },
|
|
1224
|
+
model: modelLabel(),
|
|
1225
|
+
matters: ledger.listMatters().length,
|
|
1226
|
+
prefs: ledger.listPreferences().length,
|
|
1227
|
+
routines: ledger.listRoutines().length,
|
|
1228
|
+
links: ledger.listLinks().length,
|
|
1229
|
+
soul: existsSync(SOUL) ? 'present' : 'not initialized',
|
|
1230
|
+
}
|
|
1231
|
+
try {
|
|
1232
|
+
const store = dbStore()
|
|
1233
|
+
data.sessions = store?.listSessions(100).length ?? 0
|
|
1234
|
+
data.deliveries = store?.countDeliveries() ?? 0
|
|
1235
|
+
const usage = store?.sumModelUsage?.()
|
|
1236
|
+
if (usage?.calls) data.modelUsage = usage
|
|
1237
|
+
} catch {}
|
|
1238
|
+
if (asJson) { console.log(JSON.stringify(data, null, 2)); return }
|
|
1239
|
+
console.log(`version ${data.version}`)
|
|
1240
|
+
console.log(`node ${data.node}`)
|
|
1241
|
+
console.log(`office ${data.office}`)
|
|
1242
|
+
console.log(`home ${data.home}`)
|
|
1243
|
+
console.log(`store ${data.store.type}${data.store.path ? ` (${data.store.path})` : ''}`)
|
|
1244
|
+
console.log(`model ${data.model}`)
|
|
1245
|
+
console.log(`matters ${data.matters}`)
|
|
1246
|
+
console.log(`prefs ${data.prefs}`)
|
|
1247
|
+
console.log(`routines ${data.routines}`)
|
|
1248
|
+
console.log(`links ${data.links}`)
|
|
1249
|
+
if (data.sessions != null) console.log(`sessions ${data.sessions}`)
|
|
1250
|
+
if (data.deliveries != null) console.log(`deliveries ${data.deliveries}`)
|
|
1251
|
+
if (data.modelUsage) console.log(`model calls ${data.modelUsage.calls} · tokens ${data.modelUsage.total_tokens} · reasoning ${data.modelUsage.reasoning_tokens}`)
|
|
1252
|
+
console.log(`soul ${data.soul}`)
|
|
1253
|
+
}
|
|
1254
|
+
|
|
1255
|
+
function loadHistory(conversationId) {
|
|
1256
|
+
try {
|
|
1257
|
+
const store = dbStore()
|
|
1258
|
+
if (!store) return { turns: [], summary: '' }
|
|
1259
|
+
const turns = store.listTurns(conversationId, 100)
|
|
1260
|
+
const summary = store.getSessionSummary(conversationId)
|
|
1261
|
+
return buildHistory({ turns, summary: summary?.summary, throughSeq: summary?.throughSeq ?? 0 })
|
|
1262
|
+
} catch {
|
|
1263
|
+
return { turns: [], summary: '' }
|
|
1264
|
+
}
|
|
1265
|
+
}
|
|
1266
|
+
|
|
1267
|
+
function recordTurn(conversationId, role, content) {
|
|
1268
|
+
if (!content) return
|
|
1269
|
+
try { dbStore()?.addTurn({ conversationId, role, content }) } catch {}
|
|
1270
|
+
}
|
|
1271
|
+
|
|
1272
|
+
async function maybeSummarize(conversationId, { apiKey, baseUrl, model, ledger } = {}) {
|
|
1273
|
+
try {
|
|
1274
|
+
const store = dbStore()
|
|
1275
|
+
if (!store) return
|
|
1276
|
+
const turns = store.listTurns(conversationId, 500)
|
|
1277
|
+
const old = store.getSessionSummary(conversationId)
|
|
1278
|
+
if (!shouldSummarize(turns, old?.throughSeq ?? 0, 10, 20)) return
|
|
1279
|
+
const latest = turns.at(-1).seq
|
|
1280
|
+
const cutoff = Math.max(0, latest - 20)
|
|
1281
|
+
const fresh = turns.filter((t) => t.seq > (old?.throughSeq ?? 0) && t.seq <= cutoff)
|
|
1282
|
+
if (!fresh.length) return
|
|
1283
|
+
const pins = buildPins({ preferences: ledger?.listPreferences({ includeCandidates: false }) ?? [], commitments: ledger?.openCommitments() ?? [] })
|
|
1284
|
+
let summary = summarizeTurns(fresh, old?.summary ?? '')
|
|
1285
|
+
if (apiKey && process.env.ADVISERS_LLM_SUMMARY !== '0') {
|
|
1286
|
+
try {
|
|
1287
|
+
const transcript = fresh.map((t) => `${t.role === 'user' ? '用户' : '助手'}:${t.content}`).join('\n')
|
|
1288
|
+
const response = await chatCompletion({
|
|
1289
|
+
apiKey,
|
|
1290
|
+
baseUrl: baseUrl || 'https://api.deepseek.com',
|
|
1291
|
+
model: model || 'deepseek-flash',
|
|
1292
|
+
task: 'summarize',
|
|
1293
|
+
thinking: false,
|
|
1294
|
+
messages: [
|
|
1295
|
+
{ role: 'system', content: '把会话压缩成给秘书续接用的摘要。必须保留:已完成什么、未决问题、承诺及截止时间、用户偏好/禁忌、下一步。不要寒暄,不超过 500 字。' },
|
|
1296
|
+
{ role: 'user', content: `${old?.summary ? `旧摘要:\n${old.summary}\n\n` : ''}${transcript}` },
|
|
1297
|
+
],
|
|
1298
|
+
})
|
|
1299
|
+
if (response.content?.trim()) summary = response.content.trim()
|
|
1300
|
+
} catch {}
|
|
1301
|
+
}
|
|
1302
|
+
summary = ensurePins(summary, pins)
|
|
1303
|
+
if (pins && !continuityProbes({ summary, pins, turns: fresh }).ok) return
|
|
1304
|
+
store.upsertSessionSummary({ conversationId, summary, throughSeq: cutoff, pins })
|
|
1305
|
+
} catch {}
|
|
1306
|
+
}
|
|
1307
|
+
|
|
1308
|
+
function printOpening(conversationId) {
|
|
1309
|
+
try {
|
|
1310
|
+
const store = dbStore()
|
|
1311
|
+
if (!store) return
|
|
1312
|
+
const turns = store.listTurns(conversationId, 20)
|
|
1313
|
+
const summary = store.getSessionSummary(conversationId)
|
|
1314
|
+
const commitments = loadLedger().openCommitments()
|
|
1315
|
+
console.log(buildOpening({ summary: summary?.summary, turns, commitments }))
|
|
1316
|
+
} catch {}
|
|
1317
|
+
}
|
|
1318
|
+
|
|
1319
|
+
function applyNudgeFeedback(text) {
|
|
1320
|
+
const outcome = classifyNudgeOutcome(text)
|
|
1321
|
+
if (!outcome) return
|
|
1322
|
+
try {
|
|
1323
|
+
const store = dbStore()
|
|
1324
|
+
const pending = store?.listNudges(20).filter((n) => n.outcome === 'pending') ?? []
|
|
1325
|
+
if (!pending.length) return
|
|
1326
|
+
for (const n of pending.slice(0, 3)) store.setNudgeOutcome(n.id, outcome)
|
|
1327
|
+
console.log(`[nudge] 记下:${outcome === 'accepted' ? '已处理' : '先不提醒'}`)
|
|
1328
|
+
} catch {}
|
|
1329
|
+
}
|
|
1330
|
+
|
|
1331
|
+
async function runTurn({ runtime, ledger, text, conversationId, debug = false, confirm, attachments = [] }) {
|
|
1332
|
+
const result = await runtime.ingest({
|
|
1333
|
+
linkId: 'cli',
|
|
1334
|
+
accountId: 'local',
|
|
1335
|
+
conversationId,
|
|
1336
|
+
messageId: `cli_${Date.now()}_${++cliSeq}`,
|
|
1337
|
+
sender: { id: 'local' },
|
|
1338
|
+
text,
|
|
1339
|
+
trusted: true,
|
|
1340
|
+
timestamp: now(),
|
|
1341
|
+
})
|
|
1342
|
+
if (!result.accepted) {
|
|
1343
|
+
console.log(`[ignored: ${result.reason}]`)
|
|
1344
|
+
return
|
|
1345
|
+
}
|
|
1346
|
+
applyNudgeFeedback(text)
|
|
1347
|
+
const context = runtime.lastContext
|
|
1348
|
+
if (!context) throw new Error('runtime did not produce a context')
|
|
1349
|
+
const egressDenied = egressDeniedReason(context.matter, 'chat')
|
|
1350
|
+
if (egressDenied) {
|
|
1351
|
+
console.log(`[blocked] ${egressDenied}`)
|
|
1352
|
+
dbStore()?.appendAudit({ actor: 'local', action: 'policy.egress_deny', allowed: false, reason: 'chat' })
|
|
1353
|
+
return
|
|
1354
|
+
}
|
|
1355
|
+
if (context.crisis && (context.crisis.tier === 'T1' || context.crisis.tier === 'T2' || (context.crisis.tier === 'T3' && context.crisis.thirdParty))) {
|
|
1356
|
+
console.log(context.crisis.script)
|
|
1357
|
+
dbStore()?.appendAudit({ actor: 'local', action: 'policy.crisis', allowed: false, reason: context.crisis.tier })
|
|
1358
|
+
return
|
|
1359
|
+
}
|
|
1360
|
+
if (context.policy && !context.policy.allowed) {
|
|
1361
|
+
console.log(`[policy] ${context.policy.reason}`)
|
|
1362
|
+
dbStore()?.appendAudit({ actor: 'local', action: 'policy.deny', allowed: false, reason: context.policy.code ?? 'DENY' })
|
|
1363
|
+
return
|
|
1364
|
+
}
|
|
1365
|
+
const intent = context.intent
|
|
1366
|
+
let agentText = text
|
|
1367
|
+
const extracted = []
|
|
1368
|
+
const attachmentLib = attachments.length ? await loadAttachments() : null
|
|
1369
|
+
for (const file of attachments) {
|
|
1370
|
+
try {
|
|
1371
|
+
const attachment = await attachmentLib.extractAttachment(file, { cwd: process.cwd() })
|
|
1372
|
+
extracted.push(attachment)
|
|
1373
|
+
console.log(`[attach] ${attachment.name} (${attachment.text.length} chars${attachment.truncated ? ', truncated' : ''})`)
|
|
1374
|
+
} catch (error) {
|
|
1375
|
+
console.log(`[attach] ${file}: ${error.message}`)
|
|
1376
|
+
}
|
|
1377
|
+
}
|
|
1378
|
+
if (extracted.length) {
|
|
1379
|
+
agentText = `${text}\n\n[attachments]\n` + extracted.map((a) => `<file name="${a.name}">\n${a.text}\n</file>`).join('\n\n')
|
|
1380
|
+
}
|
|
1381
|
+
try {
|
|
1382
|
+
dbStore()?.upsertSession({ conversationId, matterId: context.matter.id, title: text.slice(0, 80) })
|
|
1383
|
+
} catch {}
|
|
1384
|
+
if (debug) {
|
|
1385
|
+
console.log('[context]')
|
|
1386
|
+
console.log(context.prompt)
|
|
1387
|
+
console.log('[/context]')
|
|
1388
|
+
}
|
|
1389
|
+
const noisy = debug || process.env.ADVISERS_VERBOSE === '1'
|
|
1390
|
+
if (intent && (noisy || intent.action === 'ask')) {
|
|
1391
|
+
console.log(intent.readback)
|
|
1392
|
+
if (intent.questions?.length) console.log(`问:${intent.questions[0]}`)
|
|
1393
|
+
}
|
|
1394
|
+
if (intent?.action === 'ask' && intent.questions?.length) return intent.questions[0]
|
|
1395
|
+
const apiKey = process.env.ADVISERS_API_KEY
|
|
1396
|
+
if (!apiKey || process.env.ADVISERS_NO_MODEL === '1') {
|
|
1397
|
+
const local = intent?.questions?.[0] ?? ''
|
|
1398
|
+
recordTurn(conversationId, 'user', text)
|
|
1399
|
+
if (local) recordTurn(conversationId, 'assistant', local)
|
|
1400
|
+
await maybeSummarize(conversationId, { apiKey, baseUrl: process.env.ADVISERS_BASE_URL, model: process.env.ADVISERS_MODEL, ledger })
|
|
1401
|
+
if (!intent?.questions?.length) console.log('[local] 未配置模型;已记录到当前会话,但没有创建承诺或文件。设置 ADVISERS_API_KEY 后可用自然语言执行;也可用 `advisers office` / `advisers template` 直接生成文件。')
|
|
1402
|
+
return intent?.questions?.[0]
|
|
1403
|
+
}
|
|
1404
|
+
const history = loadHistory(conversationId)
|
|
1405
|
+
const pins = buildPins({
|
|
1406
|
+
preferences: ledger.listPreferences({ matterId: context.matter.id }),
|
|
1407
|
+
commitments: ledger.openCommitments(context.matter.id),
|
|
1408
|
+
})
|
|
1409
|
+
const prompt = pins ? `${context.prompt}\n<session-pins>\n${pins}\n</session-pins>` : context.prompt
|
|
1410
|
+
const fitted = fitHistory({ system: prompt, summary: history.summary, history: history.turns, current: agentText, maxTokens: Number(process.env.ADVISERS_CONTEXT_TOKENS || 12000) })
|
|
1411
|
+
if (fitted.trimmed) console.log(`[compact] 裁剪 ${fitted.trimmed} 轮旧历史`)
|
|
1412
|
+
const { reply, artifacts, toolLog } = await runAgent({
|
|
1413
|
+
runtime,
|
|
1414
|
+
text: agentText,
|
|
1415
|
+
context: { ...context, prompt },
|
|
1416
|
+
history: fitted.history,
|
|
1417
|
+
summary: history.summary,
|
|
1418
|
+
ledger,
|
|
1419
|
+
matterId: context.matter.id,
|
|
1420
|
+
turnId: `cli_${Date.now()}_${cliSeq}`,
|
|
1421
|
+
backupDir: join(HOME, 'undo'),
|
|
1422
|
+
store: dbStore(),
|
|
1423
|
+
apiKey,
|
|
1424
|
+
baseUrl: process.env.ADVISERS_BASE_URL || 'https://api.deepseek.com',
|
|
1425
|
+
model: process.env.ADVISERS_MODEL || 'deepseek-flash',
|
|
1426
|
+
cwd: process.cwd(),
|
|
1427
|
+
force: process.env.ADVISERS_FORCE === '1',
|
|
1428
|
+
confirm,
|
|
1429
|
+
effort: process.env.ADVISERS_THINKING_EFFORT,
|
|
1430
|
+
onTool: (name) => { if (debug || process.env.ADVISERS_PROGRESS !== '0') console.log(`[tool] ${name}`) },
|
|
1431
|
+
})
|
|
1432
|
+
lastRun = { artifacts: [...new Set(artifacts)], toolLog }
|
|
1433
|
+
recordTurn(conversationId, 'user', text)
|
|
1434
|
+
recordTurn(conversationId, 'assistant', reply || '')
|
|
1435
|
+
await maybeSummarize(conversationId, { apiKey, baseUrl: process.env.ADVISERS_BASE_URL, model: process.env.ADVISERS_MODEL, ledger })
|
|
1436
|
+
if (reply) console.log(reply)
|
|
1437
|
+
const uniqueArtifacts = [...new Set(artifacts)]
|
|
1438
|
+
if (uniqueArtifacts.length) {
|
|
1439
|
+
for (const file of uniqueArtifacts) {
|
|
1440
|
+
let bytes = 0
|
|
1441
|
+
try { bytes = statSync(file).size } catch {}
|
|
1442
|
+
console.log(`[完成] ${text.replace(/\s+/g, ' ').slice(0, 48)} -> ${file}(${bytes} B)`)
|
|
1443
|
+
}
|
|
1444
|
+
const structural = toolLog.filter((t) => t.name === 'office_build' || t.name === 'office_template')
|
|
1445
|
+
if (structural.length && structural.every((t) => t.ok && !(t.payload?.missing?.length))) console.log('校验:结构通过(内容未逐字核对)')
|
|
1446
|
+
else if (structural.length) console.log('校验:未通过,文件保留但未记成完成')
|
|
1447
|
+
else console.log('校验:文本已保存')
|
|
1448
|
+
console.log('下一步:打开确认;要改哪段直接说')
|
|
1449
|
+
for (const file of uniqueArtifacts) console.log(`[file] ${file}`)
|
|
1450
|
+
}
|
|
1451
|
+
if (artifacts.length) {
|
|
1452
|
+
try {
|
|
1453
|
+
dbStore()?.addDelivery({
|
|
1454
|
+
matterId: context.matter.id,
|
|
1455
|
+
conversationId,
|
|
1456
|
+
files: artifacts,
|
|
1457
|
+
tool: toolLog.map((t) => t.name).join(','),
|
|
1458
|
+
title: text.slice(0, 80),
|
|
1459
|
+
validation: toolLog.every((t) => t.ok !== false) ? 'ok' : 'failed',
|
|
1460
|
+
})
|
|
1461
|
+
dbStore()?.appendAudit({ actor: 'local', action: 'delivery', allowed: true, reason: artifacts.join(',') })
|
|
1462
|
+
} catch {}
|
|
1463
|
+
}
|
|
1464
|
+
let runId
|
|
1465
|
+
try {
|
|
1466
|
+
runId = dbStore()?.addTaskRun({
|
|
1467
|
+
conversationId,
|
|
1468
|
+
matterId: context.matter.id,
|
|
1469
|
+
task: text.slice(0, 500),
|
|
1470
|
+
tools: toolLog.map((t) => ({ name: t.name, ok: t.ok })),
|
|
1471
|
+
artifacts,
|
|
1472
|
+
outcome: toolLog.some((t) => !t.ok) ? 'partial' : 'ok',
|
|
1473
|
+
})
|
|
1474
|
+
} catch {}
|
|
1475
|
+
if (runId && process.env.ADVISERS_LEARNING === 'auto' && apiKey) {
|
|
1476
|
+
try {
|
|
1477
|
+
const run = dbStore()?.listTaskRuns(50).find((r) => r.id === runId)
|
|
1478
|
+
const review = await reviewRun({ run, routines: ledger.listRoutines(), apiKey, baseUrl: process.env.ADVISERS_BASE_URL, model: process.env.ADVISERS_MODEL })
|
|
1479
|
+
const checked = lintReview(review, { run, routines: ledger.listRoutines() })
|
|
1480
|
+
if (checked.ok && checked.review.verdict !== 'NONE') {
|
|
1481
|
+
const made = materializeReview(checked.review, { run, ledger })
|
|
1482
|
+
saveLedger(ledger)
|
|
1483
|
+
console.log(`[learn] ${made.verdict}${made.routine ? ` draft ${made.routine.id}` : made.patch ? ` patch ${made.patch.id}` : ''}`)
|
|
1484
|
+
}
|
|
1485
|
+
} catch {}
|
|
1486
|
+
}
|
|
1487
|
+
const candidate = buildRoutineCandidate({ text, toolLog, artifacts })
|
|
1488
|
+
if (candidate && !ledger.listRoutines().some((r) => r.name === candidate.name)) {
|
|
1489
|
+
try {
|
|
1490
|
+
const routine = ledger.addRoutine(candidate)
|
|
1491
|
+
console.log(`[routine] draft ${routine.id} (${routine.steps.length} steps); approve with \`advisers routine approve ${routine.id}\``)
|
|
1492
|
+
saveLedger(ledger)
|
|
1493
|
+
} catch {}
|
|
1494
|
+
}
|
|
1495
|
+
if (/我会|我来|稍后|明天|提醒你/.test(reply || '') && !toolLog.some((t) => t.name === 'commitment_add')) console.log('[warn] 空承诺:回复里答应跟进,但账本没有承诺。请用 /commit add 或让我重做。')
|
|
1496
|
+
const failed = toolLog.filter((t) => !t.ok)
|
|
1497
|
+
if (failed.length) console.log(`[没做成] ${failed.length} 个步骤失败;已完成 ${uniqueArtifacts.length} 个文件,原文件未丢。下一步:/retry 或告诉我换一种做法。`)
|
|
1498
|
+
}
|
|
1499
|
+
|
|
1500
|
+
function parseChatArgs(args) {
|
|
1501
|
+
const files = []
|
|
1502
|
+
const words = []
|
|
1503
|
+
for (let i = 0; i < args.length; i++) {
|
|
1504
|
+
if (args[i] === '--file' || args[i] === '-f') {
|
|
1505
|
+
if (args[i + 1]) files.push(args[++i])
|
|
1506
|
+
} else {
|
|
1507
|
+
words.push(args[i])
|
|
1508
|
+
}
|
|
1509
|
+
}
|
|
1510
|
+
return { text: words.join(' ').trim(), files }
|
|
1511
|
+
}
|
|
1512
|
+
|
|
1513
|
+
async function chat(args) {
|
|
1514
|
+
const { text, files } = parseChatArgs(args)
|
|
1515
|
+
if (!text) {
|
|
1516
|
+
if (process.stdin.isTTY) { await repl(); return }
|
|
1517
|
+
console.error('usage: advisers chat [--file <path>] <text>')
|
|
1518
|
+
process.exitCode = 1
|
|
1519
|
+
return
|
|
1520
|
+
}
|
|
1521
|
+
const ledger = loadLedger()
|
|
1522
|
+
const runtime = runtimeFor(ledger)
|
|
1523
|
+
await runTurn({ runtime, ledger, text, conversationId: latestConversationId(), attachments: files })
|
|
1524
|
+
saveLedger(ledger)
|
|
1525
|
+
}
|
|
1526
|
+
|
|
1527
|
+
async function repl() {
|
|
1528
|
+
const readline = await import('node:readline/promises')
|
|
1529
|
+
const rl = readline.createInterface({ input: process.stdin, output: process.stdout, historySize: 100 })
|
|
1530
|
+
const ledger = loadLedger()
|
|
1531
|
+
const runtime = runtimeFor(ledger)
|
|
1532
|
+
let conversationId = latestConversationId()
|
|
1533
|
+
let debug = process.env.ADVISERS_DEBUG === '1'
|
|
1534
|
+
let pendingFiles = []
|
|
1535
|
+
let lastTask
|
|
1536
|
+
console.log('advisers · local')
|
|
1537
|
+
if (process.env.ADVISERS_DEBUG === '1') {
|
|
1538
|
+
console.log(`model: ${modelLabel()}`)
|
|
1539
|
+
console.log(`home: ${HOME}`)
|
|
1540
|
+
}
|
|
1541
|
+
try {
|
|
1542
|
+
const latest = dbStore()?.listSessions(1)[0]
|
|
1543
|
+
printOpening(latest?.conversationId ?? conversationId)
|
|
1544
|
+
} catch {}
|
|
1545
|
+
console.log('/help for commands, /quit to leave')
|
|
1546
|
+
|
|
1547
|
+
const runTask = async (taskText, files = [], { skipPlan = false } = {}) => {
|
|
1548
|
+
const brief = runtime.brief(taskText)
|
|
1549
|
+
if (!skipPlan && shouldPlan(taskText, brief)) {
|
|
1550
|
+
console.log('计划:')
|
|
1551
|
+
for (const step of planLines(brief)) console.log(` ${step}`)
|
|
1552
|
+
if (!(await askYesNo(rl, '按这个计划执行?[Y/n] ', true))) { console.log('已取消'); return }
|
|
1553
|
+
}
|
|
1554
|
+
const confirm = async ({ path }) => {
|
|
1555
|
+
console.log(`${path} 已存在`)
|
|
1556
|
+
return askYesNo(rl, '覆盖?[y/N] ', false)
|
|
1557
|
+
}
|
|
1558
|
+
lastTask = { text: taskText, files: [...files] }
|
|
1559
|
+
try {
|
|
1560
|
+
const question = await runTurn({ runtime, ledger, text: taskText, conversationId, debug, confirm, attachments: files })
|
|
1561
|
+
saveLedger(ledger)
|
|
1562
|
+
pendingFiles = []
|
|
1563
|
+
if (question) {
|
|
1564
|
+
let answer
|
|
1565
|
+
try { answer = await rl.question('? ') } catch { return }
|
|
1566
|
+
if (answer.trim().startsWith('/')) {
|
|
1567
|
+
console.log('已取消补充,请重新输入命令')
|
|
1568
|
+
return
|
|
1569
|
+
}
|
|
1570
|
+
if (answer.trim()) {
|
|
1571
|
+
await runTurn({ runtime, ledger, text: `${taskText}\n补充:${answer.trim()}`, conversationId, debug, confirm, attachments: files })
|
|
1572
|
+
saveLedger(ledger)
|
|
1573
|
+
}
|
|
1574
|
+
}
|
|
1575
|
+
} catch (error) {
|
|
1576
|
+
console.error(`[没做成] ${error.message}`)
|
|
1577
|
+
console.error('已保留:任务和会话;没有丢文件。下一步:/retry 重试。')
|
|
1578
|
+
}
|
|
1579
|
+
}
|
|
1580
|
+
|
|
1581
|
+
for (;;) {
|
|
1582
|
+
let line
|
|
1583
|
+
try { line = await rl.question('› ') } catch { break }
|
|
1584
|
+
const text = line.trim()
|
|
1585
|
+
if (!text) continue
|
|
1586
|
+
if (text === '/quit' || text === '/exit') break
|
|
1587
|
+
if (text === '/help') {
|
|
1588
|
+
console.log(' /help this help')
|
|
1589
|
+
console.log(' /status home/store/model/counts')
|
|
1590
|
+
console.log(' /history recent conversations')
|
|
1591
|
+
console.log(' /resume <n|id> resume a conversation')
|
|
1592
|
+
console.log(' /deliveries recent generated files')
|
|
1593
|
+
console.log(' /new start a new conversation')
|
|
1594
|
+
console.log(' /file <path> attach a file to the next task')
|
|
1595
|
+
console.log(' /files list pending attachments')
|
|
1596
|
+
console.log(' /clear clear pending attachments')
|
|
1597
|
+
console.log(' /retry rerun the last task')
|
|
1598
|
+
console.log(' /correct <text> record a correction; 2nd time promotes it')
|
|
1599
|
+
console.log(' /who who I owe / who owes me')
|
|
1600
|
+
console.log(' /memory what I remember')
|
|
1601
|
+
console.log(' /commit add <action> --quote <text> [--due ISO]')
|
|
1602
|
+
console.log(' /commit ls')
|
|
1603
|
+
console.log(' /done <id> --evidence <text>')
|
|
1604
|
+
console.log(' /search <text> full-text search old turns')
|
|
1605
|
+
console.log(' /tick due in the next 7 days')
|
|
1606
|
+
console.log(' /week last 7 days')
|
|
1607
|
+
console.log(' /digest [day] today/week digest')
|
|
1608
|
+
console.log(' /diff show the last changed file')
|
|
1609
|
+
console.log(' /undo restore the last overwritten/created file')
|
|
1610
|
+
console.log(' /links list candidate/confirmed links')
|
|
1611
|
+
console.log(' /forget <id> forget a preference')
|
|
1612
|
+
console.log(' /prefs list preferences (incl. candidates)')
|
|
1613
|
+
console.log(' /audit verify and show the audit hash chain')
|
|
1614
|
+
console.log(' /decay apply 30-day preference decay')
|
|
1615
|
+
console.log(' /why <pref-id> explain a preference')
|
|
1616
|
+
console.log(' /routine save save the last task as a draft routine')
|
|
1617
|
+
console.log(' /brief <text> print the IntentBrief without calling the model')
|
|
1618
|
+
console.log(' /debug toggle full context')
|
|
1619
|
+
console.log(' /quit leave')
|
|
1620
|
+
continue
|
|
1621
|
+
}
|
|
1622
|
+
if (text === '/status') { printStatus(); continue }
|
|
1623
|
+
if (text === '/who') {
|
|
1624
|
+
const open = ledger.openCommitments()
|
|
1625
|
+
const mine = open.filter((c) => c.debtor === 'user' || c.debtor === 'agent')
|
|
1626
|
+
const waiting = open.filter((c) => c.debtor === 'third' || c.debtor.startsWith('third:'))
|
|
1627
|
+
console.log(`我欠别人(${mine.length})`)
|
|
1628
|
+
for (const c of mine) console.log(` ${c.id} ${c.creditor} · ${c.action}${c.dueAt ? ` · ${c.dueAt.slice(0, 10)}` : ''}`)
|
|
1629
|
+
console.log(`等别人/别人欠我(${waiting.length})`)
|
|
1630
|
+
for (const c of waiting) console.log(` ${c.id} ${c.debtor} · ${c.action}${c.dueAt ? ` · ${c.dueAt.slice(0, 10)}` : ''}`)
|
|
1631
|
+
continue
|
|
1632
|
+
}
|
|
1633
|
+
if (text === '/history') { printHistory(); continue }
|
|
1634
|
+
if (text === '/deliveries') { printDeliveries(); continue }
|
|
1635
|
+
if (text === '/new') { conversationId = `local_${Date.now()}`; pendingFiles = []; console.log('new conversation'); continue }
|
|
1636
|
+
if (text === '/debug') { debug = !debug; console.log(`debug ${debug ? 'on' : 'off'}`); continue }
|
|
1637
|
+
if (text === '/files') { console.log(pendingFiles.length ? pendingFiles.join('\n') : 'no pending attachments'); continue }
|
|
1638
|
+
if (text === '/clear') { pendingFiles = []; console.log('attachments cleared'); continue }
|
|
1639
|
+
if (text.startsWith('/correct ')) {
|
|
1640
|
+
const statement = text.slice(9).trim()
|
|
1641
|
+
if (!statement) { console.log('usage: /correct <statement>'); continue }
|
|
1642
|
+
const result = learnPreference(ledger, statement, statement)
|
|
1643
|
+
saveLedger(ledger)
|
|
1644
|
+
printLearnReceipt(result)
|
|
1645
|
+
continue
|
|
1646
|
+
}
|
|
1647
|
+
if (text === '/decay') {
|
|
1648
|
+
const changed = applyPreferenceDecay(ledger.listPreferences({ includeCandidates: true }))
|
|
1649
|
+
saveLedger(ledger)
|
|
1650
|
+
console.log(`[decay] ${changed.length} preference(s) updated`)
|
|
1651
|
+
continue
|
|
1652
|
+
}
|
|
1653
|
+
if (text === '/prefs') { printPreferences(); continue }
|
|
1654
|
+
if (text === '/links') { printLinks(); continue }
|
|
1655
|
+
if (text === '/memory') { printMemory(ledger); continue }
|
|
1656
|
+
if (text === '/tick') { tick(ledger); continue }
|
|
1657
|
+
if (text.startsWith('/search ')) {
|
|
1658
|
+
const q = text.slice(8).trim()
|
|
1659
|
+
const rows = dbStore()?.searchTurns(q, { limit: 10 }) ?? []
|
|
1660
|
+
if (!rows.length) console.log('没有匹配')
|
|
1661
|
+
for (const r of rows) console.log(`${r.seq}\t${r.role}\t${r.content.replace(/\s+/g, ' ').slice(0, 160)}`)
|
|
1662
|
+
continue
|
|
1663
|
+
}
|
|
1664
|
+
if (text === '/week') { printWeek(ledger); continue }
|
|
1665
|
+
if (text === '/digest' || text === '/digest day' || text === '/digest week') {
|
|
1666
|
+
const store = dbStore()
|
|
1667
|
+
console.log(buildDigest({
|
|
1668
|
+
period: text.endsWith('week') ? 'week' : 'day',
|
|
1669
|
+
turns: store?.listTurns(conversationId, 200) ?? [],
|
|
1670
|
+
commitments: ledger.listCommitments(),
|
|
1671
|
+
deliveries: store?.listDeliveries(100) ?? [],
|
|
1672
|
+
}))
|
|
1673
|
+
continue
|
|
1674
|
+
}
|
|
1675
|
+
if (text === '/diff') {
|
|
1676
|
+
const result = await diffLatest({ cwd: process.cwd(), backupDir: join(HOME, 'undo') })
|
|
1677
|
+
console.log(result.ok ? result.diff : `diff failed: ${result.error}`)
|
|
1678
|
+
continue
|
|
1679
|
+
}
|
|
1680
|
+
if (text === '/undo') {
|
|
1681
|
+
const result = await undoLatest({ cwd: process.cwd(), backupDir: join(HOME, 'undo'), force: args.includes('--force') })
|
|
1682
|
+
console.log(result.ok ? `已回滚:${result.path}` : `撤销失败:${result.error}`)
|
|
1683
|
+
continue
|
|
1684
|
+
}
|
|
1685
|
+
if (text.startsWith('/commit ')) {
|
|
1686
|
+
const { flags, positional } = parseFlags(text.slice(8).trim().split(/\s+/))
|
|
1687
|
+
if (positional[0] === 'ls') { printCommitments(ledger); continue }
|
|
1688
|
+
if (positional[0] === 'add') {
|
|
1689
|
+
const action = positional.slice(1).join(' ')
|
|
1690
|
+
if (!action || !flags.quote) { console.log('用法:/commit add <action> --quote <原话> [--due ISO]'); continue }
|
|
1691
|
+
const c = ledger.addCommitment({ matterId: activeMatterId(ledger), debtor: flags.debtor ?? 'user', creditor: flags.creditor ?? 'me', action, dueAt: flags.due, capability: 'todo', evidence: [{ sessionId: conversationId, turnId: 'cli', quote: String(flags.quote) }] })
|
|
1692
|
+
saveLedger(ledger)
|
|
1693
|
+
console.log(`${c.id} open ${c.action}`)
|
|
1694
|
+
continue
|
|
1695
|
+
}
|
|
1696
|
+
console.log('用法:/commit add ... 或 /commit ls'); continue
|
|
1697
|
+
}
|
|
1698
|
+
if (text.startsWith('/done ')) {
|
|
1699
|
+
const { flags, positional } = parseFlags(text.slice(6).trim().split(/\s+/))
|
|
1700
|
+
const id = positional[0]
|
|
1701
|
+
if (!id || !flags.evidence) { console.log('用法:/done <id> --evidence <证据>'); continue }
|
|
1702
|
+
ledger.completeCommitment(id, [{ sessionId: conversationId, turnId: 'cli', quote: String(flags.evidence) }])
|
|
1703
|
+
saveLedger(ledger)
|
|
1704
|
+
console.log(`done: ${id}`)
|
|
1705
|
+
continue
|
|
1706
|
+
}
|
|
1707
|
+
if (text.startsWith('/forget ')) {
|
|
1708
|
+
const id = text.slice(8).trim()
|
|
1709
|
+
const ok = ledger.forget('preference', id)
|
|
1710
|
+
saveLedger(ledger)
|
|
1711
|
+
console.log(ok ? `forgotten: ${id}` : `unknown preference: ${id}`)
|
|
1712
|
+
continue
|
|
1713
|
+
}
|
|
1714
|
+
if (text === '/audit') { printAudit(); continue }
|
|
1715
|
+
if (text.startsWith('/why ')) { why(text.slice(5).trim()); continue }
|
|
1716
|
+
if (text === '/routine save') {
|
|
1717
|
+
if (!lastTask) { console.log('nothing to save'); continue }
|
|
1718
|
+
const tools = lastRun?.toolLog?.map((t) => t.name) ?? []
|
|
1719
|
+
const routine = ledger.addRoutine({
|
|
1720
|
+
name: lastTask.text.slice(0, 60),
|
|
1721
|
+
description: '从本地任务沉淀的流程草稿',
|
|
1722
|
+
trigger: [],
|
|
1723
|
+
steps: tools.length ? tools : ['执行任务'],
|
|
1724
|
+
preferences: [],
|
|
1725
|
+
pitfalls: [],
|
|
1726
|
+
verification: ['产物已生成并记录 delivery'],
|
|
1727
|
+
createdBy: 'agent',
|
|
1728
|
+
})
|
|
1729
|
+
saveLedger(ledger)
|
|
1730
|
+
console.log(`draft routine ${routine.id}: ${routine.name}`)
|
|
1731
|
+
console.log(`approve with \`advisers routine approve ${routine.id}\``)
|
|
1732
|
+
continue
|
|
1733
|
+
}
|
|
1734
|
+
if (text === '/retry') {
|
|
1735
|
+
if (!lastTask) { console.log('nothing to retry'); continue }
|
|
1736
|
+
await runTask(lastTask.text, lastTask.files, { skipPlan: true })
|
|
1737
|
+
continue
|
|
1738
|
+
}
|
|
1739
|
+
if (text.startsWith('/file ')) {
|
|
1740
|
+
const path = text.slice(6).trim()
|
|
1741
|
+
if (!path) { console.log('usage: /file <path>'); continue }
|
|
1742
|
+
pendingFiles.push(path)
|
|
1743
|
+
console.log(`attached: ${path} (${pendingFiles.length} pending)`)
|
|
1744
|
+
continue
|
|
1745
|
+
}
|
|
1746
|
+
if (text.startsWith('/resume ')) {
|
|
1747
|
+
const arg = text.slice(8).trim()
|
|
1748
|
+
try {
|
|
1749
|
+
const rows = dbStore()?.listSessions(50) ?? []
|
|
1750
|
+
const pick = /^\d+$/.test(arg) ? rows[Number(arg) - 1] : rows.find((r) => r.conversationId === arg)
|
|
1751
|
+
if (!pick) { console.log(`unknown session: ${arg}`); continue }
|
|
1752
|
+
conversationId = pick.conversationId
|
|
1753
|
+
pendingFiles = []
|
|
1754
|
+
console.log(`resumed: ${pick.title} [${pick.conversationId}]`)
|
|
1755
|
+
} catch { console.log('history is not available') }
|
|
1756
|
+
printOpening(conversationId)
|
|
1757
|
+
continue
|
|
1758
|
+
}
|
|
1759
|
+
if (text.startsWith('/brief ')) {
|
|
1760
|
+
const brief = runtime.brief(text.slice(7).trim())
|
|
1761
|
+
console.log(core.renderIntentBrief(brief))
|
|
1762
|
+
console.log(core.renderReadback(brief))
|
|
1763
|
+
continue
|
|
1764
|
+
}
|
|
1765
|
+
if (text.startsWith('/')) { console.log(`unknown command: ${text}; /help`); continue }
|
|
1766
|
+
const feedback = correctionStatement(text)
|
|
1767
|
+
if (feedback) {
|
|
1768
|
+
const result = learnPreference(ledger, feedback, text, { explicit: /^(以后|记住|每次)/.test(text) })
|
|
1769
|
+
saveLedgerWithAudit(ledger, { actor: 'local', action: 'correct', allowed: true, reason: result.preference.id })
|
|
1770
|
+
printLearnReceipt(result)
|
|
1771
|
+
continue
|
|
1772
|
+
}
|
|
1773
|
+
await runTask(text, pendingFiles)
|
|
1774
|
+
}
|
|
1775
|
+
rl.close()
|
|
1776
|
+
saveLedger(ledger)
|
|
1777
|
+
}
|
|
1778
|
+
|
|
1779
|
+
function ls() {
|
|
1780
|
+
const matters = loadLedger().listMatters()
|
|
1781
|
+
if (!matters.length) {
|
|
1782
|
+
console.log('no matters yet')
|
|
1783
|
+
return
|
|
1784
|
+
}
|
|
1785
|
+
for (const m of matters) {
|
|
1786
|
+
console.log(`${m.id}\t${m.status}\tsecrecy=${m.secrecy}\t${m.title}`)
|
|
1787
|
+
}
|
|
1788
|
+
}
|
|
1789
|
+
|
|
1790
|
+
function why(id) {
|
|
1791
|
+
if (!id) {
|
|
1792
|
+
console.error('usage: advisers why <pref-id|fact-id>')
|
|
1793
|
+
process.exitCode = 1
|
|
1794
|
+
return
|
|
1795
|
+
}
|
|
1796
|
+
if (id.startsWith('fact_')) {
|
|
1797
|
+
const ledger = loadLedger()
|
|
1798
|
+
const fact = ledger.listFacts(undefined, true).find((f) => f.id === id)
|
|
1799
|
+
if (!fact) { console.error(`unknown fact: ${id}`); process.exitCode = 1; return }
|
|
1800
|
+
console.log(`${fact.id} [${fact.authority}] ${fact.subject} ${fact.predicate} ${fact.object}`)
|
|
1801
|
+
console.log(`status: ${fact.status}; confidence: ${fact.confidence}`)
|
|
1802
|
+
for (const e of fact.evidence ?? []) console.log(`evidence: ${e.ref ?? '-'} 「${e.quote ?? ''}」`)
|
|
1803
|
+
return
|
|
1804
|
+
}
|
|
1805
|
+
const pref = loadLedger().findPreference(id)
|
|
1806
|
+
if (!pref) {
|
|
1807
|
+
console.error(`unknown preference: ${id}`)
|
|
1808
|
+
process.exitCode = 1
|
|
1809
|
+
return
|
|
1810
|
+
}
|
|
1811
|
+
console.log(`${pref.id} [${pref.kind}/${pref.priority}] ${pref.statement}`)
|
|
1812
|
+
console.log(`scope: ${pref.scope.level}${pref.scope.value ? ':' + pref.scope.value : ''}`)
|
|
1813
|
+
console.log(`source: ${pref.source.type}${pref.source.quote ? ' — ' + pref.source.quote : ''}`)
|
|
1814
|
+
console.log(`confidence: ${pref.confidence}; status: ${pref.status}`)
|
|
1815
|
+
}
|
|
1816
|
+
|
|
1817
|
+
function forget(id) {
|
|
1818
|
+
if (!id) {
|
|
1819
|
+
console.error('usage: advisers forget <pref-id>')
|
|
1820
|
+
process.exitCode = 1
|
|
1821
|
+
return
|
|
1822
|
+
}
|
|
1823
|
+
const ledger = loadLedger()
|
|
1824
|
+
const kind = id.startsWith('fact_') ? 'fact' : 'preference'
|
|
1825
|
+
const ok = ledger.forget(kind, id)
|
|
1826
|
+
saveLedger(ledger)
|
|
1827
|
+
console.log(ok ? `forgotten: ${id}` : `unknown ${kind}: ${id}`)
|
|
1828
|
+
if (!ok) process.exitCode = 1
|
|
1829
|
+
}
|
|
1830
|
+
|
|
1831
|
+
async function exportLedger(all = false, options = {}) {
|
|
1832
|
+
const ledger = loadLedger().toJSON()
|
|
1833
|
+
const payload = all ? (() => {
|
|
1834
|
+
const store = dbStore()
|
|
1835
|
+
const tables = ['sessions', 'turns', 'session_summaries', 'summary_versions', 'deliveries', 'nudges', 'task_runs', 'audit', 'memory_candidates', 'permit_consumed']
|
|
1836
|
+
const data = {}
|
|
1837
|
+
for (const table of tables) data[table] = store ? store.db.prepare(`SELECT * FROM ${table}`).all() : []
|
|
1838
|
+
return { version: VERSION, exportedAt: now(), ledger, data }
|
|
1839
|
+
})() : ledger
|
|
1840
|
+
let text = JSON.stringify(payload, null, 2)
|
|
1841
|
+
if (options.encrypted) {
|
|
1842
|
+
const passphrase = process.env.ADVISERS_EXPORT_PASSPHRASE
|
|
1843
|
+
if (!passphrase) { console.error('export --encrypted requires ADVISERS_EXPORT_PASSPHRASE (min 8 chars)'); process.exitCode = 1; return }
|
|
1844
|
+
const { encryptJson } = await loadVault()
|
|
1845
|
+
text = JSON.stringify(encryptJson(payload, passphrase), null, 2)
|
|
1846
|
+
}
|
|
1847
|
+
if (options.out) {
|
|
1848
|
+
ensureHome()
|
|
1849
|
+
writeFileSync(options.out, text + '\n', { mode: 0o600 })
|
|
1850
|
+
dbStore()?.appendAudit({ actor: 'local', action: options.encrypted ? 'export.encrypted' : 'export', allowed: true, reason: basename(options.out) })
|
|
1851
|
+
console.log(`wrote ${options.out}${options.encrypted ? ' (AES-256-GCM)' : ''}`)
|
|
1852
|
+
} else console.log(text)
|
|
1853
|
+
}
|
|
1854
|
+
|
|
1855
|
+
async function importLedger(file, { replace = false } = {}) {
|
|
1856
|
+
if (!file) { console.error('usage: advisers import <file> [--replace]'); process.exitCode = 1; return }
|
|
1857
|
+
if (!replace) { console.error('import replaces the local ledger; pass --replace to confirm'); process.exitCode = 1; return }
|
|
1858
|
+
let payload
|
|
1859
|
+
try {
|
|
1860
|
+
const { isVaultEnvelope, decryptJson } = await loadVault()
|
|
1861
|
+
const raw = JSON.parse(readFileSync(file, 'utf8'))
|
|
1862
|
+
if (isVaultEnvelope(raw)) {
|
|
1863
|
+
const passphrase = process.env.ADVISERS_EXPORT_PASSPHRASE
|
|
1864
|
+
if (!passphrase) { console.error('encrypted import requires ADVISERS_EXPORT_PASSPHRASE'); process.exitCode = 1; return }
|
|
1865
|
+
payload = decryptJson(raw, passphrase)
|
|
1866
|
+
} else payload = raw
|
|
1867
|
+
} catch (error) { console.error(`import failed: ${error.message}`); process.exitCode = 1; return }
|
|
1868
|
+
const data = payload?.ledger ?? payload
|
|
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' })
|
|
1871
|
+
ensureHome()
|
|
1872
|
+
try {
|
|
1873
|
+
const store = dbStore()
|
|
1874
|
+
if (store) copyFileSync(DB, join(HOME, `import-backup-${Date.now()}.db`))
|
|
1875
|
+
} catch {}
|
|
1876
|
+
try {
|
|
1877
|
+
const ledger = Ledger.fromJSON(data, LOCAL_PORTS)
|
|
1878
|
+
saveLedgerWithAudit(ledger, { actor: 'local', action: 'import.ledger', allowed: true, reason: basename(file) })
|
|
1879
|
+
console.log(`imported ${data.matters.length} matters, ${data.commitments?.length ?? 0} commitments`)
|
|
1880
|
+
if (payload?.data) console.error('note: SQLite-only tables in the import were not merged; ledger was replaced.')
|
|
1881
|
+
} catch (error) { console.error(`import failed: ${error.message}`); process.exitCode = 1 }
|
|
1882
|
+
}
|
|
1883
|
+
|
|
1884
|
+
function backup(file) {
|
|
1885
|
+
if (!file) { console.error('usage: advisers backup <path.db>'); process.exitCode = 1; return }
|
|
1886
|
+
const store = openStore()
|
|
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 }
|
|
1889
|
+
mkdirSync(dirname(file), { recursive: true })
|
|
1890
|
+
copyFileSync(DB, file)
|
|
1891
|
+
chmodSync(file, 0o600)
|
|
1892
|
+
console.log(`backup: ${file}`)
|
|
1893
|
+
}
|
|
1894
|
+
|
|
1895
|
+
async function brief(text, deep = false) {
|
|
1896
|
+
if (!text) {
|
|
1897
|
+
console.error('usage: advisers brief <text>')
|
|
1898
|
+
process.exitCode = 1
|
|
1899
|
+
return
|
|
1900
|
+
}
|
|
1901
|
+
const stage = process.env.ADVISERS_STAGE === 'trusted' ? 'trusted' : 'probation'
|
|
1902
|
+
const brief = core.buildIntentBrief(text, { stage })
|
|
1903
|
+
console.log(core.renderIntentBrief(brief))
|
|
1904
|
+
console.log('\n' + core.renderReadback(brief))
|
|
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 }
|
|
1909
|
+
try {
|
|
1910
|
+
const response = await chatCompletion({
|
|
1911
|
+
apiKey: process.env.ADVISERS_API_KEY,
|
|
1912
|
+
baseUrl: process.env.ADVISERS_BASE_URL,
|
|
1913
|
+
model: process.env.ADVISERS_MODEL,
|
|
1914
|
+
task: 'intent', thinking: true, effort: 'high', maxTokens: 2048,
|
|
1915
|
+
messages: [
|
|
1916
|
+
{ role: 'system', content: 'Return ONLY JSON: {"goal":"","deliverable":"","audience":"","constraints":[],"assumptions":[],"unknowns":[],"question":"one question that changes the plan or empty","risk":"low|medium|high"}. Do not invent facts; ask at most one question.' },
|
|
1917
|
+
{ role: 'user', content: text },
|
|
1918
|
+
],
|
|
1919
|
+
})
|
|
1920
|
+
const parsed = JSON.parse(String(response.content).replace(/^```(?:json)?\s*/i, '').replace(/\s*```$/, ''))
|
|
1921
|
+
console.log('\n深层 brief:')
|
|
1922
|
+
console.log(JSON.stringify(parsed, null, 2))
|
|
1923
|
+
} catch (error) { console.error(`deep brief failed: ${error.message}`) }
|
|
1924
|
+
}
|
|
1925
|
+
}
|
|
1926
|
+
|
|
1927
|
+
async function routine(sub, arg, arg2) {
|
|
1928
|
+
const ledger = loadLedger()
|
|
1929
|
+
if (typeof ledger.addRoutine !== 'function') {
|
|
1930
|
+
console.error('routine requires advisers-core@0.1.0-preview.3 or newer')
|
|
1931
|
+
process.exitCode = 1
|
|
1932
|
+
return
|
|
1933
|
+
}
|
|
1934
|
+
if (sub === 'ls' || !sub) {
|
|
1935
|
+
const rows = ledger.listRoutines()
|
|
1936
|
+
if (!rows.length) {
|
|
1937
|
+
console.log('no routines yet')
|
|
1938
|
+
return
|
|
1939
|
+
}
|
|
1940
|
+
for (const r of rows) console.log(`${r.id}\t${r.status}\tv${r.version}\t${r.name}`)
|
|
1941
|
+
return
|
|
1942
|
+
}
|
|
1943
|
+
if (sub === 'add') {
|
|
1944
|
+
if (!arg) {
|
|
1945
|
+
console.error('usage: advisers routine add <spec.json>')
|
|
1946
|
+
process.exitCode = 1
|
|
1947
|
+
return
|
|
1948
|
+
}
|
|
1949
|
+
await requireTosReaccept({ scope: 'routine', subject: 'routine:add', action: 'routine add' })
|
|
1950
|
+
const spec = JSON.parse(readFileSync(arg, 'utf8'))
|
|
1951
|
+
const routine = ledger.addRoutine({
|
|
1952
|
+
name: spec.name,
|
|
1953
|
+
description: spec.description ?? '',
|
|
1954
|
+
trigger: spec.trigger ?? [],
|
|
1955
|
+
steps: spec.steps ?? [],
|
|
1956
|
+
preferences: spec.preferences ?? [],
|
|
1957
|
+
pitfalls: spec.pitfalls ?? [],
|
|
1958
|
+
verification: spec.verification ?? [],
|
|
1959
|
+
scope: spec.scope,
|
|
1960
|
+
createdBy: spec.createdBy ?? 'user',
|
|
1961
|
+
})
|
|
1962
|
+
saveLedger(ledger)
|
|
1963
|
+
console.log(`draft routine ${routine.id}: ${routine.name}; approve with \`advisers routine approve ${routine.id}\``)
|
|
1964
|
+
return
|
|
1965
|
+
}
|
|
1966
|
+
if (sub === 'patches') {
|
|
1967
|
+
const rows = ledger.listRoutinePatches()
|
|
1968
|
+
if (!rows.length) {
|
|
1969
|
+
console.log('no routine patches')
|
|
1970
|
+
return
|
|
1971
|
+
}
|
|
1972
|
+
for (const p of rows) console.log(`${p.id}\t${p.status}\troutine=${p.routineId}\tbase=v${p.baseVersion}`)
|
|
1973
|
+
return
|
|
1974
|
+
}
|
|
1975
|
+
if (sub === 'patch') {
|
|
1976
|
+
if (!arg || !arg2) {
|
|
1977
|
+
console.error('usage: advisers routine patch <routine-id> <changes.json>')
|
|
1978
|
+
process.exitCode = 1
|
|
1979
|
+
return
|
|
1980
|
+
}
|
|
1981
|
+
await requireTosReaccept({ scope: 'routine', subject: `routine:${arg}`, action: 'routine patch' })
|
|
1982
|
+
const changes = JSON.parse(readFileSync(arg2, 'utf8'))
|
|
1983
|
+
const patch = ledger.proposeRoutinePatch(arg, changes)
|
|
1984
|
+
saveLedger(ledger)
|
|
1985
|
+
console.log(`patch ${patch.id} (base v${patch.baseVersion}):\n${patch.diff}`)
|
|
1986
|
+
console.log(`approve with \`advisers routine apply ${patch.id}\``)
|
|
1987
|
+
return
|
|
1988
|
+
}
|
|
1989
|
+
if (sub === 'check') {
|
|
1990
|
+
if (!arg) { console.error('usage: advisers routine check <id>'); process.exitCode = 1; return }
|
|
1991
|
+
const routine = ledger.listRoutines().find((r) => r.id === arg)
|
|
1992
|
+
if (!routine) { console.error(`unknown routine: ${arg}`); process.exitCode = 1; return }
|
|
1993
|
+
const result = checkRoutine(routine)
|
|
1994
|
+
for (const item of result.results) console.log(`${item.ok ? 'ok' : 'FAIL'}\t${item.kind}\t${item.entry}`)
|
|
1995
|
+
if (!result.ok) process.exitCode = 1
|
|
1996
|
+
return
|
|
1997
|
+
}
|
|
1998
|
+
if (sub === 'diff') {
|
|
1999
|
+
if (!arg) {
|
|
2000
|
+
console.error('usage: advisers routine diff <patch-id>')
|
|
2001
|
+
process.exitCode = 1
|
|
2002
|
+
return
|
|
2003
|
+
}
|
|
2004
|
+
const patch = ledger.listRoutinePatches().find((p) => p.id === arg)
|
|
2005
|
+
console.log(patch ? patch.diff : `unknown patch: ${arg}`)
|
|
2006
|
+
if (!patch) process.exitCode = 1
|
|
2007
|
+
return
|
|
2008
|
+
}
|
|
2009
|
+
if (sub === 'curate') {
|
|
2010
|
+
const apply = arg === '--apply'
|
|
2011
|
+
if (apply) await requireTosReaccept({ scope: 'routine', subject: 'routine:curate', action: 'routine curate --apply' })
|
|
2012
|
+
const now = Date.now()
|
|
2013
|
+
let changed = 0
|
|
2014
|
+
for (const r of ledger.listRoutines().filter((x) => x.status === 'active')) {
|
|
2015
|
+
const idleDays = (now - Date.parse(r.updatedAt)) / 86_400_000
|
|
2016
|
+
if (idleDays >= 90) {
|
|
2017
|
+
console.log(`${r.id}\tarchive candidate\t${Math.floor(idleDays)}d\t${r.name}`)
|
|
2018
|
+
if (apply) { ledger.deprecateRoutine(r.id); changed++ }
|
|
2019
|
+
} else if (idleDays >= 30) {
|
|
2020
|
+
console.log(`${r.id}\tstale\t${Math.floor(idleDays)}d\t${r.name}`)
|
|
2021
|
+
if (apply) { ledger.staleRoutine(r.id); changed++ }
|
|
2022
|
+
}
|
|
2023
|
+
}
|
|
2024
|
+
if (!changed && !apply) console.log('no stale routines (dry-run; use --apply)')
|
|
2025
|
+
if (apply) { saveLedger(ledger); console.log(`curated: ${changed}`) }
|
|
2026
|
+
return
|
|
2027
|
+
}
|
|
2028
|
+
if (sub === 'restore') {
|
|
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' })
|
|
2031
|
+
const r = ledger.restoreRoutine(arg)
|
|
2032
|
+
saveLedger(ledger)
|
|
2033
|
+
console.log(`restored to draft: ${r.id}`)
|
|
2034
|
+
return
|
|
2035
|
+
}
|
|
2036
|
+
if (sub === 'revert') {
|
|
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' })
|
|
2039
|
+
const patch = ledger.revertRoutinePatch(arg)
|
|
2040
|
+
saveLedger(ledger)
|
|
2041
|
+
console.log(`rolled_back: ${patch.id}`)
|
|
2042
|
+
return
|
|
2043
|
+
}
|
|
2044
|
+
if (sub === 'apply' || sub === 'reject') {
|
|
2045
|
+
if (!arg) {
|
|
2046
|
+
console.error(`usage: advisers routine ${sub} <patch-id>`)
|
|
2047
|
+
process.exitCode = 1
|
|
2048
|
+
return
|
|
2049
|
+
}
|
|
2050
|
+
if (sub === 'apply') {
|
|
2051
|
+
await requireTosReaccept({ scope: 'routine', subject: `routine:${arg}`, action: 'routine apply' })
|
|
2052
|
+
const pending = ledger.listRoutinePatches('pending').find((p) => p.id === arg)
|
|
2053
|
+
if (!pending) { console.error(`unknown or closed routine patch: ${arg}`); process.exitCode = 1; return }
|
|
2054
|
+
const routine = ledger.listRoutines().find((r) => r.id === pending.routineId)
|
|
2055
|
+
if (!routine) { console.error(`unknown routine: ${pending.routineId}`); process.exitCode = 1; return }
|
|
2056
|
+
const candidate = { ...routine, ...pending.changes }
|
|
2057
|
+
const check = checkRoutine(candidate)
|
|
2058
|
+
if (!check.ok) {
|
|
2059
|
+
console.error('routine checks failed; patch not applied')
|
|
2060
|
+
for (const item of check.results.filter((r) => !r.ok)) console.error(`FAIL ${item.entry}`)
|
|
2061
|
+
process.exitCode = 1
|
|
2062
|
+
return
|
|
2063
|
+
}
|
|
2064
|
+
}
|
|
2065
|
+
const patch = sub === 'apply' ? ledger.applyRoutinePatch(arg) : ledger.rejectRoutinePatch(arg)
|
|
2066
|
+
saveLedger(ledger)
|
|
2067
|
+
console.log(`${patch.status}: ${patch.id}`)
|
|
2068
|
+
return
|
|
2069
|
+
}
|
|
2070
|
+
if (sub === 'approve' || sub === 'archive') {
|
|
2071
|
+
if (!arg) {
|
|
2072
|
+
console.error(`usage: advisers routine ${sub} <id>`)
|
|
2073
|
+
process.exitCode = 1
|
|
2074
|
+
return
|
|
2075
|
+
}
|
|
2076
|
+
await requireTosReaccept({ scope: 'routine', subject: `routine:${arg}`, action: `routine ${sub}` })
|
|
2077
|
+
const routine = sub === 'approve' ? ledger.approveRoutine(arg) : ledger.archiveRoutine(arg)
|
|
2078
|
+
saveLedger(ledger)
|
|
2079
|
+
console.log(`${routine.status}: ${routine.id}`)
|
|
2080
|
+
return
|
|
2081
|
+
}
|
|
2082
|
+
console.error(`unknown routine subcommand: ${sub}`)
|
|
2083
|
+
process.exitCode = 1
|
|
2084
|
+
}
|
|
2085
|
+
|
|
2086
|
+
async function template(name, dataFile, outFile) {
|
|
2087
|
+
const names = ['weekly', 'budget', 'presentation', 'flow', 'mindmap', 'minutes', 'notice']
|
|
2088
|
+
if (!names.includes(name) || !dataFile || !outFile) {
|
|
2089
|
+
console.error('usage: advisers template <weekly|budget|presentation|flow|mindmap|minutes|notice> <data.json> <out>')
|
|
2090
|
+
process.exitCode = 1
|
|
2091
|
+
return
|
|
2092
|
+
}
|
|
2093
|
+
let mod
|
|
2094
|
+
if (process.env.ADVISERS_OFFICE_LOCAL === '1') {
|
|
2095
|
+
mod = await import('../../office/dist/index.js')
|
|
2096
|
+
} else {
|
|
2097
|
+
try {
|
|
2098
|
+
mod = await import('advisers-office')
|
|
2099
|
+
} catch {
|
|
2100
|
+
console.error('advisers-office is not installed; run `npm i -g advisers-office@next`')
|
|
2101
|
+
process.exitCode = 1
|
|
2102
|
+
return
|
|
2103
|
+
}
|
|
2104
|
+
}
|
|
2105
|
+
const data = JSON.parse(readFileSync(dataFile, 'utf8'))
|
|
2106
|
+
const spec = name === 'weekly' ? mod.weeklyReport(data)
|
|
2107
|
+
: name === 'budget' ? mod.budget(data)
|
|
2108
|
+
: name === 'presentation' ? mod.presentation(data)
|
|
2109
|
+
: name === 'flow' ? mod.flow(data)
|
|
2110
|
+
: name === 'minutes' ? mod.meetingMinutes(data)
|
|
2111
|
+
: name === 'notice' ? mod.notice(data)
|
|
2112
|
+
: mod.mindmap(data)
|
|
2113
|
+
mkdirSync(dirname(outFile), { recursive: true })
|
|
2114
|
+
const ext = outFile.split('.').pop()?.toLowerCase()
|
|
2115
|
+
const expected = name === 'budget' ? ['xlsx'] : name === 'presentation' ? ['pptx'] : (name === 'flow' || name === 'mindmap') ? ['mmd', 'mermaid', 'drawio'] : ['docx']
|
|
2116
|
+
if (!expected.includes(ext)) { console.error(`template ${name} writes ${expected.join('/')}; got .${ext}`); process.exitCode = 1; return }
|
|
2117
|
+
let buffer
|
|
2118
|
+
let result
|
|
2119
|
+
if (ext === 'docx') {
|
|
2120
|
+
buffer = await mod.buildDocx(spec); result = await mod.validateOffice(buffer, 'docx')
|
|
2121
|
+
} else if (ext === 'xlsx') {
|
|
2122
|
+
buffer = await mod.buildXlsx(spec); result = await mod.validateOffice(buffer, 'xlsx')
|
|
2123
|
+
} else if (ext === 'pptx') {
|
|
2124
|
+
buffer = await mod.buildPptx(spec); result = await mod.validateOffice(buffer, 'pptx')
|
|
2125
|
+
} else if (ext === 'xmind') {
|
|
2126
|
+
buffer = await mod.buildXmind(spec); result = await mod.validateXmind(buffer)
|
|
2127
|
+
} else if (ext === 'drawio') {
|
|
2128
|
+
await backupCliFile(outFile)
|
|
2129
|
+
writeFileSync(outFile, mod.buildDrawio(spec)); console.log(`wrote ${outFile}`); return
|
|
2130
|
+
} else {
|
|
2131
|
+
await backupCliFile(outFile)
|
|
2132
|
+
writeFileSync(outFile, mod.buildMermaid(spec)); console.log(`wrote ${outFile}`); return
|
|
2133
|
+
}
|
|
2134
|
+
await backupCliFile(outFile)
|
|
2135
|
+
writeFileSync(outFile, buffer)
|
|
2136
|
+
dbStore()?.appendAudit({ actor: 'local', action: 'office.template', allowed: true, reason: outFile })
|
|
2137
|
+
recordManualDelivery([outFile], 'template', name, result)
|
|
2138
|
+
console.log(result.ok ? `wrote ${outFile} (${buffer.length} bytes)` : `wrote ${outFile}, missing: ${result.missing.join(', ')}`)
|
|
2139
|
+
if (!result.ok) process.exitCode = 1
|
|
2140
|
+
}
|
|
2141
|
+
|
|
2142
|
+
async function documentReview(args) {
|
|
2143
|
+
const { flags, positional } = parseFlags(args)
|
|
2144
|
+
const file = positional[0]
|
|
2145
|
+
if (!file) { console.error('usage: advisers review <file> --request "..."'); process.exitCode = 1; return }
|
|
2146
|
+
const apiKey = process.env.ADVISERS_API_KEY
|
|
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 }
|
|
2151
|
+
let mod
|
|
2152
|
+
if (process.env.ADVISERS_OFFICE_LOCAL === '1') mod = await import('../../office/dist/index.js')
|
|
2153
|
+
else { try { mod = await import('advisers-office') } catch { mod = await import('../../office/dist/index.js') } }
|
|
2154
|
+
const doc = await mod.readOffice(readFileSync(file))
|
|
2155
|
+
const result = await reviewDocument({ text: mod.officeToText(doc, 20_000), request: flags.request, apiKey, baseUrl: process.env.ADVISERS_BASE_URL, model: process.env.ADVISERS_MODEL })
|
|
2156
|
+
dbStore()?.appendAudit({ actor: 'local', action: 'doc.review', allowed: !result.findings.some((f) => f.severity === 'blocker'), reason: file })
|
|
2157
|
+
console.log(result.summary || '(no summary)')
|
|
2158
|
+
for (const f of result.findings) console.log(`[${f.severity}] ${f.message}${f.evidence ? `(原文:${f.evidence})` : ''}`)
|
|
2159
|
+
if (result.invalid) { console.error('review output was not valid JSON'); process.exitCode = 1 }
|
|
2160
|
+
if (result.findings.some((f) => f.severity === 'blocker')) process.exitCode = 1
|
|
2161
|
+
}
|
|
2162
|
+
|
|
2163
|
+
async function research(args) {
|
|
2164
|
+
const { flags, positional } = parseFlags(args)
|
|
2165
|
+
if (!flags.web && !flags.url) { console.error('research requires explicit --web or --url (egress)'); process.exitCode = 1; return }
|
|
2166
|
+
const apiKey = process.env.ADVISERS_API_KEY
|
|
2167
|
+
if (!apiKey) { console.error('research requires ADVISERS_API_KEY'); process.exitCode = 1; return }
|
|
2168
|
+
const query = positional.join(' ').trim()
|
|
2169
|
+
const urls = flags.url ? [String(flags.url)] : []
|
|
2170
|
+
if (!query && !urls.length) { console.error('usage: advisers research --web|--url <url> [--deep] <query>'); process.exitCode = 1; return }
|
|
2171
|
+
const ledger = loadLedger()
|
|
2172
|
+
const matterId = activeMatterId(ledger)
|
|
2173
|
+
const denied = egressDeniedReason(ledger.getMatter(matterId), 'research')
|
|
2174
|
+
if (denied) { console.error(denied); process.exitCode = 1; return }
|
|
2175
|
+
const result = await runResearch({ query, urls, apiKey, baseUrl: process.env.ADVISERS_BASE_URL, deep: Boolean(flags.deep) })
|
|
2176
|
+
const store = dbStore()
|
|
2177
|
+
store?.addResearchRun({ matterId, query: query || urls[0], answer: result.answer, sources: result.sources, usage: result.usage, stopReason: result.stopReason })
|
|
2178
|
+
store?.appendAudit({ actor: 'local', action: 'egress.research', allowed: true, reason: `${urls.length ? 'url' : 'search'}:${result.sources.length}` })
|
|
2179
|
+
console.log(result.answer.trim())
|
|
2180
|
+
if (result.sources.length) {
|
|
2181
|
+
console.log('\n来源:')
|
|
2182
|
+
for (const source of result.sources) console.log(`- ${source.title || '(untitled)'} ${source.url}${source.pageAge ? ` (${source.pageAge.slice(0, 10)})` : ''}`)
|
|
2183
|
+
console.log('提示:网页引用是服务商返回,不等于本地文件证据。')
|
|
2184
|
+
}
|
|
2185
|
+
}
|
|
2186
|
+
|
|
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 }) {
|
|
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 })
|
|
2214
|
+
if (!result.candidates.length) return { count: 0, candidates: [] }
|
|
2215
|
+
const conversationId = latestConversationId()
|
|
2216
|
+
const turn = store.addTurn({ conversationId, role: 'user', content: text })
|
|
2217
|
+
const capturedAt = new Date().toISOString()
|
|
2218
|
+
const created = []
|
|
2219
|
+
for (const c of result.candidates) {
|
|
2220
|
+
const evidenceSource = await buildCaptureSource({ meta, quote: c.quote, ref: `${conversationId}#${turn.id}`, capturedAt })
|
|
2221
|
+
const candidate = store.proposeCandidate({
|
|
2222
|
+
kind: 'commitment',
|
|
2223
|
+
payload: { matterId, debtor: c.debtor === 'third' ? 'third' : 'user', creditor: c.creditor || 'someone', action: c.action, dueAt: c.dueAt, capability: 'none' },
|
|
2224
|
+
evidence: [{ quote: c.quote, turnId: turn.id, sessionId: conversationId, source: evidenceSource }],
|
|
2225
|
+
})
|
|
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)}」`)
|
|
2228
|
+
}
|
|
2229
|
+
store.appendAudit({ actor: 'local', action: 'capture.propose', allowed: true, reason: `${created.length} candidates` })
|
|
2230
|
+
return { count: created.length, candidates: created }
|
|
2231
|
+
}
|
|
2232
|
+
|
|
2233
|
+
async function capture(args) {
|
|
2234
|
+
const { flags, positional } = parseFlags(args)
|
|
2235
|
+
if (flags['from-mail']) return captureFromMail(flags)
|
|
2236
|
+
if (flags['from-transcript']) return captureFromTranscript(flags)
|
|
2237
|
+
if (flags['from-imap']) return captureFromImap(flags)
|
|
2238
|
+
let text = positional.join(' ').trim()
|
|
2239
|
+
if (flags.file) {
|
|
2240
|
+
try {
|
|
2241
|
+
const { extractAttachment } = await loadAttachments()
|
|
2242
|
+
const extracted = await extractAttachment(flags.file, { cwd: process.cwd() })
|
|
2243
|
+
if (!extracted.text) throw new Error('no extractable text')
|
|
2244
|
+
text = extracted.text
|
|
2245
|
+
} catch (error) { console.error(`capture --file failed: ${error.message}`); process.exitCode = 1; return }
|
|
2246
|
+
}
|
|
2247
|
+
if (!text) { console.error('usage: advisers capture [--file path] [--source wechat|meeting|email|contract] [--date ISO] [--matter id] <text>'); process.exitCode = 1; return }
|
|
2248
|
+
const apiKey = process.env.ADVISERS_API_KEY
|
|
2249
|
+
if (!apiKey) { console.error('capture requires ADVISERS_API_KEY'); process.exitCode = 1; return }
|
|
2250
|
+
ensureHome()
|
|
2251
|
+
const store = dbStore()
|
|
2252
|
+
if (!store) { console.error('capture requires SQLite store'); process.exitCode = 1; return }
|
|
2253
|
+
const ledger = loadLedger()
|
|
2254
|
+
const matterId = activeMatterId(ledger, flags.matter)
|
|
2255
|
+
const denied = egressDeniedReason(ledger.getMatter(matterId), 'capture')
|
|
2256
|
+
if (denied) { console.error(denied); process.exitCode = 1; return }
|
|
2257
|
+
saveLedger(ledger)
|
|
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('没有找到可确认的承诺候选。')
|
|
2264
|
+
else console.log('确认:advisers memory accept <id>;拒绝:advisers memory reject <id>')
|
|
2265
|
+
}
|
|
2266
|
+
|
|
2267
|
+
function parseEmailDate(value) {
|
|
2268
|
+
if (!value) return undefined
|
|
2269
|
+
const t = Date.parse(value)
|
|
2270
|
+
return Number.isFinite(t) ? new Date(t).toISOString() : undefined
|
|
2271
|
+
}
|
|
2272
|
+
|
|
2273
|
+
async function captureFromMail(flags) {
|
|
2274
|
+
const target = flags['from-mail']
|
|
2275
|
+
if (typeof target !== 'string') { console.error('usage: advisers capture --from-mail <file|dir> [--limit n]'); process.exitCode = 1; return }
|
|
2276
|
+
const apiKey = process.env.ADVISERS_API_KEY
|
|
2277
|
+
if (!apiKey) { console.error('capture --from-mail requires ADVISERS_API_KEY'); process.exitCode = 1; return }
|
|
2278
|
+
ensureHome()
|
|
2279
|
+
const store = dbStore()
|
|
2280
|
+
const ledger = loadLedger()
|
|
2281
|
+
const matterId = activeMatterId(ledger, flags.matter)
|
|
2282
|
+
const denied = egressDeniedReason(ledger.getMatter(matterId), 'mail')
|
|
2283
|
+
if (denied) { console.error(denied); process.exitCode = 1; return }
|
|
2284
|
+
saveLedger(ledger)
|
|
2285
|
+
const { parseMbox, parseEml, dedupeKey, toCaptureInput } = await loadImporters()
|
|
2286
|
+
let files = []
|
|
2287
|
+
try {
|
|
2288
|
+
const info = statSync(target)
|
|
2289
|
+
files = info.isDirectory() ? readdirSync(target).filter((f) => /\.(eml|mbox)$/i.test(f)).map((f) => join(target, f)) : [target]
|
|
2290
|
+
} catch (error) { console.error(`cannot read mail path: ${error.message}`); process.exitCode = 1; return }
|
|
2291
|
+
const limit = Math.max(1, Math.min(200, Number(flags.limit) || 20))
|
|
2292
|
+
let seen = 0, skipped = 0, failed = 0
|
|
2293
|
+
const created = []
|
|
2294
|
+
for (const file of files.slice(0, limit)) {
|
|
2295
|
+
let messages = []
|
|
2296
|
+
try {
|
|
2297
|
+
const raw = readFileSync(file, 'utf8')
|
|
2298
|
+
messages = extname(file).toLowerCase() === '.mbox' ? parseMbox(raw) : [parseEml(raw)]
|
|
2299
|
+
} catch (error) { failed++; console.error(`${file}: ${error.message}`); continue }
|
|
2300
|
+
for (const msg of messages) {
|
|
2301
|
+
seen++
|
|
2302
|
+
const key = dedupeKey('email', msg)
|
|
2303
|
+
if (store.hasSeen('import', 'mail', key, 30)) { skipped++; continue }
|
|
2304
|
+
const input = toCaptureInput(msg, { source: 'email' })
|
|
2305
|
+
if (!input.text.trim()) { skipped++; continue }
|
|
2306
|
+
try {
|
|
2307
|
+
const result = await proposeCaptureText({
|
|
2308
|
+
text: input.text, source: 'email', date: parseEmailDate(msg.date), matterId, store, json: flags.json === true,
|
|
2309
|
+
meta: { type: 'mail', messageId: msg.messageId, subject: msg.subject, from: msg.from },
|
|
2310
|
+
})
|
|
2311
|
+
created.push(...result.candidates)
|
|
2312
|
+
store.markSeen('import', 'mail', key)
|
|
2313
|
+
} catch (error) { failed++; console.error(`${msg.messageId || file}: ${error.message}`) }
|
|
2314
|
+
}
|
|
2315
|
+
}
|
|
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`)
|
|
2322
|
+
}
|
|
2323
|
+
|
|
2324
|
+
async function captureFromTranscript(flags) {
|
|
2325
|
+
const file = flags['from-transcript']
|
|
2326
|
+
if (typeof file !== 'string') { console.error('usage: advisers capture --from-transcript <file>'); process.exitCode = 1; return }
|
|
2327
|
+
const apiKey = process.env.ADVISERS_API_KEY
|
|
2328
|
+
if (!apiKey) { console.error('capture --from-transcript requires ADVISERS_API_KEY'); process.exitCode = 1; return }
|
|
2329
|
+
ensureHome()
|
|
2330
|
+
const store = dbStore()
|
|
2331
|
+
const ledger = loadLedger()
|
|
2332
|
+
const matterId = activeMatterId(ledger, flags.matter)
|
|
2333
|
+
const denied = egressDeniedReason(ledger.getMatter(matterId), 'transcript')
|
|
2334
|
+
if (denied) { console.error(denied); process.exitCode = 1; return }
|
|
2335
|
+
saveLedger(ledger)
|
|
2336
|
+
const { parseTranscript, dedupeKey, toCaptureInput } = await loadImporters()
|
|
2337
|
+
let parsed
|
|
2338
|
+
try { parsed = parseTranscript(readFileSync(file, 'utf8')) } catch (error) { console.error(`cannot parse transcript: ${error.message}`); process.exitCode = 1; return }
|
|
2339
|
+
const key = dedupeKey('transcript', parsed)
|
|
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
|
+
}
|
|
2345
|
+
const input = toCaptureInput(parsed, { source: 'meeting' })
|
|
2346
|
+
if (!input.text.trim()) { console.error('transcript has no text'); process.exitCode = 1; return }
|
|
2347
|
+
const result = await proposeCaptureText({
|
|
2348
|
+
text: input.text, source: 'meeting', matterId, store, json: flags.json === true,
|
|
2349
|
+
meta: { type: 'transcript', file: basename(file), speakers: input.meta?.speakers ?? [] },
|
|
2350
|
+
})
|
|
2351
|
+
store.markSeen('import', 'transcript', key)
|
|
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`)
|
|
2358
|
+
}
|
|
2359
|
+
|
|
2360
|
+
async function captureFromImap(flags) {
|
|
2361
|
+
const host = process.env.ADVISERS_IMAP_HOST
|
|
2362
|
+
const user = process.env.ADVISERS_IMAP_USER
|
|
2363
|
+
const pass = process.env.ADVISERS_IMAP_PASS
|
|
2364
|
+
if (!host || !user || !pass) { console.error('capture --from-imap requires ADVISERS_IMAP_HOST / ADVISERS_IMAP_USER / ADVISERS_IMAP_PASS'); process.exitCode = 1; return }
|
|
2365
|
+
if (!process.env.ADVISERS_API_KEY) { console.error('capture --from-imap requires ADVISERS_API_KEY'); process.exitCode = 1; return }
|
|
2366
|
+
ensureHome()
|
|
2367
|
+
const store = dbStore()
|
|
2368
|
+
const ledger = loadLedger()
|
|
2369
|
+
const matterId = activeMatterId(ledger, flags.matter)
|
|
2370
|
+
const denied = egressDeniedReason(ledger.getMatter(matterId), 'imap')
|
|
2371
|
+
if (denied) { console.error(denied); process.exitCode = 1; return }
|
|
2372
|
+
saveLedger(ledger)
|
|
2373
|
+
const { parseEml, dedupeKey, toCaptureInput } = await loadImporters()
|
|
2374
|
+
let messages
|
|
2375
|
+
try {
|
|
2376
|
+
messages = await fetchImapMessages({
|
|
2377
|
+
host,
|
|
2378
|
+
port: Number(process.env.ADVISERS_IMAP_PORT) || (String(process.env.ADVISERS_IMAP_SECURE) === '0' ? 143 : 993),
|
|
2379
|
+
secure: String(process.env.ADVISERS_IMAP_SECURE) !== '0',
|
|
2380
|
+
user, pass,
|
|
2381
|
+
mailbox: process.env.ADVISERS_IMAP_MAILBOX || 'INBOX',
|
|
2382
|
+
sinceDays: Math.max(1, Number(flags['since-days']) || 30),
|
|
2383
|
+
limit: Math.max(1, Math.min(100, Number(flags.limit) || 20)),
|
|
2384
|
+
})
|
|
2385
|
+
} catch (error) { console.error(`imap failed: ${error.message}`); process.exitCode = 1; return }
|
|
2386
|
+
let seen = 0, skipped = 0, failed = 0
|
|
2387
|
+
const created = []
|
|
2388
|
+
for (const msg of messages) {
|
|
2389
|
+
seen++
|
|
2390
|
+
let parsed
|
|
2391
|
+
try { parsed = parseEml(msg.raw.toString('utf8')) } catch (error) { failed++; console.error(`imap message ${msg.uid}: ${error.message}`); continue }
|
|
2392
|
+
const key = dedupeKey('email', parsed)
|
|
2393
|
+
if (store.hasSeen('import', 'imap', key, 30)) { skipped++; continue }
|
|
2394
|
+
const input = toCaptureInput(parsed, { source: 'email' })
|
|
2395
|
+
if (!input.text.trim()) { skipped++; continue }
|
|
2396
|
+
try {
|
|
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)
|
|
2399
|
+
store.markSeen('import', 'imap', key)
|
|
2400
|
+
} catch (error) { failed++; console.error(`imap message ${msg.uid}: ${error.message}`) }
|
|
2401
|
+
}
|
|
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)`)
|
|
2408
|
+
}
|
|
2409
|
+
|
|
2410
|
+
async function calendarImport(args) {
|
|
2411
|
+
const { flags, positional } = parseFlags(args)
|
|
2412
|
+
const file = typeof flags.ics === 'string' ? flags.ics : positional[0]
|
|
2413
|
+
if (!file) { console.error('usage: advisers calendar import --ics <file>'); process.exitCode = 1; return }
|
|
2414
|
+
ensureHome()
|
|
2415
|
+
const store = dbStore()
|
|
2416
|
+
const ledger = loadLedger()
|
|
2417
|
+
const matterId = activeMatterId(ledger)
|
|
2418
|
+
const denied = egressDeniedReason(ledger.getMatter(matterId), 'calendar')
|
|
2419
|
+
if (denied) { console.error(denied); process.exitCode = 1; return }
|
|
2420
|
+
let events
|
|
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 }
|
|
2425
|
+
let imported = 0
|
|
2426
|
+
for (const e of events) {
|
|
2427
|
+
if (!e.uid) continue
|
|
2428
|
+
store.upsertCalendarEvent({ uid: e.uid, summary: e.summary, startsAt: e.start, endsAt: e.end, allDay: e.allDay, tzid: e.tzid, location: e.location, rrule: e.rrule, source: basename(file) })
|
|
2429
|
+
imported++
|
|
2430
|
+
}
|
|
2431
|
+
store.appendAudit({ actor: 'local', action: 'calendar.import', allowed: true, reason: `${imported} events` })
|
|
2432
|
+
console.log(`calendar import: ${imported} events (read-only)`)
|
|
2433
|
+
}
|
|
2434
|
+
|
|
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() {
|
|
2442
|
+
const store = dbStore()
|
|
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 }
|
|
2470
|
+
console.log(`日历(本地只读,${localDay}):`)
|
|
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
|
+
}
|
|
2475
|
+
}
|
|
2476
|
+
|
|
2477
|
+
async function ui(args) {
|
|
2478
|
+
const flags = parseFlags(args).flags
|
|
2479
|
+
const port = Number(flags.port) || 17860
|
|
2480
|
+
const ledger = loadLedger()
|
|
2481
|
+
const store = dbStore()
|
|
2482
|
+
const { buildReminders } = await loadRemind()
|
|
2483
|
+
const snapshot = {
|
|
2484
|
+
today: () => {
|
|
2485
|
+
const open = ledger.openCommitments()
|
|
2486
|
+
return { open: open.length, commitments: open.map((c) => ({ id: c.id, action: c.action, dueAt: c.dueAt, creditor: c.creditor })) }
|
|
2487
|
+
},
|
|
2488
|
+
commitments: () => ledger.listCommitments().map((c) => ({ id: c.id, status: c.status, action: c.action, dueAt: c.dueAt, creditor: c.creditor })),
|
|
2489
|
+
who: () => ({ mine: ledger.openCommitments().filter((c) => c.debtor === 'user' || c.debtor === 'agent'), waiting: ledger.openCommitments().filter((c) => c.debtor === 'third' || c.debtor.startsWith('third:')) }),
|
|
2490
|
+
reminders: () => buildReminders(ledger, { now: new Date() }),
|
|
2491
|
+
}
|
|
2492
|
+
const app = createReadOnlyServer({ snapshot, port })
|
|
2493
|
+
const url = await app.listen()
|
|
2494
|
+
console.log(`advisers ui (read-only): ${url}`)
|
|
2495
|
+
console.log('Ctrl-C to stop; no writes, no telemetry, 127.0.0.1 only.')
|
|
2496
|
+
await new Promise((resolve) => process.once('SIGINT', resolve))
|
|
2497
|
+
await app.close()
|
|
2498
|
+
}
|
|
2499
|
+
|
|
2500
|
+
async function remind(args) {
|
|
2501
|
+
const { flags, positional } = parseFlags(args)
|
|
2502
|
+
ensureHome()
|
|
2503
|
+
const store = dbStore()
|
|
2504
|
+
const ledger = loadLedger()
|
|
2505
|
+
const scheduler = await loadScheduler()
|
|
2506
|
+
const sub = positional[0]
|
|
2507
|
+
const apply = flags.apply === true
|
|
2508
|
+
if (sub === 'install' || flags.install) {
|
|
2509
|
+
const dir = join(HOME, 'scheduler')
|
|
2510
|
+
mkdirSync(dir, { recursive: true, mode: 0o700 })
|
|
2511
|
+
const nodeBin = process.execPath
|
|
2512
|
+
const cli = process.argv[1]
|
|
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 })
|
|
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')
|
|
2516
|
+
store?.appendAudit({ actor: 'local', action: 'notify.install', allowed: true, reason: dir })
|
|
2517
|
+
console.log('scheduler scripts written: ' + dir)
|
|
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 })
|
|
2535
|
+
return
|
|
2536
|
+
}
|
|
2537
|
+
if (sub === 'uninstall' || flags.uninstall) {
|
|
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 })
|
|
2547
|
+
if (existsSync(dir)) rmSync(dir, { recursive: true, force: true })
|
|
2548
|
+
store?.appendAudit({ actor: 'local', action: 'notify.uninstall', allowed: true, reason: dir })
|
|
2549
|
+
console.log('scheduler scripts removed (calendar events remain in your calendar app).')
|
|
2550
|
+
return
|
|
2551
|
+
}
|
|
2552
|
+
if (sub === 'status' || flags.status) {
|
|
2553
|
+
const dir = join(HOME, 'scheduler')
|
|
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
|
+
}
|
|
2573
|
+
return
|
|
2574
|
+
}
|
|
2575
|
+
const { buildReminders, toIcs } = await loadRemind()
|
|
2576
|
+
const snoozed = {}
|
|
2577
|
+
for (const c of ledger.listCommitments()) {
|
|
2578
|
+
const until = store?.getMeta('snooze:' + c.id)
|
|
2579
|
+
if (until) snoozed[c.id] = until
|
|
2580
|
+
}
|
|
2581
|
+
const reminders = buildReminders(ledger, { now: new Date(), snoozedUntil: snoozed })
|
|
2582
|
+
if (flags.ics) {
|
|
2583
|
+
const path = typeof flags.ics === 'string' ? flags.ics : (positional[0] || join(HOME, 'reminders.ics'))
|
|
2584
|
+
writeFileSync(path, toIcs(reminders, { now: new Date() }), { mode: 0o600 })
|
|
2585
|
+
store?.appendAudit({ actor: 'local', action: 'notify.ics', allowed: true, reason: basename(path) })
|
|
2586
|
+
console.log('ics written: ' + path + ' (' + reminders.length + ' events)')
|
|
2587
|
+
return
|
|
2588
|
+
}
|
|
2589
|
+
if (flags.json) { console.log(JSON.stringify({ now: new Date().toISOString(), reminders }, null, 2)); return }
|
|
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) : ''))
|
|
2596
|
+
if (flags.deliver) {
|
|
2597
|
+
const line = new Date().toISOString() + '\t' + reminders.length + '\t' + reminders.map((r) => r.action).join(';') + '\n'
|
|
2598
|
+
writeFileSync(join(HOME, 'reminders.log'), line, { flag: 'a', mode: 0o600 })
|
|
2599
|
+
let channel = 'log'
|
|
2600
|
+
if (flags.notify) {
|
|
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
|
+
}
|
|
2667
|
+
}
|
|
2668
|
+
return { applied: false, results: [] }
|
|
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 }
|
|
2682
|
+
}
|
|
2683
|
+
|
|
2684
|
+
async function deliver(args) {
|
|
2685
|
+
const { flags, positional } = parseFlags(args)
|
|
2686
|
+
const type = String(flags.type ?? 'confirmation')
|
|
2687
|
+
const format = String(flags.format ?? (type === 'ledger' ? 'xlsx' : 'docx'))
|
|
2688
|
+
const out = flags.out ? String(flags.out) : join(process.cwd(), `${type}-${new Date().toISOString().slice(0, 10)}.${format}`)
|
|
2689
|
+
ensureHome()
|
|
2690
|
+
const store = dbStore()
|
|
2691
|
+
const ledger = loadLedger()
|
|
2692
|
+
const denied = egressDeniedReason(ledger.getMatter(activeMatterId(ledger)), 'deliver')
|
|
2693
|
+
if (denied) { console.error(denied); process.exitCode = 1; return }
|
|
2694
|
+
let commitments
|
|
2695
|
+
if (flags.commit) {
|
|
2696
|
+
const c = ledger.getCommitment?.(String(flags.commit)) ?? ledger.listCommitments().find((x) => x.id === String(flags.commit))
|
|
2697
|
+
if (!c) { console.error(`unknown commitment: ${flags.commit}`); process.exitCode = 1; return }
|
|
2698
|
+
commitments = [c]
|
|
2699
|
+
} else commitments = ledger.openCommitments()
|
|
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()
|
|
2710
|
+
const label = type === 'weekly' ? '周报' : type === 'statement' ? '对账单' : '确认单'
|
|
2711
|
+
const scopeLine = truncated
|
|
2712
|
+
? `承诺数:${totalOpen}(本文件只列前 ${commitments.length} 条;用 --all 生成全部)`
|
|
2713
|
+
: `承诺数:${commitments.length}`
|
|
2714
|
+
const sections = [{ heading: label, paragraphs: [`生成时间:${new Date().toISOString()}`, scopeLine] }]
|
|
2715
|
+
for (const c of commitments) {
|
|
2716
|
+
sections.push({ heading: c.action, paragraphs: [`对象:${c.creditor}`, `截止:${c.dueAt ?? '未定'}`, `状态:${c.status}`, `证据:${(c.evidence ?? []).length} 条`] })
|
|
2717
|
+
}
|
|
2718
|
+
sections.push({ heading: '校验', paragraphs: [`内容哈希:${sha256Hex(JSON.stringify(commitments.map((c) => ({ id: c.id, action: c.action, dueAt: c.dueAt, evidence: c.evidence }))))}`, '本文件由本地账本生成;哈希用于事后比对,不是第三方存证。'] })
|
|
2719
|
+
try {
|
|
2720
|
+
const mod = process.env.ADVISERS_OFFICE_LOCAL === '1' ? await import('../../office/dist/index.js') : await import('advisers-office')
|
|
2721
|
+
let buffer
|
|
2722
|
+
if (format === 'pdf') {
|
|
2723
|
+
const { buildSimplePdf } = await loadPdf()
|
|
2724
|
+
const lines = commitments.map((c) => `${c.id} ${c.creditor} · ${c.action}${c.dueAt ? ` · 截止 ${c.dueAt}` : ''} · ${c.status}`)
|
|
2725
|
+
buffer = await buildSimplePdf({ title: `${label} · Advisers`, paragraphs: [`承诺数:${commitments.length}`, ...lines, 'SHA256SUMS/回执说明:本 PDF 为本地账本生成,不是第三方存证。'] })
|
|
2726
|
+
if (!buffer.subarray(0, 5).equals(Buffer.from('%PDF-'))) throw new Error('pdf builder returned a non-PDF buffer')
|
|
2727
|
+
await backupCliFile(out)
|
|
2728
|
+
writeFileSync(out, buffer)
|
|
2729
|
+
} else if (format === 'xlsx') {
|
|
2730
|
+
const rows = commitments.map((c) => ({
|
|
2731
|
+
id: c.id, creditor: c.creditor, action: c.action, due: c.dueAt ?? '',
|
|
2732
|
+
status: c.status, evidence: (c.evidence ?? []).length,
|
|
2733
|
+
source: (c.evidence ?? []).map((e) => e.source?.type ? `${e.source.type}:${e.source.messageId ?? e.source.file ?? e.source.uid ?? ''}` : (e.sessionId ? `${e.sessionId}#${e.turnId}` : 'legacy')).join('; '),
|
|
2734
|
+
}))
|
|
2735
|
+
buffer = await mod.buildXlsx({ sheet: label, columns: [
|
|
2736
|
+
{ header: 'ID', key: 'id', width: 22 }, { header: '对象', key: 'creditor', width: 16 },
|
|
2737
|
+
{ header: '事项', key: 'action', width: 32 }, { header: '截止', key: 'due', width: 26 },
|
|
2738
|
+
{ header: '状态', key: 'status', width: 10 }, { header: '证据数', key: 'evidence', width: 8 },
|
|
2739
|
+
{ header: '来源', key: 'source', width: 40 },
|
|
2740
|
+
], rows })
|
|
2741
|
+
await mod.validateOffice(buffer, 'xlsx')
|
|
2742
|
+
await backupCliFile(out)
|
|
2743
|
+
writeFileSync(out, buffer)
|
|
2744
|
+
} else {
|
|
2745
|
+
buffer = await mod.buildDocx({ title: `${label} · Advisers`, sections })
|
|
2746
|
+
await mod.validateOffice(buffer, 'docx')
|
|
2747
|
+
await backupCliFile(out)
|
|
2748
|
+
writeFileSync(out, buffer)
|
|
2749
|
+
}
|
|
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
|
+
}
|
|
2763
|
+
} catch (error) { console.error(`deliver failed: ${error.message}`); process.exitCode = 1 }
|
|
2764
|
+
}
|
|
2765
|
+
|
|
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
|
+
*/
|
|
2776
|
+
async function mcpServer() {
|
|
2777
|
+
ensureHome()
|
|
2778
|
+
const store = dbStore()
|
|
2779
|
+
const ledger = loadLedger()
|
|
2780
|
+
const { createMcpServer } = await loadMcpServer()
|
|
2781
|
+
const server = createMcpServer({
|
|
2782
|
+
store,
|
|
2783
|
+
ledger,
|
|
2784
|
+
version: VERSION,
|
|
2785
|
+
audit: (entry) => store?.appendAudit(entry),
|
|
2786
|
+
})
|
|
2787
|
+
await server.serve(process.stdin, process.stdout)
|
|
2788
|
+
}
|
|
2789
|
+
|
|
2790
|
+
async function ocrCommand(args) {
|
|
2791
|
+
const file = args.find((a) => !a.startsWith('--'))
|
|
2792
|
+
if (!file) { console.error('usage: advisers ocr <image> [--out text]'); process.exitCode = 1; return }
|
|
2793
|
+
try {
|
|
2794
|
+
const { runLocalOcr } = await loadOcr()
|
|
2795
|
+
const text = await runLocalOcr(file)
|
|
2796
|
+
const outIdx = args.indexOf('--out')
|
|
2797
|
+
if (outIdx >= 0 && args[outIdx + 1]) {
|
|
2798
|
+
writeFileSync(args[outIdx + 1], text + '\n', { mode: 0o600 })
|
|
2799
|
+
dbStore()?.appendAudit({ actor: 'local', action: 'ocr.local', allowed: true, reason: basename(args[outIdx + 1]) })
|
|
2800
|
+
console.log(`wrote ${args[outIdx + 1]} (${text.length} chars)`)
|
|
2801
|
+
} else {
|
|
2802
|
+
dbStore()?.appendAudit({ actor: 'local', action: 'ocr.local', allowed: true, reason: basename(file) })
|
|
2803
|
+
console.log(text)
|
|
2804
|
+
}
|
|
2805
|
+
} catch (error) { console.error(`ocr failed: ${error.message}`); process.exitCode = 1 }
|
|
2806
|
+
}
|
|
2807
|
+
|
|
2808
|
+
function vaultPass() {
|
|
2809
|
+
const pass = process.env.ADVISERS_VAULT_PASSPHRASE
|
|
2810
|
+
if (!pass || pass.length < 8) { console.error('vault requires ADVISERS_VAULT_PASSPHRASE (min 8 chars)'); process.exitCode = 1; return null }
|
|
2811
|
+
return pass
|
|
2812
|
+
}
|
|
2813
|
+
|
|
2814
|
+
async function vaultSeal(args) {
|
|
2815
|
+
const { flags } = parseFlags(args)
|
|
2816
|
+
ensureHome()
|
|
2817
|
+
if (!existsSync(DB)) { console.error(`no database at ${DB}`); process.exitCode = 1; return }
|
|
2818
|
+
const pass = vaultPass(); if (!pass) return
|
|
2819
|
+
const { encryptJson, decryptJson } = await loadVault()
|
|
2820
|
+
const removePlaintext = Boolean(flags.remove) || args.includes('--remove')
|
|
2821
|
+
try {
|
|
2822
|
+
const store = new SqliteStore(DB)
|
|
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
|
+
}
|
|
2834
|
+
} catch (error) { console.error(`vault seal failed: ${error.message}`); process.exitCode = 1; return }
|
|
2835
|
+
try {
|
|
2836
|
+
const bytes = readFileSync(DB)
|
|
2837
|
+
const sha = createHash('sha256').update(bytes).digest('hex')
|
|
2838
|
+
const envelope = encryptJson({ kind: 'advisers-db', version: VERSION, sha256: sha, db: bytes.toString('base64') }, pass)
|
|
2839
|
+
const out = typeof flags.out === 'string' ? flags.out : `${DB}.vault`
|
|
2840
|
+
atomicWriteFileSync(out, JSON.stringify(envelope) + '\n', { mode: 0o600 })
|
|
2841
|
+
const check = decryptJson(JSON.parse(readFileSync(out, 'utf8')), pass)
|
|
2842
|
+
if (check.sha256 !== sha) throw new Error('sealed file verification failed')
|
|
2843
|
+
if (removePlaintext) {
|
|
2844
|
+
for (const f of [DB, `${DB}-wal`, `${DB}-shm`]) { try { if (existsSync(f)) rmSync(f) } catch {} }
|
|
2845
|
+
fsyncDir(HOME)
|
|
2846
|
+
}
|
|
2847
|
+
console.log(`sealed ${DB} -> ${out}${removePlaintext ? ' (plaintext removed)' : ' (plaintext kept; pass --remove)'}`)
|
|
2848
|
+
} catch (error) { console.error(`vault seal failed: ${error.message}`); process.exitCode = 1 }
|
|
2849
|
+
}
|
|
2850
|
+
|
|
2851
|
+
async function vaultUnseal(args) {
|
|
2852
|
+
const file = args.find((a) => !a.startsWith('--')) || `${DB}.vault`
|
|
2853
|
+
if (!existsSync(file)) { console.error(`no sealed database at ${file}`); process.exitCode = 1; return }
|
|
2854
|
+
const pass = vaultPass(); if (!pass) return
|
|
2855
|
+
let bytes
|
|
2856
|
+
try {
|
|
2857
|
+
const { decryptJson } = await loadVault()
|
|
2858
|
+
const payload = decryptJson(JSON.parse(readFileSync(file, 'utf8')), pass)
|
|
2859
|
+
if (payload.kind !== 'advisers-db' || typeof payload.db !== 'string') throw new Error('not an Advisers database vault')
|
|
2860
|
+
bytes = Buffer.from(payload.db, 'base64')
|
|
2861
|
+
const sha = createHash('sha256').update(bytes).digest('hex')
|
|
2862
|
+
if (sha !== payload.sha256) throw new Error('vault checksum mismatch')
|
|
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)
|
|
2895
|
+
try { chmodSync(DB, 0o600) } catch {}
|
|
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
|
+
}
|
|
2905
|
+
}
|
|
2906
|
+
|
|
2907
|
+
function vaultStatus() {
|
|
2908
|
+
ensureHome()
|
|
2909
|
+
const sealed = `${DB}.vault`
|
|
2910
|
+
console.log(`database: ${existsSync(DB) ? DB : 'absent'}`)
|
|
2911
|
+
console.log(`sealed: ${existsSync(sealed) ? sealed : 'none'}`)
|
|
2912
|
+
console.log(`state: ${existsSync(DB) ? 'plaintext at rest' : existsSync(sealed) ? 'encrypted at rest (run vault unseal)' : 'empty'}`)
|
|
2913
|
+
}
|
|
2914
|
+
|
|
2915
|
+
async function timestampCommand(args) {
|
|
2916
|
+
const file = args.find((a) => !a.startsWith('--'))
|
|
2917
|
+
if (!file) { console.error('usage: advisers timestamp <file> [--out proof]'); process.exitCode = 1; return }
|
|
2918
|
+
try {
|
|
2919
|
+
const { runLocalTimestamp } = await loadTimestamp()
|
|
2920
|
+
const proof = await runLocalTimestamp(file)
|
|
2921
|
+
const outIdx = args.indexOf('--out')
|
|
2922
|
+
if (outIdx >= 0 && args[outIdx + 1]) {
|
|
2923
|
+
writeFileSync(args[outIdx + 1], proof + '\n', { mode: 0o600 })
|
|
2924
|
+
dbStore()?.appendAudit({ actor: 'local', action: 'timestamp.local', allowed: true, reason: basename(args[outIdx + 1]) })
|
|
2925
|
+
console.log(`wrote ${args[outIdx + 1]}`)
|
|
2926
|
+
} else { console.log(proof) }
|
|
2927
|
+
} catch (error) { console.error(`timestamp failed: ${error.message}`); process.exitCode = 1 }
|
|
2928
|
+
}
|
|
2929
|
+
|
|
2930
|
+
async function tui(args) {
|
|
2931
|
+
const once = args.includes('--once')
|
|
2932
|
+
const { buildReminders } = await loadRemind()
|
|
2933
|
+
const render = () => {
|
|
2934
|
+
const ledger = loadLedger()
|
|
2935
|
+
const store = dbStore()
|
|
2936
|
+
const open = ledger.openCommitments()
|
|
2937
|
+
const localDay = localDayOf(Date.now())
|
|
2938
|
+
const due = open.filter((c) => c.dueAt && c.dueAt.slice(0, 10) <= localDay)
|
|
2939
|
+
const reminders = buildReminders(ledger, { now: new Date() })
|
|
2940
|
+
const deliveries = store?.listDeliveries(3) ?? []
|
|
2941
|
+
const lines = [
|
|
2942
|
+
'Advisers TUI (read-only)',
|
|
2943
|
+
`today ${localDay} · open ${open.length} · due ${due.length} · reminders ${reminders.length}`,
|
|
2944
|
+
'',
|
|
2945
|
+
'reminders:',
|
|
2946
|
+
...(reminders.length ? reminders.slice(0, 8).map((r) => ` [${r.level}/${r.bucket}] ${r.action}${r.dueAt ? ` · ${r.dueAt.slice(0, 16)}` : ''}`) : [' (none)']),
|
|
2947
|
+
'',
|
|
2948
|
+
'open commitments:',
|
|
2949
|
+
...(open.length ? open.slice(0, 8).map((c) => ` ${c.id} ${c.creditor} · ${c.action}${c.dueAt ? ` · ${c.dueAt.slice(0, 10)}` : ''}`) : [' (none)']),
|
|
2950
|
+
'',
|
|
2951
|
+
'recent deliveries:',
|
|
2952
|
+
...(deliveries.length ? deliveries.map((d) => ` ${d.createdAt.slice(0, 16)} ${d.title ?? d.tool ?? d.id}`) : [' (none)']),
|
|
2953
|
+
]
|
|
2954
|
+
return lines.join(String.fromCharCode(10))
|
|
2955
|
+
}
|
|
2956
|
+
if (once) { console.log(render()); return }
|
|
2957
|
+
const readline = await import('node:readline')
|
|
2958
|
+
const rl = readline.createInterface({ input: process.stdin, output: process.stdout })
|
|
2959
|
+
const draw = () => { process.stdout.write('\x1b[2J\x1b[H' + render() + '\n\n[r] refresh [q] quit\n') }
|
|
2960
|
+
draw()
|
|
2961
|
+
await new Promise((resolve) => {
|
|
2962
|
+
const onKey = (str, key) => {
|
|
2963
|
+
if (key?.name === 'q' || str === 'q') { rl.close(); resolve() }
|
|
2964
|
+
else if (key?.name === 'r' || str === 'r') draw()
|
|
2965
|
+
}
|
|
2966
|
+
process.stdin.on('keypress', onKey)
|
|
2967
|
+
rl.on('close', resolve)
|
|
2968
|
+
})
|
|
2969
|
+
}
|
|
2970
|
+
|
|
2971
|
+
function syncPass() {
|
|
2972
|
+
const pass = process.env.ADVISERS_SYNC_PASSPHRASE
|
|
2973
|
+
if (!pass || pass.length < 8) { console.error('sync requires ADVISERS_SYNC_PASSPHRASE (min 8 chars)'); process.exitCode = 1; return null }
|
|
2974
|
+
return pass
|
|
2975
|
+
}
|
|
2976
|
+
|
|
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) {
|
|
3021
|
+
const { flags, positional } = parseFlags(args)
|
|
3022
|
+
const sub = positional[0]
|
|
3023
|
+
const dir = typeof flags.dir === 'string' ? flags.dir : undefined
|
|
3024
|
+
if (!dir) { console.error('usage: advisers sync push|pull|status --dir <sync-dir>'); process.exitCode = 1; return }
|
|
3025
|
+
if (sub === 'status') {
|
|
3026
|
+
const { listSnapshots } = await loadSync()
|
|
3027
|
+
const snaps = listSnapshots(dir)
|
|
3028
|
+
if (flags.json) { console.log(JSON.stringify(snaps, null, 2)); return }
|
|
3029
|
+
console.log(`sync dir: ${dir}`)
|
|
3030
|
+
if (!snaps.length) { console.log('no snapshots'); return }
|
|
3031
|
+
for (const s of snaps.slice(0, 10)) console.log(` ${s.name} ${(s.bytes / 1024).toFixed(1)} KB ${new Date(s.mtimeMs).toISOString()}`)
|
|
3032
|
+
return
|
|
3033
|
+
}
|
|
3034
|
+
const pass = syncPass(); if (!pass) return
|
|
3035
|
+
ensureHome()
|
|
3036
|
+
if (sub === 'push') {
|
|
3037
|
+
if (!existsSync(DB)) { console.error(`no database at ${DB}`); process.exitCode = 1; return }
|
|
3038
|
+
const device = typeof flags.device === 'string' ? flags.device : hostname()
|
|
3039
|
+
try {
|
|
3040
|
+
const store = new SqliteStore(DB)
|
|
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)
|
|
3053
|
+
console.log(`pushed ${result.file}`)
|
|
3054
|
+
console.log(`sha256 ${result.sha256}`)
|
|
3055
|
+
} catch (error) { console.error(`sync push failed: ${error.message}`); process.exitCode = 1 }
|
|
3056
|
+
} else if (sub === 'pull') {
|
|
3057
|
+
const force = Boolean(flags.force)
|
|
3058
|
+
try {
|
|
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
|
+
})
|
|
3076
|
+
if (!result.changed) console.log('local database already matches the latest snapshot')
|
|
3077
|
+
else console.log(`pulled ${result.file} (${result.sha256})${result.backup ? `; backup ${result.backup}` : ''}`)
|
|
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
|
+
}
|
|
3082
|
+
} catch (error) { console.error(`sync pull failed: ${error.message}`); process.exitCode = 1 }
|
|
3083
|
+
} else { console.error('usage: advisers sync push|pull|status --dir <sync-dir>'); process.exitCode = 1 }
|
|
3084
|
+
}
|
|
3085
|
+
|
|
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) {
|
|
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
|
+
}
|
|
3111
|
+
ensureHome()
|
|
3112
|
+
const store = dbStore()
|
|
3113
|
+
const ledger = loadLedger()
|
|
3114
|
+
const id = positional[1] || positional[0]
|
|
3115
|
+
if (!id) { console.error('usage: advisers evidence show <id> [--json]'); process.exitCode = 1; return }
|
|
3116
|
+
let result
|
|
3117
|
+
try {
|
|
3118
|
+
const { evidenceForCommitment, evidenceForFact, evidenceForPreference } = await loadEvidence()
|
|
3119
|
+
if (id.startsWith('cm_')) result = evidenceForCommitment(store, ledger, id)
|
|
3120
|
+
else if (id.startsWith('fact_')) result = evidenceForFact(store, ledger, id)
|
|
3121
|
+
else if (id.startsWith('pref_')) result = evidenceForPreference(store, ledger, id)
|
|
3122
|
+
else { console.error('unknown evidence id prefix (want cm_/fact_/pref_)'); process.exitCode = 1; return }
|
|
3123
|
+
} catch (error) { console.error(error.message); process.exitCode = 1; return }
|
|
3124
|
+
if (!result || (!result.commitment && !result.fact && !result.preference)) { console.error(`not found: ${id}`); process.exitCode = 1; return }
|
|
3125
|
+
await normalizeEvidenceSources(result)
|
|
3126
|
+
if (flags.json) { console.log(JSON.stringify(result, null, 2)); return }
|
|
3127
|
+
const label = result.commitment ? `${result.commitment.action}` : result.fact ? `${result.fact.subject} ${result.fact.predicate}` : result.preference?.statement
|
|
3128
|
+
console.log(`${id} ${label ?? ''}`)
|
|
3129
|
+
if (!result.sources.length) console.log(' (没有可回溯来源)')
|
|
3130
|
+
for (const s of result.sources) console.log(` ${s.sessionId}#${s.turnId} 「${(s.quote ?? '').slice(0, 120)}」`)
|
|
3131
|
+
for (const m of result.missing) console.log(` MISSING ${m.reason}${m.ref ? ` ${m.ref}` : ''}`)
|
|
3132
|
+
}
|
|
3133
|
+
|
|
3134
|
+
async function evidencePack(args) {
|
|
3135
|
+
const { flags, positional } = parseFlags(args)
|
|
3136
|
+
ensureHome()
|
|
3137
|
+
const store = dbStore()
|
|
3138
|
+
const ledger = loadLedger()
|
|
3139
|
+
const denied = egressDeniedReason(ledger.getMatter(activeMatterId(ledger)), 'evidence')
|
|
3140
|
+
if (denied) { console.error(denied); process.exitCode = 1; return }
|
|
3141
|
+
const ids = flags.ids ? String(flags.ids).split(',').map((s) => s.trim()).filter(Boolean) : undefined
|
|
3142
|
+
if (ids?.length === 0) { console.error('--ids is empty'); process.exitCode = 1; return }
|
|
3143
|
+
const targetIds = ids ?? {
|
|
3144
|
+
commitments: ledger.listCommitments().map((c) => c.id),
|
|
3145
|
+
facts: ledger.listFacts().map((f) => f.id),
|
|
3146
|
+
preferences: ledger.listPreferences({ includeCandidates: false }).map((p) => p.id),
|
|
3147
|
+
}
|
|
3148
|
+
const { buildEvidencePack, toDocxRows, verifyPack } = await loadEvidence()
|
|
3149
|
+
const pack = buildEvidencePack({ store, ledger, ids: targetIds })
|
|
3150
|
+
const out = flags.out ? String(flags.out) : join(HOME, 'evidence', `evidence-${new Date().toISOString().replace(/[:.]/g, '-')}`)
|
|
3151
|
+
mkdirSync(out, { recursive: true, mode: 0o700 })
|
|
3152
|
+
for (const [name, content] of Object.entries(pack.files)) writeFileSync(join(out, name), content, { mode: 0o600 })
|
|
3153
|
+
let receipt
|
|
3154
|
+
try {
|
|
3155
|
+
const mod = process.env.ADVISERS_OFFICE_LOCAL === '1' ? await import('../../office/dist/index.js') : await import('advisers-office')
|
|
3156
|
+
const rows = toDocxRows(pack, { maxRows: 80 })
|
|
3157
|
+
const buffer = await mod.buildDocx({ title: '证据包回执', sections: [{ heading: '证据清单', paragraphs: rows.length ? rows : ['(没有可导出条目)'] }, { heading: '校验', paragraphs: [`manifest.json / README.txt 的 SHA256 见 SHA256SUMS`, `生成时间:${new Date().toISOString()}`, 'SHA256SUMS 只证明包生成后未被修改;不是签名或第三方存证。'] }] })
|
|
3158
|
+
await mod.validateOffice(buffer, 'docx')
|
|
3159
|
+
writeFileSync(join(out, 'receipt.docx'), buffer)
|
|
3160
|
+
receipt = join(out, 'receipt.docx')
|
|
3161
|
+
} catch (error) { console.error(`docx receipt skipped: ${error.message}`) }
|
|
3162
|
+
const verification = verifyPack(pack.files)
|
|
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
|
+
})
|
|
3171
|
+
console.log(JSON.stringify({ out, files: Object.keys(pack.files), receipt, verification }, null, 2))
|
|
3172
|
+
if (!verification.ok) process.exitCode = 1
|
|
3173
|
+
}
|
|
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
|
|
96
3200
|
}
|
|
97
3201
|
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
const ledger = loadLedger()
|
|
105
|
-
const runtime = runtimeFor(ledger)
|
|
106
|
-
const context = runtime.handleInbound({
|
|
107
|
-
linkId: 'cli',
|
|
108
|
-
accountId: 'local',
|
|
109
|
-
conversationId: 'cli',
|
|
110
|
-
messageId: `cli_${Date.now()}`,
|
|
111
|
-
sender: { id: 'local' },
|
|
112
|
-
text,
|
|
113
|
-
timestamp: now(),
|
|
114
|
-
})
|
|
115
|
-
saveLedger(ledger)
|
|
116
|
-
console.log(`[thread] ${context.threadId}`)
|
|
117
|
-
console.log(context.prompt)
|
|
118
|
-
if (context.hints.length) {
|
|
119
|
-
console.log('\nhints:')
|
|
120
|
-
for (const hint of context.hints) console.log(`- ${hint.title}: ${hint.why}`)
|
|
121
|
-
}
|
|
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]
|
|
122
3208
|
}
|
|
123
3209
|
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
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 })
|
|
129
3220
|
}
|
|
130
|
-
|
|
131
|
-
|
|
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
|
+
}
|
|
132
3234
|
}
|
|
3235
|
+
return results
|
|
133
3236
|
}
|
|
134
3237
|
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
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`。')
|
|
138
3263
|
process.exitCode = 1
|
|
139
3264
|
return
|
|
140
3265
|
}
|
|
141
|
-
const
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
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
|
+
})
|
|
146
3285
|
}
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
console.log(`confidence: ${pref.confidence}; status: ${pref.status}`)
|
|
151
|
-
}
|
|
152
|
-
|
|
153
|
-
function forget(id) {
|
|
154
|
-
if (!id) {
|
|
155
|
-
console.error('usage: advisers forget <pref-id>')
|
|
3286
|
+
if (!deliveries.length) {
|
|
3287
|
+
console.error('没有仍存在的交付文件,无法生成回执包(文件可能已被移动或删除)。')
|
|
3288
|
+
if (skippedFiles.length) console.error('缺失:' + skippedFiles.slice(0, 5).join('; '))
|
|
156
3289
|
process.exitCode = 1
|
|
157
3290
|
return
|
|
158
3291
|
}
|
|
159
|
-
|
|
160
|
-
const ok = ledger.forget('preference', id)
|
|
161
|
-
saveLedger(ledger)
|
|
162
|
-
console.log(ok ? `forgotten: ${id}` : `unknown preference: ${id}`)
|
|
163
|
-
if (!ok) process.exitCode = 1
|
|
164
|
-
}
|
|
165
|
-
|
|
166
|
-
function exportLedger() {
|
|
167
|
-
console.log(JSON.stringify(loadLedger().toJSON(), null, 2))
|
|
168
|
-
}
|
|
3292
|
+
if (skippedFiles.length) console.error('注意:' + skippedFiles.length + ' 个交付文件缺失,已跳过(回执只覆盖仍存在的文件)。')
|
|
169
3293
|
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
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))
|
|
173
3342
|
process.exitCode = 1
|
|
174
3343
|
return
|
|
175
3344
|
}
|
|
176
|
-
const
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
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
|
|
180
3381
|
}
|
|
181
3382
|
|
|
182
|
-
function
|
|
3383
|
+
function link(sub, from, to, type) {
|
|
183
3384
|
const ledger = loadLedger()
|
|
184
|
-
if (typeof ledger.addRoutine !== 'function') {
|
|
185
|
-
console.error('routine requires advisers-core@0.1.0-preview.3 or newer')
|
|
186
|
-
process.exitCode = 1
|
|
187
|
-
return
|
|
188
|
-
}
|
|
189
3385
|
if (sub === 'ls' || !sub) {
|
|
190
|
-
const rows = ledger.
|
|
3386
|
+
const rows = ledger.listLinks()
|
|
191
3387
|
if (!rows.length) {
|
|
192
|
-
console.log('no
|
|
3388
|
+
console.log('no links yet')
|
|
193
3389
|
return
|
|
194
3390
|
}
|
|
195
|
-
for (const
|
|
3391
|
+
for (const l of rows) console.log(`${l.id}\t${l.status}\t${l.fromMatter} -[${l.type}]-> ${l.toMatter}`)
|
|
196
3392
|
return
|
|
197
3393
|
}
|
|
198
3394
|
if (sub === 'add') {
|
|
199
|
-
if (!
|
|
200
|
-
console.error('usage: advisers
|
|
3395
|
+
if (!from || !to || !type) {
|
|
3396
|
+
console.error('usage: advisers link add <from-matter> <to-matter> <type>')
|
|
201
3397
|
process.exitCode = 1
|
|
202
3398
|
return
|
|
203
3399
|
}
|
|
204
|
-
const
|
|
205
|
-
const routine = ledger.addRoutine({
|
|
206
|
-
name: spec.name,
|
|
207
|
-
description: spec.description ?? '',
|
|
208
|
-
trigger: spec.trigger ?? [],
|
|
209
|
-
steps: spec.steps ?? [],
|
|
210
|
-
preferences: spec.preferences ?? [],
|
|
211
|
-
pitfalls: spec.pitfalls ?? [],
|
|
212
|
-
verification: spec.verification ?? [],
|
|
213
|
-
scope: spec.scope,
|
|
214
|
-
createdBy: spec.createdBy ?? 'user',
|
|
215
|
-
})
|
|
3400
|
+
const l = ledger.proposeLink({ fromMatter: from, toMatter: to, type })
|
|
216
3401
|
saveLedger(ledger)
|
|
217
|
-
console.log(`
|
|
3402
|
+
console.log(`link ${l.id} (${l.status}); confirm with \`advisers link confirm ${l.id}\``)
|
|
218
3403
|
return
|
|
219
3404
|
}
|
|
220
|
-
if (sub === '
|
|
221
|
-
if (!
|
|
222
|
-
console.error(
|
|
3405
|
+
if (sub === 'confirm') {
|
|
3406
|
+
if (!from) {
|
|
3407
|
+
console.error('usage: advisers link confirm <id>')
|
|
223
3408
|
process.exitCode = 1
|
|
224
3409
|
return
|
|
225
3410
|
}
|
|
226
|
-
const
|
|
3411
|
+
const l = ledger.confirmLink(from)
|
|
227
3412
|
saveLedger(ledger)
|
|
228
|
-
console.log(
|
|
3413
|
+
console.log(`confirmed: ${l.id}`)
|
|
229
3414
|
return
|
|
230
3415
|
}
|
|
231
|
-
|
|
3416
|
+
if (sub === 'suggest') {
|
|
3417
|
+
if (!from) { console.error('usage: advisers link suggest <matter-id>'); process.exitCode = 1; return }
|
|
3418
|
+
const source = ledger.getMatter(from)
|
|
3419
|
+
if (!source) { console.error(`unknown matter: ${from}`); process.exitCode = 1; return }
|
|
3420
|
+
const base = tokenize(`${source.title} ${source.summary ?? ''}`)
|
|
3421
|
+
let count = 0
|
|
3422
|
+
for (const other of ledger.listMatters()) {
|
|
3423
|
+
if (other.id === source.id) continue
|
|
3424
|
+
if (ledger.listLinks(source.id, false).some((l) => (l.fromMatter === other.id || l.toMatter === other.id))) continue
|
|
3425
|
+
const tokens = tokenize(`${other.title} ${other.summary ?? ''}`)
|
|
3426
|
+
let shared = 0
|
|
3427
|
+
for (const t of base) if (tokens.has(t)) shared++
|
|
3428
|
+
const score = shared / Math.max(1, base.size + tokens.size - shared)
|
|
3429
|
+
if (score < 0.18) continue
|
|
3430
|
+
const link = ledger.proposeLink({ fromMatter: source.id, toMatter: other.id, type: 'similar', confidence: Math.min(0.7, score), evidence: [`shared terms: ${shared}`] })
|
|
3431
|
+
console.log(`${link.id}\t${link.confidence.toFixed(2)}\t${other.title}`)
|
|
3432
|
+
count++
|
|
3433
|
+
}
|
|
3434
|
+
saveLedger(ledger)
|
|
3435
|
+
if (!count) console.log('no suggestions')
|
|
3436
|
+
return
|
|
3437
|
+
}
|
|
3438
|
+
if (sub === 'diff') {
|
|
3439
|
+
if (!from) { console.error('usage: advisers link diff <update-id>'); process.exitCode = 1; return }
|
|
3440
|
+
const u = ledger.listUpdates().find((x) => x.id === from)
|
|
3441
|
+
if (!u) { console.error(`unknown update: ${from}`); process.exitCode = 1; return }
|
|
3442
|
+
console.log(`${u.id}\t${u.status}`)
|
|
3443
|
+
console.log(`${u.sourceMatter} -> ${u.targetMatter}`)
|
|
3444
|
+
console.log(`change: ${u.change}`)
|
|
3445
|
+
if (u.rollback) console.log(`rollback: ${u.rollback}`)
|
|
3446
|
+
return
|
|
3447
|
+
}
|
|
3448
|
+
if (sub === 'updates') {
|
|
3449
|
+
const rows = ledger.listUpdates()
|
|
3450
|
+
if (!rows.length) { console.log('no update proposals'); return }
|
|
3451
|
+
for (const u of rows) console.log(`${u.id}\t${u.status}\t${u.sourceMatter} -> ${u.targetMatter}\t${u.change}${u.rollback?.startsWith('rolledback:') ? ' (rolled back)' : ''}`)
|
|
3452
|
+
return
|
|
3453
|
+
}
|
|
3454
|
+
if (sub === 'propose-update') {
|
|
3455
|
+
if (!from || !to || !type) {
|
|
3456
|
+
console.error('usage: advisers link propose-update <source> <target> <change>')
|
|
3457
|
+
process.exitCode = 1
|
|
3458
|
+
return
|
|
3459
|
+
}
|
|
3460
|
+
const linked = ledger.listLinks(from, false).some((l) => (l.fromMatter === from && l.toMatter === to) || (l.fromMatter === to && l.toMatter === from))
|
|
3461
|
+
if (!linked) {
|
|
3462
|
+
console.error('confirm the matter link first: advisers link add <from> <to> <type>; advisers link confirm <id>')
|
|
3463
|
+
process.exitCode = 1
|
|
3464
|
+
return
|
|
3465
|
+
}
|
|
3466
|
+
const u = ledger.proposeUpdate({ sourceMatter: from, targetMatter: to, change: type })
|
|
3467
|
+
saveLedger(ledger)
|
|
3468
|
+
console.log(`${u.id} pending; apply with \`advisers link apply ${u.id}\``)
|
|
3469
|
+
return
|
|
3470
|
+
}
|
|
3471
|
+
if (sub === 'rollback') {
|
|
3472
|
+
if (!from) { console.error('usage: advisers link rollback <id>'); process.exitCode = 1; return }
|
|
3473
|
+
const proposal = ledger.listUpdates().find((u) => u.id === from)
|
|
3474
|
+
if (!proposal || proposal.status !== 'applied' || !proposal.rollback?.startsWith('fact:')) {
|
|
3475
|
+
console.error(`no applied update with a rollback fact: ${from}`)
|
|
3476
|
+
process.exitCode = 1
|
|
3477
|
+
return
|
|
3478
|
+
}
|
|
3479
|
+
const factId = proposal.rollback.slice(5)
|
|
3480
|
+
const ok = ledger.forget('fact', factId)
|
|
3481
|
+
proposal.rollback = `rolledback:${factId}`
|
|
3482
|
+
saveLedgerWithAudit(ledger, { actor: 'local', action: 'link.rollback', allowed: true, reason: factId })
|
|
3483
|
+
console.log(ok ? `rolled back: ${factId}` : `fact not found: ${factId}`)
|
|
3484
|
+
if (!ok) process.exitCode = 1
|
|
3485
|
+
return
|
|
3486
|
+
}
|
|
3487
|
+
if (sub === 'curate') {
|
|
3488
|
+
const apply = from === '--apply'
|
|
3489
|
+
const now = Date.now()
|
|
3490
|
+
let changed = 0
|
|
3491
|
+
for (const r of ledger.listRoutines().filter((x) => x.status === 'active')) {
|
|
3492
|
+
const idleDays = (now - Date.parse(r.updatedAt)) / 86_400_000
|
|
3493
|
+
if (idleDays >= 90) {
|
|
3494
|
+
console.log(`${r.id}\tarchive candidate\t${Math.floor(idleDays)}d\t${r.name}`)
|
|
3495
|
+
if (apply) { ledger.deprecateRoutine(r.id); changed++ }
|
|
3496
|
+
} else if (idleDays >= 30) {
|
|
3497
|
+
console.log(`${r.id}\tstale\t${Math.floor(idleDays)}d\t${r.name}`)
|
|
3498
|
+
if (apply) { ledger.staleRoutine(r.id); changed++ }
|
|
3499
|
+
}
|
|
3500
|
+
}
|
|
3501
|
+
if (!changed && !apply) console.log('no stale routines (dry-run; use --apply)')
|
|
3502
|
+
if (apply) { saveLedger(ledger); console.log(`curated: ${changed}`) }
|
|
3503
|
+
return
|
|
3504
|
+
}
|
|
3505
|
+
if (sub === 'restore') {
|
|
3506
|
+
if (!from) { console.error('usage: advisers routine restore <id>'); process.exitCode = 1; return }
|
|
3507
|
+
const r = ledger.restoreRoutine(from)
|
|
3508
|
+
saveLedger(ledger)
|
|
3509
|
+
console.log(`restored to draft: ${r.id}`)
|
|
3510
|
+
return
|
|
3511
|
+
}
|
|
3512
|
+
if (sub === 'revert') {
|
|
3513
|
+
if (!from) { console.error('usage: advisers routine revert <patch-id>'); process.exitCode = 1; return }
|
|
3514
|
+
const patch = ledger.revertRoutinePatch(from)
|
|
3515
|
+
saveLedger(ledger)
|
|
3516
|
+
console.log(`rolled_back: ${patch.id}`)
|
|
3517
|
+
return
|
|
3518
|
+
}
|
|
3519
|
+
if (sub === 'apply' || sub === 'reject') {
|
|
3520
|
+
if (!from) {
|
|
3521
|
+
console.error(`usage: advisers link ${sub} <id>`)
|
|
3522
|
+
process.exitCode = 1
|
|
3523
|
+
return
|
|
3524
|
+
}
|
|
3525
|
+
const proposal = ledger.listUpdates().find((u) => u.id === from)
|
|
3526
|
+
if (!proposal || proposal.status !== 'pending') {
|
|
3527
|
+
console.error(`unknown or closed update: ${from}`)
|
|
3528
|
+
process.exitCode = 1
|
|
3529
|
+
return
|
|
3530
|
+
}
|
|
3531
|
+
if (sub === 'reject') {
|
|
3532
|
+
ledger.resolveUpdate(from, 'rejected')
|
|
3533
|
+
saveLedgerWithAudit(ledger, { actor: 'local', action: 'link.reject', allowed: true, reason: from })
|
|
3534
|
+
console.log(`rejected: ${from}`)
|
|
3535
|
+
return
|
|
3536
|
+
}
|
|
3537
|
+
const fact = ledger.remember({
|
|
3538
|
+
matterId: proposal.targetMatter,
|
|
3539
|
+
subject: 'update',
|
|
3540
|
+
predicate: 'from',
|
|
3541
|
+
object: proposal.change,
|
|
3542
|
+
authority: 'user',
|
|
3543
|
+
source: { type: 'import', ref: proposal.id },
|
|
3544
|
+
})
|
|
3545
|
+
ledger.resolveUpdate(from, 'applied', `fact:${fact.id}`)
|
|
3546
|
+
saveLedgerWithAudit(ledger, { actor: 'local', action: 'link.apply', allowed: true, reason: `${from} -> ${fact.id}` })
|
|
3547
|
+
console.log(`applied: ${from} -> target fact ${fact.id}`)
|
|
3548
|
+
return
|
|
3549
|
+
}
|
|
3550
|
+
console.error(`unknown link subcommand: ${sub}`)
|
|
232
3551
|
process.exitCode = 1
|
|
233
3552
|
}
|
|
234
3553
|
|
|
3554
|
+
async function bridge(args) {
|
|
3555
|
+
let dir
|
|
3556
|
+
let name = 'advisers'
|
|
3557
|
+
for (let i = 0; i < args.length; i++) {
|
|
3558
|
+
if (args[i] === '--dir') dir = args[++i]
|
|
3559
|
+
else if (args[i] === '--name') name = args[++i]
|
|
3560
|
+
}
|
|
3561
|
+
dir = dir || process.env.HERMES_BRIDGE_DIR
|
|
3562
|
+
if (!dir) {
|
|
3563
|
+
console.error('usage: advisers bridge --dir <BRIDGE_DIR> [--name advisers]')
|
|
3564
|
+
process.exitCode = 1
|
|
3565
|
+
return
|
|
3566
|
+
}
|
|
3567
|
+
let mod
|
|
3568
|
+
if (process.env.ADVISERS_BRIDGE_LOCAL === '1') {
|
|
3569
|
+
mod = await import('../../bridge-hermes/dist/index.js')
|
|
3570
|
+
} else {
|
|
3571
|
+
try {
|
|
3572
|
+
mod = await import('advisers-bridge-hermes')
|
|
3573
|
+
} catch {
|
|
3574
|
+
console.error('advisers-bridge-hermes is not installed; run `npm i -g advisers-bridge-hermes@next`')
|
|
3575
|
+
process.exitCode = 1
|
|
3576
|
+
return
|
|
3577
|
+
}
|
|
3578
|
+
}
|
|
3579
|
+
const ledger = loadLedger()
|
|
3580
|
+
const runtime = runtimeFor(ledger)
|
|
3581
|
+
const link = new mod.HermesBridgeLink({ bridgeDir: dir, name })
|
|
3582
|
+
const permitSecret = process.env.ADVISERS_PERMIT_SECRET || randomUUID()
|
|
3583
|
+
const permitGate = new core.PermitGate(permitSecret, { replay: dbStore()?.permitReplayStore() })
|
|
3584
|
+
const host = {
|
|
3585
|
+
async ingest(event) {
|
|
3586
|
+
const result = await runtime.ingest(event)
|
|
3587
|
+
if (result.accepted && runtime.lastContext) {
|
|
3588
|
+
const context = runtime.lastContext
|
|
3589
|
+
let reply
|
|
3590
|
+
if (context.crisis && (context.crisis.tier === 'T1' || context.crisis.tier === 'T2' || (context.crisis.tier === 'T3' && context.crisis.thirdParty))) {
|
|
3591
|
+
dbStore()?.appendAudit({ actor: 'bridge', action: 'policy.crisis', allowed: false, reason: context.crisis.tier })
|
|
3592
|
+
reply = context.crisis.script
|
|
3593
|
+
} else if (context.policy && !context.policy.allowed) {
|
|
3594
|
+
dbStore()?.appendAudit({ actor: 'bridge', action: 'policy.deny', allowed: false, reason: context.policy.code ?? 'DENY' })
|
|
3595
|
+
reply = context.policy.reason
|
|
3596
|
+
}
|
|
3597
|
+
const key = process.env.ADVISERS_API_KEY
|
|
3598
|
+
if (!reply && key && process.env.ADVISERS_NO_MODEL !== '1') {
|
|
3599
|
+
try {
|
|
3600
|
+
const { complete } = await import('../lib/model.js')
|
|
3601
|
+
reply = await complete({
|
|
3602
|
+
prompt: `${context.prompt}\n\n[user]\n${event.text ?? ''}`,
|
|
3603
|
+
apiKey: key,
|
|
3604
|
+
baseUrl: process.env.ADVISERS_BASE_URL || 'https://api.deepseek.com',
|
|
3605
|
+
model: process.env.ADVISERS_MODEL || 'deepseek-flash',
|
|
3606
|
+
})
|
|
3607
|
+
} catch (error) {
|
|
3608
|
+
reply = `模型调用失败:${error.message}`
|
|
3609
|
+
}
|
|
3610
|
+
} else if (!reply) {
|
|
3611
|
+
reply = context.intent?.readback ?? '[advisers] received'
|
|
3612
|
+
}
|
|
3613
|
+
const message = {
|
|
3614
|
+
conversationId: event.conversationId,
|
|
3615
|
+
threadId: event.threadId,
|
|
3616
|
+
replyTo: event.messageId,
|
|
3617
|
+
text: reply,
|
|
3618
|
+
idempotencyKey: event.dedupeKey ?? event.messageId,
|
|
3619
|
+
}
|
|
3620
|
+
if (permitGate) {
|
|
3621
|
+
const draft = { text: reply, replyTo: event.messageId }
|
|
3622
|
+
const request = { linkId: link.id, accountId: event.accountId, conversationId: event.conversationId, threadId: event.threadId, purpose: 'reply', draft }
|
|
3623
|
+
const permit = permitGate.issue(request)
|
|
3624
|
+
const auth = permitGate.authorize(permit, request)
|
|
3625
|
+
if (!auth.ok) {
|
|
3626
|
+
dbStore()?.appendAudit({ actor: 'bridge', action: 'egress.deny', allowed: false, reason: auth.reason })
|
|
3627
|
+
console.log(`[bridge] blocked: ${auth.reason}`)
|
|
3628
|
+
return result
|
|
3629
|
+
}
|
|
3630
|
+
message.permit = permit
|
|
3631
|
+
}
|
|
3632
|
+
const sent = await link.send(message)
|
|
3633
|
+
dbStore()?.appendAudit({ actor: 'bridge', action: sent.ok ? 'egress.sent' : 'egress.failed', allowed: sent.ok, reason: sent.error ?? undefined })
|
|
3634
|
+
saveLedger(ledger)
|
|
3635
|
+
}
|
|
3636
|
+
return result
|
|
3637
|
+
},
|
|
3638
|
+
async resolvePrincipal(account) {
|
|
3639
|
+
return `${account.linkId}:${account.accountId}`
|
|
3640
|
+
},
|
|
3641
|
+
}
|
|
3642
|
+
await link.start(host)
|
|
3643
|
+
console.log(`[bridge] ${name} listening at ${dir}`)
|
|
3644
|
+
const keepalive = setInterval(() => {}, 60_000)
|
|
3645
|
+
const shutdown = async () => { clearInterval(keepalive); await link.stop(); process.exit(0) }
|
|
3646
|
+
process.once('SIGINT', shutdown)
|
|
3647
|
+
process.once('SIGTERM', shutdown)
|
|
3648
|
+
await new Promise(() => {})
|
|
3649
|
+
}
|
|
3650
|
+
|
|
235
3651
|
async function office(kind, specFile, outFile) {
|
|
236
3652
|
const kinds = ['docx', 'xlsx', 'pptx', 'xmind', 'mermaid', 'drawio']
|
|
237
3653
|
if (!kinds.includes(kind) || !specFile || !outFile) {
|
|
@@ -252,25 +3668,34 @@ async function office(kind, specFile, outFile) {
|
|
|
252
3668
|
}
|
|
253
3669
|
}
|
|
254
3670
|
const spec = JSON.parse(readFileSync(specFile, 'utf8'))
|
|
3671
|
+
mkdirSync(dirname(outFile), { recursive: true })
|
|
255
3672
|
if (kind === 'mermaid') {
|
|
3673
|
+
await backupCliFile(outFile)
|
|
256
3674
|
writeFileSync(outFile, mod.buildMermaid(spec))
|
|
257
3675
|
console.log(`wrote ${outFile}`)
|
|
258
3676
|
return
|
|
259
3677
|
}
|
|
260
3678
|
if (kind === 'drawio') {
|
|
3679
|
+
await backupCliFile(outFile)
|
|
261
3680
|
writeFileSync(outFile, mod.buildDrawio(spec))
|
|
262
3681
|
console.log(`wrote ${outFile}`)
|
|
263
3682
|
return
|
|
264
3683
|
}
|
|
3684
|
+
const ext = outFile.split('.').pop()?.toLowerCase()
|
|
3685
|
+
const expected = kind === 'docx' ? ['docx'] : kind === 'xlsx' ? ['xlsx'] : kind === 'pptx' ? ['pptx'] : kind === 'xmind' ? ['xmind'] : kind === 'drawio' ? ['drawio'] : ['mmd', 'mermaid']
|
|
3686
|
+
if (!expected.includes(ext)) { console.error(`office ${kind} writes ${expected.join('/')}; got .${ext}`); process.exitCode = 1; return }
|
|
265
3687
|
const builder = kind === 'docx' ? mod.buildDocx : kind === 'xlsx' ? mod.buildXlsx : kind === 'xmind' ? mod.buildXmind : mod.buildPptx
|
|
266
3688
|
const buffer = await builder(spec)
|
|
3689
|
+
await backupCliFile(outFile)
|
|
267
3690
|
writeFileSync(outFile, buffer)
|
|
268
3691
|
const result = kind === 'xmind' ? await mod.validateXmind(buffer) : await mod.validateOffice(buffer, kind)
|
|
3692
|
+
dbStore()?.appendAudit({ actor: 'local', action: 'office.build', allowed: true, reason: outFile })
|
|
3693
|
+
recordManualDelivery([outFile], 'office', kind, result)
|
|
269
3694
|
console.log(result.ok ? `wrote ${outFile} (${buffer.length} bytes)` : `wrote ${outFile}, missing: ${result.missing.join(', ')}`)
|
|
270
3695
|
if (!result.ok) process.exitCode = 1
|
|
271
3696
|
}
|
|
272
3697
|
|
|
273
|
-
function soul(sub, file) {
|
|
3698
|
+
async function soul(sub, file) {
|
|
274
3699
|
if (sub === 'show') {
|
|
275
3700
|
const doc = loadSoul()
|
|
276
3701
|
if (!doc) {
|
|
@@ -292,6 +3717,7 @@ function soul(sub, file) {
|
|
|
292
3717
|
process.exitCode = 1
|
|
293
3718
|
return
|
|
294
3719
|
}
|
|
3720
|
+
await requireTosReaccept({ scope: 'config', subject: 'soul', action: 'soul set' })
|
|
295
3721
|
const previous = loadSoul()
|
|
296
3722
|
const content = readFileSync(file, 'utf8')
|
|
297
3723
|
const doc = {
|
|
@@ -310,13 +3736,14 @@ function soul(sub, file) {
|
|
|
310
3736
|
console.log('soul.md already exists; use `advisers soul set <file>` to replace it')
|
|
311
3737
|
return
|
|
312
3738
|
}
|
|
3739
|
+
await requireTosReaccept({ scope: 'config', subject: 'soul', action: 'soul init' })
|
|
313
3740
|
const doc = {
|
|
314
3741
|
id: 'soul',
|
|
315
3742
|
version: 1,
|
|
316
3743
|
content:
|
|
317
|
-
'
|
|
318
|
-
'
|
|
319
|
-
'
|
|
3744
|
+
'你是我的幕僚:直接、简洁、有用。\n' +
|
|
3745
|
+
'你是我生活里的客人:私事保持私密。\n' +
|
|
3746
|
+
'如果你要改这个文件,先告诉我。\n',
|
|
320
3747
|
updatedAt: now(),
|
|
321
3748
|
updatedBy: 'human',
|
|
322
3749
|
}
|
|
@@ -328,27 +3755,708 @@ function soul(sub, file) {
|
|
|
328
3755
|
process.exitCode = 1
|
|
329
3756
|
}
|
|
330
3757
|
|
|
331
|
-
|
|
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
|
+
|
|
4051
|
+
if (!command) {
|
|
4052
|
+
if (process.stdin.isTTY) await repl()
|
|
4053
|
+
else help()
|
|
4054
|
+
} else if (command === 'version' || command === '--version' || command === '-v') {
|
|
4055
|
+
console.log(VERSION)
|
|
4056
|
+
} else if (command === 'help' || command === '--help') {
|
|
332
4057
|
help()
|
|
333
4058
|
} else if (command === 'chat') {
|
|
334
|
-
chat(args
|
|
4059
|
+
await chat(args)
|
|
4060
|
+
} else if (command === 'status') {
|
|
4061
|
+
printStatus(args.includes('--json'))
|
|
4062
|
+
} else if (command === 'doctor') {
|
|
4063
|
+
await doctor()
|
|
4064
|
+
} else if (command === 'init') {
|
|
4065
|
+
init()
|
|
4066
|
+
} else if (command === 'history') {
|
|
4067
|
+
printHistory()
|
|
4068
|
+
} else if (command === 'mcp') {
|
|
4069
|
+
if (args.includes('--stdio')) await mcpServer()
|
|
4070
|
+
else { console.error('usage: advisers mcp --stdio'); process.exitCode = 1 }
|
|
4071
|
+
} else if (command === 'deliver') {
|
|
4072
|
+
await deliver(args)
|
|
4073
|
+
} else if (command === 'timestamp') {
|
|
4074
|
+
await timestampCommand(args)
|
|
4075
|
+
} else if (command === 'tui') {
|
|
4076
|
+
await tui(args)
|
|
4077
|
+
} else if (command === 'ocr') {
|
|
4078
|
+
await ocrCommand(args)
|
|
4079
|
+
} else if (command === 'evidence') {
|
|
4080
|
+
await printEvidence(args)
|
|
4081
|
+
} else if (command === 'receipt') {
|
|
4082
|
+
printReceipt()
|
|
4083
|
+
} else if (command === 'deliveries') {
|
|
4084
|
+
if (args.includes('--receipt')) await receiptPack(args)
|
|
4085
|
+
else if (args.includes('--pack')) await evidencePack(args)
|
|
4086
|
+
else if (args.includes('--json')) console.log(JSON.stringify(dbStore()?.listDeliveries(100) ?? [], null, 2))
|
|
4087
|
+
else printDeliveries()
|
|
4088
|
+
} else if (command === 'learn') {
|
|
4089
|
+
const sub = args[0]
|
|
4090
|
+
const store = dbStore()
|
|
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') {
|
|
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)}`)
|
|
4099
|
+
} else if (sub === 'review') {
|
|
4100
|
+
const run = store?.listTaskRuns(100).find((r) => r.id === args[1])
|
|
4101
|
+
const apiKey = process.env.ADVISERS_API_KEY
|
|
4102
|
+
if (!run || !apiKey) { console.error('usage: ADVISERS_API_KEY=... advisers learn review <run-id>'); process.exitCode = 1 }
|
|
4103
|
+
else {
|
|
4104
|
+
const ledger = loadLedger()
|
|
4105
|
+
const review = await reviewRun({ run, routines: ledger.listRoutines(), apiKey, baseUrl: process.env.ADVISERS_BASE_URL, model: process.env.ADVISERS_MODEL })
|
|
4106
|
+
const checked = lintReview(review, { run, routines: ledger.listRoutines() })
|
|
4107
|
+
if (!checked.ok) { console.error(`review rejected: ${checked.error}`); process.exitCode = 1 }
|
|
4108
|
+
else {
|
|
4109
|
+
const made = materializeReview(checked.review, { run, ledger })
|
|
4110
|
+
saveLedger(ledger)
|
|
4111
|
+
console.log(`verdict: ${made.verdict}${made.routine ? ` draft ${made.routine.id}` : made.patch ? ` patch ${made.patch.id}` : ''}`)
|
|
4112
|
+
}
|
|
4113
|
+
}
|
|
4114
|
+
} else { console.error('usage: advisers learn ls|review <run-id>'); process.exitCode = 1 }
|
|
4115
|
+
} else if (command === 'commit') {
|
|
4116
|
+
const sub = args[0]
|
|
4117
|
+
const ledger = loadLedger()
|
|
4118
|
+
const { flags, positional } = parseFlags(args.slice(1))
|
|
4119
|
+
if (sub === 'add') {
|
|
4120
|
+
const action = positional.join(' ').trim()
|
|
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 }
|
|
4122
|
+
else {
|
|
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
|
+
}
|
|
4173
|
+
}
|
|
4174
|
+
} else if (sub === 'ls') printCommitments(ledger, flags.json)
|
|
4175
|
+
else if (sub === 'snooze') {
|
|
4176
|
+
const id = positional[0]
|
|
4177
|
+
const hours = Number(positional[1] ?? 24)
|
|
4178
|
+
const c = ledger.listCommitments().find((x) => x.id === id)
|
|
4179
|
+
if (!c || !Number.isFinite(hours) || hours <= 0) { console.error('usage: advisers commit snooze <id> <hours>'); process.exitCode = 1 }
|
|
4180
|
+
else {
|
|
4181
|
+
c.status = 'snoozed'
|
|
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()))
|
|
4183
|
+
console.log(`snoozed: ${id} for ${hours}h`)
|
|
4184
|
+
}
|
|
4185
|
+
}
|
|
4186
|
+
else if (sub === 'done') {
|
|
4187
|
+
const id = positional[0]
|
|
4188
|
+
const evidence = flags.evidence
|
|
4189
|
+
if (!id || !evidence) { console.error('usage: advisers commit done <id> --evidence "<证据/原话>"'); process.exitCode = 1 }
|
|
4190
|
+
else {
|
|
4191
|
+
if (String(evidence).startsWith('file:') && !existsSync(String(evidence).slice(5))) {
|
|
4192
|
+
console.error(`evidence file not found: ${String(evidence).slice(5)}`); process.exitCode = 1
|
|
4193
|
+
} else {
|
|
4194
|
+
ledger.completeCommitment(id, [{ sessionId: latestConversationId(), turnId: 'cli', quote: String(evidence) }])
|
|
4195
|
+
saveLedgerWithAudit(ledger, { actor: 'local', action: 'commit.done', allowed: true, reason: id })
|
|
4196
|
+
console.log(`done: ${id}`)
|
|
4197
|
+
}
|
|
4198
|
+
}
|
|
4199
|
+
} else { console.error('usage: advisers commit add|edit|ls|done|snooze'); process.exitCode = 1 }
|
|
4200
|
+
} else if (command === 'diff') {
|
|
4201
|
+
const result = await diffLatest({ cwd: process.cwd(), backupDir: join(HOME, 'undo') })
|
|
4202
|
+
console.log(result.ok ? result.diff : `diff failed: ${result.error}`)
|
|
4203
|
+
if (!result.ok) process.exitCode = 1
|
|
4204
|
+
} else if (command === 'undo') {
|
|
4205
|
+
if (args.includes('--list')) {
|
|
4206
|
+
for (const row of await listBackups(join(HOME, 'undo'), { workspace: process.cwd() })) console.log(`${row.id}\t${row.path}\t${row.existed ? 'overwrite' : 'create'}`)
|
|
4207
|
+
} else {
|
|
4208
|
+
const result = await undoLatest({ cwd: process.cwd(), backupDir: join(HOME, 'undo'), force: args.includes('--force') })
|
|
4209
|
+
console.log(result.ok ? `已回滚:${result.path}` : `撤销失败:${result.error}`)
|
|
4210
|
+
if (!result.ok) process.exitCode = 1
|
|
4211
|
+
}
|
|
4212
|
+
} else if (command === 'compact') {
|
|
4213
|
+
const store = dbStore()
|
|
4214
|
+
const conversationId = latestConversationId()
|
|
4215
|
+
if (args[0] === 'ls') {
|
|
4216
|
+
for (const v of store?.listSummaryVersions(conversationId) ?? []) console.log(`${v.version}\t${v.throughSeq}\t${v.summary.slice(0, 100)}`)
|
|
4217
|
+
} else if (args[0] === 'rollback') {
|
|
4218
|
+
const version = Number(args[1])
|
|
4219
|
+
const old = store?.listSummaryVersions(conversationId).find((v) => v.version === version)
|
|
4220
|
+
if (!old) { console.error('usage: advisers compact rollback <version>'); process.exitCode = 1 }
|
|
4221
|
+
else { store.upsertSessionSummary({ conversationId, summary: old.summary, throughSeq: old.throughSeq, pins: old.pins }); console.log(`restored summary v${version}`) }
|
|
4222
|
+
} else { console.error('usage: advisers compact ls|rollback <version>'); process.exitCode = 1 }
|
|
4223
|
+
} else if (command === 'search') {
|
|
4224
|
+
const q = args.join(' ').trim()
|
|
4225
|
+
if (!q) { console.error('usage: advisers search <text>'); process.exitCode = 1 }
|
|
4226
|
+
else {
|
|
4227
|
+
const rows = dbStore()?.searchTurns(q, { limit: 10 }) ?? []
|
|
4228
|
+
if (!rows.length) console.log('没有匹配')
|
|
4229
|
+
for (const r of rows) console.log(`${r.seq}\t${r.role}\t${r.content.replace(/\s+/g, ' ').slice(0, 160)}`)
|
|
4230
|
+
}
|
|
4231
|
+
} else if (command === 'nudge') {
|
|
4232
|
+
const sub = args[0]
|
|
4233
|
+
const store = dbStore()
|
|
4234
|
+
if (sub === 'list') {
|
|
4235
|
+
for (const n of store?.listNudges(50) ?? []) console.log(`${n.id}\t${n.local_day}\t${n.level}\t${n.outcome}\t${n.body}`)
|
|
4236
|
+
} else if (sub === 'done' || sub === 'ignore') {
|
|
4237
|
+
const id = args[1]
|
|
4238
|
+
if (!id || !store?.setNudgeOutcome(id, sub === 'done' ? 'accepted' : 'ignored')) { console.error('usage: advisers nudge done|ignore <nudge-id>'); process.exitCode = 1 }
|
|
4239
|
+
else console.log(`${sub}: ${id}`)
|
|
4240
|
+
} else { console.error('usage: advisers nudge list|done|ignore'); process.exitCode = 1 }
|
|
4241
|
+
} else if (command === 'risks') {
|
|
4242
|
+
risks(loadLedger())
|
|
4243
|
+
} else if (command === 'pet-brief') {
|
|
4244
|
+
await petBrief(args)
|
|
4245
|
+
} else if (command === 'today') {
|
|
4246
|
+
await today(loadLedger(), { calendar: args.includes('--calendar'), sources: args.includes('--sources'), json: args.includes('--json') })
|
|
4247
|
+
} else if (command === 'tick') {
|
|
4248
|
+
tick(loadLedger(), args.includes('--json'))
|
|
4249
|
+
} else if (command === 'ui') {
|
|
4250
|
+
await ui(args)
|
|
4251
|
+
} else if (command === 'remind') {
|
|
4252
|
+
await remind(args)
|
|
4253
|
+
} else if (command === 'calendar') {
|
|
4254
|
+
await calendarImport(args.slice(1))
|
|
4255
|
+
} else if (command === 'who') {
|
|
4256
|
+
const open = loadLedger().openCommitments()
|
|
4257
|
+
const mine = open.filter((c) => c.debtor === 'user' || c.debtor === 'agent')
|
|
4258
|
+
const waiting = open.filter((c) => c.debtor === 'third' || c.debtor.startsWith('third:'))
|
|
4259
|
+
if (args.includes('--json')) { console.log(JSON.stringify({ mine, waiting }, null, 2)); }
|
|
4260
|
+
else {
|
|
4261
|
+
console.log(`我欠别人(${mine.length})`)
|
|
4262
|
+
for (const c of mine) console.log(` ${c.id} ${c.creditor} · ${c.action}${c.dueAt ? ` · ${c.dueAt.slice(0, 10)}` : ''}`)
|
|
4263
|
+
console.log(`等别人/别人欠我(${waiting.length})`)
|
|
4264
|
+
for (const c of waiting) console.log(` ${c.id} ${c.debtor} · ${c.action}${c.dueAt ? ` · ${c.dueAt.slice(0, 10)}` : ''}`)
|
|
4265
|
+
}
|
|
4266
|
+
} else if (command === 'memory') {
|
|
4267
|
+
const ledger = loadLedger()
|
|
4268
|
+
if (args[0] === 'candidates') {
|
|
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
|
+
}
|
|
4275
|
+
} else if (args[0] === 'accept') {
|
|
4276
|
+
const store = dbStore()
|
|
4277
|
+
const candidate = store?.getCandidate(args[1])
|
|
4278
|
+
if (!candidate) { console.error('candidate not found'); process.exitCode = 1 }
|
|
4279
|
+
else {
|
|
4280
|
+
try {
|
|
4281
|
+
const sourceRef = (e) => ({ ...(e.sessionId ? { quote: e.quote, ref: `${e.sessionId}#${e.turnId}` } : { quote: e.quote, ref: e.turnId ? `legacy#${e.turnId}` : undefined }), ...(e.source ? { source: e.source } : {}) })
|
|
4282
|
+
const commitmentEvidence = (e) => {
|
|
4283
|
+
if (!e.sessionId) return { quote: e.quote, turnId: e.turnId, sessionId: 'legacy', ...(e.source ? { source: e.source } : {}) }
|
|
4284
|
+
const turn = store.getTurn(e.turnId)
|
|
4285
|
+
if (!turn || turn.conversationId !== e.sessionId) throw new Error(`evidence turn not found: ${e.turnId}`)
|
|
4286
|
+
return { quote: e.quote, turnId: e.turnId, sessionId: e.sessionId, ...(e.source ? { source: e.source } : {}) }
|
|
4287
|
+
}
|
|
4288
|
+
if (candidate.kind === 'fact') ledger.remember({ ...candidate.payload, authority: 'user', evidence: candidate.evidence.map(sourceRef) })
|
|
4289
|
+
else if (candidate.kind === 'preference') ledger.addPreference({ ...candidate.payload, evidence: candidate.evidence.map(sourceRef) })
|
|
4290
|
+
else if (candidate.kind === 'commitment') ledger.addCommitment({ ...candidate.payload, matterId: candidate.payload.matterId ?? ledger.listMatters()[0]?.id, evidence: candidate.evidence.map(commitmentEvidence) })
|
|
4291
|
+
saveLedgerWithAudit(ledger, { actor: 'local', action: 'memory.accept', allowed: true, reason: candidate.id }, (s) => s.reviewCandidate(candidate.id, 'accepted'))
|
|
4292
|
+
console.log(`accepted ${candidate.id}`)
|
|
4293
|
+
} catch (error) { console.error(error.message); process.exitCode = 1 }
|
|
4294
|
+
}
|
|
4295
|
+
} else if (args[0] === 'reject') {
|
|
4296
|
+
const store = dbStore()
|
|
4297
|
+
const candidate = store?.getCandidate(args[1])
|
|
4298
|
+
if (!candidate) { console.error('candidate not found'); process.exitCode = 1 }
|
|
4299
|
+
else {
|
|
4300
|
+
updateStoreWithAudit((s) => s.reviewCandidate(candidate.id, 'rejected', args.slice(2).join(' ') || undefined), { actor: 'local', action: 'memory.reject', allowed: true, reason: candidate.id })
|
|
4301
|
+
console.log(`rejected ${candidate.id}`)
|
|
4302
|
+
}
|
|
4303
|
+
} else if (args[0] === 'search') {
|
|
4304
|
+
const q = args.slice(1).join(' ').trim()
|
|
4305
|
+
if (!q) { console.error('usage: advisers memory search <query>'); process.exitCode = 1 }
|
|
4306
|
+
else {
|
|
4307
|
+
const store = dbStore()
|
|
4308
|
+
const rows = store?.searchMemory(q) ?? ledger.searchMemory(q)
|
|
4309
|
+
if (!rows.length) console.log('(没有记忆匹配)')
|
|
4310
|
+
for (const r of rows) console.log(`${r.kind}\t${r.id}\t${r.text}${r.matterId ? `\t[${r.matterId}]` : ''}`)
|
|
4311
|
+
const turns = store?.searchTurns(q) ?? []
|
|
4312
|
+
for (const t of turns) console.log(`turn\t${t.conversationId}#${t.seq}\t${String(t.text).replace(/\s+/g, ' ').slice(0, 120)}`)
|
|
4313
|
+
}
|
|
4314
|
+
} else printMemory(ledger)
|
|
4315
|
+
} else if (command === 'digest') {
|
|
4316
|
+
const period = args[0] === 'week' ? 'week' : 'day'
|
|
4317
|
+
const store = dbStore()
|
|
4318
|
+
console.log(buildDigest({
|
|
4319
|
+
period,
|
|
4320
|
+
turns: store?.listTurns(latestConversationId(), 200) ?? [],
|
|
4321
|
+
commitments: loadLedger().listCommitments(),
|
|
4322
|
+
deliveries: store?.listDeliveries(100) ?? [],
|
|
4323
|
+
}))
|
|
4324
|
+
} else if (command === 'week') {
|
|
4325
|
+
printWeek(loadLedger())
|
|
4326
|
+
} else if (command === 'prefs') {
|
|
4327
|
+
printPreferences()
|
|
4328
|
+
} else if (command === 'privacy') {
|
|
4329
|
+
printPrivacy(args)
|
|
4330
|
+
} else if (command === 'audit') {
|
|
4331
|
+
printAudit(args)
|
|
4332
|
+
} else if (command === 'purge') {
|
|
4333
|
+
purgeMatter(args[0], args.includes('--yes'))
|
|
4334
|
+
} else if (command === 'decay') {
|
|
4335
|
+
const ledger = loadLedger()
|
|
4336
|
+
const changed = applyPreferenceDecay(ledger.listPreferences({ includeCandidates: true }))
|
|
4337
|
+
saveLedger(ledger)
|
|
4338
|
+
console.log(`[decay] ${changed.length} preference(s) updated`)
|
|
4339
|
+
} else if (command === 'correct') {
|
|
4340
|
+
const statement = args.join(' ').trim()
|
|
4341
|
+
if (!statement) { console.error('usage: advisers correct <statement>'); process.exitCode = 1 }
|
|
4342
|
+
else {
|
|
4343
|
+
const ledger = loadLedger()
|
|
4344
|
+
const result = learnPreference(ledger, statement, statement, { explicit: true })
|
|
4345
|
+
saveLedgerWithAudit(ledger, { actor: 'local', action: 'correct', allowed: true, reason: result.preference.id })
|
|
4346
|
+
printLearnReceipt(result)
|
|
4347
|
+
}
|
|
335
4348
|
} else if (command === 'ls') {
|
|
336
4349
|
ls()
|
|
337
4350
|
} else if (command === 'why') {
|
|
338
4351
|
why(args[0])
|
|
339
4352
|
} else if (command === 'forget') {
|
|
340
4353
|
forget(args[0])
|
|
4354
|
+
} else if (command === 'sync') {
|
|
4355
|
+
await syncCommand(args)
|
|
4356
|
+
} else if (command === 'vault') {
|
|
4357
|
+
const sub = args[0]
|
|
4358
|
+
if (sub === 'seal') await vaultSeal(args.slice(1))
|
|
4359
|
+
else if (sub === 'unseal') await vaultUnseal(args.slice(1))
|
|
4360
|
+
else if (sub === 'status' || !sub) vaultStatus()
|
|
4361
|
+
else { console.error('usage: advisers vault seal [--out file] [--remove] | unseal [file] | status'); process.exitCode = 1 }
|
|
341
4362
|
} else if (command === 'export') {
|
|
342
|
-
|
|
4363
|
+
const { flags } = parseFlags(args)
|
|
4364
|
+
await exportLedger(flags.all === true || args.includes('--all'), { encrypted: args.includes('--encrypted'), out: typeof flags.out === 'string' ? flags.out : undefined })
|
|
4365
|
+
} else if (command === 'import') {
|
|
4366
|
+
await importLedger(args.find((a) => !a.startsWith('--')), { replace: args.includes('--replace') })
|
|
4367
|
+
} else if (command === 'backup') {
|
|
4368
|
+
backup(args[0])
|
|
343
4369
|
} else if (command === 'brief') {
|
|
344
|
-
brief(args.join(' ').trim())
|
|
4370
|
+
await brief(args.filter((a) => a !== '--deep').join(' ').trim(), args.includes('--deep'))
|
|
4371
|
+
} else if (command === 'review') {
|
|
4372
|
+
await documentReview(args)
|
|
4373
|
+
} else if (command === 'research') {
|
|
4374
|
+
await research(args)
|
|
4375
|
+
} else if (command === 'capture') {
|
|
4376
|
+
await capture(args)
|
|
4377
|
+
} else if (command === 'policy') {
|
|
4378
|
+
const sub = args[0]
|
|
4379
|
+
if (sub === 'check') {
|
|
4380
|
+
const text = args.slice(1).join(' ').trim()
|
|
4381
|
+
if (!text) { console.error('usage: advisers policy check "<text>"'); process.exitCode = 1 }
|
|
4382
|
+
else {
|
|
4383
|
+
const crisis = new core.KeywordCrisisPolicy().scan(text)
|
|
4384
|
+
const pack = StrictPolicyPack ? new StrictPolicyPack() : undefined
|
|
4385
|
+
const decision = pack?.resolve({ use: 'understanding', crisis: crisis.tier === 'T1' || crisis.tier === 'T2' || (crisis.tier === 'T3' && crisis.thirdParty) }) ?? { allowed: false, action: 'deny', code: 'FAIL_CLOSED', reason: 'policy pack missing' }
|
|
4386
|
+
console.log(JSON.stringify({ tier: crisis.tier, crisis: crisis.crisis, decision }, null, 2))
|
|
4387
|
+
}
|
|
4388
|
+
} else { console.error('usage: advisers policy check "<text>"'); process.exitCode = 1 }
|
|
4389
|
+
} else if (command === 'office-edit') {
|
|
4390
|
+
const source = args[0]
|
|
4391
|
+
const opsFile = args[1]
|
|
4392
|
+
const out = args[2] || source
|
|
4393
|
+
if (!source || !opsFile) { console.error('usage: advisers office-edit <file> <ops.json> [out]'); process.exitCode = 1 }
|
|
4394
|
+
else {
|
|
4395
|
+
let mod
|
|
4396
|
+
if (process.env.ADVISERS_OFFICE_LOCAL === '1') mod = await import('../../office/dist/index.js')
|
|
4397
|
+
else { try { mod = await import('advisers-office') } catch { mod = await import('../../office/dist/index.js') } }
|
|
4398
|
+
const ext = source.split('.').pop()?.toLowerCase()
|
|
4399
|
+
const result = await mod.editOffice(readFileSync(source), ext, JSON.parse(readFileSync(opsFile, 'utf8')))
|
|
4400
|
+
if (!result.ok) { console.error(result.error); process.exitCode = 1 }
|
|
4401
|
+
else { await backupCliFile(out); writeFileSync(out, result.buffer); recordManualDelivery([out], 'office-edit', source, 'edited'); console.log(JSON.stringify({ ok: true, out, changes: result.changes }, null, 2)) }
|
|
4402
|
+
}
|
|
4403
|
+
} else if (command === 'office-read') {
|
|
4404
|
+
const file = args[0]
|
|
4405
|
+
if (!file) { console.error('usage: advisers office-read <file>'); process.exitCode = 1 }
|
|
4406
|
+
else {
|
|
4407
|
+
if (file.toLowerCase().endsWith('.ofd')) {
|
|
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 }
|
|
4412
|
+
} else {
|
|
4413
|
+
let mod
|
|
4414
|
+
if (process.env.ADVISERS_OFFICE_LOCAL === '1') mod = await import('../../office/dist/index.js')
|
|
4415
|
+
else { try { mod = await import('advisers-office') } catch { mod = await import('../../office/dist/index.js') } }
|
|
4416
|
+
const doc = await mod.readOffice(readFileSync(file))
|
|
4417
|
+
console.log(mod.officeToText(doc, Number(args[1]) || 20_000))
|
|
4418
|
+
}
|
|
4419
|
+
}
|
|
4420
|
+
} else if (command === 'verify') {
|
|
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 }
|
|
4424
|
+
else {
|
|
4425
|
+
const ext = file.split('.').pop()?.toLowerCase()
|
|
4426
|
+
if (!['docx', 'xlsx', 'pptx'].includes(ext)) { console.error('verify supports docx/xlsx/pptx'); process.exitCode = 1 }
|
|
4427
|
+
else {
|
|
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
|
+
}
|
|
4442
|
+
}
|
|
4443
|
+
}
|
|
345
4444
|
} else if (command === 'office') {
|
|
346
4445
|
await office(args[0], args[1], args[2])
|
|
347
4446
|
process.exit(process.exitCode || 0)
|
|
348
4447
|
} else if (command === 'routine') {
|
|
349
|
-
routine(args[0], args[1])
|
|
4448
|
+
await routine(args[0], args[1], args[2])
|
|
4449
|
+
} else if (command === 'template') {
|
|
4450
|
+
await template(args[0], args[1], args[2])
|
|
4451
|
+
process.exit(process.exitCode || 0)
|
|
4452
|
+
} else if (command === 'link') {
|
|
4453
|
+
link(args[0], args[1], args[2], args[3])
|
|
4454
|
+
} else if (command === 'bridge') {
|
|
4455
|
+
await bridge(args)
|
|
350
4456
|
} else if (command === 'soul') {
|
|
351
|
-
soul(args[0], args[1])
|
|
4457
|
+
await soul(args[0], args[1])
|
|
4458
|
+
} else if (command === 'tos') {
|
|
4459
|
+
await tosCommand(args)
|
|
352
4460
|
} else {
|
|
353
4461
|
console.error(`unknown command: ${command}`)
|
|
354
4462
|
help()
|