@carloswon/cairn-memory 0.0.0-stage → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +81 -0
- package/LICENSE +21 -0
- package/README.md +158 -2
- package/dist/src/agents/adapters.d.ts +82 -0
- package/dist/src/agents/adapters.js +209 -0
- package/dist/src/agents/adapters.js.map +1 -0
- package/dist/src/agents/config.d.ts +82 -0
- package/dist/src/agents/config.js +603 -0
- package/dist/src/agents/config.js.map +1 -0
- package/dist/src/agents/cordisPatch.d.ts +89 -0
- package/dist/src/agents/cordisPatch.js +201 -0
- package/dist/src/agents/cordisPatch.js.map +1 -0
- package/dist/src/agents/index.d.ts +2 -0
- package/dist/src/agents/index.js +3 -0
- package/dist/src/agents/index.js.map +1 -0
- package/dist/src/core/errors.d.ts +36 -0
- package/dist/src/core/errors.js +74 -0
- package/dist/src/core/errors.js.map +1 -0
- package/dist/src/core/hash.d.ts +14 -0
- package/dist/src/core/hash.js +48 -0
- package/dist/src/core/hash.js.map +1 -0
- package/dist/src/core/ids.d.ts +10 -0
- package/dist/src/core/ids.js +41 -0
- package/dist/src/core/ids.js.map +1 -0
- package/dist/src/core/index.d.ts +6 -0
- package/dist/src/core/index.js +7 -0
- package/dist/src/core/index.js.map +1 -0
- package/dist/src/core/scope.d.ts +78 -0
- package/dist/src/core/scope.js +181 -0
- package/dist/src/core/scope.js.map +1 -0
- package/dist/src/core/secrets.d.ts +13 -0
- package/dist/src/core/secrets.js +122 -0
- package/dist/src/core/secrets.js.map +1 -0
- package/dist/src/core/time.d.ts +7 -0
- package/dist/src/core/time.js +18 -0
- package/dist/src/core/time.js.map +1 -0
- package/dist/src/core/types.d.ts +139 -0
- package/dist/src/core/types.js +30 -0
- package/dist/src/core/types.js.map +1 -0
- package/dist/src/governance/apply.d.ts +64 -0
- package/dist/src/governance/apply.js +160 -0
- package/dist/src/governance/apply.js.map +1 -0
- package/dist/src/governance/archive.d.ts +29 -0
- package/dist/src/governance/archive.js +52 -0
- package/dist/src/governance/archive.js.map +1 -0
- package/dist/src/governance/dedup.d.ts +21 -0
- package/dist/src/governance/dedup.js +23 -0
- package/dist/src/governance/dedup.js.map +1 -0
- package/dist/src/governance/index.d.ts +16 -0
- package/dist/src/governance/index.js +17 -0
- package/dist/src/governance/index.js.map +1 -0
- package/dist/src/governance/propose.d.ts +78 -0
- package/dist/src/governance/propose.js +150 -0
- package/dist/src/governance/propose.js.map +1 -0
- package/dist/src/index.d.ts +15 -0
- package/dist/src/index.js +24 -0
- package/dist/src/index.js.map +1 -0
- package/dist/src/interfaces/app-service.d.ts +292 -0
- package/dist/src/interfaces/app-service.js +743 -0
- package/dist/src/interfaces/app-service.js.map +1 -0
- package/dist/src/interfaces/cli/main.d.ts +2 -0
- package/dist/src/interfaces/cli/main.js +854 -0
- package/dist/src/interfaces/cli/main.js.map +1 -0
- package/dist/src/interfaces/console/assets/page.d.ts +18 -0
- package/dist/src/interfaces/console/assets/page.js +39 -0
- package/dist/src/interfaces/console/assets/page.js.map +1 -0
- package/dist/src/interfaces/console/assets/ui-css.d.ts +11 -0
- package/dist/src/interfaces/console/assets/ui-css.js +119 -0
- package/dist/src/interfaces/console/assets/ui-css.js.map +1 -0
- package/dist/src/interfaces/console/assets/ui-js.d.ts +14 -0
- package/dist/src/interfaces/console/assets/ui-js.js +1098 -0
- package/dist/src/interfaces/console/assets/ui-js.js.map +1 -0
- package/dist/src/interfaces/console/assets/url-state.d.ts +9 -0
- package/dist/src/interfaces/console/assets/url-state.js +45 -0
- package/dist/src/interfaces/console/assets/url-state.js.map +1 -0
- package/dist/src/interfaces/console/export.d.ts +46 -0
- package/dist/src/interfaces/console/export.js +84 -0
- package/dist/src/interfaces/console/export.js.map +1 -0
- package/dist/src/interfaces/console/model.d.ts +372 -0
- package/dist/src/interfaces/console/model.js +731 -0
- package/dist/src/interfaces/console/model.js.map +1 -0
- package/dist/src/interfaces/console/review-store.d.ts +142 -0
- package/dist/src/interfaces/console/review-store.js +342 -0
- package/dist/src/interfaces/console/review-store.js.map +1 -0
- package/dist/src/interfaces/console/security.d.ts +76 -0
- package/dist/src/interfaces/console/security.js +105 -0
- package/dist/src/interfaces/console/security.js.map +1 -0
- package/dist/src/interfaces/console/server.d.ts +45 -0
- package/dist/src/interfaces/console/server.js +476 -0
- package/dist/src/interfaces/console/server.js.map +1 -0
- package/dist/src/interfaces/console/suggestions.d.ts +112 -0
- package/dist/src/interfaces/console/suggestions.js +511 -0
- package/dist/src/interfaces/console/suggestions.js.map +1 -0
- package/dist/src/interfaces/console/text.d.ts +4 -0
- package/dist/src/interfaces/console/text.js +18 -0
- package/dist/src/interfaces/console/text.js.map +1 -0
- package/dist/src/interfaces/mcp/server.d.ts +4 -0
- package/dist/src/interfaces/mcp/server.js +480 -0
- package/dist/src/interfaces/mcp/server.js.map +1 -0
- package/dist/src/jobs/index.d.ts +6 -0
- package/dist/src/jobs/index.js +7 -0
- package/dist/src/jobs/index.js.map +1 -0
- package/dist/src/jobs/remote.d.ts +42 -0
- package/dist/src/jobs/remote.js +34 -0
- package/dist/src/jobs/remote.js.map +1 -0
- package/dist/src/jobs/worker.d.ts +67 -0
- package/dist/src/jobs/worker.js +169 -0
- package/dist/src/jobs/worker.js.map +1 -0
- package/dist/src/onboarding/auto.d.ts +88 -0
- package/dist/src/onboarding/auto.js +399 -0
- package/dist/src/onboarding/auto.js.map +1 -0
- package/dist/src/onboarding/batches.d.ts +103 -0
- package/dist/src/onboarding/batches.js +219 -0
- package/dist/src/onboarding/batches.js.map +1 -0
- package/dist/src/onboarding/discover.d.ts +54 -0
- package/dist/src/onboarding/discover.js +369 -0
- package/dist/src/onboarding/discover.js.map +1 -0
- package/dist/src/onboarding/import.d.ts +69 -0
- package/dist/src/onboarding/import.js +279 -0
- package/dist/src/onboarding/import.js.map +1 -0
- package/dist/src/onboarding/index.d.ts +24 -0
- package/dist/src/onboarding/index.js +22 -0
- package/dist/src/onboarding/index.js.map +1 -0
- package/dist/src/onboarding/judgement.d.ts +50 -0
- package/dist/src/onboarding/judgement.js +121 -0
- package/dist/src/onboarding/judgement.js.map +1 -0
- package/dist/src/onboarding/policy.d.ts +86 -0
- package/dist/src/onboarding/policy.js +249 -0
- package/dist/src/onboarding/policy.js.map +1 -0
- package/dist/src/projection/brief.d.ts +112 -0
- package/dist/src/projection/brief.js +200 -0
- package/dist/src/projection/brief.js.map +1 -0
- package/dist/src/projection/index.d.ts +1 -0
- package/dist/src/projection/index.js +2 -0
- package/dist/src/projection/index.js.map +1 -0
- package/dist/src/projection/markdown.d.ts +82 -0
- package/dist/src/projection/markdown.js +313 -0
- package/dist/src/projection/markdown.js.map +1 -0
- package/dist/src/retrieval/export.d.ts +80 -0
- package/dist/src/retrieval/export.js +215 -0
- package/dist/src/retrieval/export.js.map +1 -0
- package/dist/src/retrieval/index.d.ts +5 -0
- package/dist/src/retrieval/index.js +6 -0
- package/dist/src/retrieval/index.js.map +1 -0
- package/dist/src/retrieval/search.d.ts +37 -0
- package/dist/src/retrieval/search.js +294 -0
- package/dist/src/retrieval/search.js.map +1 -0
- package/dist/src/store/archives.d.ts +94 -0
- package/dist/src/store/archives.js +135 -0
- package/dist/src/store/archives.js.map +1 -0
- package/dist/src/store/audit.d.ts +57 -0
- package/dist/src/store/audit.js +131 -0
- package/dist/src/store/audit.js.map +1 -0
- package/dist/src/store/backup.d.ts +36 -0
- package/dist/src/store/backup.js +90 -0
- package/dist/src/store/backup.js.map +1 -0
- package/dist/src/store/blocks.d.ts +64 -0
- package/dist/src/store/blocks.js +104 -0
- package/dist/src/store/blocks.js.map +1 -0
- package/dist/src/store/conflicts.d.ts +52 -0
- package/dist/src/store/conflicts.js +112 -0
- package/dist/src/store/conflicts.js.map +1 -0
- package/dist/src/store/db.d.ts +44 -0
- package/dist/src/store/db.js +162 -0
- package/dist/src/store/db.js.map +1 -0
- package/dist/src/store/device.d.ts +46 -0
- package/dist/src/store/device.js +111 -0
- package/dist/src/store/device.js.map +1 -0
- package/dist/src/store/index.d.ts +14 -0
- package/dist/src/store/index.js +15 -0
- package/dist/src/store/index.js.map +1 -0
- package/dist/src/store/memories.d.ts +133 -0
- package/dist/src/store/memories.js +442 -0
- package/dist/src/store/memories.js.map +1 -0
- package/dist/src/store/migrate.d.ts +32 -0
- package/dist/src/store/migrate.js +87 -0
- package/dist/src/store/migrate.js.map +1 -0
- package/dist/src/store/open.d.ts +53 -0
- package/dist/src/store/open.js +203 -0
- package/dist/src/store/open.js.map +1 -0
- package/dist/src/store/outbox.d.ts +65 -0
- package/dist/src/store/outbox.js +137 -0
- package/dist/src/store/outbox.js.map +1 -0
- package/dist/src/store/plans.d.ts +137 -0
- package/dist/src/store/plans.js +243 -0
- package/dist/src/store/plans.js.map +1 -0
- package/dist/src/store/schema.d.ts +46 -0
- package/dist/src/store/schema.js +544 -0
- package/dist/src/store/schema.js.map +1 -0
- package/dist/src/store/scopes.d.ts +44 -0
- package/dist/src/store/scopes.js +220 -0
- package/dist/src/store/scopes.js.map +1 -0
- package/dist/src/store/write-guard.d.ts +10 -0
- package/dist/src/store/write-guard.js +10 -0
- package/dist/src/store/write-guard.js.map +1 -0
- package/dist/src/sync/apply.d.ts +24 -0
- package/dist/src/sync/apply.js +130 -0
- package/dist/src/sync/apply.js.map +1 -0
- package/dist/src/sync/cryptoutil.d.ts +86 -0
- package/dist/src/sync/cryptoutil.js +339 -0
- package/dist/src/sync/cryptoutil.js.map +1 -0
- package/dist/src/sync/events.d.ts +69 -0
- package/dist/src/sync/events.js +78 -0
- package/dist/src/sync/events.js.map +1 -0
- package/dist/src/sync/obs-store.d.ts +41 -0
- package/dist/src/sync/obs-store.js +325 -0
- package/dist/src/sync/obs-store.js.map +1 -0
- package/dist/src/sync/orchestrate.d.ts +37 -0
- package/dist/src/sync/orchestrate.js +84 -0
- package/dist/src/sync/orchestrate.js.map +1 -0
- package/dist/src/sync/pull.d.ts +24 -0
- package/dist/src/sync/pull.js +150 -0
- package/dist/src/sync/pull.js.map +1 -0
- package/dist/src/sync/push.d.ts +19 -0
- package/dist/src/sync/push.js +227 -0
- package/dist/src/sync/push.js.map +1 -0
- package/dist/src/sync/syncd-store.d.ts +31 -0
- package/dist/src/sync/syncd-store.js +92 -0
- package/dist/src/sync/syncd-store.js.map +1 -0
- package/dist/src/sync/vault.d.ts +37 -0
- package/dist/src/sync/vault.js +53 -0
- package/dist/src/sync/vault.js.map +1 -0
- package/docs/cairn-security.md +267 -0
- package/docs/cairn-usage.md +919 -0
- package/package.json +71 -4
|
@@ -0,0 +1,743 @@
|
|
|
1
|
+
import { openStore, } from '../store/index.js';
|
|
2
|
+
import { schemaVersion } from '../store/migrate.js';
|
|
3
|
+
import { MEMORY_KINDS, } from '../core/types.js';
|
|
4
|
+
import { err, ExitCode } from '../core/errors.js';
|
|
5
|
+
import { readAuditConfig } from '../store/audit.js';
|
|
6
|
+
import { contentHash } from '../core/hash.js';
|
|
7
|
+
import { scopeAllowsUpstream, scopeAllowsRead } from '../core/scope.js';
|
|
8
|
+
import { searchMemories } from '../retrieval/search.js';
|
|
9
|
+
import { exportData } from '../retrieval/export.js';
|
|
10
|
+
import { registerDefaultHandlers, runOnce } from '../jobs/worker.js';
|
|
11
|
+
import { getRemoteStore } from '../jobs/remote.js';
|
|
12
|
+
import { scanText } from '../core/secrets.js';
|
|
13
|
+
import { loadVaultConfig } from '../sync/vault.js';
|
|
14
|
+
import { loadKeys, exportRecoveryMaterial, importRecoveryMaterial, saveKeys } from '../sync/cryptoutil.js';
|
|
15
|
+
import { nowIso } from '../core/time.js';
|
|
16
|
+
import { syncContext, initRemote, syncPush, syncPull, registerSyncWorker } from '../sync/orchestrate.js';
|
|
17
|
+
import { importSnapshot } from '../onboarding/import.js';
|
|
18
|
+
import { findDuplicate } from '../governance/dedup.js';
|
|
19
|
+
import { decideWrite, describeJudgement } from '../onboarding/judgement.js';
|
|
20
|
+
import { assignBatch, batchProgress, nextBatchChunk, markItemPromoted, listSkippedItems, promotedPredicate } from '../onboarding/batches.js';
|
|
21
|
+
import { proposePlan } from '../governance/propose.js';
|
|
22
|
+
import { applyPlan } from '../governance/apply.js';
|
|
23
|
+
import { discoverSources } from '../onboarding/discover.js';
|
|
24
|
+
export class AppService {
|
|
25
|
+
store;
|
|
26
|
+
constructor(store) {
|
|
27
|
+
this.store = store;
|
|
28
|
+
// 操作审计配置:打开时读一次(env > config.json > 默认);改配置重启生效
|
|
29
|
+
this.auditCfg = readAuditConfig(store.paths.home);
|
|
30
|
+
registerDefaultHandlers();
|
|
31
|
+
// vault 已配置时,用真实上行 handler 覆盖诚实失败 handler
|
|
32
|
+
if (loadVaultConfig(store.paths.dataDir)) {
|
|
33
|
+
try {
|
|
34
|
+
const ctx = syncContext(store);
|
|
35
|
+
if (ctx)
|
|
36
|
+
registerSyncWorker(store, ctx.remote, ctx.vault);
|
|
37
|
+
}
|
|
38
|
+
catch {
|
|
39
|
+
// 环境变量缺失等:保持诚实失败 handler,doctor 会如实报告
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
auditCfg;
|
|
44
|
+
/**
|
|
45
|
+
* 操作留痕(add-operation-audit):读取操作记 `operation` 类目。
|
|
46
|
+
* 写入操作沿用既有 `memory` 类目审计,不在这里重复记录。
|
|
47
|
+
* FAIL-OPEN:审计写入失败只进 stderr,绝不影响业务结果;受 `audit.operations` 开关控制。
|
|
48
|
+
* 摘要纪律:detail 由调用点给白名单计数字段,查询原文/参数/正文永不入审计。
|
|
49
|
+
*/
|
|
50
|
+
recordOperation(action, subject, detail) {
|
|
51
|
+
if (!this.auditCfg.operations)
|
|
52
|
+
return;
|
|
53
|
+
try {
|
|
54
|
+
this.store.audit.record('operation', action, subject, detail);
|
|
55
|
+
}
|
|
56
|
+
catch (e) {
|
|
57
|
+
console.error(`[cairn] 操作审计写入失败(不影响业务): ${e.message}`);
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
/** 审计过滤查询(只读;MCP memory_audit 与 CLI cairn audit list 共用)。 */
|
|
61
|
+
auditList(filter = {}) {
|
|
62
|
+
return this.store.audit.list(filter);
|
|
63
|
+
}
|
|
64
|
+
static open(home) {
|
|
65
|
+
return new AppService(openStore(home ? { home } : {}));
|
|
66
|
+
}
|
|
67
|
+
close() {
|
|
68
|
+
this.store.close();
|
|
69
|
+
}
|
|
70
|
+
get caller() {
|
|
71
|
+
return {
|
|
72
|
+
deviceId: this.store.identity.deviceId,
|
|
73
|
+
agentId: process.env['CAIRN_AGENT_ID'] ?? 'cli',
|
|
74
|
+
channel: process.env['CAIRN_CHANNEL'] === 'agent' ? 'agent' : 'user',
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
// -------------------------------------------------------------------------
|
|
78
|
+
// 作用域解析
|
|
79
|
+
// -------------------------------------------------------------------------
|
|
80
|
+
resolveScope(sel) {
|
|
81
|
+
const store = this.store;
|
|
82
|
+
if (sel?.scopeId) {
|
|
83
|
+
return store.scopes.requireById(sel.scopeId);
|
|
84
|
+
}
|
|
85
|
+
const preset = sel?.preset ?? 'personal-global';
|
|
86
|
+
const overrides = {
|
|
87
|
+
...(sel?.ttlDays != null ? { ttlDays: sel.ttlDays } : {}),
|
|
88
|
+
};
|
|
89
|
+
switch (preset) {
|
|
90
|
+
case 'personal-global':
|
|
91
|
+
return store.scopes.resolvePreset('personal-global', { overrides });
|
|
92
|
+
case 'project-global': {
|
|
93
|
+
if (!sel?.projectId)
|
|
94
|
+
throw err('E_VALIDATION', 'project-global 需要 --project');
|
|
95
|
+
return store.scopes.resolvePreset('project-global', {
|
|
96
|
+
projectId: sel.projectId,
|
|
97
|
+
projectName: sel.projectName ?? sel.projectId,
|
|
98
|
+
overrides,
|
|
99
|
+
});
|
|
100
|
+
}
|
|
101
|
+
case 'project-device': {
|
|
102
|
+
if (!sel?.projectId)
|
|
103
|
+
throw err('E_VALIDATION', 'project-device 需要 --project');
|
|
104
|
+
return store.scopes.resolvePreset('project-device', {
|
|
105
|
+
projectId: sel.projectId,
|
|
106
|
+
projectName: sel.projectName ?? sel.projectId,
|
|
107
|
+
deviceId: this.caller.deviceId,
|
|
108
|
+
});
|
|
109
|
+
}
|
|
110
|
+
case 'device-local':
|
|
111
|
+
return store.scopes.resolvePreset('device-local', { deviceId: this.caller.deviceId });
|
|
112
|
+
case 'agent-private': {
|
|
113
|
+
if (!sel?.agentId)
|
|
114
|
+
throw err('E_VALIDATION', 'agent-private 需要 --agent');
|
|
115
|
+
return store.scopes.resolvePreset('agent-private', { agentId: sel.agentId });
|
|
116
|
+
}
|
|
117
|
+
case 'session-ephemeral':
|
|
118
|
+
return store.scopes.resolvePreset('session-ephemeral', { ttlDays: sel?.ttlDays ?? 7 });
|
|
119
|
+
default: {
|
|
120
|
+
const exhaustive = preset;
|
|
121
|
+
throw err('E_VALIDATION', `未知预设 ${String(exhaustive)}`);
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
// -------------------------------------------------------------------------
|
|
126
|
+
// 显式记忆生命周期
|
|
127
|
+
// -------------------------------------------------------------------------
|
|
128
|
+
/**
|
|
129
|
+
* 显式写入。判断(`judgement`)是建议不是授权:它只能影响"这条值不值得记",
|
|
130
|
+
* 敏感度与作用域永远取自写入参数,不取自判断(design D10)。
|
|
131
|
+
*
|
|
132
|
+
* 查重在这里做,因为写入路径的重复不是判断出来的、是对比出来的。
|
|
133
|
+
*/
|
|
134
|
+
addMemory(input, opts = {}) {
|
|
135
|
+
const store = this.store;
|
|
136
|
+
store.assertWritable();
|
|
137
|
+
const authority = input.authority ?? 'user_explicit';
|
|
138
|
+
const kind = input.kind ?? 'fact';
|
|
139
|
+
if (!MEMORY_KINDS.includes(kind)) {
|
|
140
|
+
throw err('E_VALIDATION', `kind 非法: ${String(kind)}`);
|
|
141
|
+
}
|
|
142
|
+
if (input.content.trim().length === 0)
|
|
143
|
+
throw err('E_VALIDATION', 'content 不能为空');
|
|
144
|
+
// 秘密扫描:显式写入同样阻断(构想 §12.3),错误只含 masked 摘要
|
|
145
|
+
const scan = scanText(input.content);
|
|
146
|
+
if (!scan.clean) {
|
|
147
|
+
throw scanError(scan);
|
|
148
|
+
}
|
|
149
|
+
const scope = this.resolveScope(input.scope);
|
|
150
|
+
// 敏感度只由写入参数决定:判断里没有这个字段,也无权改它。
|
|
151
|
+
const sensitivity = input.sensitivity ?? 'normal';
|
|
152
|
+
if (sensitivity === 'sensitive' && scope.syncPolicy !== 'local_only') {
|
|
153
|
+
throw err('E_VALIDATION', 'sensitive 记忆必须使用 local_only 作用域(device-local / project-device / 自定义 local_only)');
|
|
154
|
+
}
|
|
155
|
+
const ctx = this.caller;
|
|
156
|
+
const createdBy = ctx.agentId === 'cli' ? 'cli' : `mcp:${ctx.agentId}`;
|
|
157
|
+
const sourceAgent = input.sourceAgent ?? ctx.agentId;
|
|
158
|
+
const judgement = opts.judgement ?? null;
|
|
159
|
+
const duplicate = findDuplicate(store.db, scope.id, input.content);
|
|
160
|
+
const decision = decideWrite({ judgement, duplicate });
|
|
161
|
+
const auditDetail = {
|
|
162
|
+
basis: decision.basis,
|
|
163
|
+
judgement: judgement ? describeJudgement(judgement) : null,
|
|
164
|
+
rationale: judgement?.rationale ?? null,
|
|
165
|
+
duplicateOf: decision.targetMemoryId,
|
|
166
|
+
scopeId: scope.id,
|
|
167
|
+
};
|
|
168
|
+
if (decision.action === 'skip') {
|
|
169
|
+
// 高置信的"不值得记":不写库,但必须留痕,否则这条路是黑洞。
|
|
170
|
+
store.audit.record('memory', 'write_skipped', undefined, auditDetail);
|
|
171
|
+
return { action: 'skip', basis: decision.basis, memory: null, duplicateOf: null };
|
|
172
|
+
}
|
|
173
|
+
if (decision.action === 'merge') {
|
|
174
|
+
const target = store.memories.require(decision.targetMemoryId);
|
|
175
|
+
if (target.scopeId !== scope.id) {
|
|
176
|
+
throw err('E_VALIDATION', '并入目标必须与写入作用域相同');
|
|
177
|
+
}
|
|
178
|
+
// 只追加证据与来源,不新建记忆(spec memory-governance)。
|
|
179
|
+
const additions = input.evidence?.length
|
|
180
|
+
? input.evidence
|
|
181
|
+
: [{ evidenceKind: 'user_statement', sourceAgent, trustLevel: 'user_supplied' }];
|
|
182
|
+
for (const ev of additions) {
|
|
183
|
+
store.memories.addEvidence(target.id, target.currentRevisionId, ev);
|
|
184
|
+
}
|
|
185
|
+
store.audit.record('memory', 'write_merged', { type: 'memory', id: target.id }, auditDetail);
|
|
186
|
+
return { action: 'merge', basis: decision.basis, memory: store.memories.require(target.id), duplicateOf: target.id };
|
|
187
|
+
}
|
|
188
|
+
if (decision.action === 'promote_candidate') {
|
|
189
|
+
const candidateId = decision.targetMemoryId;
|
|
190
|
+
// 本次写入自己就不具备晋升权威时,不能把它变成 active——只把证据并回候选。
|
|
191
|
+
if (authority === 'agent_inferred' || authority === 'imported_unverified') {
|
|
192
|
+
const cand = store.memories.require(candidateId);
|
|
193
|
+
for (const ev of input.evidence ?? []) {
|
|
194
|
+
store.memories.addEvidence(cand.id, cand.currentRevisionId, ev);
|
|
195
|
+
}
|
|
196
|
+
store.audit.record('memory', 'write_merged_candidate', { type: 'memory', id: cand.id }, auditDetail);
|
|
197
|
+
return { action: 'candidate', basis: decision.basis, memory: cand, duplicateOf: cand.id };
|
|
198
|
+
}
|
|
199
|
+
const promoted = store.memories.promoteToActive(candidateId, authority, createdBy);
|
|
200
|
+
for (const ev of input.evidence ?? []) {
|
|
201
|
+
store.memories.addEvidence(promoted.id, promoted.currentRevisionId, ev);
|
|
202
|
+
}
|
|
203
|
+
store.audit.record('memory', 'write_promoted_candidate', { type: 'memory', id: promoted.id }, auditDetail);
|
|
204
|
+
return { action: 'promote_candidate', basis: decision.basis, memory: promoted, duplicateOf: promoted.id };
|
|
205
|
+
}
|
|
206
|
+
// insert 与 candidate 都走新建:candidate 是低置信"不值得记"的可逆降级,不是丢弃。
|
|
207
|
+
const memory = store.memories.add({
|
|
208
|
+
kind,
|
|
209
|
+
content: input.content,
|
|
210
|
+
scopeId: scope.id,
|
|
211
|
+
authority: decision.action === 'candidate' ? 'agent_inferred' : authority,
|
|
212
|
+
createdBy,
|
|
213
|
+
sourceAgent,
|
|
214
|
+
sourceSessionId: input.sourceSessionId ?? null,
|
|
215
|
+
evidence: input.evidence,
|
|
216
|
+
expiresAt: input.expiresAt ?? null,
|
|
217
|
+
sensitivity,
|
|
218
|
+
}, ctx.deviceId);
|
|
219
|
+
if (scopeAllowsUpstream(scope)) {
|
|
220
|
+
store.outbox.enqueue({
|
|
221
|
+
jobType: 'sync_upstream',
|
|
222
|
+
scopeId: scope.id,
|
|
223
|
+
entityType: 'memory',
|
|
224
|
+
entityId: memory.id,
|
|
225
|
+
payload: { op: 'memory_upsert', memoryId: memory.id },
|
|
226
|
+
idempotencyKey: `memory:${memory.id}`,
|
|
227
|
+
});
|
|
228
|
+
}
|
|
229
|
+
const auditAction = decision.action === 'candidate' ? 'added_candidate' : 'added';
|
|
230
|
+
store.audit.record('memory', auditAction, { type: 'memory', id: memory.id }, { ...auditDetail, kind, authority, sensitivity });
|
|
231
|
+
return { action: decision.action, basis: decision.basis, memory, duplicateOf: null };
|
|
232
|
+
}
|
|
233
|
+
reviseMemory(id, newContent, opts = {}) {
|
|
234
|
+
const store = this.store;
|
|
235
|
+
store.assertWritable();
|
|
236
|
+
const mem = store.memories.require(id);
|
|
237
|
+
const scan = scanText(newContent);
|
|
238
|
+
if (!scan.clean) {
|
|
239
|
+
throw err('E_SECRET_DETECTED', '更正内容疑似包含秘密,已阻断', {
|
|
240
|
+
findings: scan.findings.map((f) => ({ kind: f.kind, masked: f.masked })),
|
|
241
|
+
});
|
|
242
|
+
}
|
|
243
|
+
const scope = store.scopes.requireById(mem.scopeId);
|
|
244
|
+
const ctx = this.caller;
|
|
245
|
+
const out = store.memories.revise(id, newContent, { reason: opts.reason ?? '用户更正', author: ctx.agentId, expectedCurrentRevisionId: opts.expectedCurrentRevisionId }, ctx.deviceId);
|
|
246
|
+
if (scopeAllowsUpstream(scope)) {
|
|
247
|
+
store.outbox.enqueue({
|
|
248
|
+
jobType: 'sync_upstream',
|
|
249
|
+
scopeId: scope.id,
|
|
250
|
+
entityType: 'memory',
|
|
251
|
+
entityId: id,
|
|
252
|
+
payload: { op: 'memory_upsert', memoryId: id },
|
|
253
|
+
idempotencyKey: `memory:${id}:rev:${out.revision.id}`,
|
|
254
|
+
});
|
|
255
|
+
}
|
|
256
|
+
store.audit.record('memory', 'revised', { type: 'memory', id }, { revisionId: out.revision.id });
|
|
257
|
+
return out;
|
|
258
|
+
}
|
|
259
|
+
forgetMemory(id, reason) {
|
|
260
|
+
const store = this.store;
|
|
261
|
+
store.assertWritable();
|
|
262
|
+
const mem = store.memories.require(id);
|
|
263
|
+
const out = store.memories.forget(id, reason, this.caller.agentId);
|
|
264
|
+
const scope = store.scopes.requireById(mem.scopeId);
|
|
265
|
+
if (scopeAllowsUpstream(scope)) {
|
|
266
|
+
store.outbox.enqueue({
|
|
267
|
+
jobType: 'sync_upstream',
|
|
268
|
+
scopeId: scope.id,
|
|
269
|
+
entityType: 'memory',
|
|
270
|
+
entityId: id,
|
|
271
|
+
payload: { op: 'memory_tombstone', memoryId: id },
|
|
272
|
+
idempotencyKey: `memory:${id}:tombstone`,
|
|
273
|
+
});
|
|
274
|
+
}
|
|
275
|
+
store.audit.record('memory', 'forgotten', { type: 'memory', id }, { reason: reason ?? null });
|
|
276
|
+
return out;
|
|
277
|
+
}
|
|
278
|
+
archiveMemory(id) {
|
|
279
|
+
this.store.assertWritable();
|
|
280
|
+
return this.store.memories.archive(id);
|
|
281
|
+
}
|
|
282
|
+
/**
|
|
283
|
+
* 候选晋升(add-candidate-promote-command)。
|
|
284
|
+
*
|
|
285
|
+
* 三件必须一起做的事:
|
|
286
|
+
* 1. 权威记为 `user_confirmed`——用户**审阅并批准**了模型推断的内容,
|
|
287
|
+
* 语义上既不是「用户亲口说的」(user_explicit),也不是「模型推断」(agent_inferred);
|
|
288
|
+
* 2. 可选迁移作用域(含带本机路径的内容落 device-local),与晋升同事务;
|
|
289
|
+
* 3. **按新作用域重建 outbox**——旧作用域下的待同步任务若照发,
|
|
290
|
+
* 会把记忆同步到错误的云端空间(design D2)。
|
|
291
|
+
*/
|
|
292
|
+
promoteCandidate(id, opts = {}) {
|
|
293
|
+
const store = this.store;
|
|
294
|
+
store.assertWritable();
|
|
295
|
+
const mem = store.memories.require(id);
|
|
296
|
+
if (mem.status !== 'candidate') {
|
|
297
|
+
throw err('E_CONFLICT_STATE', `只有候选可晋升,当前 ${mem.status}`);
|
|
298
|
+
}
|
|
299
|
+
const previousScopeId = mem.scopeId;
|
|
300
|
+
let targetScopeId = mem.scopeId;
|
|
301
|
+
if (opts.scopePreset !== undefined) {
|
|
302
|
+
const sel = { preset: opts.scopePreset };
|
|
303
|
+
if (opts.projectId !== undefined)
|
|
304
|
+
sel.projectId = opts.projectId;
|
|
305
|
+
targetScopeId = this.resolveScope(sel).id;
|
|
306
|
+
}
|
|
307
|
+
const out = store.memories.promoteToActive(id, 'user_confirmed', this.caller.agentId, {
|
|
308
|
+
scopeId: targetScopeId,
|
|
309
|
+
});
|
|
310
|
+
const scope = store.scopes.requireById(out.scopeId);
|
|
311
|
+
// outbox:旧作用域的任务必须作废(否则发到错空间),新作用域按新修订重新入队。
|
|
312
|
+
store.db.run("DELETE FROM outbox_job WHERE entity_type = 'memory' AND entity_id = ? AND status = 'pending'", id);
|
|
313
|
+
if (scopeAllowsUpstream(scope)) {
|
|
314
|
+
store.outbox.enqueue({
|
|
315
|
+
jobType: 'sync_upstream',
|
|
316
|
+
scopeId: scope.id,
|
|
317
|
+
entityType: 'memory',
|
|
318
|
+
entityId: id,
|
|
319
|
+
payload: { op: 'memory_upsert', memoryId: id },
|
|
320
|
+
idempotencyKey: `memory:${id}:rev:${out.currentRevisionId ?? ''}`,
|
|
321
|
+
});
|
|
322
|
+
}
|
|
323
|
+
store.audit.record('memory', 'promoted_candidate', { type: 'memory', id }, {
|
|
324
|
+
fromScope: previousScopeId,
|
|
325
|
+
toScope: out.scopeId,
|
|
326
|
+
authority: out.authority,
|
|
327
|
+
channel: 'cli',
|
|
328
|
+
scopeChanged: previousScopeId !== out.scopeId,
|
|
329
|
+
});
|
|
330
|
+
return { memory: out, scope, previousScopeId };
|
|
331
|
+
}
|
|
332
|
+
/** 拒绝候选:转墓碑(不是物理删除),留审计理由;恢复需显式重做(design D4)。 */
|
|
333
|
+
rejectCandidate(id, opts) {
|
|
334
|
+
const store = this.store;
|
|
335
|
+
store.assertWritable();
|
|
336
|
+
const mem = store.memories.require(id);
|
|
337
|
+
if (mem.status !== 'candidate') {
|
|
338
|
+
throw err('E_CONFLICT_STATE', `只有候选可拒绝,当前 ${mem.status}`);
|
|
339
|
+
}
|
|
340
|
+
const reason = opts.reason.trim();
|
|
341
|
+
if (reason.length === 0)
|
|
342
|
+
throw err('E_VALIDATION', '拒绝理由不能为空');
|
|
343
|
+
const scan = scanText(reason);
|
|
344
|
+
if (!scan.clean) {
|
|
345
|
+
throw err('E_SECRET_DETECTED', '拒绝理由疑似包含秘密,已阻断', {
|
|
346
|
+
findings: scan.findings.map((f) => ({ kind: f.kind, masked: f.masked })),
|
|
347
|
+
});
|
|
348
|
+
}
|
|
349
|
+
const out = store.memories.forget(id, reason, this.caller.agentId);
|
|
350
|
+
store.audit.record('memory', 'rejected_candidate', { type: 'memory', id }, {
|
|
351
|
+
reason,
|
|
352
|
+
channel: 'cli',
|
|
353
|
+
});
|
|
354
|
+
return { memory: out };
|
|
355
|
+
}
|
|
356
|
+
showMemory(id) {
|
|
357
|
+
const startedAt = Date.now();
|
|
358
|
+
const store = this.store;
|
|
359
|
+
const memory = store.memories.require(id);
|
|
360
|
+
const scope = store.scopes.requireById(memory.scopeId);
|
|
361
|
+
if (this.caller.channel === 'agent') {
|
|
362
|
+
const query = {
|
|
363
|
+
deviceId: this.caller.deviceId,
|
|
364
|
+
agentId: this.caller.agentId,
|
|
365
|
+
projectId: process.env['CAIRN_PROJECT_ID'] ?? null,
|
|
366
|
+
};
|
|
367
|
+
if (!scopeAllowsRead(scope, query)) {
|
|
368
|
+
throw err('E_SCOPE_MISMATCH', '当前调用方无权读取该记忆详情(作用域不匹配)', { memoryId: id });
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
this.recordOperation('memory_get', { type: 'memory', id }, { ms: Date.now() - startedAt });
|
|
372
|
+
return {
|
|
373
|
+
memory,
|
|
374
|
+
revisions: store.memories.revisions(id),
|
|
375
|
+
evidence: store.memories.evidence(id),
|
|
376
|
+
relations: store.memories.relationsOf(id),
|
|
377
|
+
openConflicts: store.conflicts.listOpen(id).map((c) => ({
|
|
378
|
+
id: c.id,
|
|
379
|
+
revisionAId: c.revisionAId,
|
|
380
|
+
revisionBId: c.revisionBId,
|
|
381
|
+
detectedAt: c.detectedAt,
|
|
382
|
+
})),
|
|
383
|
+
tombstone: store.memories.getTombstone(id),
|
|
384
|
+
scope,
|
|
385
|
+
};
|
|
386
|
+
}
|
|
387
|
+
/** MCP memory_propose:只生成候选,绝不静默成为高权威活动记忆(memory-governance spec)。 */
|
|
388
|
+
proposeCandidate(input) {
|
|
389
|
+
const store = this.store;
|
|
390
|
+
store.assertWritable();
|
|
391
|
+
const scan = scanText(input.content);
|
|
392
|
+
if (!scan.clean) {
|
|
393
|
+
throw scanError(scan);
|
|
394
|
+
}
|
|
395
|
+
const scope = this.resolveScope(undefined);
|
|
396
|
+
const ctx = this.caller;
|
|
397
|
+
const m = store.memories.add({
|
|
398
|
+
kind: input.kind ?? 'fact',
|
|
399
|
+
content: input.content,
|
|
400
|
+
scopeId: scope.id,
|
|
401
|
+
authority: 'agent_inferred',
|
|
402
|
+
createdBy: `mcp:${ctx.agentId}`,
|
|
403
|
+
sourceAgent: ctx.agentId,
|
|
404
|
+
sourceSessionId: input.sourceSessionId ?? null,
|
|
405
|
+
evidence: input.evidence,
|
|
406
|
+
importance: input.importance ?? null,
|
|
407
|
+
}, ctx.deviceId);
|
|
408
|
+
store.audit.record('memory', 'candidate_proposed', { type: 'memory', id: m.id }, {
|
|
409
|
+
kind: m.kind,
|
|
410
|
+
importance: m.importance,
|
|
411
|
+
});
|
|
412
|
+
return m;
|
|
413
|
+
}
|
|
414
|
+
// -------------------------------------------------------------------------
|
|
415
|
+
// 检索 / 导出
|
|
416
|
+
// -------------------------------------------------------------------------
|
|
417
|
+
/**
|
|
418
|
+
* 检索 + 使用信号(add-memory-importance-and-usage-signal)。
|
|
419
|
+
*
|
|
420
|
+
* `incrementUsage` 缺省 true(显式检索),插件自动召回传 false。
|
|
421
|
+
* 只对**实际返回**的命中小心写入——被过滤掉的候选不算「被看到」。
|
|
422
|
+
*
|
|
423
|
+
* 写痕迹失败不得影响检索结果:审计与信号都是旁路,业务不能因它们挂掉。
|
|
424
|
+
*/
|
|
425
|
+
search(input, opts = {}) {
|
|
426
|
+
const startedAt = Date.now();
|
|
427
|
+
const r = searchMemories(this.store, input);
|
|
428
|
+
const incrementUsage = opts.incrementUsage ?? true;
|
|
429
|
+
try {
|
|
430
|
+
const at = nowIso();
|
|
431
|
+
for (const hit of r.results)
|
|
432
|
+
this.store.memories.markUsed(hit.memory.id, at, incrementUsage);
|
|
433
|
+
}
|
|
434
|
+
catch {
|
|
435
|
+
/* 使用信号是旁路:写失败不改检索结果 */
|
|
436
|
+
}
|
|
437
|
+
this.recordOperation('memory_search', undefined, {
|
|
438
|
+
candidates: r.results.length,
|
|
439
|
+
matchedBy: r.matchedBy,
|
|
440
|
+
degraded: r.degraded === true,
|
|
441
|
+
ms: Date.now() - startedAt,
|
|
442
|
+
});
|
|
443
|
+
return r;
|
|
444
|
+
}
|
|
445
|
+
export(input) {
|
|
446
|
+
return exportData(this.store, input);
|
|
447
|
+
}
|
|
448
|
+
findByContent(scopeId, text) {
|
|
449
|
+
return this.store.memories.findByContentHash(scopeId, contentHash(text));
|
|
450
|
+
}
|
|
451
|
+
// -------------------------------------------------------------------------
|
|
452
|
+
// 后台任务
|
|
453
|
+
// -------------------------------------------------------------------------
|
|
454
|
+
async workerRunOnce(opts = {}) {
|
|
455
|
+
return runOnce(this.store, { remote: getRemoteStore(), ...opts });
|
|
456
|
+
}
|
|
457
|
+
// -------------------------------------------------------------------------
|
|
458
|
+
// 健康检查(任务 5.4:诚实分级,无模型无云端核心可用)
|
|
459
|
+
// -------------------------------------------------------------------------
|
|
460
|
+
doctor() {
|
|
461
|
+
const store = this.store;
|
|
462
|
+
const problems = [];
|
|
463
|
+
const notes = [];
|
|
464
|
+
let integrity = 'unknown';
|
|
465
|
+
try {
|
|
466
|
+
integrity = store.db.integrityCheck() ? 'ok' : 'fail';
|
|
467
|
+
if (integrity !== 'ok')
|
|
468
|
+
problems.push('数据库完整性检查未通过');
|
|
469
|
+
}
|
|
470
|
+
catch (e) {
|
|
471
|
+
integrity = 'error';
|
|
472
|
+
problems.push(`完整性检查失败: ${e.message}`);
|
|
473
|
+
}
|
|
474
|
+
const fkViolations = store.db.foreignKeyCheck().length;
|
|
475
|
+
if (fkViolations > 0)
|
|
476
|
+
problems.push(`外键违规 ${fkViolations} 处`);
|
|
477
|
+
let ftsOk = false;
|
|
478
|
+
let ftsNote = '';
|
|
479
|
+
try {
|
|
480
|
+
store.db.all("SELECT rowid FROM memory_fts WHERE memory_fts MATCH '\"测试\"' LIMIT 1");
|
|
481
|
+
ftsOk = true;
|
|
482
|
+
ftsNote = 'FTS5 trigram 索引可查询';
|
|
483
|
+
}
|
|
484
|
+
catch (e) {
|
|
485
|
+
ftsNote = `FTS 索引异常(检索将走有界 LIKE 回退): ${e.message}`;
|
|
486
|
+
notes.push('FTS 不可用不影响权威数据;检索自动降级为有界回退');
|
|
487
|
+
}
|
|
488
|
+
if (store.cloneCheck.cloned) {
|
|
489
|
+
problems.push('检测到设备目录克隆:写入已暂停,请运行 device re-enroll');
|
|
490
|
+
}
|
|
491
|
+
const plansByStatus = {};
|
|
492
|
+
for (const r of store.db.all('SELECT status, COUNT(*) AS n FROM onboarding_plan GROUP BY status')) {
|
|
493
|
+
plansByStatus[String(r.status)] = Number(r.n);
|
|
494
|
+
}
|
|
495
|
+
const archiveCounts = store.archives.counts();
|
|
496
|
+
// remote 三态:not_configured / configured_untested / verified(首次成功往返后置 verified)
|
|
497
|
+
let remote = 'not_configured';
|
|
498
|
+
let remoteProvider;
|
|
499
|
+
const vault = loadVaultConfig(store.paths.dataDir);
|
|
500
|
+
if (vault) {
|
|
501
|
+
remoteProvider = vault.provider;
|
|
502
|
+
try {
|
|
503
|
+
syncContext(store);
|
|
504
|
+
const okRow = store.db.get("SELECT value FROM meta WHERE key = 'sync_last_ok'");
|
|
505
|
+
remote = okRow ? 'verified' : 'configured_untested';
|
|
506
|
+
}
|
|
507
|
+
catch (e) {
|
|
508
|
+
notes.push(`远端已配置但当前不可用:${e.message.slice(0, 120)}`);
|
|
509
|
+
remote = 'configured_untested';
|
|
510
|
+
}
|
|
511
|
+
}
|
|
512
|
+
if (remote === 'not_configured') {
|
|
513
|
+
notes.push('模型未配置(本变更无模型路径);云端未配置(remote=not_configured)。核心功能不依赖二者。');
|
|
514
|
+
}
|
|
515
|
+
return {
|
|
516
|
+
ok: problems.length === 0,
|
|
517
|
+
home: store.paths.home,
|
|
518
|
+
schemaVersion: schemaVersion(store.db),
|
|
519
|
+
device: { id: store.identity.deviceId, enrollment: store.cloneCheck.device?.enrollment ?? 'unknown', cloned: store.cloneCheck.cloned },
|
|
520
|
+
db: { integrity, foreignKeyViolations: fkViolations },
|
|
521
|
+
fts: { ok: ftsOk, note: ftsNote },
|
|
522
|
+
counts: {
|
|
523
|
+
memoryByStatus: store.memories.countsByStatus(),
|
|
524
|
+
importArchives: archiveCounts.archives,
|
|
525
|
+
importItems: { total: archiveCounts.items, clean: archiveCounts.items - archiveCounts.blockedItems, blocked: archiveCounts.blockedItems },
|
|
526
|
+
plansByStatus,
|
|
527
|
+
outboxByStatus: store.outbox.counts(),
|
|
528
|
+
openConflicts: store.conflicts.countOpen(),
|
|
529
|
+
},
|
|
530
|
+
remote,
|
|
531
|
+
remoteProvider,
|
|
532
|
+
model: 'not_configured',
|
|
533
|
+
problems,
|
|
534
|
+
notes,
|
|
535
|
+
};
|
|
536
|
+
}
|
|
537
|
+
// -------------------------------------------------------------------------
|
|
538
|
+
// 云同步(OpenSpec: add-real-cloud-sync)
|
|
539
|
+
// -------------------------------------------------------------------------
|
|
540
|
+
vaultInitRemote(input) {
|
|
541
|
+
return initRemote(this.store, input);
|
|
542
|
+
}
|
|
543
|
+
vaultStatus() {
|
|
544
|
+
const vault = loadVaultConfig(this.store.paths.dataDir);
|
|
545
|
+
const keys = vault ? Boolean(loadKeys(this.store.paths.dataDir)) : false;
|
|
546
|
+
return {
|
|
547
|
+
configured: vault != null,
|
|
548
|
+
vaultId: vault?.vaultId ?? null,
|
|
549
|
+
provider: vault?.provider ?? null,
|
|
550
|
+
obs: vault?.obs ?? null,
|
|
551
|
+
syncd: vault?.syncd ?? null,
|
|
552
|
+
keysPresent: keys,
|
|
553
|
+
};
|
|
554
|
+
}
|
|
555
|
+
vaultImportKey(recovery) {
|
|
556
|
+
const keys = importRecoveryMaterial(recovery);
|
|
557
|
+
saveKeys(this.store.paths.dataDir, keys);
|
|
558
|
+
this.store.audit.record('sync', 'keys_imported', { type: 'system', id: keys.vaultId }, {});
|
|
559
|
+
}
|
|
560
|
+
vaultExportKey() {
|
|
561
|
+
const keys = loadKeys(this.store.paths.dataDir);
|
|
562
|
+
if (!keys)
|
|
563
|
+
throw err('E_VALIDATION', '未找到 vault 密钥');
|
|
564
|
+
return exportRecoveryMaterial(keys);
|
|
565
|
+
}
|
|
566
|
+
async syncPushCmd() {
|
|
567
|
+
const ctx = this.requireSyncContext();
|
|
568
|
+
const r = await syncPush(this.store, ctx.remote, ctx.vault);
|
|
569
|
+
if (r && r.publishedChunks.length > 0)
|
|
570
|
+
this.markSyncOk();
|
|
571
|
+
return r;
|
|
572
|
+
}
|
|
573
|
+
async syncPullCmd() {
|
|
574
|
+
const ctx = this.requireSyncContext();
|
|
575
|
+
const r = await syncPull(this.store, ctx.remote, ctx.vault);
|
|
576
|
+
this.markSyncOk();
|
|
577
|
+
return r;
|
|
578
|
+
}
|
|
579
|
+
requireSyncContext() {
|
|
580
|
+
const ctx = syncContext(this.store);
|
|
581
|
+
if (!ctx)
|
|
582
|
+
throw err('E_VALIDATION', '未配置云端:请先 cairn vault init-remote');
|
|
583
|
+
return ctx;
|
|
584
|
+
}
|
|
585
|
+
markSyncOk() {
|
|
586
|
+
this.store.db.run("INSERT OR REPLACE INTO meta (key, value) VALUES ('sync_last_ok', ?)", nowIso());
|
|
587
|
+
}
|
|
588
|
+
status() {
|
|
589
|
+
const store = this.store;
|
|
590
|
+
const outbox = store.outbox.counts();
|
|
591
|
+
return {
|
|
592
|
+
device: store.identity.deviceId,
|
|
593
|
+
memories: store.memories.countsByStatus(),
|
|
594
|
+
outbox,
|
|
595
|
+
openConflicts: store.conflicts.countOpen(),
|
|
596
|
+
};
|
|
597
|
+
}
|
|
598
|
+
// -------------------------------------------------------------------------
|
|
599
|
+
// 首次初始化:发现 / 导入 / 分批 / 治理计划(任务 4.x / 3.x)
|
|
600
|
+
// -------------------------------------------------------------------------
|
|
601
|
+
/** 元数据发现:只列来源,不读正文(agent-onboarding spec)。 */
|
|
602
|
+
async discover(opts) {
|
|
603
|
+
return discoverSources({ homeDir: opts.homeDir, projectRoots: opts.projectRoots });
|
|
604
|
+
}
|
|
605
|
+
/** 快照导入:不可变快照 + imported_unverified 档案,源文件不变,重复导入幂等。 */
|
|
606
|
+
async importFromPath(input) {
|
|
607
|
+
const store = this.store;
|
|
608
|
+
store.assertWritable();
|
|
609
|
+
// 防回环:受管投影文件不作为导入来源(导出—回读—再导出循环)
|
|
610
|
+
const { readFileSync } = await import('node:fs');
|
|
611
|
+
const { hasCairnMarker } = await import('../projection/markdown.js');
|
|
612
|
+
const text = readFileSync(input.sourcePath, 'utf8');
|
|
613
|
+
if (hasCairnMarker(text)) {
|
|
614
|
+
throw err('E_PROJECTION_LOOP', '来源文件包含本产品受管投影标记;导入它会造成投影回环,已拒绝', { sourcePath: input.sourcePath });
|
|
615
|
+
}
|
|
616
|
+
const outcome = await importSnapshot(store, {
|
|
617
|
+
agentKind: input.agentKind,
|
|
618
|
+
sourcePath: input.sourcePath,
|
|
619
|
+
batchId: input.batchId,
|
|
620
|
+
sourceKind: input.sourceKind,
|
|
621
|
+
});
|
|
622
|
+
const batchId = outcome.batchId ?? assignBatch(store, outcome.reusedArchiveId ?? outcome.archiveId);
|
|
623
|
+
store.audit.record('import', 'imported_via_service', { type: 'archive', id: outcome.archiveId ?? outcome.reusedArchiveId }, { batchId });
|
|
624
|
+
return { outcome, batchId };
|
|
625
|
+
}
|
|
626
|
+
/** 活跃批次:最后一个仍有待晋升条目的批次 id。 */
|
|
627
|
+
activeBatchId() {
|
|
628
|
+
const rows = this.store.db.all(`SELECT i.batch_id AS bid, COUNT(*) AS n FROM import_item i
|
|
629
|
+
WHERE i.scan_state = 'clean' AND i.batch_id IS NOT NULL
|
|
630
|
+
AND ${promotedPredicate('i').handledNotExists}
|
|
631
|
+
GROUP BY i.batch_id ORDER BY i.batch_id DESC LIMIT 1`);
|
|
632
|
+
return rows.length > 0 ? String(rows[0].bid) : null;
|
|
633
|
+
}
|
|
634
|
+
batchStatus(batchId) {
|
|
635
|
+
return batchProgress(this.store, batchId);
|
|
636
|
+
}
|
|
637
|
+
batchChunk(batchId, limit) {
|
|
638
|
+
return nextBatchChunk(this.store, batchId, limit);
|
|
639
|
+
}
|
|
640
|
+
/** 某批次的已跳过条目:出队但可查(本次变更的核心取舍)。 */
|
|
641
|
+
batchSkipped(batchId, limit) {
|
|
642
|
+
return listSkippedItems(this.store, batchId, limit);
|
|
643
|
+
}
|
|
644
|
+
/** 由批次生成治理计划(Agent 建议 → 确定性管线),并标记对应条目来源。 */
|
|
645
|
+
proposeForBatch(input) {
|
|
646
|
+
const store = this.store;
|
|
647
|
+
store.assertWritable();
|
|
648
|
+
const batchId = input.batchId ?? this.activeBatchId();
|
|
649
|
+
if (!batchId)
|
|
650
|
+
throw err('E_VALIDATION', '没有活跃的导入批次;请先 cairn import');
|
|
651
|
+
const scope = this.resolveScope(input.scope ?? { preset: 'personal-global' });
|
|
652
|
+
const archiveIds = [...new Set(store.db.all('SELECT DISTINCT archive_id AS a FROM import_item WHERE batch_id = ?', batchId).map((r) => String(r.a)))];
|
|
653
|
+
const out = proposePlan(store, {
|
|
654
|
+
scopeId: scope.id,
|
|
655
|
+
items: input.items,
|
|
656
|
+
sourceArchiveIds: archiveIds,
|
|
657
|
+
proposedBy: input.proposedBy,
|
|
658
|
+
scan: scanText,
|
|
659
|
+
});
|
|
660
|
+
store.audit.record('plan', 'proposed_for_batch', { type: 'plan', id: out.plan.id }, { batchId, accepted: out.accepted, rejected: out.rejected.length });
|
|
661
|
+
return { ...out, plan: out.plan, planHash: out.planHash };
|
|
662
|
+
}
|
|
663
|
+
/** 本地可信审批通道(CLI approve / 控制台 webui):展示差异后由用户签发。 */
|
|
664
|
+
approve(planId, opts = {}) {
|
|
665
|
+
const store = this.store;
|
|
666
|
+
store.assertWritable();
|
|
667
|
+
const channel = opts.channel ?? 'cli';
|
|
668
|
+
store.plans.expireStale();
|
|
669
|
+
const plan = store.plans.requireById(planId);
|
|
670
|
+
if (plan.status !== 'awaiting_approval') {
|
|
671
|
+
throw err('E_APPROVAL_INVALID', `计划状态为 ${plan.status},只有 awaiting_approval 可批准`);
|
|
672
|
+
}
|
|
673
|
+
const { approval } = store.plans.issueApproval({ planId, channel, ttlMs: opts.ttlMs });
|
|
674
|
+
// 审计动作名携带签发通道:事后能回答"这次批准是在终端还是网页上给的"。
|
|
675
|
+
store.audit.record('approval', `issued_via_${channel}`, { type: 'approval', id: approval.id }, { planId, planHash: plan.planHash.slice(0, 16), channel });
|
|
676
|
+
return { approvalId: approval.id, expiresAt: approval.expiresAt, itemCount: plan.itemCount };
|
|
677
|
+
}
|
|
678
|
+
/** 应用治理计划(消费一次性审批),成功后把批次条目标记为已晋升。 */
|
|
679
|
+
applyPlan(planId, approvalId) {
|
|
680
|
+
const store = this.store;
|
|
681
|
+
store.assertWritable();
|
|
682
|
+
const plan = store.plans.requireById(planId);
|
|
683
|
+
const report = applyPlan(store, { planId, approvalId, deviceId: this.caller.deviceId, scan: scanText });
|
|
684
|
+
// 批次晋升游标:把成功 add/keep_both/merge 的条目标记为已晋升(audit 即状态)
|
|
685
|
+
for (const r of report.results) {
|
|
686
|
+
if (r.memoryId && r.opIndex != null) {
|
|
687
|
+
const op = store.plans.ops(planId).find((o) => o.opIndex === r.opIndex);
|
|
688
|
+
if (op?.itemId) {
|
|
689
|
+
try {
|
|
690
|
+
markItemPromoted(store, op.itemId, r.memoryId);
|
|
691
|
+
}
|
|
692
|
+
catch {
|
|
693
|
+
/* 同条目重复晋升已在 batches 层拦截 */
|
|
694
|
+
}
|
|
695
|
+
}
|
|
696
|
+
}
|
|
697
|
+
}
|
|
698
|
+
const archiveIds = plan.sourceArchiveIds;
|
|
699
|
+
const batchRow = archiveIds.length > 0 ? store.db.get('SELECT batch_id AS b FROM import_archive WHERE id = ?', archiveIds[0]) : null;
|
|
700
|
+
return { report, batchId: batchRow ? String(batchRow.b) : null };
|
|
701
|
+
}
|
|
702
|
+
/** 计划差异预览(供 CLI approve 展示;不含正文的统计 + 每操作的类型/目标)。 */
|
|
703
|
+
planSummary(planId) {
|
|
704
|
+
const store = this.store;
|
|
705
|
+
const plan = store.plans.requireById(planId);
|
|
706
|
+
const ops = store.plans.ops(planId);
|
|
707
|
+
return {
|
|
708
|
+
plan,
|
|
709
|
+
ops: ops.map((o) => ({
|
|
710
|
+
opIndex: o.opIndex,
|
|
711
|
+
opType: o.opType,
|
|
712
|
+
targetMemoryId: o.targetMemoryId,
|
|
713
|
+
targetExpectedRevision: o.targetExpectedRevision,
|
|
714
|
+
hasContent: o.content != null,
|
|
715
|
+
contentHash: o.contentHash,
|
|
716
|
+
kind: o.kind,
|
|
717
|
+
itemId: o.itemId,
|
|
718
|
+
status: o.status,
|
|
719
|
+
reason: o.reason,
|
|
720
|
+
})),
|
|
721
|
+
counts: {
|
|
722
|
+
add: ops.filter((o) => o.opType === 'add').length,
|
|
723
|
+
merge: ops.filter((o) => o.opType === 'merge').length,
|
|
724
|
+
keep_both: ops.filter((o) => o.opType === 'keep_both').length,
|
|
725
|
+
skip: ops.filter((o) => o.opType === 'skip').length,
|
|
726
|
+
},
|
|
727
|
+
};
|
|
728
|
+
}
|
|
729
|
+
}
|
|
730
|
+
/** 扫描命中错误:秘密优先;仅注入命中 → E_INJECTION_SUSPECTED。均不回显原文。 */
|
|
731
|
+
function scanError(scan) {
|
|
732
|
+
if (scan.findings.length > 0) {
|
|
733
|
+
return err('E_SECRET_DETECTED', '内容疑似包含秘密,已阻断(详情见 masked 摘要,不回显原文)', {
|
|
734
|
+
findings: scan.findings.map((f) => ({ kind: f.kind, masked: f.masked })),
|
|
735
|
+
injectionFindings: scan.injectionFindings.map((f) => ({ kind: f.kind, rule: f.rule })),
|
|
736
|
+
});
|
|
737
|
+
}
|
|
738
|
+
return err('E_INJECTION_SUSPECTED', '内容疑似提示注入指令,已按不可信数据处理并阻断该写入', {
|
|
739
|
+
injectionFindings: scan.injectionFindings.map((f) => ({ kind: f.kind, rule: f.rule })),
|
|
740
|
+
});
|
|
741
|
+
}
|
|
742
|
+
export { ExitCode };
|
|
743
|
+
//# sourceMappingURL=app-service.js.map
|