dsh-memory-bond 0.3.0-beta.0 → 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 (145) hide show
  1. package/CHANGELOG.md +6 -7
  2. package/README.md +125 -91
  3. package/README.zh-CN.md +122 -92
  4. package/SECURITY.md +29 -0
  5. package/dist/audit.js +155 -80
  6. package/dist/automatic.js +10 -2
  7. package/dist/client.js +2035 -0
  8. package/dist/command-scope.js +4 -4
  9. package/dist/commands.js +15 -9
  10. package/dist/consolidation-store.js +87 -20
  11. package/dist/consolidation.js +2 -6
  12. package/dist/domain.js +8 -4
  13. package/dist/encoder.js +46 -5
  14. package/dist/file-import-store.js +120 -0
  15. package/dist/file-import.js +265 -0
  16. package/dist/foreground-attempts.js +91 -0
  17. package/dist/guidance.js +133 -92
  18. package/dist/host.js +13 -0
  19. package/dist/index-policy.js +91 -48
  20. package/dist/index.js +102 -40
  21. package/dist/knowledge-hooks.js +70 -27
  22. package/dist/knowledge.js +2 -3
  23. package/dist/maintenance-store.js +38 -4
  24. package/dist/maintenance.js +29 -5
  25. package/dist/personal.js +37 -0
  26. package/dist/policy.js +45 -47
  27. package/dist/prompt-copy.js +93 -0
  28. package/dist/proposal-receipts.js +70 -0
  29. package/dist/proposal-review.js +656 -0
  30. package/dist/propose-contract.js +32 -36
  31. package/dist/question-answers.js +86 -29
  32. package/dist/retrieval.js +25 -8
  33. package/dist/scope-narrowing.js +49 -0
  34. package/dist/search-index.js +93 -13
  35. package/dist/semantic.js +69 -207
  36. package/dist/service.js +633 -204
  37. package/dist/sharing.js +7 -13
  38. package/dist/sources.js +28 -3
  39. package/dist/store.js +432 -96
  40. package/dist/tool-experience.js +87 -0
  41. package/dist/turn-review-store.js +83 -16
  42. package/dist/turn-review.js +155 -59
  43. package/dist/ui.js +128 -26
  44. package/dist/vector-index.js +69 -33
  45. package/docs/architecture.zh-CN.md +52 -0
  46. package/docs/benchmark.zh-CN.md +60 -0
  47. package/docs/benchmarks/repository-tasks.json +5355 -0
  48. package/docs/images/bond-memory-principle-en.svg +644 -0
  49. package/docs/images/bond-memory-principle-zh.svg +644 -0
  50. package/docs/images/bond-memory-principle.drawio +644 -0
  51. package/docs/images/memory-settings-en.png +0 -0
  52. package/docs/images/memory-settings-zh.png +0 -0
  53. package/docs/images/memory-turn-recalled-en.png +0 -0
  54. package/docs/images/memory-turn-recalled-zh.png +0 -0
  55. package/docs/images/memory-turn-saved-en.png +0 -0
  56. package/docs/images/memory-turn-saved-zh.png +0 -0
  57. package/docs/media/memory-bond-name-en.gif +0 -0
  58. package/docs/media/memory-bond-name-en.mp4 +0 -0
  59. package/docs/media/memory-bond-name-zh.gif +0 -0
  60. package/docs/media/memory-bond-name-zh.mp4 +0 -0
  61. package/locale/detail.en.md +5 -1
  62. package/locale/detail.zh.md +5 -1
  63. package/locale/en.json +338 -0
  64. package/locale/zh.json +338 -0
  65. package/native/embeddings/NOTICE.md +2 -2
  66. package/package.json +39 -19
  67. package/scripts/benchmark-bond.mjs +72 -0
  68. package/scripts/benchmark-conditions.mjs +144 -0
  69. package/scripts/benchmark-example.mjs +37 -0
  70. package/scripts/benchmark-scale.mjs +119 -0
  71. package/scripts/benchmark-scenarios.mjs +57 -0
  72. package/scripts/benchmark-tasks.mjs +244 -0
  73. package/src/audit.ts +144 -85
  74. package/src/automatic.ts +12 -2
  75. package/src/command-scope.ts +4 -4
  76. package/src/commands.ts +12 -8
  77. package/src/consolidation-store.ts +80 -18
  78. package/src/consolidation.ts +2 -6
  79. package/src/domain.ts +9 -4
  80. package/src/encoder.ts +46 -6
  81. package/src/file-import-store.ts +139 -0
  82. package/src/file-import.ts +256 -0
  83. package/src/foreground-attempts.ts +97 -0
  84. package/src/guidance.ts +138 -102
  85. package/src/host.ts +22 -2
  86. package/src/index-policy.ts +93 -46
  87. package/src/index.ts +87 -43
  88. package/src/knowledge-hooks.ts +71 -29
  89. package/src/knowledge.ts +2 -3
  90. package/src/maintenance-store.ts +37 -4
  91. package/src/maintenance.ts +25 -5
  92. package/src/personal.ts +36 -0
  93. package/src/policy.ts +55 -52
  94. package/src/prompt-copy.ts +99 -0
  95. package/src/proposal-receipts.ts +59 -0
  96. package/src/proposal-review.ts +614 -0
  97. package/src/propose-contract.ts +31 -35
  98. package/src/question-answers.ts +99 -29
  99. package/src/retrieval.ts +26 -9
  100. package/src/scope-narrowing.ts +58 -0
  101. package/src/search-index.ts +94 -14
  102. package/src/semantic.ts +67 -188
  103. package/src/service.ts +595 -210
  104. package/src/sharing.ts +7 -14
  105. package/src/sources.ts +26 -4
  106. package/src/store.ts +434 -97
  107. package/src/tool-experience.ts +93 -0
  108. package/src/turn-review-store.ts +86 -15
  109. package/src/turn-review.ts +142 -60
  110. package/src/ui.ts +122 -27
  111. package/src/vector-index.ts +57 -29
  112. package/client/index.js +0 -1186
  113. package/design/dsh-memory-plugin-design.md +0 -46
  114. package/design/dsh-memory-plugin-evaluation.md +0 -135
  115. package/design/evaluations/locomo-conv-26-2026-12-03.json +0 -252
  116. package/design/evaluations/locomo-conv-26-paired-2026-12-03.json +0 -549
  117. package/design/evaluations/locomo-conv-26-write-replay-2026-12-03.json +0 -289
  118. package/design/evaluations/project-memory-tasks-2026-12-03.json +0 -1059
  119. package/design/memory-lifecycle-consolidation.excalidraw +0 -1212
  120. package/design/memory-lifecycle-consolidation.mobile.excalidraw +0 -1083
  121. package/design/memory-lifecycle-consolidation.mobile.svg +0 -2
  122. package/design/memory-lifecycle-consolidation.mobile.zh-CN.excalidraw +0 -1083
  123. package/design/memory-lifecycle-consolidation.mobile.zh-CN.svg +0 -94
  124. package/design/memory-lifecycle-consolidation.svg +0 -2
  125. package/design/memory-lifecycle-consolidation.zh-CN.excalidraw +0 -1212
  126. package/design/memory-lifecycle-consolidation.zh-CN.svg +0 -94
  127. package/design/memory-lifecycle.excalidraw +0 -2105
  128. package/design/memory-lifecycle.mobile.excalidraw +0 -1896
  129. package/design/memory-lifecycle.mobile.svg +0 -95
  130. package/design/memory-lifecycle.mobile.zh-CN.excalidraw +0 -1896
  131. package/design/memory-lifecycle.mobile.zh-CN.svg +0 -97
  132. package/design/memory-lifecycle.svg +0 -95
  133. package/design/memory-lifecycle.zh-CN.excalidraw +0 -2105
  134. package/design/memory-lifecycle.zh-CN.svg +0 -97
  135. package/native/embeddings/LICENSE +0 -21
  136. package/native/embeddings/en/model.onnx +0 -4
  137. package/native/embeddings/en/vocab.txt +0 -30522
  138. package/native/embeddings/runtime/LICENSE +0 -21
  139. package/native/embeddings/runtime/ThirdPartyNotices.txt +0 -6156
  140. package/native/embeddings/runtime/ort-wasm-simd-threaded.mjs +0 -70
  141. package/native/embeddings/runtime/ort-wasm-simd-threaded.wasm +0 -0
  142. package/native/embeddings/runtime/ort.wasm.min.mjs +0 -7
  143. package/native/embeddings/worker.mjs +0 -97
  144. package/native/embeddings/zh/model.onnx +0 -0
  145. package/native/embeddings/zh/vocab.txt +0 -21128
