dsh-memu-memory 1.3.1 → 1.3.3

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 (58) hide show
  1. package/AGENTS.md +6 -3
  2. package/CHANGELOG.md +57 -0
  3. package/README.md +8 -7
  4. package/README.zh.md +8 -5
  5. package/assets/screenshots/drawer.jpg +0 -0
  6. package/assets/screenshots/mobile.jpg +0 -0
  7. package/assets/screenshots/relations.jpg +0 -0
  8. package/assets/screenshots/settings.jpg +0 -0
  9. package/assets/screenshots/stats.jpg +0 -0
  10. package/assets/screenshots/webui-dark.jpg +0 -0
  11. package/assets/screenshots/webui-memory.jpg +0 -0
  12. package/docs/client-conventions.md +11 -0
  13. package/docs/contributing.md +6 -4
  14. package/docs/env-and-commands.md +12 -1
  15. package/docs/memory-semantics.md +8 -2
  16. package/docs/troubleshooting.md +24 -6
  17. package/lib/auto-link/apply.js +249 -0
  18. package/lib/auto-link/candidates.js +155 -0
  19. package/lib/auto-link/decide.js +304 -0
  20. package/lib/auto-link/normalize.js +99 -0
  21. package/lib/auto-link/policy.js +42 -0
  22. package/lib/auto-link/suppression.js +101 -0
  23. package/lib/auto-link/terminology.js +265 -0
  24. package/lib/binding-diagnostics.js +2 -2
  25. package/lib/client.js +1509 -72
  26. package/lib/graph.js +269 -18
  27. package/lib/memory.js +11 -0
  28. package/lib/memu.js +7 -6
  29. package/lib/private-links.js +105 -137
  30. package/lib/private.js +138 -38
  31. package/lib/rpc.js +73 -8
  32. package/lib/state.js +7 -2
  33. package/lib/tools.js +4 -2
  34. package/lib/webui/graph-LICENSE.txt +1 -62
  35. package/lib/webui/graph-view.bundle.js +1 -1
  36. package/lib/webui/graph-view.js +921 -126
  37. package/lib/webui/standalone.js +3 -3
  38. package/package.json +1 -2
  39. package/scripts/build-graph.mjs +35 -7
  40. package/scripts/check-all.mjs +2 -0
  41. package/scripts/check-graph-browser.mjs +106 -23
  42. package/scripts/make-readme-shots.mjs +59 -0
  43. package/scripts/rebuild-auto-links.mjs +252 -0
  44. package/tests/audit-regression.test.mjs +11 -8
  45. package/tests/auto-link-candidates.test.mjs +161 -0
  46. package/tests/auto-link-decide.test.mjs +512 -0
  47. package/tests/auto-link-migration.test.mjs +133 -0
  48. package/tests/browser.test.mjs +27 -0
  49. package/tests/client-render.test.mjs +178 -6
  50. package/tests/consolidation-fork.test.mjs +148 -0
  51. package/tests/cycle.test.mjs +1 -1
  52. package/tests/graph-view.test.mjs +221 -22
  53. package/tests/graph.test.mjs +5 -0
  54. package/tests/help-page.test.mjs +3 -3
  55. package/tests/memu-resident-route.test.mjs +130 -0
  56. package/tests/private-links.test.mjs +81 -45
  57. package/tests/stubs/child-process-spy.mjs +14 -0
  58. package/tests/tools.test.mjs +24 -18
@@ -1,35 +1,18 @@
1
- // Private auto-association + entity hubs (algorithm-first, zero extra model tokens).
1
+ // Private auto-association, split into a legacy candidate pass and the
2
+ // deterministic write layer (DESIGN v3).
2
3
  //
