dsh-memory-bond 0.0.0-stage → 1.0.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.
Files changed (126) hide show
  1. package/CHANGELOG.md +10 -0
  2. package/LICENSE +21 -0
  3. package/README.md +181 -2
  4. package/README.zh-CN.md +180 -0
  5. package/SECURITY.md +29 -0
  6. package/client/memory-icon.svg +21 -0
  7. package/cordis.patch.yml +3 -0
  8. package/dist/audit.js +286 -0
  9. package/dist/automatic.js +16 -0
  10. package/dist/cache.js +40 -0
  11. package/dist/client.js +2035 -0
  12. package/dist/command-scope.js +123 -0
  13. package/dist/commands.js +156 -0
  14. package/dist/consolidation-store.js +357 -0
  15. package/dist/consolidation.js +182 -0
  16. package/dist/domain.js +245 -0
  17. package/dist/encoder.js +138 -0
  18. package/dist/export-files.js +161 -0
  19. package/dist/file-import-store.js +120 -0
  20. package/dist/file-import.js +265 -0
  21. package/dist/foreground-attempts.js +91 -0
  22. package/dist/guidance.js +242 -0
  23. package/dist/host.js +19 -0
  24. package/dist/index-policy.js +191 -0
  25. package/dist/index.js +349 -0
  26. package/dist/knowledge-hooks.js +398 -0
  27. package/dist/knowledge.js +359 -0
  28. package/dist/maintenance-episodes.js +73 -0
  29. package/dist/maintenance-import.js +92 -0
  30. package/dist/maintenance-store.js +738 -0
  31. package/dist/maintenance.js +376 -0
  32. package/dist/model-review.js +16 -0
  33. package/dist/personal.js +60 -0
  34. package/dist/policy.js +382 -0
  35. package/dist/prompt-copy.js +93 -0
  36. package/dist/proposal-receipts.js +70 -0
  37. package/dist/proposal-review.js +656 -0
  38. package/dist/propose-contract.js +38 -0
  39. package/dist/question-answers.js +176 -0
  40. package/dist/retrieval.js +126 -0
  41. package/dist/scope-narrowing.js +49 -0
  42. package/dist/search-index.js +164 -0
  43. package/dist/search-words.js +5 -0
  44. package/dist/semantic.js +157 -0
  45. package/dist/service.js +1473 -0
  46. package/dist/sharing.js +289 -0
  47. package/dist/sources.js +149 -0
  48. package/dist/store.js +1578 -0
  49. package/dist/tool-experience.js +87 -0
  50. package/dist/turn-review-store.js +159 -0
  51. package/dist/turn-review.js +459 -0
  52. package/dist/ui.js +346 -0
  53. package/dist/vector-index.js +232 -0
  54. package/docs/architecture.zh-CN.md +52 -0
  55. package/docs/benchmark.zh-CN.md +60 -0
  56. package/docs/benchmarks/repository-tasks.json +5355 -0
  57. package/docs/images/bond-memory-principle-en.svg +644 -0
  58. package/docs/images/bond-memory-principle-zh.svg +644 -0
  59. package/docs/images/bond-memory-principle.drawio +644 -0
  60. package/docs/images/memory-settings-en.png +0 -0
  61. package/docs/images/memory-settings-zh.png +0 -0
  62. package/docs/images/memory-turn-recalled-en.png +0 -0
  63. package/docs/images/memory-turn-recalled-zh.png +0 -0
  64. package/docs/images/memory-turn-saved-en.png +0 -0
  65. package/docs/images/memory-turn-saved-zh.png +0 -0
  66. package/docs/media/memory-bond-name-en.gif +0 -0
  67. package/docs/media/memory-bond-name-en.mp4 +0 -0
  68. package/docs/media/memory-bond-name-zh.gif +0 -0
  69. package/docs/media/memory-bond-name-zh.mp4 +0 -0
  70. package/locale/detail.en.md +13 -0
  71. package/locale/detail.zh.md +13 -0
  72. package/locale/en.json +345 -0
  73. package/locale/zh.json +345 -0
  74. package/native/embeddings/NOTICE.md +12 -0
  75. package/package.json +117 -4
  76. package/scripts/benchmark-bond.mjs +72 -0
  77. package/scripts/benchmark-conditions.mjs +144 -0
  78. package/scripts/benchmark-example.mjs +37 -0
  79. package/scripts/benchmark-scale.mjs +119 -0
  80. package/scripts/benchmark-scenarios.mjs +57 -0
  81. package/scripts/benchmark-tasks.mjs +244 -0
  82. package/src/audit.ts +286 -0
  83. package/src/automatic.ts +21 -0
  84. package/src/cache.ts +38 -0
  85. package/src/command-scope.ts +125 -0
  86. package/src/commands.ts +159 -0
  87. package/src/consolidation-store.ts +350 -0
  88. package/src/consolidation.ts +176 -0
  89. package/src/domain.ts +254 -0
  90. package/src/encoder.ts +142 -0
  91. package/src/export-files.ts +178 -0
  92. package/src/file-import-store.ts +139 -0
  93. package/src/file-import.ts +256 -0
  94. package/src/foreground-attempts.ts +97 -0
  95. package/src/guidance.ts +265 -0
  96. package/src/host.ts +119 -0
  97. package/src/index-policy.ts +231 -0
  98. package/src/index.ts +333 -0
  99. package/src/knowledge-hooks.ts +456 -0
  100. package/src/knowledge.ts +432 -0
  101. package/src/maintenance-episodes.ts +76 -0
  102. package/src/maintenance-import.ts +107 -0
  103. package/src/maintenance-store.ts +868 -0
  104. package/src/maintenance.ts +380 -0
  105. package/src/model-review.ts +27 -0
  106. package/src/personal.ts +68 -0
  107. package/src/policy.ts +508 -0
  108. package/src/prompt-copy.ts +99 -0
  109. package/src/proposal-receipts.ts +59 -0
  110. package/src/proposal-review.ts +614 -0
  111. package/src/propose-contract.ts +39 -0
  112. package/src/question-answers.ts +181 -0
  113. package/src/retrieval.ts +133 -0
  114. package/src/scope-narrowing.ts +58 -0
  115. package/src/search-index.ts +177 -0
  116. package/src/search-words.ts +6 -0
  117. package/src/semantic.ts +178 -0
  118. package/src/service.ts +1488 -0
  119. package/src/sharing.ts +349 -0
  120. package/src/sources.ts +150 -0
  121. package/src/store.ts +1829 -0
  122. package/src/tool-experience.ts +93 -0
  123. package/src/turn-review-store.ts +158 -0
  124. package/src/turn-review.ts +418 -0
  125. package/src/ui.ts +385 -0
  126. package/src/vector-index.ts +228 -0