@@ -1,8 +1,10 @@
1
+ import { prompts } from "./prompt-copy.js";
1
2
  import { randomUUID } from 'node:crypto';
2
- import { relative } from 'node:path';
3
3
  import { bashScope } from "./command-scope.js";
4
+ import { originalBashCall } from "./tool-experience.js";
5
+ import { projectRelative } from "./domain.js";
4
6
  import { isKnowledge, knowledgeValid, recordSuccess, runbookBasis } from "./knowledge.js";
5
- import { messageText, } from "./host.js";
7
+ import { messageText, registerConditionalTool, } from "./host.js";
6
8
  const active = new WeakMap();
7
9
  const ttl = 5 * 60_000;
8
10
  function table(memory, agent) {
@@ -44,7 +46,7 @@ function issue(memory, agent, d, position, rows) {
44
46
  content: [
45
47
  {
46
48
  type: 'text',
47
- text: '如需查阅本次相关的项目知识,可调用 project_memory_ticket,参数 ticket 为 ' + ticket + '。',
49
+ text: prompts[memory.promptLanguage(agent)].ticketOffer + ticket,
48
50
  },
49
51
  ],
50
52
  };
@@ -80,7 +82,7 @@ export function readTicket(memory, agent, key, call, lookup) {
80
82
  ];
81
83
  });
82
84
  if (call && lookup)
83
- lookup(agent, d, call, rows.map(({ id, rev }) => ({ id, rev })));
85
+ lookup(agent, d, call, rows);
84
86
  memory.store.audit(d.id, agent.id, 'ticket_read', { call, outcome: rows.length });
85
87
  return { items: rows };
86
88
  }
@@ -108,7 +110,7 @@ function invocation(memory, exec) {
108
110
  d,
109
111
  command: scope.command,
110
112
  cwd: scope.cwd,
111
- workdir: relative(d.root, scope.cwd) || '.',
113
+ workdir: projectRelative(d.root, scope.cwd) || '.',
112
114
  revisions: [],
113
115
  episodes: [],
114
116
  };
@@ -129,19 +131,24 @@ function exitStatus(result, invocation) {
129
131
  return;
130
132
  return Number(value.exitCode);
131
133
  }