3
- // Trigger: after a private consolidation settles, the created/updated entry ids are
4
- // handed to this module. It never calls an LLM. Two layers live here:
4
+ // * suggestPrivateLinks — PURE legacy candidate suggestion. It still finds
5
+ // statistically name-like pairs, but its output is only a review hint. It
6
+ // never decides that an edge exists.
7
+ // * autoLinkPrivateMemories — MODE GATED. In the default 'suggest' mode it
8
+ // returns candidates and writes nothing. In 'deterministic' mode it refreshes
9
+ // the edges that lib/auto-link/ decided: memory→confirmed-entity mentions and
10
+ // explicit field evidence. Lexical similarity, shared tokens and vectors are
11
+ // never written as edges.
5
12
  //
6
- // * suggestPrivateLinks — PURE. Reads an index snapshot (+ the library's entity
7
- // list) and returns what it would connect. No disk writes, no activity log.
8
- // * autoLinkPrivateMemories — APPLIES the high-confidence half: memory↔memory
9
- // relation links and entity hubs. Uncertain pairs are returned as candidates
10
- // for the current consolidation worker to adjudicate (it already has the
11
- // transcript in hand; starting another consolidation would re-read everything).
12
- //
13
- // The high-precision signals:
14
- // * both entries are eligible (active, not expired, not automatic-secret),
15
- // visible to the conversation, share the same fact context and the same track;
16
- // * their titles share a RARE token (df <= max(2, ceil(0.15·N))): a Latin token
17
- // of >= 3 chars, or a CJK bigram. These are the "name-like" tokens;
18
- // * pairScore < 0.82 — at/above that band it is a duplicate/merge problem, not
19
- // a link; findConflict must find no contradiction; an existing relation/person
20
- // link in either direction means it is already handled (idempotent);
21
- // * a name-like shared token whose entity kind is resolved (person cue, or a
22
- // Latin token with no cue → thing) becomes a hub: >= 2 memories sharing the
23
- // stable name are linked to one entity, and the memory pair is auto-linked.
24
- // A CJK token with no person cue has an uncertain kind (null) and a token
25
- // that contradicts an existing entity kind is a mismatch: neither creates a
26
- // hub or a memory link; the pair becomes one uncertain candidate with a
27
- // suggestedEntity for this consolidation's worker.
28
- //
29
- // Non-name-like shared tokens never auto-link. They surface as uncertain
30
- // candidates only when 0.55 <= pairScore < 0.82. A pair appears in exactly one
31
- // output: auto-linked pairs are never duplicated into candidates, and uncertain
32
- // pairs are never auto-linked.
13
+ // The write layer is incremental: the consolidation hands over the ids it just
14
+ // created/updated, and only those rows are recomputed (O(Δ)). Rebuilding the
15
+ // whole library is the migration script's job.
33
16
  //
34
17
  // Links are metadata only: they never touch the vector store, never delete
35
18
  // memory, and can be removed from the relationship graph. A failed association
@@ -37,11 +20,14 @@
37
20
  // caught and only a warning is logged; the top-level index load is caught too.
38
21
 
39
22
  import { sameFactContext } from './context.js'
40
- import { createEntity, linkEntries, listEntities } from './graph.js'
23
+ import { listEntities } from './graph.js'
41
24
  import { findConflict, isMemoryEligible, visibleToSession } from './memory.js'
42
25
  import { pairFeatures, pairScore, tokenize } from './text-retrieval.js'
43
- import { loadPrivateIndex } from './state.js'
26
+ import { getSettings, loadPrivateIndex } from './state.js'
44
27
  import { record } from './activity-log.js'
28
+ import { applyAutoEdges, refreshMemoryAutoLinks } from './auto-link/apply.js'
29
+ import { decideAutoLinks } from './auto-link/decide.js'
30
+ import { suppressionSet } from './auto-link/suppression.js'
45
31
 
46
32
  const DEFAULT_PER_ENTRY = 2
47
33
  const DEFAULT_TOTAL = 5
@@ -51,7 +37,6 @@ const SCORE_CANDIDATE_MIN = 0.55
51
37
  const SCORE_DUPLICATE = 0.82
52
38
  const DF_RATIO = 0.15
53
39
  const LATIN_NAME_MIN_LENGTH = 3
54
- const ENTITY_CONFIDENCE = 0.65
55
40
  // findConflict compares the same five identity keys; grouping hubs by the same