@@ -0,0 +1,123 @@
1
+ import { existsSync, statSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { scopedPath } from "./domain.js";
4
+ const shellExecutable = '(?:make|just|npm|pnpm|yarn|bun|go|cargo|pytest|gradle|mvn|docker|podman|git|cd|pushd|popd|bash|sh|env|node|python3?|cat|cp|mv|ls|find|rg|sed|awk|tar|echo|printf)';
5
+ const commandStart = new RegExp('^(?:' + shellExecutable + '(?=\\s|$)|[./])', 'u');
6
+ // A literal "executable args..." run anchored at the END of the text, independent of
7
+ // shellExecutable's fixed names: recovers an unrecognized-but-real command (e.g.
8
+ // docker-compose, kubectl, terraform) for scope checking even behind a leading
9
+ // natural-language phrase that keeps literalActionCommand from stripping it.
10
+ const literalTail = /[A-Za-z][\w.+-]*(?:[ \t]+[A-Za-z0-9_./:+@=-]+)+$/u;
11
+ /** One literal executable and literal arguments, with no interpolation, redirection or shell operators. */
12
+ export function literalBashCommand(input) {
13
+ if (typeof input !== 'string' || /[\n\r]/u.test(input))
14
+ return;
15
+ const trimmed = input.trim();
16
+ if (!/^[A-Za-z0-9_./+-]+(?:[ \t]+[A-Za-z0-9_./:+@=-]+)*$/u.test(trimmed))
17
+ return;
18
+ return trimmed.split(/[ \t]+/u).join(' ');
19
+ }
20
+ export function literalActionCommand(action) {
21
+ // Match one affirmed command only. Alternatives, negations and examples are ambiguous for behavioral credit.
22
+ if (/[\n\r??;&|$<>]|不要|禁止|勿|别|避免|停用|不应|不能|不得|不用|不再|不运行|不执行|跳过|省略|替换掉|不使用|不采用|例子|例如|示例|改掉|废弃|拒绝|以免|引用|引文|转述|文档说|假设|\b(?:no|not|never|avoid|instead|unless|without|except|stop|skip|example|replace|disable|deprecated|from|or|don't|quoted?|says?|hypothetical)\b/iu.test(action))
23
+ return;
24
+ // Text prefixes are bounded to an affirmative imperative, e.g. “运行 make test” or “Run `make test`”.
25
+ const extract = (prefix, command, suffix) => {
26
+ if (prefix &&
27
+ !/(?:运行|执行|使用|采用|改用|用|改为|先跑|运行命令|命令为|入口是|\b(?:run|use|execute|invoke|call))\s*[::]?\s*$/iu.test(prefix))
28
+ return;
29
+ if (!/^[\s.。!!]*$/u.test(suffix))
30
+ return;
31
+ return literalBashCommand(command);
32
+ };
33
+ const quoted = /^([^`]*?)`([^`]+)`([^`]*)$/u.exec(action.trim());
34
+ if (quoted)
35
+ return extract(quoted[1], quoted[2], quoted[3]);
36
+ const plain = new RegExp('^(.*?)(' + shellExecutable + '(?:[ \\t]+[A-Za-z0-9_./:+@=-]+)+)([。!!]?)$', 'u').exec(action.trim());
37
+ if (plain)
38
+ return extract(plain[1], plain[2], plain[3]);
39
+ // A raw literal command can contain another executable name, e.g. "npm run build".
40
+ return literalBashCommand(action);
41
+ }
42
+ const directoryOption = /^(?:-C|--directory|--chdir|--cwd|--workdir)$/;
43
+ const attachedDirectory = /^(?:-C(.+)|--(?:directory|chdir|cwd|workdir)=(.*))$/;
44
+ /** Return the shell process cwd and the command's effective directory only for literal local operands. */
45
+ export function bashScope(domain, input, workdir = domain.cwd) {
46
+ const command = literalBashCommand(input);
47
+ if (!command)
48
+ return;
49
+ try {
50
+ const cwd = scopedPath(domain, workdir);
51
+ if (!statSync(cwd).isDirectory())
52
+ return;
53
+ const [program, ...args] = command.split(' ');
54
+ if (program.includes('/'))
55
+ scopedPath(domain, program, cwd);
56
+ let directory = cwd;
57
+ const operands = [];
58
+ for (let i = 0; i < args.length; i++) {
59
+ const arg = args[i];
60
+ const attached = attachedDirectory.exec(arg);
61
+ if (directoryOption.test(arg) || attached) {
62
+ const target = attached ? (attached[1] ?? attached[2]) : args[++i];
63
+ if (!target || target.startsWith('-'))
64
+ return;
65
+ directory = scopedPath(domain, target, directory);
66
+ if (!statSync(directory).isDirectory())
67
+ return;
68
+ }
69
+ else {
70
+ operands.push(arg);
71
+ }
72
+ }
73
+ for (const arg of operands) {
74
+ // Handle --file=../src, name=/path and common short file options such as -I../include.
75
+ const equal = arg.indexOf('=');
76
+ const value = equal >= 0 ? arg.slice(equal + 1) : arg.replace(/^-[fFIoL](?=.+)/u, '');
77
+ if (!value)
78
+ continue;
79
+ if (value.includes(':') && value.includes('/'))
80
+ return; // host:path, URI, or a bind mount
81
+ if (value.includes('/') || value === '..' || value === '.' || existsSync(join(directory, value))) {
82
+ if (value.startsWith('-') || value.startsWith('@'))
83
+ return;
84
+ scopedPath(domain, value, directory);
85
+ if (directory !== cwd && !['make', 'git', 'just'].includes(program))
86
+ scopedPath(domain, value, cwd);
87
+ }
88
+ }
89
+ return { command, cwd, directory, program, operands };
90
+ }
91
+ catch {
92
+ return undefined;
93
+ }
94
+ }
95
+ /** Prose and negative preferences have no implicit operation. Ambiguous shell syntax gets no active rule. */
96
+ export function actionInDomain(domain, action, check = bashScope) {
97
+ const command = literalActionCommand(action);
98
+ const raw = action.trim();
99
+ const invocation = commandStart.test(raw) || /^[a-zA-Z_][\w.-]*\s+(?:\.\.(?:\s|$)|[./~]|-[A-Za-z-])/u.test(raw);
100
+ if (invocation) {
101
+ // A tool name can be the subject of a preference ("git 提交说明使用中文").
102
+ // An actual cwd option, path operand or shell operator still requires a known scope.
103
+ const prose = !command &&
104
+ /\p{Script=Han}/u.test(raw) &&
105
+ !/(?:^|\s)(?:-+[A-Za-z]|[./~])|[;&|$<>]|^(?:cd|pushd|popd)\s/u.test(raw);
106
+ return prose || !!check(domain, command ?? raw);
107
+ }
108
+ if (command && command !== raw)
109
+ return !!check(domain, command);
110
+ // Preserve natural-language exceptions and negations even if they cite shell commands.
111
+ if (/(?:不|别|勿|禁止|避免|停用|\b(?:not|never|avoid|without|unless|except|don't)\b)/iu.test(action))
112
+ return true;
113
+ // An unrecognized leading token (docker-compose, kubectl, terraform, ...) is not by
114
+ // itself evidence of harmless prose: a literal, checkable invocation can still be
115
+ // sitting behind it, so a trailing run that is itself a clean command still gets
116
+ // the real scope check instead of being waved through on name recognition alone.
117
+ const tail = literalTail.exec(raw)?.[0];
118
+ if (tail)
119
+ return !!check(domain, tail);
120
+ const affirmative = /(?:运行|执行|采用|改用|使用|\b(?:run|execute|invoke))\s*[::]?\s*`?\s*([^\s`]+)(?:\s|$)/iu;
121
+ const embedded = affirmative.exec(action)?.[1];
122
+ return !embedded || !commandStart.test(embedded);
123
+ }
@@ -0,0 +1,156 @@
1
+ import { latestTurn, matches, publicRule, ruleFields } from "./service.js";
2
+ import { StoreError } from "./store.js";
3
+ import { maintenanceCommand } from "./maintenance.js";
4
+ import { knowledgeCommand, isKnowledge } from "./knowledge.js";
5
+ import { exportCommand } from "./sharing.js";
6
+ const usage = 'inbox · remember <动作或 JSON> · revise <ID@版本> <新动作或 JSON> · confirm <提案ID> <卡片版本> <摘要> all|选择数组 · reject <提案ID> <卡片版本> <摘要> · search [--hybrid|--semantic|--keyword] <查询> · read|source|why|forget|undo|clear-quote|pin|unpin <ID@版本> · usage <ID@版本> proactive|on_demand · status · fact|episode|reference|runbook|guard <JSON> · episode-stats <经历ID> · import [all|agents|claude|claude-memory] · import list · import undo <批次ID> · history [会话ID] · history import <旧会话ID> · backup [personal] · restore [personal] <备份ID> · clear <ID@版本> · export agents|skill <ID@版本> [名称] · export apply <预览凭据>';
7
+ export function parseRef(text) {
8
+ const match = /^(mem-[a-z0-9-]+)(?:@([1-9]\d*))?$/i.exec(text);
9
+ return match ? { id: match[1], rev: match[2] ? Number(match[2]) : undefined } : undefined;
10
+ }
11
+ function manualFields(value, base) {
12
+ let updates = { action: value.trim() };
13
+ if (value.trim().startsWith('{'))
14
+ updates = JSON.parse(value);
15
+ const fields = base
16
+ ? ruleFields(base)
17
+ : { user_quote: '', when: '', action: '', paths: [], exceptions: '', conflicts_with_repo_guidance: false };
18
+ return { ...fields, ...updates };
19
+ }
20
+ export function registerCommands(ctx, memory, hostIssues = []) {
21
+ ctx.commands.register({
22
+ name: 'project-memory',
23
+ description: '查询和管理全局偏好、项目规则与知识',
24
+ recordInput: false,
25
+ input: { hint: usage },
26
+ async handler({ agent, rawInput, commandId }) {
27
+ try {
28
+ const value = await run(memory, agent, rawInput.trim(), commandId, hostIssues);
29
+ return { kind: 'success', text: typeof value === 'string' ? value : JSON.stringify(value, null, 2) };
30
+ }
31
+ catch (error) {
32
+ return { kind: 'error', text: error instanceof Error ? error.message : 'operation_failed' };
33
+ }
34
+ },
35
+ });
36
+ }
37
+ async function run(memory, agent, input, commandId, hostIssues) {
38
+ const [verb = '', ...rest] = input.split(/\s+/);
39
+ const query = input.slice(verb.length).trim();
40
+ const [identifier, revision, digest] = rest;
41
+ const mutate = [
42
+ 'confirm',
43
+ 'reject',
44
+ 'remember',
45
+ 'revise',
46
+ 'forget',
47
+ 'undo',
48
+ 'clear-quote',
49
+ 'pin',
50
+ 'unpin',
51
+ 'usage',
52
+ ].includes(verb);
53
+ let d = memory.rootDomain(agent, mutate);
54
+ if (!verb || verb === 'help')
55
+ return usage;
56
+ if (['history', 'backup', 'restore', 'clear'].includes(verb))
57
+ return maintenanceCommand(memory, agent, verb, query);
58
+ if (['fact', 'episode', 'episode-stats', 'reference', 'runbook', 'guard'].includes(verb))
59
+ return knowledgeCommand(memory, agent, verb, query, commandId);
60
+ if (verb === 'import')
61
+ return memory.fileImport(agent, query, commandId);
62
+ if (verb === 'export')
63
+ return exportCommand(memory, agent, query);
64
+ if (verb === 'inbox')
65
+ return memory.view(agent).proposals.filter((p) => p.state === 'pending');
66
+ if (verb === 'confirm' || verb === 'reject') {
67
+ const p = memory.proposalOf(agent, identifier ?? '')?.p;
68
+ if (!p)
69
+ throw new StoreError('not_found');
70
+ // The render supplies the token. Never fill in a missing digest from the database.
71
+ const choices = query.replace(/^\S+\s+\S+\s+\S+\s*/, '');
72
+ const selections = verb === 'reject'
73
+ ? []
74
+ : choices === 'all'
75
+ ? p.items.map((_, index) => ({ index }))
76
+ : JSON.parse(choices);
77
+ return memory.review(agent, { id: p.id, revision: Number(revision), digest, selections }, verb === 'reject' ? 'reject' : choices === 'all' ? 'all' : undefined, 'user_command');
78
+ }
79
+ if (verb === 'search') {
80
+ const flag = /^--(keyword|semantic|hybrid)(?:\s+|$)/.exec(query);
81
+ return (await memory.search(agent, flag ? query.slice(flag[0].length) : query, flag?.[1])).map(publicRule);
82
+ }
83
+ if (verb === 'status') {
84
+ const { rules: status, proposals, needs_review } = memory.view(agent);
85
+ return {
86
+ memoryEnabled: memory.store.memoryEnabled(),
87
+ hostIssues,
88
+ embeddingLanguages: memory.retrieval.vectors.languages,
89
+ rules: status,
90
+ pending: proposals.filter((p) => p.state === 'pending').length,
91
+ needs_review,
92
+ withdrawn: memory.scopes(agent, d).flatMap((s) => memory.store.withdrawn(s.id, agent.id)),
93
+ };
94
+ }
95
+ if (verb === 'remember')
96
+ return memory.manual(agent, { turnId: Number(latestTurn(agent.session)), items: [manualFields(query)], userAuthored: true }, commandId);
97
+ const ref = parseRef(identifier ?? '');
98
+ // A query can locate a rule; mutations use the exact revision the person saw.
99
+ if (!ref)
100
+ return {
101
+ matches: memory
102
+ .visible(agent, d)
103
+ .filter((r) => matches(r, query))
104
+ .map((r) => ({ ...publicRule(r), ref: r.id + '@' + r.rev })),
105
+ hint: usage,
106
+ };
107
+ d = memory.owner(agent, d, ref.id) ?? d;
108
+ if (verb === 'why' || verb === 'source') {
109
+ const evidence = await memory.read(agent, ref.id, ref.rev, true);
110
+ if (!memory.scopes(agent, memory.rootDomain(agent)).some(scope => scope.id === d.id))
111
+ throw new StoreError('not_found');
112
+ const rule = memory.current(d, ref.id, ref.rev);
113
+ const visible = rule && 'quote' in evidence && evidence.rev === rule.rev && memory.canPublishEvidence(rule, evidence);
114
+ if (verb === 'source')
115
+ return visible ? evidence : { status: 'not_found' };
116
+ const history = memory.store.history(d.id, ref.id);
117
+ if (!history.length && !rule)
118
+ throw new StoreError('not_found');
119
+ return {
120
+ rule: visible ? { ...publicRule(rule), ...evidence } : undefined,
121
+ history,
122
+ };
123
+ }
124
+ if (verb === 'read')
125
+ return memory.read(agent, ref.id, ref.rev);
126
+ if (ref.rev === undefined)
127
+ throw new StoreError('expected_revision', '请使用卡片上显示的 ID@版本');
128
+ if (verb === 'revise') {
129
+ if (d.id === memory.personal.id)
130
+ return '在管理记忆中编辑这条全局记忆,或在聊天里说明要更正的内容。';
131
+ const old = memory.store.read(d.id, ref.id, ref.rev);
132
+ if (!old)
133
+ throw new StoreError('conflict');
134
+ if (isKnowledge(old))
135
+ return ('使用 /project-memory ' +
136
+ old.kind +
137
+ ' 并在 JSON 中传入 replace 字段 ' +
138
+ identifier +
139
+ ' 以更新结构化内容。');
140
+ const change = query.slice(identifier.length).trim();
141
+ if (!change)
142
+ throw new StoreError('invalid_item', '请在 ' + identifier + ' 之后写出新的动作,或一段 JSON。');
143
+ const fields = manualFields(change, old);
144
+ // The old quote authorized the old action. Default to a fresh manual receipt.
145
+ fields.user_quote = '';
146
+ return memory.manual(agent, { turnId: Number(latestTurn(agent.session)), items: [fields], userAuthored: true }, commandId, {
147
+ id: ref.id,
148
+ rev: ref.rev,
149
+ });
150
+ }
151
+ if (verb === 'usage')
152
+ return memory.manage(agent, verb, { ...ref, usage: rest[1] });
153
+ if (['undo', 'forget', 'clear-quote', 'pin', 'unpin'].includes(verb))
154
+ return memory.manage(agent, verb, ref);
155
+ throw new StoreError('invalid_command', usage);
156
+ }
@@ -0,0 +1,357 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { skipsAutomaticMemory } from "./automatic.js";
3
+ import { normalizeLabel } from "./personal.js";
4
+ import { indexWords } from "./search-index.js";
5
+ import { encoderId, modelLanguages } from "./encoder.js";
6
+ import { StoreError, storedVector } from "./store.js";
7
+ const dayMs = 86_400_000;
8
+ const intervalMs = 3_600_000;
9
+ const leaseMs = 300_000;
10
+ const pageSize = 24;
11
+ // Session IDs are used only to compare origins locally. The model projection below has no
12
+ // source coordinates, raw quote, or general-purpose revision payload.
13
+ const columns = `r.rid,r.id,r.rev,r.action,r.condition,r.paths,
14
+ json_extract(r.payload,'$.semanticTopic') topic,json_extract(r.payload,'$.subject') subject,
15
+ json_extract(r.payload,'$.exceptions') exceptions,json_extract(r.payload,'$.keywords') keywords,
16
+ json_extract(r.payload,'$.kind') kind,json_extract(r.payload,'$.usage') usage,
17
+ json_extract(r.payload,'$.hard','$.guidance') constraints,json_extract(e.source,'$.sessionId') session`;
18
+ const joins = `JOIN heads h USING(domain,id,rev) JOIN evidence e USING(domain,id,rev)`;
19
+ const eligible = `r.state='confirmed' AND r.slot GLOB 'project.topic.*' AND h.pinned=0
20
+ AND json_extract(r.payload,'$.channel')='automatic'
21
+ AND json_extract(r.payload,'$.kind') IN ('fact','preference','rule')
22
+ AND json_extract(r.payload,'$.sensitive') IS NOT 1 AND json_extract(r.payload,'$.usageOverride') IS NOT 1
23
+ AND json_extract(r.payload,'$.localException') IS NULL AND json_extract(r.payload,'$.semanticTopic') IS NOT NULL
24
+ AND e.type='user_quote' AND json_extract(e.source,'$.sessionId')<>''`;
25
+ function candidate(row) {
26
+ if (!row)
27
+ return;
28
+ const item = {
29
+ id: String(row.id), rev: Number(row.rev), topic: String(row.topic),
30
+ ...(row.subject != null && { subject: String(row.subject) }),
31
+ kind: row.kind, usage: row.usage === 'proactive' ? 'proactive' : 'on_demand',
32
+ action: String(row.action), when: String(row.condition), exceptions: String(row.exceptions ?? ''),
33
+ paths: JSON.parse(String(row.paths)),
34
+ };
35
+ const labels = [item.topic, ...JSON.parse(String(row.keywords ?? '[]'))].map(normalizeLabel);
36
+ if (skipsAutomaticMemory([item.subject, ...labels, item.action, item.when, item.exceptions, ...item.paths].join(' ')))
37
+ return;
38
+ return { rid: Number(row.rid), session: String(row.session), constraints: String(row.constraints), labels, item,
39
+ words: new Set(indexWords(normalizeLabel([item.topic, item.action].join(' ')))) };
40
+ }
41
+ function comparable(a, b) {
42
+ // The model sees both subjects, kinds and usage policies. Repository guards
43
+ // are not in that projection; differing guards cannot be safely compared.
44
+ return a.session !== b.session && a.constraints === b.constraints;
45
+ }
46
+ function lexicalSimilarity(a, b) {
47
+ if (normalizeLabel(a.item.action) === normalizeLabel(b.item.action) || a.labels.some(l => b.labels.includes(l)))
48
+ return 1;
49
+ const common = [...a.words].filter(w => b.words.has(w)).length;
50
+ return common / Math.sqrt(Math.max(1, a.words.size * b.words.size));
51
+ }
52
+ const schema = `
53
+ CREATE TABLE IF NOT EXISTS consolidation_settings (
54
+ singleton INTEGER PRIMARY KEY CHECK(singleton=1), enabled INTEGER NOT NULL, generation INTEGER NOT NULL
55
+ );
56
+ INSERT OR IGNORE INTO consolidation_settings(singleton,enabled,generation) VALUES(1,0,0);
57
+ CREATE TABLE IF NOT EXISTS consolidation_scans(domain TEXT PRIMARY KEY,cursor INTEGER NOT NULL,checked INTEGER NOT NULL);
58
+ CREATE TABLE IF NOT EXISTS consolidation_unpin_scans(domain TEXT PRIMARY KEY,cursor INTEGER NOT NULL);
59
+ CREATE TABLE IF NOT EXISTS consolidation_vector_jobs(domain TEXT NOT NULL,rid INTEGER NOT NULL,
60
+ PRIMARY KEY(domain,rid));
61
+ CREATE INDEX IF NOT EXISTS consolidation_vector_lookup ON memory_vectors(domain,model) WHERE model GLOB '*/passage-0';
62
+ CREATE TRIGGER IF NOT EXISTS queue_consolidation_vector AFTER INSERT ON memory_vectors
63
+ WHEN NEW.model GLOB '*/passage-0' BEGIN
64
+ INSERT OR IGNORE INTO consolidation_vector_jobs SELECT r.domain,r.rid FROM revisions r
65
+ WHERE r.domain=NEW.domain AND r.id=NEW.id AND r.rev=NEW.rev AND r.slot GLOB 'project.topic.*';
66
+ END;
67
+ CREATE TRIGGER IF NOT EXISTS discard_retired_vector_job AFTER UPDATE OF state ON revisions
68
+ WHEN OLD.state='confirmed' AND NEW.state<>'confirmed' BEGIN
69
+ DELETE FROM consolidation_vector_jobs WHERE domain=NEW.domain AND rid=NEW.rid;
70
+ END;
71
+ CREATE INDEX IF NOT EXISTS consolidation_unpin_events ON audit(domain,seq) WHERE event='unpin';
72
+ CREATE TABLE IF NOT EXISTS consolidation_pairs(
73
+ domain TEXT NOT NULL, a INTEGER NOT NULL REFERENCES revisions(rid), b INTEGER NOT NULL REFERENCES revisions(rid),
74
+ state TEXT NOT NULL DEFAULT 'queued', run TEXT, decided INTEGER, kept INTEGER, priority REAL NOT NULL DEFAULT 0,
75
+ PRIMARY KEY(domain,a,b), CHECK(a<b), CHECK(kept IS NULL OR kept IN (a,b))
76
+ );
77
+ CREATE INDEX IF NOT EXISTS consolidation_pending ON consolidation_pairs(domain,state,b,a);
78
+ CREATE INDEX IF NOT EXISTS consolidation_pair_run ON consolidation_pairs(run) WHERE run IS NOT NULL;
79
+ CREATE TABLE IF NOT EXISTS consolidation_runs(
80
+ token TEXT PRIMARY KEY, domain TEXT NOT NULL, day INTEGER NOT NULL, started INTEGER NOT NULL,
81
+ generation INTEGER NOT NULL, memory_generation INTEGER NOT NULL, finished INTEGER, outcome TEXT
82
+ );
83
+ CREATE INDEX IF NOT EXISTS consolidation_day ON consolidation_runs(day);
84
+ CREATE INDEX IF NOT EXISTS consolidation_domain_start ON consolidation_runs(domain,started);
85
+ CREATE INDEX IF NOT EXISTS consolidation_changes ON revisions(domain,rid) WHERE state='confirmed' AND slot GLOB 'project.topic.*';
86
+ CREATE TRIGGER IF NOT EXISTS remove_retired_consolidation AFTER UPDATE OF state ON revisions
87
+ WHEN OLD.state='confirmed' AND NEW.state<>'confirmed' BEGIN
88
+ DELETE FROM consolidation_pairs WHERE domain=NEW.domain AND (a=NEW.rid OR b=NEW.rid) AND state NOT IN ('accepted','dismissed');
89
+ END;
90
+ CREATE TRIGGER IF NOT EXISTS remove_redacted_consolidation AFTER UPDATE OF type ON evidence
91
+ WHEN OLD.type='user_quote' AND NEW.type<>'user_quote' BEGIN
92
+ DELETE FROM consolidation_pairs WHERE domain=NEW.domain AND state NOT IN ('accepted','dismissed')
93
+ AND (SELECT rid FROM revisions WHERE domain=NEW.domain AND id=NEW.id AND rev=NEW.rev) IN (a,b);
94
+ END;
95
+ `;
96
+ export class ConsolidationStore {
97
+ db;
98
+ ops;
99
+ constructor(db, ops) {
100
+ this.db = db;
101
+ this.ops = ops;
102
+ this.ops.transaction(() => {
103
+ if (db.prepare("SELECT 1 FROM pragma_table_info('consolidation_settings') WHERE name='budget'").get()) {
104
+ db.exec(`ALTER TABLE consolidation_settings DROP COLUMN budget;
105
+ ALTER TABLE consolidation_runs DROP COLUMN reserved;
106
+ ALTER TABLE consolidation_runs DROP COLUMN actual;`);
107
+ }
108
+ db.exec(schema);
109
+ if (!db.prepare("SELECT 1 FROM pragma_table_info('consolidation_pairs') WHERE name='priority'").get()) {
110
+ db.exec(`ALTER TABLE consolidation_pairs ADD COLUMN priority REAL NOT NULL DEFAULT 0;
111
+ UPDATE consolidation_scans SET cursor=-1;`);
112
+ }
113
+ });
114
+ }
115
+ settings() {
116
+ return this.db.prepare('SELECT enabled,generation FROM consolidation_settings WHERE singleton=1').get();
117
+ }
118
+ status() {
119
+ const now = Date.now();
120
+ const settings = this.settings();
121
+ const last = this.db.prepare(`SELECT COALESCE(finished,started+?) AS at,COALESCE(outcome,'failed') AS outcome
122
+ FROM consolidation_runs WHERE finished IS NOT NULL OR started<=? ORDER BY at DESC,rowid DESC LIMIT 1`).get(leaseMs, now - leaseMs);
123
+ const checked = this.db.prepare('SELECT max(checked) AS at FROM consolidation_scans').get()?.at;
124
+ return { enabled: Boolean(settings.enabled),
125
+ lastScanAt: checked == null ? null : Number(checked),
126
+ lastRun: last ? { at: Number(last.at), outcome: last.outcome } : null };
127
+ }
128
+ configure(change) {
129
+ if (typeof change?.enabled !== 'boolean')
130
+ throw new StoreError('invalid_input');
131
+ return this.ops.transaction(() => {
132
+ if (this.ops.generation() === undefined)
133
+ throw new StoreError('memory_disabled');
134
+ const enabled = Number(change.enabled);
135
+ this.db.prepare('UPDATE consolidation_settings SET enabled=?,generation=generation+1 WHERE singleton=1 AND enabled<>?')
136
+ .run(enabled, enabled);
137
+ return this.status();
138
+ });
139
+ }
140
+ byRid(domain, rid) {
141
+ return candidate(this.db.prepare(`SELECT ${columns} FROM revisions r ${joins}
142
+ WHERE r.domain=? AND r.rid=? AND ${eligible}`).get(domain, rid));
143
+ }
144
+ byRef(domain, ref) {
145
+ return candidate(this.db.prepare(`SELECT ${columns} FROM revisions r ${joins}
146
+ WHERE r.domain=? AND r.id=? AND r.rev=? AND ${eligible}`).get(domain, ref.id, ref.rev));
147
+ }
148
+ available(domain, now) {
149
+ const settings = this.settings();
150
+ if (!settings.enabled || this.ops.generation() === undefined || domain === 'profile:personal')
151
+ return false;
152
+ return !this.db.prepare('SELECT 1 FROM consolidation_runs WHERE domain=? AND started>? LIMIT 1').get(domain, now - intervalMs);
153
+ }
154
+ scan(domain, now) {
155
+ const cursor = Number(this.db.prepare('SELECT cursor FROM consolidation_scans WHERE domain=?').get(domain)?.cursor ?? -1);
156
+ const high = Number(this.db.prepare(`SELECT max(rid) AS rid FROM revisions
157
+ WHERE domain=? AND state='confirmed' AND slot GLOB 'project.topic.*'`).get(domain)?.rid ?? 0);
158
+ // Unpinning keeps the revision number. Its durable audit receipt also covers heads
159
+ // unpinned before this cursor existed or by another process using the same profile.
160
+ const unpins = this.db.prepare(`SELECT seq,memory,rev FROM audit WHERE domain=? AND event='unpin'
161
+ AND seq>COALESCE((SELECT cursor FROM consolidation_unpin_scans WHERE domain=?),0)
162
+ ORDER BY seq LIMIT ?`).all(domain, domain, pageSize);
163
+ if (high <= cursor && !unpins.length)
164
+ return;
165
+ const changes = this.db.prepare(`SELECT ${columns} FROM revisions r ${joins}
166
+ WHERE r.domain=? AND r.rid>? AND r.rid<=? AND ${eligible} ORDER BY r.rid LIMIT ?`).all(domain, cursor, high, pageSize);
167
+ const partners = this.db.prepare(`SELECT ${columns} FROM memory_fts CROSS JOIN revisions r ON r.rid=memory_fts.rowid ${joins}
168
+ WHERE memory_fts MATCH ? AND r.domain=? AND r.rid<=? AND json_extract(e.source,'$.sessionId')<>?
169
+ AND ${eligible} ORDER BY rank,r.rid LIMIT 32`);
170
+ const vectorJob = this.db.prepare(`INSERT OR IGNORE INTO consolidation_vector_jobs
171
+ SELECT r.domain,r.rid FROM revisions r JOIN memory_vectors v USING(domain,id,rev)
172
+ WHERE r.domain=? AND r.rid=? AND v.model GLOB '*/passage-0'`);
173
+ const queuePartners = (head, throughRid) => {
174
+ vectorJob.run(domain, head.rid);
175
+ const terms = [...new Set([...head.words, ...head.labels.flatMap(indexWords)])];
176
+ if (!terms.length)
177
+ return;
178
+ let added = 0;
179
+ for (const hit of partners.iterate('words:(' + terms.join(' OR ') + ')', domain, throughRid, head.session)) {
180
+ const other = candidate(hit);
181
+ if (!other || !comparable(head, other))
182
+ continue;
183
+ this.queuePair(domain, head.rid, other.rid, lexicalSimilarity(head, other));
184
+ // Bound noisy common aliases. SQLite orders partners by lexical relevance.
185
+ if (++added === 8)
186
+ break;
187
+ }
188
+ };
189
+ for (const row of changes) {
190
+ const head = candidate(row);
191
+ if (head)
192
+ queuePartners(head, head.rid - 1);
193
+ }
194
+ const rechecked = new Set();
195
+ for (const event of unpins) {
196
+ const head = this.byRef(domain, { id: String(event.memory), rev: Number(event.rev) });
197
+ // Newer heads will visit this one in their ordinary scan. Recheck older and
198
+ // newer partners which the revision cursor has already passed.
199
+ if (!head || head.rid > cursor || rechecked.has(head.rid))
200
+ continue;
201
+ rechecked.add(head.rid);
202
+ queuePartners(head, cursor);
203
+ }
204
+ if (unpins.length)
205
+ this.db.prepare(`INSERT INTO consolidation_unpin_scans(domain,cursor) VALUES(?,?)
206
+ ON CONFLICT(domain) DO UPDATE SET cursor=excluded.cursor`).run(domain, unpins.at(-1).seq);
207
+ const watermark = changes.length < pageSize ? high : Number(changes.at(-1).rid);
208
+ this.db.prepare(`INSERT INTO consolidation_scans VALUES(?,?,?) ON CONFLICT(domain) DO UPDATE
209
+ SET cursor=max(cursor,excluded.cursor),checked=excluded.checked`).run(domain, watermark, now);
210
+ }
211
+ queuePair(domain, a, b, priority) {
212
+ this.db.prepare(`INSERT INTO consolidation_pairs(domain,a,b,priority) VALUES(?,?,?,?)
213
+ ON CONFLICT(domain,a,b) DO UPDATE SET priority=max(priority,excluded.priority) WHERE state='queued'`)
214
+ .run(domain, Math.min(a, b), Math.max(a, b), priority);
215
+ }
216
+ scanVectors(domain) {
217
+ const jobs = this.db.prepare('SELECT rid FROM consolidation_vector_jobs WHERE domain=? ORDER BY rid LIMIT 4').all(domain);
218
+ if (!jobs.length)
219
+ return;
220
+ const models = modelLanguages.map(lang => encoderId(lang) + '/passage-0');
221
+ const vectors = this.db.prepare(`SELECT r.rid,v.dimensions,v.vector FROM memory_vectors v
222
+ JOIN revisions r USING(domain,id,rev) ${joins}
223
+ WHERE v.domain=? AND v.model=? AND v.model GLOB '*/passage-0' AND r.rid<>? AND ${eligible}
224
+ AND json_extract(e.source,'$.sessionId')<>?
225
+ AND json_extract(r.payload,'$.hard','$.guidance')=?`);
226
+ for (const { rid } of jobs) {
227
+ const head = this.byRid(domain, Number(rid));
228
+ if (head) {
229
+ const passages = this.db.prepare(`SELECT model,dimensions,vector FROM memory_vectors
230
+ WHERE domain=? AND id=? AND rev=? AND model IN (?,?)`).all(domain, head.item.id, head.item.rev, ...models);
231
+ for (const passage of passages) {
232
+ const q = storedVector(passage);
233
+ if (!q)
234
+ continue;
235
+ const best = [];
236
+ for (const other of vectors.iterate(domain, passage.model, rid, head.session, head.constraints)) {
237
+ const v = storedVector(other);
238
+ if (!v || v.length !== q.length)
239
+ continue;
240
+ const score = v.reduce((sum, value, i) => sum + value * q[i], 0);
241
+ if (score < 0.65 || (best.length === 8 && score <= best[7].score))
242
+ continue;
243
+ best.push({ rid: Number(other.rid), score });
244
+ best.sort((a, b) => b.score - a.score || a.rid - b.rid);
245
+ if (best.length > 8)
246
+ best.pop();
247
+ }
248
+ for (const hit of best)
249
+ this.queuePair(domain, Number(rid), hit.rid, hit.score);
250
+ }
251
+ }
252
+ this.db.prepare('DELETE FROM consolidation_vector_jobs WHERE domain=? AND rid=?').run(domain, rid);
253
+ }
254
+ }
255
+ next(domain, visible = () => true) {
256
+ const now = Date.now();
257
+ if (!this.available(domain, now))
258
+ return;
259
+ const scanned = this.ops.transaction(() => {
260
+ if (!this.available(domain, now))
261
+ return false;
262
+ const cutoff = Math.floor(now / dayMs) - 30;
263
+ // Decisions belong to immutable revisions. Keep the latest run for the settings screen.
264
+ this.db.prepare(`UPDATE consolidation_pairs SET state='queued',run=NULL
265
+ WHERE state IN ('failed','stale','running') AND run IN (SELECT token FROM consolidation_runs WHERE day<?)`).run(cutoff);
266
+ this.db.prepare(`DELETE FROM consolidation_runs WHERE day<? AND token<>(
267
+ SELECT token FROM consolidation_runs ORDER BY started DESC LIMIT 1)`).run(cutoff);
268
+ this.scan(domain, now);
269
+ this.scanVectors(domain);
270
+ return true;
271
+ });
272
+ if (!scanned)
273
+ return;
274
+ const pending = this.db.prepare(`SELECT p.a,p.b FROM consolidation_pairs p LEFT JOIN consolidation_runs t ON p.run=t.token
275
+ WHERE p.domain=? AND (p.state='queued' OR (p.state IN ('failed','stale','running') AND t.day<?))
276
+ ORDER BY p.state='queued' DESC,p.priority DESC,p.b,p.a`);
277
+ for (const row of pending.iterate(domain, Math.floor(now / dayMs))) {
278
+ const left = this.byRid(domain, Number(row.a)), right = this.byRid(domain, Number(row.b));
279
+ if (!left || !right || !comparable(left, right) || !visible(left.item) || !visible(right.item))
280
+ continue;
281
+ return { left: left.item, right: right.item };
282
+ }
283
+ }
284
+ reserve(domain, pair) {
285
+ return this.ops.transaction(() => {
286
+ const now = Date.now();
287
+ if (!this.available(domain, now))
288
+ return;
289
+ const left = this.byRef(domain, pair.left), right = this.byRef(domain, pair.right);
290
+ if (!left || !right || !comparable(left, right))
291
+ return;
292
+ const day = Math.floor(now / dayMs);
293
+ const token = randomUUID();
294
+ const changed = this.db.prepare(`UPDATE consolidation_pairs SET state='running',run=?
295
+ WHERE domain=? AND a=? AND b=? AND (state='queued' OR (state IN ('failed','stale','running') AND
296
+ run IN (SELECT token FROM consolidation_runs WHERE day<?)))`).run(token, domain, left.rid, right.rid, day);
297
+ if (!changed.changes)
298
+ return;
299
+ this.db.prepare(`INSERT INTO consolidation_runs(token,domain,day,started,generation,memory_generation)
300
+ VALUES(?,?,?,?,?,?)`).run(token, domain, day, now, this.settings().generation, this.ops.generation());
301
+ return { domain, token };
302
+ });
303
+ }
304
+ current(lease) {
305
+ const now = Date.now(), settings = this.settings(), generation = this.ops.generation();
306
+ if (!settings.enabled || generation === undefined)
307
+ return false;
308
+ const p = this.db.prepare(`SELECT p.a,p.b FROM consolidation_pairs p JOIN consolidation_runs t ON t.token=p.run
309
+ WHERE p.domain=? AND p.run=? AND p.state='running' AND t.finished IS NULL AND t.started>?
310
+ AND t.generation=? AND t.memory_generation=?`).get(lease.domain, lease.token, now - leaseMs, settings.generation, generation);
311
+ if (!p)
312
+ return false;
313
+ const left = this.byRid(lease.domain, Number(p.a)), right = this.byRid(lease.domain, Number(p.b));
314
+ return Boolean(left && right && comparable(left, right));
315
+ }
316
+ finish(lease, outcome) {
317
+ if (!['duplicate', 'distinct', 'failed', 'stale'].includes(outcome))
318
+ throw new StoreError('invalid_input');
319
+ return this.ops.transaction(() => {
320
+ if (!this.current(lease))
321
+ outcome = 'stale';
322
+ const settled = this.db.prepare(`UPDATE consolidation_runs SET finished=?,outcome=?
323
+ WHERE token=? AND domain=? AND finished IS NULL`).run(Date.now(), outcome, lease.token, lease.domain);
324
+ if (!settled.changes)
325
+ return false;
326
+ this.db.prepare(`UPDATE consolidation_pairs SET state=? WHERE run=? AND domain=? AND state='running'`)
327
+ .run(outcome, lease.token, lease.domain);
328
+ return true;
329
+ });
330
+ }
331
+ suggestions(domain) {
332
+ const result = [];
333
+ for (const row of this.db.prepare("SELECT a,b FROM consolidation_pairs WHERE domain=? AND state='duplicate' ORDER BY b,a").iterate(domain)) {
334
+ const left = this.byRid(domain, Number(row.a)), right = this.byRid(domain, Number(row.b));
335
+ if (left && right && comparable(left, right))
336
+ result.push({ left: { id: left.item.id, rev: left.item.rev }, right: { id: right.item.id, rev: right.item.rev } });
337
+ }
338
+ return result;
339
+ }
340
+ decide(domain, a, b, keep, sessionId) {
341
+ return this.ops.transaction(() => {
342
+ const left = this.byRef(domain, a), right = this.byRef(domain, b);
343
+ if (!left || !right || !comparable(left, right))
344
+ throw new StoreError('conflict');
345
+ if (keep && ![a, b].some(r => r.id === keep.id && r.rev === keep.rev))
346
+ throw new StoreError('invalid_input');
347
+ const kept = keep ? (keep.id === a.id ? left.rid : right.rid) : null;
348
+ const decision = this.db.prepare(`UPDATE consolidation_pairs SET state=?,decided=?,kept=?
349
+ WHERE domain=? AND a=? AND b=? AND state='duplicate'`).run(keep ? 'accepted' : 'dismissed', Date.now(), kept, domain, Math.min(left.rid, right.rid), Math.max(left.rid, right.rid));
350
+ if (!decision.changes)
351
+ throw new StoreError('conflict');
352
+ if (keep)
353
+ this.ops.revoke(domain, keep.id === a.id ? b : a, sessionId);
354
+ return { status: keep ? 'accepted' : 'dismissed' };
355
+ });
356
+ }
357
+ }