dsh-memu-memory 1.4.4 → 1.4.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +3 -1
- package/CHANGELOG.md +11 -0
- package/README.md +33 -14
- package/README.zh.md +34 -12
- package/assets/screenshots/drawer.jpg +0 -0
- package/assets/screenshots/libraries.jpg +0 -0
- package/assets/screenshots/mobile.jpg +0 -0
- package/assets/screenshots/relations.jpg +0 -0
- package/assets/screenshots/settings.jpg +0 -0
- package/assets/screenshots/webui-dark.jpg +0 -0
- package/assets/screenshots/webui-memory.jpg +0 -0
- package/docs/client-conventions.md +19 -3
- package/docs/contributing.md +4 -2
- package/docs/env-and-commands.md +9 -1
- package/docs/graph-scale.md +214 -0
- package/docs/lexicon-recall.md +100 -0
- package/docs/mcp-porting.md +8 -6
- package/docs/memory-semantics.md +35 -3
- package/docs/pending-work.md +3 -1
- package/docs/retention.md +83 -0
- package/docs/rt-index.md +452 -0
- package/docs/scale-performance.md +101 -0
- package/docs/token-budget.md +92 -0
- package/docs/troubleshooting.md +50 -11
- package/lib/auto-link/apply.js +7 -2
- package/lib/auto-link/candidates.js +32 -10
- package/lib/backup.js +67 -32
- package/lib/binding-diagnostics.js +1 -1
- package/lib/bounded-cache.js +80 -0
- package/lib/client.js +2096 -409
- package/lib/consolidation-ledger.js +21 -4
- package/lib/consolidation-worker.js +14 -1
- package/lib/cycle.js +16 -11
- package/lib/diagnostic-context.js +372 -0
- package/lib/diagnostics.js +147 -61
- package/lib/embedding-download.js +7 -8
- package/lib/engine-sources.js +286 -0
- package/lib/engine.js +23 -10
- package/lib/entity-repair.js +43 -13
- package/lib/entity-review.js +64 -0
- package/lib/environment-check.js +348 -36
- package/lib/feedback.js +25 -0
- package/lib/global-graph.js +46 -2
- package/lib/graph-adjacency-index.js +525 -0
- package/lib/graph-overview.js +293 -0
- package/lib/graph.js +658 -105
- package/lib/inbound.js +44 -15
- package/lib/index-pages.js +57 -0
- package/lib/index.js +44 -6
- package/lib/inject.js +119 -50
- package/lib/lexicon-rt-source.js +25 -0
- package/lib/lexicon-rt-worker.js +26 -0
- package/lib/lexicon-rt.js +224 -0
- package/lib/lexicon-scope.js +56 -5
- package/lib/lexicon.js +143 -54
- package/lib/local-vector-service.js +3 -0
- package/lib/maintenance-ledger.js +542 -12
- package/lib/managed-runtime.js +260 -80
- package/lib/media.js +1 -1
- package/lib/memory.js +564 -131
- package/lib/port-surface.js +96 -11
- package/lib/private.js +47 -21
- package/lib/recall-cache.js +20 -34
- package/lib/retention.js +173 -0
- package/lib/rpc.js +135 -52
- package/lib/rt-index/builder.js +209 -0
- package/lib/rt-index/format.js +231 -0
- package/lib/rt-index/manifest.js +105 -0
- package/lib/rt-index/reader.js +673 -0
- package/lib/rt-index-retention.js +151 -0
- package/lib/rt-index-service.js +283 -0
- package/lib/rt-index-worker.js +21 -0
- package/lib/salient-wake.js +55 -4
- package/lib/state.js +195 -24
- package/lib/temporal.js +39 -13
- package/lib/token-measurement.js +126 -0
- package/lib/tools.js +101 -6
- package/lib/turn-log.js +108 -3
- package/lib/webui/graph-layout-worker.js +68 -0
- package/lib/webui/graph-local-physics.js +390 -0
- package/lib/webui/graph-spatial-grid.js +64 -0
- package/lib/webui/graph-view.bundle.js +6 -1
- package/lib/webui/graph-view.js +478 -135
- package/lib/webui/graph-webgl-renderer.js +74 -0
- package/lib/webui/standalone.js +1 -1
- package/lib/worker-pool.js +30 -4
- package/package.json +3 -2
- package/scripts/acceptance-local.mjs +4 -10
- package/scripts/bench-all-libraries.mjs +47 -0
- package/scripts/check-classic-graph-browser.mjs +189 -0
- package/scripts/check-client-browser.mjs +929 -0
- package/scripts/check-graph-browser.mjs +6 -0
- package/scripts/check-graph-elastic-browser.mjs +139 -0
- package/scripts/check-memory-review-browser.mjs +124 -0
- package/scripts/entity-dedupe.mjs +19 -3
- package/scripts/graph-artifact-provenance.mjs +30 -0
- package/scripts/graph-freeze-manifest.mjs +129 -0
- package/scripts/graph-geometry-fixture.mjs +40 -0
- package/scripts/graph-physics-bench.mjs +218 -0
- package/scripts/graph-scale-bench.mjs +213 -0
- package/scripts/graph-scale-memory.mjs +48 -0
- package/scripts/graph-service-bench.mjs +72 -0
- package/scripts/make-readme-shots.mjs +17 -5
- package/scripts/preview.mjs +1 -0
- package/scripts/rebuild-rt.mjs +18 -0
- package/scripts/scale-bench.mjs +183 -0
- package/scripts/simulate-injection.mjs +47 -8
- package/scripts/verify-host-fixtures.mjs +108 -0
- package/scripts/verify-host-recovery.mjs +565 -0
- package/scripts/verify-vector-recovery.mjs +740 -0
- package/tests/auto-link-candidates.test.mjs +20 -0
- package/tests/browser.test.mjs +16 -2
- package/tests/client-export.test.mjs +16 -1
- package/tests/client-pagination.test.mjs +1495 -0
- package/tests/client-render.test.mjs +223 -28
- package/tests/consolidation-fork.test.mjs +93 -10
- package/tests/consolidation-ledger.test.mjs +17 -1
- package/tests/diagnostic-entity-candidates.test.mjs +54 -0
- package/tests/diagnostic-report.test.mjs +429 -0
- package/tests/diagnostic-wiring.test.mjs +88 -0
- package/tests/diagnostics.test.mjs +27 -0
- package/tests/embedding-download.test.mjs +44 -0
- package/tests/engine-source-settings.test.mjs +69 -0
- package/tests/engine-sources.test.mjs +145 -0
- package/tests/entity-dedupe.test.mjs +143 -0
- package/tests/entity-merge-review.test.mjs +363 -0
- package/tests/entity-merge.test.mjs +12 -4
- package/tests/entity-review.test.mjs +87 -0
- package/tests/environment-check.test.mjs +51 -1
- package/tests/feedback.test.mjs +95 -0
- package/tests/graph-adjacency-index.test.mjs +536 -0
- package/tests/graph-cascade.test.mjs +229 -0
- package/tests/graph-import-diagnostic.test.mjs +25 -0
- package/tests/graph-overview.test.mjs +709 -0
- package/tests/graph-session-authorization.test.mjs +419 -0
- package/tests/graph-view-geometry.test.mjs +426 -0
- package/tests/graph-view-scale.test.mjs +88 -0
- package/tests/graph-view.test.mjs +444 -5
- package/tests/graph.test.mjs +43 -0
- package/tests/help-page.test.mjs +128 -54
- package/tests/inbound.test.mjs +19 -0
- package/tests/index-pagination.test.mjs +113 -0
- package/tests/index-read-view.test.mjs +212 -0
- package/tests/inject-guide.test.mjs +9 -0
- package/tests/injection-dedupe.test.mjs +213 -0
- package/tests/lexicon-recall.test.mjs +641 -0
- package/tests/lexicon-rt-lifecycle.test.mjs +196 -0
- package/tests/lexicon-rt.test.mjs +468 -0
- package/tests/local-embedding-worker.test.mjs +38 -0
- package/tests/local-vector-service.test.mjs +32 -3
- package/tests/maintenance-compat.test.mjs +128 -0
- package/tests/maintenance-settlement.test.mjs +1003 -0
- package/tests/managed-memory.test.mjs +39 -11
- package/tests/managed-runtime.test.mjs +109 -0
- package/tests/memory-fields.test.mjs +24 -12
- package/tests/observed-evidence.test.mjs +52 -0
- package/tests/port-surface.test.mjs +93 -1
- package/tests/recall-cache.test.mjs +56 -3
- package/tests/recall-dedup.test.mjs +63 -2
- package/tests/retention.test.mjs +260 -0
- package/tests/rt-index-cross-library.test.mjs +230 -0
- package/tests/rt-index-integration.test.mjs +194 -0
- package/tests/rt-index-retention.test.mjs +552 -0
- package/tests/rt-index-scale.test.mjs +204 -0
- package/tests/rt-index.test.mjs +705 -0
- package/tests/salient-date-boundaries.test.mjs +121 -0
- package/tests/salient-wake.test.mjs +29 -0
- package/tests/scale-bench.test.mjs +53 -0
- package/tests/settings-plumbing.test.mjs +25 -0
- package/tests/simulate-injection.test.mjs +15 -1
- package/tests/standalone-navigation.test.mjs +44 -0
- package/tests/state.test.mjs +51 -0
- package/tests/temporal-precision.test.mjs +102 -0
- package/tests/temporal.test.mjs +10 -6
- package/tests/token-measurement.test.mjs +98 -0
- package/tests/tool-schema.test.mjs +41 -5
- package/tests/tools.test.mjs +6 -3
- package/tests/turn-token-budget.test.mjs +149 -0
- package/tests/webui-auth.test.mjs +57 -1
- package/tests/webui.test.mjs +40 -15
package/lib/tools.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { defineTool } from '@deepseek-ai/dsh-tools'
|
|
2
2
|
import {
|
|
3
|
-
privateRemember, privateRecall, privateList, privateUpdate, privateArchive,
|
|
3
|
+
privateRemember, privateRecall, privateList, privateUpdate, privateArchive, privateFeedback,
|
|
4
4
|
privateUnpin, globalRecall, globalList, bindingFor, peekBinding, sessionIdOf, domainOf, relativeTime,
|
|
5
5
|
isDatedSalientDate, readMemoryByRef,
|
|
6
6
|
} from './memory.js'
|
|
@@ -8,11 +8,12 @@ import { engineStatus, ENGINE_VERSION } from './engine.js'
|
|
|
8
8
|
import { getMissingVectorLibraries } from './local-vector-service.js'
|
|
9
9
|
import { centeredSnippetWindow } from './snippet.js'
|
|
10
10
|
import { redactSecrets } from './paths.js'
|
|
11
|
-
import { linkEntries, linkNamedEntity, updateRelationship } from './graph.js'
|
|
11
|
+
import { linkEntries, linkNamedEntity, updateRelationship, suggestEntityMergeReviews, holdEntityMergeReview, mergeEntities, setEntityMergeRejection } from './graph.js'
|
|
12
12
|
import { autoLinkPrivateMemories } from './private-links.js'
|
|
13
13
|
import { getSettings, listLibraries, getLibrary, loadPrivateIndex, loadGlobalIndex, storageHealth, syncActivity } from './state.js'
|
|
14
14
|
import { lexiconSearch, lexiconSources } from './lexicon-scope.js'
|
|
15
15
|
import { maintenanceStatus } from './maintenance-ledger.js'
|
|
16
|
+
import { record } from './activity-log.js'
|
|
16
17
|
|
|
17
18
|
function text(value) {
|
|
18
19
|
return String(value ?? '')
|
|
@@ -158,6 +159,9 @@ function toolBase(name, description, parameters, execute, options = {}) {
|
|
|
158
159
|
isConcurrencySafe: options.isConcurrencySafe ?? (() => false),
|
|
159
160
|
async execute(args, exec) {
|
|
160
161
|
try {
|
|
162
|
+
if (peekBinding(exec)?.entityReviewOnly && !['memu_private_entity_merge_suggest', 'memu_private_entity_merge_decide'].includes(name)) {
|
|
163
|
+
throw new Error('entity review worker may only read and adjudicate its entity candidate batch')
|
|
164
|
+
}
|
|
161
165
|
return await execute(args || {}, exec)
|
|
162
166
|
} catch (error) {
|
|
163
167
|
try { exec?.logger?.warn?.(`dsh-memu-memory ${name}: ${error?.stack || error}`) } catch {}
|
|
@@ -419,6 +423,78 @@ export function registerTools(ctx, { only = null } = {}) {
|
|
|
419
423
|
{ isConcurrencySafe: () => false, timeoutMs: 120_000 },
|
|
420
424
|
))
|
|
421
425
|
|
|
426
|
+
tools.push(toolBase(
|
|
427
|
+
'memu_private_entity_merge_suggest',
|
|
428
|
+
'Read a bounded batch of similar-entity candidates in the bound private library, with visible linked-memory summaries and relationship evidence. Similar names are only a discovery signal. Use after consolidating memories; do not start another fork or read outside the returned evidence. Continue with nextCursor only when scanComplete is false.',
|
|
429
|
+
{ cursor: { type: 'string', description: 'Optional continuation cursor returned by the previous batch.' } },
|
|
430
|
+
(args, exec) => {
|
|
431
|
+
const binding = peekBinding(exec)
|
|
432
|
+
if (!binding?.libraryId) return JSON.stringify({ items: [], total: 0, totalExact: true, scanComplete: true, nextCursor: null, unbound: true })
|
|
433
|
+
const result = suggestEntityMergeReviews({ exec, libraryId: binding.libraryId, cursor: args.cursor, reviewState: 'model',
|
|
434
|
+
...(binding.entityReviewOnly ? { pairs: binding.entityReviewPairs || [] } : {}) })
|
|
435
|
+
return JSON.stringify(result)
|
|
436
|
+
},
|
|
437
|
+
{ isConcurrencySafe: () => true, timeoutMs: 120_000 },
|
|
438
|
+
))
|
|
439
|
+
|
|
440
|
+
tools.push(toolBase(
|
|
441
|
+
'memu_private_entity_merge_decide',
|
|
442
|
+
'Adjudicate one exact candidate from memu_private_entity_merge_suggest. Merge only when visible memory and relationship evidence establish the same identity; reject only when evidence establishes distinct identities; otherwise hold. Names, edit distance, shared surname, family relation or role similarity alone never justify a merge. Confidence below 0.85 is always converted to hold. Uses the current candidate reviewToken and cannot cross libraries or visibility boundaries.',
|
|
443
|
+
{
|
|
444
|
+
source_id: { type: 'string', required: true, description: 'Candidate sourceId.' },
|
|
445
|
+
target_id: { type: 'string', required: true, description: 'Candidate targetId.' },
|
|
446
|
+
review_token: { type: 'string', required: true, description: 'Exact reviewToken returned for this candidate.' },
|
|
447
|
+
decision: { type: 'string', required: true, description: 'merge, reject, or hold.' },
|
|
448
|
+
confidence: { type: 'number', required: true, description: 'Your evidence-based confidence, 0..1. Below 0.85 becomes hold.' },
|
|
449
|
+
reason: { type: 'string', required: true, description: 'At least 8 characters, citing the specific returned memory/relationship evidence.' },
|
|
450
|
+
},
|
|
451
|
+
(args, exec) => {
|
|
452
|
+
const binding = peekBinding(exec)
|
|
453
|
+
if (!binding?.libraryId) return '当前整理 worker 没有绑定记忆库,候选未处理。'
|
|
454
|
+
const sourceId = String(args.source_id || '').trim()
|
|
455
|
+
const targetId = String(args.target_id || '').trim()
|
|
456
|
+
const reviewToken = String(args.review_token || '')
|
|
457
|
+
const requestedDecision = String(args.decision || '').trim().toLowerCase()
|
|
458
|
+
const confidence = Number(args.confidence)
|
|
459
|
+
const reason = String(args.reason || '').trim()
|
|
460
|
+
if (!sourceId || !targetId || !/^[a-f0-9]{64}$/.test(reviewToken)) throw new Error('实体候选参数无效;请重新读取候选')
|
|
461
|
+
if (binding.entityReviewOnly && !(binding.entityReviewPairs || []).some(pair => pair.sourceId === sourceId
|
|
462
|
+
&& pair.targetId === targetId && pair.reviewToken === reviewToken)) throw new Error('candidate is outside this entity review batch')
|
|
463
|
+
if (!['merge', 'reject', 'hold'].includes(requestedDecision)) throw new Error('decision must be merge, reject or hold')
|
|
464
|
+
if (!Number.isFinite(confidence) || confidence < 0 || confidence > 1) throw new Error('confidence must be between 0 and 1')
|
|
465
|
+
if (reason.replace(/\s/gu, '').length < 8 || reason.length > 500) throw new Error('reason must contain 8-500 characters')
|
|
466
|
+
const decision = requestedDecision !== 'hold' && confidence < 0.85 ? 'hold' : requestedDecision
|
|
467
|
+
if (decision === 'hold') {
|
|
468
|
+
holdEntityMergeReview({ exec, libraryId: binding.libraryId, sourceId, targetId, reviewToken, reason, confidence })
|
|
469
|
+
record({ kind: 'consolidate', scope: 'private', libraryId: binding.libraryId,
|
|
470
|
+
sessionId: sessionIdOf(exec), ok: true, message: '实体候选保留待用户裁决',
|
|
471
|
+
detail: { phase: 'entity-review', actor: 'worker', decision: 'hold', sourceId, targetId,
|
|
472
|
+
requestedDecision, confidence, reason: redactSecrets(reason).slice(0, 500) }, refs: [sourceId, targetId] })
|
|
473
|
+
return JSON.stringify({ ok: true, decision: 'hold', requestedDecision,
|
|
474
|
+
reason: decision !== requestedDecision ? 'confidence-below-threshold' : reason,
|
|
475
|
+
pendingUserReview: true, sourceId, targetId })
|
|
476
|
+
}
|
|
477
|
+
if (decision === 'merge') {
|
|
478
|
+
const result = mergeEntities({ exec, libraryId: binding.libraryId, targetId, sourceIds: [sourceId], reviewToken })
|
|
479
|
+
record({ kind: 'consolidate', scope: 'private', libraryId: binding.libraryId,
|
|
480
|
+
sessionId: sessionIdOf(exec), ok: true, message: '整理 worker 已根据证据合并实体',
|
|
481
|
+
detail: { phase: 'entity-review', actor: 'worker', decision, confidence,
|
|
482
|
+
reason: redactSecrets(reason).slice(0, 500), remappedLinks: result.remappedLinks,
|
|
483
|
+
duplicateLinks: result.duplicateLinks }, refs: [sourceId, targetId] })
|
|
484
|
+
return JSON.stringify({ ok: true, decision, sourceId, targetId,
|
|
485
|
+
remappedLinks: result.remappedLinks, duplicateLinks: result.duplicateLinks })
|
|
486
|
+
}
|
|
487
|
+
const result = setEntityMergeRejection({ exec, libraryId: binding.libraryId, sourceId, targetId,
|
|
488
|
+
reviewToken, rejected: true, confirmed: true })
|
|
489
|
+
record({ kind: 'consolidate', scope: 'private', libraryId: binding.libraryId,
|
|
490
|
+
sessionId: sessionIdOf(exec), ok: true, message: '整理 worker 已排除不同实体候选',
|
|
491
|
+
detail: { phase: 'entity-review', actor: 'worker', decision, confidence,
|
|
492
|
+
reason: redactSecrets(reason).slice(0, 500) }, refs: [sourceId, targetId] })
|
|
493
|
+
return JSON.stringify({ ok: true, decision, sourceId, targetId, rejected: result.rejected })
|
|
494
|
+
},
|
|
495
|
+
{ isConcurrencySafe: () => false, timeoutMs: 120_000 },
|
|
496
|
+
))
|
|
497
|
+
|
|
422
498
|
tools.push(toolBase(
|
|
423
499
|
'memu_private_remember',
|
|
424
500
|
'Write one durable private memory. Match the domain; never copy a transcript or invent evidence. layer=must_remember requires pin_reason and pin_source.',
|
|
@@ -602,7 +678,7 @@ export function registerTools(ctx, { only = null } = {}) {
|
|
|
602
678
|
|
|
603
679
|
tools.push(toolBase(
|
|
604
680
|
'memu_private_recall',
|
|
605
|
-
'Retrieve relevant private memories from the library bound to this conversation. Natural queries return short snippets;
|
|
681
|
+
'Retrieve relevant private memories from the library bound to this conversation. Natural queries return short snippets plus a separate lexicon section (up to 2 scene conventions, [lex:termId] references and matchedBy); lexicon concept search also matches meaning/usage without naming the term. Lexicon rows are conventions, not remembered facts. Exact mem- ids (or unique prefixes, optionally .md, no whitespace) read one redacted body page with auto/full. Secret memories remain explicitly readable with disclosure restrictions. Use libraryId only to disambiguate an allowed exact reference, never to widen scope.',
|
|
606
682
|
{
|
|
607
683
|
query: { type: 'string', required: true, description: 'Natural-language search or exact mem- id / unique prefix (optional .md, no whitespace).' },
|
|
608
684
|
topK: { type: 'integer', description: 'Search row limit, integer 1..20; default from settings. Exact reads return one entry.' },
|
|
@@ -619,13 +695,17 @@ export function registerTools(ctx, { only = null } = {}) {
|
|
|
619
695
|
const result = await privateRecall({ exec, query: request.query, topK: request.topK, purpose: 'explicit' })
|
|
620
696
|
// Surface a degraded semantic leg on the explicit tool path too; silently
|
|
621
697
|
// returning fewer hits would make a failed backend look like an empty library.
|
|
622
|
-
const
|
|
698
|
+
const warnings = [...(result.errors || []), ...(result.lexiconErrors || [])]
|
|
699
|
+
const warning = warnings.length ? `\n注意:本次召回已降级:${warnings.join('; ')}` : ''
|
|
623
700
|
// Read-only: never materialize a binding/library from a recall header.
|
|
624
701
|
const binding = peekBinding(exec)
|
|
625
702
|
const foreign = (result.libraries || []).filter((id) => id !== binding?.libraryId)
|
|
626
703
|
const header = `私有记忆(library=${binding?.libraryId || '?'}, domain=${domainOf(binding)}${foreign.length ? `,跨库=${foreign.join(',')}` : ''})`
|
|
627
|
-
|
|
628
|
-
|
|
704
|
+
const lines = [header, ...(result.files || []).map((f, i) => formatPrivateItem(f, i + 1, { query: args.query, homeLibraryId: binding?.libraryId || null }))]
|
|
705
|
+
if (result.lexicon?.length) lines.push('lexicon · 场景约定(不是记忆事实)', ...result.lexicon.map(hit => redactSecrets(
|
|
706
|
+
`- [lex:${hit.termId}] ${hit.term}${hit.meaning || hit.usage ? `:${hit.meaning || hit.usage}` : ''} · matchedBy=${hit.matchedBy} · library=${hit.libraryId}`)))
|
|
707
|
+
if (!result.files?.length && !result.lexicon?.length) lines.push('没有命中。')
|
|
708
|
+
return lines.join('\n\n') + warning
|
|
629
709
|
},
|
|
630
710
|
{ isConcurrencySafe: () => true },
|
|
631
711
|
))
|
|
@@ -757,6 +837,21 @@ export function registerTools(ctx, { only = null } = {}) {
|
|
|
757
837
|
{ timeoutMs: 180_000 },
|
|
758
838
|
))
|
|
759
839
|
|
|
840
|
+
tools.push(toolBase(
|
|
841
|
+
'memu_private_feedback',
|
|
842
|
+
'Record observed confirmation, denial or irrelevance of a private memory in the bound library. Use only explicit feedback, with a reason; do not infer a verdict from silence or recall alone. Confirm/deny adjust strength; two denials marginalize without deleting or unpinning. A new fact replacing an old one still uses link kind=supersede.',
|
|
843
|
+
{
|
|
844
|
+
id: { type: 'string', required: true, description: 'Memory id in the bound library.' },
|
|
845
|
+
verdict: { type: 'string', required: true, enum: ['confirm', 'deny', 'irrelevant'] },
|
|
846
|
+
reason: { type: 'string', required: true, description: 'Brief evidence of the observed feedback; never invent it.' },
|
|
847
|
+
revision: { type: 'string', description: 'Optional content revision for optimistic concurrency.' },
|
|
848
|
+
},
|
|
849
|
+
(args, exec) => {
|
|
850
|
+
const result = privateFeedback({ exec, id: args.id, verdict: args.verdict, reason: args.reason, expectedRevision: args.revision })
|
|
851
|
+
return `已记录反馈 ${result.id}: ${args.verdict} (confirm=${result.entry.feedback.confirm}, deny=${result.entry.feedback.deny}${result.entry.marginalized ? ', marginalized' : ''})`
|
|
852
|
+
},
|
|
853
|
+
))
|
|
854
|
+
|
|
760
855
|
tools.push(toolBase(
|
|
761
856
|
'memu_private_archive',
|
|
762
857
|
'Archive a private memory. It stays in the library but is filtered out of normal retrieval.',
|
package/lib/turn-log.js
CHANGED
|
@@ -19,6 +19,7 @@ export const TURNLOG_TOOL_ARGS_CHARS = 120
|
|
|
19
19
|
export const TURNLOG_RECORD_CHARS = 4000
|
|
20
20
|
export const TURNLOG_KEEP_CHARS = 200_000
|
|
21
21
|
export const TURNLOG_GC_DAYS = 30
|
|
22
|
+
export const TURNLOG_ORPHAN_RETENTION_DAYS = 90
|
|
22
23
|
|
|
23
24
|
// 编码域的「修改重点」几乎全在工具行里(命令、错误签名、diff 参数),160 字只留得下
|
|
24
25
|
// 开头。给编码域更宽的单项额度,整条记录仍受 4000 字总闸约束(先砍 tools 尾)。
|
|
@@ -279,14 +280,49 @@ function scanTurnLog(sessionId) {
|
|
|
279
280
|
return { file, entries, badLines, unreadable: false }
|
|
280
281
|
}
|
|
281
282
|
|
|
283
|
+
function writePrivateFile(file, text) {
|
|
284
|
+
const fd = fs.openSync(file, 'w', 0o600)
|
|
285
|
+
try {
|
|
286
|
+
fs.fchmodSync(fd, 0o600)
|
|
287
|
+
fs.writeFileSync(fd, text, 'utf8')
|
|
288
|
+
fs.fsyncSync(fd)
|
|
289
|
+
} finally {
|
|
290
|
+
fs.closeSync(fd)
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
function appendPrivateFile(file, text) {
|
|
295
|
+
ensureDir(path.dirname(file))
|
|
296
|
+
const fd = fs.openSync(file, 'a', 0o600)
|
|
297
|
+
try {
|
|
298
|
+
fs.fchmodSync(fd, 0o600)
|
|
299
|
+
fs.writeFileSync(fd, text, 'utf8')
|
|
300
|
+
fs.fsyncSync(fd)
|
|
301
|
+
} finally {
|
|
302
|
+
fs.closeSync(fd)
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
function syncDirectoryBestEffort(dir) {
|
|
307
|
+
let fd
|
|
308
|
+
try {
|
|
309
|
+
fd = fs.openSync(dir, 'r')
|
|
310
|
+
fs.fsyncSync(fd)
|
|
311
|
+
} catch {
|
|
312
|
+
// Some supported filesystems do not permit directory fsync.
|
|
313
|
+
} finally {
|
|
314
|
+
if (fd !== undefined) { try { fs.closeSync(fd) } catch {} }
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
|
|
282
318
|
/** 坏行原样保留地原子重写(Windows 上 rename 的 EPERM/EBUSY 重试用 paths.js 同款节奏)。 */
|
|
283
319
|
function rewriteTurnLog(file, lines) {
|
|
284
320
|
ensureDir(path.dirname(file))
|
|
285
321
|
const tmp = `${file}.tmp-${process.pid}-${crypto.randomUUID()}`
|
|
286
322
|
try {
|
|
287
|
-
|
|
323
|
+
writePrivateFile(tmp, lines.length > 0 ? lines.join('\n') + '\n' : '', 'utf8')
|
|
288
324
|
for (let attempt = 0; ; attempt++) {
|
|
289
|
-
try { fs.renameSync(tmp, file); break } catch (error) {
|
|
325
|
+
try { fs.renameSync(tmp, file); syncDirectoryBestEffort(path.dirname(file)); break } catch (error) {
|
|
290
326
|
if (!['EPERM', 'EBUSY', 'EACCES'].includes(error?.code) || attempt >= 5) throw error
|
|
291
327
|
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 8 * (attempt + 1))
|
|
292
328
|
}
|
|
@@ -335,7 +371,7 @@ export function recordTurn(sessionId, record) {
|
|
|
335
371
|
return null
|
|
336
372
|
}
|
|
337
373
|
const line = JSON.stringify({ ...record, at: record.at || stamp() })
|
|
338
|
-
|
|
374
|
+
appendPrivateFile(turnLogPath(sessionId), line + '\n', 'utf8')
|
|
339
375
|
try {
|
|
340
376
|
let lastSleepSeq = null
|
|
341
377
|
try { lastSleepSeq = getSessionBinding(String(sessionId))?.lastSleepSeq ?? null } catch {}
|
|
@@ -481,6 +517,75 @@ export function pruneHead(sessionId, keepChars = TURNLOG_KEEP_CHARS, lastSleepSe
|
|
|
481
517
|
return { pruned, charsBefore: total, charsAfter }
|
|
482
518
|
}
|
|
483
519
|
|
|
520
|
+
function orphanTurnLogDays(value) {
|
|
521
|
+
const days = Number(value)
|
|
522
|
+
if (!Number.isFinite(days) || days <= 0) throw new Error('olderThanDays must be a positive number of days')
|
|
523
|
+
return days
|
|
524
|
+
}
|
|
525
|
+
|
|
526
|
+
function isTurnLogBasename(name) {
|
|
527
|
+
const value = String(name || '')
|
|
528
|
+
const suffix = '.turnlog.jsonl'
|
|
529
|
+
const id = value.endsWith(suffix) ? value.slice(0, -suffix.length) : ''
|
|
530
|
+
return /^[A-Za-z0-9._-]{1,128}$/.test(id)
|
|
531
|
+
}
|
|
532
|
+
|
|
533
|
+
function boundTurnLogNames(bindings) {
|
|
534
|
+
return new Set((Array.isArray(bindings) ? bindings : [])
|
|
535
|
+
.map((binding) => binding?.sessionId)
|
|
536
|
+
.filter((sessionId) => typeof sessionId === 'string' && sessionId)
|
|
537
|
+
.map((sessionId) => logFileName(sessionId)))
|
|
538
|
+
}
|
|
539
|
+
|
|
540
|
+
/** List old, unbound regular turn-log files. This is planning only; it never deletes. */
|
|
541
|
+
export function listOrphanTurnLogs(bindings, { now = Date.now(), olderThanDays = TURNLOG_ORPHAN_RETENTION_DAYS } = {}) {
|
|
542
|
+
const days = orphanTurnLogDays(olderThanDays)
|
|
543
|
+
const cutoff = Number(now) - days * 86_400_000
|
|
544
|
+
const dir = path.join(dataDir(), 'sessions')
|
|
545
|
+
const bound = boundTurnLogNames(bindings)
|
|
546
|
+
let names
|
|
547
|
+
try { names = fs.readdirSync(dir) } catch (error) {
|
|
548
|
+
if (error?.code === 'ENOENT') return { candidates: [], kept: [], olderThanDays: days }
|
|
549
|
+
throw error
|
|
550
|
+
}
|
|
551
|
+
const candidates = []
|
|
552
|
+
const kept = []
|
|
553
|
+
for (const name of names) {
|
|
554
|
+
if (!isTurnLogBasename(name)) continue
|
|
555
|
+
if (bound.has(name)) { kept.push({ name, reason: 'bound-session' }); continue }
|
|
556
|
+
const file = path.join(dir, name)
|
|
557
|
+
let info
|
|
558
|
+
try { info = fs.lstatSync(file) } catch { kept.push({ name, reason: 'stat-failed' }); continue }
|
|
559
|
+
if (!info.isFile()) { kept.push({ name, reason: 'not-regular-file' }); continue }
|
|
560
|
+
if (!(info.mtimeMs < cutoff)) { kept.push({ name, reason: 'within-retention' }); continue }
|
|
561
|
+
candidates.push({ name, size: info.size, mtimeMs: info.mtimeMs })
|
|
562
|
+
}
|
|
563
|
+
return { candidates, kept, olderThanDays: days }
|
|
564
|
+
}
|
|
565
|
+
|
|
566
|
+
/** Revalidate an orphan candidate immediately before unlinking it. */
|
|
567
|
+
export function deleteOrphanTurnLog(candidate, bindings, { now = Date.now(), olderThanDays = TURNLOG_ORPHAN_RETENTION_DAYS } = {}) {
|
|
568
|
+
const days = orphanTurnLogDays(olderThanDays)
|
|
569
|
+
const name = candidate?.name
|
|
570
|
+
if (!isTurnLogBasename(name)) return { ok: false, reason: 'invalid-name' }
|
|
571
|
+
if (boundTurnLogNames(bindings).has(name)) return { ok: false, reason: 'bound-session' }
|
|
572
|
+
const dir = path.join(dataDir(), 'sessions')
|
|
573
|
+
const file = path.join(dir, name)
|
|
574
|
+
let info
|
|
575
|
+
try { info = fs.lstatSync(file) } catch (error) {
|
|
576
|
+
return { ok: false, reason: error?.code === 'ENOENT' ? 'missing' : 'stat-failed' }
|
|
577
|
+
}
|
|
578
|
+
if (!info.isFile()) return { ok: false, reason: 'not-regular-file' }
|
|
579
|
+
if (!(info.mtimeMs < Number(now) - days * 86_400_000)) return { ok: false, reason: 'within-retention' }
|
|
580
|
+
if (info.size !== candidate.size || info.mtimeMs !== candidate.mtimeMs) return { ok: false, reason: 'changed-since-plan' }
|
|
581
|
+
try {
|
|
582
|
+
fs.unlinkSync(file)
|
|
583
|
+
return { ok: true, name }
|
|
584
|
+
} catch (error) {
|
|
585
|
+
return { ok: false, reason: `unlink-failed:${error?.code || 'unknown'}` }
|
|
586
|
+
}
|
|
587
|
+
}
|
|
588
|
+
|
|
484
589
|
/**
|
|
485
590
|
* 休眠 GC(§3.4):日志无未结算增量(max seqEnd ≤ lastSleepSeq)且会话 ≥30 天
|
|
486
591
|
* 无活动 → 删文件。缓存级操作;复活后交接尾部/增量走重建路径自动补。
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
// Self-contained so the same deterministic prelayout can run in a Blob worker
|
|
2
|
+
// (no extra asset route) or synchronously when CSP/Worker is unavailable.
|
|
3
|
+
export function prelayoutGraph(graph) {
|
|
4
|
+
const nodes = graph.nodes || [], positions = new Float64Array(nodes.length * 2)
|
|
5
|
+
const byId = new Map(nodes.map((node, i) => [node.id, i]))
|
|
6
|
+
const adjacency = Array.from(nodes, () => [])
|
|
7
|
+
for (const edge of graph.edges || []) {
|
|
8
|
+
const a = byId.get(edge.from), b = byId.get(edge.to)
|
|
9
|
+
if (a === undefined || b === undefined || a === b) continue
|
|
10
|
+
adjacency[a].push(b); adjacency[b].push(a)
|
|
11
|
+
}
|
|
12
|
+
const seen = new Uint8Array(nodes.length), groups = []
|
|
13
|
+
for (let i = 0; i < nodes.length; i++) {
|
|
14
|
+
if (seen[i]) continue
|
|
15
|
+
seen[i] = 1
|
|
16
|
+
const group = [i]
|
|
17
|
+
for (let j = 0; j < group.length; j++) for (const next of adjacency[group[j]]) {
|
|
18
|
+
if (!seen[next]) { seen[next] = 1; group.push(next) }
|
|
19
|
+
}
|
|
20
|
+
groups.push(group)
|
|
21
|
+
}
|
|
22
|
+
const columns = Math.max(1, Math.ceil(Math.sqrt(groups.length)))
|
|
23
|
+
const largest = groups.reduce((max, group) => Math.max(max, group.length), 1)
|
|
24
|
+
const stride = Math.ceil(Math.sqrt(largest)) * 28 + 80
|
|
25
|
+
groups.forEach((group, g) => {
|
|
26
|
+
const cols = Math.ceil(Math.sqrt(group.length)), rows = Math.ceil(group.length / cols)
|
|
27
|
+
group.forEach((index, j) => {
|
|
28
|
+
const node = nodes[index]
|
|
29
|
+
positions[index * 2] = Number.isFinite(node.x) ? node.x : (g % columns) * stride + (j % cols - (cols - 1) / 2) * 28
|
|
30
|
+
positions[index * 2 + 1] = Number.isFinite(node.y) ? node.y : Math.floor(g / columns) * stride + (Math.floor(j / cols) - (rows - 1) / 2) * 28
|
|
31
|
+
})
|
|
32
|
+
})
|
|
33
|
+
return positions
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export function createLayoutWorker(win, { onResult, onFallback = () => {}, timeoutMs = 5000 } = {}) {
|
|
37
|
+
let worker = null, url = null, serial = 0, timer = null, failed = false, expectedLength = 0
|
|
38
|
+
const clearTimer = () => { if (timer !== null) { (win.clearTimeout || clearTimeout)(timer); timer = null } }
|
|
39
|
+
const stop = () => { clearTimer(); worker?.terminate(); worker = null; if (url) win.URL.revokeObjectURL(url); url = null }
|
|
40
|
+
const fail = reason => { if (failed) return; failed = true; stop(); onFallback(reason) }
|
|
41
|
+
const request = graph => {
|
|
42
|
+
if (failed) return false
|
|
43
|
+
if (!win.Worker || !win.Blob || !win.URL?.createObjectURL) { fail('worker-unavailable'); return false }
|
|
44
|
+
try {
|
|
45
|
+
if (!worker) {
|
|
46
|
+
const source = `const layout=${prelayoutGraph.toString()};self.onmessage=e=>{const {serial,graph}=e.data;try{const positions=layout(graph);self.postMessage({serial,positions},[positions.buffer])}catch(error){self.postMessage({serial,error:String(error.message||error)})}}`
|
|
47
|
+
url = win.URL.createObjectURL(new win.Blob([source], { type: 'text/javascript' }))
|
|
48
|
+
worker = new win.Worker(url)
|
|
49
|
+
worker.onmessage = event => {
|
|
50
|
+
if (event.data?.serial !== serial) return
|
|
51
|
+
clearTimer()
|
|
52
|
+
if (event.data.error) { fail('worker-layout-error'); return }
|
|
53
|
+
if (!(event.data.positions instanceof Float64Array) || event.data.positions.length !== expectedLength
|
|
54
|
+
|| !event.data.positions.every(Number.isFinite)) { fail('worker-invalid-output'); return }
|
|
55
|
+
onResult(event.data.positions)
|
|
56
|
+
}
|
|
57
|
+
worker.onerror = () => fail('worker-start-error')
|
|
58
|
+
}
|
|
59
|
+
clearTimer()
|
|
60
|
+
const requestSerial = ++serial
|
|
61
|
+
expectedLength = graph.nodes.length * 2
|
|
62
|
+
timer = (win.setTimeout || setTimeout)(() => { if (serial === requestSerial) fail('worker-timeout') }, timeoutMs)
|
|
63
|
+
worker.postMessage({ serial: requestSerial, graph: { nodes: graph.nodes.map(({ id, x, y }) => ({ id, x, y })), edges: graph.edges } })
|
|
64
|
+
return true
|
|
65
|
+
} catch { fail('worker-blocked'); return false }
|
|
66
|
+
}
|
|
67
|
+
return { request, cancel() { serial++; clearTimer() }, dispose() { serial++; stop(); failed = true } }
|
|
68
|
+
}
|