56
41
  // key keeps "not across context" true for the entity side too.
57
42
  const FACT_KEYS = ['channelId', 'speakerId', 'characterId', 'worldId', 'branchId']
@@ -426,28 +411,21 @@ export function suggestPrivateLinks({
426
411
  }
427
412
  }
428
413
 
429
- function autoLinkNote(link) {
430
- return `自动关联:两条记忆共享稳定称谓「${link.token}」;内容相似度 ${link.score.toFixed(2)}。算法自动建立,可在关系图移除。`
431
- }
432
-
433
- function hubNote(hub) {
434
- return `自动实体枢纽:多条记忆共享稳定称谓「${hub.token}」。`
435
- }
436
-
437
- function execFor(sessionId) {
438
- return sessionId ? { agent: { session: { header: { id: sessionId } } } } : undefined
439
- }
440
-
441
414
  /**
442
- * Apply the high-confidence part of suggestPrivateLinks and return the uncertain
443
- * candidates untouched. `ids` are the entries created/updated by the finished
444
- * consolidation; an entry that is no longer eligible is ignored by the pure pass.
415
+ * Mode-gated entry point used by the consolidation settle path and the worker
416
+ * tool. `ids` are the entries created/updated by the finished consolidation.
417
+ *
418
+ * * 'suggest' (default): compute the legacy review candidates, write nothing.
419
+ * * 'deterministic': additionally refresh this layer's edges in lib/auto-link/
420
+ * for those ids — mention edges to confirmed entities and explicit field
421
+ * evidence. Legacy statistical pairs remain candidates only.
422
+ * * 'off': no candidates, no writes.
445
423
  *
446
- * Return counts: `linked` = memory↔memory relation links written, `entities` =
447
- * memory→entity links written, `suggested` = number of candidates handed to the
448
- * worker. A consolidation must never fail because of this module: the index load
449
- * and the suggestion pass are caught at the top, every individual write is caught
450
- * and logged at warn level.
424
+ * A consolidation must never fail because of this module: the index load, the
425
+ * suggestion pass and the deterministic write are each caught and logged at warn
426
+ * level. Return counts: `linked` = memory↔memory evidence edges written,
427
+ * `entities` = memory→confirmed-entity edges written, `suggested` = candidate
428
+ * count handed to the worker.
451
429
  */