132
- function guardMatches(row, item) {
134
+ function guardMatches(row, item, anchors) {
133
135
  if (!isKnowledge(row) ||
134
136
  row.kind !== 'guard' ||
135
137
  !['user_command', 'owner_card'].includes(String(row.channel)))
136
138
  return false;
137
139
  const match = row.knowledge?.match;
138
- return match?.command === item.command && match.workdir === item.workdir && knowledgeValid(item.d, row).ok;
140
+ return match?.command === item.command && match.workdir === item.workdir && knowledgeValid(item.d, row, anchors).ok;
139
141
  }
140
- export function registerKnowledge(ctx, memory, lookup) {
142
+ export function registerKnowledge(ctx, memory, lookup, receipts) {
141
143
  // Guard is called only after native ask/cancel/deny resolution. Returning undefined can never allow a denied call.
142
- const tools = ctx.tools;
143
144
  const attempts = new WeakMap();
144
145
  ctx.on('session/event', (session, event) => {
146
+ if (event.type === 'turn/end') {
147
+ const agent = ctx.agents.get(session.id);
148
+ if (agent?.session === session)
149
+ memory.bashEvidence.endTurn(agent);
150
+ return;
151
+ }
145
152
  if (event.type !== 'tool/call' ||
146
153
  event.data.name !== 'bash' ||
147
154
  !event.data.arguments ||
@@ -161,8 +168,9 @@ export function registerKnowledge(ctx, memory, lookup) {
161
168
  if (!item)
162
169
  return;
163
170
  // A downstream ask/cancel/deny may prevent the monotonic guard from ever running.
164
- for (const row of memory.store.list(item.d.id)) {
165
- if (guardMatches(row, item))
171
+ const anchors = new Map();
172
+ for (const row of memory.store.commandCandidates(item.d.id, item.command, item.workdir, 'attempt')) {
173
+ if (guardMatches(row, item, anchors))
166
174
  memory.store.audit(item.d.id, agent.id, 'guard_attempt', {
167
175
  id: row.id,
168
176
  rev: row.rev,
@@ -171,7 +179,7 @@ export function registerKnowledge(ctx, memory, lookup) {
171
179
  });
172
180
  }
173
181
  });
174
- tools.guard((exec) => {
182
+ ctx.tools.guard((exec) => {
175
183
  const item = invocation(memory, exec);
176
184
  if (!item || !exec.agent)
177
185
  return;
@@ -181,27 +189,45 @@ export function registerKnowledge(ctx, memory, lookup) {
181
189
  calls.set(exec.callId, item);
182
190
  if (calls.size > 128)
183
191
  calls.delete(calls.keys().next().value);
192
+ if (exec.agent.session.header.origin !== 'subagent') {
193
+ try {
194
+ memory.rootDomain(exec.agent, true);
195
+ const call = originalBashCall(exec.agent, exec.callId);
196
+ if (call)
197
+ item.evidence = { ...call, storeId: memory.storeId(exec.agent.session) };
198
+ }
199
+ catch { /* A read-only session cannot offer a memory proposal. */ }
200
+ }
184
201
  try {
185
202
  const runbookMatches = [];
186
- for (const row of memory.store.list(item.d.id)) {
203
+ const anchors = new Map();
204
+ for (const row of memory.store.commandCandidates(item.d.id, item.command, item.workdir, 'guard')) {
187
205
  if (!isKnowledge(row))
188
206
  continue;
189
207
  if (row.kind === 'runbook' &&
190
208
  row.knowledge?.steps?.verify === item.command &&
191
209
  row.knowledge.steps.workdir === item.workdir &&
192
- knowledgeValid(item.d, row).ok) {
210
+ knowledgeValid(item.d, row, anchors).ok) {
193
211
  runbookMatches.push({ ref: { id: row.id, rev: row.rev }, basis: runbookBasis(row) });
194
212
  }
195
213
  if (row.kind === 'episode' &&
196
214
  row.knowledge?.failure?.command === item.command &&
197
215
  row.knowledge.failure.workdir === item.workdir &&
198
- knowledgeValid(item.d, row).ok)
216
+ knowledgeValid(item.d, row, anchors).ok)
199
217
  item.episodes.push({ id: row.id, rev: row.rev });
200
- if (!guardMatches(row, item))
218
+ if (!guardMatches(row, item, anchors))
201
219
  continue;
202
220
  const record = { id: row.id, rev: row.rev, call: exec.callId };
203
- memory.store.audit(item.d.id, exec.agent.id, 'guard_block', record);
204
- return '用户确认的项目禁令 [' + row.id + '@' + row.rev + ']:' + row.action;
221
+ const reason = prompts[memory.promptLanguage(exec.agent)].guard + ' [' + row.id + '@' + row.rev + '] ' + row.action;
222
+ try {
223
+ memory.store.audit(item.d.id, exec.agent.id, 'guard_block', record);
224
+ receipts?.blocked(exec.agent, item.d, exec.callId, { id: row.id, rev: row.rev }, reason);
225
+ }
226
+ catch (error) {
227
+ // Receipt persistence cannot turn a denial into permission to dispatch.
228
+ ctx.logger.warn('项目记忆无法记录本次守卫回执:' + String(error));
229
+ }
230
+ return reason;
205
231
  }
206
232
  // A (verify, workdir) signature shared by more than one runbook cannot be
207
233
  // attributed to either from one real run, so this run credits neither.
@@ -239,13 +265,14 @@ export function registerKnowledge(ctx, memory, lookup) {
239
265
  if (code === undefined || code === 0)
240
266
  return decision;
241
267
  try {
242
- const rows = memory.store.list(item.d.id).filter((row) => {
268
+ const anchors = new Map();
269
+ const rows = memory.store.commandCandidates(item.d.id, item.command, item.workdir, 'failure').filter((row) => {
243
270
  if (!isKnowledge(row) || ['episode', 'guard'].includes(row.kind))
244
271
  return false;
245
272
  const trigger = row.knowledge?.trigger;
246
273
  return (trigger?.command === item.command &&
247
274
  trigger.workdir === item.workdir &&
248
- knowledgeValid(item.d, row).ok);
275
+ knowledgeValid(item.d, row, anchors).ok);
249
276
  });
250
277
  const message = issue(memory, exec.agent, item.d, 'post:' + exec.callId, rows);
251
278
  return message
@@ -267,6 +294,21 @@ export function registerKnowledge(ctx, memory, lookup) {
267
294
  const code = item && exitStatus(result, item);
268
295
  if (!item || code === undefined || item.rawExit !== code)
269
296
  return;
297
+ try {
298
+ receipts?.executed(exec, item.command, item.cwd, code);
299
+ }
300
+ catch (error) {
301
+ ctx.logger.warn('项目记忆无法记录本次执行回执:' + String(error));
302
+ }
303
+ if (item.evidence) {
304
+ try {
305
+ const domain = memory.rootDomain(exec.agent, true);
306
+ memory.bashEvidence.observe(exec.agent, exec.callId, {
307
+ ...item.evidence, domain, generation: item.generation, command: item.command, cwd: item.cwd, workdir: item.workdir, exitCode: code,
308
+ });
309
+ }
310
+ catch { /* A read-only session cannot offer a memory proposal. */ }
311
+ }
270
312
  if (code !== 0) {
271
313
  const delegated = exec.agent.session.header.origin === 'subagent';
272
314
  const root = delegated ? ctx.get('subagents')?.rootOf(exec.agent) : exec.agent;
@@ -313,20 +355,21 @@ export function registerKnowledge(ctx, memory, lookup) {
313
355
  return decision;
314
356
  if (memory.assistantGeneration() === undefined)
315
357
  return decision;
316
- const direct = decision.messages.filter((m) => m.source?.kind === 'user');
358
+ const direct = decision.messages.filter(m => m.source?.kind === 'user').map(messageText);
317
359
  if (!direct.length)
318
360
  return decision;
319
361
  const d = memory.domain(agent);
320
362
  if (!d || d.id === memory.personal.id)
321
363
  return decision;
322
364
  try {
323
- const rows = memory.store.list(d.id).filter((row) => {
365
+ const anchors = new Map();
366
+ const rows = memory.store.messageCandidates(d.id, direct).filter((row) => {
324
367
  if (!isKnowledge(row) || ['episode', 'guard'].includes(row.kind))
325
368
  return false;
326
369
  const trigger = row.knowledge?.trigger?.text;
327
370
  return (!!trigger &&
328
- direct.some((message) => messageText(message).includes(trigger)) &&
329
- knowledgeValid(d, row).ok);
371
+ direct.some(message => message.includes(trigger)) &&
372
+ knowledgeValid(d, row, anchors).ok);
330
373
  });
331
374
  const hint = issue(memory, agent, d, 'pre:' + turn + '/' + step, rows);
332
375
  return hint ? { ...decision, messages: [...decision.messages, hint] } : decision;
@@ -338,9 +381,9 @@ export function registerKnowledge(ctx, memory, lookup) {
338
381
  return decision;
339
382
  }
340
383
  }, { prepend: true });
341
- ctx.tools.register({
384
+ registerConditionalTool(ctx, {
342
385
  name: 'project_memory_ticket',
343
- description: '按本步票据显式查阅仍然适用的项目知识。',
386
+ description: prompts[memory.promptLanguage()].ticket,
344
387
  parameters: {
345
388
  type: 'object',
346
389
  properties: { ticket: { type: 'string' } },
@@ -351,5 +394,5 @@ export function registerKnowledge(ctx, memory, lookup) {
351
394
  async execute(args, exec) {
352
395
  return JSON.stringify(exec.agent ? readTicket(memory, exec.agent, args.ticket, exec.callId, lookup) : { items: [] });
353
396
  },
354
- }, { when: () => memory.assistantGeneration() !== undefined });
397
+ }, () => memory.assistantGeneration() !== undefined);
355
398
  }
package/dist/knowledge.js CHANGED
@@ -1,8 +1,7 @@
1
1
  import { createHash } from 'node:crypto';
2
2
  import { closeSync, constants, fstatSync, openSync, readSync, statSync } from 'node:fs';
3
- import { relative } from 'node:path';
4
3
  import { bashScope, literalBashCommand } from "./command-scope.js";
5
- import { cleanRelative, projectPath, scopedPath } from "./domain.js";
4
+ import { cleanRelative, projectPath, scopedPath, projectRelative } from "./domain.js";
6
5
  import { StoreError } from "./store.js";
7
6
  import { isSemanticSlot } from "./personal.js";
8
7
  import { notifyUI } from "./ui.js";
@@ -89,7 +88,7 @@ function workdir(domain, value, base) {
89
88
  const path = scopedPath(domain, cleanRelative(field(value ?? '.', 768)), base);
90
89
  if (!statSync(path).isDirectory())
91
90
  invalid('invalid_workdir');
92
- return relative(domain.root, path) || '.';
91
+ return projectRelative(domain.root, path) || '.';
93
92
  }
94
93
  catch {
95
94
  return invalid('invalid_workdir');
@@ -6,6 +6,9 @@ import { StoreError } from "./store.js";
6
6
  import { episodeBodyDays } from "./maintenance-episodes.js";
7
7
  import { isMemorySlot } from "./personal.js";
8
8
  import { indexRevision, promptRole } from "./search-index.js";
9
+ // Settled proposal receipts need their event identity. Detailed evidence belongs only to
10
+ // the erasable revision and to managed snapshots that share its deletion policy.
11
+ export const sourceDetailPaths = "'$.toolResult','$.fileImport','$.formSelection','$.scopeClarification'";
9
12
  export const maintenanceSchema = `
10
13
  CREATE TABLE IF NOT EXISTS history_jobs (
11
14
  domain TEXT NOT NULL, stream TEXT NOT NULL, session TEXT NOT NULL, seq INTEGER NOT NULL, kind TEXT NOT NULL,
@@ -72,6 +75,8 @@ export class MaintenanceState {
72
75
  CREATE TABLE IF NOT EXISTS profile_clocks(domain TEXT NOT NULL,slot TEXT NOT NULL,stream TEXT NOT NULL,
73
76
  seq INTEGER NOT NULL,time INTEGER,PRIMARY KEY(domain,slot,stream));
74
77
  CREATE TABLE IF NOT EXISTS fences(domain TEXT NOT NULL,id TEXT NOT NULL,rev INTEGER NOT NULL,PRIMARY KEY(domain,id));
78
+ CREATE TABLE IF NOT EXISTS transferred_revisions(domain TEXT NOT NULL,id TEXT NOT NULL,rev INTEGER NOT NULL,
79
+ PRIMARY KEY(domain,id,rev));
75
80
  CREATE TABLE IF NOT EXISTS suppression_keys(domain TEXT PRIMARY KEY,secret BLOB NOT NULL);
76
81
  CREATE TABLE IF NOT EXISTS purges(domain TEXT NOT NULL,id TEXT NOT NULL,mode TEXT NOT NULL,rev INTEGER NOT NULL,
77
82
  PRIMARY KEY(domain,id,mode));
@@ -268,6 +273,8 @@ export class MaintenanceState {
268
273
  .run(Date.now(), f.domain, f.id, head.rev);
269
274
  changed.add(String(f.domain));
270
275
  }
276
+ for (const row of this.archive.prepare('SELECT domain,id,rev FROM transferred_revisions').iterate())
277
+ this.eraseTransferredRevision(String(row.domain), String(row.id), Number(row.rev));
271
278
  for (const f of this.archive.prepare('SELECT * FROM purges').all()) {
272
279
  const args = [f.domain, f.id, f.rev];
273
280
  if (f.mode === 'signature') {
@@ -306,6 +313,33 @@ export class MaintenanceState {
306
313
  this.ops.bump(domain);
307
314
  }
308
315
  }
316
+ // A scope correction moves the source and wording of exactly one revision. A
317
+ // purge-through fence would also erase unrelated, earlier versions of that ID.
318
+ releaseTransferredRevision(domain, id, rev) {
319
+ this.eraseTransferredRevision(domain, id, rev);
320
+ this.guards.push(() => {
321
+ this.archive.prepare('INSERT OR IGNORE INTO transferred_revisions VALUES(?,?,?)').run(domain, id, rev);
322
+ });
323
+ }
324
+ eraseTransferredRevision(domain, id, rev) {
325
+ const versions = [domain, id, rev];
326
+ const old = this.db.prepare(`SELECT r.batch,r.payload,p.source FROM revisions r JOIN proposals p
327
+ ON p.domain=r.domain AND p.id=r.batch WHERE r.domain=? AND r.id=? AND r.rev=? AND r.state<>'confirmed'`).get(...versions);
328
+ if (!old)
329
+ return;
330
+ if (old.payload !== '{}') {
331
+ this.db.prepare("UPDATE evidence SET quote='',type='receipt',source='{}' WHERE domain=? AND id=? AND rev=?").run(...versions);
332
+ this.db.prepare(`UPDATE revisions SET action='',condition='',paths='[]',slot=NULL,payload='{}',
333
+ proactive=NULL,fingerprint='',retired=NULL WHERE domain=? AND id=? AND rev=?`).run(...versions);
334
+ // retire() already sealed the source clock and replay guards before the move.
335
+ this.db.prepare('DELETE FROM automatic_sources WHERE domain=? AND id=? AND rev=?').run(...versions);
336
+ }
337
+ if (old.source === '{}')
338
+ return;
339
+ this.db.prepare(`UPDATE proposals SET source='{}' WHERE domain=? AND id=? AND NOT EXISTS
340
+ (SELECT 1 FROM revisions WHERE domain=? AND batch=? AND (id<>? OR rev<>?))`)
341
+ .run(domain, old.batch, domain, old.batch, id, rev);
342
+ }
309
343
  forgetSignature(domain, id, rev) {
310
344
  this.db.prepare('DELETE FROM episode_signatures WHERE domain=? AND id=?').run(domain, id);
311
345
  this.purgeThrough(domain, id, 'signature', rev);
@@ -429,11 +463,11 @@ export class MaintenanceState {
429
463
  });
430
464
  }
431
465
  hasRetainedQuote(domain, id) {
432
- const quote = this.db.prepare("SELECT 1 FROM evidence WHERE domain=? AND id=? AND quote<>'' LIMIT 1");
466
+ const quote = this.db.prepare("SELECT 1 FROM evidence WHERE domain=? AND id=? AND (quote<>'' OR type='tool_result') LIMIT 1");
433
467
  if (quote.get(domain, id))
434
468
  return true;
435
469
  return !!this.archive
436
- .prepare("SELECT 1 FROM entries WHERE domain=? AND id=? AND json_extract(rule,'$.user_quote')<>'' LIMIT 1")
470
+ .prepare("SELECT 1 FROM entries WHERE domain=? AND id=? AND (json_extract(rule,'$.user_quote')<>'' OR json_extract(rule,'$.quoteType')='tool_result') LIMIT 1")
437
471
  .get(domain, id);
438
472
  }
439
473
  suppressQuotes(domain, id) {
@@ -553,13 +587,13 @@ export class MaintenanceState {
553
587
  const batch = 'auto-' + randomUUID(), receipt = JSON.stringify({ state: 'confirmed', entries: [{ id: memory, rev }] });
554
588
  this.db
555
589
  .prepare(`INSERT INTO proposals(domain,id,session,turn,source,items,created,rev,epoch,digest,idem,state,receipt)
556
- VALUES(?,?,?,'restore',?,'[]',?,1,?,'',?,'confirmed',?)`)
590
+ VALUES(?,?,?,'restore',json_remove(?,${sourceDetailPaths}),'[]',?,1,?,'',?,'confirmed',?)`)
557
591
  .run(domain, batch, session, JSON.stringify(source), Date.now(), this.ops.epoch(domain), batch, receipt);
558
592
  const saved = this.db
559
593
  .prepare(`INSERT INTO revisions(domain,id,rev,batch,family,slot,action,condition,paths,payload,confirmed,state,fingerprint,proactive)
560
594
  VALUES(?,?,?,?,?,?,?,?,?,?,?,'confirmed',?,?)`)
561
595
  .run(domain, memory, rev, batch, familyId, r.slot ?? null, r.action, r.when, JSON.stringify(r.paths), JSON.stringify(payload), confirmedAt, this.ops.fingerprint(r), promptRole(r));
562
- indexRevision(this.db, saved.lastInsertRowid, r);
596
+ indexRevision(this.db, domain, saved.lastInsertRowid, r);
563
597
  this.db
564
598
  .prepare('INSERT INTO evidence VALUES(?,?,?,?,?,?)')
565
599
  .run(domain, memory, rev, quoteType, user_quote, JSON.stringify(source));
@@ -6,7 +6,8 @@ import { messageText } from "./host.js";
6
6
  import { prepareItems } from "./policy.js";
7
7
  import { ruleFields } from "./service.js";
8
8
  import { loadedGuidance, sourceStore } from "./sources.js";
9
- import { verifiedQuestionAnswers } from "./question-answers.js";
9
+ import { isNativeProposalResult } from "./proposal-receipts.js";
10
+ import { verifiedQuestionForm } from "./question-answers.js";
10
11
  import { StoreError } from "./store.js";
11
12
  import { notifyUI } from "./ui.js";
12
13
  const marker = 'plugin:project-memory/source';
@@ -136,8 +137,12 @@ async function extract(memory, agent, d, source, event, h) {
136
137
  if (!turn)
137
138
  return undefined;
138
139
  const cut = Math.max(h.inheritedEventCount, turn[0]?.seq ?? 0);
139
- if (turn.some(entry => (userMessage(entry, entry.seq) && refusesAutomaticMemory(messageText(entry.data))) ||
140
- (entry.type === 'tool/result' && verifiedQuestionAnswers(turn, cut, entry).some(answer => refusesAutomaticMemory(answer.text)))))
140
+ if (turn.some(entry => {
141
+ if (userMessage(entry, entry.seq))
142
+ return refusesAutomaticMemory(messageText(entry.data));
143
+ const form = entry.type === 'tool/result' ? verifiedQuestionForm(turn, cut, entry) : undefined;
144
+ return form?.refusedBy !== undefined || form?.custom.some(answer => refusesAutomaticMemory(answer.text));
145
+ }))
141
146
  return [];
142
147
  const blocks = [];
143
148
  let offset = 0;
@@ -149,6 +154,25 @@ async function extract(memory, agent, d, source, event, h) {
149
154
  seq: source.seq, text, offset, block });
150
155
  offset += text.length + 1;
151
156
  }
157
+ // A completed write already has an authoritative decision for every proposed
158
+ // item. Its draft labels and wording can differ from the normalized revision.
159
+ // Reconstruct only calls which never received a write decision.
160
+ const calls = new Map(turn.filter(e => e.type === 'tool/call' && e.data.name === 'project_memory_propose')
161
+ .map(e => [e.seq, e]));
162
+ const settled = new Set();
163
+ for (const entry of turn) {
164
+ const message = entry.data.message;
165
+ const call = calls.get(entry.sourceEventSeqs?.[0] ?? -1);
166
+ if (!call?.data.callId || !message?.toolCallId || message.isError || entry.data.error !== undefined ||
167
+ call.data.turn !== entry.data.turn || !isNativeProposalResult(entry, call.seq, call.data.callId, call.data.step))
168
+ continue;
169
+ try {
170
+ const reply = JSON.parse(messageText(message));
171
+ if (['saved', 'partial', 'duplicate', 'skipped'].includes(reply?.status))
172
+ settled.add(message.toolCallId);
173
+ }
174
+ catch { /* An interrupted or unrecognized result is not a completed write. */ }
175
+ }
152
176
  const result = [];
153
177
  const guidance = loadedGuidance(agent.session, d, memory.ctx);
154
178
  for (const entry of turn) {
@@ -156,12 +180,12 @@ async function extract(memory, agent, d, source, event, h) {
156
180
  continue;
157
181
  if (entry.type === 'working-directory/change' || userMessage(entry, entry.seq))
158
182
  break;
159
- if (entry.type !== 'tool/call' || entry.data.name !== 'project_memory_propose' ||
183
+ if (entry.type !== 'tool/call' || entry.data.name !== 'project_memory_propose' || settled.has(entry.data.callId ?? '') ||
160
184
  String(entry.data.turn) !== source.turnId)
161
185
  continue;
162
186
  try {
163
187
  for (const row of parseCandidates(JSON.parse(entry.data.arguments ?? ''))) {
164
- if (row.scope !== 'project' || row.replaces || row.correction || skipsCandidate(row))
188
+ if (row.scope !== 'project' || row.replaces || skipsCandidate(row) || !row.user_quote.includes(row.action))
165
189
  continue;
166
190
  const [draft] = prepareItems(d, { items: [ruleFields(row)] }, blocks, guidance);
167
191
  result.push(semanticDraft(row, draft));
package/dist/personal.js CHANGED
@@ -5,6 +5,43 @@ export function normalizeLabel(label) {
5
5
  export function validLabel(label) {
6
6
  return typeof label === 'string' && label.length <= 80 && !/[\p{Cc}\p{Cf}]/u.test(label) && !!normalizeLabel(label);
7
7
  }
8
+ export const subjectOwners = ['speaker', 'project', 'named', 'unspecified'];
9
+ /** Canonical roles are selected by the model from the utterance. They survive a rename. */
10
+ export function subjectForOwner(owner, proposed) {
11
+ if (owner === 'speaker')
12
+ return 'self';
13
+ if (owner === 'project')
14
+ return 'project';
15
+ return owner === 'named' ? proposed : undefined;
16
+ }
17
+ export function reviewedSubject(owner, proposed, target, explicit = false, named) {
18
+ const role = owner;
19
+ if (!subjectOwners.includes(role))
20
+ return { reason: 'invalid_model_result' };
21
+ let subject = subjectForOwner(role, proposed);
22
+ if (role === 'named') {
23
+ if (!named || !validLabel(named.subject))
24
+ return { reason: 'invalid_model_result' };
25
+ subject = named.subject.trim();
26
+ const label = normalizeLabel(subject);
27
+ if (label === 'self' || label === 'project' || !named.source.some(text => normalizeLabel(text).includes(label)))
28
+ return { reason: 'subject_mismatch' };
29
+ if (target && proposed && normalizeLabel(proposed) !== label) {
30
+ // A candidate's name and the first model's label can differ. The user's own
31
+ // wording must support the alias and the reviewer must cite that wording.
32
+ const quote = named.aliasQuote;
33
+ if (explicit || typeof quote !== 'string' || !quote.trim() || !named.source.some(text => text.includes(quote)) ||
34
+ ![label, normalizeLabel(proposed)].every(name => normalizeLabel(quote).includes(name)))
35
+ return { reason: 'subject_mismatch' };
36
+ }
37
+ }
38
+ if (!target)
39
+ return { subject };
40
+ const retained = normalizeLabel(target.subject ?? '');
41
+ if (normalizeLabel(subject ?? '') === retained)
42
+ return { subject: target.subject };
43
+ return { reason: 'subject_mismatch' };
44
+ }
8
45
  /** Subjects and topics are model-provided labels. Hash a tuple to avoid separator collisions. */
9
46
  export function semanticSlot(scope, topic, subject, context) {
10
47
  if (!validLabel(topic) || (subject !== undefined && !validLabel(subject)))
package/dist/policy.js CHANGED
@@ -1,17 +1,12 @@
1
1
  import { accessSync, constants, existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
2
- import { delimiter, dirname, join, posix, relative } from 'node:path';
3
- import { branchOfCached, cleanRelative, inside, projectPath } from "./domain.js";
2
+ import { delimiter, dirname, join, posix } from 'node:path';
3
+ import { branchOfCached, cleanRelative, inside, projectPath, projectRelative } from "./domain.js";
4
4
  import { actionInDomain, bashScope, literalActionCommand } from "./command-scope.js";
5
5
  import { currentGuidance, inspectGuidance } from "./guidance.js";
6
- import { memoryInstructions } from "./propose-contract.js";
7
6
  import { SignatureCache } from "./cache.js";
8
7
  export * from "./domain.js";
9
8
  export * from "./command-scope.js";
10
9
  export * from "./index-policy.js";
11
- export { proposeTool } from "./propose-contract.js";
12
- export const systemSection = memoryInstructions +
13
- ' 本轮有值得保存的内容时调用 project_memory_propose。日常答复专注用户的问题,直接使用相关记忆。读写结果由界面提示,避免在正文复述存储、搜索过程或工具名。用户询问来源、保存状态或明确要求记忆操作时,简短说明实际结果。个人事实查不到时直接向用户确认,避免用系统账号或 Git 作者信息推断身份。常驻上下文列出当前可主动遵守的约定,结合当前任务判断是否适用。' +
14
- '回答依赖过往事实、经历或约定,且当前对话和索引缺少所问细节时,先用 project_memory_search 查一次,再判断能否回答。query 写明主体和要找的细节,主体和主题明确时附上 subject 和 topic。索引已给出适用条件和完整动作时直接使用。任务完成后按本轮执行结果答复。需要展开索引时,用 project_memory_read 读取现行结论和条件。仅在用户追问出处或要求核对原话时调用 project_memory_source,并按核验状态说明出处。遵守现行仓库指令。';
15
10
  const fields = [
16
11
  'action',
17
12
  'when',
@@ -80,24 +75,24 @@ function hardConditions(domain, row) {
80
75
  names.find((name) => name.toLowerCase() === candidate.toLowerCase()));
81
76
  })
82
77
  .find(Boolean) ?? (target.dialect === 'make' ? 'Makefile' : 'justfile');
83
- const path = posix.join(relative(domain.root, dir), filename);
78
+ const path = posix.join(projectRelative(domain.root, dir), filename);
84
79
  projectPath(domain, path);
85
80
  files.push(path);
86
81
  targets.push({ ...target, path });
87
82
  }
88
83
  return { files, targets };
89
84
  }
90
- function enrich(domain, input, loaded) {
85
+ function enrich(domain, input, loaded, fileImport, previous) {
91
86
  // Freeze the physical scope selected through any local alias so retargeting a link
92
87
  // cannot silently move an approved rule to a different project subtree.
93
88
  const paths = [
94
- ...new Set(input.paths.map((p) => relative(domain.root, projectPath(domain, p)) || '.')),
89
+ ...new Set(input.paths.map((p) => projectRelative(domain.root, projectPath(domain, p)) || '.')),
95
90
  ].sort();
96
91
  input = { ...input, paths };
97
92
  if (!actionInDomain(domain, input.action))
98
93
  throw new Error('outside_command_scope');
99
94
  const hard = hardConditions(domain, input);
100
- const guidance = inspectGuidance(domain, input, loaded);
95
+ const guidance = inspectGuidance(domain, input, loaded, undefined, fileImport, previous);
101
96
  const user_quote = redact(input.user_quote).slice(0, 480);
102
97
  const action = redact(input.action), when = redact(input.when), exceptions = redact(input.exceptions);
103
98
  return {
@@ -114,27 +109,8 @@ function enrich(domain, input, loaded) {
114
109
  };
115
110
  }
116
111
  function hasVerbatimAction(source, quote, action) {
117
- if (!quote.includes(action))
118
- return false;
119
- if (!simpleTarget(action) || !/^(?:make|just) [\w.-]+$/u.test(action))
120
- return false;
121
- if (/[??]|假设|据说|同事说|引文|引用|转述|示例|\b(?:example|quote|reportedly)\b/iu.test(source))
122
- return false;
123
- const before = quote
124
- .slice(0, quote.indexOf(action))
125
- .split(/[,。;;.!!\n]/u)
126
- .at(-1) ?? '';
127
- if (/不|别|禁止|停用|拒绝|\b(?:no|not|never|avoid|without)\b/iu.test(before))
128
- return false;
129
- const start = source.indexOf(quote) + quote.indexOf(action);
130
- const clause = source
131
- .slice(0, start)
132
- .split(/[,。;;.!!\n]/u)
133
- .at(-1) ?? '';
134
- if (/不|别|禁止|停用|拒绝|\b(?:no|not|never|avoid|without)\b/iu.test(clause))
135
- return false;
136
- return (quote.includes(action) &&
137
- !/^[A-Za-z0-9_.-]|^[ \t]+[-\w]|^\s*[&|;$<>]/u.test(source.slice(start + action.length)));
112
+ // Literal equality establishes provenance; quoted substrings can omit modality or negation.
113
+ return source.trim() === quote.trim() && quote.trim() === action && !!literalActionCommand(action);
138
114
  }
139
115
  export function prepareItems(domain, args, events, guidance = []) {
140
116
  if (!record(args) ||
@@ -179,8 +155,8 @@ export function prepareItems(domain, args, events, guidance = []) {
179
155
  };
180
156
  });
181
157
  }
182
- export function manualItem(domain, input, guidance = []) {
183
- return { ...enrich(domain, fieldsOf(input), guidance), kind: 'rule', usage: 'proactive' };
158
+ export function manualItem(domain, input, guidance = [], fileImport, previous) {
159
+ return { ...enrich(domain, fieldsOf(input), guidance, fileImport, previous), kind: 'rule', usage: 'proactive' };
184
160
  }
185
161
  // Collects every target/recipe name a Makefile or justfile defines, so one parse of the file
186
162
  // (cached below, keyed on its own stat signature) serves every rule that references it.
@@ -260,13 +236,18 @@ export function validateRule(domain, row) {
260
236
  return { ok: false, reason: 'needs_review' };
261
237
  if (row.guidance && !currentGuidance(domain, row.paths, row.guidance))
262
238
  return { ok: false, reason: 'stale_guidance' };
239
+ if (row.guidance?.status === 'review_required' || row.guidance?.status === 'ambiguous')
240
+ return { ok: false, reason: 'repo_guidance_review_required' };
263
241
  if (row.guidance && row.guidance.status !== 'clear') {
264
- if (!['ambiguous', 'permitted'].includes(row.guidance.status) || !row.localException)
242
+ if (row.guidance.status !== 'permitted' || !row.localException)
265
243
  return { ok: false, reason: 'needs_clarification' };
266
244
  }
267
- if (row.localException &&
268
- (row.localException.machine !== domain.machine || !environmentMatches(row.localException.environment)))
269
- return { ok: false, reason: 'outside_environment' };
245
+ if (row.localException) {
246
+ if (!validCommands(row.localException.commands))
247
+ return { ok: false, reason: 'local_conditions_review_required' };
248
+ if (row.localException.machine !== domain.machine || !environmentMatches(row.localException.commands))
249
+ return { ok: false, reason: 'outside_environment' };
250
+ }
270
251
  return { ok: true };
271
252
  }
272
253
  catch {
@@ -288,7 +269,7 @@ function executable(name) {
288
269
  }
289
270
  });
290
271
  }
291
- function environmentMatches(description) {
272
+ function environmentMatches(commands) {
292
273
  // Per-machine overrides are exclusively local. Keep them out of a CI execution on the same host.
293
274
  const ci = [
294
275
  process.env.CI,
@@ -299,11 +280,17 @@ function environmentMatches(description) {
299
280
  ];
300
281
  if (ci.some((value) => value && !/^(?:0|false|no)$/iu.test(value)))
301
282
  return false;
302
- if (/只有\s*podman|仅有\s*podman|only\s+podman|podman\s+only/iu.test(description))
303
- return executable('podman') && !executable('docker');
304
- return true;
283
+ return commands.present.every(executable) && !commands.absent.some(executable);
284
+ }
285
+ // Only literal executable names are accepted. These checks inspect PATH and never run a command.
286
+ function validCommands(value) {
287
+ if (!record(value) || Object.keys(value).some(k => k !== 'present' && k !== 'absent'))
288
+ return false;
289
+ const names = (list) => Array.isArray(list) && list.length <= 16 &&
290
+ list.every(name => typeof name === 'string' && /^[a-zA-Z0-9][a-zA-Z0-9._+-]{0,79}$/u.test(name));
291
+ return names(value.present) && names(value.absent) && !value.present.some(name => value.absent.includes(name));
305
292
  }
306
- export function reviewItem(domain, draft, edits = {}, exception, loaded = [], branch) {
293
+ export function reviewItem(domain, draft, edits = {}, exception, loaded = [], branch, fileImport, guidanceReviewed = false) {
307
294
  if (!record(edits) || Object.keys(edits).some((k) => !fields.some((f) => f === k)))
308
295
  throw new Error('invalid_input');
309
296
  if (draft.guidance && !currentGuidance(domain, draft.paths, draft.guidance))
@@ -314,7 +301,19 @@ export function reviewItem(domain, draft, edits = {}, exception, loaded = [], br
314
301
  const file = f.external ?? projectPath(domain, f.path);
315
302
  return { path: f.path, absolutePath: file, text: readFileSync(file, 'utf8') };
316
303
  });
317
- const updated = enrich(domain, input, [...previousSources, ...loaded]);
304
+ const unchanged = input.action === draft.action && input.when === draft.when && input.exceptions === draft.exceptions &&
305
+ JSON.stringify(input.paths) === JSON.stringify(draft.paths) && !input.conflicts_with_repo_guidance;
306
+ const updated = enrich(domain, input, [...previousSources, ...loaded], unchanged ? fileImport : undefined, unchanged ? draft.guidance : undefined);
307
+ if (updated.guidance.status === 'review_required' || updated.guidance.status === 'ambiguous') {
308
+ // The authenticated owner reviewed this candidate and these exact file hashes. A local
309
+ // alternative needs both an explicit human decision and machine-checkable scope below.
310
+ if (guidanceReviewed !== true || input.conflicts_with_repo_guidance)
311
+ throw new Error('repo_guidance_review_required');
312
+ const displayed = new Map(draft.guidance?.files.map(file => [file.path, file.hash]));
313
+ if (updated.guidance.files.some(file => displayed.get(file.path) !== file.hash))
314
+ throw new Error('stale_guidance');
315
+ updated.guidance = { ...updated.guidance, status: exception ? 'permitted' : 'clear' };
316
+ }
318
317
  if (['mandatory', 'unavailable'].includes(updated.guidance.status))
319
318
  throw new Error('needs_clarification');
320
319
  if (updated.guidance.status === 'duplicate')
@@ -328,13 +327,12 @@ export function reviewItem(domain, draft, edits = {}, exception, loaded = [], br
328
327
  exception.environment.length > 512 ||
329
328
  exception.scope.length > 512)
330
329
  throw new Error('needs_clarification');
331
- const ciBoundary = /\bci\b|pipeline|流水线/iu;
332
- const excludesCI = /(?:排除|不含|不包括|不适用|不在|除外|outside|excluding|except|not in)\s*(?:于\s*)?(?:ci|pipeline|流水线)|(?:\bci\b|pipeline|流水线).{0,12}(?:按仓库|遵守仓库|沿用|保留|除外|不适用|unchanged|follows? (?:the )?repo)/iu;
333
- if ([input.when, exception.scope].some((s) => ciBoundary.test(s) && !excludesCI.test(s)))
330
+ if (!validCommands(exception.commands))
334
331
  throw new Error('needs_clarification');
335
332
  updated.localException = {
336
333
  environment: redact(exception.environment.trim()),
337
334
  scope: redact(exception.scope.trim()),
335
+ commands: { present: [...new Set(exception.commands.present)], absent: [...new Set(exception.commands.absent)] },
338
336
  machine: domain.machine,
339
337
  };
340
338
  }