advisers 0.3.2 → 0.4.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README-zh.md +13 -14
- package/README.md +37 -23
- package/THIRD-PARTY-NOTICES.md +1 -1
- package/bin/advisers.js +2302 -95
- package/index.js +1 -1
- package/lib/brief-archive.js +267 -0
- package/lib/client-pack.js +1016 -0
- package/lib/consent.js +390 -0
- package/lib/credentials.js +195 -0
- package/lib/error-codes.js +516 -7
- package/lib/evidence.js +697 -113
- package/lib/kb-extract.js +626 -0
- package/lib/kb-facts.js +429 -0
- package/lib/kb-pages.js +1084 -0
- package/lib/kb.js +1036 -0
- package/lib/mail-errors.js +46 -0
- package/lib/mail-extract.js +351 -0
- package/lib/mail-imap.js +446 -0
- package/lib/mail-import.js +176 -0
- package/lib/mail-parse.js +223 -0
- package/lib/mail-store.js +731 -0
- package/lib/mail.js +506 -0
- package/lib/mcp-server.js +196 -10
- package/lib/notify.js +265 -7
- package/lib/policy/decision.js +315 -0
- package/lib/policy/egress.js +268 -0
- package/lib/policy/errors.js +71 -0
- package/lib/policy/index.js +99 -0
- package/lib/policy/rules.js +468 -0
- package/lib/policy/surfaces.js +141 -0
- package/lib/receipt-verify.js +199 -19
- package/lib/receivables.js +1653 -0
- package/lib/scheduler.js +453 -9
- package/lib/shell.js +1406 -0
- package/lib/source.js +98 -3
- package/lib/sqlite.js +366 -49
- package/lib/tos/index.js +2 -2
- package/lib/tos/manifest.json +6 -6
- package/lib/tos/privacy.zh-CN.md +33 -20
- package/lib/tos/safety.zh-CN.md +7 -6
- package/lib/tos/summary.zh-CN.md +3 -2
- package/lib/tos/terms.zh-CN.md +31 -16
- package/lib/urgency.js +467 -0
- package/package.json +4 -4
package/bin/advisers.js
CHANGED
|
@@ -120,6 +120,24 @@ const loadContextWindow = lazyModule(() => import('../lib/context-window.js'))
|
|
|
120
120
|
const loadPetBrief = lazyModule(() => import('../lib/pet-brief.js'))
|
|
121
121
|
const loadImap = lazyModule(() => import('../lib/imap.js'))
|
|
122
122
|
const loadUi = lazyModule(() => import('../lib/ui.js'))
|
|
123
|
+
// 0.4.0 (task-29): interactive shell + KB/mail/money/consent command families.
|
|
124
|
+
// Each one is only imported by the commands that need it, so ordinary commands
|
|
125
|
+
// keep the 0.3.2 startup graph (and --version/help pay for nothing extra).
|
|
126
|
+
const loadShell = lazyModule(() => import('../lib/shell.js'))
|
|
127
|
+
const loadUrgency = lazyModule(() => import('../lib/urgency.js'))
|
|
128
|
+
const loadBriefArchive = lazyModule(() => import('../lib/brief-archive.js'))
|
|
129
|
+
const loadKb = lazyModule(() => import('../lib/kb.js'))
|
|
130
|
+
const loadKbPages = lazyModule(() => import('../lib/kb-pages.js'))
|
|
131
|
+
const loadKbFacts = lazyModule(() => import('../lib/kb-facts.js'))
|
|
132
|
+
const loadMail = lazyModule(() => import('../lib/mail.js'))
|
|
133
|
+
const loadCredentials = lazyModule(() => import('../lib/credentials.js'))
|
|
134
|
+
const loadConsent = lazyModule(() => import('../lib/consent.js'))
|
|
135
|
+
const loadPolicy = lazyModule(() => import('../lib/policy/index.js'))
|
|
136
|
+
const loadMailStore = lazyModule(() => import('../lib/mail-store.js'))
|
|
137
|
+
const loadClientPack = lazyModule(() => import('../lib/client-pack.js'))
|
|
138
|
+
// Money sidecar: the library lands with the 0.4.0 receivables wave; the loader
|
|
139
|
+
// fails only when a money command is actually run, never at startup.
|
|
140
|
+
const loadReceivablesLib = lazyModule(() => import('../lib/receivables.js'))
|
|
123
141
|
|
|
124
142
|
let core
|
|
125
143
|
if (process.env.ADVISERS_CORE_LOCAL === '1') {
|
|
@@ -1194,7 +1212,8 @@ function help() {
|
|
|
1194
1212
|
console.log(`advisers — a staff of AI advisers
|
|
1195
1213
|
|
|
1196
1214
|
Usage:
|
|
1197
|
-
advisers start the local conversation (TTY)
|
|
1215
|
+
advisers start the local conversation (TTY shell)
|
|
1216
|
+
(status line + result blocks; non-TTY prints help; ADVISERS_NO_SHELL=1 keeps the legacy REPL)
|
|
1198
1217
|
advisers chat [--file <path>] [--allow-path <dir>]... [text]
|
|
1199
1218
|
one-shot task, or start the local conversation
|
|
1200
1219
|
advisers init initialize home + soul
|
|
@@ -1211,10 +1230,12 @@ Usage:
|
|
|
1211
1230
|
advisers compact ls|rollback summary versions
|
|
1212
1231
|
advisers today [--calendar] [--sources] [--json [--limit n]]
|
|
1213
1232
|
one-screen today/week/waiting view (+ local events)
|
|
1214
|
-
advisers remind [--json] [--ics [path]] [--deliver [--notify]] due reminders + ICS/VALARM export
|
|
1233
|
+
advisers remind [--json] [--ics [path]] [--deliver [--notify]] [--quiet-hours HH:MM-HH:MM] [--force-notify] due reminders + ICS/VALARM export
|
|
1215
1234
|
advisers remind install|uninstall|status [--apply] [--schedule "0 9 * * *"]
|
|
1216
1235
|
scheduler scripts + OS plan (dry-run by default; --apply executes)
|
|
1217
|
-
|
|
1236
|
+
--morning adds the second morning block (--morning-time 08:30, --morning-days 1-5)
|
|
1237
|
+
status v2 shows the remind + morning sections and both OS plans
|
|
1238
|
+
advisers remind --json [--now ISO] reminders + per-row urgency (pure read)
|
|
1218
1239
|
advisers calendar import --ics <file> local .ics read-only import
|
|
1219
1240
|
advisers risks up to 3 deterministic obligation risks
|
|
1220
1241
|
advisers pet-brief [--json] [--out [path]] [--check [--strict]] [--display-policy public|private|none]
|
|
@@ -1223,8 +1244,9 @@ Usage:
|
|
|
1223
1244
|
advisers week [--json] last 7 local days (Asia/Shanghai); --json is one JSON document
|
|
1224
1245
|
advisers agenda [--days 7] [--json]
|
|
1225
1246
|
7-day agenda: commitments + calendar_events, Asia/Shanghai days
|
|
1226
|
-
advisers morning [--json] [--out f]
|
|
1227
|
-
deterministic local morning brief (no model, no network)
|
|
1247
|
+
advisers morning [--json] [--out f] [--top 1..5] [--archive [--keep 1..365]]
|
|
1248
|
+
deterministic local morning brief (no model, no network);
|
|
1249
|
+
--archive writes ~/.advisers/briefs/<day>.md + latest.md
|
|
1228
1250
|
advisers digest day|week|morning short digest (morning = the deterministic brief)
|
|
1229
1251
|
advisers diff show the last changed file
|
|
1230
1252
|
advisers undo [--list] restore the last file write
|
|
@@ -1263,6 +1285,7 @@ Usage:
|
|
|
1263
1285
|
advisers client archive <id> [--dry-run] [--json]
|
|
1264
1286
|
advisers client merge <from> <into> [--dry-run] [--json]
|
|
1265
1287
|
advisers client export <id> [--format md|docx] [--out <file>] [--redact-names] [--json]
|
|
1288
|
+
advisers client export <id> --pack [--out <dir>] [--force] [--json] client status pack v1 (no money fields)
|
|
1266
1289
|
advisers client note add <id> "<summary>" [--kind k] [--at ISO] [--project id] [--matter id] [--json]
|
|
1267
1290
|
advisers client note list <id> [--project id] [--limit n] [--json]
|
|
1268
1291
|
advisers project add <client-id> "<name>" [--start YYYY-MM-DD] [--end YYYY-MM-DD]
|
|
@@ -1272,6 +1295,33 @@ Usage:
|
|
|
1272
1295
|
advisers project archive <id> [--dry-run] [--json]
|
|
1273
1296
|
customer/project entities + derived timeline (SQLite store;
|
|
1274
1297
|
see docs/CLIENTS.md)
|
|
1298
|
+
advisers kb add <file>... [--title s] [--kind k] [--client|--project|--matter id] [--secrecy 0-3]
|
|
1299
|
+
[--replace] [--from list.txt] [--json] index a local document (text extracted locally)
|
|
1300
|
+
advisers kb ls|show <id>|rm <id>|purge <id>|reindex [--rebuild] [--json]
|
|
1301
|
+
list/inspect/tombstone/physically purge documents; reindex verifies/rebuilds KB FTS
|
|
1302
|
+
advisers kb page ls|show <id>|rebuild|diff ... deterministic compiled pages (client/project/timeline/facts)
|
|
1303
|
+
advisers kb search <q> [--scope kb|pages|all] [--limit n] [--clearance 0-3] [--json]
|
|
1304
|
+
local KB search (no model, no network; clearance filtered before counting)
|
|
1305
|
+
advisers search <q> --scope turns|kb|pages|facts|all [--json]
|
|
1306
|
+
scoped local search; without --scope the 0.3.2 turn search output is unchanged
|
|
1307
|
+
advisers fact show <id>|history <id>|as-of <YYYY-MM-DD|ISO> [--json]
|
|
1308
|
+
fact source/supersede chain/value as-of a moment (no model, no network)
|
|
1309
|
+
advisers mail account add --name n --host h [--port 993] [--tls tls|starttls] --user u [--pass-stdin]
|
|
1310
|
+
store an IMAP account; password only from the TTY prompt or stdin, never argv
|
|
1311
|
+
advisers mail account ls|show <acct>|rm <acct> [--json]
|
|
1312
|
+
advisers mail sync [<acct>] [--full] [--dry-run] [--json] the only IMAP network entry (read-only EXAMINE/FETCH)
|
|
1313
|
+
advisers mail ls|show <id> [--body]|purge [--older-than 30d] [--dry-run|--yes]|import <file|dir> [--json]
|
|
1314
|
+
local reads; purge clears bodies (metadata/hash stay); import reads .eml/.mbox offline
|
|
1315
|
+
advisers mail extract [<id>...] [--all-new] [--local|--model --yes] [--matter id] [--dry-run] [--json]
|
|
1316
|
+
default local rules (offline); --model needs --yes + ADVISERS_API_KEY + consent + secrecy 0
|
|
1317
|
+
advisers receivable add <client-id> "<label>" --amount 8000.00 [--due DATE] [--currency CNY] [--json]
|
|
1318
|
+
advisers receivable ls|show <id>|edit <id>|void <id> [--aging] [--json]
|
|
1319
|
+
money sidecars in integer minor units; amounts never enter MCP/receipt packs
|
|
1320
|
+
advisers payment add <client-id> --amount 4000.00 [--receivable rcv] [--method bank] [--json]
|
|
1321
|
+
advisers payment ls|void <id> [--json] payments reopen/complete the follow-up commitment atomically
|
|
1322
|
+
advisers consent status|grant <surface>|revoke <surface> [--data-class mail|kb] [--yes] [--json]
|
|
1323
|
+
separate model-egress consent (provider/base-URL bound; TTY typed confirmation)
|
|
1324
|
+
advisers privacy --matrix [--json] policy surface/action/gate matrix from the registry
|
|
1275
1325
|
advisers privacy [--json] [--prove] show/verify local data & egress facts
|
|
1276
1326
|
advisers why <pref-id> explain a preference
|
|
1277
1327
|
advisers forget <pref-id> forget a preference (tombstone)
|
|
@@ -1550,7 +1600,7 @@ function purgeMatter(id, confirmed) {
|
|
|
1550
1600
|
function parseFlags(args) {
|
|
1551
1601
|
const flags = {}
|
|
1552
1602
|
const positional = []
|
|
1553
|
-
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', 'dry-run', 'unclassified', 'no-calendar', 'include-done', 'record-delivery', 'include-global'])
|
|
1603
|
+
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', 'dry-run', 'unclassified', 'no-calendar', 'include-done', 'record-delivery', 'include-global', 'archive', 'morning', 'include-deleted', 'all-new', 'local', 'model', 'full', 'pass-stdin', 'force-notify'])
|
|
1554
1604
|
for (let i = 0; i < args.length; i++) {
|
|
1555
1605
|
if (args[i].startsWith('--')) {
|
|
1556
1606
|
const key = args[i].slice(2)
|
|
@@ -2246,7 +2296,7 @@ const CUSTOMER_USAGE = {
|
|
|
2246
2296
|
projectList: 'usage: advisers project list [--client <id>] [--all] [--limit n] [--json]',
|
|
2247
2297
|
projectShow: 'usage: advisers project show <id> [--timeline-limit n] [--clearance 0-3] [--json]',
|
|
2248
2298
|
projectArchive: 'usage: advisers project archive <id> [--dry-run] [--json]',
|
|
2249
|
-
export: 'usage: advisers client export <id> [--format md|docx] [--out <file>] [--redact-names] [--json]'
|
|
2299
|
+
export: 'usage: advisers client export <id> [--format md|docx] [--out <file>] [--redact-names] [--json]\n advisers client export <id> --pack [--out <dir>] [--force] [--json]'
|
|
2250
2300
|
}
|
|
2251
2301
|
|
|
2252
2302
|
/** An application error with a stable E_* code and optional actionable hint. */
|
|
@@ -2809,7 +2859,7 @@ function clientList(rest) {
|
|
|
2809
2859
|
} catch (error) { reportCustomerFailure(error) }
|
|
2810
2860
|
}
|
|
2811
2861
|
|
|
2812
|
-
function clientShow(rest) {
|
|
2862
|
+
async function clientShow(rest) {
|
|
2813
2863
|
const usage = CUSTOMER_USAGE.show
|
|
2814
2864
|
try {
|
|
2815
2865
|
const parsed = customerFlags(rest, { booleans: ['json'], values: ['timeline-limit', 'clearance'] }, usage)
|
|
@@ -2818,6 +2868,9 @@ function clientShow(rest) {
|
|
|
2818
2868
|
const timelineLimit = customerIntegerFlag(parsed.flags['timeline-limit'], 'timeline-limit', 0, CUSTOMER_TIMELINE_MAX, CUSTOMER_TIMELINE_DEFAULT, usage)
|
|
2819
2869
|
if (!customerStoreOrFail()) return
|
|
2820
2870
|
const store = readStoreOrExit()
|
|
2871
|
+
// 0.4.0 additive: money summary (no amounts beyond per-currency totals; the
|
|
2872
|
+
// lib also fails closed above clearance and only counts hidden rows).
|
|
2873
|
+
const money = await loadReceivablesLib().catch(() => null)
|
|
2821
2874
|
const payload = store.read(() => {
|
|
2822
2875
|
const view = readClientView(store, id)
|
|
2823
2876
|
const filtered = clearCustomerView(view, clearance)
|
|
@@ -2856,6 +2909,7 @@ function clientShow(rest) {
|
|
|
2856
2909
|
clearance: clearance,
|
|
2857
2910
|
protectedExcluded: filtered.protectedExcluded,
|
|
2858
2911
|
degraded: timeline.degraded,
|
|
2912
|
+
...(money ? { receivables: money.clientReceivablesBlock(store, id, { clearance }) } : {}),
|
|
2859
2913
|
}
|
|
2860
2914
|
})
|
|
2861
2915
|
const lines = []
|
|
@@ -3086,7 +3140,8 @@ function clientNoteList(rest) {
|
|
|
3086
3140
|
async function clientExport(rest) {
|
|
3087
3141
|
const usage = CUSTOMER_USAGE.export
|
|
3088
3142
|
try {
|
|
3089
|
-
const parsed = customerFlags(rest, { booleans: ['json', 'redact-names'], values: ['format', 'out'] }, usage)
|
|
3143
|
+
const parsed = customerFlags(rest, { booleans: ['json', 'redact-names', 'pack', 'force', 'include-receivables'], values: ['format', 'out'] }, usage)
|
|
3144
|
+
if (parsed.flags['include-receivables'] === true) throw customerError('E_CLIENT_PACK_RECEIVABLES_UNSUPPORTED', 'client status packs do not carry receivable/payment amounts in 0.4.0', 'amounts stay local; --include-receivables is reserved until legal review (0.4.1)')
|
|
3090
3145
|
const id = customerIdArg(parsed.positional, 0, 'a client id', usage)
|
|
3091
3146
|
const format = parsed.flags.format === undefined ? 'md' : String(parsed.flags.format).toLowerCase()
|
|
3092
3147
|
if (format !== 'md' && format !== 'docx') throw customerError('E_USAGE', '--format must be md or docx', usage)
|
|
@@ -3171,6 +3226,84 @@ async function clientExport(rest) {
|
|
|
3171
3226
|
} else {
|
|
3172
3227
|
buffer = Buffer.from(markdown, 'utf8')
|
|
3173
3228
|
}
|
|
3229
|
+
// 0.4.0: client status pack v2 (directory pack). The pack contains no money
|
|
3230
|
+
// fields (amounts stay local in 0.4.0; --include-receivables would fail
|
|
3231
|
+
// closed in the library), is written 0700/0600 atomically and self-verified.
|
|
3232
|
+
if (parsed.flags.pack === true) {
|
|
3233
|
+
const packLib = await loadClientPack()
|
|
3234
|
+
const statusPayload = {
|
|
3235
|
+
ok: true,
|
|
3236
|
+
command: 'client export',
|
|
3237
|
+
format: 'json',
|
|
3238
|
+
scope: 'client',
|
|
3239
|
+
subject: { kind: 'client', id: data.client.id, name: data.displayName },
|
|
3240
|
+
generatedAt: generatedAt,
|
|
3241
|
+
clearance: clearance,
|
|
3242
|
+
protectedExcluded: data.protectedExcluded,
|
|
3243
|
+
counts: data.counts,
|
|
3244
|
+
projects: data.projects,
|
|
3245
|
+
open: data.open,
|
|
3246
|
+
nextDueAt: data.nextDueAt,
|
|
3247
|
+
timeline: data.timeline,
|
|
3248
|
+
timelineTotal: data.timelineTotal,
|
|
3249
|
+
timelineTruncated: data.timelineTruncated,
|
|
3250
|
+
disclaimer: true,
|
|
3251
|
+
}
|
|
3252
|
+
const outDir = typeof parsed.flags.out === 'string' && parsed.flags.out.trim()
|
|
3253
|
+
? parsed.flags.out.trim()
|
|
3254
|
+
: join(HOME, 'exports', 'client-' + data.client.id + '-' + generatedAt.replace(/[:.]/g, '-'))
|
|
3255
|
+
const packResult = packLib.exportClientStatusPack({
|
|
3256
|
+
outDir,
|
|
3257
|
+
status: statusPayload,
|
|
3258
|
+
markdown: markdown,
|
|
3259
|
+
...(format === 'docx' ? { docx: buffer } : {}),
|
|
3260
|
+
subject: { kind: 'client', id: data.client.id, name: data.displayName },
|
|
3261
|
+
generatedAt: generatedAt,
|
|
3262
|
+
overwrite: parsed.flags.force === true,
|
|
3263
|
+
env: { advisersVersion: VERSION, command: 'client export --pack' },
|
|
3264
|
+
})
|
|
3265
|
+
try {
|
|
3266
|
+
const writeStore = dbStore()
|
|
3267
|
+
if (writeStore) {
|
|
3268
|
+
writeStore.appendAudit({
|
|
3269
|
+
actor: 'local',
|
|
3270
|
+
action: 'client.export',
|
|
3271
|
+
allowed: true,
|
|
3272
|
+
reason: 'client ' + data.client.id + ' format=pack bytes=' + packResult.bytes + ' files=' + packResult.fileCount + ' protected=' + data.protectedExcluded,
|
|
3273
|
+
})
|
|
3274
|
+
}
|
|
3275
|
+
} catch {}
|
|
3276
|
+
const payload = {
|
|
3277
|
+
ok: true,
|
|
3278
|
+
command: 'client export --pack',
|
|
3279
|
+
format: packResult.format,
|
|
3280
|
+
version: packResult.version,
|
|
3281
|
+
scope: packResult.scope,
|
|
3282
|
+
subject: packResult.subject,
|
|
3283
|
+
out: packResult.out,
|
|
3284
|
+
replaced: packResult.replaced,
|
|
3285
|
+
generatedAt: packResult.generatedAt,
|
|
3286
|
+
counts: packResult.counts,
|
|
3287
|
+
bytes: packResult.bytes,
|
|
3288
|
+
fileCount: packResult.fileCount,
|
|
3289
|
+
checksumCount: packResult.checksumCount,
|
|
3290
|
+
manifestDigest: packResult.manifestDigest,
|
|
3291
|
+
verificationBasis: packResult.verificationBasis,
|
|
3292
|
+
verification: packResult.verification,
|
|
3293
|
+
clearance: clearance,
|
|
3294
|
+
protectedExcluded: data.protectedExcluded,
|
|
3295
|
+
disclaimer: true,
|
|
3296
|
+
}
|
|
3297
|
+
const human = [
|
|
3298
|
+
'已生成客户状态包目录(pack v1):' + payload.out,
|
|
3299
|
+
'客户:' + data.displayName + ' (' + data.client.id + ') · files=' + payload.fileCount + ' · bytes=' + payload.bytes + ' · manifestDigest=' + String(payload.manifestDigest).slice(0, 16),
|
|
3300
|
+
'离线校验:' + (payload.verification.ok ? '通过(仅证明包内 SHA-256 自洽,不是签名/第三方存证)' : '失败:' + (payload.verification.errors ?? []).slice(0, 3).join(' | ')),
|
|
3301
|
+
'边界:状态说明,不是对账单/合同/法律意见;不含金额、对话原文与备注正文。',
|
|
3302
|
+
]
|
|
3303
|
+
customerPrint(parsed.flags.json === true, payload, human)
|
|
3304
|
+
if (!payload.verification.ok) process.exitCode = 1
|
|
3305
|
+
return
|
|
3306
|
+
}
|
|
3174
3307
|
const out = typeof parsed.flags.out === 'string'
|
|
3175
3308
|
? parsed.flags.out.trim()
|
|
3176
3309
|
: join(HOME, 'exports', 'client-' + data.client.id + '-' + generatedAt.replace(/[:.]/g, '-') + '.' + format)
|
|
@@ -3221,7 +3354,7 @@ async function clientExport(rest) {
|
|
|
3221
3354
|
customerPrint(parsed.flags.json === true, payload, human)
|
|
3222
3355
|
} catch (error) { reportCustomerFailure(error) }
|
|
3223
3356
|
}
|
|
3224
|
-
function clientCommand(rawArgs) {
|
|
3357
|
+
async function clientCommand(rawArgs) {
|
|
3225
3358
|
const sub = rawArgs[0]
|
|
3226
3359
|
const rest = rawArgs.slice(1)
|
|
3227
3360
|
if (!sub || sub === 'help' || sub === '--help') { clientUsage(); return }
|
|
@@ -3671,15 +3804,24 @@ async function buildAgendaData(input) {
|
|
|
3671
3804
|
conflicts.sort((a, b) => (a.date === b.date ? (a.items.join(',') < b.items.join(',') ? -1 : 1) : (a.date < b.date ? -1 : 1)))
|
|
3672
3805
|
const perDayLoad = {}
|
|
3673
3806
|
for (const day of daysOut) if (day.load) perDayLoad[day.date] = day.load
|
|
3807
|
+
// 0.4.0 proactive (task-29): urgency is a derived, additive field attached
|
|
3808
|
+
// after the deterministic projection. It is never part of the morning hash
|
|
3809
|
+
// (buildMorningReport strips it before hashing) and calendar items are left
|
|
3810
|
+
// untouched. Secrecy is not an input (see lib/urgency.js).
|
|
3811
|
+
const { scoreUrgency } = await loadUrgency()
|
|
3812
|
+
const urgencyRecords = new Map()
|
|
3813
|
+
for (const commitment of input.ledger.listCommitments()) urgencyRecords.set(commitment.id, commitment)
|
|
3814
|
+
const urgencyOptions = { now: nowMs, timezone: AGENDA_TIMEZONE, records: urgencyRecords }
|
|
3815
|
+
const withUrgency = (items) => items.map((item) => (item.kind === 'commitment' ? { ...item, urgency: scoreUrgency(item, urgencyOptions) } : item))
|
|
3674
3816
|
return {
|
|
3675
3817
|
ok: true,
|
|
3676
3818
|
command: 'agenda',
|
|
3677
3819
|
now: new Date(nowMs).toISOString(),
|
|
3678
3820
|
window: { from: startDay, to: lastDay, days: days, timezone: AGENDA_TIMEZONE },
|
|
3679
|
-
overdue: overdue.slice(0, 50),
|
|
3680
|
-
days: daysOut,
|
|
3681
|
-
waiting: waiting.slice(0, 20),
|
|
3682
|
-
unscheduled: unscheduled.slice(0, 20),
|
|
3821
|
+
overdue: withUrgency(overdue.slice(0, 50)),
|
|
3822
|
+
days: daysOut.map((day) => ({ ...day, items: withUrgency(day.items) })),
|
|
3823
|
+
waiting: withUrgency(waiting.slice(0, 20)),
|
|
3824
|
+
unscheduled: withUrgency(unscheduled.slice(0, 20)),
|
|
3683
3825
|
conflicts: conflicts,
|
|
3684
3826
|
counts: { overdue: overdue.length, today: daysOut[0] ? daysOut[0].load : 0, days: days, waiting: waiting.length, unscheduled: unscheduled.length, conflicts: conflicts.length, perDayLoad: perDayLoad },
|
|
3685
3827
|
degraded: degraded,
|
|
@@ -3814,9 +3956,44 @@ async function buildMorningReport(input) {
|
|
|
3814
3956
|
if (agenda.conflicts.length) risks.push('时间冲突 ' + agenda.conflicts.length + ' 处')
|
|
3815
3957
|
if (today.load >= 3) risks.push('今日负载较高(' + today.load + ' 项)')
|
|
3816
3958
|
if (agenda.unscheduled.length) risks.push('未排期 ' + agenda.unscheduled.length + ' 条')
|
|
3959
|
+
// 0.4.0 proactive: urgency now rides on the agenda commitment items, but the
|
|
3960
|
+
// frozen dataSha256 must cover exactly the 0.3.2 shape. Strip the derived field
|
|
3961
|
+
// before hashing (the same data still ships in payloadInput below).
|
|
3962
|
+
const stripUrgency = (value) => {
|
|
3963
|
+
if (Array.isArray(value)) return value.map(stripUrgency)
|
|
3964
|
+
if (value && typeof value === 'object') {
|
|
3965
|
+
const out = {}
|
|
3966
|
+
for (const [key, entry] of Object.entries(value)) if (key !== 'urgency') out[key] = stripUrgency(entry)
|
|
3967
|
+
return out
|
|
3968
|
+
}
|
|
3969
|
+
return value
|
|
3970
|
+
}
|
|
3971
|
+
const counts = {
|
|
3972
|
+
mustDo: mustDo.length,
|
|
3973
|
+
overdue: agenda.overdue.length,
|
|
3974
|
+
meetings: meetings.length,
|
|
3975
|
+
waiting: agenda.waiting.length,
|
|
3976
|
+
upcoming: upcoming.length,
|
|
3977
|
+
unscheduled: agenda.unscheduled.length,
|
|
3978
|
+
conflicts: agenda.conflicts.length,
|
|
3979
|
+
}
|
|
3817
3980
|
const hashInput = {
|
|
3818
3981
|
localDay: agenda.window.from,
|
|
3819
3982
|
window: agenda.window,
|
|
3983
|
+
mustDo: stripUrgency(mustDo),
|
|
3984
|
+
overdue: stripUrgency(agenda.overdue),
|
|
3985
|
+
meetings: meetings,
|
|
3986
|
+
waiting: stripUrgency(agenda.waiting),
|
|
3987
|
+
upcoming: upcoming,
|
|
3988
|
+
unscheduled: stripUrgency(agenda.unscheduled),
|
|
3989
|
+
conflicts: agenda.conflicts,
|
|
3990
|
+
counts: counts,
|
|
3991
|
+
}
|
|
3992
|
+
const evidence = await loadEvidence()
|
|
3993
|
+
const dataSha256 = evidence.sha256Hex(evidence.stableStringify(hashInput, { space: 0 }))
|
|
3994
|
+
const payloadInput = {
|
|
3995
|
+
localDay: hashInput.localDay,
|
|
3996
|
+
window: agenda.window,
|
|
3820
3997
|
mustDo: mustDo,
|
|
3821
3998
|
overdue: agenda.overdue,
|
|
3822
3999
|
meetings: meetings,
|
|
@@ -3824,19 +4001,26 @@ async function buildMorningReport(input) {
|
|
|
3824
4001
|
upcoming: upcoming,
|
|
3825
4002
|
unscheduled: agenda.unscheduled,
|
|
3826
4003
|
conflicts: agenda.conflicts,
|
|
3827
|
-
counts:
|
|
3828
|
-
|
|
3829
|
-
|
|
3830
|
-
|
|
3831
|
-
|
|
3832
|
-
|
|
3833
|
-
|
|
3834
|
-
|
|
3835
|
-
},
|
|
3836
|
-
|
|
3837
|
-
const
|
|
3838
|
-
|
|
3839
|
-
|
|
4004
|
+
counts: counts,
|
|
4005
|
+
}
|
|
4006
|
+
// Deterministic human priority list (score desc -> dueAt asc -> id asc); it is
|
|
4007
|
+
// presentation only and never enters dataSha256.
|
|
4008
|
+
const { selectTopUrgent } = await loadUrgency()
|
|
4009
|
+
const topLimit = Number.isInteger(input.top) && input.top >= 1 && input.top <= 5 ? input.top : 3
|
|
4010
|
+
const topCandidates = [
|
|
4011
|
+
...mustDo.map((item) => ({ ...item, source: 'today' })),
|
|
4012
|
+
...agenda.overdue.map((item) => ({ ...item, source: 'overdue' })),
|
|
4013
|
+
]
|
|
4014
|
+
const top = selectTopUrgent(topCandidates, { limit: topLimit }).map((item) => ({
|
|
4015
|
+
id: item.id,
|
|
4016
|
+
kind: item.kind,
|
|
4017
|
+
title: item.title,
|
|
4018
|
+
...(item.localTime ? { localTime: item.localTime } : {}),
|
|
4019
|
+
urgency: item.urgency,
|
|
4020
|
+
whyNow: item.urgency?.whyNow ?? '',
|
|
4021
|
+
source: item.source,
|
|
4022
|
+
}))
|
|
4023
|
+
return { agenda: agenda, today: today, risks: risks, hashInput: hashInput, payloadInput: payloadInput, dataSha256: dataSha256, top: top, topLimit: topLimit }
|
|
3840
4024
|
}
|
|
3841
4025
|
|
|
3842
4026
|
function morningMarkdown(report) {
|
|
@@ -3846,6 +4030,17 @@ function morningMarkdown(report) {
|
|
|
3846
4030
|
lines.push('# 晨报 ' + day + '(' + agendaWeekday(day) + ')')
|
|
3847
4031
|
lines.push('> 本地确定性生成 · 不含模型推理 · 数据哈希 sha256:' + report.dataSha256.slice(0, 16))
|
|
3848
4032
|
lines.push('')
|
|
4033
|
+
// 0.4.0 additive section: top-urgency view (<=3/--top). The full "今天必须做"
|
|
4034
|
+
// list below keeps its 0.3.2 meaning, so existing readers do not break.
|
|
4035
|
+
const urgencyLevelLabels = { low: '低', medium: '中', high: '高', critical: '急' }
|
|
4036
|
+
lines.push('## 今天优先(最多 ' + report.topLimit + ')')
|
|
4037
|
+
if (!report.top.length) lines.push('(无)')
|
|
4038
|
+
for (let index = 0; index < report.top.length; index++) {
|
|
4039
|
+
const item = report.top[index]
|
|
4040
|
+
const level = urgencyLevelLabels[item.urgency?.level] ?? String(item.urgency?.level ?? '低')
|
|
4041
|
+
lines.push((index + 1) + '. ' + item.title + (item.localTime ? '(今天 ' + item.localTime + ' 到期)' : '') + ',urgency ' + (item.urgency?.score ?? 0) + '/' + level + (item.whyNow ? ':' + item.whyNow : ''))
|
|
4042
|
+
}
|
|
4043
|
+
lines.push('')
|
|
3849
4044
|
lines.push('## 今天必须做')
|
|
3850
4045
|
if (!report.hashInput.mustDo.length) lines.push('(无)')
|
|
3851
4046
|
for (let index = 0; index < report.hashInput.mustDo.length; index++) {
|
|
@@ -3891,19 +4086,34 @@ async function morningReportCommand(args) {
|
|
|
3891
4086
|
const parsed = parseFlags(args)
|
|
3892
4087
|
const flags = parsed.flags
|
|
3893
4088
|
if (flags.help === true) {
|
|
3894
|
-
console.log('usage: advisers morning [digest morning] [--days 1..31] [--matter id] [--out file] [--json] [--now ISO]')
|
|
4089
|
+
console.log('usage: advisers morning [digest morning] [--days 1..31] [--matter id] [--top 1..5] [--out file] [--archive [--keep 1..365]] [--json] [--now ISO]')
|
|
3895
4090
|
return
|
|
3896
4091
|
}
|
|
3897
4092
|
const window = parseAgendaWindowFlags(flags, 'morning')
|
|
3898
4093
|
if (!window) return
|
|
4094
|
+
// 0.4.0 flags: --top (human priority count) and --keep (archive retention).
|
|
4095
|
+
let top
|
|
4096
|
+
if (flags.top !== undefined) {
|
|
4097
|
+
if (flags.top === true || !/^\d+$/.test(String(flags.top)) || Number(flags.top) < 1 || Number(flags.top) > 5) { agendaUsageFail('--top must be an integer 1..5'); return }
|
|
4098
|
+
top = Number(flags.top)
|
|
4099
|
+
}
|
|
4100
|
+
let keep
|
|
4101
|
+
if (flags.keep !== undefined) {
|
|
4102
|
+
if (flags.keep === true || !/^\d+$/.test(String(flags.keep)) || Number(flags.keep) < 1 || Number(flags.keep) > 365) { agendaUsageFail('--keep must be an integer 1..365'); return }
|
|
4103
|
+
keep = Number(flags.keep)
|
|
4104
|
+
}
|
|
3899
4105
|
try {
|
|
3900
4106
|
const inputs = loadAgendaInputs()
|
|
3901
4107
|
if (window.matterId) {
|
|
3902
4108
|
try { resolveMatterForCommand(inputs.ledger, window.matterId, 'morning') } catch (error) { agendaMatterErrorLine(error); return }
|
|
3903
4109
|
}
|
|
3904
|
-
const report = await buildMorningReport({ ledger: inputs.ledger, events: inputs.events, nowMs: window.nowMs, days: window.days, fromDay: window.fromDay, matterId: window.matterId })
|
|
4110
|
+
const report = await buildMorningReport({ ledger: inputs.ledger, events: inputs.events, nowMs: window.nowMs, days: window.days, fromDay: window.fromDay, matterId: window.matterId, top: top })
|
|
3905
4111
|
const markdown = morningMarkdown(report)
|
|
3906
|
-
const payload = Object.assign(
|
|
4112
|
+
const payload = Object.assign(
|
|
4113
|
+
{ ok: true, command: 'morning', generatedAt: new Date(window.nowMs).toISOString() },
|
|
4114
|
+
report.payloadInput,
|
|
4115
|
+
{ dataSha256: report.dataSha256, degraded: report.agenda.degraded, top: report.top, urgencyModelVersion: 1 },
|
|
4116
|
+
)
|
|
3907
4117
|
let outPath
|
|
3908
4118
|
if (flags.out !== undefined) {
|
|
3909
4119
|
if (typeof flags.out !== 'string') { agendaUsageFail('--out requires a file path'); return }
|
|
@@ -3912,9 +4122,45 @@ async function morningReportCommand(args) {
|
|
|
3912
4122
|
atomicWriteFileSync(outPath, markdown, { mode: 0o600 })
|
|
3913
4123
|
payload.out = outPath
|
|
3914
4124
|
}
|
|
4125
|
+
// 0.4.0 proactive: --archive is the only write path here. It takes the
|
|
4126
|
+
// writer lock (audit row brief.archive inside the same transaction), writes
|
|
4127
|
+
// briefs/<localDay>.md + latest.md atomically, and prunes old day files.
|
|
4128
|
+
let archiveInfo
|
|
4129
|
+
if (flags.archive === true) {
|
|
4130
|
+
const archive = await loadBriefArchive()
|
|
4131
|
+
const localDay = report.hashInput.localDay
|
|
4132
|
+
const writeBrief = () => archive.archiveBrief({ home: HOME, env: process.env, localDay, markdown, keep })
|
|
4133
|
+
try {
|
|
4134
|
+
if (dbStore()) {
|
|
4135
|
+
mutateWithAudit(() => { archiveInfo = writeBrief(); return null }, archive.briefAuditRow({ localDay }))
|
|
4136
|
+
} else {
|
|
4137
|
+
archiveInfo = writeBrief()
|
|
4138
|
+
}
|
|
4139
|
+
} catch (error) { reportCommandFailure(error); return }
|
|
4140
|
+
try {
|
|
4141
|
+
const scheduler = await loadScheduler()
|
|
4142
|
+
scheduler.recordSchedulerRunV2({ homeDir: HOME, at: new Date(window.nowMs), section: 'morning', result: 'ok', count: report.top.length, path: archiveInfo.path, dryRun: false })
|
|
4143
|
+
} catch (error) {
|
|
4144
|
+
console.error(sanitizeConsoleText('scheduler status not recorded: ' + (error?.message ?? error), { max: 2000 }))
|
|
4145
|
+
}
|
|
4146
|
+
payload.archive = {
|
|
4147
|
+
path: archiveInfo.path,
|
|
4148
|
+
latestPath: archiveInfo.latestPath,
|
|
4149
|
+
keep: archiveInfo.keep,
|
|
4150
|
+
bytes: archiveInfo.bytes,
|
|
4151
|
+
removed: archiveInfo.removed,
|
|
4152
|
+
failed: archiveInfo.failed,
|
|
4153
|
+
}
|
|
4154
|
+
}
|
|
3915
4155
|
if (flags.json === true) { console.log(JSON.stringify(payload, null, 2)); return }
|
|
3916
4156
|
process.stdout.write(markdown)
|
|
3917
4157
|
if (outPath) console.log('wrote ' + outPath + ' (mode 600)')
|
|
4158
|
+
if (archiveInfo) {
|
|
4159
|
+
console.log('已归档:' + sanitizeConsoleText(archiveInfo.path, { max: 240 }) + '(' + formatBytes(archiveInfo.bytes) + ',keep=' + archiveInfo.keep + ')')
|
|
4160
|
+
console.log('最新:' + sanitizeConsoleText(archiveInfo.latestPath, { max: 240 }))
|
|
4161
|
+
for (const removed of archiveInfo.removed) console.log('已删除:' + sanitizeConsoleText(removed, { max: 240 }))
|
|
4162
|
+
for (const failed of archiveInfo.failed) console.error(sanitizeConsoleText('归档清理失败:' + failed.path + ' (' + failed.code + ')', { max: 2000 }))
|
|
4163
|
+
}
|
|
3918
4164
|
} catch (error) { reportCommandFailure(error) }
|
|
3919
4165
|
}
|
|
3920
4166
|
|
|
@@ -4174,8 +4420,9 @@ function tick(ledger, asJson = false) {
|
|
|
4174
4420
|
* pointed at by `verifyFtsIntegrity()` / reader warnings ("advisers audit
|
|
4175
4421
|
* --rebuild-fts"). Runs in the single-writer lock inside one immediate
|
|
4176
4422
|
* transaction so a failure leaves the previous index intact, then verifies the
|
|
4177
|
-
* rebuilt index and records an audit row. `
|
|
4178
|
-
*
|
|
4423
|
+
* rebuilt index and records an audit row. `rebuildAllFtsIndexes()` (0.4.0)
|
|
4424
|
+
* rebuilds the v19 turn pair AND the v22 KB pair with the same probed tokenizer,
|
|
4425
|
+
* so a KB FTS drift is repairable here instead of only detectable.
|
|
4179
4426
|
*/
|
|
4180
4427
|
async function rebuildFtsIndexes({ asJson = false } = {}) {
|
|
4181
4428
|
let store
|
|
@@ -4190,7 +4437,7 @@ async function rebuildFtsIndexes({ asJson = false } = {}) {
|
|
|
4190
4437
|
try {
|
|
4191
4438
|
store.db.exec('BEGIN IMMEDIATE')
|
|
4192
4439
|
try {
|
|
4193
|
-
store.
|
|
4440
|
+
store.rebuildAllFtsIndexes()
|
|
4194
4441
|
store.db.exec('COMMIT')
|
|
4195
4442
|
} catch (error) {
|
|
4196
4443
|
try { store.db.exec('ROLLBACK') } catch {}
|
|
@@ -4398,6 +4645,17 @@ async function printPrivacy(args = []) {
|
|
|
4398
4645
|
ensureHome()
|
|
4399
4646
|
const asJson = args.includes('--json')
|
|
4400
4647
|
const prove = args.includes('--prove')
|
|
4648
|
+
// 0.4.0: surface x action x gate matrix generated from the policy registry
|
|
4649
|
+
// (read-only; no ledger rows). Replaces the hand-maintained coverage narrative.
|
|
4650
|
+
if (args.includes('--matrix')) {
|
|
4651
|
+
const policy = await loadPolicy()
|
|
4652
|
+
const matrix = policy.surfaceMatrix()
|
|
4653
|
+
const payload = { ok: true, command: 'privacy --matrix', policyVersion: matrix.policyVersion, rulesetVersion: matrix.rulesetVersion, generatedAt: new Date().toISOString(), rows: matrix.rows }
|
|
4654
|
+
if (asJson) { console.log(JSON.stringify(payload, null, 2)); return }
|
|
4655
|
+
console.log('policy matrix · policy v' + payload.policyVersion + ' · ruleset ' + payload.rulesetVersion + ' · generatedAt ' + payload.generatedAt)
|
|
4656
|
+
for (const row of payload.rows) console.log(row.surface + '\t' + row.actions.join(',') + '\t' + row.dataClass + '\t' + row.gate + '\tdefault=' + row.default)
|
|
4657
|
+
return
|
|
4658
|
+
}
|
|
4401
4659
|
const store = readStoreOrExit()
|
|
4402
4660
|
let audit = null
|
|
4403
4661
|
try { const v = store?.verifyAudit(); if (v) audit = { ok: v.ok, count: v.count ?? 0 } } catch {}
|
|
@@ -4438,6 +4696,8 @@ async function printPrivacy(args = []) {
|
|
|
4438
4696
|
'model provider — chat / brief --deep / review / learn review (only when ADVISERS_API_KEY is set; ADVISERS_BASE_URL)',
|
|
4439
4697
|
'research --web|--url — provider web search/read tool (explicit opt-in; no silent research egress)',
|
|
4440
4698
|
'capture --from-imap — read-only IMAP fetch from the server you configure (TLS by default)',
|
|
4699
|
+
'mail sync — IMAP server you configure (TLS/STARTTLS, read-only EXAMINE/FETCH)',
|
|
4700
|
+
'mail extract --model — mail body excerpts sent to the model provider only after explicit opt-in + separate consent (ADVISERS_API_KEY)',
|
|
4441
4701
|
'remind --deliver --notify — optional outbound webhook or local notifier you configure',
|
|
4442
4702
|
'sync push|pull — the directory you provide; snapshots are AES-256-GCM encrypted before writing',
|
|
4443
4703
|
'bridge — Hermes file gateway: inbox/outbox JSON files are handed to the Hermes process',
|
|
@@ -4494,7 +4754,7 @@ async function printPrivacy(args = []) {
|
|
|
4494
4754
|
console.log(`[FAIL] audit anchor ${auditAnchor.code ?? auditAnchor.status} (local self-check: the audit tail is shorter/rewritten vs the recorded anchor; see \`advisers audit\`)`)
|
|
4495
4755
|
}
|
|
4496
4756
|
}
|
|
4497
|
-
console.log('egress gate coverage: chat/model, review, research, brief --deep, learn review, bridge and
|
|
4757
|
+
console.log('egress gate coverage: chat/model, review, research, brief --deep, learn review, bridge, capture, mail sync and mail extract --model are wired to the local secrecy gate (mail extract --model also requires a separate consent record); the other surfaces listed above are self-attested.')
|
|
4498
4758
|
if (failed) process.exitCode = 1
|
|
4499
4759
|
}
|
|
4500
4760
|
}
|
|
@@ -5220,7 +5480,7 @@ async function doctorRepair(flags) {
|
|
|
5220
5480
|
if (!before.ok) {
|
|
5221
5481
|
store.db.exec('BEGIN IMMEDIATE')
|
|
5222
5482
|
try {
|
|
5223
|
-
store.
|
|
5483
|
+
store.rebuildAllFtsIndexes()
|
|
5224
5484
|
store.db.exec('COMMIT')
|
|
5225
5485
|
} catch (error) {
|
|
5226
5486
|
try { store.db.exec('ROLLBACK') } catch {}
|
|
@@ -5338,6 +5598,9 @@ function printStatus(asJson = false) {
|
|
|
5338
5598
|
// queries on the same read snapshot (no row materialisation).
|
|
5339
5599
|
clients: Number(store.db.prepare("SELECT COUNT(*) AS n FROM clients WHERE status = 'active' AND deleted_at IS NULL").get()?.n ?? 0),
|
|
5340
5600
|
projects: Number(store.db.prepare("SELECT COUNT(*) AS n FROM projects WHERE status = 'active' AND deleted_at IS NULL").get()?.n ?? 0),
|
|
5601
|
+
// 0.4.0 additive status counts: money rows (never amounts).
|
|
5602
|
+
receivables: Number(store.db.prepare('SELECT COUNT(*) AS n FROM receivables WHERE deleted_at IS NULL').get()?.n ?? 0),
|
|
5603
|
+
payments: Number(store.db.prepare('SELECT COUNT(*) AS n FROM payments WHERE deleted_at IS NULL').get()?.n ?? 0),
|
|
5341
5604
|
usage: store.sumModelUsage(),
|
|
5342
5605
|
}))
|
|
5343
5606
|
data.matters = counts.matters
|
|
@@ -5348,6 +5611,8 @@ function printStatus(asJson = false) {
|
|
|
5348
5611
|
data.deliveries = counts.deliveries
|
|
5349
5612
|
data.clients = counts.clients
|
|
5350
5613
|
data.projects = counts.projects
|
|
5614
|
+
data.receivables = counts.receivables
|
|
5615
|
+
data.payments = counts.payments
|
|
5351
5616
|
const usage = counts.usage
|
|
5352
5617
|
if (usage.calls) data.modelUsage = usage
|
|
5353
5618
|
}
|
|
@@ -5562,7 +5827,7 @@ async function runTurn(options) {
|
|
|
5562
5827
|
}
|
|
5563
5828
|
}
|
|
5564
5829
|
|
|
5565
|
-
async function runTurnInner({ runtime, ledger, text, conversationId, debug = false, confirm, attachments = [], allowPaths = [], renderWidth = null }) {
|
|
5830
|
+
async function runTurnInner({ runtime, ledger, text, conversationId, debug = false, confirm, attachments = [], allowPaths = [], renderWidth = null, signal = null }) {
|
|
5566
5831
|
// 0.3.0 Wave 3 (plan 26 §4.1): internal process lines ([tool]/[attach]/[compact])
|
|
5567
5832
|
// are hidden by default; ADVISERS_PROGRESS=1 (or /debug) is the explicit
|
|
5568
5833
|
// opt-in. Results, confirmations and failures are never gated.
|
|
@@ -5686,6 +5951,10 @@ async function runTurnInner({ runtime, ledger, text, conversationId, debug = fal
|
|
|
5686
5951
|
effort: process.env.ADVISERS_THINKING_EFFORT,
|
|
5687
5952
|
onTool: (name) => { if (showProgress) console.log('[tool] ' + sanitizeConsoleText(name, { max: 120 })) },
|
|
5688
5953
|
onToolAction: auditToolAction,
|
|
5954
|
+
// 0.4.0: the interactive shell passes an AbortSignal so Ctrl+C/Esc can
|
|
5955
|
+
// interrupt one turn; one-shot chat passes null and keeps the exact old
|
|
5956
|
+
// options object shape (no behavioural change).
|
|
5957
|
+
...(signal ? { signal } : {}),
|
|
5689
5958
|
})
|
|
5690
5959
|
// 0.2.3 Wave 1: consume the structured warnings (they used to be discarded)
|
|
5691
5960
|
// and treat a blocked turn as a failure, never as a successful reply.
|
|
@@ -6121,6 +6390,1469 @@ async function repl({ allowPaths = [] } = {}) {
|
|
|
6121
6390
|
saveLedger(ledger)
|
|
6122
6391
|
}
|
|
6123
6392
|
|
|
6393
|
+
/* ---------------------------------------------------------------------------
|
|
6394
|
+
* 0.4.0 Wave 1 (task-29): interactive shell entry.
|
|
6395
|
+
*
|
|
6396
|
+
* The state machine / rendering / paste guard live in lib/shell.js. This file
|
|
6397
|
+
* keeps the process-level concerns (the TOS gate already ran, the ledger and
|
|
6398
|
+
* model runtime, the writer lock) and injects read-only JSON views plus one
|
|
6399
|
+
* turn executor. The legacy REPL (repl) stays as the explicit fallback
|
|
6400
|
+
* (ADVISERS_NO_SHELL=1); a non-TTY stdin keeps the 0.3.x "print help, exit 0"
|
|
6401
|
+
* path byte for byte, and `advisers tui --once/--json` is untouched.
|
|
6402
|
+
* ------------------------------------------------------------------------- */
|
|
6403
|
+
|
|
6404
|
+
/** Today counts for the shell status line (same definition as repl()). */
|
|
6405
|
+
function shellTodayCounts(ledger, nowMs = Date.now()) {
|
|
6406
|
+
const today = localDayOf(nowMs)
|
|
6407
|
+
let due = 0
|
|
6408
|
+
let overdue = 0
|
|
6409
|
+
try {
|
|
6410
|
+
for (const commitment of ledger.openCommitments()) {
|
|
6411
|
+
if (!commitment.dueAt) continue
|
|
6412
|
+
const ms = Date.parse(commitment.dueAt)
|
|
6413
|
+
if (Number.isNaN(ms)) continue
|
|
6414
|
+
if (ms < nowMs && localDayOf(ms) !== today) overdue += 1
|
|
6415
|
+
else if (localDayOf(ms) === today) due += 1
|
|
6416
|
+
}
|
|
6417
|
+
} catch {}
|
|
6418
|
+
return { due, overdue }
|
|
6419
|
+
}
|
|
6420
|
+
|
|
6421
|
+
function shellModelState() {
|
|
6422
|
+
const local = !process.env.ADVISERS_API_KEY || process.env.ADVISERS_NO_MODEL === '1'
|
|
6423
|
+
return { local, model: local ? null : (process.env.ADVISERS_MODEL || 'deepseek-flash') }
|
|
6424
|
+
}
|
|
6425
|
+
|
|
6426
|
+
/**
|
|
6427
|
+
* Run legacy printing code and collect its stdout as result-block lines.
|
|
6428
|
+
* Keeps the old /commands alive inside the shell without a second command
|
|
6429
|
+
* surface: the functions print like before, the shell renders the captured
|
|
6430
|
+
* lines through the sanitising kernel.
|
|
6431
|
+
*/
|
|
6432
|
+
async function captureConsole(fn) {
|
|
6433
|
+
const lines = []
|
|
6434
|
+
const original = console.log
|
|
6435
|
+
console.log = (...values) => { lines.push(values.map((value) => (typeof value === 'string' ? value : String(value))).join(' ')) }
|
|
6436
|
+
try { await fn() } finally { console.log = original }
|
|
6437
|
+
return lines
|
|
6438
|
+
}
|
|
6439
|
+
|
|
6440
|
+
/** Read-only evidence view shared by /evidence (no exit-code side effects). */
|
|
6441
|
+
async function shellEvidenceBlock(id) {
|
|
6442
|
+
const store = mode === 'sqlite' ? readStore() : null
|
|
6443
|
+
const ledger = readLedgerForCommand(id.startsWith('fact_') ? { facts: {} } : id.startsWith('pref_') ? { preferences: {} } : { commitments: {} })
|
|
6444
|
+
const { evidenceForCommitment, evidenceForFact, evidenceForPreference } = await loadEvidence()
|
|
6445
|
+
const lookups = await buildEvidenceLookups(store)
|
|
6446
|
+
let result
|
|
6447
|
+
if (id.startsWith('cm_')) result = await evidenceForCommitment(store, ledger, id, undefined, { lookup: lookups })
|
|
6448
|
+
else if (id.startsWith('fact_')) result = await evidenceForFact(store, ledger, id, undefined, { lookup: lookups })
|
|
6449
|
+
else if (id.startsWith('pref_')) result = await evidenceForPreference(store, ledger, id, undefined, { lookup: lookups })
|
|
6450
|
+
else throw Object.assign(new Error('unknown evidence id prefix (want cm_/fact_/pref_)'), { code: 'E_USAGE' })
|
|
6451
|
+
if (!result || (!result.commitment && !result.fact && !result.preference)) throw new Error('not found: ' + id)
|
|
6452
|
+
await normalizeEvidenceSources(result)
|
|
6453
|
+
const unverifiable = Array.isArray(result.unverifiable) ? result.unverifiable : []
|
|
6454
|
+
const label = result.commitment ? result.commitment.action : result.fact ? result.fact.subject + ' ' + result.fact.predicate : result.preference?.statement
|
|
6455
|
+
const lines = []
|
|
6456
|
+
if (!result.sources.length && !unverifiable.length) lines.push({ role: 'fact', text: '(没有可回溯来源)' })
|
|
6457
|
+
for (const source of result.sources) lines.push({ role: 'fact', text: source.sessionId + '#' + source.turnId + ' 「' + String(source.quote ?? '').slice(0, 120) + '」' })
|
|
6458
|
+
for (const missing of result.missing) lines.push({ role: 'fact', text: 'MISSING ' + missing.reason + (missing.ref ? ' ' + missing.ref : '') })
|
|
6459
|
+
for (const item of unverifiable) lines.push({ role: 'fact', text: 'MANUAL 操作者录入(未外部核验) 「' + String(item.quote ?? '').slice(0, 120) + '」' })
|
|
6460
|
+
return { headline: String(id) + ' ' + String(label ?? ''), lines, next: 'advisers evidence show ' + id + ' --json' }
|
|
6461
|
+
}
|
|
6462
|
+
|
|
6463
|
+
/** Read-only client view for /client [id|list]. */
|
|
6464
|
+
function shellClientBlock(args, arg) {
|
|
6465
|
+
const store = readStore()
|
|
6466
|
+
if (!store) throw new Error('customer views need the SQLite store (ADVISERS_STORE=sqlite)')
|
|
6467
|
+
const words = Array.isArray(args) ? args : []
|
|
6468
|
+
const sub = words[0]
|
|
6469
|
+
if (!sub || sub === 'list' || sub === 'ls') {
|
|
6470
|
+
const rows = store.listClients({ status: 'active', limit: 50 })
|
|
6471
|
+
return {
|
|
6472
|
+
headline: '客户(' + rows.length + ')',
|
|
6473
|
+
lines: rows.length ? rows.map((client) => ({ role: 'item', text: client.id + ' ' + client.name })) : [{ role: 'fact', text: '(还没有客户)' }],
|
|
6474
|
+
next: 'advisers client show <id>',
|
|
6475
|
+
}
|
|
6476
|
+
}
|
|
6477
|
+
const id = sub === 'show' ? words[1] : sub
|
|
6478
|
+
if (!id) throw new Error('usage: /client [list|<id>]')
|
|
6479
|
+
const view = readClientView(store, id)
|
|
6480
|
+
const openRows = Array.isArray(view.open) ? view.open : []
|
|
6481
|
+
const lines = [
|
|
6482
|
+
{ role: 'fact', text: '状态 ' + String(view.client.status ?? 'active') + ' · secrecy ' + String(view.client.secrecyDefault ?? 0) },
|
|
6483
|
+
{ role: 'item', text: '项目 ' + view.projects.length + ' · 事项 ' + view.matters.length + ' · 未完成 ' + openRows.length + ' · 备注 ' + view.notes.length },
|
|
6484
|
+
]
|
|
6485
|
+
for (const item of openRows.slice(0, 5)) lines.push({ role: 'item', text: item.id + ' ' + String(item.action ?? item.title ?? '') })
|
|
6486
|
+
return { headline: view.client.name + ' [' + view.client.id + ']', lines, next: 'advisers client show ' + view.client.id + ' --json' }
|
|
6487
|
+
}
|
|
6488
|
+
|
|
6489
|
+
/** Open commitments grouped for /today and /who (no store reads). */
|
|
6490
|
+
function shellOpenRows(ledger) {
|
|
6491
|
+
const rows = []
|
|
6492
|
+
try {
|
|
6493
|
+
for (const commitment of ledger.openCommitments()) rows.push(commitment)
|
|
6494
|
+
} catch {}
|
|
6495
|
+
return rows
|
|
6496
|
+
}
|
|
6497
|
+
|
|
6498
|
+
/** Build the runShell() handler table for one interactive session. */
|
|
6499
|
+
async function runShellEntry({ allowPaths = [] } = {}) {
|
|
6500
|
+
const shell = await loadShell()
|
|
6501
|
+
ensureHome()
|
|
6502
|
+
const ledger = loadLedger()
|
|
6503
|
+
const runtime = runtimeFor(ledger)
|
|
6504
|
+
const state = {
|
|
6505
|
+
ledger,
|
|
6506
|
+
runtime,
|
|
6507
|
+
conversationId: latestConversationId(),
|
|
6508
|
+
debug: process.env.ADVISERS_DEBUG === '1',
|
|
6509
|
+
allowPaths: [...allowPaths],
|
|
6510
|
+
}
|
|
6511
|
+
const handlers = {
|
|
6512
|
+
status: () => {
|
|
6513
|
+
const model = shellModelState()
|
|
6514
|
+
return { kind: 'idle', today: shellTodayCounts(state.ledger), local: model.local, model: model.model, hint: '/help' }
|
|
6515
|
+
},
|
|
6516
|
+
turn: async (payload) => {
|
|
6517
|
+
let question
|
|
6518
|
+
try {
|
|
6519
|
+
question = await runTurn({
|
|
6520
|
+
runtime: state.runtime,
|
|
6521
|
+
ledger: state.ledger,
|
|
6522
|
+
text: payload.text,
|
|
6523
|
+
conversationId: state.conversationId,
|
|
6524
|
+
debug: state.debug,
|
|
6525
|
+
confirm: payload.confirm,
|
|
6526
|
+
attachments: Array.isArray(payload.attachments) ? payload.attachments : [],
|
|
6527
|
+
allowPaths: [...state.allowPaths, ...(Array.isArray(payload.allowPaths) ? payload.allowPaths : [])],
|
|
6528
|
+
renderWidth: null,
|
|
6529
|
+
signal: payload.signal ?? null,
|
|
6530
|
+
})
|
|
6531
|
+
} finally {
|
|
6532
|
+
try { saveLedger(state.ledger) } catch {}
|
|
6533
|
+
}
|
|
6534
|
+
if (lastTurnSafetyBlock) {
|
|
6535
|
+
return { kind: 'error', error: { title: '本轮被内容安全拦截', reason: '没有执行;未创建承诺或文件。', next: '/retry 或 /help', code: lastTurnSafetyBlock.code ?? undefined } }
|
|
6536
|
+
}
|
|
6537
|
+
if (question) return { question: String(question) }
|
|
6538
|
+
return undefined
|
|
6539
|
+
},
|
|
6540
|
+
history: async () => {
|
|
6541
|
+
const rows = dbStore()?.listSessions(50) ?? []
|
|
6542
|
+
return { sessions: rows.map((row, index) => ({ n: index + 1, id: row.conversationId, title: row.title, updatedAt: row.updatedAt })) }
|
|
6543
|
+
},
|
|
6544
|
+
resume: async ({ arg }) => {
|
|
6545
|
+
const rows = dbStore()?.listSessions(50) ?? []
|
|
6546
|
+
const pick = /^\d+$/.test(String(arg)) ? rows[Number(arg) - 1] : rows.find((row) => row.conversationId === arg)
|
|
6547
|
+
if (!pick) throw new Error('unknown session: ' + arg)
|
|
6548
|
+
state.conversationId = pick.conversationId
|
|
6549
|
+
return { kind: 'notice', headline: '已恢复会话', summary: String(pick.title ?? '') + ' [' + pick.conversationId + ']', next: '直接输入下一步' }
|
|
6550
|
+
},
|
|
6551
|
+
newSession: async () => {
|
|
6552
|
+
state.conversationId = 'local_' + Date.now()
|
|
6553
|
+
return { kind: 'notice', headline: '新会话', summary: '下一条消息写在新会话里' }
|
|
6554
|
+
},
|
|
6555
|
+
today: async () => {
|
|
6556
|
+
const nowMs = Date.now()
|
|
6557
|
+
const today = localDayOf(nowMs)
|
|
6558
|
+
const due = []
|
|
6559
|
+
const overdue = []
|
|
6560
|
+
for (const commitment of shellOpenRows(state.ledger)) {
|
|
6561
|
+
if (!commitment.dueAt) continue
|
|
6562
|
+
const ms = Date.parse(commitment.dueAt)
|
|
6563
|
+
if (Number.isNaN(ms)) continue
|
|
6564
|
+
if (ms < nowMs && localDayOf(ms) !== today) overdue.push(commitment)
|
|
6565
|
+
else if (localDayOf(ms) === today) due.push(commitment)
|
|
6566
|
+
}
|
|
6567
|
+
const lines = []
|
|
6568
|
+
for (const commitment of due.slice(0, 8)) lines.push({ role: 'item', text: '今天 · ' + commitment.id + ' ' + String(commitment.action) })
|
|
6569
|
+
for (const commitment of overdue.slice(0, 8)) lines.push({ role: 'item', text: '逾期 · ' + commitment.id + ' ' + String(commitment.action) + '(' + String(commitment.dueAt).slice(0, 10) + ')' })
|
|
6570
|
+
if (!lines.length) lines.push({ role: 'fact', text: '今天没有到期的承诺。' })
|
|
6571
|
+
return { headline: '今天 · 今天到期 ' + due.length + ' · 逾期 ' + overdue.length, lines, next: 'advisers today --json' }
|
|
6572
|
+
},
|
|
6573
|
+
remind: async () => {
|
|
6574
|
+
const { buildReminders } = await loadRemind()
|
|
6575
|
+
const snoozed = {}
|
|
6576
|
+
for (const [key, value] of readStore()?.listMetaByPrefix('snooze:') ?? []) snoozed[key.slice('snooze:'.length)] = value
|
|
6577
|
+
const reminders = buildReminders(state.ledger, { now: new Date(), snoozedUntil: snoozed })
|
|
6578
|
+
const lines = reminders.slice(0, 8).map((reminder) => ({ role: 'item', text: '[' + reminder.level + '/' + reminder.bucket + '] ' + String(reminder.action) + (reminder.dueAt ? ' · ' + String(reminder.dueAt).slice(0, 16) : '') }))
|
|
6579
|
+
return { headline: '提醒(' + reminders.length + ')', lines: lines.length ? lines : [{ role: 'fact', text: '现在没有到期的提醒。' }], next: 'advisers remind --json' }
|
|
6580
|
+
},
|
|
6581
|
+
who: async () => {
|
|
6582
|
+
const open = shellOpenRows(state.ledger)
|
|
6583
|
+
const mine = open.filter((commitment) => commitment.debtor === 'user' || commitment.debtor === 'agent')
|
|
6584
|
+
const waiting = open.filter((commitment) => commitment.debtor === 'third' || String(commitment.debtor).startsWith('third:'))
|
|
6585
|
+
const lines = []
|
|
6586
|
+
for (const commitment of mine) lines.push({ role: 'item', text: '我欠 ' + commitment.id + ' ' + commitment.creditor + ' · ' + String(commitment.action) })
|
|
6587
|
+
for (const commitment of waiting) lines.push({ role: 'item', text: '等人 ' + commitment.id + ' ' + String(commitment.action) })
|
|
6588
|
+
return { headline: '我欠别人 ' + mine.length + ' · 等别人 ' + waiting.length, lines: lines.length ? lines.slice(0, 12) : [{ role: 'fact', text: '(没有未完成的承诺)' }], next: 'advisers who' }
|
|
6589
|
+
},
|
|
6590
|
+
client: async ({ args, arg }) => shellClientBlock(args, arg),
|
|
6591
|
+
evidence: async ({ arg }) => {
|
|
6592
|
+
if (!arg) throw Object.assign(new Error('usage: /evidence <cm_|fact_|pref_ id>'), { code: 'E_USAGE' })
|
|
6593
|
+
return shellEvidenceBlock(String(arg).split(/\s+/)[0])
|
|
6594
|
+
},
|
|
6595
|
+
opening: async () => {
|
|
6596
|
+
const lines = await captureConsole(() => printOpening(state.conversationId))
|
|
6597
|
+
return lines.filter((line) => line.trim() !== '').slice(0, 2)
|
|
6598
|
+
},
|
|
6599
|
+
legacyCommand: async ({ name, args, arg }) => {
|
|
6600
|
+
const sub = Array.isArray(args) ? args[0] : undefined
|
|
6601
|
+
switch (name) {
|
|
6602
|
+
case '/deliveries': { const lines = await captureConsole(() => printDeliveries()); return { lines } }
|
|
6603
|
+
case '/tick': { const lines = await captureConsole(() => tick(state.ledger)); return { lines } }
|
|
6604
|
+
case '/week': { const lines = await captureConsole(() => printWeek(state.ledger)); return { lines } }
|
|
6605
|
+
case '/memory': { const lines = await captureConsole(() => printMemory(state.ledger)); return { lines } }
|
|
6606
|
+
case '/prefs': { const lines = await captureConsole(() => printPreferences()); return { lines } }
|
|
6607
|
+
case '/links': { const lines = await captureConsole(() => printLinks()); return { lines } }
|
|
6608
|
+
case '/audit': { const lines = await captureConsole(() => auditCommand([])); return { lines } }
|
|
6609
|
+
case '/agenda': {
|
|
6610
|
+
const lines = await captureConsole(async () => {
|
|
6611
|
+
const inputs = loadAgendaInputs()
|
|
6612
|
+
const data = await buildAgendaData({ ledger: inputs.ledger, events: inputs.events, nowMs: Date.now(), days: 7, includeCalendar: true, includeDone: false })
|
|
6613
|
+
printAgenda(data)
|
|
6614
|
+
})
|
|
6615
|
+
return { lines }
|
|
6616
|
+
}
|
|
6617
|
+
case '/search': {
|
|
6618
|
+
const query = String(arg ?? '').trim()
|
|
6619
|
+
if (!query) throw Object.assign(new Error('usage: /search <text>'), { code: 'E_USAGE' })
|
|
6620
|
+
const rows = dbStore()?.searchTurns(query, { limit: 10 }) ?? []
|
|
6621
|
+
return { headline: '搜索 · ' + query, lines: rows.length ? rows.map((row) => ({ role: 'item', text: row.seq + '\t' + row.role + '\t' + String(row.content).replace(/\s+/g, ' ').slice(0, 160) })) : [{ role: 'fact', text: '没有匹配' }] }
|
|
6622
|
+
}
|
|
6623
|
+
case '/digest': {
|
|
6624
|
+
const lines = await captureConsole(async () => {
|
|
6625
|
+
const store = dbStore()
|
|
6626
|
+
const { buildDigest } = await loadDigest()
|
|
6627
|
+
console.log(buildDigest({
|
|
6628
|
+
period: String(arg ?? '').endsWith('week') ? 'week' : 'day',
|
|
6629
|
+
turns: store?.listTurns(state.conversationId, 200) ?? [],
|
|
6630
|
+
commitments: state.ledger.listCommitments(),
|
|
6631
|
+
deliveries: store?.listDeliveries(100) ?? [],
|
|
6632
|
+
}))
|
|
6633
|
+
})
|
|
6634
|
+
return { lines }
|
|
6635
|
+
}
|
|
6636
|
+
case '/diff': { const lines = await captureConsole(async () => { const { diffLatest } = await loadUndo(); const result = await diffLatest({ cwd: process.cwd(), backupDir: join(HOME, 'undo') }); console.log(result.ok ? result.diff : 'diff failed: ' + result.error) }); return { lines } }
|
|
6637
|
+
case '/undo': { const lines = await captureConsole(async () => { const { undoLatest } = await loadUndo(); const result = await undoLatest({ cwd: process.cwd(), backupDir: join(HOME, 'undo'), force: args.includes('--force') }); console.log(result.ok ? '已回滚:' + result.path : '撤销失败:' + result.error) }); return { lines } }
|
|
6638
|
+
case '/why': { const id = String(arg ?? '').trim(); if (!id) throw Object.assign(new Error('usage: /why <pref-id>'), { code: 'E_USAGE' }); const lines = await captureConsole(() => why(id)); return { lines } }
|
|
6639
|
+
case '/debug': {
|
|
6640
|
+
state.debug = !state.debug
|
|
6641
|
+
return { kind: 'notice', headline: state.debug ? '明细已开启' : '明细已关闭', summary: state.debug ? '会打印上下文与内部行。' : undefined }
|
|
6642
|
+
}
|
|
6643
|
+
case '/forget': {
|
|
6644
|
+
const id = String(arg ?? '').trim()
|
|
6645
|
+
if (!id) throw Object.assign(new Error('usage: /forget <pref-id>'), { code: 'E_USAGE' })
|
|
6646
|
+
const ok = state.ledger.forget('preference', id)
|
|
6647
|
+
saveLedger(state.ledger)
|
|
6648
|
+
return { kind: 'notice', headline: ok ? '已忘记:' + id : '没有这条偏好:' + id }
|
|
6649
|
+
}
|
|
6650
|
+
case '/correct': {
|
|
6651
|
+
const statement = String(arg ?? '').trim()
|
|
6652
|
+
if (!statement) throw Object.assign(new Error('usage: /correct <text>'), { code: 'E_USAGE' })
|
|
6653
|
+
const lines = await captureConsole(() => { const result = learnPreference(state.ledger, statement, statement); saveLedger(state.ledger); printLearnReceipt(result) })
|
|
6654
|
+
return { lines }
|
|
6655
|
+
}
|
|
6656
|
+
case '/decay': {
|
|
6657
|
+
const lines = await captureConsole(async () => { const { applyPreferenceDecay } = await loadLearning(); const changed = applyPreferenceDecay(state.ledger.listPreferences({ includeCandidates: true })); saveLedger(state.ledger); console.log('[decay] ' + changed.length + ' preference(s) updated') })
|
|
6658
|
+
return { lines }
|
|
6659
|
+
}
|
|
6660
|
+
case '/matter': {
|
|
6661
|
+
const useId = sub === 'use' && Array.isArray(args) ? args[1] : undefined
|
|
6662
|
+
if (!useId) throw Object.assign(new Error('usage: /matter use <matter-id>'), { code: 'E_USAGE' })
|
|
6663
|
+
const matter = state.ledger.getMatter(useId)
|
|
6664
|
+
if (!matter) throw new Error('unknown matter: ' + useId)
|
|
6665
|
+
if (matter.status !== 'active') throw new Error('matter 已归档:' + useId)
|
|
6666
|
+
state.ledger.setRoute('active-matter', useId)
|
|
6667
|
+
saveLedger(state.ledger)
|
|
6668
|
+
return { kind: 'notice', headline: 'active matter: ' + useId, summary: String(matter.title ?? '') }
|
|
6669
|
+
}
|
|
6670
|
+
case '/commit': {
|
|
6671
|
+
const { flags, positional } = parseFlags(Array.isArray(args) ? args : [])
|
|
6672
|
+
if (positional[0] === 'ls') { const lines = await captureConsole(() => printCommitments(state.ledger)); return { lines } }
|
|
6673
|
+
if (positional[0] === 'add') {
|
|
6674
|
+
const action = positional.slice(1).join(' ')
|
|
6675
|
+
if (!action || !flags.quote) throw Object.assign(new Error('用法:/commit add <action> --quote <原话> [--due ISO]'), { code: 'E_USAGE' })
|
|
6676
|
+
const c = state.ledger.addCommitment({ matterId: resolveMatterForCommand(state.ledger, flags.matter, 'commit add'), debtor: flags.debtor ?? 'user', creditor: flags.creditor ?? 'me', action, dueAt: flags.due, capability: 'todo', evidence: [manualEvidence(String(flags.quote), 'repl commit add')] })
|
|
6677
|
+
saveLedger(state.ledger)
|
|
6678
|
+
return { kind: 'notice', headline: c.id + ' open ' + c.action }
|
|
6679
|
+
}
|
|
6680
|
+
throw Object.assign(new Error('用法:/commit add ... 或 /commit ls'), { code: 'E_USAGE' })
|
|
6681
|
+
}
|
|
6682
|
+
case '/done': {
|
|
6683
|
+
const { flags, positional } = parseFlags(Array.isArray(args) ? args : [])
|
|
6684
|
+
const id = positional[0]
|
|
6685
|
+
if (!id || !flags.evidence) throw Object.assign(new Error('用法:/done <id> --evidence <证据>'), { code: 'E_USAGE' })
|
|
6686
|
+
state.ledger.completeCommitment(id, [manualEvidence(String(flags.evidence), 'repl commit done')])
|
|
6687
|
+
saveLedger(state.ledger)
|
|
6688
|
+
return { kind: 'notice', headline: 'done: ' + id }
|
|
6689
|
+
}
|
|
6690
|
+
case '/routine': {
|
|
6691
|
+
if (sub !== 'save') throw Object.assign(new Error('usage: /routine save'), { code: 'E_USAGE' })
|
|
6692
|
+
const last = lastRun
|
|
6693
|
+
const routine = state.ledger.addRoutine({
|
|
6694
|
+
name: (last?.toolLog?.map((tool) => tool.name).join(' ') || '本地任务').slice(0, 60),
|
|
6695
|
+
description: '从本地任务沉淀的流程草稿',
|
|
6696
|
+
trigger: [],
|
|
6697
|
+
steps: last?.toolLog?.map((tool) => tool.name).length ? last.toolLog.map((tool) => tool.name) : ['执行任务'],
|
|
6698
|
+
preferences: [],
|
|
6699
|
+
pitfalls: [],
|
|
6700
|
+
verification: ['产物已生成并记录 delivery'],
|
|
6701
|
+
createdBy: 'agent',
|
|
6702
|
+
})
|
|
6703
|
+
saveLedger(state.ledger)
|
|
6704
|
+
return { kind: 'notice', headline: 'draft routine ' + routine.id, summary: String(routine.name), next: 'advisers routine approve ' + routine.id }
|
|
6705
|
+
}
|
|
6706
|
+
case '/brief': {
|
|
6707
|
+
const text = String(arg ?? '').trim()
|
|
6708
|
+
if (!text) throw Object.assign(new Error('usage: /brief <text>'), { code: 'E_USAGE' })
|
|
6709
|
+
const lines = await captureConsole(() => { const brief = state.runtime.brief(text); console.log(core.renderIntentBrief(brief)); console.log(core.renderReadback(brief)) })
|
|
6710
|
+
return { lines }
|
|
6711
|
+
}
|
|
6712
|
+
default:
|
|
6713
|
+
return undefined
|
|
6714
|
+
}
|
|
6715
|
+
},
|
|
6716
|
+
}
|
|
6717
|
+
const result = await shell.runShell({
|
|
6718
|
+
argv: outputArgv,
|
|
6719
|
+
env: process.env,
|
|
6720
|
+
stdin: process.stdin,
|
|
6721
|
+
stdout: process.stdout,
|
|
6722
|
+
stderr: process.stderr,
|
|
6723
|
+
store: null,
|
|
6724
|
+
allowPaths: state.allowPaths,
|
|
6725
|
+
handlers,
|
|
6726
|
+
})
|
|
6727
|
+
try { saveLedger(state.ledger) } catch {}
|
|
6728
|
+
return result
|
|
6729
|
+
}
|
|
6730
|
+
|
|
6731
|
+
|
|
6732
|
+
/* ---------------------------------------------------------------------------
|
|
6733
|
+
* 0.4.0 Wave 2 (task-29): KB / fact / scoped-search commands.
|
|
6734
|
+
*
|
|
6735
|
+
* Design source: 04-0.4-research/45-kb-design.md sections 3.4-3.7. Human output
|
|
6736
|
+
* and machine output stay separate: --json prints one JSON document and nothing
|
|
6737
|
+
* else; failures go to stderr as {error:{code,message,hint?}} with exit code 1
|
|
6738
|
+
* (the TOS gate still uses 3).
|
|
6739
|
+
* ------------------------------------------------------------------------- */
|
|
6740
|
+
|
|
6741
|
+
/** One structured family error (new 0.4 command family style). */
|
|
6742
|
+
function familyError(code, message, hint) {
|
|
6743
|
+
const error = new Error(message)
|
|
6744
|
+
error.code = code
|
|
6745
|
+
if (typeof hint === 'string' && hint) error.hint = hint
|
|
6746
|
+
return error
|
|
6747
|
+
}
|
|
6748
|
+
|
|
6749
|
+
/** Print one family failure as stderr JSON and exit 1 (store failures keep the
|
|
6750
|
+
* documented E_DB_* hint path instead). */
|
|
6751
|
+
function reportFamilyFailure(error) {
|
|
6752
|
+
if (isStoreWriteFailure(error)) { exitStoreWriteFailure(error); return }
|
|
6753
|
+
const code = typeof error?.code === 'string' && error.code ? error.code : 'E_INTERNAL'
|
|
6754
|
+
let message = String(error?.message ?? error)
|
|
6755
|
+
if (message.startsWith(code + ': ')) message = message.slice(code.length + 2)
|
|
6756
|
+
const hintTail = message.lastIndexOf(' (hint: ')
|
|
6757
|
+
if (hintTail !== -1 && message.endsWith(')')) message = message.slice(0, hintTail)
|
|
6758
|
+
const payload = { error: { code, message } }
|
|
6759
|
+
if (typeof error?.hint === 'string' && error.hint) payload.error.hint = error.hint
|
|
6760
|
+
console.error(JSON.stringify(payload))
|
|
6761
|
+
process.exitCode = 1
|
|
6762
|
+
}
|
|
6763
|
+
|
|
6764
|
+
/** Resolve the SQLite store for a family command (null in JSON-store mode). */
|
|
6765
|
+
function familyStore({ write = false } = {}) {
|
|
6766
|
+
if (mode !== 'sqlite') {
|
|
6767
|
+
throw familyError('E_STORE_REQUIRED', 'this command needs the SQLite store (ADVISERS_STORE=sqlite)', 'unset ADVISERS_STORE=json or run advisers doctor')
|
|
6768
|
+
}
|
|
6769
|
+
if (write) {
|
|
6770
|
+
const store = dbStore()
|
|
6771
|
+
if (!store) throw familyError('E_STORE_REQUIRED', 'the SQLite store is unavailable for writing', 'run advisers doctor')
|
|
6772
|
+
return store
|
|
6773
|
+
}
|
|
6774
|
+
return readStoreOrExit()
|
|
6775
|
+
}
|
|
6776
|
+
|
|
6777
|
+
/** Shared strict flag parse that reports E_USAGE for the family commands. */
|
|
6778
|
+
function familyFlags(args, spec, usage) {
|
|
6779
|
+
const parsed = parseStrictFlags(args, spec)
|
|
6780
|
+
if (!parsed.ok) { usageFail(parsed.error, usage); return null }
|
|
6781
|
+
return parsed
|
|
6782
|
+
}
|
|
6783
|
+
|
|
6784
|
+
function familyInteger(value, name, min, max) {
|
|
6785
|
+
if (value === undefined) return undefined
|
|
6786
|
+
if (!/^\d+$/.test(String(value))) throw familyError('E_USAGE', name + ' must be an integer')
|
|
6787
|
+
const number = Number(value)
|
|
6788
|
+
if (number < min || number > max) throw familyError('E_USAGE', name + ' must be an integer ' + min + '..' + max)
|
|
6789
|
+
return number
|
|
6790
|
+
}
|
|
6791
|
+
|
|
6792
|
+
const KB_USAGE = [
|
|
6793
|
+
'usage: advisers kb add <file>... [--title s] [--kind quote|contract|receipt|delivery|note|other]',
|
|
6794
|
+
' [--client id] [--project id] [--matter id] [--secrecy 0-3] [--replace] [--from list.txt] [--json]',
|
|
6795
|
+
' advisers kb ls [--client|--matter|--kind] [--all] [--limit n] [--clearance 0-3] [--json]',
|
|
6796
|
+
' advisers kb show <id> [--chunks 0..20] [--json]',
|
|
6797
|
+
' advisers kb rm <id> [--json]',
|
|
6798
|
+
' advisers kb purge <id> [--dry-run|--yes] [--json]',
|
|
6799
|
+
' advisers kb reindex [--rebuild] [--json]',
|
|
6800
|
+
' advisers kb search <query> [--scope kb|pages|all] [--limit n] [--clearance 0-3] [--json]',
|
|
6801
|
+
' advisers kb page ls|show|rebuild|diff ... [--json]',
|
|
6802
|
+
' advisers kb link <doc-id> --fact <fact-id> [--relation source|mentions] [--chunk id] [--json]',
|
|
6803
|
+
' advisers kb unlink <doc-id> --fact <fact-id> [--relation source|mentions] [--json]',
|
|
6804
|
+
].join('\n')
|
|
6805
|
+
|
|
6806
|
+
function kbDocRowText(doc) {
|
|
6807
|
+
return doc.id + ' ' + doc.kind + ' ' + (doc.status === 'active' ? '' : '[' + doc.status + '] ') + doc.title + ' (' + doc.chunkCount + ' chunks, ' + doc.sizeBytes + ' B)'
|
|
6808
|
+
}
|
|
6809
|
+
|
|
6810
|
+
async function kbAddCommand(args) {
|
|
6811
|
+
const usage = 'usage: advisers kb add <file>... [--title s] [--kind k] [--client id] [--project id] [--matter id] [--secrecy 0-3] [--replace] [--from list.txt] [--json]'
|
|
6812
|
+
const parsed = familyFlags(args, { booleans: ['json', 'replace'], values: ['title', 'kind', 'client', 'project', 'matter', 'secrecy', 'from'] }, usage)
|
|
6813
|
+
if (!parsed) return
|
|
6814
|
+
const flags = parsed.flags
|
|
6815
|
+
let secrecy
|
|
6816
|
+
if (flags.secrecy !== undefined) secrecy = familyInteger(flags.secrecy, '--secrecy', 0, 3)
|
|
6817
|
+
const files = [...parsed.positional]
|
|
6818
|
+
if (typeof flags.from === 'string') {
|
|
6819
|
+
let list
|
|
6820
|
+
try { list = readFileSync(flags.from, 'utf8') } catch (error) { throw familyError('E_KB_READ', 'cannot read --from list: ' + (error?.message ?? error)) }
|
|
6821
|
+
for (const line of list.split(/\r?\n/)) {
|
|
6822
|
+
const value = line.trim()
|
|
6823
|
+
if (value && !value.startsWith('#')) files.push(value)
|
|
6824
|
+
}
|
|
6825
|
+
}
|
|
6826
|
+
if (!files.length) { usageFail('no input files', usage); return }
|
|
6827
|
+
const store = familyStore({ write: true })
|
|
6828
|
+
const kb = await loadKb()
|
|
6829
|
+
const added = []
|
|
6830
|
+
const skipped = []
|
|
6831
|
+
const failed = []
|
|
6832
|
+
let chunks = 0
|
|
6833
|
+
let textBytes = 0
|
|
6834
|
+
let truncated = 0
|
|
6835
|
+
let needsOcr = 0
|
|
6836
|
+
for (const file of files) {
|
|
6837
|
+
try {
|
|
6838
|
+
const result = await kb.kbAdd(store, { file, title: flags.title, kind: flags.kind, clientId: flags.client, projectId: flags.project, matterId: flags.matter, secrecy, replace: flags.replace === true, hmacKey: process.env.ADVISERS_AUDIT_KEY })
|
|
6839
|
+
const doc = result.document
|
|
6840
|
+
added.push({ id: doc.id, title: doc.title, kind: doc.kind, sizeBytes: doc.sizeBytes, textBytes: result.counts.textBytes, chunks: result.counts.chunks, truncated: result.truncated, needsOcr: doc.needsOcr, encoding: doc.encoding })
|
|
6841
|
+
chunks += result.counts.chunks
|
|
6842
|
+
textBytes += result.counts.textBytes
|
|
6843
|
+
if (result.truncated) truncated += 1
|
|
6844
|
+
if (doc.needsOcr) needsOcr += 1
|
|
6845
|
+
} catch (error) {
|
|
6846
|
+
if (error?.skip === true) skipped.push({ file, code: error.code ?? 'E_KB_DUPLICATE', existingId: error.existingId })
|
|
6847
|
+
else failed.push({ file, code: typeof error?.code === 'string' ? error.code : 'E_KB_INVALID', message: String(error?.message ?? error) })
|
|
6848
|
+
}
|
|
6849
|
+
}
|
|
6850
|
+
const payload = { ok: failed.length === 0, command: 'kb add', counts: { added: added.length, skipped: skipped.length, failed: failed.length, chunks, textBytes }, added, skipped, failed, truncated, needsOcr }
|
|
6851
|
+
if (failed.length) process.exitCode = 1
|
|
6852
|
+
if (flags.json) { console.log(JSON.stringify(payload, null, 2)); return }
|
|
6853
|
+
for (const item of added) console.log('added ' + item.id + ' ' + item.title + ' (' + item.chunks + ' chunks, ' + item.textBytes + ' B text)')
|
|
6854
|
+
for (const item of skipped) console.log('skipped ' + item.file + ' ' + item.code + (item.existingId ? ' existing ' + item.existingId : ''))
|
|
6855
|
+
for (const item of failed) console.error('failed ' + item.file + ' ' + item.code + ': ' + item.message)
|
|
6856
|
+
console.log('counts: added=' + added.length + ' skipped=' + skipped.length + ' failed=' + failed.length + ' chunks=' + chunks + ' textBytes=' + textBytes)
|
|
6857
|
+
}
|
|
6858
|
+
|
|
6859
|
+
async function kbListCommand(args) {
|
|
6860
|
+
const usage = 'usage: advisers kb ls [--client id] [--matter id] [--kind k] [--all] [--limit n] [--clearance 0-3] [--json]'
|
|
6861
|
+
const parsed = familyFlags(args, { booleans: ['json', 'all'], values: ['client', 'matter', 'kind', 'limit', 'clearance'] }, usage)
|
|
6862
|
+
if (!parsed) return
|
|
6863
|
+
const flags = parsed.flags
|
|
6864
|
+
const store = familyStore()
|
|
6865
|
+
const kb = await loadKb()
|
|
6866
|
+
const result = kb.kbList(store, {
|
|
6867
|
+
clientId: flags.client,
|
|
6868
|
+
matterId: flags.matter,
|
|
6869
|
+
kind: flags.kind,
|
|
6870
|
+
all: flags.all === true,
|
|
6871
|
+
limit: familyInteger(flags.limit, '--limit', 1, 200),
|
|
6872
|
+
clearance: familyInteger(flags.clearance, '--clearance', 0, 3),
|
|
6873
|
+
})
|
|
6874
|
+
if (flags.json) { console.log(JSON.stringify(result, null, 2)); return }
|
|
6875
|
+
if (!result.documents.length) console.log('(没有 KB 文档)')
|
|
6876
|
+
for (const doc of result.documents) console.log(kbDocRowText(doc))
|
|
6877
|
+
console.log('total=' + result.total + ' limit=' + result.limit + ' clearance=' + result.clearance + (result.truncated ? ' truncated' : '') + (result.protectedExcluded ? ' protectedExcluded=' + result.protectedExcluded : ''))
|
|
6878
|
+
}
|
|
6879
|
+
|
|
6880
|
+
async function kbShowCommand(args) {
|
|
6881
|
+
const usage = 'usage: advisers kb show <id> [--chunks 0..20] [--clearance 0-3] [--json]'
|
|
6882
|
+
const parsed = familyFlags(args, { booleans: ['json'], values: ['chunks', 'clearance'] }, usage)
|
|
6883
|
+
if (!parsed) return
|
|
6884
|
+
const id = parsed.positional[0]
|
|
6885
|
+
if (!id) { usageFail('missing document id', usage); return }
|
|
6886
|
+
const kb = await loadKb()
|
|
6887
|
+
const result = kb.kbShow(familyStore(), id, { chunks: familyInteger(parsed.flags.chunks, '--chunks', 0, 20), clearance: familyInteger(parsed.flags.clearance, '--clearance', 0, 3) })
|
|
6888
|
+
if (parsed.flags.json) { console.log(JSON.stringify(result, null, 2)); return }
|
|
6889
|
+
const doc = result.document
|
|
6890
|
+
console.log(doc.id + ' ' + doc.kind + ' ' + doc.title)
|
|
6891
|
+
console.log('size=' + doc.sizeBytes + ' textBytes=' + doc.textBytes + ' chunks=' + doc.chunkCount + ' secrecy=' + doc.secrecy + ' status=' + doc.status)
|
|
6892
|
+
console.log('source=' + doc.sourceName + ' sha256=' + String(doc.sourceSha256 ?? '').slice(0, 16) + ' capturedAt=' + doc.capturedAt)
|
|
6893
|
+
if (result.chunks.length) {
|
|
6894
|
+
console.log('chunks (showing ' + result.chunks.length + '/' + result.chunksTotal + '):')
|
|
6895
|
+
for (const chunk of result.chunks) console.log(' #' + chunk.seq + ' ' + chunk.text + (chunk.truncated ? '…' : ''))
|
|
6896
|
+
}
|
|
6897
|
+
}
|
|
6898
|
+
|
|
6899
|
+
async function kbRmCommand(args) {
|
|
6900
|
+
const usage = 'usage: advisers kb rm <id> [--json]'
|
|
6901
|
+
const parsed = familyFlags(args, { booleans: ['json'], values: [] }, usage)
|
|
6902
|
+
if (!parsed) return
|
|
6903
|
+
const id = parsed.positional[0]
|
|
6904
|
+
if (!id) { usageFail('missing document id', usage); return }
|
|
6905
|
+
const kb = await loadKb()
|
|
6906
|
+
const result = kb.kbRm(familyStore({ write: true }), id)
|
|
6907
|
+
if (parsed.flags.json) { console.log(JSON.stringify(result, null, 2)); return }
|
|
6908
|
+
console.log('removed ' + result.document.id + ' ' + result.document.title + ' (' + result.counts.chunks + ' chunks)')
|
|
6909
|
+
}
|
|
6910
|
+
|
|
6911
|
+
async function kbPurgeCommand(args) {
|
|
6912
|
+
const usage = 'usage: advisers kb purge <id> [--dry-run|--yes] [--json]'
|
|
6913
|
+
const parsed = familyFlags(args, { booleans: ['json', 'dry-run', 'yes'], values: [] }, usage)
|
|
6914
|
+
if (!parsed) return
|
|
6915
|
+
const id = parsed.positional[0]
|
|
6916
|
+
if (!id) { usageFail('missing document id', usage); return }
|
|
6917
|
+
let yes = parsed.flags.yes === true
|
|
6918
|
+
if (!yes && parsed.flags['dry-run'] !== true && process.stdin.isTTY) yes = await askYesNo(null, '永久删除 KB 文档 ' + id + '?[y/N] ', false)
|
|
6919
|
+
const kb = await loadKb()
|
|
6920
|
+
const result = kb.kbPurge(familyStore({ write: yes }), id, { yes })
|
|
6921
|
+
if (parsed.flags.json) { console.log(JSON.stringify(result, null, 2)); return }
|
|
6922
|
+
if (result.dryRun) console.log('dry-run: 会物理删除 ' + id + '(chunks=' + result.counts.chunks + ', factLinks=' + result.counts.factLinks + ');加 --yes 执行')
|
|
6923
|
+
else console.log('purged ' + result.document.id + ' (' + result.counts.chunks + ' chunks, ' + result.counts.factLinks + ' fact links)')
|
|
6924
|
+
}
|
|
6925
|
+
|
|
6926
|
+
async function kbReindexCommand(args) {
|
|
6927
|
+
const usage = 'usage: advisers kb reindex [--rebuild] [--json]'
|
|
6928
|
+
const parsed = familyFlags(args, { booleans: ['json', 'rebuild'], values: [] }, usage)
|
|
6929
|
+
if (!parsed) return
|
|
6930
|
+
const kb = await loadKb()
|
|
6931
|
+
// kbReindex() may rebuild (a write) when the integrity probe fails, so it
|
|
6932
|
+
// always runs on the writable store (one audit row when anything changed).
|
|
6933
|
+
const store = familyStore({ write: true })
|
|
6934
|
+
const result = kb.kbReindex(store, { rebuild: parsed.flags.rebuild === true })
|
|
6935
|
+
if (parsed.flags.json) { console.log(JSON.stringify(result, null, 2)); return }
|
|
6936
|
+
console.log('integrity: ' + (result.integrity.ok ? 'ok' : 'BROKEN') + ' tokenizer=' + (result.integrity.tokenizer ?? 'LIKE-only'))
|
|
6937
|
+
if (result.rebuilt.length) console.log('rebuilt: ' + result.rebuilt.join(', '))
|
|
6938
|
+
else console.log('rebuilt: none (indexes already consistent; --rebuild forces)')
|
|
6939
|
+
console.log('counts: documents=' + result.counts.documents + ' chunks=' + result.counts.chunks + ' pages=' + result.counts.pages)
|
|
6940
|
+
if (result.degraded.length) console.log('degraded: ' + result.degraded.join(', '))
|
|
6941
|
+
if (!result.ok) process.exitCode = 1
|
|
6942
|
+
}
|
|
6943
|
+
|
|
6944
|
+
async function kbPageCommand(args) {
|
|
6945
|
+
const usage = [
|
|
6946
|
+
'usage: advisers kb page ls [--kind client|project|timeline|facts] [--check] [--limit n] [--json]',
|
|
6947
|
+
' advisers kb page show <id> [--stored] [--diff] [--json]',
|
|
6948
|
+
' advisers kb page rebuild [--kind k] [--id page-id] [--only-stale] [--dry-run] [--json]',
|
|
6949
|
+
' advisers kb page diff <id> [--json]',
|
|
6950
|
+
].join('\n')
|
|
6951
|
+
const sub = args[0]
|
|
6952
|
+
const parsed = familyFlags(args.slice(1), { booleans: ['json', 'check', 'stored', 'diff', 'dry-run', 'only-stale'], values: ['kind', 'id', 'limit', 'clearance'] }, usage)
|
|
6953
|
+
if (!parsed) return
|
|
6954
|
+
const flags = parsed.flags
|
|
6955
|
+
const pages = await loadKbPages()
|
|
6956
|
+
const baseOptions = { kind: flags.kind, id: parsed.positional[0] ?? flags.id, limit: familyInteger(flags.limit, '--limit', 1, 500), clearance: familyInteger(flags.clearance, '--clearance', 0, 3) }
|
|
6957
|
+
if (sub === 'ls') {
|
|
6958
|
+
const result = pages.kbPageList(familyStore(), { ...baseOptions, check: flags.check === true })
|
|
6959
|
+
if (flags.json) { console.log(JSON.stringify(result, null, 2)); return }
|
|
6960
|
+
if (!result.pages.length) console.log('(没有页面;先运行 advisers kb page rebuild)')
|
|
6961
|
+
for (const page of result.pages) console.log(page.id + ' ' + page.kind + ' ' + page.title + (page.stale === true ? ' [STALE]' : page.stale === false ? ' [fresh]' : ''))
|
|
6962
|
+
console.log('total=' + result.total + ' limit=' + result.limit + (flags.check === true ? ' staleCount=' + result.staleCount : '') + (result.protectedExcluded ? ' protectedExcluded=' + result.protectedExcluded : ''))
|
|
6963
|
+
return
|
|
6964
|
+
}
|
|
6965
|
+
if (sub === 'show' || sub === 'diff') {
|
|
6966
|
+
const id = parsed.positional[0]
|
|
6967
|
+
if (!id) { usageFail('missing page id', usage); return }
|
|
6968
|
+
const result = sub === 'diff' ? pages.kbPageDiff(familyStore(), id, baseOptions) : pages.kbPageShow(familyStore(), id, { ...baseOptions, stored: flags.stored === true, diff: flags.diff === true })
|
|
6969
|
+
if (flags.json) { console.log(JSON.stringify(result, null, 2)); return }
|
|
6970
|
+
if (sub === 'diff') { console.log(result.diff || '(页面没有变化)'); return }
|
|
6971
|
+
const page = result.page
|
|
6972
|
+
console.log(page.id + ' ' + page.kind + ' ' + page.title + ' [' + (result.stale ? 'STALE' : 'fresh') + ']')
|
|
6973
|
+
if (page.markdown) process.stdout.write(page.markdown.endsWith('\n') ? page.markdown : page.markdown + '\n')
|
|
6974
|
+
if (result.diff) process.stdout.write(result.diff)
|
|
6975
|
+
return
|
|
6976
|
+
}
|
|
6977
|
+
if (sub === 'rebuild') {
|
|
6978
|
+
const result = pages.kbPageRebuild(familyStore({ write: flags['dry-run'] !== true }), { ...baseOptions, dryRun: flags['dry-run'] === true })
|
|
6979
|
+
if (flags.json) { console.log(JSON.stringify(result, null, 2)); return }
|
|
6980
|
+
console.log((result.dryRun ? 'dry-run: ' : '') + 'built=' + result.counts.built + ' written=' + result.counts.written + ' unchanged=' + result.counts.unchanged + ' skipped=' + result.counts.skipped)
|
|
6981
|
+
if (result.degraded.length) console.log('degraded: ' + result.degraded.join(', '))
|
|
6982
|
+
return
|
|
6983
|
+
}
|
|
6984
|
+
usageFail('unknown kb page subcommand: ' + (sub ?? '(none)'), usage)
|
|
6985
|
+
}
|
|
6986
|
+
|
|
6987
|
+
async function kbSearchCommand(args, options = {}) {
|
|
6988
|
+
const usage = 'usage: advisers kb search <query> [--scope kb|pages|all] [--client id] [--matter id] [--kind k] [--limit n] [--clearance 0-3] [--json]'
|
|
6989
|
+
const parsed = familyFlags(args, { booleans: ['json'], values: ['scope', 'client', 'matter', 'kind', 'limit', 'clearance'] }, usage)
|
|
6990
|
+
if (!parsed) return
|
|
6991
|
+
const query = parsed.positional.join(' ').trim()
|
|
6992
|
+
if (!query) { usageFail('missing query', usage); return }
|
|
6993
|
+
const scope = options.scope ?? (parsed.flags.scope === undefined ? 'kb' : String(parsed.flags.scope))
|
|
6994
|
+
const kb = await loadKb()
|
|
6995
|
+
const store = familyStore()
|
|
6996
|
+
const result = kb.kbSearch(store, query, {
|
|
6997
|
+
scope,
|
|
6998
|
+
clientId: parsed.flags.client,
|
|
6999
|
+
matterId: parsed.flags.matter,
|
|
7000
|
+
kind: parsed.flags.kind,
|
|
7001
|
+
limit: familyInteger(parsed.flags.limit, '--limit', 1, 200),
|
|
7002
|
+
clearance: familyInteger(parsed.flags.clearance, '--clearance', 0, 3),
|
|
7003
|
+
})
|
|
7004
|
+
if (parsed.flags.json) { console.log(JSON.stringify(result, null, 2)); return }
|
|
7005
|
+
if (!result.hits.length) console.log('没有匹配')
|
|
7006
|
+
for (const hit of result.hits) console.log(hit.kind + '\t' + String(hit.title ?? hit.snippet ?? '') + (hit.snippet ? ' 「' + String(hit.snippet).replace(/\s+/g, ' ').slice(0, 120) + '」' : ''))
|
|
7007
|
+
console.log('counts: docs=' + result.counts.kbDocs + ' chunks=' + result.counts.kbChunks + ' pages=' + result.counts.kbPages + ' total=' + result.total + ' clearance=' + result.clearance + (result.degraded.length ? ' degraded=' + result.degraded.join(',') : ''))
|
|
7008
|
+
}
|
|
7009
|
+
|
|
7010
|
+
async function kbCommand(rawArgs) {
|
|
7011
|
+
const sub = rawArgs[0]
|
|
7012
|
+
try {
|
|
7013
|
+
if (!sub || sub === 'help' || sub === '--help') { console.log(KB_USAGE); return }
|
|
7014
|
+
if (sub === 'add') return await kbAddCommand(rawArgs.slice(1))
|
|
7015
|
+
if (sub === 'ls' || sub === 'list') return await kbListCommand(rawArgs.slice(1))
|
|
7016
|
+
if (sub === 'show') return await kbShowCommand(rawArgs.slice(1))
|
|
7017
|
+
if (sub === 'rm' || sub === 'remove') return await kbRmCommand(rawArgs.slice(1))
|
|
7018
|
+
if (sub === 'purge') return await kbPurgeCommand(rawArgs.slice(1))
|
|
7019
|
+
if (sub === 'reindex') return await kbReindexCommand(rawArgs.slice(1))
|
|
7020
|
+
if (sub === 'page') return await kbPageCommand(rawArgs.slice(1))
|
|
7021
|
+
if (sub === 'search') return await kbSearchCommand(rawArgs.slice(1))
|
|
7022
|
+
if (sub === 'link') return await kbLinkCommand(rawArgs.slice(1), false)
|
|
7023
|
+
if (sub === 'unlink') return await kbLinkCommand(rawArgs.slice(1), true)
|
|
7024
|
+
usageFail('unknown kb subcommand: ' + sub, KB_USAGE)
|
|
7025
|
+
} catch (error) { reportFamilyFailure(error) }
|
|
7026
|
+
}
|
|
7027
|
+
|
|
7028
|
+
/** kb link/unlink: explicit fact <-> document provenance (0.4.x follow-up). */
|
|
7029
|
+
async function kbLinkCommand(rawArgs, unlink = false) {
|
|
7030
|
+
const usage = unlink
|
|
7031
|
+
? 'usage: advisers kb unlink <doc-id> --fact <fact-id> [--relation source|mentions] [--json]'
|
|
7032
|
+
: 'usage: advisers kb link <doc-id> --fact <fact-id> [--relation source|mentions] [--chunk id] [--json]'
|
|
7033
|
+
const parsed = familyFlags(rawArgs, { booleans: ['json'], values: ['fact', 'relation', 'chunk'] }, usage)
|
|
7034
|
+
if (!parsed) return
|
|
7035
|
+
const docId = parsed.positional[0]
|
|
7036
|
+
const factId = parsed.flags.fact
|
|
7037
|
+
if (!docId) { usageFail('missing document id', usage); return }
|
|
7038
|
+
if (!factId) { usageFail('--fact is required', usage); return }
|
|
7039
|
+
const kb = await loadKb()
|
|
7040
|
+
const store = familyStore({ write: true })
|
|
7041
|
+
const result = unlink
|
|
7042
|
+
? kb.kbUnlink(store, { docId, factId, relation: parsed.flags.relation })
|
|
7043
|
+
: kb.kbLink(store, { docId, factId, relation: parsed.flags.relation, chunkId: parsed.flags.chunk })
|
|
7044
|
+
if (parsed.flags.json) { console.log(JSON.stringify(result, null, 2)); return }
|
|
7045
|
+
if (unlink) console.log('unlinked ' + result.removed + ' link(s): ' + docId + ' x ' + factId)
|
|
7046
|
+
else console.log('linked ' + docId + ' -> ' + factId + ' (' + result.link.relation + ')')
|
|
7047
|
+
}
|
|
7048
|
+
|
|
7049
|
+
const FACT_USAGE = [
|
|
7050
|
+
'usage: advisers fact show <id> [--include-deleted] [--json]',
|
|
7051
|
+
' advisers fact history <id> [--json]',
|
|
7052
|
+
' advisers fact as-of <YYYY-MM-DD|ISO> [--matter id] [--client id] [--subject s] [--predicate s] [--limit n] [--include-deleted] [--json]',
|
|
7053
|
+
].join('\n')
|
|
7054
|
+
|
|
7055
|
+
function factLine(fact) {
|
|
7056
|
+
return fact.id + ' ' + fact.subject + ' ' + fact.predicate + ' ' + String(fact.object ?? '') + (fact.matterId ? ' [' + fact.matterId + ']' : '') + ' status=' + fact.status + ' recordedAt=' + fact.recordedAt + (fact.validFrom ? ' validFrom=' + fact.validFrom : '') + (fact.validTo ? ' validTo=' + fact.validTo : '')
|
|
7057
|
+
}
|
|
7058
|
+
|
|
7059
|
+
async function factCommand(rawArgs) {
|
|
7060
|
+
const sub = rawArgs[0]
|
|
7061
|
+
try {
|
|
7062
|
+
if (!sub || sub === 'help' || sub === '--help') { console.log(FACT_USAGE); return }
|
|
7063
|
+
const parsed = familyFlags(rawArgs.slice(1), { booleans: ['json', 'include-deleted'], values: ['matter', 'client', 'subject', 'predicate', 'limit', 'at'] }, FACT_USAGE)
|
|
7064
|
+
if (!parsed) return
|
|
7065
|
+
const flags = parsed.flags
|
|
7066
|
+
const facts = await loadKbFacts()
|
|
7067
|
+
if (sub === 'show') {
|
|
7068
|
+
const id = parsed.positional[0]
|
|
7069
|
+
if (!id) { usageFail('missing fact id', FACT_USAGE); return }
|
|
7070
|
+
const result = facts.factShow(familyStore(), id, { includeDeleted: flags['include-deleted'] === true })
|
|
7071
|
+
if (flags.json) { console.log(JSON.stringify(result, null, 2)); return }
|
|
7072
|
+
console.log(factLine(result.fact))
|
|
7073
|
+
for (const evidence of result.fact.evidence ?? []) console.log(' evidence 「' + String(evidence.quote ?? '').slice(0, 200) + '」')
|
|
7074
|
+
for (const source of result.kbSources ?? []) console.log(' kb ' + source.docId + ' ' + String(source.title ?? ''))
|
|
7075
|
+
for (const warning of result.warnings ?? []) console.log(' warning: ' + warning)
|
|
7076
|
+
return
|
|
7077
|
+
}
|
|
7078
|
+
if (sub === 'history') {
|
|
7079
|
+
const id = parsed.positional[0]
|
|
7080
|
+
if (!id) { usageFail('missing fact id', FACT_USAGE); return }
|
|
7081
|
+
const result = facts.factHistory(familyStore(), id, { includeDeleted: flags['include-deleted'] !== false })
|
|
7082
|
+
if (flags.json) { console.log(JSON.stringify(result, null, 2)); return }
|
|
7083
|
+
console.log('history of ' + result.rootId + ' (' + result.items.length + ')')
|
|
7084
|
+
result.items.forEach((fact, index) => console.log(' ' + (index + 1) + '. ' + factLine(fact)))
|
|
7085
|
+
for (const warning of result.warnings) console.log(' warning: ' + warning)
|
|
7086
|
+
return
|
|
7087
|
+
}
|
|
7088
|
+
if (sub === 'as-of' || sub === 'asof') {
|
|
7089
|
+
const at = parsed.positional[0] ?? flags.at
|
|
7090
|
+
if (!at) { usageFail('missing as-of instant (YYYY-MM-DD or ISO)', FACT_USAGE); return }
|
|
7091
|
+
const result = facts.factAsOf(familyStore(), {
|
|
7092
|
+
at,
|
|
7093
|
+
matterId: flags.matter,
|
|
7094
|
+
clientId: flags.client,
|
|
7095
|
+
subject: flags.subject,
|
|
7096
|
+
predicate: flags.predicate,
|
|
7097
|
+
limit: familyInteger(flags.limit, '--limit', 1, 500),
|
|
7098
|
+
includeDeleted: flags['include-deleted'] === true,
|
|
7099
|
+
})
|
|
7100
|
+
if (flags.json) { console.log(JSON.stringify(result, null, 2)); return }
|
|
7101
|
+
console.log('as-of ' + result.at + '(本地日 ' + result.asOfLocalDay + ')· ' + result.items.length + ' 条')
|
|
7102
|
+
for (const fact of result.items) console.log(' ' + factLine(fact))
|
|
7103
|
+
for (const warning of result.warnings) console.log(' warning: ' + warning)
|
|
7104
|
+
if (result.degraded.length) console.log(' degraded: ' + result.degraded.join(', '))
|
|
7105
|
+
return
|
|
7106
|
+
}
|
|
7107
|
+
usageFail('unknown fact subcommand: ' + sub, FACT_USAGE)
|
|
7108
|
+
} catch (error) { reportFamilyFailure(error) }
|
|
7109
|
+
}
|
|
7110
|
+
|
|
7111
|
+
/**
|
|
7112
|
+
* 'search <q> --scope turns|kb|pages|facts|all' (0.4.0 additive).
|
|
7113
|
+
*
|
|
7114
|
+
* The default (no --scope, or --scope turns) path is the frozen 0.3.2 output;
|
|
7115
|
+
* this helper only runs for the KB-inclusive scopes. KB hits come from
|
|
7116
|
+
* lib/kb.kbSearch; scope=all also merges local turn hits (never model calls).
|
|
7117
|
+
*/
|
|
7118
|
+
async function scopedSearch(args) {
|
|
7119
|
+
const usage = 'usage: advisers search <query> [--scope turns|kb|pages|facts|all] [--client id] [--matter id] [--kind k] [--limit n] [--clearance 0-3] [--json]'
|
|
7120
|
+
const parsed = familyFlags(args, { booleans: ['json', 'explain'], values: ['scope', 'client', 'matter', 'kind', 'limit', 'clearance'] }, usage)
|
|
7121
|
+
if (!parsed) return
|
|
7122
|
+
const query = parsed.positional.join(' ').trim()
|
|
7123
|
+
if (!query) { usageFail('missing query', usage); return }
|
|
7124
|
+
const scope = String(parsed.flags.scope ?? 'all')
|
|
7125
|
+
if (!['kb', 'pages', 'all', 'facts', 'turns'].includes(scope)) { usageFail('--scope must be turns, kb, pages, facts or all', usage); return }
|
|
7126
|
+
if (scope === 'turns') {
|
|
7127
|
+
const rows = readStoreOrExit()?.searchTurns(query, { limit: 10 }) ?? []
|
|
7128
|
+
if (parsed.flags.json) {
|
|
7129
|
+
console.log(JSON.stringify({ ok: true, command: 'search', query, scope: 'turns', counts: { turns: rows.length, kbDocs: 0, kbChunks: 0, kbPages: 0, facts: 0, preferences: 0 }, hits: rows.map((row) => ({ kind: 'turn', ref: { kind: 'turn', id: row.conversationId + '#' + row.seq }, snippet: String(row.content).slice(0, 240), at: row.createdAt })), total: rows.length, truncated: false, protectedExcluded: 0 }, null, 2))
|
|
7130
|
+
return
|
|
7131
|
+
}
|
|
7132
|
+
if (!rows.length) console.log('没有匹配')
|
|
7133
|
+
for (const row of rows) console.log(row.seq + '\t' + row.role + '\t' + row.content.replace(/\s+/g, ' ').slice(0, 160))
|
|
7134
|
+
return
|
|
7135
|
+
}
|
|
7136
|
+
const store = familyStore()
|
|
7137
|
+
const kb = await loadKb()
|
|
7138
|
+
const result = kb.kbSearch(store, query, {
|
|
7139
|
+
scope: scope === 'facts' ? 'kb' : scope,
|
|
7140
|
+
clientId: parsed.flags.client,
|
|
7141
|
+
matterId: parsed.flags.matter,
|
|
7142
|
+
kind: parsed.flags.kind,
|
|
7143
|
+
limit: familyInteger(parsed.flags.limit, '--limit', 1, 200),
|
|
7144
|
+
clearance: familyInteger(parsed.flags.clearance, '--clearance', 0, 3),
|
|
7145
|
+
})
|
|
7146
|
+
if (scope === 'all') {
|
|
7147
|
+
const turns = readStoreOrExit()?.searchTurns(query, { limit: 10 }) ?? []
|
|
7148
|
+
result.counts.turns = turns.length
|
|
7149
|
+
for (const row of turns) {
|
|
7150
|
+
if (result.hits.length >= result.limit) break
|
|
7151
|
+
result.hits.push({ kind: 'turn', ref: { kind: 'turn', id: row.conversationId + '#' + row.seq }, snippet: String(row.content).slice(0, 240), at: row.createdAt })
|
|
7152
|
+
}
|
|
7153
|
+
result.total = result.counts.kbDocs + result.counts.kbChunks + result.counts.kbPages + result.counts.turns
|
|
7154
|
+
result.truncated = result.total > result.hits.length
|
|
7155
|
+
}
|
|
7156
|
+
if (parsed.flags.json) { console.log(JSON.stringify(result, null, 2)); return }
|
|
7157
|
+
if (!result.hits.length) console.log('没有匹配')
|
|
7158
|
+
for (const hit of result.hits) console.log(String(hit.kind) + '\t' + String(hit.title ?? hit.snippet ?? '').slice(0, 200))
|
|
7159
|
+
console.log('counts: turns=' + result.counts.turns + ' docs=' + result.counts.kbDocs + ' chunks=' + result.counts.kbChunks + ' pages=' + result.counts.kbPages + ' facts=' + result.counts.facts + ' total=' + result.total + ' clearance=' + result.clearance)
|
|
7160
|
+
}
|
|
7161
|
+
|
|
7162
|
+
|
|
7163
|
+
/* ---------------------------------------------------------------------------
|
|
7164
|
+
* 0.4.0 Wave 3 (task-29): mail / receivable / payment / consent commands.
|
|
7165
|
+
*
|
|
7166
|
+
* Design sources: 41-mail-entry.md section 3.7, 48-customer-v2.md section 3.3,
|
|
7167
|
+
* 46-policy-evidence.md section 3.5. All of them are additive CLI commands:
|
|
7168
|
+
* human output and --json output are separate, failures go to stderr as
|
|
7169
|
+
* {error:{code,message,hint?}} with exit 1, and credentials never appear on
|
|
7170
|
+
* argv, in the ledger or in logs.
|
|
7171
|
+
* ------------------------------------------------------------------------- */
|
|
7172
|
+
|
|
7173
|
+
function flagString(flags, name, label, usage) {
|
|
7174
|
+
const value = flags[name]
|
|
7175
|
+
if (value === undefined) return undefined
|
|
7176
|
+
if (typeof value !== 'string' || !value.trim()) { usageFail('--' + label + ' requires a value', usage); return undefined }
|
|
7177
|
+
return value.trim()
|
|
7178
|
+
}
|
|
7179
|
+
|
|
7180
|
+
/** Prompt for a secret on the terminal without echo (TTY only). */
|
|
7181
|
+
async function promptHidden(question) {
|
|
7182
|
+
if (!process.stdin.isTTY) throw familyError('E_TERM_REQUIRED', 'a terminal is required for the hidden password prompt', 'pipe one line with --pass-stdin instead')
|
|
7183
|
+
return await new Promise((resolve) => {
|
|
7184
|
+
const stdin = process.stdin
|
|
7185
|
+
const output = process.stderr
|
|
7186
|
+
let value = ''
|
|
7187
|
+
let done = false
|
|
7188
|
+
const wasRaw = Boolean(stdin.isRaw)
|
|
7189
|
+
const finish = (result) => {
|
|
7190
|
+
if (done) return
|
|
7191
|
+
done = true
|
|
7192
|
+
try { stdin.setRawMode(wasRaw) } catch {}
|
|
7193
|
+
try { stdin.off('data', onData) } catch {}
|
|
7194
|
+
try { stdin.pause() } catch {}
|
|
7195
|
+
output.write('\n')
|
|
7196
|
+
resolve(result)
|
|
7197
|
+
}
|
|
7198
|
+
const onData = (chunk) => {
|
|
7199
|
+
for (const char of String(chunk)) {
|
|
7200
|
+
if (char === '\r' || char === '\n') { finish(value); return }
|
|
7201
|
+
if (char === '\u0003') { finish(undefined); return }
|
|
7202
|
+
if (char === '\u0004') { finish(value); return }
|
|
7203
|
+
if (char === '\u007f' || char === '\b') {
|
|
7204
|
+
if (value) { const chars = Array.from(value); chars.pop(); value = chars.join(''); output.write('\b \b') }
|
|
7205
|
+
continue
|
|
7206
|
+
}
|
|
7207
|
+
value += char
|
|
7208
|
+
output.write('*')
|
|
7209
|
+
}
|
|
7210
|
+
}
|
|
7211
|
+
output.write(question)
|
|
7212
|
+
try { stdin.setRawMode(true) } catch {}
|
|
7213
|
+
try { stdin.resume() } catch {}
|
|
7214
|
+
stdin.on('data', onData)
|
|
7215
|
+
})
|
|
7216
|
+
}
|
|
7217
|
+
|
|
7218
|
+
/** Read one secret line from stdin (non-TTY --pass-stdin path). */
|
|
7219
|
+
async function readSecretFromStdin() {
|
|
7220
|
+
let text = ''
|
|
7221
|
+
process.stdin.setEncoding('utf8')
|
|
7222
|
+
for await (const chunk of process.stdin) text += chunk
|
|
7223
|
+
const first = text.split(/\r?\n/)[0]
|
|
7224
|
+
return first === undefined ? '' : first
|
|
7225
|
+
}
|
|
7226
|
+
|
|
7227
|
+
/* -------------------------------- mail ---------------------------------- */
|
|
7228
|
+
|
|
7229
|
+
const MAIL_USAGE = [
|
|
7230
|
+
'usage: advisers mail account add --name n --host h [--port 993] [--tls tls|starttls] --user u [--pass-stdin]',
|
|
7231
|
+
' [--mailbox INBOX] [--retention-days 30] [--client id] [--matter id] [--json]',
|
|
7232
|
+
' advisers mail account ls|show <account>|rm <account> [--json]',
|
|
7233
|
+
' advisers mail sync [<account>] [--full] [--dry-run] [--since-days 30] [--limit 50] [--mailbox INBOX] [--json]',
|
|
7234
|
+
' advisers mail ls [--account a] [--client id] [--status s] [--since 30d] [--limit n] [--json]',
|
|
7235
|
+
' advisers mail show <id> [--body] [--json]',
|
|
7236
|
+
' advisers mail extract [<id>...] [--all-new] [--local|--model] [--yes] [--matter id] [--limit n] [--dry-run] [--json]',
|
|
7237
|
+
' advisers mail import <file|dir> [--limit n] [--dry-run] [--client id] [--project id] [--json]',
|
|
7238
|
+
' advisers mail purge [--older-than 30d] [--dry-run|--yes] [--account a] [--json]',
|
|
7239
|
+
' advisers mail link <message> [--client id] [--project id] [--json]',
|
|
7240
|
+
' advisers mail dismiss <message> [--json]',
|
|
7241
|
+
].join('\n')
|
|
7242
|
+
|
|
7243
|
+
function mailHumanRow(message) {
|
|
7244
|
+
const from = sanitizeConsoleText(String(message.from ?? ''), { max: 120 })
|
|
7245
|
+
const subject = sanitizeConsoleText(String(message.subject ?? ''), { max: 200 })
|
|
7246
|
+
return message.id + ' ' + String(message.receivedAt ?? '').slice(0, 16) + ' ' + from + ' ' + subject + ' [' + message.status + ']'
|
|
7247
|
+
}
|
|
7248
|
+
|
|
7249
|
+
async function mailAccountCommand(args) {
|
|
7250
|
+
const sub = args[0]
|
|
7251
|
+
const rest = args.slice(1)
|
|
7252
|
+
const usage = 'usage: advisers mail account add|ls|show|rm ...'
|
|
7253
|
+
if (!sub || sub === 'help' || sub === '--help') { console.log(MAIL_USAGE); return }
|
|
7254
|
+
const mail = await loadMail()
|
|
7255
|
+
if (sub === 'add') {
|
|
7256
|
+
const parsed = familyFlags(rest, { booleans: ['json', 'pass-stdin'], values: ['name', 'host', 'port', 'tls', 'user', 'mailbox', 'client', 'matter', 'retention-days', 'pass'] }, usage)
|
|
7257
|
+
if (!parsed) return
|
|
7258
|
+
const flags = parsed.flags
|
|
7259
|
+
if (flags.pass !== undefined) throw familyError('E_MAIL_CONFIG', 'refusing a password on the command line (--pass)', 'use the interactive TTY prompt or --pass-stdin')
|
|
7260
|
+
const name = flagString(flags, 'name', 'name', usage)
|
|
7261
|
+
const host = flagString(flags, 'host', 'host', usage)
|
|
7262
|
+
const user = flagString(flags, 'user', 'user', usage)
|
|
7263
|
+
if (!name || !host || !user) { usageFail('--name, --host and --user are required', usage); return }
|
|
7264
|
+
let pass
|
|
7265
|
+
if (flags['pass-stdin'] === true) pass = await readSecretFromStdin()
|
|
7266
|
+
else pass = await promptHidden('IMAP 密码(输入不回显):')
|
|
7267
|
+
if (typeof pass !== 'string' || pass === '') throw familyError('E_MAIL_CONFIG', 'no IMAP password was provided', 'run in a terminal for the hidden prompt, or pipe one line with --pass-stdin')
|
|
7268
|
+
const store = familyStore({ write: true })
|
|
7269
|
+
const result = mail.mailAccountAdd(store, {
|
|
7270
|
+
name,
|
|
7271
|
+
host,
|
|
7272
|
+
port: flags.port === undefined ? undefined : familyInteger(flags.port, '--port', 1, 65535),
|
|
7273
|
+
tls: flags.tls,
|
|
7274
|
+
username: user,
|
|
7275
|
+
mailbox: flags.mailbox,
|
|
7276
|
+
clientId: flags.client,
|
|
7277
|
+
defaultMatterId: flags.matter,
|
|
7278
|
+
retentionDays: flags['retention-days'] === undefined ? undefined : familyInteger(flags['retention-days'], '--retention-days', 0, 3650),
|
|
7279
|
+
}, { credential: { user, pass }, home: HOME })
|
|
7280
|
+
if (flags.json) { console.log(JSON.stringify(result, null, 2)); return }
|
|
7281
|
+
const account = result.account
|
|
7282
|
+
console.log('added ' + account.id + ' ' + account.name + ' ' + account.username + '@' + account.host + ':' + account.port + ' (' + account.tls + ')')
|
|
7283
|
+
console.log('credential: ' + (account.hasCredential ? 'stored (0600, outside the ledger)' : 'not stored'))
|
|
7284
|
+
return
|
|
7285
|
+
}
|
|
7286
|
+
if (sub === 'ls' || sub === 'list') {
|
|
7287
|
+
const parsed = familyFlags(rest, { booleans: ['json', 'all'], values: [] }, usage)
|
|
7288
|
+
if (!parsed) return
|
|
7289
|
+
const result = mail.mailAccountList(familyStore(), { includeRemoved: parsed.flags.all === true, home: HOME })
|
|
7290
|
+
if (parsed.flags.json) { console.log(JSON.stringify(result, null, 2)); return }
|
|
7291
|
+
if (!result.accounts.length) console.log('(没有邮件账号)')
|
|
7292
|
+
for (const account of result.accounts) console.log(account.id + ' ' + account.name + ' ' + account.username + '@' + account.host + ':' + account.port + ' ' + account.status + (account.hasCredential ? ' credential' : ' no-credential'))
|
|
7293
|
+
return
|
|
7294
|
+
}
|
|
7295
|
+
if (sub === 'show') {
|
|
7296
|
+
const parsed = familyFlags(rest, { booleans: ['json'], values: [] }, usage)
|
|
7297
|
+
if (!parsed) return
|
|
7298
|
+
const ref = parsed.positional[0]
|
|
7299
|
+
if (!ref) { usageFail('missing account id or name', usage); return }
|
|
7300
|
+
const result = mail.mailAccountShow(familyStore(), ref, { home: HOME })
|
|
7301
|
+
if (parsed.flags.json) { console.log(JSON.stringify(result, null, 2)); return }
|
|
7302
|
+
const account = result.account
|
|
7303
|
+
console.log(account.id + ' ' + account.name + ' ' + account.username + '@' + account.host + ':' + account.port + ' (' + account.tls + ') ' + account.status)
|
|
7304
|
+
console.log('mailbox=' + account.mailbox + ' retentionDays=' + account.retentionDays + ' credential=' + (account.hasCredential ? 'stored' : 'missing') + (account.lastSyncAt ? ' lastSyncAt=' + account.lastSyncAt : ''))
|
|
7305
|
+
return
|
|
7306
|
+
}
|
|
7307
|
+
if (sub === 'rm' || sub === 'remove') {
|
|
7308
|
+
const parsed = familyFlags(rest, { booleans: ['json', 'purge-messages'], values: [] }, usage)
|
|
7309
|
+
if (!parsed) return
|
|
7310
|
+
const ref = parsed.positional[0]
|
|
7311
|
+
if (!ref) { usageFail('missing account id or name', usage); return }
|
|
7312
|
+
const result = mail.mailAccountRemove(familyStore({ write: true }), ref, { home: HOME, purgeMessages: parsed.flags['purge-messages'] === true })
|
|
7313
|
+
if (parsed.flags.json) { console.log(JSON.stringify(result, null, 2)); return }
|
|
7314
|
+
console.log('removed ' + result.accountId + ' credentialRemoved=' + (result.credentialRemoved ? 'yes' : 'no') + ' messagesDeleted=' + result.messagesDeleted)
|
|
7315
|
+
return
|
|
7316
|
+
}
|
|
7317
|
+
usageFail('unknown mail account subcommand: ' + sub, MAIL_USAGE)
|
|
7318
|
+
}
|
|
7319
|
+
|
|
7320
|
+
async function mailSyncCommand(args) {
|
|
7321
|
+
const usage = 'usage: advisers mail sync [<account>] [--full] [--dry-run] [--since-days n] [--limit n] [--mailbox INBOX] [--json]'
|
|
7322
|
+
const parsed = familyFlags(args, { booleans: ['json', 'full', 'dry-run'], values: ['account', 'since-days', 'limit', 'mailbox'] }, usage)
|
|
7323
|
+
if (!parsed) return
|
|
7324
|
+
const flags = parsed.flags
|
|
7325
|
+
const mail = await loadMail()
|
|
7326
|
+
const store = familyStore({ write: true })
|
|
7327
|
+
const requested = parsed.positional[0] ?? flags.account
|
|
7328
|
+
let accounts
|
|
7329
|
+
if (requested) accounts = [String(requested)]
|
|
7330
|
+
else {
|
|
7331
|
+
const listed = mail.mailAccountList(store, { home: HOME })
|
|
7332
|
+
accounts = listed.accounts.filter((account) => account.status === 'active' && (account.tls === 'tls' || account.tls === 'starttls')).map((account) => account.id)
|
|
7333
|
+
if (!accounts.length) throw familyError('E_MAIL_CONFIG', 'no IMAP account is configured', 'add one with advisers mail account add')
|
|
7334
|
+
}
|
|
7335
|
+
const results = []
|
|
7336
|
+
for (const account of accounts) {
|
|
7337
|
+
results.push(await mail.mailSync(store, account, {
|
|
7338
|
+
full: flags.full === true,
|
|
7339
|
+
dryRun: flags['dry-run'] === true,
|
|
7340
|
+
sinceDays: flags['since-days'] === undefined ? undefined : familyInteger(flags['since-days'], '--since-days', 1, 3650),
|
|
7341
|
+
limit: flags.limit === undefined ? undefined : familyInteger(flags.limit, '--limit', 1, 200),
|
|
7342
|
+
mailbox: flags.mailbox,
|
|
7343
|
+
home: HOME,
|
|
7344
|
+
}))
|
|
7345
|
+
}
|
|
7346
|
+
const payload = requested ? results[0] : { ok: true, command: 'mail sync', results }
|
|
7347
|
+
if (flags.json) { console.log(JSON.stringify(payload, null, 2)); return }
|
|
7348
|
+
for (const result of results) console.log('sync ' + result.accountId + ' ' + result.mailbox + ': fetched=' + result.fetched + ' inserted=' + result.inserted + ' skipped=' + result.skipped + ' failed=' + result.failed + ' duplicates=' + result.duplicates + (result.dryRun ? ' (dry-run)' : '') + (result.needsResync ? ' NEEDS-RESYNC(--full)' : ''))
|
|
7349
|
+
}
|
|
7350
|
+
|
|
7351
|
+
function mailSinceDays(value) {
|
|
7352
|
+
if (value === undefined) return undefined
|
|
7353
|
+
const text = String(value).trim()
|
|
7354
|
+
const match = /^(\d+)d$/.exec(text)
|
|
7355
|
+
if (match) return familyInteger(match[1], '--since', 1, 3650)
|
|
7356
|
+
return familyInteger(text, '--since', 1, 3650)
|
|
7357
|
+
}
|
|
7358
|
+
|
|
7359
|
+
async function mailLsCommand(args) {
|
|
7360
|
+
const usage = 'usage: advisers mail ls [--account a] [--client id] [--status s] [--since 30d] [--limit n] [--json]'
|
|
7361
|
+
const parsed = familyFlags(args, { booleans: ['json'], values: ['account', 'client', 'status', 'since', 'limit'] }, usage)
|
|
7362
|
+
if (!parsed) return
|
|
7363
|
+
const flags = parsed.flags
|
|
7364
|
+
const mail = await loadMail()
|
|
7365
|
+
const result = mail.mailList(familyStore(), {
|
|
7366
|
+
account: flags.account,
|
|
7367
|
+
clientId: flags.client,
|
|
7368
|
+
status: flags.status,
|
|
7369
|
+
sinceDays: mailSinceDays(flags.since),
|
|
7370
|
+
limit: flags.limit === undefined ? undefined : familyInteger(flags.limit, '--limit', 1, 500),
|
|
7371
|
+
})
|
|
7372
|
+
if (flags.json) { console.log(JSON.stringify(result, null, 2)); return }
|
|
7373
|
+
if (!result.messages.length) console.log('(没有邮件)')
|
|
7374
|
+
for (const message of result.messages) console.log(mailHumanRow(message))
|
|
7375
|
+
console.log('total=' + result.total + ' limit=' + result.limit + (result.truncated ? ' truncated' : ''))
|
|
7376
|
+
}
|
|
7377
|
+
|
|
7378
|
+
async function mailShowCommand(args) {
|
|
7379
|
+
const usage = 'usage: advisers mail show <id> [--body] [--json]'
|
|
7380
|
+
const parsed = familyFlags(args, { booleans: ['json', 'body'], values: [] }, usage)
|
|
7381
|
+
if (!parsed) return
|
|
7382
|
+
const ref = parsed.positional[0]
|
|
7383
|
+
if (!ref) { usageFail('missing mail message id', usage); return }
|
|
7384
|
+
const mail = await loadMail()
|
|
7385
|
+
const result = mail.mailShow(familyStore(), ref, { body: parsed.flags.body === true })
|
|
7386
|
+
if (parsed.flags.json) { console.log(JSON.stringify(result, null, 2)); return }
|
|
7387
|
+
const message = result.message
|
|
7388
|
+
console.log(mailHumanRow(message))
|
|
7389
|
+
console.log('messageId=' + (message.messageId ?? '-') + ' uid=' + message.uid + ' size=' + (message.sizeBytes ?? '-') + ' retained=' + (message.retained === true ? 'yes' : 'no') + (message.clientId ? ' client=' + message.clientId : ''))
|
|
7390
|
+
if (parsed.flags.body === true) {
|
|
7391
|
+
console.log('---')
|
|
7392
|
+
process.stdout.write(String(message.bodyText ?? '') + '\n')
|
|
7393
|
+
}
|
|
7394
|
+
}
|
|
7395
|
+
|
|
7396
|
+
/**
|
|
7397
|
+
* Authorization + consent gate for model egress of local content.
|
|
7398
|
+
* evaluate/authorize come from lib/policy; the consent record is bound to the
|
|
7399
|
+
* surface + data class + provider + base URL. An audit failure fails closed.
|
|
7400
|
+
*/
|
|
7401
|
+
async function authorizeModelEgress(surface, dataClass, options = {}) {
|
|
7402
|
+
const policy = await loadPolicy()
|
|
7403
|
+
const consent = await loadConsent()
|
|
7404
|
+
const provider = process.env.ADVISERS_PROVIDER || 'deepseek'
|
|
7405
|
+
const baseUrl = process.env.ADVISERS_BASE_URL || 'https://api.deepseek.com'
|
|
7406
|
+
const consentFact = consent.consentFacts(HOME, { surface, dataClass, provider, baseUrl })
|
|
7407
|
+
let tosFacts = { accepted: true, version: '', currentVersion: '', hashOk: true }
|
|
7408
|
+
try {
|
|
7409
|
+
const tos = await loadTos()
|
|
7410
|
+
const { info } = resolveTosFacts(tos)
|
|
7411
|
+
const status = tos.acceptanceStatus({ home: HOME, version: info.version, sha256: info.sha256 })
|
|
7412
|
+
tosFacts = { accepted: status.accepted === true, version: String(status.record?.version ?? info.version), currentVersion: info.version, hashOk: status.reason !== 'hash_mismatch' }
|
|
7413
|
+
} catch {}
|
|
7414
|
+
const audit = (event) => {
|
|
7415
|
+
const store = mode === 'sqlite' ? dbStore() : undefined
|
|
7416
|
+
if (!store) return { ok: false }
|
|
7417
|
+
try {
|
|
7418
|
+
store.appendAudit({
|
|
7419
|
+
actor: 'policy',
|
|
7420
|
+
action: 'policy.' + String(event.surface) + '.' + String(event.policyAction ?? event.action ?? 'unknown'),
|
|
7421
|
+
allowed: event.allowed === true,
|
|
7422
|
+
reason: [String(event.phase ?? ''), String(event.code ?? event.policyCode ?? '')].filter(Boolean).join(' ').slice(0, 300),
|
|
7423
|
+
})
|
|
7424
|
+
return { ok: true }
|
|
7425
|
+
} catch { return { ok: false } }
|
|
7426
|
+
}
|
|
7427
|
+
const facts = {
|
|
7428
|
+
v: 1,
|
|
7429
|
+
surface,
|
|
7430
|
+
action: 'model-egress',
|
|
7431
|
+
actor: 'cli',
|
|
7432
|
+
interactive: Boolean(process.stdin.isTTY),
|
|
7433
|
+
record: options && options.record && typeof options.record === 'object' ? options.record : null,
|
|
7434
|
+
safety: { action: 'allow' },
|
|
7435
|
+
tos: tosFacts,
|
|
7436
|
+
consent: consentFact,
|
|
7437
|
+
audit: { available: mode === 'sqlite' },
|
|
7438
|
+
trust: { tainted: true, sourceKinds: [dataClass] },
|
|
7439
|
+
now: new Date().toISOString(),
|
|
7440
|
+
}
|
|
7441
|
+
const decision = policy.authorize('model-egress', facts, { audit })
|
|
7442
|
+
if (decision.authorized !== true) {
|
|
7443
|
+
const code = typeof decision.code === 'string' ? decision.code : 'E_POLICY_DENIED'
|
|
7444
|
+
const hint = consentFact.granted === true
|
|
7445
|
+
? 'model egress is not allowed for this surface/data class; see advisers privacy --matrix'
|
|
7446
|
+
: 'run advisers consent grant ' + surface + ' and read the prompt before sending content to the model provider'
|
|
7447
|
+
throw familyError(code, String(decision.reason ?? 'policy denied model egress'), hint)
|
|
7448
|
+
}
|
|
7449
|
+
// The effect digest authorize() bound is computed from the facts (surface /
|
|
7450
|
+
// action / dataClass; the facts carry record=null and no top-level provider),
|
|
7451
|
+
// so consumeDecision() must receive exactly that shape or it refuses.
|
|
7452
|
+
const effectRecord = options && options.record && typeof options.record === 'object' ? { kind: String(options.record.kind ?? 'record'), secrecy: Number(options.record.secrecy ?? 0) } : null
|
|
7453
|
+
return { policy, token: decision.token, effect: { surface, action: 'model-egress', dataClass, ...(effectRecord ? { record: effectRecord } : {}) }, audit }
|
|
7454
|
+
}
|
|
7455
|
+
|
|
7456
|
+
/** Run one authorized model effect, then write its result audit row. */
|
|
7457
|
+
async function runAuthorizedModelEffect(authorization, effectFn) {
|
|
7458
|
+
const { consumeDecision } = await loadPolicy()
|
|
7459
|
+
const consumed = consumeDecision(authorization.token, authorization.effect)
|
|
7460
|
+
let result
|
|
7461
|
+
try {
|
|
7462
|
+
result = await effectFn()
|
|
7463
|
+
} catch (error) {
|
|
7464
|
+
try { authorization.audit({ surface: authorization.effect.surface, policyAction: authorization.effect.action, phase: 'result', allowed: true, decisionId: consumed.decisionId, ok: false, code: typeof error?.code === 'string' ? error.code : 'E_POLICY_EFFECT_FAILED' }) } catch {}
|
|
7465
|
+
throw error
|
|
7466
|
+
}
|
|
7467
|
+
const wrote = authorization.audit({ surface: authorization.effect.surface, policyAction: authorization.effect.action, phase: 'result', allowed: true, decisionId: consumed.decisionId, ok: true })
|
|
7468
|
+
if (wrote?.ok !== true) throw familyError('E_POLICY_AUDIT_UNAVAILABLE', 'model extraction completed but its result audit could not be written', 'the effect already happened; run advisers audit and inspect the ledger before continuing')
|
|
7469
|
+
return result
|
|
7470
|
+
}
|
|
7471
|
+
|
|
7472
|
+
async function mailExtractCommand(args) {
|
|
7473
|
+
const usage = 'usage: advisers mail extract [<id>...] [--all-new] [--local|--model] [--yes] [--matter id] [--limit n] [--dry-run] [--json]'
|
|
7474
|
+
const parsed = familyFlags(args, { booleans: ['json', 'local', 'model', 'all-new', 'dry-run', 'yes'], values: ['account', 'matter', 'limit'] }, usage)
|
|
7475
|
+
if (!parsed) return
|
|
7476
|
+
const flags = parsed.flags
|
|
7477
|
+
if (flags.local === true && flags.model === true) { usageFail('--local and --model are mutually exclusive', usage); return }
|
|
7478
|
+
const useModel = flags.model === true
|
|
7479
|
+
if (useModel && flags.yes !== true) throw familyError('E_MAIL_MODEL_OPT_IN', 'mail extract --model requires an explicit --yes opt-in', 'the default local path is offline; --model sends message text to your configured model provider and needs consent')
|
|
7480
|
+
const mail = await loadMail()
|
|
7481
|
+
const store = familyStore({ write: true })
|
|
7482
|
+
const extractOptions = {
|
|
7483
|
+
model: useModel,
|
|
7484
|
+
confirmModel: useModel && flags.yes === true,
|
|
7485
|
+
apiKey: process.env.ADVISERS_API_KEY,
|
|
7486
|
+
modelName: process.env.ADVISERS_MODEL,
|
|
7487
|
+
account: flags.account,
|
|
7488
|
+
ids: parsed.positional.length ? parsed.positional : undefined,
|
|
7489
|
+
all: flags['all-new'] === true,
|
|
7490
|
+
matterId: flags.matter,
|
|
7491
|
+
limit: flags.limit === undefined ? undefined : familyInteger(flags.limit, '--limit', 1, 500),
|
|
7492
|
+
dryRun: flags['dry-run'] === true,
|
|
7493
|
+
secrecy: 0,
|
|
7494
|
+
}
|
|
7495
|
+
let result
|
|
7496
|
+
if (useModel) {
|
|
7497
|
+
// Protection by matter: model egress is refused for secrecy > 0 (the lib
|
|
7498
|
+
// repeats the check; the policy facts also carry the record secrecy).
|
|
7499
|
+
let secrecy = 0
|
|
7500
|
+
if (flags.matter) {
|
|
7501
|
+
const matter = familyStore().getMatter(String(flags.matter))
|
|
7502
|
+
if (!matter) throw familyError('E_MATTER_NOT_FOUND', 'unknown matter: ' + flags.matter, 'advisers matter ls')
|
|
7503
|
+
secrecy = Number(matter.secrecy ?? 0)
|
|
7504
|
+
}
|
|
7505
|
+
if (Number.isFinite(secrecy) && secrecy > 0) throw familyError('E_MAIL_MODEL_DISABLED', 'model extraction is disabled for protected matters (secrecy > 0)', 'use the default local extraction or move the mail to an unprotected matter')
|
|
7506
|
+
extractOptions.secrecy = secrecy
|
|
7507
|
+
const authorization = await authorizeModelEgress('mail.extract', 'mail', { record: { kind: 'mail', secrecy } })
|
|
7508
|
+
result = await runAuthorizedModelEffect(authorization, () => mail.mailExtract(store, extractOptions))
|
|
7509
|
+
} else {
|
|
7510
|
+
result = await mail.mailExtract(store, extractOptions)
|
|
7511
|
+
}
|
|
7512
|
+
if (flags.json) { console.log(JSON.stringify(result, null, 2)); return }
|
|
7513
|
+
console.log('mail extract (' + result.mode + '): scanned=' + result.scanned + ' candidates=' + result.candidates.length + ' skipped=' + result.skipped + ' failed=' + result.failed + (result.dryRun ? ' (dry-run)' : ''))
|
|
7514
|
+
for (const candidate of result.candidates.slice(0, 20)) console.log(' ' + String(candidate.id ?? '(preview)') + ' ' + String(candidate.action ?? candidate.statement ?? candidate.text ?? '').slice(0, 120))
|
|
7515
|
+
if (result.safetyWarnings?.length) console.log(' safety warnings: ' + result.safetyWarnings.length)
|
|
7516
|
+
}
|
|
7517
|
+
|
|
7518
|
+
async function mailImportCommand(args) {
|
|
7519
|
+
const usage = 'usage: advisers mail import <file|dir> [--limit n] [--dry-run] [--client id] [--project id] [--json]'
|
|
7520
|
+
const parsed = familyFlags(args, { booleans: ['json', 'dry-run'], values: ['limit', 'client', 'project', 'account'] }, usage)
|
|
7521
|
+
if (!parsed) return
|
|
7522
|
+
const target = parsed.positional[0]
|
|
7523
|
+
if (!target) { usageFail('missing .eml/.mbox file or directory', usage); return }
|
|
7524
|
+
const mail = await loadMail()
|
|
7525
|
+
const result = await mail.mailImport(familyStore({ write: parsed.flags['dry-run'] !== true }), {
|
|
7526
|
+
path: target,
|
|
7527
|
+
accountId: parsed.flags.account,
|
|
7528
|
+
clientId: parsed.flags.client,
|
|
7529
|
+
projectId: parsed.flags.project,
|
|
7530
|
+
limit: parsed.flags.limit === undefined ? undefined : familyInteger(parsed.flags.limit, '--limit', 1, 500),
|
|
7531
|
+
dryRun: parsed.flags['dry-run'] === true,
|
|
7532
|
+
})
|
|
7533
|
+
if (parsed.flags.json) { console.log(JSON.stringify(result, null, 2)); return }
|
|
7534
|
+
console.log('mail import: files=' + result.files + ' scanned=' + result.scanned + ' inserted=' + result.inserted + ' skipped=' + result.skipped + ' failed=' + result.failed + (result.dryRun ? ' (dry-run)' : ''))
|
|
7535
|
+
}
|
|
7536
|
+
|
|
7537
|
+
async function mailPurgeCommand(args) {
|
|
7538
|
+
const usage = 'usage: advisers mail purge [--older-than 30d] [--dry-run|--yes] [--account a] [--json]'
|
|
7539
|
+
const parsed = familyFlags(args, { booleans: ['json', 'dry-run', 'yes'], values: ['older-than', 'account'] }, usage)
|
|
7540
|
+
if (!parsed) return
|
|
7541
|
+
let olderThanDays
|
|
7542
|
+
if (parsed.flags['older-than'] !== undefined) {
|
|
7543
|
+
const text = String(parsed.flags['older-than']).trim()
|
|
7544
|
+
const match = /^(\d+)d$/.exec(text)
|
|
7545
|
+
olderThanDays = familyInteger(match ? match[1] : text, '--older-than', 1, 3650)
|
|
7546
|
+
}
|
|
7547
|
+
let yes = parsed.flags.yes === true
|
|
7548
|
+
const dryRun = parsed.flags['dry-run'] === true || !yes
|
|
7549
|
+
if (!dryRun && process.stdin.isTTY && parsed.flags['dry-run'] !== true) {
|
|
7550
|
+
yes = await askYesNo(null, '永久清除保留期外的邮件正文(元数据保留)?[y/N] ', false)
|
|
7551
|
+
if (!yes) { console.log('已取消。'); return }
|
|
7552
|
+
}
|
|
7553
|
+
const mail = await loadMail()
|
|
7554
|
+
const result = mail.mailPurge(familyStore({ write: yes }), { olderThanDays, account: parsed.flags.account, dryRun: !yes })
|
|
7555
|
+
if (parsed.flags.json) { console.log(JSON.stringify(result, null, 2)); return }
|
|
7556
|
+
if (result.dryRun) console.log('dry-run: 将清除 ' + result.wouldPurge + ' 封正文(' + formatBytes(result.bytesWouldFree) + '),跳过 ' + result.skippedPending + ' 封有待处理候选;加 --yes 执行')
|
|
7557
|
+
else console.log('purged bodies=' + result.messagesPurged + ' bytesFreed=' + formatBytes(result.bytesFreed) + ' skippedPending=' + result.skippedPending)
|
|
7558
|
+
}
|
|
7559
|
+
|
|
7560
|
+
async function mailCommand(rawArgs) {
|
|
7561
|
+
const sub = rawArgs[0]
|
|
7562
|
+
try {
|
|
7563
|
+
if (!sub || sub === 'help' || sub === '--help') { console.log(MAIL_USAGE); return }
|
|
7564
|
+
if (sub === 'account') return await mailAccountCommand(rawArgs.slice(1))
|
|
7565
|
+
if (sub === 'sync') return await mailSyncCommand(rawArgs.slice(1))
|
|
7566
|
+
if (sub === 'ls' || sub === 'list') return await mailLsCommand(rawArgs.slice(1))
|
|
7567
|
+
if (sub === 'show') return await mailShowCommand(rawArgs.slice(1))
|
|
7568
|
+
if (sub === 'extract') return await mailExtractCommand(rawArgs.slice(1))
|
|
7569
|
+
if (sub === 'import') return await mailImportCommand(rawArgs.slice(1))
|
|
7570
|
+
if (sub === 'purge') return await mailPurgeCommand(rawArgs.slice(1))
|
|
7571
|
+
if (sub === 'link') return await mailLinkCommand(rawArgs.slice(1), false)
|
|
7572
|
+
if (sub === 'dismiss') return await mailLinkCommand(rawArgs.slice(1), true)
|
|
7573
|
+
usageFail('unknown mail subcommand: ' + sub, MAIL_USAGE)
|
|
7574
|
+
} catch (error) { reportFamilyFailure(error) }
|
|
7575
|
+
}
|
|
7576
|
+
|
|
7577
|
+
/** mail link/dismiss: explicit review decisions on one imported message (0.4.x follow-up). */
|
|
7578
|
+
async function mailLinkCommand(rawArgs, dismiss = false) {
|
|
7579
|
+
const usage = dismiss
|
|
7580
|
+
? 'usage: advisers mail dismiss <message> [--json]'
|
|
7581
|
+
: 'usage: advisers mail link <message> [--client id] [--project id] [--json]'
|
|
7582
|
+
const parsed = familyFlags(rawArgs, { booleans: ['json'], values: ['client', 'project'] }, usage)
|
|
7583
|
+
if (!parsed) return
|
|
7584
|
+
const ref = parsed.positional[0]
|
|
7585
|
+
if (!ref) { usageFail('missing message id', usage); return }
|
|
7586
|
+
const mail = await loadMail()
|
|
7587
|
+
const store = familyStore({ write: true })
|
|
7588
|
+
const result = dismiss
|
|
7589
|
+
? mail.mailDismiss(store, ref, {})
|
|
7590
|
+
: mail.mailLink(store, ref, { clientId: parsed.flags.client, projectId: parsed.flags.project })
|
|
7591
|
+
if (parsed.flags.json) { console.log(JSON.stringify(result, null, 2)); return }
|
|
7592
|
+
const message = result.message
|
|
7593
|
+
console.log((dismiss ? 'dismissed ' : 'linked ') + message.id + ' [' + message.status + ']' + (message.clientId ? ' client=' + message.clientId : '') + (message.projectId ? ' project=' + message.projectId : ''))
|
|
7594
|
+
}
|
|
7595
|
+
|
|
7596
|
+
/* ------------------------- receivable / payment ------------------------- */
|
|
7597
|
+
/* ------------------------- receivable / payment ------------------------- */
|
|
7598
|
+
|
|
7599
|
+
const RECEIVABLE_USAGE = [
|
|
7600
|
+
'usage: advisers receivable add <client-id> "<label>" --amount 8000.00 [--currency CNY] [--due YYYY-MM-DD]',
|
|
7601
|
+
' [--project id] [--matter id] [--kind quote|milestone|retainer|other] [--memo text]',
|
|
7602
|
+
' [--remind-offsets "-3d,-1d"] [--no-remind] [--json]',
|
|
7603
|
+
' advisers receivable ls|list [--client id] [--project id] [--status open|partial|overdue|settled|all]',
|
|
7604
|
+
' [--currency CNY] [--aging] [--due-within 7d|30d] [--clearance 0-3] [--limit n] [--json]',
|
|
7605
|
+
' advisers receivable show <id> [--json]',
|
|
7606
|
+
' advisers receivable edit <id> [--amount 9000.00|--due DATE|--memo text|--kind k|--label text] [--json]',
|
|
7607
|
+
' advisers receivable void <id> [--reason text] [--json]',
|
|
7608
|
+
].join('\n')
|
|
7609
|
+
|
|
7610
|
+
const PAYMENT_USAGE = [
|
|
7611
|
+
'usage: advisers payment add <client-id> --amount 4000.00 [--currency CNY] [--paid-at ISO] [--method bank|wechat|alipay|cash|other]',
|
|
7612
|
+
' [--receivable rcv] [--memo text] [--no-complete] [--json]',
|
|
7613
|
+
' advisers payment ls|list [--client id] [--receivable rcv] [--since 90d|ISO] [--limit n] [--json]',
|
|
7614
|
+
' advisers payment void <id> [--reason text] [--json]',
|
|
7615
|
+
].join('\n')
|
|
7616
|
+
|
|
7617
|
+
function receivableMoney(row) {
|
|
7618
|
+
return String(row.amount ?? '') + ' ' + String(row.currency ?? '') + (row.state ? ' ' + row.state : '') + (row.outstanding && row.outstanding !== row.amount ? ' outstanding ' + row.outstanding : '')
|
|
7619
|
+
}
|
|
7620
|
+
|
|
7621
|
+
async function receivableCommand(rawArgs) {
|
|
7622
|
+
const sub = rawArgs[0]
|
|
7623
|
+
try {
|
|
7624
|
+
if (!sub || sub === 'help' || sub === '--help') { console.log(RECEIVABLE_USAGE); return }
|
|
7625
|
+
const receivable = await loadReceivablesLib()
|
|
7626
|
+
if (sub === 'add') {
|
|
7627
|
+
const usage = RECEIVABLE_USAGE
|
|
7628
|
+
const parsed = familyFlags(rawArgs.slice(1), { booleans: ['json', 'no-remind'], values: ['amount', 'currency', 'due', 'project', 'matter', 'kind', 'memo', 'remind-offsets'] }, usage)
|
|
7629
|
+
if (!parsed) return
|
|
7630
|
+
const clientId = parsed.positional[0]
|
|
7631
|
+
const label = parsed.positional.slice(1).join(' ').trim()
|
|
7632
|
+
if (!clientId || !label) { usageFail('usage: advisers receivable add <client-id> "<label>" --amount 8000.00', usage); return }
|
|
7633
|
+
if (parsed.flags.amount === undefined) { usageFail('--amount is required', usage); return }
|
|
7634
|
+
const result = receivable.receivableAdd(familyStore({ write: true }), {
|
|
7635
|
+
clientId,
|
|
7636
|
+
label,
|
|
7637
|
+
amount: parsed.flags.amount,
|
|
7638
|
+
currency: parsed.flags.currency,
|
|
7639
|
+
dueAt: parsed.flags.due,
|
|
7640
|
+
projectId: parsed.flags.project,
|
|
7641
|
+
matterId: parsed.flags.matter,
|
|
7642
|
+
kind: parsed.flags.kind,
|
|
7643
|
+
memo: parsed.flags.memo,
|
|
7644
|
+
reminderOffsets: parsed.flags['remind-offsets'],
|
|
7645
|
+
noRemind: parsed.flags['no-remind'] === true,
|
|
7646
|
+
})
|
|
7647
|
+
if (parsed.flags.json) { console.log(JSON.stringify(result, null, 2)); return }
|
|
7648
|
+
const row = result.receivable
|
|
7649
|
+
console.log('added ' + (row ? row.id : '(hidden)') + ' ' + label + ' ' + (row ? receivableMoney(row) : '') + (row && row.dueAt ? ' due ' + row.dueAt : ''))
|
|
7650
|
+
console.log('follow-up commitment: ' + result.commitment.id)
|
|
7651
|
+
return
|
|
7652
|
+
}
|
|
7653
|
+
if (sub === 'ls' || sub === 'list') {
|
|
7654
|
+
const usage = RECEIVABLE_USAGE
|
|
7655
|
+
const parsed = familyFlags(rawArgs.slice(1), { booleans: ['json', 'aging'], values: ['client', 'project', 'status', 'currency', 'due-within', 'clearance', 'limit'] }, usage)
|
|
7656
|
+
if (!parsed) return
|
|
7657
|
+
const flags = parsed.flags
|
|
7658
|
+
const store = familyStore()
|
|
7659
|
+
const options = {
|
|
7660
|
+
clientId: flags.client,
|
|
7661
|
+
projectId: flags.project,
|
|
7662
|
+
status: flags.status,
|
|
7663
|
+
currency: flags.currency,
|
|
7664
|
+
dueWithin: flags['due-within'],
|
|
7665
|
+
clearance: flags.clearance === undefined ? undefined : familyInteger(flags.clearance, '--clearance', 0, 3),
|
|
7666
|
+
limit: flags.limit === undefined ? undefined : familyInteger(flags.limit, '--limit', 1, 500),
|
|
7667
|
+
}
|
|
7668
|
+
const result = flags.aging === true ? receivable.receivablesSummary(store, options) : receivable.receivableList(store, options)
|
|
7669
|
+
if (flags.json) { console.log(JSON.stringify(result, null, 2)); return }
|
|
7670
|
+
if (flags.aging === true) {
|
|
7671
|
+
console.log('unsettled=' + result.unsettled + ' overdue=' + result.overdue + ' settled=' + result.settled + ' writtenOff=' + result.writtenOff)
|
|
7672
|
+
for (const total of result.totals) console.log(' ' + total.currency + ' amount=' + receivable.formatMinorAmount(BigInt(total.amountMinor)) + ' paid=' + receivable.formatMinorAmount(BigInt(total.paidMinor)) + ' outstanding=' + receivable.formatMinorAmount(BigInt(total.outstandingMinor)) + ' overdueCount=' + total.overdueCount + ' aging=' + JSON.stringify(total.aging))
|
|
7673
|
+
return
|
|
7674
|
+
}
|
|
7675
|
+
if (!result.receivables.length) console.log('(没有回款记录)')
|
|
7676
|
+
for (const row of result.receivables) console.log(row.id + ' ' + String(row.clientName ?? row.clientId) + ' ' + row.label + ' ' + receivableMoney(row) + (row.dueAt ? ' due ' + row.dueAt : ''))
|
|
7677
|
+
for (const total of result.totals) console.log('total ' + total.currency + ' outstanding=' + receivable.formatMinorAmount(BigInt(total.outstandingMinor)) + ' overdueCount=' + total.overdueCount)
|
|
7678
|
+
console.log('total=' + result.total + ' limit=' + result.limit + (result.truncated ? ' truncated' : '') + (result.protectedExcluded ? ' protectedExcluded=' + result.protectedExcluded : ''))
|
|
7679
|
+
return
|
|
7680
|
+
}
|
|
7681
|
+
if (sub === 'show') {
|
|
7682
|
+
const parsed = familyFlags(rawArgs.slice(1), { booleans: ['json'], values: ['clearance'] }, RECEIVABLE_USAGE)
|
|
7683
|
+
if (!parsed) return
|
|
7684
|
+
const id = parsed.positional[0]
|
|
7685
|
+
if (!id) { usageFail('missing receivable id', RECEIVABLE_USAGE); return }
|
|
7686
|
+
const result = receivable.receivableShow(familyStore(), id, { clearance: parsed.flags.clearance === undefined ? undefined : familyInteger(parsed.flags.clearance, '--clearance', 0, 3) })
|
|
7687
|
+
if (parsed.flags.json) { console.log(JSON.stringify(result, null, 2)); return }
|
|
7688
|
+
const row = result.receivable
|
|
7689
|
+
console.log(row.id + ' ' + row.label + ' ' + receivableMoney(row) + (row.dueAt ? ' due ' + row.dueAt : '') + (row.overdueDays ? ' overdueDays=' + row.overdueDays : ''))
|
|
7690
|
+
console.log('client=' + row.clientId + (row.projectId ? ' project=' + row.projectId : '') + (row.matterId ? ' matter=' + row.matterId : '') + ' commitment=' + row.commitmentId)
|
|
7691
|
+
for (const payment of result.payments) console.log(' payment ' + payment.id + ' ' + payment.amount + ' ' + payment.currency + ' ' + payment.paidAt + ' ' + payment.method + (payment.deletedAt ? ' [void]' : ''))
|
|
7692
|
+
return
|
|
7693
|
+
}
|
|
7694
|
+
if (sub === 'edit') {
|
|
7695
|
+
const parsed = familyFlags(rawArgs.slice(1), { booleans: ['json', 'no-remind'], values: ['amount', 'due', 'memo', 'kind', 'label', 'remind-offsets'] }, RECEIVABLE_USAGE)
|
|
7696
|
+
if (!parsed) return
|
|
7697
|
+
const id = parsed.positional[0]
|
|
7698
|
+
if (!id) { usageFail('missing receivable id', RECEIVABLE_USAGE); return }
|
|
7699
|
+
const patch = {}
|
|
7700
|
+
if (parsed.flags.amount !== undefined) patch.amount = parsed.flags.amount
|
|
7701
|
+
if (parsed.flags.due !== undefined) patch.dueAt = parsed.flags.due
|
|
7702
|
+
if (parsed.flags.memo !== undefined) patch.memo = parsed.flags.memo
|
|
7703
|
+
if (parsed.flags.kind !== undefined) patch.kind = parsed.flags.kind
|
|
7704
|
+
if (parsed.flags.label !== undefined) patch.label = parsed.flags.label
|
|
7705
|
+
if (parsed.flags['no-remind'] === true) patch.noRemind = true
|
|
7706
|
+
else if (parsed.flags['remind-offsets'] !== undefined) patch.reminderOffsets = parsed.flags['remind-offsets']
|
|
7707
|
+
const result = receivable.receivableEdit(familyStore({ write: true }), id, patch)
|
|
7708
|
+
if (parsed.flags.json) { console.log(JSON.stringify(result, null, 2)); return }
|
|
7709
|
+
console.log('updated ' + id + (result.receivable ? ' ' + receivableMoney(result.receivable) : ''))
|
|
7710
|
+
return
|
|
7711
|
+
}
|
|
7712
|
+
if (sub === 'void') {
|
|
7713
|
+
const parsed = familyFlags(rawArgs.slice(1), { booleans: ['json'], values: ['reason'] }, RECEIVABLE_USAGE)
|
|
7714
|
+
if (!parsed) return
|
|
7715
|
+
const id = parsed.positional[0]
|
|
7716
|
+
if (!id) { usageFail('missing receivable id', RECEIVABLE_USAGE); return }
|
|
7717
|
+
const result = receivable.receivableVoid(familyStore({ write: true }), id, { reason: parsed.flags.reason })
|
|
7718
|
+
if (parsed.flags.json) { console.log(JSON.stringify(result, null, 2)); return }
|
|
7719
|
+
console.log('void ' + id + (result.alreadyVoid ? ' (already void)' : '') + ' commitmentReopened=' + (result.reopenedCommitment ? 'yes' : 'no') + ' commitmentDropped=' + (result.droppedCommitment ? 'yes' : 'no'))
|
|
7720
|
+
return
|
|
7721
|
+
}
|
|
7722
|
+
usageFail('unknown receivable subcommand: ' + sub, RECEIVABLE_USAGE)
|
|
7723
|
+
} catch (error) { reportFamilyFailure(error) }
|
|
7724
|
+
}
|
|
7725
|
+
|
|
7726
|
+
async function paymentCommand(rawArgs) {
|
|
7727
|
+
const sub = rawArgs[0]
|
|
7728
|
+
try {
|
|
7729
|
+
if (!sub || sub === 'help' || sub === '--help') { console.log(PAYMENT_USAGE); return }
|
|
7730
|
+
const money = await loadReceivablesLib()
|
|
7731
|
+
if (sub === 'add') {
|
|
7732
|
+
const parsed = familyFlags(rawArgs.slice(1), { booleans: ['json', 'no-complete'], values: ['amount', 'currency', 'paid-at', 'method', 'receivable', 'commitment', 'memo'] }, PAYMENT_USAGE)
|
|
7733
|
+
if (!parsed) return
|
|
7734
|
+
const clientId = parsed.positional[0]
|
|
7735
|
+
if (!clientId) { usageFail('usage: advisers payment add <client-id> --amount 4000.00', PAYMENT_USAGE); return }
|
|
7736
|
+
if (parsed.flags.amount === undefined) { usageFail('--amount is required', PAYMENT_USAGE); return }
|
|
7737
|
+
const result = money.paymentAdd(familyStore({ write: true }), {
|
|
7738
|
+
clientId,
|
|
7739
|
+
amount: parsed.flags.amount,
|
|
7740
|
+
currency: parsed.flags.currency,
|
|
7741
|
+
paidAt: parsed.flags['paid-at'],
|
|
7742
|
+
method: parsed.flags.method,
|
|
7743
|
+
receivableId: parsed.flags.receivable,
|
|
7744
|
+
commitmentId: parsed.flags.commitment,
|
|
7745
|
+
memo: parsed.flags.memo,
|
|
7746
|
+
noComplete: parsed.flags['no-complete'] === true,
|
|
7747
|
+
})
|
|
7748
|
+
if (parsed.flags.json) { console.log(JSON.stringify(result, null, 2)); return }
|
|
7749
|
+
console.log('added ' + result.payment.id + ' ' + result.payment.amount + ' ' + result.payment.currency + ' ' + result.payment.paidAt + ' ' + result.payment.method + (result.receivable ? ' receivable=' + result.receivable.id : '') + (result.completedCommitment ? ' commitmentCompleted=yes' : ''))
|
|
7750
|
+
return
|
|
7751
|
+
}
|
|
7752
|
+
if (sub === 'ls' || sub === 'list') {
|
|
7753
|
+
const parsed = familyFlags(rawArgs.slice(1), { booleans: ['json'], values: ['client', 'receivable', 'since', 'limit', 'clearance'] }, PAYMENT_USAGE)
|
|
7754
|
+
if (!parsed) return
|
|
7755
|
+
const result = money.paymentList(familyStore(), {
|
|
7756
|
+
clientId: parsed.flags.client,
|
|
7757
|
+
receivableId: parsed.flags.receivable,
|
|
7758
|
+
since: parsed.flags.since,
|
|
7759
|
+
clearance: parsed.flags.clearance === undefined ? undefined : familyInteger(parsed.flags.clearance, '--clearance', 0, 3),
|
|
7760
|
+
limit: parsed.flags.limit === undefined ? undefined : familyInteger(parsed.flags.limit, '--limit', 1, 500),
|
|
7761
|
+
})
|
|
7762
|
+
if (parsed.flags.json) { console.log(JSON.stringify(result, null, 2)); return }
|
|
7763
|
+
if (!result.payments.length) console.log('(没有收款记录)')
|
|
7764
|
+
for (const payment of result.payments) console.log(payment.id + ' ' + payment.amount + ' ' + payment.currency + ' ' + payment.paidAt + ' ' + payment.method + (payment.receivableId ? ' rcv=' + payment.receivableId : ''))
|
|
7765
|
+
console.log('total=' + result.total + ' limit=' + result.limit + (result.truncated ? ' truncated' : ''))
|
|
7766
|
+
return
|
|
7767
|
+
}
|
|
7768
|
+
if (sub === 'void') {
|
|
7769
|
+
const parsed = familyFlags(rawArgs.slice(1), { booleans: ['json'], values: ['reason'] }, PAYMENT_USAGE)
|
|
7770
|
+
if (!parsed) return
|
|
7771
|
+
const id = parsed.positional[0]
|
|
7772
|
+
if (!id) { usageFail('missing payment id', PAYMENT_USAGE); return }
|
|
7773
|
+
const result = money.paymentVoid(familyStore({ write: true }), id, { reason: parsed.flags.reason })
|
|
7774
|
+
if (parsed.flags.json) { console.log(JSON.stringify(result, null, 2)); return }
|
|
7775
|
+
console.log('void ' + id + (result.alreadyVoid ? ' (already void)' : '') + ' commitmentReopened=' + (result.reopenedCommitment ? 'yes' : 'no'))
|
|
7776
|
+
return
|
|
7777
|
+
}
|
|
7778
|
+
usageFail('unknown payment subcommand: ' + sub, PAYMENT_USAGE)
|
|
7779
|
+
} catch (error) { reportFamilyFailure(error) }
|
|
7780
|
+
}
|
|
7781
|
+
|
|
7782
|
+
/* ------------------------------- consent -------------------------------- */
|
|
7783
|
+
|
|
7784
|
+
const CONSENT_USAGE = [
|
|
7785
|
+
'usage: advisers consent status [--json]',
|
|
7786
|
+
' advisers consent grant <surface> [--data-class mail|kb] [--provider deepseek] [--base-url URL] [--yes] [--json]',
|
|
7787
|
+
' advisers consent revoke <surface> [--data-class mail|kb] [--provider p] [--base-url URL] [--yes] [--json]',
|
|
7788
|
+
].join('\n')
|
|
7789
|
+
|
|
7790
|
+
function consentDataClassFor(surface, explicit) {
|
|
7791
|
+
if (explicit !== undefined) return String(explicit)
|
|
7792
|
+
const table = { 'mail.extract': 'mail', 'mail.sync': 'mail', 'kb.ask': 'kb', 'kb.ingest': 'kb', 'kb.search': 'kb' }
|
|
7793
|
+
return table[surface] ?? undefined
|
|
7794
|
+
}
|
|
7795
|
+
|
|
7796
|
+
async function consentCommand(rawArgs) {
|
|
7797
|
+
const sub = rawArgs[0]
|
|
7798
|
+
try {
|
|
7799
|
+
if (!sub || sub === 'help' || sub === '--help') { console.log(CONSENT_USAGE); return }
|
|
7800
|
+
const consent = await loadConsent()
|
|
7801
|
+
if (sub === 'status') {
|
|
7802
|
+
const parsed = familyFlags(rawArgs.slice(1), { booleans: ['json'], values: [] }, CONSENT_USAGE)
|
|
7803
|
+
if (!parsed) return
|
|
7804
|
+
const entries = consent.listConsents(HOME)
|
|
7805
|
+
const payload = { ok: true, command: 'consent status', path: consent.consentPath(HOME), configured: entries.length > 0, entries }
|
|
7806
|
+
if (parsed.flags.json) { console.log(JSON.stringify(payload, null, 2)); return }
|
|
7807
|
+
console.log('consent file: ' + payload.path + (payload.configured ? '' : '(尚未记录任何同意)'))
|
|
7808
|
+
if (!entries.length) console.log('(没有同意的数据外发)')
|
|
7809
|
+
for (const entry of entries) console.log(entry.surface + ' ' + entry.dataClass + ' ' + entry.provider + (entry.baseUrl ? ' ' + entry.baseUrl : '') + ' ' + (entry.active ? 'granted ' + entry.grantedAt : 'revoked ' + entry.revokedAt))
|
|
7810
|
+
return
|
|
7811
|
+
}
|
|
7812
|
+
if (sub === 'grant' || sub === 'revoke') {
|
|
7813
|
+
const parsed = familyFlags(rawArgs.slice(1), { booleans: ['json', 'yes'], values: ['data-class', 'provider', 'base-url', 'consent'] }, CONSENT_USAGE)
|
|
7814
|
+
if (!parsed) return
|
|
7815
|
+
const surface = parsed.positional[0]
|
|
7816
|
+
if (!surface) { usageFail('missing surface (for example mail.extract)', CONSENT_USAGE); return }
|
|
7817
|
+
const dataClass = consentDataClassFor(surface, parsed.flags['data-class'])
|
|
7818
|
+
if (!dataClass) throw familyError('E_POLICY_INVALID_FACTS', 'unknown consent data class for ' + surface, 'pass --data-class mail or --data-class kb')
|
|
7819
|
+
const provider = typeof parsed.flags.provider === 'string' ? parsed.flags.provider : (process.env.ADVISERS_PROVIDER || 'deepseek')
|
|
7820
|
+
const baseUrl = typeof parsed.flags['base-url'] === 'string' ? parsed.flags['base-url'] : (process.env.ADVISERS_BASE_URL || 'https://api.deepseek.com')
|
|
7821
|
+
const isTTY = Boolean(process.stdin.isTTY)
|
|
7822
|
+
const envOverride = process.env['ADVISERS_CONSENT_' + surface.toUpperCase().replace(/[^A-Z0-9]/g, '_')] === '1'
|
|
7823
|
+
const explicit = parsed.flags.yes === true || parsed.flags.consent !== undefined || envOverride
|
|
7824
|
+
if (sub === 'grant') {
|
|
7825
|
+
if (!isTTY && !explicit) throw familyError('E_CONSENT_CONFIRMATION_UNAVAILABLE', 'non-interactive consent grant requires an explicit --yes (or ADVISERS_CONSENT_<SURFACE>=1)', 'read advisers tos show and docs/PRIVACY.md first; this is a separate model-egress consent')
|
|
7826
|
+
if (isTTY && !explicit) {
|
|
7827
|
+
const answer = await askYesNo(null, '同意把 ' + dataClass + ' 内容发送给模型服务 ' + provider + (baseUrl ? ' (' + baseUrl + ')' : '') + '(' + surface + ')?[y/N] ', false)
|
|
7828
|
+
if (!answer) { console.log('已取消,未写入同意记录。'); return }
|
|
7829
|
+
}
|
|
7830
|
+
} else {
|
|
7831
|
+
if (!isTTY && !explicit) throw familyError('E_CONSENT_CONFIRMATION_UNAVAILABLE', 'non-interactive consent revoke requires an explicit --yes', 'run in a terminal to confirm the revocation')
|
|
7832
|
+
if (isTTY && !explicit) {
|
|
7833
|
+
const answer = await askYesNo(null, '撤回 ' + surface + ' 的同意?[y/N] ', false)
|
|
7834
|
+
if (!answer) { console.log('已取消。'); return }
|
|
7835
|
+
}
|
|
7836
|
+
}
|
|
7837
|
+
const audit = (event) => {
|
|
7838
|
+
const store = mode === 'sqlite' ? dbStore() : undefined
|
|
7839
|
+
if (!store) return { ok: false }
|
|
7840
|
+
try { store.appendAudit({ actor: 'local', action: event.action, allowed: event.ok === true, reason: String(event.surface) + ' ' + String(event.dataClass ?? '') }); return { ok: true } } catch { return { ok: false } }
|
|
7841
|
+
}
|
|
7842
|
+
const channel = isTTY ? 'tty' : 'flag'
|
|
7843
|
+
const result = sub === 'grant'
|
|
7844
|
+
? consent.grantConsent(HOME, { surface, dataClass, provider, baseUrl, channel, audit })
|
|
7845
|
+
: consent.revokeConsent(HOME, { surface, dataClass, provider, baseUrl, audit })
|
|
7846
|
+
const payload = { ok: true, command: 'consent ' + sub, ...result, auditWritten: result.auditWritten === true }
|
|
7847
|
+
if (parsed.flags.json) { console.log(JSON.stringify(payload, null, 2)); return }
|
|
7848
|
+
if (sub === 'grant') console.log('granted ' + surface + ' / ' + dataClass + ' / ' + provider + ' (channel=' + channel + ')')
|
|
7849
|
+
else console.log('revoked ' + result.revoked + ' consent entr' + (result.revoked === 1 ? 'y' : 'ies') + ' for ' + surface)
|
|
7850
|
+
return
|
|
7851
|
+
}
|
|
7852
|
+
usageFail('unknown consent subcommand: ' + sub, CONSENT_USAGE)
|
|
7853
|
+
} catch (error) { reportFamilyFailure(error) }
|
|
7854
|
+
}
|
|
7855
|
+
|
|
6124
7856
|
function ls() {
|
|
6125
7857
|
const matters = loadReadLedger({ matters: {} }).listMatters()
|
|
6126
7858
|
if (!matters.length) {
|
|
@@ -6431,6 +8163,121 @@ function applyCustomerImport(store, tables) {
|
|
|
6431
8163
|
return { clients: clientCount, projects: projectCount, clientNotes: noteCount, reconciledDeliveries: reconciledDeliveries }
|
|
6432
8164
|
}
|
|
6433
8165
|
|
|
8166
|
+
|
|
8167
|
+
/* ---------------------------------------------------------------------------
|
|
8168
|
+
* 0.4.0 (task-29): export --all / import --replace symmetry.
|
|
8169
|
+
*
|
|
8170
|
+
* export --all writes DATA_TABLES (KB, mail, money included). import --replace
|
|
8171
|
+
* validates and restores the same table list in ONE transaction: the ledger via
|
|
8172
|
+
* saveWithAudit, the customer tables through the 0.3.2 reference checks, and the
|
|
8173
|
+
* derived/auxiliary tables (sessions/turns/deliveries/audit/KB/mail/money).
|
|
8174
|
+
* Derived FTS tables and mail_cursors are never imported; kb_pages is dropped
|
|
8175
|
+
* because its inputs changed.
|
|
8176
|
+
* ------------------------------------------------------------------------- */
|
|
8177
|
+
const MONEY_IMPORT_TABLES = ['receivables', 'payments']
|
|
8178
|
+
// mail_cursors: server-side IMAP cursors are meaningless on another machine.
|
|
8179
|
+
// audit: the hash chain is keyed by THIS home's audit.key, so importing another
|
|
8180
|
+
// home's rows would report a broken chain; the local chain is preserved and the
|
|
8181
|
+
// import keeps appending to it.
|
|
8182
|
+
const IMPORT_TABLE_DENYLIST = new Set(['mail_cursors', 'audit'])
|
|
8183
|
+
const IMPORT_TABLES = DATA_TABLES.filter((table) => !IMPORT_TABLE_DENYLIST.has(table))
|
|
8184
|
+
|
|
8185
|
+
/** Validate the shape of payload.data before any write happens (all DATA_TABLES). */
|
|
8186
|
+
function prepareDataImport(payloadData) {
|
|
8187
|
+
if (!payloadData || typeof payloadData !== 'object' || Array.isArray(payloadData)) return null
|
|
8188
|
+
const present = IMPORT_TABLES.filter((table) => Object.prototype.hasOwnProperty.call(payloadData, table))
|
|
8189
|
+
if (!present.length) return null
|
|
8190
|
+
const tables = {}
|
|
8191
|
+
for (const table of IMPORT_TABLES) {
|
|
8192
|
+
if (!Object.prototype.hasOwnProperty.call(payloadData, table)) {
|
|
8193
|
+
// A pre-0.4 export has no money tables: clear them so old commitments are
|
|
8194
|
+
// never left with dangling money rows. Other absent tables are left as-is.
|
|
8195
|
+
tables[table] = MONEY_IMPORT_TABLES.includes(table) ? [] : null
|
|
8196
|
+
continue
|
|
8197
|
+
}
|
|
8198
|
+
const rows = payloadData[table]
|
|
8199
|
+
if (!Array.isArray(rows)) throw importDataError('import data.' + table + ' must be an array')
|
|
8200
|
+
if (rows.length > CUSTOMER_IMPORT_MAX_ROWS) throw importDataError('import data.' + table + ' has too many rows (max ' + CUSTOMER_IMPORT_MAX_ROWS + ')')
|
|
8201
|
+
for (let index = 0; index < rows.length; index += 1) {
|
|
8202
|
+
const row = rows[index]
|
|
8203
|
+
if (!row || typeof row !== 'object' || Array.isArray(row)) throw importDataError('import data.' + table + '[' + index + '] must be an object')
|
|
8204
|
+
}
|
|
8205
|
+
tables[table] = rows
|
|
8206
|
+
}
|
|
8207
|
+
return tables
|
|
8208
|
+
}
|
|
8209
|
+
|
|
8210
|
+
/**
|
|
8211
|
+
* Restore every exported DATA_TABLES entry inside the import transaction.
|
|
8212
|
+
* Throws importDataError on a dangling reference; the caller's transaction rolls
|
|
8213
|
+
* back and the pre-import backup stays as the recovery copy.
|
|
8214
|
+
*/
|
|
8215
|
+
function applyDataImport(store, tables) {
|
|
8216
|
+
const report = { tables: {}, customer: null, cleared: [], kbReconciled: 0, kbPagesCleared: 0 }
|
|
8217
|
+
const customerPresent = CUSTOMER_IMPORT_TABLES.some((table) => Array.isArray(tables[table]))
|
|
8218
|
+
if (customerPresent) {
|
|
8219
|
+
report.customer = applyCustomerImport(store, {
|
|
8220
|
+
clients: Array.isArray(tables.clients) ? tables.clients : [],
|
|
8221
|
+
projects: Array.isArray(tables.projects) ? tables.projects : [],
|
|
8222
|
+
client_notes: Array.isArray(tables.client_notes) ? tables.client_notes : [],
|
|
8223
|
+
})
|
|
8224
|
+
report.tables.clients = report.customer.clients
|
|
8225
|
+
report.tables.projects = report.customer.projects
|
|
8226
|
+
report.tables.client_notes = report.customer.clientNotes
|
|
8227
|
+
}
|
|
8228
|
+
const restored = (table) => !CUSTOMER_IMPORT_TABLES.includes(table)
|
|
8229
|
+
for (const table of IMPORT_TABLES) {
|
|
8230
|
+
if (!restored(table)) continue
|
|
8231
|
+
const rows = tables[table]
|
|
8232
|
+
if (rows === null || rows === undefined) continue
|
|
8233
|
+
report.tables[table] = replaceCustomerTable(store, table, rows)
|
|
8234
|
+
}
|
|
8235
|
+
// KB: chunks must point at a restored document; entity ids are reconciled to
|
|
8236
|
+
// NULL (KB is derived data, never a reason to reject the whole import).
|
|
8237
|
+
if (tables.kb_documents !== null || tables.kb_chunks !== null || tables.kb_fact_links !== null) {
|
|
8238
|
+
const docIds = new Set(store.db.prepare('SELECT id FROM kb_documents').all().map((row) => row.id))
|
|
8239
|
+
for (const chunk of store.db.prepare('SELECT id, doc_id FROM kb_chunks').all()) {
|
|
8240
|
+
if (!docIds.has(chunk.doc_id)) throw importDataError('import data.kb_chunks references a missing document: ' + String(chunk.doc_id))
|
|
8241
|
+
}
|
|
8242
|
+
const clientIds = new Set(store.db.prepare('SELECT id FROM clients').all().map((row) => row.id))
|
|
8243
|
+
const projectIds = new Set(store.db.prepare('SELECT id FROM projects').all().map((row) => row.id))
|
|
8244
|
+
const matterIds = new Set(store.db.prepare('SELECT id FROM matters').all().map((row) => row.id))
|
|
8245
|
+
for (const doc of store.db.prepare('SELECT id, client_id, project_id, matter_id FROM kb_documents').all()) {
|
|
8246
|
+
const nextClient = doc.client_id !== null && clientIds.has(doc.client_id) ? doc.client_id : null
|
|
8247
|
+
const nextProject = doc.project_id !== null && projectIds.has(doc.project_id) ? doc.project_id : null
|
|
8248
|
+
const nextMatter = doc.matter_id !== null && matterIds.has(doc.matter_id) ? doc.matter_id : null
|
|
8249
|
+
if (nextClient !== doc.client_id || nextProject !== doc.project_id || nextMatter !== doc.matter_id) {
|
|
8250
|
+
store.db.prepare('UPDATE kb_documents SET client_id = ?, project_id = ?, matter_id = ? WHERE id = ?').run(nextClient, nextProject, nextMatter, doc.id)
|
|
8251
|
+
report.kbReconciled += 1
|
|
8252
|
+
}
|
|
8253
|
+
}
|
|
8254
|
+
for (const link of store.db.prepare('SELECT fact_id, doc_id FROM kb_fact_links').all()) {
|
|
8255
|
+
if (!docIds.has(link.doc_id)) { store.db.prepare('DELETE FROM kb_fact_links WHERE fact_id = ? AND doc_id = ?').run(link.fact_id, link.doc_id); report.kbReconciled += 1 }
|
|
8256
|
+
}
|
|
8257
|
+
report.kbPagesCleared = Number(store.db.prepare('DELETE FROM kb_pages').run().changes ?? 0)
|
|
8258
|
+
try { store.rebuildAllFtsIndexes() } catch {}
|
|
8259
|
+
}
|
|
8260
|
+
// Money: an import must not leave money rows pointing at missing entities.
|
|
8261
|
+
if (tables.receivables !== null || tables.payments !== null) {
|
|
8262
|
+
const commitmentIds = new Set(store.db.prepare('SELECT id FROM commitments').all().map((row) => row.id))
|
|
8263
|
+
const clientIds = new Set(store.db.prepare('SELECT id FROM clients').all().map((row) => row.id))
|
|
8264
|
+
const receivableById = new Map(store.db.prepare('SELECT id, commitment_id, client_id, currency FROM receivables').all().map((row) => [row.id, row]))
|
|
8265
|
+
for (const row of receivableById.values()) {
|
|
8266
|
+
if (!commitmentIds.has(row.commitment_id)) throw importDataError('import data.receivables references a missing commitment: ' + String(row.commitment_id))
|
|
8267
|
+
if (!clientIds.has(row.client_id)) throw importDataError('import data.receivables references a missing client: ' + String(row.client_id))
|
|
8268
|
+
}
|
|
8269
|
+
for (const payment of store.db.prepare('SELECT id, client_id, commitment_id, currency FROM payments').all()) {
|
|
8270
|
+
if (!clientIds.has(payment.client_id)) throw importDataError('import data.payments references a missing client: ' + String(payment.client_id))
|
|
8271
|
+
if (payment.commitment_id !== null && !commitmentIds.has(payment.commitment_id)) throw importDataError('import data.payments references a missing commitment: ' + String(payment.commitment_id))
|
|
8272
|
+
if (payment.commitment_id !== null) {
|
|
8273
|
+
const receivable = [...receivableById.values()].find((row) => row.commitment_id === payment.commitment_id)
|
|
8274
|
+
if (receivable && receivable.currency !== payment.currency) throw importDataError('import data.payments currency does not match its receivable: ' + String(payment.id))
|
|
8275
|
+
}
|
|
8276
|
+
}
|
|
8277
|
+
}
|
|
8278
|
+
return report
|
|
8279
|
+
}
|
|
8280
|
+
|
|
6434
8281
|
async function importLedger(file, { replace = false } = {}) {
|
|
6435
8282
|
if (!file) { console.error('usage: advisers import <file> [--replace]'); process.exitCode = 1; return }
|
|
6436
8283
|
if (!replace) { console.error('import replaces the local ledger; pass --replace to confirm'); process.exitCode = 1; return }
|
|
@@ -6464,8 +8311,8 @@ async function importLedger(file, { replace = false } = {}) {
|
|
|
6464
8311
|
}
|
|
6465
8312
|
// Validate the customer-table payload shape BEFORE any write; the restore
|
|
6466
8313
|
// itself runs inside the import transaction and rolls back on a bad reference.
|
|
6467
|
-
let
|
|
6468
|
-
try {
|
|
8314
|
+
let dataImport = null
|
|
8315
|
+
try { dataImport = prepareDataImport(payload?.data) } catch (error) {
|
|
6469
8316
|
console.error('import failed: ' + error.message)
|
|
6470
8317
|
process.exitCode = 1
|
|
6471
8318
|
return
|
|
@@ -6480,16 +8327,26 @@ async function importLedger(file, { replace = false } = {}) {
|
|
|
6480
8327
|
facts: Array.isArray(data.facts) ? data.facts.length : 0,
|
|
6481
8328
|
preferences: Array.isArray(data.preferences) ? data.preferences.length : 0,
|
|
6482
8329
|
}
|
|
6483
|
-
if (
|
|
6484
|
-
|
|
6485
|
-
|
|
6486
|
-
|
|
8330
|
+
if (dataImport) {
|
|
8331
|
+
// Additive per-table line: the old clients/projects/clientNotes keys stay.
|
|
8332
|
+
for (const table of Object.keys(dataImport)) {
|
|
8333
|
+
const rows = dataImport[table]
|
|
8334
|
+
if (!Array.isArray(rows)) continue
|
|
8335
|
+
incoming[table] = rows.length
|
|
8336
|
+
}
|
|
8337
|
+
incoming.clients = (dataImport.clients ?? []).length
|
|
8338
|
+
incoming.projects = (dataImport.projects ?? []).length
|
|
8339
|
+
incoming.clientNotes = (dataImport.client_notes ?? []).length
|
|
6487
8340
|
}
|
|
6488
8341
|
const importBackupFile = mode === 'sqlite' ? join(HOME, 'import-backup-' + Date.now() + '.db') : null
|
|
6489
8342
|
console.log('! 需要确认:整库替换本地账本(不是合并)')
|
|
6490
|
-
console.log(' 写入:' + incoming.matters + ' 个事项 / ' + incoming.commitments + ' 条承诺 / ' + incoming.facts + ' 条事实 / ' + incoming.preferences + ' 条偏好' + (
|
|
8343
|
+
console.log(' 写入:' + incoming.matters + ' 个事项 / ' + incoming.commitments + ' 条承诺 / ' + incoming.facts + ' 条事实 / ' + incoming.preferences + ' 条偏好' + (dataImport ? ' / ' + incoming.clients + ' 个客户 / ' + incoming.projects + ' 个项目 / ' + incoming.clientNotes + ' 条客户备注' : ''))
|
|
8344
|
+
if (dataImport) {
|
|
8345
|
+
const summary = Object.keys(dataImport).filter((table) => Array.isArray(dataImport[table])).map((table) => table + '=' + dataImport[table].length).join(', ')
|
|
8346
|
+
console.log(' 导出表:' + summary)
|
|
8347
|
+
}
|
|
6491
8348
|
console.log(' 备份:' + (importBackupFile ?? '(JSON store:无数据库备份,旧 state.json 会被覆盖)'))
|
|
6492
|
-
console.log(' 不可撤销:替换后只能用上面的备份恢复;' + (
|
|
8349
|
+
console.log(' 不可撤销:替换后只能用上面的备份恢复;' + (dataImport ? '导出的 DATA_TABLES 按同一事务恢复(派生 FTS 与 mail_cursors 除外),kb_pages 需重新生成。' : '未导入的 SQLite-only 表不会被保留。'))
|
|
6493
8350
|
// import replaces the ledger wholesale; serialize it with every other store
|
|
6494
8351
|
// user (P0-1) before copying the pre-import backup and writing.
|
|
6495
8352
|
ensureInstanceLock()
|
|
@@ -6522,21 +8379,32 @@ async function importLedger(file, { replace = false } = {}) {
|
|
|
6522
8379
|
try {
|
|
6523
8380
|
const ledger = Ledger.fromJSON(data, LOCAL_PORTS)
|
|
6524
8381
|
const audit = { actor: 'local', action: 'import.ledger', allowed: true, reason: basename(file) }
|
|
6525
|
-
let
|
|
6526
|
-
if (
|
|
6527
|
-
// One transaction: the
|
|
6528
|
-
//
|
|
6529
|
-
//
|
|
8382
|
+
let dataReport = null
|
|
8383
|
+
if (dataImport && mode === 'sqlite') {
|
|
8384
|
+
// One transaction: the ledger tables (saveWithAudit) and every exported
|
|
8385
|
+
// DATA_TABLES entry (applyDataImport), including their cross-reference
|
|
8386
|
+
// validation. A bad reference throws and rolls the whole replace back; the
|
|
8387
|
+
// pre-import backup remains as a second net.
|
|
6530
8388
|
openStore().saveWithAudit(ledger.toJSON(), audit, (innerStore) => {
|
|
6531
|
-
|
|
8389
|
+
dataReport = applyDataImport(innerStore, dataImport)
|
|
6532
8390
|
})
|
|
6533
8391
|
} else {
|
|
6534
8392
|
saveLedgerWithAudit(ledger, audit)
|
|
6535
8393
|
}
|
|
6536
8394
|
console.log(`imported ${data.matters.length} matters, ${data.commitments?.length ?? 0} commitments`)
|
|
6537
|
-
if (
|
|
8395
|
+
if (dataReport?.customer) {
|
|
8396
|
+
const customerReport = dataReport.customer
|
|
6538
8397
|
console.log('restored clients=' + customerReport.clients + ' projects=' + customerReport.projects + ' client_notes=' + customerReport.clientNotes + (customerReport.reconciledDeliveries ? ' · delivery lineage reconciled=' + customerReport.reconciledDeliveries : ''))
|
|
6539
|
-
|
|
8398
|
+
}
|
|
8399
|
+
if (dataReport) {
|
|
8400
|
+
const restoredTables = Object.entries(dataReport.tables)
|
|
8401
|
+
.filter(([table]) => !CUSTOMER_IMPORT_TABLES.includes(table))
|
|
8402
|
+
.map(([table, count]) => table + '=' + count)
|
|
8403
|
+
.join(', ')
|
|
8404
|
+
if (restoredTables) console.log('restored tables: ' + restoredTables)
|
|
8405
|
+
if (dataReport.kbReconciled) console.log('kb reconciled rows=' + dataReport.kbReconciled)
|
|
8406
|
+
if (dataReport.kbPagesCleared) console.log('kb_pages cleared=' + dataReport.kbPagesCleared + ' (run advisers kb page rebuild)')
|
|
8407
|
+
console.error('note: ledger + exported DATA_TABLES were replaced (derived FTS tables, mail_cursors and the machine-local audit chain excluded); the local audit chain stays valid.')
|
|
6540
8408
|
} else if (payload?.data) {
|
|
6541
8409
|
console.error('note: SQLite-only tables in the import were not merged; ledger was replaced.')
|
|
6542
8410
|
}
|
|
@@ -8282,6 +10150,95 @@ async function ui(args) {
|
|
|
8282
10150
|
await app.close()
|
|
8283
10151
|
}
|
|
8284
10152
|
|
|
10153
|
+
let webhookSecretWarned = false
|
|
10154
|
+
|
|
10155
|
+
/** Parse remind --now into a Date (fixed instant for reproducible JSON + planning). */
|
|
10156
|
+
function parseRemindNow(flags) {
|
|
10157
|
+
if (flags.now === undefined) return { date: new Date() }
|
|
10158
|
+
if (typeof flags.now !== 'string' || Number.isNaN(Date.parse(flags.now))) return { error: '--now must be an ISO timestamp' }
|
|
10159
|
+
return { date: new Date(Date.parse(flags.now)) }
|
|
10160
|
+
}
|
|
10161
|
+
|
|
10162
|
+
const QUIET_HOURS_RE = /^([01]\d|2[0-3]):([0-5]\d)-([01]\d|2[0-3]):([0-5]\d)$/
|
|
10163
|
+
/** Validate --quiet-hours HH:MM-HH:MM; the value is baked into the scheduler script only. */
|
|
10164
|
+
function parseQuietHours(value) {
|
|
10165
|
+
if (value === undefined) return { value: null }
|
|
10166
|
+
if (typeof value !== 'string' || !QUIET_HOURS_RE.test(value)) return { error: '--quiet-hours must be HH:MM-HH:MM (for example 22:00-08:00)' }
|
|
10167
|
+
return { value: value }
|
|
10168
|
+
}
|
|
10169
|
+
|
|
10170
|
+
const QUIET_HOURS_PARTS_RE = /^([01]\d|2[0-3]):([0-5]\d)-([01]\d|2[0-3]):([0-5]\d)$/
|
|
10171
|
+
|
|
10172
|
+
/** Local minute-of-day in the agenda timezone (deterministic for --now tests). */
|
|
10173
|
+
function localMinuteOfDay(date) {
|
|
10174
|
+
const parts = new Intl.DateTimeFormat('en-GB', { timeZone: AGENDA_TIMEZONE, hour: '2-digit', minute: '2-digit', hour12: false }).formatToParts(date)
|
|
10175
|
+
const hour = Number(parts.find((part) => part.type === 'hour')?.value ?? 0) % 24
|
|
10176
|
+
const minute = Number(parts.find((part) => part.type === 'minute')?.value ?? 0)
|
|
10177
|
+
return hour * 60 + minute
|
|
10178
|
+
}
|
|
10179
|
+
|
|
10180
|
+
/** True when `date` falls inside a validated HH:MM-HH:MM quiet window (cross-midnight supported). */
|
|
10181
|
+
function isInsideQuietHours(spec, date) {
|
|
10182
|
+
const match = QUIET_HOURS_PARTS_RE.exec(String(spec ?? ''))
|
|
10183
|
+
if (!match) return false
|
|
10184
|
+
const start = Number(match[1]) * 60 + Number(match[2])
|
|
10185
|
+
const end = Number(match[3]) * 60 + Number(match[4])
|
|
10186
|
+
if (start === end) return false
|
|
10187
|
+
const minute = localMinuteOfDay(date)
|
|
10188
|
+
return start < end ? minute >= start && minute < end : minute >= start || minute < end
|
|
10189
|
+
}
|
|
10190
|
+
|
|
10191
|
+
/** Dedupe key for one reminder notification scoped to a local day. */
|
|
10192
|
+
function reminderNotifyDedupeKey(reminder, localDay) {
|
|
10193
|
+
return 'notify:dedupe:' + [reminder.commitmentId, reminder.bucket, reminder.ruleId, localDay].join('|')
|
|
10194
|
+
}
|
|
10195
|
+
|
|
10196
|
+
function localDayOfInstant(date) {
|
|
10197
|
+
return new Intl.DateTimeFormat('en-CA', { timeZone: AGENDA_TIMEZONE }).format(date)
|
|
10198
|
+
}
|
|
10199
|
+
|
|
10200
|
+
/** Drop dedupe keys older than 30 local days (bounded metadata growth). */
|
|
10201
|
+
function pruneNotifyDedupe(store, nowDate) {
|
|
10202
|
+
if (!store || typeof store.listMetaByPrefix !== 'function' || typeof store.deleteMeta !== 'function') return
|
|
10203
|
+
const cutoff = nowDate.getTime() - 30 * 86400_000
|
|
10204
|
+
for (const [key, value] of store.listMetaByPrefix('notify:dedupe:')) {
|
|
10205
|
+
const at = Date.parse(String(value ?? ''))
|
|
10206
|
+
if (Number.isFinite(at) && at < cutoff) store.deleteMeta(key)
|
|
10207
|
+
}
|
|
10208
|
+
}
|
|
10209
|
+
|
|
10210
|
+
const HHMM_RE = /^([01]\d|2[0-3]):([0-5]\d)$/
|
|
10211
|
+
function parseHhmm(value, flag) {
|
|
10212
|
+
if (typeof value !== 'string' || !HHMM_RE.test(value)) return { error: flag + ' must be HH:MM' }
|
|
10213
|
+
const parts = value.split(':').map(Number)
|
|
10214
|
+
return { time: value, hour: parts[0], minute: parts[1] }
|
|
10215
|
+
}
|
|
10216
|
+
|
|
10217
|
+
const MORNING_WINDOWS_DAYS = ['SUN', 'MON', 'TUE', 'WED', 'THU', 'FRI', 'SAT']
|
|
10218
|
+
/** Accept a cron day list (1-5, 1,3,5) and derive both cron and schtasks forms. */
|
|
10219
|
+
function parseMorningDays(value) {
|
|
10220
|
+
const text = value === undefined ? '1-5' : String(value).trim()
|
|
10221
|
+
if (!/^[0-7](?:[-,][0-7])*$/.test(text)) return { error: '--morning-days must be a cron day list like 1-5 or 1,3,5' }
|
|
10222
|
+
const numeric = []
|
|
10223
|
+
for (const part of text.split(',')) {
|
|
10224
|
+
if (part.includes('-')) {
|
|
10225
|
+
const bounds = part.split('-').map(Number)
|
|
10226
|
+
const from = Math.min(bounds[0], bounds[1])
|
|
10227
|
+
const to = Math.max(bounds[0], bounds[1])
|
|
10228
|
+
for (let day = from; day <= to; day++) numeric.push(day % 7)
|
|
10229
|
+
} else numeric.push(Number(part) % 7)
|
|
10230
|
+
}
|
|
10231
|
+
const unique = [...new Set(numeric)]
|
|
10232
|
+
if (!unique.length) return { error: '--morning-days must name at least one day' }
|
|
10233
|
+
return { cron: text, windows: unique.map((day) => MORNING_WINDOWS_DAYS[day]) }
|
|
10234
|
+
}
|
|
10235
|
+
|
|
10236
|
+
/** m h * * <days> cron schedule from an HH:MM time. */
|
|
10237
|
+
function cronScheduleFor(timeText, daysCron) {
|
|
10238
|
+
const parts = timeText.split(':').map(Number)
|
|
10239
|
+
return parts[1] + ' ' + parts[0] + ' * * ' + (daysCron ?? '*')
|
|
10240
|
+
}
|
|
10241
|
+
|
|
8285
10242
|
async function remind(args) {
|
|
8286
10243
|
const { flags, positional } = parseFlags(args)
|
|
8287
10244
|
ensureHome()
|
|
@@ -8311,39 +10268,95 @@ async function remind(args) {
|
|
|
8311
10268
|
mkdirSync(dir, { recursive: true, mode: 0o700 })
|
|
8312
10269
|
const nodeBin = process.execPath
|
|
8313
10270
|
const cli = process.argv[1]
|
|
8314
|
-
|
|
8315
|
-
|
|
8316
|
-
|
|
10271
|
+
const quiet = parseQuietHours(flags['quiet-hours'])
|
|
10272
|
+
if (quiet.error) { usageFail(quiet.error, 'usage: advisers remind install [--apply] [--schedule "0 9 * * *"] [--morning [--morning-time 08:30] [--morning-days 1-5]] [--quiet-hours 22:00-08:00]'); return }
|
|
10273
|
+
const withMorning = flags.morning === true
|
|
10274
|
+
const remindArgs = [...scheduler.DEFAULT_REMIND_ARGS, ...(quiet.value ? ['--quiet-hours', quiet.value] : [])]
|
|
10275
|
+
const remindCommand = scheduler.buildCronCommand({ nodeBin, cliPath: cli, args: remindArgs })
|
|
10276
|
+
writeFileSync(join(dir, 'remind.sh'), '#!/bin/sh\n"' + nodeBin + '" "' + cli + '" ' + remindArgs.join(' ') + ' >> "' + join(HOME, 'reminders.log') + '" 2>&1\n', { mode: 0o700 })
|
|
10277
|
+
writeFileSync(join(dir, 'remind.ps1'), '& "' + nodeBin + '" "' + cli + '" ' + remindArgs.join(' ') + ' *>> "' + join(HOME, 'reminders.log') + '"\n', { mode: 0o700 })
|
|
10278
|
+
let morningCommand
|
|
10279
|
+
let morningPlan = null
|
|
10280
|
+
if (withMorning) {
|
|
10281
|
+
const morningTime = parseHhmm(flags['morning-time'] === undefined ? scheduler.DEFAULT_MORNING_TASK_TIME : flags['morning-time'], '--morning-time')
|
|
10282
|
+
if (morningTime.error) { usageFail(morningTime.error, 'usage: advisers remind install --morning [--morning-time 08:30] [--morning-days 1-5]'); return }
|
|
10283
|
+
const morningDays = parseMorningDays(flags['morning-days'])
|
|
10284
|
+
if (morningDays.error) { usageFail(morningDays.error, 'usage: advisers remind install --morning [--morning-time 08:30] [--morning-days 1-5]'); return }
|
|
10285
|
+
morningCommand = scheduler.buildCronCommand({ nodeBin, cliPath: cli, args: scheduler.DEFAULT_MORNING_ARGS })
|
|
10286
|
+
writeFileSync(join(dir, 'morning.sh'), '#!/bin/sh\n"' + nodeBin + '" "' + cli + '" ' + scheduler.DEFAULT_MORNING_ARGS.join(' ') + ' >> "' + join(HOME, 'morning.log') + '" 2>&1\n', { mode: 0o700 })
|
|
10287
|
+
writeFileSync(join(dir, 'morning.ps1'), '& "' + nodeBin + '" "' + cli + '" ' + scheduler.DEFAULT_MORNING_ARGS.join(' ') + ' *>> "' + join(HOME, 'morning.log') + '"\n', { mode: 0o700 })
|
|
10288
|
+
// The second block is opt-in: without --morning the 0.3.2 single-block
|
|
10289
|
+
// install (and its exact dry-run output) is unchanged.
|
|
10290
|
+
const blocks = process.platform === 'win32'
|
|
10291
|
+
? [
|
|
10292
|
+
{ marker: scheduler.CRON_MARKER, taskName: scheduler.DEFAULT_TASK_NAME, time: typeof flags.time === 'string' ? flags.time : scheduler.DEFAULT_TASK_TIME, schedule: 'daily', command: remindCommand },
|
|
10293
|
+
{ marker: scheduler.MORNING_CRON_MARKER, taskName: scheduler.DEFAULT_MORNING_TASK_NAME, time: morningTime.time, schedule: 'weekly', days: morningDays.windows, command: morningCommand },
|
|
10294
|
+
]
|
|
10295
|
+
: [
|
|
10296
|
+
{ marker: scheduler.CRON_MARKER, schedule: typeof flags.schedule === 'string' ? flags.schedule : scheduler.DEFAULT_CRON_SCHEDULE, command: remindCommand },
|
|
10297
|
+
{ marker: scheduler.MORNING_CRON_MARKER, schedule: cronScheduleFor(morningTime.time, morningDays.cron), command: morningCommand },
|
|
10298
|
+
]
|
|
10299
|
+
morningPlan = { blocks, schedule: cronScheduleFor(morningTime.time, morningDays.cron), days: morningDays }
|
|
10300
|
+
}
|
|
10301
|
+
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\n' + (withMorning ? 'Morning brief: register morning.sh/.ps1 for ' + morningPlan.schedule + ' (or point Task Scheduler at morning.ps1).\n' : '') + 'Or import ~/.advisers/reminders.ics into your calendar.\n')
|
|
8317
10302
|
store?.appendAudit({ actor: 'local', action: 'notify.install', allowed: true, reason: dir })
|
|
8318
10303
|
console.log('scheduler scripts written: ' + dir)
|
|
8319
10304
|
console.log('opt-in: import ~/.advisers/reminders.ics, or register remind.sh/.ps1 with your OS scheduler.')
|
|
8320
|
-
|
|
10305
|
+
if (withMorning) console.log('morning scripts written: ' + join(dir, 'morning.sh') + ' / morning.ps1')
|
|
10306
|
+
const existing = apply ? await readCrontabText() : { ok: false }
|
|
10307
|
+
if (withMorning) {
|
|
10308
|
+
const plan = scheduler.planSchedulerBlocks({
|
|
10309
|
+
platform: process.platform,
|
|
10310
|
+
action: 'install',
|
|
10311
|
+
dryRun: !apply,
|
|
10312
|
+
blocks: morningPlan.blocks,
|
|
10313
|
+
...(existing.ok ? { existingText: existing.text } : {}),
|
|
10314
|
+
})
|
|
10315
|
+
console.log('schedule: ' + (plan.platform === 'win32' ? scheduler.DEFAULT_TASK_NAME + ' daily ' + scheduler.DEFAULT_TASK_TIME : morningPlan.blocks[0].schedule))
|
|
10316
|
+
console.log('morning schedule: ' + (plan.platform === 'win32' ? scheduler.DEFAULT_MORNING_TASK_NAME + ' weekly ' + morningPlan.blocks[1].time + ' ' + morningPlan.blocks[1].days.join(',') : morningPlan.schedule))
|
|
10317
|
+
console.log('command: ' + remindCommand)
|
|
10318
|
+
console.log('morning command: ' + morningCommand)
|
|
10319
|
+
await applySchedulerPlan(plan, { apply })
|
|
10320
|
+
return
|
|
10321
|
+
}
|
|
8321
10322
|
const schedule = typeof flags.schedule === 'string' ? flags.schedule : scheduler.DEFAULT_CRON_SCHEDULE
|
|
8322
10323
|
const time = typeof flags.time === 'string' ? flags.time : scheduler.DEFAULT_TASK_TIME
|
|
8323
|
-
|
|
10324
|
+
// Windows Task Scheduler has no cron expression: a user cron schedule is
|
|
10325
|
+
// accepted for compatibility but the task is registered daily at `time`.
|
|
10326
|
+
const winSchedule = process.platform === 'win32' ? 'daily' : schedule
|
|
8324
10327
|
const plan = scheduler.planScheduler({
|
|
8325
10328
|
platform: process.platform,
|
|
8326
10329
|
action: 'install',
|
|
8327
10330
|
dryRun: !apply,
|
|
8328
|
-
command,
|
|
8329
|
-
schedule,
|
|
10331
|
+
command: remindCommand,
|
|
10332
|
+
schedule: winSchedule,
|
|
8330
10333
|
time,
|
|
8331
10334
|
...(existing.ok ? { existingText: existing.text } : {}),
|
|
8332
10335
|
})
|
|
8333
10336
|
console.log('schedule: ' + (plan.platform === 'win32' ? plan.taskName + ' daily ' + plan.time : plan.schedule))
|
|
8334
|
-
console.log('command: ' +
|
|
10337
|
+
console.log('command: ' + remindCommand)
|
|
8335
10338
|
await applySchedulerPlan(plan, { apply })
|
|
8336
10339
|
return
|
|
8337
10340
|
}
|
|
8338
10341
|
if (sub === 'uninstall' || flags.uninstall) {
|
|
8339
10342
|
const dir = join(HOME, 'scheduler')
|
|
8340
10343
|
const existing = await readCrontabText()
|
|
8341
|
-
|
|
8342
|
-
|
|
8343
|
-
|
|
8344
|
-
|
|
8345
|
-
|
|
8346
|
-
|
|
10344
|
+
// 0.4.0: remove BOTH owned blocks precisely (remind + morning) and leave
|
|
10345
|
+
// every unmanaged crontab line byte-identical.
|
|
10346
|
+
const plan = process.platform === 'win32'
|
|
10347
|
+
? scheduler.planSchedulerBlocks({
|
|
10348
|
+
platform: 'win32',
|
|
10349
|
+
action: 'uninstall',
|
|
10350
|
+
dryRun: !apply,
|
|
10351
|
+
blocks: [{ taskName: scheduler.DEFAULT_TASK_NAME }, { taskName: scheduler.DEFAULT_MORNING_TASK_NAME }],
|
|
10352
|
+
})
|
|
10353
|
+
: scheduler.planSchedulerBlocks({
|
|
10354
|
+
platform: process.platform,
|
|
10355
|
+
action: 'uninstall',
|
|
10356
|
+
dryRun: !apply,
|
|
10357
|
+
markers: [scheduler.CRON_MARKER, scheduler.MORNING_CRON_MARKER],
|
|
10358
|
+
...(existing.ok ? { existingText: existing.text } : {}),
|
|
10359
|
+
})
|
|
8347
10360
|
await applySchedulerPlan(plan, { apply })
|
|
8348
10361
|
if (existsSync(dir)) rmSync(dir, { recursive: true, force: true })
|
|
8349
10362
|
store?.appendAudit({ actor: 'local', action: 'notify.uninstall', allowed: true, reason: dir })
|
|
@@ -8354,38 +10367,70 @@ async function remind(args) {
|
|
|
8354
10367
|
const dir = join(HOME, 'scheduler')
|
|
8355
10368
|
console.log('scheduler scripts: ' + (existsSync(dir) ? dir : 'not installed (optional)'))
|
|
8356
10369
|
console.log('reminder log: ' + join(HOME, 'reminders.log'))
|
|
8357
|
-
|
|
8358
|
-
|
|
8359
|
-
|
|
10370
|
+
// 0.4.0 status v2: two sections (remind + morning). A 0.3.2 flat file is
|
|
10371
|
+
// mapped into the remind section by the library, so old runs still show.
|
|
10372
|
+
const status = scheduler.readSchedulerStatusV2({ homeDir: HOME })
|
|
10373
|
+
const remindStatus = status.remind ?? {}
|
|
10374
|
+
if (!remindStatus.lastRun) console.log('last run: none recorded' + (status.corrupt ? ' (status.json corrupt)' : ''))
|
|
10375
|
+
else console.log('last run: ' + remindStatus.lastRun + ' · result=' + (remindStatus.lastResult ?? '-') + ' · count=' + (remindStatus.lastCount ?? '-') + ' · channel=' + (remindStatus.lastChannel ?? '-'))
|
|
10376
|
+
const morningStatus = status.morning ?? {}
|
|
10377
|
+
if (!morningStatus.lastRun) console.log('morning: none recorded')
|
|
10378
|
+
else console.log('morning: ' + morningStatus.lastRun + ' · result=' + (morningStatus.lastResult ?? '-') + ' · count=' + (morningStatus.lastCount ?? '-') + ' · path=' + (morningStatus.lastPath ?? '-'))
|
|
8360
10379
|
if (process.platform === 'win32') {
|
|
8361
10380
|
const plan = scheduler.planWindowsStatus({})
|
|
8362
10381
|
console.log('os plan: ' + plan.commands.map((entry) => entry.command + ' ' + entry.args.join(' ')).join('; ') + '(运行该命令;exit 0 表示已注册)')
|
|
10382
|
+
const morningPlan = scheduler.planWindowsStatus({ taskName: scheduler.DEFAULT_MORNING_TASK_NAME })
|
|
10383
|
+
console.log('os plan (morning): ' + morningPlan.commands.map((entry) => entry.command + ' ' + entry.args.join(' ')).join('; ') + '(运行该命令;exit 0 表示已注册)')
|
|
8363
10384
|
} else if (scheduler.CRON_PLATFORMS.includes(process.platform)) {
|
|
8364
10385
|
const existing = await readCrontabText()
|
|
8365
10386
|
if (existing.ok) {
|
|
8366
10387
|
const plan = scheduler.planCronStatus({ existingText: existing.text })
|
|
8367
10388
|
console.log(plan.installed ? 'os plan: installed (' + plan.schedule + ')' : 'os plan: not installed')
|
|
10389
|
+
const blocks = scheduler.planCronStatusBlocks({ existingText: existing.text, markers: [scheduler.CRON_MARKER, scheduler.MORNING_CRON_MARKER] })
|
|
10390
|
+
const morningEntry = blocks.entries.find((entry) => entry.marker === scheduler.MORNING_CRON_MARKER)
|
|
10391
|
+
console.log(morningEntry && morningEntry.installed ? 'os plan (morning): installed (' + morningEntry.schedule + ')' : 'os plan (morning): not installed')
|
|
8368
10392
|
} else {
|
|
8369
10393
|
console.log('os plan: unknown (' + (existing.error ?? 'crontab unavailable') + ')')
|
|
10394
|
+
console.log('os plan (morning): unknown (' + (existing.error ?? 'crontab unavailable') + ')')
|
|
8370
10395
|
}
|
|
8371
10396
|
} else {
|
|
8372
10397
|
console.log('os plan: unsupported platform ' + process.platform)
|
|
10398
|
+
console.log('os plan (morning): unsupported platform ' + process.platform)
|
|
8373
10399
|
}
|
|
8374
10400
|
return
|
|
8375
10401
|
}
|
|
8376
10402
|
const { buildReminders, toIcs } = await loadRemind()
|
|
10403
|
+
// 0.4.0: --now pins planning and the echoed instant, so a fixed run is
|
|
10404
|
+
// byte-reproducible (the same value is used by reminders/ICS/JSON/webhook).
|
|
10405
|
+
const nowInfo = parseRemindNow(flags)
|
|
10406
|
+
if (nowInfo.error) { usageFail(nowInfo.error, 'usage: advisers remind [--json] [--now ISO] [--ics [path]] [--deliver [--notify]] [--quiet-hours HH:MM-HH:MM] [--force-notify]'); return }
|
|
10407
|
+
if (flags['quiet-hours'] !== undefined) {
|
|
10408
|
+
const quiet = parseQuietHours(flags['quiet-hours'])
|
|
10409
|
+
if (quiet.error) { usageFail(quiet.error, 'usage: advisers remind [--json] [--now ISO] [--ics [path]] [--deliver [--notify]] [--quiet-hours HH:MM-HH:MM] [--force-notify]'); return }
|
|
10410
|
+
}
|
|
10411
|
+
const nowDate = nowInfo.date
|
|
8377
10412
|
// One prefix query instead of getMeta() per commitment (read-only store safe).
|
|
8378
10413
|
const snoozed = {}
|
|
8379
10414
|
for (const [key, value] of store?.listMetaByPrefix('snooze:') ?? []) snoozed[key.slice('snooze:'.length)] = value
|
|
8380
|
-
const reminders = buildReminders(plannerLedger(), { now:
|
|
10415
|
+
const reminders = buildReminders(plannerLedger(), { now: nowDate, snoozedUntil: snoozed })
|
|
8381
10416
|
if (flags.ics) {
|
|
8382
10417
|
const path = typeof flags.ics === 'string' ? flags.ics : (positional[0] || join(HOME, 'reminders.ics'))
|
|
8383
|
-
writeFileSync(path, toIcs(reminders, { now:
|
|
10418
|
+
writeFileSync(path, toIcs(reminders, { now: nowDate }), { mode: 0o600 })
|
|
8384
10419
|
store?.appendAudit({ actor: 'local', action: 'notify.ics', allowed: true, reason: basename(path) })
|
|
8385
10420
|
console.log('ics written: ' + path + ' (' + reminders.length + ' events)')
|
|
8386
10421
|
return
|
|
8387
10422
|
}
|
|
8388
|
-
if (flags.json) {
|
|
10423
|
+
if (flags.json) {
|
|
10424
|
+
// 0.4.0 additive read model: ok/command/timezone + per-row urgency. The old
|
|
10425
|
+
// now/reminders keys are unchanged and --json stays a pure read (it wins over
|
|
10426
|
+
// --deliver/--notify exactly as in 0.3.2).
|
|
10427
|
+
const { buildRemindPayload } = await loadUrgency()
|
|
10428
|
+
const records = new Map()
|
|
10429
|
+
for (const commitment of plannerLedger().listCommitments()) records.set(commitment.id, commitment)
|
|
10430
|
+
const payload = buildRemindPayload(reminders, { now: nowDate, timezone: AGENDA_TIMEZONE, records })
|
|
10431
|
+
console.log(JSON.stringify(payload, null, 2))
|
|
10432
|
+
return
|
|
10433
|
+
}
|
|
8389
10434
|
if (!reminders.length) {
|
|
8390
10435
|
console.log('现在没有到期的提醒。')
|
|
8391
10436
|
if (flags.deliver) recordReminderRun(scheduler, { count: 0, channel: 'log' })
|
|
@@ -8398,16 +10443,51 @@ async function remind(args) {
|
|
|
8398
10443
|
// control characters before appending; otherwise one entry could forge log
|
|
8399
10444
|
// lines in the user's reminder history.
|
|
8400
10445
|
const actions = reminders.map((r) => sanitizeConsoleText(r.action, { max: 2000 }))
|
|
8401
|
-
const line =
|
|
10446
|
+
const line = nowDate.toISOString() + '\t' + reminders.length + '\t' + actions.join(';') + '\n'
|
|
8402
10447
|
writeFileSync(join(HOME, 'reminders.log'), line, { flag: 'a', mode: 0o600 })
|
|
8403
10448
|
let channel = 'log'
|
|
8404
10449
|
if (flags.notify) {
|
|
8405
10450
|
const notify = await loadNotify()
|
|
8406
|
-
const
|
|
8407
|
-
|
|
8408
|
-
|
|
8409
|
-
|
|
8410
|
-
|
|
10451
|
+
const forceNotify = flags['force-notify'] === true
|
|
10452
|
+
const quietSpec = typeof flags['quiet-hours'] === 'string' ? flags['quiet-hours'] : (typeof process.env.ADVISERS_QUIET_HOURS === 'string' ? process.env.ADVISERS_QUIET_HOURS : null)
|
|
10453
|
+
if (!forceNotify && quietSpec && isInsideQuietHours(quietSpec, nowDate)) {
|
|
10454
|
+
// Quiet hours are a delivery policy, not an error: the log line above is
|
|
10455
|
+
// still written, the channel is recorded as suppressed and the audit row
|
|
10456
|
+
// records why. --force-notify bypasses (for an explicit one-off).
|
|
10457
|
+
channel = 'quiet-suppressed'
|
|
10458
|
+
console.log('通知已静默:当前处于安静时段 ' + quietSpec + '(本地日志已记录;--force-notify 可强制发送)')
|
|
10459
|
+
} else {
|
|
10460
|
+
const localDay = localDayOfInstant(nowDate)
|
|
10461
|
+
let notifyList = reminders
|
|
10462
|
+
if (!forceNotify && store && typeof store.listMetaByPrefix === 'function') {
|
|
10463
|
+
const seen = new Set(store.listMetaByPrefix('notify:dedupe:').keys())
|
|
10464
|
+
notifyList = reminders.filter((reminder) => !seen.has(reminderNotifyDedupeKey(reminder, localDay)))
|
|
10465
|
+
if (!notifyList.length) {
|
|
10466
|
+
channel = 'deduped'
|
|
10467
|
+
console.log('通知已去重:本批提醒今天已经通知过(本地日志仍记录;--force-notify 可重发)')
|
|
10468
|
+
}
|
|
10469
|
+
}
|
|
10470
|
+
if (channel !== 'deduped') {
|
|
10471
|
+
const local = await notify.sendNotification({ title: 'Advisers · 到期提醒', body: notifyList.length + ' 条承诺到期或即将到期' })
|
|
10472
|
+
channel = local.sent ? local.channel : 'log-only'
|
|
10473
|
+
const webhook = await notify.sendWebhookNotification(notifyList, { now: nowDate })
|
|
10474
|
+
if (webhook.sent) {
|
|
10475
|
+
channel = channel === 'log-only' ? 'webhook' : channel + '+webhook'
|
|
10476
|
+
// 0.4.0: remember whether the delivery was signed, without changing the
|
|
10477
|
+
// payload bytes. A configured webhook with no secret still sends but says
|
|
10478
|
+
// so exactly once per process (sanitised, no secret material).
|
|
10479
|
+
if (typeof webhook.signing === 'string' && webhook.signing !== '') channel += '+signing:' + webhook.signing
|
|
10480
|
+
if (webhook.warning === 'missing-secret' && !webhookSecretWarned) {
|
|
10481
|
+
webhookSecretWarned = true
|
|
10482
|
+
console.error(sanitizeConsoleText('webhook 已配置但未设置 ADVISERS_NOTIFY_WEBHOOK_SECRET:本次按未签名发送(signing=none);建议设置 secret,否则接收端无法验证请求来源。', { max: 2000 }))
|
|
10483
|
+
}
|
|
10484
|
+
} else if (webhook.configured) { console.error(sanitizeConsoleText('webhook 未发送:' + (webhook.error ?? 'unknown') + (webhook.detail ? '(' + webhook.detail + ')' : ''), { max: 2000 })) }
|
|
10485
|
+
if (store && typeof store.setMeta === 'function') {
|
|
10486
|
+
for (const reminder of notifyList) store.setMeta(reminderNotifyDedupeKey(reminder, localDay), nowDate.toISOString())
|
|
10487
|
+
pruneNotifyDedupe(store, nowDate)
|
|
10488
|
+
}
|
|
10489
|
+
}
|
|
10490
|
+
}
|
|
8411
10491
|
}
|
|
8412
10492
|
store?.appendAudit({ actor: 'local', action: 'notify.delivered', allowed: true, reason: reminders.length + ' reminders channel=' + channel })
|
|
8413
10493
|
recordReminderRun(scheduler, { count: reminders.length, channel })
|
|
@@ -8441,7 +10521,15 @@ async function readCrontabText() {
|
|
|
8441
10521
|
/** Record a successful delivery run in ~/.advisers/scheduler/status.json. */
|
|
8442
10522
|
function recordReminderRun(scheduler, { count, channel }) {
|
|
8443
10523
|
try {
|
|
8444
|
-
|
|
10524
|
+
// 0.4.0: once a v2 status document exists (a morning --archive run writes
|
|
10525
|
+
// the morning section), keep writing v2 so the other section survives. A
|
|
10526
|
+
// fresh home keeps the 0.3.2 flat v1 layout for byte-compatible readers.
|
|
10527
|
+
const current = scheduler.readSchedulerStatusV2({ homeDir: HOME })
|
|
10528
|
+
if (current.exists && current.legacy !== true && current.corrupt !== true) {
|
|
10529
|
+
scheduler.recordSchedulerRunV2({ homeDir: HOME, at: new Date(), section: 'remind', result: 'ok', count, channel, dryRun: false })
|
|
10530
|
+
} else {
|
|
10531
|
+
scheduler.recordSchedulerRun({ homeDir: HOME, at: new Date(), result: 'ok', count, channel, dryRun: false })
|
|
10532
|
+
}
|
|
8445
10533
|
} catch (error) {
|
|
8446
10534
|
console.error('scheduler status not recorded: ' + error.message)
|
|
8447
10535
|
}
|
|
@@ -9242,6 +11330,57 @@ async function normalizeEvidenceSources(result) {
|
|
|
9242
11330
|
return result
|
|
9243
11331
|
}
|
|
9244
11332
|
|
|
11333
|
+
/**
|
|
11334
|
+
* Typed evidence lookups injected into lib/evidence.js: the mail body table and
|
|
11335
|
+
* the KB chunk/page tables. The library treats a missing lookup as honest
|
|
11336
|
+
* not_checked/unverifiable (never missing), so a read-only command still works.
|
|
11337
|
+
*/
|
|
11338
|
+
async function buildEvidenceLookups(store) {
|
|
11339
|
+
if (!store || typeof store.db?.prepare !== 'function') return undefined
|
|
11340
|
+
const lookups = {}
|
|
11341
|
+
try {
|
|
11342
|
+
const mailStore = await loadMailStore()
|
|
11343
|
+
lookups.mail = (selector) => {
|
|
11344
|
+
const ref = selector?.messageId ?? selector?.ref
|
|
11345
|
+
if (typeof ref !== 'string' || !ref) return null
|
|
11346
|
+
try { return mailStore.getMailMessage(store, ref, { includeBody: true }) } catch { return null }
|
|
11347
|
+
}
|
|
11348
|
+
} catch {}
|
|
11349
|
+
lookups.kbChunk = (selector) => {
|
|
11350
|
+
try {
|
|
11351
|
+
if (typeof selector?.chunkId === 'string' && selector.chunkId) return store.db.prepare('SELECT * FROM kb_chunks WHERE id = ?').get(selector.chunkId) ?? null
|
|
11352
|
+
if (typeof selector?.docId === 'string' && selector.docId && Number.isInteger(selector.chunkIndex)) {
|
|
11353
|
+
return store.db.prepare('SELECT * FROM kb_chunks WHERE doc_id = ? AND seq = ?').get(selector.docId, selector.chunkIndex) ?? null
|
|
11354
|
+
}
|
|
11355
|
+
return null
|
|
11356
|
+
} catch { return null }
|
|
11357
|
+
}
|
|
11358
|
+
lookups.kbPage = (selector) => {
|
|
11359
|
+
try {
|
|
11360
|
+
const id = typeof selector?.pageId === 'string' && selector.pageId
|
|
11361
|
+
? selector.pageId
|
|
11362
|
+
: typeof selector?.docId === 'string' && selector.docId
|
|
11363
|
+
? selector.docId
|
|
11364
|
+
: typeof selector?.ref === 'string' ? selector.ref.replace(/^kb_page:/i, '') : ''
|
|
11365
|
+
if (!id) return null
|
|
11366
|
+
return store.db.prepare('SELECT * FROM kb_pages WHERE id = ? AND deleted_at IS NULL').get(id) ?? null
|
|
11367
|
+
} catch { return null }
|
|
11368
|
+
}
|
|
11369
|
+
return lookups
|
|
11370
|
+
}
|
|
11371
|
+
|
|
11372
|
+
/** One human line for a verified evidence entry, rendered by its source type. */
|
|
11373
|
+
function verifiedEvidenceLine(entry) {
|
|
11374
|
+
const quote = String(entry?.quote ?? '').slice(0, 120)
|
|
11375
|
+
const type = String(entry?.type ?? 'unknown')
|
|
11376
|
+
if (type === 'conversation') return ' ' + String(entry.sessionId ?? '') + '#' + String(entry.turnId ?? '') + ' 「' + quote + '」'
|
|
11377
|
+
if (type === 'mail') return ' mail ' + String(entry.messageId ?? entry.ref ?? '') + ' 「' + quote + '」' + (entry.subject ? ' ' + String(entry.subject).slice(0, 80) : '')
|
|
11378
|
+
if (type === 'kb_chunk') return ' kb_chunk ' + String(entry.docId ?? '') + (entry.chunkIndex !== undefined ? '#' + entry.chunkIndex : '') + ' 「' + quote + '」'
|
|
11379
|
+
if (type === 'kb_page') return ' kb_page ' + String(entry.pageId ?? '') + ' 「' + quote + '」'
|
|
11380
|
+
if (type === 'ledger') return ' ledger ' + String(entry.ref ?? '') + ' 「' + quote + '」'
|
|
11381
|
+
return ' ' + type + (entry.ref ? ' ' + String(entry.ref) : '') + ' 「' + quote + '」'
|
|
11382
|
+
}
|
|
11383
|
+
|
|
9245
11384
|
async function printEvidence(args) {
|
|
9246
11385
|
const { flags, positional } = parseFlags(args)
|
|
9247
11386
|
// Offline receipt-pack verification: reads only the given directory. It runs
|
|
@@ -9249,6 +11388,23 @@ async function printEvidence(args) {
|
|
|
9249
11388
|
if (positional[0] === 'verify') {
|
|
9250
11389
|
const dir = positional[1] ?? (typeof flags.dir === 'string' ? flags.dir : undefined)
|
|
9251
11390
|
if (!dir) { console.error('usage: advisers evidence verify <dir>'); process.exitCode = 1; return }
|
|
11391
|
+
// 0.4.0: dispatch by manifest.format. A client status pack is verified by
|
|
11392
|
+
// the client-pack verifier (its own limits/semantics); everything else stays
|
|
11393
|
+
// on the frozen receipt verifier.
|
|
11394
|
+
try {
|
|
11395
|
+
const clientPack = await loadClientPack()
|
|
11396
|
+
const header = clientPack.readClientPackManifestHeader(dir)
|
|
11397
|
+
if (header.ok && header.format === clientPack.CLIENT_PACK_MANIFEST_FORMAT) {
|
|
11398
|
+
const result = clientPack.verifyClientStatusPackDir(dir)
|
|
11399
|
+
console.log(JSON.stringify(result, null, 2))
|
|
11400
|
+
if (result.code === clientPack.CLIENT_PACK_LIMIT_CODE) {
|
|
11401
|
+
const violation = result.limitViolation ?? {}
|
|
11402
|
+
console.error(sanitizeConsoleText(clientPack.CLIENT_PACK_LIMIT_CODE + ': client status pack ' + (violation.limit ?? 'limit') + ' exceeded ' + (violation.max ?? '?') + ' (actual ' + (violation.actual ?? '?') + '); refusing to verify a pack that could exhaust memory or time.', { max: 2000 }))
|
|
11403
|
+
}
|
|
11404
|
+
process.exitCode = result.ok ? 0 : 1
|
|
11405
|
+
return
|
|
11406
|
+
}
|
|
11407
|
+
} catch {}
|
|
9252
11408
|
const { verifyReceiptPackDir, RECEIPT_LIMIT_CODE } = await loadReceiptVerify()
|
|
9253
11409
|
// The verifier caps entries/depth/file size/total size/SHA256SUMS/manifest
|
|
9254
11410
|
// for an untrusted pack (lib/receipt-verify.js). A pack that trips a cap is
|
|
@@ -9272,31 +11428,40 @@ async function printEvidence(args) {
|
|
|
9272
11428
|
if (!id) { console.error('usage: advisers evidence show <id> [--json]'); process.exitCode = 1; return }
|
|
9273
11429
|
const ledger = readLedgerForCommand(id.startsWith('fact_') ? { facts: {} } : id.startsWith('pref_') ? { preferences: {} } : { commitments: {} })
|
|
9274
11430
|
let result
|
|
11431
|
+
const lookups = await buildEvidenceLookups(store)
|
|
9275
11432
|
try {
|
|
9276
11433
|
const { evidenceForCommitment, evidenceForFact, evidenceForPreference } = await loadEvidence()
|
|
9277
|
-
if (id.startsWith('cm_')) result = evidenceForCommitment(store, ledger, id)
|
|
9278
|
-
else if (id.startsWith('fact_')) result = evidenceForFact(store, ledger, id)
|
|
9279
|
-
else if (id.startsWith('pref_')) result = evidenceForPreference(store, ledger, id)
|
|
11434
|
+
if (id.startsWith('cm_')) result = evidenceForCommitment(store, ledger, id, undefined, { lookup: lookups })
|
|
11435
|
+
else if (id.startsWith('fact_')) result = evidenceForFact(store, ledger, id, undefined, { lookup: lookups })
|
|
11436
|
+
else if (id.startsWith('pref_')) result = evidenceForPreference(store, ledger, id, undefined, { lookup: lookups })
|
|
9280
11437
|
else { console.error('unknown evidence id prefix (want cm_/fact_/pref_)'); process.exitCode = 1; return }
|
|
9281
11438
|
} catch (error) { console.error(error.message); process.exitCode = 1; return }
|
|
9282
11439
|
if (!result || (!result.commitment && !result.fact && !result.preference)) { console.error(`not found: ${id}`); process.exitCode = 1; return }
|
|
9283
11440
|
await normalizeEvidenceSources(result)
|
|
9284
11441
|
const unverifiable = Array.isArray(result.unverifiable) ? result.unverifiable : []
|
|
11442
|
+
const notChecked = Array.isArray(result.notChecked) ? result.notChecked : []
|
|
9285
11443
|
const manualSources = unverifiable.filter((item) => item && (item.kind === 'manual' || item.type === 'manual'))
|
|
11444
|
+
// 0.4.0: prefer the resolver summary (four-state byKind, notCheckedCount,
|
|
11445
|
+
// verificationBasis); fall back to the 0.3.2 tally for legacy result objects.
|
|
9286
11446
|
const summary = {
|
|
9287
|
-
byKind: { observed: result.sources.length, manual: manualSources.length },
|
|
11447
|
+
byKind: result.byKind && typeof result.byKind === 'object' ? result.byKind : { observed: result.sources.length, manual: manualSources.length },
|
|
9288
11448
|
missing: result.missing.length,
|
|
9289
11449
|
unverifiable: unverifiable.length,
|
|
9290
11450
|
operatorEntered: manualSources.length,
|
|
11451
|
+
notCheckedCount: Number.isInteger(result.notCheckedCount) ? result.notCheckedCount : notChecked.length,
|
|
11452
|
+
verificationBasis: typeof result.verificationBasis === 'string' ? result.verificationBasis : 'build-time',
|
|
9291
11453
|
}
|
|
9292
11454
|
if (flags.json) { console.log(JSON.stringify(Object.assign({}, result, { summary: summary }), null, 2)); return }
|
|
9293
11455
|
const label = result.commitment ? `${result.commitment.action}` : result.fact ? `${result.fact.subject} ${result.fact.predicate}` : result.preference?.statement
|
|
9294
11456
|
console.log(`${id} ${label ?? ''}`)
|
|
9295
|
-
if (!result.sources.length && !unverifiable.length) console.log(' (没有可回溯来源)')
|
|
9296
|
-
for (const s of result.sources) console.log(
|
|
11457
|
+
if (!result.sources.length && !unverifiable.length && !notChecked.length) console.log(' (没有可回溯来源)')
|
|
11458
|
+
for (const s of result.sources) console.log(verifiedEvidenceLine(s))
|
|
9297
11459
|
for (const m of result.missing) console.log(` MISSING ${m.reason}${m.ref ? ` ${m.ref}` : ''}`)
|
|
11460
|
+
for (const item of notChecked) console.log(` NOT CHECKED ${String(item.type ?? 'unknown')} ${String(item.reason ?? 'not_checked')}${item.ref ? ' ' + String(item.ref) : ''}`)
|
|
9298
11461
|
for (const item of unverifiable) console.log(` MANUAL 操作者录入(未外部核验,不是缺失) 「${(item.quote ?? '').slice(0, 120)}」 sha256:${String(item.quoteSha256 ?? '').slice(0, 16)}`)
|
|
9299
11462
|
if (unverifiable.length) console.log(' 说明:manual/operator-entered 证据由用户手工录入;本地无法外部核验,不计入 missing。')
|
|
11463
|
+
if (notChecked.length) console.log(' 说明:not-checked 指本地没有对应的类型化查找能力/记录(如邮件正文未留存);它既不是 resolved,也不是 missing。')
|
|
11464
|
+
console.log(' 校验口径:' + summary.verificationBasis + '——本地解析只证明构建时状态,不代表第三方审计或不可伪造。')
|
|
9300
11465
|
}
|
|
9301
11466
|
|
|
9302
11467
|
/**
|
|
@@ -9343,6 +11508,7 @@ async function evidencePack(args) {
|
|
|
9343
11508
|
preferences: ledger.listPreferences({ includeCandidates: false }).map((p) => p.id),
|
|
9344
11509
|
}
|
|
9345
11510
|
const { buildEvidencePack, toDocxRows, verifyPack, EvidencePackLimitError } = await loadEvidence()
|
|
11511
|
+
const lookups = await buildEvidenceLookups(store)
|
|
9346
11512
|
let pack
|
|
9347
11513
|
try {
|
|
9348
11514
|
// Performance audit P1-1: --all was parsed but never forwarded, so the
|
|
@@ -9357,6 +11523,7 @@ async function evidencePack(args) {
|
|
|
9357
11523
|
all: flags.all === true,
|
|
9358
11524
|
clearance: 0,
|
|
9359
11525
|
protectedPolicy: ids ? 'error' : 'exclude',
|
|
11526
|
+
lookups,
|
|
9360
11527
|
})
|
|
9361
11528
|
} catch (error) {
|
|
9362
11529
|
if (error instanceof EvidencePackLimitError || error?.code === 'EVIDENCE_PACK_TOO_LARGE') {
|
|
@@ -9776,6 +11943,7 @@ async function receiptPack(args) {
|
|
|
9776
11943
|
if (skippedFiles.length) console.error('注意:' + skippedFiles.length + ' 个交付文件缺失,已跳过(回执只覆盖仍存在的文件)。')
|
|
9777
11944
|
const verifyResults = await verifyDeliveryArtifacts(deliveries.flatMap((delivery) => delivery.files))
|
|
9778
11945
|
const { buildEvidencePack, buildReceiptPack, EvidencePackLimitError } = await loadEvidence()
|
|
11946
|
+
const lookups = await buildEvidenceLookups(store)
|
|
9779
11947
|
let evidence
|
|
9780
11948
|
let evidenceGlobalExcluded = 0
|
|
9781
11949
|
let evidenceClientDefaultExcluded = 0
|
|
@@ -9790,6 +11958,7 @@ async function receiptPack(args) {
|
|
|
9790
11958
|
all: flags.all === true,
|
|
9791
11959
|
clearance: 0,
|
|
9792
11960
|
protectedPolicy: 'error',
|
|
11961
|
+
lookups,
|
|
9793
11962
|
})
|
|
9794
11963
|
} else {
|
|
9795
11964
|
// A-1 (0.2.5) + 0.3.2: per-item clearance is max(client default, matter
|
|
@@ -9819,6 +11988,7 @@ async function receiptPack(args) {
|
|
|
9819
11988
|
// Explicit --ids fail closed (A-1); the bulk path excludes protected
|
|
9820
11989
|
// rows and reports them through evidence.protectedExcluded.
|
|
9821
11990
|
protectedPolicy: ids ? 'error' : 'exclude',
|
|
11991
|
+
lookups,
|
|
9822
11992
|
})
|
|
9823
11993
|
}
|
|
9824
11994
|
} catch (error) {
|
|
@@ -10434,6 +12604,9 @@ const KNOWN_COMMANDS = new Set([
|
|
|
10434
12604
|
'forget', 'sync', 'vault', 'export', 'import', 'backup', 'backups', 'restore', 'brief', 'review', 'research', 'capture', 'policy',
|
|
10435
12605
|
'office-edit', 'office-read', 'verify', 'office', 'routine', 'template', 'link', 'bridge', 'soul', 'tos',
|
|
10436
12606
|
'matter', 'agenda', 'morning',
|
|
12607
|
+
// 0.4.0: KB / mail / money / consent commands are gated like every other
|
|
12608
|
+
// command (unknown names keep the plain error instead of the gate).
|
|
12609
|
+
'kb', 'fact', 'mail', 'receivable', 'payment', 'consent',
|
|
10437
12610
|
// 0.3.0 customer entities: reads and writes both go through the L1/TOS gate
|
|
10438
12611
|
// (they touch the local ledger); there is no exempt customer command.
|
|
10439
12612
|
'client', 'project',
|
|
@@ -10749,8 +12922,22 @@ async function tosCommand(argv) {
|
|
|
10749
12922
|
await tosGate()
|
|
10750
12923
|
|
|
10751
12924
|
if (!command) {
|
|
10752
|
-
|
|
10753
|
-
|
|
12925
|
+
// 0.4.0: a TTY with no command enters the readline shell (lib/shell.js);
|
|
12926
|
+
// stdin not a TTY keeps the frozen 0.3.x "print help, exit 0" path.
|
|
12927
|
+
if (process.stdin.isTTY) {
|
|
12928
|
+
const shellResult = await runShellEntry()
|
|
12929
|
+
if (shellResult.entered) {
|
|
12930
|
+
process.exitCode = shellResult.exitCode
|
|
12931
|
+
} else if (shellResult.reason === 'json-unsupported') {
|
|
12932
|
+
console.error('advisers: E_USAGE: --json is not supported by the interactive shell; use `advisers tui --once --json` or a CLI command with --json.')
|
|
12933
|
+
process.exitCode = 1
|
|
12934
|
+
} else {
|
|
12935
|
+
// ADVISERS_NO_SHELL=1 (or an unusable stream pair) keeps the old REPL.
|
|
12936
|
+
await repl()
|
|
12937
|
+
}
|
|
12938
|
+
} else {
|
|
12939
|
+
help()
|
|
12940
|
+
}
|
|
10754
12941
|
} else if (command === 'version' || command === '--version' || command === '-v') {
|
|
10755
12942
|
console.log(VERSION)
|
|
10756
12943
|
} else if (command === 'help' || command === '--help') {
|
|
@@ -11014,13 +13201,18 @@ if (!command) {
|
|
|
11014
13201
|
else { store.upsertSessionSummary({ conversationId, summary: old.summary, throughSeq: old.throughSeq, pins: old.pins }); console.log(`restored summary v${version}`) }
|
|
11015
13202
|
} else { console.error('usage: advisers compact ls|rollback <version>'); process.exitCode = 1 }
|
|
11016
13203
|
} else if (command === 'search') {
|
|
11017
|
-
|
|
11018
|
-
|
|
13204
|
+
// 0.4.0 additive routing: --scope turns|kb|pages|facts|all. Without --scope
|
|
13205
|
+
// the 0.3.2 bytes are unchanged (turn search, human lines).
|
|
13206
|
+
if (args.includes('--scope')) await scopedSearch(args)
|
|
11019
13207
|
else {
|
|
11020
|
-
|
|
11021
|
-
|
|
11022
|
-
|
|
11023
|
-
|
|
13208
|
+
const q = args.join(' ').trim()
|
|
13209
|
+
if (!q) { console.error('usage: advisers search <text>'); process.exitCode = 1 }
|
|
13210
|
+
else {
|
|
13211
|
+
// 0.2.3: turn search is a pure read (lock-free; reads the WAL snapshot).
|
|
13212
|
+
const rows = readStoreOrExit()?.searchTurns(q, { limit: 10 }) ?? []
|
|
13213
|
+
if (!rows.length) console.log('没有匹配')
|
|
13214
|
+
for (const r of rows) console.log(`${r.seq}\t${r.role}\t${r.content.replace(/\s+/g, ' ').slice(0, 160)}`)
|
|
13215
|
+
}
|
|
11024
13216
|
}
|
|
11025
13217
|
} else if (command === 'nudge') {
|
|
11026
13218
|
const sub = args[0]
|
|
@@ -11135,7 +13327,10 @@ if (!command) {
|
|
|
11135
13327
|
} else if (candidate.kind === 'commitment') {
|
|
11136
13328
|
const input = {
|
|
11137
13329
|
...candidate.payload,
|
|
11138
|
-
|
|
13330
|
+
// Mail/KB candidates may arrive before any matter exists; a
|
|
13331
|
+
// commitment must always point at a real matter (SQLite binds
|
|
13332
|
+
// undefined as an error, and the ledger tolerates no dangling).
|
|
13333
|
+
matterId: candidate.payload.matterId ?? s.firstActiveMatter?.()?.id ?? resolveDeliveryMatterId(s),
|
|
11139
13334
|
evidence: candidate.evidence.map(commitmentEvidence),
|
|
11140
13335
|
}
|
|
11141
13336
|
s.insertCommitment(core.createCommitment(opsPorts, input))
|
|
@@ -11172,13 +13367,25 @@ if (!command) {
|
|
|
11172
13367
|
} else if (command === 'matter') {
|
|
11173
13368
|
await matterCommand(args)
|
|
11174
13369
|
} else if (command === 'client') {
|
|
11175
|
-
clientCommand(args)
|
|
13370
|
+
await clientCommand(args)
|
|
11176
13371
|
} else if (command === 'project') {
|
|
11177
13372
|
projectCommand(args)
|
|
11178
13373
|
} else if (command === 'agenda') {
|
|
11179
13374
|
await agendaCommand(args)
|
|
11180
13375
|
} else if (command === 'morning') {
|
|
11181
13376
|
await morningReportCommand(args)
|
|
13377
|
+
} else if (command === 'kb') {
|
|
13378
|
+
await kbCommand(args)
|
|
13379
|
+
} else if (command === 'fact') {
|
|
13380
|
+
await factCommand(args)
|
|
13381
|
+
} else if (command === 'mail') {
|
|
13382
|
+
await mailCommand(args)
|
|
13383
|
+
} else if (command === 'receivable') {
|
|
13384
|
+
await receivableCommand(args)
|
|
13385
|
+
} else if (command === 'payment') {
|
|
13386
|
+
await paymentCommand(args)
|
|
13387
|
+
} else if (command === 'consent') {
|
|
13388
|
+
await consentCommand(args)
|
|
11182
13389
|
} else if (command === 'digest') {
|
|
11183
13390
|
if (args[0] === 'morning') await morningReportCommand(args.slice(1))
|
|
11184
13391
|
else {
|