452
430
  export async function autoLinkPrivateMemories({
453
431
  libraryId,
@@ -460,6 +438,10 @@ export async function autoLinkPrivateMemories({
460
438
  } = {}) {
461
439
  const result = { linked: 0, entities: 0, suggested: 0, candidates: [], autoLinked: [] }
462
440
  if (!libraryId) return result
441
+ // S0 止血:默认的 'suggest' 只出候选、不写边;'off' 连候选都不算。
442
+ // 误连的代价远高于漏连,迁移期间先停写,再按 DESIGN 的确定性判定层重建。
443
+ const mode = getSettings().autoLinkMode
444
+ if (mode === 'off') return result
463
445
  const idList = (Array.isArray(ids) ? ids : []).map(id => String(id)).filter(Boolean)
464
446
  if (!idList.length) return result
465
447
 
@@ -494,94 +476,80 @@ export async function autoLinkPrivateMemories({
494
476
  }
495
477
  result.suggested = suggestion.candidates.length
496
478
  result.candidates = suggestion.candidates
497
-
498
- const exec = execFor(sessionId)
499
- for (const link of suggestion.autoLinks) {
500
- try {
501
- linkEntries({
502
- exec,
503
- libraryId,
504
- fromId: link.from,
505
- toId: link.to,
506
- kind: 'relation',
507
- note: autoLinkNote(link),
508
- confidence: link.confidence,
509
- source: 'auto',
510
- })
511
- result.linked += 1
512
- result.autoLinked.push({ from: link.from, to: link.to, kind: 'relation' })
513
- record({
514
- kind: 'write', scope: 'private', sessionId, libraryId, ok: true,
515
- message: `自动关联 ${link.from} → ${link.to}(「${link.token}」)`,
516
- detail: {
517
- op: 'auto-link', from: link.from, to: link.to, kind: 'relation',
518
- score: link.score, token: link.token, confidence: link.confidence, source: 'auto',
519
- },
520
- refs: [link.from, link.to],
521
- })
522
- } catch (error) {
523
- record({
524
- kind: 'write', scope: 'private', sessionId, libraryId, ok: false, level: 'warn',
525
- message: `自动关联跳过 ${link.from} → ${link.to}:${String(error?.message || error)}`,
526
- detail: { op: 'auto-link', from: link.from, to: link.to, error: String(error?.message || error) },
527
- refs: [link.from, link.to],
528
- })
529
- }
479
+ // Only deterministic mode writes edges. suggest/off stop here with the candidates.
480
+ if (mode !== 'deterministic') return result
481
+
482
+ // Deterministic pass: only confirmed-entity mentions and explicit field
483
+ // evidence are written; the legacy statistical pairs stay candidates.
484
+ const refreshed = await refreshPrivateAutoLinks({ libraryId, sessionId, ids: idList, entities: entityList })
485
+ if (refreshed.applied) {
486
+ result.linked = refreshed.applied.memory
487
+ result.entities = refreshed.applied.entity
488
+ result.autoLinked = refreshed.applied.applied.map(({ from, to, kind }) => ({ from, to, kind }))
530
489
  }
490
+ return result
491
+ }
531
492
 
532
- for (const hub of suggestion.entityHubs) {
533
- let entity = null
534
- try {
535
- entity = hub.entityId
536
- ? { id: hub.entityId, kind: hub.kind }
537
- : createEntity({ exec, libraryId, name: hub.name, kind: hub.kind })
538
- } catch (error) {
539
- record({
540
- kind: 'write', scope: 'private', sessionId, libraryId, ok: false, level: 'warn',
541
- message: `自动实体枢纽跳过「${hub.name}」:${String(error?.message || error)}`,
542
- detail: { op: 'auto-entity', name: hub.name, kind: hub.kind, error: String(error?.message || error) },
543
- refs: hub.memoryIds,
493
+ /**
494
+ * Deterministic-only incremental refresh, shared by every write path that can
495
+ * change what the edges should be: consolidation settle, the worker tool, a
496
+ * private write carrying conflicts_with / supersedes / a fact_key pair, and a
497
+ * review accept that turns a claim into a supersede. Returns `{ skipped, applied }`
498
+ * and never throws — a failure is logged and the caller's write stays valid.
499
+ */
500
+ export async function refreshPrivateAutoLinks({ libraryId, sessionId = null, ids, entities = null, full = false } = {}) {
501
+ const mode = getSettings().autoLinkMode
502
+ if (mode !== 'deterministic') return { skipped: mode || 'suggest', applied: null }
503
+ const idList = [...new Set((Array.isArray(ids) ? ids : []).map(id => String(id ?? '').trim()).filter(Boolean))]
504
+ if (!libraryId || (!full && !idList.length)) return { skipped: 'no-ids', applied: null }
505
+ let entityList
506
+ try {
507
+ entityList = Array.isArray(entities) ? entities : listEntities({ libraryId }).items
508
+ } catch (error) {
509
+ record({
510
+ kind: 'write', scope: 'private', sessionId, libraryId, ok: false, level: 'warn',
511
+ message: `私有自动关联跳过:实体表不可读(${String(error?.message || error)})`,
512
+ detail: { op: 'auto-link', phase: 'entities', error: String(error?.message || error) },
513
+ refs: [],
514
+ })
515
+ return { skipped: 'entities', applied: null }
516
+ }
517
+ let suppression
518
+ try {
519
+ suppression = suppressionSet(libraryId)
520
+ } catch (error) {
521
+ record({
522
+ kind: 'write', scope: 'private', sessionId, libraryId, ok: false, level: 'warn',
523
+ message: `私有自动关联跳过:抑制表不可读(${String(error?.message || error)})`,
524
+ detail: { op: 'auto-link', phase: 'suppression', error: String(error?.message || error) },
525
+ refs: [],
526
+ })
527
+ return { skipped: 'suppression', applied: null }
528
+ }
529
+ try {
530
+ // `full` recomputes the whole library in one transaction. It is the catch-up
531
+ // path for entities confirmed while the mode was off: their status is already
532
+ // confirmed, so a later per-id refresh has nothing to trigger.
533
+ if (full) {
534
+ const edges = decideAutoLinks({ index: loadPrivateIndex(libraryId), entities: entityList, suppression })
535
+ const applied = applyAutoEdges({
536
+ libraryId, edges, entities: entityList, sessionId, operation: 'auto-link-rebuild',
544
537
  })
545
- continue
546
- }
547
- for (const memoryId of hub.memoryIds) {
548
- try {
549
- const fresh = loadPrivateIndex(libraryId).entries[memoryId]
550
- if (!fresh) throw new Error('memory is gone')
551
- if ((fresh.links || []).some(link => link?.to === entity.id)) continue
552
- linkEntries({
553
- exec,
554
- libraryId,
555
- fromId: memoryId,
556
- toId: entity.id,
557
- kind: hub.kind === 'person' ? 'person' : 'relation',
558
- note: hubNote(hub),
559
- confidence: ENTITY_CONFIDENCE,
560
- source: 'auto',
561
- })
562
- result.entities += 1
563
- result.autoLinked.push({ from: memoryId, to: entity.id, kind: hub.kind === 'person' ? 'person' : 'relation' })
564
- record({
565
- kind: 'write', scope: 'private', sessionId, libraryId, ok: true,
566
- message: `自动实体枢纽 ${memoryId} → ${entity.id}(「${hub.name}」)`,
567
- detail: {
568
- op: 'auto-entity', memory: memoryId, entity: entity.id, name: hub.name,
569
- kind: hub.kind, token: hub.token, confidence: ENTITY_CONFIDENCE, source: 'auto',
570
- },
571
- refs: [memoryId, entity.id],
572
- })
573
- } catch (error) {
574
- record({
575
- kind: 'write', scope: 'private', sessionId, libraryId, ok: false, level: 'warn',
576
- message: `自动实体枢纽跳过 ${memoryId} → 「${hub.name}」:${String(error?.message || error)}`,
577
- detail: { op: 'auto-entity', memory: memoryId, entity: entity?.id || null, name: hub.name, error: String(error?.message || error) },
578
- refs: [memoryId],
579
- })
580
- }
538
+ return { skipped: null, applied, full: true }
581
539
  }
540
+ const applied = refreshMemoryAutoLinks({
541
+ libraryId, ids: idList, entities: entityList, suppression, sessionId,
542
+ })
543
+ return { skipped: null, applied }
544
+ } catch (error) {
545
+ record({
546
+ kind: 'write', scope: 'private', sessionId, libraryId, ok: false, level: 'warn',
547
+ message: `私有自动关联写入失败:${String(error?.message || error)}`,
548
+ detail: { op: 'auto-link', phase: 'apply', error: String(error?.message || error) },
549
+ refs: [],
550
+ })
551
+ return { skipped: 'apply', applied: null }
582
552
  }
583
-
584
- return result
585
553
  }
586
554
 
587
- export default { suggestPrivateLinks, autoLinkPrivateMemories, normalizeEntityName, inferEntityKind }
555
+ export default { suggestPrivateLinks, autoLinkPrivateMemories, refreshPrivateAutoLinks, normalizeEntityName, inferEntityKind }
package/lib/private.js CHANGED
@@ -191,6 +191,10 @@ const SEED_EVENT_TYPES = new Set([
191
191
  'turn/start', 'turn/end', 'step/start', 'step/end',
192
192
  ])
193
193
 
194
+ // The subset that joins the host's model-visible surface: every one of these
195
+ // must carry a surfaceOp marker, and their seqs form the fold a replacement cites.
196
+ const SEED_SURFACE_TYPES = new Set(['user/message', 'assistant/message', 'tool/result'])
197
+
194
198
  function capSeedText(value, limit = SEED_TEXT_CHARS) {
195
199
  const text = String(value ?? '')
196
200
  return text.length > limit ? text.slice(0, limit) + '…[已截断]' : text
@@ -222,16 +226,104 @@ function cloneSeedBlocks(blocks, caps = {}, seenToolText = null) {
222
226
  return out
223
227
  }
224
228
 
229
+ // Renumber survivors and rewrite every citation to its final index. A replace
230
+ // whose endpoints did not survive cannot be replayed at all; report it so the
231
+ // caller drops it before seqs are handed out (dropping after renumbering is what
232
+ // left holes the host rejected with "seed event at index N has seq M").
233
+ function buildSeedEvents(pending, offset) {
234
+ const index = new Map()
235
+ pending.forEach((event, i) => index.set(Number(event.seq), i + offset))
236
+ const prepared = []
237
+ const origins = []
238
+ let dropped = false
239
+ pending.forEach((event, origin) => {
240
+ const next = { ...event, seq: index.get(Number(event.seq)) }
241
+ if (Array.isArray(next.sourceEventSeqs)) {
242
+ const mapped = [...new Set(next.sourceEventSeqs
243
+ .map(value => index.get(Number(value)))
244
+ .filter(value => Number.isInteger(value) && value < next.seq))]
245
+ .sort((a, b) => a - b)
246
+ if (mapped.length) next.sourceEventSeqs = mapped
247
+ else delete next.sourceEventSeqs
248
+ }
249
+ if (next.surfaceOp && typeof next.surfaceOp === 'object' && !Array.isArray(next.surfaceOp)) {
250
+ const start = index.get(Number(next.surfaceOp.startSeq))
251
+ const end = index.get(Number(next.surfaceOp.endSeq))
252
+ if (!Number.isInteger(start) || !Number.isInteger(end) || start > end || !Array.isArray(next.sourceEventSeqs)) {
253
+ dropped = true
254
+ return
255
+ }
256
+ next.surfaceOp = { op: 'replace', startSeq: start, endSeq: end }
257
+ }
258
+ prepared.push(next)
259
+ origins.push(origin)
260
+ })
261
+ return { prepared, origins, dropped }
262
+ }
263
+
264
+ // Mirror the host's surface-fold checks (session `validateNext`) over a candidate
265
+ // seed. A replacement is only accepted when both endpoints are current nodes and
266
+ // sourceEventSeqs cite every node the range shadows — dropping a replacement can
267
+ // reveal nodes it had shadowed, which is why this must run on the whole seed and
268
+ // not just the event being rewritten. Returns the prepared indices that failed.
269
+ function seedSurfaceIssues(events) {
270
+ const nodes = []
271
+ const issues = []
272
+ events.forEach((event, index) => {
273
+ if (!SEED_SURFACE_TYPES.has(event.type)) return
274
+ const op = event.surfaceOp
275
+ if (op === 'append') {
276
+ nodes.push(event.seq)
277
+ return
278
+ }
279
+ if (!op || typeof op !== 'object' || Array.isArray(op) || op.op !== 'replace') {
280
+ issues.push(index)
281
+ return
282
+ }
283
+ const startSeq = Number(op.startSeq)
284
+ const endSeq = Number(op.endSeq)
285
+ const startIdx = nodes.indexOf(startSeq)
286
+ const endIdx = nodes.indexOf(endSeq)
287
+ const sources = Array.isArray(event.sourceEventSeqs) ? event.sourceEventSeqs : []
288
+ const cited = new Set(sources)
289
+ if (startSeq >= event.seq || endSeq >= event.seq
290
+ || startIdx < 0 || endIdx < startIdx
291
+ || sources.length === 0 || sources.length !== cited.size
292
+ || sources.some(seq => Number(seq) >= event.seq)
293
+ || nodes.slice(startIdx, endIdx + 1).some(seq => !cited.has(seq))) {
294
+ issues.push(index)
295
+ return
296
+ }
297
+ nodes.splice(startIdx, endIdx - startIdx + 1)
298
+ nodes.push(event.seq)
299
+ })
300
+ return issues
301
+ }
302
+
225
303
  /**
226
304
  * Build the seed body for one window: only conversation events, with reasoning /
227
305
  * replay state / repeated tool output removed, then renumbered seq 0..n so
228
306
  * Session's "contiguous from zero" rule holds. The optional catalog event takes
229
307
  * seq 0 and is the only synthetic message.
308
+ *
309
+ * Surface replacements are not append-only: their surfaceOp cites the range they
310
+ * shadow, and the host validates those citations while replaying the seed. When
311
+ * the noise filter drops neighbours (or the window starts inside a compacted
312
+ * range), an unremapped startSeq/endSeq points forward or at a node the seed no
313
+ * longer contains and the whole fork is refused. Resolve every replacement
314
+ * against the surviving events, drop the ones that cannot be replayed, and only
315
+ * renumber once the survivor set is stable.
230
316
  */
231
317
  export function compactSeedEvents(events, prelude = null) {
232
318
  const preludeEvents = (Array.isArray(prelude) ? prelude : (prelude ? [prelude] : []))
233
319
  .filter((event) => event && typeof event === 'object')
234
- .map((event, index) => ({ ...event, seq: index }))
320
+ .map((event, index) => {
321
+ // Preludes are synthetic and sit at the head, so they can only append: a
322
+ // replacement marker there would cite positions that do not exist yet. The
323
+ // host also refuses a surface-eligible event without a marker at all.
324
+ const surfaceOp = SEED_SURFACE_TYPES.has(event.type) ? 'append' : event.surfaceOp
325
+ return { ...event, seq: index, surfaceOp }
326
+ })
235
327
  const offset = preludeEvents.length
236
328
  const kept = []
237
329
  const seenToolText = new Set()
@@ -269,29 +361,25 @@ export function compactSeedEvents(events, prelude = null) {
269
361
  const timeLabel = eventTimeLabel(event)
270
362
  if (timeLabel) clone.data.content.unshift({ type: 'text', text: `[事件时间 ${timeLabel}]` })
271
363
  }
364
+ // Old logs and fixtures can omit the marker; the host refuses a
365
+ // surface-eligible event without one, and inside a seed it can only append.
366
+ if (clone.surfaceOp === undefined && SEED_SURFACE_TYPES.has(clone.type)) clone.surfaceOp = 'append'
272
367
  kept.push(clone)
273
368
  }
274
369
 
275
- const mapping = new Map()
276
- kept.forEach((event, index) => mapping.set(Number(event.seq), index + offset))
277
- const out = [...preludeEvents]
278
- kept.forEach((event, index) => {
279
- const next = { ...event, seq: index + offset }
280
- if (Array.isArray(next.sourceEventSeqs)) {
281
- const mapped = [...new Set(next.sourceEventSeqs
282
- .map(value => mapping.get(Number(value)))
283
- .filter(value => Number.isInteger(value) && value < next.seq))]
284
- .sort((a, b) => a - b)
285
- if (mapped.length) next.sourceEventSeqs = mapped
286
- else delete next.sourceEventSeqs
287
- }
288
- // A surface replace cites the nodes it shadows; if any citation was dropped
289
- // with the noise filter, replaying it would fail validation. Dropping the
290
- // whole patch is the safe choice — the seed is evidence, not state.
291
- if (next.surfaceOp && typeof next.surfaceOp === 'object' && !Array.isArray(next.sourceEventSeqs)) return
292
- out.push(next)
293
- })
294
- return out
370
+ let pending = kept
371
+ for (;;) {
372
+ const { prepared, origins, dropped } = buildSeedEvents(pending, offset)
373
+ const issues = seedSurfaceIssues([...preludeEvents, ...prepared])
374
+ if (!dropped && issues.length === 0) return [...preludeEvents, ...prepared]
375
+ // Each pass removes at least one event, so this converges; two passes cover
376
+ // the replacement-cites-a-replacement case the host rejects first.
377
+ const survivors = new Set(origins)
378
+ const doomed = new Set()
379
+ pending.forEach((_, origin) => { if (!survivors.has(origin)) doomed.add(origin) })
380
+ for (const index of issues) doomed.add(origins[index - offset])
381
+ pending = pending.filter((_, origin) => !doomed.has(origin))
382
+ }
295
383
  }
296
384
 
297
385
  // P3: spend the worker's context on turns that can produce a durable memory.
@@ -810,7 +898,7 @@ const inFlight = new Map()
810
898
  const WORKER_STOP_GRACE_MS = 5_000
811
899
 
812
900
  // 这里的 import 刻意写在语句之后:lib/binding-diagnostics.js 的 RUNTIME_STATE 把 `inFlight`
813
- // 的 file:line 当成诊断契约(当前 lib/private.js:805),修改位置时同步更新该诊断映射,
901
+ // 的 file:line 当成诊断契约(当前 lib/private.js:893),修改位置时同步更新该诊断映射,
814
902
  // 而那是别人的文件、本包不改。ESM 的 import 声明是提升的,写在语句之后合法。
815
903
  import { warn } from './paths.js'
816
904
  import { captureSessionSnapshot, eventSeq, safePrefix, snapshotHash } from './consolidation-snapshot.js'
@@ -1232,22 +1320,34 @@ export async function requestHistoricalConsolidation(ctx, sessionId, options = {
1232
1320
  // 种子只种这一窗:worker 看到的世界就是它要对账的那一段,窗口之外的事件
1233
1321
  // 留给下一批。seq 已按 compactSeedEvents 重排成从 0 连续,inheritedEventCount
1234
1322
  // 必须等于种子长度(不是父会话的 throughSeq),否则宿主会拒绝这份种子。
1235
- handle = await agents.create({
1236
- sessionId: childId,
1237
- meta: {
1238
- cwd: header.cwd,
1239
- parentSession: sessionId,
1240
- isSeeded: true,
1241
- // Without this the fork is treated as an ordinary user conversation by
1242
- // the injection path and the sidebar session lists.
1243
- origin: 'subagent',
1244
- agentPreset: header.agentPreset,
1245
- },
1246
- inheritedEventCount: seedEvents.length,
1247
- seed: buildForkSeed(seedEvents, seedEvents.length - 1),
1248
- agentOptions,
1249
- signal: abort.signal,
1250
- })
1323
+ try {
1324
+ handle = await agents.create({
1325
+ sessionId: childId,
1326
+ meta: {
1327
+ cwd: header.cwd,
1328
+ parentSession: sessionId,
1329
+ isSeeded: true,
1330
+ // Without this the fork is treated as an ordinary user conversation by
1331
+ // the injection path and the sidebar session lists.
1332
+ origin: 'subagent',
1333
+ agentPreset: header.agentPreset,
1334
+ },
1335
+ inheritedEventCount: seedEvents.length,
1336
+ seed: buildForkSeed(seedEvents, seedEvents.length - 1),
1337
+ agentOptions,
1338
+ signal: abort.signal,
1339
+ })
1340
+ } catch (error) {
1341
+ // 宿主拒绝种子时最需要的诊断信息就在这条错误里("seed event at index …"),
1342
+ // 用独立 reasonCode 写进活动日志,别让它塌成一句 exception。
1343
+ const failure = String(error?.message || error)
1344
+ safeLedger(() => failJob({ sessionId, jobId, reasonCode: 'fork-create-failed', retryable: true, error: failure }))
1345
+ return finish({
1346
+ ok: false, sessionId, childId, settled: false, retryable: true,
1347
+ reasonCode: 'fork-create-failed',
1348
+ error: 'the host rejected the consolidation fork: ' + failure,
1349
+ })
1350
+ }
1251
1351
 
1252
1352
  // header 无法证明 worker 有写工具时(PTC 会话名单只有 run_code / 旧会话没有名单),
1253
1353
  // 把 worker 读写面挂进 fork 自己的 scope,保证 SDK 面(PTC)与原生面(普通会话)都真能写入。